EIVE upstream #29
7
.clang-format
Normal file
7
.clang-format
Normal file
@ -0,0 +1,7 @@
|
||||
---
|
||||
BasedOnStyle: Google
|
||||
IndentWidth: 2
|
||||
---
|
||||
Language: Cpp
|
||||
ColumnLimit: 100
|
||||
---
|
175
CHANGELOG
175
CHANGELOG
@ -1,175 +0,0 @@
|
||||
# Changed from ASTP 1.1.0 to 1.2.0
|
||||
|
||||
## API Changes
|
||||
|
||||
### FSFW Architecture
|
||||
|
||||
- New src folder which contains all source files except the HAL, contributed code and test code
|
||||
- External and internal API mostly stayed the same
|
||||
- Folder names are now all smaller case: internalError was renamed to internalerror and
|
||||
FreeRTOS was renamed to freertos
|
||||
- Warning if optional headers are used but the modules was not added to the source files to compile
|
||||
|
||||
### HAL
|
||||
|
||||
- HAL added back into FSFW. It is tightly bound to the FSFW, and compiling it as a static library
|
||||
made using it more complicated than necessary
|
||||
|
||||
## Bugfixes
|
||||
|
||||
### FreeRTOS QueueMapManager
|
||||
|
||||
- Fixed a bug which causes the first generated Queue ID to be invalid
|
||||
|
||||
## Enhancements
|
||||
|
||||
### FSFW Architecture
|
||||
|
||||
- See API changes chapter. This change will keep the internal API consistent in the future
|
||||
|
||||
# Changes from ASTP 1.0.0 to 1.1.0
|
||||
|
||||
## API Changes
|
||||
|
||||
### PUS
|
||||
|
||||
- Added PUS C support
|
||||
- SUBSYSTEM_IDs added for PUS Services
|
||||
- Added new Parameter which must be defined in config: fsfwconfig::FSFW_MAX_TM_PACKET_SIZE
|
||||
|
||||
### ObjectManager
|
||||
|
||||
- ObjectManager is now a singelton
|
||||
|
||||
|
||||
### Configuration
|
||||
|
||||
- Additional configuration option fsfwconfig::FSFW_MAX_TM_PACKET_SIZE which
|
||||
need to be specified in FSFWConfig.h
|
||||
|
||||
### CMake
|
||||
|
||||
- Changed Cmake FSFW_ADDITIONAL_INC_PATH to FSFW_ADDITIONAL_INC_PATHS
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- timemanager/TimeStamperIF.h: Timestamp config was not used correctly, leading to different timestamp sizes than configured in fsfwconfig::FSFW_MISSION_TIMESTAMP_SIZE
|
||||
- TCP server fixes
|
||||
|
||||
## Enhancements
|
||||
|
||||
### FreeRTOS Queue Handles
|
||||
|
||||
- Fixed an internal issue how FreeRTOS MessageQueues were handled
|
||||
|
||||
### Linux OSAL
|
||||
|
||||
- Better printf error messages
|
||||
|
||||
### CMake
|
||||
|
||||
- Check for C++11 as mininimum required Version
|
||||
|
||||
### Debug Output
|
||||
|
||||
- Changed Warning color to magenta, which is well readable on both dark and light mode IDEs
|
||||
|
||||
|
||||
# Changes from ASTP 0.0.1 to 1.0.0
|
||||
|
||||
### Host OSAL
|
||||
|
||||
- Bugfix in MessageQueue, which caused the sender not to be set properly
|
||||
|
||||
### FreeRTOS OSAL
|
||||
|
||||
- vRequestContextSwitchFromISR is declared extern "C" so it can be defined in
|
||||
a C file without issues
|
||||
|
||||
### PUS Services
|
||||
|
||||
- It is now possible to change the message queue depth for the telecommand verification service (PUS1)
|
||||
- The same is possible for the event reporting service (PUS5)
|
||||
- PUS Health Service added, which allows to command and retrieve health via PUS packets
|
||||
|
||||
|
||||
### EnhancedControllerBase
|
||||
|
||||
- New base class for a controller which also implements HasActionsIF and HasLocalDataPoolIF
|
||||
|
||||
### Local Pool
|
||||
|
||||
- Interface of LocalPools has changed. LocalPool is not a template anymore. Instead the size and
|
||||
bucket number of the pools per page and the number of pages are passed to the ctor instead of
|
||||
two ctor arguments and a template parameter
|
||||
|
||||
### Parameter Service
|
||||
|
||||
- The API of the parameter service has been changed to prevent inconsistencies
|
||||
between documentation and actual code and to clarify usage.
|
||||
- The parameter ID now consists of:
|
||||
1. Domain ID (1 byte)
|
||||
2. Unique Identifier (1 byte)
|
||||
3. Linear Index (2 bytes)
|
||||
The linear index can be used for arrays as well as matrices.
|
||||
The parameter load command now explicitely expects the ECSS PTC and PFC
|
||||
information as well as the rows and column number. Rows and column will
|
||||
default to one, which is equivalent to one scalar parameter (the most
|
||||
important use-case)
|
||||
|
||||
### File System Interface
|
||||
|
||||
- A new interfaces specifies the functions for a software object which exposes the file system of
|
||||
a given hardware to use message based file handling (e.g. PUS commanding)
|
||||
|
||||
### Internal Error Reporter
|
||||
|
||||
- The new internal error reporter uses the local data pools. The pool IDs for
|
||||
the exisiting three error values and the new error set will be hardcoded for
|
||||
now, the the constructor for the internal error reporter just takes an object
|
||||
ID for now.
|
||||
|
||||
### Device Handler Base
|
||||
|
||||
- There is an additional `PERFORM_OPERATION` step for the device handler base. It is important
|
||||
that DHB users adapt their polling sequence tables to perform this step. This steps allows for
|
||||
a clear distinction between operation and communication steps
|
||||
- setNormalDatapoolEntriesInvalid is not an abstract method and a default implementation was provided
|
||||
- getTransitionDelayMs is now an abstract method
|
||||
|
||||
### DeviceHandlerIF
|
||||
|
||||
- Typo for UNKNOWN_DEVICE_REPLY
|
||||
|
||||
### Events
|
||||
|
||||
- makeEvent function: Now takes three input parameters instead of two and
|
||||
allows setting a unique ID. Event.cpp source file removed, functions now
|
||||
defined in header directly. Namespaces renamed. Functions declared `constexpr`
|
||||
now
|
||||
|
||||
### Commanding Service Base
|
||||
|
||||
- CSB uses the new fsfwconfig::FSFW_CSB_FIFO_DEPTH variable to determine the FIFO depth for each
|
||||
CSB instance. This variable has to be set in the FSFWConfig.h file
|
||||
|
||||
### Service Interface
|
||||
|
||||
- Proper printf support contained in ServiceInterfacePrinter.h
|
||||
- CPP ostream support now optional (can reduce executable size by 150 - 250 kB)
|
||||
- Amalagated header which determines automatically which service interface to use depending on FSFWConfig.h configuration.
|
||||
Users can just use #include <fsfw/serviceinterface/ServiceInterface.h>
|
||||
- If CPP streams are excluded, sif:: calls won't work anymore and need to be replaced by their printf counterparts.
|
||||
For the fsfw, this can be done by checking the processor define FSFW_CPP_OSTREAM_ENABLED from FSFWConfig.h.
|
||||
For mission code, developers need to replace sif:: calls by the printf counterparts, but only if the CPP stream are excluded.
|
||||
If this is not the case, everything should work as usual.
|
||||
|
||||
### ActionHelper and ActionMessage
|
||||
|
||||
- ActionHelper finish function and ActionMessage::setCompletionReply now expects explicit
|
||||
information whether to report a success or failure message instead of deriving it implicitely
|
||||
from returnvalue
|
||||
|
||||
### PUS Parameter Service 20
|
||||
|
||||
Added PUS parameter service 20 (only custom subservices available).
|
404
CHANGELOG.md
Normal file
404
CHANGELOG.md
Normal file
@ -0,0 +1,404 @@
|
||||
Change Log
|
||||
=======
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](http://keepachangelog.com/)
|
||||
and this project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
# [unreleased]
|
||||
|
||||
# [v5.0.0]
|
||||
|
||||
## Changes
|
||||
|
||||
- GPIO HAL: Renamed entries of enumerations to avoid nameclashes with Windows defines.
|
||||
`IN` and `OUT` in `Direction` changed to `DIR_IN` and `DIR_OUT`.
|
||||
`CALLBACK` in `GpioTypes` changed to `TYPE_CALLBACK`
|
||||
- HAL Devicehandlers: Periodic printout is run-time configurable now
|
||||
- `oneShotAction` flag in the `TestTask` class is not static anymore
|
||||
|
||||
## Removed
|
||||
|
||||
- Removed the `HkSwitchHelper`. This module should not be needed anymore, now that the local
|
||||
datapools have been implemented
|
||||
|
||||
## Additions
|
||||
|
||||
- Linux HAL: Add wiretapping option for I2C. Enabled with `FSFW_HAL_I2C_WIRETAPPING` defined to 1
|
||||
|
||||
# [v4.0.0]
|
||||
|
||||
## Additions
|
||||
|
||||
- CFDP Packet Stack and related tests added. It also refactors the existing TMTC infastructure to
|
||||
allow sending of CFDP packets to the CCSDS handlers.
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/528
|
||||
- added virtual function to print datasets
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/544
|
||||
- doSendRead Hook
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/545
|
||||
- Dockumentation for DHB
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/551
|
||||
|
||||
### HAL additions
|
||||
|
||||
- Linux Command Executor, which can execute shell commands in blocking and non-blocking mode
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/536
|
||||
- uio Mapper
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/543
|
||||
|
||||
## Changes
|
||||
|
||||
- Applied the `clang-format` auto-formatter to all source code
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/534
|
||||
- Updated Catch2 to v3.0.0-preview4
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/538
|
||||
- Changed CI to use prebuilt docker image
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/549
|
||||
|
||||
## Bugfix
|
||||
|
||||
- CMake fixes in PR https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/533 , was problematic
|
||||
if the uppermost user `CMakeLists.txt` did not have the include paths set up properly, which
|
||||
could lead to compile errors that `#include "fsfw/FSFW.h"` was not found.
|
||||
- Fix for build regression in Catch2 v3.0.0-preview4
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/548
|
||||
- Fix in unittest which failed on CI
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/552
|
||||
- Fix in helper script
|
||||
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/553
|
||||
|
||||
## API Changes
|
||||
|
||||
- Aforementioned changes to existing TMTC stack
|
||||
|
||||
## Known bugs
|
||||
|
||||
-
|
||||
|
||||
# [v3.0.1]
|
||||
|
||||
## API Changes
|
||||
|
||||
*
|
||||
|
||||
## Bugfixes
|
||||
|
||||
* Version number was not updated for v3.0.0 #542
|
||||
|
||||
## Enhancement
|
||||
|
||||
*
|
||||
|
||||
## Known bugs
|
||||
|
||||
*
|
||||
|
||||
# [v3.0.0]
|
||||
|
||||
## API Changes
|
||||
|
||||
#### TCP Socket Changes
|
||||
|
||||
* Keep Open TCP Implementation #496
|
||||
* The socket will now kept open after disconnect. This allows reconnecting.
|
||||
* Only one connection is allowed
|
||||
* No internal influence but clients need to change their Code.
|
||||
|
||||
### GPIO IF
|
||||
|
||||
* Add feature to open GPIO by line name #506
|
||||
|
||||
### Bitutil
|
||||
|
||||
* Unittests for Op Divider and Bitutility #510
|
||||
|
||||
### Filesystem IF changed
|
||||
|
||||
* Filesystem Base Interface: Use IF instead of void pointer #511
|
||||
|
||||
### STM32
|
||||
|
||||
* STM32 SPI Updates #518
|
||||
|
||||
## Bugfixes
|
||||
|
||||
* Small bugfix for LIS3 handler #504
|
||||
* Spelling fixed for function names #509
|
||||
* CMakeLists fixes #517
|
||||
* Out of bound reads and writes in unittests #519
|
||||
* Bug in TmPacketStoredPusC (#478)
|
||||
* Windows ifdef fixed #529
|
||||
|
||||
## Enhancement
|
||||
|
||||
* FSFW.h.in more default values #491
|
||||
* Minor updates for PUS services #498
|
||||
* HasReturnvaluesIF naming for parameter #499
|
||||
* Tests can now be built as part of FSFW and versioning moved to CMake #500
|
||||
* Added integration test code #508
|
||||
* More printouts for rejected TC packets #505
|
||||
* Arrayprinter format improvements #514
|
||||
* Adding code for CI with docker and jenkins #520
|
||||
* Added new function in SerializeAdapter #513
|
||||
* Enables simple deSerialize if you keep track of the buffer position yourself
|
||||
* `` static ReturnValue_t deSerialize(T *object, const uint8_t* buffer,
|
||||
size_t* deserSize, SerializeIF::Endianness streamEndianness) ``
|
||||
* Unittest helper scripts has a new Parameter to open the coverage html in the webrowser #525
|
||||
* ``'-o', '--open', Open coverage data in webbrowser``
|
||||
* Documentation updated. Sphinx Documentation can now be build with python script #526
|
||||
|
||||
## Known bugs
|
||||
|
||||
* Version number was not updated for v3.0.0 #542
|
||||
|
||||
|
||||
All Pull Requests:
|
||||
|
||||
Milestone: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/milestone/19
|
||||
|
||||
# [v2.0.0]
|
||||
|
||||
## API Changes
|
||||
|
||||
|
||||
### File Structure changed to fit more common structure
|
||||
|
||||
* See pull request (#445)
|
||||
* HAL is now part of the main project
|
||||
* **See Instructions below:**
|
||||
|
||||
#### Instruction how to update existing / user code
|
||||
|
||||
* Changes in `#include`:
|
||||
* Rename `internalError` in includes to `internalerror`
|
||||
* Rename `fsfw/hal` to `fsfw_hal`
|
||||
* Rename `fsfw/tests` to `fsfw_tests`
|
||||
* Rename `osal/FreeRTOS` to `osal/freertos`
|
||||
|
||||
* Changes in `CMakeLists.txt`:
|
||||
* Rename `OS_FSFW` to `FSFW_OSAL`
|
||||
|
||||
* Changes in `DleEncoder.cpp`
|
||||
* Create an instance of the `DleEncoder` first before calling the `encode` and `decode` functions
|
||||
|
||||
### Removed osal/linux/Timer (#486)
|
||||
|
||||
* Was redundant to timemanager/Countdown
|
||||
|
||||
#### Instruction how to update existing / user code
|
||||
|
||||
* Use timemanager/Countdown instead
|
||||
|
||||
## Bugfixes
|
||||
|
||||
### TM Stack
|
||||
|
||||
* Increased TM stack robustness by introducing `nullptr` checks and more printouts (#483)
|
||||
|
||||
#### Host OSAL / FreeRTOS
|
||||
|
||||
* QueueMapManager Bugfix (NO_QUEUE was used as MessageQueueId) (#444)
|
||||
|
||||
#### Events
|
||||
|
||||
* Event output is now consistent (#447)
|
||||
|
||||
#### DLE Encoder
|
||||
|
||||
* Fixed possible out of bounds access in DLE Encoder (#492)
|
||||
|
||||
## Enhancment
|
||||
|
||||
* HAL as major new feature, also includes three MEMS devicehandlers as part of #481
|
||||
* Linux HAL updates (#456)
|
||||
* FreeRTOS Header cleaning update and Cmake tweaks (#442)
|
||||
* Printer updates (#453)
|
||||
* New returnvalue for for empty PST (#485)
|
||||
* TMTC Bridge: Increase limit of packets stored (#484)
|
||||
|
||||
## Known bugs
|
||||
|
||||
* Bug in TmPacketStoredPusC (#478)
|
||||
|
||||
|
||||
All Pull Requests:
|
||||
|
||||
Milestone: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/milestone/5
|
||||
|
||||
# [v1.2.0]
|
||||
|
||||
## API Changes
|
||||
|
||||
### FSFW Architecture
|
||||
|
||||
- New src folder which contains all source files except the HAL, contributed code and test code
|
||||
- External and internal API mostly stayed the same
|
||||
- Folder names are now all smaller case: internalError was renamed to internalerror and
|
||||
FreeRTOS was renamed to freertos
|
||||
- Warning if optional headers are used but the modules was not added to the source files to compile
|
||||
|
||||
### HAL
|
||||
|
||||
- HAL added back into FSFW. It is tightly bound to the FSFW, and compiling it as a static library
|
||||
made using it more complicated than necessary
|
||||
|
||||
## Bugfixes
|
||||
|
||||
### FreeRTOS QueueMapManager
|
||||
|
||||
- Fixed a bug which causes the first generated Queue ID to be invalid
|
||||
|
||||
## Enhancements
|
||||
|
||||
### FSFW Architecture
|
||||
|
||||
- See API changes chapter. This change will keep the internal API consistent in the future
|
||||
|
||||
# [v1.1.0]
|
||||
|
||||
## API Changes
|
||||
|
||||
### PUS
|
||||
|
||||
- Added PUS C support
|
||||
- SUBSYSTEM_IDs added for PUS Services
|
||||
- Added new Parameter which must be defined in config: fsfwconfig::FSFW_MAX_TM_PACKET_SIZE
|
||||
|
||||
### ObjectManager
|
||||
|
||||
- ObjectManager is now a singelton
|
||||
|
||||
|
||||
### Configuration
|
||||
|
||||
- Additional configuration option fsfwconfig::FSFW_MAX_TM_PACKET_SIZE which
|
||||
need to be specified in FSFWConfig.h
|
||||
|
||||
### CMake
|
||||
|
||||
- Changed Cmake FSFW_ADDITIONAL_INC_PATH to FSFW_ADDITIONAL_INC_PATHS
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- timemanager/TimeStamperIF.h: Timestamp config was not used correctly, leading to different timestamp sizes than configured in fsfwconfig::FSFW_MISSION_TIMESTAMP_SIZE
|
||||
- TCP server fixes
|
||||
|
||||
## Enhancements
|
||||
|
||||
### FreeRTOS Queue Handles
|
||||
|
||||
- Fixed an internal issue how FreeRTOS MessageQueues were handled
|
||||
|
||||
### Linux OSAL
|
||||
|
||||
- Better printf error messages
|
||||
|
||||
### CMake
|
||||
|
||||
- Check for C++11 as mininimum required Version
|
||||
|
||||
### Debug Output
|
||||
|
||||
- Changed Warning color to magenta, which is well readable on both dark and light mode IDEs
|
||||
|
||||
|
||||
# Changes from ASTP 0.0.1 to 1.0.0
|
||||
|
||||
### Host OSAL
|
||||
|
||||
- Bugfix in MessageQueue, which caused the sender not to be set properly
|
||||
|
||||
### FreeRTOS OSAL
|
||||
|
||||
- vRequestContextSwitchFromISR is declared extern "C" so it can be defined in
|
||||
a C file without issues
|
||||
|
||||
### PUS Services
|
||||
|
||||
- It is now possible to change the message queue depth for the telecommand verification service (PUS1)
|
||||
- The same is possible for the event reporting service (PUS5)
|
||||
- PUS Health Service added, which allows to command and retrieve health via PUS packets
|
||||
|
||||
|
||||
### EnhancedControllerBase
|
||||
|
||||
- New base class for a controller which also implements HasActionsIF and HasLocalDataPoolIF
|
||||
|
||||
### Local Pool
|
||||
|
||||
- Interface of LocalPools has changed. LocalPool is not a template anymore. Instead the size and
|
||||
bucket number of the pools per page and the number of pages are passed to the ctor instead of
|
||||
two ctor arguments and a template parameter
|
||||
|
||||
### Parameter Service
|
||||
|
||||
- The API of the parameter service has been changed to prevent inconsistencies
|
||||
between documentation and actual code and to clarify usage.
|
||||
- The parameter ID now consists of:
|
||||
1. Domain ID (1 byte)
|
||||
2. Unique Identifier (1 byte)
|
||||
3. Linear Index (2 bytes)
|
||||
The linear index can be used for arrays as well as matrices.
|
||||
The parameter load command now explicitely expects the ECSS PTC and PFC
|
||||
information as well as the rows and column number. Rows and column will
|
||||
default to one, which is equivalent to one scalar parameter (the most
|
||||
important use-case)
|
||||
|
||||
### File System Interface
|
||||
|
||||
- A new interfaces specifies the functions for a software object which exposes the file system of
|
||||
a given hardware to use message based file handling (e.g. PUS commanding)
|
||||
|
||||
### Internal Error Reporter
|
||||
|
||||
- The new internal error reporter uses the local data pools. The pool IDs for
|
||||
the exisiting three error values and the new error set will be hardcoded for
|
||||
now, the the constructor for the internal error reporter just takes an object
|
||||
ID for now.
|
||||
|
||||
### Device Handler Base
|
||||
|
||||
- There is an additional `PERFORM_OPERATION` step for the device handler base. It is important
|
||||
that DHB users adapt their polling sequence tables to perform this step. This steps allows for
|
||||
a clear distinction between operation and communication steps
|
||||
- setNormalDatapoolEntriesInvalid is not an abstract method and a default implementation was provided
|
||||
- getTransitionDelayMs is now an abstract method
|
||||
|
||||
### DeviceHandlerIF
|
||||
|
||||
- Typo for UNKNOWN_DEVICE_REPLY
|
||||
|
||||
### Events
|
||||
|
||||
- makeEvent function: Now takes three input parameters instead of two and
|
||||
allows setting a unique ID. Event.cpp source file removed, functions now
|
||||
defined in header directly. Namespaces renamed. Functions declared `constexpr`
|
||||
now
|
||||
|
||||
### Commanding Service Base
|
||||
|
||||
- CSB uses the new fsfwconfig::FSFW_CSB_FIFO_DEPTH variable to determine the FIFO depth for each
|
||||
CSB instance. This variable has to be set in the FSFWConfig.h file
|
||||
|
||||
### Service Interface
|
||||
|
||||
- Proper printf support contained in ServiceInterfacePrinter.h
|
||||
- CPP ostream support now optional (can reduce executable size by 150 - 250 kB)
|
||||
- Amalagated header which determines automatically which service interface to use depending on FSFWConfig.h configuration.
|
||||
Users can just use #include <fsfw/serviceinterface/ServiceInterface.h>
|
||||
- If CPP streams are excluded, sif:: calls won't work anymore and need to be replaced by their printf counterparts.
|
||||
For the fsfw, this can be done by checking the processor define FSFW_CPP_OSTREAM_ENABLED from FSFWConfig.h.
|
||||
For mission code, developers need to replace sif:: calls by the printf counterparts, but only if the CPP stream are excluded.
|
||||
If this is not the case, everything should work as usual.
|
||||
|
||||
### ActionHelper and ActionMessage
|
||||
|
||||
- ActionHelper finish function and ActionMessage::setCompletionReply now expects explicit
|
||||
information whether to report a success or failure message instead of deriving it implicitely
|
||||
from returnvalue
|
||||
|
||||
### PUS Parameter Service 20
|
||||
|
||||
Added PUS parameter service 20 (only custom subservices available).
|
@ -1,9 +1,12 @@
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
|
||||
set(FSFW_VERSION 2)
|
||||
set(FSFW_VERSION 4)
|
||||
set(FSFW_SUBVERSION 0)
|
||||
set(FSFW_REVISION 0)
|
||||
|
||||
# Add the cmake folder so the FindSphinx module is found
|
||||
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH})
|
||||
|
||||
option(FSFW_GENERATE_SECTIONS
|
||||
"Generate function and data sections. Required to remove unused code" ON
|
||||
)
|
||||
@ -12,6 +15,7 @@ if(FSFW_GENERATE_SECTIONS)
|
||||
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()
|
||||
@ -36,7 +40,9 @@ 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)
|
||||
|
||||
project(${LIB_FSFW_NAME})
|
||||
add_library(${LIB_FSFW_NAME})
|
||||
|
||||
if(FSFW_BUILD_UNITTESTS)
|
||||
@ -50,16 +56,17 @@ if(FSFW_BUILD_UNITTESTS)
|
||||
FetchContent_Declare(
|
||||
Catch2
|
||||
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
|
||||
GIT_TAG v3.0.0-preview3
|
||||
GIT_TAG v3.0.0-preview4
|
||||
)
|
||||
|
||||
FetchContent_MakeAvailable(Catch2)
|
||||
#fixes regression -preview4, to be confirmed in later releases
|
||||
set_target_properties(Catch2 PROPERTIES DEBUG_POSTFIX "")
|
||||
endif()
|
||||
|
||||
set(FSFW_CONFIG_PATH tests/src/fsfw_tests/unit/testcfg)
|
||||
configure_file(tests/src/fsfw_tests/unit/testcfg/FSFWConfig.h.in FSFWConfig.h)
|
||||
configure_file(tests/src/fsfw_tests/unit/testcfg/TestsConfig.h.in tests/TestsConfig.h)
|
||||
configure_file(tests/src/fsfw_tests/unit/testcfg/OBSWConfig.h.in OBSWConfig.h)
|
||||
|
||||
project(${FSFW_TEST_TGT} CXX C)
|
||||
add_executable(${FSFW_TEST_TGT})
|
||||
@ -85,7 +92,7 @@ set(FSFW_CORE_INC_PATH "inc")
|
||||
|
||||
set_property(CACHE FSFW_OSAL PROPERTY STRINGS host linux rtems freertos)
|
||||
|
||||
# Configure Files
|
||||
# For configure files
|
||||
target_include_directories(${LIB_FSFW_NAME} PRIVATE
|
||||
${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
@ -147,13 +154,8 @@ else()
|
||||
set(OS_FSFW "host")
|
||||
endif()
|
||||
|
||||
if(FSFW_BUILD_UNITTESTS)
|
||||
configure_file(src/fsfw/FSFW.h.in fsfw/FSFW.h)
|
||||
configure_file(src/fsfw/FSFWVersion.h.in fsfw/FSFWVersion.h)
|
||||
else()
|
||||
configure_file(src/fsfw/FSFW.h.in FSFW.h)
|
||||
configure_file(src/fsfw/FSFWVersion.h.in FSFWVersion.h)
|
||||
endif()
|
||||
configure_file(src/fsfw/FSFW.h.in fsfw/FSFW.h)
|
||||
configure_file(src/fsfw/FSFWVersion.h.in fsfw/FSFWVersion.h)
|
||||
|
||||
message(STATUS "Compiling FSFW for the ${FSFW_OS_NAME} operating system.")
|
||||
|
||||
@ -163,6 +165,9 @@ if(FSFW_ADD_HAL)
|
||||
add_subdirectory(hal)
|
||||
endif()
|
||||
add_subdirectory(contrib)
|
||||
if(FSFW_BUILD_DOCS)
|
||||
add_subdirectory(docs)
|
||||
endif()
|
||||
|
||||
if(FSFW_BUILD_UNITTESTS)
|
||||
if(FSFW_TESTS_GEN_COV)
|
||||
@ -189,13 +194,13 @@ if(FSFW_BUILD_UNITTESTS)
|
||||
"--exclude-unreachable-branches"
|
||||
)
|
||||
set(COVERAGE_EXCLUDES
|
||||
"/c/msys64/mingw64/*"
|
||||
"/c/msys64/mingw64/*" "*/fsfw_hal/*"
|
||||
)
|
||||
elseif(UNIX)
|
||||
set(COVERAGE_EXCLUDES
|
||||
"/usr/include/*" "/usr/bin/*" "Catch2/*"
|
||||
"/usr/local/include/*" "*/fsfw_tests/*"
|
||||
"*/catch2-src/*"
|
||||
"*/catch2-src/*" "*/fsfw_hal/*"
|
||||
)
|
||||
endif()
|
||||
|
||||
@ -234,9 +239,11 @@ endif()
|
||||
# The project CMakeLists file has to set the FSFW_CONFIG_PATH and add it.
|
||||
# If this is not given, we include the default configuration and emit a warning.
|
||||
if(NOT FSFW_CONFIG_PATH)
|
||||
message(WARNING "Flight Software Framework configuration path not set!")
|
||||
set(DEF_CONF_PATH misc/defaultcfg/fsfwconfig)
|
||||
message(WARNING "Setting default configuration from ${DEF_CONF_PATH} ..")
|
||||
if(NOT FSFW_BUILD_DOCS)
|
||||
message(WARNING "Flight Software Framework configuration path not set!")
|
||||
message(WARNING "Setting default configuration from ${DEF_CONF_PATH} ..")
|
||||
endif()
|
||||
add_subdirectory(${DEF_CONF_PATH})
|
||||
set(FSFW_CONFIG_PATH ${DEF_CONF_PATH})
|
||||
endif()
|
||||
@ -274,6 +281,24 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
-Wimplicit-fallthrough=1
|
||||
-Wno-unused-parameter
|
||||
-Wno-psabi
|
||||
-Wduplicated-cond # check for duplicate conditions
|
||||
-Wduplicated-branches # check for duplicate branches
|
||||
-Wlogical-op # Search for bitwise operations instead of logical
|
||||
-Wnull-dereference # Search for NULL dereference
|
||||
-Wundef # Warn if undefind marcos are used
|
||||
-Wformat=2 # Format string problem detection
|
||||
-Wformat-overflow=2 # Formatting issues in printf
|
||||
-Wformat-truncation=2 # Formatting issues in printf
|
||||
-Wformat-security # Search for dangerous printf operations
|
||||
-Wstrict-overflow=3 # Warn if integer overflows might happen
|
||||
-Warray-bounds=2 # Some array bounds violations will be found
|
||||
-Wshift-overflow=2 # Search for bit left shift overflows (<c++14)
|
||||
-Wcast-qual # Warn if the constness is cast away
|
||||
-Wstringop-overflow=4
|
||||
# -Wstack-protector # Emits a few false positives for low level access
|
||||
# -Wconversion # Creates many false positives
|
||||
# -Warith-conversion # Use with Wconversion to find more implicit conversions
|
||||
# -fanalyzer # Should be used to look through problems
|
||||
)
|
||||
endif()
|
||||
|
||||
|
68
README.md
68
README.md
@ -42,7 +42,7 @@ There are some functions like `printChar` which are different depending on the t
|
||||
and need to be implemented by the mission developer.
|
||||
|
||||
A template configuration folder was provided and can be copied into the project root to have
|
||||
a starting point. The [configuration section](doc/README-config.md#top) provides more specific
|
||||
a starting point. The [configuration section](docs/README-config.md#top) provides more specific
|
||||
information about the possible options.
|
||||
|
||||
## Adding the library
|
||||
@ -71,9 +71,9 @@ add and link against the FSFW library in general.
|
||||
|
||||
4. Link against the FSFW library
|
||||
|
||||
```cmake
|
||||
target_link_libraries(<YourProjectName> PRIVATE fsfw)
|
||||
```
|
||||
```cmake
|
||||
target_link_libraries(${YourProjectName} PRIVATE fsfw)
|
||||
```
|
||||
|
||||
5. It should now be possible use the FSFW as a static library from the user code.
|
||||
|
||||
@ -91,7 +91,7 @@ You can use the following commands inside the `fsfw` folder to set up the build
|
||||
|
||||
```sh
|
||||
mkdir build-Unittest && cd build-Unittest
|
||||
cmake -DFSFW_BUILD_UNITTESTS=ON -DFSFW_OSAL=host ..
|
||||
cmake -DFSFW_BUILD_UNITTESTS=ON -DFSFW_OSAL=host -DCMAKE_BUILD_TYPE=Debug ..
|
||||
```
|
||||
|
||||
You can also use `-DFSFW_OSAL=linux` on Linux systems.
|
||||
@ -107,16 +107,58 @@ cmake --build . -- fsfw-tests_coverage -j
|
||||
|
||||
The `coverage.py` script located in the `script` folder can also be used to do this conveniently.
|
||||
|
||||
## Building the documentations
|
||||
|
||||
The FSFW documentation is built using the tools Sphinx, doxygen and breathe based on the
|
||||
instructions provided in [this blogpost](https://devblogs.microsoft.com/cppblog/clear-functional-c-documentation-with-sphinx-breathe-doxygen-cmake/). If you
|
||||
want to do this locally, set up the prerequisites first. This requires a ``python3``
|
||||
installation as well. Example here is for Ubuntu.
|
||||
|
||||
```sh
|
||||
sudo apt-get install doxygen graphviz
|
||||
```
|
||||
|
||||
And the following Python packages
|
||||
|
||||
```sh
|
||||
python3 -m pip install sphinx breathe
|
||||
```
|
||||
|
||||
You can set up a documentation build system using the following commands
|
||||
|
||||
```sh
|
||||
mkdir build-docs && cd build-docs
|
||||
cmake -DFSFW_BUILD_DOCS=ON -DFSFW_OSAL=host ..
|
||||
```
|
||||
|
||||
Then you can generate the documentation using
|
||||
|
||||
```sh
|
||||
cmake --build . -j
|
||||
```
|
||||
|
||||
You can find the generated documentation inside the `docs/sphinx` folder inside the build
|
||||
folder. Simply open the `index.html` in the webbrowser of your choice.
|
||||
|
||||
The `helper.py` script located in the script` folder can also be used to create, build
|
||||
and open the documentation conveniently. Try `helper.py -h for more information.
|
||||
|
||||
## Formatting the sources
|
||||
|
||||
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
|
||||
can run the `apply-clang-format.sh` helper script to format all source files consistently.
|
||||
|
||||
## Index
|
||||
|
||||
[1. High-level overview](doc/README-highlevel.md#top) <br>
|
||||
[2. Core components](doc/README-core.md#top) <br>
|
||||
[3. Configuration](doc/README-config.md#top) <br>
|
||||
[4. OSAL overview](doc/README-osal.md#top) <br>
|
||||
[5. PUS services](doc/README-pus.md#top) <br>
|
||||
[6. Device Handler overview](doc/README-devicehandlers.md#top) <br>
|
||||
[7. Controller overview](doc/README-controllers.md#top) <br>
|
||||
[8. Local Data Pools](doc/README-localpools.md#top) <br>
|
||||
[1. High-level overview](docs/README-highlevel.md#top) <br>
|
||||
[2. Core components](docs/README-core.md#top) <br>
|
||||
[3. Configuration](docs/README-config.md#top) <br>
|
||||
[4. OSAL overview](docs/README-osal.md#top) <br>
|
||||
[5. PUS services](docs/README-pus.md#top) <br>
|
||||
[6. Device Handler overview](docs/README-devicehandlers.md#top) <br>
|
||||
[7. Controller overview](docs/README-controllers.md#top) <br>
|
||||
[8. Local Data Pools](docs/README-localpools.md#top) <br>
|
||||
|
||||
|
||||
|
||||
|
@ -5,4 +5,4 @@ RUN apt-get --yes upgrade
|
||||
|
||||
#tzdata is a dependency, won't install otherwise
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get --yes install gcc g++ cmake make lcov git valgrind nano
|
||||
RUN apt-get --yes install gcc g++ cmake make lcov git valgrind nano iputils-ping
|
||||
|
43
automation/Jenkinsfile
vendored
43
automation/Jenkinsfile
vendored
@ -1,28 +1,17 @@
|
||||
pipeline {
|
||||
agent any
|
||||
environment {
|
||||
BUILDDIR = 'build-unittests'
|
||||
BUILDDIR = 'build-tests'
|
||||
}
|
||||
agent {
|
||||
docker { image 'fsfw-ci:d1'}
|
||||
}
|
||||
stages {
|
||||
stage('Create Docker') {
|
||||
agent {
|
||||
dockerfile {
|
||||
dir 'automation'
|
||||
additionalBuildArgs '--no-cache'
|
||||
reuseNode true
|
||||
}
|
||||
}
|
||||
stage('Clean') {
|
||||
steps {
|
||||
sh 'rm -rf $BUILDDIR'
|
||||
}
|
||||
}
|
||||
stage('Configure') {
|
||||
agent {
|
||||
dockerfile {
|
||||
dir 'automation'
|
||||
reuseNode true
|
||||
}
|
||||
}
|
||||
steps {
|
||||
dir(BUILDDIR) {
|
||||
sh 'cmake -DFSFW_OSAL=host -DFSFW_BUILD_UNITTESTS=ON ..'
|
||||
@ -30,38 +19,20 @@ pipeline {
|
||||
}
|
||||
}
|
||||
stage('Build') {
|
||||
agent {
|
||||
dockerfile {
|
||||
dir 'automation'
|
||||
reuseNode true
|
||||
}
|
||||
}
|
||||
steps {
|
||||
dir(BUILDDIR) {
|
||||
sh 'cmake --build . -j'
|
||||
sh 'cmake --build . -j4'
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Unittests') {
|
||||
agent {
|
||||
dockerfile {
|
||||
dir 'automation'
|
||||
reuseNode true
|
||||
}
|
||||
}
|
||||
steps {
|
||||
dir(BUILDDIR) {
|
||||
sh 'cmake --build . -- fsfw-tests_coverage -j'
|
||||
sh 'cmake --build . -- fsfw-tests_coverage -j4'
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Valgrind') {
|
||||
agent {
|
||||
dockerfile {
|
||||
dir 'automation'
|
||||
reuseNode true
|
||||
}
|
||||
}
|
||||
steps {
|
||||
dir(BUILDDIR) {
|
||||
sh 'valgrind --leak-check=full --error-exitcode=1 ./fsfw-tests'
|
||||
|
13
cmake/FindSphinx.cmake
Normal file
13
cmake/FindSphinx.cmake
Normal file
@ -0,0 +1,13 @@
|
||||
# Look for an executable called sphinx-build
|
||||
find_program(SPHINX_EXECUTABLE
|
||||
NAMES sphinx-build
|
||||
DOC "Path to sphinx-build executable")
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
|
||||
# Handle standard arguments to find_package like REQUIRED and QUIET
|
||||
find_package_handle_standard_args(
|
||||
Sphinx
|
||||
"Failed to find sphinx-build executable"
|
||||
SPHINX_EXECUTABLE
|
||||
)
|
1
docs/.gitignore
vendored
Normal file
1
docs/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/_build
|
66
docs/CMakeLists.txt
Normal file
66
docs/CMakeLists.txt
Normal file
@ -0,0 +1,66 @@
|
||||
# This is based on this excellent posting provided by Sy:
|
||||
# https://devblogs.microsoft.com/cppblog/clear-functional-c-documentation-with-sphinx-breathe-doxygen-cmake/
|
||||
find_package(Doxygen REQUIRED)
|
||||
find_package(Sphinx REQUIRED)
|
||||
|
||||
get_target_property(LIB_FSFW_PUBLIC_HEADER_DIRS ${LIB_FSFW_NAME} INTERFACE_INCLUDE_DIRECTORIES)
|
||||
# TODO: Add HAL as well
|
||||
file(GLOB_RECURSE LIB_FSFW_PUBLIC_HEADERS ${PROJECT_SOURCE_DIR}/src/*.h)
|
||||
file(GLOB_RECURSE RST_DOC_FILES ${PROJECT_SOURCE_DIR}/docs/*.rst)
|
||||
|
||||
set(DOXYGEN_INPUT_DIR ${PROJECT_SOURCE_DIR}/src)
|
||||
set(DOXYGEN_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/doxygen)
|
||||
set(DOXYGEN_INDEX_FILE ${DOXYGEN_OUTPUT_DIR}/xml/index.xml)
|
||||
set(DOXYFILE_IN ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in)
|
||||
set(DOXYFILE_OUT ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile)
|
||||
|
||||
# Replace variables inside @@ with the current values
|
||||
configure_file(${DOXYFILE_IN} ${DOXYFILE_OUT} @ONLY)
|
||||
|
||||
# Doxygen won't create this for us
|
||||
file(MAKE_DIRECTORY ${DOXYGEN_OUTPUT_DIR})
|
||||
|
||||
# Only regenerate Doxygen when the Doxyfile or public headers change
|
||||
add_custom_command(
|
||||
OUTPUT ${DOXYGEN_INDEX_FILE}
|
||||
DEPENDS ${LIB_FSFW_PUBLIC_HEADERS}
|
||||
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYFILE_OUT}
|
||||
MAIN_DEPENDENCY ${DOXYFILE_OUT} ${DOXYFILE_IN}
|
||||
COMMENT "Generating docs"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
# Nice named target so we can run the job easily
|
||||
add_custom_target(Doxygen ALL DEPENDS ${DOXYGEN_INDEX_FILE})
|
||||
|
||||
set(SPHINX_SOURCE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
set(SPHINX_BUILD ${CMAKE_CURRENT_BINARY_DIR}/sphinx)
|
||||
set(SPHINX_INDEX_FILE ${SPHINX_BUILD}/index.html)
|
||||
|
||||
# Only regenerate Sphinx when:
|
||||
# - Doxygen has rerun
|
||||
# - Our doc files have been updated
|
||||
# - The Sphinx config has been updated
|
||||
add_custom_command(
|
||||
OUTPUT ${SPHINX_INDEX_FILE}
|
||||
COMMAND
|
||||
${SPHINX_EXECUTABLE} -b html
|
||||
# Tell Breathe where to find the Doxygen output
|
||||
-Dbreathe_projects.fsfw=${DOXYGEN_OUTPUT_DIR}/xml
|
||||
${SPHINX_SOURCE} ${SPHINX_BUILD}
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
DEPENDS
|
||||
# Other docs files you want to track should go here (or in some variable)
|
||||
${RST_DOC_FILES}
|
||||
${DOXYGEN_INDEX_FILE}
|
||||
MAIN_DEPENDENCY ${SPHINX_SOURCE}/conf.py
|
||||
COMMENT "Generating documentation with Sphinx"
|
||||
)
|
||||
|
||||
# Nice named target so we can run the job easily
|
||||
add_custom_target(Sphinx ALL DEPENDS ${SPHINX_INDEX_FILE})
|
||||
|
||||
# Add an install target to install the docs
|
||||
include(GNUInstallDirs)
|
||||
install(DIRECTORY ${SPHINX_BUILD}
|
||||
DESTINATION ${CMAKE_INSTALL_DOCDIR})
|
7
docs/Doxyfile.in
Normal file
7
docs/Doxyfile.in
Normal file
@ -0,0 +1,7 @@
|
||||
INPUT = "@DOXYGEN_INPUT_DIR@"
|
||||
|
||||
RECURSIVE = YES
|
||||
|
||||
OUTPUT_DIRECTORY = "@DOXYGEN_OUTPUT_DIR@"
|
||||
|
||||
GENERATE_XML = YES
|
20
docs/Makefile
Normal file
20
docs/Makefile
Normal file
@ -0,0 +1,20 @@
|
||||
# Minimal makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line, and also
|
||||
# from the environment for the first two.
|
||||
SPHINXOPTS ?=
|
||||
SPHINXBUILD ?= sphinx-build
|
||||
SOURCEDIR = .
|
||||
BUILDDIR = _build
|
||||
|
||||
# Put it first so that "make" without argument is like "make help".
|
||||
help:
|
||||
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||
|
||||
.PHONY: help Makefile
|
||||
|
||||
# Catch-all target: route all unknown targets to Sphinx using the new
|
||||
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
||||
%: Makefile
|
||||
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
@ -31,7 +31,9 @@ cohesive pool variables. These sets simply iterator over the list of variables a
|
||||
`read` and `commit` functions of each variable. The following diagram shows the
|
||||
high-level architecture of the local data pools.
|
||||
|
||||
<img align="center" src="./images/PoolArchitecture.png" width="50%"> <br>
|
||||
.. 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
|
16
docs/api.rst
Normal file
16
docs/api.rst
Normal file
@ -0,0 +1,16 @@
|
||||
API
|
||||
====
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 4
|
||||
|
||||
api/objectmanager
|
||||
api/task
|
||||
api/ipc
|
||||
api/returnvalue
|
||||
api/event
|
||||
api/modes
|
||||
api/health
|
||||
api/action
|
||||
api/devicehandler
|
||||
api/controller
|
15
docs/api/action.rst
Normal file
15
docs/api/action.rst
Normal file
@ -0,0 +1,15 @@
|
||||
Action Module API
|
||||
=================
|
||||
|
||||
``ActionHelper``
|
||||
-----------------
|
||||
|
||||
.. doxygenclass:: ActionHelper
|
||||
:members:
|
||||
|
||||
``HasActionsIF``
|
||||
-----------------
|
||||
|
||||
.. doxygenclass:: HasActionsIF
|
||||
:members:
|
||||
:protected-members:
|
16
docs/api/controller.rst
Normal file
16
docs/api/controller.rst
Normal file
@ -0,0 +1,16 @@
|
||||
Controller API
|
||||
=================
|
||||
|
||||
``ControllerBase``
|
||||
-------------------------
|
||||
|
||||
.. doxygenclass:: ControllerBase
|
||||
:members:
|
||||
:protected-members:
|
||||
|
||||
``ExtendedControllerBase``
|
||||
-----------------------------
|
||||
|
||||
.. doxygenclass:: ExtendedControllerBase
|
||||
:members:
|
||||
:protected-members:
|
16
docs/api/devicehandler.rst
Normal file
16
docs/api/devicehandler.rst
Normal file
@ -0,0 +1,16 @@
|
||||
Device Handler Base API
|
||||
=========================
|
||||
|
||||
``DeviceHandlerBase``
|
||||
-----------------------
|
||||
|
||||
.. doxygenclass:: DeviceHandlerBase
|
||||
:members:
|
||||
:protected-members:
|
||||
|
||||
``DeviceHandlerIF``
|
||||
-----------------------
|
||||
|
||||
.. doxygenclass:: DeviceHandlerIF
|
||||
:members:
|
||||
:protected-members:
|
6
docs/api/event.rst
Normal file
6
docs/api/event.rst
Normal file
@ -0,0 +1,6 @@
|
||||
.. _eventapi:
|
||||
|
||||
Event API
|
||||
============
|
||||
|
||||
.. doxygenfile:: Event.h
|
9
docs/api/health.rst
Normal file
9
docs/api/health.rst
Normal file
@ -0,0 +1,9 @@
|
||||
Health API
|
||||
===========
|
||||
|
||||
``HasHealthIF``
|
||||
------------------
|
||||
|
||||
.. doxygenclass:: HasHealthIF
|
||||
:members:
|
||||
:protected-members:
|
9
docs/api/ipc.rst
Normal file
9
docs/api/ipc.rst
Normal file
@ -0,0 +1,9 @@
|
||||
IPC Module API
|
||||
=================
|
||||
|
||||
``MessageQueueIF``
|
||||
-------------------
|
||||
|
||||
.. doxygenclass:: MessageQueueIF
|
||||
:members:
|
||||
:protected-members:
|
10
docs/api/modes.rst
Normal file
10
docs/api/modes.rst
Normal file
@ -0,0 +1,10 @@
|
||||
Modes API
|
||||
=========
|
||||
|
||||
|
||||
``HasModesIF``
|
||||
---------------
|
||||
|
||||
.. doxygenclass:: HasModesIF
|
||||
:members:
|
||||
:protected-members:
|
30
docs/api/objectmanager.rst
Normal file
30
docs/api/objectmanager.rst
Normal file
@ -0,0 +1,30 @@
|
||||
Object Manager API
|
||||
=========================
|
||||
|
||||
``SystemObject``
|
||||
--------------------
|
||||
|
||||
.. doxygenclass:: SystemObject
|
||||
:members:
|
||||
:protected-members:
|
||||
|
||||
``ObjectManager``
|
||||
-----------------------
|
||||
|
||||
.. doxygenclass:: ObjectManager
|
||||
:members:
|
||||
:protected-members:
|
||||
|
||||
``SystemObjectIF``
|
||||
--------------------
|
||||
|
||||
.. doxygenclass:: SystemObjectIF
|
||||
:members:
|
||||
:protected-members:
|
||||
|
||||
``ObjectManagerIF``
|
||||
-----------------------
|
||||
|
||||
.. doxygenclass:: ObjectManagerIF
|
||||
:members:
|
||||
:protected-members:
|
10
docs/api/returnvalue.rst
Normal file
10
docs/api/returnvalue.rst
Normal file
@ -0,0 +1,10 @@
|
||||
.. _retvalapi:
|
||||
|
||||
Returnvalue API
|
||||
==================
|
||||
|
||||
.. doxygenfile:: HasReturnvaluesIF.h
|
||||
|
||||
.. _fwclassids:
|
||||
|
||||
.. doxygenfile:: FwClassIds.h
|
8
docs/api/task.rst
Normal file
8
docs/api/task.rst
Normal file
@ -0,0 +1,8 @@
|
||||
Task API
|
||||
=========
|
||||
|
||||
``ExecutableObjectIF``
|
||||
-----------------------
|
||||
|
||||
.. doxygenclass:: ExecutableObjectIF
|
||||
:members:
|
56
docs/conf.py
Normal file
56
docs/conf.py
Normal file
@ -0,0 +1,56 @@
|
||||
# Configuration file for the Sphinx documentation builder.
|
||||
#
|
||||
# This file only contains a selection of the most common options. For a full
|
||||
# list see the documentation:
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html
|
||||
|
||||
# -- Path setup --------------------------------------------------------------
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#
|
||||
# import os
|
||||
# import sys
|
||||
# sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
|
||||
# -- Project information -----------------------------------------------------
|
||||
|
||||
project = 'Flight Software Framework'
|
||||
copyright = '2021, Institute of Space Systems (IRS)'
|
||||
author = 'Institute of Space Systems (IRS)'
|
||||
|
||||
# The full version, including alpha/beta/rc tags
|
||||
release = '2.0.1'
|
||||
|
||||
|
||||
# -- General configuration ---------------------------------------------------
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be
|
||||
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
||||
# ones.
|
||||
extensions = [ "breathe" ]
|
||||
|
||||
breathe_default_project = "fsfw"
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
# This pattern also affects html_static_path and html_extra_path.
|
||||
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
|
||||
|
||||
|
||||
# -- Options for HTML output -------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
#
|
||||
html_theme = 'alabaster'
|
||||
|
||||
# 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,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = []
|
41
docs/config.rst
Normal file
41
docs/config.rst
Normal file
@ -0,0 +1,41 @@
|
||||
Configuring the FSFW
|
||||
=====================
|
||||
|
||||
The FSFW can be configured via the ``fsfwconfig`` folder. A template folder has been provided in
|
||||
``misc/defaultcfg`` 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
|
||||
`fsfwgen Python scripts <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-gen>`_.
|
||||
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/develop/generators>`_
|
||||
or the `FSFW example <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-hosted/src/branch/master/generators>`_
|
||||
|
||||
Configuring the Event Manager
|
||||
----------------------------------
|
||||
|
||||
The number of allowed subscriptions can be modified with the following
|
||||
parameters:
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
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;
|
||||
}
|
2
docs/controllers.rst
Normal file
2
docs/controllers.rst
Normal file
@ -0,0 +1,2 @@
|
||||
Controllers
|
||||
=============
|
70
docs/core.rst
Normal file
70
docs/core.rst
Normal file
@ -0,0 +1,70 @@
|
||||
.. _core:
|
||||
|
||||
Core Modules
|
||||
=============
|
||||
|
||||
The 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
|
||||
|
||||
Object Manager
|
||||
---------------
|
||||
|
||||
- Must be created during program startup
|
||||
- The component which handles all references. All :cpp:class:`SystemObject`\s register at this
|
||||
component.
|
||||
- All :cpp:class:`SystemObject`\s needs to have a unique Object ID. Those can be managed like
|
||||
framework objects.
|
||||
- A reference to an object can be retrieved by calling the ``get`` function of
|
||||
:cpp:class:`ObjectManagerIF`. The target type must be specified as a template argument.
|
||||
A ``nullptr`` check of the returning pointer must be done. This function is based on
|
||||
run-time type information.
|
||||
|
||||
.. code-block:: 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::instance()->initialize(produceFunc)`` the
|
||||
produce function will be called and all :cpp:class:`SystemObject`\s 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
|
||||
|
110
docs/devicehandlers.rst
Normal file
110
docs/devicehandlers.rst
Normal file
@ -0,0 +1,110 @@
|
||||
.. _dhb-prim-doc:
|
||||
|
||||
Device Handlers
|
||||
==================
|
||||
|
||||
Device handler components represent, control and monitor equipment, for example sensors or actuators
|
||||
of a spacecraft or the payload.
|
||||
|
||||
Most device handlers have the same common functionality or
|
||||
requirements, which are fulfilled by implementing certain interfaces:
|
||||
|
||||
- The handler/device needs to be commandable: :cpp:class:`HasActionsIF`
|
||||
- The handler needs to communicate with the physical device via a dedicated
|
||||
communication bus, for example SpaceWire, UART or SPI: :cpp:class:`DeviceCommunicationIF`
|
||||
- The handler has housekeeping data which has to be exposed to the operator and/or other software
|
||||
components: :cpp:class:`HasLocalDataPoolIF`
|
||||
- The handler has configurable parameters: :cpp:class:`ReceivesParameterMessagesIF` which
|
||||
also implements :cpp:class:`HasParametersIF`
|
||||
- The handler has health states, for example to indicate a broken device:
|
||||
:cpp:class:`HasHealthIF`
|
||||
- The handler has modes. For example there are the core modes `MODE_ON`, `MODE_OFF`
|
||||
and `MODE_NORMAL` provided by the FSFW. `MODE_ON` means that a device is physically powered
|
||||
but that it is not periodically polling data from the
|
||||
physical device, `MODE_NORMAL` means that it is able to do that: :cpp:class:`HasModesIF`
|
||||
|
||||
The device handler base therefore provides abstractions for a lot of common
|
||||
functionality, which can potentially avoid high amounts or logic and code duplication.
|
||||
|
||||
Template Device Handler Base File
|
||||
----------------------------------
|
||||
|
||||
This is an example template device handler header file with all necessary
|
||||
functions implemented:
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
#ifndef __TESTDEVICEHANDLER_H_
|
||||
#define __TESTDEVICEHANDLER_H_
|
||||
|
||||
#include <fsfw/devicehandlers/DeviceHandlerBase.h>
|
||||
|
||||
class TestDeviceHandler: DeviceHandlerBase {
|
||||
public:
|
||||
TestDeviceHandler(object_id_t objectId, object_id_t comIF, CookieIF* cookie);
|
||||
private:
|
||||
void doStartUp() override;
|
||||
void doShutDown() override;
|
||||
ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t* id) override;
|
||||
ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t* id) override;
|
||||
void fillCommandAndReplyMap() override;
|
||||
ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t* commandData,
|
||||
size_t commandDataLen) override;
|
||||
ReturnValue_t scanForReply(const uint8_t* start, size_t remainingSize, DeviceCommandId_t* foundId,
|
||||
size_t* foundLen) override;
|
||||
ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t* packet) override;
|
||||
uint32_t getTransitionDelayMs(Mode_t modeFrom, Mode_t modeTo) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool& localDataPoolMap,
|
||||
LocalDataPoolManager& poolManager) override;
|
||||
|
||||
};
|
||||
|
||||
#endif /* __TESTDEVICEHANDLER_H_ */
|
||||
|
||||
and the respective source file with sensible default return values:
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
#include "TestDeviceHandler.h"
|
||||
|
||||
TestDeviceHandler::TestDeviceHandler(object_id_t objectId, object_id_t comIF, CookieIF* cookie)
|
||||
: DeviceHandlerBase(objectId, comIF, cookie) {}
|
||||
|
||||
void TestDeviceHandler::doStartUp() {}
|
||||
|
||||
void TestDeviceHandler::doShutDown() {}
|
||||
|
||||
ReturnValue_t TestDeviceHandler::buildNormalDeviceCommand(DeviceCommandId_t* id) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t TestDeviceHandler::buildTransitionDeviceCommand(DeviceCommandId_t* id) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void TestDeviceHandler::fillCommandAndReplyMap() {}
|
||||
|
||||
ReturnValue_t TestDeviceHandler::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t* commandData,
|
||||
size_t commandDataLen) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t TestDeviceHandler::scanForReply(const uint8_t* start, size_t remainingSize,
|
||||
DeviceCommandId_t* foundId, size_t* foundLen) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t TestDeviceHandler::interpretDeviceReply(DeviceCommandId_t id,
|
||||
const uint8_t* packet) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
uint32_t TestDeviceHandler::getTransitionDelayMs(Mode_t modeFrom, Mode_t modeTo) {
|
||||
return 10000;
|
||||
}
|
||||
|
||||
ReturnValue_t TestDeviceHandler::initializeLocalDataPool(localpool::DataPool& localDataPoolMap,
|
||||
LocalDataPoolManager& poolManager) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
136
docs/getting_started.rst
Normal file
136
docs/getting_started.rst
Normal file
@ -0,0 +1,136 @@
|
||||
Getting Started
|
||||
================
|
||||
|
||||
|
||||
Getting started
|
||||
----------------
|
||||
|
||||
The `Hosted FSFW example`_ provides a good starting point and a demo to see the FSFW capabilities.
|
||||
It is recommended to get started by building and playing around with the demo application.
|
||||
There are also other examples provided for all OSALs using the popular embedded platforms
|
||||
Raspberry Pi, Beagle Bone Black and STM32H7.
|
||||
|
||||
Generally, the FSFW is included in a project by providing
|
||||
a configuration folder, building the static library and linking against it.
|
||||
There are some functions like ``printChar`` which are different depending on the target architecture
|
||||
and need to be implemented by the mission developer.
|
||||
|
||||
A template configuration folder was provided and can be copied into the project root to have
|
||||
a starting point. The [configuration section](docs/README-config.md#top) provides more specific
|
||||
information about the possible options.
|
||||
|
||||
Adding the library
|
||||
-------------------
|
||||
|
||||
The following steps show how to add and use FSFW components. It is still recommended to
|
||||
try out the example mentioned above to get started, but the following steps show how to
|
||||
add and link against the FSFW library in general.
|
||||
|
||||
1. Add this repository as a submodule
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
git submodule add https://egit.irs.uni-stuttgart.de/fsfw/fsfw.git fsfw
|
||||
|
||||
2. Add the following directive inside the uppermost ``CMakeLists.txt`` file of your project
|
||||
|
||||
.. code-block:: cmake
|
||||
|
||||
add_subdirectory(fsfw)
|
||||
|
||||
3. Make sure to provide a configuration folder and supply the path to that folder with
|
||||
the `FSFW_CONFIG_PATH` CMake variable from the uppermost `CMakeLists.txt` file.
|
||||
It is also necessary to provide the `printChar` function. You can find an example
|
||||
implementation for a hosted build
|
||||
`here <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-hosted/src/branch/master/bsp_hosted/utility/printChar.c>`_.
|
||||
|
||||
4. Link against the FSFW library
|
||||
|
||||
.. code-block:: cmake
|
||||
|
||||
target_link_libraries(<YourProjectName> PRIVATE fsfw)
|
||||
|
||||
|
||||
5. It should now be possible use the FSFW as a static library from the user code.
|
||||
|
||||
Building the unittests
|
||||
-------------------------
|
||||
|
||||
The FSFW also has unittests which use the `Catch2 library`_.
|
||||
These are built by setting the CMake option ``FSFW_BUILD_UNITTESTS`` to ``ON`` or `TRUE`
|
||||
from your project `CMakeLists.txt` file or from the command line.
|
||||
|
||||
The fsfw-tests binary will be built as part of the static library and dropped alongside it.
|
||||
If the unittests are built, the library and the tests will be built with coverage information by
|
||||
default. This can be disabled by setting the `FSFW_TESTS_COV_GEN` option to `OFF` or `FALSE`.
|
||||
|
||||
You can use the following commands inside the ``fsfw`` folder to set up the build system
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
mkdir build-tests && cd build-tests
|
||||
cmake -DFSFW_BUILD_UNITTESTS=ON -DFSFW_OSAL=host ..
|
||||
|
||||
|
||||
You can also use ``-DFSFW_OSAL=linux`` on Linux systems.
|
||||
|
||||
Coverage data in HTML format can be generated using the `Code coverage`_ CMake module.
|
||||
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
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
cmake --build . -- fsfw-tests_coverage -j
|
||||
|
||||
|
||||
The ``helper.py`` script located in the ``script`` folder can also be used to create, build
|
||||
and open the unittests conveniently. Try ``helper.py -h`` for more information.
|
||||
|
||||
Building the documentation
|
||||
----------------------------
|
||||
|
||||
The FSFW documentation is built using the tools Sphinx, doxygen and breathe based on the
|
||||
instructions provided in `this blogpost <https://devblogs.microsoft.com/cppblog/clear-functional-c-documentation-with-sphinx-breathe-doxygen-cmake/>`_. If you
|
||||
want to do this locally, set up the prerequisites first. This requires a ``python3``
|
||||
installation as well. Example here is for Ubuntu.
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
sudo apt-get install doxygen graphviz
|
||||
|
||||
And the following Python packages
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
python3 -m pip install sphinx breathe
|
||||
|
||||
You can set up a documentation build system using the following commands
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
mkdir build-docs && cd build-docs
|
||||
cmake -DFSFW_BUILD_DOCS=ON -DFSFW_OSAL=host ..
|
||||
|
||||
Then you can generate the documentation using
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
cmake --build . -j
|
||||
|
||||
You can find the generated documentation inside the ``docs/sphinx`` folder inside the build
|
||||
folder. Simply open the ``index.html`` in the webbrowser of your choice.
|
||||
|
||||
The ``helper.py`` script located in the ``script`` folder can also be used to create, build
|
||||
and open the documentation conveniently. Try ``helper.py -h`` for more information.
|
||||
|
||||
Formatting the source
|
||||
-----------------------
|
||||
|
||||
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
|
||||
can run the ``apply-clang-format.sh`` helper script to format all source files consistently.
|
||||
|
||||
|
||||
.. _`Hosted FSFW example`: https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-hosted
|
||||
.. _`Catch2 library`: https://github.com/catchorg/Catch2
|
||||
.. _`Code coverage`: https://github.com/bilke/cmake-modules/tree/master
|
149
docs/highlevel.rst
Normal file
149
docs/highlevel.rst
Normal file
@ -0,0 +1,149 @@
|
||||
.. _highlevel:
|
||||
|
||||
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 :cpp:type:`ReturnValue_t` to signal to the caller that something has
|
||||
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.
|
||||
See the :ref:`FSFW Class IDs file <fwclassids>`. 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 :ref:`OSAL README <osal>` 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
|
||||
:ref:`core component section <core>`:
|
||||
|
||||
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.
|
||||
4. Clock: This module provided common time related functions
|
||||
5. EventManager: This module allows routing of events generated by `SystemObjects`
|
||||
6. 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 ``misc/defaultcfg/fsfwconfig/objects``
|
||||
inside the function ``Factory::setStaticFrameworkObjectIds``.
|
||||
|
||||
Events
|
||||
----------------
|
||||
|
||||
Events are tied to objects. EventIds can be generated by calling the
|
||||
:ref:`macro MAKE_EVENT <eventapi>` or the function :cpp:func:`event::makeEvent`.
|
||||
This works analog to the returnvalues. Every object that needs own Event IDs has to get a
|
||||
unique ``SUBSYSTEM_ID``. Every :cpp:class:`SystemObject` can call
|
||||
:cpp:func:`SystemObject::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/robamu-org/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 :ref:`documentation section <dhb-prim-doc>`.
|
||||
|
||||
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.
|
||||
|
||||
- Device handlers 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 top level subsystem components
|
||||
- The top level subsystem components are used to group assemblies, controllers and device handlers.
|
||||
For example, a spacecraft can have a atttitude control subsystem and a power subsystem.
|
||||
|
||||
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.
|
After Width: | Height: | Size: 52 KiB |
69
docs/index.rst
Normal file
69
docs/index.rst
Normal file
@ -0,0 +1,69 @@
|
||||
.. Flight Software Framework documentation master file, created by
|
||||
sphinx-quickstart on Tue Nov 30 10:56:03 2021.
|
||||
You can adapt this file completely to your liking, but it should at least
|
||||
contain the root `toctree` directive.
|
||||
|
||||
Flight Software Framework (FSFW) documentation
|
||||
================================================
|
||||
|
||||
.. image:: ../misc/logo/FSFW_Logo_V3_bw.png
|
||||
:alt: FSFW Logo
|
||||
|
||||
The Flight Software Framework is a C++ Object Oriented Framework for unmanned,
|
||||
automated systems like Satellites.
|
||||
|
||||
The initial version of the Flight Software Framework was developed during
|
||||
the Flying Laptop Project by the University of Stuttgart in cooperation
|
||||
with Airbus Defence and Space GmbH.
|
||||
|
||||
Quick facts
|
||||
---------------
|
||||
|
||||
The framework is designed for systems, which communicate with external devices, perform control
|
||||
loops, receive telecommands and send telemetry, and need to maintain a high level of availability.
|
||||
Therefore, a mode and health system provides control over the states of the software and the
|
||||
controlled devices. In addition, a simple mechanism of event based fault detection, isolation and
|
||||
recovery is implemented as well.
|
||||
|
||||
The FSFW provides abstraction layers for operating systems to provide a uniform operating system
|
||||
abstraction layer (OSAL). Some components of this OSAL are required internally by the FSFW but is
|
||||
also very useful for developers to implement the same application logic on different operating
|
||||
systems with a uniform interface.
|
||||
|
||||
Currently, the FSFW provides the following OSALs:
|
||||
|
||||
- Linux
|
||||
- Host
|
||||
- FreeRTOS
|
||||
- RTEMS
|
||||
|
||||
The recommended hardware is a microprocessor with more than 1 MB of RAM and 1 MB of non-volatile
|
||||
memory. For reference, current applications use a Cobham Gaisler UT699 (LEON3FT), a
|
||||
ISISPACE IOBC or a Zynq-7020 SoC. The ``fsfw`` was also successfully run on the
|
||||
STM32H743ZI-Nucleo board and on a Raspberry Pi and is currently running on the active
|
||||
satellite mission Flying Laptop.
|
||||
|
||||
Index
|
||||
-------
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: Contents:
|
||||
|
||||
getting_started
|
||||
highlevel
|
||||
core
|
||||
config
|
||||
osal
|
||||
pus
|
||||
devicehandlers
|
||||
controllers
|
||||
localpools
|
||||
api
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
181
docs/localpools.rst
Normal file
181
docs/localpools.rst
Normal file
@ -0,0 +1,181 @@
|
||||
Local Data Pools
|
||||
=========================================
|
||||
|
||||
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:: ../docs/images/PoolArchitecture.png
|
||||
:alt: Pool Architecture
|
||||
|
||||
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:
|
||||
|
||||
.. code-block:: 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, the ``GyroHandler`` will now have the set class
|
||||
as a member:
|
||||
|
||||
.. code-block:: 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:
|
||||
|
||||
.. code-block:: 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:
|
||||
|
||||
.. code-block:: 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.
|
||||
|
||||
.. code-block:: 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:
|
||||
|
||||
.. code-block:: 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
|
||||
|
||||
|
35
docs/make.bat
Normal file
35
docs/make.bat
Normal file
@ -0,0 +1,35 @@
|
||||
@ECHO OFF
|
||||
|
||||
pushd %~dp0
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set SOURCEDIR=.
|
||||
set BUILDDIR=_build
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
%SPHINXBUILD% >NUL 2>NUL
|
||||
if errorlevel 9009 (
|
||||
echo.
|
||||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||
echo.may add the Sphinx directory to PATH.
|
||||
echo.
|
||||
echo.If you don't have Sphinx installed, grab it from
|
||||
echo.http://sphinx-doc.org/
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||
goto end
|
||||
|
||||
:help
|
||||
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||
|
||||
:end
|
||||
popd
|
63
docs/osal.rst
Normal file
63
docs/osal.rst
Normal file
@ -0,0 +1,63 @@
|
||||
.. _osal:
|
||||
|
||||
Operating System Abstraction Layer (OSAL)
|
||||
============================================
|
||||
|
||||
Some specific information on the provided OSALs are provided.
|
||||
|
||||
Linux
|
||||
-------
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Example Applications
|
||||
----------------------
|
||||
|
||||
There are example applications available for each OSAL
|
||||
|
||||
- `Hosted OSAL <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-hosted>`_
|
||||
- `Linux OSAL for MCUs <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-linux-mcu>`_
|
||||
- `FreeRTOS OSAL on the STM32H743ZIT <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-stm32h7-freertos>`_
|
||||
- `RTEMS OSAL on the STM32H743ZIT <https://egit.irs.uni-stuttgart.de/fsfw/fsfw-example-stm32h7-rtems>`_
|
2
docs/pus.rst
Normal file
2
docs/pus.rst
Normal file
@ -0,0 +1,2 @@
|
||||
PUS Services
|
||||
==============
|
@ -3,7 +3,14 @@ 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. Required gpiod library" OFF)
|
||||
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)
|
||||
|
@ -1,7 +1,7 @@
|
||||
add_subdirectory(devicehandlers)
|
||||
add_subdirectory(common)
|
||||
|
||||
if(FSFW_HAL_ADD_LINUX)
|
||||
if(UNIX)
|
||||
add_subdirectory(linux)
|
||||
endif()
|
||||
|
||||
|
@ -1,50 +1,48 @@
|
||||
#include "fsfw_hal/common/gpio/GpioCookie.h"
|
||||
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
|
||||
GpioCookie::GpioCookie() {
|
||||
}
|
||||
GpioCookie::GpioCookie() {}
|
||||
|
||||
ReturnValue_t GpioCookie::addGpio(gpioId_t gpioId, GpioBase* gpioConfig) {
|
||||
if (gpioConfig == nullptr) {
|
||||
if (gpioConfig == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "GpioCookie::addGpio: gpioConfig is nullpointer" << std::endl;
|
||||
sif::warning << "GpioCookie::addGpio: gpioConfig is nullpointer" << std::endl;
|
||||
#else
|
||||
sif::printWarning("GpioCookie::addGpio: gpioConfig is nullpointer\n");
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
auto gpioMapIter = gpioMap.find(gpioId);
|
||||
if(gpioMapIter == gpioMap.end()) {
|
||||
auto statusPair = gpioMap.emplace(gpioId, gpioConfig);
|
||||
if (statusPair.second == false) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "GpioCookie::addGpio: Failed to add GPIO " << gpioId <<
|
||||
" to GPIO map" << std::endl;
|
||||
#else
|
||||
sif::printWarning("GpioCookie::addGpio: Failed to add GPIO %d to GPIO map\n", gpioId);
|
||||
#endif
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "GpioCookie::addGpio: GPIO already exists in GPIO map " << std::endl;
|
||||
#else
|
||||
sif::printWarning("GpioCookie::addGpio: GPIO already exists in GPIO map\n");
|
||||
#endif
|
||||
sif::printWarning("GpioCookie::addGpio: gpioConfig is nullpointer\n");
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
auto gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()) {
|
||||
auto statusPair = gpioMap.emplace(gpioId, gpioConfig);
|
||||
if (statusPair.second == false) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "GpioCookie::addGpio: Failed to add GPIO " << gpioId << " to GPIO map"
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("GpioCookie::addGpio: Failed to add GPIO %d to GPIO map\n", gpioId);
|
||||
#endif
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "GpioCookie::addGpio: GPIO already exists in GPIO map " << std::endl;
|
||||
#else
|
||||
sif::printWarning("GpioCookie::addGpio: GPIO already exists in GPIO map\n");
|
||||
#endif
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
GpioMap GpioCookie::getGpioMap() const {
|
||||
return gpioMap;
|
||||
}
|
||||
GpioMap GpioCookie::getGpioMap() const { return gpioMap; }
|
||||
|
||||
GpioCookie::~GpioCookie() {
|
||||
for(auto& config: gpioMap) {
|
||||
delete(config.second);
|
||||
}
|
||||
for (auto& config : gpioMap) {
|
||||
delete (config.second);
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,12 @@
|
||||
#ifndef COMMON_GPIO_GPIOCOOKIE_H_
|
||||
#define COMMON_GPIO_GPIOCOOKIE_H_
|
||||
|
||||
#include "GpioIF.h"
|
||||
#include "gpioDefinitions.h"
|
||||
|
||||
#include <fsfw/devicehandlers/CookieIF.h>
|
||||
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
|
||||
|
||||
#include "GpioIF.h"
|
||||
#include "gpioDefinitions.h"
|
||||
|
||||
/**
|
||||
* @brief Cookie for the GpioIF. Allows the GpioIF to determine which
|
||||
* GPIOs to initialize and whether they should be configured as in- or
|
||||
@ -17,25 +17,24 @@
|
||||
*
|
||||
* @author J. Meier
|
||||
*/
|
||||
class GpioCookie: public CookieIF {
|
||||
public:
|
||||
class GpioCookie : public CookieIF {
|
||||
public:
|
||||
GpioCookie();
|
||||
|
||||
GpioCookie();
|
||||
virtual ~GpioCookie();
|
||||
|
||||
virtual ~GpioCookie();
|
||||
ReturnValue_t addGpio(gpioId_t gpioId, GpioBase* gpioConfig);
|
||||
|
||||
ReturnValue_t addGpio(gpioId_t gpioId, GpioBase* gpioConfig);
|
||||
/**
|
||||
* @brief Get map with registered GPIOs.
|
||||
*/
|
||||
GpioMap getGpioMap() const;
|
||||
|
||||
/**
|
||||
* @brief Get map with registered GPIOs.
|
||||
*/
|
||||
GpioMap getGpioMap() const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* Returns a copy of the internal GPIO map.
|
||||
*/
|
||||
GpioMap gpioMap;
|
||||
private:
|
||||
/**
|
||||
* Returns a copy of the internal GPIO map.
|
||||
*/
|
||||
GpioMap gpioMap;
|
||||
};
|
||||
|
||||
#endif /* COMMON_GPIO_GPIOCOOKIE_H_ */
|
||||
|
@ -1,9 +1,10 @@
|
||||
#ifndef COMMON_GPIO_GPIOIF_H_
|
||||
#define COMMON_GPIO_GPIOIF_H_
|
||||
|
||||
#include "gpioDefinitions.h"
|
||||
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
|
||||
#include <fsfw/devicehandlers/CookieIF.h>
|
||||
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
|
||||
|
||||
#include "gpioDefinitions.h"
|
||||
|
||||
class GpioCookie;
|
||||
|
||||
@ -13,42 +14,41 @@ class GpioCookie;
|
||||
* @author J. Meier
|
||||
*/
|
||||
class GpioIF : public HasReturnvaluesIF {
|
||||
public:
|
||||
public:
|
||||
virtual ~GpioIF(){};
|
||||
|
||||
virtual ~GpioIF() {};
|
||||
/**
|
||||
* @brief Called by the GPIO using object.
|
||||
* @param cookie Cookie specifying informations of the GPIOs required
|
||||
* by a object.
|
||||
*/
|
||||
virtual ReturnValue_t addGpios(GpioCookie* cookie) = 0;
|
||||
|
||||
/**
|
||||
* @brief Called by the GPIO using object.
|
||||
* @param cookie Cookie specifying informations of the GPIOs required
|
||||
* by a object.
|
||||
*/
|
||||
virtual ReturnValue_t addGpios(GpioCookie* cookie) = 0;
|
||||
/**
|
||||
* @brief By implementing this function a child must provide the
|
||||
* functionality to pull a certain GPIO to high logic level.
|
||||
*
|
||||
* @param gpioId A unique number which specifies the GPIO to drive.
|
||||
* @return Returns RETURN_OK for success. This should never return RETURN_FAILED.
|
||||
*/
|
||||
virtual ReturnValue_t pullHigh(gpioId_t gpioId) = 0;
|
||||
|
||||
/**
|
||||
* @brief By implementing this function a child must provide the
|
||||
* functionality to pull a certain GPIO to high logic level.
|
||||
*
|
||||
* @param gpioId A unique number which specifies the GPIO to drive.
|
||||
* @return Returns RETURN_OK for success. This should never return RETURN_FAILED.
|
||||
*/
|
||||
virtual ReturnValue_t pullHigh(gpioId_t gpioId) = 0;
|
||||
/**
|
||||
* @brief By implementing this function a child must provide the
|
||||
* functionality to pull a certain GPIO to low logic level.
|
||||
*
|
||||
* @param gpioId A unique number which specifies the GPIO to drive.
|
||||
*/
|
||||
virtual ReturnValue_t pullLow(gpioId_t gpioId) = 0;
|
||||
|
||||
/**
|
||||
* @brief By implementing this function a child must provide the
|
||||
* functionality to pull a certain GPIO to low logic level.
|
||||
*
|
||||
* @param gpioId A unique number which specifies the GPIO to drive.
|
||||
*/
|
||||
virtual ReturnValue_t pullLow(gpioId_t gpioId) = 0;
|
||||
|
||||
/**
|
||||
* @brief This function requires a child to implement the functionality to read the state of
|
||||
* an ouput or input gpio.
|
||||
*
|
||||
* @param gpioId A unique number which specifies the GPIO to read.
|
||||
* @param gpioState State of GPIO will be written to this pointer.
|
||||
*/
|
||||
virtual ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) = 0;
|
||||
/**
|
||||
* @brief This function requires a child to implement the functionality to read the state of
|
||||
* an ouput or input gpio.
|
||||
*
|
||||
* @param gpioId A unique number which specifies the GPIO to read.
|
||||
* @param gpioState State of GPIO will be written to this pointer.
|
||||
*/
|
||||
virtual ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) = 0;
|
||||
};
|
||||
|
||||
#endif /* COMMON_GPIO_GPIOIF_H_ */
|
||||
|
@ -1,44 +1,34 @@
|
||||
#ifndef COMMON_GPIO_GPIODEFINITIONS_H_
|
||||
#define COMMON_GPIO_GPIODEFINITIONS_H_
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <map>
|
||||
|
||||
using gpioId_t = uint16_t;
|
||||
|
||||
namespace gpio {
|
||||
|
||||
enum Levels: uint8_t {
|
||||
LOW = 0,
|
||||
HIGH = 1,
|
||||
NONE = 99
|
||||
};
|
||||
enum class Levels : int { LOW = 0, HIGH = 1, NONE = 99 };
|
||||
|
||||
enum Direction: uint8_t {
|
||||
IN = 0,
|
||||
OUT = 1
|
||||
};
|
||||
enum class Direction : int { IN = 0, OUT = 1 };
|
||||
|
||||
enum GpioOperation {
|
||||
READ,
|
||||
WRITE
|
||||
};
|
||||
enum class GpioOperation { READ, WRITE };
|
||||
|
||||
enum class GpioTypes {
|
||||
NONE,
|
||||
GPIO_REGULAR_BY_CHIP,
|
||||
GPIO_REGULAR_BY_LABEL,
|
||||
GPIO_REGULAR_BY_LINE_NAME,
|
||||
CALLBACK
|
||||
NONE,
|
||||
GPIO_REGULAR_BY_CHIP,
|
||||
GPIO_REGULAR_BY_LABEL,
|
||||
GPIO_REGULAR_BY_LINE_NAME,
|
||||
CALLBACK
|
||||
};
|
||||
|
||||
static constexpr gpioId_t NO_GPIO = -1;
|
||||
|
||||
using gpio_cb_t = void (*) (gpioId_t gpioId, gpio::GpioOperation gpioOp, gpio::Levels value,
|
||||
void* args);
|
||||
using gpio_cb_t = void (*)(gpioId_t gpioId, gpio::GpioOperation gpioOp, gpio::Levels value,
|
||||
void* args);
|
||||
|
||||
}
|
||||
} // namespace gpio
|
||||
|
||||
/**
|
||||
* @brief Struct containing information about the GPIO to use. This is
|
||||
@ -55,78 +45,71 @@ using gpio_cb_t = void (*) (gpioId_t gpioId, gpio::GpioOperation gpioOp, gpio::L
|
||||
* pointer.
|
||||
*/
|
||||
class GpioBase {
|
||||
public:
|
||||
public:
|
||||
GpioBase() = default;
|
||||
|
||||
GpioBase() = default;
|
||||
GpioBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue)
|
||||
: gpioType(gpioType), consumer(consumer), direction(direction), initValue(initValue) {}
|
||||
|
||||
GpioBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue):
|
||||
gpioType(gpioType), consumer(consumer),direction(direction), initValue(initValue) {}
|
||||
virtual ~GpioBase(){};
|
||||
|
||||
virtual~ GpioBase() {};
|
||||
|
||||
// Can be used to cast GpioBase to a concrete child implementation
|
||||
gpio::GpioTypes gpioType = gpio::GpioTypes::NONE;
|
||||
std::string consumer;
|
||||
gpio::Direction direction = gpio::Direction::IN;
|
||||
gpio::Levels initValue = gpio::Levels::NONE;
|
||||
// Can be used to cast GpioBase to a concrete child implementation
|
||||
gpio::GpioTypes gpioType = gpio::GpioTypes::NONE;
|
||||
std::string consumer;
|
||||
gpio::Direction direction = gpio::Direction::IN;
|
||||
gpio::Levels initValue = gpio::Levels::NONE;
|
||||
};
|
||||
|
||||
class GpiodRegularBase: public GpioBase {
|
||||
public:
|
||||
GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue, int lineNum):
|
||||
GpioBase(gpioType, consumer, direction, initValue), lineNum(lineNum) {
|
||||
}
|
||||
class GpiodRegularBase : public GpioBase {
|
||||
public:
|
||||
GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue, int lineNum)
|
||||
: GpioBase(gpioType, consumer, direction, initValue), lineNum(lineNum) {}
|
||||
|
||||
// line number will be configured at a later point for the open by line name configuration
|
||||
GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue): GpioBase(gpioType, consumer, direction, initValue) {
|
||||
}
|
||||
// line number will be configured at a later point for the open by line name configuration
|
||||
GpiodRegularBase(gpio::GpioTypes gpioType, std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue)
|
||||
: GpioBase(gpioType, consumer, direction, initValue) {}
|
||||
|
||||
int lineNum = 0;
|
||||
struct gpiod_line* lineHandle = nullptr;
|
||||
int lineNum = 0;
|
||||
struct gpiod_line* lineHandle = nullptr;
|
||||
};
|
||||
|
||||
class GpiodRegularByChip: public GpiodRegularBase {
|
||||
public:
|
||||
GpiodRegularByChip() :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP,
|
||||
std::string(), gpio::Direction::IN, gpio::LOW, 0) {
|
||||
}
|
||||
class GpiodRegularByChip : public GpiodRegularBase {
|
||||
public:
|
||||
GpiodRegularByChip()
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, std::string(), gpio::Direction::IN,
|
||||
gpio::Levels::LOW, 0) {}
|
||||
|
||||
GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_,
|
||||
gpio::Direction direction_, gpio::Levels initValue_) :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP,
|
||||
consumer_, direction_, initValue_, lineNum_),
|
||||
chipname(chipname_){
|
||||
}
|
||||
GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_,
|
||||
gpio::Direction direction_, gpio::Levels initValue_)
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, consumer_, direction_, initValue_,
|
||||
lineNum_),
|
||||
chipname(chipname_) {}
|
||||
|
||||
GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_) :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, consumer_,
|
||||
gpio::Direction::IN, gpio::LOW, lineNum_),
|
||||
chipname(chipname_) {
|
||||
}
|
||||
GpiodRegularByChip(std::string chipname_, int lineNum_, std::string consumer_)
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP, consumer_, gpio::Direction::IN,
|
||||
gpio::Levels::LOW, lineNum_),
|
||||
chipname(chipname_) {}
|
||||
|
||||
std::string chipname;
|
||||
std::string chipname;
|
||||
};
|
||||
|
||||
class GpiodRegularByLabel: public GpiodRegularBase {
|
||||
public:
|
||||
GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_,
|
||||
gpio::Direction direction_, gpio::Levels initValue_) :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_,
|
||||
direction_, initValue_, lineNum_),
|
||||
label(label_) {
|
||||
}
|
||||
class GpiodRegularByLabel : public GpiodRegularBase {
|
||||
public:
|
||||
GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_,
|
||||
gpio::Direction direction_, gpio::Levels initValue_)
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_, direction_, initValue_,
|
||||
lineNum_),
|
||||
label(label_) {}
|
||||
|
||||
GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_) :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_,
|
||||
gpio::Direction::IN, gpio::LOW, lineNum_),
|
||||
label(label_) {
|
||||
}
|
||||
GpiodRegularByLabel(std::string label_, int lineNum_, std::string consumer_)
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL, consumer_, gpio::Direction::IN,
|
||||
gpio::Levels::LOW, lineNum_),
|
||||
label(label_) {}
|
||||
|
||||
std::string label;
|
||||
std::string label;
|
||||
};
|
||||
|
||||
/**
|
||||
@ -134,34 +117,34 @@ public:
|
||||
* line name. This line name can be set in the device tree and must be unique. Otherwise
|
||||
* the driver will open the first line with the given name.
|
||||
*/
|
||||
class GpiodRegularByLineName: public GpiodRegularBase {
|
||||
public:
|
||||
GpiodRegularByLineName(std::string lineName_, std::string consumer_, gpio::Direction direction_,
|
||||
gpio::Levels initValue_) :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, direction_,
|
||||
initValue_), lineName(lineName_) {
|
||||
}
|
||||
class GpiodRegularByLineName : public GpiodRegularBase {
|
||||
public:
|
||||
GpiodRegularByLineName(std::string lineName_, std::string consumer_, gpio::Direction direction_,
|
||||
gpio::Levels initValue_)
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, direction_,
|
||||
initValue_),
|
||||
lineName(lineName_) {}
|
||||
|
||||
GpiodRegularByLineName(std::string lineName_, std::string consumer_) :
|
||||
GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_,
|
||||
gpio::Direction::IN, gpio::LOW), lineName(lineName_) {
|
||||
}
|
||||
GpiodRegularByLineName(std::string lineName_, std::string consumer_)
|
||||
: GpiodRegularBase(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME, consumer_, gpio::Direction::IN,
|
||||
gpio::Levels::LOW),
|
||||
lineName(lineName_) {}
|
||||
|
||||
std::string lineName;
|
||||
std::string lineName;
|
||||
};
|
||||
|
||||
class GpioCallback: public GpioBase {
|
||||
public:
|
||||
GpioCallback(std::string consumer, gpio::Direction direction_, gpio::Levels initValue_,
|
||||
gpio::gpio_cb_t callback, void* callbackArgs):
|
||||
GpioBase(gpio::GpioTypes::CALLBACK, consumer, direction_, initValue_),
|
||||
callback(callback), callbackArgs(callbackArgs) {}
|
||||
class GpioCallback : public GpioBase {
|
||||
public:
|
||||
GpioCallback(std::string consumer, gpio::Direction direction_, gpio::Levels initValue_,
|
||||
gpio::gpio_cb_t callback, void* callbackArgs)
|
||||
: GpioBase(gpio::GpioTypes::CALLBACK, consumer, direction_, initValue_),
|
||||
callback(callback),
|
||||
callbackArgs(callbackArgs) {}
|
||||
|
||||
gpio::gpio_cb_t callback = nullptr;
|
||||
void* callbackArgs = nullptr;
|
||||
gpio::gpio_cb_t callback = nullptr;
|
||||
void* callbackArgs = nullptr;
|
||||
};
|
||||
|
||||
|
||||
using GpioMap = std::map<gpioId_t, GpioBase*>;
|
||||
using GpioUnorderedMap = std::unordered_map<gpioId_t, GpioBase*>;
|
||||
using GpioMapIter = GpioMap::iterator;
|
||||
|
@ -5,12 +5,7 @@
|
||||
|
||||
namespace spi {
|
||||
|
||||
enum SpiModes: uint8_t {
|
||||
MODE_0,
|
||||
MODE_1,
|
||||
MODE_2,
|
||||
MODE_3
|
||||
};
|
||||
enum SpiModes : uint8_t { MODE_0, MODE_1, MODE_2, MODE_3 };
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,287 +1,275 @@
|
||||
#include "GyroL3GD20Handler.h"
|
||||
|
||||
#include "fsfw/datapool/PoolReadGuard.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "fsfw/datapool/PoolReadGuard.h"
|
||||
|
||||
GyroHandlerL3GD20H::GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication,
|
||||
CookieIF *comCookie, uint32_t transitionDelayMs):
|
||||
DeviceHandlerBase(objectId, deviceCommunication, comCookie),
|
||||
transitionDelayMs(transitionDelayMs), dataset(this) {
|
||||
#if FSFW_HAL_L3GD20_GYRO_DEBUG == 1
|
||||
debugDivider = new PeriodicOperationDivider(3);
|
||||
#endif
|
||||
}
|
||||
CookieIF *comCookie, uint32_t transitionDelayMs)
|
||||
: DeviceHandlerBase(objectId, deviceCommunication, comCookie),
|
||||
transitionDelayMs(transitionDelayMs),
|
||||
dataset(this) {}
|
||||
|
||||
GyroHandlerL3GD20H::~GyroHandlerL3GD20H() {}
|
||||
|
||||
void GyroHandlerL3GD20H::doStartUp() {
|
||||
if(internalState == InternalState::NONE) {
|
||||
internalState = InternalState::CONFIGURE;
|
||||
}
|
||||
if (internalState == InternalState::NONE) {
|
||||
internalState = InternalState::CONFIGURE;
|
||||
}
|
||||
|
||||
if(internalState == InternalState::CONFIGURE) {
|
||||
if(commandExecuted) {
|
||||
internalState = InternalState::CHECK_REGS;
|
||||
commandExecuted = false;
|
||||
}
|
||||
if (internalState == InternalState::CONFIGURE) {
|
||||
if (commandExecuted) {
|
||||
internalState = InternalState::CHECK_REGS;
|
||||
commandExecuted = false;
|
||||
}
|
||||
}
|
||||
|
||||
if(internalState == InternalState::CHECK_REGS) {
|
||||
if(commandExecuted) {
|
||||
internalState = InternalState::NORMAL;
|
||||
if(goNormalModeImmediately) {
|
||||
setMode(MODE_NORMAL);
|
||||
}
|
||||
else {
|
||||
setMode(_MODE_TO_ON);
|
||||
}
|
||||
commandExecuted = false;
|
||||
}
|
||||
if (internalState == InternalState::CHECK_REGS) {
|
||||
if (commandExecuted) {
|
||||
internalState = InternalState::NORMAL;
|
||||
if (goNormalModeImmediately) {
|
||||
setMode(MODE_NORMAL);
|
||||
} else {
|
||||
setMode(_MODE_TO_ON);
|
||||
}
|
||||
commandExecuted = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GyroHandlerL3GD20H::doShutDown() {
|
||||
setMode(_MODE_POWER_DOWN);
|
||||
}
|
||||
void GyroHandlerL3GD20H::doShutDown() { setMode(_MODE_POWER_DOWN); }
|
||||
|
||||
ReturnValue_t GyroHandlerL3GD20H::buildTransitionDeviceCommand(DeviceCommandId_t *id) {
|
||||
switch(internalState) {
|
||||
case(InternalState::NONE):
|
||||
case(InternalState::NORMAL): {
|
||||
return NOTHING_TO_SEND;
|
||||
switch (internalState) {
|
||||
case (InternalState::NONE):
|
||||
case (InternalState::NORMAL): {
|
||||
return NOTHING_TO_SEND;
|
||||
}
|
||||
case(InternalState::CONFIGURE): {
|
||||
*id = L3GD20H::CONFIGURE_CTRL_REGS;
|
||||
uint8_t command [5];
|
||||
command[0] = L3GD20H::CTRL_REG_1_VAL;
|
||||
command[1] = L3GD20H::CTRL_REG_2_VAL;
|
||||
command[2] = L3GD20H::CTRL_REG_3_VAL;
|
||||
command[3] = L3GD20H::CTRL_REG_4_VAL;
|
||||
command[4] = L3GD20H::CTRL_REG_5_VAL;
|
||||
return buildCommandFromCommand(*id, command, 5);
|
||||
case (InternalState::CONFIGURE): {
|
||||
*id = L3GD20H::CONFIGURE_CTRL_REGS;
|
||||
uint8_t command[5];
|
||||
command[0] = L3GD20H::CTRL_REG_1_VAL;
|
||||
command[1] = L3GD20H::CTRL_REG_2_VAL;
|
||||
command[2] = L3GD20H::CTRL_REG_3_VAL;
|
||||
command[3] = L3GD20H::CTRL_REG_4_VAL;
|
||||
command[4] = L3GD20H::CTRL_REG_5_VAL;
|
||||
return buildCommandFromCommand(*id, command, 5);
|
||||
}
|
||||
case(InternalState::CHECK_REGS): {
|
||||
*id = L3GD20H::READ_REGS;
|
||||
return buildCommandFromCommand(*id, nullptr, 0);
|
||||
case (InternalState::CHECK_REGS): {
|
||||
*id = L3GD20H::READ_REGS;
|
||||
return buildCommandFromCommand(*id, nullptr, 0);
|
||||
}
|
||||
default:
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
/* Might be a configuration error. */
|
||||
sif::warning << "GyroL3GD20Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state!" << std::endl;
|
||||
/* Might be a configuration error. */
|
||||
sif::warning << "GyroL3GD20Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state!"
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printDebug("GyroL3GD20Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state!\n");
|
||||
sif::printDebug(
|
||||
"GyroL3GD20Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state!\n");
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroHandlerL3GD20H::buildNormalDeviceCommand(DeviceCommandId_t *id) {
|
||||
*id = L3GD20H::READ_REGS;
|
||||
return buildCommandFromCommand(*id, nullptr, 0);
|
||||
*id = L3GD20H::READ_REGS;
|
||||
return buildCommandFromCommand(*id, nullptr, 0);
|
||||
}
|
||||
|
||||
ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(
|
||||
DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
switch(deviceCommand) {
|
||||
case(L3GD20H::READ_REGS): {
|
||||
commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | L3GD20H::READ_MASK;
|
||||
std::memset(commandBuffer + 1, 0, L3GD20H::READ_LEN);
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = L3GD20H::READ_LEN + 1;
|
||||
break;
|
||||
ReturnValue_t GyroHandlerL3GD20H::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
switch (deviceCommand) {
|
||||
case (L3GD20H::READ_REGS): {
|
||||
commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | L3GD20H::READ_MASK;
|
||||
std::memset(commandBuffer + 1, 0, L3GD20H::READ_LEN);
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = L3GD20H::READ_LEN + 1;
|
||||
break;
|
||||
}
|
||||
case(L3GD20H::CONFIGURE_CTRL_REGS): {
|
||||
commandBuffer[0] = L3GD20H::CTRL_REG_1 | L3GD20H::AUTO_INCREMENT_MASK;
|
||||
if(commandData == nullptr or commandDataLen != 5) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
case (L3GD20H::CONFIGURE_CTRL_REGS): {
|
||||
commandBuffer[0] = L3GD20H::CTRL_REG_1 | L3GD20H::AUTO_INCREMENT_MASK;
|
||||
if (commandData == nullptr or commandDataLen != 5) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
|
||||
ctrlReg1Value = commandData[0];
|
||||
ctrlReg2Value = commandData[1];
|
||||
ctrlReg3Value = commandData[2];
|
||||
ctrlReg4Value = commandData[3];
|
||||
ctrlReg5Value = commandData[4];
|
||||
ctrlReg1Value = commandData[0];
|
||||
ctrlReg2Value = commandData[1];
|
||||
ctrlReg3Value = commandData[2];
|
||||
ctrlReg4Value = commandData[3];
|
||||
ctrlReg5Value = commandData[4];
|
||||
|
||||
bool fsH = ctrlReg4Value & L3GD20H::SET_FS_1;
|
||||
bool fsL = ctrlReg4Value & L3GD20H::SET_FS_0;
|
||||
bool fsH = ctrlReg4Value & L3GD20H::SET_FS_1;
|
||||
bool fsL = ctrlReg4Value & L3GD20H::SET_FS_0;
|
||||
|
||||
if(not fsH and not fsL) {
|
||||
sensitivity = L3GD20H::SENSITIVITY_00;
|
||||
}
|
||||
else if(not fsH and fsL) {
|
||||
sensitivity = L3GD20H::SENSITIVITY_01;
|
||||
}
|
||||
else {
|
||||
sensitivity = L3GD20H::SENSITIVITY_11;
|
||||
}
|
||||
if (not fsH and not fsL) {
|
||||
sensitivity = L3GD20H::SENSITIVITY_00;
|
||||
} else if (not fsH and fsL) {
|
||||
sensitivity = L3GD20H::SENSITIVITY_01;
|
||||
} else {
|
||||
sensitivity = L3GD20H::SENSITIVITY_11;
|
||||
}
|
||||
|
||||
commandBuffer[1] = ctrlReg1Value;
|
||||
commandBuffer[2] = ctrlReg2Value;
|
||||
commandBuffer[3] = ctrlReg3Value;
|
||||
commandBuffer[4] = ctrlReg4Value;
|
||||
commandBuffer[5] = ctrlReg5Value;
|
||||
commandBuffer[1] = ctrlReg1Value;
|
||||
commandBuffer[2] = ctrlReg2Value;
|
||||
commandBuffer[3] = ctrlReg3Value;
|
||||
commandBuffer[4] = ctrlReg4Value;
|
||||
commandBuffer[5] = ctrlReg5Value;
|
||||
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 6;
|
||||
break;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 6;
|
||||
break;
|
||||
}
|
||||
case(L3GD20H::READ_CTRL_REGS): {
|
||||
commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK |
|
||||
L3GD20H::READ_MASK;
|
||||
case (L3GD20H::READ_CTRL_REGS): {
|
||||
commandBuffer[0] = L3GD20H::READ_START | L3GD20H::AUTO_INCREMENT_MASK | L3GD20H::READ_MASK;
|
||||
|
||||
std::memset(commandBuffer + 1, 0, 5);
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 6;
|
||||
break;
|
||||
std::memset(commandBuffer + 1, 0, 5);
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 6;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroHandlerL3GD20H::scanForReply(const uint8_t *start, size_t len,
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) {
|
||||
// For SPI, the ID will always be the one of the last sent command
|
||||
*foundId = this->getPendingCommand();
|
||||
*foundLen = this->rawPacketLen;
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) {
|
||||
// For SPI, the ID will always be the one of the last sent command
|
||||
*foundId = this->getPendingCommand();
|
||||
*foundLen = this->rawPacketLen;
|
||||
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroHandlerL3GD20H::interpretDeviceReply(DeviceCommandId_t id,
|
||||
const uint8_t *packet) {
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
switch(id) {
|
||||
case(L3GD20H::CONFIGURE_CTRL_REGS): {
|
||||
const uint8_t *packet) {
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
switch (id) {
|
||||
case (L3GD20H::CONFIGURE_CTRL_REGS): {
|
||||
commandExecuted = true;
|
||||
break;
|
||||
}
|
||||
case (L3GD20H::READ_CTRL_REGS): {
|
||||
if (packet[1] == ctrlReg1Value and packet[2] == ctrlReg2Value and
|
||||
packet[3] == ctrlReg3Value and packet[4] == ctrlReg4Value and
|
||||
packet[5] == ctrlReg5Value) {
|
||||
commandExecuted = true;
|
||||
break;
|
||||
} else {
|
||||
// Attempt reconfiguration
|
||||
internalState = InternalState::CONFIGURE;
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(L3GD20H::READ_CTRL_REGS): {
|
||||
if(packet[1] == ctrlReg1Value and packet[2] == ctrlReg2Value and
|
||||
packet[3] == ctrlReg3Value and packet[4] == ctrlReg4Value and
|
||||
packet[5] == ctrlReg5Value) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
else {
|
||||
// Attempt reconfiguration
|
||||
internalState = InternalState::CONFIGURE;
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(L3GD20H::READ_REGS): {
|
||||
if(packet[1] != ctrlReg1Value and packet[2] != ctrlReg2Value and
|
||||
packet[3] != ctrlReg3Value and packet[4] != ctrlReg4Value and
|
||||
packet[5] != ctrlReg5Value) {
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
else {
|
||||
if(internalState == InternalState::CHECK_REGS) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
case (L3GD20H::READ_REGS): {
|
||||
if (packet[1] != ctrlReg1Value and packet[2] != ctrlReg2Value and
|
||||
packet[3] != ctrlReg3Value and packet[4] != ctrlReg4Value and
|
||||
packet[5] != ctrlReg5Value) {
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
} else {
|
||||
if (internalState == InternalState::CHECK_REGS) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
}
|
||||
|
||||
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 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];
|
||||
float angVelocX = angVelocXRaw * sensitivity;
|
||||
float angVelocY = angVelocYRaw * sensitivity;
|
||||
float angVelocZ = angVelocZRaw * sensitivity;
|
||||
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 angVelocZRaw = packet[L3GD20H::OUT_Z_H] << 8 | packet[L3GD20H::OUT_Z_L];
|
||||
float angVelocX = angVelocXRaw * sensitivity;
|
||||
float angVelocY = angVelocYRaw * sensitivity;
|
||||
float angVelocZ = angVelocZRaw * sensitivity;
|
||||
|
||||
int8_t temperaturOffset = (-1) * packet[L3GD20H::TEMPERATURE_IDX];
|
||||
float temperature = 25.0 + temperaturOffset;
|
||||
#if FSFW_HAL_L3GD20_GYRO_DEBUG == 1
|
||||
if(debugDivider->checkAndIncrement()) {
|
||||
/* Set terminal to utf-8 if there is an issue with micro printout. */
|
||||
int8_t temperaturOffset = (-1) * packet[L3GD20H::TEMPERATURE_IDX];
|
||||
float temperature = 25.0 + temperaturOffset;
|
||||
if (periodicPrintout) {
|
||||
if (debugDivider.checkAndIncrement()) {
|
||||
/* Set terminal to utf-8 if there is an issue with micro printout. */
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << "GyroHandlerL3GD20H: Angular velocities (deg/s):" << std::endl;
|
||||
sif::info << "X: " << angVelocX << std::endl;
|
||||
sif::info << "Y: " << angVelocY << std::endl;
|
||||
sif::info << "Z: " << angVelocZ << std::endl;
|
||||
sif::info << "GyroHandlerL3GD20H: Angular velocities (deg/s):" << std::endl;
|
||||
sif::info << "X: " << angVelocX << std::endl;
|
||||
sif::info << "Y: " << angVelocY << std::endl;
|
||||
sif::info << "Z: " << angVelocZ << std::endl;
|
||||
#else
|
||||
sif::printInfo("GyroHandlerL3GD20H: Angular velocities (deg/s):\n");
|
||||
sif::printInfo("X: %f\n", angVelocX);
|
||||
sif::printInfo("Y: %f\n", angVelocY);
|
||||
sif::printInfo("Z: %f\n", angVelocZ);
|
||||
sif::printInfo("GyroHandlerL3GD20H: Angular velocities (deg/s):\n");
|
||||
sif::printInfo("X: %f\n", angVelocX);
|
||||
sif::printInfo("Y: %f\n", angVelocY);
|
||||
sif::printInfo("Z: %f\n", angVelocZ);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
PoolReadGuard readSet(&dataset);
|
||||
if(readSet.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
|
||||
if(std::abs(angVelocX) < this->absLimitX) {
|
||||
dataset.angVelocX = angVelocX;
|
||||
dataset.angVelocX.setValid(true);
|
||||
}
|
||||
else {
|
||||
dataset.angVelocX.setValid(false);
|
||||
}
|
||||
|
||||
if(std::abs(angVelocY) < this->absLimitY) {
|
||||
dataset.angVelocY = angVelocY;
|
||||
dataset.angVelocY.setValid(true);
|
||||
}
|
||||
else {
|
||||
dataset.angVelocY.setValid(false);
|
||||
}
|
||||
|
||||
if(std::abs(angVelocZ) < this->absLimitZ) {
|
||||
dataset.angVelocZ = angVelocZ;
|
||||
dataset.angVelocZ.setValid(true);
|
||||
}
|
||||
else {
|
||||
dataset.angVelocZ.setValid(false);
|
||||
}
|
||||
|
||||
dataset.temperature = temperature;
|
||||
dataset.temperature.setValid(true);
|
||||
PoolReadGuard readSet(&dataset);
|
||||
if (readSet.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
|
||||
if (std::abs(angVelocX) < this->absLimitX) {
|
||||
dataset.angVelocX = angVelocX;
|
||||
dataset.angVelocX.setValid(true);
|
||||
} else {
|
||||
dataset.angVelocX.setValid(false);
|
||||
}
|
||||
break;
|
||||
|
||||
if (std::abs(angVelocY) < this->absLimitY) {
|
||||
dataset.angVelocY = angVelocY;
|
||||
dataset.angVelocY.setValid(true);
|
||||
} else {
|
||||
dataset.angVelocY.setValid(false);
|
||||
}
|
||||
|
||||
if (std::abs(angVelocZ) < this->absLimitZ) {
|
||||
dataset.angVelocZ = angVelocZ;
|
||||
dataset.angVelocZ.setValid(true);
|
||||
} else {
|
||||
dataset.angVelocZ.setValid(false);
|
||||
}
|
||||
|
||||
dataset.temperature = temperature;
|
||||
dataset.temperature.setValid(true);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return result;
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
uint32_t GyroHandlerL3GD20H::getTransitionDelayMs(Mode_t from, Mode_t to) {
|
||||
return this->transitionDelayMs;
|
||||
return this->transitionDelayMs;
|
||||
}
|
||||
|
||||
void GyroHandlerL3GD20H::setToGoToNormalMode(bool enable) {
|
||||
this->goNormalModeImmediately = true;
|
||||
}
|
||||
void GyroHandlerL3GD20H::setToGoToNormalMode(bool enable) { this->goNormalModeImmediately = true; }
|
||||
|
||||
ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool(
|
||||
localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) {
|
||||
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_Z, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(L3GD20H::TEMPERATURE, new PoolEntry<float>({0.0}));
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t GyroHandlerL3GD20H::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) {
|
||||
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_Z, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(L3GD20H::TEMPERATURE, new PoolEntry<float>({0.0}));
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void GyroHandlerL3GD20H::fillCommandAndReplyMap() {
|
||||
insertInCommandAndReplyMap(L3GD20H::READ_REGS, 1, &dataset);
|
||||
insertInCommandAndReplyMap(L3GD20H::CONFIGURE_CTRL_REGS, 1);
|
||||
insertInCommandAndReplyMap(L3GD20H::READ_CTRL_REGS, 1);
|
||||
insertInCommandAndReplyMap(L3GD20H::READ_REGS, 1, &dataset);
|
||||
insertInCommandAndReplyMap(L3GD20H::CONFIGURE_CTRL_REGS, 1);
|
||||
insertInCommandAndReplyMap(L3GD20H::READ_CTRL_REGS, 1);
|
||||
}
|
||||
|
||||
void GyroHandlerL3GD20H::modeChanged() {
|
||||
internalState = InternalState::NONE;
|
||||
}
|
||||
void GyroHandlerL3GD20H::modeChanged() { internalState = InternalState::NONE; }
|
||||
|
||||
void GyroHandlerL3GD20H::setAbsoluteLimits(float limitX, float limitY, float limitZ) {
|
||||
this->absLimitX = limitX;
|
||||
this->absLimitY = limitY;
|
||||
this->absLimitZ = limitZ;
|
||||
this->absLimitX = limitX;
|
||||
this->absLimitY = limitY;
|
||||
this->absLimitZ = limitZ;
|
||||
}
|
||||
|
||||
void GyroHandlerL3GD20H::enablePeriodicPrintouts(bool enable, uint8_t divider) {
|
||||
periodicPrintout = enable;
|
||||
debugDivider.setDivider(divider);
|
||||
}
|
||||
|
@ -1,12 +1,11 @@
|
||||
#ifndef MISSION_DEVICES_GYROL3GD20HANDLER_H_
|
||||
#define MISSION_DEVICES_GYROL3GD20HANDLER_H_
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "devicedefinitions/GyroL3GD20Definitions.h"
|
||||
|
||||
#include <fsfw/devicehandlers/DeviceHandlerBase.h>
|
||||
#include <fsfw/globalfunctions/PeriodicOperationDivider.h>
|
||||
|
||||
#include "devicedefinitions/GyroL3GD20Definitions.h"
|
||||
|
||||
/**
|
||||
* @brief Device Handler for the L3GD20H gyroscope sensor
|
||||
* (https://www.st.com/en/mems-and-sensors/l3gd20h.html)
|
||||
@ -16,84 +15,74 @@
|
||||
*
|
||||
* Data is read big endian with the smallest possible range of 245 degrees per second.
|
||||
*/
|
||||
class GyroHandlerL3GD20H: public DeviceHandlerBase {
|
||||
public:
|
||||
GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication,
|
||||
CookieIF* comCookie, uint32_t transitionDelayMs);
|
||||
virtual ~GyroHandlerL3GD20H();
|
||||
class GyroHandlerL3GD20H : public DeviceHandlerBase {
|
||||
public:
|
||||
GyroHandlerL3GD20H(object_id_t objectId, object_id_t deviceCommunication, CookieIF *comCookie,
|
||||
uint32_t transitionDelayMs);
|
||||
virtual ~GyroHandlerL3GD20H();
|
||||
|
||||
/**
|
||||
* Set the absolute limit for the values on the axis in degrees per second.
|
||||
* The dataset values will be marked as invalid if that limit is exceeded
|
||||
* @param xLimit
|
||||
* @param yLimit
|
||||
* @param zLimit
|
||||
*/
|
||||
void setAbsoluteLimits(float limitX, float limitY, float limitZ);
|
||||
void enablePeriodicPrintouts(bool enable, uint8_t divider);
|
||||
|
||||
/**
|
||||
* @brief Configure device handler to go to normal mode immediately
|
||||
*/
|
||||
void setToGoToNormalMode(bool enable);
|
||||
protected:
|
||||
/**
|
||||
* Set the absolute limit for the values on the axis in degrees per second.
|
||||
* The dataset values will be marked as invalid if that limit is exceeded
|
||||
* @param xLimit
|
||||
* @param yLimit
|
||||
* @param zLimit
|
||||
*/
|
||||
void setAbsoluteLimits(float limitX, float limitY, float limitZ);
|
||||
|
||||
/* DeviceHandlerBase overrides */
|
||||
ReturnValue_t buildTransitionDeviceCommand(
|
||||
DeviceCommandId_t *id) override;
|
||||
void doStartUp() override;
|
||||
void doShutDown() override;
|
||||
ReturnValue_t buildNormalDeviceCommand(
|
||||
DeviceCommandId_t *id) override;
|
||||
ReturnValue_t buildCommandFromCommand(
|
||||
DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) override;
|
||||
ReturnValue_t scanForReply(const uint8_t *start, size_t len,
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) override;
|
||||
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id,
|
||||
const uint8_t *packet) override;
|
||||
/**
|
||||
* @brief Configure device handler to go to normal mode immediately
|
||||
*/
|
||||
void setToGoToNormalMode(bool enable);
|
||||
|
||||
void fillCommandAndReplyMap() override;
|
||||
void modeChanged() override;
|
||||
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) override;
|
||||
protected:
|
||||
/* DeviceHandlerBase overrides */
|
||||
ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t *id) override;
|
||||
void doStartUp() override;
|
||||
void doShutDown() override;
|
||||
ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
|
||||
ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) override;
|
||||
ReturnValue_t scanForReply(const uint8_t *start, size_t len, DeviceCommandId_t *foundId,
|
||||
size_t *foundLen) override;
|
||||
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
|
||||
|
||||
private:
|
||||
uint32_t transitionDelayMs = 0;
|
||||
GyroPrimaryDataset dataset;
|
||||
void fillCommandAndReplyMap() override;
|
||||
void modeChanged() override;
|
||||
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) override;
|
||||
|
||||
float absLimitX = L3GD20H::RANGE_DPS_00;
|
||||
float absLimitY = L3GD20H::RANGE_DPS_00;
|
||||
float absLimitZ = L3GD20H::RANGE_DPS_00;
|
||||
private:
|
||||
uint32_t transitionDelayMs = 0;
|
||||
GyroPrimaryDataset dataset;
|
||||
|
||||
enum class InternalState {
|
||||
NONE,
|
||||
CONFIGURE,
|
||||
CHECK_REGS,
|
||||
NORMAL
|
||||
};
|
||||
InternalState internalState = InternalState::NONE;
|
||||
bool commandExecuted = false;
|
||||
float absLimitX = L3GD20H::RANGE_DPS_00;
|
||||
float absLimitY = L3GD20H::RANGE_DPS_00;
|
||||
float absLimitZ = L3GD20H::RANGE_DPS_00;
|
||||
|
||||
uint8_t statusReg = 0;
|
||||
bool goNormalModeImmediately = false;
|
||||
enum class InternalState { NONE, CONFIGURE, CHECK_REGS, NORMAL };
|
||||
InternalState internalState = InternalState::NONE;
|
||||
bool commandExecuted = false;
|
||||
|
||||
uint8_t ctrlReg1Value = L3GD20H::CTRL_REG_1_VAL;
|
||||
uint8_t ctrlReg2Value = L3GD20H::CTRL_REG_2_VAL;
|
||||
uint8_t ctrlReg3Value = L3GD20H::CTRL_REG_3_VAL;
|
||||
uint8_t ctrlReg4Value = L3GD20H::CTRL_REG_4_VAL;
|
||||
uint8_t ctrlReg5Value = L3GD20H::CTRL_REG_5_VAL;
|
||||
uint8_t statusReg = 0;
|
||||
bool goNormalModeImmediately = false;
|
||||
|
||||
uint8_t commandBuffer[L3GD20H::READ_LEN + 1];
|
||||
uint8_t ctrlReg1Value = L3GD20H::CTRL_REG_1_VAL;
|
||||
uint8_t ctrlReg2Value = L3GD20H::CTRL_REG_2_VAL;
|
||||
uint8_t ctrlReg3Value = L3GD20H::CTRL_REG_3_VAL;
|
||||
uint8_t ctrlReg4Value = L3GD20H::CTRL_REG_4_VAL;
|
||||
uint8_t ctrlReg5Value = L3GD20H::CTRL_REG_5_VAL;
|
||||
|
||||
// Set default value
|
||||
float sensitivity = L3GD20H::SENSITIVITY_00;
|
||||
uint8_t commandBuffer[L3GD20H::READ_LEN + 1];
|
||||
|
||||
#if FSFW_HAL_L3GD20_GYRO_DEBUG == 1
|
||||
PeriodicOperationDivider* debugDivider = nullptr;
|
||||
#endif
|
||||
// Set default value
|
||||
float sensitivity = L3GD20H::SENSITIVITY_00;
|
||||
|
||||
bool periodicPrintout = false;
|
||||
PeriodicOperationDivider debugDivider = PeriodicOperationDivider(3);
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif /* MISSION_DEVICES_GYROL3GD20HANDLER_H_ */
|
||||
|
@ -8,513 +8,483 @@
|
||||
#include <cmath>
|
||||
|
||||
MgmLIS3MDLHandler::MgmLIS3MDLHandler(object_id_t objectId, object_id_t deviceCommunication,
|
||||
CookieIF* comCookie, uint32_t transitionDelay):
|
||||
DeviceHandlerBase(objectId, deviceCommunication, comCookie),
|
||||
dataset(this), transitionDelay(transitionDelay) {
|
||||
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
|
||||
debugDivider = new PeriodicOperationDivider(3);
|
||||
#endif
|
||||
// Set to default values right away
|
||||
registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
|
||||
registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
|
||||
registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
|
||||
registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
|
||||
registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
|
||||
|
||||
}
|
||||
|
||||
MgmLIS3MDLHandler::~MgmLIS3MDLHandler() {
|
||||
CookieIF *comCookie, uint32_t transitionDelay)
|
||||
: DeviceHandlerBase(objectId, deviceCommunication, comCookie),
|
||||
dataset(this),
|
||||
transitionDelay(transitionDelay) {
|
||||
// Set to default values right away
|
||||
registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
|
||||
registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
|
||||
registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
|
||||
registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
|
||||
registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
|
||||
}
|
||||
|
||||
MgmLIS3MDLHandler::~MgmLIS3MDLHandler() {}
|
||||
|
||||
void MgmLIS3MDLHandler::doStartUp() {
|
||||
switch (internalState) {
|
||||
case(InternalState::STATE_NONE): {
|
||||
internalState = InternalState::STATE_FIRST_CONTACT;
|
||||
break;
|
||||
switch (internalState) {
|
||||
case (InternalState::STATE_NONE): {
|
||||
internalState = InternalState::STATE_FIRST_CONTACT;
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_FIRST_CONTACT): {
|
||||
/* Will be set by checking device ID (WHO AM I register) */
|
||||
if(commandExecuted) {
|
||||
commandExecuted = false;
|
||||
internalState = InternalState::STATE_SETUP;
|
||||
case (InternalState::STATE_FIRST_CONTACT): {
|
||||
/* Will be set by checking device ID (WHO AM I register) */
|
||||
if (commandExecuted) {
|
||||
commandExecuted = false;
|
||||
internalState = InternalState::STATE_SETUP;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case (InternalState::STATE_SETUP): {
|
||||
internalState = InternalState::STATE_CHECK_REGISTERS;
|
||||
break;
|
||||
}
|
||||
case (InternalState::STATE_CHECK_REGISTERS): {
|
||||
/* Set up cached registers which will be used to configure the MGM. */
|
||||
if (commandExecuted) {
|
||||
commandExecuted = false;
|
||||
if (goToNormalMode) {
|
||||
setMode(MODE_NORMAL);
|
||||
} else {
|
||||
setMode(_MODE_TO_ON);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_SETUP): {
|
||||
internalState = InternalState::STATE_CHECK_REGISTERS;
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_CHECK_REGISTERS): {
|
||||
/* Set up cached registers which will be used to configure the MGM. */
|
||||
if(commandExecuted) {
|
||||
commandExecuted = false;
|
||||
if(goToNormalMode) {
|
||||
setMode(MODE_NORMAL);
|
||||
}
|
||||
else {
|
||||
setMode(_MODE_TO_ON);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void MgmLIS3MDLHandler::doShutDown() {
|
||||
setMode(_MODE_POWER_DOWN);
|
||||
}
|
||||
void MgmLIS3MDLHandler::doShutDown() { setMode(_MODE_POWER_DOWN); }
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand(
|
||||
DeviceCommandId_t *id) {
|
||||
switch (internalState) {
|
||||
case(InternalState::STATE_NONE):
|
||||
case(InternalState::STATE_NORMAL): {
|
||||
return DeviceHandlerBase::NOTHING_TO_SEND;
|
||||
ReturnValue_t MgmLIS3MDLHandler::buildTransitionDeviceCommand(DeviceCommandId_t *id) {
|
||||
switch (internalState) {
|
||||
case (InternalState::STATE_NONE):
|
||||
case (InternalState::STATE_NORMAL): {
|
||||
return DeviceHandlerBase::NOTHING_TO_SEND;
|
||||
}
|
||||
case(InternalState::STATE_FIRST_CONTACT): {
|
||||
*id = MGMLIS3MDL::IDENTIFY_DEVICE;
|
||||
break;
|
||||
case (InternalState::STATE_FIRST_CONTACT): {
|
||||
*id = MGMLIS3MDL::IDENTIFY_DEVICE;
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_SETUP): {
|
||||
*id = MGMLIS3MDL::SETUP_MGM;
|
||||
break;
|
||||
case (InternalState::STATE_SETUP): {
|
||||
*id = MGMLIS3MDL::SETUP_MGM;
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_CHECK_REGISTERS): {
|
||||
*id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
|
||||
break;
|
||||
case (InternalState::STATE_CHECK_REGISTERS): {
|
||||
*id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
/* might be a configuration error. */
|
||||
/* might be a configuration error. */
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "GyroHandler::buildTransitionDeviceCommand: Unknown internal state!" <<
|
||||
std::endl;
|
||||
sif::warning << "GyroHandler::buildTransitionDeviceCommand: Unknown internal state!"
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("GyroHandler::buildTransitionDeviceCommand: Unknown internal state!\n");
|
||||
sif::printWarning("GyroHandler::buildTransitionDeviceCommand: Unknown internal state!\n");
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
return HasReturnvaluesIF::RETURN_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;
|
||||
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;
|
||||
command &= ~(1 << MGMLIS3MDL::RW_BIT);
|
||||
if (continuousCom == true) {
|
||||
command |= (1 << MGMLIS3MDL::MS_BIT);
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
void MgmLIS3MDLHandler::setupMgm() {
|
||||
registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
|
||||
registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
|
||||
registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
|
||||
registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
|
||||
registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
|
||||
|
||||
registers[0] = MGMLIS3MDL::CTRL_REG1_DEFAULT;
|
||||
registers[1] = MGMLIS3MDL::CTRL_REG2_DEFAULT;
|
||||
registers[2] = MGMLIS3MDL::CTRL_REG3_DEFAULT;
|
||||
registers[3] = MGMLIS3MDL::CTRL_REG4_DEFAULT;
|
||||
registers[4] = MGMLIS3MDL::CTRL_REG5_DEFAULT;
|
||||
|
||||
prepareCtrlRegisterWrite();
|
||||
prepareCtrlRegisterWrite();
|
||||
}
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::buildNormalDeviceCommand(
|
||||
DeviceCommandId_t *id) {
|
||||
// Data/config register will be read in an alternating manner.
|
||||
if(communicationStep == CommunicationStep::DATA) {
|
||||
*id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
|
||||
communicationStep = CommunicationStep::TEMPERATURE;
|
||||
return buildCommandFromCommand(*id, NULL, 0);
|
||||
}
|
||||
else {
|
||||
*id = MGMLIS3MDL::READ_TEMPERATURE;
|
||||
communicationStep = CommunicationStep::DATA;
|
||||
return buildCommandFromCommand(*id, NULL, 0);
|
||||
}
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::buildNormalDeviceCommand(DeviceCommandId_t *id) {
|
||||
// Data/config register will be read in an alternating manner.
|
||||
if (communicationStep == CommunicationStep::DATA) {
|
||||
*id = MGMLIS3MDL::READ_CONFIG_AND_DATA;
|
||||
communicationStep = CommunicationStep::TEMPERATURE;
|
||||
return buildCommandFromCommand(*id, NULL, 0);
|
||||
} else {
|
||||
*id = MGMLIS3MDL::READ_TEMPERATURE;
|
||||
communicationStep = CommunicationStep::DATA;
|
||||
return buildCommandFromCommand(*id, NULL, 0);
|
||||
}
|
||||
}
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::buildCommandFromCommand(
|
||||
DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
switch(deviceCommand) {
|
||||
case(MGMLIS3MDL::READ_CONFIG_AND_DATA): {
|
||||
std::memset(commandBuffer, 0, sizeof(commandBuffer));
|
||||
commandBuffer[0] = readCommand(MGMLIS3MDL::CTRL_REG1, true);
|
||||
ReturnValue_t MgmLIS3MDLHandler::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
switch (deviceCommand) {
|
||||
case (MGMLIS3MDL::READ_CONFIG_AND_DATA): {
|
||||
std::memset(commandBuffer, 0, sizeof(commandBuffer));
|
||||
commandBuffer[0] = readCommand(MGMLIS3MDL::CTRL_REG1, true);
|
||||
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1;
|
||||
return RETURN_OK;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1;
|
||||
return RETURN_OK;
|
||||
}
|
||||
case(MGMLIS3MDL::READ_TEMPERATURE): {
|
||||
std::memset(commandBuffer, 0, 3);
|
||||
commandBuffer[0] = readCommand(MGMLIS3MDL::TEMP_LOWBYTE, true);
|
||||
case (MGMLIS3MDL::READ_TEMPERATURE): {
|
||||
std::memset(commandBuffer, 0, 3);
|
||||
commandBuffer[0] = readCommand(MGMLIS3MDL::TEMP_LOWBYTE, true);
|
||||
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 3;
|
||||
return RETURN_OK;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 3;
|
||||
return RETURN_OK;
|
||||
}
|
||||
case(MGMLIS3MDL::IDENTIFY_DEVICE): {
|
||||
return identifyDevice();
|
||||
case (MGMLIS3MDL::IDENTIFY_DEVICE): {
|
||||
return identifyDevice();
|
||||
}
|
||||
case(MGMLIS3MDL::TEMP_SENSOR_ENABLE): {
|
||||
return enableTemperatureSensor(commandData, commandDataLen);
|
||||
case (MGMLIS3MDL::TEMP_SENSOR_ENABLE): {
|
||||
return enableTemperatureSensor(commandData, commandDataLen);
|
||||
}
|
||||
case(MGMLIS3MDL::SETUP_MGM): {
|
||||
setupMgm();
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
case (MGMLIS3MDL::SETUP_MGM): {
|
||||
setupMgm();
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
case(MGMLIS3MDL::ACCURACY_OP_MODE_SET): {
|
||||
return setOperatingMode(commandData, commandDataLen);
|
||||
case (MGMLIS3MDL::ACCURACY_OP_MODE_SET): {
|
||||
return setOperatingMode(commandData, commandDataLen);
|
||||
}
|
||||
default:
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::identifyDevice() {
|
||||
uint32_t size = 2;
|
||||
commandBuffer[0] = readCommand(MGMLIS3MDL::IDENTIFY_DEVICE_REG_ADDR);
|
||||
commandBuffer[1] = 0x00;
|
||||
uint32_t size = 2;
|
||||
commandBuffer[0] = readCommand(MGMLIS3MDL::IDENTIFY_DEVICE_REG_ADDR);
|
||||
commandBuffer[1] = 0x00;
|
||||
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = size;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = size;
|
||||
|
||||
return RETURN_OK;
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start,
|
||||
size_t len, DeviceCommandId_t *foundId, size_t *foundLen) {
|
||||
ReturnValue_t MgmLIS3MDLHandler::scanForReply(const uint8_t *start, size_t len,
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) {
|
||||
*foundLen = len;
|
||||
if (len == MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1) {
|
||||
*foundLen = len;
|
||||
if (len == MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1) {
|
||||
*foundLen = len;
|
||||
*foundId = MGMLIS3MDL::READ_CONFIG_AND_DATA;
|
||||
// Check validity by checking config registers
|
||||
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]) {
|
||||
*foundId = MGMLIS3MDL::READ_CONFIG_AND_DATA;
|
||||
// Check validity by checking config registers
|
||||
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]) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "MGMHandlerLIS3MDL::scanForReply: Invalid registers!" << std::endl;
|
||||
sif::warning << "MGMHandlerLIS3MDL::scanForReply: Invalid registers!" << std::endl;
|
||||
#else
|
||||
sif::printWarning("MGMHandlerLIS3MDL::scanForReply: Invalid registers!\n");
|
||||
sif::printWarning("MGMHandlerLIS3MDL::scanForReply: Invalid registers!\n");
|
||||
#endif
|
||||
#endif
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
}
|
||||
if(mode == _MODE_START_UP) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
}
|
||||
if (mode == _MODE_START_UP) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
|
||||
}
|
||||
else if(len == MGMLIS3MDL::TEMPERATURE_REPLY_LEN) {
|
||||
*foundLen = len;
|
||||
*foundId = MGMLIS3MDL::READ_TEMPERATURE;
|
||||
}
|
||||
else if (len == MGMLIS3MDL::SETUP_REPLY_LEN) {
|
||||
*foundLen = len;
|
||||
*foundId = MGMLIS3MDL::SETUP_MGM;
|
||||
}
|
||||
else if (len == SINGLE_COMMAND_ANSWER_LEN) {
|
||||
*foundLen = len;
|
||||
*foundId = getPendingCommand();
|
||||
if(*foundId == MGMLIS3MDL::IDENTIFY_DEVICE) {
|
||||
if(start[1] != MGMLIS3MDL::DEVICE_ID) {
|
||||
} else if (len == MGMLIS3MDL::TEMPERATURE_REPLY_LEN) {
|
||||
*foundLen = len;
|
||||
*foundId = MGMLIS3MDL::READ_TEMPERATURE;
|
||||
} else if (len == MGMLIS3MDL::SETUP_REPLY_LEN) {
|
||||
*foundLen = len;
|
||||
*foundId = MGMLIS3MDL::SETUP_MGM;
|
||||
} else if (len == SINGLE_COMMAND_ANSWER_LEN) {
|
||||
*foundLen = len;
|
||||
*foundId = getPendingCommand();
|
||||
if (*foundId == MGMLIS3MDL::IDENTIFY_DEVICE) {
|
||||
if (start[1] != MGMLIS3MDL::DEVICE_ID) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "MGMHandlerLIS3MDL::scanForReply: "
|
||||
"Device identification failed!" << std::endl;
|
||||
sif::warning << "MGMHandlerLIS3MDL::scanForReply: "
|
||||
"Device identification failed!"
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("MGMHandlerLIS3MDL::scanForReply: "
|
||||
"Device identification failed!\n");
|
||||
sif::printWarning(
|
||||
"MGMHandlerLIS3MDL::scanForReply: "
|
||||
"Device identification failed!\n");
|
||||
#endif
|
||||
#endif
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
}
|
||||
|
||||
if(mode == _MODE_START_UP) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
}
|
||||
}
|
||||
|
||||
/* Data with SPI Interface always has this answer */
|
||||
if (start[0] == 0b11111111) {
|
||||
return RETURN_OK;
|
||||
}
|
||||
else {
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
if (mode == _MODE_START_UP) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
}
|
||||
|
||||
/* Data with SPI Interface always has this answer */
|
||||
if (start[0] == 0b11111111) {
|
||||
return RETURN_OK;
|
||||
} else {
|
||||
return DeviceHandlerIF::INVALID_DATA;
|
||||
}
|
||||
}
|
||||
ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id,
|
||||
const uint8_t *packet) {
|
||||
|
||||
switch (id) {
|
||||
ReturnValue_t MgmLIS3MDLHandler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) {
|
||||
switch (id) {
|
||||
case MGMLIS3MDL::IDENTIFY_DEVICE: {
|
||||
break;
|
||||
break;
|
||||
}
|
||||
case MGMLIS3MDL::SETUP_MGM: {
|
||||
break;
|
||||
break;
|
||||
}
|
||||
case MGMLIS3MDL::READ_CONFIG_AND_DATA: {
|
||||
// TODO: Store configuration in new local datasets.
|
||||
float sensitivityFactor = getSensitivityFactor(getSensitivity(registers[2]));
|
||||
// TODO: Store configuration in new local datasets.
|
||||
float sensitivityFactor = getSensitivityFactor(getSensitivity(registers[2]));
|
||||
|
||||
int16_t mgmMeasurementRawX = packet[MGMLIS3MDL::X_HIGHBYTE_IDX] << 8
|
||||
| packet[MGMLIS3MDL::X_LOWBYTE_IDX] ;
|
||||
int16_t mgmMeasurementRawY = packet[MGMLIS3MDL::Y_HIGHBYTE_IDX] << 8
|
||||
| packet[MGMLIS3MDL::Y_LOWBYTE_IDX] ;
|
||||
int16_t mgmMeasurementRawZ = packet[MGMLIS3MDL::Z_HIGHBYTE_IDX] << 8
|
||||
| packet[MGMLIS3MDL::Z_LOWBYTE_IDX] ;
|
||||
int16_t mgmMeasurementRawX =
|
||||
packet[MGMLIS3MDL::X_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::X_LOWBYTE_IDX];
|
||||
int16_t mgmMeasurementRawY =
|
||||
packet[MGMLIS3MDL::Y_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::Y_LOWBYTE_IDX];
|
||||
int16_t mgmMeasurementRawZ =
|
||||
packet[MGMLIS3MDL::Z_HIGHBYTE_IDX] << 8 | packet[MGMLIS3MDL::Z_LOWBYTE_IDX];
|
||||
|
||||
/* Target value in microtesla */
|
||||
float mgmX = static_cast<float>(mgmMeasurementRawX) * sensitivityFactor
|
||||
* MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
|
||||
float mgmY = static_cast<float>(mgmMeasurementRawY) * sensitivityFactor
|
||||
* MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
|
||||
float mgmZ = static_cast<float>(mgmMeasurementRawZ) * sensitivityFactor
|
||||
* MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
|
||||
// Target value in microtesla
|
||||
float mgmX = static_cast<float>(mgmMeasurementRawX) * sensitivityFactor *
|
||||
MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
|
||||
float mgmY = static_cast<float>(mgmMeasurementRawY) * sensitivityFactor *
|
||||
MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
|
||||
float mgmZ = static_cast<float>(mgmMeasurementRawZ) * sensitivityFactor *
|
||||
MGMLIS3MDL::GAUSS_TO_MICROTESLA_FACTOR;
|
||||
|
||||
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
|
||||
if(debugDivider->checkAndIncrement()) {
|
||||
if (periodicPrintout) {
|
||||
if (debugDivider.checkAndIncrement()) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << "MGMHandlerLIS3: Magnetic field strength in"
|
||||
" microtesla:" << std::endl;
|
||||
sif::info << "X: " << mgmX << " uT" << std::endl;
|
||||
sif::info << "Y: " << mgmY << " uT" << std::endl;
|
||||
sif::info << "Z: " << mgmZ << " uT" << std::endl;
|
||||
sif::info << "MGMHandlerLIS3: Magnetic field strength in"
|
||||
" microtesla:"
|
||||
<< std::endl;
|
||||
sif::info << "X: " << mgmX << " uT" << std::endl;
|
||||
sif::info << "Y: " << mgmY << " uT" << std::endl;
|
||||
sif::info << "Z: " << mgmZ << " uT" << std::endl;
|
||||
#else
|
||||
sif::printInfo("MGMHandlerLIS3: Magnetic field strength in microtesla:\n");
|
||||
sif::printInfo("X: %f uT\n", mgmX);
|
||||
sif::printInfo("Y: %f uT\n", mgmY);
|
||||
sif::printInfo("Z: %f uT\n", mgmZ);
|
||||
sif::printInfo("MGMHandlerLIS3: Magnetic field strength in microtesla:\n");
|
||||
sif::printInfo("X: %f uT\n", mgmX);
|
||||
sif::printInfo("Y: %f uT\n", mgmY);
|
||||
sif::printInfo("Z: %f uT\n", mgmZ);
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 0 */
|
||||
}
|
||||
#endif /* OBSW_VERBOSE_LEVEL >= 1 */
|
||||
PoolReadGuard readHelper(&dataset);
|
||||
if(readHelper.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
|
||||
if(std::abs(mgmX) < absLimitX) {
|
||||
dataset.fieldStrengthX = mgmX;
|
||||
dataset.fieldStrengthX.setValid(true);
|
||||
}
|
||||
else {
|
||||
dataset.fieldStrengthX.setValid(false);
|
||||
}
|
||||
}
|
||||
|
||||
if(std::abs(mgmY) < absLimitY) {
|
||||
dataset.fieldStrengthY = mgmY;
|
||||
dataset.fieldStrengthY.setValid(true);
|
||||
}
|
||||
else {
|
||||
dataset.fieldStrengthY.setValid(false);
|
||||
}
|
||||
|
||||
if(std::abs(mgmZ) < absLimitZ) {
|
||||
dataset.fieldStrengthZ = mgmZ;
|
||||
dataset.fieldStrengthZ.setValid(true);
|
||||
}
|
||||
else {
|
||||
dataset.fieldStrengthZ.setValid(false);
|
||||
}
|
||||
PoolReadGuard readHelper(&dataset);
|
||||
if (readHelper.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
|
||||
if (std::abs(mgmX) < absLimitX) {
|
||||
dataset.fieldStrengthX = mgmX;
|
||||
dataset.fieldStrengthX.setValid(true);
|
||||
} else {
|
||||
dataset.fieldStrengthX.setValid(false);
|
||||
}
|
||||
break;
|
||||
|
||||
if (std::abs(mgmY) < absLimitY) {
|
||||
dataset.fieldStrengthY = mgmY;
|
||||
dataset.fieldStrengthY.setValid(true);
|
||||
} else {
|
||||
dataset.fieldStrengthY.setValid(false);
|
||||
}
|
||||
|
||||
if (std::abs(mgmZ) < absLimitZ) {
|
||||
dataset.fieldStrengthZ = mgmZ;
|
||||
dataset.fieldStrengthZ.setValid(true);
|
||||
} else {
|
||||
dataset.fieldStrengthZ.setValid(false);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case MGMLIS3MDL::READ_TEMPERATURE: {
|
||||
int16_t tempValueRaw = packet[2] << 8 | packet[1];
|
||||
float tempValue = 25.0 + ((static_cast<float>(tempValueRaw)) / 8.0);
|
||||
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
|
||||
if(debugDivider->check()) {
|
||||
int16_t tempValueRaw = packet[2] << 8 | packet[1];
|
||||
float tempValue = 25.0 + ((static_cast<float>(tempValueRaw)) / 8.0);
|
||||
if (periodicPrintout) {
|
||||
if (debugDivider.check()) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << "MGMHandlerLIS3: Temperature: " << tempValue << " C" <<
|
||||
std::endl;
|
||||
sif::info << "MGMHandlerLIS3: Temperature: " << tempValue << " C" << std::endl;
|
||||
#else
|
||||
sif::printInfo("MGMHandlerLIS3: Temperature: %f C\n");
|
||||
sif::printInfo("MGMHandlerLIS3: Temperature: %f C\n");
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
ReturnValue_t result = dataset.read();
|
||||
if(result == HasReturnvaluesIF::RETURN_OK) {
|
||||
dataset.temperature = tempValue;
|
||||
dataset.commit();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
ReturnValue_t result = dataset.read();
|
||||
if (result == HasReturnvaluesIF::RETURN_OK) {
|
||||
dataset.temperature = tempValue;
|
||||
dataset.commit();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY;
|
||||
return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY;
|
||||
}
|
||||
|
||||
}
|
||||
return RETURN_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
|
||||
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;
|
||||
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;
|
||||
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_8): {
|
||||
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_8_SENS;
|
||||
}
|
||||
case(MGMLIS3MDL::GAUSS_12): {
|
||||
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_12_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;
|
||||
case (MGMLIS3MDL::GAUSS_16): {
|
||||
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_16_SENS;
|
||||
}
|
||||
default: {
|
||||
// Should never happen
|
||||
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_4_SENS;
|
||||
}
|
||||
// Should never happen
|
||||
return MGMLIS3MDL::FIELD_LSB_PER_GAUSS_4_SENS;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(
|
||||
const uint8_t *commandData, size_t commandDataLen) {
|
||||
triggerEvent(CHANGE_OF_SETUP_PARAMETER);
|
||||
uint32_t size = 2;
|
||||
commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1);
|
||||
if (commandDataLen > 1) {
|
||||
return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS;
|
||||
}
|
||||
switch (*commandData) {
|
||||
ReturnValue_t MgmLIS3MDLHandler::enableTemperatureSensor(const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
triggerEvent(CHANGE_OF_SETUP_PARAMETER);
|
||||
uint32_t size = 2;
|
||||
commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1);
|
||||
if (commandDataLen > 1) {
|
||||
return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS;
|
||||
}
|
||||
switch (*commandData) {
|
||||
case (MGMLIS3MDL::ON): {
|
||||
commandBuffer[1] = registers[0] | (1 << 7);
|
||||
break;
|
||||
commandBuffer[1] = registers[0] | (1 << 7);
|
||||
break;
|
||||
}
|
||||
case (MGMLIS3MDL::OFF): {
|
||||
commandBuffer[1] = registers[0] & ~(1 << 7);
|
||||
break;
|
||||
commandBuffer[1] = registers[0] & ~(1 << 7);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
registers[0] = commandBuffer[1];
|
||||
return INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
registers[0] = commandBuffer[1];
|
||||
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = size;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = size;
|
||||
|
||||
return RETURN_OK;
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::setOperatingMode(const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
triggerEvent(CHANGE_OF_SETUP_PARAMETER);
|
||||
if (commandDataLen != 1) {
|
||||
return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS;
|
||||
}
|
||||
size_t commandDataLen) {
|
||||
triggerEvent(CHANGE_OF_SETUP_PARAMETER);
|
||||
if (commandDataLen != 1) {
|
||||
return INVALID_NUMBER_OR_LENGTH_OF_PARAMETERS;
|
||||
}
|
||||
|
||||
switch (commandData[0]) {
|
||||
switch (commandData[0]) {
|
||||
case MGMLIS3MDL::LOW:
|
||||
registers[0] = (registers[0] & (~(1 << MGMLIS3MDL::OM1))) & (~(1 << MGMLIS3MDL::OM0));
|
||||
registers[3] = (registers[3] & (~(1 << MGMLIS3MDL::OMZ1))) & (~(1 << MGMLIS3MDL::OMZ0));
|
||||
break;
|
||||
registers[0] = (registers[0] & (~(1 << MGMLIS3MDL::OM1))) & (~(1 << MGMLIS3MDL::OM0));
|
||||
registers[3] = (registers[3] & (~(1 << MGMLIS3MDL::OMZ1))) & (~(1 << MGMLIS3MDL::OMZ0));
|
||||
break;
|
||||
case MGMLIS3MDL::MEDIUM:
|
||||
registers[0] = (registers[0] & (~(1 << MGMLIS3MDL::OM1))) | (1 << MGMLIS3MDL::OM0);
|
||||
registers[3] = (registers[3] & (~(1 << MGMLIS3MDL::OMZ1))) | (1 << MGMLIS3MDL::OMZ0);
|
||||
break;
|
||||
registers[0] = (registers[0] & (~(1 << MGMLIS3MDL::OM1))) | (1 << MGMLIS3MDL::OM0);
|
||||
registers[3] = (registers[3] & (~(1 << MGMLIS3MDL::OMZ1))) | (1 << MGMLIS3MDL::OMZ0);
|
||||
break;
|
||||
|
||||
case MGMLIS3MDL::HIGH:
|
||||
registers[0] = (registers[0] | (1 << MGMLIS3MDL::OM1)) & (~(1 << MGMLIS3MDL::OM0));
|
||||
registers[3] = (registers[3] | (1 << MGMLIS3MDL::OMZ1)) & (~(1 << MGMLIS3MDL::OMZ0));
|
||||
break;
|
||||
registers[0] = (registers[0] | (1 << MGMLIS3MDL::OM1)) & (~(1 << MGMLIS3MDL::OM0));
|
||||
registers[3] = (registers[3] | (1 << MGMLIS3MDL::OMZ1)) & (~(1 << MGMLIS3MDL::OMZ0));
|
||||
break;
|
||||
|
||||
case MGMLIS3MDL::ULTRA:
|
||||
registers[0] = (registers[0] | (1 << MGMLIS3MDL::OM1)) | (1 << MGMLIS3MDL::OM0);
|
||||
registers[3] = (registers[3] | (1 << MGMLIS3MDL::OMZ1)) | (1 << MGMLIS3MDL::OMZ0);
|
||||
break;
|
||||
registers[0] = (registers[0] | (1 << MGMLIS3MDL::OM1)) | (1 << MGMLIS3MDL::OM0);
|
||||
registers[3] = (registers[3] | (1 << MGMLIS3MDL::OMZ1)) | (1 << MGMLIS3MDL::OMZ0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return prepareCtrlRegisterWrite();
|
||||
return prepareCtrlRegisterWrite();
|
||||
}
|
||||
|
||||
void MgmLIS3MDLHandler::fillCommandAndReplyMap() {
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::READ_CONFIG_AND_DATA, 1, &dataset);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::READ_TEMPERATURE, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::SETUP_MGM, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::IDENTIFY_DEVICE, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::TEMP_SENSOR_ENABLE, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::ACCURACY_OP_MODE_SET, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::READ_CONFIG_AND_DATA, 1, &dataset);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::READ_TEMPERATURE, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::SETUP_MGM, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::IDENTIFY_DEVICE, 1);
|
||||
insertInCommandAndReplyMap(MGMLIS3MDL::TEMP_SENSOR_ENABLE, 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() {
|
||||
commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1, true);
|
||||
commandBuffer[0] = writeCommand(MGMLIS3MDL::CTRL_REG1, true);
|
||||
|
||||
for (size_t i = 0; i < MGMLIS3MDL::NR_OF_CTRL_REGISTERS; i++) {
|
||||
commandBuffer[i + 1] = registers[i];
|
||||
}
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = MGMLIS3MDL::NR_OF_CTRL_REGISTERS + 1;
|
||||
for (size_t i = 0; i < MGMLIS3MDL::NR_OF_CTRL_REGISTERS; i++) {
|
||||
commandBuffer[i + 1] = registers[i];
|
||||
}
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = MGMLIS3MDL::NR_OF_CTRL_REGISTERS + 1;
|
||||
|
||||
// We dont have to check if this is working because we just did i
|
||||
return RETURN_OK;
|
||||
// We dont have to check if this is working because we just did i
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
void MgmLIS3MDLHandler::doTransition(Mode_t modeFrom, Submode_t subModeFrom) {
|
||||
|
||||
DeviceHandlerBase::doTransition(modeFrom, subModeFrom);
|
||||
}
|
||||
|
||||
uint32_t MgmLIS3MDLHandler::getTransitionDelayMs(Mode_t from, Mode_t to) {
|
||||
return transitionDelay;
|
||||
}
|
||||
uint32_t MgmLIS3MDLHandler::getTransitionDelayMs(Mode_t from, Mode_t to) { return transitionDelay; }
|
||||
|
||||
void MgmLIS3MDLHandler::modeChanged(void) {
|
||||
internalState = InternalState::STATE_NONE;
|
||||
}
|
||||
void MgmLIS3MDLHandler::modeChanged(void) { internalState = InternalState::STATE_NONE; }
|
||||
|
||||
ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool(
|
||||
localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) {
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_X,
|
||||
new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Y,
|
||||
new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Z,
|
||||
new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::TEMPERATURE_CELCIUS,
|
||||
new PoolEntry<float>({0.0}));
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t MgmLIS3MDLHandler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) {
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(MGMLIS3MDL::TEMPERATURE_CELCIUS, new PoolEntry<float>({0.0}));
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void MgmLIS3MDLHandler::setAbsoluteLimits(float xLimit, float yLimit, float zLimit) {
|
||||
this->absLimitX = xLimit;
|
||||
this->absLimitY = yLimit;
|
||||
this->absLimitZ = zLimit;
|
||||
this->absLimitX = xLimit;
|
||||
this->absLimitY = yLimit;
|
||||
this->absLimitZ = zLimit;
|
||||
}
|
||||
|
||||
void MgmLIS3MDLHandler::enablePeriodicPrintouts(bool enable, uint8_t divider) {
|
||||
periodicPrintout = enable;
|
||||
debugDivider.setDivider(divider);
|
||||
}
|
||||
|
@ -1,11 +1,10 @@
|
||||
#ifndef MISSION_DEVICES_MGMLIS3MDLHANDLER_H_
|
||||
#define MISSION_DEVICES_MGMLIS3MDLHANDLER_H_
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "events/subsystemIdRanges.h"
|
||||
#include "devicedefinitions/MgmLIS3HandlerDefs.h"
|
||||
|
||||
#include "events/subsystemIdRanges.h"
|
||||
#include "fsfw/devicehandlers/DeviceHandlerBase.h"
|
||||
#include "fsfw/globalfunctions/PeriodicOperationDivider.h"
|
||||
|
||||
class PeriodicOperationDivider;
|
||||
|
||||
@ -18,169 +17,159 @@ class PeriodicOperationDivider;
|
||||
* https://egit.irs.uni-stuttgart.de/redmine/projects/eive-flight-manual/wiki/LIS3MDL_MGM
|
||||
* @author L. Loidold, R. Mueller
|
||||
*/
|
||||
class MgmLIS3MDLHandler: public DeviceHandlerBase {
|
||||
public:
|
||||
enum class CommunicationStep {
|
||||
DATA,
|
||||
TEMPERATURE
|
||||
};
|
||||
class MgmLIS3MDLHandler : public DeviceHandlerBase {
|
||||
public:
|
||||
enum class CommunicationStep { DATA, TEMPERATURE };
|
||||
|
||||
static const uint8_t INTERFACE_ID = CLASS_ID::MGM_LIS3MDL;
|
||||
static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::MGM_LIS3MDL;
|
||||
//Notifies a command to change the setup parameters
|
||||
static const Event CHANGE_OF_SETUP_PARAMETER = MAKE_EVENT(0, severity::LOW);
|
||||
static const uint8_t INTERFACE_ID = CLASS_ID::MGM_LIS3MDL;
|
||||
static const uint8_t SUBSYSTEM_ID = SUBSYSTEM_ID::MGM_LIS3MDL;
|
||||
// Notifies a command to change the setup parameters
|
||||
static const Event CHANGE_OF_SETUP_PARAMETER = MAKE_EVENT(0, severity::LOW);
|
||||
|
||||
MgmLIS3MDLHandler(uint32_t objectId, object_id_t deviceCommunication, CookieIF* comCookie,
|
||||
uint32_t transitionDelay);
|
||||
virtual ~MgmLIS3MDLHandler();
|
||||
MgmLIS3MDLHandler(uint32_t objectId, object_id_t deviceCommunication, CookieIF *comCookie,
|
||||
uint32_t transitionDelay);
|
||||
virtual ~MgmLIS3MDLHandler();
|
||||
|
||||
/**
|
||||
* Set the absolute limit for the values on the axis in microtesla. The dataset values will
|
||||
* be marked as invalid if that limit is exceeded
|
||||
* @param xLimit
|
||||
* @param yLimit
|
||||
* @param zLimit
|
||||
*/
|
||||
void setAbsoluteLimits(float xLimit, float yLimit, float zLimit);
|
||||
void setToGoToNormalMode(bool enable);
|
||||
void enablePeriodicPrintouts(bool enable, uint8_t divider);
|
||||
/**
|
||||
* Set the absolute limit for the values on the axis in microtesla. The dataset values will
|
||||
* be marked as invalid if that limit is exceeded
|
||||
* @param xLimit
|
||||
* @param yLimit
|
||||
* @param zLimit
|
||||
*/
|
||||
void setAbsoluteLimits(float xLimit, float yLimit, float zLimit);
|
||||
void setToGoToNormalMode(bool enable);
|
||||
|
||||
protected:
|
||||
protected:
|
||||
/** DeviceHandlerBase overrides */
|
||||
void doShutDown() override;
|
||||
void doStartUp() override;
|
||||
void doTransition(Mode_t modeFrom, Submode_t subModeFrom) override;
|
||||
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
|
||||
ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) override;
|
||||
ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t *id) override;
|
||||
ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
|
||||
ReturnValue_t scanForReply(const uint8_t *start, size_t len, DeviceCommandId_t *foundId,
|
||||
size_t *foundLen) override;
|
||||
/**
|
||||
* This implementation is tailored towards space applications and will flag values larger
|
||||
* than 100 microtesla on X,Y and 150 microtesla on Z as invalid
|
||||
* @param id
|
||||
* @param packet
|
||||
* @return
|
||||
*/
|
||||
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
|
||||
void fillCommandAndReplyMap() override;
|
||||
void modeChanged(void) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) override;
|
||||
|
||||
/** DeviceHandlerBase overrides */
|
||||
void doShutDown() override;
|
||||
void doStartUp() override;
|
||||
void doTransition(Mode_t modeFrom, Submode_t subModeFrom) override;
|
||||
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
|
||||
ReturnValue_t buildCommandFromCommand(
|
||||
DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) override;
|
||||
ReturnValue_t buildTransitionDeviceCommand(
|
||||
DeviceCommandId_t *id) override;
|
||||
ReturnValue_t buildNormalDeviceCommand(
|
||||
DeviceCommandId_t *id) override;
|
||||
ReturnValue_t scanForReply(const uint8_t *start, size_t len,
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) override;
|
||||
/**
|
||||
* This implementation is tailored towards space applications and will flag values larger
|
||||
* than 100 microtesla on X,Y and 150 microtesla on Z as invalid
|
||||
* @param id
|
||||
* @param packet
|
||||
* @return
|
||||
*/
|
||||
virtual ReturnValue_t interpretDeviceReply(DeviceCommandId_t id,
|
||||
const uint8_t *packet) override;
|
||||
void fillCommandAndReplyMap() override;
|
||||
void modeChanged(void) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) override;
|
||||
private:
|
||||
MGMLIS3MDL::MgmPrimaryDataset dataset;
|
||||
// Length a single command SPI answer
|
||||
static const uint8_t SINGLE_COMMAND_ANSWER_LEN = 2;
|
||||
|
||||
private:
|
||||
MGMLIS3MDL::MgmPrimaryDataset dataset;
|
||||
//Length a single command SPI answer
|
||||
static const uint8_t SINGLE_COMMAND_ANSWER_LEN = 2;
|
||||
uint32_t transitionDelay;
|
||||
// Single SPI command has 2 bytes, first for adress, second for content
|
||||
size_t singleComandSize = 2;
|
||||
// Has the size for all adresses of the lis3mdl + the continous write bit
|
||||
uint8_t commandBuffer[MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1];
|
||||
|
||||
uint32_t transitionDelay;
|
||||
// Single SPI command has 2 bytes, first for adress, second for content
|
||||
size_t singleComandSize = 2;
|
||||
// Has the size for all adresses of the lis3mdl + the continous write bit
|
||||
uint8_t commandBuffer[MGMLIS3MDL::NR_OF_DATA_AND_CFG_REGISTERS + 1];
|
||||
float absLimitX = 100;
|
||||
float absLimitY = 100;
|
||||
float absLimitZ = 150;
|
||||
|
||||
float absLimitX = 100;
|
||||
float absLimitY = 100;
|
||||
float absLimitZ = 150;
|
||||
/**
|
||||
* We want to save the registers we set, so we dont have to read the
|
||||
* registers when we want to change something.
|
||||
* --> everytime we change set a register we have to save it
|
||||
*/
|
||||
uint8_t registers[MGMLIS3MDL::NR_OF_CTRL_REGISTERS];
|
||||
|
||||
/**
|
||||
* We want to save the registers we set, so we dont have to read the
|
||||
* registers when we want to change something.
|
||||
* --> everytime we change set a register we have to save it
|
||||
*/
|
||||
uint8_t registers[MGMLIS3MDL::NR_OF_CTRL_REGISTERS];
|
||||
uint8_t statusRegister = 0;
|
||||
bool goToNormalMode = false;
|
||||
|
||||
uint8_t statusRegister = 0;
|
||||
bool goToNormalMode = false;
|
||||
enum class InternalState {
|
||||
STATE_NONE,
|
||||
STATE_FIRST_CONTACT,
|
||||
STATE_SETUP,
|
||||
STATE_CHECK_REGISTERS,
|
||||
STATE_NORMAL
|
||||
};
|
||||
|
||||
enum class InternalState {
|
||||
STATE_NONE,
|
||||
STATE_FIRST_CONTACT,
|
||||
STATE_SETUP,
|
||||
STATE_CHECK_REGISTERS,
|
||||
STATE_NORMAL
|
||||
};
|
||||
InternalState internalState = InternalState::STATE_NONE;
|
||||
CommunicationStep communicationStep = CommunicationStep::DATA;
|
||||
bool commandExecuted = false;
|
||||
|
||||
InternalState internalState = InternalState::STATE_NONE;
|
||||
CommunicationStep communicationStep = CommunicationStep::DATA;
|
||||
bool commandExecuted = false;
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* 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);
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
ReturnValue_t identifyDevice();
|
||||
|
||||
/**
|
||||
* This Command detects the device ID
|
||||
*/
|
||||
ReturnValue_t identifyDevice();
|
||||
virtual void setupMgm();
|
||||
|
||||
virtual void setupMgm();
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Non normal commands */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/**
|
||||
* Enables/Disables the integrated Temperaturesensor
|
||||
* @param commandData On or Off
|
||||
* @param length of the commandData: has to be 1
|
||||
*/
|
||||
virtual ReturnValue_t enableTemperatureSensor(const uint8_t *commandData, size_t commandDataLen);
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Non normal commands */
|
||||
/*------------------------------------------------------------------------*/
|
||||
/**
|
||||
* Enables/Disables the integrated Temperaturesensor
|
||||
* @param commandData On or Off
|
||||
* @param length of the commandData: has to be 1
|
||||
*/
|
||||
virtual ReturnValue_t enableTemperatureSensor(const uint8_t *commandData,
|
||||
size_t commandDataLen);
|
||||
/**
|
||||
* Sets the accuracy of the measurement of the axis. The noise is changing.
|
||||
* @param commandData LOW, MEDIUM, HIGH, ULTRA
|
||||
* @param length of the command, has to be 1
|
||||
*/
|
||||
virtual ReturnValue_t setOperatingMode(const uint8_t *commandData, size_t commandDataLen);
|
||||
|
||||
/**
|
||||
* Sets the accuracy of the measurement of the axis. The noise is changing.
|
||||
* @param commandData LOW, MEDIUM, HIGH, ULTRA
|
||||
* @param length of the command, has to be 1
|
||||
*/
|
||||
virtual ReturnValue_t setOperatingMode(const uint8_t *commandData,
|
||||
size_t commandDataLen);
|
||||
/**
|
||||
* We always update all registers together, so this method updates
|
||||
* the rawpacket and rawpacketLen, so we just manipulate the local
|
||||
* saved register
|
||||
*
|
||||
*/
|
||||
ReturnValue_t prepareCtrlRegisterWrite();
|
||||
|
||||
/**
|
||||
* We always update all registers together, so this method updates
|
||||
* the rawpacket and rawpacketLen, so we just manipulate the local
|
||||
* saved register
|
||||
*
|
||||
*/
|
||||
ReturnValue_t prepareCtrlRegisterWrite();
|
||||
|
||||
#if FSFW_HAL_LIS3MDL_MGM_DEBUG == 1
|
||||
PeriodicOperationDivider* debugDivider;
|
||||
#endif
|
||||
bool periodicPrintout = false;
|
||||
PeriodicOperationDivider debugDivider = PeriodicOperationDivider(3);
|
||||
};
|
||||
|
||||
#endif /* MISSION_DEVICES_MGMLIS3MDLHANDLER_H_ */
|
||||
|
@ -1,376 +1,368 @@
|
||||
#include "MgmRM3100Handler.h"
|
||||
|
||||
#include "fsfw/datapool/PoolReadGuard.h"
|
||||
#include "fsfw/globalfunctions/bitutility.h"
|
||||
#include "fsfw/devicehandlers/DeviceHandlerMessage.h"
|
||||
#include "fsfw/globalfunctions/bitutility.h"
|
||||
#include "fsfw/objectmanager/SystemObjectIF.h"
|
||||
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
|
||||
|
||||
|
||||
MgmRM3100Handler::MgmRM3100Handler(object_id_t objectId,
|
||||
object_id_t deviceCommunication, CookieIF* comCookie, uint32_t transitionDelay):
|
||||
DeviceHandlerBase(objectId, deviceCommunication, comCookie),
|
||||
primaryDataset(this), transitionDelay(transitionDelay) {
|
||||
#if FSFW_HAL_RM3100_MGM_DEBUG == 1
|
||||
debugDivider = new PeriodicOperationDivider(3);
|
||||
#endif
|
||||
}
|
||||
MgmRM3100Handler::MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication,
|
||||
CookieIF *comCookie, uint32_t transitionDelay)
|
||||
: DeviceHandlerBase(objectId, deviceCommunication, comCookie),
|
||||
primaryDataset(this),
|
||||
transitionDelay(transitionDelay) {}
|
||||
|
||||
MgmRM3100Handler::~MgmRM3100Handler() {}
|
||||
|
||||
void MgmRM3100Handler::doStartUp() {
|
||||
switch(internalState) {
|
||||
case(InternalState::NONE): {
|
||||
internalState = InternalState::CONFIGURE_CMM;
|
||||
break;
|
||||
switch (internalState) {
|
||||
case (InternalState::NONE): {
|
||||
internalState = InternalState::CONFIGURE_CMM;
|
||||
break;
|
||||
}
|
||||
case(InternalState::CONFIGURE_CMM): {
|
||||
internalState = InternalState::READ_CMM;
|
||||
break;
|
||||
case (InternalState::CONFIGURE_CMM): {
|
||||
internalState = InternalState::READ_CMM;
|
||||
break;
|
||||
}
|
||||
case(InternalState::READ_CMM): {
|
||||
if(commandExecuted) {
|
||||
internalState = InternalState::STATE_CONFIGURE_TMRC;
|
||||
case (InternalState::READ_CMM): {
|
||||
if (commandExecuted) {
|
||||
internalState = InternalState::STATE_CONFIGURE_TMRC;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case (InternalState::STATE_CONFIGURE_TMRC): {
|
||||
if (commandExecuted) {
|
||||
internalState = InternalState::STATE_READ_TMRC;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case (InternalState::STATE_READ_TMRC): {
|
||||
if (commandExecuted) {
|
||||
internalState = InternalState::NORMAL;
|
||||
if (goToNormalModeAtStartup) {
|
||||
setMode(MODE_NORMAL);
|
||||
} else {
|
||||
setMode(_MODE_TO_ON);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_CONFIGURE_TMRC): {
|
||||
if(commandExecuted) {
|
||||
internalState = InternalState::STATE_READ_TMRC;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_READ_TMRC): {
|
||||
if(commandExecuted) {
|
||||
internalState = InternalState::NORMAL;
|
||||
if(goToNormalModeAtStartup) {
|
||||
setMode(MODE_NORMAL);
|
||||
}
|
||||
else {
|
||||
setMode(_MODE_TO_ON);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MgmRM3100Handler::doShutDown() {
|
||||
setMode(_MODE_POWER_DOWN);
|
||||
}
|
||||
void MgmRM3100Handler::doShutDown() { setMode(_MODE_POWER_DOWN); }
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(
|
||||
DeviceCommandId_t *id) {
|
||||
size_t commandLen = 0;
|
||||
switch(internalState) {
|
||||
case(InternalState::NONE):
|
||||
case(InternalState::NORMAL): {
|
||||
return NOTHING_TO_SEND;
|
||||
ReturnValue_t MgmRM3100Handler::buildTransitionDeviceCommand(DeviceCommandId_t *id) {
|
||||
size_t commandLen = 0;
|
||||
switch (internalState) {
|
||||
case (InternalState::NONE):
|
||||
case (InternalState::NORMAL): {
|
||||
return NOTHING_TO_SEND;
|
||||
}
|
||||
case(InternalState::CONFIGURE_CMM): {
|
||||
*id = RM3100::CONFIGURE_CMM;
|
||||
break;
|
||||
case (InternalState::CONFIGURE_CMM): {
|
||||
*id = RM3100::CONFIGURE_CMM;
|
||||
break;
|
||||
}
|
||||
case(InternalState::READ_CMM): {
|
||||
*id = RM3100::READ_CMM;
|
||||
break;
|
||||
case (InternalState::READ_CMM): {
|
||||
*id = RM3100::READ_CMM;
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_CONFIGURE_TMRC): {
|
||||
commandBuffer[0] = RM3100::TMRC_DEFAULT_VALUE;
|
||||
commandLen = 1;
|
||||
*id = RM3100::CONFIGURE_TMRC;
|
||||
break;
|
||||
case (InternalState::STATE_CONFIGURE_TMRC): {
|
||||
commandBuffer[0] = RM3100::TMRC_DEFAULT_VALUE;
|
||||
commandLen = 1;
|
||||
*id = RM3100::CONFIGURE_TMRC;
|
||||
break;
|
||||
}
|
||||
case(InternalState::STATE_READ_TMRC): {
|
||||
*id = RM3100::READ_TMRC;
|
||||
break;
|
||||
case (InternalState::STATE_READ_TMRC): {
|
||||
*id = RM3100::READ_TMRC;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
// Might be a configuration error
|
||||
sif::warning << "MgmRM3100Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state" << std::endl;
|
||||
// Might be a configuration error
|
||||
sif::warning << "MgmRM3100Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state"
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("MgmRM3100Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state\n");
|
||||
sif::printWarning(
|
||||
"MgmRM3100Handler::buildTransitionDeviceCommand: "
|
||||
"Unknown internal state\n");
|
||||
#endif
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
return buildCommandFromCommand(*id, commandBuffer, commandLen);
|
||||
return buildCommandFromCommand(*id, commandBuffer, commandLen);
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::buildCommandFromCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData, size_t commandDataLen) {
|
||||
switch(deviceCommand) {
|
||||
case(RM3100::CONFIGURE_CMM): {
|
||||
commandBuffer[0] = RM3100::CMM_REGISTER;
|
||||
commandBuffer[1] = RM3100::CMM_VALUE;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 2;
|
||||
break;
|
||||
const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
switch (deviceCommand) {
|
||||
case (RM3100::CONFIGURE_CMM): {
|
||||
commandBuffer[0] = RM3100::CMM_REGISTER;
|
||||
commandBuffer[1] = RM3100::CMM_VALUE;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 2;
|
||||
break;
|
||||
}
|
||||
case(RM3100::READ_CMM): {
|
||||
commandBuffer[0] = RM3100::CMM_REGISTER | RM3100::READ_MASK;
|
||||
commandBuffer[1] = 0;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 2;
|
||||
break;
|
||||
case (RM3100::READ_CMM): {
|
||||
commandBuffer[0] = RM3100::CMM_REGISTER | RM3100::READ_MASK;
|
||||
commandBuffer[1] = 0;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 2;
|
||||
break;
|
||||
}
|
||||
case(RM3100::CONFIGURE_TMRC): {
|
||||
return handleTmrcConfigCommand(deviceCommand, commandData, commandDataLen);
|
||||
case (RM3100::CONFIGURE_TMRC): {
|
||||
return handleTmrcConfigCommand(deviceCommand, commandData, commandDataLen);
|
||||
}
|
||||
case(RM3100::READ_TMRC): {
|
||||
commandBuffer[0] = RM3100::TMRC_REGISTER | RM3100::READ_MASK;
|
||||
commandBuffer[1] = 0;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 2;
|
||||
break;
|
||||
case (RM3100::READ_TMRC): {
|
||||
commandBuffer[0] = RM3100::TMRC_REGISTER | RM3100::READ_MASK;
|
||||
commandBuffer[1] = 0;
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 2;
|
||||
break;
|
||||
}
|
||||
case(RM3100::CONFIGURE_CYCLE_COUNT): {
|
||||
return handleCycleCountConfigCommand(deviceCommand, commandData, commandDataLen);
|
||||
case (RM3100::CONFIGURE_CYCLE_COUNT): {
|
||||
return handleCycleCountConfigCommand(deviceCommand, commandData, commandDataLen);
|
||||
}
|
||||
case(RM3100::READ_CYCLE_COUNT): {
|
||||
commandBuffer[0] = RM3100::CYCLE_COUNT_START_REGISTER | RM3100::READ_MASK;
|
||||
std::memset(commandBuffer + 1, 0, 6);
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 7;
|
||||
break;
|
||||
case (RM3100::READ_CYCLE_COUNT): {
|
||||
commandBuffer[0] = RM3100::CYCLE_COUNT_START_REGISTER | RM3100::READ_MASK;
|
||||
std::memset(commandBuffer + 1, 0, 6);
|
||||
rawPacket = commandBuffer;
|
||||
rawPacketLen = 7;
|
||||
break;
|
||||
}
|
||||
case(RM3100::READ_DATA): {
|
||||
commandBuffer[0] = RM3100::MEASUREMENT_REG_START | RM3100::READ_MASK;
|
||||
std::memset(commandBuffer + 1, 0, 9);
|
||||
rawPacketLen = 10;
|
||||
break;
|
||||
case (RM3100::READ_DATA): {
|
||||
commandBuffer[0] = RM3100::MEASUREMENT_REG_START | RM3100::READ_MASK;
|
||||
std::memset(commandBuffer + 1, 0, 9);
|
||||
rawPacketLen = 10;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return RETURN_OK;
|
||||
return DeviceHandlerIF::COMMAND_NOT_IMPLEMENTED;
|
||||
}
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::buildNormalDeviceCommand(
|
||||
DeviceCommandId_t *id) {
|
||||
*id = RM3100::READ_DATA;
|
||||
return buildCommandFromCommand(*id, nullptr, 0);
|
||||
ReturnValue_t MgmRM3100Handler::buildNormalDeviceCommand(DeviceCommandId_t *id) {
|
||||
*id = RM3100::READ_DATA;
|
||||
return buildCommandFromCommand(*id, nullptr, 0);
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::scanForReply(const uint8_t *start,
|
||||
size_t len, DeviceCommandId_t *foundId,
|
||||
size_t *foundLen) {
|
||||
|
||||
// For SPI, ID will always be the one of the last sent command
|
||||
*foundId = this->getPendingCommand();
|
||||
*foundLen = len;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t MgmRM3100Handler::scanForReply(const uint8_t *start, size_t len,
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) {
|
||||
// For SPI, ID will always be the one of the last sent command
|
||||
*foundId = this->getPendingCommand();
|
||||
*foundLen = len;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) {
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
switch(id) {
|
||||
case(RM3100::CONFIGURE_CMM):
|
||||
case(RM3100::CONFIGURE_CYCLE_COUNT):
|
||||
case(RM3100::CONFIGURE_TMRC): {
|
||||
// We can only check whether write was successful with read operation
|
||||
if(mode == _MODE_START_UP) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
break;
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
switch (id) {
|
||||
case (RM3100::CONFIGURE_CMM):
|
||||
case (RM3100::CONFIGURE_CYCLE_COUNT):
|
||||
case (RM3100::CONFIGURE_TMRC): {
|
||||
// We can only check whether write was successful with read operation
|
||||
if (mode == _MODE_START_UP) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(RM3100::READ_CMM): {
|
||||
uint8_t cmmValue = packet[1];
|
||||
// We clear the seventh bit in any case
|
||||
// because this one is zero sometimes for some reason
|
||||
bitutil::clear(&cmmValue, 6);
|
||||
if(cmmValue == cmmRegValue and internalState == InternalState::READ_CMM) {
|
||||
commandExecuted = true;
|
||||
}
|
||||
else {
|
||||
// Attempt reconfiguration
|
||||
internalState = InternalState::CONFIGURE_CMM;
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
break;
|
||||
case (RM3100::READ_CMM): {
|
||||
uint8_t cmmValue = packet[1];
|
||||
// We clear the seventh bit in any case
|
||||
// because this one is zero sometimes for some reason
|
||||
bitutil::clear(&cmmValue, 6);
|
||||
if (cmmValue == cmmRegValue and internalState == InternalState::READ_CMM) {
|
||||
commandExecuted = true;
|
||||
} else {
|
||||
// Attempt reconfiguration
|
||||
internalState = InternalState::CONFIGURE_CMM;
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(RM3100::READ_TMRC): {
|
||||
if(packet[1] == tmrcRegValue) {
|
||||
commandExecuted = true;
|
||||
// Reading TMRC was commanded. Trigger event to inform ground
|
||||
if(mode != _MODE_START_UP) {
|
||||
triggerEvent(tmrcSet, tmrcRegValue, 0);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Attempt reconfiguration
|
||||
internalState = InternalState::STATE_CONFIGURE_TMRC;
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(RM3100::READ_CYCLE_COUNT): {
|
||||
uint16_t cycleCountX = packet[1] << 8 | packet[2];
|
||||
uint16_t cycleCountY = packet[3] << 8 | packet[4];
|
||||
uint16_t cycleCountZ = packet[5] << 8 | packet[6];
|
||||
if(cycleCountX != cycleCountRegValueX or cycleCountY != cycleCountRegValueY or
|
||||
cycleCountZ != cycleCountRegValueZ) {
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
case (RM3100::READ_TMRC): {
|
||||
if (packet[1] == tmrcRegValue) {
|
||||
commandExecuted = true;
|
||||
// Reading TMRC was commanded. Trigger event to inform ground
|
||||
if(mode != _MODE_START_UP) {
|
||||
uint32_t eventParam1 = (cycleCountX << 16) | cycleCountY;
|
||||
triggerEvent(cycleCountersSet, eventParam1, cycleCountZ);
|
||||
if (mode != _MODE_START_UP) {
|
||||
triggerEvent(tmrcSet, tmrcRegValue, 0);
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
// Attempt reconfiguration
|
||||
internalState = InternalState::STATE_CONFIGURE_TMRC;
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(RM3100::READ_DATA): {
|
||||
result = handleDataReadout(packet);
|
||||
break;
|
||||
case (RM3100::READ_CYCLE_COUNT): {
|
||||
uint16_t cycleCountX = packet[1] << 8 | packet[2];
|
||||
uint16_t cycleCountY = packet[3] << 8 | packet[4];
|
||||
uint16_t cycleCountZ = packet[5] << 8 | packet[6];
|
||||
if (cycleCountX != cycleCountRegValueX or cycleCountY != cycleCountRegValueY or
|
||||
cycleCountZ != cycleCountRegValueZ) {
|
||||
return DeviceHandlerIF::DEVICE_REPLY_INVALID;
|
||||
}
|
||||
// Reading TMRC was commanded. Trigger event to inform ground
|
||||
if (mode != _MODE_START_UP) {
|
||||
uint32_t eventParam1 = (cycleCountX << 16) | cycleCountY;
|
||||
triggerEvent(cycleCountersSet, eventParam1, cycleCountZ);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case (RM3100::READ_DATA): {
|
||||
result = handleDataReadout(packet);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY;
|
||||
}
|
||||
return DeviceHandlerIF::UNKNOWN_DEVICE_REPLY;
|
||||
}
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData, size_t commandDataLen) {
|
||||
if(commandData == nullptr) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
if (commandData == nullptr) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
|
||||
// Set cycle count
|
||||
if(commandDataLen == 2) {
|
||||
handleCycleCommand(true, commandData, commandDataLen);
|
||||
}
|
||||
else if(commandDataLen == 6) {
|
||||
handleCycleCommand(false, commandData, commandDataLen);
|
||||
}
|
||||
else {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
// Set cycle count
|
||||
if (commandDataLen == 2) {
|
||||
handleCycleCommand(true, commandData, commandDataLen);
|
||||
} else if (commandDataLen == 6) {
|
||||
handleCycleCommand(false, commandData, commandDataLen);
|
||||
} else {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
|
||||
commandBuffer[0] = RM3100::CYCLE_COUNT_VALUE;
|
||||
std::memcpy(commandBuffer + 1, &cycleCountRegValueX, 2);
|
||||
std::memcpy(commandBuffer + 3, &cycleCountRegValueY, 2);
|
||||
std::memcpy(commandBuffer + 5, &cycleCountRegValueZ, 2);
|
||||
rawPacketLen = 7;
|
||||
rawPacket = commandBuffer;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
commandBuffer[0] = RM3100::CYCLE_COUNT_VALUE;
|
||||
std::memcpy(commandBuffer + 1, &cycleCountRegValueX, 2);
|
||||
std::memcpy(commandBuffer + 3, &cycleCountRegValueY, 2);
|
||||
std::memcpy(commandBuffer + 5, &cycleCountRegValueZ, 2);
|
||||
rawPacketLen = 7;
|
||||
rawPacket = commandBuffer;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue,
|
||||
const uint8_t *commandData, size_t commandDataLen) {
|
||||
RM3100::CycleCountCommand command(oneCycleValue);
|
||||
ReturnValue_t result = command.deSerialize(&commandData, &commandDataLen,
|
||||
SerializeIF::Endianness::BIG);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
ReturnValue_t MgmRM3100Handler::handleCycleCommand(bool oneCycleValue, const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
RM3100::CycleCountCommand command(oneCycleValue);
|
||||
ReturnValue_t result =
|
||||
command.deSerialize(&commandData, &commandDataLen, SerializeIF::Endianness::BIG);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Data sheet p.30 "while noise limits the useful upper range to ~400 cycle counts."
|
||||
if(command.cycleCountX > 450 ) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
// Data sheet p.30 "while noise limits the useful upper range to ~400 cycle counts."
|
||||
if (command.cycleCountX > 450) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
|
||||
if(not oneCycleValue and (command.cycleCountY > 450 or command.cycleCountZ > 450)) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
if (not oneCycleValue and (command.cycleCountY > 450 or command.cycleCountZ > 450)) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
|
||||
cycleCountRegValueX = command.cycleCountX;
|
||||
cycleCountRegValueY = command.cycleCountY;
|
||||
cycleCountRegValueZ = command.cycleCountZ;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
cycleCountRegValueX = command.cycleCountX;
|
||||
cycleCountRegValueY = command.cycleCountY;
|
||||
cycleCountRegValueZ = command.cycleCountZ;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::handleTmrcConfigCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData, size_t commandDataLen) {
|
||||
if(commandData == nullptr or commandDataLen != 1) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
const uint8_t *commandData,
|
||||
size_t commandDataLen) {
|
||||
if (commandData == nullptr or commandDataLen != 1) {
|
||||
return DeviceHandlerIF::INVALID_COMMAND_PARAMETER;
|
||||
}
|
||||
|
||||
commandBuffer[0] = RM3100::TMRC_REGISTER;
|
||||
commandBuffer[1] = commandData[0];
|
||||
tmrcRegValue = commandData[0];
|
||||
rawPacketLen = 2;
|
||||
rawPacket = commandBuffer;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
commandBuffer[0] = RM3100::TMRC_REGISTER;
|
||||
commandBuffer[1] = commandData[0];
|
||||
tmrcRegValue = commandData[0];
|
||||
rawPacketLen = 2;
|
||||
rawPacket = commandBuffer;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void MgmRM3100Handler::fillCommandAndReplyMap() {
|
||||
insertInCommandAndReplyMap(RM3100::CONFIGURE_CMM, 3);
|
||||
insertInCommandAndReplyMap(RM3100::READ_CMM, 3);
|
||||
insertInCommandAndReplyMap(RM3100::CONFIGURE_CMM, 3);
|
||||
insertInCommandAndReplyMap(RM3100::READ_CMM, 3);
|
||||
|
||||
insertInCommandAndReplyMap(RM3100::CONFIGURE_TMRC, 3);
|
||||
insertInCommandAndReplyMap(RM3100::READ_TMRC, 3);
|
||||
insertInCommandAndReplyMap(RM3100::CONFIGURE_TMRC, 3);
|
||||
insertInCommandAndReplyMap(RM3100::READ_TMRC, 3);
|
||||
|
||||
insertInCommandAndReplyMap(RM3100::CONFIGURE_CYCLE_COUNT, 3);
|
||||
insertInCommandAndReplyMap(RM3100::READ_CYCLE_COUNT, 3);
|
||||
insertInCommandAndReplyMap(RM3100::CONFIGURE_CYCLE_COUNT, 3);
|
||||
insertInCommandAndReplyMap(RM3100::READ_CYCLE_COUNT, 3);
|
||||
|
||||
insertInCommandAndReplyMap(RM3100::READ_DATA, 3, &primaryDataset);
|
||||
insertInCommandAndReplyMap(RM3100::READ_DATA, 3, &primaryDataset);
|
||||
}
|
||||
|
||||
void MgmRM3100Handler::modeChanged(void) {
|
||||
internalState = InternalState::NONE;
|
||||
}
|
||||
void MgmRM3100Handler::modeChanged(void) { internalState = InternalState::NONE; }
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::initializeLocalDataPool(
|
||||
localpool::DataPool &localDataPoolMap, LocalDataPoolManager &poolManager) {
|
||||
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t MgmRM3100Handler::initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) {
|
||||
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_X, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Y, new PoolEntry<float>({0.0}));
|
||||
localDataPoolMap.emplace(RM3100::FIELD_STRENGTH_Z, new PoolEntry<float>({0.0}));
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
uint32_t MgmRM3100Handler::getTransitionDelayMs(Mode_t from, Mode_t to) {
|
||||
return this->transitionDelay;
|
||||
return this->transitionDelay;
|
||||
}
|
||||
|
||||
void MgmRM3100Handler::setToGoToNormalMode(bool enable) {
|
||||
goToNormalModeAtStartup = enable;
|
||||
}
|
||||
void MgmRM3100Handler::setToGoToNormalMode(bool enable) { goToNormalModeAtStartup = enable; }
|
||||
|
||||
ReturnValue_t MgmRM3100Handler::handleDataReadout(const uint8_t *packet) {
|
||||
// Analyze data here. The sensor generates 24 bit signed values so we need to do some bitshift
|
||||
// trickery here to calculate the raw values first
|
||||
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 fieldStrengthRawZ = ((packet[7] << 24) | (packet[8] << 16) | (packet[3] << 8)) >> 8;
|
||||
// Analyze data here. The sensor generates 24 bit signed values so we need to do some bitshift
|
||||
// trickery here to calculate the raw values first
|
||||
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 fieldStrengthRawZ = ((packet[7] << 24) | (packet[8] << 16) | (packet[3] << 8)) >> 8;
|
||||
|
||||
// Now scale to physical value in microtesla
|
||||
float fieldStrengthX = fieldStrengthRawX * scaleFactorX;
|
||||
float fieldStrengthY = fieldStrengthRawY * scaleFactorX;
|
||||
float fieldStrengthZ = fieldStrengthRawZ * scaleFactorX;
|
||||
// Now scale to physical value in microtesla
|
||||
float fieldStrengthX = fieldStrengthRawX * scaleFactorX;
|
||||
float fieldStrengthY = fieldStrengthRawY * scaleFactorX;
|
||||
float fieldStrengthZ = fieldStrengthRawZ * scaleFactorX;
|
||||
|
||||
#if FSFW_HAL_RM3100_MGM_DEBUG == 1
|
||||
if(debugDivider->checkAndIncrement()) {
|
||||
if (periodicPrintout) {
|
||||
if (debugDivider.checkAndIncrement()) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << "MgmRM3100Handler: Magnetic field strength in"
|
||||
" microtesla:" << std::endl;
|
||||
sif::info << "X: " << fieldStrengthX << " uT" << std::endl;
|
||||
sif::info << "Y: " << fieldStrengthY << " uT" << std::endl;
|
||||
sif::info << "Z: " << fieldStrengthZ << " uT" << std::endl;
|
||||
sif::info << "MgmRM3100Handler: Magnetic field strength in"
|
||||
" microtesla:"
|
||||
<< std::endl;
|
||||
sif::info << "X: " << fieldStrengthX << " uT" << std::endl;
|
||||
sif::info << "Y: " << fieldStrengthY << " uT" << std::endl;
|
||||
sif::info << "Z: " << fieldStrengthZ << " uT" << std::endl;
|
||||
#else
|
||||
sif::printInfo("MgmRM3100Handler: Magnetic field strength in microtesla:\n");
|
||||
sif::printInfo("X: %f uT\n", fieldStrengthX);
|
||||
sif::printInfo("Y: %f uT\n", fieldStrengthY);
|
||||
sif::printInfo("Z: %f uT\n", fieldStrengthZ);
|
||||
sif::printInfo("MgmRM3100Handler: Magnetic field strength in microtesla:\n");
|
||||
sif::printInfo("X: %f uT\n", fieldStrengthX);
|
||||
sif::printInfo("Y: %f uT\n", fieldStrengthY);
|
||||
sif::printInfo("Z: %f uT\n", fieldStrengthZ);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// TODO: Sanity check on values?
|
||||
PoolReadGuard readGuard(&primaryDataset);
|
||||
if(readGuard.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
|
||||
primaryDataset.fieldStrengthX = fieldStrengthX;
|
||||
primaryDataset.fieldStrengthY = fieldStrengthY;
|
||||
primaryDataset.fieldStrengthZ = fieldStrengthZ;
|
||||
primaryDataset.setValidity(true, true);
|
||||
}
|
||||
return RETURN_OK;
|
||||
// TODO: Sanity check on values?
|
||||
PoolReadGuard readGuard(&primaryDataset);
|
||||
if (readGuard.getReadResult() == HasReturnvaluesIF::RETURN_OK) {
|
||||
primaryDataset.fieldStrengthX = fieldStrengthX;
|
||||
primaryDataset.fieldStrengthY = fieldStrengthY;
|
||||
primaryDataset.fieldStrengthZ = fieldStrengthZ;
|
||||
primaryDataset.setValidity(true, true);
|
||||
}
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
void MgmRM3100Handler::enablePeriodicPrintouts(bool enable, uint8_t divider) {
|
||||
periodicPrintout = enable;
|
||||
debugDivider.setDivider(divider);
|
||||
}
|
||||
|
@ -1,13 +1,9 @@
|
||||
#ifndef MISSION_DEVICES_MGMRM3100HANDLER_H_
|
||||
#define MISSION_DEVICES_MGMRM3100HANDLER_H_
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "devicedefinitions/MgmRM3100HandlerDefs.h"
|
||||
#include "fsfw/devicehandlers/DeviceHandlerBase.h"
|
||||
|
||||
#if FSFW_HAL_RM3100_MGM_DEBUG == 1
|
||||
#include "fsfw/globalfunctions/PeriodicOperationDivider.h"
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Device Handler for the RM3100 geomagnetic magnetometer sensor
|
||||
@ -16,95 +12,92 @@
|
||||
* Flight manual:
|
||||
* https://egit.irs.uni-stuttgart.de/redmine/projects/eive-flight-manual/wiki/RM3100_MGM
|
||||
*/
|
||||
class MgmRM3100Handler: public DeviceHandlerBase {
|
||||
public:
|
||||
static const uint8_t INTERFACE_ID = CLASS_ID::MGM_RM3100;
|
||||
class MgmRM3100Handler : public DeviceHandlerBase {
|
||||
public:
|
||||
static const uint8_t INTERFACE_ID = CLASS_ID::MGM_RM3100;
|
||||
|
||||
//! [EXPORT] : [COMMENT] P1: TMRC value which was set, P2: 0
|
||||
static constexpr Event tmrcSet = event::makeEvent(SUBSYSTEM_ID::MGM_RM3100,
|
||||
0x00, severity::INFO);
|
||||
//! [EXPORT] : [COMMENT] P1: TMRC value which was set, P2: 0
|
||||
static constexpr Event tmrcSet = event::makeEvent(SUBSYSTEM_ID::MGM_RM3100, 0x00, severity::INFO);
|
||||
|
||||
//! [EXPORT] : [COMMENT] Cycle counter set. P1: First two bytes new Cycle Count X
|
||||
//! P1: Second two bytes new Cycle Count Y
|
||||
//! P2: New cycle count Z
|
||||
static constexpr Event cycleCountersSet = event::makeEvent(
|
||||
SUBSYSTEM_ID::MGM_RM3100, 0x01, severity::INFO);
|
||||
//! [EXPORT] : [COMMENT] Cycle counter set. P1: First two bytes new Cycle Count X
|
||||
//! P1: Second two bytes new Cycle Count Y
|
||||
//! P2: New cycle count Z
|
||||
static constexpr Event cycleCountersSet =
|
||||
event::makeEvent(SUBSYSTEM_ID::MGM_RM3100, 0x01, severity::INFO);
|
||||
|
||||
MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication,
|
||||
CookieIF* comCookie, uint32_t transitionDelay);
|
||||
virtual ~MgmRM3100Handler();
|
||||
MgmRM3100Handler(object_id_t objectId, object_id_t deviceCommunication, CookieIF *comCookie,
|
||||
uint32_t transitionDelay);
|
||||
virtual ~MgmRM3100Handler();
|
||||
|
||||
/**
|
||||
* Configure device handler to go to normal mode after startup immediately
|
||||
* @param enable
|
||||
*/
|
||||
void setToGoToNormalMode(bool enable);
|
||||
void enablePeriodicPrintouts(bool enable, uint8_t divider);
|
||||
/**
|
||||
* Configure device handler to go to normal mode after startup immediately
|
||||
* @param enable
|
||||
*/
|
||||
void setToGoToNormalMode(bool enable);
|
||||
|
||||
protected:
|
||||
protected:
|
||||
/* DeviceHandlerBase overrides */
|
||||
ReturnValue_t buildTransitionDeviceCommand(DeviceCommandId_t *id) override;
|
||||
void doStartUp() override;
|
||||
void doShutDown() override;
|
||||
ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
|
||||
ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen) override;
|
||||
ReturnValue_t scanForReply(const uint8_t *start, size_t len, DeviceCommandId_t *foundId,
|
||||
size_t *foundLen) override;
|
||||
ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
|
||||
|
||||
/* DeviceHandlerBase overrides */
|
||||
ReturnValue_t buildTransitionDeviceCommand(
|
||||
DeviceCommandId_t *id) override;
|
||||
void doStartUp() override;
|
||||
void doShutDown() override;
|
||||
ReturnValue_t buildNormalDeviceCommand(DeviceCommandId_t *id) override;
|
||||
ReturnValue_t buildCommandFromCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData, size_t commandDataLen) override;
|
||||
ReturnValue_t scanForReply(const uint8_t *start, size_t len,
|
||||
DeviceCommandId_t *foundId, size_t *foundLen) override;
|
||||
ReturnValue_t interpretDeviceReply(DeviceCommandId_t id, const uint8_t *packet) override;
|
||||
void fillCommandAndReplyMap() override;
|
||||
void modeChanged(void) override;
|
||||
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) override;
|
||||
|
||||
void fillCommandAndReplyMap() override;
|
||||
void modeChanged(void) override;
|
||||
virtual uint32_t getTransitionDelayMs(Mode_t from, Mode_t to) override;
|
||||
ReturnValue_t initializeLocalDataPool(localpool::DataPool &localDataPoolMap,
|
||||
LocalDataPoolManager &poolManager) override;
|
||||
private:
|
||||
enum class InternalState {
|
||||
NONE,
|
||||
CONFIGURE_CMM,
|
||||
READ_CMM,
|
||||
// The cycle count states are propably not going to be used because
|
||||
// the default cycle count will be used.
|
||||
STATE_CONFIGURE_CYCLE_COUNT,
|
||||
STATE_READ_CYCLE_COUNT,
|
||||
STATE_CONFIGURE_TMRC,
|
||||
STATE_READ_TMRC,
|
||||
NORMAL
|
||||
};
|
||||
InternalState internalState = InternalState::NONE;
|
||||
bool commandExecuted = false;
|
||||
RM3100::Rm3100PrimaryDataset primaryDataset;
|
||||
|
||||
private:
|
||||
uint8_t commandBuffer[10];
|
||||
uint8_t commandBufferLen = 0;
|
||||
|
||||
enum class InternalState {
|
||||
NONE,
|
||||
CONFIGURE_CMM,
|
||||
READ_CMM,
|
||||
// The cycle count states are propably not going to be used because
|
||||
// the default cycle count will be used.
|
||||
STATE_CONFIGURE_CYCLE_COUNT,
|
||||
STATE_READ_CYCLE_COUNT,
|
||||
STATE_CONFIGURE_TMRC,
|
||||
STATE_READ_TMRC,
|
||||
NORMAL
|
||||
};
|
||||
InternalState internalState = InternalState::NONE;
|
||||
bool commandExecuted = false;
|
||||
RM3100::Rm3100PrimaryDataset primaryDataset;
|
||||
uint8_t cmmRegValue = RM3100::CMM_VALUE;
|
||||
uint8_t tmrcRegValue = RM3100::TMRC_DEFAULT_VALUE;
|
||||
uint16_t cycleCountRegValueX = RM3100::CYCLE_COUNT_VALUE;
|
||||
uint16_t cycleCountRegValueY = RM3100::CYCLE_COUNT_VALUE;
|
||||
uint16_t cycleCountRegValueZ = RM3100::CYCLE_COUNT_VALUE;
|
||||
float scaleFactorX = 1.0 / RM3100::DEFAULT_GAIN;
|
||||
float scaleFactorY = 1.0 / RM3100::DEFAULT_GAIN;
|
||||
float scaleFactorZ = 1.0 / RM3100::DEFAULT_GAIN;
|
||||
|
||||
uint8_t commandBuffer[10];
|
||||
uint8_t commandBufferLen = 0;
|
||||
bool goToNormalModeAtStartup = false;
|
||||
uint32_t transitionDelay;
|
||||
|
||||
uint8_t cmmRegValue = RM3100::CMM_VALUE;
|
||||
uint8_t tmrcRegValue = RM3100::TMRC_DEFAULT_VALUE;
|
||||
uint16_t cycleCountRegValueX = RM3100::CYCLE_COUNT_VALUE;
|
||||
uint16_t cycleCountRegValueY = RM3100::CYCLE_COUNT_VALUE;
|
||||
uint16_t cycleCountRegValueZ = RM3100::CYCLE_COUNT_VALUE;
|
||||
float scaleFactorX = 1.0 / RM3100::DEFAULT_GAIN;
|
||||
float scaleFactorY = 1.0 / RM3100::DEFAULT_GAIN;
|
||||
float scaleFactorZ = 1.0 / RM3100::DEFAULT_GAIN;
|
||||
ReturnValue_t handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData, size_t commandDataLen);
|
||||
ReturnValue_t handleCycleCommand(bool oneCycleValue, const uint8_t *commandData,
|
||||
size_t commandDataLen);
|
||||
|
||||
bool goToNormalModeAtStartup = false;
|
||||
uint32_t transitionDelay;
|
||||
ReturnValue_t handleTmrcConfigCommand(DeviceCommandId_t deviceCommand, const uint8_t *commandData,
|
||||
size_t commandDataLen);
|
||||
|
||||
ReturnValue_t handleCycleCountConfigCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData,size_t commandDataLen);
|
||||
ReturnValue_t handleCycleCommand(bool oneCycleValue,
|
||||
const uint8_t *commandData, size_t commandDataLen);
|
||||
ReturnValue_t handleDataReadout(const uint8_t *packet);
|
||||
|
||||
ReturnValue_t handleTmrcConfigCommand(DeviceCommandId_t deviceCommand,
|
||||
const uint8_t *commandData,size_t commandDataLen);
|
||||
|
||||
ReturnValue_t handleDataReadout(const uint8_t* packet);
|
||||
#if FSFW_HAL_RM3100_MGM_DEBUG == 1
|
||||
PeriodicOperationDivider* debugDivider;
|
||||
#endif
|
||||
bool periodicPrintout = false;
|
||||
PeriodicOperationDivider debugDivider = PeriodicOperationDivider(3);
|
||||
};
|
||||
|
||||
#endif /* MISSION_DEVICEHANDLING_MGMRM3100HANDLER_H_ */
|
||||
|
@ -3,6 +3,7 @@
|
||||
|
||||
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
|
||||
#include <fsfw/devicehandlers/DeviceHandlerIF.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace L3GD20H {
|
||||
@ -36,8 +37,8 @@ static constexpr uint8_t SET_Z_ENABLE = 1 << 2;
|
||||
static constexpr uint8_t SET_X_ENABLE = 1 << 1;
|
||||
static constexpr uint8_t SET_Y_ENABLE = 1;
|
||||
|
||||
static constexpr uint8_t CTRL_REG_1_VAL = SET_POWER_NORMAL_MODE | SET_Z_ENABLE |
|
||||
SET_Y_ENABLE | SET_X_ENABLE;
|
||||
static constexpr uint8_t CTRL_REG_1_VAL =
|
||||
SET_POWER_NORMAL_MODE | SET_Z_ENABLE | SET_Y_ENABLE | SET_X_ENABLE;
|
||||
|
||||
/* Register 2 */
|
||||
static constexpr uint8_t EXTERNAL_EDGE_ENB = 1 << 7;
|
||||
@ -104,40 +105,29 @@ static constexpr DeviceCommandId_t READ_CTRL_REGS = 2;
|
||||
|
||||
static constexpr uint32_t GYRO_DATASET_ID = READ_REGS;
|
||||
|
||||
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
|
||||
|
||||
class GyroPrimaryDataset : public StaticLocalDataSet<5> {
|
||||
public:
|
||||
/** Constructor for data users like controllers */
|
||||
GyroPrimaryDataset(object_id_t mgmId)
|
||||
: StaticLocalDataSet(sid_t(mgmId, L3GD20H::GYRO_DATASET_ID)) {
|
||||
setAllVariablesReadOnly();
|
||||
}
|
||||
|
||||
/* 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> 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> temperature = lp_var_t<float>(sid.objectId, L3GD20H::TEMPERATURE, this);
|
||||
|
||||
private:
|
||||
friend class GyroHandlerL3GD20H;
|
||||
/** Constructor for the data creator */
|
||||
GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner)
|
||||
: StaticLocalDataSet(hkOwner, L3GD20H::GYRO_DATASET_ID) {}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
class GyroPrimaryDataset: public StaticLocalDataSet<5> {
|
||||
public:
|
||||
|
||||
/** Constructor for data users like controllers */
|
||||
GyroPrimaryDataset(object_id_t mgmId):
|
||||
StaticLocalDataSet(sid_t(mgmId, L3GD20H::GYRO_DATASET_ID)) {
|
||||
setAllVariablesReadOnly();
|
||||
}
|
||||
|
||||
/* 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> 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> temperature = lp_var_t<float>(sid.objectId,
|
||||
L3GD20H::TEMPERATURE, this);
|
||||
private:
|
||||
|
||||
friend class GyroHandlerL3GD20H;
|
||||
/** Constructor for the data creator */
|
||||
GyroPrimaryDataset(HasLocalDataPoolIF* hkOwner):
|
||||
StaticLocalDataSet(hkOwner, L3GD20H::GYRO_DATASET_ID) {}
|
||||
};
|
||||
|
||||
|
||||
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_GYROL3GD20DEFINITIONS_H_ */
|
||||
|
@ -1,26 +1,18 @@
|
||||
#ifndef MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_
|
||||
#define MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_
|
||||
|
||||
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
|
||||
#include <fsfw/datapoollocal/LocalPoolVariable.h>
|
||||
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
|
||||
#include <fsfw/devicehandlers/DeviceHandlerIF.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace MGMLIS3MDL {
|
||||
|
||||
enum Set {
|
||||
ON, OFF
|
||||
};
|
||||
enum OpMode {
|
||||
LOW, MEDIUM, HIGH, ULTRA
|
||||
};
|
||||
enum Set { ON, OFF };
|
||||
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 };
|
||||
|
||||
/* Actually 15, we just round up a bit */
|
||||
static constexpr size_t MAX_BUFFER_SIZE = 16;
|
||||
@ -54,7 +46,7 @@ static const uint8_t SETUP_REPLY_LEN = 6;
|
||||
/*------------------------------------------------------------------------*/
|
||||
/* Register adress returns identifier of device with default 0b00111101 */
|
||||
static const uint8_t IDENTIFY_DEVICE_REG_ADDR = 0b00001111;
|
||||
static const uint8_t DEVICE_ID = 0b00111101; // Identifier for Device
|
||||
static const uint8_t DEVICE_ID = 0b00111101; // Identifier for Device
|
||||
|
||||
/* Register adress to access register 1 */
|
||||
static const uint8_t CTRL_REG1 = 0b00100000;
|
||||
@ -105,74 +97,67 @@ static const uint8_t RW_BIT = 7;
|
||||
static const uint8_t MS_BIT = 6;
|
||||
|
||||
/* CTRL_REG1 bits */
|
||||
static const uint8_t ST = 0; // Self test enable bit, enabled = 1
|
||||
static const uint8_t ST = 0; // Self test enable bit, enabled = 1
|
||||
// Enable rates higher than 80 Hz enabled = 1
|
||||
static const uint8_t FAST_ODR = 1;
|
||||
static const uint8_t DO0 = 2; // Output data rate bit 2
|
||||
static const uint8_t DO1 = 3; // Output data rate bit 3
|
||||
static const uint8_t DO2 = 4; // Output data rate bit 4
|
||||
static const uint8_t OM0 = 5; // XY operating mode bit 5
|
||||
static const uint8_t OM1 = 6; // XY operating mode bit 6
|
||||
static const uint8_t TEMP_EN = 7; // Temperature sensor enable enabled = 1
|
||||
static const uint8_t CTRL_REG1_DEFAULT = (1 << TEMP_EN) | (1 << OM1) |
|
||||
(1 << DO0) | (1 << DO1) | (1 << DO2);
|
||||
static const uint8_t DO0 = 2; // Output data rate bit 2
|
||||
static const uint8_t DO1 = 3; // Output data rate bit 3
|
||||
static const uint8_t DO2 = 4; // Output data rate bit 4
|
||||
static const uint8_t OM0 = 5; // XY operating mode bit 5
|
||||
static const uint8_t OM1 = 6; // XY operating mode bit 6
|
||||
static const uint8_t TEMP_EN = 7; // Temperature sensor enable enabled = 1
|
||||
static const uint8_t CTRL_REG1_DEFAULT =
|
||||
(1 << TEMP_EN) | (1 << OM1) | (1 << DO0) | (1 << DO1) | (1 << DO2);
|
||||
|
||||
/* CTRL_REG2 bits */
|
||||
//reset configuration registers and user registers
|
||||
// reset configuration registers and user registers
|
||||
static const uint8_t SOFT_RST = 2;
|
||||
static const uint8_t REBOOT = 3; //reboot memory content
|
||||
static const uint8_t FSO = 5; //full-scale selection bit 5
|
||||
static const uint8_t FS1 = 6; //full-scale selection bit 6
|
||||
static const uint8_t REBOOT = 3; // reboot memory content
|
||||
static const uint8_t FSO = 5; // full-scale selection bit 5
|
||||
static const uint8_t FS1 = 6; // full-scale selection bit 6
|
||||
static const uint8_t CTRL_REG2_DEFAULT = 0;
|
||||
|
||||
/* CTRL_REG3 bits */
|
||||
static const uint8_t MD0 = 0; //Operating mode bit 0
|
||||
static const uint8_t MD1 = 1; //Operating mode bit 1
|
||||
//SPI serial interface mode selection enabled = 3-wire-mode
|
||||
static const uint8_t MD0 = 0; // Operating mode bit 0
|
||||
static const uint8_t MD1 = 1; // Operating mode bit 1
|
||||
// SPI serial interface mode selection enabled = 3-wire-mode
|
||||
static const uint8_t SIM = 2;
|
||||
static const uint8_t LP = 5; //low-power mode
|
||||
static const uint8_t LP = 5; // low-power mode
|
||||
static const uint8_t CTRL_REG3_DEFAULT = 0;
|
||||
|
||||
/* CTRL_REG4 bits */
|
||||
//big/little endian data selection enabled = MSb at lower adress
|
||||
// big/little endian data selection enabled = MSb at lower adress
|
||||
static const uint8_t BLE = 1;
|
||||
static const uint8_t OMZ0 = 2; //Z operating mode bit 2
|
||||
static const uint8_t OMZ1 = 3; //Z operating mode bit 3
|
||||
static const uint8_t OMZ0 = 2; // Z operating mode bit 2
|
||||
static const uint8_t OMZ1 = 3; // Z operating mode bit 3
|
||||
static const uint8_t CTRL_REG4_DEFAULT = (1 << OMZ1);
|
||||
|
||||
/* CTRL_REG5 bits */
|
||||
static const uint8_t BDU = 6; //Block data update
|
||||
static const uint8_t FAST_READ = 7; //Fast read enabled = 1
|
||||
static const uint8_t BDU = 6; // Block data update
|
||||
static const uint8_t FAST_READ = 7; // Fast read enabled = 1
|
||||
static const uint8_t CTRL_REG5_DEFAULT = 0;
|
||||
|
||||
static const uint32_t MGM_DATA_SET_ID = READ_CONFIG_AND_DATA;
|
||||
|
||||
enum MgmPoolIds: lp_id_t {
|
||||
FIELD_STRENGTH_X,
|
||||
FIELD_STRENGTH_Y,
|
||||
FIELD_STRENGTH_Z,
|
||||
TEMPERATURE_CELCIUS
|
||||
enum MgmPoolIds : lp_id_t {
|
||||
FIELD_STRENGTH_X,
|
||||
FIELD_STRENGTH_Y,
|
||||
FIELD_STRENGTH_Z,
|
||||
TEMPERATURE_CELCIUS
|
||||
};
|
||||
|
||||
class MgmPrimaryDataset: public StaticLocalDataSet<4> {
|
||||
public:
|
||||
MgmPrimaryDataset(HasLocalDataPoolIF* hkOwner):
|
||||
StaticLocalDataSet(hkOwner, MGM_DATA_SET_ID) {}
|
||||
class MgmPrimaryDataset : public StaticLocalDataSet<4> {
|
||||
public:
|
||||
MgmPrimaryDataset(HasLocalDataPoolIF* hkOwner) : StaticLocalDataSet(hkOwner, MGM_DATA_SET_ID) {}
|
||||
|
||||
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);
|
||||
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_var_t<float> temperature = lp_var_t<float>(sid.objectId,
|
||||
TEMPERATURE_CELCIUS, this);
|
||||
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_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Z, this);
|
||||
lp_var_t<float> temperature = lp_var_t<float>(sid.objectId, TEMPERATURE_CELCIUS, this);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
} // namespace MGMLIS3MDL
|
||||
|
||||
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMLIS3HANDLERDEFS_H_ */
|
||||
|
@ -1,10 +1,11 @@
|
||||
#ifndef MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_
|
||||
#define MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_
|
||||
|
||||
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
|
||||
#include <fsfw/datapoollocal/LocalPoolVariable.h>
|
||||
#include <fsfw/datapoollocal/StaticLocalDataSet.h>
|
||||
#include <fsfw/devicehandlers/DeviceHandlerIF.h>
|
||||
#include <fsfw/serialize/SerialLinkedListAdapter.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace RM3100 {
|
||||
@ -24,8 +25,8 @@ static constexpr uint8_t SET_CMM_DRDM = 1 << 2;
|
||||
static constexpr uint8_t SET_CMM_START = 1;
|
||||
static constexpr uint8_t CMM_REGISTER = 0x01;
|
||||
|
||||
static constexpr uint8_t CMM_VALUE = SET_CMM_CMZ | SET_CMM_CMY | SET_CMM_CMX |
|
||||
SET_CMM_DRDM | SET_CMM_START;
|
||||
static constexpr uint8_t CMM_VALUE =
|
||||
SET_CMM_CMZ | SET_CMM_CMY | SET_CMM_CMX | SET_CMM_DRDM | SET_CMM_START;
|
||||
|
||||
/*----------------------------------------------------------------------------*/
|
||||
/* Cycle count register */
|
||||
@ -33,8 +34,7 @@ static constexpr uint8_t CMM_VALUE = SET_CMM_CMZ | SET_CMM_CMY | SET_CMM_CMX |
|
||||
// Default value (200)
|
||||
static constexpr uint8_t CYCLE_COUNT_VALUE = 0xC8;
|
||||
|
||||
static constexpr float DEFAULT_GAIN = static_cast<float>(CYCLE_COUNT_VALUE) /
|
||||
100 * 38;
|
||||
static constexpr float DEFAULT_GAIN = static_cast<float>(CYCLE_COUNT_VALUE) / 100 * 38;
|
||||
static constexpr uint8_t CYCLE_COUNT_START_REGISTER = 0x04;
|
||||
|
||||
/*----------------------------------------------------------------------------*/
|
||||
@ -67,66 +67,58 @@ static constexpr DeviceCommandId_t READ_TMRC = 4;
|
||||
static constexpr DeviceCommandId_t CONFIGURE_CYCLE_COUNT = 5;
|
||||
static constexpr DeviceCommandId_t READ_CYCLE_COUNT = 6;
|
||||
|
||||
class CycleCountCommand: public SerialLinkedListAdapter<SerializeIF> {
|
||||
public:
|
||||
CycleCountCommand(bool oneCycleCount = true): oneCycleCount(oneCycleCount) {
|
||||
setLinks(oneCycleCount);
|
||||
}
|
||||
class CycleCountCommand : public SerialLinkedListAdapter<SerializeIF> {
|
||||
public:
|
||||
CycleCountCommand(bool oneCycleCount = true) : oneCycleCount(oneCycleCount) {
|
||||
setLinks(oneCycleCount);
|
||||
}
|
||||
|
||||
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
|
||||
Endianness streamEndianness) override {
|
||||
ReturnValue_t result = SerialLinkedListAdapter::deSerialize(buffer,
|
||||
size, streamEndianness);
|
||||
if(oneCycleCount) {
|
||||
cycleCountY = cycleCountX;
|
||||
cycleCountZ = cycleCountX;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
ReturnValue_t deSerialize(const uint8_t** buffer, size_t* size,
|
||||
Endianness streamEndianness) override {
|
||||
ReturnValue_t result = SerialLinkedListAdapter::deSerialize(buffer, size, streamEndianness);
|
||||
if (oneCycleCount) {
|
||||
cycleCountY = cycleCountX;
|
||||
cycleCountZ = cycleCountX;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
SerializeElement<uint16_t> cycleCountX;
|
||||
SerializeElement<uint16_t> cycleCountY;
|
||||
SerializeElement<uint16_t> cycleCountZ;
|
||||
SerializeElement<uint16_t> cycleCountX;
|
||||
SerializeElement<uint16_t> cycleCountY;
|
||||
SerializeElement<uint16_t> cycleCountZ;
|
||||
|
||||
private:
|
||||
void setLinks(bool oneCycleCount) {
|
||||
setStart(&cycleCountX);
|
||||
if(not oneCycleCount) {
|
||||
cycleCountX.setNext(&cycleCountY);
|
||||
cycleCountY.setNext(&cycleCountZ);
|
||||
}
|
||||
}
|
||||
private:
|
||||
void setLinks(bool oneCycleCount) {
|
||||
setStart(&cycleCountX);
|
||||
if (not oneCycleCount) {
|
||||
cycleCountX.setNext(&cycleCountY);
|
||||
cycleCountY.setNext(&cycleCountZ);
|
||||
}
|
||||
}
|
||||
|
||||
bool oneCycleCount;
|
||||
bool oneCycleCount;
|
||||
};
|
||||
|
||||
static constexpr uint32_t MGM_DATASET_ID = READ_DATA;
|
||||
|
||||
enum MgmPoolIds: lp_id_t {
|
||||
FIELD_STRENGTH_X,
|
||||
FIELD_STRENGTH_Y,
|
||||
FIELD_STRENGTH_Z,
|
||||
enum MgmPoolIds : lp_id_t {
|
||||
FIELD_STRENGTH_X,
|
||||
FIELD_STRENGTH_Y,
|
||||
FIELD_STRENGTH_Z,
|
||||
};
|
||||
|
||||
class Rm3100PrimaryDataset: public StaticLocalDataSet<3> {
|
||||
public:
|
||||
Rm3100PrimaryDataset(HasLocalDataPoolIF* hkOwner):
|
||||
StaticLocalDataSet(hkOwner, MGM_DATASET_ID) {}
|
||||
class Rm3100PrimaryDataset : public StaticLocalDataSet<3> {
|
||||
public:
|
||||
Rm3100PrimaryDataset(HasLocalDataPoolIF* hkOwner) : StaticLocalDataSet(hkOwner, MGM_DATASET_ID) {}
|
||||
|
||||
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.
|
||||
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_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId,
|
||||
FIELD_STRENGTH_Z, this);
|
||||
// Field strengths in micro Tesla.
|
||||
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_var_t<float> fieldStrengthZ = lp_var_t<float>(sid.objectId, FIELD_STRENGTH_Z, this);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
} // namespace RM3100
|
||||
|
||||
#endif /* MISSION_DEVICES_DEVICEDEFINITIONS_MGMHANDLERRM3100DEFINITIONS_H_ */
|
||||
|
@ -4,10 +4,17 @@ endif()
|
||||
|
||||
target_sources(${LIB_FSFW_NAME} PRIVATE
|
||||
UnixFileGuard.cpp
|
||||
CommandExecutor.cpp
|
||||
utility.cpp
|
||||
)
|
||||
|
||||
add_subdirectory(gpio)
|
||||
add_subdirectory(spi)
|
||||
add_subdirectory(i2c)
|
||||
add_subdirectory(uart)
|
||||
if(FSFW_HAL_LINUX_ADD_PERIPHERAL_DRIVERS)
|
||||
if(FSFW_HAL_LINUX_ADD_LIBGPIOD)
|
||||
add_subdirectory(gpio)
|
||||
endif()
|
||||
add_subdirectory(spi)
|
||||
add_subdirectory(i2c)
|
||||
add_subdirectory(uart)
|
||||
endif()
|
||||
|
||||
add_subdirectory(uio)
|
||||
|
207
hal/src/fsfw_hal/linux/CommandExecutor.cpp
Normal file
207
hal/src/fsfw_hal/linux/CommandExecutor.cpp
Normal file
@ -0,0 +1,207 @@
|
||||
#include "CommandExecutor.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "fsfw/container/DynamicFIFO.h"
|
||||
#include "fsfw/container/SimpleRingBuffer.h"
|
||||
#include "fsfw/serviceinterface.h"
|
||||
|
||||
CommandExecutor::CommandExecutor(const size_t maxSize) : readVec(maxSize) {
|
||||
waiter.events = POLLIN;
|
||||
}
|
||||
|
||||
ReturnValue_t CommandExecutor::load(std::string command, bool blocking, bool printOutput) {
|
||||
if (state == States::PENDING) {
|
||||
return COMMAND_PENDING;
|
||||
}
|
||||
|
||||
currentCmd = command;
|
||||
this->blocking = blocking;
|
||||
this->printOutput = printOutput;
|
||||
if (state == States::IDLE) {
|
||||
state = States::COMMAND_LOADED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t CommandExecutor::execute() {
|
||||
if (state == States::IDLE) {
|
||||
return NO_COMMAND_LOADED_OR_PENDING;
|
||||
} else if (state == States::PENDING) {
|
||||
return COMMAND_PENDING;
|
||||
}
|
||||
currentCmdFile = popen(currentCmd.c_str(), "r");
|
||||
if (currentCmdFile == nullptr) {
|
||||
lastError = errno;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
if (blocking) {
|
||||
ReturnValue_t result = executeBlocking();
|
||||
state = States::IDLE;
|
||||
return result;
|
||||
} else {
|
||||
currentFd = fileno(currentCmdFile);
|
||||
waiter.fd = currentFd;
|
||||
}
|
||||
state = States::PENDING;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t CommandExecutor::close() {
|
||||
if (state == States::PENDING) {
|
||||
// Attempt to close process, irrespective of if it is running or not
|
||||
if (currentCmdFile != nullptr) {
|
||||
pclose(currentCmdFile);
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void CommandExecutor::printLastError(std::string funcName) const {
|
||||
if (lastError != 0) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << funcName << " pclose failed with code " << lastError << ": "
|
||||
<< strerror(lastError) << std::endl;
|
||||
#else
|
||||
sif::printError("%s pclose failed with code %d: %s\n", funcName, lastError,
|
||||
strerror(lastError));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void CommandExecutor::setRingBuffer(SimpleRingBuffer* ringBuffer,
|
||||
DynamicFIFO<uint16_t>* sizesFifo) {
|
||||
this->ringBuffer = ringBuffer;
|
||||
this->sizesFifo = sizesFifo;
|
||||
}
|
||||
|
||||
ReturnValue_t CommandExecutor::check(bool& replyReceived) {
|
||||
if (blocking) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
switch (state) {
|
||||
case (States::IDLE):
|
||||
case (States::COMMAND_LOADED): {
|
||||
return NO_COMMAND_LOADED_OR_PENDING;
|
||||
}
|
||||
case (States::PENDING): {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int result = poll(&waiter, 1, 0);
|
||||
switch (result) {
|
||||
case (0): {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
break;
|
||||
}
|
||||
case (1): {
|
||||
if (waiter.revents & POLLIN) {
|
||||
ssize_t readBytes = read(currentFd, readVec.data(), readVec.size());
|
||||
if (readBytes == 0) {
|
||||
// Should not happen
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "CommandExecutor::check: No bytes read "
|
||||
"after poll event.."
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("CommandExecutor::check: No bytes read after poll event..\n");
|
||||
#endif
|
||||
break;
|
||||
} else if (readBytes > 0) {
|
||||
replyReceived = true;
|
||||
if (printOutput) {
|
||||
// It is assumed the command output is line terminated
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << currentCmd << " | " << readVec.data();
|
||||
#else
|
||||
sif::printInfo("%s | %s", currentCmd, readVec.data());
|
||||
#endif
|
||||
}
|
||||
if (ringBuffer != nullptr) {
|
||||
ringBuffer->writeData(reinterpret_cast<const uint8_t*>(readVec.data()), readBytes);
|
||||
}
|
||||
if (sizesFifo != nullptr) {
|
||||
if (not sizesFifo->full()) {
|
||||
sizesFifo->insert(readBytes);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Should also not happen
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "CommandExecutor::check: Error " << errno << ": " << strerror(errno)
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("CommandExecutor::check: Error %d: %s\n", errno, strerror(errno));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
if (waiter.revents & POLLERR) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "CommandExecuter::check: Poll error" << std::endl;
|
||||
#else
|
||||
sif::printWarning("CommandExecuter::check: Poll error\n");
|
||||
#endif
|
||||
return COMMAND_ERROR;
|
||||
}
|
||||
if (waiter.revents & POLLHUP) {
|
||||
result = pclose(currentCmdFile);
|
||||
ReturnValue_t retval = EXECUTION_FINISHED;
|
||||
if (result != 0) {
|
||||
lastError = result;
|
||||
retval = HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
state = States::IDLE;
|
||||
currentCmdFile = nullptr;
|
||||
currentFd = 0;
|
||||
return retval;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void CommandExecutor::reset() {
|
||||
CommandExecutor::close();
|
||||
currentCmdFile = nullptr;
|
||||
currentFd = 0;
|
||||
state = States::IDLE;
|
||||
}
|
||||
|
||||
int CommandExecutor::getLastError() const {
|
||||
// See:
|
||||
// https://stackoverflow.com/questions/808541/any-benefit-in-using-wexitstatus-macro-in-c-over-division-by-256-on-exit-statu
|
||||
return WEXITSTATUS(this->lastError);
|
||||
}
|
||||
|
||||
CommandExecutor::States CommandExecutor::getCurrentState() const { return state; }
|
||||
|
||||
ReturnValue_t CommandExecutor::executeBlocking() {
|
||||
while (fgets(readVec.data(), readVec.size(), currentCmdFile) != nullptr) {
|
||||
std::string output(readVec.data());
|
||||
if (printOutput) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << currentCmd << " | " << output;
|
||||
#else
|
||||
sif::printInfo("%s | %s", currentCmd, output);
|
||||
#endif
|
||||
}
|
||||
if (ringBuffer != nullptr) {
|
||||
ringBuffer->writeData(reinterpret_cast<const uint8_t*>(output.data()), output.size());
|
||||
}
|
||||
if (sizesFifo != nullptr) {
|
||||
if (not sizesFifo->full()) {
|
||||
sizesFifo->insert(output.size());
|
||||
}
|
||||
}
|
||||
}
|
||||
int result = pclose(currentCmdFile);
|
||||
if (result != 0) {
|
||||
lastError = result;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
129
hal/src/fsfw_hal/linux/CommandExecutor.h
Normal file
129
hal/src/fsfw_hal/linux/CommandExecutor.h
Normal file
@ -0,0 +1,129 @@
|
||||
#ifndef FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_
|
||||
#define FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_
|
||||
|
||||
#include <poll.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "fsfw/returnvalues/FwClassIds.h"
|
||||
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
|
||||
|
||||
class SimpleRingBuffer;
|
||||
template <typename T>
|
||||
class DynamicFIFO;
|
||||
|
||||
/**
|
||||
* @brief Helper class to execute shell commands in blocking and non-blocking mode
|
||||
* @details
|
||||
* This class is able to execute processes by using the Linux popen call. It also has the
|
||||
* capability of writing the read output of a process into a provided ring buffer.
|
||||
*
|
||||
* The executor works by first loading the command which should be executed and specifying
|
||||
* whether it should be executed blocking or non-blocking. After that, execution can be started
|
||||
* with the execute command. In blocking mode, the execute command will block until the command
|
||||
* has finished
|
||||
*/
|
||||
class CommandExecutor {
|
||||
public:
|
||||
enum class States { IDLE, COMMAND_LOADED, PENDING };
|
||||
|
||||
static constexpr uint8_t CLASS_ID = CLASS_ID::LINUX_OSAL;
|
||||
|
||||
//! [EXPORT] : [COMMENT] Execution of the current command has finished
|
||||
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
|
||||
//! to load another command but a command is still pending
|
||||
static constexpr ReturnValue_t COMMAND_PENDING = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 1);
|
||||
//! [EXPORT] : [COMMENT] Some bytes have been read from the executing process
|
||||
static constexpr ReturnValue_t BYTES_READ = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 2);
|
||||
//! [EXPORT] : [COMMENT] Command execution failed
|
||||
static constexpr ReturnValue_t COMMAND_ERROR = HasReturnvaluesIF::makeReturnCode(CLASS_ID, 3);
|
||||
//! [EXPORT] : [COMMENT]
|
||||
static constexpr ReturnValue_t NO_COMMAND_LOADED_OR_PENDING =
|
||||
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
|
||||
* executed process.
|
||||
* @param maxSize
|
||||
*/
|
||||
CommandExecutor(const size_t maxSize);
|
||||
|
||||
/**
|
||||
* Load a new command which should be executed
|
||||
* @param command
|
||||
* @param blocking
|
||||
* @param printOutput
|
||||
* @return
|
||||
*/
|
||||
ReturnValue_t load(std::string command, bool blocking, bool printOutput = true);
|
||||
/**
|
||||
* Execute the loaded command.
|
||||
* @return
|
||||
* - 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
|
||||
* getLastError
|
||||
* - In non-blocking mode, this call will start
|
||||
* the execution and then return RETURN_OK
|
||||
*/
|
||||
ReturnValue_t execute();
|
||||
/**
|
||||
* Only used in non-blocking mode. Checks the currently running command.
|
||||
* @param bytesRead Will be set to the number of bytes read, if bytes have been read
|
||||
* @return
|
||||
* - BYTES_READ if bytes have been read from the executing process. It is recommended to call
|
||||
* check again after this
|
||||
* - RETURN_OK execution is pending, but no bytes have been read from the executing process
|
||||
* - RETURN_FAILED if execution has failed, error value can be accessed using getLastError
|
||||
* - EXECUTION_FINISHED if the process was executed successfully
|
||||
* - NO_COMMAND_LOADED_OR_PENDING self-explanatory
|
||||
* - COMMAND_ERROR internal poll error
|
||||
*/
|
||||
ReturnValue_t check(bool& replyReceived);
|
||||
/**
|
||||
* Abort the current command. Should normally not be necessary, check can be used to find
|
||||
* out whether command execution was successful
|
||||
* @return RETURN_OK
|
||||
*/
|
||||
ReturnValue_t close();
|
||||
|
||||
States getCurrentState() const;
|
||||
int getLastError() const;
|
||||
void printLastError(std::string funcName) const;
|
||||
|
||||
/**
|
||||
* Assign a ring buffer and a FIFO which will be filled by the executor with the output
|
||||
* read from the started process
|
||||
* @param ringBuffer
|
||||
* @param sizesFifo
|
||||
*/
|
||||
void setRingBuffer(SimpleRingBuffer* ringBuffer, DynamicFIFO<uint16_t>* sizesFifo);
|
||||
|
||||
/**
|
||||
* Reset the executor. This calls close internally and then reset the state machine so new
|
||||
* commands can be loaded and executed
|
||||
*/
|
||||
void reset();
|
||||
|
||||
private:
|
||||
std::string currentCmd;
|
||||
bool blocking = true;
|
||||
FILE* currentCmdFile = nullptr;
|
||||
int currentFd = 0;
|
||||
bool printOutput = true;
|
||||
std::vector<char> readVec;
|
||||
struct pollfd waiter {};
|
||||
SimpleRingBuffer* ringBuffer = nullptr;
|
||||
DynamicFIFO<uint16_t>* sizesFifo = nullptr;
|
||||
|
||||
States state = States::IDLE;
|
||||
int lastError = 0;
|
||||
|
||||
ReturnValue_t executeBlocking();
|
||||
};
|
||||
|
||||
#endif /* FSFW_SRC_FSFW_OSAL_LINUX_COMMANDEXECUTOR_H_ */
|
@ -1,37 +1,36 @@
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw/serviceinterface.h"
|
||||
#include "fsfw_hal/linux/UnixFileGuard.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw/serviceinterface.h"
|
||||
|
||||
UnixFileGuard::UnixFileGuard(std::string device, int* fileDescriptor, int flags,
|
||||
std::string diagnosticPrefix):
|
||||
fileDescriptor(fileDescriptor) {
|
||||
if(fileDescriptor == nullptr) {
|
||||
return;
|
||||
}
|
||||
*fileDescriptor = open(device.c_str(), flags);
|
||||
if (*fileDescriptor < 0) {
|
||||
std::string diagnosticPrefix)
|
||||
: fileDescriptor(fileDescriptor) {
|
||||
if (fileDescriptor == nullptr) {
|
||||
return;
|
||||
}
|
||||
*fileDescriptor = open(device.c_str(), flags);
|
||||
if (*fileDescriptor < 0) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << diagnosticPrefix << ": Opening device failed with error code " <<
|
||||
errno << ": " << strerror(errno) << std::endl;
|
||||
sif::warning << diagnosticPrefix << ": Opening device failed with error code " << errno << ": "
|
||||
<< strerror(errno) << std::endl;
|
||||
#else
|
||||
sif::printWarning("%s: Opening device failed with error code %d: %s\n",
|
||||
diagnosticPrefix, errno, strerror(errno));
|
||||
sif::printWarning("%s: Opening device failed with error code %d: %s\n", diagnosticPrefix, errno,
|
||||
strerror(errno));
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
openStatus = OPEN_FILE_FAILED;
|
||||
}
|
||||
openStatus = OPEN_FILE_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
UnixFileGuard::~UnixFileGuard() {
|
||||
if(fileDescriptor != nullptr) {
|
||||
close(*fileDescriptor);
|
||||
}
|
||||
if (fileDescriptor != nullptr) {
|
||||
close(*fileDescriptor);
|
||||
}
|
||||
}
|
||||
|
||||
ReturnValue_t UnixFileGuard::getOpenResult() const {
|
||||
return openStatus;
|
||||
}
|
||||
ReturnValue_t UnixFileGuard::getOpenResult() const { return openStatus; }
|
||||
|
@ -1,33 +1,30 @@
|
||||
#ifndef LINUX_UTILITY_UNIXFILEGUARD_H_
|
||||
#define LINUX_UTILITY_UNIXFILEGUARD_H_
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
|
||||
class UnixFileGuard {
|
||||
public:
|
||||
static constexpr int READ_WRITE_FLAG = O_RDWR;
|
||||
static constexpr int READ_ONLY_FLAG = O_RDONLY;
|
||||
static constexpr int NON_BLOCKING_IO_FLAG = O_NONBLOCK;
|
||||
public:
|
||||
static constexpr int READ_WRITE_FLAG = O_RDWR;
|
||||
static constexpr int READ_ONLY_FLAG = O_RDONLY;
|
||||
static constexpr int NON_BLOCKING_IO_FLAG = O_NONBLOCK;
|
||||
|
||||
static constexpr ReturnValue_t OPEN_FILE_FAILED = 1;
|
||||
static constexpr ReturnValue_t OPEN_FILE_FAILED = 1;
|
||||
|
||||
UnixFileGuard(std::string device, int* fileDescriptor, int flags,
|
||||
std::string diagnosticPrefix = "");
|
||||
UnixFileGuard(std::string device, int* fileDescriptor, int flags,
|
||||
std::string diagnosticPrefix = "");
|
||||
|
||||
virtual~ UnixFileGuard();
|
||||
virtual ~UnixFileGuard();
|
||||
|
||||
ReturnValue_t getOpenResult() const;
|
||||
private:
|
||||
int* fileDescriptor = nullptr;
|
||||
ReturnValue_t openStatus = HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t getOpenResult() const;
|
||||
|
||||
private:
|
||||
int* fileDescriptor = nullptr;
|
||||
ReturnValue_t openStatus = HasReturnvaluesIF::RETURN_OK;
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif /* LINUX_UTILITY_UNIXFILEGUARD_H_ */
|
||||
|
@ -1,12 +1,16 @@
|
||||
target_sources(${LIB_FSFW_NAME} PRIVATE
|
||||
LinuxLibgpioIF.cpp
|
||||
)
|
||||
|
||||
# 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 REQUIRED)
|
||||
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()
|
||||
|
||||
target_link_libraries(${LIB_FSFW_NAME} PRIVATE
|
||||
${LIB_GPIO}
|
||||
)
|
@ -1,442 +1,447 @@
|
||||
#include "LinuxLibgpioIF.h"
|
||||
|
||||
#include "fsfw_hal/common/gpio/gpioDefinitions.h"
|
||||
#include "fsfw_hal/common/gpio/GpioCookie.h"
|
||||
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
#include <gpiod.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <utility>
|
||||
#include <unistd.h>
|
||||
#include <gpiod.h>
|
||||
|
||||
LinuxLibgpioIF::LinuxLibgpioIF(object_id_t objectId) : SystemObject(objectId) {
|
||||
}
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
#include "fsfw_hal/common/gpio/GpioCookie.h"
|
||||
#include "fsfw_hal/common/gpio/gpioDefinitions.h"
|
||||
|
||||
LinuxLibgpioIF::LinuxLibgpioIF(object_id_t objectId) : SystemObject(objectId) {}
|
||||
|
||||
LinuxLibgpioIF::~LinuxLibgpioIF() {
|
||||
for(auto& config: gpioMap) {
|
||||
delete(config.second);
|
||||
}
|
||||
for (auto& config : gpioMap) {
|
||||
delete (config.second);
|
||||
}
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::addGpios(GpioCookie* gpioCookie) {
|
||||
ReturnValue_t result;
|
||||
if(gpioCookie == nullptr) {
|
||||
sif::error << "LinuxLibgpioIF::addGpios: Invalid cookie" << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
ReturnValue_t result;
|
||||
if (gpioCookie == nullptr) {
|
||||
sif::error << "LinuxLibgpioIF::addGpios: Invalid cookie" << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
|
||||
GpioMap mapToAdd = gpioCookie->getGpioMap();
|
||||
GpioMap mapToAdd = gpioCookie->getGpioMap();
|
||||
|
||||
/* Check whether this ID already exists in the map and remove duplicates */
|
||||
result = checkForConflicts(mapToAdd);
|
||||
if (result != RETURN_OK){
|
||||
return result;
|
||||
}
|
||||
/* Check whether this ID already exists in the map and remove duplicates */
|
||||
result = checkForConflicts(mapToAdd);
|
||||
if (result != RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
|
||||
result = configureGpios(mapToAdd);
|
||||
if (result != RETURN_OK) {
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
result = configureGpios(mapToAdd);
|
||||
if (result != RETURN_OK) {
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
|
||||
/* Register new GPIOs in gpioMap */
|
||||
gpioMap.insert(mapToAdd.begin(), mapToAdd.end());
|
||||
/* Register new GPIOs in gpioMap */
|
||||
gpioMap.insert(mapToAdd.begin(), mapToAdd.end());
|
||||
|
||||
return RETURN_OK;
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::configureGpios(GpioMap& mapToAdd) {
|
||||
for(auto& gpioConfig: mapToAdd) {
|
||||
auto& gpioType = gpioConfig.second->gpioType;
|
||||
switch(gpioType) {
|
||||
case(gpio::GpioTypes::NONE): {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
for (auto& gpioConfig : mapToAdd) {
|
||||
auto& gpioType = gpioConfig.second->gpioType;
|
||||
switch (gpioType) {
|
||||
case (gpio::GpioTypes::NONE): {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_CHIP): {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularByChip*>(gpioConfig.second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP): {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularByChip*>(gpioConfig.second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
configureGpioByChip(gpioConfig.first, *regularGpio);
|
||||
break;
|
||||
configureGpioByChip(gpioConfig.first, *regularGpio);
|
||||
break;
|
||||
}
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_LABEL): {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularByLabel*>(gpioConfig.second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL):{
|
||||
auto regularGpio = dynamic_cast<GpiodRegularByLabel*>(gpioConfig.second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
configureGpioByLabel(gpioConfig.first, *regularGpio);
|
||||
break;
|
||||
}
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME):{
|
||||
auto regularGpio = dynamic_cast<GpiodRegularByLineName*>(gpioConfig.second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
configureGpioByLineName(gpioConfig.first, *regularGpio);
|
||||
break;
|
||||
}
|
||||
case(gpio::GpioTypes::CALLBACK): {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioConfig.second);
|
||||
if(gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
gpioCallback->callback(gpioConfig.first, gpio::GpioOperation::WRITE,
|
||||
gpioCallback->initValue, gpioCallback->callbackArgs);
|
||||
configureGpioByLabel(gpioConfig.first, *regularGpio);
|
||||
break;
|
||||
}
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME): {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularByLineName*>(gpioConfig.second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
configureGpioByLineName(gpioConfig.first, *regularGpio);
|
||||
break;
|
||||
}
|
||||
case (gpio::GpioTypes::CALLBACK): {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioConfig.second);
|
||||
if (gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
gpioCallback->callback(gpioConfig.first, gpio::GpioOperation::WRITE,
|
||||
gpioCallback->initValue, gpioCallback->callbackArgs);
|
||||
}
|
||||
}
|
||||
return RETURN_OK;
|
||||
}
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::configureGpioByLabel(gpioId_t gpioId,
|
||||
GpiodRegularByLabel &gpioByLabel) {
|
||||
std::string& label = gpioByLabel.label;
|
||||
struct gpiod_chip* chip = gpiod_chip_open_by_label(label.c_str());
|
||||
if (chip == nullptr) {
|
||||
sif::warning << "LinuxLibgpioIF::configureGpioByLabel: Failed to open gpio from gpio "
|
||||
<< "group with label " << label << ". Gpio ID: " << gpioId << std::endl;
|
||||
return RETURN_FAILED;
|
||||
|
||||
}
|
||||
std::string failOutput = "label: " + label;
|
||||
return configureRegularGpio(gpioId, chip, gpioByLabel, failOutput);
|
||||
GpiodRegularByLabel& gpioByLabel) {
|
||||
std::string& label = gpioByLabel.label;
|
||||
struct gpiod_chip* chip = gpiod_chip_open_by_label(label.c_str());
|
||||
if (chip == nullptr) {
|
||||
sif::warning << "LinuxLibgpioIF::configureGpioByLabel: Failed to open gpio from gpio "
|
||||
<< "group with label " << label << ". Gpio ID: " << gpioId << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
std::string failOutput = "label: " + label;
|
||||
return configureRegularGpio(gpioId, chip, gpioByLabel, failOutput);
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::configureGpioByChip(gpioId_t gpioId,
|
||||
GpiodRegularByChip &gpioByChip) {
|
||||
std::string& chipname = gpioByChip.chipname;
|
||||
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname.c_str());
|
||||
if (chip == nullptr) {
|
||||
sif::warning << "LinuxLibgpioIF::configureGpioByChip: Failed to open chip "
|
||||
<< chipname << ". Gpio ID: " << gpioId << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
std::string failOutput = "chipname: " + chipname;
|
||||
return configureRegularGpio(gpioId, chip, gpioByChip, failOutput);
|
||||
ReturnValue_t LinuxLibgpioIF::configureGpioByChip(gpioId_t gpioId, GpiodRegularByChip& gpioByChip) {
|
||||
std::string& chipname = gpioByChip.chipname;
|
||||
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname.c_str());
|
||||
if (chip == nullptr) {
|
||||
sif::warning << "LinuxLibgpioIF::configureGpioByChip: Failed to open chip " << chipname
|
||||
<< ". Gpio ID: " << gpioId << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
std::string failOutput = "chipname: " + chipname;
|
||||
return configureRegularGpio(gpioId, chip, gpioByChip, failOutput);
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::configureGpioByLineName(gpioId_t gpioId,
|
||||
GpiodRegularByLineName &gpioByLineName) {
|
||||
std::string& lineName = gpioByLineName.lineName;
|
||||
char chipname[MAX_CHIPNAME_LENGTH];
|
||||
unsigned int lineOffset;
|
||||
GpiodRegularByLineName& gpioByLineName) {
|
||||
std::string& lineName = gpioByLineName.lineName;
|
||||
char chipname[MAX_CHIPNAME_LENGTH];
|
||||
unsigned int lineOffset;
|
||||
|
||||
int result = gpiod_ctxless_find_line(lineName.c_str(), chipname, MAX_CHIPNAME_LENGTH,
|
||||
&lineOffset);
|
||||
if (result != LINE_FOUND) {
|
||||
parseFindeLineResult(result, lineName);
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
int result =
|
||||
gpiod_ctxless_find_line(lineName.c_str(), chipname, MAX_CHIPNAME_LENGTH, &lineOffset);
|
||||
if (result != LINE_FOUND) {
|
||||
parseFindeLineResult(result, lineName);
|
||||
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);
|
||||
if (chip == nullptr) {
|
||||
sif::warning << "LinuxLibgpioIF::configureGpioByLineName: Failed to open chip "
|
||||
<< chipname << ". <Gpio ID: " << gpioId << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
std::string failOutput = "line name: " + lineName;
|
||||
return configureRegularGpio(gpioId, chip, gpioByLineName, failOutput);
|
||||
struct gpiod_chip* chip = gpiod_chip_open_by_name(chipname);
|
||||
if (chip == nullptr) {
|
||||
sif::warning << "LinuxLibgpioIF::configureGpioByLineName: Failed to open chip " << chipname
|
||||
<< ". <Gpio ID: " << gpioId << std::endl;
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
std::string failOutput = "line name: " + lineName;
|
||||
return configureRegularGpio(gpioId, chip, gpioByLineName, failOutput);
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip,
|
||||
GpiodRegularBase& regularGpio, std::string failOutput) {
|
||||
unsigned int lineNum;
|
||||
gpio::Direction direction;
|
||||
std::string consumer;
|
||||
struct gpiod_line *lineHandle;
|
||||
int result = 0;
|
||||
GpiodRegularBase& regularGpio,
|
||||
std::string failOutput) {
|
||||
unsigned int lineNum;
|
||||
gpio::Direction direction;
|
||||
std::string consumer;
|
||||
struct gpiod_line* lineHandle;
|
||||
int result = 0;
|
||||
|
||||
lineNum = regularGpio.lineNum;
|
||||
lineHandle = gpiod_chip_get_line(chip, lineNum);
|
||||
if (!lineHandle) {
|
||||
sif::warning << "LinuxLibgpioIF::configureRegularGpio: Failed to open line " << std::endl;
|
||||
sif::warning << "GPIO ID: " << gpioId << ", line number: " << lineNum <<
|
||||
", " << failOutput << std::endl;
|
||||
sif::warning << "Check if Linux GPIO configuration has changed. " << std::endl;
|
||||
gpiod_chip_close(chip);
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
lineNum = regularGpio.lineNum;
|
||||
lineHandle = gpiod_chip_get_line(chip, lineNum);
|
||||
if (!lineHandle) {
|
||||
sif::warning << "LinuxLibgpioIF::configureRegularGpio: Failed to open line " << std::endl;
|
||||
sif::warning << "GPIO ID: " << gpioId << ", line number: " << lineNum << ", " << failOutput
|
||||
<< std::endl;
|
||||
sif::warning << "Check if Linux GPIO configuration has changed. " << std::endl;
|
||||
gpiod_chip_close(chip);
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
|
||||
direction = regularGpio.direction;
|
||||
consumer = regularGpio.consumer;
|
||||
/* Configure direction and add a description to the GPIO */
|
||||
switch (direction) {
|
||||
case(gpio::OUT): {
|
||||
result = gpiod_line_request_output(lineHandle, consumer.c_str(),
|
||||
regularGpio.initValue);
|
||||
break;
|
||||
direction = regularGpio.direction;
|
||||
consumer = regularGpio.consumer;
|
||||
/* Configure direction and add a description to the GPIO */
|
||||
switch (direction) {
|
||||
case (gpio::Direction::OUT): {
|
||||
result = gpiod_line_request_output(lineHandle, consumer.c_str(),
|
||||
static_cast<int>(regularGpio.initValue));
|
||||
break;
|
||||
}
|
||||
case(gpio::IN): {
|
||||
result = gpiod_line_request_input(lineHandle, consumer.c_str());
|
||||
break;
|
||||
case (gpio::Direction::IN): {
|
||||
result = gpiod_line_request_input(lineHandle, consumer.c_str());
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
sif::error << "LinuxLibgpioIF::configureGpios: Invalid direction specified"
|
||||
<< std::endl;
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
sif::error << "LinuxLibgpioIF::configureGpios: Invalid direction specified" << std::endl;
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
|
||||
if (result < 0) {
|
||||
if (result < 0) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "LinuxLibgpioIF::configureRegularGpio: Failed to request line " <<
|
||||
lineNum << " from GPIO instance with ID: " << gpioId << std::endl;
|
||||
sif::error << "LinuxLibgpioIF::configureRegularGpio: Failed to request line " << lineNum
|
||||
<< " from GPIO instance with ID: " << gpioId << std::endl;
|
||||
#else
|
||||
sif::printError("LinuxLibgpioIF::configureRegularGpio: "
|
||||
"Failed to request line %d from GPIO instance with ID: %d\n", lineNum, gpioId);
|
||||
sif::printError(
|
||||
"LinuxLibgpioIF::configureRegularGpio: "
|
||||
"Failed to request line %d from GPIO instance with ID: %d\n",
|
||||
lineNum, gpioId);
|
||||
#endif
|
||||
gpiod_line_release(lineHandle);
|
||||
return RETURN_FAILED;
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* Write line handle to GPIO configuration instance so it can later be used to set or
|
||||
* read states of GPIOs.
|
||||
*/
|
||||
regularGpio.lineHandle = lineHandle;
|
||||
return RETURN_OK;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Write line handle to GPIO configuration instance so it can later be used to set or
|
||||
* read states of GPIOs.
|
||||
*/
|
||||
regularGpio.lineHandle = lineHandle;
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::pullHigh(gpioId_t gpioId) {
|
||||
gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()) {
|
||||
sif::warning << "LinuxLibgpioIF::pullHigh: Unknown GPIO ID " << gpioId << std::endl;
|
||||
return UNKNOWN_GPIO_ID;
|
||||
}
|
||||
gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()) {
|
||||
sif::warning << "LinuxLibgpioIF::pullHigh: Unknown GPIO ID " << gpioId << std::endl;
|
||||
return UNKNOWN_GPIO_ID;
|
||||
}
|
||||
|
||||
auto gpioType = gpioMapIter->second->gpioType;
|
||||
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP
|
||||
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL
|
||||
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
return driveGpio(gpioId, *regularGpio, gpio::HIGH);
|
||||
auto gpioType = gpioMapIter->second->gpioType;
|
||||
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP or
|
||||
gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL or
|
||||
gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
else {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
|
||||
if(gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE,
|
||||
gpio::Levels::HIGH, gpioCallback->callbackArgs);
|
||||
return RETURN_OK;
|
||||
return driveGpio(gpioId, *regularGpio, gpio::Levels::HIGH);
|
||||
} else {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
|
||||
if (gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
return GPIO_TYPE_FAILURE;
|
||||
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::HIGH,
|
||||
gpioCallback->callbackArgs);
|
||||
return RETURN_OK;
|
||||
}
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::pullLow(gpioId_t gpioId) {
|
||||
gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()) {
|
||||
gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()) {
|
||||
#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;
|
||||
#else
|
||||
sif::printWarning("LinuxLibgpioIF::pullLow: Unknown GPIO ID %d\n", gpioId);
|
||||
sif::printWarning("LinuxLibgpioIF::pullLow: Unknown GPIO ID %d\n", gpioId);
|
||||
#endif
|
||||
return UNKNOWN_GPIO_ID;
|
||||
}
|
||||
return UNKNOWN_GPIO_ID;
|
||||
}
|
||||
|
||||
auto& gpioType = gpioMapIter->second->gpioType;
|
||||
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP
|
||||
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL
|
||||
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
return driveGpio(gpioId, *regularGpio, gpio::LOW);
|
||||
auto& gpioType = gpioMapIter->second->gpioType;
|
||||
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP or
|
||||
gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL or
|
||||
gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
else {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
|
||||
if(gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE,
|
||||
gpio::Levels::LOW, gpioCallback->callbackArgs);
|
||||
return RETURN_OK;
|
||||
return driveGpio(gpioId, *regularGpio, gpio::Levels::LOW);
|
||||
} else {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
|
||||
if (gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
return GPIO_TYPE_FAILURE;
|
||||
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::WRITE, gpio::Levels::LOW,
|
||||
gpioCallback->callbackArgs);
|
||||
return RETURN_OK;
|
||||
}
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::driveGpio(gpioId_t gpioId,
|
||||
GpiodRegularBase& regularGpio, gpio::Levels logicLevel) {
|
||||
int result = gpiod_line_set_value(regularGpio.lineHandle, logicLevel);
|
||||
if (result < 0) {
|
||||
ReturnValue_t LinuxLibgpioIF::driveGpio(gpioId_t gpioId, GpiodRegularBase& regularGpio,
|
||||
gpio::Levels logicLevel) {
|
||||
int result = gpiod_line_set_value(regularGpio.lineHandle, static_cast<int>(logicLevel));
|
||||
if (result < 0) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID " << gpioId <<
|
||||
" to logic level " << logicLevel << std::endl;
|
||||
sif::warning << "LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID " << gpioId
|
||||
<< " to logic level " << static_cast<int>(logicLevel) << std::endl;
|
||||
#else
|
||||
sif::printWarning("LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID %d to "
|
||||
"logic level %d\n", gpioId, logicLevel);
|
||||
sif::printWarning(
|
||||
"LinuxLibgpioIF::driveGpio: Failed to pull GPIO with ID %d to "
|
||||
"logic level %d\n",
|
||||
gpioId, logicLevel);
|
||||
#endif
|
||||
return DRIVE_GPIO_FAILURE;
|
||||
}
|
||||
return DRIVE_GPIO_FAILURE;
|
||||
}
|
||||
|
||||
return RETURN_OK;
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::readGpio(gpioId_t gpioId, int* gpioState) {
|
||||
gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()){
|
||||
gpioMapIter = gpioMap.find(gpioId);
|
||||
if (gpioMapIter == gpioMap.end()) {
|
||||
#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;
|
||||
#else
|
||||
sif::printWarning("LinuxLibgpioIF::readGpio: Unknown GPIOD ID %d\n", gpioId);
|
||||
sif::printWarning("LinuxLibgpioIF::readGpio: Unknown GPIOD ID %d\n", gpioId);
|
||||
#endif
|
||||
return UNKNOWN_GPIO_ID;
|
||||
}
|
||||
return UNKNOWN_GPIO_ID;
|
||||
}
|
||||
|
||||
auto gpioType = gpioMapIter->second->gpioType;
|
||||
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP
|
||||
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL
|
||||
or gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
*gpioState = gpiod_line_get_value(regularGpio->lineHandle);
|
||||
auto gpioType = gpioMapIter->second->gpioType;
|
||||
if (gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_CHIP or
|
||||
gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LABEL or
|
||||
gpioType == gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME) {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioMapIter->second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
else {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
|
||||
if(gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::READ,
|
||||
gpio::Levels::NONE, gpioCallback->callbackArgs);
|
||||
return RETURN_OK;
|
||||
*gpioState = gpiod_line_get_value(regularGpio->lineHandle);
|
||||
} else {
|
||||
auto gpioCallback = dynamic_cast<GpioCallback*>(gpioMapIter->second);
|
||||
if (gpioCallback->callback == nullptr) {
|
||||
return GPIO_INVALID_INSTANCE;
|
||||
}
|
||||
gpioCallback->callback(gpioMapIter->first, gpio::GpioOperation::READ, gpio::Levels::NONE,
|
||||
gpioCallback->callbackArgs);
|
||||
return RETURN_OK;
|
||||
}
|
||||
return RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd){
|
||||
ReturnValue_t status = HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
for(auto& gpioConfig: mapToAdd) {
|
||||
switch(gpioConfig.second->gpioType) {
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP):
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL):
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME): {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioConfig.second);
|
||||
if(regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
// Check for conflicts and remove duplicates if necessary
|
||||
result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
status = result;
|
||||
}
|
||||
break;
|
||||
ReturnValue_t LinuxLibgpioIF::checkForConflicts(GpioMap& mapToAdd) {
|
||||
ReturnValue_t status = HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
for (auto& gpioConfig : mapToAdd) {
|
||||
switch (gpioConfig.second->gpioType) {
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_CHIP):
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_LABEL):
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME): {
|
||||
auto regularGpio = dynamic_cast<GpiodRegularBase*>(gpioConfig.second);
|
||||
if (regularGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
case(gpio::GpioTypes::CALLBACK): {
|
||||
auto callbackGpio = dynamic_cast<GpioCallback*>(gpioConfig.second);
|
||||
if(callbackGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
// Check for conflicts and remove duplicates if necessary
|
||||
result = checkForConflictsById(gpioConfig.first,
|
||||
gpioConfig.second->gpioType, mapToAdd);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
status = result;
|
||||
}
|
||||
break;
|
||||
// Check for conflicts and remove duplicates if necessary
|
||||
result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
status = result;
|
||||
}
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
case (gpio::GpioTypes::CALLBACK): {
|
||||
auto callbackGpio = dynamic_cast<GpioCallback*>(gpioConfig.second);
|
||||
if (callbackGpio == nullptr) {
|
||||
return GPIO_TYPE_FAILURE;
|
||||
}
|
||||
// Check for conflicts and remove duplicates if necessary
|
||||
result = checkForConflictsById(gpioConfig.first, gpioConfig.second->gpioType, mapToAdd);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
status = result;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "Invalid GPIO type detected for GPIO ID " << gpioConfig.first
|
||||
<< std::endl;
|
||||
sif::warning << "Invalid GPIO type detected for GPIO ID " << gpioConfig.first << std::endl;
|
||||
#else
|
||||
sif::printWarning("Invalid GPIO type detected for GPIO ID %d\n", gpioConfig.first);
|
||||
sif::printWarning("Invalid GPIO type detected for GPIO ID %d\n", gpioConfig.first);
|
||||
#endif
|
||||
status = GPIO_TYPE_FAILURE;
|
||||
}
|
||||
}
|
||||
status = GPIO_TYPE_FAILURE;
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
ReturnValue_t LinuxLibgpioIF::checkForConflictsById(gpioId_t gpioIdToCheck,
|
||||
gpio::GpioTypes expectedType, GpioMap& mapToAdd) {
|
||||
// Cross check with private map
|
||||
gpioMapIter = gpioMap.find(gpioIdToCheck);
|
||||
if(gpioMapIter != gpioMap.end()) {
|
||||
auto& gpioType = gpioMapIter->second->gpioType;
|
||||
bool eraseDuplicateDifferentType = false;
|
||||
switch(expectedType) {
|
||||
case(gpio::GpioTypes::NONE): {
|
||||
break;
|
||||
gpio::GpioTypes expectedType,
|
||||
GpioMap& mapToAdd) {
|
||||
// Cross check with private map
|
||||
gpioMapIter = gpioMap.find(gpioIdToCheck);
|
||||
if (gpioMapIter != gpioMap.end()) {
|
||||
auto& gpioType = gpioMapIter->second->gpioType;
|
||||
bool eraseDuplicateDifferentType = false;
|
||||
switch (expectedType) {
|
||||
case (gpio::GpioTypes::NONE): {
|
||||
break;
|
||||
}
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_CHIP):
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_LABEL):
|
||||
case (gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME): {
|
||||
if (gpioType == gpio::GpioTypes::NONE or gpioType == gpio::GpioTypes::CALLBACK) {
|
||||
eraseDuplicateDifferentType = true;
|
||||
}
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_CHIP):
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_LABEL):
|
||||
case(gpio::GpioTypes::GPIO_REGULAR_BY_LINE_NAME): {
|
||||
if(gpioType == gpio::GpioTypes::NONE or gpioType == gpio::GpioTypes::CALLBACK) {
|
||||
eraseDuplicateDifferentType = true;
|
||||
}
|
||||
break;
|
||||
break;
|
||||
}
|
||||
case (gpio::GpioTypes::CALLBACK): {
|
||||
if (gpioType != gpio::GpioTypes::CALLBACK) {
|
||||
eraseDuplicateDifferentType = true;
|
||||
}
|
||||
case(gpio::GpioTypes::CALLBACK): {
|
||||
if(gpioType != gpio::GpioTypes::CALLBACK) {
|
||||
eraseDuplicateDifferentType = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(eraseDuplicateDifferentType) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "LinuxLibgpioIF::checkForConflicts: ID already exists for "
|
||||
"different GPIO type " << gpioIdToCheck <<
|
||||
". Removing duplicate from map to add" << std::endl;
|
||||
#else
|
||||
sif::printWarning("LinuxLibgpioIF::checkForConflicts: ID already exists for "
|
||||
"different GPIO type %d. Removing duplicate from map to add\n", gpioIdToCheck);
|
||||
#endif
|
||||
mapToAdd.erase(gpioIdToCheck);
|
||||
return GPIO_DUPLICATE_DETECTED;
|
||||
}
|
||||
|
||||
// Remove element from map to add because a entry for this GPIO already exists
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO "
|
||||
"definition with ID " << gpioIdToCheck << " detected. " <<
|
||||
"Duplicate will be removed from map to add" << std::endl;
|
||||
#else
|
||||
sif::printWarning("LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO definition "
|
||||
"with ID %d detected. Duplicate will be removed from map to add\n", gpioIdToCheck);
|
||||
#endif
|
||||
mapToAdd.erase(gpioIdToCheck);
|
||||
return GPIO_DUPLICATE_DETECTED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
if (eraseDuplicateDifferentType) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "LinuxLibgpioIF::checkForConflicts: ID already exists for "
|
||||
"different GPIO type "
|
||||
<< gpioIdToCheck << ". Removing duplicate from map to add" << std::endl;
|
||||
#else
|
||||
sif::printWarning(
|
||||
"LinuxLibgpioIF::checkForConflicts: ID already exists for "
|
||||
"different GPIO type %d. Removing duplicate from map to add\n",
|
||||
gpioIdToCheck);
|
||||
#endif
|
||||
mapToAdd.erase(gpioIdToCheck);
|
||||
return GPIO_DUPLICATE_DETECTED;
|
||||
}
|
||||
|
||||
// Remove element from map to add because a entry for this GPIO already exists
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO "
|
||||
"definition with ID "
|
||||
<< gpioIdToCheck << " detected. "
|
||||
<< "Duplicate will be removed from map to add" << std::endl;
|
||||
#else
|
||||
sif::printWarning(
|
||||
"LinuxLibgpioIF::checkForConflictsRegularGpio: Duplicate GPIO definition "
|
||||
"with ID %d detected. Duplicate will be removed from map to add\n",
|
||||
gpioIdToCheck);
|
||||
#endif
|
||||
mapToAdd.erase(gpioIdToCheck);
|
||||
return GPIO_DUPLICATE_DETECTED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void LinuxLibgpioIF::parseFindeLineResult(int result, std::string& lineName) {
|
||||
switch (result) {
|
||||
switch (result) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
case LINE_NOT_EXISTS:
|
||||
case LINE_ERROR: {
|
||||
sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Line with name " << lineName <<
|
||||
" does not exist" << std::endl;
|
||||
break;
|
||||
sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Line with name " << lineName
|
||||
<< " does not exist" << std::endl;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line "
|
||||
"with name " << lineName << std::endl;
|
||||
break;
|
||||
sif::warning << "LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line "
|
||||
"with name "
|
||||
<< lineName << std::endl;
|
||||
break;
|
||||
}
|
||||
#else
|
||||
case LINE_NOT_EXISTS:
|
||||
case LINE_ERROR: {
|
||||
sif::printWarning("LinuxLibgpioIF::parseFindeLineResult: Line with name %s "
|
||||
"does not exist\n", lineName);
|
||||
break;
|
||||
sif::printWarning(
|
||||
"LinuxLibgpioIF::parseFindeLineResult: Line with name %s "
|
||||
"does not exist\n",
|
||||
lineName);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
sif::printWarning("LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line "
|
||||
"with name %s\n", lineName);
|
||||
break;
|
||||
sif::printWarning(
|
||||
"LinuxLibgpioIF::parseFindeLineResult: Unknown return code for line "
|
||||
"with name %s\n",
|
||||
lineName);
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
#ifndef LINUX_GPIO_LINUXLIBGPIOIF_H_
|
||||
#define LINUX_GPIO_LINUXLIBGPIOIF_H_
|
||||
|
||||
#include "fsfw/objectmanager/SystemObject.h"
|
||||
#include "fsfw/returnvalues/FwClassIds.h"
|
||||
#include "fsfw_hal/common/gpio/GpioIF.h"
|
||||
#include "fsfw/objectmanager/SystemObject.h"
|
||||
|
||||
class GpioCookie;
|
||||
class GpiodRegularIF;
|
||||
@ -16,76 +16,71 @@ class GpiodRegularIF;
|
||||
* The Petalinux SDK from Xilinx supports libgpiod since Petalinux 2019.1.
|
||||
*/
|
||||
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 =
|
||||
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 1);
|
||||
static constexpr ReturnValue_t DRIVE_GPIO_FAILURE =
|
||||
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 2);
|
||||
static constexpr ReturnValue_t GPIO_TYPE_FAILURE =
|
||||
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 UNKNOWN_GPIO_ID =
|
||||
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 1);
|
||||
static constexpr ReturnValue_t DRIVE_GPIO_FAILURE =
|
||||
HasReturnvaluesIF::makeReturnCode(gpioRetvalId, 2);
|
||||
static constexpr ReturnValue_t GPIO_TYPE_FAILURE =
|
||||
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);
|
||||
LinuxLibgpioIF(object_id_t objectId);
|
||||
virtual ~LinuxLibgpioIF();
|
||||
|
||||
LinuxLibgpioIF(object_id_t objectId);
|
||||
virtual ~LinuxLibgpioIF();
|
||||
ReturnValue_t addGpios(GpioCookie* gpioCookie) override;
|
||||
ReturnValue_t pullHigh(gpioId_t gpioId) override;
|
||||
ReturnValue_t pullLow(gpioId_t gpioId) override;
|
||||
ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) override;
|
||||
|
||||
ReturnValue_t addGpios(GpioCookie* gpioCookie) override;
|
||||
ReturnValue_t pullHigh(gpioId_t gpioId) override;
|
||||
ReturnValue_t pullLow(gpioId_t gpioId) override;
|
||||
ReturnValue_t readGpio(gpioId_t gpioId, int* gpioState) override;
|
||||
private:
|
||||
static const size_t MAX_CHIPNAME_LENGTH = 11;
|
||||
static const int LINE_NOT_EXISTS = 0;
|
||||
static const int LINE_ERROR = -1;
|
||||
static const int LINE_FOUND = 1;
|
||||
|
||||
private:
|
||||
// Holds the information and configuration of all used GPIOs
|
||||
GpioUnorderedMap gpioMap;
|
||||
GpioUnorderedMapIter gpioMapIter;
|
||||
|
||||
static const size_t MAX_CHIPNAME_LENGTH = 11;
|
||||
static const int LINE_NOT_EXISTS = 0;
|
||||
static const int LINE_ERROR = -1;
|
||||
static const int LINE_FOUND = 1;
|
||||
/**
|
||||
* @brief This functions drives line of a GPIO specified by the GPIO ID.
|
||||
*
|
||||
* @param gpioId The GPIO ID of the GPIO to drive.
|
||||
* @param logiclevel The logic level to set. O or 1.
|
||||
*/
|
||||
ReturnValue_t driveGpio(gpioId_t gpioId, GpiodRegularBase& regularGpio, gpio::Levels logicLevel);
|
||||
|
||||
// Holds the information and configuration of all used GPIOs
|
||||
GpioUnorderedMap gpioMap;
|
||||
GpioUnorderedMapIter gpioMapIter;
|
||||
ReturnValue_t configureGpioByLabel(gpioId_t gpioId, GpiodRegularByLabel& gpioByLabel);
|
||||
ReturnValue_t configureGpioByChip(gpioId_t gpioId, GpiodRegularByChip& gpioByChip);
|
||||
ReturnValue_t configureGpioByLineName(gpioId_t gpioId, GpiodRegularByLineName& gpioByLineName);
|
||||
ReturnValue_t configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip,
|
||||
GpiodRegularBase& regularGpio, std::string failOutput);
|
||||
|
||||
/**
|
||||
* @brief This functions drives line of a GPIO specified by the GPIO ID.
|
||||
*
|
||||
* @param gpioId The GPIO ID of the GPIO to drive.
|
||||
* @param logiclevel The logic level to set. O or 1.
|
||||
*/
|
||||
ReturnValue_t driveGpio(gpioId_t gpioId, GpiodRegularBase& regularGpio,
|
||||
gpio::Levels logicLevel);
|
||||
/**
|
||||
* @brief This function checks if GPIOs are already registered and whether
|
||||
* there exists a conflict in the GPIO configuration. E.g. the
|
||||
* direction.
|
||||
*
|
||||
* @param mapToAdd The GPIOs which shall be added to the gpioMap.
|
||||
*
|
||||
* @return RETURN_OK if successful, otherwise RETURN_FAILED
|
||||
*/
|
||||
ReturnValue_t checkForConflicts(GpioMap& mapToAdd);
|
||||
|
||||
ReturnValue_t configureGpioByLabel(gpioId_t gpioId, GpiodRegularByLabel& gpioByLabel);
|
||||
ReturnValue_t configureGpioByChip(gpioId_t gpioId, GpiodRegularByChip& gpioByChip);
|
||||
ReturnValue_t configureGpioByLineName(gpioId_t gpioId,
|
||||
GpiodRegularByLineName &gpioByLineName);
|
||||
ReturnValue_t configureRegularGpio(gpioId_t gpioId, struct gpiod_chip* chip,
|
||||
GpiodRegularBase& regularGpio, std::string failOutput);
|
||||
ReturnValue_t checkForConflictsById(gpioId_t gpiodId, gpio::GpioTypes type, GpioMap& mapToAdd);
|
||||
|
||||
/**
|
||||
* @brief This function checks if GPIOs are already registered and whether
|
||||
* there exists a conflict in the GPIO configuration. E.g. the
|
||||
* direction.
|
||||
*
|
||||
* @param mapToAdd The GPIOs which shall be added to the gpioMap.
|
||||
*
|
||||
* @return RETURN_OK if successful, otherwise RETURN_FAILED
|
||||
*/
|
||||
ReturnValue_t checkForConflicts(GpioMap& mapToAdd);
|
||||
/**
|
||||
* @brief Performs the initial configuration of all GPIOs specified in the GpioMap mapToAdd.
|
||||
*/
|
||||
ReturnValue_t configureGpios(GpioMap& mapToAdd);
|
||||
|
||||
ReturnValue_t checkForConflictsById(gpioId_t gpiodId, gpio::GpioTypes type,
|
||||
GpioMap& mapToAdd);
|
||||
|
||||
/**
|
||||
* @brief Performs the initial configuration of all GPIOs specified in the GpioMap mapToAdd.
|
||||
*/
|
||||
ReturnValue_t configureGpios(GpioMap& mapToAdd);
|
||||
|
||||
void parseFindeLineResult(int result, std::string& lineName);
|
||||
void parseFindeLineResult(int result, std::string& lineName);
|
||||
};
|
||||
|
||||
#endif /* LINUX_GPIO_LINUXLIBGPIOIF_H_ */
|
||||
|
@ -1,205 +1,237 @@
|
||||
#include "fsfw_hal/linux/i2c/I2cComIF.h"
|
||||
#include "fsfw_hal/linux/utility.h"
|
||||
#include "I2cComIF.h"
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw/serviceinterface.h"
|
||||
#include "fsfw_hal/linux/UnixFileGuard.h"
|
||||
#include "fsfw_hal/linux/utility.h"
|
||||
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
#if FSFW_HAL_I2C_WIRETAPPING == 1
|
||||
#include "fsfw/globalfunctions/arrayprinter.h"
|
||||
#endif
|
||||
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <linux/i2c-dev.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/i2c-dev.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
|
||||
I2cComIF::I2cComIF(object_id_t objectId): SystemObject(objectId){
|
||||
}
|
||||
I2cComIF::I2cComIF(object_id_t objectId) : SystemObject(objectId) {}
|
||||
|
||||
I2cComIF::~I2cComIF() {}
|
||||
|
||||
ReturnValue_t I2cComIF::initializeInterface(CookieIF* cookie) {
|
||||
address_t i2cAddress;
|
||||
std::string deviceFile;
|
||||
|
||||
address_t i2cAddress;
|
||||
std::string deviceFile;
|
||||
|
||||
if(cookie == nullptr) {
|
||||
sif::error << "I2cComIF::initializeInterface: Invalid cookie!" << std::endl;
|
||||
return NULLPOINTER;
|
||||
}
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if(i2cCookie == nullptr) {
|
||||
sif::error << "I2cComIF::initializeInterface: Invalid I2C cookie!" << std::endl;
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
i2cAddress = i2cCookie->getAddress();
|
||||
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if(i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
size_t maxReplyLen = i2cCookie->getMaxReplyLen();
|
||||
I2cInstance i2cInstance = {std::vector<uint8_t>(maxReplyLen), 0};
|
||||
auto statusPair = i2cDeviceMap.emplace(i2cAddress, i2cInstance);
|
||||
if (not statusPair.second) {
|
||||
sif::error << "I2cComIF::initializeInterface: Failed to insert device with address " <<
|
||||
i2cAddress << "to I2C device " << "map" << std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
sif::error << "I2cComIF::initializeInterface: Device with address " << i2cAddress <<
|
||||
"already in use" << std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::sendMessage(CookieIF *cookie,
|
||||
const uint8_t *sendData, size_t sendLen) {
|
||||
|
||||
ReturnValue_t result;
|
||||
int fd;
|
||||
std::string deviceFile;
|
||||
|
||||
if(sendData == nullptr) {
|
||||
sif::error << "I2cComIF::sendMessage: Send Data is nullptr"
|
||||
<< std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
if(sendLen == 0) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if(i2cCookie == nullptr) {
|
||||
sif::error << "I2cComIF::sendMessage: Invalid I2C Cookie!" << std::endl;
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
address_t i2cAddress = i2cCookie->getAddress();
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
sif::error << "I2cComIF::sendMessage: i2cAddress of Cookie not "
|
||||
<< "registered in i2cDeviceMap" << std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
deviceFile = i2cCookie->getDeviceFile();
|
||||
UnixFileGuard fileHelper(deviceFile, &fd, O_RDWR, "I2cComIF::sendMessage");
|
||||
if(fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return fileHelper.getOpenResult();
|
||||
}
|
||||
result = openDevice(deviceFile, i2cAddress, &fd);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK){
|
||||
return result;
|
||||
}
|
||||
|
||||
if (write(fd, sendData, sendLen) != (int)sendLen) {
|
||||
sif::error << "I2cComIF::sendMessage: Failed to send data to I2C "
|
||||
"device with error code " << errno << ". Error description: "
|
||||
<< strerror(errno) << std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::getSendSuccess(CookieIF *cookie) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF *cookie,
|
||||
size_t requestLen) {
|
||||
ReturnValue_t result;
|
||||
int fd;
|
||||
std::string deviceFile;
|
||||
|
||||
if (requestLen == 0) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if(i2cCookie == nullptr) {
|
||||
sif::error << "I2cComIF::requestReceiveMessage: Invalid I2C Cookie!" << std::endl;
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
address_t i2cAddress = i2cCookie->getAddress();
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
sif::error << "I2cComIF::requestReceiveMessage: i2cAddress of Cookie not "
|
||||
<< "registered in i2cDeviceMap" << std::endl;
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
deviceFile = i2cCookie->getDeviceFile();
|
||||
UnixFileGuard fileHelper(deviceFile, &fd, O_RDWR, "I2cComIF::requestReceiveMessage");
|
||||
if(fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return fileHelper.getOpenResult();
|
||||
}
|
||||
result = openDevice(deviceFile, i2cAddress, &fd);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK){
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
uint8_t* replyBuffer = i2cDeviceMapIter->second.replyBuffer.data();
|
||||
|
||||
int readLen = read(fd, replyBuffer, requestLen);
|
||||
if (readLen != static_cast<int>(requestLen)) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1 and FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::requestReceiveMessage: Reading from I2C "
|
||||
<< "device failed with error code " << errno <<". Description"
|
||||
<< " of error: " << strerror(errno) << std::endl;
|
||||
sif::error << "I2cComIF::requestReceiveMessage: Read only " << readLen << " from "
|
||||
<< requestLen << " bytes" << std::endl;
|
||||
if (cookie == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::initializeInterface: Invalid cookie!" << std::endl;
|
||||
#endif
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
sif::debug << "I2cComIF::requestReceiveMessage: Read " << readLen << " of " << requestLen << " bytes" << std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return NULLPOINTER;
|
||||
}
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if (i2cCookie == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::initializeInterface: Invalid I2C cookie!" << std::endl;
|
||||
#endif
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
i2cDeviceMapIter->second.replyLen = requestLen;
|
||||
i2cAddress = i2cCookie->getAddress();
|
||||
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
size_t maxReplyLen = i2cCookie->getMaxReplyLen();
|
||||
I2cInstance i2cInstance = {std::vector<uint8_t>(maxReplyLen), 0};
|
||||
auto statusPair = i2cDeviceMap.emplace(i2cAddress, i2cInstance);
|
||||
if (not statusPair.second) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::initializeInterface: Failed to insert device with address "
|
||||
<< i2cAddress << "to I2C device "
|
||||
<< "map" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::initializeInterface: Device with address " << i2cAddress
|
||||
<< "already in use" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::readReceivedMessage(CookieIF *cookie,
|
||||
uint8_t **buffer, size_t* size) {
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if(i2cCookie == nullptr) {
|
||||
sif::error << "I2cComIF::readReceivedMessage: Invalid I2C Cookie!" << std::endl;
|
||||
return NULLPOINTER;
|
||||
}
|
||||
ReturnValue_t I2cComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
|
||||
ReturnValue_t result;
|
||||
int fd;
|
||||
std::string deviceFile;
|
||||
|
||||
address_t i2cAddress = i2cCookie->getAddress();
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
sif::error << "I2cComIF::readReceivedMessage: i2cAddress of Cookie not "
|
||||
<< "found in i2cDeviceMap" << std::endl;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
*buffer = i2cDeviceMapIter->second.replyBuffer.data();
|
||||
*size = i2cDeviceMapIter->second.replyLen;
|
||||
if (sendData == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::sendMessage: Send Data is nullptr" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
if (sendLen == 0) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if (i2cCookie == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::sendMessage: Invalid I2C Cookie!" << std::endl;
|
||||
#endif
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
address_t i2cAddress = i2cCookie->getAddress();
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::sendMessage: i2cAddress of Cookie not "
|
||||
<< "registered in i2cDeviceMap" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
deviceFile = i2cCookie->getDeviceFile();
|
||||
UnixFileGuard fileHelper(deviceFile, &fd, O_RDWR, "I2cComIF::sendMessage");
|
||||
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return fileHelper.getOpenResult();
|
||||
}
|
||||
result = openDevice(deviceFile, i2cAddress, &fd);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (write(fd, sendData, sendLen) != static_cast<int>(sendLen)) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::sendMessage: Failed to send data to I2C "
|
||||
"device with error code "
|
||||
<< errno << ". Error description: " << strerror(errno) << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
#if FSFW_HAL_I2C_WIRETAPPING == 1
|
||||
sif::info << "Sent I2C data to bus " << deviceFile << ":" << std::endl;
|
||||
arrayprinter::print(sendData, sendLen);
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::openDevice(std::string deviceFile,
|
||||
address_t i2cAddress, int* fileDescriptor) {
|
||||
ReturnValue_t I2cComIF::getSendSuccess(CookieIF* cookie) { return HasReturnvaluesIF::RETURN_OK; }
|
||||
|
||||
if (ioctl(*fileDescriptor, I2C_SLAVE, i2cAddress) < 0) {
|
||||
ReturnValue_t I2cComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
|
||||
ReturnValue_t result;
|
||||
int fd;
|
||||
std::string deviceFile;
|
||||
|
||||
if (requestLen == 0) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if (i2cCookie == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::requestReceiveMessage: Invalid I2C Cookie!" << std::endl;
|
||||
#endif
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
address_t i2cAddress = i2cCookie->getAddress();
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::requestReceiveMessage: i2cAddress of Cookie not "
|
||||
<< "registered in i2cDeviceMap" << std::endl;
|
||||
#endif
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
deviceFile = i2cCookie->getDeviceFile();
|
||||
UnixFileGuard fileHelper(deviceFile, &fd, O_RDWR, "I2cComIF::requestReceiveMessage");
|
||||
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return fileHelper.getOpenResult();
|
||||
}
|
||||
result = openDevice(deviceFile, i2cAddress, &fd);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
uint8_t* replyBuffer = i2cDeviceMapIter->second.replyBuffer.data();
|
||||
|
||||
int readLen = read(fd, replyBuffer, requestLen);
|
||||
if (readLen != static_cast<int>(requestLen)) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1 and FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::requestReceiveMessage: Reading from I2C "
|
||||
<< "device failed with error code " << errno << ". Description"
|
||||
<< " of error: " << strerror(errno) << std::endl;
|
||||
sif::error << "I2cComIF::requestReceiveMessage: Read only " << readLen << " from " << requestLen
|
||||
<< " bytes" << std::endl;
|
||||
#endif
|
||||
i2cDeviceMapIter->second.replyLen = 0;
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::debug << "I2cComIF::requestReceiveMessage: Read " << readLen << " of " << requestLen
|
||||
<< " bytes" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
#if FSFW_HAL_I2C_WIRETAPPING == 1
|
||||
sif::info << "I2C read bytes from bus " << deviceFile << ":" << std::endl;
|
||||
arrayprinter::print(replyBuffer, requestLen);
|
||||
#endif
|
||||
|
||||
i2cDeviceMapIter->second.replyLen = requestLen;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
|
||||
I2cCookie* i2cCookie = dynamic_cast<I2cCookie*>(cookie);
|
||||
if (i2cCookie == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::readReceivedMessage: Invalid I2C Cookie!" << std::endl;
|
||||
#endif
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
address_t i2cAddress = i2cCookie->getAddress();
|
||||
i2cDeviceMapIter = i2cDeviceMap.find(i2cAddress);
|
||||
if (i2cDeviceMapIter == i2cDeviceMap.end()) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "I2cComIF::readReceivedMessage: i2cAddress of Cookie not "
|
||||
<< "found in i2cDeviceMap" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
*buffer = i2cDeviceMapIter->second.replyBuffer.data();
|
||||
*size = i2cDeviceMapIter->second.replyLen;
|
||||
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t I2cComIF::openDevice(std::string deviceFile, address_t i2cAddress,
|
||||
int* fileDescriptor) {
|
||||
if (ioctl(*fileDescriptor, I2C_SLAVE, i2cAddress) < 0) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "I2cComIF: Specifying target device failed with error code " << errno << "."
|
||||
<< std::endl;
|
||||
sif::warning << "Error description " << strerror(errno) << std::endl;
|
||||
sif::warning << "I2cComIF: Specifying target device failed with error code " << errno << "."
|
||||
<< std::endl;
|
||||
sif::warning << "Error description " << strerror(errno) << std::endl;
|
||||
#else
|
||||
sif::printWarning("I2cComIF: Specifying target device failed with error code %d.\n");
|
||||
sif::printWarning("Error description: %s\n", strerror(errno));
|
||||
sif::printWarning("I2cComIF: Specifying target device failed with error code %d.\n");
|
||||
sif::printWarning("Error description: %s\n", strerror(errno));
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
@ -1,13 +1,14 @@
|
||||
#ifndef LINUX_I2C_I2COMIF_H_
|
||||
#define LINUX_I2C_I2COMIF_H_
|
||||
|
||||
#include "I2cCookie.h"
|
||||
#include <fsfw/objectmanager/SystemObject.h>
|
||||
#include <fsfw/devicehandlers/DeviceCommunicationIF.h>
|
||||
#include <fsfw/objectmanager/SystemObject.h>
|
||||
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "I2cCookie.h"
|
||||
|
||||
/**
|
||||
* @brief This is the communication interface for I2C devices connected
|
||||
* to a system running a Linux OS.
|
||||
@ -16,46 +17,41 @@
|
||||
*
|
||||
* @author J. Meier
|
||||
*/
|
||||
class I2cComIF: public DeviceCommunicationIF, public SystemObject {
|
||||
public:
|
||||
I2cComIF(object_id_t objectId);
|
||||
class I2cComIF : public DeviceCommunicationIF, public SystemObject {
|
||||
public:
|
||||
I2cComIF(object_id_t objectId);
|
||||
|
||||
virtual ~I2cComIF();
|
||||
virtual ~I2cComIF();
|
||||
|
||||
ReturnValue_t initializeInterface(CookieIF * cookie) override;
|
||||
ReturnValue_t sendMessage(CookieIF *cookie,const uint8_t *sendData,
|
||||
size_t sendLen) override;
|
||||
ReturnValue_t getSendSuccess(CookieIF *cookie) override;
|
||||
ReturnValue_t requestReceiveMessage(CookieIF *cookie,
|
||||
size_t requestLen) override;
|
||||
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
|
||||
size_t *size) override;
|
||||
ReturnValue_t initializeInterface(CookieIF *cookie) override;
|
||||
ReturnValue_t sendMessage(CookieIF *cookie, const uint8_t *sendData, size_t sendLen) override;
|
||||
ReturnValue_t getSendSuccess(CookieIF *cookie) override;
|
||||
ReturnValue_t requestReceiveMessage(CookieIF *cookie, size_t requestLen) override;
|
||||
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer, size_t *size) override;
|
||||
|
||||
private:
|
||||
private:
|
||||
struct I2cInstance {
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
size_t replyLen;
|
||||
};
|
||||
|
||||
struct I2cInstance {
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
size_t replyLen;
|
||||
};
|
||||
using I2cDeviceMap = std::unordered_map<address_t, I2cInstance>;
|
||||
using I2cDeviceMapIter = I2cDeviceMap::iterator;
|
||||
|
||||
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
|
||||
* the appropriate file descriptor will be stored */
|
||||
I2cDeviceMap i2cDeviceMap;
|
||||
I2cDeviceMapIter i2cDeviceMapIter;
|
||||
|
||||
/* In this map all i2c devices will be registered with their address and
|
||||
* the appropriate file descriptor will be stored */
|
||||
I2cDeviceMap i2cDeviceMap;
|
||||
I2cDeviceMapIter i2cDeviceMapIter;
|
||||
|
||||
/**
|
||||
* @brief This function opens an I2C device and binds the opened file
|
||||
* to a specific I2C address.
|
||||
* @param deviceFile The name of the device file. E.g. i2c-0
|
||||
* @param i2cAddress The address of the i2c slave device.
|
||||
* @param fileDescriptor Pointer to device descriptor.
|
||||
* @return RETURN_OK if successful, otherwise RETURN_FAILED.
|
||||
*/
|
||||
ReturnValue_t openDevice(std::string deviceFile,
|
||||
address_t i2cAddress, int* fileDescriptor);
|
||||
/**
|
||||
* @brief This function opens an I2C device and binds the opened file
|
||||
* to a specific I2C address.
|
||||
* @param deviceFile The name of the device file. E.g. i2c-0
|
||||
* @param i2cAddress The address of the i2c slave device.
|
||||
* @param fileDescriptor Pointer to device descriptor.
|
||||
* @return RETURN_OK if successful, otherwise RETURN_FAILED.
|
||||
*/
|
||||
ReturnValue_t openDevice(std::string deviceFile, address_t i2cAddress, int *fileDescriptor);
|
||||
};
|
||||
|
||||
#endif /* LINUX_I2C_I2COMIF_H_ */
|
||||
|
@ -1,20 +1,12 @@
|
||||
#include "fsfw_hal/linux/i2c/I2cCookie.h"
|
||||
|
||||
I2cCookie::I2cCookie(address_t i2cAddress_, size_t maxReplyLen_,
|
||||
std::string deviceFile_) :
|
||||
i2cAddress(i2cAddress_), maxReplyLen(maxReplyLen_), deviceFile(deviceFile_) {
|
||||
}
|
||||
I2cCookie::I2cCookie(address_t i2cAddress_, size_t maxReplyLen_, std::string 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; }
|
||||
|
||||
std::string I2cCookie::getDeviceFile() const {
|
||||
return deviceFile;
|
||||
}
|
||||
std::string I2cCookie::getDeviceFile() const { return deviceFile; }
|
||||
|
||||
I2cCookie::~I2cCookie() {}
|
||||
|
@ -2,6 +2,7 @@
|
||||
#define LINUX_I2C_I2CCOOKIE_H_
|
||||
|
||||
#include <fsfw/devicehandlers/CookieIF.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
@ -9,30 +10,27 @@
|
||||
*
|
||||
* @author J. Meier
|
||||
*/
|
||||
class I2cCookie: public CookieIF {
|
||||
public:
|
||||
class I2cCookie : public CookieIF {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the I2C cookie.
|
||||
* @param i2cAddress_ The i2c address of the target device.
|
||||
* @param maxReplyLen_ The maximum expected length of a reply from the
|
||||
* target device.
|
||||
* @param devicFile_ The device file specifying the i2c interface to use. E.g. "/dev/i2c-0".
|
||||
*/
|
||||
I2cCookie(address_t i2cAddress_, size_t maxReplyLen_, std::string deviceFile_);
|
||||
|
||||
/**
|
||||
* @brief Constructor for the I2C cookie.
|
||||
* @param i2cAddress_ The i2c address of the target device.
|
||||
* @param maxReplyLen_ The maximum expected length of a reply from the
|
||||
* target device.
|
||||
* @param devicFile_ The device file specifying the i2c interface to use. E.g. "/dev/i2c-0".
|
||||
*/
|
||||
I2cCookie(address_t i2cAddress_, size_t maxReplyLen_,
|
||||
std::string deviceFile_);
|
||||
virtual ~I2cCookie();
|
||||
|
||||
virtual ~I2cCookie();
|
||||
address_t getAddress() const;
|
||||
size_t getMaxReplyLen() const;
|
||||
std::string getDeviceFile() const;
|
||||
|
||||
address_t getAddress() const;
|
||||
size_t getMaxReplyLen() const;
|
||||
std::string getDeviceFile() const;
|
||||
|
||||
private:
|
||||
|
||||
address_t i2cAddress = 0;
|
||||
size_t maxReplyLen = 0;
|
||||
std::string deviceFile;
|
||||
private:
|
||||
address_t i2cAddress = 0;
|
||||
size_t maxReplyLen = 0;
|
||||
std::string deviceFile;
|
||||
};
|
||||
|
||||
#endif /* LINUX_I2C_I2CCOOKIE_H_ */
|
||||
|
@ -1,38 +1,38 @@
|
||||
#include "fsfw/FSFW.h"
|
||||
|
||||
#include "fsfw_hal/linux/rpi/GpioRPi.h"
|
||||
#include "fsfw_hal/common/gpio/GpioCookie.h"
|
||||
|
||||
#include <fsfw/serviceinterface/ServiceInterface.h>
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw_hal/common/gpio/GpioCookie.h"
|
||||
|
||||
ReturnValue_t gpio::createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int bcmPin,
|
||||
std::string consumer, gpio::Direction direction, int initValue) {
|
||||
if(cookie == nullptr) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue) {
|
||||
if (cookie == nullptr) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
auto config = new GpiodRegularByChip();
|
||||
/* Default chipname for Raspberry Pi. There is still gpiochip1 for expansion, but most users
|
||||
will not need this */
|
||||
config->chipname = "gpiochip0";
|
||||
auto config = new GpiodRegularByChip();
|
||||
/* Default chipname for Raspberry Pi. There is still gpiochip1 for expansion, but most users
|
||||
will not need this */
|
||||
config->chipname = "gpiochip0";
|
||||
|
||||
config->consumer = consumer;
|
||||
config->direction = direction;
|
||||
config->initValue = initValue;
|
||||
config->consumer = consumer;
|
||||
config->direction = direction;
|
||||
config->initValue = initValue;
|
||||
|
||||
/* Sanity check for the BCM pins before assigning it */
|
||||
if(bcmPin > 27) {
|
||||
/* Sanity check for the BCM pins before assigning it */
|
||||
if (bcmPin > 27) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "createRpiGpioConfig: BCM pin " << bcmPin << " invalid!" << std::endl;
|
||||
sif::error << "createRpiGpioConfig: BCM pin " << bcmPin << " invalid!" << std::endl;
|
||||
#else
|
||||
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_VERBOSE_LEVEL >= 1 */
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
config->lineNum = bcmPin;
|
||||
cookie->addGpio(gpioId, config);
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
config->lineNum = bcmPin;
|
||||
cookie->addGpio(gpioId, config);
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
@ -2,6 +2,7 @@
|
||||
#define BSP_RPI_GPIO_GPIORPI_H_
|
||||
|
||||
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
|
||||
|
||||
#include "../../common/gpio/gpioDefinitions.h"
|
||||
|
||||
class GpioCookie;
|
||||
@ -20,7 +21,8 @@ namespace gpio {
|
||||
* @return
|
||||
*/
|
||||
ReturnValue_t createRpiGpioConfig(GpioCookie* cookie, gpioId_t gpioId, int bcmPin,
|
||||
std::string consumer, gpio::Direction direction, int initValue);
|
||||
}
|
||||
std::string consumer, gpio::Direction direction,
|
||||
gpio::Levels initValue);
|
||||
} // namespace gpio
|
||||
|
||||
#endif /* BSP_RPI_GPIO_GPIORPI_H_ */
|
||||
|
@ -1,408 +1,412 @@
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw_hal/linux/spi/SpiComIF.h"
|
||||
#include "fsfw_hal/linux/spi/SpiCookie.h"
|
||||
#include "fsfw_hal/linux/utility.h"
|
||||
#include "fsfw_hal/linux/UnixFileGuard.h"
|
||||
|
||||
#include <fsfw/ipc/MutexFactory.h>
|
||||
#include <fsfw/globalfunctions/arrayprinter.h>
|
||||
|
||||
#include <linux/spi/spidev.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <fsfw/globalfunctions/arrayprinter.h>
|
||||
#include <fsfw/ipc/MutexFactory.h>
|
||||
#include <linux/spi/spidev.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
|
||||
SpiComIF::SpiComIF(object_id_t objectId, GpioIF* gpioComIF):
|
||||
SystemObject(objectId), gpioComIF(gpioComIF) {
|
||||
if(gpioComIF == nullptr) {
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw_hal/linux/UnixFileGuard.h"
|
||||
#include "fsfw_hal/linux/spi/SpiCookie.h"
|
||||
#include "fsfw_hal/linux/utility.h"
|
||||
|
||||
SpiComIF::SpiComIF(object_id_t objectId, GpioIF* gpioComIF)
|
||||
: SystemObject(objectId), gpioComIF(gpioComIF) {
|
||||
if (gpioComIF == nullptr) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "SpiComIF::SpiComIF: GPIO communication interface invalid!" << std::endl;
|
||||
sif::error << "SpiComIF::SpiComIF: GPIO communication interface invalid!" << std::endl;
|
||||
#else
|
||||
sif::printError("SpiComIF::SpiComIF: GPIO communication interface invalid!\n");
|
||||
sif::printError("SpiComIF::SpiComIF: GPIO communication interface invalid!\n");
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
}
|
||||
}
|
||||
|
||||
spiMutex = MutexFactory::instance()->createMutex();
|
||||
spiMutex = MutexFactory::instance()->createMutex();
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
|
||||
int retval = 0;
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if(spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
ReturnValue_t SpiComIF::initializeInterface(CookieIF* cookie) {
|
||||
int retval = 0;
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if (spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
address_t spiAddress = spiCookie->getSpiAddress();
|
||||
address_t spiAddress = spiCookie->getSpiAddress();
|
||||
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if(iter == spiDeviceMap.end()) {
|
||||
size_t bufferSize = spiCookie->getMaxBufferSize();
|
||||
SpiInstance spiInstance(bufferSize);
|
||||
auto statusPair = spiDeviceMap.emplace(spiAddress, spiInstance);
|
||||
if (not statusPair.second) {
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if (iter == spiDeviceMap.end()) {
|
||||
size_t bufferSize = spiCookie->getMaxBufferSize();
|
||||
SpiInstance spiInstance(bufferSize);
|
||||
auto statusPair = spiDeviceMap.emplace(spiAddress, spiInstance);
|
||||
if (not statusPair.second) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "SpiComIF::initializeInterface: Failed to insert device with address " <<
|
||||
spiAddress << "to SPI device map" << std::endl;
|
||||
sif::error << "SpiComIF::initializeInterface: Failed to insert device with address "
|
||||
<< spiAddress << "to SPI device map" << std::endl;
|
||||
#else
|
||||
sif::printError("SpiComIF::initializeInterface: Failed to insert device with address "
|
||||
"%lu to SPI device map\n", static_cast<unsigned long>(spiAddress));
|
||||
sif::printError(
|
||||
"SpiComIF::initializeInterface: Failed to insert device with address "
|
||||
"%lu to SPI device map\n",
|
||||
static_cast<unsigned long>(spiAddress));
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
/* Now we emplaced the read buffer in the map, we still need to assign that location
|
||||
to the SPI driver transfer struct */
|
||||
spiCookie->assignReadBuffer(statusPair.first->second.replyBuffer.data());
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
else {
|
||||
/* Now we emplaced the read buffer in the map, we still need to assign that location
|
||||
to the SPI driver transfer struct */
|
||||
spiCookie->assignReadBuffer(statusPair.first->second.replyBuffer.data());
|
||||
} else {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "SpiComIF::initializeInterface: SPI address already exists!" << std::endl;
|
||||
sif::error << "SpiComIF::initializeInterface: SPI address already exists!" << std::endl;
|
||||
#else
|
||||
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_VERBOSE_LEVEL >= 1 */
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
/* Pull CS high in any case to be sure that device is inactive */
|
||||
gpioId_t gpioId = spiCookie->getChipSelectPin();
|
||||
if (gpioId != gpio::NO_GPIO) {
|
||||
gpioComIF->pullHigh(gpioId);
|
||||
}
|
||||
|
||||
uint32_t spiSpeed = 0;
|
||||
spi::SpiModes spiMode = spi::SpiModes::MODE_0;
|
||||
|
||||
SpiCookie::UncommonParameters params;
|
||||
spiCookie->getSpiParameters(spiMode, spiSpeed, ¶ms);
|
||||
|
||||
int fileDescriptor = 0;
|
||||
UnixFileGuard fileHelper(spiCookie->getSpiDevice(), &fileDescriptor, O_RDWR,
|
||||
"SpiComIF::initializeInterface");
|
||||
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return fileHelper.getOpenResult();
|
||||
}
|
||||
|
||||
/* These flags are rather uncommon */
|
||||
if (params.threeWireSpi or params.noCs or params.csHigh) {
|
||||
uint32_t currentMode = 0;
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_RD_MODE32, ¤tMode);
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initialiezInterface: Could not read full mode!");
|
||||
}
|
||||
|
||||
/* Pull CS high in any case to be sure that device is inactive */
|
||||
gpioId_t gpioId = spiCookie->getChipSelectPin();
|
||||
if(gpioId != gpio::NO_GPIO) {
|
||||
gpioComIF->pullHigh(gpioId);
|
||||
if (params.threeWireSpi) {
|
||||
currentMode |= SPI_3WIRE;
|
||||
}
|
||||
|
||||
uint32_t spiSpeed = 0;
|
||||
spi::SpiModes spiMode = spi::SpiModes::MODE_0;
|
||||
|
||||
SpiCookie::UncommonParameters params;
|
||||
spiCookie->getSpiParameters(spiMode, spiSpeed, ¶ms);
|
||||
|
||||
int fileDescriptor = 0;
|
||||
UnixFileGuard fileHelper(spiCookie->getSpiDevice(), &fileDescriptor, O_RDWR,
|
||||
"SpiComIF::initializeInterface");
|
||||
if(fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return fileHelper.getOpenResult();
|
||||
if (params.noCs) {
|
||||
/* Some drivers like the Raspberry Pi ignore this flag in any case */
|
||||
currentMode |= SPI_NO_CS;
|
||||
}
|
||||
|
||||
/* These flags are rather uncommon */
|
||||
if(params.threeWireSpi or params.noCs or params.csHigh) {
|
||||
uint32_t currentMode = 0;
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_RD_MODE32, ¤tMode);
|
||||
if(retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initialiezInterface: Could not read full mode!");
|
||||
}
|
||||
|
||||
if(params.threeWireSpi) {
|
||||
currentMode |= SPI_3WIRE;
|
||||
}
|
||||
if(params.noCs) {
|
||||
/* Some drivers like the Raspberry Pi ignore this flag in any case */
|
||||
currentMode |= SPI_NO_CS;
|
||||
}
|
||||
if(params.csHigh) {
|
||||
currentMode |= SPI_CS_HIGH;
|
||||
}
|
||||
/* Write adapted mode */
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_WR_MODE32, ¤tMode);
|
||||
if(retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initialiezInterface: Could not write full mode!");
|
||||
}
|
||||
if (params.csHigh) {
|
||||
currentMode |= SPI_CS_HIGH;
|
||||
}
|
||||
if(params.lsbFirst) {
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_WR_LSB_FIRST, ¶ms.lsbFirst);
|
||||
if(retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initializeInterface: Setting LSB first failed");
|
||||
}
|
||||
/* Write adapted mode */
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_WR_MODE32, ¤tMode);
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initialiezInterface: Could not write full mode!");
|
||||
}
|
||||
if(params.bitsPerWord != 8) {
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_WR_BITS_PER_WORD, ¶ms.bitsPerWord);
|
||||
if(retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initializeInterface: "
|
||||
"Could not write bits per word!");
|
||||
}
|
||||
}
|
||||
if (params.lsbFirst) {
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_WR_LSB_FIRST, ¶ms.lsbFirst);
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::initializeInterface: Setting LSB first failed");
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
if (params.bitsPerWord != 8) {
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_WR_BITS_PER_WORD, ¶ms.bitsPerWord);
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError(
|
||||
"SpiComIF::initializeInterface: "
|
||||
"Could not write bits per word!");
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::sendMessage(CookieIF *cookie, const uint8_t *sendData, size_t sendLen) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
ReturnValue_t SpiComIF::sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
|
||||
if(spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
if (spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
if(sendLen > spiCookie->getMaxBufferSize()) {
|
||||
if (sendLen > spiCookie->getMaxBufferSize()) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "SpiComIF::sendMessage: Too much data sent, send length " << sendLen <<
|
||||
"larger than maximum buffer length " << spiCookie->getMaxBufferSize() << std::endl;
|
||||
sif::warning << "SpiComIF::sendMessage: Too much data sent, send length " << sendLen
|
||||
<< "larger than maximum buffer length " << spiCookie->getMaxBufferSize()
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::sendMessage: Too much data sent, send length %lu larger "
|
||||
"than maximum buffer length %lu!\n", static_cast<unsigned long>(sendLen),
|
||||
static_cast<unsigned long>(spiCookie->getMaxBufferSize()));
|
||||
sif::printWarning(
|
||||
"SpiComIF::sendMessage: Too much data sent, send length %lu larger "
|
||||
"than maximum buffer length %lu!\n",
|
||||
static_cast<unsigned long>(sendLen),
|
||||
static_cast<unsigned long>(spiCookie->getMaxBufferSize()));
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
return DeviceCommunicationIF::TOO_MUCH_DATA;
|
||||
}
|
||||
return DeviceCommunicationIF::TOO_MUCH_DATA;
|
||||
}
|
||||
|
||||
if(spiCookie->getComIfMode() == spi::SpiComIfModes::REGULAR) {
|
||||
result = performRegularSendOperation(spiCookie, sendData, sendLen);
|
||||
if (spiCookie->getComIfMode() == spi::SpiComIfModes::REGULAR) {
|
||||
result = performRegularSendOperation(spiCookie, sendData, sendLen);
|
||||
} else if (spiCookie->getComIfMode() == spi::SpiComIfModes::CALLBACK) {
|
||||
spi::send_callback_function_t sendFunc = nullptr;
|
||||
void* funcArgs = nullptr;
|
||||
spiCookie->getCallback(&sendFunc, &funcArgs);
|
||||
if (sendFunc != nullptr) {
|
||||
result = sendFunc(this, spiCookie, sendData, sendLen, funcArgs);
|
||||
}
|
||||
else if(spiCookie->getComIfMode() == spi::SpiComIfModes::CALLBACK) {
|
||||
spi::send_callback_function_t sendFunc = nullptr;
|
||||
void* funcArgs = nullptr;
|
||||
spiCookie->getCallback(&sendFunc, &funcArgs);
|
||||
if(sendFunc != nullptr) {
|
||||
result = sendFunc(this, spiCookie, sendData, sendLen, funcArgs);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie *spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen) {
|
||||
address_t spiAddress = spiCookie->getSpiAddress();
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if(iter != spiDeviceMap.end()) {
|
||||
spiCookie->assignReadBuffer(iter->second.replyBuffer.data());
|
||||
}
|
||||
ReturnValue_t SpiComIF::performRegularSendOperation(SpiCookie* spiCookie, const uint8_t* sendData,
|
||||
size_t sendLen) {
|
||||
address_t spiAddress = spiCookie->getSpiAddress();
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if (iter != spiDeviceMap.end()) {
|
||||
spiCookie->assignReadBuffer(iter->second.replyBuffer.data());
|
||||
}
|
||||
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
int retval = 0;
|
||||
/* Prepare transfer */
|
||||
int fileDescriptor = 0;
|
||||
std::string device = spiCookie->getSpiDevice();
|
||||
UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::sendMessage");
|
||||
if(fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return OPENING_FILE_FAILED;
|
||||
}
|
||||
spi::SpiModes spiMode = spi::SpiModes::MODE_0;
|
||||
uint32_t spiSpeed = 0;
|
||||
spiCookie->getSpiParameters(spiMode, spiSpeed, nullptr);
|
||||
setSpiSpeedAndMode(fileDescriptor, spiMode, spiSpeed);
|
||||
spiCookie->assignWriteBuffer(sendData);
|
||||
spiCookie->setTransferSize(sendLen);
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
int retval = 0;
|
||||
/* Prepare transfer */
|
||||
int fileDescriptor = 0;
|
||||
std::string device = spiCookie->getSpiDevice();
|
||||
UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::sendMessage");
|
||||
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return OPENING_FILE_FAILED;
|
||||
}
|
||||
spi::SpiModes spiMode = spi::SpiModes::MODE_0;
|
||||
uint32_t spiSpeed = 0;
|
||||
spiCookie->getSpiParameters(spiMode, spiSpeed, nullptr);
|
||||
setSpiSpeedAndMode(fileDescriptor, spiMode, spiSpeed);
|
||||
spiCookie->assignWriteBuffer(sendData);
|
||||
spiCookie->setTransferSize(sendLen);
|
||||
|
||||
bool fullDuplex = spiCookie->isFullDuplex();
|
||||
gpioId_t gpioId = spiCookie->getChipSelectPin();
|
||||
bool fullDuplex = spiCookie->isFullDuplex();
|
||||
gpioId_t gpioId = spiCookie->getChipSelectPin();
|
||||
|
||||
/* Pull SPI CS low. For now, no support for active high given */
|
||||
if(gpioId != gpio::NO_GPIO) {
|
||||
result = spiMutex->lockMutex(timeoutType, timeoutMs);
|
||||
if (result != RETURN_OK) {
|
||||
/* Pull SPI CS low. For now, no support for active high given */
|
||||
if (gpioId != gpio::NO_GPIO) {
|
||||
result = spiMutex->lockMutex(timeoutType, timeoutMs);
|
||||
if (result != RETURN_OK) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "SpiComIF::sendMessage: Failed to lock mutex" << std::endl;
|
||||
sif::error << "SpiComIF::sendMessage: Failed to lock mutex" << std::endl;
|
||||
#else
|
||||
sif::printError("SpiComIF::sendMessage: Failed to lock mutex\n");
|
||||
sif::printError("SpiComIF::sendMessage: Failed to lock mutex\n");
|
||||
#endif
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
ReturnValue_t result = gpioComIF->pullLow(gpioId);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
ReturnValue_t result = gpioComIF->pullLow(gpioId);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 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;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::sendMessage: Pulling low CS pin failed");
|
||||
sif::printWarning("SpiComIF::sendMessage: Pulling low CS pin failed");
|
||||
#endif
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/* Execute transfer */
|
||||
if(fullDuplex) {
|
||||
/* Initiate a full duplex SPI transfer. */
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_MESSAGE(1), spiCookie->getTransferStructHandle());
|
||||
if(retval < 0) {
|
||||
utility::handleIoctlError("SpiComIF::sendMessage: ioctl error.");
|
||||
result = FULL_DUPLEX_TRANSFER_FAILED;
|
||||
}
|
||||
/* Execute transfer */
|
||||
if (fullDuplex) {
|
||||
/* Initiate a full duplex SPI transfer. */
|
||||
retval = ioctl(fileDescriptor, SPI_IOC_MESSAGE(1), spiCookie->getTransferStructHandle());
|
||||
if (retval < 0) {
|
||||
utility::handleIoctlError("SpiComIF::sendMessage: ioctl error.");
|
||||
result = FULL_DUPLEX_TRANSFER_FAILED;
|
||||
}
|
||||
#if FSFW_HAL_SPI_WIRETAPPING == 1
|
||||
performSpiWiretapping(spiCookie);
|
||||
performSpiWiretapping(spiCookie);
|
||||
#endif /* FSFW_LINUX_SPI_WIRETAPPING == 1 */
|
||||
}
|
||||
else {
|
||||
/* We write with a blocking half-duplex transfer here */
|
||||
if (write(fileDescriptor, sendData, sendLen) != static_cast<ssize_t>(sendLen)) {
|
||||
} else {
|
||||
/* We write with a blocking half-duplex transfer here */
|
||||
if (write(fileDescriptor, sendData, sendLen) != static_cast<ssize_t>(sendLen)) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 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;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::sendMessage: Half-Duplex write operation failed!\n");
|
||||
sif::printWarning("SpiComIF::sendMessage: Half-Duplex write operation failed!\n");
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
result = HALF_DUPLEX_TRANSFER_FAILED;
|
||||
}
|
||||
result = HALF_DUPLEX_TRANSFER_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
if(gpioId != gpio::NO_GPIO) {
|
||||
gpioComIF->pullHigh(gpioId);
|
||||
result = spiMutex->unlockMutex();
|
||||
if (result != RETURN_OK) {
|
||||
if (gpioId != gpio::NO_GPIO) {
|
||||
gpioComIF->pullHigh(gpioId);
|
||||
result = spiMutex->unlockMutex();
|
||||
if (result != RETURN_OK) {
|
||||
#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
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::getSendSuccess(CookieIF *cookie) {
|
||||
ReturnValue_t SpiComIF::getSendSuccess(CookieIF* cookie) { return HasReturnvaluesIF::RETURN_OK; }
|
||||
|
||||
ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF* cookie, size_t requestLen) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if (spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
if (spiCookie->isFullDuplex()) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
return performHalfDuplexReception(spiCookie);
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF *cookie, size_t requestLen) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if(spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
if(spiCookie->isFullDuplex()) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
return performHalfDuplexReception(spiCookie);
|
||||
}
|
||||
|
||||
|
||||
ReturnValue_t SpiComIF::performHalfDuplexReception(SpiCookie* spiCookie) {
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
std::string device = spiCookie->getSpiDevice();
|
||||
int fileDescriptor = 0;
|
||||
UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR,
|
||||
"SpiComIF::requestReceiveMessage");
|
||||
if(fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return OPENING_FILE_FAILED;
|
||||
}
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
std::string device = spiCookie->getSpiDevice();
|
||||
int fileDescriptor = 0;
|
||||
UnixFileGuard fileHelper(device, &fileDescriptor, O_RDWR, "SpiComIF::requestReceiveMessage");
|
||||
if (fileHelper.getOpenResult() != HasReturnvaluesIF::RETURN_OK) {
|
||||
return OPENING_FILE_FAILED;
|
||||
}
|
||||
|
||||
uint8_t* rxBuf = nullptr;
|
||||
size_t readSize = spiCookie->getCurrentTransferSize();
|
||||
result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
uint8_t* rxBuf = nullptr;
|
||||
size_t readSize = spiCookie->getCurrentTransferSize();
|
||||
result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
|
||||
gpioId_t gpioId = spiCookie->getChipSelectPin();
|
||||
if(gpioId != gpio::NO_GPIO) {
|
||||
result = spiMutex->lockMutex(timeoutType, timeoutMs);
|
||||
if (result != RETURN_OK) {
|
||||
gpioId_t gpioId = spiCookie->getChipSelectPin();
|
||||
if (gpioId != gpio::NO_GPIO) {
|
||||
result = spiMutex->lockMutex(timeoutType, timeoutMs);
|
||||
if (result != RETURN_OK) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "SpiComIF::getSendSuccess: Failed to lock mutex" << std::endl;
|
||||
sif::error << "SpiComIF::getSendSuccess: Failed to lock mutex" << std::endl;
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
gpioComIF->pullLow(gpioId);
|
||||
return result;
|
||||
}
|
||||
gpioComIF->pullLow(gpioId);
|
||||
}
|
||||
|
||||
if(read(fileDescriptor, rxBuf, readSize) != static_cast<ssize_t>(readSize)) {
|
||||
if (read(fileDescriptor, rxBuf, readSize) != static_cast<ssize_t>(readSize)) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "SpiComIF::sendMessage: Half-Duplex read operation failed!" << std::endl;
|
||||
sif::warning << "SpiComIF::sendMessage: Half-Duplex read operation failed!" << std::endl;
|
||||
#else
|
||||
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_VERBOSE_LEVEL >= 1 */
|
||||
result = HALF_DUPLEX_TRANSFER_FAILED;
|
||||
}
|
||||
result = HALF_DUPLEX_TRANSFER_FAILED;
|
||||
}
|
||||
|
||||
if(gpioId != gpio::NO_GPIO) {
|
||||
gpioComIF->pullHigh(gpioId);
|
||||
result = spiMutex->unlockMutex();
|
||||
if (result != RETURN_OK) {
|
||||
if (gpioId != gpio::NO_GPIO) {
|
||||
gpioComIF->pullHigh(gpioId);
|
||||
result = spiMutex->unlockMutex();
|
||||
if (result != RETURN_OK) {
|
||||
#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
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::readReceivedMessage(CookieIF *cookie, uint8_t **buffer, size_t *size) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if(spiCookie == nullptr) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
uint8_t* rxBuf = nullptr;
|
||||
ReturnValue_t result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
ReturnValue_t SpiComIF::readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if (spiCookie == nullptr) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
uint8_t* rxBuf = nullptr;
|
||||
ReturnValue_t result = getReadBuffer(spiCookie->getSpiAddress(), &rxBuf);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
|
||||
*buffer = rxBuf;
|
||||
*size = spiCookie->getCurrentTransferSize();
|
||||
spiCookie->setTransferSize(0);
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
*buffer = rxBuf;
|
||||
*size = spiCookie->getCurrentTransferSize();
|
||||
spiCookie->setTransferSize(0);
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
MutexIF* SpiComIF::getMutex(MutexIF::TimeoutType* timeoutType, uint32_t* timeoutMs) {
|
||||
if(timeoutType != nullptr) {
|
||||
*timeoutType = this->timeoutType;
|
||||
}
|
||||
if(timeoutMs != nullptr) {
|
||||
*timeoutMs = this->timeoutMs;
|
||||
}
|
||||
return spiMutex;
|
||||
if (timeoutType != nullptr) {
|
||||
*timeoutType = this->timeoutType;
|
||||
}
|
||||
if (timeoutMs != nullptr) {
|
||||
*timeoutMs = this->timeoutMs;
|
||||
}
|
||||
return spiMutex;
|
||||
}
|
||||
|
||||
void SpiComIF::performSpiWiretapping(SpiCookie* spiCookie) {
|
||||
if(spiCookie == nullptr) {
|
||||
return;
|
||||
}
|
||||
size_t dataLen = spiCookie->getTransferStructHandle()->len;
|
||||
uint8_t* dataPtr = reinterpret_cast<uint8_t*>(spiCookie->getTransferStructHandle()->tx_buf);
|
||||
if (spiCookie == nullptr) {
|
||||
return;
|
||||
}
|
||||
size_t dataLen = spiCookie->getTransferStructHandle()->len;
|
||||
uint8_t* dataPtr = reinterpret_cast<uint8_t*>(spiCookie->getTransferStructHandle()->tx_buf);
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::info << "Sent SPI data: " << std::endl;
|
||||
arrayprinter::print(dataPtr, dataLen, OutputType::HEX, false);
|
||||
sif::info << "Received SPI data: " << std::endl;
|
||||
sif::info << "Sent SPI data: " << std::endl;
|
||||
arrayprinter::print(dataPtr, dataLen, OutputType::HEX, false);
|
||||
sif::info << "Received SPI data: " << std::endl;
|
||||
#else
|
||||
sif::printInfo("Sent SPI data: \n");
|
||||
arrayprinter::print(dataPtr, dataLen, OutputType::HEX, false);
|
||||
sif::printInfo("Received SPI data: \n");
|
||||
sif::printInfo("Sent SPI data: \n");
|
||||
arrayprinter::print(dataPtr, dataLen, OutputType::HEX, false);
|
||||
sif::printInfo("Received SPI data: \n");
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
dataPtr = reinterpret_cast<uint8_t*>(spiCookie->getTransferStructHandle()->rx_buf);
|
||||
arrayprinter::print(dataPtr, dataLen, OutputType::HEX, false);
|
||||
dataPtr = reinterpret_cast<uint8_t*>(spiCookie->getTransferStructHandle()->rx_buf);
|
||||
arrayprinter::print(dataPtr, dataLen, OutputType::HEX, false);
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::getReadBuffer(address_t spiAddress, uint8_t** buffer) {
|
||||
if(buffer == nullptr) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
if (buffer == nullptr) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if(iter == spiDeviceMap.end()) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if (iter == spiDeviceMap.end()) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
*buffer = iter->second.replyBuffer.data();
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
*buffer = iter->second.replyBuffer.data();
|
||||
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) {
|
||||
int retval = ioctl(spiFd, SPI_IOC_WR_MODE, reinterpret_cast<uint8_t*>(&mode));
|
||||
if(retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI mode failed");
|
||||
}
|
||||
int retval = ioctl(spiFd, SPI_IOC_WR_MODE, reinterpret_cast<uint8_t*>(&mode));
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI mode failed");
|
||||
}
|
||||
|
||||
retval = ioctl(spiFd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
|
||||
if(retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI speed failed");
|
||||
}
|
||||
retval = ioctl(spiFd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Setting SPI speed failed");
|
||||
}
|
||||
// This updates the SPI clock default polarity. Only setting the mode does not update
|
||||
// the line state, which can be an issue on mode switches because the clock line will
|
||||
// switch the state after the chip select is pulled low
|
||||
clockUpdateTransfer.len = 0;
|
||||
retval = ioctl(spiFd, SPI_IOC_MESSAGE(1), &clockUpdateTransfer);
|
||||
if (retval != 0) {
|
||||
utility::handleIoctlError("SpiComIF::setSpiSpeedAndMode: Updating SPI default clock failed");
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +1,15 @@
|
||||
#ifndef LINUX_SPI_SPICOMIF_H_
|
||||
#define LINUX_SPI_SPICOMIF_H_
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "spiDefinitions.h"
|
||||
#include "returnvalues/classIds.h"
|
||||
#include "fsfw_hal/common/gpio/GpioIF.h"
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw/devicehandlers/DeviceCommunicationIF.h"
|
||||
#include "fsfw/objectmanager/SystemObject.h"
|
||||
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
#include "fsfw_hal/common/gpio/GpioIF.h"
|
||||
#include "returnvalues/classIds.h"
|
||||
#include "spiDefinitions.h"
|
||||
|
||||
class SpiCookie;
|
||||
|
||||
@ -21,71 +20,68 @@ class SpiCookie;
|
||||
* are contained in the SPI cookie.
|
||||
* @author R. Mueller
|
||||
*/
|
||||
class SpiComIF: public DeviceCommunicationIF, public SystemObject {
|
||||
public:
|
||||
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);
|
||||
class SpiComIF : public DeviceCommunicationIF, public SystemObject {
|
||||
public:
|
||||
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);
|
||||
SpiComIF(object_id_t objectId, GpioIF* gpioComIF);
|
||||
|
||||
ReturnValue_t initializeInterface(CookieIF * cookie) override;
|
||||
ReturnValue_t sendMessage(CookieIF *cookie,const uint8_t *sendData,
|
||||
size_t sendLen) override;
|
||||
ReturnValue_t getSendSuccess(CookieIF *cookie) override;
|
||||
ReturnValue_t requestReceiveMessage(CookieIF *cookie,
|
||||
size_t requestLen) override;
|
||||
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
|
||||
size_t *size) override;
|
||||
ReturnValue_t initializeInterface(CookieIF* cookie) override;
|
||||
ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override;
|
||||
ReturnValue_t getSendSuccess(CookieIF* cookie) override;
|
||||
ReturnValue_t requestReceiveMessage(CookieIF* cookie, size_t requestLen) override;
|
||||
ReturnValue_t readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) override;
|
||||
|
||||
/**
|
||||
* @brief This function returns the mutex which can be used to protect the spi bus when
|
||||
* the chip select must be driven from outside of the com if.
|
||||
*/
|
||||
MutexIF* getMutex(MutexIF::TimeoutType* timeoutType = nullptr, uint32_t* timeoutMs = nullptr);
|
||||
/**
|
||||
* @brief This function returns the mutex which can be used to protect the spi bus when
|
||||
* the chip select must be driven from outside of the com if.
|
||||
*/
|
||||
MutexIF* getMutex(MutexIF::TimeoutType* timeoutType = nullptr, uint32_t* timeoutMs = nullptr);
|
||||
|
||||
/**
|
||||
* Perform a regular send operation using Linux iotcl. This is public so it can be used
|
||||
* in functions like a user callback if special handling is only necessary for certain commands.
|
||||
* @param spiCookie
|
||||
* @param sendData
|
||||
* @param sendLen
|
||||
* @return
|
||||
*/
|
||||
ReturnValue_t performRegularSendOperation(SpiCookie* spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen);
|
||||
/**
|
||||
* Perform a regular send operation using Linux iotcl. This is public so it can be used
|
||||
* in functions like a user callback if special handling is only necessary for certain commands.
|
||||
* @param spiCookie
|
||||
* @param sendData
|
||||
* @param sendLen
|
||||
* @return
|
||||
*/
|
||||
ReturnValue_t performRegularSendOperation(SpiCookie* spiCookie, const uint8_t* sendData,
|
||||
size_t sendLen);
|
||||
|
||||
GpioIF* getGpioInterface();
|
||||
void setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed);
|
||||
void performSpiWiretapping(SpiCookie* spiCookie);
|
||||
GpioIF* getGpioInterface();
|
||||
void setSpiSpeedAndMode(int spiFd, spi::SpiModes mode, uint32_t speed);
|
||||
void performSpiWiretapping(SpiCookie* spiCookie);
|
||||
|
||||
ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer);
|
||||
ReturnValue_t getReadBuffer(address_t spiAddress, uint8_t** buffer);
|
||||
|
||||
private:
|
||||
private:
|
||||
struct SpiInstance {
|
||||
SpiInstance(size_t maxRecvSize) : replyBuffer(std::vector<uint8_t>(maxRecvSize)) {}
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
};
|
||||
|
||||
struct SpiInstance {
|
||||
SpiInstance(size_t maxRecvSize): replyBuffer(std::vector<uint8_t>(maxRecvSize)) {}
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
};
|
||||
GpioIF* gpioComIF = nullptr;
|
||||
|
||||
GpioIF* gpioComIF = nullptr;
|
||||
MutexIF* spiMutex = nullptr;
|
||||
MutexIF::TimeoutType timeoutType = MutexIF::TimeoutType::WAITING;
|
||||
uint32_t timeoutMs = 20;
|
||||
spi_ioc_transfer clockUpdateTransfer = {};
|
||||
|
||||
MutexIF* spiMutex = nullptr;
|
||||
MutexIF::TimeoutType timeoutType = MutexIF::TimeoutType::WAITING;
|
||||
uint32_t timeoutMs = 20;
|
||||
using SpiDeviceMap = std::unordered_map<address_t, SpiInstance>;
|
||||
using SpiDeviceMapIter = SpiDeviceMap::iterator;
|
||||
|
||||
using SpiDeviceMap = std::unordered_map<address_t, SpiInstance>;
|
||||
using SpiDeviceMapIter = SpiDeviceMap::iterator;
|
||||
SpiDeviceMap spiDeviceMap;
|
||||
|
||||
SpiDeviceMap spiDeviceMap;
|
||||
|
||||
ReturnValue_t performHalfDuplexReception(SpiCookie* spiCookie);
|
||||
ReturnValue_t performHalfDuplexReception(SpiCookie* spiCookie);
|
||||
};
|
||||
|
||||
#endif /* LINUX_SPI_SPICOMIF_H_ */
|
||||
|
@ -1,144 +1,109 @@
|
||||
#include "fsfw_hal/linux/spi/SpiCookie.h"
|
||||
|
||||
SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
|
||||
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed):
|
||||
SpiCookie(spi::SpiComIfModes::REGULAR, spiAddress, chipSelect, spiDev, maxSize, spiMode,
|
||||
spiSpeed, nullptr, nullptr) {
|
||||
|
||||
}
|
||||
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):
|
||||
SpiCookie(spiAddress, gpio::NO_GPIO, spiDev, maxSize, spiMode, spiSpeed) {
|
||||
}
|
||||
spi::SpiModes spiMode, uint32_t spiSpeed)
|
||||
: SpiCookie(spiAddress, gpio::NO_GPIO, spiDev, maxSize, spiMode, spiSpeed) {}
|
||||
|
||||
SpiCookie::SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
|
||||
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed,
|
||||
spi::send_callback_function_t callback, void *args):
|
||||
SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, spiDev, maxSize,
|
||||
spiMode, spiSpeed, callback, args) {
|
||||
}
|
||||
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed,
|
||||
spi::send_callback_function_t callback, void* args)
|
||||
: SpiCookie(spi::SpiComIfModes::CALLBACK, spiAddress, chipSelect, spiDev, maxSize, spiMode,
|
||||
spiSpeed, callback, args) {}
|
||||
|
||||
SpiCookie::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), chipSelectPin(chipSelect), spiDevice(spiDev),
|
||||
comIfMode(comIfMode), maxSize(maxSize), spiMode(spiMode), spiSpeed(spiSpeed),
|
||||
sendCallback(callback), callbackArgs(args) {
|
||||
}
|
||||
std::string spiDev, const size_t maxSize, spi::SpiModes spiMode,
|
||||
uint32_t spiSpeed, spi::send_callback_function_t callback, void* args)
|
||||
: spiAddress(spiAddress),
|
||||
chipSelectPin(chipSelect),
|
||||
spiDevice(spiDev),
|
||||
comIfMode(comIfMode),
|
||||
maxSize(maxSize),
|
||||
spiMode(spiMode),
|
||||
spiSpeed(spiSpeed),
|
||||
sendCallback(callback),
|
||||
callbackArgs(args) {}
|
||||
|
||||
spi::SpiComIfModes SpiCookie::getComIfMode() const {
|
||||
return this->comIfMode;
|
||||
}
|
||||
spi::SpiComIfModes SpiCookie::getComIfMode() const { return this->comIfMode; }
|
||||
|
||||
void SpiCookie::getSpiParameters(spi::SpiModes& spiMode, uint32_t& spiSpeed,
|
||||
UncommonParameters* parameters) const {
|
||||
spiMode = this->spiMode;
|
||||
spiSpeed = this->spiSpeed;
|
||||
UncommonParameters* parameters) const {
|
||||
spiMode = this->spiMode;
|
||||
spiSpeed = this->spiSpeed;
|
||||
|
||||
if(parameters != nullptr) {
|
||||
parameters->threeWireSpi = uncommonParameters.threeWireSpi;
|
||||
parameters->lsbFirst = uncommonParameters.lsbFirst;
|
||||
parameters->noCs = uncommonParameters.noCs;
|
||||
parameters->bitsPerWord = uncommonParameters.bitsPerWord;
|
||||
parameters->csHigh = uncommonParameters.csHigh;
|
||||
}
|
||||
if (parameters != nullptr) {
|
||||
parameters->threeWireSpi = uncommonParameters.threeWireSpi;
|
||||
parameters->lsbFirst = uncommonParameters.lsbFirst;
|
||||
parameters->noCs = uncommonParameters.noCs;
|
||||
parameters->bitsPerWord = uncommonParameters.bitsPerWord;
|
||||
parameters->csHigh = uncommonParameters.csHigh;
|
||||
}
|
||||
}
|
||||
|
||||
gpioId_t SpiCookie::getChipSelectPin() const {
|
||||
return chipSelectPin;
|
||||
}
|
||||
gpioId_t SpiCookie::getChipSelectPin() const { return chipSelectPin; }
|
||||
|
||||
size_t SpiCookie::getMaxBufferSize() const {
|
||||
return maxSize;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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; }
|
||||
|
||||
void SpiCookie::setNoCs(bool enable) {
|
||||
uncommonParameters.noCs = enable;
|
||||
}
|
||||
void SpiCookie::setNoCs(bool enable) { uncommonParameters.noCs = enable; }
|
||||
|
||||
void SpiCookie::setBitsPerWord(uint8_t bitsPerWord) {
|
||||
uncommonParameters.bitsPerWord = bitsPerWord;
|
||||
uncommonParameters.bitsPerWord = bitsPerWord;
|
||||
}
|
||||
|
||||
void SpiCookie::setCsHigh(bool enable) {
|
||||
uncommonParameters.csHigh = enable;
|
||||
}
|
||||
void SpiCookie::setCsHigh(bool enable) { uncommonParameters.csHigh = enable; }
|
||||
|
||||
void SpiCookie::activateCsDeselect(bool deselectCs, uint16_t delayUsecs) {
|
||||
spiTransferStruct.cs_change = deselectCs;
|
||||
spiTransferStruct.delay_usecs = delayUsecs;
|
||||
spiTransferStruct.cs_change = deselectCs;
|
||||
spiTransferStruct.delay_usecs = delayUsecs;
|
||||
}
|
||||
|
||||
void SpiCookie::assignReadBuffer(uint8_t* rx) {
|
||||
if(rx != nullptr) {
|
||||
spiTransferStruct.rx_buf = reinterpret_cast<__u64>(rx);
|
||||
}
|
||||
if (rx != nullptr) {
|
||||
spiTransferStruct.rx_buf = reinterpret_cast<__u64>(rx);
|
||||
}
|
||||
}
|
||||
|
||||
void SpiCookie::assignWriteBuffer(const uint8_t* tx) {
|
||||
if(tx != nullptr) {
|
||||
spiTransferStruct.tx_buf = reinterpret_cast<__u64>(tx);
|
||||
}
|
||||
if (tx != nullptr) {
|
||||
spiTransferStruct.tx_buf = reinterpret_cast<__u64>(tx);
|
||||
}
|
||||
}
|
||||
|
||||
void SpiCookie::setCallbackMode(spi::send_callback_function_t callback,
|
||||
void *args) {
|
||||
this->comIfMode = spi::SpiComIfModes::CALLBACK;
|
||||
this->sendCallback = callback;
|
||||
this->callbackArgs = args;
|
||||
void SpiCookie::setCallbackMode(spi::send_callback_function_t callback, void* args) {
|
||||
this->comIfMode = spi::SpiComIfModes::CALLBACK;
|
||||
this->sendCallback = callback;
|
||||
this->callbackArgs = args;
|
||||
}
|
||||
|
||||
void SpiCookie::setCallbackArgs(void *args) {
|
||||
this->callbackArgs = args;
|
||||
}
|
||||
void SpiCookie::setCallbackArgs(void* args) { this->callbackArgs = args; }
|
||||
|
||||
spi_ioc_transfer* SpiCookie::getTransferStructHandle() {
|
||||
return &spiTransferStruct;
|
||||
}
|
||||
spi_ioc_transfer* SpiCookie::getTransferStructHandle() { return &spiTransferStruct; }
|
||||
|
||||
void SpiCookie::setFullOrHalfDuplex(bool halfDuplex) {
|
||||
this->halfDuplex = halfDuplex;
|
||||
}
|
||||
void SpiCookie::setFullOrHalfDuplex(bool halfDuplex) { this->halfDuplex = halfDuplex; }
|
||||
|
||||
bool SpiCookie::isFullDuplex() const {
|
||||
return not this->halfDuplex;
|
||||
}
|
||||
bool SpiCookie::isFullDuplex() const { return not this->halfDuplex; }
|
||||
|
||||
void SpiCookie::setTransferSize(size_t transferSize) {
|
||||
spiTransferStruct.len = transferSize;
|
||||
}
|
||||
void SpiCookie::setTransferSize(size_t transferSize) { spiTransferStruct.len = transferSize; }
|
||||
|
||||
size_t SpiCookie::getCurrentTransferSize() const {
|
||||
return spiTransferStruct.len;
|
||||
}
|
||||
size_t SpiCookie::getCurrentTransferSize() const { return spiTransferStruct.len; }
|
||||
|
||||
void SpiCookie::setSpiSpeed(uint32_t newSpeed) {
|
||||
this->spiSpeed = newSpeed;
|
||||
}
|
||||
void SpiCookie::setSpiSpeed(uint32_t newSpeed) { this->spiSpeed = newSpeed; }
|
||||
|
||||
void SpiCookie::setSpiMode(spi::SpiModes newMode) {
|
||||
this->spiMode = newMode;
|
||||
}
|
||||
void SpiCookie::setSpiMode(spi::SpiModes newMode) { this->spiMode = newMode; }
|
||||
|
||||
void SpiCookie::getCallback(spi::send_callback_function_t *callback,
|
||||
void **args) {
|
||||
*callback = this->sendCallback;
|
||||
*args = this->callbackArgs;
|
||||
void SpiCookie::getCallback(spi::send_callback_function_t* callback, void** args) {
|
||||
*callback = this->sendCallback;
|
||||
*args = this->callbackArgs;
|
||||
}
|
||||
|
@ -1,13 +1,12 @@
|
||||
#ifndef LINUX_SPI_SPICOOKIE_H_
|
||||
#define LINUX_SPI_SPICOOKIE_H_
|
||||
|
||||
#include "spiDefinitions.h"
|
||||
#include "../../common/gpio/gpioDefinitions.h"
|
||||
|
||||
#include <fsfw/devicehandlers/CookieIF.h>
|
||||
|
||||
#include <linux/spi/spidev.h>
|
||||
|
||||
#include "../../common/gpio/gpioDefinitions.h"
|
||||
#include "spiDefinitions.h"
|
||||
|
||||
/**
|
||||
* @brief This cookie class is passed to the SPI communication interface
|
||||
* @details
|
||||
@ -19,165 +18,163 @@
|
||||
* special requirements like expander slave select switching (e.g. GPIO or I2C expander)
|
||||
* or special timing related requirements.
|
||||
*/
|
||||
class SpiCookie: public CookieIF {
|
||||
public:
|
||||
/**
|
||||
* 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
|
||||
* sent and received and the GPIO pin used to toggle the SPI slave select pin.
|
||||
* @param spiAddress
|
||||
* @param chipSelect Chip select. gpio::NO_GPIO can be used for hardware slave selects.
|
||||
* @param spiDev
|
||||
* @param maxSize
|
||||
*/
|
||||
SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev,
|
||||
const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed);
|
||||
|
||||
/**
|
||||
* Like constructor above, but without a dedicated GPIO CS. Can be used for hardware
|
||||
* slave select or if CS logic is performed with decoders.
|
||||
*/
|
||||
SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxReplySize,
|
||||
class SpiCookie : public CookieIF {
|
||||
public:
|
||||
/**
|
||||
* 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
|
||||
* sent and received and the GPIO pin used to toggle the SPI slave select pin.
|
||||
* @param spiAddress
|
||||
* @param chipSelect Chip select. gpio::NO_GPIO can be used for hardware slave selects.
|
||||
* @param spiDev
|
||||
* @param maxSize
|
||||
*/
|
||||
SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize,
|
||||
spi::SpiModes spiMode, uint32_t spiSpeed);
|
||||
|
||||
/**
|
||||
* Use the callback mode of the SPI communication interface. The user can pass the callback
|
||||
* function here or by using the setter function #setCallbackMode
|
||||
*/
|
||||
SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize,
|
||||
/**
|
||||
* Like constructor above, but without a dedicated GPIO CS. Can be used for hardware
|
||||
* slave select or if CS logic is performed with decoders.
|
||||
*/
|
||||
SpiCookie(address_t spiAddress, std::string spiDev, const size_t maxReplySize,
|
||||
spi::SpiModes spiMode, uint32_t spiSpeed);
|
||||
|
||||
/**
|
||||
* Use the callback mode of the SPI communication interface. The user can pass the callback
|
||||
* function here or by using the setter function #setCallbackMode
|
||||
*/
|
||||
SpiCookie(address_t spiAddress, gpioId_t chipSelect, std::string spiDev, const size_t maxSize,
|
||||
spi::SpiModes spiMode, uint32_t spiSpeed, spi::send_callback_function_t callback,
|
||||
void *args);
|
||||
void* args);
|
||||
|
||||
/**
|
||||
* Get the callback function
|
||||
* @param callback
|
||||
* @param args
|
||||
*/
|
||||
void getCallback(spi::send_callback_function_t* callback, void** args);
|
||||
/**
|
||||
* Get the callback function
|
||||
* @param callback
|
||||
* @param args
|
||||
*/
|
||||
void getCallback(spi::send_callback_function_t* callback, void** args);
|
||||
|
||||
address_t getSpiAddress() const;
|
||||
std::string getSpiDevice() const;
|
||||
gpioId_t getChipSelectPin() const;
|
||||
size_t getMaxBufferSize() const;
|
||||
address_t getSpiAddress() const;
|
||||
std::string getSpiDevice() const;
|
||||
gpioId_t getChipSelectPin() const;
|
||||
size_t getMaxBufferSize() const;
|
||||
|
||||
spi::SpiComIfModes getComIfMode() const;
|
||||
spi::SpiComIfModes getComIfMode() const;
|
||||
|
||||
/** Enables changing SPI speed at run-time */
|
||||
void setSpiSpeed(uint32_t newSpeed);
|
||||
/** Enables changing the SPI mode at run-time */
|
||||
void setSpiMode(spi::SpiModes newMode);
|
||||
/** Enables changing SPI speed at run-time */
|
||||
void setSpiSpeed(uint32_t newSpeed);
|
||||
/** Enables changing the SPI mode at run-time */
|
||||
void setSpiMode(spi::SpiModes newMode);
|
||||
|
||||
/**
|
||||
* Set the SPI to callback mode and assigns the user supplied callback and an argument
|
||||
* passed to the callback.
|
||||
* @param callback
|
||||
* @param args
|
||||
*/
|
||||
void setCallbackMode(spi::send_callback_function_t callback, void* args);
|
||||
/**
|
||||
* Set the SPI to callback mode and assigns the user supplied callback and an argument
|
||||
* passed to the callback.
|
||||
* @param callback
|
||||
* @param args
|
||||
*/
|
||||
void setCallbackMode(spi::send_callback_function_t callback, void* args);
|
||||
|
||||
/**
|
||||
* Can be used to set the callback arguments and a later point than initialization.
|
||||
* @param args
|
||||
*/
|
||||
void setCallbackArgs(void* args);
|
||||
/**
|
||||
* Can be used to set the callback arguments and a later point than initialization.
|
||||
* @param args
|
||||
*/
|
||||
void setCallbackArgs(void* args);
|
||||
|
||||
/**
|
||||
* True if SPI transfers should be performed in full duplex mode
|
||||
* @return
|
||||
*/
|
||||
bool isFullDuplex() const;
|
||||
/**
|
||||
* True if SPI transfers should be performed in full duplex mode
|
||||
* @return
|
||||
*/
|
||||
bool isFullDuplex() const;
|
||||
|
||||
/**
|
||||
* Set transfer type to full duplex or half duplex. Full duplex is the default setting,
|
||||
* ressembling common SPI hardware implementation with shift registers, where read and writes
|
||||
* happen simultaneosly.
|
||||
* @param fullDuplex
|
||||
*/
|
||||
void setFullOrHalfDuplex(bool halfDuplex);
|
||||
/**
|
||||
* Set transfer type to full duplex or half duplex. Full duplex is the default setting,
|
||||
* ressembling common SPI hardware implementation with shift registers, where read and writes
|
||||
* happen simultaneosly.
|
||||
* @param fullDuplex
|
||||
*/
|
||||
void setFullOrHalfDuplex(bool halfDuplex);
|
||||
|
||||
/**
|
||||
* This needs to be called to specify where the SPI driver writes to or reads from.
|
||||
* @param readLocation
|
||||
* @param writeLocation
|
||||
*/
|
||||
void assignReadBuffer(uint8_t* rx);
|
||||
void assignWriteBuffer(const uint8_t* tx);
|
||||
/**
|
||||
* Set size for the next transfer. Set to 0 for no transfer
|
||||
* @param transferSize
|
||||
*/
|
||||
void setTransferSize(size_t transferSize);
|
||||
size_t getCurrentTransferSize() const;
|
||||
/**
|
||||
* This needs to be called to specify where the SPI driver writes to or reads from.
|
||||
* @param readLocation
|
||||
* @param writeLocation
|
||||
*/
|
||||
void assignReadBuffer(uint8_t* rx);
|
||||
void assignWriteBuffer(const uint8_t* tx);
|
||||
/**
|
||||
* Set size for the next transfer. Set to 0 for no transfer
|
||||
* @param transferSize
|
||||
*/
|
||||
void setTransferSize(size_t transferSize);
|
||||
size_t getCurrentTransferSize() const;
|
||||
|
||||
struct UncommonParameters {
|
||||
uint8_t bitsPerWord = 8;
|
||||
bool noCs = false;
|
||||
bool csHigh = false;
|
||||
bool threeWireSpi = false;
|
||||
/* MSB first is more common */
|
||||
bool lsbFirst = false;
|
||||
};
|
||||
struct UncommonParameters {
|
||||
uint8_t bitsPerWord = 8;
|
||||
bool noCs = false;
|
||||
bool csHigh = false;
|
||||
bool threeWireSpi = false;
|
||||
/* MSB first is more common */
|
||||
bool lsbFirst = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Can be used to explicitely disable hardware chip select.
|
||||
* Some drivers like the Raspberry Pi Linux driver will not use hardware chip select by default
|
||||
* (see https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md)
|
||||
* @param enable
|
||||
*/
|
||||
void setNoCs(bool enable);
|
||||
void setThreeWireSpi(bool enable);
|
||||
void setLsbFirst(bool enable);
|
||||
void setCsHigh(bool enable);
|
||||
void setBitsPerWord(uint8_t bitsPerWord);
|
||||
/**
|
||||
* Can be used to explicitely disable hardware chip select.
|
||||
* Some drivers like the Raspberry Pi Linux driver will not use hardware chip select by default
|
||||
* (see https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md)
|
||||
* @param enable
|
||||
*/
|
||||
void setNoCs(bool enable);
|
||||
void setThreeWireSpi(bool enable);
|
||||
void setLsbFirst(bool enable);
|
||||
void setCsHigh(bool enable);
|
||||
void setBitsPerWord(uint8_t bitsPerWord);
|
||||
|
||||
void getSpiParameters(spi::SpiModes& spiMode, uint32_t& spiSpeed,
|
||||
UncommonParameters* parameters = nullptr) const;
|
||||
void getSpiParameters(spi::SpiModes& spiMode, uint32_t& spiSpeed,
|
||||
UncommonParameters* parameters = nullptr) const;
|
||||
|
||||
/**
|
||||
* See spidev.h cs_change and delay_usecs
|
||||
* @param deselectCs
|
||||
* @param delayUsecs
|
||||
*/
|
||||
void activateCsDeselect(bool deselectCs, uint16_t delayUsecs);
|
||||
/**
|
||||
* See spidev.h cs_change and delay_usecs
|
||||
* @param deselectCs
|
||||
* @param delayUsecs
|
||||
*/
|
||||
void activateCsDeselect(bool deselectCs, uint16_t delayUsecs);
|
||||
|
||||
spi_ioc_transfer* getTransferStructHandle();
|
||||
private:
|
||||
spi_ioc_transfer* getTransferStructHandle();
|
||||
|
||||
/**
|
||||
* Internal constructor which initializes every field
|
||||
* @param spiAddress
|
||||
* @param chipSelect
|
||||
* @param spiDev
|
||||
* @param maxSize
|
||||
* @param spiMode
|
||||
* @param spiSpeed
|
||||
* @param callback
|
||||
* @param args
|
||||
*/
|
||||
SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect,
|
||||
private:
|
||||
/**
|
||||
* Internal constructor which initializes every field
|
||||
* @param spiAddress
|
||||
* @param chipSelect
|
||||
* @param spiDev
|
||||
* @param maxSize
|
||||
* @param spiMode
|
||||
* @param spiSpeed
|
||||
* @param callback
|
||||
* @param args
|
||||
*/
|
||||
SpiCookie(spi::SpiComIfModes comIfMode, address_t spiAddress, gpioId_t chipSelect,
|
||||
std::string spiDev, const size_t maxSize, spi::SpiModes spiMode, uint32_t spiSpeed,
|
||||
spi::send_callback_function_t callback, void* args);
|
||||
|
||||
address_t spiAddress;
|
||||
gpioId_t chipSelectPin;
|
||||
std::string spiDevice;
|
||||
address_t spiAddress;
|
||||
gpioId_t chipSelectPin;
|
||||
std::string spiDevice;
|
||||
|
||||
spi::SpiComIfModes comIfMode;
|
||||
spi::SpiComIfModes comIfMode;
|
||||
|
||||
// Required for regular mode
|
||||
const size_t maxSize;
|
||||
spi::SpiModes spiMode;
|
||||
uint32_t spiSpeed;
|
||||
bool halfDuplex = false;
|
||||
// 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;
|
||||
// Required for callback mode
|
||||
spi::send_callback_function_t sendCallback = nullptr;
|
||||
void* callbackArgs = nullptr;
|
||||
|
||||
struct spi_ioc_transfer spiTransferStruct = {};
|
||||
UncommonParameters uncommonParameters;
|
||||
struct spi_ioc_transfer spiTransferStruct = {};
|
||||
UncommonParameters uncommonParameters;
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif /* LINUX_SPI_SPICOOKIE_H_ */
|
||||
|
@ -1,28 +1,25 @@
|
||||
#ifndef LINUX_SPI_SPIDEFINITONS_H_
|
||||
#define LINUX_SPI_SPIDEFINITONS_H_
|
||||
|
||||
#include "../../common/gpio/gpioDefinitions.h"
|
||||
#include "../../common/spi/spiCommon.h"
|
||||
|
||||
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
|
||||
#include <linux/spi/spidev.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "../../common/gpio/gpioDefinitions.h"
|
||||
#include "../../common/spi/spiCommon.h"
|
||||
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
|
||||
|
||||
class SpiCookie;
|
||||
class SpiComIF;
|
||||
|
||||
namespace spi {
|
||||
|
||||
enum SpiComIfModes {
|
||||
REGULAR,
|
||||
CALLBACK
|
||||
};
|
||||
enum SpiComIfModes { REGULAR, CALLBACK };
|
||||
|
||||
using send_callback_function_t = ReturnValue_t (*)(SpiComIF* comIf, SpiCookie* cookie,
|
||||
const uint8_t* sendData, size_t sendLen,
|
||||
void* args);
|
||||
|
||||
using send_callback_function_t = ReturnValue_t (*) (SpiComIF* comIf, SpiCookie *cookie,
|
||||
const uint8_t *sendData, size_t sendLen, void* args);
|
||||
|
||||
}
|
||||
} // namespace spi
|
||||
|
||||
#endif /* LINUX_SPI_SPIDEFINITONS_H_ */
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,13 +1,14 @@
|
||||
#ifndef BSP_Q7S_COMIF_UARTCOMIF_H_
|
||||
#define BSP_Q7S_COMIF_UARTCOMIF_H_
|
||||
|
||||
#include "UartCookie.h"
|
||||
#include <fsfw/objectmanager/SystemObject.h>
|
||||
#include <fsfw/devicehandlers/DeviceCommunicationIF.h>
|
||||
#include <fsfw/objectmanager/SystemObject.h>
|
||||
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "UartCookie.h"
|
||||
|
||||
/**
|
||||
* @brief This is the communication interface to access serial ports on linux based operating
|
||||
* systems.
|
||||
@ -17,109 +18,104 @@
|
||||
*
|
||||
* @author J. Meier
|
||||
*/
|
||||
class UartComIF: public DeviceCommunicationIF, public SystemObject {
|
||||
public:
|
||||
static constexpr uint8_t uartRetvalId = CLASS_ID::HAL_UART;
|
||||
class UartComIF : public DeviceCommunicationIF, public SystemObject {
|
||||
public:
|
||||
static constexpr uint8_t uartRetvalId = CLASS_ID::HAL_UART;
|
||||
|
||||
static constexpr ReturnValue_t UART_READ_FAILURE =
|
||||
HasReturnvaluesIF::makeReturnCode(uartRetvalId, 1);
|
||||
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);
|
||||
static constexpr ReturnValue_t UART_READ_FAILURE =
|
||||
HasReturnvaluesIF::makeReturnCode(uartRetvalId, 1);
|
||||
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);
|
||||
|
||||
UartComIF(object_id_t objectId);
|
||||
UartComIF(object_id_t objectId);
|
||||
|
||||
virtual ~UartComIF();
|
||||
virtual ~UartComIF();
|
||||
|
||||
ReturnValue_t initializeInterface(CookieIF * cookie) override;
|
||||
ReturnValue_t sendMessage(CookieIF *cookie,const uint8_t *sendData,
|
||||
size_t sendLen) override;
|
||||
ReturnValue_t getSendSuccess(CookieIF *cookie) override;
|
||||
ReturnValue_t requestReceiveMessage(CookieIF *cookie,
|
||||
size_t requestLen) override;
|
||||
ReturnValue_t readReceivedMessage(CookieIF *cookie, uint8_t **buffer,
|
||||
size_t *size) override;
|
||||
ReturnValue_t initializeInterface(CookieIF* cookie) override;
|
||||
ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData, size_t sendLen) override;
|
||||
ReturnValue_t getSendSuccess(CookieIF* cookie) override;
|
||||
ReturnValue_t requestReceiveMessage(CookieIF* cookie, size_t requestLen) override;
|
||||
ReturnValue_t readReceivedMessage(CookieIF* cookie, uint8_t** buffer, size_t* size) override;
|
||||
|
||||
/**
|
||||
* @brief This function discards all data received but not read in the UART buffer.
|
||||
*/
|
||||
ReturnValue_t flushUartRxBuffer(CookieIF *cookie);
|
||||
/**
|
||||
* @brief This function discards all data received but not read in the UART buffer.
|
||||
*/
|
||||
ReturnValue_t flushUartRxBuffer(CookieIF* cookie);
|
||||
|
||||
/**
|
||||
* @brief This function discards all data in the transmit buffer of the UART driver.
|
||||
*/
|
||||
ReturnValue_t flushUartTxBuffer(CookieIF *cookie);
|
||||
/**
|
||||
* @brief This function discards all data in the transmit buffer of the UART driver.
|
||||
*/
|
||||
ReturnValue_t flushUartTxBuffer(CookieIF* cookie);
|
||||
|
||||
/**
|
||||
* @brief This function discards both data in the transmit and receive buffer of the UART.
|
||||
*/
|
||||
ReturnValue_t flushUartTxAndRxBuf(CookieIF *cookie);
|
||||
/**
|
||||
* @brief This function discards both data in the transmit and receive buffer of the UART.
|
||||
*/
|
||||
ReturnValue_t flushUartTxAndRxBuf(CookieIF* cookie);
|
||||
|
||||
private:
|
||||
private:
|
||||
using UartDeviceFile_t = std::string;
|
||||
|
||||
using UartDeviceFile_t = std::string;
|
||||
struct UartElements {
|
||||
int fileDescriptor;
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
/** Number of bytes read will be written to this variable */
|
||||
size_t replyLen;
|
||||
};
|
||||
|
||||
struct UartElements {
|
||||
int fileDescriptor;
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
/** Number of bytes read will be written to this variable */
|
||||
size_t replyLen;
|
||||
};
|
||||
using UartDeviceMap = std::unordered_map<UartDeviceFile_t, UartElements>;
|
||||
using UartDeviceMapIter = UartDeviceMap::iterator;
|
||||
|
||||
using UartDeviceMap = std::unordered_map<UartDeviceFile_t, UartElements>;
|
||||
using UartDeviceMapIter = UartDeviceMap::iterator;
|
||||
/**
|
||||
* The uart devie map stores informations of initialized uart ports.
|
||||
*/
|
||||
UartDeviceMap uartDeviceMap;
|
||||
|
||||
/**
|
||||
* The uart devie map stores informations of initialized uart ports.
|
||||
*/
|
||||
UartDeviceMap uartDeviceMap;
|
||||
/**
|
||||
* @brief This function opens and configures a uart device by using the information stored
|
||||
* in the uart cookie.
|
||||
* @param uartCookie Pointer to uart cookie with information about the uart. Contains the
|
||||
* uart device file, baudrate, parity, stopbits etc.
|
||||
* @return The file descriptor of the configured uart.
|
||||
*/
|
||||
int configureUartPort(UartCookie* uartCookie);
|
||||
|
||||
/**
|
||||
* @brief This function opens and configures a uart device by using the information stored
|
||||
* in the uart cookie.
|
||||
* @param uartCookie Pointer to uart cookie with information about the uart. Contains the
|
||||
* uart device file, baudrate, parity, stopbits etc.
|
||||
* @return The file descriptor of the configured uart.
|
||||
*/
|
||||
int configureUartPort(UartCookie* 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);
|
||||
|
||||
/**
|
||||
* @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);
|
||||
|
||||
void setStopBitOptions(struct termios* options, UartCookie* uartCookie);
|
||||
/**
|
||||
* @brief This function sets options which are not configurable by the uartCookie.
|
||||
*/
|
||||
void setFixedOptions(struct termios* options);
|
||||
|
||||
/**
|
||||
* @brief This function sets options which are not configurable by the uartCookie.
|
||||
*/
|
||||
void setFixedOptions(struct termios* options);
|
||||
/**
|
||||
* @brief With this function the datasize settings are added to the termios options struct.
|
||||
*/
|
||||
void setDatasizeOptions(struct termios* options, UartCookie* uartCookie);
|
||||
|
||||
/**
|
||||
* @brief With this function the datasize settings are added to the termios options struct.
|
||||
*/
|
||||
void setDatasizeOptions(struct termios* options, UartCookie* uartCookie);
|
||||
/**
|
||||
* @brief This functions adds the baudrate specified in the uartCookie to the termios options
|
||||
* struct.
|
||||
*/
|
||||
void configureBaudrate(struct termios* options, UartCookie* uartCookie);
|
||||
|
||||
/**
|
||||
* @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);
|
||||
ReturnValue_t handleNoncanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
|
||||
size_t requestLen);
|
||||
void setUartMode(struct termios* options, UartCookie& uartCookie);
|
||||
|
||||
ReturnValue_t handleCanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
|
||||
size_t requestLen);
|
||||
ReturnValue_t handleNoncanonicalRead(UartCookie& uartCookie, UartDeviceMapIter& iter,
|
||||
size_t requestLen);
|
||||
};
|
||||
|
||||
#endif /* BSP_Q7S_COMIF_UARTCOMIF_H_ */
|
||||
|
@ -1,97 +1,65 @@
|
||||
#include "fsfw_hal/linux/uart/UartCookie.h"
|
||||
#include "UartCookie.h"
|
||||
|
||||
#include <fsfw/serviceinterface/ServiceInterface.h>
|
||||
#include <fsfw/serviceinterface.h>
|
||||
|
||||
UartCookie::UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode,
|
||||
uint32_t baudrate, size_t maxReplyLen):
|
||||
handlerId(handlerId), deviceFile(deviceFile), uartMode(uartMode),
|
||||
baudrate(baudrate), maxReplyLen(maxReplyLen) {
|
||||
}
|
||||
uint32_t baudrate, size_t maxReplyLen)
|
||||
: handlerId(handlerId),
|
||||
deviceFile(deviceFile),
|
||||
uartMode(uartMode),
|
||||
baudrate(baudrate),
|
||||
maxReplyLen(maxReplyLen) {}
|
||||
|
||||
UartCookie::~UartCookie() {}
|
||||
|
||||
uint32_t UartCookie::getBaudrate() const {
|
||||
return baudrate;
|
||||
}
|
||||
uint32_t UartCookie::getBaudrate() const { return baudrate; }
|
||||
|
||||
size_t UartCookie::getMaxReplyLen() const {
|
||||
return maxReplyLen;
|
||||
}
|
||||
size_t UartCookie::getMaxReplyLen() const { return maxReplyLen; }
|
||||
|
||||
std::string UartCookie::getDeviceFile() const {
|
||||
return deviceFile;
|
||||
}
|
||||
std::string UartCookie::getDeviceFile() const { return deviceFile; }
|
||||
|
||||
void UartCookie::setParityOdd() {
|
||||
parity = Parity::ODD;
|
||||
}
|
||||
void UartCookie::setParityOdd() { parity = Parity::ODD; }
|
||||
|
||||
void UartCookie::setParityEven() {
|
||||
parity = Parity::EVEN;
|
||||
}
|
||||
void UartCookie::setParityEven() { parity = Parity::EVEN; }
|
||||
|
||||
Parity UartCookie::getParity() const {
|
||||
return parity;
|
||||
}
|
||||
Parity UartCookie::getParity() const { return parity; }
|
||||
|
||||
void UartCookie::setBitsPerWord(uint8_t bitsPerWord_) {
|
||||
switch(bitsPerWord_) {
|
||||
switch (bitsPerWord_) {
|
||||
case 5:
|
||||
case 6:
|
||||
case 7:
|
||||
case 8:
|
||||
break;
|
||||
break;
|
||||
default:
|
||||
sif::debug << "UartCookie::setBitsPerWord: Invalid bits per word specified" << std::endl;
|
||||
return;
|
||||
}
|
||||
bitsPerWord = bitsPerWord_;
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::debug << "UartCookie::setBitsPerWord: Invalid bits per word specified" << std::endl;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
bitsPerWord = bitsPerWord_;
|
||||
}
|
||||
|
||||
uint8_t UartCookie::getBitsPerWord() const {
|
||||
return bitsPerWord;
|
||||
}
|
||||
uint8_t UartCookie::getBitsPerWord() const { return bitsPerWord; }
|
||||
|
||||
StopBits UartCookie::getStopBits() const {
|
||||
return stopBits;
|
||||
}
|
||||
StopBits UartCookie::getStopBits() const { return stopBits; }
|
||||
|
||||
void UartCookie::setTwoStopBits() {
|
||||
stopBits = StopBits::TWO_STOP_BITS;
|
||||
}
|
||||
void UartCookie::setTwoStopBits() { stopBits = StopBits::TWO_STOP_BITS; }
|
||||
|
||||
void UartCookie::setOneStopBit() {
|
||||
stopBits = StopBits::ONE_STOP_BIT;
|
||||
}
|
||||
void UartCookie::setOneStopBit() { stopBits = StopBits::ONE_STOP_BIT; }
|
||||
|
||||
UartModes UartCookie::getUartMode() const {
|
||||
return uartMode;
|
||||
}
|
||||
UartModes UartCookie::getUartMode() const { return uartMode; }
|
||||
|
||||
void UartCookie::setReadCycles(uint8_t readCycles) {
|
||||
this->readCycles = readCycles;
|
||||
}
|
||||
void UartCookie::setReadCycles(uint8_t readCycles) { this->readCycles = readCycles; }
|
||||
|
||||
void UartCookie::setToFlushInput(bool enable) {
|
||||
this->flushInput = enable;
|
||||
}
|
||||
void UartCookie::setToFlushInput(bool enable) { this->flushInput = enable; }
|
||||
|
||||
uint8_t UartCookie::getReadCycles() const {
|
||||
return readCycles;
|
||||
}
|
||||
uint8_t UartCookie::getReadCycles() const { return readCycles; }
|
||||
|
||||
bool UartCookie::getInputShouldBeFlushed() {
|
||||
return this->flushInput;
|
||||
}
|
||||
bool UartCookie::getInputShouldBeFlushed() { return this->flushInput; }
|
||||
|
||||
object_id_t UartCookie::getHandlerId() const {
|
||||
return this->handlerId;
|
||||
}
|
||||
object_id_t UartCookie::getHandlerId() const { return this->handlerId; }
|
||||
|
||||
void UartCookie::setNoFixedSizeReply() {
|
||||
replySizeFixed = false;
|
||||
}
|
||||
void UartCookie::setNoFixedSizeReply() { replySizeFixed = false; }
|
||||
|
||||
bool UartCookie::isReplySizeFixed() {
|
||||
return replySizeFixed;
|
||||
}
|
||||
bool UartCookie::isReplySizeFixed() { return replySizeFixed; }
|
||||
|
@ -6,21 +6,11 @@
|
||||
|
||||
#include <string>
|
||||
|
||||
enum class Parity {
|
||||
NONE,
|
||||
EVEN,
|
||||
ODD
|
||||
};
|
||||
enum class Parity { NONE, EVEN, ODD };
|
||||
|
||||
enum class StopBits {
|
||||
ONE_STOP_BIT,
|
||||
TWO_STOP_BITS
|
||||
};
|
||||
enum class StopBits { ONE_STOP_BIT, TWO_STOP_BITS };
|
||||
|
||||
enum class UartModes {
|
||||
CANONICAL,
|
||||
NON_CANONICAL
|
||||
};
|
||||
enum class UartModes { CANONICAL, NON_CANONICAL };
|
||||
|
||||
/**
|
||||
* @brief Cookie for the UartComIF. There are many options available to configure the UART driver.
|
||||
@ -29,93 +19,91 @@ enum class UartModes {
|
||||
*
|
||||
* @author J. Meier
|
||||
*/
|
||||
class UartCookie: public CookieIF {
|
||||
public:
|
||||
class UartCookie : public CookieIF {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the uart cookie.
|
||||
* @param deviceFile The device file specifying the uart to use, e.g. "/dev/ttyPS1"
|
||||
* @param uartMode Specify the UART mode. The canonical mode should be used if the
|
||||
* messages are separated by a delimited character like '\n'. See the
|
||||
* termios documentation for more information
|
||||
* @param baudrate The baudrate to use for input and output. Possible Baudrates are: 50,
|
||||
* 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, B19200,
|
||||
* 38400, 57600, 115200, 230400, 460800
|
||||
* @param maxReplyLen The maximum size an object using this cookie expects
|
||||
* @details
|
||||
* Default configuration: No parity
|
||||
* 8 databits (number of bits transfered with one uart frame)
|
||||
* One stop bit
|
||||
*/
|
||||
UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode, uint32_t baudrate,
|
||||
size_t maxReplyLen);
|
||||
|
||||
/**
|
||||
* @brief Constructor for the uart cookie.
|
||||
* @param deviceFile The device file specifying the uart to use, e.g. "/dev/ttyPS1"
|
||||
* @param uartMode Specify the UART mode. The canonical mode should be used if the
|
||||
* messages are separated by a delimited character like '\n'. See the
|
||||
* termios documentation for more information
|
||||
* @param baudrate The baudrate to use for input and output. Possible Baudrates are: 50,
|
||||
* 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, B19200,
|
||||
* 38400, 57600, 115200, 230400, 460800
|
||||
* @param maxReplyLen The maximum size an object using this cookie expects
|
||||
* @details
|
||||
* Default configuration: No parity
|
||||
* 8 databits (number of bits transfered with one uart frame)
|
||||
* One stop bit
|
||||
*/
|
||||
UartCookie(object_id_t handlerId, std::string deviceFile, UartModes uartMode,
|
||||
uint32_t baudrate, size_t maxReplyLen);
|
||||
virtual ~UartCookie();
|
||||
|
||||
virtual ~UartCookie();
|
||||
uint32_t getBaudrate() const;
|
||||
size_t getMaxReplyLen() const;
|
||||
std::string getDeviceFile() const;
|
||||
Parity getParity() const;
|
||||
uint8_t getBitsPerWord() const;
|
||||
StopBits getStopBits() const;
|
||||
UartModes getUartMode() const;
|
||||
object_id_t getHandlerId() const;
|
||||
|
||||
uint32_t getBaudrate() const;
|
||||
size_t getMaxReplyLen() const;
|
||||
std::string getDeviceFile() const;
|
||||
Parity getParity() const;
|
||||
uint8_t getBitsPerWord() const;
|
||||
StopBits getStopBits() const;
|
||||
UartModes getUartMode() const;
|
||||
object_id_t getHandlerId() const;
|
||||
/**
|
||||
* The UART ComIF will only perform a specified number of read cycles for the canonical mode.
|
||||
* The user can specify how many of those read cycles are performed for one device handler
|
||||
* communication cycle. An example use-case would be to read all available GPS NMEA strings
|
||||
* at once.
|
||||
* @param readCycles
|
||||
*/
|
||||
void setReadCycles(uint8_t readCycles);
|
||||
uint8_t getReadCycles() const;
|
||||
|
||||
/**
|
||||
* The UART ComIF will only perform a specified number of read cycles for the canonical mode.
|
||||
* The user can specify how many of those read cycles are performed for one device handler
|
||||
* communication cycle. An example use-case would be to read all available GPS NMEA strings
|
||||
* at once.
|
||||
* @param readCycles
|
||||
*/
|
||||
void setReadCycles(uint8_t readCycles);
|
||||
uint8_t getReadCycles() const;
|
||||
/**
|
||||
* Allows to flush the data which was received but has not been read yet. This is useful
|
||||
* to discard obsolete data at software startup.
|
||||
*/
|
||||
void setToFlushInput(bool enable);
|
||||
bool getInputShouldBeFlushed();
|
||||
|
||||
/**
|
||||
* Allows to flush the data which was received but has not been read yet. This is useful
|
||||
* to discard obsolete data at software startup.
|
||||
*/
|
||||
void setToFlushInput(bool enable);
|
||||
bool getInputShouldBeFlushed();
|
||||
/**
|
||||
* Functions two enable parity checking.
|
||||
*/
|
||||
void setParityOdd();
|
||||
void setParityEven();
|
||||
|
||||
/**
|
||||
* Functions two enable parity checking.
|
||||
*/
|
||||
void setParityOdd();
|
||||
void setParityEven();
|
||||
/**
|
||||
* Function two set number of bits per UART frame.
|
||||
*/
|
||||
void setBitsPerWord(uint8_t bitsPerWord_);
|
||||
|
||||
/**
|
||||
* Function two set number of bits per UART frame.
|
||||
*/
|
||||
void setBitsPerWord(uint8_t bitsPerWord_);
|
||||
/**
|
||||
* Function to specify the number of stopbits.
|
||||
*/
|
||||
void setTwoStopBits();
|
||||
void setOneStopBit();
|
||||
|
||||
/**
|
||||
* Function to specify the number of stopbits.
|
||||
*/
|
||||
void setTwoStopBits();
|
||||
void setOneStopBit();
|
||||
/**
|
||||
* Calling this function prevents the UartComIF to return failed if not all requested bytes
|
||||
* could be read. This is required by a device handler when the size of a reply is not known.
|
||||
*/
|
||||
void setNoFixedSizeReply();
|
||||
|
||||
/**
|
||||
* Calling this function prevents the UartComIF to return failed if not all requested bytes
|
||||
* could be read. This is required by a device handler when the size of a reply is not known.
|
||||
*/
|
||||
void setNoFixedSizeReply();
|
||||
bool isReplySizeFixed();
|
||||
|
||||
bool isReplySizeFixed();
|
||||
|
||||
private:
|
||||
|
||||
const object_id_t handlerId;
|
||||
std::string deviceFile;
|
||||
const UartModes uartMode;
|
||||
bool flushInput = false;
|
||||
uint32_t baudrate;
|
||||
size_t maxReplyLen = 0;
|
||||
Parity parity = Parity::NONE;
|
||||
uint8_t bitsPerWord = 8;
|
||||
uint8_t readCycles = 1;
|
||||
StopBits stopBits = StopBits::ONE_STOP_BIT;
|
||||
bool replySizeFixed = true;
|
||||
private:
|
||||
const object_id_t handlerId;
|
||||
std::string deviceFile;
|
||||
const UartModes uartMode;
|
||||
bool flushInput = false;
|
||||
uint32_t baudrate;
|
||||
size_t maxReplyLen = 0;
|
||||
Parity parity = Parity::NONE;
|
||||
uint8_t bitsPerWord = 8;
|
||||
uint8_t readCycles = 1;
|
||||
StopBits stopBits = StopBits::ONE_STOP_BIT;
|
||||
bool replySizeFixed = true;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
3
hal/src/fsfw_hal/linux/uio/CMakeLists.txt
Normal file
3
hal/src/fsfw_hal/linux/uio/CMakeLists.txt
Normal file
@ -0,0 +1,3 @@
|
||||
target_sources(${LIB_FSFW_NAME} PUBLIC
|
||||
UioMapper.cpp
|
||||
)
|
86
hal/src/fsfw_hal/linux/uio/UioMapper.cpp
Normal file
86
hal/src/fsfw_hal/linux/uio/UioMapper.cpp
Normal file
@ -0,0 +1,86 @@
|
||||
#include "UioMapper.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
#include "fsfw/serviceinterface.h"
|
||||
|
||||
const char UioMapper::UIO_PATH_PREFIX[] = "/sys/class/uio/";
|
||||
const char UioMapper::MAP_SUBSTR[] = "/maps/map";
|
||||
const char UioMapper::SIZE_FILE_PATH[] = "/size";
|
||||
|
||||
UioMapper::UioMapper(std::string uioFile, int mapNum) : uioFile(uioFile), mapNum(mapNum) {}
|
||||
|
||||
UioMapper::~UioMapper() {}
|
||||
|
||||
ReturnValue_t UioMapper::getMappedAdress(uint32_t** address, Permissions permissions) {
|
||||
ReturnValue_t result = HasReturnvaluesIF::RETURN_OK;
|
||||
int fd = open(uioFile.c_str(), O_RDWR);
|
||||
if (fd < 1) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "PtmeAxiConfig::initialize: Invalid UIO device file" << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
size_t size = 0;
|
||||
result = getMapSize(&size);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
*address = static_cast<uint32_t*>(
|
||||
mmap(NULL, size, static_cast<int>(permissions), MAP_SHARED, fd, mapNum * getpagesize()));
|
||||
|
||||
if (*address == MAP_FAILED) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "UioMapper::getMappedAdress: Failed to map physical address of uio device "
|
||||
<< uioFile.c_str() << " and map" << static_cast<int>(mapNum) << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t UioMapper::getMapSize(size_t* size) {
|
||||
std::stringstream namestream;
|
||||
namestream << UIO_PATH_PREFIX << uioFile.substr(5, std::string::npos) << MAP_SUBSTR << mapNum
|
||||
<< SIZE_FILE_PATH;
|
||||
FILE* fp;
|
||||
fp = fopen(namestream.str().c_str(), "r");
|
||||
if (fp == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "UioMapper::getMapSize: Failed to open file " << namestream.str() << std::endl;
|
||||
#endif
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
char hexstring[SIZE_HEX_STRING] = "";
|
||||
int items = fscanf(fp, "%s", hexstring);
|
||||
if (items != 1) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "UioMapper::getMapSize: Failed with error code " << errno
|
||||
<< " to read size "
|
||||
"string from file "
|
||||
<< namestream.str() << std::endl;
|
||||
#endif
|
||||
fclose(fp);
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
uint32_t sizeTmp = 0;
|
||||
items = sscanf(hexstring, "%x", &sizeTmp);
|
||||
if (size != nullptr) {
|
||||
*size = sizeTmp;
|
||||
}
|
||||
if (items != 1) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "UioMapper::getMapSize: Failed with error code " << errno << "to convert "
|
||||
<< "size of map" << mapNum << " to integer" << std::endl;
|
||||
#endif
|
||||
fclose(fp);
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
fclose(fp);
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
58
hal/src/fsfw_hal/linux/uio/UioMapper.h
Normal file
58
hal/src/fsfw_hal/linux/uio/UioMapper.h
Normal file
@ -0,0 +1,58 @@
|
||||
#ifndef FSFW_HAL_SRC_FSFW_HAL_LINUX_UIO_UIOMAPPER_H_
|
||||
#define FSFW_HAL_SRC_FSFW_HAL_LINUX_UIO_UIOMAPPER_H_
|
||||
|
||||
#include <sys/mman.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
|
||||
|
||||
/**
|
||||
* @brief Class to help opening uio device files and mapping the physical addresses into the user
|
||||
* address space.
|
||||
*
|
||||
* @author J. Meier
|
||||
*/
|
||||
class UioMapper {
|
||||
public:
|
||||
enum class Permissions : int {
|
||||
READ_ONLY = PROT_READ,
|
||||
WRITE_ONLY = PROT_WRITE,
|
||||
READ_WRITE = PROT_READ | PROT_WRITE
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Constructor
|
||||
*
|
||||
* @param uioFile The device file of the uiO to open
|
||||
* @param uioMap Number of memory map. Most UIO drivers have only one map which has than 0.
|
||||
*/
|
||||
UioMapper(std::string uioFile, int mapNum = 0);
|
||||
virtual ~UioMapper();
|
||||
|
||||
/**
|
||||
* @brief Maps the physical address into user address space and returns the mapped address
|
||||
*
|
||||
* @address The mapped user space address
|
||||
* @permissions Specifies the read/write permissions of the address region
|
||||
*/
|
||||
ReturnValue_t getMappedAdress(uint32_t** address, Permissions permissions);
|
||||
|
||||
private:
|
||||
static const char UIO_PATH_PREFIX[];
|
||||
static const char MAP_SUBSTR[];
|
||||
static const char SIZE_FILE_PATH[];
|
||||
static constexpr int SIZE_HEX_STRING = 10;
|
||||
|
||||
std::string uioFile;
|
||||
int mapNum = 0;
|
||||
|
||||
/**
|
||||
* @brief Reads the map size from the associated sysfs size file
|
||||
*
|
||||
* @param size The read map size
|
||||
*/
|
||||
ReturnValue_t getMapSize(size_t* size);
|
||||
};
|
||||
|
||||
#endif /* FSFW_HAL_SRC_FSFW_HAL_LINUX_UIO_UIOMAPPER_H_ */
|
@ -1,26 +1,23 @@
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
#include "fsfw_hal/linux/utility.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
|
||||
#include "fsfw/FSFW.h"
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
|
||||
void utility::handleIoctlError(const char* const customPrintout) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
if(customPrintout != nullptr) {
|
||||
sif::warning << customPrintout << std::endl;
|
||||
}
|
||||
sif::warning << "handleIoctlError: Error code " << errno << ", "<< strerror(errno) <<
|
||||
std::endl;
|
||||
if (customPrintout != nullptr) {
|
||||
sif::warning << customPrintout << std::endl;
|
||||
}
|
||||
sif::warning << "handleIoctlError: Error code " << errno << ", " << strerror(errno) << std::endl;
|
||||
#else
|
||||
if(customPrintout != nullptr) {
|
||||
sif::printWarning("%s\n", customPrintout);
|
||||
}
|
||||
sif::printWarning("handleIoctlError: Error code %d, %s\n", errno, strerror(errno));
|
||||
if (customPrintout != nullptr) {
|
||||
sif::printWarning("%s\n", customPrintout);
|
||||
}
|
||||
sif::printWarning("handleIoctlError: Error code %d, %s\n", errno, strerror(errno));
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -2,6 +2,7 @@
|
||||
#define FSFW_HAL_STM32H7_DEFINITIONS_H_
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "stm32h7xx.h"
|
||||
|
||||
namespace stm32h7 {
|
||||
@ -11,15 +12,15 @@ namespace stm32h7 {
|
||||
* and the second entry is the pin number
|
||||
*/
|
||||
struct GpioCfg {
|
||||
GpioCfg(): port(nullptr), pin(0), altFnc(0) {};
|
||||
GpioCfg() : port(nullptr), pin(0), altFnc(0){};
|
||||
|
||||
GpioCfg(GPIO_TypeDef* port, uint16_t pin, uint8_t altFnc = 0):
|
||||
port(port), pin(pin), altFnc(altFnc) {};
|
||||
GPIO_TypeDef* port;
|
||||
uint16_t pin;
|
||||
uint8_t altFnc;
|
||||
GpioCfg(GPIO_TypeDef* port, uint16_t pin, uint8_t altFnc = 0)
|
||||
: port(port), pin(pin), altFnc(altFnc){};
|
||||
GPIO_TypeDef* port;
|
||||
uint16_t pin;
|
||||
uint8_t altFnc;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace stm32h7
|
||||
|
||||
#endif /* #ifndef FSFW_HAL_STM32H7_DEFINITIONS_H_ */
|
||||
|
@ -1,549 +1,547 @@
|
||||
#include "fsfw_hal/stm32h7/devicetest/GyroL3GD20H.h"
|
||||
|
||||
#include "fsfw_hal/stm32h7/spi/mspInit.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiCore.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
|
||||
#include "fsfw_hal/stm32h7/spi/stm32h743zi.h"
|
||||
|
||||
#include "fsfw/tasks/TaskFactory.h"
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
|
||||
#include "stm32h7xx_hal_spi.h"
|
||||
#include "stm32h7xx_hal_rcc.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "fsfw/serviceinterface/ServiceInterface.h"
|
||||
#include "fsfw/tasks/TaskFactory.h"
|
||||
#include "fsfw_hal/stm32h7/spi/mspInit.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiCore.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
|
||||
#include "fsfw_hal/stm32h7/spi/stm32h743zi.h"
|
||||
#include "stm32h7xx_hal_rcc.h"
|
||||
#include "stm32h7xx_hal_spi.h"
|
||||
|
||||
alignas(32) std::array<uint8_t, GyroL3GD20H::recvBufferSize> GyroL3GD20H::rxBuffer;
|
||||
alignas(32) std::array<uint8_t, GyroL3GD20H::txBufferSize>
|
||||
GyroL3GD20H::txBuffer __attribute__((section(".dma_buffer")));
|
||||
alignas(32) std::array<uint8_t, GyroL3GD20H::txBufferSize> GyroL3GD20H::txBuffer
|
||||
__attribute__((section(".dma_buffer")));
|
||||
|
||||
TransferStates transferState = TransferStates::IDLE;
|
||||
spi::TransferModes GyroL3GD20H::transferMode = spi::TransferModes::POLLING;
|
||||
spi::TransferModes GyroL3GD20H::transferMode = spi::TransferModes::POLLING;
|
||||
|
||||
GyroL3GD20H::GyroL3GD20H(SPI_HandleTypeDef *spiHandle, spi::TransferModes transferMode_)
|
||||
: spiHandle(spiHandle) {
|
||||
txDmaHandle = new DMA_HandleTypeDef();
|
||||
rxDmaHandle = new DMA_HandleTypeDef();
|
||||
spi::setSpiHandle(spiHandle);
|
||||
spi::assignSpiUserArgs(spi::SpiBus::SPI_1, spiHandle);
|
||||
transferMode = transferMode_;
|
||||
if (transferMode == spi::TransferModes::DMA) {
|
||||
mspCfg = new spi::MspDmaConfigStruct();
|
||||
auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct *>(mspCfg);
|
||||
spi::setDmaHandles(txDmaHandle, rxDmaHandle);
|
||||
stm32h7::h743zi::standardDmaCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS,
|
||||
IrqPriorities::HIGHEST_FREERTOS,
|
||||
IrqPriorities::HIGHEST_FREERTOS);
|
||||
spi::setSpiDmaMspFunctions(typedCfg);
|
||||
} else if (transferMode == spi::TransferModes::INTERRUPT) {
|
||||
mspCfg = new spi::MspIrqConfigStruct();
|
||||
auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct *>(mspCfg);
|
||||
stm32h7::h743zi::standardInterruptCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS);
|
||||
spi::setSpiIrqMspFunctions(typedCfg);
|
||||
} else if (transferMode == spi::TransferModes::POLLING) {
|
||||
mspCfg = new spi::MspPollingConfigStruct();
|
||||
auto typedCfg = dynamic_cast<spi::MspPollingConfigStruct *>(mspCfg);
|
||||
stm32h7::h743zi::standardPollingCfg(*typedCfg);
|
||||
spi::setSpiPollingMspFunctions(typedCfg);
|
||||
}
|
||||
|
||||
GyroL3GD20H::GyroL3GD20H(SPI_HandleTypeDef *spiHandle, spi::TransferModes transferMode_):
|
||||
spiHandle(spiHandle) {
|
||||
txDmaHandle = new DMA_HandleTypeDef();
|
||||
rxDmaHandle = new DMA_HandleTypeDef();
|
||||
spi::setSpiHandle(spiHandle);
|
||||
spi::assignSpiUserArgs(spi::SpiBus::SPI_1, spiHandle);
|
||||
transferMode = transferMode_;
|
||||
if(transferMode == spi::TransferModes::DMA) {
|
||||
mspCfg = new spi::MspDmaConfigStruct();
|
||||
auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct*>(mspCfg);
|
||||
spi::setDmaHandles(txDmaHandle, rxDmaHandle);
|
||||
stm32h7::h743zi::standardDmaCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS,
|
||||
IrqPriorities::HIGHEST_FREERTOS, IrqPriorities::HIGHEST_FREERTOS);
|
||||
spi::setSpiDmaMspFunctions(typedCfg);
|
||||
}
|
||||
else if(transferMode == spi::TransferModes::INTERRUPT) {
|
||||
mspCfg = new spi::MspIrqConfigStruct();
|
||||
auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct*>(mspCfg);
|
||||
stm32h7::h743zi::standardInterruptCfg(*typedCfg, IrqPriorities::HIGHEST_FREERTOS);
|
||||
spi::setSpiIrqMspFunctions(typedCfg);
|
||||
}
|
||||
else if(transferMode == spi::TransferModes::POLLING) {
|
||||
mspCfg = new spi::MspPollingConfigStruct();
|
||||
auto typedCfg = dynamic_cast<spi::MspPollingConfigStruct*>(mspCfg);
|
||||
stm32h7::h743zi::standardPollingCfg(*typedCfg);
|
||||
spi::setSpiPollingMspFunctions(typedCfg);
|
||||
}
|
||||
spi::assignTransferRxTxCompleteCallback(&spiTransferCompleteCallback, nullptr);
|
||||
spi::assignTransferErrorCallback(&spiTransferErrorCallback, nullptr);
|
||||
|
||||
spi::assignTransferRxTxCompleteCallback(&spiTransferCompleteCallback, nullptr);
|
||||
spi::assignTransferErrorCallback(&spiTransferErrorCallback, nullptr);
|
||||
|
||||
GPIO_InitTypeDef chipSelect = {};
|
||||
__HAL_RCC_GPIOD_CLK_ENABLE();
|
||||
chipSelect.Pin = GPIO_PIN_14;
|
||||
chipSelect.Mode = GPIO_MODE_OUTPUT_PP;
|
||||
HAL_GPIO_Init(GPIOD, &chipSelect);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
GPIO_InitTypeDef chipSelect = {};
|
||||
__HAL_RCC_GPIOD_CLK_ENABLE();
|
||||
chipSelect.Pin = GPIO_PIN_14;
|
||||
chipSelect.Mode = GPIO_MODE_OUTPUT_PP;
|
||||
HAL_GPIO_Init(GPIOD, &chipSelect);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
}
|
||||
|
||||
GyroL3GD20H::~GyroL3GD20H() {
|
||||
delete txDmaHandle;
|
||||
delete rxDmaHandle;
|
||||
if(mspCfg != nullptr) {
|
||||
delete mspCfg;
|
||||
}
|
||||
delete txDmaHandle;
|
||||
delete rxDmaHandle;
|
||||
if (mspCfg != nullptr) {
|
||||
delete mspCfg;
|
||||
}
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::initialize() {
|
||||
// Configure the SPI peripheral
|
||||
spiHandle->Instance = SPI1;
|
||||
spiHandle->Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), 3900000);
|
||||
spiHandle->Init.Direction = SPI_DIRECTION_2LINES;
|
||||
spi::assignSpiMode(spi::SpiModes::MODE_3, *spiHandle);
|
||||
spiHandle->Init.DataSize = SPI_DATASIZE_8BIT;
|
||||
spiHandle->Init.FirstBit = SPI_FIRSTBIT_MSB;
|
||||
spiHandle->Init.TIMode = SPI_TIMODE_DISABLE;
|
||||
spiHandle->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
|
||||
spiHandle->Init.CRCPolynomial = 7;
|
||||
spiHandle->Init.CRCLength = SPI_CRC_LENGTH_8BIT;
|
||||
spiHandle->Init.NSS = SPI_NSS_SOFT;
|
||||
spiHandle->Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
|
||||
// Recommended setting to avoid glitches
|
||||
spiHandle->Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_ENABLE;
|
||||
spiHandle->Init.Mode = SPI_MODE_MASTER;
|
||||
if(HAL_SPI_Init(spiHandle) != HAL_OK) {
|
||||
sif::printWarning("Error initializing SPI\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
// Configure the SPI peripheral
|
||||
spiHandle->Instance = SPI1;
|
||||
spiHandle->Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), 3900000);
|
||||
spiHandle->Init.Direction = SPI_DIRECTION_2LINES;
|
||||
spi::assignSpiMode(spi::SpiModes::MODE_3, *spiHandle);
|
||||
spiHandle->Init.DataSize = SPI_DATASIZE_8BIT;
|
||||
spiHandle->Init.FirstBit = SPI_FIRSTBIT_MSB;
|
||||
spiHandle->Init.TIMode = SPI_TIMODE_DISABLE;
|
||||
spiHandle->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
|
||||
spiHandle->Init.CRCPolynomial = 7;
|
||||
spiHandle->Init.CRCLength = SPI_CRC_LENGTH_8BIT;
|
||||
spiHandle->Init.NSS = SPI_NSS_SOFT;
|
||||
spiHandle->Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
|
||||
// Recommended setting to avoid glitches
|
||||
spiHandle->Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_ENABLE;
|
||||
spiHandle->Init.Mode = SPI_MODE_MASTER;
|
||||
if (HAL_SPI_Init(spiHandle) != HAL_OK) {
|
||||
sif::printWarning("Error initializing SPI\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
delete mspCfg;
|
||||
transferState = TransferStates::WAIT;
|
||||
|
||||
sif::printInfo("GyroL3GD20H::performOperation: Reading WHO AM I register\n");
|
||||
|
||||
txBuffer[0] = WHO_AM_I_REG | STM_READ_MASK;
|
||||
txBuffer[1] = 0;
|
||||
|
||||
switch (transferMode) {
|
||||
case (spi::TransferModes::DMA): {
|
||||
return handleDmaTransferInit();
|
||||
}
|
||||
|
||||
delete mspCfg;
|
||||
transferState = TransferStates::WAIT;
|
||||
|
||||
sif::printInfo("GyroL3GD20H::performOperation: Reading WHO AM I register\n");
|
||||
|
||||
txBuffer[0] = WHO_AM_I_REG | STM_READ_MASK;
|
||||
txBuffer[1] = 0;
|
||||
|
||||
switch(transferMode) {
|
||||
case(spi::TransferModes::DMA): {
|
||||
return handleDmaTransferInit();
|
||||
case (spi::TransferModes::INTERRUPT): {
|
||||
return handleInterruptTransferInit();
|
||||
}
|
||||
case(spi::TransferModes::INTERRUPT): {
|
||||
return handleInterruptTransferInit();
|
||||
}
|
||||
case(spi::TransferModes::POLLING): {
|
||||
return handlePollingTransferInit();
|
||||
case (spi::TransferModes::POLLING): {
|
||||
return handlePollingTransferInit();
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::performOperation() {
|
||||
switch(transferMode) {
|
||||
case(spi::TransferModes::DMA): {
|
||||
return handleDmaSensorRead();
|
||||
switch (transferMode) {
|
||||
case (spi::TransferModes::DMA): {
|
||||
return handleDmaSensorRead();
|
||||
}
|
||||
case(spi::TransferModes::POLLING): {
|
||||
return handlePollingSensorRead();
|
||||
case (spi::TransferModes::POLLING): {
|
||||
return handlePollingSensorRead();
|
||||
}
|
||||
case(spi::TransferModes::INTERRUPT): {
|
||||
return handleInterruptSensorRead();
|
||||
case (spi::TransferModes::INTERRUPT): {
|
||||
return handleInterruptSensorRead();
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::handleDmaTransferInit() {
|
||||
/* Clean D-cache */
|
||||
/* Make sure the address is 32-byte aligned and add 32-bytes to length,
|
||||
in case it overlaps cacheline */
|
||||
// See https://community.st.com/s/article/FAQ-DMA-is-not-working-on-STM32H7-devices
|
||||
HAL_StatusTypeDef result = performDmaTransfer(2);
|
||||
if(result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printWarning("GyroL3GD20H::initialize: Error transmitting SPI with DMA\n");
|
||||
}
|
||||
/* Clean D-cache */
|
||||
/* Make sure the address is 32-byte aligned and add 32-bytes to length,
|
||||
in case it overlaps cacheline */
|
||||
// See https://community.st.com/s/article/FAQ-DMA-is-not-working-on-STM32H7-devices
|
||||
HAL_StatusTypeDef result = performDmaTransfer(2);
|
||||
if (result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printWarning("GyroL3GD20H::initialize: Error transmitting SPI with DMA\n");
|
||||
}
|
||||
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
|
||||
switch(transferState) {
|
||||
case(TransferStates::SUCCESS): {
|
||||
uint8_t whoAmIVal = rxBuffer[1];
|
||||
if(whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
|
||||
sif::printDebug("GyroL3GD20H::initialize: "
|
||||
"Read WHO AM I value %d not equal to expected value!\n", whoAmIVal);
|
||||
}
|
||||
transferState = TransferStates::IDLE;
|
||||
break;
|
||||
switch (transferState) {
|
||||
case (TransferStates::SUCCESS): {
|
||||
uint8_t whoAmIVal = rxBuffer[1];
|
||||
if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
|
||||
sif::printDebug(
|
||||
"GyroL3GD20H::initialize: "
|
||||
"Read WHO AM I value %d not equal to expected value!\n",
|
||||
whoAmIVal);
|
||||
}
|
||||
transferState = TransferStates::IDLE;
|
||||
break;
|
||||
}
|
||||
case(TransferStates::FAILURE): {
|
||||
sif::printWarning("Transfer failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (TransferStates::FAILURE): {
|
||||
sif::printWarning("Transfer failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuring device\n");
|
||||
// Configure the 5 configuration registers
|
||||
uint8_t configRegs[5];
|
||||
prepareConfigRegs(configRegs);
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuring device\n");
|
||||
// Configure the 5 configuration registers
|
||||
uint8_t configRegs[5];
|
||||
prepareConfigRegs(configRegs);
|
||||
|
||||
result = performDmaTransfer(6);
|
||||
if(result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printWarning("Error transmitting SPI with DMA\n");
|
||||
}
|
||||
result = performDmaTransfer(6);
|
||||
if (result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printWarning("Error transmitting SPI with DMA\n");
|
||||
}
|
||||
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
|
||||
switch(transferState) {
|
||||
case(TransferStates::SUCCESS): {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration transfer success\n");
|
||||
transferState = TransferStates::IDLE;
|
||||
break;
|
||||
switch (transferState) {
|
||||
case (TransferStates::SUCCESS): {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration transfer success\n");
|
||||
transferState = TransferStates::IDLE;
|
||||
break;
|
||||
}
|
||||
case(TransferStates::FAILURE): {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (TransferStates::FAILURE): {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0, 5);
|
||||
result = performDmaTransfer(6);
|
||||
if (result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printWarning("Error transmitting SPI with DMA\n");
|
||||
}
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0 , 5);
|
||||
result = performDmaTransfer(6);
|
||||
if(result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printWarning("Error transmitting SPI with DMA\n");
|
||||
switch (transferState) {
|
||||
case (TransferStates::SUCCESS): {
|
||||
if (rxBuffer[1] != configRegs[0] or rxBuffer[2] != configRegs[1] or
|
||||
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
|
||||
rxBuffer[5] != configRegs[4]) {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
|
||||
} else {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
|
||||
}
|
||||
transferState = TransferStates::IDLE;
|
||||
break;
|
||||
}
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
|
||||
switch(transferState) {
|
||||
case(TransferStates::SUCCESS): {
|
||||
if(rxBuffer[1] != configRegs[0] or rxBuffer[2] != configRegs[1] or
|
||||
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
|
||||
rxBuffer[5] != configRegs[4]) {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
|
||||
}
|
||||
else {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
|
||||
}
|
||||
transferState = TransferStates::IDLE;
|
||||
break;
|
||||
}
|
||||
case(TransferStates::FAILURE): {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (TransferStates::FAILURE): {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration transfer failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::handleDmaSensorRead() {
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0 , 14);
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0, 14);
|
||||
|
||||
HAL_StatusTypeDef result = performDmaTransfer(15);
|
||||
if(result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printDebug("GyroL3GD20H::handleDmaSensorRead: Error transmitting SPI with DMA\n");
|
||||
}
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
HAL_StatusTypeDef result = performDmaTransfer(15);
|
||||
if (result != HAL_OK) {
|
||||
// Transfer error in transmission process
|
||||
sif::printDebug("GyroL3GD20H::handleDmaSensorRead: Error transmitting SPI with DMA\n");
|
||||
}
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
|
||||
switch(transferState) {
|
||||
case(TransferStates::SUCCESS): {
|
||||
handleSensorReadout();
|
||||
break;
|
||||
switch (transferState) {
|
||||
case (TransferStates::SUCCESS): {
|
||||
handleSensorReadout();
|
||||
break;
|
||||
}
|
||||
case(TransferStates::FAILURE): {
|
||||
sif::printWarning("GyroL3GD20H::handleDmaSensorRead: Sensor read failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (TransferStates::FAILURE): {
|
||||
sif::printWarning("GyroL3GD20H::handleDmaSensorRead: Sensor read failure\n");
|
||||
transferState = TransferStates::FAILURE;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
HAL_StatusTypeDef GyroL3GD20H::performDmaTransfer(size_t sendSize) {
|
||||
transferState = TransferStates::WAIT;
|
||||
transferState = TransferStates::WAIT;
|
||||
#if STM_USE_PERIPHERAL_TX_BUFFER_MPU_PROTECTION == 0
|
||||
SCB_CleanDCache_by_Addr((uint32_t*)(((uint32_t)txBuffer.data()) & ~(uint32_t)0x1F),
|
||||
txBuffer.size()+32);
|
||||
SCB_CleanDCache_by_Addr((uint32_t *)(((uint32_t)txBuffer.data()) & ~(uint32_t)0x1F),
|
||||
txBuffer.size() + 32);
|
||||
#endif
|
||||
|
||||
// Start SPI transfer via DMA
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
return HAL_SPI_TransmitReceive_DMA(spiHandle, txBuffer.data(), rxBuffer.data(), sendSize);
|
||||
// Start SPI transfer via DMA
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
return HAL_SPI_TransmitReceive_DMA(spiHandle, txBuffer.data(), rxBuffer.data(), sendSize);
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::handlePollingTransferInit() {
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 2, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
switch(result) {
|
||||
case(HAL_OK): {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Polling transfer success\n");
|
||||
uint8_t whoAmIVal = rxBuffer[1];
|
||||
if(whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
|
||||
sif::printDebug("GyroL3GD20H::performOperation: "
|
||||
"Read WHO AM I value %d not equal to expected value!\n", whoAmIVal);
|
||||
}
|
||||
break;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 2, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
switch (result) {
|
||||
case (HAL_OK): {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Polling transfer success\n");
|
||||
uint8_t whoAmIVal = rxBuffer[1];
|
||||
if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
|
||||
sif::printDebug(
|
||||
"GyroL3GD20H::performOperation: "
|
||||
"Read WHO AM I value %d not equal to expected value!\n",
|
||||
whoAmIVal);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
case(HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuring device\n");
|
||||
// Configure the 5 configuration registers
|
||||
uint8_t configRegs[5];
|
||||
prepareConfigRegs(configRegs);
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuring device\n");
|
||||
// Configure the 5 configuration registers
|
||||
uint8_t configRegs[5];
|
||||
prepareConfigRegs(configRegs);
|
||||
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 6, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
switch(result) {
|
||||
case(HAL_OK): {
|
||||
break;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 6, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
switch (result) {
|
||||
case (HAL_OK): {
|
||||
break;
|
||||
}
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
case(HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0 , 5);
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0, 5);
|
||||
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 6, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
switch(result) {
|
||||
case(HAL_OK): {
|
||||
if(rxBuffer[1] != configRegs[0] or rxBuffer[2] != configRegs[1] or
|
||||
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
|
||||
rxBuffer[5] != configRegs[4]) {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
|
||||
}
|
||||
else {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
|
||||
}
|
||||
break;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 6, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
switch (result) {
|
||||
case (HAL_OK): {
|
||||
if (rxBuffer[1] != configRegs[0] or rxBuffer[2] != configRegs[1] or
|
||||
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
|
||||
rxBuffer[5] != configRegs[4]) {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
|
||||
} else {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
case(HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::handlePollingSensorRead() {
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0 , 14);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 15, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0, 14);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuffer.data(), rxBuffer.data(), 15, 1000);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
|
||||
switch(result) {
|
||||
case(HAL_OK): {
|
||||
handleSensorReadout();
|
||||
break;
|
||||
switch (result) {
|
||||
case (HAL_OK): {
|
||||
handleSensorReadout();
|
||||
break;
|
||||
}
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer timeout\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
case(HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_ERROR): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Polling transfer failure\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::handleInterruptTransferInit() {
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch(HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 2)) {
|
||||
case(HAL_OK): {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Interrupt transfer success\n");
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch (HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 2)) {
|
||||
case (HAL_OK): {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Interrupt transfer success\n");
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
|
||||
uint8_t whoAmIVal = rxBuffer[1];
|
||||
if(whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
|
||||
sif::printDebug("GyroL3GD20H::initialize: "
|
||||
"Read WHO AM I value %d not equal to expected value!\n", whoAmIVal);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(HAL_BUSY):
|
||||
case(HAL_ERROR):
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
uint8_t whoAmIVal = rxBuffer[1];
|
||||
if (whoAmIVal != EXPECTED_WHO_AM_I_VAL) {
|
||||
sif::printDebug(
|
||||
"GyroL3GD20H::initialize: "
|
||||
"Read WHO AM I value %d not equal to expected value!\n",
|
||||
whoAmIVal);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case (HAL_BUSY):
|
||||
case (HAL_ERROR):
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuring device\n");
|
||||
transferState = TransferStates::WAIT;
|
||||
// Configure the 5 configuration registers
|
||||
uint8_t configRegs[5];
|
||||
prepareConfigRegs(configRegs);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch(HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 6)) {
|
||||
case(HAL_OK): {
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(HAL_BUSY):
|
||||
case(HAL_ERROR):
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuring device\n");
|
||||
transferState = TransferStates::WAIT;
|
||||
// Configure the 5 configuration registers
|
||||
uint8_t configRegs[5];
|
||||
prepareConfigRegs(configRegs);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch (HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 6)) {
|
||||
case (HAL_OK): {
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case (HAL_BUSY):
|
||||
case (HAL_ERROR):
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0 , 5);
|
||||
transferState = TransferStates::WAIT;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch(HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 6)) {
|
||||
case(HAL_OK): {
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
if(rxBuffer[1] != configRegs[0] or rxBuffer[2] != configRegs[1] or
|
||||
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
|
||||
rxBuffer[5] != configRegs[4]) {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
|
||||
}
|
||||
else {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
|
||||
}
|
||||
break;
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0, 5);
|
||||
transferState = TransferStates::WAIT;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch (HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 6)) {
|
||||
case (HAL_OK): {
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
if (rxBuffer[1] != configRegs[0] or rxBuffer[2] != configRegs[1] or
|
||||
rxBuffer[3] != configRegs[2] or rxBuffer[4] != configRegs[3] or
|
||||
rxBuffer[5] != configRegs[4]) {
|
||||
sif::printWarning("GyroL3GD20H::initialize: Configuration failure\n");
|
||||
} else {
|
||||
sif::printInfo("GyroL3GD20H::initialize: Configuration success\n");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case(HAL_BUSY):
|
||||
case(HAL_ERROR):
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_BUSY):
|
||||
case (HAL_ERROR):
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Initialization failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t GyroL3GD20H::handleInterruptSensorRead() {
|
||||
transferState = TransferStates::WAIT;
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0 , 14);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch(HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 15)) {
|
||||
case(HAL_OK): {
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
handleSensorReadout();
|
||||
break;
|
||||
transferState = TransferStates::WAIT;
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK | STM_READ_MASK;
|
||||
std::memset(txBuffer.data() + 1, 0, 14);
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
switch (HAL_SPI_TransmitReceive_IT(spiHandle, txBuffer.data(), rxBuffer.data(), 15)) {
|
||||
case (HAL_OK): {
|
||||
// Wait for the transfer to complete
|
||||
while (transferState == TransferStates::WAIT) {
|
||||
TaskFactory::delayTask(1);
|
||||
}
|
||||
handleSensorReadout();
|
||||
break;
|
||||
}
|
||||
case(HAL_BUSY):
|
||||
case(HAL_ERROR):
|
||||
case(HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Sensor read failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
case (HAL_BUSY):
|
||||
case (HAL_ERROR):
|
||||
case (HAL_TIMEOUT): {
|
||||
sif::printDebug("GyroL3GD20H::initialize: Sensor read failure using interrupts\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void GyroL3GD20H::prepareConfigRegs(uint8_t* configRegs) {
|
||||
// Enable sensor
|
||||
configRegs[0] = 0b00001111;
|
||||
configRegs[1] = 0b00000000;
|
||||
configRegs[2] = 0b00000000;
|
||||
// Big endian select
|
||||
configRegs[3] = 0b01000000;
|
||||
configRegs[4] = 0b00000000;
|
||||
void GyroL3GD20H::prepareConfigRegs(uint8_t *configRegs) {
|
||||
// Enable sensor
|
||||
configRegs[0] = 0b00001111;
|
||||
configRegs[1] = 0b00000000;
|
||||
configRegs[2] = 0b00000000;
|
||||
// Big endian select
|
||||
configRegs[3] = 0b01000000;
|
||||
configRegs[4] = 0b00000000;
|
||||
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK;
|
||||
std::memcpy(txBuffer.data() + 1, configRegs, 5);
|
||||
txBuffer[0] = CTRL_REG_1 | STM_AUTO_INCREMENT_MASK;
|
||||
std::memcpy(txBuffer.data() + 1, configRegs, 5);
|
||||
}
|
||||
|
||||
uint8_t GyroL3GD20H::readRegPolling(uint8_t reg) {
|
||||
uint8_t rxBuf[2] = {};
|
||||
uint8_t txBuf[2] = {};
|
||||
txBuf[0] = reg | STM_READ_MASK;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuf, rxBuf, 2, 1000);
|
||||
if(result) {};
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
return rxBuf[1];
|
||||
uint8_t rxBuf[2] = {};
|
||||
uint8_t txBuf[2] = {};
|
||||
txBuf[0] = reg | STM_READ_MASK;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_RESET);
|
||||
auto result = HAL_SPI_TransmitReceive(spiHandle, txBuf, rxBuf, 2, 1000);
|
||||
if (result) {
|
||||
};
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
return rxBuf[1];
|
||||
}
|
||||
|
||||
void GyroL3GD20H::handleSensorReadout() {
|
||||
uint8_t statusReg = rxBuffer[8];
|
||||
int16_t gyroXRaw = rxBuffer[9] << 8 | rxBuffer[10];
|
||||
float gyroX = static_cast<float>(gyroXRaw) * 0.00875;
|
||||
int16_t gyroYRaw = rxBuffer[11] << 8 | rxBuffer[12];
|
||||
float gyroY = static_cast<float>(gyroYRaw) * 0.00875;
|
||||
int16_t gyroZRaw = rxBuffer[13] << 8 | rxBuffer[14];
|
||||
float gyroZ = static_cast<float>(gyroZRaw) * 0.00875;
|
||||
sif::printInfo("Status register: 0b" BYTE_TO_BINARY_PATTERN "\n", BYTE_TO_BINARY(statusReg));
|
||||
sif::printInfo("Gyro X: %f\n", gyroX);
|
||||
sif::printInfo("Gyro Y: %f\n", gyroY);
|
||||
sif::printInfo("Gyro Z: %f\n", gyroZ);
|
||||
uint8_t statusReg = rxBuffer[8];
|
||||
int16_t gyroXRaw = rxBuffer[9] << 8 | rxBuffer[10];
|
||||
float gyroX = static_cast<float>(gyroXRaw) * 0.00875;
|
||||
int16_t gyroYRaw = rxBuffer[11] << 8 | rxBuffer[12];
|
||||
float gyroY = static_cast<float>(gyroYRaw) * 0.00875;
|
||||
int16_t gyroZRaw = rxBuffer[13] << 8 | rxBuffer[14];
|
||||
float gyroZ = static_cast<float>(gyroZRaw) * 0.00875;
|
||||
sif::printInfo("Status register: 0b" BYTE_TO_BINARY_PATTERN "\n", BYTE_TO_BINARY(statusReg));
|
||||
sif::printInfo("Gyro X: %f\n", gyroX);
|
||||
sif::printInfo("Gyro Y: %f\n", gyroY);
|
||||
sif::printInfo("Gyro Z: %f\n", gyroZ);
|
||||
}
|
||||
|
||||
|
||||
void GyroL3GD20H::spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void* args) {
|
||||
transferState = TransferStates::SUCCESS;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
if(GyroL3GD20H::transferMode == spi::TransferModes::DMA) {
|
||||
// Invalidate cache prior to access by CPU
|
||||
SCB_InvalidateDCache_by_Addr ((uint32_t *)GyroL3GD20H::rxBuffer.data(),
|
||||
GyroL3GD20H::recvBufferSize);
|
||||
}
|
||||
void GyroL3GD20H::spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void *args) {
|
||||
transferState = TransferStates::SUCCESS;
|
||||
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_14, GPIO_PIN_SET);
|
||||
if (GyroL3GD20H::transferMode == spi::TransferModes::DMA) {
|
||||
// Invalidate cache prior to access by CPU
|
||||
SCB_InvalidateDCache_by_Addr((uint32_t *)GyroL3GD20H::rxBuffer.data(),
|
||||
GyroL3GD20H::recvBufferSize);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -553,6 +551,6 @@ void GyroL3GD20H::spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void* arg
|
||||
* add your own implementation.
|
||||
* @retval None
|
||||
*/
|
||||
void GyroL3GD20H::spiTransferErrorCallback(SPI_HandleTypeDef *hspi, void* args) {
|
||||
transferState = TransferStates::FAILURE;
|
||||
void GyroL3GD20H::spiTransferErrorCallback(SPI_HandleTypeDef *hspi, void *args) {
|
||||
transferState = TransferStates::FAILURE;
|
||||
}
|
||||
|
@ -1,70 +1,61 @@
|
||||
#ifndef FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_
|
||||
#define FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_
|
||||
|
||||
#include "stm32h7xx_hal.h"
|
||||
#include "stm32h7xx_hal_spi.h"
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
|
||||
#include "../spi/mspInit.h"
|
||||
#include "../spi/spiDefinitions.h"
|
||||
|
||||
#include "fsfw/returnvalues/HasReturnvaluesIF.h"
|
||||
#include "stm32h7xx_hal.h"
|
||||
#include "stm32h7xx_hal_spi.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <array>
|
||||
|
||||
enum class TransferStates {
|
||||
IDLE,
|
||||
WAIT,
|
||||
SUCCESS,
|
||||
FAILURE
|
||||
};
|
||||
enum class TransferStates { IDLE, WAIT, SUCCESS, FAILURE };
|
||||
|
||||
class GyroL3GD20H {
|
||||
public:
|
||||
GyroL3GD20H(SPI_HandleTypeDef* spiHandle, spi::TransferModes transferMode);
|
||||
~GyroL3GD20H();
|
||||
public:
|
||||
GyroL3GD20H(SPI_HandleTypeDef* spiHandle, spi::TransferModes transferMode);
|
||||
~GyroL3GD20H();
|
||||
|
||||
ReturnValue_t initialize();
|
||||
ReturnValue_t performOperation();
|
||||
ReturnValue_t initialize();
|
||||
ReturnValue_t performOperation();
|
||||
|
||||
private:
|
||||
private:
|
||||
const uint8_t WHO_AM_I_REG = 0b00001111;
|
||||
const uint8_t STM_READ_MASK = 0b10000000;
|
||||
const uint8_t STM_AUTO_INCREMENT_MASK = 0b01000000;
|
||||
const uint8_t EXPECTED_WHO_AM_I_VAL = 0b11010111;
|
||||
const uint8_t CTRL_REG_1 = 0b00100000;
|
||||
const uint32_t L3G_RANGE = 245;
|
||||
|
||||
const uint8_t WHO_AM_I_REG = 0b00001111;
|
||||
const uint8_t STM_READ_MASK = 0b10000000;
|
||||
const uint8_t STM_AUTO_INCREMENT_MASK = 0b01000000;
|
||||
const uint8_t EXPECTED_WHO_AM_I_VAL = 0b11010111;
|
||||
const uint8_t CTRL_REG_1 = 0b00100000;
|
||||
const uint32_t L3G_RANGE = 245;
|
||||
SPI_HandleTypeDef* spiHandle;
|
||||
|
||||
SPI_HandleTypeDef* spiHandle;
|
||||
static spi::TransferModes transferMode;
|
||||
static constexpr size_t recvBufferSize = 32 * 10;
|
||||
static std::array<uint8_t, recvBufferSize> rxBuffer;
|
||||
static constexpr size_t txBufferSize = 32;
|
||||
static std::array<uint8_t, txBufferSize> txBuffer;
|
||||
|
||||
static spi::TransferModes transferMode;
|
||||
static constexpr size_t recvBufferSize = 32 * 10;
|
||||
static std::array<uint8_t, recvBufferSize> rxBuffer;
|
||||
static constexpr size_t txBufferSize = 32;
|
||||
static std::array<uint8_t, txBufferSize> txBuffer;
|
||||
ReturnValue_t handleDmaTransferInit();
|
||||
ReturnValue_t handlePollingTransferInit();
|
||||
ReturnValue_t handleInterruptTransferInit();
|
||||
|
||||
ReturnValue_t handleDmaTransferInit();
|
||||
ReturnValue_t handlePollingTransferInit();
|
||||
ReturnValue_t handleInterruptTransferInit();
|
||||
ReturnValue_t handleDmaSensorRead();
|
||||
HAL_StatusTypeDef performDmaTransfer(size_t sendSize);
|
||||
ReturnValue_t handlePollingSensorRead();
|
||||
ReturnValue_t handleInterruptSensorRead();
|
||||
|
||||
ReturnValue_t handleDmaSensorRead();
|
||||
HAL_StatusTypeDef performDmaTransfer(size_t sendSize);
|
||||
ReturnValue_t handlePollingSensorRead();
|
||||
ReturnValue_t handleInterruptSensorRead();
|
||||
uint8_t readRegPolling(uint8_t reg);
|
||||
|
||||
uint8_t readRegPolling(uint8_t reg);
|
||||
static void spiTransferCompleteCallback(SPI_HandleTypeDef* hspi, void* args);
|
||||
static void spiTransferErrorCallback(SPI_HandleTypeDef* hspi, void* args);
|
||||
|
||||
static void spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void* args);
|
||||
static void spiTransferErrorCallback(SPI_HandleTypeDef *hspi, void* args);
|
||||
void prepareConfigRegs(uint8_t* configRegs);
|
||||
void handleSensorReadout();
|
||||
|
||||
|
||||
void prepareConfigRegs(uint8_t* configRegs);
|
||||
void handleSensorReadout();
|
||||
|
||||
|
||||
DMA_HandleTypeDef* txDmaHandle = {};
|
||||
DMA_HandleTypeDef* rxDmaHandle = {};
|
||||
spi::MspCfgBase* mspCfg = {};
|
||||
DMA_HandleTypeDef* txDmaHandle = {};
|
||||
DMA_HandleTypeDef* rxDmaHandle = {};
|
||||
spi::MspCfgBase* mspCfg = {};
|
||||
};
|
||||
|
||||
#endif /* FSFW_HAL_STM32H7_DEVICETEST_GYRO_L3GD20H_H_ */
|
||||
|
@ -1,7 +1,7 @@
|
||||
#include <fsfw_hal/stm32h7/dma.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
user_handler_t DMA_1_USER_HANDLERS[8];
|
||||
user_args_t DMA_1_USER_ARGS[8];
|
||||
@ -10,15 +10,14 @@ user_handler_t DMA_2_USER_HANDLERS[8];
|
||||
user_args_t DMA_2_USER_ARGS[8];
|
||||
|
||||
void dma::assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx,
|
||||
user_handler_t user_handler, user_args_t user_args) {
|
||||
if(dma_idx == DMA_1) {
|
||||
DMA_1_USER_HANDLERS[stream_idx] = user_handler;
|
||||
DMA_1_USER_ARGS[stream_idx] = user_args;
|
||||
}
|
||||
else if(dma_idx == DMA_2) {
|
||||
DMA_2_USER_HANDLERS[stream_idx] = user_handler;
|
||||
DMA_2_USER_ARGS[stream_idx] = user_args;
|
||||
}
|
||||
user_handler_t user_handler, user_args_t user_args) {
|
||||
if (dma_idx == DMA_1) {
|
||||
DMA_1_USER_HANDLERS[stream_idx] = user_handler;
|
||||
DMA_1_USER_ARGS[stream_idx] = user_args;
|
||||
} else if (dma_idx == DMA_2) {
|
||||
DMA_2_USER_HANDLERS[stream_idx] = user_handler;
|
||||
DMA_2_USER_ARGS[stream_idx] = user_args;
|
||||
}
|
||||
}
|
||||
|
||||
// The interrupt handlers in the format required for the IRQ vector table
|
||||
@ -26,59 +25,27 @@ void dma::assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx,
|
||||
/* Do not change these function names! They need to be exactly equal to the name of the functions
|
||||
defined in the startup_stm32h743xx.s files! */
|
||||
|
||||
#define GENERIC_DMA_IRQ_HANDLER(DMA_IDX, STREAM_IDX) \
|
||||
if(DMA_##DMA_IDX##_USER_HANDLERS[STREAM_IDX] != NULL) { \
|
||||
DMA_##DMA_IDX##_USER_HANDLERS[STREAM_IDX](DMA_##DMA_IDX##_USER_ARGS[STREAM_IDX]); \
|
||||
return; \
|
||||
} \
|
||||
Default_Handler() \
|
||||
#define GENERIC_DMA_IRQ_HANDLER(DMA_IDX, STREAM_IDX) \
|
||||
if (DMA_##DMA_IDX##_USER_HANDLERS[STREAM_IDX] != NULL) { \
|
||||
DMA_##DMA_IDX##_USER_HANDLERS[STREAM_IDX](DMA_##DMA_IDX##_USER_ARGS[STREAM_IDX]); \
|
||||
return; \
|
||||
} \
|
||||
Default_Handler()
|
||||
|
||||
extern"C" void DMA1_Stream0_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 0);
|
||||
}
|
||||
extern"C" void DMA1_Stream1_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 1);
|
||||
}
|
||||
extern"C" void DMA1_Stream2_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 2);
|
||||
}
|
||||
extern"C" void DMA1_Stream3_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 3);
|
||||
}
|
||||
extern"C" void DMA1_Stream4_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 4);
|
||||
}
|
||||
extern"C" void DMA1_Stream5_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 5);
|
||||
}
|
||||
extern"C" void DMA1_Stream6_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 6);
|
||||
}
|
||||
extern"C" void DMA1_Stream7_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(1, 7);
|
||||
}
|
||||
extern "C" void DMA1_Stream0_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 0); }
|
||||
extern "C" void DMA1_Stream1_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 1); }
|
||||
extern "C" void DMA1_Stream2_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 2); }
|
||||
extern "C" void DMA1_Stream3_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 3); }
|
||||
extern "C" void DMA1_Stream4_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 4); }
|
||||
extern "C" void DMA1_Stream5_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 5); }
|
||||
extern "C" void DMA1_Stream6_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 6); }
|
||||
extern "C" void DMA1_Stream7_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(1, 7); }
|
||||
|
||||
extern"C" void DMA2_Stream0_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 0);
|
||||
}
|
||||
extern"C" void DMA2_Stream1_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 1);
|
||||
}
|
||||
extern"C" void DMA2_Stream2_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 2);
|
||||
}
|
||||
extern"C" void DMA2_Stream3_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 3);
|
||||
}
|
||||
extern"C" void DMA2_Stream4_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 4);
|
||||
}
|
||||
extern"C" void DMA2_Stream5_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 5);
|
||||
}
|
||||
extern"C" void DMA2_Stream6_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 6);
|
||||
}
|
||||
extern"C" void DMA2_Stream7_IRQHandler() {
|
||||
GENERIC_DMA_IRQ_HANDLER(2, 7);
|
||||
}
|
||||
extern "C" void DMA2_Stream0_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 0); }
|
||||
extern "C" void DMA2_Stream1_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 1); }
|
||||
extern "C" void DMA2_Stream2_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 2); }
|
||||
extern "C" void DMA2_Stream3_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 3); }
|
||||
extern "C" void DMA2_Stream4_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 4); }
|
||||
extern "C" void DMA2_Stream5_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 5); }
|
||||
extern "C" void DMA2_Stream6_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 6); }
|
||||
extern "C" void DMA2_Stream7_IRQHandler() { GENERIC_DMA_IRQ_HANDLER(2, 7); }
|
||||
|
@ -5,31 +5,26 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include "interrupts.h"
|
||||
#include <cstdint>
|
||||
|
||||
#include "interrupts.h"
|
||||
|
||||
namespace dma {
|
||||
|
||||
enum DMAType {
|
||||
TX = 0,
|
||||
RX = 1
|
||||
};
|
||||
enum DMAType { TX = 0, RX = 1 };
|
||||
|
||||
enum DMAIndexes: uint8_t {
|
||||
DMA_1 = 1,
|
||||
DMA_2 = 2
|
||||
};
|
||||
enum DMAIndexes : uint8_t { DMA_1 = 1, DMA_2 = 2 };
|
||||
|
||||
enum DMAStreams {
|
||||
STREAM_0 = 0,
|
||||
STREAM_1 = 1,
|
||||
STREAM_2 = 2,
|
||||
STREAM_3 = 3,
|
||||
STREAM_4 = 4,
|
||||
STREAM_5 = 5,
|
||||
STREAM_6 = 6,
|
||||
STREAM_7 = 7,
|
||||
} ;
|
||||
STREAM_0 = 0,
|
||||
STREAM_1 = 1,
|
||||
STREAM_2 = 2,
|
||||
STREAM_3 = 3,
|
||||
STREAM_4 = 4,
|
||||
STREAM_5 = 5,
|
||||
STREAM_6 = 6,
|
||||
STREAM_7 = 7,
|
||||
};
|
||||
|
||||
/**
|
||||
* Assign user interrupt handlers for DMA streams, allowing to pass an
|
||||
@ -37,10 +32,10 @@ enum DMAStreams {
|
||||
* @param user_handler
|
||||
* @param user_args
|
||||
*/
|
||||
void assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx,
|
||||
user_handler_t user_handler, user_args_t user_args);
|
||||
void assignDmaUserHandler(DMAIndexes dma_idx, DMAStreams stream_idx, user_handler_t user_handler,
|
||||
user_args_t user_args);
|
||||
|
||||
}
|
||||
} // namespace dma
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
@ -4,68 +4,68 @@
|
||||
|
||||
void gpio::initializeGpioClock(GPIO_TypeDef* gpioPort) {
|
||||
#ifdef GPIOA
|
||||
if(gpioPort == GPIOA) {
|
||||
__HAL_RCC_GPIOA_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOA) {
|
||||
__HAL_RCC_GPIOA_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOB
|
||||
if(gpioPort == GPIOB) {
|
||||
__HAL_RCC_GPIOB_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOB) {
|
||||
__HAL_RCC_GPIOB_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOC
|
||||
if(gpioPort == GPIOC) {
|
||||
__HAL_RCC_GPIOC_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOC) {
|
||||
__HAL_RCC_GPIOC_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOD
|
||||
if(gpioPort == GPIOD) {
|
||||
__HAL_RCC_GPIOD_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOD) {
|
||||
__HAL_RCC_GPIOD_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOE
|
||||
if(gpioPort == GPIOE) {
|
||||
__HAL_RCC_GPIOE_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOE) {
|
||||
__HAL_RCC_GPIOE_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOF
|
||||
if(gpioPort == GPIOF) {
|
||||
__HAL_RCC_GPIOF_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOF) {
|
||||
__HAL_RCC_GPIOF_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOG
|
||||
if(gpioPort == GPIOG) {
|
||||
__HAL_RCC_GPIOG_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOG) {
|
||||
__HAL_RCC_GPIOG_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOH
|
||||
if(gpioPort == GPIOH) {
|
||||
__HAL_RCC_GPIOH_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOH) {
|
||||
__HAL_RCC_GPIOH_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOI
|
||||
if(gpioPort == GPIOI) {
|
||||
__HAL_RCC_GPIOI_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOI) {
|
||||
__HAL_RCC_GPIOI_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOJ
|
||||
if(gpioPort == GPIOJ) {
|
||||
__HAL_RCC_GPIOJ_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOJ) {
|
||||
__HAL_RCC_GPIOJ_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef GPIOK
|
||||
if(gpioPort == GPIOK) {
|
||||
__HAL_RCC_GPIOK_CLK_ENABLE();
|
||||
}
|
||||
if (gpioPort == GPIOK) {
|
||||
__HAL_RCC_GPIOK_CLK_ENABLE();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
@ -12,14 +12,10 @@ extern "C" {
|
||||
*/
|
||||
extern void Default_Handler();
|
||||
|
||||
typedef void (*user_handler_t) (void*);
|
||||
typedef void (*user_handler_t)(void*);
|
||||
typedef void* user_args_t;
|
||||
|
||||
enum IrqPriorities: uint8_t {
|
||||
HIGHEST = 0,
|
||||
HIGHEST_FREERTOS = 6,
|
||||
LOWEST = 15
|
||||
};
|
||||
enum IrqPriorities : uint8_t { HIGHEST = 0, HIGHEST_FREERTOS = 6, LOWEST = 15 };
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
@ -1,11 +1,11 @@
|
||||
#include "fsfw_hal/stm32h7/spi/SpiComIF.h"
|
||||
#include "fsfw_hal/stm32h7/spi/SpiCookie.h"
|
||||
|
||||
#include "fsfw/tasks/SemaphoreFactory.h"
|
||||
#include "fsfw_hal/stm32h7/gpio/gpio.h"
|
||||
#include "fsfw_hal/stm32h7/spi/SpiCookie.h"
|
||||
#include "fsfw_hal/stm32h7/spi/mspInit.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiCore.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiInterrupts.h"
|
||||
#include "fsfw_hal/stm32h7/spi/mspInit.h"
|
||||
#include "fsfw_hal/stm32h7/gpio/gpio.h"
|
||||
|
||||
// FreeRTOS required special Semaphore handling from an ISR. Therefore, we use the concrete
|
||||
// instance here, because RTEMS and FreeRTOS are the only relevant OSALs currently
|
||||
@ -13,468 +13,462 @@
|
||||
#if defined FSFW_OSAL_RTEMS
|
||||
#include "fsfw/osal/rtems/BinarySemaphore.h"
|
||||
#elif defined FSFW_OSAL_FREERTOS
|
||||
#include "fsfw/osal/freertos/TaskManagement.h"
|
||||
#include "fsfw/osal/freertos/BinarySemaphore.h"
|
||||
#include "fsfw/osal/freertos/TaskManagement.h"
|
||||
#endif
|
||||
|
||||
#include "stm32h7xx_hal_gpio.h"
|
||||
|
||||
SpiComIF::SpiComIF(object_id_t objectId): SystemObject(objectId) {
|
||||
void* irqArgsVoided = reinterpret_cast<void*>(&irqArgs);
|
||||
spi::assignTransferRxTxCompleteCallback(&spiTransferCompleteCallback, irqArgsVoided);
|
||||
spi::assignTransferRxCompleteCallback(&spiTransferRxCompleteCallback, irqArgsVoided);
|
||||
spi::assignTransferTxCompleteCallback(&spiTransferTxCompleteCallback, irqArgsVoided);
|
||||
spi::assignTransferErrorCallback(&spiTransferErrorCallback, irqArgsVoided);
|
||||
SpiComIF::SpiComIF(object_id_t objectId) : SystemObject(objectId) {
|
||||
void *irqArgsVoided = reinterpret_cast<void *>(&irqArgs);
|
||||
spi::assignTransferRxTxCompleteCallback(&spiTransferCompleteCallback, irqArgsVoided);
|
||||
spi::assignTransferRxCompleteCallback(&spiTransferRxCompleteCallback, irqArgsVoided);
|
||||
spi::assignTransferTxCompleteCallback(&spiTransferTxCompleteCallback, irqArgsVoided);
|
||||
spi::assignTransferErrorCallback(&spiTransferErrorCallback, irqArgsVoided);
|
||||
}
|
||||
|
||||
void SpiComIF::configureCacheMaintenanceOnTxBuffer(bool enable) {
|
||||
this->cacheMaintenanceOnTxBuffer = enable;
|
||||
this->cacheMaintenanceOnTxBuffer = enable;
|
||||
}
|
||||
|
||||
void SpiComIF::addDmaHandles(DMA_HandleTypeDef *txHandle, DMA_HandleTypeDef *rxHandle) {
|
||||
spi::setDmaHandles(txHandle, rxHandle);
|
||||
spi::setDmaHandles(txHandle, rxHandle);
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::initialize() {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
ReturnValue_t SpiComIF::initialize() { return HasReturnvaluesIF::RETURN_OK; }
|
||||
|
||||
ReturnValue_t SpiComIF::initializeInterface(CookieIF *cookie) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if(spiCookie == nullptr) {
|
||||
SpiCookie *spiCookie = dynamic_cast<SpiCookie *>(cookie);
|
||||
if (spiCookie == nullptr) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error < "SpiComIF::initializeInterface: Invalid cookie" << std::endl;
|
||||
sif::error < "SpiComIF::initializeInterface: Invalid cookie" << std::endl;
|
||||
#else
|
||||
sif::printError("SpiComIF::initializeInterface: Invalid cookie\n");
|
||||
sif::printError("SpiComIF::initializeInterface: Invalid cookie\n");
|
||||
#endif
|
||||
return NULLPOINTER;
|
||||
}
|
||||
auto transferMode = spiCookie->getTransferMode();
|
||||
return NULLPOINTER;
|
||||
}
|
||||
auto transferMode = spiCookie->getTransferMode();
|
||||
|
||||
if(transferMode == spi::TransferModes::DMA) {
|
||||
DMA_HandleTypeDef *txHandle = nullptr;
|
||||
DMA_HandleTypeDef *rxHandle = nullptr;
|
||||
spi::getDmaHandles(&txHandle, &rxHandle);
|
||||
if(txHandle == nullptr or rxHandle == nullptr) {
|
||||
sif::printError("SpiComIF::initialize: DMA handles not set!\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
if (transferMode == spi::TransferModes::DMA) {
|
||||
DMA_HandleTypeDef *txHandle = nullptr;
|
||||
DMA_HandleTypeDef *rxHandle = nullptr;
|
||||
spi::getDmaHandles(&txHandle, &rxHandle);
|
||||
if (txHandle == nullptr or rxHandle == nullptr) {
|
||||
sif::printError("SpiComIF::initialize: DMA handles not set!\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
// This semaphore ensures thread-safety for a given bus
|
||||
spiSemaphore = dynamic_cast<BinarySemaphore*>(
|
||||
SemaphoreFactory::instance()->createBinarySemaphore());
|
||||
address_t spiAddress = spiCookie->getDeviceAddress();
|
||||
}
|
||||
// This semaphore ensures thread-safety for a given bus
|
||||
spiSemaphore =
|
||||
dynamic_cast<BinarySemaphore *>(SemaphoreFactory::instance()->createBinarySemaphore());
|
||||
address_t spiAddress = spiCookie->getDeviceAddress();
|
||||
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if(iter == spiDeviceMap.end()) {
|
||||
size_t bufferSize = spiCookie->getMaxRecvSize();
|
||||
auto statusPair = spiDeviceMap.emplace(spiAddress, SpiInstance(bufferSize));
|
||||
if (not statusPair.second) {
|
||||
auto iter = spiDeviceMap.find(spiAddress);
|
||||
if (iter == spiDeviceMap.end()) {
|
||||
size_t bufferSize = spiCookie->getMaxRecvSize();
|
||||
auto statusPair = spiDeviceMap.emplace(spiAddress, SpiInstance(bufferSize));
|
||||
if (not statusPair.second) {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::error << "SpiComIF::initializeInterface: Failed to insert device with address " <<
|
||||
spiAddress << "to SPI device map" << std::endl;
|
||||
sif::error << "SpiComIF::initializeInterface: Failed to insert device with address "
|
||||
<< spiAddress << "to SPI device map" << std::endl;
|
||||
#else
|
||||
sif::printError("SpiComIF::initializeInterface: Failed to insert device with address "
|
||||
"%lu to SPI device map\n", static_cast<unsigned long>(spiAddress));
|
||||
sif::printError(
|
||||
"SpiComIF::initializeInterface: Failed to insert device with address "
|
||||
"%lu to SPI device map\n",
|
||||
static_cast<unsigned long>(spiAddress));
|
||||
#endif /* FSFW_CPP_OSTREAM_ENABLED == 1 */
|
||||
#endif /* FSFW_VERBOSE_LEVEL >= 1 */
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
auto gpioPin = spiCookie->getChipSelectGpioPin();
|
||||
auto gpioPort = spiCookie->getChipSelectGpioPort();
|
||||
}
|
||||
auto gpioPin = spiCookie->getChipSelectGpioPin();
|
||||
auto gpioPort = spiCookie->getChipSelectGpioPort();
|
||||
|
||||
SPI_HandleTypeDef& spiHandle = spiCookie->getSpiHandle();
|
||||
SPI_HandleTypeDef &spiHandle = spiCookie->getSpiHandle();
|
||||
|
||||
auto spiIdx = spiCookie->getSpiIdx();
|
||||
if(spiIdx == spi::SpiBus::SPI_1) {
|
||||
auto spiIdx = spiCookie->getSpiIdx();
|
||||
if (spiIdx == spi::SpiBus::SPI_1) {
|
||||
#ifdef SPI1
|
||||
spiHandle.Instance = SPI1;
|
||||
spiHandle.Instance = SPI1;
|
||||
#endif
|
||||
}
|
||||
else if(spiIdx == spi::SpiBus::SPI_2) {
|
||||
} else if (spiIdx == spi::SpiBus::SPI_2) {
|
||||
#ifdef SPI2
|
||||
spiHandle.Instance = SPI2;
|
||||
spiHandle.Instance = SPI2;
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
printCfgError("SPI Bus Index");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
} else {
|
||||
printCfgError("SPI Bus Index");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
|
||||
auto mspCfg = spiCookie->getMspCfg();
|
||||
auto mspCfg = spiCookie->getMspCfg();
|
||||
|
||||
if(transferMode == spi::TransferModes::POLLING) {
|
||||
auto typedCfg = dynamic_cast<spi::MspPollingConfigStruct*>(mspCfg);
|
||||
if(typedCfg == nullptr) {
|
||||
printCfgError("Polling MSP");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
spi::setSpiPollingMspFunctions(typedCfg);
|
||||
if (transferMode == spi::TransferModes::POLLING) {
|
||||
auto typedCfg = dynamic_cast<spi::MspPollingConfigStruct *>(mspCfg);
|
||||
if (typedCfg == nullptr) {
|
||||
printCfgError("Polling MSP");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
else if(transferMode == spi::TransferModes::INTERRUPT) {
|
||||
auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct*>(mspCfg);
|
||||
if(typedCfg == nullptr) {
|
||||
printCfgError("IRQ MSP");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
spi::setSpiIrqMspFunctions(typedCfg);
|
||||
spi::setSpiPollingMspFunctions(typedCfg);
|
||||
} else if (transferMode == spi::TransferModes::INTERRUPT) {
|
||||
auto typedCfg = dynamic_cast<spi::MspIrqConfigStruct *>(mspCfg);
|
||||
if (typedCfg == nullptr) {
|
||||
printCfgError("IRQ MSP");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
else if(transferMode == spi::TransferModes::DMA) {
|
||||
auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct*>(mspCfg);
|
||||
if(typedCfg == nullptr) {
|
||||
printCfgError("DMA MSP");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
// Check DMA handles
|
||||
DMA_HandleTypeDef* txHandle = nullptr;
|
||||
DMA_HandleTypeDef* rxHandle = nullptr;
|
||||
spi::getDmaHandles(&txHandle, &rxHandle);
|
||||
if(txHandle == nullptr or rxHandle == nullptr) {
|
||||
printCfgError("DMA Handle");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
spi::setSpiDmaMspFunctions(typedCfg);
|
||||
spi::setSpiIrqMspFunctions(typedCfg);
|
||||
} else if (transferMode == spi::TransferModes::DMA) {
|
||||
auto typedCfg = dynamic_cast<spi::MspDmaConfigStruct *>(mspCfg);
|
||||
if (typedCfg == nullptr) {
|
||||
printCfgError("DMA MSP");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
// Check DMA handles
|
||||
DMA_HandleTypeDef *txHandle = nullptr;
|
||||
DMA_HandleTypeDef *rxHandle = nullptr;
|
||||
spi::getDmaHandles(&txHandle, &rxHandle);
|
||||
if (txHandle == nullptr or rxHandle == nullptr) {
|
||||
printCfgError("DMA Handle");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
spi::setSpiDmaMspFunctions(typedCfg);
|
||||
}
|
||||
|
||||
if(gpioPort != nullptr) {
|
||||
gpio::initializeGpioClock(gpioPort);
|
||||
GPIO_InitTypeDef chipSelect = {};
|
||||
chipSelect.Pin = gpioPin;
|
||||
chipSelect.Mode = GPIO_MODE_OUTPUT_PP;
|
||||
HAL_GPIO_Init(gpioPort, &chipSelect);
|
||||
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_SET);
|
||||
}
|
||||
if (gpioPort != nullptr) {
|
||||
gpio::initializeGpioClock(gpioPort);
|
||||
GPIO_InitTypeDef chipSelect = {};
|
||||
chipSelect.Pin = gpioPin;
|
||||
chipSelect.Mode = GPIO_MODE_OUTPUT_PP;
|
||||
HAL_GPIO_Init(gpioPort, &chipSelect);
|
||||
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_SET);
|
||||
}
|
||||
|
||||
if(HAL_SPI_Init(&spiHandle) != HAL_OK) {
|
||||
sif::printWarning("SpiComIF::initialize: Error initializing SPI\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
// The MSP configuration struct is not required anymore
|
||||
spiCookie->deleteMspCfg();
|
||||
if (HAL_SPI_Init(&spiHandle) != HAL_OK) {
|
||||
sif::printWarning("SpiComIF::initialize: Error initializing SPI\n");
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
// The MSP configuration struct is not required anymore
|
||||
spiCookie->deleteMspCfg();
|
||||
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::sendMessage(CookieIF *cookie, const uint8_t *sendData, size_t sendLen) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if(spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
SpiCookie *spiCookie = dynamic_cast<SpiCookie *>(cookie);
|
||||
if (spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
|
||||
SPI_HandleTypeDef& spiHandle = spiCookie->getSpiHandle();
|
||||
SPI_HandleTypeDef &spiHandle = spiCookie->getSpiHandle();
|
||||
|
||||
auto iter = spiDeviceMap.find(spiCookie->getDeviceAddress());
|
||||
if(iter == spiDeviceMap.end()) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
iter->second.currentTransferLen = sendLen;
|
||||
auto iter = spiDeviceMap.find(spiCookie->getDeviceAddress());
|
||||
if (iter == spiDeviceMap.end()) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
iter->second.currentTransferLen = sendLen;
|
||||
|
||||
auto transferMode = spiCookie->getTransferMode();
|
||||
switch(spiCookie->getTransferState()) {
|
||||
case(spi::TransferStates::IDLE): {
|
||||
break;
|
||||
auto transferMode = spiCookie->getTransferMode();
|
||||
switch (spiCookie->getTransferState()) {
|
||||
case (spi::TransferStates::IDLE): {
|
||||
break;
|
||||
}
|
||||
case(spi::TransferStates::WAIT):
|
||||
case(spi::TransferStates::FAILURE):
|
||||
case(spi::TransferStates::SUCCESS):
|
||||
case (spi::TransferStates::WAIT):
|
||||
case (spi::TransferStates::FAILURE):
|
||||
case (spi::TransferStates::SUCCESS):
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
switch(transferMode) {
|
||||
case(spi::TransferModes::POLLING): {
|
||||
return handlePollingSendOperation(iter->second.replyBuffer.data(), spiHandle, *spiCookie,
|
||||
sendData, sendLen);
|
||||
switch (transferMode) {
|
||||
case (spi::TransferModes::POLLING): {
|
||||
return handlePollingSendOperation(iter->second.replyBuffer.data(), spiHandle, *spiCookie,
|
||||
sendData, sendLen);
|
||||
}
|
||||
case(spi::TransferModes::INTERRUPT): {
|
||||
return handleInterruptSendOperation(iter->second.replyBuffer.data(), spiHandle, *spiCookie,
|
||||
sendData, sendLen);
|
||||
case (spi::TransferModes::INTERRUPT): {
|
||||
return handleInterruptSendOperation(iter->second.replyBuffer.data(), spiHandle, *spiCookie,
|
||||
sendData, sendLen);
|
||||
}
|
||||
case(spi::TransferModes::DMA): {
|
||||
return handleDmaSendOperation(iter->second.replyBuffer.data(), spiHandle, *spiCookie,
|
||||
sendData, sendLen);
|
||||
case (spi::TransferModes::DMA): {
|
||||
return handleDmaSendOperation(iter->second.replyBuffer.data(), spiHandle, *spiCookie,
|
||||
sendData, sendLen);
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::getSendSuccess(CookieIF *cookie) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
ReturnValue_t SpiComIF::getSendSuccess(CookieIF *cookie) { return HasReturnvaluesIF::RETURN_OK; }
|
||||
|
||||
ReturnValue_t SpiComIF::requestReceiveMessage(CookieIF *cookie, size_t requestLen) {
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::readReceivedMessage(CookieIF *cookie, uint8_t **buffer, size_t *size) {
|
||||
SpiCookie* spiCookie = dynamic_cast<SpiCookie*>(cookie);
|
||||
if(spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
SpiCookie *spiCookie = dynamic_cast<SpiCookie *>(cookie);
|
||||
if (spiCookie == nullptr) {
|
||||
return NULLPOINTER;
|
||||
}
|
||||
switch (spiCookie->getTransferState()) {
|
||||
case (spi::TransferStates::SUCCESS): {
|
||||
auto iter = spiDeviceMap.find(spiCookie->getDeviceAddress());
|
||||
if (iter == spiDeviceMap.end()) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
*buffer = iter->second.replyBuffer.data();
|
||||
*size = iter->second.currentTransferLen;
|
||||
spiCookie->setTransferState(spi::TransferStates::IDLE);
|
||||
break;
|
||||
}
|
||||
switch(spiCookie->getTransferState()) {
|
||||
case(spi::TransferStates::SUCCESS): {
|
||||
auto iter = spiDeviceMap.find(spiCookie->getDeviceAddress());
|
||||
if(iter == spiDeviceMap.end()) {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
*buffer = iter->second.replyBuffer.data();
|
||||
*size = iter->second.currentTransferLen;
|
||||
spiCookie->setTransferState(spi::TransferStates::IDLE);
|
||||
break;
|
||||
}
|
||||
case(spi::TransferStates::FAILURE): {
|
||||
case (spi::TransferStates::FAILURE): {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "SpiComIF::readReceivedMessage: Transfer failure" << std::endl;
|
||||
sif::warning << "SpiComIF::readReceivedMessage: Transfer failure" << std::endl;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::readReceivedMessage: Transfer failure\n");
|
||||
sif::printWarning("SpiComIF::readReceivedMessage: Transfer failure\n");
|
||||
#endif
|
||||
#endif
|
||||
spiCookie->setTransferState(spi::TransferStates::IDLE);
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
spiCookie->setTransferState(spi::TransferStates::IDLE);
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
case(spi::TransferStates::WAIT):
|
||||
case(spi::TransferStates::IDLE): {
|
||||
break;
|
||||
case (spi::TransferStates::WAIT):
|
||||
case (spi::TransferStates::IDLE): {
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void SpiComIF::setDefaultPollingTimeout(dur_millis_t timeout) {
|
||||
this->defaultPollingTimeout = timeout;
|
||||
this->defaultPollingTimeout = timeout;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t *sendData, size_t sendLen) {
|
||||
auto gpioPort = spiCookie.getChipSelectGpioPort();
|
||||
auto gpioPin = spiCookie.getChipSelectGpioPin();
|
||||
auto returnval = spiSemaphore->acquire(timeoutType, timeoutMs);
|
||||
if(returnval != HasReturnvaluesIF::RETURN_OK) {
|
||||
return returnval;
|
||||
}
|
||||
spiCookie.setTransferState(spi::TransferStates::WAIT);
|
||||
if(gpioPort != nullptr) {
|
||||
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_RESET);
|
||||
}
|
||||
ReturnValue_t SpiComIF::handlePollingSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
|
||||
SpiCookie &spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen) {
|
||||
auto gpioPort = spiCookie.getChipSelectGpioPort();
|
||||
auto gpioPin = spiCookie.getChipSelectGpioPin();
|
||||
auto returnval = spiSemaphore->acquire(timeoutType, timeoutMs);
|
||||
if (returnval != HasReturnvaluesIF::RETURN_OK) {
|
||||
return returnval;
|
||||
}
|
||||
spiCookie.setTransferState(spi::TransferStates::WAIT);
|
||||
if (gpioPort != nullptr) {
|
||||
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_RESET);
|
||||
}
|
||||
|
||||
auto result = HAL_SPI_TransmitReceive(&spiHandle, const_cast<uint8_t*>(sendData),
|
||||
recvPtr, sendLen, defaultPollingTimeout);
|
||||
if(gpioPort != nullptr) {
|
||||
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_SET);
|
||||
auto result = HAL_SPI_TransmitReceive(&spiHandle, const_cast<uint8_t *>(sendData), recvPtr,
|
||||
sendLen, defaultPollingTimeout);
|
||||
if (gpioPort != nullptr) {
|
||||
HAL_GPIO_WritePin(gpioPort, gpioPin, GPIO_PIN_SET);
|
||||
}
|
||||
spiSemaphore->release();
|
||||
switch (result) {
|
||||
case (HAL_OK): {
|
||||
spiCookie.setTransferState(spi::TransferStates::SUCCESS);
|
||||
break;
|
||||
}
|
||||
spiSemaphore->release();
|
||||
switch(result) {
|
||||
case(HAL_OK): {
|
||||
spiCookie.setTransferState(spi::TransferStates::SUCCESS);
|
||||
break;
|
||||
}
|
||||
case(HAL_TIMEOUT): {
|
||||
case (HAL_TIMEOUT): {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "SpiComIF::sendMessage: Polling Mode | Timeout for SPI device" <<
|
||||
spiCookie->getDeviceAddress() << std::endl;
|
||||
sif::warning << "SpiComIF::sendMessage: Polling Mode | Timeout for SPI device"
|
||||
<< spiCookie->getDeviceAddress() << std::endl;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::sendMessage: Polling Mode | Timeout for SPI device %d\n",
|
||||
spiCookie.getDeviceAddress());
|
||||
sif::printWarning("SpiComIF::sendMessage: Polling Mode | Timeout for SPI device %d\n",
|
||||
spiCookie.getDeviceAddress());
|
||||
#endif
|
||||
#endif
|
||||
spiCookie.setTransferState(spi::TransferStates::FAILURE);
|
||||
return spi::HAL_TIMEOUT_RETVAL;
|
||||
spiCookie.setTransferState(spi::TransferStates::FAILURE);
|
||||
return spi::HAL_TIMEOUT_RETVAL;
|
||||
}
|
||||
case(HAL_ERROR):
|
||||
case (HAL_ERROR):
|
||||
default: {
|
||||
#if FSFW_VERBOSE_LEVEL >= 1
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "SpiComIF::sendMessage: Polling Mode | HAL error for SPI device" <<
|
||||
spiCookie->getDeviceAddress() << std::endl;
|
||||
sif::warning << "SpiComIF::sendMessage: Polling Mode | HAL error for SPI device"
|
||||
<< spiCookie->getDeviceAddress() << std::endl;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::sendMessage: Polling Mode | HAL error for SPI device %d\n",
|
||||
spiCookie.getDeviceAddress());
|
||||
sif::printWarning("SpiComIF::sendMessage: Polling Mode | HAL error for SPI device %d\n",
|
||||
spiCookie.getDeviceAddress());
|
||||
#endif
|
||||
#endif
|
||||
spiCookie.setTransferState(spi::TransferStates::FAILURE);
|
||||
return spi::HAL_ERROR_RETVAL;
|
||||
spiCookie.setTransferState(spi::TransferStates::FAILURE);
|
||||
return spi::HAL_ERROR_RETVAL;
|
||||
}
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::handleInterruptSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen) {
|
||||
return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen);
|
||||
ReturnValue_t SpiComIF::handleInterruptSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
|
||||
SpiCookie &spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen) {
|
||||
return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen);
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::handleDmaSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen) {
|
||||
return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen);
|
||||
ReturnValue_t SpiComIF::handleDmaSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
|
||||
SpiCookie &spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen) {
|
||||
return handleIrqSendOperation(recvPtr, spiHandle, spiCookie, sendData, sendLen);
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::handleIrqSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t *sendData, size_t sendLen) {
|
||||
ReturnValue_t result = genericIrqSendSetup(recvPtr, spiHandle, spiCookie, sendData, sendLen);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
// yet another HAL driver which is not const-correct..
|
||||
HAL_StatusTypeDef status = HAL_OK;
|
||||
auto transferMode = spiCookie.getTransferMode();
|
||||
if(transferMode == spi::TransferModes::DMA) {
|
||||
if(cacheMaintenanceOnTxBuffer) {
|
||||
/* Clean D-cache. Make sure the address is 32-byte aligned and add 32-bytes to length,
|
||||
in case it overlaps cacheline */
|
||||
SCB_CleanDCache_by_Addr((uint32_t*)(((uint32_t) sendData ) & ~(uint32_t)0x1F),
|
||||
sendLen + 32);
|
||||
}
|
||||
status = HAL_SPI_TransmitReceive_DMA(&spiHandle, const_cast<uint8_t*>(sendData),
|
||||
currentRecvPtr, sendLen);
|
||||
}
|
||||
else {
|
||||
status = HAL_SPI_TransmitReceive_IT(&spiHandle, const_cast<uint8_t*>(sendData),
|
||||
currentRecvPtr, sendLen);
|
||||
}
|
||||
switch(status) {
|
||||
case(HAL_OK): {
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return halErrorHandler(status, transferMode);
|
||||
}
|
||||
}
|
||||
ReturnValue_t SpiComIF::handleIrqSendOperation(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
|
||||
SpiCookie &spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen) {
|
||||
ReturnValue_t result = genericIrqSendSetup(recvPtr, spiHandle, spiCookie, sendData, sendLen);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
return result;
|
||||
}
|
||||
// yet another HAL driver which is not const-correct..
|
||||
HAL_StatusTypeDef status = HAL_OK;
|
||||
auto transferMode = spiCookie.getTransferMode();
|
||||
if (transferMode == spi::TransferModes::DMA) {
|
||||
if (cacheMaintenanceOnTxBuffer) {
|
||||
/* Clean D-cache. Make sure the address is 32-byte aligned and add 32-bytes to length,
|
||||
in case it overlaps cacheline */
|
||||
SCB_CleanDCache_by_Addr((uint32_t *)(((uint32_t)sendData) & ~(uint32_t)0x1F), sendLen + 32);
|
||||
}
|
||||
status = HAL_SPI_TransmitReceive_DMA(&spiHandle, const_cast<uint8_t *>(sendData),
|
||||
currentRecvPtr, sendLen);
|
||||
} else {
|
||||
status = HAL_SPI_TransmitReceive_IT(&spiHandle, const_cast<uint8_t *>(sendData), currentRecvPtr,
|
||||
sendLen);
|
||||
}
|
||||
switch (status) {
|
||||
case (HAL_OK): {
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return halErrorHandler(status, transferMode);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::halErrorHandler(HAL_StatusTypeDef status, spi::TransferModes transferMode) {
|
||||
char modeString[10];
|
||||
if(transferMode == spi::TransferModes::DMA) {
|
||||
std::snprintf(modeString, sizeof(modeString), "Dma");
|
||||
char modeString[10];
|
||||
if (transferMode == spi::TransferModes::DMA) {
|
||||
std::snprintf(modeString, sizeof(modeString), "Dma");
|
||||
} else {
|
||||
std::snprintf(modeString, sizeof(modeString), "Interrupt");
|
||||
}
|
||||
sif::printWarning("SpiComIF::handle%sSendOperation: HAL error %d occured\n", modeString, status);
|
||||
switch (status) {
|
||||
case (HAL_BUSY): {
|
||||
return spi::HAL_BUSY_RETVAL;
|
||||
}
|
||||
else {
|
||||
std::snprintf(modeString, sizeof(modeString), "Interrupt");
|
||||
case (HAL_ERROR): {
|
||||
return spi::HAL_ERROR_RETVAL;
|
||||
}
|
||||
sif::printWarning("SpiComIF::handle%sSendOperation: HAL error %d occured\n", modeString,
|
||||
status);
|
||||
switch(status) {
|
||||
case(HAL_BUSY): {
|
||||
return spi::HAL_BUSY_RETVAL;
|
||||
}
|
||||
case(HAL_ERROR): {
|
||||
return spi::HAL_ERROR_RETVAL;
|
||||
}
|
||||
case(HAL_TIMEOUT): {
|
||||
return spi::HAL_TIMEOUT_RETVAL;
|
||||
case (HAL_TIMEOUT): {
|
||||
return spi::HAL_TIMEOUT_RETVAL;
|
||||
}
|
||||
default: {
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_FAILED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ReturnValue_t SpiComIF::genericIrqSendSetup(uint8_t *recvPtr, SPI_HandleTypeDef &spiHandle,
|
||||
SpiCookie &spiCookie, const uint8_t *sendData,
|
||||
size_t sendLen) {
|
||||
currentRecvPtr = recvPtr;
|
||||
currentRecvBuffSize = sendLen;
|
||||
|
||||
ReturnValue_t SpiComIF::genericIrqSendSetup(uint8_t *recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t *sendData, size_t sendLen) {
|
||||
currentRecvPtr = recvPtr;
|
||||
currentRecvBuffSize = sendLen;
|
||||
|
||||
// Take the semaphore which will be released by a callback when the transfer is complete
|
||||
ReturnValue_t result = spiSemaphore->acquire(SemaphoreIF::TimeoutType::WAITING, timeoutMs);
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
// Configuration error
|
||||
sif::printWarning("SpiComIF::handleInterruptSendOperation: Semaphore "
|
||||
"could not be acquired after %d ms\n", timeoutMs);
|
||||
return result;
|
||||
}
|
||||
// Cache the current SPI handle in any case
|
||||
spi::setSpiHandle(&spiHandle);
|
||||
// Assign the IRQ arguments for the user callbacks
|
||||
irqArgs.comIF = this;
|
||||
irqArgs.spiCookie = &spiCookie;
|
||||
// The SPI handle is passed to the default SPI callback as a void argument. This callback
|
||||
// is different from the user callbacks specified above!
|
||||
spi::assignSpiUserArgs(spiCookie.getSpiIdx(), reinterpret_cast<void*>(&spiHandle));
|
||||
if(spiCookie.getChipSelectGpioPort() != nullptr) {
|
||||
HAL_GPIO_WritePin(spiCookie.getChipSelectGpioPort(), spiCookie.getChipSelectGpioPin(),
|
||||
GPIO_PIN_RESET);
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
// Take the semaphore which will be released by a callback when the transfer is complete
|
||||
ReturnValue_t result = spiSemaphore->acquire(SemaphoreIF::TimeoutType::WAITING, timeoutMs);
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
// Configuration error
|
||||
sif::printWarning(
|
||||
"SpiComIF::handleInterruptSendOperation: Semaphore "
|
||||
"could not be acquired after %d ms\n",
|
||||
timeoutMs);
|
||||
return result;
|
||||
}
|
||||
// Cache the current SPI handle in any case
|
||||
spi::setSpiHandle(&spiHandle);
|
||||
// Assign the IRQ arguments for the user callbacks
|
||||
irqArgs.comIF = this;
|
||||
irqArgs.spiCookie = &spiCookie;
|
||||
// The SPI handle is passed to the default SPI callback as a void argument. This callback
|
||||
// is different from the user callbacks specified above!
|
||||
spi::assignSpiUserArgs(spiCookie.getSpiIdx(), reinterpret_cast<void *>(&spiHandle));
|
||||
if (spiCookie.getChipSelectGpioPort() != nullptr) {
|
||||
HAL_GPIO_WritePin(spiCookie.getChipSelectGpioPort(), spiCookie.getChipSelectGpioPin(),
|
||||
GPIO_PIN_RESET);
|
||||
}
|
||||
return HasReturnvaluesIF::RETURN_OK;
|
||||
}
|
||||
|
||||
void SpiComIF::spiTransferTxCompleteCallback(SPI_HandleTypeDef *hspi, void *args) {
|
||||
genericIrqHandler(args, spi::TransferStates::SUCCESS);
|
||||
genericIrqHandler(args, spi::TransferStates::SUCCESS);
|
||||
}
|
||||
|
||||
void SpiComIF::spiTransferRxCompleteCallback(SPI_HandleTypeDef *hspi, void *args) {
|
||||
genericIrqHandler(args, spi::TransferStates::SUCCESS);
|
||||
genericIrqHandler(args, spi::TransferStates::SUCCESS);
|
||||
}
|
||||
|
||||
void SpiComIF::spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void *args) {
|
||||
genericIrqHandler(args, spi::TransferStates::SUCCESS);
|
||||
genericIrqHandler(args, spi::TransferStates::SUCCESS);
|
||||
}
|
||||
|
||||
void SpiComIF::spiTransferErrorCallback(SPI_HandleTypeDef *hspi, void *args) {
|
||||
genericIrqHandler(args, spi::TransferStates::FAILURE);
|
||||
genericIrqHandler(args, spi::TransferStates::FAILURE);
|
||||
}
|
||||
|
||||
void SpiComIF::genericIrqHandler(void *irqArgsVoid, spi::TransferStates targetState) {
|
||||
IrqArgs* irqArgs = reinterpret_cast<IrqArgs*>(irqArgsVoid);
|
||||
if(irqArgs == nullptr) {
|
||||
return;
|
||||
}
|
||||
SpiCookie* spiCookie = irqArgs->spiCookie;
|
||||
SpiComIF* comIF = irqArgs->comIF;
|
||||
if(spiCookie == nullptr or comIF == nullptr) {
|
||||
return;
|
||||
}
|
||||
IrqArgs *irqArgs = reinterpret_cast<IrqArgs *>(irqArgsVoid);
|
||||
if (irqArgs == nullptr) {
|
||||
return;
|
||||
}
|
||||
SpiCookie *spiCookie = irqArgs->spiCookie;
|
||||
SpiComIF *comIF = irqArgs->comIF;
|
||||
if (spiCookie == nullptr or comIF == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
spiCookie->setTransferState(targetState);
|
||||
|
||||
if(spiCookie->getChipSelectGpioPort() != nullptr) {
|
||||
// Pull CS pin high again
|
||||
HAL_GPIO_WritePin(spiCookie->getChipSelectGpioPort(), spiCookie->getChipSelectGpioPin(),
|
||||
GPIO_PIN_SET);
|
||||
}
|
||||
spiCookie->setTransferState(targetState);
|
||||
|
||||
if (spiCookie->getChipSelectGpioPort() != nullptr) {
|
||||
// Pull CS pin high again
|
||||
HAL_GPIO_WritePin(spiCookie->getChipSelectGpioPort(), spiCookie->getChipSelectGpioPin(),
|
||||
GPIO_PIN_SET);
|
||||
}
|
||||
|
||||
#if defined FSFW_OSAL_FREERTOS
|
||||
// Release the task semaphore
|
||||
BaseType_t taskWoken = pdFALSE;
|
||||
ReturnValue_t result = BinarySemaphore::releaseFromISR(comIF->spiSemaphore->getSemaphore(),
|
||||
&taskWoken);
|
||||
// Release the task semaphore
|
||||
BaseType_t taskWoken = pdFALSE;
|
||||
ReturnValue_t result =
|
||||
BinarySemaphore::releaseFromISR(comIF->spiSemaphore->getSemaphore(), &taskWoken);
|
||||
#elif defined FSFW_OSAL_RTEMS
|
||||
ReturnValue_t result = comIF->spiSemaphore->release();
|
||||
ReturnValue_t result = comIF->spiSemaphore->release();
|
||||
#endif
|
||||
if(result != HasReturnvaluesIF::RETURN_OK) {
|
||||
// Configuration error
|
||||
printf("SpiComIF::genericIrqHandler: Failure releasing Semaphore!\n");
|
||||
}
|
||||
if (result != HasReturnvaluesIF::RETURN_OK) {
|
||||
// Configuration error
|
||||
printf("SpiComIF::genericIrqHandler: Failure releasing Semaphore!\n");
|
||||
}
|
||||
|
||||
// Perform cache maintenance operation for DMA transfers
|
||||
if(spiCookie->getTransferMode() == spi::TransferModes::DMA) {
|
||||
// Invalidate cache prior to access by CPU
|
||||
SCB_InvalidateDCache_by_Addr ((uint32_t *) comIF->currentRecvPtr,
|
||||
comIF->currentRecvBuffSize);
|
||||
}
|
||||
// Perform cache maintenance operation for DMA transfers
|
||||
if (spiCookie->getTransferMode() == spi::TransferModes::DMA) {
|
||||
// Invalidate cache prior to access by CPU
|
||||
SCB_InvalidateDCache_by_Addr((uint32_t *)comIF->currentRecvPtr, comIF->currentRecvBuffSize);
|
||||
}
|
||||
#if defined FSFW_OSAL_FREERTOS
|
||||
/* Request a context switch if the SPI ComIF task was woken up and has a higher priority
|
||||
than the currently running task */
|
||||
if(taskWoken == pdTRUE) {
|
||||
TaskManagement::requestContextSwitch(CallContext::ISR);
|
||||
}
|
||||
/* Request a context switch if the SPI ComIF task was woken up and has a higher priority
|
||||
than the currently running task */
|
||||
if (taskWoken == pdTRUE) {
|
||||
TaskManagement::requestContextSwitch(CallContext::ISR);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void SpiComIF::printCfgError(const char *const type) {
|
||||
#if FSFW_CPP_OSTREAM_ENABLED == 1
|
||||
sif::warning << "SpiComIF::initializeInterface: Invalid " << type << " configuration"
|
||||
<< std::endl;
|
||||
sif::warning << "SpiComIF::initializeInterface: Invalid " << type << " configuration"
|
||||
<< std::endl;
|
||||
#else
|
||||
sif::printWarning("SpiComIF::initializeInterface: Invalid %s configuration\n", type);
|
||||
sif::printWarning("SpiComIF::initializeInterface: Invalid %s configuration\n", type);
|
||||
#endif
|
||||
}
|
||||
|
@ -1,16 +1,15 @@
|
||||
#ifndef FSFW_HAL_STM32H7_SPI_SPICOMIF_H_
|
||||
#define FSFW_HAL_STM32H7_SPI_SPICOMIF_H_
|
||||
|
||||
#include "fsfw/tasks/SemaphoreIF.h"
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
#include "fsfw/devicehandlers/DeviceCommunicationIF.h"
|
||||
#include "fsfw/objectmanager/SystemObject.h"
|
||||
|
||||
#include "fsfw/tasks/SemaphoreIF.h"
|
||||
#include "fsfw_hal/stm32h7/spi/spiDefinitions.h"
|
||||
#include "stm32h7xx_hal_spi.h"
|
||||
#include "stm32h743xx.h"
|
||||
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "stm32h7xx_hal_spi.h"
|
||||
|
||||
class SpiCookie;
|
||||
class BinarySemaphore;
|
||||
@ -28,102 +27,100 @@ class BinarySemaphore;
|
||||
* implementation limits the transfer mode for a given SPI bus.
|
||||
* @author R. Mueller
|
||||
*/
|
||||
class SpiComIF:
|
||||
public SystemObject,
|
||||
public DeviceCommunicationIF {
|
||||
public:
|
||||
/**
|
||||
* Create a SPI communication interface for the given SPI peripheral (spiInstance)
|
||||
* @param objectId
|
||||
* @param spiInstance
|
||||
* @param spiHandle
|
||||
* @param transferMode
|
||||
*/
|
||||
SpiComIF(object_id_t objectId);
|
||||
class SpiComIF : public SystemObject, public DeviceCommunicationIF {
|
||||
public:
|
||||
/**
|
||||
* Create a SPI communication interface for the given SPI peripheral (spiInstance)
|
||||
* @param objectId
|
||||
* @param spiInstance
|
||||
* @param spiHandle
|
||||
* @param transferMode
|
||||
*/
|
||||
SpiComIF(object_id_t objectId);
|
||||
|
||||
/**
|
||||
* Allows the user to disable cache maintenance on the TX buffer. This can be done if the
|
||||
* TX buffers are places and MPU protected properly like specified in this link:
|
||||
* https://community.st.com/s/article/FAQ-DMA-is-not-working-on-STM32H7-devices
|
||||
* The cache maintenace is enabled by default.
|
||||
* @param enable
|
||||
*/
|
||||
void configureCacheMaintenanceOnTxBuffer(bool enable);
|
||||
/**
|
||||
* Allows the user to disable cache maintenance on the TX buffer. This can be done if the
|
||||
* TX buffers are places and MPU protected properly like specified in this link:
|
||||
* https://community.st.com/s/article/FAQ-DMA-is-not-working-on-STM32H7-devices
|
||||
* The cache maintenace is enabled by default.
|
||||
* @param enable
|
||||
*/
|
||||
void configureCacheMaintenanceOnTxBuffer(bool enable);
|
||||
|
||||
void setDefaultPollingTimeout(dur_millis_t timeout);
|
||||
void setDefaultPollingTimeout(dur_millis_t timeout);
|
||||
|
||||
/**
|
||||
* Add the DMA handles. These need to be set in the DMA transfer mode is used.
|
||||
* @param txHandle
|
||||
* @param rxHandle
|
||||
*/
|
||||
void addDmaHandles(DMA_HandleTypeDef* txHandle, DMA_HandleTypeDef* rxHandle);
|
||||
/**
|
||||
* Add the DMA handles. These need to be set in the DMA transfer mode is used.
|
||||
* @param txHandle
|
||||
* @param rxHandle
|
||||
*/
|
||||
void addDmaHandles(DMA_HandleTypeDef* txHandle, DMA_HandleTypeDef* rxHandle);
|
||||
|
||||
ReturnValue_t initialize() override;
|
||||
ReturnValue_t initialize() override;
|
||||
|
||||
// DeviceCommunicationIF overrides
|
||||
virtual ReturnValue_t initializeInterface(CookieIF * cookie) override;
|
||||
virtual ReturnValue_t sendMessage(CookieIF *cookie,
|
||||
const uint8_t * sendData, size_t sendLen) override;
|
||||
virtual ReturnValue_t getSendSuccess(CookieIF *cookie) override;
|
||||
virtual ReturnValue_t requestReceiveMessage(CookieIF *cookie,
|
||||
size_t requestLen) override;
|
||||
virtual ReturnValue_t readReceivedMessage(CookieIF *cookie,
|
||||
uint8_t **buffer, size_t *size) override;
|
||||
// DeviceCommunicationIF overrides
|
||||
virtual ReturnValue_t initializeInterface(CookieIF* cookie) override;
|
||||
virtual ReturnValue_t sendMessage(CookieIF* cookie, const uint8_t* sendData,
|
||||
size_t sendLen) override;
|
||||
virtual ReturnValue_t getSendSuccess(CookieIF* cookie) override;
|
||||
virtual ReturnValue_t requestReceiveMessage(CookieIF* cookie, size_t requestLen) override;
|
||||
virtual ReturnValue_t readReceivedMessage(CookieIF* cookie, uint8_t** buffer,
|
||||
size_t* size) override;
|
||||
|
||||
protected:
|
||||
protected:
|
||||
struct SpiInstance {
|
||||
SpiInstance(size_t maxRecvSize) : replyBuffer(std::vector<uint8_t>(maxRecvSize)) {}
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
size_t currentTransferLen = 0;
|
||||
};
|
||||
|
||||
struct SpiInstance {
|
||||
SpiInstance(size_t maxRecvSize): replyBuffer(std::vector<uint8_t>(maxRecvSize)) {}
|
||||
std::vector<uint8_t> replyBuffer;
|
||||
size_t currentTransferLen = 0;
|
||||
};
|
||||
struct IrqArgs {
|
||||
SpiComIF* comIF = nullptr;
|
||||
SpiCookie* spiCookie = nullptr;
|
||||
};
|
||||
|
||||
struct IrqArgs {
|
||||
SpiComIF* comIF = nullptr;
|
||||
SpiCookie* spiCookie = nullptr;
|
||||
};
|
||||
IrqArgs irqArgs;
|
||||
|
||||
IrqArgs irqArgs;
|
||||
uint32_t defaultPollingTimeout = 50;
|
||||
|
||||
uint32_t defaultPollingTimeout = 50;
|
||||
SemaphoreIF::TimeoutType timeoutType = SemaphoreIF::TimeoutType::WAITING;
|
||||
dur_millis_t timeoutMs = 20;
|
||||
|
||||
SemaphoreIF::TimeoutType timeoutType = SemaphoreIF::TimeoutType::WAITING;
|
||||
dur_millis_t timeoutMs = 20;
|
||||
BinarySemaphore* spiSemaphore = nullptr;
|
||||
bool cacheMaintenanceOnTxBuffer = true;
|
||||
|
||||
BinarySemaphore* spiSemaphore = nullptr;
|
||||
bool cacheMaintenanceOnTxBuffer = true;
|
||||
using SpiDeviceMap = std::map<address_t, SpiInstance>;
|
||||
using SpiDeviceMapIter = SpiDeviceMap::iterator;
|
||||
|
||||
using SpiDeviceMap = std::map<address_t, SpiInstance>;
|
||||
using SpiDeviceMapIter = SpiDeviceMap::iterator;
|
||||
uint8_t* currentRecvPtr = nullptr;
|
||||
size_t currentRecvBuffSize = 0;
|
||||
|
||||
uint8_t* currentRecvPtr = nullptr;
|
||||
size_t currentRecvBuffSize = 0;
|
||||
SpiDeviceMap spiDeviceMap;
|
||||
|
||||
SpiDeviceMap spiDeviceMap;
|
||||
ReturnValue_t handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t* sendData,
|
||||
size_t sendLen);
|
||||
ReturnValue_t handleInterruptSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t* sendData,
|
||||
size_t sendLen);
|
||||
ReturnValue_t handleDmaSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t* sendData,
|
||||
size_t sendLen);
|
||||
ReturnValue_t handleIrqSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t* sendData,
|
||||
size_t sendLen);
|
||||
ReturnValue_t genericIrqSendSetup(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t* sendData, size_t sendLen);
|
||||
ReturnValue_t halErrorHandler(HAL_StatusTypeDef status, spi::TransferModes transferMode);
|
||||
|
||||
ReturnValue_t handlePollingSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen);
|
||||
ReturnValue_t handleInterruptSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen);
|
||||
ReturnValue_t handleDmaSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen);
|
||||
ReturnValue_t handleIrqSendOperation(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen);
|
||||
ReturnValue_t genericIrqSendSetup(uint8_t* recvPtr, SPI_HandleTypeDef& spiHandle,
|
||||
SpiCookie& spiCookie, const uint8_t * sendData, size_t sendLen);
|
||||
ReturnValue_t halErrorHandler(HAL_StatusTypeDef status, spi::TransferModes transferMode);
|
||||
static void spiTransferTxCompleteCallback(SPI_HandleTypeDef* hspi, void* args);
|
||||
static void spiTransferRxCompleteCallback(SPI_HandleTypeDef* hspi, void* args);
|
||||
static void spiTransferCompleteCallback(SPI_HandleTypeDef* hspi, void* args);
|
||||
static void spiTransferErrorCallback(SPI_HandleTypeDef* hspi, void* args);
|
||||
|
||||
static void spiTransferTxCompleteCallback(SPI_HandleTypeDef *hspi, void* args);
|
||||
static void spiTransferRxCompleteCallback(SPI_HandleTypeDef *hspi, void* args);
|
||||
static void spiTransferCompleteCallback(SPI_HandleTypeDef *hspi, void* args);
|
||||
static void spiTransferErrorCallback(SPI_HandleTypeDef *hspi, void* args);
|
||||
static void genericIrqHandler(void* irqArgs, spi::TransferStates targetState);
|
||||
|
||||
static void genericIrqHandler(void* irqArgs, spi::TransferStates targetState);
|
||||
|
||||
void printCfgError(const char* const type);
|
||||
void printCfgError(const char* const type);
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif /* FSFW_HAL_STM32H7_SPI_SPICOMIF_H_ */
|
||||
|
@ -1,78 +1,60 @@
|
||||
#include "fsfw_hal/stm32h7/spi/SpiCookie.h"
|
||||
|
||||
|
||||
SpiCookie::SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode,
|
||||
spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode,
|
||||
size_t maxRecvSize, stm32h7::GpioCfg csGpio):
|
||||
deviceAddress(deviceAddress), spiIdx(spiIdx), spiSpeed(spiSpeed), spiMode(spiMode),
|
||||
transferMode(transferMode), csGpio(csGpio),
|
||||
mspCfg(mspCfg), maxRecvSize(maxRecvSize) {
|
||||
spiHandle.Init.DataSize = SPI_DATASIZE_8BIT;
|
||||
spiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB;
|
||||
spiHandle.Init.TIMode = SPI_TIMODE_DISABLE;
|
||||
spiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
|
||||
spiHandle.Init.CRCPolynomial = 7;
|
||||
spiHandle.Init.CRCLength = SPI_CRC_LENGTH_8BIT;
|
||||
spiHandle.Init.NSS = SPI_NSS_SOFT;
|
||||
spiHandle.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
|
||||
spiHandle.Init.Direction = SPI_DIRECTION_2LINES;
|
||||
// Recommended setting to avoid glitches
|
||||
spiHandle.Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_ENABLE;
|
||||
spiHandle.Init.Mode = SPI_MODE_MASTER;
|
||||
spi::assignSpiMode(spiMode, spiHandle);
|
||||
spiHandle.Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), spiSpeed);
|
||||
spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode,
|
||||
size_t maxRecvSize, stm32h7::GpioCfg csGpio)
|
||||
: deviceAddress(deviceAddress),
|
||||
spiIdx(spiIdx),
|
||||
spiSpeed(spiSpeed),
|
||||
spiMode(spiMode),
|
||||
transferMode(transferMode),
|
||||
csGpio(csGpio),
|
||||
mspCfg(mspCfg),
|
||||
maxRecvSize(maxRecvSize) {
|
||||
spiHandle.Init.DataSize = SPI_DATASIZE_8BIT;
|
||||
spiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB;
|
||||
spiHandle.Init.TIMode = SPI_TIMODE_DISABLE;
|
||||
spiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
|
||||
spiHandle.Init.CRCPolynomial = 7;
|
||||
spiHandle.Init.CRCLength = SPI_CRC_LENGTH_8BIT;
|
||||
spiHandle.Init.NSS = SPI_NSS_SOFT;
|
||||
spiHandle.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
|
||||
spiHandle.Init.Direction = SPI_DIRECTION_2LINES;
|
||||
// Recommended setting to avoid glitches
|
||||
spiHandle.Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_ENABLE;
|
||||
spiHandle.Init.Mode = SPI_MODE_MASTER;
|
||||
spi::assignSpiMode(spiMode, spiHandle);
|
||||
spiHandle.Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), spiSpeed);
|
||||
}
|
||||
|
||||
uint16_t SpiCookie::getChipSelectGpioPin() const {
|
||||
return csGpio.pin;
|
||||
}
|
||||
uint16_t SpiCookie::getChipSelectGpioPin() const { return csGpio.pin; }
|
||||
|
||||
GPIO_TypeDef* SpiCookie::getChipSelectGpioPort() {
|
||||
return csGpio.port;
|
||||
}
|
||||
GPIO_TypeDef* SpiCookie::getChipSelectGpioPort() { return csGpio.port; }
|
||||
|
||||
address_t SpiCookie::getDeviceAddress() const {
|
||||
return deviceAddress;
|
||||
}
|
||||
address_t SpiCookie::getDeviceAddress() const { return deviceAddress; }
|
||||
|
||||
spi::SpiBus SpiCookie::getSpiIdx() const {
|
||||
return spiIdx;
|
||||
}
|
||||
spi::SpiBus SpiCookie::getSpiIdx() const { return spiIdx; }
|
||||
|
||||
spi::SpiModes SpiCookie::getSpiMode() const {
|
||||
return spiMode;
|
||||
}
|
||||
spi::SpiModes SpiCookie::getSpiMode() const { return spiMode; }
|
||||
|
||||
uint32_t SpiCookie::getSpiSpeed() const {
|
||||
return spiSpeed;
|
||||
}
|
||||
uint32_t SpiCookie::getSpiSpeed() const { return spiSpeed; }
|
||||
|
||||
size_t SpiCookie::getMaxRecvSize() const {
|
||||
return maxRecvSize;
|
||||
}
|
||||
size_t SpiCookie::getMaxRecvSize() const { return maxRecvSize; }
|
||||
|
||||
SPI_HandleTypeDef& SpiCookie::getSpiHandle() {
|
||||
return spiHandle;
|
||||
}
|
||||
SPI_HandleTypeDef& SpiCookie::getSpiHandle() { return spiHandle; }
|
||||
|
||||
spi::MspCfgBase* SpiCookie::getMspCfg() {
|
||||
return mspCfg;
|
||||
}
|
||||
spi::MspCfgBase* SpiCookie::getMspCfg() { return mspCfg; }
|
||||
|
||||
void SpiCookie::deleteMspCfg() {
|
||||
if(mspCfg != nullptr) {
|
||||
delete mspCfg;
|
||||
}
|
||||
if (mspCfg != nullptr) {
|
||||
delete mspCfg;
|
||||
}
|
||||
}
|
||||
|
||||
spi::TransferModes SpiCookie::getTransferMode() const {
|
||||
return transferMode;
|
||||
}
|
||||
spi::TransferModes SpiCookie::getTransferMode() const { return transferMode; }
|
||||
|
||||
void SpiCookie::setTransferState(spi::TransferStates transferState) {
|
||||
this->transferState = transferState;
|
||||
this->transferState = transferState;
|
||||
}
|
||||
|
||||
spi::TransferStates SpiCookie::getTransferState() const {
|
||||
return this->transferState;
|
||||
}
|
||||
spi::TransferStates SpiCookie::getTransferState() const { return this->transferState; }
|
||||
|
@ -1,16 +1,14 @@
|
||||
#ifndef FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_
|
||||
#define FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_
|
||||
|
||||
#include "spiDefinitions.h"
|
||||
#include "mspInit.h"
|
||||
#include "../definitions.h"
|
||||
|
||||
#include "fsfw/devicehandlers/CookieIF.h"
|
||||
|
||||
#include "stm32h743xx.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "../definitions.h"
|
||||
#include "fsfw/devicehandlers/CookieIF.h"
|
||||
#include "mspInit.h"
|
||||
#include "spiDefinitions.h"
|
||||
#include "stm32h743xx.h"
|
||||
|
||||
/**
|
||||
* @brief SPI cookie implementation for the STM32H7 device family
|
||||
* @details
|
||||
@ -18,63 +16,61 @@
|
||||
* SPI communication interface
|
||||
* @author R. Mueller
|
||||
*/
|
||||
class SpiCookie: public CookieIF {
|
||||
friend class SpiComIF;
|
||||
public:
|
||||
class SpiCookie : public CookieIF {
|
||||
friend class SpiComIF;
|
||||
|
||||
/**
|
||||
* Allows construction of a SPI cookie for a connected SPI device
|
||||
* @param deviceAddress
|
||||
* @param spiIdx SPI bus, e.g. SPI1 or SPI2
|
||||
* @param transferMode
|
||||
* @param mspCfg This is the MSP configuration. The user is expected to supply
|
||||
* a valid MSP configuration. See mspInit.h for functions
|
||||
* to create one.
|
||||
* @param spiSpeed
|
||||
* @param spiMode
|
||||
* @param chipSelectGpioPin GPIO port. Don't use a number here, use the 16 bit type
|
||||
* definitions supplied in the MCU header file! (e.g. GPIO_PIN_X)
|
||||
* @param chipSelectGpioPort GPIO port (e.g. GPIOA)
|
||||
* @param maxRecvSize Maximum expected receive size. Chose as small as possible.
|
||||
* @param csGpio Optional CS GPIO definition.
|
||||
*/
|
||||
SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode,
|
||||
spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode,
|
||||
size_t maxRecvSize, stm32h7::GpioCfg csGpio = stm32h7::GpioCfg(nullptr, 0, 0));
|
||||
public:
|
||||
/**
|
||||
* Allows construction of a SPI cookie for a connected SPI device
|
||||
* @param deviceAddress
|
||||
* @param spiIdx SPI bus, e.g. SPI1 or SPI2
|
||||
* @param transferMode
|
||||
* @param mspCfg This is the MSP configuration. The user is expected to supply
|
||||
* a valid MSP configuration. See mspInit.h for functions
|
||||
* to create one.
|
||||
* @param spiSpeed
|
||||
* @param spiMode
|
||||
* @param chipSelectGpioPin GPIO port. Don't use a number here, use the 16 bit type
|
||||
* definitions supplied in the MCU header file! (e.g. GPIO_PIN_X)
|
||||
* @param chipSelectGpioPort GPIO port (e.g. GPIOA)
|
||||
* @param maxRecvSize Maximum expected receive size. Chose as small as possible.
|
||||
* @param csGpio Optional CS GPIO definition.
|
||||
*/
|
||||
SpiCookie(address_t deviceAddress, spi::SpiBus spiIdx, spi::TransferModes transferMode,
|
||||
spi::MspCfgBase* mspCfg, uint32_t spiSpeed, spi::SpiModes spiMode, size_t maxRecvSize,
|
||||
stm32h7::GpioCfg csGpio = stm32h7::GpioCfg(nullptr, 0, 0));
|
||||
|
||||
uint16_t getChipSelectGpioPin() const;
|
||||
GPIO_TypeDef* getChipSelectGpioPort();
|
||||
address_t getDeviceAddress() const;
|
||||
spi::SpiBus getSpiIdx() const;
|
||||
spi::SpiModes getSpiMode() const;
|
||||
spi::TransferModes getTransferMode() const;
|
||||
uint32_t getSpiSpeed() const;
|
||||
size_t getMaxRecvSize() const;
|
||||
SPI_HandleTypeDef& getSpiHandle();
|
||||
uint16_t getChipSelectGpioPin() const;
|
||||
GPIO_TypeDef* getChipSelectGpioPort();
|
||||
address_t getDeviceAddress() const;
|
||||
spi::SpiBus getSpiIdx() const;
|
||||
spi::SpiModes getSpiMode() const;
|
||||
spi::TransferModes getTransferMode() const;
|
||||
uint32_t getSpiSpeed() const;
|
||||
size_t getMaxRecvSize() const;
|
||||
SPI_HandleTypeDef& getSpiHandle();
|
||||
|
||||
private:
|
||||
address_t deviceAddress;
|
||||
SPI_HandleTypeDef spiHandle = {};
|
||||
spi::SpiBus spiIdx;
|
||||
uint32_t spiSpeed;
|
||||
spi::SpiModes spiMode;
|
||||
spi::TransferModes transferMode;
|
||||
volatile spi::TransferStates transferState = spi::TransferStates::IDLE;
|
||||
stm32h7::GpioCfg csGpio;
|
||||
private:
|
||||
address_t deviceAddress;
|
||||
SPI_HandleTypeDef spiHandle = {};
|
||||
spi::SpiBus spiIdx;
|
||||
uint32_t spiSpeed;
|
||||
spi::SpiModes spiMode;
|
||||
spi::TransferModes transferMode;
|
||||
volatile spi::TransferStates transferState = spi::TransferStates::IDLE;
|
||||
stm32h7::GpioCfg csGpio;
|
||||
|
||||
// The MSP configuration is cached here. Be careful when using this, it is automatically
|
||||
// deleted by the SPI communication interface if it is not required anymore!
|
||||
spi::MspCfgBase* mspCfg = nullptr;
|
||||
const size_t maxRecvSize;
|
||||
// The MSP configuration is cached here. Be careful when using this, it is automatically
|
||||
// deleted by the SPI communication interface if it is not required anymore!
|
||||
spi::MspCfgBase* mspCfg = nullptr;
|
||||
const size_t maxRecvSize;
|
||||
|
||||
// Only the SpiComIF is allowed to use this to prevent dangling pointers issues
|
||||
spi::MspCfgBase* getMspCfg();
|
||||
void deleteMspCfg();
|
||||
// Only the SpiComIF is allowed to use this to prevent dangling pointers issues
|
||||
spi::MspCfgBase* getMspCfg();
|
||||
void deleteMspCfg();
|
||||
|
||||
void setTransferState(spi::TransferStates transferState);
|
||||
spi::TransferStates getTransferState() const;
|
||||
void setTransferState(spi::TransferStates transferState);
|
||||
spi::TransferStates getTransferState() const;
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif /* FSFW_HAL_STM32H7_SPI_SPICOOKIE_H_ */
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user