repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
fprime
data/projects/fprime/Svc/SystemResources/test/ut/SystemResourcesTestMain.cpp
// ---------------------------------------------------------------------- // TestMain.cpp // ---------------------------------------------------------------------- #include "SystemResourcesTester.hpp" TEST(Nominal, Telemetry) { Svc::SystemResourcesTester tester; tester.test_tlm(); } TEST(OffNominal, Disabled) { Svc::SystemResourcesTester tester; tester.test_disable_enable(); } TEST(Nominal, Events) { Svc::SystemResourcesTester tester; tester.test_version_evr(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/SystemResources/test/ut/SystemResourcesTester.cpp
// ====================================================================== // \title SystemResources.hpp // \author mstarch // \brief cpp file for SystemResources test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include "SystemResourcesTester.hpp" #include "version.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 100 namespace Svc { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- SystemResourcesTester ::SystemResourcesTester() : SystemResourcesGTestBase("Tester", MAX_HISTORY_SIZE), component("SystemResources") { this->initComponents(); this->connectPorts(); } SystemResourcesTester ::~SystemResourcesTester() {} // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void SystemResourcesTester ::test_tlm(bool enabled) { U32 count = 0; if (Os::SystemResources::getCpuCount(count) == Os::SystemResources::SYSTEM_RESOURCES_OK) { this->invoke_to_run(0, 0); count = (count <= 16) ? count : 16; // All cascades expected switch (count) { case 16: ASSERT_TLM_CPU_15_SIZE((enabled) ? 1 : 0); // Cascade expected case 15: ASSERT_TLM_CPU_14_SIZE((enabled) ? 1 : 0); // Cascade expected case 14: ASSERT_TLM_CPU_13_SIZE((enabled) ? 1 : 0); // Cascade expected case 13: ASSERT_TLM_CPU_12_SIZE((enabled) ? 1 : 0); // Cascade expected case 12: ASSERT_TLM_CPU_11_SIZE((enabled) ? 1 : 0); // Cascade expected case 11: ASSERT_TLM_CPU_10_SIZE((enabled) ? 1 : 0); // Cascade expected case 10: ASSERT_TLM_CPU_09_SIZE((enabled) ? 1 : 0); // Cascade expected case 9: ASSERT_TLM_CPU_08_SIZE((enabled) ? 1 : 0); // Cascade expected case 8: ASSERT_TLM_CPU_07_SIZE((enabled) ? 1 : 0); // Cascade expected case 7: ASSERT_TLM_CPU_06_SIZE((enabled) ? 1 : 0); // Cascade expected case 6: ASSERT_TLM_CPU_05_SIZE((enabled) ? 1 : 0); // Cascade expected case 5: ASSERT_TLM_CPU_04_SIZE((enabled) ? 1 : 0); // Cascade expected case 4: ASSERT_TLM_CPU_03_SIZE((enabled) ? 1 : 0); // Cascade expected case 3: ASSERT_TLM_CPU_02_SIZE((enabled) ? 1 : 0); // Cascade expected case 2: ASSERT_TLM_CPU_01_SIZE((enabled) ? 1 : 0); // Cascade expected case 1: ASSERT_TLM_CPU_00_SIZE((enabled) ? 1 : 0); // Cascade expected default: FwSizeType free = 0; FwSizeType total = 0; Os::SystemResources::MemUtil memory_info; ASSERT_TLM_CPU_SIZE((enabled) ? 1 : 0); // Check that the filesystem reads well before asserting telemetry if (enabled && Os::SystemResources::getMemUtil(memory_info) == Os::SystemResources::SYSTEM_RESOURCES_OK) { ASSERT_TLM_MEMORY_USED_SIZE(1); ASSERT_TLM_MEMORY_TOTAL_SIZE(1); count += 2; } else { ASSERT_TLM_MEMORY_USED_SIZE(0); ASSERT_TLM_MEMORY_TOTAL_SIZE(0); } // Check that the filesystem reads well before asserting telemetry if (enabled && Os::FileSystem::getFreeSpace("/", free, total ) == Os::FileSystem::OP_OK) { ASSERT_TLM_NON_VOLATILE_FREE_SIZE(1); ASSERT_TLM_NON_VOLATILE_TOTAL_SIZE(1); count += 2; } else { ASSERT_TLM_NON_VOLATILE_FREE_SIZE(0); ASSERT_TLM_NON_VOLATILE_TOTAL_SIZE(0); } ASSERT_TLM_FRAMEWORK_VERSION_SIZE((enabled) ? 1 : 0); ASSERT_TLM_PROJECT_VERSION_SIZE((enabled) ? 1 : 0); if (enabled) { ASSERT_TLM_FRAMEWORK_VERSION(0, FRAMEWORK_VERSION); ASSERT_TLM_PROJECT_VERSION(0, PROJECT_VERSION); } ASSERT_TLM_SIZE((enabled) ? (count + 3) : 0); // CPU count channels + avg + 2 ver break; } } } void SystemResourcesTester ::test_disable_enable() { this->sendCmd_ENABLE(0, 0, SystemResourceEnabled::DISABLED); this->test_tlm(false); this->sendCmd_ENABLE(0, 0, SystemResourceEnabled::ENABLED); this->test_tlm(true); } void SystemResourcesTester ::test_version_evr() { this->sendCmd_VERSION(0, 0); ASSERT_EVENTS_FRAMEWORK_VERSION_SIZE(1); ASSERT_EVENTS_FRAMEWORK_VERSION(0, FRAMEWORK_VERSION); ASSERT_EVENTS_PROJECT_VERSION_SIZE(1); ASSERT_EVENTS_PROJECT_VERSION(0, FRAMEWORK_VERSION); } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void SystemResourcesTester ::connectPorts() { // run this->connect_to_run(0, this->component.get_run_InputPort(0)); // CmdDisp this->connect_to_CmdDisp(0, this->component.get_CmdDisp_InputPort(0)); // CmdStatus this->component.set_CmdStatus_OutputPort(0, this->get_from_CmdStatus(0)); // CmdReg this->component.set_CmdReg_OutputPort(0, this->get_from_CmdReg(0)); // Tlm this->component.set_Tlm_OutputPort(0, this->get_from_Tlm(0)); // Time this->component.set_Time_OutputPort(0, this->get_from_Time(0)); // Log this->component.set_Log_OutputPort(0, this->get_from_Log(0)); // LogText this->component.set_LogText_OutputPort(0, this->get_from_LogText(0)); } void SystemResourcesTester ::initComponents() { this->init(); this->component.init(INSTANCE); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/PolyDb/PolyDb.hpp
// ====================================================================== // PolyDb.hpp // Standardization header for PolyDb // ====================================================================== #ifndef Svc_PolyDb_HPP #define Svc_PolyDb_HPP #include "Svc/PolyDb/PolyDbImpl.hpp" namespace Svc { typedef PolyDbImpl PolyDb; } #endif
hpp
fprime
data/projects/fprime/Svc/PolyDb/PolyDbImpl.cpp
/* * PolyDbImpl.cpp * * Created on: May 13, 2014 * Author: Timothy Canham */ #include <Svc/PolyDb/PolyDbImpl.hpp> #include <Fw/Types/Assert.hpp> #include <FpConfig.hpp> namespace Svc { PolyDbImpl::PolyDbImpl(const char* name) : PolyDbComponentBase(name) { // initialize all entries to stale for (NATIVE_INT_TYPE entry = 0; entry < POLYDB_NUM_DB_ENTRIES; entry++) { this->m_db[entry].status = MeasurementStatus::STALE; } } void PolyDbImpl::init(NATIVE_INT_TYPE instance) { PolyDbComponentBase::init(instance); } // If ports are no longer guarded, these accesses need to be protected from each other // If there are a lot of accesses, perhaps an interrupt lock could be used instead of guarded ports void PolyDbImpl::getValue_handler(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val) { FW_ASSERT(entry < POLYDB_NUM_DB_ENTRIES,entry); status = this->m_db[entry].status; time = this->m_db[entry].time; val = this->m_db[entry].val; } void PolyDbImpl::setValue_handler(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val) { FW_ASSERT(entry < POLYDB_NUM_DB_ENTRIES,entry); this->m_db[entry].status = status; this->m_db[entry].time = time; this->m_db[entry].val = val; } PolyDbImpl::~PolyDbImpl() { } }
cpp
fprime
data/projects/fprime/Svc/PolyDb/PolyDbImpl.hpp
/** * \file * \author T. Canham * \brief PolyDb is a database for storing telemetry for internal software use * * \copyright * Copyright 2009-2015, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * <br /><br /> */ #ifndef POLYDBIMPL_HPP_ #define POLYDBIMPL_HPP_ #include <Svc/PolyDb/PolyDbComponentAc.hpp> #include <Fw/Types/PolyType.hpp> #include <PolyDbImplCfg.hpp> namespace Svc { //! \class PolyDbImpl //! \brief PolyDb Component Class //! //! This component allows the setting and retrieving of PolyType //! telemetry values. It be used as a central analog database //! that can decouple measurement sources from measurement users. //! The intent is that measurement sources would convert DNs (data numbers) //! to ENs (Engineering Numbers) to decouple the conversion as well. //! class PolyDbImpl : public PolyDbComponentBase { public: //! \brief PolyDbImpl constructor //! //! The constructor initializes the database to "MeasurementStatus::STALE." //! All values retrieved will have this status until the first //! update is received. //! PolyDbImpl(const char* name); //! \brief PolyDbImpl initialization //! //! The PolyDbImpl initialization function calls the base //! class initializer. //! void init(NATIVE_INT_TYPE instance); //! \brief PolyDbImpl destructor //! //! The destructor is empty. //! virtual ~PolyDbImpl(); protected: private: //! \brief The value getter port handler //! //! The getter port handler looks up the indicated entry //! in the database and copies the contents into the user //! supplied arguments status, time, and val. //! //! \param portNum port number of request (always 0) //! \param status last status of retrieved measurement //! \param time time tag of latest measurement //! \param val value of latest measurement void getValue_handler(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val); //! \brief The value setter port handler //! //! The setter port handler takes the values passed //! and updates the entry in the database //! //! \param portNum port number of request (always 0) //! \param status status of new measurement //! \param time time tag of new measurement //! \param val value of new measurement void setValue_handler(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val); //! \struct t_dbStruct //! \brief PolyDb database structure //! //! This structure stores the latest values of the measurements. //! The statuses are all initialized to MeasurementStatus::STALE by the constructor. //! struct t_dbStruct { MeasurementStatus status; //!< last status of measurement Fw::PolyType val; //!< the last value of the measurement Fw::Time time; //!< the timetag of the last measurement } m_db[POLYDB_NUM_DB_ENTRIES]; }; } #endif /* POLYDBIMPL_HPP_ */
hpp
fprime
data/projects/fprime/Svc/PolyDb/test/ut/PolyDbImplTester.cpp
/* * PolyDbImplTester.cpp * * Created on: Sept 14, 2015 * Author: tcanham */ #include <Svc/PolyDb/test/ut/PolyDbImplTester.hpp> #include <cstdio> #include <gtest/gtest.h> #include <Fw/Test/UnitTest.hpp> namespace Svc { void PolyDbImplTester::init(NATIVE_INT_TYPE instance) { Svc::PolyDbTesterComponentBase::init(); } PolyDbImplTester::PolyDbImplTester(Svc::PolyDbImpl& inst) : Svc::PolyDbTesterComponentBase("testerbase") { } PolyDbImplTester::~PolyDbImplTester() { } void PolyDbImplTester::runNominalReadWrite() { enum { NUM_TEST_VALS = 12 // one for each type supported }; Fw::PolyType vals[NUM_TEST_VALS]; // set test values vals[0] = static_cast<U8>(1); vals[1] = static_cast<I8>(2); vals[2] = static_cast<U16>(3); vals[3] = static_cast<I16>(4); vals[4] = static_cast<U32>(5); vals[5] = static_cast<I32>(6); vals[6] = static_cast<U64>(7); vals[7] = static_cast<I64>(8); vals[8] = static_cast<F32>(9.0); vals[9] = static_cast<F64>(10.0); vals[10] = true; vals[11] = reinterpret_cast<void*>(0x100); Fw::Time ts(TB_NONE,6,7); bool r001Emitted = false; bool r002Emitted = false; bool r003Emitted = false; bool r004Emitted = false; // read and write normal values for each entry in the database with each status type for (MeasurementStatus::t mstatValue = MeasurementStatus::OK; mstatValue <= MeasurementStatus::STALE;) { MeasurementStatus mstat(mstatValue); for (U32 entry = 0; entry < POLYDB_NUM_DB_ENTRIES; entry++) { if (not r001Emitted) { REQUIREMENT("PDB-001"); r001Emitted = true; } this->setValue_out(0,entry,mstat,ts,vals[entry%NUM_TEST_VALS]); Fw::PolyType check; if (not r003Emitted) { REQUIREMENT("PDB-003"); r003Emitted = true; } Fw::Time checkTs; MeasurementStatus checkStat; this->getValue_out(0,entry,checkStat,checkTs,check); if (not r002Emitted) { REQUIREMENT("PDB-002"); r002Emitted = true; } if (vals[entry%NUM_TEST_VALS].isF32() or vals[entry%NUM_TEST_VALS].isF64()) { ASSERT_NE(check,vals[entry%NUM_TEST_VALS]); } else { ASSERT_EQ(check,vals[entry%NUM_TEST_VALS]); } ASSERT_EQ(checkTs,ts); if (not r004Emitted) { REQUIREMENT("PDB-004"); r004Emitted = true; } ASSERT_EQ(mstatValue,checkStat.e); } mstatValue = static_cast<MeasurementStatus::t>(mstatValue + 1); } } } /* namespace Svc */
cpp
fprime
data/projects/fprime/Svc/PolyDb/test/ut/PolyDbTester.cpp
/* * PolyDbTester.cpp * * Created on: Sept 14, 2015 * Author: tcanham */ #include <Svc/PolyDb/test/ut/PolyDbImplTester.hpp> #include <Svc/PolyDb/PolyDbImpl.hpp> #include <Fw/Obj/SimpleObjRegistry.hpp> #include <gtest/gtest.h> #include <Fw/Test/UnitTest.hpp> void connectPorts(Svc::PolyDbImpl& impl, Svc::PolyDbImplTester& tester) { //Fw::SimpleObjRegistry simpleReg; // command ports tester.set_getValue_OutputPort(0,impl.get_getValue_InputPort(0)); tester.set_setValue_OutputPort(0,impl.get_setValue_InputPort(0)); #if FW_PORT_TRACING //Fw::PortBase::setTrace(true); #endif //simpleReg.dump(); } TEST(CmdDispTestNominal,NominalReadWrite) { TEST_CASE(104.1.1, "PolyDb Nominal Read/Write Test"); COMMENT( "Read and write values to the database while varying" "the measurement statuses." ); Svc::PolyDbImpl impl("PolyDbImpl"); impl.init(0); Svc::PolyDbImplTester tester(impl); tester.init(); // connect ports connectPorts(impl,tester); tester.runNominalReadWrite(); } #ifndef TGT_OS_TYPE_VXWORKS int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif
cpp
fprime
data/projects/fprime/Svc/PolyDb/test/ut/PolyDbImplTester.hpp
/* * PolyDbImplTester.hpp * * Created on: Sept 14, 2015 * Author: tcanham */ #ifndef POLYDB_TEST_UT_TLMCHANIMPLTESTER_HPP_ #define POLYDB_TEST_UT_TLMCHANIMPLTESTER_HPP_ #include <Svc/PolyDb/test/ut/PolyDbComponentTestAc.hpp> #include <Svc/PolyDb/PolyDbImpl.hpp> namespace Svc { class PolyDbImplTester: public Svc::PolyDbTesterComponentBase { public: PolyDbImplTester(Svc::PolyDbImpl& inst); virtual ~PolyDbImplTester(); void init(NATIVE_INT_TYPE instance = 0); void runNominalReadWrite(); }; } /* namespace Svc */ #endif /* POLYDB_TEST_UT_TLMCHANIMPLTESTER_HPP_ */
hpp
fprime
data/projects/fprime/Svc/PolyDb/test/ut/PolyDbComponentTestAc.hpp
/* * PolyDbComponentTestAc.hpp * * Created on: Monday, 14 September 2015 * Author: tcanham * */ #ifndef POLYDBCOMP_TESTER_HPP_ #define POLYDBCOMP_TESTER_HPP_ #include <FpConfig.hpp> #include <Fw/Comp/PassiveComponentBase.hpp> // type includes #include <Fw/Types/PolyType.hpp> #include <Fw/Time/Time.hpp> // port includes #include <Svc/PolyIf/PolyPortAc.hpp> // serializable includes namespace Svc { class PolyDbTesterComponentBase : public Fw::PassiveComponentBase { public: void set_getValue_OutputPort(NATIVE_INT_TYPE portNum, Svc::InputPolyPort *port); void set_setValue_OutputPort(NATIVE_INT_TYPE portNum, Svc::InputPolyPort *port); protected: // Only called by derived class PolyDbTesterComponentBase(const char* compName); virtual ~PolyDbTesterComponentBase(void); virtual void init(NATIVE_INT_TYPE instance = 0); // downcalls for input ports // upcalls for output ports void getValue_out(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val); void setValue_out(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val); NATIVE_INT_TYPE getNum_getValue_OutputPorts(void); NATIVE_INT_TYPE getNum_setValue_OutputPorts(void); // check to see if output port is connected bool isConnected_getValue_OutputPort(NATIVE_INT_TYPE portNum); bool isConnected_setValue_OutputPort(NATIVE_INT_TYPE portNum); private: // output ports Svc::OutputPolyPort m_getValue_OutputPort[1]; Svc::OutputPolyPort m_setValue_OutputPort[1]; // input ports // calls for incoming ports }; }; #endif /* POLYDBCOMP_TEST_HPP_ */
hpp
fprime
data/projects/fprime/Svc/PolyDb/test/ut/PolyDbComponentTestAc.cpp
#include <cstdio> #include <FpConfig.hpp> // The following header will need to be modified when test code is moved // If the component tester is regenerated, this will need to be modified again. // Make the compile fail to make sure it is changed #include <Svc/PolyDb/test/ut/PolyDbComponentTestAc.hpp> #include <Fw/Types/Assert.hpp> namespace Svc { // public methods void PolyDbTesterComponentBase::set_getValue_OutputPort(NATIVE_INT_TYPE portNum, Svc::InputPolyPort* port) { FW_ASSERT(portNum < this->getNum_getValue_OutputPorts()); this->m_getValue_OutputPort[portNum].addCallPort(port); } void PolyDbTesterComponentBase::set_setValue_OutputPort(NATIVE_INT_TYPE portNum, Svc::InputPolyPort* port) { FW_ASSERT(portNum < this->getNum_setValue_OutputPorts()); this->m_setValue_OutputPort[portNum].addCallPort(port); } PolyDbTesterComponentBase::PolyDbTesterComponentBase(const char* compName) : Fw::PassiveComponentBase(compName) { } PolyDbTesterComponentBase::~PolyDbTesterComponentBase() { } void PolyDbTesterComponentBase::init(NATIVE_INT_TYPE instance) { // initialize base class Fw::PassiveComponentBase::init(instance); // Input ports attached to component here with external component interfaces // Set output ports for (NATIVE_INT_TYPE port = 0; port < this->getNum_getValue_OutputPorts(); port++) { this->m_getValue_OutputPort[port].init(); #if FW_OBJECT_NAMES == 1 char portName[120]; snprintf(portName, sizeof(portName), "%s_getValue_OutputPort[%d]", this->m_objName.toChar(), port); this->m_getValue_OutputPort[port].setObjName(portName); #endif } for (NATIVE_INT_TYPE port = 0; port < this->getNum_setValue_OutputPorts(); port++) { this->m_setValue_OutputPort[port].init(); #if FW_OBJECT_NAMES == 1 char portName[120]; snprintf(portName, sizeof(portName), "%s_setValue_OutputPort[%d]", this->m_objName.toChar(), port); this->m_setValue_OutputPort[port].setObjName(portName); #endif } } // Up-calls, calls for output ports void PolyDbTesterComponentBase::getValue_out(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val) { FW_ASSERT(portNum < this->getNum_getValue_OutputPorts()); this->m_getValue_OutputPort[portNum].invoke(entry, status, time, val); } void PolyDbTesterComponentBase::setValue_out(NATIVE_INT_TYPE portNum, U32 entry, MeasurementStatus &status, Fw::Time &time, Fw::PolyType &val) { FW_ASSERT(portNum < this->getNum_setValue_OutputPorts()); this->m_setValue_OutputPort[portNum].invoke(entry, status, time, val); } NATIVE_INT_TYPE PolyDbTesterComponentBase::getNum_getValue_OutputPorts() { return static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_getValue_OutputPort)); } NATIVE_INT_TYPE PolyDbTesterComponentBase::getNum_setValue_OutputPorts() { return static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_setValue_OutputPort)); } bool PolyDbTesterComponentBase::isConnected_getValue_OutputPort(NATIVE_INT_TYPE portNum) { FW_ASSERT(portNum < this->getNum_getValue_OutputPorts(),portNum); return this->m_getValue_OutputPort[portNum].isConnected(); } bool PolyDbTesterComponentBase::isConnected_setValue_OutputPort(NATIVE_INT_TYPE portNum) { FW_ASSERT(portNum < this->getNum_setValue_OutputPorts(),portNum); return this->m_setValue_OutputPort[portNum].isConnected(); } // private methods }
cpp
fprime
data/projects/fprime/Svc/AssertFatalAdapter/AssertFatalAdapterComponentImpl.hpp
// ====================================================================== // \title AssertFatalAdapterImpl.hpp // \author tcanham // \brief hpp file for AssertFatalAdapter component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef AssertFatalAdapter_HPP #define AssertFatalAdapter_HPP #include "Svc/AssertFatalAdapter/AssertFatalAdapterComponentAc.hpp" namespace Svc { class AssertFatalAdapterComponentImpl : public AssertFatalAdapterComponentBase { public: // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct object AssertFatalAdapter //! AssertFatalAdapterComponentImpl( const char *const compName /*!< The component name*/ ); //! Initialize object AssertFatalAdapter //! void init( const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/ ); //! Destroy object AssertFatalAdapter //! ~AssertFatalAdapterComponentImpl(); //! Report the assert as a FATAL void reportAssert( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, FwAssertArgType arg1, FwAssertArgType arg2, FwAssertArgType arg3, FwAssertArgType arg4, FwAssertArgType arg5, FwAssertArgType arg6 ); private: class AssertFatalAdapter : public Fw::AssertHook { public: AssertFatalAdapter(); ~AssertFatalAdapter(); void regAssertReporter(AssertFatalAdapterComponentImpl* compPtr); private: void reportAssert( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, FwAssertArgType arg1, FwAssertArgType arg2, FwAssertArgType arg3, FwAssertArgType arg4, FwAssertArgType arg5, FwAssertArgType arg6 ); // Prevent actual assert since FATAL handler will deal with it void doAssert(); AssertFatalAdapterComponentImpl* m_compPtr; }; AssertFatalAdapter m_adapter; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/AssertFatalAdapter/AssertFatalAdapterComponentImpl.cpp
// ====================================================================== // \title AssertFatalAdapterImpl.cpp // \author tcanham // \brief cpp file for AssertFatalAdapter component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/AssertFatalAdapter/AssertFatalAdapterComponentImpl.hpp> #include <FpConfig.hpp> #include <Fw/Types/Assert.hpp> #include <Fw/Logger/Logger.hpp> #include <cassert> #include <cstdio> namespace Fw { void defaultReportAssert ( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, FwAssertArgType arg1, FwAssertArgType arg2, FwAssertArgType arg3, FwAssertArgType arg4, FwAssertArgType arg5, FwAssertArgType arg6, CHAR* destBuffer, NATIVE_INT_TYPE buffSize ); } namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- AssertFatalAdapterComponentImpl :: AssertFatalAdapterComponentImpl( const char *const compName ) : AssertFatalAdapterComponentBase(compName) { // register component with adapter this->m_adapter.regAssertReporter(this); // register adapter this->m_adapter.registerHook(); } void AssertFatalAdapterComponentImpl :: init( const NATIVE_INT_TYPE instance ) { AssertFatalAdapterComponentBase::init(instance); } AssertFatalAdapterComponentImpl :: ~AssertFatalAdapterComponentImpl() { } void AssertFatalAdapterComponentImpl::AssertFatalAdapter::reportAssert( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, FwAssertArgType arg1, FwAssertArgType arg2, FwAssertArgType arg3, FwAssertArgType arg4, FwAssertArgType arg5, FwAssertArgType arg6 ) { if (m_compPtr) { m_compPtr->reportAssert(file,lineNo,numArgs, arg1,arg2,arg3,arg4,arg5,arg6); } else { // Can't assert, what else can we do? Maybe somebody will see it. Fw::Logger::logMsg("Svc::AssertFatalAdapter not registered!\n"); assert(0); } } void AssertFatalAdapterComponentImpl::AssertFatalAdapter::regAssertReporter(AssertFatalAdapterComponentImpl* compPtr) { this->m_compPtr = compPtr; } AssertFatalAdapterComponentImpl::AssertFatalAdapter::AssertFatalAdapter() : m_compPtr(nullptr) { } AssertFatalAdapterComponentImpl::AssertFatalAdapter::~AssertFatalAdapter() { } void AssertFatalAdapterComponentImpl::AssertFatalAdapter::doAssert() { // do nothing since there will be a FATAL } void AssertFatalAdapterComponentImpl::reportAssert( FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo, NATIVE_UINT_TYPE numArgs, FwAssertArgType arg1, FwAssertArgType arg2, FwAssertArgType arg3, FwAssertArgType arg4, FwAssertArgType arg5, FwAssertArgType arg6 ) { #if FW_ASSERT_LEVEL == FW_FILEID_ASSERT Fw::LogStringArg fileArg; fileArg.format("0x%08" PRIX32,file); #else Fw::LogStringArg fileArg(file); #endif CHAR msg[FW_ASSERT_TEXT_SIZE] = {0}; Fw::defaultReportAssert(file,lineNo,numArgs,arg1,arg2,arg3,arg4,arg5,arg6,msg,sizeof(msg)); // fprintf(stderr... allocates large buffers on stack as stderr is unbuffered by the OS // and this can conflict with the traditionally smaller stack sizes. printf("%s\n", msg); // Handle the case where the ports aren't connected yet if (not this->isConnected_Log_OutputPort(0)) { assert(0); return; } switch (numArgs) { case 0: this->log_FATAL_AF_ASSERT_0(fileArg,lineNo); break; case 1: this->log_FATAL_AF_ASSERT_1(fileArg,lineNo,arg1); break; case 2: this->log_FATAL_AF_ASSERT_2(fileArg,lineNo,arg1,arg2); break; case 3: this->log_FATAL_AF_ASSERT_3(fileArg,lineNo,arg1,arg2,arg3); break; case 4: this->log_FATAL_AF_ASSERT_4(fileArg,lineNo,arg1,arg2,arg3,arg4); break; case 5: this->log_FATAL_AF_ASSERT_5(fileArg,lineNo,arg1,arg2,arg3,arg4,arg5); break; case 6: this->log_FATAL_AF_ASSERT_6(fileArg,lineNo,arg1,arg2,arg3,arg4,arg5,arg6); break; default: this->log_FATAL_AF_UNEXPECTED_ASSERT(fileArg,lineNo,numArgs); break; } } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/AssertFatalAdapter/AssertFatalAdapter.hpp
// ====================================================================== // AssertFatalAdapter.hpp // Standardization header for AssertFatalAdapter // ====================================================================== #ifndef Svc_AssertFatalAdapter_HPP #define Svc_AssertFatalAdapter_HPP #include "Svc/AssertFatalAdapter/AssertFatalAdapterComponentImpl.hpp" namespace Svc { typedef AssertFatalAdapterComponentImpl AssertFatalAdapter; } #endif
hpp
fprime
data/projects/fprime/Svc/AssertFatalAdapter/test/ut/main.cpp
#include "AssertFatalAdapterTester.hpp" TEST(Nominal,NominalInit) { Svc::AssertFatalAdapterTester tester; tester.testAsserts(); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/AssertFatalAdapter/test/ut/AssertFatalAdapterTester.hpp
// ====================================================================== // \title AssertFatalAdapter/test/ut/Tester.hpp // \author tcanham // \brief hpp file for AssertFatalAdapter test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef TESTER_HPP #define TESTER_HPP #include "AssertFatalAdapterGTestBase.hpp" #include "Svc/AssertFatalAdapter/AssertFatalAdapterComponentImpl.hpp" namespace Svc { class AssertFatalAdapterTester : public AssertFatalAdapterGTestBase { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- public: //! Construct object AssertFatalAdapterTester //! AssertFatalAdapterTester(); //! Destroy object AssertFatalAdapterTester //! ~AssertFatalAdapterTester(); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! To do //! void testAsserts(); private: // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- //! Connect ports //! void connectPorts(); //! Initialize components //! void initComponents(); private: // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- //! The component under test //! AssertFatalAdapterComponentImpl component; void textLogIn( const FwEventIdType id, //!< The event ID const Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ) override; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/AssertFatalAdapter/test/ut/AssertFatalAdapterTester.cpp
// ====================================================================== // \title AssertFatalAdapter.hpp // \author tcanham // \brief cpp file for AssertFatalAdapter test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include "Fw/Types/String.hpp" #include "Fw/Types/StringUtils.hpp" #include "AssertFatalAdapterTester.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 10 namespace Svc { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- AssertFatalAdapterTester::AssertFatalAdapterTester() : AssertFatalAdapterGTestBase("Tester", MAX_HISTORY_SIZE), component( "AssertFatalAdapter") { this->initComponents(); this->connectPorts(); } AssertFatalAdapterTester::~AssertFatalAdapterTester() { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void AssertFatalAdapterTester::testAsserts() { U32 lineNo; char file[80 + 1]; // Limit to 80 characters in the port call Fw::String fileString; // Asserts may be turned off resulting in this component doing a no-op #if FW_ASSERT_LEVEL == FW_NO_ASSERT const int expectedSize = 0; #else const int expectedSize = 1; #endif #if FW_ASSERT_LEVEL == FW_FILEID_ASSERT fileString.format("0x%08" PRIX32, ASSERT_FILE_ID); #else fileString = __FILE__; #endif (void) Fw::StringUtils::string_copy(file, fileString.toChar(), sizeof(file)); // FW_ASSERT_0 FW_ASSERT(0);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_0_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_0(0,file,lineNo); } // FW_ASSERT_1 FW_ASSERT(0,1);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_1_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_1(0,file,lineNo,1); } // FW_ASSERT_2 FW_ASSERT(0,1,2);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_2_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_2(0,file,lineNo,1,2); } // FW_ASSERT_3 FW_ASSERT(0,1,2,3);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_3_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_3(0,file,lineNo,1,2,3); } // FW_ASSERT_4 FW_ASSERT(0,1,2,3,4);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_4_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_4(0,file,lineNo,1,2,3,4); } // FW_ASSERT_5 FW_ASSERT(0,1,2,3,4,5);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_5_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_5(0,file,lineNo,1,2,3,4,5); } // FW_ASSERT_6 FW_ASSERT(0,1,2,3,4,5,6);lineNo = __LINE__; ASSERT_EVENTS_AF_ASSERT_6_SIZE(expectedSize); if (expectedSize > 0) { ASSERT_EVENTS_AF_ASSERT_6(0,file,lineNo,1,2,3,4,5,6); } // Test unexpected assert #if FW_ASSERT_LEVEL == FW_FILEID_ASSERT U32 unexpectedFile = 0xF00; const char *const unexpectedFileArg = "0x00000F00"; #else const char *const unexpectedFile = "foo"; const char *const unexpectedFileArg = unexpectedFile; #endif this->component.reportAssert(unexpectedFile,1000,10,1,2,3,4,5,6); ASSERT_EVENTS_AF_UNEXPECTED_ASSERT_SIZE(1); ASSERT_EVENTS_AF_UNEXPECTED_ASSERT(0,unexpectedFileArg,1000,10); } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void AssertFatalAdapterTester::connectPorts() { // Time this->component.set_Time_OutputPort(0, this->get_from_Time(0)); // Log this->component.set_Log_OutputPort(0, this->get_from_Log(0)); // LogText this->component.set_LogText_OutputPort(0, this->get_from_LogText(0)); } void AssertFatalAdapterTester::initComponents() { this->init(); this->component.init( INSTANCE); } void AssertFatalAdapterTester::textLogIn(const FwEventIdType id, //!< The event ID const Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ) { TextLogEntry e = { id, timeTag, severity, text }; printTextLogHistoryEntry(e, stdout); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/BufferRepeater/BufferRepeater.hpp
// ====================================================================== // \title BufferRepeater.hpp // \author lestarch // \brief hpp file for GenericRepeater component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef BufferRepeater_HPP #define BufferRepeater_HPP #include "Svc/BufferRepeater/BufferRepeaterComponentAc.hpp" namespace Svc { class BufferRepeater : public BufferRepeaterComponentBase { public: /** * Set of responses to failures to allocate a buffer when requested */ enum BufferRepeaterFailureOption { NO_RESPONSE_ON_OUT_OF_MEMORY, /*!< The component will continue regardless of allocation failures */ WARNING_ON_OUT_OF_MEMORY, /*!< The component will produce a warning on allocation failures */ FATAL_ON_OUT_OF_MEMORY, /*!< The component will produce a FATAL on allocation failures */ NUM_BUFFER_REPEATER_FAILURE_OPTIONS /*!< Maximum value of this setting. Used to mark as uninitialized. */ }; // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct object BufferRepeater //! BufferRepeater(const char* const compName /*!< The component name*/ ); //! Initialize object BufferRepeater //! void init(const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/ ); //! Destroy object BufferRepeater //! ~BufferRepeater(); /** * Set the response used when an allocation request fails to produce a buffer. By default this will assert. * @param allocation_failure_response: set response */ void configure(BufferRepeaterFailureOption allocation_failure_response); private: // ---------------------------------------------------------------------- // Helper functions // ---------------------------------------------------------------------- /** * Checks the allocation for viability and reports if it fails. * @param index: index of the port that needs this allocation * @param new_allocation: new allocation for a copy of the incoming buffer. * @param incoming_buffer: buffer that is to be cloned * @return true when the allocation is valid, false otherwise */ bool check_allocation(FwIndexType index, const Fw::Buffer& new_allocation, const Fw::Buffer& incoming_buffer); private: // ---------------------------------------------------------------------- // Handler implementations for user-defined serial input ports // ---------------------------------------------------------------------- //! Handler implementation for portIn //! void portIn_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& Buffer /*!< The serialization buffer*/ ); BufferRepeaterFailureOption m_allocation_failure_response; //!< Local storage for configured response }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/BufferRepeater/BufferRepeater.cpp
// ====================================================================== // \title BufferRepeater.cpp // \author lestarch // \brief cpp file for GenericRepeater component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <FpConfig.hpp> #include <Svc/BufferRepeater/BufferRepeater.hpp> namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- BufferRepeater ::BufferRepeater(const char* const compName) : BufferRepeaterComponentBase(compName), m_allocation_failure_response(BufferRepeater::NUM_BUFFER_REPEATER_FAILURE_OPTIONS) {} void BufferRepeater ::init(const NATIVE_INT_TYPE instance) { BufferRepeaterComponentBase::init(instance); } BufferRepeater ::~BufferRepeater() {} void BufferRepeater ::configure(BufferRepeater::BufferRepeaterFailureOption allocation_failure_response) { this->m_allocation_failure_response = allocation_failure_response; } bool BufferRepeater ::check_allocation(FwIndexType index, const Fw::Buffer& new_allocation, const Fw::Buffer& incoming_buffer) { FW_ASSERT(index < NUM_PORTOUT_OUTPUT_PORTS, index); bool is_valid = (new_allocation.getData() != nullptr) && (new_allocation.getSize() >= incoming_buffer.getSize()); // Respond to invalid buffer allocation if (!is_valid) { switch (this->m_allocation_failure_response) { case NO_RESPONSE_ON_OUT_OF_MEMORY: // No response intended break; case WARNING_ON_OUT_OF_MEMORY: this->log_WARNING_HI_AllocationSoftFailure(index, incoming_buffer.getSize()); break; case FATAL_ON_OUT_OF_MEMORY: this->log_FATAL_AllocationHardFailure(index, incoming_buffer.getSize()); break; default: FW_ASSERT(0); break; } } return is_valid; } // ---------------------------------------------------------------------- // Handler implementations for user-defined serial input ports // ---------------------------------------------------------------------- void BufferRepeater ::portIn_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& buffer /*!< The serialization buffer*/ ) { FW_ASSERT(this->m_allocation_failure_response < NUM_BUFFER_REPEATER_FAILURE_OPTIONS); for (FwIndexType i = 0; i < NUM_PORTOUT_OUTPUT_PORTS; i++) { if (isConnected_portOut_OutputPort(i)) { Fw::Buffer new_allocation = this->allocate_out(0, buffer.getSize()); if (this->check_allocation(i, new_allocation, buffer)) { // Clone the data and send it ::memcpy(new_allocation.getData(), buffer.getData(), buffer.getSize()); new_allocation.setSize(buffer.getSize()); this->portOut_out(i, new_allocation); } } } this->deallocate_out(0, buffer); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/BufferRepeater/test/ut/BufferRepeaterTestMain.cpp
// ---------------------------------------------------------------------- // TestMain.cpp // ---------------------------------------------------------------------- #include "BufferRepeaterTester.hpp" TEST(Nominal, TestRepeater) { Svc::BufferRepeaterTester tester; tester.testRepeater(); } TEST(OffNominal, NoMemoryResponse) { Svc::BufferRepeaterTester tester; tester.testFailure(Svc::BufferRepeater::NO_RESPONSE_ON_OUT_OF_MEMORY); } TEST(OffNominal, WarningMemoryResponse) { Svc::BufferRepeaterTester tester; tester.testFailure(Svc::BufferRepeater::WARNING_ON_OUT_OF_MEMORY); } TEST(OffNominal, FatalMemoryResponse) { Svc::BufferRepeaterTester tester; tester.testFailure(Svc::BufferRepeater::FATAL_ON_OUT_OF_MEMORY); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/BufferRepeater/test/ut/BufferRepeaterTester.hpp
// ====================================================================== // \title BufferRepeater/test/ut/Tester.hpp // \author lestarch // \brief hpp file for GenericRepeater test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef TESTER_HPP #define TESTER_HPP #include "BufferRepeaterGTestBase.hpp" #include "Svc/BufferRepeater/BufferRepeater.hpp" namespace Svc { class BufferRepeaterTester : public BufferRepeaterGTestBase { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- public: //! Construct object BufferRepeaterTester //! BufferRepeaterTester(); //! Destroy object BufferRepeaterTester //! ~BufferRepeaterTester(); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Test the repeating capability of the buffer //! void testRepeater(); //! Test the repeating capability of the buffer //! void testFailure(BufferRepeater::BufferRepeaterFailureOption failure_option); private: // ---------------------------------------------------------------------- // Handlers for serial from ports // ---------------------------------------------------------------------- //! Handler for from_allocate //! Fw::Buffer from_allocate_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 size); //! Handler for from_deallocate //! void from_deallocate_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& fwBuffer); //! Handler for from_portOut //! void from_portOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& fwBuffer); private: // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- //! Connect ports //! void connectPorts(); //! Initialize components //! void initComponents(); private: // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- //! The component under test //! BufferRepeater component; History<NATIVE_INT_TYPE> m_port_index_history; Fw::Buffer m_initial_buffer; bool m_failure; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/BufferRepeater/test/ut/BufferRepeaterTester.cpp
// ====================================================================== // \title BufferRepeater.hpp // \author lestarch // \brief cpp file for BufferRepeater test harness implementation class // ====================================================================== #include "BufferRepeaterTester.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 10 namespace Svc { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- BufferRepeaterTester ::BufferRepeaterTester() : BufferRepeaterGTestBase("Tester", MAX_HISTORY_SIZE), component("BufferRepeater"), m_port_index_history(MAX_HISTORY_SIZE), m_initial_buffer(), m_failure(false) { this->initComponents(); this->connectPorts(); } BufferRepeaterTester ::~BufferRepeaterTester() {} // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void BufferRepeaterTester ::testRepeater() { this->component.configure(BufferRepeater::FATAL_ON_OUT_OF_MEMORY); m_initial_buffer.setSize(1024); m_initial_buffer.setData(new U8[1024]); for (U32 i = 0; i < m_initial_buffer.getSize(); i++) { m_initial_buffer.getData()[i] = static_cast<U8>(i); } invoke_to_portIn(0, m_initial_buffer); ASSERT_EVENTS_AllocationHardFailure_SIZE(0); ASSERT_EVENTS_AllocationSoftFailure_SIZE(0); ASSERT_from_portOut_SIZE(this->component.getNum_portOut_OutputPorts()); ASSERT_EQ(fromPortHistory_portOut->size(), this->m_port_index_history.size()); for (NATIVE_INT_TYPE i = 0; i < this->component.getNum_portOut_OutputPorts(); i++) { NATIVE_INT_TYPE port_index = this->m_port_index_history.at(i); ASSERT_EQ(i, port_index); Fw::Buffer buffer_under_test = this->fromPortHistory_portOut->at(i).fwBuffer; ASSERT_EQ(buffer_under_test.getSize(), m_initial_buffer.getSize()); for (U32 j = 0; j < FW_MIN(buffer_under_test.getSize(), m_initial_buffer.getSize()); j++) { ASSERT_EQ(buffer_under_test.getData()[j], m_initial_buffer.getData()[j]) << "Data not copied correctly at offset: " << j; } // Deallocate allocated data if (buffer_under_test.getData() != nullptr) { delete[] buffer_under_test.getData(); } } // Check proper deallocation ASSERT_from_deallocate_SIZE(1); ASSERT_EQ(m_initial_buffer.getData(), fromPortHistory_deallocate->at(0).fwBuffer.getData()); ASSERT_EQ(m_initial_buffer.getSize(), fromPortHistory_deallocate->at(0).fwBuffer.getSize()); delete[] m_initial_buffer.getData(); m_initial_buffer.setData(nullptr); } void BufferRepeaterTester ::testFailure(BufferRepeater::BufferRepeaterFailureOption failure_option) { this->m_failure = true; this->component.configure(failure_option); m_initial_buffer.setSize(1024); m_initial_buffer.setData(new U8[1024]); invoke_to_portIn(0, m_initial_buffer); switch (failure_option) { case BufferRepeater::WARNING_ON_OUT_OF_MEMORY: ASSERT_EVENTS_AllocationHardFailure_SIZE(0); ASSERT_EVENTS_AllocationSoftFailure_SIZE(this->component.getNum_portOut_OutputPorts()); break; case BufferRepeater::FATAL_ON_OUT_OF_MEMORY: ASSERT_EVENTS_AllocationHardFailure_SIZE(this->component.getNum_portOut_OutputPorts()); ASSERT_EVENTS_AllocationSoftFailure_SIZE(0); break; // Cascade intended case BufferRepeater::NO_RESPONSE_ON_OUT_OF_MEMORY: case BufferRepeater::NUM_BUFFER_REPEATER_FAILURE_OPTIONS: ASSERT_EVENTS_AllocationHardFailure_SIZE(0); ASSERT_EVENTS_AllocationSoftFailure_SIZE(0); break; } ASSERT_from_portOut_SIZE(0); // Check proper deallocation ASSERT_from_deallocate_SIZE(1); ASSERT_EQ(m_initial_buffer.getData(), fromPortHistory_deallocate->at(0).fwBuffer.getData()); ASSERT_EQ(m_initial_buffer.getSize(), fromPortHistory_deallocate->at(0).fwBuffer.getSize()); delete[] m_initial_buffer.getData(); m_initial_buffer.setData(nullptr); } // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- Fw::Buffer BufferRepeaterTester ::from_allocate_handler(const NATIVE_INT_TYPE portNum, U32 size) { this->pushFromPortEntry_allocate(size); Fw::Buffer new_buffer; if (m_failure) { new_buffer.setSize(0); new_buffer.setData(nullptr); } else { new_buffer.setSize(size); new_buffer.setData(new U8[size]); } return new_buffer; } void BufferRepeaterTester ::from_deallocate_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) { this->pushFromPortEntry_deallocate(fwBuffer); EXPECT_EQ(fwBuffer.getData(), m_initial_buffer.getData()) << "Deallocated non-initial buffer"; } void BufferRepeaterTester ::from_portOut_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) { this->m_port_index_history.push_back(portNum); this->pushFromPortEntry_portOut(fwBuffer); EXPECT_NE(fwBuffer.getData(), nullptr) << "Passed invalid buffer out port"; } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void BufferRepeaterTester ::connectPorts() { // portIn this->connect_to_portIn(0, this->component.get_portIn_InputPort(0)); // Log this->component.set_Log_OutputPort(0, this->get_from_Log(0)); // LogText this->component.set_LogText_OutputPort(0, this->get_from_LogText(0)); // Time this->component.set_Time_OutputPort(0, this->get_from_Time(0)); // allocate this->component.set_allocate_OutputPort(0, this->get_from_allocate(0)); // deallocate this->component.set_deallocate_OutputPort(0, this->get_from_deallocate(0)); // portOut for (NATIVE_INT_TYPE i = 0; i < this->component.getNum_portOut_OutputPorts(); ++i) { this->component.set_portOut_OutputPort(i, this->get_from_portOut(i)); } } void BufferRepeaterTester ::initComponents() { this->init(); this->component.init(INSTANCE); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/Deframer/Deframer.hpp
// ====================================================================== // \title Deframer.hpp // \author mstarch, bocchino // \brief hpp file for Deframer component implementation class // // \copyright // Copyright 2009-2022, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef Svc_Deframer_HPP #define Svc_Deframer_HPP #include "Svc/Deframer/DeframerComponentAc.hpp" #include "Svc/FramingProtocol/DeframingProtocol.hpp" #include "Svc/FramingProtocol/DeframingProtocolInterface.hpp" #include "Utils/Types/CircularBuffer.hpp" #include "config/DeframerCfg.hpp" namespace Svc { /** * \brief Generic deframing component using DeframingProtocol implementation for actual deframing * * Deframing component used to take byte streams and expand them into Com/File buffers. This is * done using a deframing protocol specified in a DeframingProtocol instance. The instance must be * supplied using the `setup` method. * * Using this component, projects can implement and supply a fresh DeframingProtocol implementation * without changing the reference topology. * * Implementation uses a circular buffer to store incoming data, which is drained one framed packet * at a time into buffers dispatched to the rest of the system. */ class Deframer : public DeframerComponentBase, public DeframingProtocolInterface { public: // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct Deframer instance Deframer( const char* const compName //!< The component name ); //! Initialize Deframer instance void init( const NATIVE_INT_TYPE instance = 0 //!< The instance number ); //! Destroy Deframer instance ~Deframer(); //! Set up the instance void setup( DeframingProtocol& protocol //!< Deframing protocol instance ); PRIVATE: // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- //! Handler for input port cmdResponseIn void cmdResponseIn_handler( NATIVE_INT_TYPE portNum, //!< The port number FwOpcodeType opcode, //!< The command opcode U32 cmdSeq, //!< The command sequence number const Fw::CmdResponse& response //!< The command response ); //! Handler implementation for framedIn void framedIn_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::Buffer& recvBuffer, //!< Buffer containing framed data const Drv::RecvStatus& recvStatus //!< Status of the bytes ); //! Handler implementation for schedIn void schedIn_handler( const NATIVE_INT_TYPE portNum, //!< The port number U32 context //!< The call order ); // ---------------------------------------------------------------------- // Implementation of DeframingProtocolInterface // ---------------------------------------------------------------------- //! The implementation of DeframingProtocolInterface::route //! Send a data packet void route( Fw::Buffer& packetBuffer //!< The packet buffer ); //! The implementation of DeframingProtocolInterface::allocate //! Allocate a packet buffer //! \return The packet buffer Fw::Buffer allocate( const U32 size //!< The number of bytes to request ); // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- //! Copy data from an incoming frame buffer into the internal //! circular buffer void processBuffer( Fw::Buffer& buffer //!< The frame buffer ); //! Process data in the circular buffer void processRing(); // ---------------------------------------------------------------------- // Member variables // ---------------------------------------------------------------------- //! The DeframingProtocol implementation DeframingProtocol* m_protocol; //! The circular buffer Types::CircularBuffer m_inRing; //! Memory for the circular buffer U8 m_ringBuffer[DeframerCfg::RING_BUFFER_SIZE]; //! Memory for the polling buffer U8 m_pollBuffer[DeframerCfg::POLL_BUFFER_SIZE]; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/Deframer/Deframer.cpp
// ====================================================================== // \title Deframer.cpp // \author mstarch, bocchino // \brief cpp file for Deframer component implementation class // // \copyright // Copyright 2009-2022, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <cstring> #include "Fw/Com/ComPacket.hpp" #include "Fw/Logger/Logger.hpp" #include <FpConfig.hpp> #include "Svc/Deframer/Deframer.hpp" namespace Svc { // ---------------------------------------------------------------------- // Static assertions // ---------------------------------------------------------------------- static_assert( DeframerCfg::POLL_BUFFER_SIZE > 0, "poll buffer size must be greater than zero" ); static_assert( DeframerCfg::RING_BUFFER_SIZE > 0, "ring buffer size must be greater than zero" ); // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- Deframer ::Deframer(const char* const compName) : DeframerComponentBase(compName), DeframingProtocolInterface(), m_protocol(nullptr), m_inRing(m_ringBuffer, sizeof m_ringBuffer) { (void) memset(m_pollBuffer, 0, sizeof m_pollBuffer); } void Deframer ::init(const NATIVE_INT_TYPE instance) { DeframerComponentBase::init(instance); } Deframer ::~Deframer() {} void Deframer ::setup(DeframingProtocol& protocol) { // Check that this is the first time we are calling setup FW_ASSERT(m_protocol == nullptr); // Assign the protocol passed in to m_protocol m_protocol = &protocol; // Pass *this as the DeframingProtocolInstance to protocol setup // Deframer is derived from and implements DeframingProtocolInterface protocol.setup(*this); } // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- void Deframer ::cmdResponseIn_handler( NATIVE_INT_TYPE portNum, FwOpcodeType opcode, U32 cmdSeq, const Fw::CmdResponse& response ) { // Nothing to do } void Deframer ::framedIn_handler( const NATIVE_INT_TYPE portNum, Fw::Buffer& recvBuffer, const Drv::RecvStatus& recvStatus ) { // Check whether there is data to process if (recvStatus.e == Drv::RecvStatus::RECV_OK) { // There is: process the data processBuffer(recvBuffer); } // Deallocate the buffer framedDeallocate_out(0, recvBuffer); } void Deframer ::schedIn_handler( const NATIVE_INT_TYPE portNum, U32 context ) { // Check for data Fw::Buffer buffer(m_pollBuffer, sizeof(m_pollBuffer)); const Drv::PollStatus status = framedPoll_out(0, buffer); if (status.e == Drv::PollStatus::POLL_OK) { // Data exists: process it processBuffer(buffer); } } // ---------------------------------------------------------------------- // Implementation of DeframingProtocolInterface // ---------------------------------------------------------------------- Fw::Buffer Deframer ::allocate(const U32 size) { return bufferAllocate_out(0, size); } void Deframer ::route(Fw::Buffer& packetBuffer) { // Read the packet type from the packet buffer FwPacketDescriptorType packetType = Fw::ComPacket::FW_PACKET_UNKNOWN; Fw::SerializeStatus status = Fw::FW_SERIALIZE_OK; { Fw::SerializeBufferBase& serial = packetBuffer.getSerializeRepr(); status = serial.setBuffLen(packetBuffer.getSize()); FW_ASSERT(status == Fw::FW_SERIALIZE_OK); status = serial.deserialize(packetType); } // Whether to deallocate the packet buffer bool deallocate = true; // Process the packet if (status == Fw::FW_SERIALIZE_OK) { U8 *const packetData = packetBuffer.getData(); const U32 packetSize = packetBuffer.getSize(); switch (packetType) { // Handle a command packet case Fw::ComPacket::FW_PACKET_COMMAND: { // Allocate a com buffer on the stack Fw::ComBuffer com; // Copy the contents of the packet buffer into the com buffer status = com.setBuff(packetData, packetSize); if (status == Fw::FW_SERIALIZE_OK) { // Send the com buffer comOut_out(0, com, 0); } else { Fw::Logger::logMsg( "[ERROR] Serializing com buffer failed with status %d\n", status ); } break; } // Handle a file packet case Fw::ComPacket::FW_PACKET_FILE: { // If the file uplink output port is connected, // send the file packet. Otherwise take no action. if (isConnected_bufferOut_OutputPort(0)) { // Shift the packet buffer to skip the packet type // The FileUplink component does not expect the packet // type to be there. packetBuffer.setData(packetData + sizeof(packetType)); packetBuffer.setSize(packetSize - sizeof(packetType)); // Send the packet buffer bufferOut_out(0, packetBuffer); // Transfer ownership of the buffer to the receiver deallocate = false; } break; } // Take no action for other packet types default: break; } } else { Fw::Logger::logMsg( "[ERROR] Deserializing packet type failed with status %d\n", status ); } if (deallocate) { // Deallocate the packet buffer bufferDeallocate_out(0, packetBuffer); } } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void Deframer ::processBuffer(Fw::Buffer& buffer) { const U32 bufferSize = buffer.getSize(); U8 *const bufferData = buffer.getData(); // Current offset into buffer U32 offset = 0; // Remaining data in buffer U32 remaining = bufferSize; for (U32 i = 0; i < bufferSize; ++i) { // If there is no data left, exit the loop if (remaining == 0) { break; } // Compute the size of data to serialize const NATIVE_UINT_TYPE ringFreeSize = m_inRing.get_free_size(); const NATIVE_UINT_TYPE serSize = (ringFreeSize <= remaining) ? ringFreeSize : static_cast<NATIVE_UINT_TYPE>(remaining); // Serialize data into the ring buffer const Fw::SerializeStatus status = m_inRing.serialize(&bufferData[offset], serSize); // If data does not fit, there is a coding error FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status, offset, serSize); // Process the data processRing(); // Update buffer offset and remaining offset += serSize; remaining -= serSize; } // In every iteration, either remaining == 0 and we break out // of the loop, or we consume at least one byte from the buffer. // So there should be no data left in the buffer. FW_ASSERT(remaining == 0, remaining); } void Deframer ::processRing() { FW_ASSERT(m_protocol != nullptr); // The number of remaining bytes in the ring buffer U32 remaining = 0; // The protocol status DeframingProtocol::DeframingStatus status = DeframingProtocol::DEFRAMING_STATUS_SUCCESS; // The ring buffer capacity const NATIVE_UINT_TYPE ringCapacity = m_inRing.get_capacity(); // Process the ring buffer looking for at least the header for (U32 i = 0; i < ringCapacity; i++) { // Get the number of bytes remaining in the ring buffer remaining = m_inRing.get_allocated_size(); // If there are none, we are done if (remaining == 0) { break; } // Needed is an out-only variable // Initialize it to zero U32 needed = 0; // Call the deframe method of the protocol, getting // needed and status status = m_protocol->deframe(m_inRing, needed); // Deframing protocol must not consume data in the ring buffer FW_ASSERT( m_inRing.get_allocated_size() == remaining, m_inRing.get_allocated_size(), remaining ); // On successful deframing, consume data from the ring buffer now if (status == DeframingProtocol::DEFRAMING_STATUS_SUCCESS) { // If deframing succeeded, protocol should set needed // to a non-zero value FW_ASSERT(needed != 0); FW_ASSERT(needed <= remaining, needed, remaining); m_inRing.rotate(needed); FW_ASSERT( m_inRing.get_allocated_size() == remaining - needed, m_inRing.get_allocated_size(), remaining, needed ); } // More data needed else if (status == DeframingProtocol::DEFRAMING_MORE_NEEDED) { // Deframing protocol should not report "more is needed" // unless more is needed FW_ASSERT(needed > remaining, needed, remaining); // Break out of loop: suspend deframing until we receive // another buffer break; } // Error occurred else { // Skip one byte of bad data m_inRing.rotate(1); FW_ASSERT( m_inRing.get_allocated_size() == remaining - 1, m_inRing.get_allocated_size(), remaining ); // Log checksum errors // This is likely a real error, not an artifact of other data corruption if (status == DeframingProtocol::DEFRAMING_INVALID_CHECKSUM) { Fw::Logger::logMsg("[ERROR] Deframing checksum validation failed\n"); } } } // If more not needed, circular buffer should be empty if (status != DeframingProtocol::DEFRAMING_MORE_NEEDED) { FW_ASSERT(remaining == 0, remaining); } } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut/DeframerTestMain.cpp
// ---------------------------------------------------------------------- // TestMain.cpp // ---------------------------------------------------------------------- #include "DeframerTester.hpp" #include <Fw/Test/UnitTest.hpp> #include <Svc/FramingProtocol/DeframingProtocol.hpp> TEST(Deframer, TestMoreNeeded) { COMMENT("Send a frame buffer to the mock protocol, expecting more needed"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-007"); Svc::DeframerTester tester; tester.test_incoming_frame(Svc::DeframingProtocol::DEFRAMING_MORE_NEEDED); } TEST(Deframer, TestSuccess) { COMMENT("Send a frame buffer to the mock protocol, expecting success"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-007"); Svc::DeframerTester tester; tester.test_incoming_frame(Svc::DeframingProtocol::DEFRAMING_STATUS_SUCCESS); } TEST(Deframer, TestBadChecksum) { COMMENT("Send a frame buffer to the mock protocol, expecting bad checksum"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-007"); Svc::DeframerTester tester; tester.test_incoming_frame(Svc::DeframingProtocol::DEFRAMING_INVALID_CHECKSUM); } TEST(Deframer, TestBadSize) { COMMENT("Send a frame buffer to the mock protocol, expecting bad size"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-007"); Svc::DeframerTester tester; tester.test_incoming_frame(Svc::DeframingProtocol::DEFRAMING_INVALID_SIZE); } TEST(Deframer, TestBadFormat) { COMMENT("Send a frame buffer to the mock protocol, expecting bad format"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-007"); Svc::DeframerTester tester; tester.test_incoming_frame(Svc::DeframingProtocol::DEFRAMING_INVALID_FORMAT); } TEST(Deframer, TestComInterface) { COMMENT("Route a com packet"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); REQUIREMENT("SVC-DEFRAMER-010"); Svc::DeframerTester tester; tester.test_com_interface(); } TEST(Deframer, TestFileInterface) { COMMENT("Route a file packet"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); REQUIREMENT("SVC-DEFRAMER-010"); Svc::DeframerTester tester; tester.test_file_interface(); } TEST(Deframer, TestUnknownInterface) { COMMENT("Attempt to route a packet of unknown type"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); Svc::DeframerTester tester; tester.test_unknown_interface(); } TEST(Deframer, TestCommandResponse) { COMMENT("Handle a command response (no-op)"); Svc::DeframerTester tester; tester.testCommandResponse(); } TEST(Deframer, TestCommandPacketTooLarge) { COMMENT("Attempt to route a command packet that is too large"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); Svc::DeframerTester tester; tester.testCommandPacketTooLarge(); } TEST(Deframer, TestPacketBufferTooSmall) { COMMENT("Attempt to route a packet that is too small"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); Svc::DeframerTester tester; tester.testPacketBufferTooSmall(); } TEST(Deframer, TestBufferOutUnconnected) { COMMENT("Test routing a file packet when bufferOut is unconnected"); REQUIREMENT("SVC-DEFRAMER-011"); Svc::DeframerTester tester(Svc::DeframerTester::ConnectStatus::UNCONNECTED); tester.testBufferOutUnconnected(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut/DeframerTester.hpp
// ====================================================================== // \title Deframer/test/ut/Tester.hpp // \author janamian, bocchino // \brief hpp file for Deframer test harness implementation class // // \copyright // Copyright 2009-2021, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef TESTER_HPP #define TESTER_HPP #include "DeframerGTestBase.hpp" #include "Svc/Deframer/Deframer.hpp" namespace Svc { class DeframerTester : public DeframerGTestBase { public: // ---------------------------------------------------------------------- // Types // ---------------------------------------------------------------------- struct ConnectStatus { //! Whether a port is connected typedef enum { CONNECTED, UNCONNECTED } t; }; // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- class MockDeframer : public DeframingProtocol { public: MockDeframer(DeframerTester& parent); DeframingStatus deframe(Types::CircularBuffer& ring_buffer, U32& needed); //! Test the implementation of DeframingProtocolInterface provided //! by the Deframer component void test_interface(Fw::ComPacket::ComPacketType com_type); DeframingStatus m_status; }; public: //! Construct object DeframerTester //! DeframerTester(ConnectStatus::t bufferOutStatus = ConnectStatus::CONNECTED); //! Destroy object DeframerTester //! ~DeframerTester(); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Send a frame to framedIn void test_incoming_frame( DeframingProtocol::DeframingStatus status //!< The status that the mock deframer will return ); //! Route a com packet void test_com_interface(); //! Route a file packet void test_file_interface(); //! Route a packet of unknown type void test_unknown_interface(); //! Invoke the command response input port void testCommandResponse(); //! Attempt to route a command packet that is too large void testCommandPacketTooLarge(); //! Attempt to route a packet buffer that is too small void testPacketBufferTooSmall(); //! Route a file packet with bufferOutUnconnected void testBufferOutUnconnected(); private: // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- //! Handler for from_comOut //! void from_comOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::ComBuffer& data, /*!< Buffer containing packet data*/ U32 context /*!< Call context value; meaning chosen by user*/ ); //! Handler for from_bufferOut //! void from_bufferOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& fwBuffer); //! Handler for from_bufferAllocate //! Fw::Buffer from_bufferAllocate_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 size); //! Handler for from_bufferDeallocate //! void from_bufferDeallocate_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& fwBuffer); //! Handler for from_framedDeallocate //! void from_framedDeallocate_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& fwBuffer); //! Handler for from_framedPoll //! Drv::PollStatus from_framedPoll_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::Buffer& pollBuffer); private: // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- //! Connect ports //! void connectPorts(); //! Initialize components //! void initComponents(); private: // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- //! The component under test //! Deframer component; Fw::Buffer m_buffer; MockDeframer m_mock; // Whether the bufferOut port is connected ConnectStatus::t bufferOutStatus; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/Deframer/test/ut/DeframerTester.cpp
// ====================================================================== // \title Deframer.hpp // \author janamian, bocchino // \brief cpp file for Deframer test harness implementation class // // \copyright // Copyright 2009-2021, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <cstring> #include "DeframerTester.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 1000 namespace Svc { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- DeframerTester::MockDeframer::MockDeframer(DeframerTester& parent) : m_status(DeframingProtocol::DEFRAMING_STATUS_SUCCESS) {} DeframerTester::MockDeframer::DeframingStatus DeframerTester::MockDeframer::deframe(Types::CircularBuffer& ring_buffer, U32& needed) { needed = ring_buffer.get_allocated_size(); if (m_status == DeframingProtocol::DEFRAMING_MORE_NEEDED) { needed = ring_buffer.get_allocated_size() + 1; // Obey the rules } return m_status; } void DeframerTester::MockDeframer::test_interface(Fw::ComPacket::ComPacketType com_packet_type) { const FwPacketDescriptorType descriptorType = com_packet_type; U8 chars[sizeof descriptorType]; m_interface->allocate(3042); Fw::Buffer buffer(chars, sizeof(chars)); buffer.getSerializeRepr().serialize(descriptorType); m_interface->route(buffer); } DeframerTester ::DeframerTester(ConnectStatus::t bufferOutStatus) : DeframerGTestBase("Tester", MAX_HISTORY_SIZE), component("Deframer"), m_mock(*this), bufferOutStatus(bufferOutStatus) { this->initComponents(); this->connectPorts(); component.setup(this->m_mock); } DeframerTester ::~DeframerTester() {} // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void DeframerTester ::test_incoming_frame(DeframerTester::MockDeframer::DeframingStatus status) { U32 buffer_size = 512; U8 data[buffer_size]; ::memset(data, 0, buffer_size); Fw::Buffer recvBuffer(data, buffer_size); m_mock.m_status = status; Drv::RecvStatus recvStatus = Drv::RecvStatus::RECV_OK; invoke_to_framedIn(0, recvBuffer, recvStatus); // Check remaining size if (status == DeframingProtocol::DEFRAMING_MORE_NEEDED) { ASSERT_EQ(component.m_inRing.get_allocated_size(), buffer_size); } else if (status == DeframingProtocol::DEFRAMING_STATUS_SUCCESS) { ASSERT_EQ(component.m_inRing.get_allocated_size(), 0); } else { ASSERT_EQ(component.m_inRing.get_allocated_size(), 0); } ASSERT_from_framedDeallocate(0, recvBuffer); } void DeframerTester ::test_com_interface() { m_mock.test_interface(Fw::ComPacket::FW_PACKET_COMMAND); ASSERT_from_comOut_SIZE(1); ASSERT_from_bufferAllocate(0, 3042); ASSERT_from_bufferOut_SIZE(0); ASSERT_from_bufferDeallocate_SIZE(1); } void DeframerTester ::test_file_interface() { m_mock.test_interface(Fw::ComPacket::FW_PACKET_FILE); ASSERT_from_comOut_SIZE(0); ASSERT_from_bufferAllocate(0, 3042); ASSERT_from_bufferOut_SIZE(1); ASSERT_from_bufferDeallocate_SIZE(0); } void DeframerTester ::test_unknown_interface() { m_mock.test_interface(Fw::ComPacket::FW_PACKET_UNKNOWN); ASSERT_from_comOut_SIZE(0); ASSERT_from_bufferAllocate(0, 3042); ASSERT_from_bufferOut_SIZE(0); ASSERT_from_bufferDeallocate_SIZE(1); } void DeframerTester ::testCommandResponse() { const U32 portNum = 0; const U32 opcode = 0; const U32 cmdSeq = 0; const Fw::CmdResponse cmdResp(Fw::CmdResponse::OK); this->invoke_to_cmdResponseIn(portNum, opcode, cmdSeq, cmdResp); ASSERT_FROM_PORT_HISTORY_SIZE(0); } void DeframerTester ::testCommandPacketTooLarge() { // Allocate a large packet buffer enum { BUFFER_SIZE = 2 * FW_COM_BUFFER_MAX_SIZE }; U8 bytes[BUFFER_SIZE]; ::memset(bytes, 0, sizeof bytes); Fw::Buffer buffer(bytes, sizeof bytes); // Serialize the packet type Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr(); const FwPacketDescriptorType descriptorType = Fw::ComPacket::FW_PACKET_COMMAND; const Fw::SerializeStatus status = serialRepr.serialize(descriptorType); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); // Call the route method this->component.route(buffer); // Assert buffer deallocated, no packet output ASSERT_FROM_PORT_HISTORY_SIZE(1); ASSERT_from_bufferDeallocate_SIZE(1); } void DeframerTester ::testPacketBufferTooSmall() { // Allocate a small packet buffer U8 byte = 0; Fw::Buffer buffer(&byte, sizeof byte); // Call the route method this->component.route(buffer); // Assert buffer deallocated, no packet output ASSERT_FROM_PORT_HISTORY_SIZE(1); ASSERT_from_bufferDeallocate_SIZE(1); } void DeframerTester ::testBufferOutUnconnected() { ASSERT_EQ(this->bufferOutStatus, ConnectStatus::UNCONNECTED); enum { BUFFER_SIZE = 256 }; U8 bytes[BUFFER_SIZE]; ::memset(bytes, 0, sizeof bytes); Fw::Buffer buffer(bytes, sizeof bytes); // Serialize the packet type Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr(); const FwPacketDescriptorType descriptorType = Fw::ComPacket::FW_PACKET_FILE; const Fw::SerializeStatus status = serialRepr.serialize(descriptorType); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); // Call the route method this->component.route(buffer); // Assert buffer deallocated, no packet output ASSERT_FROM_PORT_HISTORY_SIZE(1); ASSERT_from_bufferDeallocate_SIZE(1); } // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- void DeframerTester ::from_comOut_handler(const NATIVE_INT_TYPE portNum, Fw::ComBuffer& data, U32 context) { this->pushFromPortEntry_comOut(data, context); } void DeframerTester ::from_bufferOut_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) { this->pushFromPortEntry_bufferOut(fwBuffer); } Fw::Buffer DeframerTester ::from_bufferAllocate_handler(const NATIVE_INT_TYPE portNum, U32 size) { this->pushFromPortEntry_bufferAllocate(size); Fw::Buffer buffer(nullptr, size); return buffer; } void DeframerTester ::from_bufferDeallocate_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) { this->pushFromPortEntry_bufferDeallocate(fwBuffer); } void DeframerTester ::from_framedDeallocate_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) { this->pushFromPortEntry_framedDeallocate(fwBuffer); } Drv::PollStatus DeframerTester ::from_framedPoll_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& pollBuffer) { this->pushFromPortEntry_framedPoll(pollBuffer); return Drv::PollStatus::POLL_OK; } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void DeframerTester ::connectPorts() { // bufferAllocate this->component.set_bufferAllocate_OutputPort(0, this->get_from_bufferAllocate(0)); // bufferDeallocate this->component.set_bufferDeallocate_OutputPort(0, this->get_from_bufferDeallocate(0)); // bufferOut if (this->bufferOutStatus == ConnectStatus::CONNECTED) { this->component.set_bufferOut_OutputPort(0, this->get_from_bufferOut(0)); } // cmdResponseIn this->connect_to_cmdResponseIn(0, this->component.get_cmdResponseIn_InputPort(0)); // comOut this->component.set_comOut_OutputPort(0, this->get_from_comOut(0)); // framedDeallocate this->component.set_framedDeallocate_OutputPort(0, this->get_from_framedDeallocate(0)); // framedIn this->connect_to_framedIn(0, this->component.get_framedIn_InputPort(0)); // framedPoll this->component.set_framedPoll_OutputPort(0, this->get_from_framedPoll(0)); // schedIn this->connect_to_schedIn(0, this->component.get_schedIn_InputPort(0)); } void DeframerTester ::initComponents() { this->init(); this->component.init(INSTANCE); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/DeframerTestMain.cpp
// ---------------------------------------------------------------------- // TestMain.cpp // ---------------------------------------------------------------------- #include <gtest/gtest.h> #include "Fw/Test/UnitTest.hpp" #include "GenerateFrames.hpp" #include "Os/Log.hpp" #include "STest/Scenario/BoundedScenario.hpp" #include "STest/Scenario/RandomScenario.hpp" #include "STest/Scenario/Scenario.hpp" #include "SendBuffer.hpp" #include "DeframerTester.hpp" #define STEP_COUNT 10000 // Uncomment the following line to turn on OS logging //Os::Log logger; // ---------------------------------------------------------------------- // Static helper functions // ---------------------------------------------------------------------- //! Run a random scenario static void runRandomScenario(Svc::DeframerTester::InputMode::t inputMode) { Svc::DeframerTester tester(Svc::DeframerTester::InputMode::PUSH); // Create rules, and assign them into the array Svc::GenerateFrames generateFrames; Svc::SendBuffer sendBuffer; // Setup a list of rules to choose from STest::Rule<Svc::DeframerTester>* rules[] = { &generateFrames, &sendBuffer }; // Construct the random scenario and run it with the defined bounds STest::RandomScenario<Svc::DeframerTester> random( "Random Rules", rules, FW_NUM_ARRAY_ELEMENTS(rules) ); // Setup a bounded scenario to run rules a set number of times STest::BoundedScenario<Svc::DeframerTester> bounded( "Bounded Random Rules Scenario", random, STEP_COUNT ); // Run! const U32 numSteps = bounded.run(tester); printf("Ran %u steps.\n", numSteps); } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- TEST(Nominal, BasicPush) { COMMENT("Send one buffer to the deframer, simulating an active driver (push)"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-004"); REQUIREMENT("SVC-DEFRAMER-007"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); REQUIREMENT("SVC-DEFRAMER-010"); Svc::DeframerTester tester(Svc::DeframerTester::InputMode::PUSH); Svc::GenerateFrames().apply(tester); Svc::SendBuffer().apply(tester); } TEST(Nominal, BasicPoll) { COMMENT("Send one buffer to the deframer, simulating a passive driver (poll)"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-005"); REQUIREMENT("SVC-DEFRAMER-006"); REQUIREMENT("SVC-DEFRAMER-007"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); REQUIREMENT("SVC-DEFRAMER-010"); Svc::DeframerTester tester(Svc::DeframerTester::InputMode::POLL); Svc::GenerateFrames().apply(tester); Svc::SendBuffer().apply(tester); } TEST(Nominal, RandomPush) { COMMENT("Send random buffers to the deframer, simulating an active driver (push)"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-004"); REQUIREMENT("SVC-DEFRAMER-007"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); REQUIREMENT("SVC-DEFRAMER-010"); runRandomScenario(Svc::DeframerTester::InputMode::PUSH); } TEST(Nominal, RandomPoll) { COMMENT("Send random buffers to the deframer, simulating a passive driver (poll)"); REQUIREMENT("SVC-DEFRAMER-001"); REQUIREMENT("SVC-DEFRAMER-002"); REQUIREMENT("SVC-DEFRAMER-003"); REQUIREMENT("SVC-DEFRAMER-005"); REQUIREMENT("SVC-DEFRAMER-006"); REQUIREMENT("SVC-DEFRAMER-007"); REQUIREMENT("SVC-DEFRAMER-008"); REQUIREMENT("SVC-DEFRAMER-009"); REQUIREMENT("SVC-DEFRAMER-010"); runRandomScenario(Svc::DeframerTester::InputMode::POLL); } TEST(Error, SizeOverflow) { COMMENT("Test handling of size overflow in F Prime deframing protocol"); Svc::DeframerTester tester(Svc::DeframerTester::InputMode::PUSH); tester.sizeOverflow(); } // ---------------------------------------------------------------------- // Main function // ---------------------------------------------------------------------- int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); STest::Random::seed(); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/GenerateFrames.cpp
//! ====================================================================== //! \title GenerateFrames.cpp //! \brief Implementation file for GenerateFrames rule //! \author mstarch, bocchino //! ====================================================================== #include "GenerateFrames.hpp" #include "Printing.hpp" #include "STest/Pick/Pick.hpp" #include "Utils/Hash/Hash.hpp" namespace Svc { GenerateFrames :: GenerateFrames() : STest::Rule<DeframerTester>("GenerateFrames") { } bool GenerateFrames :: precondition(const Svc::DeframerTester &state) { return state.m_framesToSend.size() == 0; } void GenerateFrames :: action(Svc::DeframerTester &state) { PRINT("----------------------------------------------------------------------"); PRINT("GenerateFrames action"); PRINT("----------------------------------------------------------------------"); // Generate 1-100 frames const U32 numFrames = STest::Pick::lowerUpper(1, 100); PRINT_ARGS("Generating %d frames", numFrames) for (U32 i = 0; i < numFrames; i++) { // Generate a random frame DeframerTester::UplinkFrame frame = DeframerTester::UplinkFrame::random(); // Push it on the sending list state.m_framesToSend.push_back(frame); } PRINT_ARGS("frameToSend.size()=%lu", state.m_framesToSend.size()) } }
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/DeframerTester.hpp
// ====================================================================== // \title DeframerTester.hpp // \brief Header file for Deframer test with F Prime protocol // \author mstarch, bocchino // // \copyright // Copyright 2009-2022, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef SVC_TESTER_HPP #define SVC_TESTER_HPP #include <deque> #include <cstring> #include "DeframerGTestBase.hpp" #include "Fw/Com/ComPacket.hpp" #include "Fw/Types/SerialBuffer.hpp" #include "STest/STest/Pick/Pick.hpp" #include "Svc/Deframer/Deframer.hpp" #include "Svc/FramingProtocol/FprimeProtocol.hpp" #include "Utils/Hash/Hash.hpp" namespace Svc { class DeframerTester : public DeframerGTestBase { // ---------------------------------------------------------------------- // Friend classes // ---------------------------------------------------------------------- friend struct GenerateFrames; friend class SendBuffer; // ---------------------------------------------------------------------- // Types // ---------------------------------------------------------------------- public: //! Enumerated constants enum Constants { //! The maximum valid frame size //! Every valid frame must fit in the ring buffer MAX_VALID_FRAME_SIZE = DeframerCfg::RING_BUFFER_SIZE, //! The max frame size that will fit in the test buffer //! Larger than max valid size, to test bad sizes MAX_FRAME_SIZE = MAX_VALID_FRAME_SIZE + 1, //! The size of the part of the frame that is outside the packet NON_PACKET_SIZE = FpFrameHeader::SIZE + HASH_DIGEST_LENGTH, //! The offset of the start word in an F Prime protocol frame START_WORD_OFFSET = 0, //! The offset of the packet size in an F Prime protocol frame PACKET_SIZE_OFFSET = START_WORD_OFFSET + sizeof FpFrameHeader::START_WORD, //! The offset of the packet type in an F Prime protocol frame PACKET_TYPE_OFFSET = FpFrameHeader::SIZE, }; //! The type of the input mode struct InputMode { typedef enum { //! Push data from another thread PUSH, //! Poll for data on the schedIn thread POLL } t; }; //! An uplink frame for testing class UplinkFrame { // ---------------------------------------------------------------------- // Types // ---------------------------------------------------------------------- //! The type of frame data typedef U8 FrameData[MAX_FRAME_SIZE]; public: // ---------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------- //! Construct an uplink frame UplinkFrame( Fw::ComPacket::ComPacketType packetType, //!< The packet type U32 packetSize //!< The packet size ); public: // ---------------------------------------------------------------------- // Public instance methods // ---------------------------------------------------------------------- //! Copy data from the frame, advancing the copy offset void copyDataOut( Fw::SerialBuffer& serialBuffer, //!< The serial buffer to copy to U32 size //!< The number of bytes to copy ); //! Get a constant reference to the frame data const FrameData& getData() const; //! Get the frame size U32 getSize() const; //! Get the size of data that remains for copying U32 getRemainingCopySize() const; //! Report whether the frame is valid bool isValid() const; public: // ---------------------------------------------------------------------- // Public static methods // ---------------------------------------------------------------------- //! Construct a random frame static UplinkFrame random(); //! Get the max packet size that will fit in the test buffer //! This is an invalid size for the deframer static U32 getInvalidPacketSize(); //! Get the max valid command packet size static U32 getMaxValidCommandPacketSize(); //! Get the max valid file packet size static U32 getMaxValidFilePacketSize(); //! Get the min packet size static U32 getMinPacketSize(); private: // ---------------------------------------------------------------------- // Private instance methods // ---------------------------------------------------------------------- //! Randomly invalidate a valid frame, or leave it alone //! If the frame is already invalid, leave it alone void randomlyInvalidate(); //! Update the frame header void updateHeader(); //! Update the hash value void updateHash(); //! Write an arbitrary packet size void writePacketSize( FpFrameHeader::TokenType ps //!< The packet size ); //! Write an arbitrary packet type void writePacketType( FwPacketDescriptorType pt //!< The packet type ); //! Write an arbitrary start word void writeStartWord( FpFrameHeader::TokenType sw //!< The start word ); public: // ---------------------------------------------------------------------- // Public member variables // ---------------------------------------------------------------------- //! The packet type const Fw::ComPacket::ComPacketType packetType; //! The packet size const U32 packetSize; private: // ---------------------------------------------------------------------- // Private member variables // ---------------------------------------------------------------------- //! The frame data, including header, packet data, and hash. //! The array is big enough to hold a frame larger than the //! max valid frame size for the deframer. U8 data[MAX_FRAME_SIZE]; //! The amount of frame data already copied out into a buffer U32 copyOffset; //! Whether the frame is valid bool valid; }; public: // ---------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------- //! Construct a DeframerTester DeframerTester(InputMode::t inputMode); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Size would cause integer overflow void sizeOverflow(); public: // ---------------------------------------------------------------------- // Public instance methods // ---------------------------------------------------------------------- //! Set up the incoming buffer void setUpIncomingBuffer(); //! Send the incoming buffer void sendIncomingBuffer(); private: // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- //! Handler for from_comOut void from_comOut_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::ComBuffer& data, //!< Buffer containing packet data U32 context //!< Call context value; meaning chosen by user ); //! Handler for from_bufferOut void from_bufferOut_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::Buffer& fwBuffer //!< The buffer ); //! Handler for from_bufferAllocate Fw::Buffer from_bufferAllocate_handler( const NATIVE_INT_TYPE portNum, //!< The port number U32 size //!< The size ); //! Handler for from_bufferDeallocate void from_bufferDeallocate_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::Buffer& fwBuffer //!< The buffer ); //! Handler for from_framedDeallocate //! void from_framedDeallocate_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::Buffer& fwBuffer //!< The buffer ); //! Handler for from_framedPoll Drv::PollStatus from_framedPoll_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::Buffer& pollBuffer //!< The poll buffer ); private: // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- //! Connect ports void connectPorts(); //! Initialize components void initComponents(); //! Allocate a packet buffer Fw::Buffer allocatePacketBuffer( U32 size //!< The buffer size ); private: // ---------------------------------------------------------------------- // Private member variables // ---------------------------------------------------------------------- //! The component under test Deframer component; //! The deframing protocol Svc::FprimeDeframing protocol; //! Frames that the DeframerTester should send to the Deframer std::deque<UplinkFrame> m_framesToSend; //! Frames that the DeframerTester should receive from the Deframer std::deque<UplinkFrame> m_framesToReceive; //! Byte store for the incoming buffer //! In polling mode, the incoming buffer must fit in the poll buffer U8 m_incomingBufferBytes[DeframerCfg::POLL_BUFFER_SIZE]; //! Serialized frame data to send to the Deframer Fw::Buffer m_incomingBuffer; //! The input mode InputMode::t m_inputMode; }; } #endif
hpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/SendBuffer.hpp
//! ====================================================================== //! \title SendBuffer.hpp //! \brief Header file for SendBuffer rule //! \author lestarch, bocchino //! ====================================================================== #ifndef SVC_SEND_BUFFER_HPP #define SVC_SEND_BUFFER_HPP #include <FpConfig.hpp> #include "Fw/Types/StringType.hpp" #include "STest/STest/Pick/Pick.hpp" #include "STest/STest/Rule/Rule.hpp" #include "DeframerTester.hpp" namespace Svc { //! Pack generated frames into a buffer //! Send the buffer class SendBuffer : public STest::Rule<DeframerTester> { public: // ---------------------------------------------------------------------- // Construction // ---------------------------------------------------------------------- //! Constructor SendBuffer(); public: // ---------------------------------------------------------------------- // Public functions // ---------------------------------------------------------------------- //! Precondition bool precondition( const DeframerTester& state //!< The test state ); //! Action void action( Svc::DeframerTester &state //!< The test state ); private: // ---------------------------------------------------------------------- // Private helper functions // ---------------------------------------------------------------------- //! Fill the incoming buffer with frame data void fillIncomingBuffer( Svc::DeframerTester &state //!< The test state ); //! Record a received frame void recordReceivedFrame( Svc::DeframerTester& state, //!< The test state Svc::DeframerTester::UplinkFrame& frame //!< The frame ); private: // ---------------------------------------------------------------------- // Private member variables // ---------------------------------------------------------------------- //! The expected number of com buffers emitted U32 expectedComCount; //! The expected number of file packet buffers emitted U32 expectedBuffCount; }; }; #endif
hpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/SendBuffer.cpp
//! ====================================================================== //! \title SendBuffer.cpp //! \brief Implementation file for SendBuffer rule //! \author mstarch, bocchino //! ====================================================================== #include "Printing.hpp" #include "STest/Pick/Pick.hpp" #include "SendBuffer.hpp" #include "Utils/Hash/Hash.hpp" namespace Svc { SendBuffer :: SendBuffer() : STest::Rule<DeframerTester>("SendBuffer"), expectedComCount(0), expectedBuffCount(0) { } bool SendBuffer :: precondition(const Svc::DeframerTester &state) { return state.m_framesToSend.size() > 0; } void SendBuffer :: action(Svc::DeframerTester &state) { PRINT("----------------------------------------------------------------------"); PRINT("SendBuffer action"); PRINT("----------------------------------------------------------------------"); // Clear the test history state.clearHistory(); // Set up the incoming buffer state.setUpIncomingBuffer(); // Fill the incoming buffer with frame data fillIncomingBuffer(state); // Send the buffer state.sendIncomingBuffer(); // Check the counts state.assert_from_comOut_size(__FILE__, __LINE__, expectedComCount); PRINT_ARGS("expectedComCount=%d", expectedComCount) state.assert_from_bufferOut_size(__FILE__, __LINE__, expectedBuffCount); PRINT_ARGS("expectedBuffCount=%d", expectedBuffCount) } void SendBuffer :: fillIncomingBuffer(Svc::DeframerTester &state) { // Get the size of the incoming buffer const U32 incomingBufferSize = state.m_incomingBuffer.getSize(); // Set up a serial buffer for data transfer Fw::SerialBuffer serialBuffer( state.m_incomingBufferBytes, incomingBufferSize ); // Reset the expected com count expectedComCount = 0; // Reset the expected buff count expectedBuffCount = 0; // The number of bytes copied into the buffer U32 copiedSize = 0; // The size of available data in the buffer U32 buffAvailable = incomingBufferSize; // Fill the incoming buffer as much as possible with available frames for (U32 i = 0; i < incomingBufferSize; ++i) { // Check if there is any room left in the buffer if (buffAvailable == 0) { break; } // Check if there are any frames to send if (state.m_framesToSend.size() == 0) { break; } // Get the frame from the head of the sending queue DeframerTester::UplinkFrame& frame = state.m_framesToSend.front(); // Compute the amount to copy const U32 frameAvailable = frame.getRemainingCopySize(); const U32 copyAmt = std::min(frameAvailable, buffAvailable); // Copy the frame data into the serial buffer frame.copyDataOut(serialBuffer, copyAmt); // Update buffAvailable ASSERT_GE(buffAvailable, copyAmt); buffAvailable -= copyAmt; // Update copiedSize copiedSize += copyAmt; ASSERT_LE(copiedSize, incomingBufferSize); // If we have copied a complete frame F, then (1) remove F from // the send queue; and (2) if F is valid, then record F as // received if (frame.getRemainingCopySize() == 0) { // If F is valid, then record it as received recordReceivedFrame(state, frame); // Remove F from the send queue state.m_framesToSend.pop_front(); PRINT_ARGS( "frameToSend.size()=%lu", state.m_framesToSend.size() ) } } // Update the buffer ASSERT_LE(copiedSize, incomingBufferSize); state.m_incomingBuffer.setSize(copiedSize); } void SendBuffer :: recordReceivedFrame( Svc::DeframerTester& state, Svc::DeframerTester::UplinkFrame& frame ) { if (frame.isValid()) { // Push frame F on the received queue state.m_framesToReceive.push_back(frame); // Update the count of expected frames switch (frame.packetType) { case Fw::ComPacket::FW_PACKET_COMMAND: PRINT("popped valid command frame") // If F contains a command packet, then increment // the expected com count ++expectedComCount; break; case Fw::ComPacket::FW_PACKET_FILE: PRINT("popped valid file frame") // If F contains a file packet, then increment // the expected buffer count ++expectedBuffCount; break; default: // This should not happen for a valid frame FW_ASSERT(0, frame.packetType); break; } } else { PRINT("popped invalid frame") } } };
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/GenerateFrames.hpp
//! ====================================================================== //! \title DeframerRules.hpp //! \brief Header file for GenerateFrames rule //! \author lestarch, bocchino //! ====================================================================== #ifndef SVC_GENERATE_FRAMES_HPP #define SVC_GENERATE_FRAMES_HPP #include <FpConfig.hpp> #include "Fw/Types/StringType.hpp" #include "STest/STest/Pick/Pick.hpp" #include "STest/STest/Rule/Rule.hpp" #include "DeframerTester.hpp" namespace Svc { //! Generate frames to send struct GenerateFrames : public STest::Rule<DeframerTester> { // ---------------------------------------------------------------------- // Construction // ---------------------------------------------------------------------- //! Constructor GenerateFrames(); // ---------------------------------------------------------------------- // Public member functions // ---------------------------------------------------------------------- //! Precondition bool precondition( const DeframerTester& state //!< The test state ); //! Action void action( DeframerTester& state //!< The test state ); }; } #endif
hpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/DeframerTester.cpp
// ====================================================================== // \title DeframerTester.cpp // \brief Implementation file for Deframer test with F Prime protocol // \author mstarch, bocchino // // \copyright // Copyright 2009-2022, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include <cstring> #include <limits> #include "Fw/Types/Assert.hpp" #include "DeframerTester.hpp" #include "Utils/Hash/Hash.hpp" #include "Utils/Hash/HashBuffer.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 10000 namespace Svc { // ---------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------- DeframerTester ::DeframerTester(InputMode::t inputMode) : DeframerGTestBase("Tester", MAX_HISTORY_SIZE), component("Deframer"), m_inputMode(inputMode) { this->initComponents(); this->connectPorts(); component.setup(protocol); memset(m_incomingBufferBytes, 0, sizeof m_incomingBufferBytes); } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void DeframerTester ::sizeOverflow() { U8 data[FpFrameHeader::SIZE]; Fw::Buffer buffer(data, sizeof data); Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr(); Fw::SerializeStatus status = serialRepr.serialize(FpFrameHeader::START_WORD); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); FpFrameHeader::TokenType size = std::numeric_limits<U32>::max(); status = serialRepr.serialize(size); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); this->component.processBuffer(buffer); // Assert no output ASSERT_FROM_PORT_HISTORY_SIZE(0); } // ---------------------------------------------------------------------- // Public instance methods // ---------------------------------------------------------------------- void DeframerTester ::setUpIncomingBuffer() { const U32 bufferSize = STest::Pick::lowerUpper( 1, sizeof m_incomingBufferBytes ); ASSERT_LE(bufferSize, sizeof m_incomingBufferBytes); m_incomingBuffer = Fw::Buffer( m_incomingBufferBytes, bufferSize ); } void DeframerTester ::sendIncomingBuffer() { switch (m_inputMode) { case InputMode::PUSH: // Push buffer to framedIn invoke_to_framedIn( 0, m_incomingBuffer, Drv::RecvStatus::RECV_OK ); break; case InputMode::POLL: // Call schedIn handler, which polls for buffer invoke_to_schedIn(0, 0); break; default: FW_ASSERT(0); break; } } // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- void DeframerTester ::from_comOut_handler( const NATIVE_INT_TYPE portNum, Fw::ComBuffer& data, U32 context ) { // Check that a received frame is expected ASSERT_GT(m_framesToReceive.size(), 0) << "Queue of frames to receive is empty" << std::endl; // Get the frame at the front UplinkFrame frame = m_framesToReceive.front(); m_framesToReceive.pop_front(); // Check the packet type ASSERT_EQ(frame.packetType, Fw::ComPacket::FW_PACKET_COMMAND); // Check the packet data for (U32 i = 0; i < data.getBuffLength(); i++) { EXPECT_EQ( (data.getBuffAddr())[i], (frame.getData())[FpFrameHeader::SIZE + i] ); } // Push the history entry this->pushFromPortEntry_comOut(data, context); } void DeframerTester ::from_bufferOut_handler( const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer ) { // Check that a received frame is expected ASSERT_GT(m_framesToReceive.size(), 0) << "Queue of frames to receive is empty" << std::endl; // Get the frame at the front UplinkFrame frame = m_framesToReceive.front(); m_framesToReceive.pop_front(); // Check the packet type ASSERT_EQ(frame.packetType, Fw::ComPacket::FW_PACKET_FILE); // Check the packet data for (U32 i = 0; i < fwBuffer.getSize(); i++) { // Deframer strips type before sending to FileUplink const U32 frameOffset = FpFrameHeader::SIZE + sizeof(FwPacketDescriptorType) + i; ASSERT_EQ( (fwBuffer.getData())[i], (frame.getData())[frameOffset] ); } // Buffers received on this port are owned by the receiver // So delete the allocation now // Before deallocating, undo the deframer's adjustment of the pointer // by the size of the packet type delete[](fwBuffer.getData() - sizeof(FwPacketDescriptorType)); // Push the history entry this->pushFromPortEntry_bufferOut(fwBuffer); } Fw::Buffer DeframerTester ::from_bufferAllocate_handler( const NATIVE_INT_TYPE portNum, U32 size ) { this->pushFromPortEntry_bufferAllocate(size); U8 *const data = new U8[size]; memset(data, 0, size); Fw::Buffer buffer(data, size); return buffer; } void DeframerTester ::from_bufferDeallocate_handler( const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer ) { delete[] fwBuffer.getData(); this->pushFromPortEntry_bufferDeallocate(fwBuffer); } void DeframerTester ::from_framedDeallocate_handler( const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer ) { this->pushFromPortEntry_framedDeallocate(fwBuffer); } Drv::PollStatus DeframerTester ::from_framedPoll_handler( const NATIVE_INT_TYPE portNum, Fw::Buffer& pollBuffer ) { this->pushFromPortEntry_framedPoll(pollBuffer); U8* incoming = m_incomingBuffer.getData(); const U32 size = m_incomingBuffer.getSize(); U8* outgoing = pollBuffer.getData(); const U32 maxSize = pollBuffer.getSize(); FW_ASSERT(size <= maxSize, size, maxSize); memcpy(outgoing, incoming, size); pollBuffer.setSize(size); return Drv::PollStatus::POLL_OK; } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void DeframerTester ::connectPorts() { // bufferAllocate this->component.set_bufferAllocate_OutputPort( 0, this->get_from_bufferAllocate(0) ); // bufferDeallocate this->component.set_bufferDeallocate_OutputPort( 0, this->get_from_bufferDeallocate(0) ); // bufferOut this->component.set_bufferOut_OutputPort( 0, this->get_from_bufferOut(0) ); // cmdResponseIn this->connect_to_cmdResponseIn( 0, this->component.get_cmdResponseIn_InputPort(0) ); // comOut this->component.set_comOut_OutputPort( 0, this->get_from_comOut(0) ); // framedDeallocate this->component.set_framedDeallocate_OutputPort( 0, this->get_from_framedDeallocate(0) ); // framedIn this->connect_to_framedIn( 0, this->component.get_framedIn_InputPort(0) ); // framedPoll this->component.set_framedPoll_OutputPort( 0, this->get_from_framedPoll(0) ); // schedIn this->connect_to_schedIn( 0, this->component.get_schedIn_InputPort(0) ); } void DeframerTester ::initComponents() { this->init(); this->component.init(INSTANCE); } }
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/UplinkFrame.cpp
// ====================================================================== // \title UplinkFrame.cpp // \author mstarch, bocchino // \brief Implementation file for DeframerTester::UplinkFrame // // \copyright // Copyright 2009-2022, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "DeframerTester.hpp" namespace Svc { // ---------------------------------------------------------------------- // Constructor // ---------------------------------------------------------------------- DeframerTester::UplinkFrame::UplinkFrame( Fw::ComPacket::ComPacketType packetType, U32 packetSize ) : packetType(packetType), packetSize(packetSize), copyOffset(0), valid(false) { // Fill in random data for (U32 i = 0; i < sizeof data; ++i) { data[i] = STest::Pick::lowerUpper(0, 0xFF); } // Update the frame header this->updateHeader(); // Update the hash value this->updateHash(); // Check validity of packet type and size if ( (packetType == Fw::ComPacket::FW_PACKET_COMMAND) && (packetSize <= getMaxValidCommandPacketSize()) ) { valid = true; } if ( (packetType == Fw::ComPacket::FW_PACKET_FILE) && (packetSize <= getMaxValidFilePacketSize()) ) { valid = true; } } // ---------------------------------------------------------------------- // Public instance methods // ---------------------------------------------------------------------- U32 DeframerTester::UplinkFrame::getRemainingCopySize() const { const U32 frameSize = getSize(); FW_ASSERT(frameSize >= copyOffset, frameSize, copyOffset); return frameSize - copyOffset; } U32 DeframerTester::UplinkFrame::getSize() const { return NON_PACKET_SIZE + packetSize; } bool DeframerTester::UplinkFrame::isValid() const { return valid; } const DeframerTester::UplinkFrame::FrameData& DeframerTester::UplinkFrame::getData() const { return data; } void DeframerTester::UplinkFrame::copyDataOut( Fw::SerialBuffer& serialBuffer, U32 size ) { ASSERT_LE(copyOffset + size, getSize()); const Fw::SerializeStatus status = serialBuffer.pushBytes( &data[copyOffset], size ); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); copyOffset += size; } // ---------------------------------------------------------------------- // Public static methods // ---------------------------------------------------------------------- DeframerTester::UplinkFrame DeframerTester::UplinkFrame::random() { // Randomly set the packet type Fw::ComPacket::ComPacketType packetType = Fw::ComPacket::FW_PACKET_UNKNOWN; const U32 packetSelector = STest::Pick::lowerUpper(0,1); U32 maxValidPacketSize = 0; switch (packetSelector) { case 0: packetType = Fw::ComPacket::FW_PACKET_COMMAND; maxValidPacketSize = getMaxValidCommandPacketSize(); break; case 1: packetType = Fw::ComPacket::FW_PACKET_FILE; maxValidPacketSize = getMaxValidFilePacketSize(); break; default: FW_ASSERT(0); break; } // Randomly set the packet size U32 packetSize = 0; // Invalidate 1 in 100 packet sizes const U32 invalidSizeIndex = STest::Pick::startLength(0, 100); if (invalidSizeIndex == 0) { // This packet size fits in the test buffer, // but is invalid for the deframer packetSize = getInvalidPacketSize(); } else { // Choose a valid packet size // This packet size fits in the test buffer and is // valid for the deframer packetSize = STest::Pick::lowerUpper( getMinPacketSize(), maxValidPacketSize ); } // Construct the frame UplinkFrame frame = UplinkFrame(packetType, packetSize); // Randomly invalidate the frame, or leave it alone frame.randomlyInvalidate(); // Return the frame return frame; } U32 DeframerTester::UplinkFrame::getInvalidPacketSize() { FW_ASSERT( MAX_FRAME_SIZE >= NON_PACKET_SIZE, MAX_FRAME_SIZE, NON_PACKET_SIZE ); const U32 result = MAX_FRAME_SIZE - NON_PACKET_SIZE; // Make sure the size is invalid FW_ASSERT( result > getMaxValidCommandPacketSize(), result, getMaxValidCommandPacketSize() ); FW_ASSERT( result > getMaxValidFilePacketSize(), result, getMaxValidFilePacketSize() ); return result; } U32 DeframerTester::UplinkFrame::getMaxValidCommandPacketSize() { return std::min( // Packet must fit into a com buffer static_cast<U32>(FW_COM_BUFFER_MAX_SIZE), // Frame must fit into the ring buffer getMaxValidFilePacketSize() ); } U32 DeframerTester::UplinkFrame::getMaxValidFilePacketSize() { FW_ASSERT( MAX_VALID_FRAME_SIZE >= NON_PACKET_SIZE, MAX_VALID_FRAME_SIZE, NON_PACKET_SIZE ); return MAX_VALID_FRAME_SIZE - NON_PACKET_SIZE; } U32 DeframerTester::UplinkFrame::getMinPacketSize() { // Packet must hold the packet type return sizeof(FwPacketDescriptorType); } // ---------------------------------------------------------------------- // Private instance methods // ---------------------------------------------------------------------- void DeframerTester::UplinkFrame::randomlyInvalidate() { if (valid) { // Invalidation cases occur out of 100 samples const U32 invalidateIndex = STest::Pick::startLength(0, 100); switch (invalidateIndex) { case 0: { // Invalidate the start word const FpFrameHeader::TokenType badStartWord = FpFrameHeader::START_WORD + 1; writeStartWord(badStartWord); valid = false; break; } case 1: // Invalidate the packet type writePacketType(Fw::ComPacket::FW_PACKET_UNKNOWN); valid = false; break; case 2: // Invalidate the hash value ++data[getSize() - 1]; valid = false; break; default: // Stay valid break; } } } void DeframerTester::UplinkFrame::updateHash() { Utils::Hash hash; Utils::HashBuffer hashBuffer; const U32 dataSize = FpFrameHeader::SIZE + packetSize; hash.update(data, dataSize); hash.final(hashBuffer); const U8 *const hashAddr = hashBuffer.getBuffAddr(); memcpy(&data[dataSize], hashAddr, HASH_DIGEST_LENGTH); } void DeframerTester::UplinkFrame::updateHeader() { // Write the correct start word writeStartWord(FpFrameHeader::START_WORD); // Write the correct packet size writePacketSize(packetSize); // Write the correct packet type writePacketType(packetType); } void DeframerTester::UplinkFrame::writePacketSize( FpFrameHeader::TokenType ps ) { Fw::SerialBuffer sb(&data[PACKET_SIZE_OFFSET], sizeof ps); const Fw::SerializeStatus status = sb.serialize(packetSize); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); } void DeframerTester::UplinkFrame::writePacketType( FwPacketDescriptorType pt ) { Fw::SerialBuffer sb(&data[PACKET_TYPE_OFFSET], sizeof pt); const Fw::SerializeStatus status = sb.serialize(pt); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); } void DeframerTester::UplinkFrame::writeStartWord( FpFrameHeader::TokenType sw ) { Fw::SerialBuffer sb(data, sizeof sw); const Fw::SerializeStatus status = sb.serialize(sw); ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); } }
cpp
fprime
data/projects/fprime/Svc/Deframer/test/ut-fprime-protocol/Printing.hpp
//! ====================================================================== //! \title Printing.hpp //! \brief Print macros for deframer unit tests //! \author bocchino //! ====================================================================== // Uncomment the following line to turn on printing //#define PRINTING #ifdef PRINTING #include <cstdio> #define PRINT(S) printf("[Deframer Tests] " S "\n"); #define PRINT_ARGS(S, ...) printf("[Deframer Tests] " S "\n", __VA_ARGS__); #else #define PRINT(S) #define PRINT_ARGS(S, ...) #endif
hpp
fprime
data/projects/fprime/Svc/FatalHandler/FatalHandlerComponentImpl.hpp
// ====================================================================== // \title FatalHandlerImpl.hpp // \author tcanham // \brief hpp file for FatalHandler component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef FatalHandler_HPP #define FatalHandler_HPP #include "Svc/FatalHandler/FatalHandlerComponentAc.hpp" namespace Svc { class FatalHandlerComponentImpl : public FatalHandlerComponentBase { public: // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct object FatalHandler //! FatalHandlerComponentImpl( const char *const compName /*!< The component name*/ ); //! Initialize object FatalHandler //! void init( const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/ ); //! Destroy object FatalHandler //! ~FatalHandlerComponentImpl(); PRIVATE: // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- //! Handler implementation for FatalReceive //! void FatalReceive_handler( const NATIVE_INT_TYPE portNum, /*!< The port number*/ FwEventIdType Id /*!< The ID of the FATAL event*/ ); }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/FatalHandler/FatalHandler.hpp
// ====================================================================== // FatalHandler.hpp // Standardization header for FatalHandler // ====================================================================== #ifndef Svc_FatalHandler_HPP #define Svc_FatalHandler_HPP #include "Svc/FatalHandler/FatalHandlerComponentImpl.hpp" namespace Svc { typedef FatalHandlerComponentImpl FatalHandler; } #endif
hpp
fprime
data/projects/fprime/Svc/FatalHandler/FatalHandlerComponentVxWorksImpl.cpp
// ====================================================================== // \title FatalHandlerImpl.cpp // \author tcanham // \brief cpp file for FatalHandler component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/FatalHandler/FatalHandlerComponentImpl.hpp> #include <FpConfig.hpp> #include <taskLib.h> #include <Fw/Logger/Logger.hpp> namespace Svc { void FatalHandlerComponentImpl::FatalReceive_handler( const NATIVE_INT_TYPE portNum, FwEventIdType Id) { Fw::Logger::logMsg("FATAL %d handled.\n",Id,0,0,0,0,0); taskSuspend(0); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/FatalHandler/FatalHandlerComponentLinuxImpl.cpp
// ====================================================================== // \title FatalHandlerImpl.cpp // \author tcanham // \brief cpp file for FatalHandler component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <cstdlib> #include <csignal> #include <Fw/Logger/Logger.hpp> #include <Svc/FatalHandler/FatalHandlerComponentImpl.hpp> #include <Os/Task.hpp> #include <FpConfig.hpp> namespace Svc { // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- void FatalHandlerComponentImpl::FatalReceive_handler( const NATIVE_INT_TYPE portNum, FwEventIdType Id) { // for **nix, delay then exit with error code Fw::Logger::logMsg("FATAL %d handled.\n",Id,0,0,0,0,0); (void)Os::Task::delay(1000); Fw::Logger::logMsg("Exiting with abort signal and core dump file.\n",0,0,0,0,0,0); (void)raise( SIGABRT ); exit(1); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/FatalHandler/FatalHandlerComponentBaremetalImpl.cpp
// ====================================================================== // \title FatalHandlerImpl.cpp // \author lestarch // \brief cpp file for FatalHandler component implementation class // ====================================================================== #include <cstdlib> #include <Os/Log.hpp> #include <Svc/FatalHandler/FatalHandlerComponentImpl.hpp> #include <FpConfig.hpp> namespace Svc { // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- void FatalHandlerComponentImpl::FatalReceive_handler( const NATIVE_INT_TYPE portNum, FwEventIdType Id) { // for **nix, delay then exit with error code Os::Log::logMsg("FATAL %d handled.\n",Id,0,0,0,0,0); while (true) {} // Returning might be bad } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/FatalHandler/FatalHandlerComponentCommonImpl.cpp
// ====================================================================== // \title FatalHandlerImpl.cpp // \author tcanham // \brief cpp file for FatalHandler component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/FatalHandler/FatalHandlerComponentImpl.hpp> #include <FpConfig.hpp> namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- FatalHandlerComponentImpl :: FatalHandlerComponentImpl( const char *const compName ) : FatalHandlerComponentBase(compName) { } void FatalHandlerComponentImpl :: init( const NATIVE_INT_TYPE instance ) { FatalHandlerComponentBase::init(instance); } FatalHandlerComponentImpl :: ~FatalHandlerComponentImpl() { } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/ComLogger/ComLogger.cpp
// ---------------------------------------------------------------------- // // ComLogger.cpp // // ---------------------------------------------------------------------- #include <Svc/ComLogger/ComLogger.hpp> #include <FpConfig.hpp> #include <Fw/Types/SerialBuffer.hpp> #include <Fw/Types/StringUtils.hpp> #include <Os/ValidateFile.hpp> #include <cstdio> namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- ComLogger :: ComLogger(const char* compName, const char* incomingFilePrefix, U32 maxFileSize, bool storeBufferLength) : ComLoggerComponentBase(compName), m_maxFileSize(maxFileSize), m_fileMode(CLOSED), m_byteCount(0), m_writeErrorOccurred(false), m_openErrorOccurred(false), m_storeBufferLength(storeBufferLength), m_initialized(true) { this->init_log_file(incomingFilePrefix, maxFileSize, storeBufferLength); } ComLogger :: ComLogger(const char* compName) : ComLoggerComponentBase(compName), m_filePrefix(), m_maxFileSize(0), m_fileMode(CLOSED), m_fileName(), m_hashFileName(), m_byteCount(0), m_writeErrorOccurred(false), m_openErrorOccurred(false), m_storeBufferLength(), m_initialized(false) { } void ComLogger :: init( NATIVE_INT_TYPE queueDepth, //!< The queue depth NATIVE_INT_TYPE instance //!< The instance number ) { ComLoggerComponentBase::init(queueDepth, instance); } void ComLogger :: init_log_file(const char* incomingFilePrefix, U32 maxFileSize, bool storeBufferLength) { FW_ASSERT(incomingFilePrefix != nullptr); this->m_maxFileSize = maxFileSize; this->m_storeBufferLength = storeBufferLength; if( this->m_storeBufferLength ) { FW_ASSERT(maxFileSize > sizeof(U16), maxFileSize); } FW_ASSERT(Fw::StringUtils::string_length(incomingFilePrefix, sizeof(this->m_filePrefix)) < sizeof(this->m_filePrefix), Fw::StringUtils::string_length(incomingFilePrefix, sizeof(this->m_filePrefix)), sizeof(this->m_filePrefix)); // ensure that file prefix is not too big (void)Fw::StringUtils::string_copy(this->m_filePrefix, incomingFilePrefix, sizeof(this->m_filePrefix)); this->m_initialized = true; } ComLogger :: ~ComLogger() { // Close file: // this->closeFile(); // NOTE: the above did not work because we don't want to issue an event // in the destructor. This can cause "virtual method called" segmentation // faults. // So I am copying part of that function here. if( OPEN == this->m_fileMode ) { // Close file: this->m_file.close(); // Write out the hash file to disk: this->writeHashFile(); // Update mode: this->m_fileMode = CLOSED; // Send event: //Fw::LogStringArg logStringArg((char*) fileName); //this->log_DIAGNOSTIC_FileClosed(logStringArg); } } // ---------------------------------------------------------------------- // Handler implementations // ---------------------------------------------------------------------- void ComLogger :: comIn_handler( NATIVE_INT_TYPE portNum, Fw::ComBuffer &data, U32 context ) { FW_ASSERT(portNum == 0); // Get length of buffer: U32 size32 = data.getBuffLength(); // ComLogger only writes 16-bit sizes to save space // on disk: FW_ASSERT(size32 < 65536, size32); U16 size = size32 & 0xFFFF; // Close the file if it will be too big: if( OPEN == this->m_fileMode ) { U32 projectedByteCount = this->m_byteCount + size; if( this->m_storeBufferLength ) { projectedByteCount += sizeof(size); } if( projectedByteCount > this->m_maxFileSize ) { this->closeFile(); } } // Open the file if it there is not one open: if( CLOSED == this->m_fileMode ){ this->openFile(); } // Write to the file if it is open: if( OPEN == this->m_fileMode ) { this->writeComBufferToFile(data, size); } } void ComLogger :: CloseFile_cmdHandler( FwOpcodeType opCode, U32 cmdSeq ) { this->closeFile(); this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); } void ComLogger :: pingIn_handler( const NATIVE_INT_TYPE portNum, U32 key ) { // return key this->pingOut_out(0,key); } void ComLogger :: openFile( ) { FW_ASSERT( CLOSED == this->m_fileMode ); if( !this->m_initialized ){ this->log_WARNING_LO_FileNotInitialized(); return; } U32 bytesCopied; // Create filename: Fw::Time timestamp = getTime(); memset(this->m_fileName, 0, sizeof(this->m_fileName)); bytesCopied = snprintf(this->m_fileName, sizeof(this->m_fileName), "%s_%" PRI_FwTimeBaseStoreType "_%" PRIu32 "_%06" PRIu32 ".com", this->m_filePrefix, static_cast<FwTimeBaseStoreType>(timestamp.getTimeBase()), timestamp.getSeconds(), timestamp.getUSeconds()); // "A return value of size or more means that the output was truncated" // See here: http://linux.die.net/man/3/snprintf FW_ASSERT( bytesCopied < sizeof(this->m_fileName) ); // Create sha filename: bytesCopied = snprintf(this->m_hashFileName, sizeof(this->m_hashFileName), "%s_%" PRI_FwTimeBaseStoreType "_%" PRIu32 "_%06" PRIu32 ".com%s", this->m_filePrefix, static_cast<FwTimeBaseStoreType>(timestamp.getTimeBase()), timestamp.getSeconds(), timestamp.getUSeconds(), Utils::Hash::getFileExtensionString()); FW_ASSERT( bytesCopied < sizeof(this->m_hashFileName) ); Os::File::Status ret = m_file.open(this->m_fileName, Os::File::OPEN_WRITE); if( Os::File::OP_OK != ret ) { if( !this->m_openErrorOccurred ) { // throttle this event, otherwise a positive // feedback event loop can occur! Fw::LogStringArg logStringArg(this->m_fileName); this->log_WARNING_HI_FileOpenError(ret, logStringArg); } this->m_openErrorOccurred = true; } else { // Reset event throttle: this->m_openErrorOccurred = false; // Reset byte count: this->m_byteCount = 0; // Set mode: this->m_fileMode = OPEN; } } void ComLogger :: closeFile( ) { if( OPEN == this->m_fileMode ) { // Close file: this->m_file.close(); // Write out the hash file to disk: this->writeHashFile(); // Update mode: this->m_fileMode = CLOSED; // Send event: Fw::LogStringArg logStringArg(this->m_fileName); this->log_DIAGNOSTIC_FileClosed(logStringArg); } } void ComLogger :: writeComBufferToFile( Fw::ComBuffer &data, U16 size ) { if( this->m_storeBufferLength ) { U8 buffer[sizeof(size)]; Fw::SerialBuffer serialLength(&buffer[0], sizeof(size)); serialLength.serialize(size); if(this->writeToFile(serialLength.getBuffAddr(), static_cast<U16>(serialLength.getBuffLength()))) { this->m_byteCount += serialLength.getBuffLength(); } else { return; } } // Write buffer to file: if(this->writeToFile(data.getBuffAddr(), size)) { this->m_byteCount += size; } } bool ComLogger :: writeToFile( void* data, U16 length ) { FwSignedSizeType size = length; Os::File::Status ret = m_file.write(reinterpret_cast<const U8*>(data), size); if( Os::File::OP_OK != ret || size != static_cast<NATIVE_INT_TYPE>(length) ) { if( !this->m_writeErrorOccurred ) { // throttle this event, otherwise a positive // feedback event loop can occur! Fw::LogStringArg logStringArg(this->m_fileName); this->log_WARNING_HI_FileWriteError(ret, size, length, logStringArg); } this->m_writeErrorOccurred = true; return false; } this->m_writeErrorOccurred = false; return true; } void ComLogger :: writeHashFile( ) { Os::ValidateFile::Status validateStatus; validateStatus = Os::ValidateFile::createValidation(this->m_fileName, this->m_hashFileName); if( Os::ValidateFile::VALIDATION_OK != validateStatus ) { Fw::LogStringArg logStringArg1(this->m_fileName); Fw::LogStringArg logStringArg2(this->m_hashFileName); this->log_WARNING_LO_FileValidationError(logStringArg1, logStringArg2, validateStatus); } } }
cpp
fprime
data/projects/fprime/Svc/ComLogger/ComLogger.hpp
// ---------------------------------------------------------------------- // // ComLogger.hpp // // ---------------------------------------------------------------------- #ifndef Svc_ComLogger_HPP #define Svc_ComLogger_HPP #include "Svc/ComLogger/ComLoggerComponentAc.hpp" #include <Os/File.hpp> #include <Os/Mutex.hpp> #include <Fw/Types/Assert.hpp> #include <Utils/Hash/Hash.hpp> #include <limits.h> #include <cstdio> #include <cstdarg> // some limits.h don't have PATH_MAX #ifdef PATH_MAX #define COMLOGGER_PATH_MAX PATH_MAX #else #define COMLOGGER_PATH_MAX 255 #endif // some limits.h don't have NAME_MAX #ifdef NAME_MAX #define COMLOGGER_NAME_MAX NAME_MAX #else #define COMLOGGER_NAME_MAX 255 #endif namespace Svc { class ComLogger : public ComLoggerComponentBase { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- public: // CONSTRUCTOR: // filePrefix: string to prepend the file name with, ie. "thermal_telemetry" // maxFileSize: the maximum size a file should reach before being closed and a new one opened // storeBufferLength: if true, store the length of each com buffer before storing the buffer itself, // otherwise just store the com buffer. false might be advantageous in a system // where you can ensure that all buffers given to the ComLogger are the same size // in which case you do not need the overhead. Or you store an id which you can // match to an expected size on the ground during post processing. ComLogger(const char* compName, const char* filePrefix, U32 maxFileSize, bool storeBufferLength=true); // CONSTRUCTOR: ComLogger(const char* compName); void init( NATIVE_INT_TYPE queueDepth, //!< The queue depth NATIVE_INT_TYPE instance //!< The instance number ); // filePrefix: string to prepend the file name with, ie. "thermal_telemetry" // maxFileSize: the maximum size a file should reach before being closed and a new one opened // storeBufferLength: if true, store the length of each com buffer before storing the buffer itself, // otherwise just store the com buffer. false might be advantageous in a system // where you can ensure that all buffers given to the ComLogger are the same size // in which case you do not need the overhead. Or you store an id which you can // match to an expected size on the ground during post processing. void init_log_file(const char* filePrefix, U32 maxFileSize, bool storeBufferLength=true); ~ComLogger(); // ---------------------------------------------------------------------- // Handler implementations // ---------------------------------------------------------------------- PRIVATE: void comIn_handler( NATIVE_INT_TYPE portNum, Fw::ComBuffer &data, U32 context ); void CloseFile_cmdHandler( FwOpcodeType opCode, U32 cmdSeq ); //! Handler implementation for pingIn //! void pingIn_handler( const NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 key /*!< Value to return to pinger*/ ); // ---------------------------------------------------------------------- // Constants: // ---------------------------------------------------------------------- // The maximum size of a filename enum { MAX_FILENAME_SIZE = COMLOGGER_NAME_MAX, MAX_PATH_SIZE = COMLOGGER_PATH_MAX }; // The filename data: CHAR m_filePrefix[MAX_FILENAME_SIZE + MAX_PATH_SIZE]; U32 m_maxFileSize; // ---------------------------------------------------------------------- // Internal state: // ---------------------------------------------------------------------- enum FileMode { CLOSED = 0, OPEN = 1 }; FileMode m_fileMode; Os::File m_file; CHAR m_fileName[MAX_FILENAME_SIZE + MAX_PATH_SIZE]; CHAR m_hashFileName[MAX_FILENAME_SIZE + MAX_PATH_SIZE]; U32 m_byteCount; bool m_writeErrorOccurred; bool m_openErrorOccurred; bool m_storeBufferLength; bool m_initialized; // ---------------------------------------------------------------------- // File functions: // ---------------------------------------------------------------------- void openFile( ); void closeFile( ); void writeComBufferToFile( Fw::ComBuffer &data, U16 size ); // ---------------------------------------------------------------------- // Helper functions: // ---------------------------------------------------------------------- bool writeToFile( void* data, U16 length ); void writeHashFile( ); }; } #endif
hpp
fprime
data/projects/fprime/Svc/ComLogger/test/ut/ComLoggerMain.cpp
// ---------------------------------------------------------------------- // Main.cpp // ---------------------------------------------------------------------- #include <iostream> #include "ComLoggerTester.hpp" TEST(Test, testLogging) { Svc::ComLoggerTester tester("Tester"); tester.testLogging(); } TEST(Test, testLoggingNoLength) { Svc::ComLoggerTester tester("Tester"); tester.testLoggingNoLength(); } TEST(Test, openError) { Svc::ComLoggerTester tester("Tester"); tester.openError(); } TEST(Test, writeError) { Svc::ComLoggerTester tester("Tester"); tester.writeError(); } TEST(Test, closeFileCommand) { Svc::ComLoggerTester tester("Tester"); tester.closeFileCommand(); } TEST(Test, testLoggingWithInit) { Svc::ComLoggerTester tester("Tester", true); tester.testLoggingWithInit(); } TEST(Test, noInitError) { Svc::ComLoggerTester tester("Tester", true); tester.noInitError(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/ComLogger/test/ut/ComLoggerTester.hpp
// ---------------------------------------------------------------------- // ComLoggerTester.hpp // ---------------------------------------------------------------------- #ifndef TESTER_HPP #define TESTER_HPP #include "ComLoggerGTestBase.hpp" #include "../../ComLogger.hpp" #include <Fw/Comp/ActiveComponentBase.hpp> #include <cstdio> #define QUEUE_DEPTH 10 #define FILE_STR "test" #define MAX_ENTRIES_PER_FILE 5 #define COM_BUFFER_LENGTH 4u #define MAX_BYTES_PER_FILE (MAX_ENTRIES_PER_FILE*COM_BUFFER_LENGTH + MAX_ENTRIES_PER_FILE*sizeof(U16)) #define MAX_BYTES_PER_FILE_NO_LENGTH (MAX_ENTRIES_PER_FILE*COM_BUFFER_LENGTH) namespace Svc { class ComLoggerTester : public ComLoggerGTestBase { public: ComLoggerTester(const char *const compName); // This constructor will construct comLogger with its // standard constructor ComLoggerTester(const char *const compName, bool standardCLInit); ~ComLoggerTester(); void testLogging(); void testLoggingNoLength(); void openError(); void writeError(); void closeFileCommand(); void testLoggingWithInit(); void noInitError(); private: void connectPorts(); void initComponents(); void dispatchOne(); void dispatchAll(); //! Handler for from_pingOut //! void from_pingOut_handler( const NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 key /*!< Value to return to pinger*/ ); ComLogger comLogger; }; }; #endif
hpp
fprime
data/projects/fprime/Svc/ComLogger/test/ut/ComLoggerTester.cpp
// ---------------------------------------------------------------------- // CommandSequencer/test/ut/Tester.cpp // ---------------------------------------------------------------------- #include <cstdio> #include "ComLoggerTester.hpp" #include "Fw/Cmd/CmdPacket.hpp" #include <Os/ValidateFile.hpp> #include <Os/FileSystem.hpp> #include <Fw/Types/SerialBuffer.hpp> #define ID_BASE 256 namespace Svc { ComLoggerTester :: ComLoggerTester( const char *const compName ) : ComLoggerGTestBase(compName, 30), comLogger("ComLogger", FILE_STR, MAX_BYTES_PER_FILE) { this->connectPorts(); this->initComponents(); } ComLoggerTester :: ComLoggerTester( const char *const compName, bool standardCLInit ) : ComLoggerGTestBase(compName, 30), comLogger("ComLogger") { this->connectPorts(); this->initComponents(); (void)standardCLInit; } ComLoggerTester :: ~ComLoggerTester() { } void ComLoggerTester :: connectPorts() { comLogger.set_cmdRegOut_OutputPort(0, this->get_from_cmdRegOut(0)); comLogger.set_cmdResponseOut_OutputPort(0, this->get_from_cmdResponseOut(0)); this->connect_to_cmdIn(0, comLogger.get_cmdIn_InputPort(0)); this->connect_to_comIn(0, comLogger.get_comIn_InputPort(0)); comLogger.set_timeCaller_OutputPort(0, this->get_from_timeCaller(0)); comLogger.set_logOut_OutputPort(0, this->get_from_logOut(0)); } void ComLoggerTester :: initComponents() { this->init(); this->comLogger.init(QUEUE_DEPTH, 0); } void ComLoggerTester :: dispatchOne() { this->comLogger.doDispatch(); } void ComLoggerTester :: dispatchAll() { while(this->comLogger.m_queue.getNumMsgs() > 0) this->dispatchOne(); } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void ComLoggerTester :: testLogging() { CHAR fileName[2048]; CHAR prevFileName[2048]; CHAR hashFileName[2048]; CHAR prevHashFileName[2048]; U8 buf[1024]; FwSignedSizeType length; U16 bufferSize = 0; Os::File::Status ret; Os::File file; ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_SIZE(0); U8 data[COM_BUFFER_LENGTH] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(&data[0], sizeof(data)); Fw::SerializeStatus stat; for(int j = 0; j < 3; j++) { // Test times for the different iterations: Fw::Time testTime(TB_NONE, j, 9876543); Fw::Time testTimePrev(TB_NONE, j-1, 9876543); Fw::Time testTimeNext(TB_NONE, j+1, 9876543); // File names for the different iterations: memset(fileName, 0, sizeof(fileName)); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds()); memset(hashFileName, 0, sizeof(hashFileName)); snprintf(hashFileName, sizeof(hashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds(), Utils::Hash::getFileExtensionString()); memset(prevFileName, 0, sizeof(prevFileName)); snprintf(prevFileName, sizeof(prevFileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTimePrev.getSeconds(), testTimePrev.getUSeconds()); memset(prevHashFileName, 0, sizeof(prevHashFileName)); snprintf(prevHashFileName, sizeof(prevHashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTimePrev.getSeconds(), testTimePrev.getUSeconds(), Utils::Hash::getFileExtensionString()); // Set the test time to the current time: setTestTime(testTime); // Write to file: for(int i = 0; i < MAX_ENTRIES_PER_FILE-1; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // OK a new file should be opened after this final invoke, set a new test time so that a file // with a new name gets opened: setTestTime(testTimeNext); invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); // A new file should have been opened from the previous loop iteration: if( j > 0 ) { ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); ASSERT_TRUE(strcmp(static_cast<char*>(comLogger.m_fileName), fileName) == 0 ); } // Make sure we got a closed file event: ASSERT_EVENTS_SIZE(j); ASSERT_EVENTS_FileClosed_SIZE(j); if( j > 0 ) { ASSERT_EVENTS_FileClosed(j-1, prevFileName); } // Make sure the file size is smaller or equal to the limit: Os::FileSystem::Status fsStat; FwSignedSizeType fileSize = 0; fsStat = Os::FileSystem::getFileSize(fileName, fileSize); //!< gets the size of the file (in bytes) at location path ASSERT_EQ(fsStat, Os::FileSystem::OP_OK); ASSERT_LE(fileSize, MAX_BYTES_PER_FILE); // Open file: ret = file.open(fileName, Os::File::OPEN_READ); ASSERT_EQ(Os::File::OP_OK,ret); // Check data: for(int i = 0; i < 5; i++) { // Get length of buffer to read FwSignedSizeType length = sizeof(U16); ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK, ret); ASSERT_EQ(length, static_cast<NATIVE_INT_TYPE>(sizeof(U16))); Fw::SerialBuffer comBuffLength(buf, length); comBuffLength.fill(); stat = comBuffLength.deserialize(bufferSize); ASSERT_EQ(stat, Fw::FW_SERIALIZE_OK); ASSERT_EQ(COM_BUFFER_LENGTH, bufferSize); // Read and check buffer: length = bufferSize; ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK,ret); ASSERT_EQ(length, static_cast<NATIVE_INT_TYPE>(bufferSize)); ASSERT_EQ(memcmp(buf, data, COM_BUFFER_LENGTH), 0); //for(int k=0; k < 4; k++) // printf("0x%02x ",buf[k]); //printf("\n"); } // Make sure we reached the end of the file: length = sizeof(NATIVE_INT_TYPE); ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK,ret); ASSERT_EQ(length, 0); file.close(); // Assert that the hashes match: if( j > 0 ) { Os::ValidateFile::Status status; status = Os::ValidateFile::validate(prevFileName, prevHashFileName); ASSERT_EQ(Os::ValidateFile::VALIDATION_OK, status); } } } void ComLoggerTester :: testLoggingNoLength() { CHAR fileName[2048]; CHAR prevFileName[2048]; CHAR hashFileName[2048]; CHAR prevHashFileName[2048]; U8 buf[1024]; FwSignedSizeType length; Os::File::Status ret; Os::File file; ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_SIZE(0); U8 data[COM_BUFFER_LENGTH] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(&data[0], sizeof(data)); // Make sure that noLengthMode is enabled: comLogger.m_storeBufferLength = false; comLogger.m_maxFileSize = MAX_BYTES_PER_FILE_NO_LENGTH; for(int j = 0; j < 3; j++) { // Test times for the different iterations: Fw::Time testTime(TB_NONE, j, 123456); Fw::Time testTimePrev(TB_NONE, j-1, 123456); Fw::Time testTimeNext(TB_NONE, j+1, 123456); // File names for the different iterations: memset(fileName, 0, sizeof(fileName)); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds()); memset(hashFileName, 0, sizeof(hashFileName)); snprintf(hashFileName, sizeof(hashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds(), Utils::Hash::getFileExtensionString()); memset(prevFileName, 0, sizeof(prevFileName)); snprintf(prevFileName, sizeof(prevFileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTimePrev.getSeconds(), testTimePrev.getUSeconds()); memset(prevHashFileName, 0, sizeof(prevHashFileName)); snprintf(prevHashFileName, sizeof(prevHashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTimePrev.getSeconds(), testTimePrev.getUSeconds(), Utils::Hash::getFileExtensionString()); // Set the test time to the current time: setTestTime(testTime); // Write to file: for(int i = 0; i < MAX_ENTRIES_PER_FILE-1; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // OK a new file should be opened after this final invoke, set a new test time so that a file // with a new name gets opened: setTestTime(testTimeNext); invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); // A new file should have been opened from the previous loop iteration: if( j > 0 ) { ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); ASSERT_TRUE(strcmp(static_cast<char*>(comLogger.m_fileName), fileName) == 0 ); } // Make sure we got a closed file event: ASSERT_EVENTS_SIZE(j); ASSERT_EVENTS_FileClosed_SIZE(j); if( j > 0 ) { ASSERT_EVENTS_FileClosed(j-1, prevFileName); } // Make sure the file size is smaller or equal to the limit: Os::FileSystem::Status fsStat; FwSignedSizeType fileSize = 0; fsStat = Os::FileSystem::getFileSize(fileName, fileSize); //!< gets the size of the file (in bytes) at location path ASSERT_EQ(fsStat, Os::FileSystem::OP_OK); ASSERT_LE(fileSize, MAX_BYTES_PER_FILE); // Open file: ret = file.open(fileName, Os::File::OPEN_READ); ASSERT_EQ(Os::File::OP_OK,ret); // Check data: for(int i = 0; i < 5; i++) { // Get length of buffer to read FwSignedSizeType length = COM_BUFFER_LENGTH; ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK,ret); ASSERT_EQ(length, COM_BUFFER_LENGTH); ASSERT_EQ(memcmp(buf, data, COM_BUFFER_LENGTH), 0); //for(int k=0; k < 4; k++) // printf("0x%02x ",buf[k]); //printf("\n"); } // Make sure we reached the end of the file: length = sizeof(NATIVE_INT_TYPE); ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK,ret); ASSERT_EQ(length, 0); file.close(); // Assert that the hashes match: if( j > 0 ) { Os::ValidateFile::Status status; status = Os::ValidateFile::validate(prevFileName, prevHashFileName); ASSERT_EQ(Os::ValidateFile::VALIDATION_OK, status); } } } void ComLoggerTester :: openError() { // Construct illegal filePrefix, and set it via the friend: CHAR filePrefix[2048]; CHAR fileName[2128]; memset(fileName, 0, sizeof(fileName)); memset(filePrefix, 0, sizeof(filePrefix)); snprintf(filePrefix, sizeof(filePrefix), "illegal/fname?;\\*"); strncpy(static_cast<char*>(comLogger.m_filePrefix), filePrefix, sizeof(comLogger.m_filePrefix)); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_SIZE(0); const U8 data[COM_BUFFER_LENGTH] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(data, sizeof(data)); Fw::Time testTime(TB_NONE, 4, 9876543); setTestTime(testTime); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", filePrefix, static_cast<U32>(testTime.getTimeBase()), testTime.getSeconds(), testTime.getUSeconds()); for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); } // Check generated events: // We only expect 1 because of the throttle ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_FileOpenError_SIZE(1); ASSERT_EVENTS_FileOpenError( 0, Os::File::DOESNT_EXIST, fileName ); // Try again with valid file name: memset(fileName, 0, sizeof(fileName)); memset(filePrefix, 0, sizeof(filePrefix)); snprintf(filePrefix, sizeof(filePrefix), "good_"); strncpy(comLogger.m_filePrefix, filePrefix, sizeof(comLogger.m_filePrefix)); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", filePrefix, static_cast<U32>(testTime.getTimeBase()), testTime.getSeconds(), testTime.getUSeconds()); for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // Check generated events: // We only expect 1 because of the throttle ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_FileOpenError_SIZE(1); comLogger.closeFile(); // Try again with invalid file name: memset(fileName, 0, sizeof(fileName)); memset(filePrefix, 0, sizeof(filePrefix)); snprintf(filePrefix, sizeof(filePrefix), "illegal/fname?;\\*"); strncpy(static_cast<char*>(comLogger.m_filePrefix), filePrefix, sizeof(comLogger.m_filePrefix)); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", filePrefix, static_cast<U32>(testTime.getTimeBase()), testTime.getSeconds(), testTime.getUSeconds()); for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); } // Check generated events: // We only expect 1 extra because of the throttle ASSERT_EVENTS_SIZE(3); // extra event here because of the file close ASSERT_EVENTS_FileOpenError_SIZE(2); } void ComLoggerTester :: writeError() { ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_SIZE(0); const U8 data[4] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(data, sizeof(data)); Fw::Time testTime(TB_NONE, 5, 9876543); setTestTime(testTime); for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // Force close the file from underneath the component: comLogger.m_file.close(); // Send 2 packets: for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // Construct filename: CHAR fileName[2048]; memset(fileName, 0, sizeof(fileName)); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", FILE_STR, static_cast<U32>(testTime.getTimeBase()), testTime.getSeconds(), testTime.getUSeconds()); // Check generated events: // We should only see a single event because write // errors are throttled. ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_FileWriteError_SIZE(1); ASSERT_EVENTS_FileWriteError( 0, Os::File::NOT_OPENED, 0, 2, fileName ); // Make comlogger open a new file: comLogger.m_fileMode = ComLogger::CLOSED; comLogger.openFile(); // Try to write and make sure it succeeds: // Send 2 packets: for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // Expect no new errors: ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_FileWriteError_SIZE(1); // Force close the file from underneath the component: comLogger.m_file.close(); // Send 2 packets: for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // Check generated events: // We should only see a single event because write // errors are throttled. ASSERT_EVENTS_SIZE(2); ASSERT_EVENTS_FileWriteError_SIZE(2); ASSERT_EVENTS_FileWriteError( 1, Os::File::NOT_OPENED, 0, 2, fileName ); } void ComLoggerTester :: closeFileCommand() { Os::File file; CHAR fileName[2048]; CHAR hashFileName[2048]; Os::File::Status ret; // Form filenames: Fw::Time testTime(TB_NONE, 6, 9876543); setTestTime(testTime); memset(fileName, 0, sizeof(fileName)); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds()); memset(hashFileName, 0, sizeof(hashFileName)); snprintf(hashFileName, sizeof(hashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds(), Utils::Hash::getFileExtensionString()); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_SIZE(0); // Send close file commands: for(int i = 0; i < 3; i++) { sendCmd_CloseFile(0, i+1); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); } ASSERT_CMD_RESPONSE_SIZE(3); for(int i = 0; i < 3; i++) { ASSERT_CMD_RESPONSE( i, ComLogger::OPCODE_CLOSEFILE, i+1, Fw::CmdResponse::OK ); } const U8 data[COM_BUFFER_LENGTH] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(data, sizeof(data)); for(int i = 0; i < 3; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // Send close file commands: for(int i = 0; i < 3; i++) { sendCmd_CloseFile(0, i+1); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); } ASSERT_CMD_RESPONSE_SIZE(6); for(int i = 0; i < 3; i++) { ASSERT_CMD_RESPONSE( i, ComLogger::OPCODE_CLOSEFILE, i+1, Fw::CmdResponse::OK ); } // Make sure we got a closed file event: ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_FileClosed_SIZE(1); ASSERT_EVENTS_FileClosed(0, fileName); // Open files to make sure they exist: ret = file.open(fileName, Os::File::OPEN_READ); ASSERT_EQ(Os::File::OP_OK,ret); file.close(); ret = file.open(hashFileName, Os::File::OPEN_READ); ASSERT_EQ(Os::File::OP_OK,ret); file.close(); } void ComLoggerTester :: testLoggingWithInit() { CHAR fileName[2048]; CHAR prevFileName[2048]; CHAR hashFileName[2048]; CHAR prevHashFileName[2048]; U8 buf[1024]; FwSignedSizeType length; U16 bufferSize = 0; Os::File::Status ret; Os::File file; this->comLogger.init_log_file(FILE_STR, MAX_BYTES_PER_FILE); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_SIZE(0); U8 data[COM_BUFFER_LENGTH] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(&data[0], sizeof(data)); Fw::SerializeStatus stat; for(int j = 0; j < 3; j++) { // Test times for the different iterations: Fw::Time testTime(TB_NONE, j, 9876543); Fw::Time testTimePrev(TB_NONE, j-1, 9876543); Fw::Time testTimeNext(TB_NONE, j+1, 9876543); // File names for the different iterations: memset(fileName, 0, sizeof(fileName)); snprintf(fileName, sizeof(fileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds()); memset(hashFileName, 0, sizeof(hashFileName)); snprintf(hashFileName, sizeof(hashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTime.getSeconds(), testTime.getUSeconds(), Utils::Hash::getFileExtensionString()); memset(prevFileName, 0, sizeof(prevFileName)); snprintf(prevFileName, sizeof(prevFileName), "%s_%d_%d_%06d.com", FILE_STR, testTime.getTimeBase(), testTimePrev.getSeconds(), testTimePrev.getUSeconds()); memset(prevHashFileName, 0, sizeof(prevHashFileName)); snprintf(prevHashFileName, sizeof(prevHashFileName), "%s_%d_%d_%06d.com%s", FILE_STR, testTime.getTimeBase(), testTimePrev.getSeconds(), testTimePrev.getUSeconds(), Utils::Hash::getFileExtensionString()); // Set the test time to the current time: setTestTime(testTime); // Write to file: for(int i = 0; i < MAX_ENTRIES_PER_FILE-1; i++) { invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); } // OK a new file should be opened after this final invoke, set a new test time so that a file // with a new name gets opened: setTestTime(testTimeNext); invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); // A new file should have been opened from the previous loop iteration: if( j > 0 ) { ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); ASSERT_TRUE(strcmp(static_cast<char*>(comLogger.m_fileName), fileName) == 0 ); } // Make sure we got a closed file event: ASSERT_EVENTS_SIZE(j); ASSERT_EVENTS_FileClosed_SIZE(j); if( j > 0 ) { ASSERT_EVENTS_FileClosed(j-1, prevFileName); } // Make sure the file size is smaller or equal to the limit: Os::FileSystem::Status fsStat; FwSignedSizeType fileSize = 0; fsStat = Os::FileSystem::getFileSize(fileName, fileSize); //!< gets the size of the file (in bytes) at location path ASSERT_EQ(fsStat, Os::FileSystem::OP_OK); ASSERT_LE(fileSize, MAX_BYTES_PER_FILE); // Open file: ret = file.open(fileName, Os::File::OPEN_READ); ASSERT_EQ(Os::File::OP_OK,ret); // Check data: for(int i = 0; i < 5; i++) { // Get length of buffer to read FwSignedSizeType length = sizeof(U16); ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK, ret); ASSERT_EQ(length, static_cast<NATIVE_INT_TYPE>(sizeof(U16))); Fw::SerialBuffer comBuffLength(buf, length); comBuffLength.fill(); stat = comBuffLength.deserialize(bufferSize); ASSERT_EQ(stat, Fw::FW_SERIALIZE_OK); ASSERT_EQ(COM_BUFFER_LENGTH, bufferSize); // Read and check buffer: length = bufferSize; ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK,ret); ASSERT_EQ(length, static_cast<NATIVE_INT_TYPE>(bufferSize)); ASSERT_EQ(memcmp(buf, data, COM_BUFFER_LENGTH), 0); } // Make sure we reached the end of the file: length = sizeof(NATIVE_INT_TYPE); ret = file.read(buf, length); ASSERT_EQ(Os::File::OP_OK,ret); ASSERT_EQ(length, 0); file.close(); // Assert that the hashes match: if( j > 0 ) { Os::ValidateFile::Status status; status = Os::ValidateFile::validate(prevFileName, prevHashFileName); ASSERT_EQ(Os::ValidateFile::VALIDATION_OK, status); } } } void ComLoggerTester :: noInitError() { U8 data[COM_BUFFER_LENGTH] = {0xde,0xad,0xbe,0xef}; Fw::ComBuffer buffer(&data[0], sizeof(data)); this->invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::CLOSED); ASSERT_EVENTS_FileNotInitialized_SIZE(1); this->comLogger.init_log_file(FILE_STR, MAX_BYTES_PER_FILE); this->clearHistory(); this->invoke_to_comIn(0, buffer, 0); dispatchAll(); ASSERT_TRUE(comLogger.m_fileMode == ComLogger::OPEN); ASSERT_EVENTS_FileNotInitialized_SIZE(0); } void ComLoggerTester :: from_pingOut_handler( const NATIVE_INT_TYPE portNum, U32 key ) { this->pushFromPortEntry_pingOut(key); } };
cpp
fprime
data/projects/fprime/Svc/Health/HealthComponentImpl.cpp
// ====================================================================== // \title Health.hpp // \author Tim // \brief hpp file for Health component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/Health/HealthComponentImpl.hpp> #include <FpConfig.hpp> #include <Fw/Types/Assert.hpp> namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- HealthImpl::HealthImpl(const char * const compName) : HealthComponentBase(compName), m_numPingEntries(0), m_key(0), m_watchDogCode(0), m_warnings(0), m_enabled(Fw::Enabled::ENABLED), queue_depth(0) { // clear tracker by disabling pings for (NATIVE_UINT_TYPE entry = 0; entry < FW_NUM_ARRAY_ELEMENTS(this->m_pingTrackerEntries); entry++) { this->m_pingTrackerEntries[entry].enabled = Fw::Enabled::DISABLED; } } void HealthImpl::init(const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE instance) { HealthComponentBase::init(queueDepth, instance); this->queue_depth = queueDepth; } void HealthImpl::setPingEntries(PingEntry* pingEntries, NATIVE_INT_TYPE numPingEntries, U32 watchDogCode) { FW_ASSERT(pingEntries); // make sure not asking for more pings than ports FW_ASSERT(numPingEntries <= NUM_PINGSEND_OUTPUT_PORTS); this->m_numPingEntries = numPingEntries; this->m_watchDogCode = watchDogCode; // copy entries to private data for (NATIVE_INT_TYPE entry = 0; entry < numPingEntries; entry++) { FW_ASSERT(pingEntries[entry].warnCycles <= pingEntries[entry].fatalCycles, pingEntries[entry].warnCycles, pingEntries[entry].fatalCycles); this->m_pingTrackerEntries[entry].entry = pingEntries[entry]; this->m_pingTrackerEntries[entry].cycleCount = 0; this->m_pingTrackerEntries[entry].enabled = Fw::Enabled::ENABLED; this->m_pingTrackerEntries[entry].key = 0; } } HealthImpl::~HealthImpl() { } // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- void HealthImpl::PingReturn_handler(const NATIVE_INT_TYPE portNum, U32 key) { // verify the key value if (key != this->m_pingTrackerEntries[portNum].key) { Fw::LogStringArg _arg = this->m_pingTrackerEntries[portNum].entry.entryName; this->log_FATAL_HLTH_PING_WRONG_KEY(_arg,key); } else { // reset the counter and clear the key this->m_pingTrackerEntries[portNum].cycleCount = 0; this->m_pingTrackerEntries[portNum].key = 0; } } void HealthImpl::Run_handler(const NATIVE_INT_TYPE portNum, U32 context) { //dispatch messages for (NATIVE_UINT_TYPE i = 0; i < this->queue_depth; i++) { MsgDispatchStatus stat = this->doDispatch(); if (MSG_DISPATCH_EMPTY == stat) { break; } FW_ASSERT(MSG_DISPATCH_OK == stat); } if (this->m_enabled == Fw::Enabled::ENABLED) { // cycle through ping table, pinging ports that are not awaiting a reply // for ports that are awaiting a reply, decrement their counters // and check for violations for (NATIVE_UINT_TYPE entry = 0; entry < this->m_numPingEntries; entry++) { if (Fw::Enabled::ENABLED == this->m_pingTrackerEntries[entry].enabled) { // If clear entry if (0 == this->m_pingTrackerEntries[entry].cycleCount) { // start a ping this->m_pingTrackerEntries[entry].key = this->m_key; // send ping this->PingSend_out(entry, this->m_pingTrackerEntries[entry].key); // increment key this->m_key++; // increment cycles for the entry this->m_pingTrackerEntries[entry].cycleCount++; } else { // check to see if it is at warning threshold if (this->m_pingTrackerEntries[entry].cycleCount == this->m_pingTrackerEntries[entry].entry.warnCycles) { Fw::LogStringArg _arg = this->m_pingTrackerEntries[entry].entry.entryName; this->log_WARNING_HI_HLTH_PING_WARN(_arg); this->tlmWrite_PingLateWarnings(++this->m_warnings); } else { // check for FATAL timeout value if (this->m_pingTrackerEntries[entry].entry.fatalCycles == this->m_pingTrackerEntries[entry].cycleCount) { Fw::LogStringArg _arg = this->m_pingTrackerEntries[entry].entry.entryName; this->log_FATAL_HLTH_PING_LATE(_arg); } } // if at warning or fatal threshold this->m_pingTrackerEntries[entry].cycleCount++; } // if clear entry } // if entry has ping enabled } // for each entry // do other specialized platform checks (e.g. VxWorks suspended tasks) this->doOtherChecks(); } // If health checking is enabled // stroke watchdog. if (this->isConnected_WdogStroke_OutputPort(0)) { this->WdogStroke_out(0,this->m_watchDogCode); } } // ---------------------------------------------------------------------- // Command handler implementations // ---------------------------------------------------------------------- void HealthImpl::HLTH_ENABLE_cmdHandler(const FwOpcodeType opCode, U32 cmdSeq, Fw::Enabled enable) { this->m_enabled = enable; Fw::Enabled isEnabled = Fw::Enabled::DISABLED; if (enable == Fw::Enabled::ENABLED) { isEnabled = Fw::Enabled::ENABLED; } this->log_ACTIVITY_HI_HLTH_CHECK_ENABLE(isEnabled); this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); } void HealthImpl::HLTH_PING_ENABLE_cmdHandler(const FwOpcodeType opCode, U32 cmdSeq, const Fw::CmdStringArg& entry, Fw::Enabled enable) { // check to see if entry is in range NATIVE_INT_TYPE entryIndex = this->findEntry(entry); if (-1 == entryIndex) { this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::VALIDATION_ERROR); return; } this->m_pingTrackerEntries[entryIndex].enabled = enable.e; Fw::Enabled isEnabled(Fw::Enabled::DISABLED); if (enable == Fw::Enabled::ENABLED) { isEnabled = Fw::Enabled::ENABLED; } Fw::LogStringArg arg; arg = entry; this->log_ACTIVITY_HI_HLTH_CHECK_PING(isEnabled,arg); this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); } void HealthImpl::HLTH_CHNG_PING_cmdHandler(const FwOpcodeType opCode, U32 cmdSeq, const Fw::CmdStringArg& entry, U32 warningValue, U32 fatalValue) { // check to see if entry is in range NATIVE_INT_TYPE entryIndex = this->findEntry(entry); if (-1 == entryIndex) { this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::VALIDATION_ERROR); return; } //check to see if warningValue less than or equal to fatalValue if (warningValue > fatalValue) { Fw::LogStringArg arg; arg = entry; this->log_WARNING_HI_HLTH_PING_INVALID_VALUES(arg,warningValue,fatalValue); this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::VALIDATION_ERROR); return; } this->m_pingTrackerEntries[entryIndex].entry.warnCycles = warningValue; this->m_pingTrackerEntries[entryIndex].entry.fatalCycles = fatalValue; Fw::LogStringArg arg = entry; this->log_ACTIVITY_HI_HLTH_PING_UPDATED(arg,warningValue,fatalValue); this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); } NATIVE_INT_TYPE HealthImpl::findEntry(const Fw::CmdStringArg& entry) { // walk through entries for (NATIVE_UINT_TYPE tableEntry = 0; tableEntry < NUM_PINGSEND_OUTPUT_PORTS; tableEntry++) { if (entry == this->m_pingTrackerEntries[tableEntry].entry.entryName) { return tableEntry; } } Fw::LogStringArg arg = entry; this->log_WARNING_LO_HLTH_CHECK_LOOKUP_ERROR(arg); return -1; } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/Health/HealthComponentImpl.hpp
// ====================================================================== // \title Health.hpp // \author Tim, J.Perez // \brief hpp file for Health component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef Health_HPP #define Health_HPP #include <Svc/Health/HealthComponentAc.hpp> #include <Fw/Types/String.hpp> namespace Svc { //! \class HealthImpl //! \brief Health component implementation class //! //! The health component iterates through each entry //! in its table and checks its status. If a ping entry //! tracker is enabled, it will ping its corresponding port //! with a provided key. If a ping return is outstanding, //! a counter is decremented, and its value is checked //! against warning and fault thresholds. A watchdog is //! always stroked in the run handler. class HealthImpl: public HealthComponentBase { public: //! \brief struct for ping entry //! //! struct for ping entry thresholds. //! Countdown is via calls to the run() //! port. If no response by warnCycles, //! an EVR will be generated and telemetry //! count will be updated. If no response //! by fatalCycles, component will send FATAL //! event. A descriptive name is stored in entryName //! for events. struct PingEntry { NATIVE_UINT_TYPE warnCycles; //!< number of cycles before WARNING NATIVE_UINT_TYPE fatalCycles; //!< number of cycles before FATAL Fw::String entryName; //!< the name of the entry }; //! \brief HealthImpl constructor //! //! The constructor for Health //! //! \param compName component name HealthImpl(const char * const compName); //! \brief HealthImpl initialization function //! //! Initializes the autocoded base class, ping table, and data members //! //! \param queueDepth Depth of queue //! \param instance The instance number void init(const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE instance); //! \brief Set ping entry tables //! //! Provides a table of ping entries //! //! \param pingEntries Pointer to provided ping table entries //! \param numPingEntries Number of ping entries in table //! \param watchDogCode Value that is sent to watchdog void setPingEntries(PingEntry* pingEntries, NATIVE_INT_TYPE numPingEntries, U32 watchDogCode); //! \brief Component destructor //! //! The destructor for HealthImpl is empty ~HealthImpl(); PROTECTED: //! \brief additional checks function //! //! Does additional checks based on the platform virtual void doOtherChecks(); PRIVATE: //! \brief ping return handler //! //! Handler implementation for pingReturn //! //! \param portNum Port number //! \param key Key value void PingReturn_handler(const NATIVE_INT_TYPE portNum, U32 key); //! \brief run handler //! //! Handler implementation for run //! //! \param portNum Port number //! \param context Port Context void Run_handler(const NATIVE_INT_TYPE portNum, U32 context); //! \brief HLTH_ENABLE handler //! //! Implementation for HLTH_ENABLE command handler //! //! \param opCode Command opcode //! \param cmdSeq Command sequence //! \param enable Enum for enabling/disabling tracker void HLTH_ENABLE_cmdHandler(const FwOpcodeType opCode, U32 cmdSeq, Fw::Enabled enable); //! \brief HLTH_PING_ENABLE handler //! //! Handler for command HLTH_PING_ENABLE //! //! \param opCode Command opcode //! \param cmdSeq Command sequence //! \param entry Ping entry number //! \param enable Enum for enabling/disabling tracker void HLTH_PING_ENABLE_cmdHandler(FwOpcodeType opCode, U32 cmdSeq, const Fw::CmdStringArg& entry, Fw::Enabled enable); //! \brief HLTH_CHNG_PING handler //! //! Implementation for HLTH_CHNG_PING command handler //! //! \param opCode Command opcode //! \param cmdSeq Command sequence //! \param entry Ping entry number //! \param warningValue Warning threshold value //! \param fatalValue Fatal threshold value void HLTH_CHNG_PING_cmdHandler(const FwOpcodeType opCode, U32 cmdSeq, const Fw::CmdStringArg& entry, U32 warningValue, U32 fatalValue); //! \brief ping tracker struct //! //! Array for storing ping table entries struct PingTracker { PingEntry entry; //!< entry passed by user U32 cycleCount; //!< current cycle count U32 key; //!< key passed to ping Fw::Enabled::t enabled; //!< if current ping result is checked } m_pingTrackerEntries[NUM_PINGSEND_OUTPUT_PORTS]; NATIVE_INT_TYPE findEntry(const Fw::CmdStringArg& entry); //! Private member data U32 m_numPingEntries; //!< stores number of entries passed to constructor U32 m_key; //!< current key value. Just increments for each ping entry. U32 m_watchDogCode; //!< stores code used for watchdog stroking U32 m_warnings; //!< number of slip warnings issued Fw::Enabled m_enabled; //!< if the pinger is enabled U32 queue_depth; //!< queue depth passed by user }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/Health/Health.hpp
// ====================================================================== // Health.hpp // Standardization header for Health // ====================================================================== #ifndef Svc_Health_HPP #define Svc_Health_HPP #include "Svc/Health/HealthComponentImpl.hpp" namespace Svc { typedef HealthImpl Health; } #endif
hpp
fprime
data/projects/fprime/Svc/Health/VxWorks/HealthComponentVxWorksChecks.cpp
// ====================================================================== // \title Health.hpp // \author Tim // \brief hpp file for Health component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/Health/HealthComponentImpl.hpp> #include <FpConfig.hpp> #include <cstdio> #include <Fw/Types/Assert.hpp> namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- void HealthImpl::doOtherChecks() { // empty } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/Health/Stub/HealthComponentStubChecks.cpp
// ====================================================================== // \title Health.hpp // \author Tim // \brief hpp file for Health component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/Health/HealthComponentImpl.hpp> #include <FpConfig.hpp> #include <cstdio> #include <Fw/Types/Assert.hpp> namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- void HealthImpl::doOtherChecks() { // empty } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/Health/test/ut/main.cpp
// ---------------------------------------------------------------------- // Main.cpp // ---------------------------------------------------------------------- #include "HealthTester.hpp" TEST(Test, NominalTlm) { Svc::HealthTester tester; tester.nominalTlm(); } TEST(Test, WarningTlm) { Svc::HealthTester tester; tester.warningTlm(); } TEST(Test, FaultTlm) { Svc::HealthTester tester; tester.faultTlm(); } TEST(Test, DisableAllMonitoring) { Svc::HealthTester tester; tester.disableAllMonitoring(); } TEST(Test, DisableOneMonitoring) { Svc::HealthTester tester; tester.disableOneMonitoring(); } TEST(Test, UpdatePingTimeout) { Svc::HealthTester tester; tester.updatePingTimeout(); } TEST(Test, WatchdogCheck) { Svc::HealthTester tester; tester.watchdogCheck(); } TEST(Test, NominalCmd) { Svc::HealthTester tester; tester.nominalCmd(); } TEST(Test, Nominal2CmdsDuringTlm) { Svc::HealthTester tester; tester.nominal2CmdsDuringTlm(); } TEST(Test, Miscellaneous) { Svc::HealthTester tester; tester.miscellaneous(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/Health/test/ut/HealthTester.hpp
// ====================================================================== // \title Health/test/ut/Tester.hpp // \author jdperez // \brief hpp file for Health test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef TESTER_HPP #define TESTER_HPP #include "HealthGTestBase.hpp" #include "Svc/Health/HealthComponentImpl.hpp" namespace Svc { class HealthTester : public HealthGTestBase { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- public: //! Construct object HealthTester //! HealthTester(); //! Destroy object HealthTester //! ~HealthTester(); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void nominalTlm(); void warningTlm(); void faultTlm(); void disableAllMonitoring(); void disableOneMonitoring(); void updatePingTimeout(); void watchdogCheck(); void nominalCmd(); void nominal2CmdsDuringTlm(); void miscellaneous(); private: // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- //! Handler for from_PingSend //! void from_PingSend_handler( const NATIVE_INT_TYPE portNum, //!< The port number U32 key //!< Value to return to pinger ) override; //! Handler for from_WdogStroke //! void from_WdogStroke_handler( const NATIVE_INT_TYPE portNum, //!< The port number U32 code //!< Watchdog stroke code ) override; private: // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- //! Connect ports //! void connectPorts(); //! Initialize components //! void initComponents(); void dispatchAll(); private: // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- NATIVE_UINT_TYPE numPingEntries; HealthImpl::PingEntry pingEntries[Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS]; U32 watchDogCode; U32 keys[Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS]; bool override; U32 override_key; //! The component under test //! HealthImpl component; void textLogIn(const FwEventIdType id, //!< The event ID const Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ) override; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/Health/test/ut/HealthTester.cpp
// ====================================================================== // \title Health.hpp // \author jdperez // \brief cpp file for Health test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include "HealthTester.hpp" #include <Fw/Test/UnitTest.hpp> #define INSTANCE 0 #define MAX_HISTORY_SIZE (Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS * Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS * Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS) #define QUEUE_DEPTH (Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2) #define FLAG_KEY_VALUE 0xcafecafe static_assert(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS < 0xcafecafe, ""); namespace Svc { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- HealthTester :: HealthTester() : HealthGTestBase("Tester", MAX_HISTORY_SIZE), component("Health") { this->connectPorts(); this->initComponents(); } HealthTester :: ~HealthTester() { } // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- void HealthTester :: from_PingSend_handler( const NATIVE_INT_TYPE portNum, U32 key ) { if(this->override) { invoke_to_PingReturn(portNum,this->override_key); } else { ASSERT_TRUE(portNum < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); if (key == this->keys[portNum]) { this->invoke_to_PingReturn(portNum, key); } } this->pushFromPortEntry_PingSend(key); } void HealthTester :: from_WdogStroke_handler( const NATIVE_INT_TYPE portNum, U32 code ) { this->pushFromPortEntry_WdogStroke(code); } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void HealthTester :: connectPorts() { // PingReturn for (NATIVE_INT_TYPE i = 0; i < this->component.getNum_PingReturn_InputPorts(); ++i) { this->connect_to_PingReturn( i, this->component.get_PingReturn_InputPort(i) ); } // Run this->connect_to_Run( 0, this->component.get_Run_InputPort(0) ); // CmdDisp this->connect_to_CmdDisp( 0, this->component.get_CmdDisp_InputPort(0) ); // PingSend for (NATIVE_INT_TYPE i = 0; i < this->component.getNum_PingSend_OutputPorts(); ++i) { this->component.set_PingSend_OutputPort( i, this->get_from_PingSend(i) ); } // WdogStroke this->component.set_WdogStroke_OutputPort( 0, this->get_from_WdogStroke(0) ); // CmdStatus this->component.set_CmdStatus_OutputPort( 0, this->get_from_CmdStatus(0) ); // CmdReg this->component.set_CmdReg_OutputPort( 0, this->get_from_CmdReg(0) ); // Tlm this->component.set_Tlm_OutputPort( 0, this->get_from_Tlm(0) ); // Time this->component.set_Time_OutputPort( 0, this->get_from_Time(0) ); // Log this->component.set_Log_OutputPort( 0, this->get_from_Log(0) ); // LogText this->component.set_LogText_OutputPort( 0, this->get_from_LogText(0) ); } void HealthTester :: initComponents() { this->init(); this->numPingEntries = Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; this->watchDogCode = 42; this->component.init( QUEUE_DEPTH, INSTANCE ); for (NATIVE_UINT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { this->pingEntries[entry].warnCycles = Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS+entry; this->pingEntries[entry].fatalCycles = Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2+entry+1; this->pingEntries[entry].entryName.format("task%d",entry); } this->component.setPingEntries(this->pingEntries, this->numPingEntries, this->watchDogCode); this->override = false; this->override_key = 0; for (U32 i = 0; i < this->numPingEntries; i++) { this->keys[i] = 100000; } } void HealthTester :: dispatchAll() { HealthComponentBase::MsgDispatchStatus stat = HealthComponentBase::MSG_DISPATCH_OK; while (HealthComponentBase::MSG_DISPATCH_OK == stat) { stat = this->component.doDispatch(); FW_ASSERT(stat != HealthComponentBase::MSG_DISPATCH_ERROR); } } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void HealthTester :: nominalTlm() { TEST_CASE(900.1.1,"Nominal Telemetry"); REQUIREMENT("ISF-HTH-001"); COMMENT("The Svc::Health component shall ping each output port specified in the provided table."); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { this->keys[port] = port; } //invoke run handler same number as number of ports for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; i++) { this->invoke_to_Run(0,0); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { this->keys[port] += Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; } // Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); } //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); } void HealthTester :: warningTlm() { TEST_CASE(900.1.2,"Warning Telemetry"); REQUIREMENT("ISF-HTH-002"); COMMENT("The Svc::Health component shall track the timeout cycles for each component."); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); return; //invoke run handler enough times for warnings for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2; i++) { this->invoke_to_Run(0,0); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { ASSERT_EQ(i+1,this->component.m_pingTrackerEntries[port].cycleCount); } } //check for expected warning EVRs from each entry ASSERT_EVENTS_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_TLM_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_EVENTS_HLTH_PING_WARN_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { char name[80]; snprintf(name, sizeof(name), "task%d",port); ASSERT_EVENTS_HLTH_PING_WARN(port,name); } } void HealthTester :: faultTlm() { TEST_CASE(900.1.3,"Fault Telemetry"); REQUIREMENT("ISF-HTH-003"); COMMENT("The Svc::Health component shall issue a FATAL event if a component fails to return a ping by the specified timeout."); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); //invoke run handler enough times for warnings for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2; i++) { this->invoke_to_Run(0,0); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { ASSERT_EQ(i+1,this->component.m_pingTrackerEntries[port].cycleCount); } } //check for expected warning EVRs from each entry ASSERT_EVENTS_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_TLM_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_EVENTS_HLTH_PING_WARN_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { char name[80]; snprintf(name, sizeof(name), "task%d",port); ASSERT_EVENTS_HLTH_PING_WARN(port,name); } this->clearEvents(); this->clearTlm(); //invoke run handler enough times for FATALs for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; i++) { this->invoke_to_Run(0,0); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { ASSERT_EQ(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2+i+1,this->component.m_pingTrackerEntries[port].cycleCount); } } this->invoke_to_Run(0,0); //check for expected warning EVRs from each entry ASSERT_EVENTS_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_EVENTS_HLTH_PING_LATE_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); for (NATIVE_UINT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { char name[80]; snprintf(name, sizeof(name), "task%d",port); ASSERT_EVENTS_HLTH_PING_LATE(port,name); } } void HealthTester :: disableAllMonitoring() { TEST_CASE(900.1.4,"Enable/Disable all monitoring"); REQUIREMENT("ISF-HTH-004"); COMMENT("The Svc::Health component shall have a command to enable or disable all monitoring."); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); //invoke run handler for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2; i++) { this->invoke_to_Run(0,0); for (NATIVE_INT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { ASSERT_EQ(i+1,this->component.m_pingTrackerEntries[entry].cycleCount); } } ASSERT_EVENTS_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_EVENTS_HLTH_PING_WARN_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); for (NATIVE_INT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { char name[80]; snprintf(name, sizeof(name), "task%d",entry); ASSERT_EVENTS_HLTH_PING_WARN(entry, name); } ASSERT_TLM_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); this->clearEvents(); this->clearTlm(); //disable all monitoring this->sendCmd_HLTH_ENABLE(0,0,Fw::Enabled::DISABLED); this->dispatchAll(); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_ENABLE_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_ENABLE(0,Fw::Enabled::DISABLED); ASSERT_EQ(this->component.m_enabled, Fw::Enabled::DISABLED); //invoke run handler 100 times for (U32 i = 0; i < 100; i++) { this->invoke_to_Run(0,0); // cycle count should stay the same ASSERT_EQ(static_cast<U32>(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS)*2, this->component.m_pingTrackerEntries[0].cycleCount); } //confirm no telemetry was received ASSERT_TLM_SIZE(0); this->clearEvents(); this->clearTlm(); //enable all monitoring this->sendCmd_HLTH_ENABLE(0,0,Fw::Enabled::ENABLED); this->dispatchAll(); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_ENABLE_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_ENABLE(0,Fw::Enabled::ENABLED); ASSERT_EQ(this->component.m_enabled, Fw::Enabled::ENABLED); this->clearEvents(); this->clearTlm(); // check that cycle counts increase again for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; i++) { this->invoke_to_Run(0,0); for (NATIVE_INT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { ASSERT_EQ(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2+1+i,this->component.m_pingTrackerEntries[entry].cycleCount); } } this->invoke_to_Run(0,0); // Should be FATAL timeouts ASSERT_EVENTS_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_EVENTS_HLTH_PING_LATE_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); for (NATIVE_INT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { char name[80]; snprintf(name,sizeof(name), "task%d",entry); ASSERT_EVENTS_HLTH_PING_LATE(entry,name); } } void HealthTester :: disableOneMonitoring() { TEST_CASE(900.1.5,"Enable/Disable individual monitors"); REQUIREMENT("ISF-HTH-005"); COMMENT("The Svc::Health component shall have a command to enable or disable monitoring for a particular port."); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); // disable monitoring one at a time for (NATIVE_INT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { this->clearEvents(); this->clearHistory(); // reset cycle count for (NATIVE_INT_TYPE e2 = 0; e2 < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; e2++) { this->component.m_pingTrackerEntries[e2].cycleCount = 0; } // disable entry char name[80]; snprintf(name, sizeof(name), "task%d",entry); Fw::CmdStringArg task(name); this->sendCmd_HLTH_PING_ENABLE(0,10,name,Fw::Enabled::DISABLED); this->dispatchAll(); ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE(0,HealthComponentBase::OPCODE_HLTH_PING_ENABLE,10,Fw::CmdResponse::OK); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_PING(0,Fw::Enabled::DISABLED,name); // run a few cycles for (NATIVE_INT_TYPE cycle = 0; cycle < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; cycle++) { // run a cycle this->invoke_to_Run(0,0); // verify only enable entries count up for (NATIVE_INT_TYPE e3 = 0; e3 < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; e3++) { if (e3 == entry) { // shouldn't be counting up ASSERT_EQ(0u,this->component.m_pingTrackerEntries[e3].cycleCount); } else { // others should be counting up ASSERT_EQ(static_cast<U32>(cycle+1),this->component.m_pingTrackerEntries[e3].cycleCount); } } } this->clearEvents(); this->clearHistory(); this->sendCmd_HLTH_PING_ENABLE(0,10,name,Fw::Enabled::ENABLED); this->dispatchAll(); ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE(0,HealthComponentBase::OPCODE_HLTH_PING_ENABLE,10,Fw::CmdResponse::OK); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_PING(0,Fw::Enabled::ENABLED,name); } } void HealthTester :: updatePingTimeout() { TEST_CASE(900.1.6,"Update ping timeouts"); REQUIREMENT("ISF-HTH-006"); COMMENT("The Svc::Health component shall have a command to update ping timeout values for a port"); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); for (NATIVE_UINT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { this->clearEvents(); this->clearHistory(); // verify previous value ASSERT_EQ(this->pingEntries[entry].warnCycles,Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS+entry); ASSERT_EQ(this->pingEntries[entry].fatalCycles,Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2+entry+1); char name[80]; snprintf(name, sizeof(name), "task%d",entry); Fw::CmdStringArg task(name); this->sendCmd_HLTH_CHNG_PING(0,10,task, Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*4+entry, Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*5+entry); this->dispatchAll(); // verify EVR ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_PING_UPDATED_SIZE(1); ASSERT_EVENTS_HLTH_PING_UPDATED(0,name, Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*4+entry, Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*5+entry); ASSERT_EQ(this->component.m_pingTrackerEntries[entry].entry.warnCycles, Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*4+entry); ASSERT_EQ(this->component.m_pingTrackerEntries[entry].entry.fatalCycles, Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*5+entry); } } void HealthTester :: watchdogCheck() { TEST_CASE(900.1.7,"Watchdog check"); REQUIREMENT("ISF-HTH-007"); COMMENT("The Svc::Health component shall stroke a watchdog port while all ping replies are within their limit and health checks pass"); //Check initial state is as expected ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); //invoke run handler 10 times and check watchdog port output for (U32 i = 0; i < 10; i++) { this->invoke_to_Run(0,0); ASSERT_from_WdogStroke_SIZE(i+1); ASSERT_from_WdogStroke(i, this->component.m_watchDogCode); //increment watchdog code this->component.m_watchDogCode += 1; } } void HealthTester :: nominalCmd() { TEST_CASE(900.1.8,"Nominal Command"); COMMENT("Process command during quiescent (no telemetry readout) period."); Fw::LogStringArg arg = "task0"; Fw::CmdStringArg carg = arg; ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); ASSERT_CMD_RESPONSE_SIZE(0); sendCmd_HLTH_ENABLE(0,0, Fw::Enabled::DISABLED); this->dispatchAll(); ASSERT_EQ(Fw::Enabled(Fw::Enabled::DISABLED), this->component.m_enabled); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_ENABLE(0,Fw::Enabled::DISABLED); this->clearEvents(); sendCmd_HLTH_ENABLE(0,0, Fw::Enabled::ENABLED); this->dispatchAll(); ASSERT_EQ(Fw::Enabled(Fw::Enabled::ENABLED), this->component.m_enabled); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_ENABLE(0,Fw::Enabled::ENABLED); this->clearEvents(); sendCmd_HLTH_PING_ENABLE(0, 0, carg, Fw::Enabled::DISABLED); this->dispatchAll(); ASSERT_EQ(Fw::Enabled(Fw::Enabled::DISABLED), this->component.m_pingTrackerEntries[0].enabled); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_PING(0,Fw::Enabled::DISABLED,"task0"); this->clearEvents(); U32 warn_val = 9; U32 fatal_val = 99; sendCmd_HLTH_CHNG_PING(0, 0, carg, warn_val, fatal_val); this->dispatchAll(); ASSERT_EQ(warn_val, this->component.m_pingTrackerEntries[0].entry.warnCycles); ASSERT_EQ(fatal_val, this->component.m_pingTrackerEntries[0].entry.fatalCycles); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_PING_UPDATED_SIZE(1); ASSERT_EVENTS_HLTH_PING_UPDATED(0,"task0",warn_val,fatal_val); ASSERT_TLM_SIZE(0); } void HealthTester :: nominal2CmdsDuringTlm() { TEST_CASE(900.1.9,"Nominal 2 commands called during telemetry readouts."); COMMENT("Process commands during busy (telemetry readout) period."); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); for (NATIVE_INT_TYPE entry = 0; entry < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; entry++) { this->keys[entry] = entry; } this->invoke_to_Run(0,0); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); sendCmd_HLTH_ENABLE(0,0, Fw::Enabled::DISABLED); this->dispatchAll(); ASSERT_EQ(Fw::Enabled(Fw::Enabled::DISABLED), this->component.m_enabled); return; //invoke schedIn handler for 50 times for (U32 i = 0; i < 50; i++) { printf("Invoke: %d\n",i); this->invoke_to_Run(0,0); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); } sendCmd_HLTH_ENABLE(0,0, Fw::Enabled::ENABLED); this->dispatchAll(); ASSERT_EQ(Fw::Enabled(Fw::Enabled::ENABLED), this->component.m_enabled); this->invoke_to_Run(0,0); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); } void HealthTester :: miscellaneous() { TEST_CASE(900.1.10,"Miscellaneous remaining tests."); COMMENT("Case 1: Ping port anomalies."); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); //send a bad ping return key this->override = true; this->override_key = FLAG_KEY_VALUE; //invoke schedIn this->invoke_to_Run(0,0); this->dispatchAll(); //check for expected EVRs ASSERT_EVENTS_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); ASSERT_EVENTS_HLTH_PING_WRONG_KEY_SIZE(Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS); for (NATIVE_INT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; port++) { char name[80]; snprintf(name, sizeof(name), "task%d",port); ASSERT_EVENTS_HLTH_PING_WRONG_KEY(port,name,FLAG_KEY_VALUE); } this->clearEvents(); this->clearTlm(); COMMENT("Case 2: Command input anomalies."); //Check no events or telemetry have occurred ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); //send command with bad value Fw::Enabled badValue = static_cast<Fw::Enabled::t>(Fw::Enabled::NUM_CONSTANTS); sendCmd_HLTH_PING_ENABLE(0,0,"task0",badValue); this->dispatchAll(); ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE(0,HealthComponentBase::OPCODE_HLTH_PING_ENABLE,0,Fw::CmdResponse::FORMAT_ERROR); //send command with bad ping entry sendCmd_HLTH_PING_ENABLE(0,0,"notask",Fw::Enabled::ENABLED); this->dispatchAll(); ASSERT_CMD_RESPONSE_SIZE(2); ASSERT_CMD_RESPONSE(1,HealthComponentBase::OPCODE_HLTH_PING_ENABLE,0,Fw::CmdResponse::VALIDATION_ERROR); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_LOOKUP_ERROR_SIZE(1); ASSERT_EVENTS_HLTH_CHECK_LOOKUP_ERROR(0,"notask"); this->clearHistory(); //send update timeout command with bad thresholds sendCmd_HLTH_CHNG_PING(0, 0,"task0", 10, 9); this->dispatchAll(); ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE(0,HealthComponentBase::OPCODE_HLTH_CHNG_PING,0,Fw::CmdResponse::VALIDATION_ERROR); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_PING_INVALID_VALUES_SIZE(1); ASSERT_EVENTS_HLTH_PING_INVALID_VALUES(0,"task0",10,9); this->clearEvents(); this->clearHistory(); //send update timeout command with ping entry sendCmd_HLTH_CHNG_PING(0, 0, "sometask", 1, 2); this->dispatchAll(); ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE(0,HealthComponentBase::OPCODE_HLTH_CHNG_PING,0,Fw::CmdResponse::VALIDATION_ERROR); this->clearEvents(); this->clearHistory(); COMMENT("Case 3: All ping ports except one respond to ping requests."); ASSERT_EVENTS_SIZE(0); //set up the correct keys for all ports except last for (NATIVE_INT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS - 1; port++) { this->keys[port] = port; } this->keys[Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS - 1] = 9999; this->override = false; this->component.m_key = 0; //reset cycle counts for (U32 i = 0; i < this->numPingEntries; i++) { this->component.m_pingTrackerEntries[i].cycleCount = 0; } //invoke schedIn handler for (U32 i = 0; i < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS*2; i++) { //invoke schedIn this->invoke_to_Run(0,0); for (NATIVE_INT_TYPE port = 0; port < Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS - 1; port++) { if (i == 0) { this->keys[port] += Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS; } else { this->keys[port] += Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS-1; } } } //check that only the last ping entry caused a warning EVR due to no ping response ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_HLTH_PING_WARN_SIZE(1); char name[80]; snprintf(name, sizeof(name), "task%d",Svc::HealthComponentBase::NUM_PINGSEND_OUTPUT_PORTS-1); ASSERT_EVENTS_HLTH_PING_WARN(0,name); ASSERT_TLM_SIZE(1); ASSERT_TLM_PingLateWarnings_SIZE(1); ASSERT_TLM_PingLateWarnings(0,1); } void HealthTester::textLogIn(const FwEventIdType id, //!< The event ID const Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ) { TextLogEntry e = { id, timeTag, severity, text }; printTextLogHistoryEntry(e, stdout); } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/RateGroupDriver/RateGroupDriver.hpp
/** * \file * \author T. Canham * \brief RateGroupDivider component implementation * * This component implements a divider function. A primary tick is invoked * via the CycleIn port. The divider array then divides down the tick into * CycleOut ports. The ports are called at the rate of * input rate/divider[port] * * \copyright * Copyright 2009-2015, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * <br /><br /> */ #ifndef SVC_RATEGROUPDRIVER_HPP #define SVC_RATEGROUPDRIVER_HPP #include <Svc/RateGroupDriver/RateGroupDriverComponentAc.hpp> #include <FpConfig.hpp> namespace Svc { //! \class RateGroupDriver //! \brief Implementation class for RateGroupDriver //! //! Takes the input from CycleIn and divides it. //! Output rate is CycleIn rate/divider[port] //! class RateGroupDriver : public RateGroupDriverComponentBase { public: //! Size of the divider table, provided as a constants to users passing the table in static const NATIVE_UINT_TYPE DIVIDER_SIZE = NUM_CYCLEOUT_OUTPUT_PORTS; //! \class Divider //! \brief Struct describing a divider struct Divider{ //! Initializes divisor and offset to 0 (unused) Divider() : divisor(0), offset(0) {} //! Initializes divisor and offset to passed-in pair Divider(NATIVE_INT_TYPE divisorIn, NATIVE_INT_TYPE offsetIn) : divisor(divisorIn), offset(offsetIn) {} //! Divisor NATIVE_INT_TYPE divisor; //! Offset NATIVE_INT_TYPE offset; }; //! \class DividerSet //! \brief Struct containing an array of dividers struct DividerSet { //! Dividers Divider dividers[Svc::RateGroupDriver::DIVIDER_SIZE]; }; //! \brief RateGroupDriver constructor //! //! The constructor takes the divider array and stores it //! for use when the CycleIn port is called. //! //! \param compName component name //! RateGroupDriver(const char* compName); //! \brief RateGroupDriver configuration function //! \param dividersSet set of dividers used to divide down input tick void configure(const DividerSet& dividersSet); //! \brief RateGroupDriverImpl destructor ~RateGroupDriver(); PRIVATE: //! downcall for input port //! NOTE: This port can execute in ISR context. void CycleIn_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart); //! divider array Divider m_dividers[NUM_CYCLEOUT_OUTPUT_PORTS]; //! tick counter NATIVE_INT_TYPE m_ticks; //! rollover counter NATIVE_INT_TYPE m_rollover; //! has the configure method been called bool m_configured; }; } #endif
hpp
fprime
data/projects/fprime/Svc/RateGroupDriver/RateGroupDriver.cpp
#include <Svc/RateGroupDriver/RateGroupDriver.hpp> #include <FpConfig.hpp> #include <cstring> #include <Fw/Types/Assert.hpp> #include <cstdio> namespace Svc { RateGroupDriver::RateGroupDriver(const char* compName) : RateGroupDriverComponentBase(compName), m_ticks(0),m_rollover(1),m_configured(false) { } void RateGroupDriver::configure(const DividerSet& dividerSet) { // check arguments FW_ASSERT(dividerSet.dividers); // verify port/table size matches FW_ASSERT(FW_NUM_ARRAY_ELEMENTS(this->m_dividers) == this->getNum_CycleOut_OutputPorts(), static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_dividers)), this->getNum_CycleOut_OutputPorts()); // copy provided array of dividers for (NATIVE_UINT_TYPE entry = 0; entry < RateGroupDriver::DIVIDER_SIZE; entry++) { // A port with an offset equal or bigger than the divisor is not accepted because it would never be called FW_ASSERT((dividerSet.dividers[entry].offset==0)||(dividerSet.dividers[entry].offset < dividerSet.dividers[entry].divisor), dividerSet.dividers[entry].offset, dividerSet.dividers[entry].divisor); this->m_dividers[entry] = dividerSet.dividers[entry]; // rollover value should be product of all dividers to make sure integer rollover doesn't jump cycles // only use non-zero dividers if (dividerSet.dividers[entry].divisor != 0) { this->m_rollover *= dividerSet.dividers[entry].divisor; } } this->m_configured = true; } RateGroupDriver::~RateGroupDriver() { } void RateGroupDriver::CycleIn_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart) { // Make sure that the dividers have been configured: // If this asserts, add the configure() call to initialization. FW_ASSERT(this->m_configured); // Loop through each divider. For a given port, the port will be called when the divider value // divides evenly into the number of ticks. For example, if the divider value for a port is 4, // it would be called every fourth invocation of the CycleIn port. for (NATIVE_UINT_TYPE entry = 0; entry < RateGroupDriver::DIVIDER_SIZE; entry++) { if (this->m_dividers[entry].divisor != 0) { if (this->isConnected_CycleOut_OutputPort(entry)) { if ((this->m_ticks % this->m_dividers[entry].divisor) == this->m_dividers[entry].offset) { this->CycleOut_out(entry,cycleStart); } } } } // rollover the tick value when the tick count reaches the rollover value // the rollover value is the product of all the dividers. See comment in constructor. this->m_ticks = (this->m_ticks + 1) % this->m_rollover; } }
cpp
fprime
data/projects/fprime/Svc/RateGroupDriver/test/ut/RateGroupDriverImplTester.hpp
/* * RateGroupDriverImplTester.hpp * * Created on: June 19, 2015 * Author: tcanham */ #ifndef RATEGROUPDRIVER_TEST_UT_RATEGROUPDRIVERIMPLTESTER_HPP_ #define RATEGROUPDRIVER_TEST_UT_RATEGROUPDRIVERIMPLTESTER_HPP_ #include <RateGroupDriverGTestBase.hpp> #include <Svc/RateGroupDriver/RateGroupDriver.hpp> namespace Svc { class RateGroupDriverImplTester: public RateGroupDriverGTestBase { public: RateGroupDriverImplTester(Svc::RateGroupDriver& inst); virtual ~RateGroupDriverImplTester(); void init(NATIVE_INT_TYPE instance = 0); void runSchedNominal(Svc::RateGroupDriver::DividerSet dividersSet, NATIVE_INT_TYPE numDividers); private: void from_CycleOut_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart); Svc::RateGroupDriver& m_impl; void clearPortCalls(); bool m_portCalls[Svc::RateGroupDriver::DIVIDER_SIZE]; }; } /* namespace Svc */ #endif /* RATEGROUPDRIVER_TEST_UT_ACTIVELOGGERIMPLTESTER_HPP_ */
hpp
fprime
data/projects/fprime/Svc/RateGroupDriver/test/ut/RateGroupDriverTester.cpp
/* * RateGroupDriverTester.cpp * * Created on: Mar 18, 2015 * Author: tcanham */ #include <Svc/RateGroupDriver/test/ut/RateGroupDriverImplTester.hpp> #include <Svc/RateGroupDriver/RateGroupDriver.hpp> #include <Fw/Obj/SimpleObjRegistry.hpp> #include <gtest/gtest.h> #if FW_OBJECT_REGISTRATION == 1 static Fw::SimpleObjRegistry simpleReg; #endif void connectPorts(Svc::RateGroupDriver& impl, Svc::RateGroupDriverImplTester& tester) { for(NATIVE_UINT_TYPE i=0; i<Svc::RateGroupDriver::DIVIDER_SIZE; i++) { impl.set_CycleOut_OutputPort(i,tester.get_from_CycleOut(i)); } tester.connect_to_CycleIn(0,impl.get_CycleIn_InputPort(0)); #if FW_PORT_TRACING // Fw::PortBase::setTrace(true); #endif // simpleReg.dump(); } TEST(RateGroupDriverTest,NominalSchedule) { Svc::RateGroupDriver::DividerSet dividersSet{}; for(FwIndexType i=0; i<static_cast<FwIndexType>(Svc::RateGroupDriver::DIVIDER_SIZE); i++) { dividersSet.dividers[i] = {i+1, i%2}; } Svc::RateGroupDriver impl("RateGroupDriver"); impl.configure(dividersSet); Svc::RateGroupDriverImplTester tester(impl); tester.init(); impl.init(); // connect ports connectPorts(impl,tester); tester.runSchedNominal(dividersSet,FW_NUM_ARRAY_ELEMENTS(dividersSet.dividers)); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/RateGroupDriver/test/ut/RateGroupDriverImplTester.cpp
/* * RateGroupDriverImplTester.cpp * * Created on: Mar 18, 2015 * Author: tcanham */ #include <Svc/RateGroupDriver/test/ut/RateGroupDriverImplTester.hpp> #include <gtest/gtest.h> #include <cstdio> #include <cstring> #include <Fw/Test/UnitTest.hpp> namespace Svc { void RateGroupDriverImplTester::init(NATIVE_INT_TYPE instance) { RateGroupDriverGTestBase::init(); } RateGroupDriverImplTester::RateGroupDriverImplTester(Svc::RateGroupDriver& inst) : RateGroupDriverGTestBase("testerbase",100), m_impl(inst) { this->clearPortCalls(); } void RateGroupDriverImplTester::clearPortCalls() { memset(this->m_portCalls,0,sizeof(this->m_portCalls)); } RateGroupDriverImplTester::~RateGroupDriverImplTester() { } void RateGroupDriverImplTester::from_CycleOut_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart) { this->m_portCalls[portNum] = true; } void RateGroupDriverImplTester::runSchedNominal(Svc::RateGroupDriver::DividerSet dividersSet, NATIVE_INT_TYPE numDividers) { TEST_CASE(106.1.1,"Nominal Execution"); COMMENT( "Call the port with enough ticks that the internal rollover value will roll over.\n" "Verify that the output ports are being called correctly.\n" ); NATIVE_INT_TYPE expected_rollover = 1; for (NATIVE_INT_TYPE div = 0; div < numDividers; div++) { expected_rollover *= dividersSet.dividers[div].divisor; } ASSERT_EQ(expected_rollover,this->m_impl.m_rollover); NATIVE_INT_TYPE iters = expected_rollover*10; REQUIREMENT("RGD-001"); for (NATIVE_INT_TYPE cycle = 0; cycle < iters; cycle++) { this->clearPortCalls(); TimerVal t; this->invoke_to_CycleIn(0,t); // make sure ticks are counting correctly ASSERT_EQ((cycle+1)%expected_rollover,this->m_impl.m_ticks); // check for various intervals for (NATIVE_INT_TYPE div = 0; div < numDividers; div++) { if (cycle % dividersSet.dividers[div].divisor == dividersSet.dividers[div].offset) { EXPECT_TRUE(this->m_portCalls[div]); } else { EXPECT_FALSE(this->m_portCalls[div]); } } } } } /* namespace SvcTest */
cpp
fprime
data/projects/fprime/Svc/UdpSender/UdpSenderComponentImpl.hpp
// ====================================================================== // \title UdpSenderImpl.hpp // \author tcanham // \brief hpp file for UdpSender component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef UdpSender_HPP #define UdpSender_HPP #include <Svc/UdpSender/UdpSenderComponentAc.hpp> #include <UdpSenderComponentImplCfg.hpp> #include <sys/socket.h> #include <arpa/inet.h> namespace Svc { class UdpSenderComponentImpl : public UdpSenderComponentBase { public: // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct object UdpSender //! UdpSenderComponentImpl( const char *const compName /*!< The component name*/ ); //! Initialize object UdpSender //! void init( const NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/ const NATIVE_INT_TYPE msgSize, /*!< The message size*/ const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/ ); //! Destroy object UdpSender //! ~UdpSenderComponentImpl(); //! Open the connection //! void open( const char* addr, /*!< server address */ const char* port /*!< server port */ ); PRIVATE: // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- //! Handler implementation for Sched //! void Sched_handler( const NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 context /*!< The call order*/ ); PRIVATE: // ---------------------------------------------------------------------- // Handler implementations for user-defined serial input ports // ---------------------------------------------------------------------- //! Handler implementation for PortsIn //! void PortsIn_handler( NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/ ); NATIVE_INT_TYPE m_fd; //!< file descriptor for UDP socket NATIVE_UINT_TYPE m_packetsSent; //!< number of packets sent to server NATIVE_UINT_TYPE m_bytesSent; //!< number of bytes sent to server U8 m_seq; //!< packet sequence number; used to detect drops on the server end struct sockaddr_in m_servAddr; //!< server address for sends class UdpSerialBuffer : public Fw::SerializeBufferBase { public: #ifdef BUILD_UT UdpSerialBuffer& operator=(const UdpSerialBuffer& other); UdpSerialBuffer(const Fw::SerializeBufferBase& other); UdpSerialBuffer(const UdpSerialBuffer& other); UdpSerialBuffer(); #endif NATIVE_UINT_TYPE getBuffCapacity() const { return sizeof(m_buff); } // Get the max number of bytes that can be serialized NATIVE_UINT_TYPE getBuffSerLeft() const { const NATIVE_UINT_TYPE size = getBuffCapacity(); const NATIVE_UINT_TYPE loc = getBuffLength(); if (loc >= (size-1) ) { return 0; } else { return (size - loc - 1); } } U8* getBuffAddr() { return m_buff; } const U8* getBuffAddr() const { return m_buff; } private: // Should be the max of all the input ports serialized sizes... U8 m_buff[UDP_SENDER_MSG_SIZE]; } m_sendBuff; }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/UdpSender/UdpSenderComponentImpl.cpp
// ====================================================================== // \title UdpSenderImpl.cpp // \author tcanham // \brief cpp file for UdpSender component implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include <Svc/UdpSender/UdpSenderComponentImpl.hpp> #include <FpConfig.hpp> #include <sys/types.h> #include <cstring> #include <cerrno> #include <cstdlib> #include <unistd.h> //#define DEBUG_PRINT(...) printf(##__VA_ARGS__) #define DEBUG_PRINT(...) namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- UdpSenderComponentImpl :: UdpSenderComponentImpl( const char *const compName ) : UdpSenderComponentBase(compName), m_fd(-1), m_packetsSent(0), m_bytesSent(0), m_seq(0) { } void UdpSenderComponentImpl :: init( const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE msgSize, const NATIVE_INT_TYPE instance ) { UdpSenderComponentBase::init(queueDepth, msgSize, instance); } UdpSenderComponentImpl :: ~UdpSenderComponentImpl() { if (this->m_fd != -1) { close(this->m_fd); } } void UdpSenderComponentImpl::open( const char* addr, /*!< server address */ const char* port /*!< server port */ ) { FW_ASSERT(addr); FW_ASSERT(port); // open UDP connection this->m_fd = socket(AF_INET, SOCK_DGRAM, 0); if (-1 == this->m_fd) { Fw::LogStringArg arg(strerror(errno)); this->log_WARNING_HI_US_SocketError(arg); return; } /* fill in the server's address and data */ memset(&m_servAddr, 0, sizeof(m_servAddr)); m_servAddr.sin_family = AF_INET; m_servAddr.sin_port = htons(atoi(port)); inet_aton(addr , &m_servAddr.sin_addr); Fw::LogStringArg arg(addr); this->log_ACTIVITY_HI_US_PortOpened(arg,atoi(port)); } // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- void UdpSenderComponentImpl :: Sched_handler( const NATIVE_INT_TYPE portNum, U32 context ) { this->tlmWrite_US_BytesSent(this->m_bytesSent); this->tlmWrite_US_PacketsSent(this->m_packetsSent); } // ---------------------------------------------------------------------- // Handler implementations for user-defined serial input ports // ---------------------------------------------------------------------- void UdpSenderComponentImpl :: PortsIn_handler( NATIVE_INT_TYPE portNum, /*!< The port number*/ Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/ ) { // return if we never successfully created the socket if (-1 == this->m_fd) { return; } DEBUG_PRINT("PortsIn_handler: %d\n",portNum); Fw::SerializeStatus stat; m_sendBuff.resetSer(); // serialize sequence number stat = m_sendBuff.serialize(this->m_seq++); FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,stat); // serialize port call stat = m_sendBuff.serialize(static_cast<U8>(portNum)); FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,stat); // serialize port arguments buffer stat = m_sendBuff.serialize(Buffer); FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,stat); // send on UDP socket DEBUG_PRINT("Sending %d bytes\n",m_sendBuff.getBuffLength()); ssize_t sendStat = sendto(this->m_fd, m_sendBuff.getBuffAddr(), m_sendBuff.getBuffLength(), 0, reinterpret_cast<struct sockaddr *>(&m_servAddr), sizeof(m_servAddr)); if (-1 == sendStat) { Fw::LogStringArg arg(strerror(errno)); this->log_WARNING_HI_US_SendError(arg); } else { FW_ASSERT((int)m_sendBuff.getBuffLength() == sendStat,(int)m_sendBuff.getBuffLength(),sendStat,portNum); this->m_packetsSent++; this->m_bytesSent += sendStat; } } #ifdef BUILD_UT UdpSerialBuffer& UdpSenderComponentImpl::UdpSerialBuffer::operator=(const Svc::UdpSenderComponentImpl::UdpSerialBuffer& other) { this->resetSer(); this->serialize(other.getBuffAddr(),other.getBuffLength(),true); return *this; } UdpSenderComponentImpl::UdpSerialBuffer::UdpSerialBuffer( const Fw::SerializeBufferBase& other) : Fw::SerializeBufferBase() { FW_ASSERT(sizeof(this->m_buff)>= other.getBuffLength(),sizeof(this->m_buff),other.getBuffLength()); memcpy(this->m_buff,other.getBuffAddr(),other.getBuffLength()); this->setBuffLen(other.getBuffLength()); } UdpSenderComponentImpl::UdpSerialBuffer::UdpSerialBuffer( const UdpSenderComponentImpl::UdpSerialBuffer& other) : Fw::SerializeBufferBase() { FW_ASSERT(sizeof(this->m_buff)>= other.getBuffLength(),sizeof(this->m_buff),other.getBuffLength()); memcpy(this->m_buff,other.m_buff,other.getBuffLength()); this->setBuffLen(other.getBuffLength()); } UdpSenderComponentImpl::UdpSerialBuffer::UdpSerialBuffer(): Fw::SerializeBufferBase() { } #endif } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/UdpSender/test/ut/main.cpp
#include <Svc/UdpSender/test/ut/Tester.hpp> #include <Fw/Test/UnitTest.hpp> TEST(Nominal,OpenConnection) { COMMENT("Open the connections"); Svc::Tester tester; tester.openTest("127.0.0.1","50000"); } TEST(Nominal,SendPacket) { COMMENT("Send a packet"); Svc::Tester tester; tester.sendTest("127.0.0.1","50000"); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/UdpSender/test/ut/Tester.cpp
// ====================================================================== // \title UdpSender.hpp // \author tcanham // \brief cpp file for UdpSender test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include "Tester.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 10 #define QUEUE_DEPTH 10 namespace Svc { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- Tester :: Tester() : UdpSenderGTestBase("Tester", MAX_HISTORY_SIZE), component("UdpSender") ,m_recvFd(-1) { this->initComponents(); this->connectPorts(); } Tester :: ~Tester() { close(this->m_recvFd); } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void Tester :: openTest(const char* server, const char* port) { this->component.open(server,port); // expect successfully opened ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_US_PortOpened_SIZE(1); } void Tester :: sendTest(const char* server, const char* port) { this->component.open(server,port); // expect successfully opened ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_US_PortOpened_SIZE(1); // open receive port this->udpRecvStart(port); this->clearEvents(); // send a buffer Svc::UdpSenderComponentImpl::UdpSerialBuffer buff; ASSERT_EQ(Fw::FW_SERIALIZE_OK,buff.serialize(static_cast<U32>(10))); this->invoke_to_PortsIn(1,buff); this->component.doDispatch(); // verify packet count ASSERT_EVENTS_SIZE(0); // verify byte count this->invoke_to_Sched(0,0); ASSERT_TLM_US_PacketsSent_SIZE(1); ASSERT_TLM_US_PacketsSent(0,1); // get data back U8 recvBytes[256]; memset(recvBytes,0xFF,sizeof(recvBytes)); NATIVE_INT_TYPE bytes = this->udpGet(recvBytes,sizeof(recvBytes)); ASSERT_EQ(bytes,8); Fw::ExternalSerializeBuffer checkBuff(recvBytes,8); checkBuff.setBuffLen(8); // deserialize data packet U8 seq; ASSERT_EQ(Fw::FW_SERIALIZE_OK,checkBuff.deserialize(seq)); ASSERT_EQ(0,seq); // deserialize port number U8 port; ASSERT_EQ(Fw::FW_SERIALIZE_OK,checkBuff.deserialize(port)); ASSERT_EQ(1,port); // deserialize buffer Svc::UdpSenderComponentImpl::UdpSerialBuffer inBuff; ASSERT_EQ(Fw::FW_SERIALIZE_OK,checkBuff.deserialize(inBuff)); ASSERT_EQ(buff,inBuff); } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void Tester :: connectPorts() { // Sched this->connect_to_Sched( 0, this->component.get_Sched_InputPort(0) ); // Tlm this->component.set_Tlm_OutputPort( 0, this->get_from_Tlm(0) ); // Time this->component.set_Time_OutputPort( 0, this->get_from_Time(0) ); // Log this->component.set_Log_OutputPort( 0, this->get_from_Log(0) ); // LogText this->component.set_LogText_OutputPort( 0, this->get_from_LogText(0) ); // ---------------------------------------------------------------------- // Connect serial input ports // ---------------------------------------------------------------------- // PortsIn for (NATIVE_INT_TYPE i = 0; i < 10; ++i) { this->connect_to_PortsIn( i, this->component.get_PortsIn_InputPort(i) ); } } void Tester :: initComponents() { this->init(); this->component.init( QUEUE_DEPTH, 255, INSTANCE ); } void Tester::textLogIn(const FwEventIdType id, //!< The event ID Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ) { TextLogEntry e = { id, timeTag, severity, text }; printTextLogHistoryEntry(e, stdout); } void Tester::udpRecvStart(const char* port) { sockaddr_in saddr; //create a UDP socket this->m_recvFd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); EXPECT_NE(-1,this->m_recvFd); // zero out the structure memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(atoi(port)); saddr.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port EXPECT_NE(-1,bind(this->m_recvFd , (struct sockaddr*)&saddr, sizeof(saddr) )); } NATIVE_INT_TYPE Tester::udpGet(U8* buff, NATIVE_UINT_TYPE size) { NATIVE_INT_TYPE psize = recvfrom(this->m_recvFd,buff,size,MSG_WAITALL,0,0); EXPECT_NE(psize,-1); return psize; } } // end namespace Svc
cpp
fprime
data/projects/fprime/Svc/UdpSender/test/ut/Tester.hpp
// ====================================================================== // \title UdpSender/test/ut/Tester.hpp // \author tcanham // \brief hpp file for UdpSender test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef TESTER_HPP #define TESTER_HPP #include "UdpSenderGTestBase.hpp" #include "Svc/UdpSender/UdpSenderComponentImpl.hpp" namespace Svc { class Tester : public UdpSenderGTestBase { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- public: //! Construct object Tester //! Tester(); //! Destroy object Tester //! ~Tester(); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! open socket test //! void openTest(const char* server, const char* port); //! open socket test //! void sendTest(const char* server, const char* port); private: // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- //! Connect ports //! void connectPorts(); //! Initialize components //! void initComponents(); private: // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- //! The component under test //! UdpSenderComponentImpl component; void textLogIn( const FwEventIdType id, //!< The event ID Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ); NATIVE_INT_TYPE m_recvFd; void udpRecvStart(const char* port); NATIVE_INT_TYPE udpGet(U8* buff, NATIVE_UINT_TYPE size); }; } // end namespace Svc #endif
hpp
fprime
data/projects/fprime/Svc/ActiveRateGroup/ActiveRateGroup.hpp
/* * \author: Tim Canham * \file: * \brief * * This file implements the ActiveRateGroup component, * which invokes a set of components the comprise the rate group. * * Copyright 2014-2022, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * */ #ifndef SVC_ACTIVERATEGROUP_HPP #define SVC_ACTIVERATEGROUP_HPP #include <Svc/ActiveRateGroup/ActiveRateGroupComponentAc.hpp> namespace Svc { //! \class ActiveRateGroup //! \brief Executes a set of components as part of a rate group //! //! ActiveRateGroup takes an input cycle call to begin the rate group cycle. //! It calls each output port in succession and passes the value in the context //! array at the index corresponding to the output port number. It keeps track of the execution //! time of the rate group and detects overruns. //! class ActiveRateGroup : public ActiveRateGroupComponentBase { public: static constexpr NATIVE_INT_TYPE CONNECTION_COUNT_MAX = NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS; //! \brief ActiveRateGroup constructor //! //! The constructor of the class clears all the flags and copies the //! contents of the context array to private storage. //! //! \param compName Name of the component ActiveRateGroup(const char* compName); //! \brief ActiveRateGroup initialization function //! //! The initialization function of the class initializes the member //! ports and the component base class //! //! \param queueDepth Depth of the active component message queue //! \param instance Identifies the instance of the rate group component void init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance); //! \brief ActiveRateGroup configuration function //! //! The configuration function takes an array of context values to pass to //! members of the rate group. //! //! \param contexts Array of integers that contain the context values that will be sent //! to each member component. The index of the array corresponds to the //! output port number. //! \param numContexts The number of elements in the context array. void configure(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts); //! \brief ActiveRateGroup destructor //! //! The destructor of the class is empty ~ActiveRateGroup(); PRIVATE: //! \brief Input cycle port handler //! //! The cycle port handler calls each component in the rate group in turn, //! passing the context value. It computes the execution time each cycle, //! and writes it to a telemetry value if it reaches a maximum time //! //! \param portNum incoming port call. For this class, should always be zero //! \param cycleStart value stored by the cycle driver, used to compute execution time. void CycleIn_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart); //! \brief Input cycle port pre message hook //! //! The input cycle port pre message hook is called on the thread of the calling //! cycle port. It sets flag to indicate that the cycle has started. //! //! \param portNum incoming port call. For this class, should always be zero //! \param cycleStart value stored by the cycle driver, used to compute execution time. void CycleIn_preMsgHook(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart); //!< CycleIn pre-message hook //! \brief Input ping port handler //! //! This port is called by the health task to verify task aliveness //! //! \param portNum incoming port call. For this class, should always be zero //! \param key value returned to health task to verify round trip void PingIn_handler(NATIVE_INT_TYPE portNum, U32 key); //! \brief Task preamble //! //! This method is called prior to entering the message loop. //! It issues an event indicating that the task has started. //! void preamble(); U32 m_cycles; //!< cycles executed U32 m_maxTime; //!< maximum execution time in microseconds volatile bool m_cycleStarted; //!< indicate that cycle has started. Used to detect overruns. NATIVE_INT_TYPE m_contexts[CONNECTION_COUNT_MAX]; //!< Must match number of output ports NATIVE_INT_TYPE m_numContexts; //!< Number of contexts passed in by user NATIVE_INT_TYPE m_overrunThrottle; //!< throttle value for overrun events U32 m_cycleSlips; //!< tracks number of cycle slips }; } #endif
hpp
fprime
data/projects/fprime/Svc/ActiveRateGroup/ActiveRateGroup.cpp
/* * \author: Tim Canham * \file: * \brief * * This file implements the ActiveRateGroup component, * which invokes a set of components the comprise the rate group. * * Copyright 2014-2015, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * */ #include <Svc/ActiveRateGroup/ActiveRateGroup.hpp> #include <ActiveRateGroupCfg.hpp> #include <FpConfig.hpp> #include <Fw/Types/Assert.hpp> #include <Os/Log.hpp> namespace Svc { ActiveRateGroup::ActiveRateGroup(const char* compName) : ActiveRateGroupComponentBase(compName), m_cycles(0), m_maxTime(0), m_cycleStarted(false), m_numContexts(0), m_overrunThrottle(0), m_cycleSlips(0) { } void ActiveRateGroup::configure( NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts) { FW_ASSERT(contexts); FW_ASSERT(numContexts == this->getNum_RateGroupMemberOut_OutputPorts(),numContexts,this->getNum_RateGroupMemberOut_OutputPorts()); FW_ASSERT(FW_NUM_ARRAY_ELEMENTS(this->m_contexts) == this->getNum_RateGroupMemberOut_OutputPorts(), FW_NUM_ARRAY_ELEMENTS(this->m_contexts), this->getNum_RateGroupMemberOut_OutputPorts()); this->m_numContexts = numContexts; // copy context values for (NATIVE_INT_TYPE entry = 0; entry < this->m_numContexts; entry++) { this->m_contexts[entry] = contexts[entry]; } } void ActiveRateGroup::init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance) { ActiveRateGroupComponentBase::init(queueDepth,instance); } ActiveRateGroup::~ActiveRateGroup() { } void ActiveRateGroup::preamble() { this->log_DIAGNOSTIC_RateGroupStarted(); } void ActiveRateGroup::CycleIn_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart) { // Make sure it's been configured FW_ASSERT(this->m_numContexts); TimerVal end; this->m_cycleStarted = false; // invoke any members of the rate group for (NATIVE_INT_TYPE port = 0; port < this->m_numContexts; port++) { if (this->isConnected_RateGroupMemberOut_OutputPort(port)) { this->RateGroupMemberOut_out(port,this->m_contexts[port]); } } // grab timer for end of cycle end.take(); // get rate group execution time U32 cycle_time = end.diffUSec(cycleStart); // check to see if the time has exceeded the previous maximum if (cycle_time > this->m_maxTime) { this->m_maxTime = cycle_time; } // update cycle telemetry this->tlmWrite_RgMaxTime(this->m_maxTime); // check for cycle slip. That will happen if new cycle message has been received // which will cause flag will be set again. if (this->m_cycleStarted) { this->m_cycleSlips++; if (this->m_overrunThrottle < ACTIVE_RATE_GROUP_OVERRUN_THROTTLE) { this->log_WARNING_HI_RateGroupCycleSlip(this->m_cycles); this->m_overrunThrottle++; } // update cycle slips this->tlmWrite_RgCycleSlips(this->m_cycleSlips); } else { // if cycle is okay start decrementing throttle value if (this->m_overrunThrottle > 0) { this->m_overrunThrottle--; } } // increment cycle this->m_cycles++; } void ActiveRateGroup::CycleIn_preMsgHook(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart) { // set flag to indicate cycle has started. Check in thread for overflow. this->m_cycleStarted = true; } void ActiveRateGroup::PingIn_handler(NATIVE_INT_TYPE portNum, U32 key) { // return the key to health this->PingOut_out(0,key); } }
cpp
fprime
data/projects/fprime/Svc/ActiveRateGroup/test/ut/ActiveRateGroupImplTester.hpp
/* * \author Tim Canham * \file * \brief * * This file is the test component header for the active rate group unit test. * * Code Generated Source Code Header * * Copyright 2014-2015, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * */ #ifndef ACTIVERATEGROUP_TEST_UT_ACTIVERATEGROUPIMPLTESTER_HPP_ #define ACTIVERATEGROUP_TEST_UT_ACTIVERATEGROUPIMPLTESTER_HPP_ #include <ActiveRateGroupGTestBase.hpp> #include <Svc/ActiveRateGroup/ActiveRateGroup.hpp> namespace Svc { class ActiveRateGroupImplTester: public ActiveRateGroupGTestBase { public: ActiveRateGroupImplTester(Svc::ActiveRateGroup& inst); virtual ~ActiveRateGroupImplTester(); void init(NATIVE_INT_TYPE instance = 0); void runNominal(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts, NATIVE_INT_TYPE instance); void runCycleOverrun(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts, NATIVE_INT_TYPE instance); void runPingTest(); private: void from_RateGroupMemberOut_handler(NATIVE_INT_TYPE portNum, U32 context); //! Handler for from_PingOut //! void from_PingOut_handler( const NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 key /*!< Value to return to pinger*/ ); Svc::ActiveRateGroup& m_impl; void clearPortCalls(); struct { bool portCalled; U32 contextVal; NATIVE_UINT_TYPE order; } m_callLog[Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS]; bool m_causeOverrun; //!< flag to cause an overrun during a rate group member port call NATIVE_UINT_TYPE m_callOrder; //!< tracks order of port call. }; } /* namespace Svc */ #endif /* ACTIVERATEGROUP_TEST_UT_ACTIVERATEGROUPIMPLTESTER_HPP_ */
hpp
fprime
data/projects/fprime/Svc/ActiveRateGroup/test/ut/ActiveRateGroupImplTester.cpp
/* * \author Tim Canham * \file * \brief * * This file is the test component for the active rate group unit test. * * Code Generated Source Code Header * * Copyright 2014-2015, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * */ #include <Svc/ActiveRateGroup/test/ut/ActiveRateGroupImplTester.hpp> #include <ActiveRateGroupCfg.hpp> #include <gtest/gtest.h> #include <Fw/Test/UnitTest.hpp> #include <cstdio> #include <cstring> namespace Svc { void ActiveRateGroupImplTester::init(NATIVE_INT_TYPE instance) { ActiveRateGroupGTestBase::init(); } ActiveRateGroupImplTester::ActiveRateGroupImplTester(Svc::ActiveRateGroup& inst) : ActiveRateGroupGTestBase("testerbase",100), m_impl(inst),m_causeOverrun(false),m_callOrder(0) { this->clearPortCalls(); } void ActiveRateGroupImplTester::clearPortCalls() { memset(this->m_callLog,0,sizeof(this->m_callLog)); this->m_callOrder = 0; } ActiveRateGroupImplTester::~ActiveRateGroupImplTester() { } void ActiveRateGroupImplTester::from_RateGroupMemberOut_handler(NATIVE_INT_TYPE portNum, U32 context) { ASSERT_TRUE(portNum < static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(m_impl.m_RateGroupMemberOut_OutputPort))); this->m_callLog[portNum].portCalled = true; this->m_callLog[portNum].contextVal = context; this->m_callLog[portNum].order = this->m_callOrder++; // we can cause an overrun by calling the cycle port in the middle of the rate // group execution if (this->m_causeOverrun) { TimerVal zero(0,0); this->invoke_to_CycleIn(0,zero); this->m_causeOverrun = false; } } void ActiveRateGroupImplTester :: from_PingOut_handler( const NATIVE_INT_TYPE portNum, U32 key ) { this->pushFromPortEntry_PingOut(key); } void ActiveRateGroupImplTester::runNominal(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts, NATIVE_INT_TYPE instance) { TEST_CASE(101.1.1,"Run nominal rate group execution"); // clear events this->clearEvents(); this->clearTlm(); // call the preamble this->m_impl.preamble(); // verify "task started" event ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_RateGroupStarted_SIZE(1); Svc::TimerVal timer; timer.take(); // clear port call log this->clearPortCalls(); // verify cycle start flag is NOT set ASSERT_FALSE(this->m_impl.m_cycleStarted); // call active rate group with timer val this->invoke_to_CycleIn(0,timer); // verify cycle started flag is set ASSERT_TRUE(this->m_impl.m_cycleStarted); // call doDispatch() for ActiveRateGroup REQUIREMENT("ARG-001"); this->m_impl.doDispatch(); // verify cycle started flag is reset ASSERT_FALSE(this->m_impl.m_cycleStarted); // check calls REQUIREMENT("ARG-002"); for (NATIVE_UINT_TYPE portNum = 0; portNum < static_cast<NATIVE_UINT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_impl.m_RateGroupMemberOut_OutputPort)); portNum++) { ASSERT_TRUE(this->m_callLog[portNum].portCalled); ASSERT_EQ(this->m_callLog[portNum].contextVal,contexts[portNum]); ASSERT_EQ(this->m_callLog[portNum].order,portNum); } // Timer should be non-zero REQUIREMENT("ARG-003"); // Should have gotten write of size ASSERT_TLM_SIZE(1); // Should not have slip ASSERT_EVENTS_RateGroupCycleSlip_SIZE(0); // Should not have increased cycle slip counter ASSERT_TLM_RgCycleSlips_SIZE(0); } void ActiveRateGroupImplTester::runCycleOverrun(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts, NATIVE_INT_TYPE instance) { TEST_CASE(101.2.1,"Run cycle slip scenario"); // call the preamble this->m_impl.preamble(); // verify "task started" event ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_RateGroupStarted_SIZE(1); Svc::TimerVal timer(1,2); // run some more cycles to verify that event is sent and telemetry is updated for (NATIVE_INT_TYPE cycle = 0; cycle < ACTIVE_RATE_GROUP_OVERRUN_THROTTLE; cycle++) { // clear events this->clearEvents(); // clear port call log this->clearPortCalls(); // clear telemetry log this->clearTlm(); // verify cycle start flag is NOT set on first cycle if (0 == cycle) { ASSERT_FALSE(this->m_impl.m_cycleStarted); } else { ASSERT_TRUE(this->m_impl.m_cycleStarted); } // set flag to cause overrun this->m_causeOverrun = true; // call active rate group with timer val this->invoke_to_CycleIn(0,timer); // verify cycle started flag is set ASSERT_TRUE(this->m_impl.m_cycleStarted); // call doDispatch() for ActiveRateGroup this->m_impl.doDispatch(); // verify cycle started flag is still set ASSERT_TRUE(this->m_impl.m_cycleStarted); // verify cycle count ASSERT_EQ(this->m_impl.m_cycles,static_cast<U32>(cycle)+1); // check calls for (NATIVE_UINT_TYPE portNum = 0; portNum < static_cast<NATIVE_UINT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_impl.m_RateGroupMemberOut_OutputPort)); portNum++) { ASSERT_TRUE(this->m_callLog[portNum].portCalled == true); } REQUIREMENT("ARG-004"); // verify overrun event ASSERT_EVENTS_RateGroupCycleSlip_SIZE(1); ASSERT_EVENTS_RateGroupCycleSlip(0,static_cast<U32>(cycle)); // verify cycle slip counter is counting up ASSERT_EQ(this->m_impl.m_overrunThrottle,cycle+1); // check to see if max time was put out if (this->tlmHistory_RgMaxTime->size() == 1) { ASSERT_TLM_SIZE(2); } else { ASSERT_TLM_SIZE(1); } ASSERT_TLM_RgCycleSlips_SIZE(1); ASSERT_TLM_RgCycleSlips(0,static_cast<U32>(cycle)+1); } // Running one more time should show event throttled // clear events this->clearEvents(); // clear port call log this->clearPortCalls(); // clear telemetry log this->clearTlm(); // verify cycle start flag is NOT set on first cycle ASSERT_TRUE(this->m_impl.m_cycleStarted); // set flag to cause overrun this->m_causeOverrun = true; // call active rate group with timer val this->invoke_to_CycleIn(0,timer); // verify cycle started flag is set from previous cycle slip ASSERT_TRUE(this->m_impl.m_cycleStarted); // call doDispatch() for ActiveRateGroup this->m_impl.doDispatch(); // verify cycle started flag is still set ASSERT_TRUE(this->m_impl.m_cycleStarted); // verify cycle count ASSERT_EQ(this->m_impl.m_cycles, static_cast<U32>(ACTIVE_RATE_GROUP_OVERRUN_THROTTLE)+1); // check calls for (NATIVE_UINT_TYPE portNum = 0; portNum < static_cast<NATIVE_UINT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_impl.m_RateGroupMemberOut_OutputPort)); portNum++) { ASSERT_TRUE(this->m_callLog[portNum].portCalled == true); } // verify overrun event is NOT sent since throttled ASSERT_EVENTS_SIZE(0); ASSERT_EVENTS_RateGroupCycleSlip_SIZE(0); // verify cycle slip counter is counting up ASSERT_EQ(this->m_impl.m_overrunThrottle,ACTIVE_RATE_GROUP_OVERRUN_THROTTLE); // verify channel updated // check to see if max time was put out if (this->tlmHistory_RgMaxTime->size() == 1) { ASSERT_TLM_SIZE(2); } else { ASSERT_TLM_SIZE(1); } ASSERT_TLM_RgCycleSlips_SIZE(1); ASSERT_TLM_RgCycleSlips(0, static_cast<U32>(ACTIVE_RATE_GROUP_OVERRUN_THROTTLE)+1); // A good cycle should count down the throttle value // clear events this->clearEvents(); // clear port call log this->clearPortCalls(); // clear telemetry log this->clearTlm(); // verify cycle start flag is NOT set on first cycle ASSERT_TRUE(this->m_impl.m_cycleStarted); // set flag to prevent overrun this->m_causeOverrun = false; // call active rate group with timer val this->invoke_to_CycleIn(0,timer); // verify cycle started flag is set from previous cycle slip ASSERT_TRUE(this->m_impl.m_cycleStarted); // call doDispatch() for ActiveRateGroup this->m_impl.doDispatch(); // verify cycle started flag is not set ASSERT_FALSE(this->m_impl.m_cycleStarted); // verify cycle count ASSERT_EQ(this->m_impl.m_cycles,static_cast<U32>(ACTIVE_RATE_GROUP_OVERRUN_THROTTLE)+2); // check calls for (NATIVE_UINT_TYPE portNum = 0; portNum < static_cast<NATIVE_UINT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_impl.m_RateGroupMemberOut_OutputPort)); portNum++) { ASSERT_TRUE(this->m_callLog[portNum].portCalled == true); } // verify overrun event is NOT sent since good cycle ASSERT_EVENTS_SIZE(0); ASSERT_EVENTS_RateGroupCycleSlip_SIZE(0); // verify cycle slip counter is counting down ASSERT_EQ(this->m_impl.m_overrunThrottle,ACTIVE_RATE_GROUP_OVERRUN_THROTTLE-1); // verify channel not updated ASSERT_TLM_SIZE(0); ASSERT_TLM_RgCycleSlips_SIZE(0); // Now one more slip to verify event is sent again // clear events this->clearEvents(); // clear port call log this->clearPortCalls(); // clear telemetry log this->clearTlm(); // verify cycle start flag is set on cycle ASSERT_FALSE(this->m_impl.m_cycleStarted); // set flag to cause overrun this->m_causeOverrun = true; // call active rate group with timer val this->invoke_to_CycleIn(0,timer); // verify cycle started flag is set from port call ASSERT_TRUE(this->m_impl.m_cycleStarted); // call doDispatch() for ActiveRateGroup this->m_impl.doDispatch(); // verify cycle started flag is still set ASSERT_TRUE(this->m_impl.m_cycleStarted); // verify cycle count ASSERT_EQ(this->m_impl.m_cycles,static_cast<U32>(ACTIVE_RATE_GROUP_OVERRUN_THROTTLE)+3); // check calls for (NATIVE_UINT_TYPE portNum = 0; portNum < static_cast<NATIVE_UINT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_impl.m_RateGroupMemberOut_OutputPort)); portNum++) { ASSERT_TRUE(this->m_callLog[portNum].portCalled == true); } // verify overrun event is sent ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_RateGroupCycleSlip_SIZE(1); // verify cycle slip counter is counting up ASSERT_EQ(this->m_impl.m_overrunThrottle,ACTIVE_RATE_GROUP_OVERRUN_THROTTLE); // verify channel updated // check to see if max time was put out if (this->tlmHistory_RgMaxTime->size() == 1) { ASSERT_TLM_SIZE(2); } else { ASSERT_TLM_SIZE(1); } ASSERT_TLM_RgCycleSlips_SIZE(1); ASSERT_TLM_RgCycleSlips(0, static_cast<U32>(ACTIVE_RATE_GROUP_OVERRUN_THROTTLE)+2); } void ActiveRateGroupImplTester::runPingTest() { // invoke ping port this->invoke_to_PingIn(0,0x123); // dispatch message this->m_impl.doDispatch(); // look for return port call ASSERT_FROM_PORT_HISTORY_SIZE(1); // look for key ASSERT_from_PingOut(0, 0x123); } } /* namespace SvcTest */
cpp
fprime
data/projects/fprime/Svc/ActiveRateGroup/test/ut/ActiveRateGroupTester.cpp
/* * \author Tim Canham * \file * \brief * * This file is the test driver for the active rate group unit test. * * Code Generated Source Code Header * * Copyright 2014-2015, by the California Institute of Technology. * ALL RIGHTS RESERVED. United States Government Sponsorship * acknowledged. * */ #include <Svc/ActiveRateGroup/test/ut/ActiveRateGroupImplTester.hpp> #include <Svc/ActiveRateGroup/ActiveRateGroup.hpp> #include <Fw/Obj/SimpleObjRegistry.hpp> #include <gtest/gtest.h> #if FW_OBJECT_REGISTRATION == 1 static Fw::SimpleObjRegistry simpleReg; #endif void connectPorts(Svc::ActiveRateGroup& impl, Svc::ActiveRateGroupImplTester& tester) { tester.connect_to_CycleIn(0,impl.get_CycleIn_InputPort(0)); for (NATIVE_UINT_TYPE portNum = 0; portNum < static_cast<NATIVE_UINT_TYPE>(FW_NUM_ARRAY_ELEMENTS(impl.m_RateGroupMemberOut_OutputPort)); portNum++) { impl.set_RateGroupMemberOut_OutputPort(portNum,tester.get_from_RateGroupMemberOut(portNum)); } impl.set_Log_OutputPort(0,tester.get_from_Log(0)); impl.set_LogText_OutputPort(0,tester.get_from_LogText(0)); impl.set_Tlm_OutputPort(0,tester.get_from_Tlm(0)); impl.set_Time_OutputPort(0,tester.get_from_Time(0)); impl.set_PingOut_OutputPort(0,tester.get_from_PingOut(0)); tester.connect_to_PingIn(0,impl.get_PingIn_InputPort(0)); #if FW_PORT_TRACING // Fw::PortBase::setTrace(true); #endif // simpleReg.dump(); } TEST(ActiveRateGroupTest,NominalSchedule) { for (NATIVE_INT_TYPE inst = 0; inst < 3; inst++) { NATIVE_INT_TYPE contexts[Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS]; for (U32 i = 0; i < Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS; i++) { contexts[i] = i + 1; } Svc::ActiveRateGroup impl("ActiveRateGroup"); impl.configure(contexts,FW_NUM_ARRAY_ELEMENTS(contexts)); Svc::ActiveRateGroupImplTester tester(impl); tester.init(); impl.init(10,inst); // connect ports connectPorts(impl,tester); tester.runNominal(contexts,FW_NUM_ARRAY_ELEMENTS(contexts), inst); } } TEST(ActiveRateGroupTest,CycleOverrun) { for (NATIVE_INT_TYPE inst = 0; inst < 3; inst++) { NATIVE_INT_TYPE contexts[Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS]; for (U32 i = 0; i < Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS; i++) { contexts[i] = i + 1; } Svc::ActiveRateGroup impl("ActiveRateGroup"); impl.configure(contexts,FW_NUM_ARRAY_ELEMENTS(contexts)); Svc::ActiveRateGroupImplTester tester(impl); tester.init(); impl.init(10,inst); // connect ports connectPorts(impl,tester); tester.runCycleOverrun(contexts,FW_NUM_ARRAY_ELEMENTS(contexts), inst); } } TEST(ActiveRateGroupTest,PingPort) { NATIVE_INT_TYPE contexts[Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS]; for (U32 i = 0; i < Svc::ActiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS; i++) { contexts[i] = i + 1; } Svc::ActiveRateGroup impl("ActiveRateGroup"); impl.configure(contexts,FW_NUM_ARRAY_ELEMENTS(contexts)); Svc::ActiveRateGroupImplTester tester(impl); tester.init(); impl.init(10,0); connectPorts(impl,tester); tester.runPingTest(); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/FPrimeSequence.cpp
// ====================================================================== // \title FPrimeSequence.cpp // \author Bocchino/Canham // \brief CmdSequencerComponentImpl::FPrimeSequence implementation // // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Fw/Types/Assert.hpp" #include "Svc/CmdSequencer/CmdSequencerImpl.hpp" extern "C" { #include "Utils/Hash/libcrc/lib_crc.h" } namespace Svc { CmdSequencerComponentImpl::FPrimeSequence::CRC :: CRC() : m_computed(INITIAL_COMPUTED_VALUE), m_stored(0) { } void CmdSequencerComponentImpl::FPrimeSequence::CRC :: init() { this->m_computed = INITIAL_COMPUTED_VALUE; } void CmdSequencerComponentImpl::FPrimeSequence::CRC :: update(const BYTE* buffer, NATIVE_UINT_TYPE bufferSize) { FW_ASSERT(buffer); for(NATIVE_UINT_TYPE index = 0; index < bufferSize; index++) { this->m_computed = update_crc_32(this->m_computed, buffer[index]); } } void CmdSequencerComponentImpl::FPrimeSequence::CRC :: finalize() { this->m_computed = ~this->m_computed; } CmdSequencerComponentImpl::FPrimeSequence :: FPrimeSequence(CmdSequencerComponentImpl& component) : Sequence(component) { } bool CmdSequencerComponentImpl::FPrimeSequence :: validateCRC() { bool result = true; if (this->m_crc.m_stored != this->m_crc.m_computed) { this->m_events.fileCRCFailure( this->m_crc.m_stored, this->m_crc.m_computed ); result = false; } return result; } bool CmdSequencerComponentImpl::FPrimeSequence :: loadFile(const Fw::CmdStringArg& fileName) { // make sure there is a buffer allocated FW_ASSERT(this->m_buffer.getBuffAddr()); this->setFileName(fileName); const bool status = this->readFile() and this->validateCRC() and this->m_header.validateTime(this->m_component) and this->validateRecords(); return status; } bool CmdSequencerComponentImpl::FPrimeSequence :: hasMoreRecords() const { return this->m_buffer.getBuffLeft() > 0; } void CmdSequencerComponentImpl::FPrimeSequence :: nextRecord(Record& record) { Fw::SerializeStatus status = this->deserializeRecord(record); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); } void CmdSequencerComponentImpl::FPrimeSequence :: reset() { this->m_buffer.resetDeser(); } void CmdSequencerComponentImpl::FPrimeSequence :: clear() { this->m_buffer.resetSer(); } bool CmdSequencerComponentImpl::FPrimeSequence :: readFile() { bool result; Os::File::Status status = this->m_sequenceFile.open( this->m_fileName.toChar(), Os::File::OPEN_READ ); if (status == Os::File::OP_OK) { result = this->readOpenFile(); } else if (status == Os::File::DOESNT_EXIST) { this->m_events.fileNotFound(); result = false; } else { this->m_events.fileReadError(); result = false; } this->m_sequenceFile.close(); return result; } bool CmdSequencerComponentImpl::FPrimeSequence :: readOpenFile() { U8 *const buffAddr = this->m_buffer.getBuffAddr(); this->m_crc.init(); bool status = this->readHeader(); if (status) { this->m_crc.update(buffAddr, Sequence::Header::SERIALIZED_SIZE); status = this->deserializeHeader() and this->readRecordsAndCRC() and this->extractCRC(); } if (status) { const NATIVE_UINT_TYPE buffLen = this->m_buffer.getBuffLength(); this->m_crc.update(buffAddr, buffLen); this->m_crc.finalize(); } return status; } bool CmdSequencerComponentImpl::FPrimeSequence :: readHeader() { Os::File& file = this->m_sequenceFile; Fw::SerializeBufferBase& buffer = this->m_buffer; bool status = true; FwSignedSizeType readLen = Sequence::Header::SERIALIZED_SIZE; FW_ASSERT(readLen >= 0, readLen); const NATIVE_UINT_TYPE capacity = buffer.getBuffCapacity(); FW_ASSERT( capacity >= static_cast<NATIVE_UINT_TYPE>(readLen), capacity, readLen ); Os::File::Status fileStatus = file.read( buffer.getBuffAddr(), readLen ); if (fileStatus != Os::File::OP_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_HEADER, fileStatus ); status = false; } if (status and readLen != Sequence::Header::SERIALIZED_SIZE) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_HEADER_SIZE, readLen ); status = false; } if (status) { const Fw::SerializeStatus serializeStatus = buffer.setBuffLen(readLen); FW_ASSERT( serializeStatus == Fw::FW_SERIALIZE_OK, serializeStatus ); } return status; } bool CmdSequencerComponentImpl::FPrimeSequence :: deserializeHeader() { Fw::SerializeBufferBase& buffer = this->m_buffer; Header& header = this->m_header; // File size Fw::SerializeStatus serializeStatus = buffer.deserialize(header.m_fileSize); if (serializeStatus != Fw::FW_SERIALIZE_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::DESER_SIZE, serializeStatus ); return false; } if (header.m_fileSize > buffer.getBuffCapacity()) { this->m_events.fileSizeError(header.m_fileSize); return false; } // Number of records serializeStatus = buffer.deserialize(header.m_numRecords); if (serializeStatus != Fw::FW_SERIALIZE_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::DESER_NUM_RECORDS, serializeStatus ); return false; } // Time base FwTimeBaseStoreType tbase; serializeStatus = buffer.deserialize(tbase); if (serializeStatus != Fw::FW_SERIALIZE_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::DESER_TIME_BASE, serializeStatus ); return false; } header.m_timeBase = static_cast<TimeBase>(tbase); // Time context serializeStatus = buffer.deserialize(header.m_timeContext); if (serializeStatus != Fw::FW_SERIALIZE_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::DESER_TIME_CONTEXT, serializeStatus ); return false; } return true; } bool CmdSequencerComponentImpl::FPrimeSequence :: readRecordsAndCRC() { Os::File& file = this->m_sequenceFile; const NATIVE_UINT_TYPE size = this->m_header.m_fileSize; Fw::SerializeBufferBase& buffer = this->m_buffer; FwSignedSizeType readLen = size; Os::File::Status fileStatus = file.read( buffer.getBuffAddr(), readLen ); // check read status if (fileStatus != Os::File::OP_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_DATA, fileStatus ); return false; } // check read size if (static_cast<NATIVE_INT_TYPE>(size) != readLen) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_DATA_SIZE, readLen ); return false; } // set buffer size Fw::SerializeStatus serializeStatus = buffer.setBuffLen(size); FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, serializeStatus); return true; } bool CmdSequencerComponentImpl::FPrimeSequence :: extractCRC() { Fw::SerializeBufferBase& buffer = this->m_buffer; U32& crc = this->m_crc.m_stored; // Compute the data size const U32 buffSize = buffer.getBuffLength(); const U32 crcSize = sizeof(crc); U8 *const buffAddr = buffer.getBuffAddr(); if (buffSize < crcSize) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_CRC, buffSize ); return false; } FW_ASSERT(buffSize >= crcSize, buffSize, crcSize); const NATIVE_UINT_TYPE dataSize = buffSize - crcSize; // Create a CRC buffer pointing at the CRC in the main buffer, after the data Fw::ExternalSerializeBuffer crcBuff(&buffAddr[dataSize], crcSize); Fw::SerializeStatus status = crcBuff.setBuffLen(crcSize); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); // Deserialize the CRC from the CRC buffer status = crcBuff.deserialize(crc); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); // Set the main buffer size to the data size status = buffer.setBuffLen(dataSize); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); return true; } Fw::SerializeStatus CmdSequencerComponentImpl::FPrimeSequence :: deserializeRecord(Record& record) { U32 recordSize; Fw::SerializeStatus status = this->deserializeDescriptor(record.m_descriptor); if ( status == Fw::FW_SERIALIZE_OK and record.m_descriptor == Record::END_OF_SEQUENCE ) { return Fw::FW_SERIALIZE_OK; } if (status == Fw::FW_SERIALIZE_OK) { status = this->deserializeTimeTag(record.m_timeTag); } if (status == Fw::FW_SERIALIZE_OK) { status = this->deserializeRecordSize(recordSize); } if (status == Fw::FW_SERIALIZE_OK) { status = this->copyCommand(record.m_command, recordSize); } return status; } Fw::SerializeStatus CmdSequencerComponentImpl::FPrimeSequence :: deserializeDescriptor(Record::Descriptor& descriptor) { Fw::SerializeBufferBase& buffer = this->m_buffer; U8 descEntry; Fw::SerializeStatus status = buffer.deserialize(descEntry); if (status != Fw::FW_SERIALIZE_OK) { return status; } if (descEntry > Sequence::Record::END_OF_SEQUENCE) { return Fw::FW_DESERIALIZE_FORMAT_ERROR; } descriptor = static_cast<Record::Descriptor>(descEntry); return Fw::FW_SERIALIZE_OK; } Fw::SerializeStatus CmdSequencerComponentImpl::FPrimeSequence :: deserializeTimeTag(Fw::Time& timeTag) { Fw::SerializeBufferBase& buffer = this->m_buffer; U32 seconds, useconds; Fw::SerializeStatus status = buffer.deserialize(seconds); if (status == Fw::FW_SERIALIZE_OK) { status = buffer.deserialize(useconds); } if (status == Fw::FW_SERIALIZE_OK) { timeTag.set(seconds,useconds); } return status; } Fw::SerializeStatus CmdSequencerComponentImpl::FPrimeSequence :: deserializeRecordSize(U32& recordSize) { Fw::SerializeBufferBase& buffer = this->m_buffer; Fw::SerializeStatus status = buffer.deserialize(recordSize); if (status == Fw::FW_SERIALIZE_OK and recordSize > buffer.getBuffLeft()) { // Not enough data left status = Fw::FW_DESERIALIZE_SIZE_MISMATCH; } if ( status == Fw::FW_SERIALIZE_OK and recordSize + sizeof(FwPacketDescriptorType) > Fw::ComBuffer::SERIALIZED_SIZE ) { // Record size is too big for com buffer status = Fw::FW_DESERIALIZE_SIZE_MISMATCH; } return status; } Fw::SerializeStatus CmdSequencerComponentImpl::FPrimeSequence :: copyCommand(Fw::ComBuffer& comBuffer, const U32 recordSize) { Fw::SerializeBufferBase& buffer = this->m_buffer; comBuffer.resetSer(); NATIVE_UINT_TYPE size = recordSize; Fw::SerializeStatus status = comBuffer.setBuffLen(recordSize); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); status = buffer.deserialize(comBuffer.getBuffAddr(), size, true); return status; } bool CmdSequencerComponentImpl::FPrimeSequence :: validateRecords() { Fw::SerializeBufferBase& buffer = this->m_buffer; const U32 numRecords = this->m_header.m_numRecords; Sequence::Record record; // Deserialize all records for (NATIVE_UINT_TYPE recordNumber = 0; recordNumber < numRecords; recordNumber++) { Fw::SerializeStatus status = this->deserializeRecord(record); if (status != Fw::FW_SERIALIZE_OK) { this->m_events.recordInvalid(recordNumber, status); return false; } } // Check there is no data left const U32 buffLeftSize = buffer.getBuffLeft(); if (buffLeftSize > 0) { this->m_events.recordMismatch(numRecords, buffLeftSize); return false; } // Rewind deserialization buffer.resetDeser(); return true; } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/Events.cpp
// ====================================================================== // \title Events.cpp // \author Bocchino // \brief Implementation for CmdSequencerComponentImpl::Sequence::Events // // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Fw/Types/Assert.hpp" #include "Svc/CmdSequencer/CmdSequencerImpl.hpp" namespace Svc { CmdSequencerComponentImpl::Sequence::Events :: Events(Sequence& sequence) : m_sequence(sequence) { } void CmdSequencerComponentImpl::Sequence::Events :: fileCRCFailure(const U32 storedCRC, const U32 computedCRC) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_FileCrcFailure( logFileName, storedCRC, computedCRC ); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: fileInvalid(const CmdSequencer_FileReadStage::t stage, const I32 error) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_FileInvalid( logFileName, stage, error ); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: fileNotFound() { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_FileNotFound(logFileName); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: fileReadError() { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_FileReadError(logFileName); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: fileSizeError(const U32 size) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_FileSizeError( logFileName, size ); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: recordInvalid(const U32 recordNumber, const I32 error) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_RecordInvalid( logFileName, recordNumber, error ); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: recordMismatch(const U32 numRecords, const U32 extraBytes) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_RecordMismatch( logFileName, numRecords, extraBytes ); // TODO: Should this be an error? } void CmdSequencerComponentImpl::Sequence::Events :: timeBaseMismatch(const TimeBase currTimeBase, const TimeBase seqTimeBase) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_TimeBaseMismatch( logFileName, currTimeBase, seqTimeBase ); component.error(); } void CmdSequencerComponentImpl::Sequence::Events :: timeContextMismatch( const FwTimeContextStoreType currTimeContext, const FwTimeContextStoreType seqTimeContext ) { Fw::LogStringArg& logFileName = this->m_sequence.getLogFileName(); CmdSequencerComponentImpl& component = this->m_sequence.m_component; component.log_WARNING_HI_CS_TimeContextMismatch( logFileName, currTimeContext, seqTimeContext ); component.error(); } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/CmdSequencerImpl.hpp
// ====================================================================== // \title CmdSequencerImpl.hpp // \author Bocchino/Canham // \brief hpp file for CmdSequencer component implementation class // // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_CmdSequencerImpl_HPP #define Svc_CmdSequencerImpl_HPP #include "Fw/Com/ComBuffer.hpp" #include "Fw/Types/MemAllocator.hpp" #include "Os/File.hpp" #include "Os/ValidateFile.hpp" #include "Svc/CmdSequencer/CmdSequencerComponentAc.hpp" namespace Svc { class CmdSequencerComponentImpl : public CmdSequencerComponentBase { PRIVATE: // ---------------------------------------------------------------------- // Private enumerations // ---------------------------------------------------------------------- //! The run mode enum RunMode { STOPPED, RUNNING }; //! The step mode enum StepMode { AUTO, MANUAL }; public: // ---------------------------------------------------------------------- // Public classes // ---------------------------------------------------------------------- //! \class Sequence //! \brief A sequence with unspecified binary format class Sequence { public: //! \class Events //! \brief Sequence event reporting class Events { public: //! Construct an Events object Events( Sequence& sequence //!< The enclosing sequence ); public: //! File CRC failure void fileCRCFailure( const U32 storedCRC, //!< The CRC stored in the file const U32 computedCRC //!< The CRC computed over the file ); //! File invalid void fileInvalid( const CmdSequencer_FileReadStage::t stage, //!< The file read stage const I32 error //!< The error ); //! File not found void fileNotFound(); //! File read error void fileReadError(); //! File size error void fileSizeError( const U32 size //!< The size ); //! Record invalid void recordInvalid( const U32 recordNumber, //!< The record number const I32 error //!< The error ); //! Record mismatch void recordMismatch( const U32 numRecords, //!< The number of records in the header const U32 extraBytes //!< The number of bytes beyond last record ); //! Time base mismatch void timeBaseMismatch( const TimeBase currTimeBase, //!< The current time base const TimeBase seqTimeBase //!< The sequence file time base ); //! Time context mismatch void timeContextMismatch( const FwTimeContextStoreType currTimeContext, //!< The current time context const FwTimeContextStoreType seqTimeContext //!< The sequence file time context ); PRIVATE: //! The enclosing component Sequence& m_sequence; }; public: //! Construct a Sequence object Sequence( CmdSequencerComponentImpl& component //!< The enclosing component ); //! Destroy a Sequence object virtual ~Sequence(); public: //! \class Header //! \brief A sequence header class Header { public: enum Constants { //! Serialized size of header SERIALIZED_SIZE = sizeof(U32) + sizeof(U32) + sizeof(FwTimeBaseStoreType) + sizeof(FwTimeContextStoreType) }; public: //! Construct a Header object Header(); public: //! Validate the time field of the sequence header //! \return Success or failure bool validateTime( CmdSequencerComponentImpl& component //!< Component for time and events ); public: //! The file size U32 m_fileSize; //! The number of records in the sequence U32 m_numRecords; //! The time base of the sequence TimeBase m_timeBase; //! The context of the sequence FwTimeContextStoreType m_timeContext; }; public: //! \class Record //! \brief A sequence record class Record { public: enum Descriptor { ABSOLUTE, //!< Absolute time RELATIVE, //!< Relative time END_OF_SEQUENCE //!< end of sequence }; public: //! Construct a Record object Record() : m_descriptor(END_OF_SEQUENCE) { } public: //! The descriptor Descriptor m_descriptor; //! The time tag. NOTE: timeBase and context not filled in Fw::Time m_timeTag; //! The command Fw::ComBuffer m_command; }; public: //! Give the sequence representation a memory buffer void allocateBuffer( NATIVE_INT_TYPE identifier, //!< The identifier Fw::MemAllocator& allocator, //!< The allocator NATIVE_UINT_TYPE bytes //!< The number of bytes ); //! Deallocate the buffer void deallocateBuffer( Fw::MemAllocator& allocator //!< The allocator ); //! Set the file name. Also sets the log file name. void setFileName(const Fw::CmdStringArg& fileName); //! Get the file name //! \return The file name Fw::CmdStringArg& getFileName(); //! Get the log file name //! \return The log file name Fw::LogStringArg& getLogFileName(); //! Get the sequence header const Header& getHeader() const; //! Load a sequence file //! \return Success or failure virtual bool loadFile( const Fw::CmdStringArg& fileName //!< The file name ) = 0; //! Query whether the sequence has any more records //! \return Yes or no virtual bool hasMoreRecords() const = 0; //! Get the next record in the sequence //! Asserts on failure virtual void nextRecord( Record& record //!< The returned record ) = 0; //! Reset the sequence to the beginning. //! After calling this, hasMoreRecords should return true, //! unless the sequence has no records virtual void reset() = 0; //! Clear the sequence records. //! After calling this, hasMoreRecords should return false virtual void clear() = 0; PROTECTED: //! The enclosing component CmdSequencerComponentImpl& m_component; //! Event reporting Events m_events; //! The sequence file name Fw::CmdStringArg m_fileName; //! Copy of file name for events Fw::LogStringArg m_logFileName; //! Serialize buffer to hold the binary sequence data Fw::ExternalSerializeBuffer m_buffer; //! The allocator ID NATIVE_INT_TYPE m_allocatorId; //! The sequence header Header m_header; }; //! \class FPrimeSequence //! \brief A sequence that uses the F Prime binary format class FPrimeSequence : public Sequence { PRIVATE: enum Constants { INITIAL_COMPUTED_VALUE = 0xFFFFFFFFU }; public: //! \class CRC //! \brief Container for computed and stored CRC values struct CRC { //! Construct a CRC CRC(); //! Initialize computed CRC void init(); //! Update computed CRC void update( const BYTE* buffer, //!< The buffer NATIVE_UINT_TYPE bufferSize //!< The buffer size ); //! Finalize computed CRC void finalize(); //! Computed CRC U32 m_computed; //! Stored CRC U32 m_stored; }; public: //! Construct an FPrimeSequence FPrimeSequence( CmdSequencerComponentImpl& component //!< The enclosing component ); public: //! Load a sequence file //! \return Success or failure bool loadFile( const Fw::CmdStringArg& fileName //!< The file name ); //! Query whether the sequence has any more records //! \return Yes or no bool hasMoreRecords() const; //! Get the next record in the sequence. //! Asserts on failure void nextRecord( Record& record //!< The returned record ); //! Reset the sequence to the beginning. //! After calling this, hasMoreRecords should return true, unless //! the sequence has no records. void reset(); //! Clear the sequence records. //! After calling this, hasMoreRecords should return false. void clear(); PRIVATE: //! Read a sequence file //! \return Success or failure bool readFile(); //! Read an open sequence file //! \return Success or failure bool readOpenFile(); //! Read a binary sequence header from the sequence file //! into the buffer //! \return Success or failure bool readHeader(); //! Deserialize the binary sequence header from the buffer //! \return Success or failure bool deserializeHeader(); //! Read records and CRC into buffer //! \return Success or failure bool readRecordsAndCRC(); //! Extract CRC from record data //! \return Success or failure bool extractCRC(); //! Validate the CRC //! \return Success or failure bool validateCRC(); //! Deserialize a record from a buffer //! \return Serialize status Fw::SerializeStatus deserializeRecord( Record& record //!< The record ); //! Deserialize a record descriptor //! \return Serialize status Fw::SerializeStatus deserializeDescriptor( Record::Descriptor& descriptor //!< The descriptor ); //! Deserialize a time tag //! \return Serialize status Fw::SerializeStatus deserializeTimeTag( Fw::Time& timeTag //!< The time tag ); //! Deserialize the record size //! \return Serialize status Fw::SerializeStatus deserializeRecordSize( U32& recordSize //!< The record size ); //! Copy the serialized command into a com buffer //! \return Serialize status Fw::SerializeStatus copyCommand( Fw::ComBuffer& comBuffer, //!< The com buffer const U32 recordSize //!< The record size ); //! Validate the sequence records in the buffer //! \return Success or failure bool validateRecords(); PRIVATE: //! The CRC values CRC m_crc; //! The sequence file Os::File m_sequenceFile; }; PRIVATE: // ---------------------------------------------------------------------- // Private classes // ---------------------------------------------------------------------- //! \class Timer //! \brief A class representing a timer class Timer { PRIVATE: //! The timer state typedef enum { SET, CLEAR } State; public: //! Construct a Timer object Timer() : m_state(CLEAR) { } //! Set the expiration time void set( Fw::Time time //!< The time ) { this->m_state = SET; this->expirationTime = time; } //! Clear the timer void clear() { this->m_state = CLEAR; } //! Determine whether the timer is expired at a given time //! \return Yes or no bool isExpiredAt( Fw::Time time //!< The time ) { if (this->m_state == CLEAR) { return false; } else if ( Fw::Time::compare(this->expirationTime, time) == Fw::Time::GT ) { return false; } return true; } PRIVATE: //! The timer state State m_state; //! The expiration time Fw::Time expirationTime; }; public: // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- //! Construct a CmdSequencer CmdSequencerComponentImpl( const char* compName //!< The component name ); //! Initialize a CmdSequencer void init( const NATIVE_INT_TYPE queueDepth, //!< The queue depth const NATIVE_INT_TYPE instance //!< The instance number ); //! (Optional) Set a timeout. //! Sequence will quit if a command takes longer than the number of //! seconds in the timeout value. void setTimeout( const NATIVE_UINT_TYPE seconds //!< The number of seconds ); //! (Optional) Set the sequence format. //! CmdSequencer will use the sequence object you pass in //! to load and run sequences. By default, it uses an FPrimeSequence //! object. void setSequenceFormat( Sequence& sequence //!< The sequence object ); //! Give the sequence a memory buffer. //! Call this after constructor and init, and after setting //! the sequence format, but before task is spawned. void allocateBuffer( const NATIVE_INT_TYPE identifier, //!< The identifier Fw::MemAllocator& allocator, //!< The allocator const NATIVE_UINT_TYPE bytes //!< The number of bytes ); //! (Optional) Load a sequence to run later. //! When you call this function, the event ports must be connected. void loadSequence( const Fw::String& fileName //!< The file name ); //! Return allocated buffer. Call during shutdown. void deallocateBuffer( Fw::MemAllocator& allocator //!< The allocator ); //! Destroy a CmdDispatcherComponentBase ~CmdSequencerComponentImpl(); PRIVATE: // ---------------------------------------------------------------------- // Handler implementations for input ports // ---------------------------------------------------------------------- //! Handler for input port cmdResponseIn void cmdResponseIn_handler( NATIVE_INT_TYPE portNum, //!< The port number FwOpcodeType opcode, //!< The command opcode U32 cmdSeq, //!< The command sequence number const Fw::CmdResponse& response //!< The command response ); //! Handler for input port schedIn void schedIn_handler( NATIVE_INT_TYPE portNum, //!< The port number NATIVE_UINT_TYPE order //!< The call order ); //! Handler for input port seqRunIn void seqRunIn_handler( NATIVE_INT_TYPE portNum, //!< The port number Fw::String &filename //!< The sequence file ); //! Handler for ping port void pingIn_handler( NATIVE_INT_TYPE portNum, //!< The port number U32 key //!< Value to return to pinger ); //! Handler implementation for seqCancelIn //! void seqCancelIn_handler( const NATIVE_INT_TYPE portNum /*!< The port number*/ ); PRIVATE: // ---------------------------------------------------------------------- // Command handler implementations // ---------------------------------------------------------------------- //! Handler for command CS_AUTO //! Set the run mode to AUTO. void CS_AUTO_cmdHandler( FwOpcodeType opcode, //!< The opcode U32 cmdSeq //!< The command sequence number ); //! Handler for command CS_CANCEL //! Validate a command sequence file void CS_CANCEL_cmdHandler( FwOpcodeType opCode, //!< The opcode U32 cmdSeq //!< The command sequence number ); //! Handler for command CS_MANUAL //! Set the run mode to MANUAL. void CS_MANUAL_cmdHandler( FwOpcodeType opcode, //!< The opcode U32 cmdSeq //!< The command sequence number ); //! Handler for command CS_RUN void CS_RUN_cmdHandler( FwOpcodeType opCode, //!< The opcode U32 cmdSeq, //!< The command sequence number const Fw::CmdStringArg& fileName, //!< The file name Svc::CmdSequencer_BlockState block /*!< Return command status when complete or not*/ ); //! Handler for command CS_START //! Start running a command sequence void CS_START_cmdHandler( FwOpcodeType opcode, //!< The opcode U32 cmdSeq //!< The command sequence number ); //! Handler for command CS_STEP //! Perform one step in a command sequence. //! Valid only if SequenceRunner is in MANUAL run mode. void CS_STEP_cmdHandler( FwOpcodeType opcode, //!< The opcode U32 cmdSeq //!< The command sequence number ); //! Handler for command CS_VALIDATE //! Run a command sequence file void CS_VALIDATE_cmdHandler( FwOpcodeType opCode, //!< The opcode U32 cmdSeq, //!< The command sequence number const Fw::CmdStringArg& fileName //!< The name of the sequence file ); //! Implementation for CS_JOIN command handler //! Wait for sequences that are running to finish. //! Allow user to run multiple seq files in SEQ_NO_BLOCK mode //! then wait for them to finish before allowing more seq run request. void CS_JOIN_WAIT_cmdHandler( const FwOpcodeType opCode, /*!< The opcode*/ const U32 cmdSeq /*!< The command sequence number*/ ); PRIVATE: // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- //! Load a sequence file //! \return Success or failure bool loadFile( const Fw::CmdStringArg& fileName //!< The file name ); //! Perform a Cancel command void performCmd_Cancel(); //! Perform a Step command void performCmd_Step(); //! Perform a Step command with a relative time void performCmd_Step_RELATIVE( Fw::Time& currentTime //!< The time ); //! Perform a Step command with an absolute time void performCmd_Step_ABSOLUTE( Fw::Time& currentTime //!< The time ); //! Record a completed command void commandComplete( const U32 opCode //!< The opcode ); //! Record a sequence complete event void sequenceComplete(); //! Record an error void error(); //! Record an error in executing a sequence command void commandError( const U32 number, //!< The command number const U32 opCode, //!< The command opcode const U32 error //!< The error code ); //! Require a run mode //! \return Whether we are in the correct mode bool requireRunMode( RunMode mode //!< The required mode ); //! Set command timeout timer void setCmdTimeout( const Fw::Time &currentTime //!< The current time ); PRIVATE: // ---------------------------------------------------------------------- // Private member variables // ---------------------------------------------------------------------- //! The F Prime sequence FPrimeSequence m_FPrimeSequence; //! The abstract sequence Sequence *m_sequence; //! The number of Load commands executed U32 m_loadCmdCount; //! The number of Cancel commands executed U32 m_cancelCmdCount; //! The number of errors U32 m_errorCount; //! The run mode RunMode m_runMode; //! The step mode StepMode m_stepMode; //! The sequence record currently being processed Sequence::Record m_record; //! The command time timer Timer m_cmdTimer; //! The number of commands executed in this sequence U32 m_executedCount; //! The total number of commands executed across all sequences U32 m_totalExecutedCount; //! The total number of sequences completed U32 m_sequencesCompletedCount; //! timeout value NATIVE_UINT_TYPE m_timeout; //! timeout timer Timer m_cmdTimeoutTimer; //! Block mode for command status Svc::CmdSequencer_BlockState::t m_blockState; FwOpcodeType m_opCode; U32 m_cmdSeq; bool m_join_waiting; }; } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/CmdSequencer.hpp
// ====================================================================== // CmdSequencer.hpp // Standardization header for CmdSequencer // ====================================================================== #ifndef Svc_CmdSequencer_HPP #define Svc_CmdSequencer_HPP #include "Svc/CmdSequencer/CmdSequencerImpl.hpp" namespace Svc { typedef CmdSequencerComponentImpl CmdSequencer; } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/Sequence.cpp
// ====================================================================== // \title Sequence.cpp // \author Bocchino/Canham // \brief Implementation file for CmdSequencer::Sequence // // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include <Fw/Types/Assert.hpp> #include <Svc/CmdSequencer/CmdSequencerImpl.hpp> namespace Svc { CmdSequencerComponentImpl::Sequence :: Sequence(CmdSequencerComponentImpl& component) : m_component(component), m_events(*this), m_allocatorId(0) { } CmdSequencerComponentImpl::Sequence :: ~Sequence() { } CmdSequencerComponentImpl::Sequence::Header :: Header() : m_fileSize(0), m_numRecords(0), m_timeBase(TB_DONT_CARE), m_timeContext(FW_CONTEXT_DONT_CARE) { } bool CmdSequencerComponentImpl::Sequence::Header :: validateTime(CmdSequencerComponentImpl& component) { Fw::Time validTime = component.getTime(); Events& events = component.m_sequence->m_events; // Time base const TimeBase validTimeBase = validTime.getTimeBase(); if ( (this->m_timeBase != validTimeBase) and (this->m_timeBase != TB_DONT_CARE) ) { events.timeBaseMismatch( validTimeBase, this->m_timeBase ); return false; } // Time context const FwTimeContextStoreType validContext = validTime.getContext(); if ( (this->m_timeContext != validContext) and (this->m_timeContext != FW_CONTEXT_DONT_CARE) ) { events.timeContextMismatch( validContext, this->m_timeContext ); return false; } // Canonicalize time this->m_timeBase = validTimeBase; this->m_timeContext = validContext; return true; } void CmdSequencerComponentImpl::Sequence :: allocateBuffer( NATIVE_INT_TYPE identifier, Fw::MemAllocator& allocator, NATIVE_UINT_TYPE bytes ) { // has to be at least as big as a header FW_ASSERT(bytes >= Sequence::Header::SERIALIZED_SIZE); bool recoverable; this->m_allocatorId = identifier; this->m_buffer.setExtBuffer( static_cast<U8*>(allocator.allocate(identifier,bytes,recoverable)), bytes ); } void CmdSequencerComponentImpl::Sequence :: deallocateBuffer(Fw::MemAllocator& allocator) { allocator.deallocate( this->m_allocatorId, this->m_buffer.getBuffAddr() ); this->m_buffer.clear(); } const CmdSequencerComponentImpl::Sequence::Header& CmdSequencerComponentImpl::Sequence :: getHeader() const { return this->m_header; } void CmdSequencerComponentImpl::Sequence :: setFileName(const Fw::CmdStringArg& fileName) { this->m_fileName = fileName; this->m_logFileName = fileName; } Fw::CmdStringArg& CmdSequencerComponentImpl::Sequence :: getFileName() { return this->m_fileName; } Fw::LogStringArg& CmdSequencerComponentImpl::Sequence :: getLogFileName() { return this->m_logFileName; } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/CmdSequencerImpl.cpp
// ====================================================================== // \title CmdSequencerImpl.cpp // \author Bocchino/Canham // \brief cpp file for CmdDispatcherComponentBase component implementation class // // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #include <Fw/Types/Assert.hpp> #include <Fw/Types/SerialBuffer.hpp> #include <Svc/CmdSequencer/CmdSequencerImpl.hpp> #include <Fw/Com/ComPacket.hpp> #include <Fw/Types/Serializable.hpp> extern "C" { #include <Utils/Hash/libcrc/lib_crc.h> } namespace Svc { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- CmdSequencerComponentImpl:: CmdSequencerComponentImpl(const char* name) : CmdSequencerComponentBase(name), m_FPrimeSequence(*this), m_sequence(&this->m_FPrimeSequence), m_loadCmdCount(0), m_cancelCmdCount(0), m_errorCount(0), m_runMode(STOPPED), m_stepMode(AUTO), m_executedCount(0), m_totalExecutedCount(0), m_sequencesCompletedCount(0), m_timeout(0), m_blockState(Svc::CmdSequencer_BlockState::NO_BLOCK), m_opCode(0), m_cmdSeq(0), m_join_waiting(false) { } void CmdSequencerComponentImpl::init(const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE instance) { CmdSequencerComponentBase::init(queueDepth, instance); } void CmdSequencerComponentImpl::setTimeout(const NATIVE_UINT_TYPE timeout) { this->m_timeout = timeout; } void CmdSequencerComponentImpl :: setSequenceFormat(Sequence& sequence) { this->m_sequence = &sequence; } void CmdSequencerComponentImpl :: allocateBuffer( const NATIVE_INT_TYPE identifier, Fw::MemAllocator& allocator, const NATIVE_UINT_TYPE bytes ) { this->m_sequence->allocateBuffer(identifier, allocator, bytes); } void CmdSequencerComponentImpl :: loadSequence(const Fw::String& fileName) { FW_ASSERT(this->m_runMode == STOPPED, this->m_runMode); if (not this->loadFile(fileName)) { this->m_sequence->clear(); } } void CmdSequencerComponentImpl :: deallocateBuffer(Fw::MemAllocator& allocator) { this->m_sequence->deallocateBuffer(allocator); } CmdSequencerComponentImpl::~CmdSequencerComponentImpl() { } // ---------------------------------------------------------------------- // Handler implementations // ---------------------------------------------------------------------- void CmdSequencerComponentImpl::CS_RUN_cmdHandler( FwOpcodeType opCode, U32 cmdSeq, const Fw::CmdStringArg& fileName, Svc::CmdSequencer_BlockState block) { if (not this->requireRunMode(STOPPED)) { if (m_join_waiting) { // Inform user previous seq file is not complete this->log_WARNING_HI_CS_JoinWaitingNotComplete(); } this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); return; } this->m_blockState = block.e; this->m_cmdSeq = cmdSeq; this->m_opCode = opCode; // load commands if (not this->loadFile(fileName)) { this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); return; } this->m_executedCount = 0; // Check the step mode. If it is auto, start the sequence if (AUTO == this->m_stepMode) { this->m_runMode = RUNNING; this->performCmd_Step(); } if (Svc::CmdSequencer_BlockState::NO_BLOCK == this->m_blockState) { this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); } } void CmdSequencerComponentImpl::CS_VALIDATE_cmdHandler( FwOpcodeType opCode, U32 cmdSeq, const Fw::CmdStringArg& fileName ) { if (!this->requireRunMode(STOPPED)) { this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); return; } // load commands if (not this->loadFile(fileName)) { this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); return; } // clear the buffer this->m_sequence->clear(); this->log_ACTIVITY_HI_CS_SequenceValid(this->m_sequence->getLogFileName()); this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); } //! Handler for input port seqRunIn void CmdSequencerComponentImpl::seqRunIn_handler( NATIVE_INT_TYPE portNum, Fw::String &filename ) { if (!this->requireRunMode(STOPPED)) { this->seqDone_out(0,0,0,Fw::CmdResponse::EXECUTION_ERROR); return; } // If file name is non-empty, load a file. // Empty file name means don't load. if (filename != "") { Fw::CmdStringArg cmdStr(filename); const bool status = this->loadFile(cmdStr); if (!status) { this->seqDone_out(0,0,0,Fw::CmdResponse::EXECUTION_ERROR); return; } } else if (not this->m_sequence->hasMoreRecords()) { // No sequence loaded this->log_WARNING_LO_CS_NoSequenceActive(); this->error(); this->seqDone_out(0,0,0,Fw::CmdResponse::EXECUTION_ERROR); return; } this->m_executedCount = 0; // Check the step mode. If it is auto, start the sequence if (AUTO == this->m_stepMode) { this->m_runMode = RUNNING; this->performCmd_Step(); } this->log_ACTIVITY_HI_CS_PortSequenceStarted(this->m_sequence->getLogFileName()); } void CmdSequencerComponentImpl :: seqCancelIn_handler( const NATIVE_INT_TYPE portNum ) { if (RUNNING == this->m_runMode) { this->performCmd_Cancel(); this->log_ACTIVITY_HI_CS_SequenceCanceled(this->m_sequence->getLogFileName()); ++this->m_cancelCmdCount; this->tlmWrite_CS_CancelCommands(this->m_cancelCmdCount); } else { this->log_WARNING_LO_CS_NoSequenceActive(); } } void CmdSequencerComponentImpl::CS_CANCEL_cmdHandler( FwOpcodeType opCode, U32 cmdSeq) { if (RUNNING == this->m_runMode) { this->performCmd_Cancel(); this->log_ACTIVITY_HI_CS_SequenceCanceled(this->m_sequence->getLogFileName()); ++this->m_cancelCmdCount; this->tlmWrite_CS_CancelCommands(this->m_cancelCmdCount); } else { this->log_WARNING_LO_CS_NoSequenceActive(); } this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK); } void CmdSequencerComponentImpl::CS_JOIN_WAIT_cmdHandler( const FwOpcodeType opCode, const U32 cmdSeq) { // If there is no running sequence do not wait if (m_runMode != RUNNING) { this->log_WARNING_LO_CS_NoSequenceActive(); this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK); return; } else { m_join_waiting = true; Fw::LogStringArg& logFileName = this->m_sequence->getLogFileName(); this->log_ACTIVITY_HI_CS_JoinWaiting(logFileName, m_cmdSeq, m_opCode); m_cmdSeq = cmdSeq; m_opCode = opCode; } } // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- bool CmdSequencerComponentImpl :: loadFile(const Fw::CmdStringArg& fileName) { const bool status = this->m_sequence->loadFile(fileName); if (status) { Fw::LogStringArg& logFileName = this->m_sequence->getLogFileName(); this->log_ACTIVITY_LO_CS_SequenceLoaded(logFileName); ++this->m_loadCmdCount; this->tlmWrite_CS_LoadCommands(this->m_loadCmdCount); } return status; } void CmdSequencerComponentImpl::error() { ++this->m_errorCount; this->tlmWrite_CS_Errors(m_errorCount); } void CmdSequencerComponentImpl::performCmd_Cancel() { this->m_sequence->reset(); this->m_runMode = STOPPED; this->m_cmdTimer.clear(); this->m_cmdTimeoutTimer.clear(); this->m_executedCount = 0; // write sequence done port with error, if connected if (this->isConnected_seqDone_OutputPort(0)) { this->seqDone_out(0,0,0,Fw::CmdResponse::EXECUTION_ERROR); } if (Svc::CmdSequencer_BlockState::BLOCK == this->m_blockState || m_join_waiting) { // Do not wait if sequence was canceled or a cmd failed this->m_join_waiting = false; this->cmdResponse_out(this->m_opCode, this->m_cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); } this->m_blockState = Svc::CmdSequencer_BlockState::NO_BLOCK; } void CmdSequencerComponentImpl :: cmdResponseIn_handler( NATIVE_INT_TYPE portNum, FwOpcodeType opcode, U32 cmdSeq, const Fw::CmdResponse& response ) { if (this->m_runMode == STOPPED) { // Sequencer is not running this->log_WARNING_HI_CS_UnexpectedCompletion(opcode); } else { // clear command timeout this->m_cmdTimeoutTimer.clear(); if (response != Fw::CmdResponse::OK) { this->commandError(this->m_executedCount, opcode, response.e); this->performCmd_Cancel(); } else if (this->m_runMode == RUNNING && this->m_stepMode == AUTO) { // Auto mode this->commandComplete(opcode); if (not this->m_sequence->hasMoreRecords()) { // No data left this->m_runMode = STOPPED; this->sequenceComplete(); } else { this->performCmd_Step(); } } else { // Manual step mode this->commandComplete(opcode); if (not this->m_sequence->hasMoreRecords()) { this->m_runMode = STOPPED; this->sequenceComplete(); } } } } void CmdSequencerComponentImpl :: schedIn_handler(NATIVE_INT_TYPE portNum, NATIVE_UINT_TYPE order) { Fw::Time currTime = this->getTime(); // check to see if a command time is pending if (this->m_cmdTimer.isExpiredAt(currTime)) { this->comCmdOut_out(0, m_record.m_command, 0); this->m_cmdTimer.clear(); // start command timeout timer this->setCmdTimeout(currTime); } else if (this->m_cmdTimeoutTimer.isExpiredAt(this->getTime())) { // check for command timeout this->log_WARNING_HI_CS_SequenceTimeout( m_sequence->getLogFileName(), this->m_executedCount ); // If there is a command timeout, cancel the sequence this->performCmd_Cancel(); } } void CmdSequencerComponentImpl :: CS_START_cmdHandler(FwOpcodeType opcode, U32 cmdSeq) { if (not this->m_sequence->hasMoreRecords()) { // No sequence loaded this->log_WARNING_LO_CS_NoSequenceActive(); this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); return; } if (!this->requireRunMode(STOPPED)) { this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); return; } this->m_blockState = Svc::CmdSequencer_BlockState::NO_BLOCK; this->m_runMode = RUNNING; this->performCmd_Step(); this->log_ACTIVITY_HI_CS_CmdStarted(this->m_sequence->getLogFileName()); this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::OK); } void CmdSequencerComponentImpl :: CS_STEP_cmdHandler(FwOpcodeType opcode, U32 cmdSeq) { if (this->requireRunMode(RUNNING)) { this->performCmd_Step(); // check for special case where end of sequence entry was encountered if (this->m_runMode != STOPPED) { this->log_ACTIVITY_HI_CS_CmdStepped( this->m_sequence->getLogFileName(), this->m_executedCount ); } this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::OK); } else { this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); } } void CmdSequencerComponentImpl :: CS_AUTO_cmdHandler(FwOpcodeType opcode, U32 cmdSeq) { if (this->requireRunMode(STOPPED)) { this->m_stepMode = AUTO; this->log_ACTIVITY_HI_CS_ModeSwitched(CmdSequencer_SeqMode::AUTO); this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::OK); } else { this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); } } void CmdSequencerComponentImpl :: CS_MANUAL_cmdHandler(FwOpcodeType opcode, U32 cmdSeq) { if (this->requireRunMode(STOPPED)) { this->m_stepMode = MANUAL; this->log_ACTIVITY_HI_CS_ModeSwitched(CmdSequencer_SeqMode::STEP); this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::OK); } else { this->cmdResponse_out(opcode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR); } } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- bool CmdSequencerComponentImpl::requireRunMode(RunMode mode) { if (this->m_runMode == mode) { return true; } else { this->log_WARNING_HI_CS_InvalidMode(); return false; } } void CmdSequencerComponentImpl :: commandError( const U32 number, const U32 opCode, const U32 error ) { this->log_WARNING_HI_CS_CommandError( this->m_sequence->getLogFileName(), number, opCode, error ); this->error(); } void CmdSequencerComponentImpl::performCmd_Step() { this->m_sequence->nextRecord(m_record); // set clock time base and context from value set when sequence was loaded const Sequence::Header& header = this->m_sequence->getHeader(); this->m_record.m_timeTag.setTimeBase(header.m_timeBase); this->m_record.m_timeTag.setTimeContext(header.m_timeContext); Fw::Time currentTime = this->getTime(); switch (this->m_record.m_descriptor) { case Sequence::Record::END_OF_SEQUENCE: this->m_runMode = STOPPED; this->sequenceComplete(); break; case Sequence::Record::RELATIVE: this->performCmd_Step_RELATIVE(currentTime); break; case Sequence::Record::ABSOLUTE: this->performCmd_Step_ABSOLUTE(currentTime); break; default: FW_ASSERT(0, m_record.m_descriptor); } } void CmdSequencerComponentImpl::sequenceComplete() { ++this->m_sequencesCompletedCount; // reset buffer this->m_sequence->clear(); this->log_ACTIVITY_HI_CS_SequenceComplete(this->m_sequence->getLogFileName()); this->tlmWrite_CS_SequencesCompleted(this->m_sequencesCompletedCount); this->m_executedCount = 0; // write sequence done port, if connected if (this->isConnected_seqDone_OutputPort(0)) { this->seqDone_out(0,0,0,Fw::CmdResponse::OK); } if (Svc::CmdSequencer_BlockState::BLOCK == this->m_blockState || m_join_waiting) { this->cmdResponse_out(this->m_opCode, this->m_cmdSeq, Fw::CmdResponse::OK); } m_join_waiting = false; this->m_blockState = Svc::CmdSequencer_BlockState::NO_BLOCK; } void CmdSequencerComponentImpl::commandComplete(const U32 opcode) { this->log_ACTIVITY_LO_CS_CommandComplete( this->m_sequence->getLogFileName(), this->m_executedCount, opcode ); ++this->m_executedCount; ++this->m_totalExecutedCount; this->tlmWrite_CS_CommandsExecuted(this->m_totalExecutedCount); } void CmdSequencerComponentImpl :: performCmd_Step_RELATIVE(Fw::Time& currentTime) { this->m_record.m_timeTag.add(currentTime.getSeconds(),currentTime.getUSeconds()); this->performCmd_Step_ABSOLUTE(currentTime); } void CmdSequencerComponentImpl :: performCmd_Step_ABSOLUTE(Fw::Time& currentTime) { if (currentTime >= this->m_record.m_timeTag) { this->comCmdOut_out(0, m_record.m_command, 0); this->setCmdTimeout(currentTime); } else { this->m_cmdTimer.set(this->m_record.m_timeTag); } } void CmdSequencerComponentImpl :: pingIn_handler( NATIVE_INT_TYPE portNum, /*!< The port number*/ U32 key /*!< Value to return to pinger*/ ) { // send ping response this->pingOut_out(0,key); } void CmdSequencerComponentImpl :: setCmdTimeout(const Fw::Time &currentTime) { // start timeout timer if enabled and not in step mode if ((this->m_timeout > 0) and (AUTO == this->m_stepMode)) { Fw::Time expTime = currentTime; expTime.add(this->m_timeout,0); this->m_cmdTimeoutTimer.set(expTime); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/formats/AMPCSSequence.cpp
// \title AMPCSSequence.cpp // \author Rob Bocchino // \brief AMPCSSequence implementation // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #include "Fw/Com/ComPacket.hpp" #include "Fw/Types/Assert.hpp" #include "Os/FileSystem.hpp" #include "Svc/CmdSequencer/formats/AMPCSSequence.hpp" extern "C" { #include "Utils/Hash/libcrc/lib_crc.h" } namespace Svc { AMPCSSequence :: AMPCSSequence(CmdSequencerComponentImpl& component) : CmdSequencerComponentImpl::Sequence(component) { } bool AMPCSSequence :: loadFile(const Fw::CmdStringArg& fileName) { // Make sure there is a buffer allocated FW_ASSERT(this->m_buffer.getBuffAddr()); Fw::CmdStringArg crcFileName = fileName; crcFileName += ".CRC32"; this->m_header.m_timeBase = TB_DONT_CARE; this->m_header.m_timeContext = FW_CONTEXT_DONT_CARE; const bool status = this->readCRCFile(crcFileName) and this->getFileSize(fileName) and this->readSequenceFile(fileName) and this->validateCRC() and this->m_header.validateTime(this->m_component) and this->validateRecords(); return status; } bool AMPCSSequence :: readCRCFile(Fw::CmdStringArg& crcFileName) { bool result; this->setFileName(crcFileName); Os::File::Status status = this->m_crcFile.open( crcFileName.toChar(), Os::File::OPEN_READ ); if (status == Os::File::OP_OK) { result = this->readCRC() and this->deserializeCRC(); } else if (status == Os::File::DOESNT_EXIST) { this->m_events.fileNotFound(); result = false; } else { this->m_events.fileReadError(); result = false; } this->m_crcFile.close(); return result; } bool AMPCSSequence :: getFileSize(const Fw::CmdStringArg& seqFileName) { bool status = true; FwSignedSizeType fileSize; this->setFileName(seqFileName); const Os::FileSystem::Status fileStatus = Os::FileSystem::getFileSize(this->m_fileName.toChar(), fileSize); if ( fileStatus == Os::FileSystem::OP_OK and fileSize >= static_cast<FwSignedSizeType>(sizeof(this->m_sequenceHeader)) ) { this->m_header.m_fileSize = static_cast<U32>(fileSize - sizeof(this->m_sequenceHeader)); } else { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_HEADER_SIZE, fileStatus ); status = false; } return status; } bool AMPCSSequence :: readSequenceFile(const Fw::CmdStringArg& seqFileName) { bool result; this->setFileName(seqFileName); Os::File::Status status = this->m_sequenceFile.open( this->m_fileName.toChar(), Os::File::OPEN_READ ); if (status == Os::File::OP_OK) { result = this->readOpenSequenceFile(); } else if (status == Os::File::DOESNT_EXIST) { this->m_events.fileNotFound(); result = false; } else { this->m_events.fileReadError(); result = false; } this->m_sequenceFile.close(); return result; } bool AMPCSSequence :: validateCRC() { bool result = true; if (this->m_crc.m_stored != this->m_crc.m_computed) { this->m_events.fileCRCFailure( this->m_crc.m_stored, this->m_crc.m_computed ); result = false; } return result; } bool AMPCSSequence :: validateRecords() { Fw::SerializeBufferBase& buffer = this->m_buffer; Sequence::Record record; // Deserialize all records and count the records const NATIVE_UINT_TYPE loopBound = buffer.getBuffLeft(); U32 numRecords = 0; for ( ; numRecords < loopBound; ++numRecords) { if (not this->hasMoreRecords()) { break; } Fw::SerializeStatus status = this->deserializeRecord(record); if (status != Fw::FW_SERIALIZE_OK) { this->m_events.recordInvalid(numRecords, status); return false; } } // Set the number of records this->m_header.m_numRecords = numRecords; // Reset deserialization this->reset(); return true; } bool AMPCSSequence :: hasMoreRecords() const { return this->m_buffer.getBuffLeft() > 0; } void AMPCSSequence :: nextRecord(Sequence::Record& record) { Fw::SerializeStatus status = this->deserializeRecord(record); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); } void AMPCSSequence :: reset() { this->m_buffer.resetDeser(); } void AMPCSSequence :: clear() { this->m_buffer.resetSer(); } bool AMPCSSequence :: readCRC() { Os::File& file = this->m_crcFile; Fw::SerializeBufferBase& buffer = this->m_buffer; bool status = true; Fw::SerializeStatus ser_status; FwSignedSizeType readLen = sizeof(U32); FW_ASSERT(readLen >= 0, readLen); ser_status = buffer.setBuffLen(readLen); FW_ASSERT(ser_status == Fw::FW_SERIALIZE_OK, ser_status); U8 *const addr = buffer.getBuffAddr(); Os::File::Status fileStatus = file.read(addr, readLen); if (fileStatus != Os::File::OP_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_CRC, fileStatus ); status = false; } return status; } bool AMPCSSequence :: deserializeCRC() { bool status = true; Fw::SerializeStatus serializeStatus = this->m_buffer.deserialize(this->m_crc.m_stored); if (serializeStatus != Fw::FW_SERIALIZE_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_CRC, serializeStatus ); status = false; } return status; } bool AMPCSSequence :: readOpenSequenceFile() { this->m_buffer.resetSer(); this->m_crc.init(); bool status = this->readSequenceHeader(); if (status) { this->m_crc.update( this->m_sequenceHeader, sizeof(this->m_sequenceHeader) ); status = this->readRecords(); } if (status) { U8 *const buffAddr = this->m_buffer.getBuffAddr(); const NATIVE_UINT_TYPE buffLen = this->m_buffer.getBuffLength(); FW_ASSERT( buffLen == this->m_header.m_fileSize, buffLen, this->m_header.m_fileSize ); this->m_crc.update(buffAddr, buffLen); this->m_crc.finalize(); } return status; } bool AMPCSSequence :: readSequenceHeader() { Os::File& file = this->m_sequenceFile; bool status = true; FwSignedSizeType readLen = sizeof this->m_sequenceHeader; const Os::File::Status fileStatus = file.read( this->m_sequenceHeader, readLen ); if (fileStatus != Os::File::OP_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_HEADER, fileStatus ); status = false; } if (status and readLen != sizeof this->m_sequenceHeader) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_HEADER_SIZE, readLen ); status = false; } return status; } bool AMPCSSequence :: readRecords() { Os::File& file = this->m_sequenceFile; const NATIVE_UINT_TYPE size = this->m_header.m_fileSize; Fw::SerializeBufferBase& buffer = this->m_buffer; U8 *const addr = buffer.getBuffAddr(); // Check file size if (size > this->m_buffer.getBuffCapacity()) { this->m_events.fileSizeError(size); return false; } FwSignedSizeType readLen = size; const Os::File::Status fileStatus = file.read(addr, readLen); // Check read status if (fileStatus != Os::File::OP_OK) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_DATA, fileStatus ); return false; } // Check read size const NATIVE_UINT_TYPE readLenUint = readLen; if (readLenUint != size) { this->m_events.fileInvalid( CmdSequencer_FileReadStage::READ_SEQ_DATA_SIZE, readLen ); return false; } // set buffer size const Fw::SerializeStatus serializeStatus = buffer.setBuffLen(size); FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, serializeStatus); return true; } Fw::SerializeStatus AMPCSSequence :: deserializeRecord(Sequence::Record& record) { Record::CmdLength::t cmdLength; Fw::SerializeStatus status = this->deserializeTimeFlag(record.m_descriptor); if (status == Fw::FW_SERIALIZE_OK) { status = this->deserializeTime(record.m_timeTag); } if (status == Fw::FW_SERIALIZE_OK) { status = this->deserializeCmdLength(cmdLength); } if (status == Fw::FW_SERIALIZE_OK) { status = this->translateCommand(record.m_command, cmdLength); } return status; } Fw::SerializeStatus AMPCSSequence :: deserializeTimeFlag(Sequence::Record::Descriptor& descriptor) { Fw::SerializeBufferBase& buffer = this->m_buffer; Record::TimeFlag::Serial::t timeFlagSerial; Fw::SerializeStatus status = buffer.deserialize(timeFlagSerial); if (status == Fw::FW_SERIALIZE_OK) { switch (timeFlagSerial) { case Record::TimeFlag::ABSOLUTE: descriptor = Sequence::Record::ABSOLUTE; break; case Record::TimeFlag::RELATIVE: descriptor = Sequence::Record::RELATIVE; break; default: status = Fw::FW_DESERIALIZE_FORMAT_ERROR; break; } } return status; } Fw::SerializeStatus AMPCSSequence :: deserializeTime(Fw::Time& timeTag) { Record::Time::t time; Fw::SerializeBufferBase& buffer = this->m_buffer; Fw::SerializeStatus status = buffer.deserialize(time); if (status == Fw::FW_SERIALIZE_OK) { timeTag.set(time, 0); } return status; } Fw::SerializeStatus AMPCSSequence :: deserializeCmdLength(Record::CmdLength::t& cmdLength) { Fw::SerializeBufferBase& buffer = this->m_buffer; Fw::SerializeStatus status = buffer.deserialize(cmdLength); if (status == Fw::FW_SERIALIZE_OK and cmdLength > buffer.getBuffLeft()) { // Not enough data left status = Fw::FW_DESERIALIZE_SIZE_MISMATCH; } if ( status == Fw::FW_SERIALIZE_OK and sizeof(FwPacketDescriptorType) + sizeof(U16) + cmdLength > Fw::ComBuffer::SERIALIZED_SIZE ) { // Record size is too big for com buffer status = Fw::FW_DESERIALIZE_SIZE_MISMATCH; } return status; } Fw::SerializeStatus AMPCSSequence :: translateCommand( Fw::ComBuffer& comBuffer, const Record::CmdLength::t cmdLength ) { Fw::SerializeBufferBase& buffer = this->m_buffer; comBuffer.resetSer(); // Serialize the command packet descriptor const FwPacketDescriptorType cmdDescriptor = Fw::ComPacket::FW_PACKET_COMMAND; Fw::SerializeStatus status = comBuffer.serialize(cmdDescriptor); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); // Zero-extend the two-byte AMPCS opcode by two bytes const U16 zeros = 0; status = comBuffer.serialize(zeros); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); // Set the buffer length const U32 fixedBuffLen = comBuffer.getBuffLength(); FW_ASSERT( fixedBuffLen == sizeof(cmdDescriptor) + sizeof(zeros), fixedBuffLen ); const U32 totalBuffLen = fixedBuffLen + cmdLength; status = comBuffer.setBuffLen(totalBuffLen); FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status); // Copy the opcode and argument bytes NATIVE_UINT_TYPE size = cmdLength; U8 *const addr = comBuffer.getBuffAddr(); FW_ASSERT(addr != nullptr); // true means "don't serialize the length" status = buffer.deserialize(&addr[fixedBuffLen], size, true); return status; } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/formats/AMPCSSequence.hpp
// ====================================================================== // \title AMPCSSequence.hpp // \author Bocchino // \brief AMPCSSequence interface // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef Svc_AMPCSSequence_HPP #define Svc_AMPCSSequence_HPP #include "Svc/CmdSequencer/CmdSequencerImpl.hpp" namespace Svc { //! \class AMPCSSequence //! \brief A sequence in AMPCS format class AMPCSSequence : public CmdSequencerComponentImpl::Sequence { public: //! AMPCS sequence header struct SequenceHeader { struct Constants { typedef enum { //! The sequence header size in bytes SIZE = 4 } t; }; typedef U8 t[Constants::SIZE]; }; //! AMPCS sequence record struct Record { //! Time flag struct TimeFlag { //! The time flag type typedef enum { ABSOLUTE = 0x00, RELATIVE = 0xFF } t; //! The serial representation of a time flag struct Serial { typedef U8 t; }; }; //! Time struct Time { //! The type of the time field typedef U32 t; }; //! Command length struct CmdLength { //! The type of the command length field typedef U16 t; }; //! Opcode struct Opcode { //! The type of an AMPCS command opcode typedef U16 t; }; }; public: //! Construct an AMPCSSequence AMPCSSequence( CmdSequencerComponentImpl& component //!< The enclosing component ); public: //! Load a sequence file //! \return Success or failure bool loadFile( const Fw::CmdStringArg& fileName //!< The file name ); //! Query whether the sequence has any more records //! \return Yes or no bool hasMoreRecords() const; //! Get the next record in the sequence. //! Asserts on failure void nextRecord( Sequence::Record& record //!< The returned record ); //! Reset the sequence to the beginning. //! After calling this, hasMoreRecords should return true, unless //! the sequence has no records. void reset(); //! Clear the sequence records. //! After calling this, hasMoreRecords should return false. void clear(); PRIVATE: //! Read a CRC file //! \return Success or failure bool readCRCFile( Fw::CmdStringArg& crcFileName //!< The CRC file name ); //! Read the CRC out of an open CRC file //! \return Success or failure bool readCRC(); //! Deserialize the CRC //! \return Success or failure bool deserializeCRC(); //! Get the aggregate size of the command records //! \return Success or failure bool getFileSize( const Fw::CmdStringArg& seqFileName //!< The sequence file name ); //! Read a sequence file //! \return Success or failure bool readSequenceFile( const Fw::CmdStringArg& seqFileName //!< The sequence file name ); //! Read an open sequence file //! \return Success or failure bool readOpenSequenceFile(); //! Read the sequence header from the sequence file //! into the buffer //! \return Success or failure bool readSequenceHeader(); //! Read records into buffer //! \return Success or failure bool readRecords(); //! Validate the CRC //! \return Success or failure bool validateCRC(); //! Deserialize a record from a buffer //! \return Serialize status Fw::SerializeStatus deserializeRecord( Sequence::Record& record //!< The record ); //! Deserialize the time flag field and convert it into a record descriptor //! \return Serialize status Fw::SerializeStatus deserializeTimeFlag( Sequence::Record::Descriptor& descriptor //!< The descriptor ); //! Deserialize the time field and convert it into a time tag //! \return Serialize status Fw::SerializeStatus deserializeTime( Fw::Time& timeTag //!< The time tag ); //! Deserialize the command length field //! \return Serialize status Fw::SerializeStatus deserializeCmdLength( Record::CmdLength::t& cmdLength //!< The command length ); //! Translate a serialized AMPCS command to a serialized F Prime command //! \return Serialize status Fw::SerializeStatus translateCommand( Fw::ComBuffer& comBuffer, //!< The com buffer const Record::CmdLength::t cmdLength //!< The command length ); //! Validate the sequence records in the buffer //! \return Success or failure bool validateRecords(); PRIVATE: //! The sequence header SequenceHeader::t m_sequenceHeader; //! The CRC values CmdSequencerComponentImpl::FPrimeSequence::CRC m_crc; //! The CRC file Os::File m_crcFile; //! The sequence file Os::File m_sequenceFile; }; } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/MixedRelativeBase.hpp
// ====================================================================== // \title MixedRelativeBase.hpp // \author Canham/Bocchino // \brief Base class for Mixed and Relative // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #ifndef Svc_MixedRelativeBase_HPP #define Svc_MixedRelativeBase_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace MixedRelativeBase { //! Base class for Mixed and Relative class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests parameterized by file type // ---------------------------------------------------------------------- //! Run an automatic sequence by command void parameterizedAutoByCommand( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/InvalidFiles.hpp
// ====================================================================== // \title InvalidFiles.hpp // \author Canham/Bocchino // \brief Test immediate command sequences with EOS record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_InvalidFiles_HPP #define Svc_InvalidFiles_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace InvalidFiles { //! Test sequences with immediate commands followed by an EOS marker class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Bad CRC void BadCRC(); //! Bad record descriptor void BadRecordDescriptor(); //! Bad time base void BadTimeBase(); //! Bad time context void BadTimeContext(); //! Empty file void EmptyFile(); //! Extra data after command records void DataAfterRecords(); //! File too large void FileTooLarge(); //! Microseconds field too short void USecFieldTooShort(); //! Missing CRC void MissingCRC(); //! Missing file void MissingFile(); //! Size field too large void SizeFieldTooLarge(); //! Size field too small void SizeFieldTooSmall(); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Immediate.hpp
// ====================================================================== // \title Immediate.hpp // \author Canham/Bocchino // \brief Test immediate command sequences with record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_Immediate_HPP #define Svc_Immediate_HPP #include "Svc/CmdSequencer/test/ut/ImmediateBase.hpp" namespace Svc { namespace Immediate { //! Test sequences with immediate commands followed by a marker class CmdSequencerTester : public ImmediateBase::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Don't load any sequence, then try to run a sequence void NeverLoaded(); //! Inject file errors void FileErrors(); //! Load a sequence, then run a sequence, then try to run a pre-loaded //! sequence void LoadRunRun(); //! Run a complete sequence and then issue a command response void UnexpectedCommandResponse(); //! Run a sequence and, while it is running, start a new sequence //! The new sequence should cause an error void NewSequence(); //! Run a sequence manually void Manual(); //! Run a sequence with failed commands void FailedCommands(); //! Run an automatic sequence by command void AutoByCommand(); //! Run an automatic sequence through a port call void AutoByPort(); //! Send invalid manual commands while a sequence is running void InvalidManualCommands(); //! Load a sequence on initialization and then run it void LoadOnInit(); //! Sequence timeout void SequenceTimeout(); //! Start and cancel a sequence void Cancel(); //! Validate a sequence file void Validate(); private: // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- //! Execute commands for a manual sequence void executeCommandsManual( const char *const fileName, //!< The file name const U32 numCommands //!< The number of commands in the sequence ); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/ImmediateEOS.hpp
// ====================================================================== // \title ImmediateEOS.hpp // \author Canham/Bocchino // \brief Test immediate command sequences with EOS record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_ImmediateEOS_HPP #define Svc_ImmediateEOS_HPP #include "Svc/CmdSequencer/test/ut/ImmediateBase.hpp" namespace Svc { namespace ImmediateEOS { //! Test sequences with immediate commands followed by an EOS marker class CmdSequencerTester : public ImmediateBase::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Inject file errors void FileErrors(); //! Run a complete sequence and then issue a command response void UnexpectedCommandResponse(); //! Run a sequence and, while it is running, start a new sequence //! The new sequence should cause an error void NewSequence(); //! Run a sequence manually void Manual(); //! Run an automatic sequence by command void AutoByCommand(); //! Run an automatic sequence through a port call void AutoByPort(); //! Send invalid manual commands while a sequence is running void InvalidManualCommands(); //! Sequence timeout void SequenceTimeout(); //! Start and cancel a sequence void Cancel(); //! Validate a sequence file void Validate(); // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- private: //! Execute commands for a manual sequence void executeCommandsManual( const char *const fileName, //!< The file name const U32 numCommands //!< The number of commands in the sequence ); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/JoinWait.hpp
// ====================================================================== // \title JoinWait.hpp // \author janamian // \brief hpp file for CmdSequencer test harness implementation class // // \copyright // Copyright 2009-2021, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // // ====================================================================== #ifndef JOIN_WAIT_HPP #define JOIN_WAIT_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace JoinWait { class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Test void test_join_wait_without_active_seq(); void test_join_wait_with_active_seq(); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/InvalidFiles.cpp
// ====================================================================== // \title InvalidFiles.cpp // \author Canham/Bocchino // \brief Test immediate command sequences with EOS record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Os/FileSystem.hpp" #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "Svc/CmdSequencer/test/ut/InvalidFiles.hpp" namespace Svc { namespace InvalidFiles { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester(const SequenceFiles::File::Format::t format) : Svc::CmdSequencerTester(format) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: BadCRC() { REQUIREMENT("ISF-CMDS-002"); // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 0, 0); this->setTestTime(testTime); // Write the file SequenceFiles::BadCRCFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events const CmdSequencerComponentImpl::FPrimeSequence::CRC& crc = file.getCRC(); ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileCrcFailure( 0, fileName, crc.m_stored, crc.m_computed ); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); } void CmdSequencerTester :: BadRecordDescriptor() { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 1, 1); this->setTestTime(testTime); // Write the file NATIVE_INT_TYPE numRecords = 1; SequenceFiles::BadDescriptorFile file(numRecords, this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_FORMAT_ERROR ); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_FORMAT_ERROR ); } void CmdSequencerTester :: BadTimeBase() { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 1, 1); this->setTestTime(testTime); // Write the file const NATIVE_INT_TYPE numRecords = 5; SequenceFiles::BadTimeBaseFile file(numRecords, this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_TimeBaseMismatch_SIZE(1); ASSERT_EVENTS_CS_TimeBaseMismatch( 0, fileName, TB_WORKSTATION_TIME, TB_PROC_TIME ); } void CmdSequencerTester :: BadTimeContext() { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 0, 1, 1); this->setTestTime(testTime); // Write the file const U32 numRecords = 5; SequenceFiles::BadTimeContextFile file(numRecords, this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_TimeContextMismatch_SIZE(1); ASSERT_EVENTS_CS_TimeContextMismatch(0, fileName, 0, 1); } void CmdSequencerTester :: EmptyFile() { // Write the file SequenceFiles::EmptyFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileInvalid( 0, fileName, CmdSequencer_FileReadStage::READ_HEADER_SIZE, Os::FileSystem::OP_OK ); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); } void CmdSequencerTester :: DataAfterRecords() { REQUIREMENT("ISF-CMDS-001"); // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 1, 1); this->setTestTime(testTime); // Write the file const U32 numRecords = 5; SequenceFiles::DataAfterRecordsFile file(numRecords, this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordMismatch_SIZE(1); ASSERT_EVENTS_CS_RecordMismatch(0, fileName, 5, 8); } void CmdSequencerTester :: FileTooLarge() { // Write the file SequenceFiles::TooLargeFile file(BUFFER_SIZE, this->format); const char *const fileName = file.getName().toChar(); file.write(); // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 0, 0); this->setTestTime(testTime); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); const U32 dataSize = file.getDataSize(); ASSERT_EVENTS_CS_FileSizeError(0, fileName, dataSize); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); } void CmdSequencerTester :: MissingCRC() { // Write the file SequenceFiles::MissingCRCFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert no response on seqDone ASSERT_from_seqDone_SIZE(0); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileInvalid( 0, fileName, CmdSequencer_FileReadStage::READ_SEQ_CRC, sizeof(U8) ); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); // Validate file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert no response on seqDone ASSERT_from_seqDone_SIZE(0); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileInvalid( 0, fileName, CmdSequencer_FileReadStage::READ_SEQ_CRC, sizeof(U8) ); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 2); // Run the sequence by port call Fw::String fArg(fileName); this->invoke_to_seqRunIn(0, fArg); this->clearAndDispatch(); // Assert seqDone response ASSERT_from_seqDone_SIZE(1); ASSERT_from_seqDone(0U, 0U, 0U, Fw::CmdResponse(Fw::CmdResponse::EXECUTION_ERROR)); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileInvalid( 0, fileName, CmdSequencer_FileReadStage::READ_SEQ_CRC, sizeof(U8) ); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 3); } void CmdSequencerTester :: MissingFile() { // Remove the file SequenceFiles::MissingFile file(this->format); const char *const fileName = file.getName().toChar(); file.remove(); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse(Fw::CmdResponse::EXECUTION_ERROR) ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileNotFound(0, fileName); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); } void CmdSequencerTester :: SizeFieldTooLarge() { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 1, 1); this->setTestTime(testTime); // Write the file SequenceFiles::SizeFieldTooLargeFile file(BUFFER_SIZE, this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_SIZE_MISMATCH ); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_SIZE_MISMATCH ); } void CmdSequencerTester :: SizeFieldTooSmall() { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 1, 1); this->setTestTime(testTime); // Write the file SequenceFiles::SizeFieldTooSmallFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_SIZE_MISMATCH ); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_SIZE_MISMATCH ); } void CmdSequencerTester :: USecFieldTooShort() { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 1, 1); this->setTestTime(testTime); // Write the file SequenceFiles::USecFieldTooShortFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->sendCmd_CS_VALIDATE(0, 0, fileName); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_VALIDATE, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_SIZE_MISMATCH ); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_RecordInvalid( 0, fileName, 0, Fw::FW_DESERIALIZE_SIZE_MISMATCH ); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Relative.hpp
// ====================================================================== // \title Relative.hpp // \author Canham/Bocchino // \brief Test relative command sequences // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_Relative_HPP #define Svc_Relative_HPP #include "Svc/CmdSequencer/test/ut/MixedRelativeBase.hpp" namespace Svc { namespace Relative { //! Test sequences with immediate commands followed by a marker class CmdSequencerTester : public MixedRelativeBase::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Run an automatic sequence by command void AutoByCommand(); //! Validate a sequence file void Validate(); private: // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- //! Execute sequence commands for an automatic sequence void executeCommandsAuto( const char *const fileName, //!< The file name const U32 numCommands, //!< The number of commands in the sequence const U32 bound, //!< The number of commands to run const CmdExecMode::t mode //!< The mode ); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/CommandBuffers.cpp
// ====================================================================== // \title CommandBuffers.cpp // \author Canham/Bocchino // \brief Command buffers for testing sequences // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #include "Fw/Com/ComPacket.hpp" #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "gtest/gtest.h" namespace Svc { namespace CommandBuffers { void create( Fw::ComBuffer& comBuff, const FwOpcodeType opcode, const U32 argument ) { comBuff.resetSer(); const FwPacketDescriptorType descriptor = Fw::ComPacket::FW_PACKET_COMMAND; ASSERT_EQ(Fw::FW_SERIALIZE_OK, comBuff.serialize(descriptor)); ASSERT_EQ(Fw::FW_SERIALIZE_OK, comBuff.serialize(opcode)); ASSERT_EQ(Fw::FW_SERIALIZE_OK, comBuff.serialize(argument)); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/AMPCS.cpp
// ====================================================================== // \title AMPCS.cpp // \author Rob Bocchino // \brief AMPCS-specific tests // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Os/FileSystem.hpp" #include "Svc/CmdSequencer/test/ut/AMPCS.hpp" namespace Svc { namespace AMPCS { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester() : Svc::CmdSequencerTester(SequenceFiles::File::Format::AMPCS) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: MissingCRC() { // Write the file SequenceFiles::MissingCRCFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert no response on seqDone ASSERT_from_seqDone_SIZE(0); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events Fw::String crcFileName(fileName); crcFileName += ".CRC32"; ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileNotFound(0, crcFileName.toChar()); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); } void CmdSequencerTester :: MissingFile() { // Remove the file SequenceFiles::MissingFile file(this->format); const char *const fileName = file.getName().toChar(); file.write(); file.remove(); // Run the sequence this->sendCmd_CS_RUN(0, 0, fileName,Svc::CmdSequencer_BlockState::NO_BLOCK); this->clearAndDispatch(); // Assert command response ASSERT_CMD_RESPONSE_SIZE(1); ASSERT_CMD_RESPONSE( 0, CmdSequencerComponentBase::OPCODE_CS_RUN, 0, Fw::CmdResponse::EXECUTION_ERROR ); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_FileInvalid( 0, fileName, CmdSequencer_FileReadStage::READ_HEADER_SIZE, Os::FileSystem::INVALID_PATH ); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_Errors(0, 1); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Immediate.cpp
// ====================================================================== // \title Immediate.cpp // \author Canham/Bocchino // \brief Test immediate command sequences with record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "Svc/CmdSequencer/test/ut/Immediate.hpp" namespace Svc { namespace Immediate { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester(const SequenceFiles::File::Format::t format) : ImmediateBase::CmdSequencerTester(format) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: AutoByCommand() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numCommands; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedAutoByCommand(file, numCommands, bound); } void CmdSequencerTester :: AutoByPort() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numCommands; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedAutoByPort(file, numCommands, bound); } void CmdSequencerTester :: Cancel() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numRecords - 1; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedCancel(file, numCommands, bound); } void CmdSequencerTester :: FailedCommands() { const U32 numRecords = 3; const U32 numCommands = numRecords; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedFailedCommands(file, numCommands); } void CmdSequencerTester :: FileErrors() { const U32 numRecords = 5; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedFileErrors(file); } void CmdSequencerTester :: InvalidManualCommands() { const U32 numRecords = 5; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedInvalidManualCommands(file); } void CmdSequencerTester :: LoadOnInit() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numCommands; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedLoadOnInit(file, numCommands, bound); } void CmdSequencerTester :: LoadRunRun() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numCommands; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedLoadRunRun(file, numCommands, bound); } void CmdSequencerTester :: Manual() { const U32 numRecords = 5; const U32 numCommands = numRecords; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedManual(file, numCommands); } void CmdSequencerTester :: NeverLoaded() { this->parameterizedNeverLoaded(); } void CmdSequencerTester :: NewSequence() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numCommands; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedNewSequence(file, numCommands, bound); } void CmdSequencerTester :: SequenceTimeout() { const U32 numRecords = 5; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedSequenceTimeout(file); } void CmdSequencerTester :: UnexpectedCommandResponse() { const U32 numRecords = 5; const U32 numCommands = numRecords; const U32 bound = numCommands; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedUnexpectedCommandResponse(file, numCommands, bound); } void CmdSequencerTester :: Validate() { const U32 numRecords = 5; SequenceFiles::ImmediateFile file(numRecords, this->format); this->parameterizedValidate(file); } // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- void CmdSequencerTester :: executeCommandsManual( const char *const fileName, const U32 numCommands ) { for (U32 i = 0; i < numCommands; ++i) { PRINT("REC %d\n", i); // Check command buffer Fw::ComBuffer comBuff; CommandBuffers::create(comBuff, i, i + 1); ASSERT_from_comCmdOut_SIZE(1); ASSERT_from_comCmdOut(0, comBuff, 0U); // Assert that timer is clear ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimeoutTimer.m_state ); // Send command response this->invoke_to_cmdResponseIn(0, i, 0, Fw::CmdResponse::OK); this->clearAndDispatch(); if (i < numCommands - 1) { // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_CommandComplete(0, fileName, i, i); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_CommandsExecuted(0, i + 1); // Step sequence this->stepSequence(12); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_CmdStepped(0, fileName, i + 1); } else { // Assert events ASSERT_EVENTS_SIZE(2); ASSERT_EVENTS_CS_CommandComplete(0, fileName, i, i); ASSERT_EVENTS_CS_SequenceComplete_SIZE(1); // Assert telemetry ASSERT_TLM_SIZE(2); ASSERT_TLM_CS_CommandsExecuted(0, i + 1); ASSERT_TLM_CS_SequencesCompleted(0, 1); } } } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/CommandBuffers.hpp
// ====================================================================== // \title CommandBuffers.hpp // \author Canham/Bocchino // \brief Command buffers for testing sequences // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #ifndef Svc_CommandBuffers_HPP #define Svc_CommandBuffers_HPP #include "Fw/Com/ComBuffer.hpp" namespace Svc { namespace CommandBuffers { //! Create a command buffer with an opcode and one U32 argument void create( Fw::ComBuffer& comBuff, //!< The com buffer const FwOpcodeType opcode, //!< The opcode const U32 argument //!< The argument ); } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/AMPCS.hpp
// ====================================================================== // \title AMPCS.hpp // \author Rob bocchino // \brief AMPCS-specific tests // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_AMPCS_HPP #define Svc_AMPCS_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace AMPCS { //! Test sequencer behavior with no input files class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester(); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Missing CRC void MissingCRC(); //! Missing file void MissingFile(); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Health.cpp
// ====================================================================== // \title Health.cpp // \author Canham/Bocchino // \brief Test health pings // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Svc/CmdSequencer/test/ut/Health.hpp" namespace Svc { namespace Health { // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: Ping() { const U32 key = 1234; this->invoke_to_pingIn(0, key); this->clearAndDispatch(); ASSERT_from_pingOut_SIZE(1); ASSERT_from_pingOut(0, key); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/NoFiles.cpp
// ====================================================================== // \title NoFiles.cpp // \author Canham/Bocchino // \brief Test immediate command sequences with EOS record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "Svc/CmdSequencer/test/ut/NoFiles.hpp" namespace Svc { namespace NoFiles { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester(const SequenceFiles::File::Format::t format) : Svc::CmdSequencerTester(format) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: Init() { // Nothing to do } void CmdSequencerTester :: NoSequenceActive() { // Send cancel command this->sendCmd_CS_CANCEL(0, 0); this->clearAndDispatch(); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_NoSequenceActive_SIZE(1); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Mixed.cpp
// ====================================================================== // \title Mixed.cpp // \author Canham/Bocchino // \brief Test mixed immediate, relative, and absolute commands // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "Svc/CmdSequencer/test/ut/Mixed.hpp" namespace Svc { namespace Mixed { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester(const SequenceFiles::File::Format::t format) : MixedRelativeBase::CmdSequencerTester(format) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: AutoByCommand() { SequenceFiles::MixedFile file(this->format); const U32 numCommands = 4; const U32 bound = numCommands; this->parameterizedAutoByCommand(file, numCommands, bound); } void CmdSequencerTester :: Validate() { SequenceFiles::MixedFile file(this->format); this->parameterizedValidate(file); } // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- void CmdSequencerTester :: executeCommandsAuto( const char *const fileName, const U32 numCommands, const U32 bound, const CmdExecMode::t mode ) { ASSERT_EQ(4U, numCommands); ASSERT_EQ(4U, bound); ASSERT_EQ(CmdExecMode::NO_NEW_SEQUENCE, mode); this->executeCommand1(fileName); this->executeCommand2(fileName); this->executeCommand3(fileName); this->executeCommand4(fileName); } void CmdSequencerTester :: executeCommand1(const char* const fileName) { // Set the time to past absolute command Fw::Time testTime(TB_WORKSTATION_TIME, 3, 0); this->setTestTime(testTime); // Invoke schedIn this->invoke_to_schedIn(0, 0); this->clearAndDispatch(); // Assert that timer is clear ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); // Check command buffer Fw::ComBuffer comBuff; CommandBuffers::create(comBuff, 0 , 1); ASSERT_from_comCmdOut_SIZE(1); ASSERT_from_comCmdOut(0, comBuff, 0U); // Send status back this->invoke_to_cmdResponseIn(0, 0, 0, Fw::CmdResponse::OK); this->clearAndDispatch(); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_CommandComplete(0, fileName, 0, 0); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_CommandsExecuted(0, 1); // Assert that timer is clear - no scheduled command ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); } void CmdSequencerTester :: executeCommand2(const char* const fileName) { // Check command buffer Fw::ComBuffer comBuff; CommandBuffers::create(comBuff, 2, 3); ASSERT_from_comCmdOut_SIZE(1); ASSERT_from_comCmdOut(0, comBuff, 0U); // Send status back this->invoke_to_cmdResponseIn(0, 2, 0, Fw::CmdResponse::OK); this->clearAndDispatch(); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_CommandComplete(0, fileName, 1, 2); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_CommandsExecuted(0, 2); // Assert that timer is waiting for relative command ASSERT_EQ( CmdSequencerComponentImpl::Timer::SET, this->component.m_cmdTimer.m_state ); } void CmdSequencerTester :: executeCommand3(const char* const fileName) { // Set the time to past relative timer Fw::Time testTime(TB_WORKSTATION_TIME, 5, 0); this->setTestTime(testTime); // Invoke schedIn this->invoke_to_schedIn(0, 0); this->clearAndDispatch(); // Assert that timer is clear ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); // Check command buffer Fw::ComBuffer comBuff; CommandBuffers::create(comBuff, 4, 5); ASSERT_from_comCmdOut_SIZE(1); ASSERT_from_comCmdOut(0, comBuff, 0U); // Send status back this->invoke_to_cmdResponseIn(0, 4, 0, Fw::CmdResponse::OK); this->clearAndDispatch(); // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_CommandComplete(0, fileName, 2, 4); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_CommandsExecuted(0, 3); // Assert that timer is clear - no scheduled command ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); } void CmdSequencerTester :: executeCommand4(const char* const fileName) { // Assert that timer is clear - immediate command ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); // Check command buffer Fw::ComBuffer comBuff; CommandBuffers::create(comBuff, 6, 7); ASSERT_from_comCmdOut_SIZE(1); ASSERT_from_comCmdOut(0, comBuff, 0U); // Send status back this->invoke_to_cmdResponseIn(0, 6, 0, Fw::CmdResponse::OK); this->clearAndDispatch(); // Assert that timer is clear - no scheduled command ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); // Assert events ASSERT_EVENTS_SIZE(2); ASSERT_EVENTS_CS_CommandComplete(0, fileName, 3, 6); ASSERT_EVENTS_CS_SequenceComplete_SIZE(1); // Assert telemetry ASSERT_TLM_SIZE(2); ASSERT_TLM_CS_SequencesCompleted(0, 1); ASSERT_TLM_CS_CommandsExecuted(0, 4); // Check for command complete on seqDone ASSERT_from_seqDone_SIZE(1); ASSERT_from_seqDone(0, 0U, 0U, Fw::CmdResponse(Fw::CmdResponse::OK)); // Run a cycle. Should be no output this->invoke_to_schedIn(0, 0); this->clearAndDispatch(); ASSERT_from_comCmdOut_SIZE(0); // Assert no more events or telemetry ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/NoFiles.hpp
// ====================================================================== // \title NoFiles.hpp // \author Canham/Bocchino // \brief Test immediate command sequences with EOS record // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_NoFiles_HPP #define Svc_NoFiles_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace NoFiles { //! Test sequencer behavior with no input files class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Initialization void Init(); //! Issue a cancel command with no sequence active void NoSequenceActive(); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/ImmediateBase.hpp
// ====================================================================== // \title ImmediateBase.hpp // \author Canham/Bocchino // \brief Base class for Immediate and ImmediateEOS // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #ifndef Svc_ImmediateBase_HPP #define Svc_ImmediateBase_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace ImmediateBase { //! Base class for Immediate and ImmediateEOS class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); public: // ---------------------------------------------------------------------- // Tests parameterized by file type // ---------------------------------------------------------------------- //! Run an automatic sequence by command void parameterizedAutoByCommand( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Run an automatic sequence by port call void parameterizedAutoByPort( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Send invalid manual commands while a sequence is running void parameterizedInvalidManualCommands( SequenceFiles::File& file //!< The file ); //! Run a manual sequence void parameterizedManual( SequenceFiles::File& file, //!< The file const U32 numCommands //!< The number of commands in the sequence ); //! Run a sequence and, while it is running, start a new sequence //! The new sequence should cause an error void parameterizedNewSequence( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Load a sequence on initialization and then run it void parameterizedLoadOnInit( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Load a sequence, then run a sequence, then try to run a pre-loaded //! sequence void parameterizedLoadRunRun( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); protected: // ---------------------------------------------------------------------- // Protected helper methods // ---------------------------------------------------------------------- //! Execute sequence commands for an automatic sequence void executeCommandsAuto( const char *const fileName, //!< The file name const U32 numCommands, //!< The number of commands in the sequence const U32 bound, //!< The number of commands to run const CmdExecMode::t mode //!< The mode ); //! Execute sequence commands with a command response error void executeCommandsError( const char *const fileName, //!< The file name const U32 numCommands //!< The number of commands in the sequence ); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Health.hpp
// ====================================================================== // \title Health.hpp // \author Canham/Bocchino // \brief Test health pings // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_Health_HPP #define Svc_Health_HPP #include "CmdSequencerTester.hpp" namespace Svc { namespace Health { class CmdSequencerTester : public Svc::CmdSequencerTester { public: // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- //! Test health pings void Ping(); }; } } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/Relative.cpp
// ====================================================================== // \title Relative.cpp // \author Canham/Bocchino // \brief Test relative command sequences // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "Svc/CmdSequencer/test/ut/Relative.hpp" namespace Svc { namespace Relative { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester(const SequenceFiles::File::Format::t format) : MixedRelativeBase::CmdSequencerTester(format) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void CmdSequencerTester :: AutoByCommand() { const U32 numRecords = 3; SequenceFiles::RelativeFile file(numRecords, this->format); const U32 numCommands = numRecords; const U32 bound = numCommands; this->parameterizedAutoByCommand(file, numCommands, bound); } void CmdSequencerTester :: Validate() { const U32 numRecords = 5; SequenceFiles::RelativeFile file(numRecords, this->format); this->parameterizedValidate(file); } // ---------------------------------------------------------------------- // Private helper methods // ---------------------------------------------------------------------- void CmdSequencerTester :: executeCommandsAuto( const char *const fileName, const U32 numCommands, const U32 bound, const CmdExecMode::t mode ) { for (U32 i = 0; i < numCommands; ++i) { // Set the time to after time of command Fw::Time testTime(TB_WORKSTATION_TIME, 2 * i + 3, 0); this->setTestTime(testTime); // Run a cycle. Should dispatch timed command this->invoke_to_schedIn(0, 0); this->clearAndDispatch(); // Assert that timer is clear ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); // Check command buffer Fw::ComBuffer comBuff; CommandBuffers::create(comBuff, i, i + 1); ASSERT_from_comCmdOut_SIZE(1); ASSERT_from_comCmdOut(0, comBuff, 0U); // Send status back this->invoke_to_cmdResponseIn(0, i, 0, Fw::CmdResponse::OK); this->clearAndDispatch(); if (i < numCommands - 1) { // Assert events ASSERT_EVENTS_SIZE(1); ASSERT_EVENTS_CS_CommandComplete(0, fileName, i, i); // Assert telemetry ASSERT_TLM_SIZE(1); ASSERT_TLM_CS_CommandsExecuted(0, i + 1); // Assert that timer is set for next i ASSERT_EQ( CmdSequencerComponentImpl::Timer::SET, this->component.m_cmdTimer.m_state ); } else { // Assert events ASSERT_EVENTS_SIZE(2); ASSERT_EVENTS_CS_CommandComplete(0, fileName, i, i); ASSERT_EVENTS_CS_SequenceComplete_SIZE(1); // Assert telemetry ASSERT_TLM_SIZE(2); ASSERT_TLM_CS_SequencesCompleted(0, 1); ASSERT_TLM_CS_CommandsExecuted(0, i + 1); // Assert that timer is clear ASSERT_EQ( CmdSequencerComponentImpl::Timer::CLEAR, this->component.m_cmdTimer.m_state ); // Assert command complete on seqDone ASSERT_from_seqDone_SIZE(1); ASSERT_from_seqDone(0, 0U, 0U, Fw::CmdResponse(Fw::CmdResponse::OK)); } // No port call ASSERT_from_comCmdOut_SIZE(0); // Run a cycle. Should be no output. this->invoke_to_schedIn(0, 0); this->clearAndDispatch(); ASSERT_from_comCmdOut_SIZE(0); // Command and sequence complete EVR ASSERT_EVENTS_SIZE(0); ASSERT_TLM_SIZE(0); } } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/MixedRelativeBase.cpp
// ====================================================================== // \title MixedRelativeBase.cpp // \author Canham/Bocchino // \brief Base class for Mixed and Relative // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #include "Svc/CmdSequencer/test/ut/CommandBuffers.hpp" #include "Svc/CmdSequencer/test/ut/MixedRelativeBase.hpp" namespace Svc { namespace MixedRelativeBase { // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- CmdSequencerTester :: CmdSequencerTester(const SequenceFiles::File::Format::t format) : Svc::CmdSequencerTester(format) { } // ---------------------------------------------------------------------- // Tests parameterized by file type // ---------------------------------------------------------------------- void CmdSequencerTester :: parameterizedAutoByCommand( SequenceFiles::File& file, const U32 numCommands, const U32 bound ) { // Set the time Fw::Time testTime(TB_WORKSTATION_TIME, 0, 0); this->setTestTime(testTime); // Write the file const char *const fileName = file.getName().toChar(); file.write(); // Validate the file this->validateFile(0, fileName); // Run the sequence this->runSequence(0, fileName); // Assert that timer is set ASSERT_EQ( CmdSequencerComponentImpl::Timer::SET, this->component.m_cmdTimer.m_state ); // Run one cycle to make sure nothing is dispatched yet this->invoke_to_schedIn(0, 0); this->clearAndDispatch(); ASSERT_from_comCmdOut_SIZE(0); ASSERT_EVENTS_SIZE(0); // Assert that timer hasn't expired ASSERT_EQ( CmdSequencerComponentImpl::Timer::SET, this->component.m_cmdTimer.m_state ); // Execute commands this->executeCommandsAuto( fileName, numCommands, bound, CmdExecMode::NO_NEW_SEQUENCE ); } } }
cpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/CmdSequencerTester.hpp
// ====================================================================== // \title CmdSequencerTester.hpp // \author Bocchino/Canham // \brief CmdSequencer test interface // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef Svc_Tester_HPP #define Svc_Tester_HPP #include "Fw/Types/MallocAllocator.hpp" #include "CmdSequencerGTestBase.hpp" #include "Os/Posix/File.hpp" #include "Svc/CmdSequencer/CmdSequencerImpl.hpp" #include "Svc/CmdSequencer/formats/AMPCSSequence.hpp" #include "Svc/CmdSequencer/test/ut/SequenceFiles/SequenceFiles.hpp" #include "Svc/CmdSequencer/test/ut/UnitTest.hpp" #define ALLOCATOR_ID 100 #define BUFFER_SIZE 1024 #define INSTANCE 0 #define MAX_HISTORY_SIZE 10 #define QUEUE_DEPTH 10 #define TIMEOUT 100 namespace Svc { class CmdSequencerTester : public CmdSequencerGTestBase { private: // ---------------------------------------------------------------------- // Constants // ---------------------------------------------------------------------- static const NATIVE_UINT_TYPE TEST_SEQ_BUFFER_SIZE = 255; protected: // ---------------------------------------------------------------------- // Types // ---------------------------------------------------------------------- //! Mode for executing commands struct CmdExecMode { typedef enum { //! Don't start a new sequence NO_NEW_SEQUENCE, //! Start a new sequence NEW_SEQUENCE } t; }; //! Sequences encoding binary formats struct Sequences { //! Construct a Sequences object Sequences( CmdSequencerComponentImpl& component //!< The component under test ) : ampcsSequence(component) { } //! The AMPCS sequence AMPCSSequence ampcsSequence; }; public: class Interceptor { public: // ---------------------------------------------------------------------- // Types // ---------------------------------------------------------------------- //! Type of injected errors struct EnableType { typedef enum { NONE, // Don't enable interception OPEN, // Intercept opens READ, // Intercept reads } t; }; //! Type of injected errors struct ErrorType { typedef enum { NONE, // Don't inject any errors READ, // Bad read status SIZE, // Bad size DATA // Unexpected data } t; }; public: // ---------------------------------------------------------------------- // Constructors // ---------------------------------------------------------------------- Interceptor(); public: // ---------------------------------------------------------------------- // Public instance methods // ---------------------------------------------------------------------- //! Enable the interceptor void enable(EnableType::t enableType); //! Disable the interceptor void disable(); class PosixFileInterceptor : public Os::Posix::File::PosixFile { friend class Interceptor; public: PosixFileInterceptor() = default; PosixFileInterceptor(const PosixFileInterceptor& other) = default; Os::FileInterface::Status open(const char *path, Mode mode, OverwriteType overwrite) override; Status read(U8 *buffer, FwSignedSizeType &size, WaitType wait) override; //! Current interceptor static Interceptor* s_current_interceptor; }; public: // ---------------------------------------------------------------------- // Public member variables // ---------------------------------------------------------------------- EnableType::t enabled; //! Error type ErrorType::t errorType; //! How many read calls to let pass before modifying U32 waitCount; //! Read data BYTE data[TEST_SEQ_BUFFER_SIZE]; //! Read size U32 size; //! Status Os::File::Status fileStatus; }; // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- //! Construct object CmdSequencerTester CmdSequencerTester( const SequenceFiles::File::Format::t format = SequenceFiles::File::Format::F_PRIME //!< The file format to use ); //! Destroy object CmdSequencerTester ~CmdSequencerTester(); private: // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- //! Handler for from_seqDone //! void from_seqDone_handler( const NATIVE_INT_TYPE portNum, //!< The port number FwOpcodeType opCode, //!< Command Op Code U32 cmdSeq, //!< Command Sequence const Fw::CmdResponse& response //!< The command response argument ); //! Handler for from_comCmdOut //! void from_comCmdOut_handler( const NATIVE_INT_TYPE portNum, //!< The port number Fw::ComBuffer &data, //!< Buffer containing packet data U32 context //!< Call context value; meaning chosen by user ); //! Handler for from_pingOut //! void from_pingOut_handler( const NATIVE_INT_TYPE portNum, //!< The port number U32 key //!< Value to return to pinger ); #if VERBOSE protected: // ---------------------------------------------------------------------- // TesterBase interface // ---------------------------------------------------------------------- //! Handle a text event void textLogIn( const FwEventIdType id, //!< The event ID Fw::Time& timeTag, //!< The time const Fw::LogSeverity severity, //!< The severity const Fw::TextLogString& text //!< The event string ); #endif protected: // ---------------------------------------------------------------------- // Virtual function interface // ---------------------------------------------------------------------- //! Execute sequence commands for an automatic sequence virtual void executeCommandsAuto( const char *const fileName, //!< The file name const U32 numCommands, //!< The number of commands in the sequence const U32 bound, //!< The number of commands to run const CmdExecMode::t mode //!< The mode ); //! Execute sequence commands with a command response error virtual void executeCommandsError( const char *const fileName, //!< The file name const U32 numCommands //!< The number of commands in the sequence ); //! Execute commands for a manual sequence virtual void executeCommandsManual( const char *const fileName, //!< The file name const U32 numCommands //!< The number of commands in the sequence ); protected: // ---------------------------------------------------------------------- // Tests parameterized by file type // ---------------------------------------------------------------------- //! Run an automatic sequence by command virtual void parameterizedAutoByCommand( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Inject data read errors void parameterizedDataReadErrors( SequenceFiles::File& file //!< The file ); //! Inject file errors void parameterizedFileErrors( SequenceFiles::File& file //!< The file ); //! Inject file open errors void parameterizedFileOpenErrors( SequenceFiles::File& file //!< The file ); //! Inject header read errors void parameterizedHeaderReadErrors( SequenceFiles::File& file //!< The file ); //! Run a sequence with failed commands void parameterizedFailedCommands( SequenceFiles::File& file, //!< The file const U32 numCommands //!< The number of commands to run ); //! Don't load any sequence, then try to run a sequence void parameterizedNeverLoaded(); //! Sequence timeout void parameterizedSequenceTimeout( SequenceFiles::File& file //!< The file ); //! Start and cancel a sequence void parameterizedCancel( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Run a complete sequence and then issue a command response void parameterizedUnexpectedCommandResponse( SequenceFiles::File& file, //!< The file const U32 numCommands, //!< The number of commands in the sequence const U32 bound //!< The number of commands to execute ); //! Validate a sequence void parameterizedValidate( SequenceFiles::File& file //!< The file ); protected: // ---------------------------------------------------------------------- // Instance helper methods // ---------------------------------------------------------------------- //! Cancel a sequence void cancelSequence( const U32 cmdSeq, //!< The command sequence number const char* const fileName //!< The file name ); //! Clear history and dispatch messages void clearAndDispatch(); //! Connect ports void connectPorts(); //! Go to auto mode void goToAutoMode( const U32 cmdSeq //!< The command sequence number ); //! Go to manual mode void goToManualMode( const U32 cmdSeq //!< The command sequence number ); //! Initialize components void initComponents(); //! Load a sequence void loadSequence( const char* const fileName //!< The file name ); //! Run a loaded sequence void runLoadedSequence(); //! Run a sequence by command void runSequence( const U32 cmdSeq, //!< The command sequence number const char* const fileName //!< The file name ); //! Run a sequence by port call void runSequenceByPortCall( const char* const fileName //!< The file name ); //! Send a step command void stepSequence( const U32 cmdSeq //!< The command sequence number ); //! Set the component sequence format void setComponentSequenceFormat(); //! Start a new sequence while checking command buffers void startNewSequence( const char *const fileName //!< The file name ); //! Start a sequence in manual mode void startSequence( const U32 cmdSeq, //!< The command sequence number const char* const fileName //!< The file name ); //! Validate a sequence file void validateFile( const U32 cmdSeq, //!< The command sequence number const char* const fileName //!< The file name ); protected: // ---------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------- //! The component under test CmdSequencerComponentImpl component; //! The file format to use const SequenceFiles::File::Format::t format; //! Sequences encoding binary formats Sequences sequences; //! The allocator Fw::MallocAllocator mallocator; //! Open/Read interceptor Interceptor interceptor; }; } #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/UnitTest.hpp
// ====================================================================== // \title UnitTester.hpp // \author Rob Bocchino // \brief Unit test macros // // \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. #ifndef Svc_UnitTest_HPP #define Svc_UnitTest_HPP #define VERBOSE 0 #if VERBOSE #include "Fw/Test/UnitTest.hpp" #define PRINT(s,...) printf(s, __VA_ARGS__) #else #define PRINT(s,...) #define REQUIREMENT(x) #define TEST_CASE(a, b) #endif #endif
hpp
fprime
data/projects/fprime/Svc/CmdSequencer/test/ut/CmdSequencerMain.cpp
// \copyright // Copyright (C) 2009-2018 California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ---------------------------------------------------------------------- // Main.cpp // ---------------------------------------------------------------------- #include <Os/FileSystem.hpp> #include "Svc/CmdSequencer/test/ut/AMPCS.hpp" #include "Svc/CmdSequencer/test/ut/Health.hpp" #include "Svc/CmdSequencer/test/ut/Immediate.hpp" #include "Svc/CmdSequencer/test/ut/ImmediateEOS.hpp" #include "Svc/CmdSequencer/test/ut/InvalidFiles.hpp" #include "Svc/CmdSequencer/test/ut/NoFiles.hpp" #include "Svc/CmdSequencer/test/ut/Relative.hpp" #include "Svc/CmdSequencer/test/ut/SequenceFiles/SequenceFiles.hpp" #include "CmdSequencerTester.hpp" #include "Svc/CmdSequencer/test/ut/Mixed.hpp" #include "Svc/CmdSequencer/test/ut/UnitTest.hpp" #include "Svc/CmdSequencer/test/ut/JoinWait.hpp" TEST(AMPCS, MissingCRC) { Svc::AMPCS::CmdSequencerTester tester; tester.MissingCRC(); } TEST(AMPCS, MissingFile) { Svc::AMPCS::CmdSequencerTester tester; tester.MissingFile(); } TEST(Health, Ping) { TEST_CASE(103.1.9,"Nominal ping test"); Svc::Health::CmdSequencerTester tester; tester.Ping(); } TEST(Immediate, AutoByCommand) { Svc::Immediate::CmdSequencerTester tester; tester.AutoByCommand(); } TEST(Immediate, AutoByCommandAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.AutoByCommand(); } TEST(Immediate, AutoByPort) { Svc::Immediate::CmdSequencerTester tester; tester.AutoByPort(); } TEST(Immediate, AutoByPortAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.AutoByPort(); } TEST(Immediate, Cancel) { Svc::Immediate::CmdSequencerTester tester; tester.Cancel(); } TEST(Immediate, CancelAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.Cancel(); } TEST(Immediate, FailedCommands) { TEST_CASE(103.2.6,"Off-Nominal failed command"); Svc::Immediate::CmdSequencerTester tester; tester.FailedCommands(); } TEST(Immediate, FailedCommandsAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.FailedCommands(); } TEST(Immediate, FileErrors) { Svc::Immediate::CmdSequencerTester tester; tester.FileErrors(); } TEST(Immediate, FileErrorsAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.FileErrors(); } TEST(Immediate, InvalidManualCommands) { Svc::Immediate::CmdSequencerTester tester; tester.InvalidManualCommands(); } TEST(Immediate, InvalidManualCommandsAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.InvalidManualCommands(); } TEST(Immediate, LoadOnInit) { Svc::Immediate::CmdSequencerTester tester; tester.LoadOnInit(); } TEST(Immediate, LoadRunRun) { Svc::Immediate::CmdSequencerTester tester; tester.LoadRunRun(); } TEST(Immediate, LoadOnInitAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.LoadOnInit(); } TEST(Immediate, Manual) { TEST_CASE(103.1.8,"Nominal Manual Sequence Stepping - No end of sequence marker"); Svc::Immediate::CmdSequencerTester tester; tester.Manual(); } TEST(Immediate, ManualAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.Manual(); } TEST(Immediate, NeverLoaded) { Svc::Immediate::CmdSequencerTester tester; tester.NeverLoaded(); } TEST(Immediate, NewSequence) { Svc::Immediate::CmdSequencerTester tester; tester.NewSequence(); } TEST(Immediate, NewSequenceAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.NewSequence(); } TEST(Immediate, SequenceTimeout) { Svc::Immediate::CmdSequencerTester tester; tester.SequenceTimeout(); } TEST(Immediate, SequenceTimeoutAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.SequenceTimeout(); } TEST(Immediate, UnexpectedCommandResponse) { Svc::Immediate::CmdSequencerTester tester; tester.UnexpectedCommandResponse(); } TEST(Immediate, UnexpectedCommandResponseAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.UnexpectedCommandResponse(); } TEST(Immediate, Validate) { Svc::Immediate::CmdSequencerTester tester; tester.Validate(); } TEST(Immediate, ValidateAMPCS) { Svc::Immediate::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.Validate(); } TEST(ImmediateEOS, AutoByCommand) { TEST_CASE(103.1.2,"Nominal Immediate Commands"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.AutoByCommand(); } TEST(ImmediateEOS, AutoByPort) { TEST_CASE(103.1.5,"Nominal Immediate Port Sequence"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.AutoByPort(); } TEST(ImmediateEOS, Cancel) { TEST_CASE(103.1.6,"Nominal Sequence Cancel"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.Cancel(); } TEST(ImmediateEOS, FileErrors) { TEST_CASE(103.2.14,"File Load errors"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.FileErrors(); } TEST(ImmediateEOS, InvalidManualCommands) { TEST_CASE(103.2.13,"Invalid Manual Commands"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.InvalidManualCommands(); } TEST(ImmediateEOS, Manual) { TEST_CASE(103.1.7,"Nominal Manual Sequence Stepping"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.Manual(); } TEST(ImmediateEOS, NewSequence) { TEST_CASE(103.2.7,"Off-Nominal invalid modes"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.NewSequence(); } TEST(ImmediateEOS, SequenceTimeout) { TEST_CASE(103.2.12,"Sequence timeout"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.SequenceTimeout(); } TEST(ImmediateEOS, UnexpectedCommandResponse) { TEST_CASE(103.2.11,"Unexpected completion after completed sequence"); Svc::ImmediateEOS::CmdSequencerTester tester; tester.UnexpectedCommandResponse(); } TEST(ImmediateEOS, Validate) { Svc::ImmediateEOS::CmdSequencerTester tester; tester.Validate(); } TEST(InvalidFiles, BadCRC) { TEST_CASE(103.2.2,"Off-Nominal Bad File CRC"); Svc::InvalidFiles::CmdSequencerTester tester; tester.BadCRC(); } TEST(InvalidFiles, BadCRCAMPCS) { Svc::InvalidFiles::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.BadCRC(); } TEST(InvalidFiles, BadRecordDescriptor) { Svc::InvalidFiles::CmdSequencerTester tester; tester.BadRecordDescriptor(); } TEST(InvalidFiles, BadRecordDescriptorAMPCS) { Svc::InvalidFiles::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.BadRecordDescriptor(); } TEST(InvalidFiles, BadTimeBase) { Svc::InvalidFiles::CmdSequencerTester tester; tester.BadTimeBase(); } TEST(InvalidFiles, BadTimeContext) { TEST_CASE(103.2.10,"Bad time context"); Svc::InvalidFiles::CmdSequencerTester tester; tester.BadTimeContext(); } TEST(InvalidFiles, DataAfterRecords) { TEST_CASE(103.2.15,"Extra Data after records"); Svc::InvalidFiles::CmdSequencerTester tester; tester.DataAfterRecords(); } TEST(InvalidFiles, EmptyFile) { TEST_CASE(103.2.3,"Off-Nominal Empty Sequence File"); Svc::InvalidFiles::CmdSequencerTester tester; tester.EmptyFile(); } TEST(InvalidFiles, EmptyFileAMPCS) { Svc::InvalidFiles::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.EmptyFile(); } TEST(InvalidFiles, FileTooLarge) { TEST_CASE(103.2.5,"Off-Nominal File Too Large"); Svc::InvalidFiles::CmdSequencerTester tester; tester.FileTooLarge(); } TEST(InvalidFiles, FileTooLargeAMPCS) { Svc::InvalidFiles::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.FileTooLarge(); } TEST(InvalidFiles, MissingCRC) { TEST_CASE(103.2.4,"Off-Nominal Missing CRC"); Svc::InvalidFiles::CmdSequencerTester tester; tester.MissingCRC(); } TEST(InvalidFiles, MissingFile) { TEST_CASE(103.2.1,"Off-Nominal Missing File"); Svc::InvalidFiles::CmdSequencerTester tester; tester.MissingFile(); } TEST(InvalidFiles, SizeFieldTooLarge) { TEST_CASE(103.2.9,"Size field too large"); Svc::InvalidFiles::CmdSequencerTester tester; tester.SizeFieldTooLarge(); } TEST(InvalidFiles, SizeFieldTooSmall) { Svc::InvalidFiles::CmdSequencerTester tester; tester.SizeFieldTooSmall(); } TEST(InvalidFiles, USecFieldTooShort) { Svc::InvalidFiles::CmdSequencerTester tester; tester.USecFieldTooShort(); } TEST(Mixed, AutoByCommand) { TEST_CASE(103.1.4,"Nominal Timed Relative Commands"); Svc::Mixed::CmdSequencerTester tester; tester.AutoByCommand(); } TEST(Mixed, AutoByCommandAMPCS) { Svc::Mixed::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.AutoByCommand(); } TEST(Mixed, Validate) { Svc::Mixed::CmdSequencerTester tester; tester.Validate(); } TEST(Mixed, ValidateAMPCS) { Svc::Mixed::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.Validate(); } TEST(NoFiles, Init) { TEST_CASE(103.1.1,"Nominal Initialization"); Svc::NoFiles::CmdSequencerTester tester; tester.Init(); } TEST(NoFiles, InitAMPCS) { Svc::NoFiles::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.Init(); } TEST(NoFiles, NoSequenceActive) { TEST_CASE(103.2.8,"Off-Nominal no active sequence"); Svc::NoFiles::CmdSequencerTester tester; tester.NoSequenceActive(); } TEST(NoFiles, NoSequenceActiveAMPCS) { Svc::NoFiles::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.NoSequenceActive(); } TEST(Relative, AutoByCommand) { TEST_CASE(103.1.3,"Nominal Relative Commands"); Svc::Relative::CmdSequencerTester tester; tester.AutoByCommand(); } TEST(Relative, AutoByCommandAMPCS) { Svc::Relative::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.AutoByCommand(); } TEST(Relative, Validate) { Svc::Relative::CmdSequencerTester tester; tester.Validate(); } TEST(Relative, ValidateAMPCS) { Svc::Relative::CmdSequencerTester tester(Svc::SequenceFiles::File::Format::AMPCS); tester.Validate(); } TEST(JoinWait, JoinWaitNoActiveSeq) { Svc::JoinWait::CmdSequencerTester tester; tester.test_join_wait_without_active_seq(); } TEST(JoinWait, JoinWaitWithActiveSeq) { Svc::JoinWait::CmdSequencerTester tester; tester.test_join_wait_with_active_seq(); } int main(int argc, char **argv) { // Create ./bin directory for test files Os::FileSystem::createDirectory("./bin"); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp