From 4b614541528dc3c2593020cf0bbb58fdebc37e1d Mon Sep 17 00:00:00 2001 From: Reg Marr Date: Sat, 23 Nov 2024 13:07:25 -0500 Subject: [PATCH] Applied fprime-util formatting --- .env | 1 - FlightComputer/CCSDSTester/CCSDSTester.cpp | 23 +- FlightComputer/CCSDSTester/CCSDSTester.fpp | 143 +++++---- FlightComputer/CCSDSTester/CCSDSTester.hpp | 2 +- FlightComputer/Common/Common.hpp | 16 +- .../FlightSequencer/FlightSequencer.cpp | 292 +++++++++-------- .../FlightSequencer/FlightSequencer.hpp | 97 +++--- FlightComputer/PingReceiver/PingReceiver.hpp | 2 +- .../PingReceiverComponentImpl.cpp | 64 ++-- .../PingReceiverComponentImpl.hpp | 77 ++--- FlightComputer/Top/FlightComputerTopology.cpp | 296 ++++++++++-------- FlightComputer/Top/FlightComputerTopology.hpp | 80 +++-- .../Top/FlightComputerTopologyDefs.cpp | 10 +- .../Top/FlightComputerTopologyDefs.hpp | 108 ++++--- FlightComputer/Top/Main.cpp | 215 ++++++------- run.sh | 61 +++- 16 files changed, 794 insertions(+), 693 deletions(-) diff --git a/.env b/.env index 31ee914..8f2f91e 100644 --- a/.env +++ b/.env @@ -12,4 +12,3 @@ BIN_DIR="${DEPLOYMENT_ROOT}/build-artifacts/Linux/FlightComputer/bin/" DICT_DIR="${DEPLOYMENT_ROOT}/build-artifacts/Linux/FlightComputer/dict/" START_MODE=${START_MODE:-"--rm"} GDS_IP="127.0.0.1" -SCRIPT_DIR="." diff --git a/FlightComputer/CCSDSTester/CCSDSTester.cpp b/FlightComputer/CCSDSTester/CCSDSTester.cpp index 7b8b891..1110579 100644 --- a/FlightComputer/CCSDSTester/CCSDSTester.cpp +++ b/FlightComputer/CCSDSTester/CCSDSTester.cpp @@ -125,11 +125,13 @@ void CCSDSTester::PING_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq) { U32 dfltMessage = 0x9944fead; com.resetSer(); - Fw::ComPacket::ComPacketType packetType = Fw::ComPacket::ComPacketType::FW_PACKET_COMMAND; + Fw::ComPacket::ComPacketType packetType = + Fw::ComPacket::ComPacketType::FW_PACKET_COMMAND; com.serialize(packetType); com.serialize(dfltMessage); PktSend_out(0, com, 0); + // cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); } void CCSDSTester::MESSAGE_cmdHandler(const FwOpcodeType opCode, @@ -142,10 +144,13 @@ void CCSDSTester::MESSAGE_cmdHandler(const FwOpcodeType opCode, Fw::Logger::log("Not Ready"); } Fw::ComBuffer com; + com.resetSer(); + // U32 starter = 0xFFFF; // com.serialize(starter); U8 packetType = Fw::ComPacket::ComPacketType::FW_PACKET_FILE; + com.serialize(packetType); com.serialize(str1); @@ -154,16 +159,24 @@ void CCSDSTester::MESSAGE_cmdHandler(const FwOpcodeType opCode, // cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); } -Drv::SendStatus CCSDSTester::drvSend_handler(FwIndexType portNum, Fw::Buffer & buffer) { +Drv::SendStatus CCSDSTester::drvSend_handler(FwIndexType portNum, + Fw::Buffer &buffer) { Types::CircularBuffer circBoi(buffer.getData(), buffer.getSize()); - Fw::SerializeStatus stat = circBoi.serialize(buffer.getData(), buffer.getSize()); + Fw::SerializeStatus stat = + circBoi.serialize(buffer.getData(), buffer.getSize()); circBoi.print(); U8 btt = 0; circBoi.peek(btt, 0); - Fw::Logger::log("circBoi %x %d alloc %d cap %d\n", btt, stat, circBoi.get_allocated_size(), circBoi.get_capacity()); + Fw::Logger::log("circBoi %x %d alloc %d cap %d\n", btt, stat, "THis is bad", + circBoi.get_allocated_size(), circBoi.get_capacity()); + + Fw::Logger::log("I dont now"); + + circBoi.print(); - // Svc::FrameDetector::Status status = Svc::FrameDetector::Status::FRAME_DETECTED; + // Svc::FrameDetector::Status status = + // Svc::FrameDetector::Status::FRAME_DETECTED; // Svc::FrameDetectors::TMSpaceDataLinkDetector ccsdsFrameDetector; // FwSizeType size_out = 0; diff --git a/FlightComputer/CCSDSTester/CCSDSTester.fpp b/FlightComputer/CCSDSTester/CCSDSTester.fpp index ac21f94..b9164b5 100644 --- a/FlightComputer/CCSDSTester/CCSDSTester.fpp +++ b/FlightComputer/CCSDSTester/CCSDSTester.fpp @@ -1,99 +1,98 @@ module FlightComputer { - @ Loopback CCSDS Testing component - active component CCSDSTester { - ############################################################################### - # Standard AC Ports: Required for Channels, Events, Commands, and Parameters # - ############################################################################### - @ Port for requesting the current time - time get port timeCaller - @ Port for sending command registrations - command reg port cmdRegOut + @ Loopback CCSDS Testing component + active component CCSDSTester { - @ Port for receiving commands - command recv port cmdIn + ############################################################################### + # Standard AC Ports: Required for Channels, Events, Commands, and Parameters # + ############################################################################### + @ Port for requesting the current time + time get port timeCaller - @ Port for sending command responses - command resp port cmdResponseOut + @ Port for sending command registrations + command reg port cmdRegOut - @ Port for sending textual representation of events - text event port logTextOut + @ Port for receiving commands + command recv port cmdIn - @ Port for sending events to downlink - event port logOut + @ Port for sending command responses + command resp port cmdResponseOut - @ Port for sending telemetry channels to downlink - telemetry port tlmOut + @ Port for sending textual representation of events + text event port logTextOut - @ Port to return the value of a parameter - param get port prmGetOut + @ Port for sending events to downlink + event port logOut - @Port to set the value of a parameter - param set port prmSetOut + @ Port for sending telemetry channels to downlink + telemetry port tlmOut + @ Port to return the value of a parameter + param get port prmGetOut - ############################################################################## - #### Test interface #### - ############################################################################## + @ Port to set the value of a parameter + param set port prmSetOut - @ Output Command Status Port - output port seqCmdStatus: [CmdDispatcherSequencePorts] Fw.CmdResponse + ############################################################################## + #### Test interface #### + ############################################################################## + @ Output Command Status Port + output port seqCmdStatus: [CmdDispatcherSequencePorts] Fw.CmdResponse - @ Command buffer input port for sequencers or other sources of command buffers - async input port seqCmdBuff: [CmdDispatcherSequencePorts] Fw.Com + @ Command buffer input port for sequencers or other sources of command buffers + async input port seqCmdBuff: [CmdDispatcherSequencePorts] Fw.Com - # ---------------------------------------------------------------------- - # Port matching specifiers - # ---------------------------------------------------------------------- - match seqCmdStatus with seqCmdBuff + # ---------------------------------------------------------------------- + # Port matching specifiers + # ---------------------------------------------------------------------- + match seqCmdStatus with seqCmdBuff - # ---------------------------------------------------------------------- - # General Ports - # ---------------------------------------------------------------------- + # ---------------------------------------------------------------------- + # General Ports + # ---------------------------------------------------------------------- + @ Buffer send in + async input port bufferSendIn: Fw.BufferSend - @ Buffer send in - async input port bufferSendIn: Fw.BufferSend + @ Buffer send out + output port bufferSendOut: Fw.BufferSend - @ Buffer send out - output port bufferSendOut: Fw.BufferSend + @ Packet send port + output port PktSend: Fw.Com - @ Packet send port - output port PktSend: Fw.Com + @ Port for receiving the status signal + async input port comStatusIn: Fw.SuccessCondition - @ Port for receiving the status signal - async input port comStatusIn: Fw.SuccessCondition + # DrvMockPorts + @ Port invoked when the driver is ready to send/receive data + output port drvReady: Drv.ByteStreamReady - # DrvMockPorts - @ Port invoked when the driver is ready to send/receive data - output port drvReady: Drv.ByteStreamReady + @ Port invoked when driver has received data + output port drvRcv: Drv.ByteStreamRecv - @ Port invoked when driver has received data - output port drvRcv: Drv.ByteStreamRecv + @ Port invoked to send data out the driver + guarded input port drvSend: Drv.ByteStreamSend - @ Port invoked to send data out the driver - guarded input port drvSend: Drv.ByteStreamSend + # @ Buffer return input port + # async input port bufferReturn: Fw.BufferSend + # @ Receives raw data from a ByteStreamDriver, ComStub, or other buffer producing component + # guarded input port dataIn: Drv.ByteStreamRecv + # Loopback output + # @ Port invoked when driver has received data + # output port $recv: Drv.ByteStreamRecv + # @ Port invoked to send data out the driver + # guarded input port $send: Drv.ByteStreamSend + # output port allocate: Fw.BufferGet + output port bufferDeallocate: Fw.BufferSend - # @ Buffer return input port - # async input port bufferReturn: Fw.BufferSend + @ Simple command received interface + async command PING - # @ Receives raw data from a ByteStreamDriver, ComStub, or other buffer producing component - # guarded input port dataIn: Drv.ByteStreamRecv + @ Simple command received interface + # async command LONG_MESSAGE(str1: string) + async command MESSAGE( + str1: string size 50 + ) - # Loopback output - # @ Port invoked when driver has received data - # output port $recv: Drv.ByteStreamRecv + } - # @ Port invoked to send data out the driver - # guarded input port $send: Drv.ByteStreamSend - - # output port allocate: Fw.BufferGet - output port bufferDeallocate: Fw.BufferSend - - @ Simple command received interface - async command PING - - @ Simple command received interface - async command MESSAGE(str1: string size 50) - # async command LONG_MESSAGE(str1: string) - } } diff --git a/FlightComputer/CCSDSTester/CCSDSTester.hpp b/FlightComputer/CCSDSTester/CCSDSTester.hpp index 5fd7917..12649f6 100644 --- a/FlightComputer/CCSDSTester/CCSDSTester.hpp +++ b/FlightComputer/CCSDSTester/CCSDSTester.hpp @@ -49,7 +49,7 @@ class CCSDSTester : public CCSDSTesterComponentBase { Fw::Success &condition //!< Condition success/failure ); - Drv::SendStatus drvSend_handler(FwIndexType, Fw::Buffer&); + Drv::SendStatus drvSend_handler(FwIndexType, Fw::Buffer &); // Commands void PING_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq); diff --git a/FlightComputer/Common/Common.hpp b/FlightComputer/Common/Common.hpp index 6e1379c..db410de 100644 --- a/FlightComputer/Common/Common.hpp +++ b/FlightComputer/Common/Common.hpp @@ -1,13 +1,13 @@ #ifndef COMMON_H_ #define COMMON_H_ -#define FW_CHECK(cond, err_string, ...) \ - do { \ - if (!(cond)) { \ - Fw::Logger::log(err_string); \ - __VA_ARGS__; \ - break; \ - } \ - } while(0); +#define FW_CHECK(cond, err_string, ...) \ + do { \ + if (!(cond)) { \ + Fw::Logger::log(err_string); \ + __VA_ARGS__; \ + break; \ + } \ + } while (0); #endif // COMMON_H_ diff --git a/FlightComputer/FlightSequencer/FlightSequencer.cpp b/FlightComputer/FlightSequencer/FlightSequencer.cpp index 10cf847..70407d1 100644 --- a/FlightComputer/FlightSequencer/FlightSequencer.cpp +++ b/FlightComputer/FlightSequencer/FlightSequencer.cpp @@ -3,196 +3,188 @@ // \brief cpp file for TransmitterInterface component implementation class // ====================================================================== -/*** INCLUDES ***************************************************************************************************************************/ +/*** INCLUDES + * ***************************************************************************************************************************/ -#include -#include +#include "FlightSequencer.hpp" #include "Drv/DataTypes/DataBuffer.hpp" #include "FlightComputer/Common/Common.hpp" #include "FlightComputer/FlightSequencer/FlightSequencer_FlightSMStatesEnumAc.hpp" #include "FlightComputer/FlightSequencer/FppConstantsAc.hpp" #include "FlightSM.hpp" -#include "FlightSequencer.hpp" #include "Fw/Sm/SmSignalBuffer.hpp" #include "Fw/Time/Time.hpp" #include "Fw/Types/BasicTypes.hpp" +#include #include //To log debug text +#include #include #include #include #include -#include "FlightComputer/Common/Common.hpp" - namespace FlightComputer { - FlightSequencer :: - FlightSequencer( - const char *const compName - ) : FlightSequencerComponentBase(compName), FlightSM_Interface(), flightSM(this), signalLock() - { - - } - - FlightSequencer ::~FlightSequencer() {} - - // Check if T-burn time is reached using Fw::Time - bool FlightSequencer::FlightSM_isTBurnReached(const FwEnumStoreType stateMachineId) { +FlightSequencer ::FlightSequencer(const char *const compName) + : FlightSequencerComponentBase(compName), FlightSM_Interface(), + flightSM(this), signalLock() {} - Fw::Time currentTime = Fw::Time(timeCnt++, 0); // Get the current time - Fw::Time burnDuration = Fw::Time(250, 0); // Burn time (tburn) in seconds - return currentTime >= burnDuration; // Check if burn time is reached - } - - void FlightSequencer::FlightSM_checkLowAltReached(const FwEnumStoreType stateMachineId) { - if (status.getaltitudeM() < 50) { - Fw::SmSignalBuffer data; - signalLock.lock(); - - lastSignal = FlightSM_Signals::TERMINATE_SIG; - flightSM.update(this->stateMachineId, lastSignal, data); +FlightSequencer ::~FlightSequencer() {} - signalLock.unLock(); - } - } - - // Initialize flight status at the beginning of the flight using Fw::Time - void FlightSequencer::FlightSM_initFlightStatus(const FwEnumStoreType stateMachineId) { - // Reset the flight status to start simulation - Fw::Logger::log("Init flight status\n"); - timeCnt = 0; +// Check if T-burn time is reached using Fw::Time +bool FlightSequencer::FlightSM_isTBurnReached( + const FwEnumStoreType stateMachineId) { - status.set(false, 0.0, 0.0, FlightSequencer_FlightSMStates::IDLE); // Reset time, engine state, altitude, and velocity - } + Fw::Time currentTime = Fw::Time(timeCnt++, 0); // Get the current time + Fw::Time burnDuration = Fw::Time(250, 0); // Burn time (tburn) in seconds + return currentTime >= burnDuration; // Check if burn time is reached +} - // Engage thrust (transition from Idle to Powered flight) - void FlightSequencer::FlightSM_engageThrust(const FwEnumStoreType stateMachineId) { - Fw::Logger::log("Engaging thrust\n"); - status.setisEngineOn(true); // Set engine ON - } +void FlightSequencer::FlightSM_checkLowAltReached( + const FwEnumStoreType stateMachineId) { + if (status.getaltitudeM() < 50) { + Fw::SmSignalBuffer data; + signalLock.lock(); - // Disengage thrust (transition from Powered flight to Ballistic flight) - void FlightSequencer::FlightSM_disengageThrust(const FwEnumStoreType stateMachineId) { - Fw::Logger::log("Disengaging thrust\n"); - status.setisEngineOn(false); // Set engine OFF - } + lastSignal = FlightSM_Signals::TERMINATE_SIG; + flightSM.update(this->stateMachineId, lastSignal, data); - // Update flight status using Fw::Time for time intervals - void FlightSequencer::FlightSM_updateFlightStatus(const FwEnumStoreType stateMachineId) { - // Get current status parameters - F32 velocity = status.getvelocityMS(); // Get current velocity - F32 altitude = status.getaltitudeM(); // Get current altitude - - Fw::Time dt = Fw::Time(1, 0); // Define a 1-second timestep - - if (status.getisEngineOn()) { - // Powered flight phase - velocity += (FlightSequencer_thrustN / FlightSequencer_massKg - FlightSequencer_gravityMSS) * dt.getSeconds(); // Calculate velocity during powered flight - } else { - // Ballistic flight phase (free fall) - velocity += (-FlightSequencer_gravityMSS) * dt.getSeconds(); // Calculate velocity during free fall - } - - altitude += velocity * dt.getSeconds(); // Update altitude based on new velocity - - // Update time, velocity, and altitude in the status - // status.setflightTimeS(status.getflightTimeS() + dt.getSeconds()); // Increment current time by dt - status.setvelocityMS(velocity); // Set updated velocity - status.setaltitudeM(altitude); // Set updated altitude + signalLock.unLock(); } - - void FlightSequencer :: - init( - const NATIVE_INT_TYPE queueDepth, - const NATIVE_INT_TYPE instance - ) - { - FlightSequencerComponentBase::init(queueDepth, instance); - flightSM.init(this->stateMachineId); - Fw::Logger::log("SM state on init %d\n", flightSM.state); +} + +// Initialize flight status at the beginning of the flight using Fw::Time +void FlightSequencer::FlightSM_initFlightStatus( + const FwEnumStoreType stateMachineId) { + // Reset the flight status to start simulation + Fw::Logger::log("Init flight status\n"); + timeCnt = 0; + + status.set(false, 0.0, 0.0, + FlightSequencer_FlightSMStates::IDLE); // Reset time, engine state, + // altitude, and velocity +} + +// Engage thrust (transition from Idle to Powered flight) +void FlightSequencer::FlightSM_engageThrust( + const FwEnumStoreType stateMachineId) { + Fw::Logger::log("Engaging thrust\n"); + status.setisEngineOn(true); // Set engine ON +} + +// Disengage thrust (transition from Powered flight to Ballistic flight) +void FlightSequencer::FlightSM_disengageThrust( + const FwEnumStoreType stateMachineId) { + Fw::Logger::log("Disengaging thrust\n"); + status.setisEngineOn(false); // Set engine OFF +} + +// Update flight status using Fw::Time for time intervals +void FlightSequencer::FlightSM_updateFlightStatus( + const FwEnumStoreType stateMachineId) { + // Get current status parameters + F32 velocity = status.getvelocityMS(); // Get current velocity + F32 altitude = status.getaltitudeM(); // Get current altitude + + Fw::Time dt = Fw::Time(1, 0); // Define a 1-second timestep + + if (status.getisEngineOn()) { + // Powered flight phase + velocity += (FlightSequencer_thrustN / FlightSequencer_massKg - + FlightSequencer_gravityMSS) * + dt.getSeconds(); // Calculate velocity during powered flight + } else { + // Ballistic flight phase (free fall) + velocity += (-FlightSequencer_gravityMSS) * + dt.getSeconds(); // Calculate velocity during free fall } - // ---------------------------------------------------------------------- - // Handler implementations for user-defined typed input ports - // ---------------------------------------------------------------------- - - bool FlightSequencer ::updateTlms() { - tlmWrite_flightStatus(status); - return true; + altitude += + velocity * dt.getSeconds(); // Update altitude based on new velocity + + // Update time, velocity, and altitude in the status + // status.setflightTimeS(status.getflightTimeS() + dt.getSeconds()); // + // Increment current time by dt + status.setvelocityMS(velocity); // Set updated velocity + status.setaltitudeM(altitude); // Set updated altitude +} + +void FlightSequencer ::init(const NATIVE_INT_TYPE queueDepth, + const NATIVE_INT_TYPE instance) { + FlightSequencerComponentBase::init(queueDepth, instance); + flightSM.init(this->stateMachineId); + Fw::Logger::log("SM state on init %d\n", flightSM.state); +} + +// ---------------------------------------------------------------------- +// Handler implementations for user-defined typed input ports +// ---------------------------------------------------------------------- + +bool FlightSequencer ::updateTlms() { + tlmWrite_flightStatus(status); + return true; +} + +void FlightSequencer ::run_handler(const NATIVE_INT_TYPE portNum, + NATIVE_UINT_TYPE context) { + + FW_CHECK(updateTlms(), "Failed to update tlms"); + + Fw::CmdResponse ret = Fw::CmdResponse::OK; + + Fw::SmSignalBuffer data; + signalLock.lock(); + // Once every few calls, send the TBURN_CHECK_SIG signal + if (signalCounter++ >= 2) { + lastSignal = FlightSM_Signals::TBURN_CHECK_INTERVAL_SIG; + signalCounter = + 0; // Reset the counter after sending the TBURN_CHECK_SIG signal + } else { + lastSignal = FlightSM_Signals::UPDATE_INTERVAL_SIG; } - void FlightSequencer :: - run_handler( - const NATIVE_INT_TYPE portNum, - NATIVE_UINT_TYPE context - ) - { + // FIXME Using static_cast to convert the integer to the enum type + FlightSequencer_FlightSMStates::T stateEnum = + static_cast(flightSM.state); - FW_CHECK(updateTlms(), "Failed to update tlms"); + status.setcurrentState(stateEnum); - Fw::CmdResponse ret = Fw::CmdResponse::OK; - - Fw::SmSignalBuffer data; - signalLock.lock(); - // Once every few calls, send the TBURN_CHECK_SIG signal - if (signalCounter++ >= 2) { - lastSignal = FlightSM_Signals::TBURN_CHECK_INTERVAL_SIG; - signalCounter = 0; // Reset the counter after sending the TBURN_CHECK_SIG signal - } else { - lastSignal = FlightSM_Signals::UPDATE_INTERVAL_SIG; - } + signalLock.unlock(); - // FIXME Using static_cast to convert the integer to the enum type - FlightSequencer_FlightSMStates::T stateEnum = static_cast(flightSM.state); + flightSM.update(this->stateMachineId, lastSignal, data); - status.setcurrentState(stateEnum); + FW_CHECK(ret == Fw::CmdResponse::OK, "Run Failed, aborting", + this->TERMINATE_cmdHandler(0, 10)) +} - signalLock.unlock(); +// ---------------------------------------------------------------------- +// Command handler implementations +// ---------------------------------------------------------------------- - flightSM.update(this->stateMachineId, lastSignal, data); +void FlightSequencer ::IGNITE_cmdHandler(const FwOpcodeType opCode, + const U32 cmdSeq) { + signalLock.lock(); - FW_CHECK(ret == Fw::CmdResponse::OK, - "Run Failed, aborting", - this->TERMINATE_cmdHandler(0, 10)) - } + Fw::SmSignalBuffer data; + lastSignal = FlightSM_Signals::IGNITE_SIG; + flightSM.update(this->stateMachineId, lastSignal, data); - // ---------------------------------------------------------------------- - // Command handler implementations - // ---------------------------------------------------------------------- + signalLock.unLock(); - void FlightSequencer :: - IGNITE_cmdHandler( - const FwOpcodeType opCode, - const U32 cmdSeq - ) - { - signalLock.lock(); + cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); +} - Fw::SmSignalBuffer data; - lastSignal = FlightSM_Signals::IGNITE_SIG; - flightSM.update(this->stateMachineId, lastSignal, data); +void FlightSequencer ::TERMINATE_cmdHandler(const FwOpcodeType opCode, + const U32 cmdSeq) { + Fw::SmSignalBuffer data; + signalLock.lock(); - signalLock.unLock(); + lastSignal = FlightSM_Signals::TERMINATE_SIG; + flightSM.update(this->stateMachineId, lastSignal, data); + signalLock.unLock(); - cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); - } - - void FlightSequencer :: - TERMINATE_cmdHandler( - const FwOpcodeType opCode, - const U32 cmdSeq - ) - { - Fw::SmSignalBuffer data; - signalLock.lock(); - - lastSignal = FlightSM_Signals::TERMINATE_SIG; - flightSM.update(this->stateMachineId, lastSignal, data); - - signalLock.unLock(); - - cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); - } + cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); +} } // end namespace FlightComputer diff --git a/FlightComputer/FlightSequencer/FlightSequencer.hpp b/FlightComputer/FlightSequencer/FlightSequencer.hpp index 460e7b8..b4ac5de 100644 --- a/FlightComputer/FlightSequencer/FlightSequencer.hpp +++ b/FlightComputer/FlightSequencer/FlightSequencer.hpp @@ -3,72 +3,67 @@ #define FlightSequencer_HPP #include "FlightComputer/FlightSequencer/FlightSM.hpp" +#include "FlightComputer/FlightSequencer/FlightSequencerComponentAc.hpp" #include "FlightComputer/FlightSequencer/FlightSequencer_FlightSMStatesEnumAc.hpp" #include "FlightComputer/FlightSequencer/FlightSequencer_statusSerializableAc.hpp" #include "Fw/Types/BasicTypes.hpp" -#include "FlightComputer/FlightSequencer/FlightSequencerComponentAc.hpp" #include "Os/Mutex.hpp" namespace FlightComputer { - class FlightSequencer : - public FlightSequencerComponentBase, public FlightSM_Interface - { - - public: +class FlightSequencer : public FlightSequencerComponentBase, + public FlightSM_Interface { - // ---------------------------------------------------------------------- - // Construction, initialization, and destruction - // ---------------------------------------------------------------------- +public: + // ---------------------------------------------------------------------- + // Construction, initialization, and destruction + // ---------------------------------------------------------------------- - //! Construct object FlightSequencer - //! - FlightSequencer( - const char *const compName /*!< The component name*/ - ); + //! Construct object FlightSequencer + //! + FlightSequencer(const char *const compName /*!< The component name*/ + ); - //! Initialize object TransmitterInterface - //! - void init( - const NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/ + //! Initialize object TransmitterInterface + //! + void init(const NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/ const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/ - ); - - //! Destroy object FlightSequencer - //! - ~FlightSequencer(); - - // TODO we should see if this definition is neccessary - virtual bool FlightSM_isTBurnReached(const FwEnumStoreType stateMachineId); - virtual void FlightSM_engageThrust(const FwEnumStoreType stateMachineId); - virtual void FlightSM_disengageThrust(const FwEnumStoreType stateMachineId); - virtual void FlightSM_initFlightStatus(const FwEnumStoreType stateMachineId); - virtual void FlightSM_updateFlightStatus(const FwEnumStoreType stateMachineId); - virtual void FlightSM_checkLowAltReached(const FwEnumStoreType stateMachineId); + ); - PRIVATE: + //! Destroy object FlightSequencer + //! + ~FlightSequencer(); - FwSizeType signalCounter; - FlightSequencer_status status; // = {0, false, 0, 0}; - FlightSM flightSM; - FlightSM_Signals lastSignal = FlightSM_Signals::TERMINATE_SIG; - FwEnumStoreType stateMachineId = 1; - Os::Mutex signalLock; - U32 timeCnt =0; + // TODO we should see if this definition is neccessary + virtual bool FlightSM_isTBurnReached(const FwEnumStoreType stateMachineId); + virtual void FlightSM_engageThrust(const FwEnumStoreType stateMachineId); + virtual void FlightSM_disengageThrust(const FwEnumStoreType stateMachineId); + virtual void FlightSM_initFlightStatus(const FwEnumStoreType stateMachineId); + virtual void + FlightSM_updateFlightStatus(const FwEnumStoreType stateMachineId); + virtual void + FlightSM_checkLowAltReached(const FwEnumStoreType stateMachineId); - bool updateTlms(); +PRIVATE: + FwSizeType signalCounter; + FlightSequencer_status status; // = {0, false, 0, 0}; + FlightSM flightSM; + FlightSM_Signals lastSignal = FlightSM_Signals::TERMINATE_SIG; + FwEnumStoreType stateMachineId = 1; + Os::Mutex signalLock; + U32 timeCnt = 0; - //! Handler implementation for run - //! - void run_handler( - const NATIVE_INT_TYPE portNum, /*!< The port number*/ - NATIVE_UINT_TYPE context /*!< - The call order - */ - ); - void IGNITE_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq); - void TERMINATE_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq); + bool updateTlms(); - }; + //! Handler implementation for run + //! + void run_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ + NATIVE_UINT_TYPE context /*!< + The call order + */ + ); + void IGNITE_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq); + void TERMINATE_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq); +}; } // end namespace FlightComputer #endif diff --git a/FlightComputer/PingReceiver/PingReceiver.hpp b/FlightComputer/PingReceiver/PingReceiver.hpp index 0f94361..2ae8a13 100644 --- a/FlightComputer/PingReceiver/PingReceiver.hpp +++ b/FlightComputer/PingReceiver/PingReceiver.hpp @@ -10,7 +10,7 @@ namespace FlightComputer { - typedef PingReceiverComponentImpl PingReceiver; +typedef PingReceiverComponentImpl PingReceiver; } diff --git a/FlightComputer/PingReceiver/PingReceiverComponentImpl.cpp b/FlightComputer/PingReceiver/PingReceiverComponentImpl.cpp index 7192ee2..6ff20ac 100644 --- a/FlightComputer/PingReceiver/PingReceiverComponentImpl.cpp +++ b/FlightComputer/PingReceiver/PingReceiverComponentImpl.cpp @@ -10,53 +10,41 @@ // // ====================================================================== - #include #include namespace FlightComputer { - // ---------------------------------------------------------------------- - // Construction, initialization, and destruction - // ---------------------------------------------------------------------- - - PingReceiverComponentImpl :: - PingReceiverComponentImpl( - const char *const compName - ) : PingReceiverComponentBase(compName), m_inhibitPings(false), m_pingsRecvd(0) - { - - } +// ---------------------------------------------------------------------- +// Construction, initialization, and destruction +// ---------------------------------------------------------------------- - PingReceiverComponentImpl :: - ~PingReceiverComponentImpl() - { +PingReceiverComponentImpl ::PingReceiverComponentImpl( + const char *const compName) + : PingReceiverComponentBase(compName), m_inhibitPings(false), + m_pingsRecvd(0) {} - } +PingReceiverComponentImpl ::~PingReceiverComponentImpl() {} - // ---------------------------------------------------------------------- - // Handler implementations for user-defined typed input ports - // ---------------------------------------------------------------------- - - void PingReceiverComponentImpl :: - PingIn_handler( - const NATIVE_INT_TYPE portNum, - U32 key - ) - { - //this->log_DIAGNOSTIC_PR_PingReceived(key); - this->tlmWrite_PR_NumPings(this->m_pingsRecvd++); - if (not this->m_inhibitPings) { - PingOut_out(0,key); - } - } +// ---------------------------------------------------------------------- +// Handler implementations for user-defined typed input ports +// ---------------------------------------------------------------------- - void PingReceiverComponentImpl::PR_StopPings_cmdHandler( - FwOpcodeType opCode, /*!< The opcode*/ - U32 cmdSeq /*!< The command sequence number*/ - ) { - this->m_inhibitPings = true; - this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); +void PingReceiverComponentImpl ::PingIn_handler(const NATIVE_INT_TYPE portNum, + U32 key) { + // this->log_DIAGNOSTIC_PR_PingReceived(key); + this->tlmWrite_PR_NumPings(this->m_pingsRecvd++); + if (not this->m_inhibitPings) { + PingOut_out(0, key); } +} + +void PingReceiverComponentImpl::PR_StopPings_cmdHandler( + FwOpcodeType opCode, /*!< The opcode*/ + U32 cmdSeq /*!< The command sequence number*/ +) { + this->m_inhibitPings = true; + this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); +} } // end namespace FlightComputer diff --git a/FlightComputer/PingReceiver/PingReceiverComponentImpl.hpp b/FlightComputer/PingReceiver/PingReceiverComponentImpl.hpp index bd57350..179ac29 100644 --- a/FlightComputer/PingReceiver/PingReceiverComponentImpl.hpp +++ b/FlightComputer/PingReceiver/PingReceiverComponentImpl.hpp @@ -17,49 +17,40 @@ namespace FlightComputer { - class PingReceiverComponentImpl : - public PingReceiverComponentBase - { - - public: - - // ---------------------------------------------------------------------- - // Construction, initialization, and destruction - // ---------------------------------------------------------------------- - - //! Construct object PingReceiver - //! - PingReceiverComponentImpl( - const char *const compName /*!< The component name*/ - ); - - //! Destroy object PingReceiver - //! - ~PingReceiverComponentImpl(); - - PRIVATE: - - // ---------------------------------------------------------------------- - // Handler implementations for user-defined typed input ports - // ---------------------------------------------------------------------- - - //! Handler implementation for PingIn - //! - void PingIn_handler( - const NATIVE_INT_TYPE portNum, /*!< The port number*/ - U32 key /*!< Value to return to pinger*/ - ); - - void PR_StopPings_cmdHandler( - FwOpcodeType opCode, /*!< The opcode*/ - U32 cmdSeq /*!< The command sequence number*/ - ); - - bool m_inhibitPings; - U32 m_pingsRecvd; - - - }; +class PingReceiverComponentImpl : public PingReceiverComponentBase { + +public: + // ---------------------------------------------------------------------- + // Construction, initialization, and destruction + // ---------------------------------------------------------------------- + + //! Construct object PingReceiver + //! + PingReceiverComponentImpl(const char *const compName /*!< The component name*/ + ); + + //! Destroy object PingReceiver + //! + ~PingReceiverComponentImpl(); + +PRIVATE: + // ---------------------------------------------------------------------- + // Handler implementations for user-defined typed input ports + // ---------------------------------------------------------------------- + + //! Handler implementation for PingIn + //! + void PingIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ + U32 key /*!< Value to return to pinger*/ + ); + + void PR_StopPings_cmdHandler(FwOpcodeType opCode, /*!< The opcode*/ + U32 cmdSeq /*!< The command sequence number*/ + ); + + bool m_inhibitPings; + U32 m_pingsRecvd; +}; } // end namespace FlightComputer diff --git a/FlightComputer/Top/FlightComputerTopology.cpp b/FlightComputer/Top/FlightComputerTopology.cpp index 69807fb..3998a58 100644 --- a/FlightComputer/Top/FlightComputerTopology.cpp +++ b/FlightComputer/Top/FlightComputerTopology.cpp @@ -1,19 +1,19 @@ #include "FlightComputer/Top/FppConstantsAc.hpp" #include "FpConfig.h" #include "Fw/Logger/Logger.hpp" -#include "Svc/FramingProtocol/CCSDSProtocols/TMSpaceDataLink/ProtocolInterface.hpp" +// #include "Svc/FramingProtocol/CCSDSProtocols/TMSpaceDataLink/ProtocolInterface.hpp" // #include "Svc/FramingProtocol/CCSDSProtocols/TCSpaceDataLink.hpp" // Provides access to autocoded functions +#include #include #include -#include // Necessary project-specified types #include #include -#include #include +#include // Used for 1Hz synthetic cycling #include @@ -26,133 +26,162 @@ using namespace FlightComputer; // Instantiate a system logger that will handle Fw::Logger::log calls Os::Console logger; -// The reference topology uses a malloc-based allocator for components that need to allocate memory during the -// initialization phase. +// The reference topology uses a malloc-based allocator for components that need +// to allocate memory during the initialization phase. Fw::MallocAllocator mallocator; -// The reference topology uses the F´ packet protocol when communicating with the ground and therefore uses the F´ -// framing and deframing implementations. +// The reference topology uses the F´ packet protocol when communicating with +// the ground and therefore uses the F´ framing and deframing implementations. Svc::FprimeFraming fprimeFraming; // Svc::TCSpaceDataLink tcFraming; -TMSpaceDataLink::MissionPhaseParameters_t missionParams{ - 0x00, // transferFrameVersion - CCSDS_SCID, // spaceCraftId - false, // hasOperationalControlFlag - false, // hasSecondaryHeader - true // isSyncFlagEnabled -}; -FwSizeType dataFieldSize = Svc::TM_DATA_FIELD_DFLT_SIZE; -Svc::TMSpaceDataLinkProtocol tmSpaceDataLink(missionParams, dataFieldSize); +// TMSpaceDataLink::MissionPhaseParameters_t missionParams{ +// 0x00, // transferFrameVersion +// CCSDS_SCID, // spaceCraftId +// false, // hasOperationalControlFlag +// false, // hasSecondaryHeader +// true // isSyncFlagEnabled +// }; +// FwSizeType dataFieldSize = Svc::TM_DATA_FIELD_DFLT_SIZE; +// Svc::TMSpaceDataLinkProtocol tmSpaceDataLink(missionParams, dataFieldSize); Svc::FrameDetectors::FprimeFrameDetector fprimeFrameDetector; -Svc::FrameDetectors::TMSpaceDataLinkDetector ccsdsFrameDetector; +// Svc::FrameDetectors::TMSpaceDataLinkDetector ccsdsFrameDetector; -// The reference topology divides the incoming clock signal (1Hz) into sub-signals: 1Hz, 1/2Hz, and 1/4Hz and -// zero offset for all the dividers +// The reference topology divides the incoming clock signal (1Hz) into +// sub-signals: 1Hz, 1/2Hz, and 1/4Hz and zero offset for all the dividers Svc::RateGroupDriver::DividerSet rateGroupDivisorsSet{{{1, 0}, {2, 0}, {4, 0}}}; -// Rate groups may supply a context token to each of the attached children whose purpose is set by the project. The -// reference topology sets each token to zero as these contexts are unused in this project. -NATIVE_INT_TYPE rateGroup1Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = {}; -NATIVE_INT_TYPE rateGroup2Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = {}; -NATIVE_INT_TYPE rateGroup3Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = {}; - -// A number of constants are needed for construction of the topology. These are specified here. +// Rate groups may supply a context token to each of the attached children whose +// purpose is set by the project. The reference topology sets each token to zero +// as these contexts are unused in this project. +NATIVE_INT_TYPE rateGroup1Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = + {}; +NATIVE_INT_TYPE rateGroup2Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = + {}; +NATIVE_INT_TYPE rateGroup3Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = + {}; + +// A number of constants are needed for construction of the topology. These are +// specified here. enum TopologyConstants { - CMD_SEQ_BUFFER_SIZE = 7 * 1024, - FILE_DOWNLINK_TIMEOUT = 1000, - FILE_DOWNLINK_COOLDOWN = 1000, - FILE_DOWNLINK_CYCLE_TIME = 1000, - FILE_DOWNLINK_FILE_QUEUE_DEPTH = 10, - HEALTH_WATCHDOG_CODE = 0x123, - COMM_PRIORITY = 100, - // Buffer manager for Uplink/Downlink - COMMS_BUFFER_MANAGER_STORE_SIZE = 2048, - COMMS_BUFFER_MANAGER_STORE_COUNT = 20, - COMMS_BUFFER_MANAGER_FILE_STORE_SIZE = 3000, - COMMS_BUFFER_MANAGER_FILE_QUEUE_SIZE = 30, - COMMS_BUFFER_MANAGER_ID = 200, + CMD_SEQ_BUFFER_SIZE = 7 * 1024, + FILE_DOWNLINK_TIMEOUT = 1000, + FILE_DOWNLINK_COOLDOWN = 1000, + FILE_DOWNLINK_CYCLE_TIME = 1000, + FILE_DOWNLINK_FILE_QUEUE_DEPTH = 10, + HEALTH_WATCHDOG_CODE = 0x123, + COMM_PRIORITY = 100, + // Buffer manager for Uplink/Downlink + COMMS_BUFFER_MANAGER_STORE_SIZE = 2048, + COMMS_BUFFER_MANAGER_STORE_COUNT = 20, + COMMS_BUFFER_MANAGER_FILE_STORE_SIZE = 3000, + COMMS_BUFFER_MANAGER_FILE_QUEUE_SIZE = 30, + COMMS_BUFFER_MANAGER_ID = 200, }; -// Ping entries are autocoded, however; this code is not properly exported. Thus, it is copied here. +// Ping entries are autocoded, however; this code is not properly exported. +// Thus, it is copied here. Svc::Health::PingEntry pingEntries[] = { - {PingEntries::FlightComputer_blockDrv::WARN, PingEntries::FlightComputer_blockDrv::FATAL, "blockDrv"}, - {PingEntries::FlightComputer_chanTlm::WARN, PingEntries::FlightComputer_chanTlm::FATAL, "chanTlm"}, - {PingEntries::FlightComputer_cmdDisp::WARN, PingEntries::FlightComputer_cmdDisp::FATAL, "cmdDisp"}, - {PingEntries::FlightComputer_cmdSeq::WARN, PingEntries::FlightComputer_cmdSeq::FATAL, "cmdSeq"}, - {PingEntries::FlightComputer_eventLogger::WARN, PingEntries::FlightComputer_eventLogger::FATAL, "eventLogger"}, - {PingEntries::FlightComputer_fileDownlink::WARN, PingEntries::FlightComputer_fileDownlink::FATAL, "fileDownlink"}, - {PingEntries::FlightComputer_fileManager::WARN, PingEntries::FlightComputer_fileManager::FATAL, "fileManager"}, - {PingEntries::FlightComputer_fileUplink::WARN, PingEntries::FlightComputer_fileUplink::FATAL, "fileUplink"}, - {PingEntries::FlightComputer_pingRcvr::WARN, PingEntries::FlightComputer_pingRcvr::FATAL, "pingRcvr"}, - {PingEntries::FlightComputer_prmDb::WARN, PingEntries::FlightComputer_prmDb::FATAL, "prmDb"}, - {PingEntries::FlightComputer_rateGroup1Comp::WARN, PingEntries::FlightComputer_rateGroup1Comp::FATAL, "rateGroup1Comp"}, - {PingEntries::FlightComputer_rateGroup2Comp::WARN, PingEntries::FlightComputer_rateGroup2Comp::FATAL, "rateGroup2Comp"}, - {PingEntries::FlightComputer_rateGroup3Comp::WARN, PingEntries::FlightComputer_rateGroup3Comp::FATAL, "rateGroup3Comp"}, + {PingEntries::FlightComputer_blockDrv::WARN, + PingEntries::FlightComputer_blockDrv::FATAL, "blockDrv"}, + {PingEntries::FlightComputer_chanTlm::WARN, + PingEntries::FlightComputer_chanTlm::FATAL, "chanTlm"}, + {PingEntries::FlightComputer_cmdDisp::WARN, + PingEntries::FlightComputer_cmdDisp::FATAL, "cmdDisp"}, + {PingEntries::FlightComputer_cmdSeq::WARN, + PingEntries::FlightComputer_cmdSeq::FATAL, "cmdSeq"}, + {PingEntries::FlightComputer_eventLogger::WARN, + PingEntries::FlightComputer_eventLogger::FATAL, "eventLogger"}, + {PingEntries::FlightComputer_fileDownlink::WARN, + PingEntries::FlightComputer_fileDownlink::FATAL, "fileDownlink"}, + {PingEntries::FlightComputer_fileManager::WARN, + PingEntries::FlightComputer_fileManager::FATAL, "fileManager"}, + {PingEntries::FlightComputer_fileUplink::WARN, + PingEntries::FlightComputer_fileUplink::FATAL, "fileUplink"}, + {PingEntries::FlightComputer_pingRcvr::WARN, + PingEntries::FlightComputer_pingRcvr::FATAL, "pingRcvr"}, + {PingEntries::FlightComputer_prmDb::WARN, + PingEntries::FlightComputer_prmDb::FATAL, "prmDb"}, + {PingEntries::FlightComputer_rateGroup1Comp::WARN, + PingEntries::FlightComputer_rateGroup1Comp::FATAL, "rateGroup1Comp"}, + {PingEntries::FlightComputer_rateGroup2Comp::WARN, + PingEntries::FlightComputer_rateGroup2Comp::FATAL, "rateGroup2Comp"}, + {PingEntries::FlightComputer_rateGroup3Comp::WARN, + PingEntries::FlightComputer_rateGroup3Comp::FATAL, "rateGroup3Comp"}, }; /** * \brief configure/setup components in project-specific way * - * This is a *helper* function which configures/sets up each component requiring project specific input. This includes - * allocating resources, passing-in arguments, etc. This function may be inlined into the topology setup function if - * desired, but is extracted here for clarity. + * This is a *helper* function which configures/sets up each component requiring + * project specific input. This includes allocating resources, passing-in + * arguments, etc. This function may be inlined into the topology setup function + * if desired, but is extracted here for clarity. */ void configureTopology() { - // Command sequencer needs to allocate memory to hold contents of command sequences - cmdSeq.allocateBuffer(0, mallocator, CMD_SEQ_BUFFER_SIZE); - - // Rate group driver needs a divisor list - rateGroupDriverComp.configure(rateGroupDivisorsSet); - - // Rate groups require context arrays. Empty for FlightComputererence example. - rateGroup1Comp.configure(rateGroup1Context, FW_NUM_ARRAY_ELEMENTS(rateGroup1Context)); - rateGroup2Comp.configure(rateGroup2Context, FW_NUM_ARRAY_ELEMENTS(rateGroup2Context)); - rateGroup3Comp.configure(rateGroup3Context, FW_NUM_ARRAY_ELEMENTS(rateGroup3Context)); - - // File downlink requires some project-derived properties. - fileDownlink.configure(FILE_DOWNLINK_TIMEOUT, FILE_DOWNLINK_COOLDOWN, FILE_DOWNLINK_CYCLE_TIME, - FILE_DOWNLINK_FILE_QUEUE_DEPTH); - - // Parameter database is configured with a database file name, and that file must be initially read. - // prmDb.configure("PrmDb.dat"); - // prmDb.readParamFile(); - - // Health is supplied a set of ping entires. - health.setPingEntries(pingEntries, FW_NUM_ARRAY_ELEMENTS(pingEntries), HEALTH_WATCHDOG_CODE); - - // Buffer managers need a configured set of buckets and an allocator used to allocate memory for those buckets. - Svc::BufferManager::BufferBins commsBuffMgrBins; - memset(&commsBuffMgrBins, 0, sizeof(commsBuffMgrBins)); - commsBuffMgrBins.bins[0].bufferSize = COMMS_BUFFER_MANAGER_STORE_SIZE; - commsBuffMgrBins.bins[0].numBuffers = COMMS_BUFFER_MANAGER_STORE_COUNT; - commsBuffMgrBins.bins[1].bufferSize = COMMS_BUFFER_MANAGER_FILE_STORE_SIZE; - commsBuffMgrBins.bins[1].numBuffers = COMMS_BUFFER_MANAGER_FILE_QUEUE_SIZE; - commsBufferManager.setup(COMMS_BUFFER_MANAGER_ID, 0, mallocator, commsBuffMgrBins); - - // Framer and Deframer components need to be passed a protocol handler - framer.setup(fprimeFraming); - ccsdsFramer.setup(tmSpaceDataLink); - // This sets up deframing - fprimeFrameAccumulator.configure(fprimeFrameDetector, 1, mallocator, 2048); - ccsdsFrameAccumulator.configure(ccsdsFrameDetector, 2, mallocator, 2048); + // Command sequencer needs to allocate memory to hold contents of command + // sequences + cmdSeq.allocateBuffer(0, mallocator, CMD_SEQ_BUFFER_SIZE); + + // Rate group driver needs a divisor list + rateGroupDriverComp.configure(rateGroupDivisorsSet); + + // Rate groups require context arrays. Empty for FlightComputererence example. + rateGroup1Comp.configure(rateGroup1Context, + FW_NUM_ARRAY_ELEMENTS(rateGroup1Context)); + rateGroup2Comp.configure(rateGroup2Context, + FW_NUM_ARRAY_ELEMENTS(rateGroup2Context)); + rateGroup3Comp.configure(rateGroup3Context, + FW_NUM_ARRAY_ELEMENTS(rateGroup3Context)); + + // File downlink requires some project-derived properties. + fileDownlink.configure(FILE_DOWNLINK_TIMEOUT, FILE_DOWNLINK_COOLDOWN, + FILE_DOWNLINK_CYCLE_TIME, + FILE_DOWNLINK_FILE_QUEUE_DEPTH); + + // Parameter database is configured with a database file name, and that file + // must be initially read. prmDb.configure("PrmDb.dat"); + // prmDb.readParamFile(); + + // Health is supplied a set of ping entires. + health.setPingEntries(pingEntries, FW_NUM_ARRAY_ELEMENTS(pingEntries), + HEALTH_WATCHDOG_CODE); + + // Buffer managers need a configured set of buckets and an allocator used to + // allocate memory for those buckets. + Svc::BufferManager::BufferBins commsBuffMgrBins; + memset(&commsBuffMgrBins, 0, sizeof(commsBuffMgrBins)); + commsBuffMgrBins.bins[0].bufferSize = COMMS_BUFFER_MANAGER_STORE_SIZE; + commsBuffMgrBins.bins[0].numBuffers = COMMS_BUFFER_MANAGER_STORE_COUNT; + commsBuffMgrBins.bins[1].bufferSize = COMMS_BUFFER_MANAGER_FILE_STORE_SIZE; + commsBuffMgrBins.bins[1].numBuffers = COMMS_BUFFER_MANAGER_FILE_QUEUE_SIZE; + commsBufferManager.setup(COMMS_BUFFER_MANAGER_ID, 0, mallocator, + commsBuffMgrBins); + + // Framer and Deframer components need to be passed a protocol handler + framer.setup(fprimeFraming); + // ccsdsFramer.setup(tmSpaceDataLink); + // This sets up deframing + fprimeFrameAccumulator.configure(fprimeFrameDetector, 1, mallocator, 2048); + // ccsdsFrameAccumulator.configure(ccsdsFrameDetector, 2, mallocator, 2048); } -// Public functions for use in main program are namespaced with deployment name FlightComputer +// Public functions for use in main program are namespaced with deployment name +// FlightComputer namespace FlightComputer { -void setupTopology(const TopologyState& state) { - configureTopology(); - setup(state); - // Initialize socket client communication if and only if there is a valid specification - if (state.hostName != nullptr && state.uplinkPort != 0) { - Os::TaskString name("ReceiveTask"); - // Uplink is configured for receive so a socket task is started - fprimeTcpLink.configure(state.hostName, state.uplinkPort); - fprimeTcpLink.start(name, true, COMM_PRIORITY, Default::stackSize); - - // ccsdsTcpLink.configure(state.hostName, state.uplinkPort+1); - // ccsdsTcpLink.start(name, true, COMM_PRIORITY, Default::stackSize); - } - +void setupTopology(const TopologyState &state) { + configureTopology(); + setup(state); + // Initialize socket client communication if and only if there is a valid + // specification + if (state.hostName != nullptr && state.uplinkPort != 0) { + Os::TaskString name("ReceiveTask"); + // Uplink is configured for receive so a socket task is started + fprimeTcpLink.configure(state.hostName, state.uplinkPort); + fprimeTcpLink.start(name, true, COMM_PRIORITY, Default::stackSize); + + // ccsdsTcpLink.configure(state.hostName, state.uplinkPort+1); + // ccsdsTcpLink.start(name, true, COMM_PRIORITY, Default::stackSize); + } } // Variables used for cycle simulation @@ -160,38 +189,39 @@ Os::Mutex cycleLock; volatile bool cycleFlag = true; void startSimulatedCycle(Fw::TimeInterval interval) { - cycleLock.lock(); - bool cycling = cycleFlag; - cycleLock.unLock(); + cycleLock.lock(); + bool cycling = cycleFlag; + cycleLock.unLock(); - // Main loop - while (cycling) { - FlightComputer::blockDrv.callIsr(); - Os::Task::delay(interval); + // Main loop + while (cycling) { + FlightComputer::blockDrv.callIsr(); + Os::Task::delay(interval); - cycleLock.lock(); - cycling = cycleFlag; - cycleLock.unLock(); - } + cycleLock.lock(); + cycling = cycleFlag; + cycleLock.unLock(); + } } void stopSimulatedCycle() { - cycleLock.lock(); - cycleFlag = false; - cycleLock.unLock(); + cycleLock.lock(); + cycleFlag = false; + cycleLock.unLock(); } -void teardownTopology(const TopologyState& state) { - // Autocoded (active component) task clean-up. Functions provided by topology autocoder. - stopTasks(state); - freeThreads(state); +void teardownTopology(const TopologyState &state) { + // Autocoded (active component) task clean-up. Functions provided by topology + // autocoder. + stopTasks(state); + freeThreads(state); - // Other task clean-up. - fprimeTcpLink.stop(); - (void)fprimeTcpLink.join(); + // Other task clean-up. + fprimeTcpLink.stop(); + (void)fprimeTcpLink.join(); - // Resource deallocation - cmdSeq.deallocateBuffer(mallocator); - commsBufferManager.cleanup(); + // Resource deallocation + cmdSeq.deallocateBuffer(mallocator); + commsBufferManager.cleanup(); } -}; // namespace FlightComputer +}; // namespace FlightComputer diff --git a/FlightComputer/Top/FlightComputerTopology.hpp b/FlightComputer/Top/FlightComputerTopology.hpp index 69ab8ac..60a183e 100644 --- a/FlightComputer/Top/FlightComputerTopology.hpp +++ b/FlightComputer/Top/FlightComputerTopology.hpp @@ -1,6 +1,7 @@ #ifndef FLIGHTCOMPUTERTOPOLOGY_H_ #define FLIGHTCOMPUTERTOPOLOGY_H_ -// Included for access to Ref::TopologyState and Ref::ConfigObjects::pingEntries. These definitions are required by the +// Included for access to Ref::TopologyState and +// Ref::ConfigObjects::pingEntries. These definitions are required by the // autocoder, but are also used in this hand-coded topology. #include "FlightComputer/Top/FlightComputerTopologyDefs.hpp" @@ -10,61 +11,79 @@ namespace FlightComputer { /** * \brief initialize and run the F´ topology * - * Initializes, configures, and runs the F´ topology. This is performed through a series of steps, some provided via - * autocoded functions, and others provided via the functions implementation. These steps are: + * Initializes, configures, and runs the F´ topology. This is performed through + * a series of steps, some provided via autocoded functions, and others provided + * via the functions implementation. These steps are: * - * 1. Call the autocoded `initComponents()` function initializing each component via the `component.init` method - * 2. Call the autocoded `setBaseIds()` function to set the base IDs (offset) for each component instance - * 3. Call the autocoded `connectComponents()` function to wire-together the topology of components + * 1. Call the autocoded `initComponents()` function initializing each + * component via the `component.init` method + * 2. Call the autocoded `setBaseIds()` function to set the base IDs (offset) + * for each component instance + * 3. Call the autocoded `connectComponents()` function to wire-together the + * topology of components * 4. Configure components requiring custom configuration - * 5. Call the autocoded `loadParameters()` function to cause each component to load initial parameter values - * 6. Call the autocoded `startTasks()` function to start the active component tasks + * 5. Call the autocoded `loadParameters()` function to cause each component + * to load initial parameter values + * 6. Call the autocoded `startTasks()` function to start the active component + * tasks * 7. Start tasks not owned by active components * - * Step 4 and step 7 are custom and supplied by the project. The ordering of steps 1, 2, 3, 5, and 6 are critical for - * F´ topologies to function. Configuration (step 4) typically assumes a connect but not started topology and is thus - * inserted between step 3 and 5. Step 7 may come before or after the active component initializations. Since these - * custom tasks often start radio communication it is convenient to start them last. + * Step 4 and step 7 are custom and supplied by the project. The ordering of + * steps 1, 2, 3, 5, and 6 are critical for F´ topologies to function. + * Configuration (step 4) typically assumes a connect but not started topology + * and is thus inserted between step 3 and 5. Step 7 may come before or after + * the active component initializations. Since these custom tasks often start + * radio communication it is convenient to start them last. * - * The state argument carries command line inputs used to setup the topology. For an explanation of the required type - * Ref::TopologyState see: RefTopologyDefs.hpp. + * The state argument carries command line inputs used to setup the topology. + * For an explanation of the required type Ref::TopologyState see: + * RefTopologyDefs.hpp. * - * \param state: object shuttling CLI arguments (hostname, port) needed to construct the topology + * \param state: object shuttling CLI arguments (hostname, port) needed to + * construct the topology */ -void setupTopology(const TopologyState& state); +void setupTopology(const TopologyState &state); /** * \brief teardown the F´ topology * - * Tears down the F´ topology in preparation for shutdown. This is done via a series of steps, some provided by - * autocoded functions, and others provided via the function implementation. These steps are: + * Tears down the F´ topology in preparation for shutdown. This is done via a + * series of steps, some provided by autocoded functions, and others provided + * via the function implementation. These steps are: * - * 1. Call the autocoded `stopTasks()` function to stop the tasks started by `startTasks()` (active components) - * 2. Call the autocoded `freeThreads()` function to join to the tasks started by `startTasks()` + * 1. Call the autocoded `stopTasks()` function to stop the tasks started by + * `startTasks()` (active components) + * 2. Call the autocoded `freeThreads()` function to join to the tasks started + * by `startTasks()` * 3. Stop the tasks not owned by active components * 4. Join to the tasks not owned by active components * 5. Deallocate other resources * - * Step 1, 2, 3, and 4 must occur in-order as the tasks must be stopped before being joined. These tasks must be stopped - * and joined before any active resources may be deallocated. + * Step 1, 2, 3, and 4 must occur in-order as the tasks must be stopped before + * being joined. These tasks must be stopped and joined before any active + * resources may be deallocated. * - * For an explanation of the required type Ref::TopologyState see: RefTopologyDefs.hpp. + * For an explanation of the required type Ref::TopologyState see: + * RefTopologyDefs.hpp. * * \param state: state object provided to setupTopology */ -void teardownTopology(const TopologyState& state); +void teardownTopology(const TopologyState &state); /** * \brief cycle the rate group driver at a crude rate * - * The reference topology does not have a true 1Hz input clock for the rate group driver because it is designed to - * operate across various computing endpoints (e.g. laptops) where a clear 1Hz source may not be easily and generically - * achieved. This function mimics the cycling via a Task::delay(Fw::Time()) loop that manually invokes the ISR call - * to the example block driver. + * The reference topology does not have a true 1Hz input clock for the rate + * group driver because it is designed to operate across various computing + * endpoints (e.g. laptops) where a clear 1Hz source may not be easily and + * generically achieved. This function mimics the cycling via a + * Task::delay(Fw::Time()) loop that manually invokes the ISR call to the + * example block driver. * * This loop is stopped via a startSimulatedCycle call. * - * Note: projects should replace this with a component that produces an output port call at the appropriate frequency. + * Note: projects should replace this with a component that produces an output + * port call at the appropriate frequency. * */ void startSimulatedCycle(Fw::TimeInterval interval); @@ -76,7 +95,6 @@ void startSimulatedCycle(Fw::TimeInterval interval); */ void stopSimulatedCycle(); -} // namespace Ref - +} // namespace FlightComputer #endif // FLIGHTCOMPUTERTOPOLOGY_H_ diff --git a/FlightComputer/Top/FlightComputerTopologyDefs.cpp b/FlightComputer/Top/FlightComputerTopologyDefs.cpp index 0441ea8..1197211 100644 --- a/FlightComputer/Top/FlightComputerTopologyDefs.cpp +++ b/FlightComputer/Top/FlightComputerTopologyDefs.cpp @@ -1,12 +1,12 @@ -#include "FlightComputer/Top/FppConstantsAc.hpp" #include "FlightComputer/Top/FlightComputerTopologyDefs.hpp" +#include "FlightComputer/Top/FppConstantsAc.hpp" namespace FlightComputer { - namespace Allocation { +namespace Allocation { - Fw::MallocAllocator mallocator; - - } +Fw::MallocAllocator mallocator; } + +} // namespace FlightComputer diff --git a/FlightComputer/Top/FlightComputerTopologyDefs.hpp b/FlightComputer/Top/FlightComputerTopologyDefs.hpp index 98b54f5..ed113de 100644 --- a/FlightComputer/Top/FlightComputerTopologyDefs.hpp +++ b/FlightComputer/Top/FlightComputerTopologyDefs.hpp @@ -2,63 +2,79 @@ #define FlightComputerTopologyDefs_HPP #include "Drv/BlockDriver/BlockDriver.hpp" +#include "FlightComputer/Top/FppConstantsAc.hpp" #include "Fw/Types/MallocAllocator.hpp" #include "Svc/FramingProtocol/FprimeProtocol.hpp" -#include "FlightComputer/Top/FppConstantsAc.hpp" namespace FlightComputer { - namespace Allocation { - - // Malloc allocator for topology construction - extern Fw::MallocAllocator mallocator; - - } +namespace Allocation { - // State for topology construction - struct TopologyState { - TopologyState() : - //Should set defaults here - hostName(""), - uplinkPort(0), - downlinkPort(0) - { +// Malloc allocator for topology construction +extern Fw::MallocAllocator mallocator; - } - TopologyState( - const char *hostName, - U32 uplinkPort, - U32 downlinkPort - ) : - hostName(hostName), - uplinkPort(uplinkPort), - downlinkPort(downlinkPort) - { +} // namespace Allocation - } - const char* hostName; - U32 uplinkPort; - U32 downlinkPort; - }; +// State for topology construction +struct TopologyState { + TopologyState() + : // Should set defaults here + hostName(""), uplinkPort(0), downlinkPort(0) {} + TopologyState(const char *hostName, U32 uplinkPort, U32 downlinkPort) + : hostName(hostName), uplinkPort(uplinkPort), downlinkPort(downlinkPort) { - // Health ping entries - namespace PingEntries { - namespace FlightComputer_blockDrv { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_chanTlm { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_gdsChanTlm { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_cmdDisp { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_cmdSeq { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_eventLogger { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_fileDownlink { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_fileManager { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_fileUplink { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_pingRcvr { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_prmDb { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_rateGroup1Comp { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_rateGroup2Comp { enum { WARN = 3, FATAL = 5 }; } - namespace FlightComputer_rateGroup3Comp { enum { WARN = 3, FATAL = 5 }; } } + const char *hostName; + U32 uplinkPort; + U32 downlinkPort; +}; +// Health ping entries +namespace PingEntries { +namespace FlightComputer_blockDrv { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_chanTlm { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_gdsChanTlm { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_cmdDisp { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_cmdSeq { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_eventLogger { +enum { WARN = 3, FATAL = 5 }; } +namespace FlightComputer_fileDownlink { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_fileManager { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_fileUplink { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_pingRcvr { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_prmDb { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_rateGroup1Comp { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_rateGroup2Comp { +enum { WARN = 3, FATAL = 5 }; +} +namespace FlightComputer_rateGroup3Comp { +enum { WARN = 3, FATAL = 5 }; +} +} // namespace PingEntries + +} // namespace FlightComputer #endif diff --git a/FlightComputer/Top/Main.cpp b/FlightComputer/Top/Main.cpp index 9e9a726..c0199e1 100644 --- a/FlightComputer/Top/Main.cpp +++ b/FlightComputer/Top/Main.cpp @@ -1,137 +1,140 @@ #include "Fw/Logger/Logger.hpp" -#include #include #include +#include #include -#include -#include #include +#include +#include -#include #include #include +#include - -void print_usage(const char* app) { - (void) printf("Usage: ./%s [options]\n" - "-p, --persist\t\tstay up regardless of component failure\n" - "-d, --downlink PORT\tset downlink port\n" - "-u, --uplink PORT\tset uplink port\n" - "-a, --address HOST\tset hostname/IP address\n" - "-h, --help\t\tshow this help message\n", app); +void print_usage(const char *app) { + (void)printf("Usage: ./%s [options]\n" + "-p, --persist\t\tstay up regardless of component failure\n" + "-d, --downlink PORT\tset downlink port\n" + "-u, --uplink PORT\tset uplink port\n" + "-a, --address HOST\tset hostname/IP address\n" + "-h, --help\t\tshow this help message\n", + app); } volatile sig_atomic_t terminate = 0; bool persist = false; enum { - EXIT_CODE_OK = 0, - EXIT_CODE_STARTUP_FAILURE, - EXIT_CODE_INIT_FAILURE, - EXIT_CODE_RUNTIME_FAILURE, + EXIT_CODE_OK = 0, + EXIT_CODE_STARTUP_FAILURE, + EXIT_CODE_INIT_FAILURE, + EXIT_CODE_RUNTIME_FAILURE, }; static volatile int EXIT_RET = EXIT_CODE_OK; static void initFailureSigHandler(int signum) { - if (persist) { - printf("Component failure detected in persist mode so no shutdown\n"); - return; - } - - printf("Component failure detected. Terminating now.\n"); - EXIT_RET = EXIT_CODE_INIT_FAILURE; - terminate = 1; + if (persist) { + printf("Component failure detected in persist mode so no shutdown\n"); + return; + } + + printf("Component failure detected. Terminating now.\n"); + EXIT_RET = EXIT_CODE_INIT_FAILURE; + terminate = 1; } -static void dfltSigHandler(int signum) { - FlightComputer::stopSimulatedCycle(); -} - -int main(int argc, char* argv[]) { - Os::Console::init(); - U32 uplink_port = 0; // Invalid port number forced - U32 downlink_port = 0; // Invalid port number forcedt - I32 option; - char* hostname; - option = 0; - hostname = nullptr; - - // Check for environment variables - const char* env_uplink_port = getenv("UPLINK_TARGET_PORT"); - const char* env_downlink_port = getenv("DOWNLINK_TARGET_PORT"); - const char* env_hostname = getenv("DOWNLINK_HOST"); - - if (env_uplink_port) { - uplink_port = static_cast(atoi(env_uplink_port)); - } - if (env_downlink_port) { - downlink_port = static_cast(atoi(env_downlink_port)); - } - if (env_hostname) { - hostname = strdup(env_hostname); // Use strdup to allocate memory for hostname - } - - static struct option long_options[] = { - {"help", no_argument, 0, 'h'}, - {"downlink", required_argument, 0, 'd'}, - {"uplink", required_argument, 0, 'u'}, - {"address", required_argument, 0, 'a'}, - {"persist", no_argument, 0, 'p'}, - {0, 0, 0, 0} - }; - - int option_index = 0; - while ((option = getopt_long(argc, argv, "hd:u:a:p", long_options, &option_index)) != -1) { - switch(option) { - case 'h': - print_usage(argv[0]); - return 0; - case 'p': - persist = true; - break; - case 'd': - downlink_port = static_cast(atoi(optarg)); - break; - case 'u': - uplink_port = static_cast(atoi(optarg)); - break; - case 'a': - hostname = optarg; - break; - case '?': - default: - EXIT_RET = EXIT_CODE_STARTUP_FAILURE; - } - } - - // Check if required variables are set - if (EXIT_RET != EXIT_CODE_OK || !hostname || uplink_port == 0 || downlink_port == 0) { - fprintf(stderr, "Missing required parameters. Please provide all required options.\n"); - print_usage(argv[0]); - return EXIT_RET; +static void dfltSigHandler(int signum) { FlightComputer::stopSimulatedCycle(); } + +int main(int argc, char *argv[]) { + Os::Console::init(); + U32 uplink_port = 0; // Invalid port number forced + U32 downlink_port = 0; // Invalid port number forcedt + I32 option; + char *hostname; + option = 0; + hostname = nullptr; + + // Check for environment variables + const char *env_uplink_port = getenv("UPLINK_TARGET_PORT"); + const char *env_downlink_port = getenv("DOWNLINK_TARGET_PORT"); + const char *env_hostname = getenv("DOWNLINK_HOST"); + + if (env_uplink_port) { + uplink_port = static_cast(atoi(env_uplink_port)); + } + if (env_downlink_port) { + downlink_port = static_cast(atoi(env_downlink_port)); + } + if (env_hostname) { + hostname = + strdup(env_hostname); // Use strdup to allocate memory for hostname + } + + static struct option long_options[] = { + {"help", no_argument, 0, 'h'}, + {"downlink", required_argument, 0, 'd'}, + {"uplink", required_argument, 0, 'u'}, + {"address", required_argument, 0, 'a'}, + {"persist", no_argument, 0, 'p'}, + {0, 0, 0, 0}}; + + int option_index = 0; + while ((option = getopt_long(argc, argv, "hd:u:a:p", long_options, + &option_index)) != -1) { + switch (option) { + case 'h': + print_usage(argv[0]); + return 0; + case 'p': + persist = true; + break; + case 'd': + downlink_port = static_cast(atoi(optarg)); + break; + case 'u': + uplink_port = static_cast(atoi(optarg)); + break; + case 'a': + hostname = optarg; + break; + case '?': + default: + EXIT_RET = EXIT_CODE_STARTUP_FAILURE; } + } + + // Check if required variables are set + if (EXIT_RET != EXIT_CODE_OK || !hostname || uplink_port == 0 || + downlink_port == 0) { + fprintf( + stderr, + "Missing required parameters. Please provide all required options.\n"); + print_usage(argv[0]); + return EXIT_RET; + } - (void) printf("Hit Ctrl-C to quit\n"); + (void)printf("Hit Ctrl-C to quit\n"); - // register signal handlers to exit program - signal(SIGINT, dfltSigHandler); - signal(SIGTERM, dfltSigHandler); - signal(SIGUSR1, initFailureSigHandler); + // register signal handlers to exit program + signal(SIGINT, dfltSigHandler); + signal(SIGTERM, dfltSigHandler); + signal(SIGUSR1, initFailureSigHandler); - Fw::Logger::log("Main Starting init\n"); - FlightComputer::TopologyState state(hostname, uplink_port, downlink_port); - (void) printf("Setting up sw runtime\n"); - FlightComputer::setupTopology(state); - FlightComputer::startSimulatedCycle(Fw::TimeInterval(1, 0)); // Program loop cycling rate groups at 1Hz - FlightComputer::teardownTopology(state); + Fw::Logger::log("Main Starting init\n"); + FlightComputer::TopologyState state(hostname, uplink_port, downlink_port); + (void)printf("Setting up sw runtime\n"); + FlightComputer::setupTopology(state); + FlightComputer::startSimulatedCycle( + Fw::TimeInterval(1, 0)); // Program loop cycling rate groups at 1Hz + FlightComputer::teardownTopology(state); - // Give time for threads to exit - (void) printf("Waiting for threads...\n"); - Os::Task::delay(Fw::TimeInterval(1, 0)); + // Give time for threads to exit + (void)printf("Waiting for threads...\n"); + Os::Task::delay(Fw::TimeInterval(1, 0)); - (void) printf("Exiting...\n"); + (void)printf("Exiting...\n"); - return EXIT_RET; + return EXIT_RET; } diff --git a/run.sh b/run.sh index e2ed6b0..b09ce78 100755 --- a/run.sh +++ b/run.sh @@ -1,7 +1,7 @@ #!/bin/bash -source .env export SCRIPT_DIR="$(cd "$(dirname "$0")"; pwd -P)" cd "$SCRIPT_DIR" +source .env set -e set -o pipefail @@ -33,6 +33,7 @@ Options: Commands: docker-build Build the Docker image build Build the project + format Leverage fprime-util's clang-format to format project inspect [container] Inspect a container exec gds Run the GDS exec FlightComputer Run the Flight Software @@ -80,7 +81,10 @@ exec_cmd() { run_docker_compose() { local cmd="$1" - local flags="-it --rm" + # Always kill the container after executing the command + # by default run the command with an interactive tty + local flags="--rm " + local flags+="${2:- -it}" flags+=" --user $(id -u):$(id -g)" [ "$DAEMON" -eq 1 ] && flags="-i -d" @@ -141,6 +145,59 @@ case $1 in exec_cmd "$CMD" ;; + "format") + if [[ "$2" == *.fpp ]]; then + container_file="${2/$SCRIPT_DIR/$FSW_WDIR}" + echo "Formatting FPP file: $container_file" + cmd="fpp-format $container_file" + # Create a temporary marker that's unlikely to appear in normal code + marker="@ COMMENT_PRESERVE@" + # Chain the commands: + # 1. Transform comments to temporary annotations + # 2. Run fpp-format + # 3. Transform back to comments + # 4. Write back to the original file + tmp_file="${container_file/.fpp/_tmp.fpp}" + + # Create a multi-line command with error checking + read -r -d '' cmd < "$tmp_file"; then + + # If successful, verify tmp file exists and has content + if [ -s "$tmp_file" ]; then + mv "$tmp_file" "$container_file" + rm "${container_file}.bak" + echo "Format successful" + else + echo "Error: Formatted file is empty" + mv "${container_file}.bak" "$container_file" + exit 1 + fi + else + echo "Error during formatting" + mv "${container_file}.bak" "$container_file" + [ -f "$tmp_file" ] && rm "$tmp_file" + exit 1 + fi +EOF + run_docker_compose "fsw bash -c \"$cmd\"" " -w $FSW_WDIR" + else + fprime_root="${2:-$SCRIPT_DIR/fprime}" # Get the path provided or use current directory + fprime_root="${fprime_root/$SCRIPT_DIR/$FSW_WDIR}" + echo "Formatting from $fprime_root" + cmd="git diff --name-only --relative | fprime-util format --no-backup --stdin" + run_docker_compose "fsw bash -c \"$cmd\"" "-w $fprime_root" + fi + ;; + "build") BUILD_CMD="fprime-util build -j10 --all"