repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
fprime | data/projects/fprime/RPI/Main.cpp | #include <cstdio>
#include <cstdlib>
#include <ctype.h>
#include <getopt.h>
#include <signal.h>
#include <RPI/Top/RPITopologyAc.hpp>
RPI::TopologyState state;
// Enable the console logging provided by Os::Log
Os::Log logger;
void print_usage(const char* app) {
(void) printf("Usage: ./%s [options]\n-p\tport_number\n-a\thostname/IP address\n",app);
}
// Handle a signal, e.g. control-C
static void sighandler(int signum) {
// Call the teardown function
// This causes the Linux timer to quit
RPI::teardown(state);
}
int main(int argc, char* argv[]) {
I32 option = 0;
while ((option = getopt(argc, argv, "hp:a:")) != -1){
switch(option) {
case 'h':
print_usage(argv[0]);
return 0;
break;
case 'p':
state.portNumber = static_cast<U32>(atoi(optarg));
break;
case 'a':
state.hostName = optarg;
break;
case '?':
return 1;
default:
print_usage(argv[0]);
return 1;
}
}
(void) printf("Hit Ctrl-C to quit\n");
RPI::setup(state);
// register signal handlers to exit program
signal(SIGINT,sighandler);
signal(SIGTERM,sighandler);
// Start the Linux timer.
// The timer runs on the main thread until it quits
// in the teardown function, called from the signal
// handler.
RPI::linuxTimer.startTimer(100); //!< 10Hz
// Signal handler was called, and linuxTimer quit.
// Time to exit the program.
// Give time for threads to exit.
(void) printf("Waiting for threads...\n");
Os::Task::delay(1000);
(void) printf("Exiting...\n");
return 0;
}
| cpp |
fprime | data/projects/fprime/RPI/Top/RPITopologyDefs.hpp | #ifndef RPITopologyDefs_HPP
#define RPITopologyDefs_HPP
#include "Fw/Types/MallocAllocator.hpp"
#include "Os/Log.hpp"
#include "RPI/Top/FppConstantsAc.hpp"
#include "Svc/FramingProtocol/FprimeProtocol.hpp"
#include "Svc/LinuxTimer/LinuxTimer.hpp"
namespace RPI {
namespace Allocation {
// Malloc allocator for topology construction
extern Fw::MallocAllocator mallocator;
}
namespace Init {
// Initialization status
extern bool status;
}
// State for topology construction
struct TopologyState {
TopologyState() :
hostName(nullptr),
portNumber(0)
{
}
TopologyState(
const char *hostName,
U32 portNumber
) :
hostName(hostName),
portNumber(portNumber)
{
}
const char* hostName;
U32 portNumber;
};
// Health ping entries
namespace PingEntries {
namespace rateGroup10HzComp { enum { WARN = 3, FATAL = 5 }; }
namespace rateGroup1HzComp { enum { WARN = 3, FATAL = 5 }; }
namespace cmdDisp { enum { WARN = 3, FATAL = 5 }; }
namespace cmdSeq { enum { WARN = 3, FATAL = 5 }; }
namespace chanTlm { enum { WARN = 3, FATAL = 5 }; }
namespace eventLogger { enum { WARN = 3, FATAL = 5 }; }
namespace prmDb { enum { WARN = 3, FATAL = 5 }; }
namespace fileDownlink { enum { WARN = 3, FATAL = 5 }; }
namespace fileUplink { enum { WARN = 3, FATAL = 5 }; }
}
}
#endif
| hpp |
fprime | data/projects/fprime/RPI/Top/Topology.cpp | #include <Components.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/Task.hpp>
#include <Os/Log.hpp>
#include <Os/File.hpp>
#include <Os/TaskString.hpp>
#include <Fw/Types/MallocAllocator.hpp>
#include <RPI/Top/RpiSchedContexts.hpp>
#include <Svc/FramingProtocol/FprimeProtocol.hpp>
enum {
UPLINK_BUFFER_STORE_SIZE = 3000,
UPLINK_BUFFER_QUEUE_SIZE = 30,
UPLINK_BUFFER_MGR_ID = 200
};
Svc::FprimeDeframing deframing;
Svc::FprimeFraming framing;
// Component instances
// Rate Group Dividers for 10Hz and 1Hz
static NATIVE_INT_TYPE rgDivs[] = {1,10,0};
Svc::RateGroupDriverImpl rateGroupDriverComp("RGDRV",rgDivs,FW_NUM_ARRAY_ELEMENTS(rgDivs));
// Context array variables are passed to rate group members if needed to distinguish one call from another
// These context must match the rate group members connected in RPITopologyAi.xml
static NATIVE_UINT_TYPE rg10HzContext[] = {Rpi::CONTEXT_RPI_DEMO_10Hz,0,0,0,0,0,0,0,0,0};
Svc::ActiveRateGroupImpl rateGroup10HzComp("RG10Hz",rg10HzContext,FW_NUM_ARRAY_ELEMENTS(rg10HzContext));
static NATIVE_UINT_TYPE rg1HzContext[] = {0,0,Rpi::CONTEXT_RPI_DEMO_1Hz,0,0,0,0,0,0,0};
Svc::ActiveRateGroupImpl rateGroup1HzComp("RG1Hz",rg1HzContext,FW_NUM_ARRAY_ELEMENTS(rg1HzContext));
// Command Components
Drv::TcpClientComponentImpl comm(FW_OPTIONAL_NAME("Tcp"));
#if FW_ENABLE_TEXT_LOGGING
Svc::ConsoleTextLoggerImpl textLogger("TLOG");
#endif
Svc::ActiveLoggerImpl eventLogger("ELOG");
Svc::PosixTime posixTime("LTIME");
Svc::LinuxTimerComponentImpl linuxTimer("LTIMER");
Svc::TlmChanImpl chanTlm("TLM");
Svc::CommandDispatcherImpl cmdDisp("CMDDISP");
// This needs to be statically allocated
Fw::MallocAllocator mallocator;
Svc::CmdSequencerComponentImpl cmdSeq("CMDSEQ");
Svc::PrmDbImpl prmDb("PRM","PrmDb.dat");
Svc::FileUplink fileUplink("fileUplink");
Svc::FileDownlink fileDownlink ("fileDownlink");
Svc::BufferManagerComponentImpl fileUplinkBufferManager("fileUplinkBufferManager");
Svc::HealthImpl health("health");
Svc::StaticMemoryComponentImpl staticMemory(FW_OPTIONAL_NAME("staticMemory"));
Svc::FramerComponentImpl downlink(FW_OPTIONAL_NAME("downlink"));
Svc::DeframerComponentImpl uplink(FW_OPTIONAL_NAME("uplink"));
Svc::AssertFatalAdapterComponentImpl fatalAdapter("fatalAdapter");
Svc::FatalHandlerComponentImpl fatalHandler("fatalHandler");
Drv::LinuxSerialDriverComponentImpl uartDrv("uartDrv");
Drv::LinuxSpiDriverComponentImpl spiDrv("spiDrv");
Drv::LinuxGpioDriverComponentImpl ledDrv("ledDrv");
Drv::LinuxGpioDriverComponentImpl gpio23Drv("gpio23Drv");
Drv::LinuxGpioDriverComponentImpl gpio24Drv("gpio24Drv");
Drv::LinuxGpioDriverComponentImpl gpio25Drv("gpio25Drv");
Drv::LinuxGpioDriverComponentImpl gpio17Drv("gpio17Drv");
Rpi::RpiDemoComponentImpl rpiDemo("rpiDemo");
void constructApp(U32 port_number, char* hostname) {
staticMemory.init(0);
// Initialize rate group driver
rateGroupDriverComp.init();
// Initialize the rate groups
rateGroup10HzComp.init(10,0);
rateGroup1HzComp.init(10,1);
#if FW_ENABLE_TEXT_LOGGING
textLogger.init();
#endif
eventLogger.init(10,0);
posixTime.init(0);
linuxTimer.init(0);
chanTlm.init(10,0);
cmdDisp.init(20,0);
cmdSeq.init(10,0);
cmdSeq.allocateBuffer(0,mallocator,5*1024);
prmDb.init(10,0);
downlink.init(0);
uplink.init(0);
comm.init(0);
fileUplink.init(30, 0);
fileDownlink.configure(1000, 200, 100, 10);
fileDownlink.init(30, 0);
fileUplinkBufferManager.init(0);
fatalAdapter.init(0);
fatalHandler.init(0);
health.init(25,0);
uartDrv.init(0);
spiDrv.init(0);
ledDrv.init(0);
gpio23Drv.init(0);
gpio24Drv.init(0);
gpio25Drv.init(0);
gpio17Drv.init(0);
rpiDemo.init(10,0);
downlink.setup(framing);
uplink.setup(deframing);
constructRPIArchitecture();
/* Register commands */
cmdSeq.regCommands();
cmdDisp.regCommands();
eventLogger.regCommands();
prmDb.regCommands();
fileDownlink.regCommands();
health.regCommands();
rpiDemo.regCommands();
// set sequencer timeout
cmdSeq.setTimeout(30);
// read parameters
prmDb.readParamFile();
// set health ping entries
// This list has to match the connections in RPITopologyAppAi.xml
Svc::HealthImpl::PingEntry pingEntries[] = {
{3,5,rateGroup10HzComp.getObjName()}, // 0
{3,5,rateGroup1HzComp.getObjName()}, // 1
{3,5,cmdDisp.getObjName()}, // 2
{3,5,cmdSeq.getObjName()}, // 3
{3,5,chanTlm.getObjName()}, // 4
{3,5,eventLogger.getObjName()}, // 5
{3,5,prmDb.getObjName()}, // 6
{3,5,fileDownlink.getObjName()}, // 7
{3,5,fileUplink.getObjName()}, // 8
};
// register ping table
health.setPingEntries(pingEntries,FW_NUM_ARRAY_ELEMENTS(pingEntries),0x123);
// load parameters
rpiDemo.loadParameters();
// set up BufferManager instances
Svc::BufferManagerComponentImpl::BufferBins upBuffMgrBins;
memset(&upBuffMgrBins,0,sizeof(upBuffMgrBins));
upBuffMgrBins.bins[0].bufferSize = UPLINK_BUFFER_STORE_SIZE;
upBuffMgrBins.bins[0].numBuffers = UPLINK_BUFFER_QUEUE_SIZE;
fileUplinkBufferManager.setup(UPLINK_BUFFER_MGR_ID,0,mallocator,upBuffMgrBins);
// Active component startup
// start rate groups
rateGroup10HzComp.start();
rateGroup1HzComp.start();
// start dispatcher
cmdDisp.start();
// start sequencer
cmdSeq.start();
// start telemetry
eventLogger.start();
chanTlm.start();
prmDb.start();
fileDownlink.start();
fileUplink.start();
rpiDemo.start();
// Use the mini-UART for our serial connection
// https://www.raspberrypi.org/documentation/configuration/uart.md
if (not uartDrv.open("/dev/serial0",
Drv::LinuxSerialDriverComponentImpl::BAUD_19200,
Drv::LinuxSerialDriverComponentImpl::NO_FLOW,
Drv::LinuxSerialDriverComponentImpl::PARITY_NONE,
true)) {
return;
}
if (not spiDrv.open(0,0,Drv::SPI_FREQUENCY_1MHZ)) {
return;
}
if (not ledDrv.open(21,Drv::LinuxGpioDriverComponentImpl::GPIO_OUT)) {
return;
}
if (not gpio23Drv.open(23,Drv::LinuxGpioDriverComponentImpl::GPIO_OUT)) {
return;
}
if (not gpio24Drv.open(24,Drv::LinuxGpioDriverComponentImpl::GPIO_OUT)) {
return;
}
if (not gpio25Drv.open(25,Drv::LinuxGpioDriverComponentImpl::GPIO_IN)) {
return;
}
if (not gpio17Drv.open(17,Drv::LinuxGpioDriverComponentImpl::GPIO_IN)) {
return;
}
uartDrv.startReadThread();
// Initialize socket server if and only if there is a valid specification
if (hostname != nullptr && port_number != 0) {
Os::TaskString name("ReceiveTask");
// Uplink is configured for receive so a socket task is started
comm.configure(hostname, port_number);
comm.startSocketTask(name);
}
}
void exitTasks() {
uartDrv.quitReadThread();
linuxTimer.quit();
rateGroup1HzComp.exit();
rateGroup10HzComp.exit();
cmdDisp.exit();
eventLogger.exit();
chanTlm.exit();
prmDb.exit();
fileUplink.exit();
fileDownlink.exit();
cmdSeq.exit();
rpiDemo.exit();
comm.stopSocketTask();
(void) comm.joinSocketTask(nullptr);
cmdSeq.deallocateBuffer(mallocator);
fileUplinkBufferManager.cleanup();
}
| cpp |
fprime | data/projects/fprime/RPI/Top/RPITopologyDefs.cpp | #include "RPI/Top/RPITopologyDefs.hpp"
namespace RPI {
namespace Allocation {
Fw::MallocAllocator mallocator;
}
namespace Init {
bool status = true;
}
}
| cpp |
fprime | data/projects/fprime/RPI/Top/Components.hpp | #ifndef __RPI_COMPONENTS_HEADER__
#define __RPI_COMPONENTS_HEADER__
#include <Svc/ActiveRateGroup/ActiveRateGroupImpl.hpp>
#include <Svc/RateGroupDriver/RateGroupDriverImpl.hpp>
#include <Svc/CmdDispatcher/CommandDispatcherImpl.hpp>
#include <Svc/CmdSequencer/CmdSequencerImpl.hpp>
#include <Svc/PassiveConsoleTextLogger/ConsoleTextLoggerImpl.hpp>
#include <Svc/ActiveLogger/ActiveLoggerImpl.hpp>
#include <Svc/PosixTime/PosixTime.hpp>
#include <Svc/LinuxTimer/LinuxTimerComponentImpl.hpp>
#include <Svc/TlmChan/TlmChanImpl.hpp>
#include <Svc/PrmDb/PrmDbImpl.hpp>
#include <Fw/Obj/SimpleObjRegistry.hpp>
#include <Svc/FileUplink/FileUplink.hpp>
#include <Svc/FileDownlink/FileDownlink.hpp>
#include <Svc/BufferManager/BufferManagerComponentImpl.hpp>
#include <Svc/Health/HealthComponentImpl.hpp>
#include <Svc/StaticMemory/StaticMemoryComponentImpl.hpp>
#include <Svc/Framer/FramerComponentImpl.hpp>
#include <Svc/Deframer/DeframerComponentImpl.hpp>
#include <Drv/TcpClient/TcpClientComponentImpl.hpp>
#include <Svc/AssertFatalAdapter/AssertFatalAdapterComponentImpl.hpp>
#include <Svc/FatalHandler/FatalHandlerComponentImpl.hpp>
// Drivers
#include <Drv/LinuxSerialDriver/LinuxSerialDriverComponentImpl.hpp>
#include <Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp>
#include <Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp>
#include <Drv/TcpClient/TcpClientComponentImpl.hpp>
#include <Drv/Udp/UdpComponentImpl.hpp>
// Main app
#include <RPI/RpiDemo/RpiDemoComponentImpl.hpp>
void constructRPIArchitecture();
void exitTasks();
void constructApp(U32 port_number, char* hostname);
extern Svc::RateGroupDriverImpl rateGroupDriverComp;
extern Svc::ActiveRateGroupImpl rateGroup10HzComp;
extern Svc::ActiveRateGroupImpl rateGroup1HzComp;
extern Svc::CmdSequencerComponentImpl cmdSeq;
extern Svc::ConsoleTextLoggerImpl textLogger;
extern Svc::ActiveLoggerImpl eventLogger;
extern Svc::PosixTime posixTime;
extern Svc::LinuxTimerComponentImpl linuxTimer;
extern Svc::TlmChanImpl chanTlm;
extern Svc::CommandDispatcherImpl cmdDisp;
extern Svc::PrmDbImpl prmDb;
extern Svc::FileUplink fileUplink;
extern Svc::FileDownlink fileDownlink;
extern Svc::BufferManagerComponentImpl fileUplinkBufferManager;
extern Svc::AssertFatalAdapterComponentImpl fatalAdapter;
extern Svc::FatalHandlerComponentImpl fatalHandler;
extern Svc::HealthImpl health;
extern Drv::LinuxSerialDriverComponentImpl uartDrv;
extern Drv::LinuxSpiDriverComponentImpl spiDrv;
extern Drv::LinuxGpioDriverComponentImpl ledDrv;
extern Drv::LinuxGpioDriverComponentImpl gpio23Drv;
extern Drv::LinuxGpioDriverComponentImpl gpio24Drv;
extern Drv::LinuxGpioDriverComponentImpl gpio25Drv;
extern Drv::LinuxGpioDriverComponentImpl gpio17Drv;
extern Rpi::RpiDemoComponentImpl rpiDemo;
extern Svc::StaticMemoryComponentImpl staticMemory;
extern Drv::TcpClientComponentImpl comm;
extern Svc::FramerComponentImpl downlink;
extern Svc::DeframerComponentImpl uplink;
#endif
| hpp |
fprime | data/projects/fprime/RPI/RpiDemo/RpiDemoComponentImplCfg.hpp | /*
* RpiDemoComponentImplCfg.hpp
*
* Created on: Mar 5, 2018
* Author: tim
*/
#ifndef RPI_RPIDEMO_RPIDEMOCOMPONENTIMPLCFG_HPP_
#define RPI_RPIDEMO_RPIDEMOCOMPONENTIMPLCFG_HPP_
namespace RPI {
// configuration values
enum {
NUM_RPI_UART_BUFFERS = 5,
RPI_UART_READ_BUFF_SIZE = 40
};
}
#endif /* RPI_RPIDEMO_RPIDEMOCOMPONENTIMPLCFG_HPP_ */
| hpp |
fprime | data/projects/fprime/RPI/RpiDemo/RpiDemoComponentImpl.hpp | // ======================================================================
// \title RpiDemoImpl.hpp
// \author tcanham
// \brief hpp file for RpiDemo component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef RPI_RpiDemoComponentImpl_HPP
#define RPI_RpiDemoComponentImpl_HPP
#include "RPI/RpiDemo/RpiDemoComponentAc.hpp"
#include <RPI/RpiDemo/RpiDemoComponentImplCfg.hpp>
namespace RPI {
class RpiDemoComponentImpl :
public RpiDemoComponentBase
{
public:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
// A list of contexts for the rate groups
enum {
RG_CONTEXT_1Hz = 10, // 1 Hz cycle
RG_CONTEXT_10Hz = 11 // 10 Hz cycle
};
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object RpiDemo
//!
RpiDemoComponentImpl(
const char *const compName /*!< The component name*/
);
//! Initialize object RpiDemo
//!
void init(
const NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object RpiDemo
//!
~RpiDemoComponentImpl();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for Run
//!
void Run_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!< The call order*/
) override;
//! Handler implementation for UartRead
//!
void UartRead_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &serBuffer, /*!< Buffer containing data*/
const Drv::RecvStatus &status /*!< Status of read*/
) override;
PRIVATE:
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
//! Implementation for RD_SendString command handler
//! Command to send a string to the UART
void RD_SendString_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
const Fw::CmdStringArg& text /*!< String to send*/
) override;
//! Implementation for RD_SetGpio command handler
//! Sets a GPIO port value
void RD_SetGpio_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
RpiDemo_GpioOutNum output, /*!< Output GPIO*/
Fw::Logic value /*!< GPIO value*/
) override;
//! Implementation for RD_GetGpio command handler
//! Gets a GPIO port value
void RD_GetGpio_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
RpiDemo_GpioInNum input /*!< Input GPIO*/
) override;
//! Implementation for RD_SendSpi command handler
//! Sends SPI data, prints read data
void RD_SendSpi_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
const Fw::CmdStringArg& data /*!< data to send*/
) override;
//! Implementation for RD_SetLed command handler
//! Sets LED state
void RD_SetLed_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
RpiDemo_LedState value /*!< GPIO value*/
) override;
//! Implementation for RD_SetLedDivider command handler
//! Sets the divided rate of the LED
void RD_SetLedDivider_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
U32 divider /*!< Divide 10Hz by this number*/
) override;
// This will be called once when task starts up
void preamble() override;
// telemetry values
U32 m_uartWriteBytes;
U32 m_uartReadBytes;
U32 m_spiBytes;
Fw::TlmString m_lastUartMsg;
Fw::Logic m_currLedVal;
// serial buffers
Fw::Buffer m_recvBuffers[NUM_RPI_UART_BUFFERS];
BYTE m_uartBuffers[NUM_RPI_UART_BUFFERS][RPI_UART_READ_BUFF_SIZE];
// LED enabled
bool m_ledOn;
// toggle LED divider
U32 m_ledDivider;
// 10Hz ticks
U32 m_1HzTicks;
// 10Hz ticks
U32 m_10HzTicks;
};
} // end namespace RPI
#endif
| hpp |
fprime | data/projects/fprime/RPI/RpiDemo/RpiDemo.hpp | // ======================================================================
// RpiDemo.hpp
// Standardization header for RpiDemo
// ======================================================================
#ifndef RPI_RpiDemo_HPP
#define RPI_RpiDemo_HPP
#include "RPI/RpiDemo/RpiDemoComponentImpl.hpp"
namespace RPI {
using RpiDemo = RpiDemoComponentImpl;
}
#endif
| hpp |
fprime | data/projects/fprime/RPI/RpiDemo/RpiDemoComponentImpl.cpp | // ======================================================================
// \title RpiDemoImpl.cpp
// \author tcanham
// \brief cpp file for RpiDemo component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <RPI/RpiDemo/RpiDemoComponentImpl.hpp>
#include <FpConfig.hpp>
#include <ctype.h>
namespace RPI {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
RpiDemoComponentImpl ::
RpiDemoComponentImpl(
const char *const compName
) :
RpiDemoComponentBase(compName)
,m_uartWriteBytes(0)
,m_uartReadBytes(0)
,m_spiBytes(0)
,m_currLedVal(Fw::Logic::LOW)
,m_ledOn(true)
,m_ledDivider(10) // start at 1Hz
,m_1HzTicks(0)
,m_10HzTicks(0)
{
}
void RpiDemoComponentImpl ::
init(
const NATIVE_INT_TYPE queueDepth,
const NATIVE_INT_TYPE instance
)
{
RpiDemoComponentBase::init(queueDepth, instance);
}
RpiDemoComponentImpl ::
~RpiDemoComponentImpl()
{
}
void RpiDemoComponentImpl::preamble() {
// check initial state parameter
Fw::ParamValid valid;
RpiDemo_LedState initState = paramGet_RD_PrmLedInitState(valid);
// check status
switch (valid.e) {
// if default or valid, use stored value
case Fw::ParamValid::DEFAULT:
case Fw::ParamValid::VALID:
this->m_ledOn = (RpiDemo_LedState::BLINKING == initState.e);
this->log_ACTIVITY_HI_RD_LedBlinkState(
this->m_ledOn ?
RpiDemo_LedState::BLINKING : RpiDemo_LedState::OFF
);
break;
default:
// use constructor default
break;
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void RpiDemoComponentImpl ::
Run_handler(
const NATIVE_INT_TYPE portNum,
U32 context
)
{
// check which rate group call it is
switch (context) {
case RG_CONTEXT_1Hz:
// write telemetry channels
this->tlmWrite_RD_LastMsg(this->m_lastUartMsg);
this->tlmWrite_RD_UartRecvBytes(this->m_uartReadBytes);
this->tlmWrite_RD_UartSentBytes(this->m_uartWriteBytes);
this->tlmWrite_RD_SpiBytes(this->m_spiBytes);
this->tlmWrite_RD_1HzTicks(this->m_1HzTicks);
this->tlmWrite_RD_10HzTicks(this->m_10HzTicks);
this->m_1HzTicks++;
break;
case RG_CONTEXT_10Hz:
// Toggle LED value
if ( (this->m_10HzTicks++%this->m_ledDivider == 0) and this->m_ledOn) {
this->GpioWrite_out(2, this->m_currLedVal);
this->m_currLedVal = (this->m_currLedVal == Fw::Logic::HIGH) ?
Fw::Logic::LOW : Fw::Logic::HIGH;
}
break;
default:
FW_ASSERT(0, context);
break; // for the code checkers
}
}
void RpiDemoComponentImpl ::
UartRead_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &serBuffer,
const Drv::RecvStatus &status
)
{
if (Drv::RecvStatus::RECV_OK == status.e) {
// convert incoming data to string. If it is not printable, set character to '*'
char uMsg[serBuffer.getSize() + 1];
char *bPtr = reinterpret_cast<char *>(serBuffer.getData());
for (NATIVE_UINT_TYPE byte = 0; byte < serBuffer.getSize(); byte++) {
uMsg[byte] = isalpha(bPtr[byte]) ? bPtr[byte] : '*';
}
uMsg[sizeof(uMsg) - 1] = 0;
Fw::LogStringArg evrMsg(uMsg);
this->log_ACTIVITY_HI_RD_UartMsgIn(evrMsg);
this->m_lastUartMsg = uMsg;
this->m_uartReadBytes += serBuffer.getSize();
}
// return buffer to buffer manager
this->UartBuffers_out(0, serBuffer);
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void RpiDemoComponentImpl ::
RD_SendString_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& text
)
{
Fw::Buffer txt;
txt.setSize(text.length());
txt.setData(reinterpret_cast<U8*>(const_cast<char*>(text.toChar())));
Drv::SendStatus status = this->UartWrite_out(0, txt);
if (Drv::SendStatus::SEND_OK == status.e) {
this->m_uartWriteBytes += text.length();
Fw::LogStringArg arg = text;
this->log_ACTIVITY_HI_RD_UartMsgOut(arg);
}
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void RpiDemoComponentImpl ::
RD_SetGpio_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
RpiDemo_GpioOutNum output, /*!< Output GPIO*/
Fw::Logic value
)
{
NATIVE_INT_TYPE port;
// convert to connected ports
switch (output.e) {
case RpiDemo_GpioOutNum::PIN_23:
port = 0;
break;
case RpiDemo_GpioOutNum::PIN_24:
port = 1;
break; // good values
default: // bad values
this->log_WARNING_HI_RD_InvalidGpio(output.e);
this->cmdResponse_out(
opCode,
cmdSeq,
Fw::CmdResponse::VALIDATION_ERROR
);
return;
}
// set value of GPIO
this->GpioWrite_out(port, value);
this->log_ACTIVITY_HI_RD_GpioSetVal(output.e, value);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void RpiDemoComponentImpl ::
RD_GetGpio_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
RpiDemo_GpioInNum input /*!< Input GPIO*/
)
{
NATIVE_INT_TYPE port;
// convert to connected ports
switch (input.e) {
case RpiDemo_GpioInNum::PIN_25:
port = 0;
break;
case RpiDemo_GpioInNum::PIN_17:
port = 1;
break; // good values
default: // bad values
this->log_WARNING_HI_RD_InvalidGpio(input.e);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::VALIDATION_ERROR);
return;
}
// get value of GPIO input
Fw::Logic val;
this->GpioRead_out(port, val);
this->log_ACTIVITY_HI_RD_GpioGetVal(input.e, val);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void RpiDemoComponentImpl ::
RD_SendSpi_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& data
)
{
// copy data from string to output buffer
char inBuf[data.length()+1];
Fw::Buffer in;
in.setData(reinterpret_cast<U8*>(inBuf));
in.setSize(sizeof(inBuf));
Fw::Buffer out;
out.setData(reinterpret_cast<U8*>(const_cast<char*>(data.toChar())));
out.setSize(data.length());
this->SpiReadWrite_out(0, out, in);
for (NATIVE_UINT_TYPE byte = 0; byte < sizeof(inBuf); byte++) {
inBuf[byte] = isalpha(inBuf[byte])?inBuf[byte]:'*';
}
inBuf[sizeof(inBuf)-1] = 0;
// write reply to event
Fw::LogStringArg arg = inBuf;
this->log_ACTIVITY_HI_RD_SpiMsgIn(arg);
this->m_spiBytes += data.length();
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void RpiDemoComponentImpl ::
RD_SetLed_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
RpiDemo_LedState value
)
{
this->m_ledOn = (RpiDemo_LedState::BLINKING == value.e);
this->log_ACTIVITY_HI_RD_LedBlinkState(
this->m_ledOn ? RpiDemo_LedState::BLINKING : RpiDemo_LedState::OFF);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void RpiDemoComponentImpl ::
RD_SetLedDivider_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
U32 divider
)
{
if (divider < 1) {
this->log_WARNING_HI_RD_InvalidDivider(divider);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::VALIDATION_ERROR);
return;
}
this->m_ledDivider = divider;
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
} // end namespace RPI
| cpp |
fprime | data/projects/fprime/Fw/Deprecate.hpp | // deprecate.hpp:
//
// A minor implementation of compile-time deprecation for the fprime framework.
#ifndef FW_DEPRECATE_HPP
#define FW_DEPRECATE_HPP
#ifndef DEPRECATED
#ifdef __GNUC__
#define DEPRECATED(func, message) func __attribute__ ((deprecated(message)))
#else
#warning "No implementation of DEPRECATED for given compiler. Please check for use of DEPRECATED() functions"
#define DEPRECATED(func) func
#endif
#endif
#endif // FW_DEPRECATE_HPP
| hpp |
fprime | data/projects/fprime/Fw/Obj/SimpleObjRegistry.cpp | #include <Fw/Logger/Logger.hpp>
#include <Fw/Obj/SimpleObjRegistry.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#include <cstring>
#if FW_OBJECT_REGISTRATION == 1
namespace Fw {
SimpleObjRegistry::SimpleObjRegistry() {
ObjBase::setObjRegistry(this);
this->m_numEntries = 0;
// Initialize pointer array
for (NATIVE_INT_TYPE entry = 0; entry < FW_OBJ_SIMPLE_REG_ENTRIES; entry++) {
this->m_objPtrArray[entry] = nullptr;
}
}
SimpleObjRegistry::~SimpleObjRegistry() {
ObjBase::setObjRegistry(nullptr);
}
void SimpleObjRegistry::dump() {
for (NATIVE_INT_TYPE obj = 0; obj < this->m_numEntries; obj++) {
#if FW_OBJECT_NAMES == 1
#if FW_OBJECT_TO_STRING == 1
char objDump[FW_OBJ_SIMPLE_REG_BUFF_SIZE];
this->m_objPtrArray[obj]->toString(objDump,sizeof(objDump));
Fw::Logger::logMsg("Entry: %d Ptr: %p Str: %s\n", obj,
reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]), reinterpret_cast<POINTER_CAST>(objDump));
#else
Fw::Logger::logMsg("Entry: %d Ptr: %p Name: %s\n",obj,
reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]),
reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]->getObjName()));
#endif // FW_OBJECT_TO_STRING
#else
Fw::Logger::logMsg("Entry: %d Ptr: %p Str:\n", obj, reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]));
#endif
}
}
#if FW_OBJECT_NAMES == 1
void SimpleObjRegistry::dump(const char* objName) {
for (NATIVE_INT_TYPE obj = 0; obj < this->m_numEntries; obj++) {
char objDump[FW_OBJ_SIMPLE_REG_BUFF_SIZE];
if (strncmp(objName,this->m_objPtrArray[obj]->getObjName(),sizeof(objDump)) == 0) {
#if FW_OBJECT_TO_STRING == 1
this->m_objPtrArray[obj]->toString(objDump,sizeof(objDump));
Fw::Logger::logMsg("Entry: %d Ptr: %p Str: %s\n", obj,
reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]), reinterpret_cast<POINTER_CAST>(objDump));
#else
Fw::Logger::logMsg("Entry: %d Ptr: %p Name: %s\n",obj,
reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]),
reinterpret_cast<POINTER_CAST>(this->m_objPtrArray[obj]->getObjName()));
#endif
}
}
}
#endif
void SimpleObjRegistry::regObject(ObjBase* obj) {
FW_ASSERT(this->m_numEntries < FW_OBJ_SIMPLE_REG_ENTRIES);
this->m_objPtrArray[this->m_numEntries++] = obj;
}
void SimpleObjRegistry::clear() {
this->m_numEntries = 0;
}
}
#endif
| cpp |
fprime | data/projects/fprime/Fw/Obj/ObjBase.hpp | /**
* \file
* \author T. Canham
* \brief Declarations for Fw::ObjBase and Fw::ObjRegistry
*
* \copyright
* Copyright 2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef FW_OBJ_BASE_HPP
#define FW_OBJ_BASE_HPP
#include <FpConfig.hpp>
#if FW_OBJECT_NAMES == 1
#include <Fw/Types/ObjectName.hpp>
#endif
namespace Fw {
#if FW_OBJECT_REGISTRATION == 1
class ObjRegistry; //!< forward declaration for object registry
#endif
//! \class ObjBase
//! \brief Brief class description
//!
//! This class is the base class of the ISF object class hierarchy.
//! Depending on which features of the architecture are enabled, this class:
//! 1) Stores an object name
//! 2) Provides for object registration
class ObjBase {
public:
#if FW_OBJECT_NAMES == 1
//! \brief Returns the object's name
//!
//! This function returns a pointer to the name of the object
//!
//! \return object name
const char* getObjName(); //!< Returns object name
//! \brief Sets the object name
//!
//! This function takes the provided string and copies it
//! to the private buffer containing the name of the object.
//!
//! \param name the name of the object
void setObjName(const char* name); //!< sets object name
#if FW_OBJECT_TO_STRING == 1
//! \brief Returns a string representation of the object
//!
//! A virtual function defined for all ObjBase types. It is
//! meant to be overridden by subclasses to return a description
//! of the object. The default implementation in this class
//! returns the name of the object.
//!
//! \param str destination buffer where string description is placed
//! \param size destination buffer size (including terminator). String should be terminated
virtual void toString(char* str, NATIVE_INT_TYPE size); //!< virtual method to get description of object
#endif // FW_OBJECT_TO_STRING
#endif // FW_OBJECT_NAMES
#if FW_OBJECT_REGISTRATION == 1
//! \brief static function to set object registry.
//!
//! This function registers an instance of an object registry class (see below).
//! After the registration call is made, any subsequent calls to ObjBase::init()
//! will call the regObject() method on the registry.
//! **NOTE** The call may not be reentrant or thread-safe. The provided
//! SimObjRegistry is not reentrant.
//!
//! \param reg Instance of registry to be stored.
static void setObjRegistry(ObjRegistry* reg); //!< sets the object registry, if desired
#endif
protected:
#if FW_OBJECT_NAMES == 1
Fw::ObjectName m_objName; //!< stores object name
#endif
//! \brief ObjBase constructor
//!
//! The constructor for the base class. Protected so it will only be called
//! by derived classes. Stores the object name (calls setObjName()).
//!
//! \param name Object name
ObjBase(const char* name);
//! \brief Destructor
//!
//! ObjBase destructor. Empty.
//!
virtual ~ObjBase(); //!< Destructor. Should only be called by derived classes
//! \brief Object initializer
//!
//! Initializes the object. For the base class, it calls
//! the object registry if registered by setObjRegistry()
//!
void init(); //!<initialization function that all objects need to implement. Allows static constructors.
private:
#if FW_OBJECT_REGISTRATION == 1
static ObjRegistry* s_objRegistry; //!< static pointer to object registry. Optionally populated.
#endif
}; // ObjBase
#if FW_OBJECT_REGISTRATION == 1
//! \class ObjRegistry
//! \brief Base class declaration for object registry.
//!
//! More detailed class description (Markdown supported)
//!
class ObjRegistry {
public:
//! \brief virtual function called when an object is registered
//!
//! This pure virtual is called through a static ObjRegistry
//! pointer set by a call to ObjBase::setObjRegistry(). It is passed
//! a pointer to the instance of the object. What is done with that
//! pointer is dependent on the derived class implementation.
//! See SimpleObjRegistry for a basic example of a registry.
//!
//! \param obj pointer to object
virtual void regObject(ObjBase* obj)=0;
//! \brief Object registry destructor
//!
//! Destructor. Base class is empty.
//!
virtual ~ObjRegistry();
}; // ObjRegistry
#endif // FW_OBJECT_REGISTRATION
}
#endif // FW_OBJ_BASE_HPP
| hpp |
fprime | data/projects/fprime/Fw/Obj/ObjBase.cpp | #include <FpConfig.hpp>
#include <Fw/Obj/ObjBase.hpp>
#include <cstring>
#include <cstdio>
#include <Fw/Types/Assert.hpp>
namespace Fw {
#if FW_OBJECT_REGISTRATION == 1
ObjRegistry* ObjBase::s_objRegistry = nullptr;
#endif
#if FW_OBJECT_NAMES == 1
ObjBase::ObjBase(const char* objName) {
if (nullptr == objName) {
this->setObjName("NoName");
} else {
this->setObjName(objName);
}
}
#else
ObjBase::ObjBase(const char* objName) {
}
#endif
void ObjBase::init() {
#if FW_OBJECT_REGISTRATION
if (ObjBase::s_objRegistry) {
ObjBase::s_objRegistry->regObject(this);
}
#endif
}
ObjBase::~ObjBase() {
}
#if FW_OBJECT_NAMES == 1
const char* ObjBase::getObjName() {
return this->m_objName.toChar();
}
void ObjBase::setObjName(const char* name) {
this->m_objName = name;
}
#if FW_OBJECT_TO_STRING == 1
void ObjBase::toString(char* str, NATIVE_INT_TYPE size) {
FW_ASSERT(size > 0);
FW_ASSERT(str != nullptr);
PlatformIntType status = snprintf(str, size, "Obj: %s", this->m_objName.toChar());
if (status < 0) {
str[0] = 0;
}
}
#endif
#endif
#if FW_OBJECT_REGISTRATION == 1
void ObjBase::setObjRegistry(ObjRegistry* reg) {
ObjBase::s_objRegistry = reg;
}
ObjRegistry::~ObjRegistry() {
}
#endif
} // Fw
| cpp |
fprime | data/projects/fprime/Fw/Obj/SimpleObjRegistry.hpp | /**
* \file
* \author T. Canham
* \brief Class declaration for a simple object registry
*
* The simple object registry is meant to give a default implementation
* and an example of an object registry. When the registry is instantiated,
* it registers itself with the object base class static function
* setObjRegistry(). Objects then register with the instance as they are
* instantiated. The object registry can then list the objects in its
* registry.
*
* \copyright
* Copyright 2013-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef FW_OBJ_SIMPLE_OBJ_REGISTRY_HPP
#define FW_OBJ_SIMPLE_OBJ_REGISTRY_HPP
#include <FpConfig.hpp>
#include <Fw/Obj/ObjBase.hpp>
#if FW_OBJECT_REGISTRATION == 1
namespace Fw {
class SimpleObjRegistry : public ObjRegistry {
public:
SimpleObjRegistry(); //!< constructor for registry
~SimpleObjRegistry(); //!< destructor for registry
void dump(); //!< dump contents of registry
void clear(); //!< clear registry entries
#if FW_OBJECT_NAMES == 1
void dump(const char* objName); //!< dump a particular object
#endif
private:
void regObject(ObjBase* obj); //!< register an object with the registry
ObjBase* m_objPtrArray[FW_OBJ_SIMPLE_REG_ENTRIES]; //!< array of objects
NATIVE_INT_TYPE m_numEntries; //!< number of entries in the registry
};
}
#endif // FW_OBJECT_REGISTRATION
#endif // FW_OBJ_SIMPLE_OBJ_REGISTRY_HPP
| hpp |
fprime | data/projects/fprime/Fw/FilePacket/Header.cpp | // ======================================================================
// \title Header.cpp
// \author bocchino
// \brief cpp file for FilePacket::Header
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
void FilePacket::Header ::
initialize(
const Type type,
const U32 sequenceIndex
)
{
this->m_type = type;
this->m_sequenceIndex = sequenceIndex;
}
U32 FilePacket::Header ::
bufferSize() const
{
return sizeof(U8) + sizeof(this->m_sequenceIndex);
}
SerializeStatus FilePacket::Header ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
U8 new_type;
SerializeStatus status;
status = serialBuffer.deserialize(new_type);
if (status != FW_SERIALIZE_OK) {
return status;
}
this->m_type = static_cast<Type>(new_type);
status = serialBuffer.deserialize(this->m_sequenceIndex);
return status;
}
SerializeStatus FilePacket::Header ::
toSerialBuffer(SerialBuffer& serialBuffer) const
{
const U8 type_casted = static_cast<U8>(this->m_type);
SerializeStatus status;
status = serialBuffer.serialize(type_casted);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.serialize(this->m_sequenceIndex);
if (status != FW_SERIALIZE_OK)
return status;
return FW_SERIALIZE_OK;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/FilePacket.cpp | // ======================================================================
// \title FilePacket.cpp
// \author bocchino
// \brief cpp file for FilePacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Fw/FilePacket/FilePacket.hpp"
#include "Fw/Types/Assert.hpp"
namespace Fw {
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
SerializeStatus FilePacket ::
fromBuffer(const Buffer& buffer)
{
SerialBuffer serialBuffer(
const_cast<Buffer&>(buffer).getData(),
const_cast<Buffer&>(buffer).getSize()
);
serialBuffer.fill();
const SerializeStatus status = this->fromSerialBuffer(serialBuffer);
return status;
}
const FilePacket::Header& FilePacket ::
asHeader() const
{
return this->m_header;
}
const FilePacket::StartPacket& FilePacket ::
asStartPacket() const
{
FW_ASSERT(this->m_header.m_type == T_START);
return this->m_startPacket;
}
const FilePacket::DataPacket& FilePacket ::
asDataPacket() const
{
FW_ASSERT(this->m_header.m_type == T_DATA);
return this->m_dataPacket;
}
const FilePacket::EndPacket& FilePacket ::
asEndPacket() const
{
FW_ASSERT(this->m_header.m_type == T_END);
return this->m_endPacket;
}
const FilePacket::CancelPacket& FilePacket ::
asCancelPacket() const
{
FW_ASSERT(this->m_header.m_type == T_CANCEL);
return this->m_cancelPacket;
}
void FilePacket ::
fromStartPacket(const StartPacket& startPacket)
{
this->m_startPacket = startPacket;
this->m_header.m_type = T_START;
}
void FilePacket ::
fromDataPacket(const DataPacket& dataPacket)
{
this->m_dataPacket = dataPacket;
this->m_header.m_type = T_DATA;
}
void FilePacket ::
fromEndPacket(const EndPacket& endPacket)
{
this->m_endPacket = endPacket;
this->m_header.m_type = T_END;
}
void FilePacket ::
fromCancelPacket(const CancelPacket& cancelPacket)
{
this->m_cancelPacket = cancelPacket;
this->m_header.m_type = T_CANCEL;
}
U32 FilePacket ::
bufferSize() const
{
switch (this->m_header.m_type) {
case T_START:
return this->m_startPacket.bufferSize();
case T_DATA:
return this->m_dataPacket.bufferSize();
case T_END:
return this->m_endPacket.bufferSize();
case T_CANCEL:
return this->m_cancelPacket.bufferSize();
case T_NONE:
return 0;
default:
FW_ASSERT(0);
return 0;
}
}
SerializeStatus FilePacket ::
toBuffer(Buffer& buffer) const
{
switch (this->m_header.m_type) {
case T_START:
return this->m_startPacket.toBuffer(buffer);
case T_DATA:
return this->m_dataPacket.toBuffer(buffer);
case T_END:
return this->m_endPacket.toBuffer(buffer);
case T_CANCEL:
return this->m_cancelPacket.toBuffer(buffer);
default:
FW_ASSERT(0);
return static_cast<SerializeStatus>(0);
}
}
// ----------------------------------------------------------------------
// Private instance methods
// ----------------------------------------------------------------------
SerializeStatus FilePacket ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
SerializeStatus status;
status = this->m_header.fromSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
switch (this->m_header.m_type) {
case T_START:
status = this->m_startPacket.fromSerialBuffer(serialBuffer);
break;
case T_DATA:
status = this->m_dataPacket.fromSerialBuffer(serialBuffer);
break;
case T_END:
status = this->m_endPacket.fromSerialBuffer(serialBuffer);
break;
case T_CANCEL:
status = this->m_cancelPacket.fromSerialBuffer(serialBuffer);
break;
case T_NONE:
status = FW_DESERIALIZE_TYPE_MISMATCH;
break;
default:
FW_ASSERT(0,status);
break;
}
return status;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/PathName.cpp | // ======================================================================
// \title PathName.cpp
// \author bocchino
// \brief cpp file for FilePacket::PathName
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <cstring>
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
void FilePacket::PathName ::
initialize(const char *const value)
{
const U8 length = static_cast<U8>(StringUtils::string_length(value, MAX_LENGTH));
this->m_length = length;
this->m_value = value;
}
U32 FilePacket::PathName ::
bufferSize() const
{
return sizeof(this->m_length) + this->m_length;
}
SerializeStatus FilePacket::PathName ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
{
const SerializeStatus status =
serialBuffer.deserialize(this->m_length);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const U8* addrLeft = serialBuffer.getBuffAddrLeft();
U8 bytes[MAX_LENGTH];
const SerializeStatus status =
serialBuffer.popBytes(bytes, this->m_length);
if (status != FW_SERIALIZE_OK)
return status;
this->m_value = reinterpret_cast<const char*>(addrLeft);
}
return FW_SERIALIZE_OK;
}
SerializeStatus FilePacket::PathName ::
toSerialBuffer(SerialBuffer& serialBuffer) const
{
{
const SerializeStatus status =
serialBuffer.serialize(this->m_length);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const SerializeStatus status = serialBuffer.pushBytes(
reinterpret_cast<const U8 *>(this->m_value),
this->m_length
);
if (status != FW_SERIALIZE_OK)
return status;
}
return FW_SERIALIZE_OK;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/CancelPacket.cpp | // ======================================================================
// \title CancelPacket.cpp
// \author bocchino
// \brief cpp file for FilePacket::CancelPacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
void FilePacket::CancelPacket ::
initialize(const U32 sequenceIndex)
{
this->m_header.initialize(FilePacket::T_CANCEL, sequenceIndex);
}
U32 FilePacket::CancelPacket ::
bufferSize() const
{
return this->m_header.bufferSize();
}
SerializeStatus FilePacket::CancelPacket ::
toBuffer(Buffer& buffer) const
{
SerialBuffer serialBuffer(
buffer.getData(),
buffer.getSize()
);
return this->m_header.toSerialBuffer(serialBuffer);
}
SerializeStatus FilePacket::CancelPacket ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
FW_ASSERT(this->m_header.m_type == T_CANCEL);
if (serialBuffer.getBuffLeft() != 0)
return FW_DESERIALIZE_SIZE_MISMATCH;
return FW_SERIALIZE_OK;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/DataPacket.cpp | // ======================================================================
// \title DataPacket.cpp
// \author bocchino
// \brief cpp file for FilePacket::DataPacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
void FilePacket::DataPacket ::
initialize(
const U32 sequenceIndex,
const U32 byteOffset,
const U16 dataSize,
const U8 *const data
)
{
this->m_header.initialize(FilePacket::T_DATA, sequenceIndex);
this->m_byteOffset = byteOffset;
this->m_dataSize = dataSize;
this->m_data = data;
}
U32 FilePacket::DataPacket ::
bufferSize() const
{
return
this->m_header.bufferSize() +
sizeof(this->m_byteOffset) +
sizeof(this->m_dataSize) +
this->m_dataSize;
}
SerializeStatus FilePacket::DataPacket ::
toBuffer(Buffer& buffer) const
{
SerialBuffer serialBuffer(
buffer.getData(),
buffer.getSize()
);
return this->toSerialBuffer(serialBuffer);
}
SerializeStatus FilePacket::DataPacket ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
FW_ASSERT(this->m_header.m_type == T_DATA);
SerializeStatus status = serialBuffer.deserialize(this->m_byteOffset);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.deserialize(this->m_dataSize);
if (status != FW_SERIALIZE_OK)
return status;
if (serialBuffer.getBuffLeft() != this->m_dataSize)
return FW_DESERIALIZE_SIZE_MISMATCH;
U8 *const addr = serialBuffer.getBuffAddr();
this->m_data = &addr[this->fixedLengthSize()];
return FW_SERIALIZE_OK;
}
U32 FilePacket::DataPacket ::
fixedLengthSize() const
{
return
this->m_header.bufferSize() +
sizeof(this->m_byteOffset) +
sizeof(this->m_dataSize);
}
SerializeStatus FilePacket::DataPacket ::
toSerialBuffer(SerialBuffer& serialBuffer) const
{
FW_ASSERT(this->m_header.m_type == T_DATA);
SerializeStatus status;
status = this->m_header.toSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.serialize(this->m_byteOffset);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.serialize(this->m_dataSize);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.pushBytes(this->m_data, this->m_dataSize);
return status;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/StartPacket.cpp | // ======================================================================
// \title StartPacket.cpp
// \author bocchino
// \brief cpp file for FilePacket::StartPacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
void FilePacket::StartPacket ::
initialize(
const U32 fileSize,
const char *const sourcePath,
const char *const destinationPath
)
{
this->m_header.initialize(FilePacket::T_START, 0);
this->m_fileSize = fileSize;
this->m_sourcePath.initialize(sourcePath);
this->m_destinationPath.initialize(destinationPath);
}
U32 FilePacket::StartPacket ::
bufferSize() const
{
return this->m_header.bufferSize() +
sizeof(this->m_fileSize) +
this->m_sourcePath.bufferSize() +
this->m_destinationPath.bufferSize();
}
SerializeStatus FilePacket::StartPacket ::
toBuffer(Buffer& buffer) const
{
SerialBuffer serialBuffer(
buffer.getData(),
buffer.getSize()
);
return this->toSerialBuffer(serialBuffer);
}
SerializeStatus FilePacket::StartPacket ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
FW_ASSERT(this->m_header.m_type == T_START);
{
const SerializeStatus status =
serialBuffer.deserialize(this->m_fileSize);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const SerializeStatus status =
this->m_sourcePath.fromSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const SerializeStatus status =
this->m_destinationPath.fromSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
}
return FW_SERIALIZE_OK;
}
SerializeStatus FilePacket::StartPacket ::
toSerialBuffer(SerialBuffer& serialBuffer) const
{
FW_ASSERT(this->m_header.m_type == T_START);
{
const SerializeStatus status =
this->m_header.toSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const SerializeStatus status =
serialBuffer.serialize(this->m_fileSize);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const SerializeStatus status =
this->m_sourcePath.toSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
}
{
const SerializeStatus status =
this->m_destinationPath.toSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
}
return FW_SERIALIZE_OK;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/EndPacket.cpp | // ======================================================================
// \title EndPacket.cpp
// \author bocchino
// \brief cpp file for FilePacket::EndPacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <cstring>
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
void FilePacket::EndPacket ::
initialize(
const U32 sequenceIndex,
const CFDP::Checksum& checksum
)
{
this->m_header.initialize(FilePacket::T_END, sequenceIndex);
this->setChecksum(checksum);
}
U32 FilePacket::EndPacket ::
bufferSize() const
{
return this->m_header.bufferSize() + sizeof(this->m_checksumValue);
}
SerializeStatus FilePacket::EndPacket ::
toBuffer(Buffer& buffer) const
{
SerialBuffer serialBuffer(
buffer.getData(),
buffer.getSize()
);
return this->toSerialBuffer(serialBuffer);
}
void FilePacket::EndPacket ::
setChecksum(const CFDP::Checksum& checksum)
{
this->m_checksumValue = checksum.getValue();
}
void FilePacket::EndPacket ::
getChecksum(CFDP::Checksum& checksum) const
{
CFDP::Checksum c(this->m_checksumValue);
checksum = c;
}
SerializeStatus FilePacket::EndPacket ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
FW_ASSERT(this->m_header.m_type == T_END);
const SerializeStatus status =
serialBuffer.deserialize(this->m_checksumValue);
return status;
}
SerializeStatus FilePacket::EndPacket ::
toSerialBuffer(SerialBuffer& serialBuffer) const
{
FW_ASSERT(this->m_header.m_type == T_END);
SerializeStatus status;
status = this->m_header.toSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.serialize(this->m_checksumValue);
if (status != FW_SERIALIZE_OK)
return status;
return FW_SERIALIZE_OK;
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/FilePacket.hpp | // ======================================================================
// \title FilePacket.hpp
// \author bocchino
// \brief hpp file for FilePacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_FilePacket_HPP
#define Fw_FilePacket_HPP
#include <CFDP/Checksum/Checksum.hpp>
#include <Fw/Buffer/Buffer.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/SerialBuffer.hpp>
#include <Fw/Types/Serializable.hpp>
namespace Fw {
//! \class FilePacket
//! \brief A file packet
//!
union FilePacket {
public:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
//! Packet type
typedef enum {
T_START = 0,
T_DATA = 1,
T_END = 2,
T_CANCEL = 3,
T_NONE = 255
} Type;
//! The type of a path name
class PathName {
friend union FilePacket;
public:
//! The maximum length of a path name
enum { MAX_LENGTH = 255 };
PRIVATE:
//! The length
U8 m_length;
//! Pointer to the path value
const char *m_value;
public:
//! Initialize a PathName
void initialize(
const char *const value //! The path value
);
//! Compute the buffer size needed to hold this PathName
U32 bufferSize() const;
//! Get the length of the path name value
U32 getLength(void) const {
return this->m_length;
};
//! Get the path name value
const char* getValue(void) const {
return this->m_value;
};
PRIVATE:
//! Initialize this PathName from a SerialBuffer
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
//! Write this PathName to a SerialBuffer
SerializeStatus toSerialBuffer(SerialBuffer& serialBuffer) const;
};
//! The type of a packet header
class Header {
friend union FilePacket;
PRIVATE:
//! The packet type
Type m_type;
//! The sequence index
U32 m_sequenceIndex;
public:
//! Header size
enum { HEADERSIZE = sizeof(U8) + sizeof(U32) };
PRIVATE:
//! Initialize a file packet header
void initialize(
const Type type, //!< The packet type
const U32 sequenceIndex //!< The sequence index
);
//! Compute the buffer size needed to hold this Header
U32 bufferSize() const;
//! Initialize this Header from a SerialBuffer
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
//! Write this Header to a SerialBuffer
SerializeStatus toSerialBuffer(SerialBuffer& serialBuffer) const;
public:
Type getType(void) const {
return this->m_type;
};
U32 getSequenceIndex(void) const {
return this->m_sequenceIndex;
};
};
//! The type of a start packet
struct StartPacket {
friend union FilePacket;
PRIVATE:
//! The packet header
Header m_header;
//! The file size
U32 m_fileSize;
//! The source path
PathName m_sourcePath;
//! The destination path
PathName m_destinationPath;
public:
//! Initialize a StartPacket with sequence number 0
void initialize(
const U32 fileSize, //!< The file size
const char *const sourcePath, //!< The source path
const char *const destinationPath //!< The destination path
);
//! Compute the buffer size needed to hold this StartPacket
U32 bufferSize() const;
//! Convert this StartPacket to a Buffer
SerializeStatus toBuffer(Buffer& buffer) const;
//! Get the destination path
const PathName& getDestinationPath() const {
return this->m_destinationPath;
};
//! Get the source path
const PathName& getSourcePath() const {
return this->m_sourcePath;
};
//! Get the file size
U32 getFileSize() const {
return this->m_fileSize;
};
PRIVATE:
//! Initialize this StartPacket from a SerialBuffer
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
//! Write this StartPacket to a SerialBuffer
SerializeStatus toSerialBuffer(SerialBuffer& serialBuffer) const;
};
//! The type of a data packet
class DataPacket {
friend union FilePacket;
PRIVATE:
//! The packet header
Header m_header;
//! The byte offset of the packet data into the destination file
U32 m_byteOffset;
//! The size of the file data in the packet
U16 m_dataSize;
//! Pointer to the file data
const U8 *m_data;
public:
//! header size
enum { HEADERSIZE = Header::HEADERSIZE +
sizeof(U32) +
sizeof(U16) };
//! Initialize a data packet
void initialize(
const U32 sequenceIndex, //!< The sequence index
const U32 byteOffset, //!< The byte offset
const U16 dataSize, //!< The data size
const U8 *const data //!< The file data
);
//! Compute the buffer size needed to hold this DataPacket
U32 bufferSize() const;
//! Convert this DataPacket to a Buffer
SerializeStatus toBuffer(Buffer& buffer) const;
//! Get this as a Header
const FilePacket::Header& asHeader() const {
return this->m_header;
};
//! Get the byte offset
U32 getByteOffset() const {
return this->m_byteOffset;
};
//! Get the data size
U32 getDataSize() const {
return this->m_dataSize;
};
//! Get the data
const U8* getData() const {
return this->m_data;
};
PRIVATE:
//! Initialize this DataPacket from a SerialBuffer
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
//! Compute the fixed-length data size of a StartPacket
U32 fixedLengthSize() const;
//! Write this DataPacket to a SerialBuffer
SerializeStatus toSerialBuffer(SerialBuffer& serialBuffer) const;
};
//! The type of an end packet
class EndPacket {
friend union FilePacket;
PRIVATE:
//! The packet header
Header m_header;
public:
//! Set the checksum
void setChecksum(const CFDP::Checksum& checksum);
//! Get the checksum
void getChecksum(CFDP::Checksum& checksum) const;
//! Compute the buffer size needed to hold this EndPacket
U32 bufferSize() const;
//! Convert this EndPacket to a Buffer
SerializeStatus toBuffer(Buffer& buffer) const;
//! Get this as a Header
const FilePacket::Header& asHeader() const {
return this->m_header;
};
public:
//! Initialize an end packet
void initialize(
const U32 sequenceIndex, //!< The sequence index
const CFDP::Checksum& checksum //!< The checksum
);
PRIVATE:
//! The checksum
U32 m_checksumValue;
//! Initialize this EndPacket from a SerialBuffer
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
//! Write this EndPacket to a SerialBuffer
SerializeStatus toSerialBuffer(SerialBuffer& serialBuffer) const;
};
//! The type of a cancel packet
class CancelPacket {
friend union FilePacket;
PRIVATE:
//! The packet header
Header m_header;
public:
//! Initialize a cancel packet
void initialize(
const U32 sequenceIndex //!< The sequence index
);
//! Compute the buffer size needed to hold this CancelPacket
U32 bufferSize() const;
//! Convert this CancelPacket to a Buffer
SerializeStatus toBuffer(Buffer& buffer) const;
//! Get this as a Header
const FilePacket::Header& asHeader() const {
return this->m_header;
};
PRIVATE:
//! Initialize this CancelPacket from a SerialBuffer
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
};
public:
// ----------------------------------------------------------------------
// Constructor
// ----------------------------------------------------------------------
FilePacket() { this->m_header.m_type = T_NONE; }
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Initialize this from a Buffer
//!
SerializeStatus fromBuffer(const Buffer& buffer);
//! Get this as a Header
//!
const Header& asHeader() const;
//! Get this as a StartPacket
//!
const StartPacket& asStartPacket() const;
//! Get this as a DataPacket
//!
const DataPacket& asDataPacket() const;
//! Get this as an EndPacket
//!
const EndPacket& asEndPacket() const;
//! Get this as a CancelPacket
//!
const CancelPacket& asCancelPacket() const;
//! Initialize this with a StartPacket
//!
void fromStartPacket(const StartPacket& startPacket);
//! Initialize this with a DataPacket
//!
void fromDataPacket(const DataPacket& dataPacket);
//! Initialize this with an EndPacket
//!
void fromEndPacket(const EndPacket& endPacket);
//! Initialize this with a CancelPacket
//!
void fromCancelPacket(const CancelPacket& cancelPacket);
//! Get the buffer size needed to hold this FilePacket
//!
U32 bufferSize() const;
//! Convert this FilePacket to a Buffer
//!
SerializeStatus toBuffer(Buffer& buffer) const;
PRIVATE:
// ----------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------
//! Initialize this from a SerialBuffer
//!
SerializeStatus fromSerialBuffer(SerialBuffer& serialBuffer);
PRIVATE:
// ----------------------------------------------------------------------
// Private data
// ----------------------------------------------------------------------
//! this, seen as a header
//!
Header m_header;
//! this, seen as a Start packet
//!
StartPacket m_startPacket;
//! this, seen as a Data packet
//!
DataPacket m_dataPacket;
//! this, seen as an End packet
//!
EndPacket m_endPacket;
//! this, seen as a Cancel packet
//!
CancelPacket m_cancelPacket;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/Header.cpp | // ======================================================================
// \title Fw/FilePacket/GTest/Header.cpp
// \author bocchino
// \brief Test utilities for file packet headers
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/GTest/FilePackets.hpp>
namespace Fw {
namespace GTest {
void FilePackets::Header ::
compare(
const FilePacket::Header& expected,
const FilePacket::Header& actual
)
{
ASSERT_EQ(expected.m_type, actual.m_type);
ASSERT_EQ(expected.m_sequenceIndex, actual.m_sequenceIndex);
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/FilePackets.hpp | // ======================================================================
// \title Fw/FilePacket/GTest/FilePackets.hpp
// \author bocchino
// \brief hpp file for File Packet testing utilities
//
// \copyright
// Copyright (C) 2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_GTest_FilePackets_HPP
#define Fw_GTest_FilePackets_HPP
#include <gtest/gtest.h>
#include <Fw/FilePacket/FilePacket.hpp>
namespace Fw {
namespace GTest {
//! Utilities for testing File Packet operations
//!
namespace FilePackets {
namespace PathName {
//! Compare two path names
void compare(
const FilePacket::PathName& expected,
const FilePacket::PathName& actual
);
}
namespace Header {
//! Compare two file packet headers
void compare(
const FilePacket::Header& expected,
const FilePacket::Header& actual
);
}
namespace StartPacket {
//! Compare two start packets
void compare(
const FilePacket::StartPacket& expected,
const FilePacket::StartPacket& actual
);
}
namespace DataPacket {
//! Compare two data packets
void compare(
const FilePacket::DataPacket& expected,
const FilePacket::DataPacket& actual
);
}
namespace EndPacket {
//! Compare two end packets
void compare(
const FilePacket::EndPacket& expected,
const FilePacket::EndPacket& actual
);
}
namespace CancelPacket {
//! Compare two cancel packets
void compare(
const FilePacket::CancelPacket& expected,
const FilePacket::CancelPacket& actual
);
}
}
}
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/PathName.cpp | // ======================================================================
// \title Fw/FilePacket/GTest/PathName.cpp
// \author bocchino
// \brief Test utilities for start file packets
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/GTest/FilePackets.hpp>
#include <Fw/Types/GTest/Bytes.hpp>
namespace Fw {
namespace GTest {
void FilePackets::PathName ::
compare(
const FilePacket::PathName& expected,
const FilePacket::PathName& actual
)
{
ASSERT_EQ(expected.m_length, actual.m_length);
Bytes expectedPath(
reinterpret_cast<const U8*>(expected.m_value),
expected.m_length
);
Bytes actualPath(
reinterpret_cast<const U8*>(actual.m_value),
actual.m_length
);
Bytes::compare(expectedPath, actualPath);
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/CancelPacket.cpp | // ======================================================================
// \title Fw/FilePacket/GTest/CancelPacket.cpp
// \author bocchino
// \brief Test utilities for data file packets
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/GTest/FilePackets.hpp>
namespace Fw {
namespace GTest {
void FilePackets::CancelPacket ::
compare(
const FilePacket::CancelPacket& expected,
const FilePacket::CancelPacket& actual
)
{
FilePackets::Header::compare(expected.m_header, actual.m_header);
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/DataPacket.cpp | // ======================================================================
// \title Fw/FilePacket/GTest/DataPacket.cpp
// \author bocchino
// \brief Test utilities for data file packets
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/GTest/FilePackets.hpp>
#include <Fw/Types/GTest/Bytes.hpp>
namespace Fw {
namespace GTest {
void FilePackets::DataPacket ::
compare(
const FilePacket::DataPacket& expected,
const FilePacket::DataPacket& actual
)
{
FilePackets::Header::compare(expected.m_header, actual.m_header);
ASSERT_EQ(expected.m_byteOffset, actual.m_byteOffset);
Bytes expectedData(expected.m_data, expected.m_dataSize);
Bytes actualData(actual.m_data, actual.m_dataSize);
Bytes::compare(expectedData, actualData);
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/StartPacket.cpp | // ======================================================================
// \title Fw/FilePacket/GTest/StartPacket.cpp
// \author bocchino
// \brief Test utilities for start file packets
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/GTest/FilePackets.hpp>
#include <Fw/Types/GTest/Bytes.hpp>
namespace Fw {
namespace GTest {
void FilePackets::StartPacket ::
compare(
const FilePacket::StartPacket& expected,
const FilePacket::StartPacket& actual
)
{
FilePackets::Header::compare(expected.m_header, actual.m_header);
ASSERT_EQ(expected.m_fileSize, actual.m_fileSize);
PathName::compare(expected.m_sourcePath, actual.m_sourcePath);
PathName::compare(expected.m_destinationPath, actual.m_destinationPath);
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/GTest/EndPacket.cpp | // ======================================================================
// \title Fw/FilePacket/GTest/EndPacket.cpp
// \author bocchino
// \brief Test utilities for data file packets
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/GTest/FilePackets.hpp>
#include <CFDP/Checksum/GTest/Checksums.hpp>
#include <Fw/Types/GTest/Bytes.hpp>
namespace Fw {
namespace GTest {
void FilePackets::EndPacket ::
compare(
const FilePacket::EndPacket& expected,
const FilePacket::EndPacket& actual
)
{
FilePackets::Header::compare(expected.m_header, actual.m_header);
CFDP::Checksum expectedChecksum;
CFDP::Checksum actualChecksum;
expected.getChecksum(expectedChecksum);
actual.getChecksum(actualChecksum);
CFDP::GTest::Checksums::compare(expectedChecksum, actualChecksum);
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/FilePacket/test/ut/FilePacketMain.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include <gtest/gtest.h>
#include <Fw/Buffer/Buffer.hpp>
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/FilePacket/GTest/FilePackets.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
// Serialize and deserialize a file packet header
TEST(FilePacket, Header) {
const FilePacket::Header expected = {
FilePacket::T_DATA, // Packet type
10 // Sequence number
};
const U32 size = expected.bufferSize();
U8 bytes[size];
SerialBuffer serialBuffer(bytes, size);
{
const SerializeStatus status =
expected.toSerialBuffer(serialBuffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
FilePacket::Header actual;
{
const SerializeStatus status =
actual.fromSerialBuffer(serialBuffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
GTest::FilePackets::Header::compare(
expected,
actual
);
}
// Serialize and deserialize a start packet
TEST(FilePacket, StartPacket) {
FilePacket::StartPacket expected;
expected.initialize(
10, // File size
"source", // Source path
"dest" // Destination path
);
const U32 size = expected.bufferSize();
U8 bytes[size];
Buffer buffer(bytes, size);
SerialBuffer serialBuffer(bytes, size);
{
const SerializeStatus status =
expected.toBuffer(buffer);
ASSERT_EQ(status, FW_SERIALIZE_OK);
}
FilePacket actual;
{
const SerializeStatus status =
actual.fromBuffer(buffer);
ASSERT_EQ(status, FW_SERIALIZE_OK);
}
const FilePacket::StartPacket& actualStartPacket =
actual.asStartPacket();
GTest::FilePackets::StartPacket::compare(
expected,
actualStartPacket
);
}
// Serialize and deserialize a data packet
TEST(FilePacket, DataPacket) {
FilePacket::DataPacket expected;
const U32 dataSize = 10;
U8 data[dataSize] = {}; // Initialize to appease valgrind
expected.initialize(
3, // Sequence index
42, // Byte offset
dataSize, // Data size
data // Data
);
const U32 size = expected.bufferSize();
U8 bytes[size];
Buffer buffer(bytes, size);
SerialBuffer serialBuffer(bytes, size);
{
const SerializeStatus status =
expected.toBuffer(buffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
FilePacket actual;
{
const SerializeStatus status =
actual.fromBuffer(buffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
const FilePacket::DataPacket& actualDataPacket =
actual.asDataPacket();
GTest::FilePackets::DataPacket::compare(
expected,
actualDataPacket
);
}
// Serialize and deserialize an end packet
TEST(FilePacket, EndPacket) {
FilePacket::EndPacket expected;
const CFDP::Checksum checksum(42);
expected.initialize(
15, // Sequence index
checksum // Checksum
);
const U32 size = expected.bufferSize();
U8 bytes[size];
Buffer buffer(bytes, size);
SerialBuffer serialBuffer(bytes, size);
{
const SerializeStatus status =
expected.toBuffer(buffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
FilePacket actual;
{
const SerializeStatus status =
actual.fromBuffer(buffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
const FilePacket::EndPacket& actualEndPacket =
actual.asEndPacket();
GTest::FilePackets::EndPacket::compare(
expected,
actualEndPacket
);
}
// Serialize and deserialize an end packet
TEST(FilePacket, CancelPacket) {
FilePacket::CancelPacket expected;
const CFDP::Checksum checksum(42);
expected.initialize(
10 // Sequence index
);
const U32 size = expected.bufferSize();
U8 bytes[size];
Buffer buffer(bytes, size);
SerialBuffer serialBuffer(bytes, size);
{
const SerializeStatus status =
expected.toBuffer(buffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
FilePacket actual;
{
const SerializeStatus status =
actual.fromBuffer(buffer);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
const FilePacket::CancelPacket& actualCancelPacket =
actual.asCancelPacket();
GTest::FilePackets::CancelPacket::compare(
expected,
actualCancelPacket
);
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Com/ComPacket.cpp | /*
* ComPacket.cpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#include <Fw/Com/ComPacket.hpp>
namespace Fw {
ComPacket::ComPacket() : m_type(FW_PACKET_UNKNOWN) {
}
ComPacket::~ComPacket() {
}
SerializeStatus ComPacket::serializeBase(SerializeBufferBase& buffer) const {
return buffer.serialize(static_cast<FwPacketDescriptorType>(this->m_type));
}
SerializeStatus ComPacket::deserializeBase(SerializeBufferBase& buffer) {
FwPacketDescriptorType serVal;
SerializeStatus stat = buffer.deserialize(serVal);
if (FW_SERIALIZE_OK == stat) {
this->m_type = static_cast<ComPacketType>(serVal);
}
return stat;
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Com/ComBuffer.cpp | #include <Fw/Com/ComBuffer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
ComBuffer::ComBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
SerializeStatus stat = SerializeBufferBase::setBuff(args,size);
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
ComBuffer::ComBuffer() {
}
ComBuffer::~ComBuffer() {
}
ComBuffer::ComBuffer(const ComBuffer& other) : Fw::SerializeBufferBase() {
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
ComBuffer& ComBuffer::operator=(const ComBuffer& other) {
if(this == &other) {
return *this;
}
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
NATIVE_UINT_TYPE ComBuffer::getBuffCapacity() const {
return sizeof(this->m_bufferData);
}
const U8* ComBuffer::getBuffAddr() const {
return this->m_bufferData;
}
U8* ComBuffer::getBuffAddr() {
return this->m_bufferData;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Com/ComBuffer.hpp | /*
* FwComBuffer.hpp
*
* Created on: May 24, 2014
* Author: tcanham
*/
/*
* Description:
* This object contains the ComBuffer type, used for sending and receiving packets from the ground
*/
#ifndef FW_COM_BUFFER_HPP
#define FW_COM_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
namespace Fw {
class ComBuffer : public SerializeBufferBase {
public:
enum {
SERIALIZED_TYPE_ID = 1010,
SERIALIZED_SIZE = FW_COM_BUFFER_MAX_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of size word
};
ComBuffer(const U8 *args, NATIVE_UINT_TYPE size);
ComBuffer();
ComBuffer(const ComBuffer& other);
virtual ~ComBuffer();
ComBuffer& operator=(const ComBuffer& other);
NATIVE_UINT_TYPE getBuffCapacity() const; // !< returns capacity, not current size, of buffer
U8* getBuffAddr();
const U8* getBuffAddr() const;
private:
U8 m_bufferData[FW_COM_BUFFER_MAX_SIZE]; // packet data buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Com/ComPacket.hpp | /*
* ComPacket.hpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#ifndef COMPACKET_HPP_
#define COMPACKET_HPP_
#include <Fw/Types/Serializable.hpp>
// Packet format:
// |32-bit packet type|packet type-specific data|
namespace Fw {
class ComPacket: public Serializable {
public:
typedef enum {
FW_PACKET_COMMAND, // !< Command packet type - incoming
FW_PACKET_TELEM, // !< Telemetry packet type - outgoing
FW_PACKET_LOG, // !< Log type - outgoing
FW_PACKET_FILE, // !< File type - incoming and outgoing
FW_PACKET_PACKETIZED_TLM, // !< Packetized telemetry packet type
FW_PACKET_DP, //!< Data product packet
FW_PACKET_IDLE, // !< Idle packet
FW_PACKET_UNKNOWN = 0xFF // !< Unknown packet
} ComPacketType;
ComPacket();
virtual ~ComPacket();
protected:
ComPacketType m_type;
SerializeStatus serializeBase(SerializeBufferBase& buffer) const ; // called by derived classes to serialize common fields
SerializeStatus deserializeBase(SerializeBufferBase& buffer); // called by derived classes to deserialize common fields
};
} /* namespace Fw */
#endif /* COMPACKET_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Prm/ParamBuffer.hpp | // Work around inconsistent spelling
#include "PrmBuffer.hpp"
| hpp |
fprime | data/projects/fprime/Fw/Prm/PrmString.cpp | #include <Fw/Prm/PrmString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
ParamString::ParamString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
ParamString::ParamString(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
ParamString::ParamString(const ParamString& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
ParamString::ParamString() : StringBase() {
this->m_buf[0] = 0;
}
ParamString& ParamString::operator=(const ParamString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
ParamString& ParamString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
ParamString& ParamString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
ParamString::~ParamString() {
}
const char* ParamString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE ParamString::getCapacity() const {
return FW_PARAM_STRING_MAX_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Prm/PrmBuffer.cpp | #include <Fw/Prm/PrmBuffer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
ParamBuffer::ParamBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
SerializeStatus stat = SerializeBufferBase::setBuff(args,size);
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
ParamBuffer::ParamBuffer() {
}
ParamBuffer::~ParamBuffer() {
}
ParamBuffer::ParamBuffer(const ParamBuffer& other) : Fw::SerializeBufferBase() {
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
ParamBuffer& ParamBuffer::operator=(const ParamBuffer& other) {
if(this == &other) {
return *this;
}
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
NATIVE_UINT_TYPE ParamBuffer::getBuffCapacity() const {
return sizeof(this->m_bufferData);
}
const U8* ParamBuffer::getBuffAddr() const {
return this->m_bufferData;
}
U8* ParamBuffer::getBuffAddr() {
return this->m_bufferData;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Prm/PrmString.hpp | #ifndef FW_PRM_STRING_TYPE_HPP
#define FW_PRM_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class ParamString : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_PRM_STR,
SERIALIZED_SIZE = FW_PARAM_STRING_MAX_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of two size words
};
ParamString(const char* src);
ParamString(const StringBase& src);
ParamString(const ParamString& src);
ParamString();
ParamString& operator=(const ParamString& other);
ParamString& operator=(const StringBase& other);
ParamString& operator=(const char* other);
~ParamString();
const char* toChar() const;
NATIVE_UINT_TYPE getCapacity() const;
private:
char m_buf[FW_PARAM_STRING_MAX_SIZE];
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Prm/PrmBuffer.hpp | /*
* Cmd.hpp
*
* Created on: Sep 10, 2012
* Author: ppandian
*/
/*
* Description:
* This object contains the ParamBuffer type, used for storing parameters
*/
#ifndef FW_PRM_BUFFER_HPP
#define FW_PRM_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class ParamBuffer : public SerializeBufferBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_PRM_BUFF,
SERIALIZED_SIZE = FW_PARAM_BUFFER_MAX_SIZE + sizeof(FwBuffSizeType)
};
ParamBuffer(const U8 *args, NATIVE_UINT_TYPE size);
ParamBuffer();
ParamBuffer(const ParamBuffer& other);
virtual ~ParamBuffer();
ParamBuffer& operator=(const ParamBuffer& other);
NATIVE_UINT_TYPE getBuffCapacity() const; // !< returns capacity, not current size, of buffer
U8* getBuffAddr();
const U8* getBuffAddr() const;
private:
U8 m_bufferData[FW_PARAM_BUFFER_MAX_SIZE]; // command argument buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/SerializableFile/SerializableFile.hpp | // ======================================================================
// \title SerializableFile.hpp
// \author dinkel
// \brief hpp file for SerializableFile
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_SerializableFile_HPP
#define Fw_SerializableFile_HPP
#include <Fw/Types/Serializable.hpp>
#include <Fw/Types/MemAllocator.hpp>
#include <Fw/Types/SerialBuffer.hpp>
namespace Fw {
//! The type of a packet header
class SerializableFile {
public:
enum Status {
OP_OK,
FILE_OPEN_ERROR,
FILE_WRITE_ERROR,
FILE_READ_ERROR,
DESERIALIZATION_ERROR
};
// NOTE!: This should not be used with an allocator that can return a smaller buffer than requested
SerializableFile(MemAllocator* allocator, NATIVE_UINT_TYPE maxSerializedSize);
~SerializableFile();
Status load(const char* fileName, Serializable& serializable);
Status save(const char* fileName, Serializable& serializable);
PRIVATE:
void reset();
MemAllocator* m_allocator;
bool m_recoverable; // don't care; for allocator
NATIVE_UINT_TYPE m_actualSize; // for checking
SerialBuffer m_buffer;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/SerializableFile/SerializableFile.cpp | // ======================================================================
// \title SerializableFile.cpp
// \author dinkel
// \brief cpp file for SerializableFile
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Fw/SerializableFile/SerializableFile.hpp"
#include "Fw/Types/Assert.hpp"
#include "Os/File.hpp"
namespace Fw {
SerializableFile::SerializableFile(MemAllocator* allocator, NATIVE_UINT_TYPE maxSerializedSize) :
m_allocator(allocator),
m_recoverable(false), // for compiler; not used
m_actualSize(maxSerializedSize),
m_buffer(static_cast<U8*>(this->m_allocator->allocate(0, m_actualSize, m_recoverable)), m_actualSize)
{
// assert if allocator returns smaller size
FW_ASSERT(maxSerializedSize == m_actualSize,maxSerializedSize,m_actualSize);
FW_ASSERT(nullptr != m_buffer.getBuffAddr());
}
SerializableFile::~SerializableFile() {
this->m_allocator->deallocate(0, this->m_buffer.getBuffAddr());
}
SerializableFile::Status SerializableFile::load(const char* fileName, Serializable& serializable) {
Os::File file;
Os::File::Status status;
status = file.open(fileName, Os::File::OPEN_READ);
if( Os::File::OP_OK != status ) {
return FILE_OPEN_ERROR;
}
FwSignedSizeType capacity = static_cast<FwSignedSizeType>(this->m_buffer.getBuffCapacity());
FwSignedSizeType length = static_cast<FwSignedSizeType>(capacity);
status = file.read(this->m_buffer.getBuffAddr(), length, Os::File::WaitType::NO_WAIT);
if( Os::File::OP_OK != status ) {
file.close();
return FILE_READ_ERROR;
}
file.close();
this->reset();
SerializeStatus serStatus;
serStatus = this->m_buffer.setBuffLen(static_cast<NATIVE_UINT_TYPE>(length));
FW_ASSERT(FW_SERIALIZE_OK == serStatus, serStatus);
serStatus = serializable.deserialize(this->m_buffer);
if(FW_SERIALIZE_OK != serStatus) {
return DESERIALIZATION_ERROR;
}
return SerializableFile::OP_OK;
}
SerializableFile::Status SerializableFile::save(const char* fileName, Serializable& serializable) {
this->reset();
SerializeStatus serStatus = serializable.serialize(this->m_buffer);
FW_ASSERT(FW_SERIALIZE_OK == serStatus, serStatus);
Os::File file;
Os::File::Status status;
status = file.open(fileName, Os::File::OPEN_WRITE);
if( Os::File::OP_OK != status ) {
return FILE_OPEN_ERROR;
}
FwSignedSizeType length = static_cast<FwSignedSizeType>(this->m_buffer.getBuffLength());
FwSignedSizeType size = length;
status = file.write(this->m_buffer.getBuffAddr(), length);
if( (Os::File::OP_OK != status) || (length != size)) {
file.close();
return FILE_WRITE_ERROR;
}
file.close();
return SerializableFile::OP_OK;
}
void SerializableFile::reset() {
this->m_buffer.resetSer(); //!< reset to beginning of buffer to reuse for serialization
this->m_buffer.resetDeser(); //!< reset deserialization to beginning
}
}
| cpp |
fprime | data/projects/fprime/Fw/SerializableFile/test/ut/Test.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include <cstring>
#include <cstdio>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/MallocAllocator.hpp>
#include <Fw/SerializableFile/SerializableFile.hpp>
#include <Fw/SerializableFile/test/TestSerializable/TestSerializableAc.hpp>
using namespace Fw;
int main(int argc, char **argv) {
// Create local serializable:
U32 element1 = 4294967284U;
I8 element2 = -18;
F64 element3 = 3.14159;
U32 size = Test::SERIALIZED_SIZE;
Test config(element1, element2, element3);
// Create the serializable file:
MallocAllocator theMallocator;
SerializableFile configFile(&theMallocator, size);
SerializableFile::Status status;
// Save the serializable to a file:
printf("Testing save... ");
status = configFile.save("test.ser", config);
FW_ASSERT(SerializableFile::OP_OK == status, status);
printf("Passed\n");
// Load the serializable from a file:
printf("Testing load... ");
Test config2;
status = configFile.load("test.ser", config2);
FW_ASSERT(SerializableFile::OP_OK == status, status);
printf("Passed\n");
// Compare the results:
printf("Testing compare... ");
FW_ASSERT(config == config2);
printf("Passed\n");
// Test saving to impossible file:
printf("Testing bad save... ");
status = configFile.save("this/file/does/not/exist", config);
FW_ASSERT(SerializableFile::FILE_OPEN_ERROR == status, status);
printf("Passed\n");
// Test reading from nonexistent file:
printf("Testing bad load... ");
Test config3;
status = configFile.load("thisfiledoesnotexist.ser", config3);
FW_ASSERT(SerializableFile::FILE_OPEN_ERROR == status, status);
printf("Passed\n");
return 0;
}
| cpp |
fprime | data/projects/fprime/Fw/Test/String.cpp | #include <Fw/Test/String.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Test {
String::String(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
String::String(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
String::String(const String& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
String::String() : StringBase() {
this->m_buf[0] = 0;
}
String& String::operator=(const String& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
String& String::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
String& String::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
String::~String() {
}
const char* String::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE String::getCapacity() const {
return STRING_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Test/String.hpp | #ifndef TEST_STRING_TYPE_HPP
#define TEST_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Test {
//! A longer string for testing
class String : public Fw::StringBase {
public:
enum {
STRING_SIZE = 256, //!< Storage for string
SERIALIZED_SIZE = STRING_SIZE + sizeof(FwBuffSizeType) //!< Serialized size is size of buffer + size field
};
String(const char* src); //!< char* source constructor
String(const StringBase& src); //!< other string constructor
String(const String& src); //!< String string constructor
String(); //!< default constructor
String& operator=(const String& other); //!< assignment operator
String& operator=(const StringBase& other); //!< other string assignment operator
String& operator=(const char* other); //!< char* assignment operator
~String(); //!< destructor
const char* toChar() const; //!< gets char buffer
NATIVE_UINT_TYPE getCapacity() const ; //!< return buffer size
private:
char m_buf[STRING_SIZE]; //!< storage for string data
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Test/UnitTest.hpp | /**
* \file
* \author T. Canham
* \brief
*
* This contains macros used to document test cases and requirements in unit tests.
* Borrowed from Insight.
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
* <br /><br />
*/
#ifndef TEST_UNITTEST_HPP_
#define TEST_UNITTEST_HPP_
#define TEST_CASE(tc, desc) \
printf("\n***************************************\n"); \
printf("TESTCASE %s: " desc "\n", #tc); \
printf("***************************************\n")
#define REQUIREMENT(str) \
printf("\n***************************************\n"); \
printf("(RQ) %s\n", str); \
printf("***************************************\n")
#define COMMENT(str) \
printf("\n***************************************\n"); \
printf("%s\n", str); \
printf("***************************************\n")
#endif /* TEST_UNITTEST_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Test/UnitTestAssert.hpp | /*
* UnitTestAssert.hpp
*
* Created on: Feb 8, 2016
* Author: tcanham
* Revised July 2020
* Author: bocchino
*/
#ifndef TEST_UNITTESTASSERT_HPP_
#define TEST_UNITTESTASSERT_HPP_
#include <Fw/Test/String.hpp>
#include <Fw/Types/Assert.hpp>
namespace Test {
class UnitTestAssert: public Fw::AssertHook {
public:
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
typedef U32 File;
#else
typedef String File;
#endif
// initial value for File
static const File fileInit;
public:
UnitTestAssert();
virtual ~UnitTestAssert();
// function for hook
void doAssert();
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
);
// retrieves assertion failure values
void retrieveAssert(
File& file,
NATIVE_UINT_TYPE& lineNo,
NATIVE_UINT_TYPE& numArgs,
FwAssertArgType& arg1,
FwAssertArgType& arg2,
FwAssertArgType& arg3,
FwAssertArgType& arg4,
FwAssertArgType& arg5,
FwAssertArgType& arg6
) const;
// check whether assertion failure occurred
bool assertFailed() const;
// clear assertion failure
void clearAssertFailure();
private:
File m_file;
NATIVE_UINT_TYPE m_lineNo;
NATIVE_INT_TYPE m_numArgs;
FwAssertArgType m_arg1;
FwAssertArgType m_arg2;
FwAssertArgType m_arg3;
FwAssertArgType m_arg4;
FwAssertArgType m_arg5;
FwAssertArgType m_arg6;
// Whether an assertion failed
bool m_assertFailed;
};
} /* namespace Test */
#endif /* TEST_UNITTESTASSERT_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Test/UnitTestAssert.cpp | /*
* UnitTestAssert.cpp
*
* Created on: Feb 8, 2016
* Author: tcanham
* Revised July 2020
* Author: bocchino
*/
#include <Fw/Test/UnitTestAssert.hpp>
#include <cstdio>
#include <cstring>
namespace Test {
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
const UnitTestAssert::File UnitTestAssert::fileInit = 0;
#else
const UnitTestAssert::File UnitTestAssert::fileInit = "";
#endif
UnitTestAssert::UnitTestAssert() :
m_file(fileInit),
m_lineNo(0),
m_numArgs(0),
m_arg1(0),
m_arg2(0),
m_arg3(0),
m_arg4(0),
m_arg5(0),
m_arg6(0),
m_assertFailed(false)
{
// register this hook
Fw::AssertHook::registerHook();
}
UnitTestAssert::~UnitTestAssert() {
// deregister the hook
Fw::AssertHook::deregisterHook();
}
void UnitTestAssert::doAssert() {
this->m_assertFailed = true;
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
(void)fprintf(stderr,"Assert: 0x%" PRIx32 ":%" PRI_PlatformUIntType "\n", this->m_file, this->m_lineNo);
#else
(void)fprintf(stderr,"Assert: %s:%" PRI_PlatformUIntType "\n", this->m_file.toChar(), this->m_lineNo);
#endif
}
void UnitTestAssert::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
this->m_file = file;
#else
this->m_file = reinterpret_cast<const char*>(file);
#endif
this->m_lineNo = lineNo;
this->m_numArgs = numArgs;
this->m_arg1 = arg1;
this->m_arg2 = arg2;
this->m_arg3 = arg3;
this->m_arg4 = arg4;
this->m_arg5 = arg5;
this->m_arg6 = arg6;
}
void UnitTestAssert::retrieveAssert(
File& file,
NATIVE_UINT_TYPE& lineNo,
NATIVE_UINT_TYPE& numArgs,
FwAssertArgType& arg1,
FwAssertArgType& arg2,
FwAssertArgType& arg3,
FwAssertArgType& arg4,
FwAssertArgType& arg5,
FwAssertArgType& arg6
) const {
file = this->m_file;
lineNo = this->m_lineNo;
numArgs = this->m_numArgs;
arg1 = this->m_arg1;
arg2 = this->m_arg2;
arg3 = this->m_arg3;
arg4 = this->m_arg4;
arg5 = this->m_arg5;
arg6 = this->m_arg6;
}
bool UnitTestAssert::assertFailed() const {
return this->m_assertFailed;
}
void UnitTestAssert::clearAssertFailure() {
this->m_assertFailed = false;
}
} /* namespace Test */
| cpp |
fprime | data/projects/fprime/Fw/Cfg/ConfigCheck.cpp | /**
* \file
* \author T. Canham
* \brief Configuration checks for ISF configuration macros
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#include <FpConfig.hpp>
#include <limits>
// Check that command/telemetry strings are not larger than an argument buffer
static_assert(FW_CMD_STRING_MAX_SIZE <= FW_CMD_ARG_BUFFER_MAX_SIZE, "FW_CMD_STRING_MAX_SIZE cannot be larger than FW_CMD_ARG_BUFFER_MAX_SIZE");
static_assert(FW_LOG_STRING_MAX_SIZE <= FW_LOG_BUFFER_MAX_SIZE, "FW_LOG_STRING_MAX_SIZE cannot be larger than FW_LOG_BUFFER_MAX_SIZE");
static_assert(FW_TLM_STRING_MAX_SIZE <= FW_TLM_BUFFER_MAX_SIZE, "FW_TLM_STRING_MAX_SIZE cannot be larger than FW_TLM_BUFFER_MAX_SIZE");
static_assert(FW_PARAM_STRING_MAX_SIZE <= FW_PARAM_BUFFER_MAX_SIZE, "FW_PARAM_STRING_MAX_SIZE cannot be larger than FW_PARAM_BUFFER_MAX_SIZE");
// Text logging needs the code generator for serializables to generate a stringified version of the
// value.
static_assert((FW_ENABLE_TEXT_LOGGING == 0) || ( FW_SERIALIZABLE_TO_STRING == 1), "FW_SERIALIZABLE_TO_STRING must be enabled to enable FW_ENABLE_TEXT_LOGGING");
static_assert(std::numeric_limits<FwBuffSizeType>::max() == std::numeric_limits<FwSizeStoreType>::max() &&
std::numeric_limits<FwBuffSizeType>::min() == std::numeric_limits<FwSizeStoreType>::min(),
"FwBuffSizeType must be equivalent to FwExternalSizeType");
static_assert(std::numeric_limits<FwSizeType>::max() >= std::numeric_limits<FwSizeStoreType>::max() &&
std::numeric_limits<FwSizeType>::min() <= std::numeric_limits<FwSizeStoreType>::min(),
"FwSizeType cannot entirely store values of type FwExternalSizeType");
| cpp |
fprime | data/projects/fprime/Fw/Cfg/SerIds.hpp | /**
* \file
* \author T. Canham
* \brief Definitions for ISF type serial IDs
*
* NOTE: Not currently being used
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
* <br /><br />
*/
#ifndef _FW_SER_IDS_HPP_
#define _FW_SER_IDS_HPP_
// Definitions of provided types serialized IDs
// Should fit in 16 bits
namespace Fw {
enum {
// Built-in types
FW_TYPEID_U8 = 10, //!< U8 serialized type id
FW_TYPEID_18 = 11, //!< I8 serialized type id
FW_TYPEID_U16 = 12, //!< U16 serialized type id
FW_TYPEID_I16 = 13, //!< I16 serialized type id
FW_TYPEID_U32 = 14, //!< U32 serialized type id
FW_TYPEID_I32 = 15, //!< I32 serialized type id
FW_TYPEID_U64 = 16, //!< U64 serialized type id
FW_TYPEID_I64 = 17, //!< I64 serialized type id
FW_TYPEID_F32 = 18, //!< F32 serialized type id
FW_TYPEID_F64 = 19, //!< F64 serialized type id
FW_TYPEID_BOOL = 20, //!< boolean serialized type id
FW_TYPEID_PTR = 21, //!< pointer serialized type id
FW_TYPEID_BUFF = 22, //!< buffer serialized type id
// PolyType
FW_TYPEID_POLY = 30, //!< PolyType serialized type id
// Command/Telemetry types
FW_TYPEID_CMD_BUFF = 40, //!< Command Buffer type id
FW_TYPEID_CMD_STR = 41, //!< Command string type id
FW_TYPEID_TLM_BUFF = 42, //!< Telemetry Buffer type id
FW_TYPEID_TLM_STR = 43, //!< Telemetry string type id
FW_TYPEID_LOG_BUFF = 44, //!< Log Buffer type id
FW_TYPEID_LOG_STR = 45, //!< Log string type id
FW_TYPEID_PRM_BUFF = 46, //!< Parameter Buffer type id
FW_TYPEID_PRM_STR = 47, //!< Parameter string type id
FW_TYPEID_FILE_BUFF = 48, //!< File piece Buffer type id
// Other types
FW_TYPEID_EIGHTY_CHAR_STRING = 50, //!< 80 char string Buffer type id
FW_TYPEID_INTERNAL_INTERFACE_STRING = 51, //!< interface string Buffer type id
FW_TYPEID_FIXED_LENGTH_STRING = 52, //!< 256 char string Buffer type id
FW_TYPEID_OBJECT_NAME = 53, //!< ObjectName string Buffer type id
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Cmd/CmdPacket.cpp | /*
* CmdPacket.cpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#include <Fw/Cmd/CmdPacket.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
namespace Fw {
CmdPacket::CmdPacket() : m_opcode(0) {
this->m_type = FW_PACKET_COMMAND;
}
CmdPacket::~CmdPacket() {
}
SerializeStatus CmdPacket::serialize(SerializeBufferBase& buffer) const {
// Shouldn't be called
FW_ASSERT(0);
return FW_SERIALIZE_OK; // for compiler
}
SerializeStatus CmdPacket::deserialize(SerializeBufferBase& buffer) {
SerializeStatus stat = ComPacket::deserializeBase(buffer);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// double check packet type
if (this->m_type != FW_PACKET_COMMAND) {
return FW_DESERIALIZE_TYPE_MISMATCH;
}
stat = buffer.deserialize(this->m_opcode);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// if non-empty, copy data
if (buffer.getBuffLeft()) {
// copy the serialized arguments to the buffer
stat = buffer.copyRaw(this->m_argBuffer,buffer.getBuffLeft());
}
return stat;
}
FwOpcodeType CmdPacket::getOpCode() const {
return this->m_opcode;
}
CmdArgBuffer& CmdPacket::getArgBuffer() {
return this->m_argBuffer;
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Cmd/CmdPacket.hpp | /*
* CmdPacket.hpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#ifndef CMDPACKET_HPP_
#define CMDPACKET_HPP_
#include <Fw/Com/ComPacket.hpp>
#include <Fw/Cmd/CmdArgBuffer.hpp>
namespace Fw {
class CmdPacket : public ComPacket {
public:
CmdPacket();
virtual ~CmdPacket();
SerializeStatus serialize(SerializeBufferBase& buffer) const; //!< serialize contents
SerializeStatus deserialize(SerializeBufferBase& buffer);
FwOpcodeType getOpCode() const;
CmdArgBuffer& getArgBuffer();
protected:
FwOpcodeType m_opcode;
CmdArgBuffer m_argBuffer;
};
} /* namespace Fw */
#endif /* CMDPACKET_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Cmd/CmdString.cpp | #include <Fw/Cmd/CmdString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
CmdStringArg::CmdStringArg(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
CmdStringArg::CmdStringArg(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
CmdStringArg::CmdStringArg(const CmdStringArg& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
CmdStringArg::CmdStringArg() : StringBase() {
this->m_buf[0] = 0;
}
CmdStringArg& CmdStringArg::operator=(const CmdStringArg& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
CmdStringArg& CmdStringArg::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
CmdStringArg& CmdStringArg::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
CmdStringArg::~CmdStringArg() {
}
const char* CmdStringArg::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE CmdStringArg::getCapacity() const {
return FW_CMD_STRING_MAX_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Cmd/CmdString.hpp | #ifndef FW_CMD_STRING_TYPE_HPP
#define FW_CMD_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class CmdStringArg : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_CMD_STR,
SERIALIZED_SIZE = FW_CMD_STRING_MAX_SIZE + sizeof(FwBuffSizeType)
};
CmdStringArg(const char* src);
CmdStringArg(const StringBase& src);
CmdStringArg(const CmdStringArg& src);
CmdStringArg();
CmdStringArg& operator=(const CmdStringArg& other);
CmdStringArg& operator=(const StringBase& other);
CmdStringArg& operator=(const char* other);
~CmdStringArg();
const char* toChar() const;
NATIVE_UINT_TYPE getCapacity() const ; //!< return buffer size
private:
char m_buf[FW_CMD_STRING_MAX_SIZE];
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Cmd/CmdArgBuffer.hpp | /*
*
*
* Created on: March 1, 2014
* Author: T. Canham
*/
/*
* Description:
* This object contains the CmdARgBuffer type, used for holding the serialized arguments of commands
*/
#ifndef FW_CMD_ARG_BUFFER_HPP
#define FW_CMD_ARG_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class CmdArgBuffer : public SerializeBufferBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_CMD_BUFF, //!< type id for CmdArgBuffer
SERIALIZED_SIZE = FW_CMD_ARG_BUFFER_MAX_SIZE + sizeof(I32) //!< size when serialized. Buffer + size of buffer
};
CmdArgBuffer(const U8 *args, NATIVE_UINT_TYPE size); //!< buffer source constructor
CmdArgBuffer(); //!< default constructor
CmdArgBuffer(const CmdArgBuffer& other); //!< other arg buffer constructor
virtual ~CmdArgBuffer(); //!< destructor
CmdArgBuffer& operator=(const CmdArgBuffer& other); //!< Equal operator
NATIVE_UINT_TYPE getBuffCapacity() const; //!< return capacity of buffer (how much it can hold)
U8* getBuffAddr(); //!< return address of buffer (non const version)
const U8* getBuffAddr() const; //!< return address of buffer (const version)
private:
U8 m_bufferData[FW_CMD_ARG_BUFFER_MAX_SIZE]; //!< command argument buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Cmd/CmdArgBuffer.cpp | #include <Fw/Cmd/CmdArgBuffer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
CmdArgBuffer::CmdArgBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
SerializeStatus stat = this->setBuff(args,size);
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
CmdArgBuffer::CmdArgBuffer() {
}
CmdArgBuffer::~CmdArgBuffer() {
}
CmdArgBuffer::CmdArgBuffer(const CmdArgBuffer& other) : Fw::SerializeBufferBase() {
SerializeStatus stat = this->setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
CmdArgBuffer& CmdArgBuffer::operator=(const CmdArgBuffer& other) {
if(this == &other) {
return *this;
}
SerializeStatus stat = this->setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
NATIVE_UINT_TYPE CmdArgBuffer::getBuffCapacity() const {
return sizeof(this->m_bufferData);
}
const U8* CmdArgBuffer::getBuffAddr() const {
return this->m_bufferData;
}
U8* CmdArgBuffer::getBuffAddr() {
return this->m_bufferData;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Logger/LogAssert.hpp | /*
* LogAssert.hpp
*
* Created on: Sep 9, 2016
* Author: tcanham
* Note: this file was originally a log assert file, under Fw::Types. It now made generic
* to log asserts to Fw::Logger
*/
#ifndef LOGGER_LOGASSERT_HPP_
#define LOGGER_LOGASSERT_HPP_
#include <Fw/Types/Assert.hpp>
namespace Fw {
class LogAssertHook: public Fw::AssertHook {
public:
LogAssertHook();
virtual ~LogAssertHook();
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
);
void printAssert(const CHAR* msg);
void doAssert();
};
}
#endif /* VXWORKSLOGASSERT_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Logger/Logger.hpp | /**
* File: Logger.hpp
* Description: Framework logging support
* Author: mstarch
*
* This file adds in support to the core 'Fw' package, to separate it from Os and other loggers, and
* allow the architect of the system to select which core framework logging should be used.
*/
#ifndef _Fw_Logger_hpp_
#define _Fw_Logger_hpp_
#include <FpConfig.hpp>
namespace Fw {
class Logger {
public:
/**
* Function called on the logger to log a message. This is abstract virtual method and
* must be supplied by the subclass. This logger object should be registered with the
* Fw::Log::registerLogger function.
* \param fmt: format string in which to place arguments
* \param a0: zeroth argument. (Default: 0)
* \param a1: first argument. (Default: 0)
* \param a2: second argument. (Default: 0)
* \param a3: third argument. (Default: 0)
* \param a4: fourth argument. (Default: 0)
* \param a5: fifth argument. (Default: 0)
* \param a6: sixth argument. (Default: 0)
* \param a7: seventh argument. (Default: 0)
* \param a8: eighth argument. (Default: 0)
* \param a9: ninth argument. (Default: 0)
*/
virtual void log(
const char* fmt,
POINTER_CAST a0 = 0,
POINTER_CAST a1 = 0,
POINTER_CAST a2 = 0,
POINTER_CAST a3 = 0,
POINTER_CAST a4 = 0,
POINTER_CAST a5 = 0,
POINTER_CAST a6 = 0,
POINTER_CAST a7 = 0,
POINTER_CAST a8 = 0,
POINTER_CAST a9 = 0
) = 0;
/**
* Logs a message using the currently specified static logger. If a logger is not
* registered, then the log message is dropped.
* \param fmt: format string in which to place arguments
* \param a0: zeroth argument. (Default: 0)
* \param a1: first argument. (Default: 0)
* \param a2: second argument. (Default: 0)
* \param a3: third argument. (Default: 0)
* \param a4: fourth argument. (Default: 0)
* \param a5: fifth argument. (Default: 0)
* \param a6: sixth argument. (Default: 0)
* \param a7: seventh argument. (Default: 0)
* \param a8: eighth argument. (Default: 0)
* \param a9: ninth argument. (Default: 0)
*/
static void logMsg(
const char* fmt,
POINTER_CAST a0 = 0,
POINTER_CAST a1 = 0,
POINTER_CAST a2 = 0,
POINTER_CAST a3 = 0,
POINTER_CAST a4 = 0,
POINTER_CAST a5 = 0,
POINTER_CAST a6 = 0,
POINTER_CAST a7 = 0,
POINTER_CAST a8 = 0,
POINTER_CAST a9 = 0
);
/**
* Registers the static logger for use with the Fw::Log::logMsg function. This must be
* a subclass of Fw::Log.
* \param logger: logger to log to when Fw::Log::logMsg is called.
*/
static void registerLogger(Logger* logger);
//!< Static logger to use when calling the above 'logMsg' function
static Logger* s_current_logger;
virtual ~Logger();
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Logger/LogAssert.cpp | /*
* LogAssert.cpp
*
* Created on: Sep 9, 2016
* Author: tcanham
* Note: this file was originally a log assert file, under Fw::Types. It now made generic
* to log asserts to Fw::Logger
*/
#include <Fw/Logger/LogAssert.hpp>
#include <Fw/Logger/Logger.hpp>
#if FW_ASSERT_LEVEL == FW_NO_ASSERT
#else
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
#define fileIdFs "Assert: %d:%d"
#define ASSERT_CAST static_cast<POINTER_CAST>
#else
#define fileIdFs "Assert: \"%s:%d\""
#define ASSERT_CAST reinterpret_cast<POINTER_CAST>
#endif
namespace Fw {
LogAssertHook::LogAssertHook() {
}
LogAssertHook::~LogAssertHook() {
}
void LogAssertHook::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
) {
// Assumption is that file (when string) goes back to static macro in the code and will persist
switch (numArgs) {
case 0:
Fw::Logger::logMsg(fileIdFs,ASSERT_CAST(file),lineNo,0,0,0,0);
break;
case 1:
Fw::Logger::logMsg(fileIdFs " %d\n",ASSERT_CAST(file),lineNo,arg1,0,0,0);
break;
case 2:
Fw::Logger::logMsg(fileIdFs " %d %d\n",ASSERT_CAST(file),lineNo,arg1,arg2,0,0);
break;
case 3:
Fw::Logger::logMsg(fileIdFs " %d %d %d\n",ASSERT_CAST(file),lineNo,arg1,arg2,arg3,0);
break;
case 4:
Fw::Logger::logMsg(fileIdFs " %d %d %d %d\n",ASSERT_CAST(file),lineNo,arg1,arg2,arg3,arg4);
break;
default: // can't fit remainder of arguments in log message
Fw::Logger::logMsg(fileIdFs " %d %d %d %d +\n",ASSERT_CAST(file),lineNo,arg1,arg2,arg3,arg4);
break;
}
}
void LogAssertHook::printAssert(const CHAR* msg) {
// do nothing since reportAssert() sends message
}
void LogAssertHook::doAssert() {
}
} // namespace Fw
#endif
| cpp |
fprime | data/projects/fprime/Fw/Logger/Logger.cpp | /**
* File: Logger.cpp
* Description: Framework logging implementation
* Author: mstarch
*
* This file adds in support to the core 'Fw' package, to separate it from Os and other loggers, and
* allow the architect of the system to select which core framework logging should be used.
*/
#include <Fw/Logger/Logger.hpp>
namespace Fw {
//Initial logger is NULL
Logger* Logger::s_current_logger = nullptr;
// Basic log implementation
void Logger::logMsg(const char* fmt, POINTER_CAST a0, POINTER_CAST a1,
POINTER_CAST a2, POINTER_CAST a3, POINTER_CAST a4, POINTER_CAST a5,
POINTER_CAST a6, POINTER_CAST a7, POINTER_CAST a8, POINTER_CAST a9) {
// Log if capable, otherwise drop
if (Logger::s_current_logger != nullptr) {
Logger::s_current_logger->log(fmt, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
}
}
// Register the logger
void Logger::registerLogger(Logger* logger) {
Logger::s_current_logger = logger;
}
Logger::~Logger() {
}
} //End namespace Fw
| cpp |
fprime | data/projects/fprime/Fw/Logger/test/ut/LoggerMain.cpp | /**
* Main.cpp:
*
* Setup the GTests for rules-based testing of Fw::Logger and runs these tests.
*
* Created on: May 23, 2019
* Author: mstarch
*/
#include <STest/Scenario/Scenario.hpp>
#include <STest/Scenario/RandomScenario.hpp>
#include <STest/Scenario/BoundedScenario.hpp>
#include <Fw/Test/UnitTest.hpp>
#include <Fw/Logger/test/ut/LoggerRules.hpp>
#include <gtest/gtest.h>
#include <cstdio>
#define STEP_COUNT 10000
/**
* A random hopper for rules. Apply STEP_COUNT times.
*/
TEST(LoggerTests, RandomLoggerTests) {
MockLogging::FakeLogger logger;
// Create rules, and assign them into the array
LoggerRules::Register reg("Register");
LoggerRules::LogGood log("Log Successfully");
LoggerRules::LogBad nolog("Log unsuccessfully");
// Setup a list of rules to choose from
STest::Rule<MockLogging::FakeLogger>* rules[] = {
®,
&log,
&nolog
};
// Construct the random scenario and run it with the defined bounds
STest::RandomScenario<MockLogging::FakeLogger> random("Random Rules", rules,
FW_NUM_ARRAY_ELEMENTS(rules));
// Setup a bounded scenario to run rules a set number of times
STest::BoundedScenario<MockLogging::FakeLogger> bounded("Bounded Random Rules Scenario",
random, STEP_COUNT);
// Run!
const U32 numSteps = bounded.run(logger);
printf("Ran %u steps.\n", numSteps);
}
/**
* Test that the most basic logging function works.
*/
TEST(LoggerTests, BasicGoodLogger) {
// Setup and register logger
MockLogging::FakeLogger logger;
Fw::Logger::registerLogger(&logger);
logger.s_current = &logger;
// Basic logging
LoggerRules::LogGood log("Log Successfully");
log.apply(logger);
}
/**
* Test that null-logging function works.
*/
TEST(LoggerTests, BasicBadLogger) {
// Basic discard logging
MockLogging::FakeLogger logger;
Fw::Logger::registerLogger(nullptr);
logger.s_current = nullptr;
LoggerRules::LogBad log("Log Discarded");
log.apply(logger);
}
/**
* Test that registration works. Multiple times, as contains randomness.
*/
TEST(LoggerTests, BasicRegLogger) {
// Basic discard logging
MockLogging::FakeLogger logger;
LoggerRules::Register reg("Register");
reg.apply(logger);
reg.apply(logger);
reg.apply(logger);
reg.apply(logger);
reg.apply(logger);
reg.apply(logger);
reg.apply(logger);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Logger/test/ut/FakeLogger.hpp | /**
* FakeLogger.hpp:
*
* Setup a fake logger for use with the testing. This allows for the capture of messages from the system and ensure that
* the proper log messages are coming through as expected.
*
* @author mstarch
*/
#include <FpConfig.hpp>
#include <Fw/Logger/Logger.hpp>
#ifndef FPRIME_FAKELOGGER_HPP
#define FPRIME_FAKELOGGER_HPP
namespace MockLogging {
/**
* LogMessage data type to map inputs too.
*/
struct LogMessage {
const char *fmt;
POINTER_CAST a0;
POINTER_CAST a1;
POINTER_CAST a2;
POINTER_CAST a3;
POINTER_CAST a4;
POINTER_CAST a5;
POINTER_CAST a6;
POINTER_CAST a7;
POINTER_CAST a8;
POINTER_CAST a9;
};
/**
* Fake logger used for two purposes:
* 1. it acts as logging truth for the test
* 2. it intercepts logging calls bound for the system
*/
class FakeLogger : public Fw::Logger {
public:
//!< Constructor
FakeLogger();
/**
* Fake implementation of the logger.
* @param fmt: format
* @param a0: arg0
* @param a1: arg1
* @param a2: arg2
* @param a3: arg3
* @param a4: arg4
* @param a5: arg5
* @param a6: arg6
* @param a7: arg7
* @param a8: arg8
* @param a9: arg9
*/
void log(
const char *fmt,
POINTER_CAST a0 = 0,
POINTER_CAST a1 = 0,
POINTER_CAST a2 = 0,
POINTER_CAST a3 = 0,
POINTER_CAST a4 = 0,
POINTER_CAST a5 = 0,
POINTER_CAST a6 = 0,
POINTER_CAST a7 = 0,
POINTER_CAST a8 = 0,
POINTER_CAST a9 = 0
);
/**
* Check last message.
* @param fmt: format
* @param a0: arg1
* @param a1: arg1
* @param a2: arg2
* @param a3: arg3
* @param a4: arg4
* @param a5: arg5
* @param a6: arg6
* @param a7: arg6
* @param a8: arg6
* @param a9: arg6
*/
virtual void check(
const char *fmt,
POINTER_CAST a0 = 0,
POINTER_CAST a1 = 0,
POINTER_CAST a2 = 0,
POINTER_CAST a3 = 0,
POINTER_CAST a4 = 0,
POINTER_CAST a5 = 0,
POINTER_CAST a6 = 0,
POINTER_CAST a7 = 0,
POINTER_CAST a8 = 0,
POINTER_CAST a9 = 0
);
//!< Reset this logger
void reset();
//!< Last message that came in
LogMessage m_last;
//!< Logger to use within the system
static Fw::Logger* s_current;
};
};
#endif //FPRIME_FAKELOGGER_HPP
| hpp |
fprime | data/projects/fprime/Fw/Logger/test/ut/LoggerRules.hpp | /**
* LoggerRules.hpp:
*
* This file specifies Rule classes for testing of the Fw::Logger. These rules can then be used by the main testing
* program to test the code.
*
* Logging rules:
*
* 1. a logger can be registered at any time.
* 2. NULL loggers discard log calls
* 3. if a valid logger is registered, the log message is called
*
* @author mstarch
*/
#ifndef FPRIME_LOGGERRULES_HPP
#define FPRIME_LOGGERRULES_HPP
#include <FpConfig.hpp>
#include <Fw/Types/String.hpp>
#include <Fw/Logger/test/ut/FakeLogger.hpp>
#include <STest/STest/Rule/Rule.hpp>
#include <STest/STest/Pick/Pick.hpp>
namespace LoggerRules {
/**
* Register:
*
* Rule to handle the registration of a logger to the global logger. It may also register a "NULL" logger and thus
* stop output logging.
*/
struct Register : public STest::Rule<MockLogging::FakeLogger> {
// Constructor
Register(const Fw::String& name);
// Check for registration, always allowed
bool precondition(const MockLogging::FakeLogger& truth);
// Register NULL or truth as the system logger
void action(MockLogging::FakeLogger& truth);
};
/**
* LogGood:
*
* As long as a non-NULL logger is set as the system logger, then valid log messages should be processed.
*/
struct LogGood : public STest::Rule<MockLogging::FakeLogger> {
// Constructor
LogGood(const Fw::String& name);
// Check for logging, only when not NULL
bool precondition(const MockLogging::FakeLogger& truth);
// Log valid messages
void action(MockLogging::FakeLogger& truth);
};
/**
* LogBad:
*
* As long as a non-NULL logger is set as the system logger, then valid log messages should be processed.
*/
struct LogBad : public STest::Rule<MockLogging::FakeLogger> {
// Constructor
LogBad(const Fw::String& name);
// Check for logging, only when not NULL
bool precondition(const MockLogging::FakeLogger& truth);
// Log valid messages
void action(MockLogging::FakeLogger& truth);
};
};
#endif //FPRIME_LOGGERRULES_HPP
| hpp |
fprime | data/projects/fprime/Fw/Logger/test/ut/LoggerRules.cpp | /**
* LoggerRules.cpp:
*
* This file specifies Rule classes for testing of the Fw::Logger. These rules can then be used by the main testing
* program to test the code.
*
* Logging rules:
*
* 1. a logger can be registered at any time.
* 2. NULL loggers discard log calls
* 3. if a valid logger is registered, the log message is called
*
* @author mstarch
*/
#include "Fw/Logger/test/ut/LoggerRules.hpp"
namespace LoggerRules {
// Constructor
Register::Register(const Fw::String& name) : STest::Rule<MockLogging::FakeLogger>(name.toChar()) {}
// Check for registration, always allowed
bool Register::precondition(const MockLogging::FakeLogger& truth) {
return true;
}
// Register NULL or truth as the system logger
void Register::action(MockLogging::FakeLogger& truth) {
// Select a registration value: 1 -> logger, 0 -> NULL
NATIVE_INT_TYPE random = STest::Pick::lowerUpper(0, 1);
if (random == 1) {
Fw::Logger::registerLogger(&truth);
truth.s_current = &truth;
}
else {
Fw::Logger::registerLogger(nullptr);
truth.s_current = nullptr;
}
ASSERT_EQ(truth.s_current, Fw::Logger::s_current_logger);
}
// Constructor
LogGood::LogGood(const Fw::String& name) : STest::Rule<MockLogging::FakeLogger>(name.toChar()) {}
// Check for logging, only when not NULL
bool LogGood::precondition(const MockLogging::FakeLogger& truth) {
return truth.s_current != nullptr;
}
// Log valid messages
void LogGood::action(MockLogging::FakeLogger& truth) {
NATIVE_INT_TYPE random = STest::Pick::lowerUpper(0, 10);
NATIVE_INT_TYPE ra[10];
for (int i = 0; i < 10; ++i) {
ra[i] = STest::Pick::lowerUpper(0, 0xffffffff);
}
switch (random) {
case 0:
Fw::Logger::logMsg("No args");
truth.check("No args");
break;
case 1:
Fw::Logger::logMsg("One arg: %lu", ra[0]);
truth.check("One arg: %lu", ra[0]);
break;
case 2:
Fw::Logger::logMsg("Two arg: %lu", ra[0], ra[1]);
truth.check("Two arg: %lu", ra[0], ra[1]);
break;
case 3:
Fw::Logger::logMsg("Three arg: %lu", ra[0], ra[1], ra[2]);
truth.check("Three arg: %lu", ra[0], ra[1], ra[2]);
break;
case 4:
Fw::Logger::logMsg("Four arg: %lu", ra[0], ra[1], ra[2], ra[3]);
truth.check("Four arg: %lu", ra[0], ra[1], ra[2], ra[3]);
break;
case 5:
Fw::Logger::logMsg("Five arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4]);
truth.check("Five arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4]);
break;
case 6:
Fw::Logger::logMsg("Six arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5]);
truth.check("Six arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5]);
break;
case 7:
Fw::Logger::logMsg("Seven arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6]);
truth.check("Seven arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6]);
break;
case 8:
Fw::Logger::logMsg("Eight arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7]);
truth.check("Eight arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7]);
break;
case 9:
Fw::Logger::logMsg("Nine arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7], ra[8]);
truth.check("Nine arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7], ra[8]);
break;
case 10:
Fw::Logger::logMsg("Ten arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7], ra[8], ra[9]);
truth.check("Ten arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7], ra[8], ra[9]);
break;
default:
ASSERT_EQ(0, 1);
}
truth.reset();
}
// Constructor
LogBad::LogBad(const Fw::String& name) : STest::Rule<MockLogging::FakeLogger>(name.toChar()) {}
// Check for logging, only when not NULL
bool LogBad::precondition(const MockLogging::FakeLogger& truth) {
return truth.s_current == nullptr;
}
// Log valid messages
void LogBad::action(MockLogging::FakeLogger& truth) {
NATIVE_INT_TYPE random = STest::Pick::lowerUpper(0, 10);
NATIVE_INT_TYPE ra[10];
for (int i = 0; i < 10; ++i) {
ra[i] = STest::Pick::lowerUpper(0, 0xffffffff);
}
switch (random) {
case 0:
Fw::Logger::logMsg("No args");
truth.check(nullptr);
break;
case 1:
Fw::Logger::logMsg("One arg: %lu", ra[0]);
truth.check(nullptr);
break;
case 2:
Fw::Logger::logMsg("Two arg: %lu", ra[0], ra[1]);
truth.check(nullptr);
break;
case 3:
Fw::Logger::logMsg("Three arg: %lu", ra[0], ra[1], ra[2]);
truth.check(nullptr);
break;
case 4:
Fw::Logger::logMsg("Four arg: %lu", ra[0], ra[1], ra[2], ra[3]);
truth.check(nullptr);
break;
case 5:
Fw::Logger::logMsg("Five arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4]);
truth.check(nullptr);
break;
case 6:
Fw::Logger::logMsg("Six arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5]);
truth.check(nullptr);
break;
case 7:
Fw::Logger::logMsg("Seven arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6]);
truth.check(nullptr);
break;
case 8:
Fw::Logger::logMsg("Eight arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7]);
truth.check(nullptr);
break;
case 9:
Fw::Logger::logMsg("Nine arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7], ra[8]);
truth.check(nullptr);
break;
case 10:
Fw::Logger::logMsg("Ten arg: %lu", ra[0], ra[1], ra[2], ra[3], ra[4], ra[5], ra[6], ra[7], ra[8], ra[9]);
truth.check(nullptr);
break;
default:
ASSERT_EQ(0, 1);
}
truth.reset();
}
};
| cpp |
fprime | data/projects/fprime/Fw/Logger/test/ut/FakeLogger.cpp | /**
* FakeLogger.cpp:
*
* Setup a fake logger for use with the testing. This allows for the capture of messages from the system and ensure that
* the proper log messages are coming through as expected.
*
* @author mstarch
*/
#include <gtest/gtest.h>
#include <Fw/Logger/test/ut/FakeLogger.hpp>
namespace MockLogging {
Fw::Logger* FakeLogger::s_current = nullptr;
FakeLogger::FakeLogger() {
memset(&m_last, 0, sizeof(m_last));
}
void FakeLogger::log(
const char *fmt,
POINTER_CAST a0,
POINTER_CAST a1,
POINTER_CAST a2,
POINTER_CAST a3,
POINTER_CAST a4,
POINTER_CAST a5,
POINTER_CAST a6,
POINTER_CAST a7,
POINTER_CAST a8,
POINTER_CAST a9
) {
m_last.fmt = fmt;
m_last.a0 = a0;
m_last.a1 = a1;
m_last.a2 = a2;
m_last.a3 = a3;
m_last.a4 = a4;
m_last.a5 = a5;
m_last.a6 = a6;
m_last.a7 = a7;
m_last.a8 = a8;
m_last.a9 = a9;
}
void FakeLogger::check(
const char *fmt,
POINTER_CAST a0,
POINTER_CAST a1,
POINTER_CAST a2,
POINTER_CAST a3,
POINTER_CAST a4,
POINTER_CAST a5,
POINTER_CAST a6,
POINTER_CAST a7,
POINTER_CAST a8,
POINTER_CAST a9
) {
ASSERT_EQ(m_last.fmt, fmt);
ASSERT_EQ(m_last.a0, a0);
ASSERT_EQ(m_last.a1, a1);
ASSERT_EQ(m_last.a2, a2);
ASSERT_EQ(m_last.a3, a3);
ASSERT_EQ(m_last.a4, a4);
ASSERT_EQ(m_last.a5, a5);
ASSERT_EQ(m_last.a6, a6);
ASSERT_EQ(m_last.a7, a7);
ASSERT_EQ(m_last.a8, a8);
ASSERT_EQ(m_last.a9, a9);
}
void FakeLogger::reset() {
m_last.fmt = nullptr;
m_last.a0 = 0;
m_last.a1 = 0;
m_last.a2 = 0;
m_last.a3 = 0;
m_last.a4 = 0;
m_last.a5 = 0;
m_last.a6 = 0;
m_last.a7 = 0;
m_last.a8 = 0;
m_last.a9 = 0;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Trap/TrapHandler.hpp | #ifndef FW_TRAP_HPP
#define FW_TRAP_HPP
#include <FpConfig.hpp>
namespace Fw {
/**
* TrapHandler:
* A framework class used to handle traps that occur during the execution of the
* the F' framework. Must be registered with a trap register. The user should
* inherit from this class and ensure that the doTrap function is implemented. The
* default implementation will be do-nothing.
*/
class TrapHandler {
public:
TrapHandler() {}; //!< constructor
virtual ~TrapHandler() {}; //!< destructor
/**
* Handles the incoming trap.
* Note: if user does not supply an implementer of this
* function, a do-nothing version will be run.
* \param trap: trap number
*/
virtual void doTrap(U32 trap) = 0;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Dp/DpContainer.hpp | // ======================================================================
// \title DpContainer.hpp
// \author bocchino
// \brief hpp file for DpContainer
// ======================================================================
#ifndef Fw_DpContainer_HPP
#define Fw_DpContainer_HPP
#include "Fw/Buffer/Buffer.hpp"
#include "Fw/Dp/DpStateEnumAc.hpp"
#include "Fw/Time/Time.hpp"
#include "Fw/Types/SuccessEnumAc.hpp"
#include "Utils/Hash/Hash.hpp"
#include "config/FppConstantsAc.hpp"
#include "config/ProcTypeEnumAc.hpp"
namespace Fw {
//! A data product Container
class DpContainer {
public:
// ----------------------------------------------------------------------
// Constants and Types
// ----------------------------------------------------------------------
//! A DpContainer packet header
struct Header {
//! The type of user data
using UserData = U8[DpCfg::CONTAINER_USER_DATA_SIZE];
//! The offset for the packet descriptor field
static constexpr FwSizeType PACKET_DESCRIPTOR_OFFSET = 0;
//! The offset for the id field
static constexpr FwSizeType ID_OFFSET = PACKET_DESCRIPTOR_OFFSET + sizeof(FwPacketDescriptorType);
//! The offset for the priority field
static constexpr FwDpPriorityType PRIORITY_OFFSET = ID_OFFSET + sizeof(FwDpIdType);
//! The offset for the time tag field
static constexpr FwSizeType TIME_TAG_OFFSET = PRIORITY_OFFSET + sizeof(FwDpPriorityType);
//! The offset for the processing types field
static constexpr FwSizeType PROC_TYPES_OFFSET = TIME_TAG_OFFSET + Time::SERIALIZED_SIZE;
//! The offset for the user data field
static constexpr FwSizeType USER_DATA_OFFSET = PROC_TYPES_OFFSET + sizeof(DpCfg::ProcType::SerialType);
//! The offset of the data product state field
static constexpr FwSizeType DP_STATE_OFFSET = USER_DATA_OFFSET + DpCfg::CONTAINER_USER_DATA_SIZE;
//! The offset for the data size field
static constexpr FwSizeType DATA_SIZE_OFFSET = DP_STATE_OFFSET + DpState::SERIALIZED_SIZE;
//! The header size
static constexpr FwSizeType SIZE = DATA_SIZE_OFFSET + sizeof(FwSizeStoreType);
};
//! The header hash offset
static constexpr FwSizeType HEADER_HASH_OFFSET = Header::SIZE;
//! The data offset
static constexpr FwSizeType DATA_OFFSET = HEADER_HASH_OFFSET + HASH_DIGEST_LENGTH;
//! The minimum packet size
//! Reserve space for the header, the header hash, and the data hash
//! This is also the number of non-data bytes in the packet
static constexpr FwSizeType MIN_PACKET_SIZE = Header::SIZE + 2 * HASH_DIGEST_LENGTH;
public:
// ----------------------------------------------------------------------
// Constructor
// ----------------------------------------------------------------------
//! Constructor for initialized container
DpContainer(FwDpIdType id, //!< The container id
const Fw::Buffer& buffer //!< The buffer
);
//! Constructor for container with default initialization
DpContainer();
public:
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Get the container id
//! \return The id
FwDpIdType getId() const { return this->m_id; }
//! Get the data size
//! \return The data size
FwSizeType getDataSize() const { return this->m_dataSize; }
//! Get the packet buffer
//! \return The buffer
Fw::Buffer getBuffer() const { return this->m_buffer; }
//! Get the packet size corresponding to the data size
FwSizeType getPacketSize() const { return getPacketSizeForDataSize(this->m_dataSize); }
//! Get the priority
//! \return The priority
FwDpPriorityType getPriority() const { return this->m_priority; }
//! Get the time tag
//! \return The time tag
Fw::Time getTimeTag() const { return this->m_timeTag; }
//! Get the processing types
//! \return The processing types
DpCfg::ProcType::SerialType getProcTypes() const { return this->m_procTypes; }
//! Get the data product state
DpState getDpState() const { return this->m_dpState; }
//! Deserialize the header from the packet buffer
//! Buffer must be valid, and its size must be at least MIN_PACKET_SIZE
//! Before calling this function, you should call checkHeaderHash() to
//! check the header hash
//! \return The serialize status
Fw::SerializeStatus deserializeHeader();
//! Serialize the header into the packet buffer and update the header hash
//! Buffer must be valid, and its size must be at least MIN_PACKET_SIZE
void serializeHeader();
//! Set the id
void setId(FwDpIdType id //!< The id
) {
this->m_id = id;
}
//! Set the priority
void setPriority(FwDpPriorityType priority //!< The priority
) {
this->m_priority = priority;
}
//! Set the time tag
void setTimeTag(Fw::Time timeTag //!< The time tag
) {
this->m_timeTag = timeTag;
}
//! Set the processing types bit mask
void setProcTypes(DpCfg::ProcType::SerialType procTypes //!< The processing types
) {
this->m_procTypes = procTypes;
}
//! Set the data product state
void setDpState(DpState dpState //!< The data product state
) {
this->m_dpState = dpState;
}
//! Set the data size
void setDataSize(FwSizeType dataSize //!< The data size
) {
this->m_dataSize = dataSize;
}
//! Set the packet buffer
void setBuffer(const Buffer& buffer //!< The packet buffer
);
//! Get the stored header hash
//! \return The hash
Utils::HashBuffer getHeaderHash() const;
//! Compute the header hash from the header data
//! \return The hash
Utils::HashBuffer computeHeaderHash() const;
//! Set the header hash
void setHeaderHash(const Utils::HashBuffer& hash //!< The hash
);
//! Compute and set the header hash
void updateHeaderHash();
//! Check the header hash
Success::T checkHeaderHash(Utils::HashBuffer& storedHash, //!< The stored hash (output)
Utils::HashBuffer& computedHash //!< The computed hash (output)
) const;
//! Get the data hash offset
FwSizeType getDataHashOffset() const {
// Data hash goes after the header, the header hash, and the data
return Header::SIZE + HASH_DIGEST_LENGTH + this->m_dataSize;
}
//! Get the stored data hash
//! \return The hash
Utils::HashBuffer getDataHash() const;
//! Compute the data hash from the data
//! \return The hash
Utils::HashBuffer computeDataHash() const;
//! Set the data hash
void setDataHash(Utils::HashBuffer hash //!< The hash
);
//! Update the data hash
void updateDataHash();
//! Check the data hash
Success::T checkDataHash(Utils::HashBuffer& storedHash, //!< The stored hash (output)
Utils::HashBuffer& computedHash //!< The computed hash (output)
) const;
public:
// ----------------------------------------------------------------------
// Public static functions
// ----------------------------------------------------------------------
//! Get the packet size for a given data size
static constexpr FwSizeType getPacketSizeForDataSize(FwSizeType dataSize //!< The data size
) {
return Header::SIZE + dataSize + 2 * HASH_DIGEST_LENGTH;
}
PRIVATE:
// ----------------------------------------------------------------------
// Private member functions
// ----------------------------------------------------------------------
//! Initialize the user data field
void initUserDataField();
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! The user data
Header::UserData m_userData;
PROTECTED:
// ----------------------------------------------------------------------
// Protected member variables
// ----------------------------------------------------------------------
//! The container id
//! This is a system-global id (component-local id + component base id)
FwDpIdType m_id;
//! The priority
FwDpPriorityType m_priority;
//! The time tag
Time m_timeTag;
//! The processing types
DpCfg::ProcType::SerialType m_procTypes;
//! The data product state
DpState m_dpState;
//! The data size
FwSizeType m_dataSize;
//! The packet buffer
Buffer m_buffer;
//! The data buffer
Fw::ExternalSerializeBuffer m_dataBuffer;
};
} // end namespace Fw
#endif
| hpp |
fprime | data/projects/fprime/Fw/Dp/DpContainer.cpp | // ======================================================================
// \title DpContainer.cpp
// \author bocchino
// \brief cpp file for DpContainer
// ======================================================================
#include <cstring>
#include "Fw/Com/ComPacket.hpp"
#include "Fw/Dp/DpContainer.hpp"
#include "Fw/Types/Assert.hpp"
namespace Fw {
// ----------------------------------------------------------------------
// Constructor
// ----------------------------------------------------------------------
DpContainer::DpContainer(FwDpIdType id, const Fw::Buffer& buffer)
: m_id(id), m_priority(0), m_timeTag(), m_procTypes(0), m_dpState(), m_dataSize(0), m_buffer(), m_dataBuffer() {
// Initialize the user data field
this->initUserDataField();
// Set the packet buffer
// This action also updates the data buffer
this->setBuffer(buffer);
}
DpContainer::DpContainer()
: m_id(0), m_priority(0), m_timeTag(), m_procTypes(0), m_dataSize(0), m_buffer(), m_dataBuffer() {
// Initialize the user data field
this->initUserDataField();
}
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
Fw::SerializeStatus DpContainer::deserializeHeader() {
FW_ASSERT(this->m_buffer.isValid());
Fw::SerializeBufferBase& serializeRepr = this->m_buffer.getSerializeRepr();
// Set buffer length
Fw::SerializeStatus status = serializeRepr.setBuffLen(this->m_buffer.getSize());
// Reset deserialization
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.moveDeserToOffset(Header::PACKET_DESCRIPTOR_OFFSET);
}
// Deserialize the packet type
if (status == Fw::FW_SERIALIZE_OK) {
FwPacketDescriptorType packetDescriptor;
status = serializeRepr.deserialize(packetDescriptor);
if (packetDescriptor != Fw::ComPacket::FW_PACKET_DP) {
status = Fw::FW_SERIALIZE_FORMAT_ERROR;
}
}
// Deserialize the container id
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.deserialize(this->m_id);
}
// Deserialize the priority
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.deserialize(this->m_priority);
}
// Deserialize the time tag
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.deserialize(this->m_timeTag);
}
// Deserialize the processing types
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.deserialize(this->m_procTypes);
}
// Deserialize the user data
if (status == Fw::FW_SERIALIZE_OK) {
const FwSizeType requestedSize = sizeof this->m_userData;
FwSizeType receivedSize = requestedSize;
status = serializeRepr.deserialize(this->m_userData, receivedSize, Fw::Serialization::OMIT_LENGTH);
if (receivedSize != requestedSize) {
status = Fw::FW_DESERIALIZE_SIZE_MISMATCH;
}
}
// Deserialize the data product state
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.deserialize(this->m_dpState);
}
// Deserialize the data size
if (status == Fw::FW_SERIALIZE_OK) {
status = serializeRepr.deserializeSize(this->m_dataSize);
}
return status;
}
void DpContainer::serializeHeader() {
FW_ASSERT(this->m_buffer.isValid());
Fw::SerializeBufferBase& serializeRepr = this->m_buffer.getSerializeRepr();
// Reset serialization
serializeRepr.resetSer();
// Serialize the packet type
Fw::SerializeStatus status =
serializeRepr.serialize(static_cast<FwPacketDescriptorType>(Fw::ComPacket::FW_PACKET_DP));
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the container id
status = serializeRepr.serialize(this->m_id);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the priority
status = serializeRepr.serialize(this->m_priority);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the time tag
status = serializeRepr.serialize(this->m_timeTag);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the processing types
status = serializeRepr.serialize(this->m_procTypes);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the user data
status = serializeRepr.serialize(this->m_userData, static_cast<FwSizeType>(sizeof this->m_userData),
Fw::Serialization::OMIT_LENGTH);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the data product state
status = serializeRepr.serialize(this->m_dpState);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Serialize the data size
status = serializeRepr.serializeSize(this->m_dataSize);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
// Update the header hash
this->updateHeaderHash();
}
void DpContainer::setBuffer(const Buffer& buffer) {
// Set the buffer
this->m_buffer = buffer;
// Check that the buffer is large enough to hold a data product packet with
// zero-size data
const FwSizeType bufferSize = buffer.getSize();
FW_ASSERT(bufferSize >= MIN_PACKET_SIZE, static_cast<FwAssertArgType>(bufferSize),
static_cast<FwAssertArgType>(MIN_PACKET_SIZE));
// Initialize the data buffer
U8* const buffAddr = buffer.getData();
const FwSizeType dataCapacity = buffer.getSize() - MIN_PACKET_SIZE;
// Check that data buffer is in bounds for packet buffer
const FwSizeType minBufferSize = DATA_OFFSET + dataCapacity;
FW_ASSERT(bufferSize >= minBufferSize, static_cast<FwAssertArgType>(bufferSize),
static_cast<FwAssertArgType>(minBufferSize));
U8* const dataAddr = &buffAddr[DATA_OFFSET];
this->m_dataBuffer.setExtBuffer(dataAddr, dataCapacity);
}
Utils::HashBuffer DpContainer::getHeaderHash() const {
const FwSizeType bufferSize = this->m_buffer.getSize();
const FwSizeType minBufferSize = HEADER_HASH_OFFSET + HASH_DIGEST_LENGTH;
FW_ASSERT(bufferSize >= minBufferSize, static_cast<FwAssertArgType>(bufferSize),
static_cast<FwAssertArgType>(minBufferSize));
const U8* const buffAddr = this->m_buffer.getData();
return Utils::HashBuffer(&buffAddr[HEADER_HASH_OFFSET], HASH_DIGEST_LENGTH);
}
Utils::HashBuffer DpContainer::computeHeaderHash() const {
const FwSizeType bufferSize = this->m_buffer.getSize();
FW_ASSERT(bufferSize >= Header::SIZE, static_cast<FwAssertArgType>(bufferSize),
static_cast<FwAssertArgType>(Header::SIZE));
U8* const buffAddr = this->m_buffer.getData();
Utils::HashBuffer computedHash;
Utils::Hash::hash(buffAddr, Header::SIZE, computedHash);
return computedHash;
}
void DpContainer::setHeaderHash(const Utils::HashBuffer& hash) {
const FwSizeType bufferSize = this->m_buffer.getSize();
const FwSizeType minBufferSize = HEADER_HASH_OFFSET + HASH_DIGEST_LENGTH;
FW_ASSERT(bufferSize >= minBufferSize, static_cast<FwAssertArgType>(bufferSize),
static_cast<FwAssertArgType>(minBufferSize));
U8* const buffAddr = this->m_buffer.getData();
(void)::memcpy(&buffAddr[HEADER_HASH_OFFSET], hash.getBuffAddr(), HASH_DIGEST_LENGTH);
}
void DpContainer::updateHeaderHash() {
this->setHeaderHash(this->computeHeaderHash());
}
Success::T DpContainer::checkHeaderHash(Utils::HashBuffer& storedHash, Utils::HashBuffer& computedHash) const {
storedHash = this->getHeaderHash();
computedHash = this->computeHeaderHash();
return (storedHash == computedHash) ? Success::SUCCESS : Success::FAILURE;
}
Utils::HashBuffer DpContainer::getDataHash() const {
const U8* const buffAddr = this->m_buffer.getData();
const FwSizeType dataHashOffset = this->getDataHashOffset();
const FwSizeType bufferSize = this->m_buffer.getSize();
FW_ASSERT(dataHashOffset + HASH_DIGEST_LENGTH <= bufferSize,
static_cast<FwAssertArgType>(dataHashOffset + HASH_DIGEST_LENGTH),
static_cast<FwAssertArgType>(bufferSize));
const U8* const dataHashAddr = &buffAddr[dataHashOffset];
return Utils::HashBuffer(dataHashAddr, HASH_DIGEST_LENGTH);
}
Utils::HashBuffer DpContainer::computeDataHash() const {
U8* const buffAddr = this->m_buffer.getData();
const U8* const dataAddr = &buffAddr[DATA_OFFSET];
const FwSizeType dataSize = this->getDataSize();
const FwSizeType bufferSize = this->m_buffer.getSize();
FW_ASSERT(DATA_OFFSET + dataSize <= bufferSize, static_cast<FwAssertArgType>(DATA_OFFSET + dataSize),
static_cast<FwAssertArgType>(bufferSize));
Utils::HashBuffer computedHash;
Utils::Hash::hash(dataAddr, dataSize, computedHash);
return computedHash;
}
void DpContainer::setDataHash(Utils::HashBuffer hash) {
U8* const buffAddr = this->m_buffer.getData();
const FwSizeType bufferSize = this->m_buffer.getSize();
const FwSizeType dataHashOffset = this->getDataHashOffset();
U8* const dataHashAddr = &buffAddr[dataHashOffset];
FW_ASSERT(dataHashOffset + HASH_DIGEST_LENGTH <= bufferSize,
static_cast<FwAssertArgType>(dataHashOffset + HASH_DIGEST_LENGTH),
static_cast<FwAssertArgType>(bufferSize));
ExternalSerializeBuffer serialBuffer(dataHashAddr, HASH_DIGEST_LENGTH);
hash.resetSer();
const Fw::SerializeStatus status = hash.copyRaw(serialBuffer, HASH_DIGEST_LENGTH);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, static_cast<FwAssertArgType>(status));
}
void DpContainer::updateDataHash() {
this->setDataHash(this->computeDataHash());
}
Success::T DpContainer::checkDataHash(Utils::HashBuffer& storedHash, Utils::HashBuffer& computedHash) const {
storedHash = this->getDataHash();
computedHash = this->computeDataHash();
return (computedHash == storedHash) ? Success::SUCCESS : Success::FAILURE;
}
// ----------------------------------------------------------------------
// Private member functions
// ----------------------------------------------------------------------
void DpContainer::initUserDataField() {
(void)::memset(this->m_userData, 0, sizeof this->m_userData);
}
} // namespace Fw
| cpp |
fprime | data/projects/fprime/Fw/Dp/test/util/DpContainerHeader.hpp | // ======================================================================
// \title DpContainerHeader.hpp
// \author bocchino
// \brief hpp file for DpContainer header test utility
// ======================================================================
#ifndef Fw_TestUtil_DpContainerHeader_HPP
#define Fw_TestUtil_DpContainerHeader_HPP
#include "gtest/gtest.h"
#include "FpConfig.hpp"
#include "Fw/Com/ComPacket.hpp"
#include "Fw/Dp/DpContainer.hpp"
#define DP_CONTAINER_HEADER_ASSERT_MSG(actual, expected) \
<< file << ":" << line << "\n" \
<< " Actual value is " << actual << "\n" \
<< " Expected value is " << expected
#define DP_CONTAINER_HEADER_ASSERT_EQ(actual, expected) \
ASSERT_EQ(actual, expected) DP_CONTAINER_HEADER_ASSERT_MSG(actual, expected)
#define DP_CONTAINER_HEADER_ASSERT_GE(actual, expected) \
ASSERT_GE(actual, expected) DP_CONTAINER_HEADER_ASSERT_MSG(actual, expected)
namespace Fw {
namespace TestUtil {
//! A container packet header for testing
struct DpContainerHeader {
DpContainerHeader() : m_id(0), m_priority(0), m_timeTag(), m_procTypes(0), m_dpState(), m_dataSize(0) {}
//! Move the buffer deserialization to the specified offset
static void moveDeserToOffset(const char* const file, //!< The call site file name
const U32 line, //!< The call site line number
Buffer& buffer, //!< The buffer
FwSizeType offset //!< The offset
) {
Fw::SerializeBufferBase& serializeRepr = buffer.getSerializeRepr();
// Reset deserialization
Fw::SerializeStatus status = serializeRepr.setBuffLen(buffer.getSize());
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
status = serializeRepr.moveDeserToOffset(offset);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
}
//! Deserialize a header from a packet buffer
//! Check that the serialization succeeded at every step
//! Check the header hash and the data hash
void deserialize(const char* const file, //!< The call site file name
const U32 line, //!< The call site line number
Fw::Buffer& buffer //!< The packet buffer
) {
Fw::SerializeBufferBase& serializeRepr = buffer.getSerializeRepr();
// Deserialize the packet descriptor
FwPacketDescriptorType packetDescriptor = Fw::ComPacket::FW_PACKET_UNKNOWN;
// Deserialize the packet descriptor
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::PACKET_DESCRIPTOR_OFFSET);
Fw::SerializeStatus status = serializeRepr.deserialize(packetDescriptor);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
DP_CONTAINER_HEADER_ASSERT_EQ(packetDescriptor, Fw::ComPacket::FW_PACKET_DP);
// Deserialize the container id
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::ID_OFFSET);
status = serializeRepr.deserialize(this->m_id);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
// Deserialize the priority
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::PRIORITY_OFFSET);
status = serializeRepr.deserialize(this->m_priority);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
// Deserialize the time tag
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::TIME_TAG_OFFSET);
status = serializeRepr.deserialize(this->m_timeTag);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
// Deserialize the processing type
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::PROC_TYPES_OFFSET);
status = serializeRepr.deserialize(this->m_procTypes);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
// Deserialize the user data
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::USER_DATA_OFFSET);
NATIVE_UINT_TYPE size = sizeof this->m_userData;
const bool omitLength = true;
status = serializeRepr.deserialize(this->m_userData, size, omitLength);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
DP_CONTAINER_HEADER_ASSERT_EQ(size, sizeof this->m_userData);
// Deserialize the data product state
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::DP_STATE_OFFSET);
status = serializeRepr.deserialize(this->m_dpState);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
// Deserialize the data size
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::Header::DATA_SIZE_OFFSET);
status = serializeRepr.deserializeSize(this->m_dataSize);
DP_CONTAINER_HEADER_ASSERT_EQ(status, FW_SERIALIZE_OK);
// After deserializing time, the deserialization index should be at
// the header hash offset
checkDeserialAtOffset(serializeRepr, DpContainer::HEADER_HASH_OFFSET);
// Check the header hash
checkHeaderHash(file, line, buffer);
// Check the data hash
this->checkDataHash(file, line, buffer);
// Move the deserialization pointer to the data offset
DpContainerHeader::moveDeserToOffset(file, line, buffer, DpContainer::DATA_OFFSET);
}
//! Check the header hash
static void checkHeaderHash(const char* const file, //!< The call site file name
const U32 line, //!< The call site line number
Fw::Buffer& buffer //!< The packet buffer
) {
Utils::HashBuffer computedHashBuffer;
U8* const buffAddr = buffer.getData();
Utils::Hash::hash(buffAddr, DpContainer::Header::SIZE, computedHashBuffer);
Utils::HashBuffer storedHashBuffer(&buffAddr[DpContainer::HEADER_HASH_OFFSET], HASH_DIGEST_LENGTH);
DP_CONTAINER_HEADER_ASSERT_EQ(computedHashBuffer, storedHashBuffer);
}
//! Check the data hash
void checkDataHash(const char* const file, //!< The call site file name
const U32 line, //!< The call site line number
Fw::Buffer& buffer //!< The packet buffer
) {
Utils::HashBuffer computedHashBuffer;
U8* const buffAddrBase = buffer.getData();
U8* const dataAddr = &buffAddrBase[DpContainer::DATA_OFFSET];
Utils::Hash::hash(dataAddr, static_cast<U32>(this->m_dataSize), computedHashBuffer);
DpContainer container(this->m_id, buffer);
container.setDataSize(this->m_dataSize);
const FwSizeType dataHashOffset = container.getDataHashOffset();
Utils::HashBuffer storedHashBuffer(&buffAddrBase[dataHashOffset], HASH_DIGEST_LENGTH);
DP_CONTAINER_HEADER_ASSERT_EQ(computedHashBuffer, storedHashBuffer);
}
//! Check a packet header against a buffer
void check(const char* const file, //!< The call site file name
const U32 line, //!< The call site line number
const Fw::Buffer& buffer, //!< The buffer
FwDpIdType id, //!< The expected id
FwDpPriorityType priority, //!< The expected priority
const Fw::Time& timeTag, //!< The expected time tag
DpCfg::ProcType::SerialType procTypes, //!< The expected processing types
const DpContainer::Header::UserData& userData, //!< The expected user data
DpState dpState, //!< The expected dp state
FwSizeType dataSize //!< The expected data size
) const {
// Check the buffer size
const FwSizeType bufferSize = buffer.getSize();
const FwSizeType minBufferSize = Fw::DpContainer::MIN_PACKET_SIZE;
DP_CONTAINER_HEADER_ASSERT_GE(bufferSize, minBufferSize);
// Check the container id
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_id, id);
// Check the priority
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_priority, priority);
// Check the time tag
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_timeTag, timeTag);
// Check the deserialized processing types
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_procTypes, procTypes);
// Check the user data
for (FwSizeType i = 0; i < DpCfg::CONTAINER_USER_DATA_SIZE; ++i) {
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_userData[i], userData[i]);
}
// Check the deserialized data product state
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_dpState, dpState);
// Check the data size
DP_CONTAINER_HEADER_ASSERT_EQ(this->m_dataSize, dataSize);
}
//! Check that the serialize repr is at the specified deserialization offset
static void checkDeserialAtOffset(SerializeBufferBase& serialRepr, //!< The serialize repr
FwSizeType offset //!< The offset
) {
const U8* buffAddr = serialRepr.getBuffAddr();
const U8* buffAddrLeft = serialRepr.getBuffAddrLeft();
ASSERT_EQ(buffAddrLeft, &buffAddr[offset]);
}
//! The container id
FwDpIdType m_id;
//! The priority
FwDpPriorityType m_priority;
//! The time tag
Time m_timeTag;
//! The processing types
DpCfg::ProcType::SerialType m_procTypes;
//! The user data
U8 m_userData[DpCfg::CONTAINER_USER_DATA_SIZE];
//! The data product state
DpState m_dpState;
//! The data size
FwSizeType m_dataSize;
};
} // namespace TestUtil
} // end namespace Fw
#endif
| hpp |
fprime | data/projects/fprime/Fw/Dp/test/ut/TestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include <cstring>
#include <limits>
#include "gtest/gtest.h"
#include "Fw/Dp/DpContainer.hpp"
#include "Fw/Dp/test/util/DpContainerHeader.hpp"
#include "Fw/Test/UnitTest.hpp"
#include "STest/Pick/Pick.hpp"
#include "STest/Random/Random.hpp"
using namespace Fw;
constexpr FwSizeType DATA_SIZE = 100;
constexpr FwSizeType PACKET_SIZE = DpContainer::getPacketSizeForDataSize(DATA_SIZE);
U8 bufferData[PACKET_SIZE];
DpContainer::Header::UserData userData;
void checkHeader(FwDpIdType id, Fw::Buffer& buffer, DpContainer& container) {
// Check the packet size
const FwSizeType expectedPacketSize = Fw::DpContainer::MIN_PACKET_SIZE;
ASSERT_EQ(container.getPacketSize(), expectedPacketSize);
// Set the priority
const FwDpPriorityType priority = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpPriorityType>::max());
container.setPriority(priority);
// Set the time tag
const U32 seconds = STest::Pick::any();
const U32 useconds = STest::Pick::startLength(0, 1000000);
Fw::Time timeTag(seconds, useconds);
container.setTimeTag(timeTag);
// Set the processing types
const FwSizeType numProcTypeStates = 1 << DpCfg::ProcType::NUM_CONSTANTS;
const DpCfg::ProcType::SerialType procTypes = STest::Pick::startLength(0, numProcTypeStates);
container.setProcTypes(procTypes);
// Set the user data
for (U8& data : userData) {
data = static_cast<U8>(STest::Pick::any());
}
FW_ASSERT(sizeof userData == sizeof container.m_userData);
(void)::memcpy(container.m_userData, userData, sizeof container.m_userData);
// Set the DP state
const DpState dpState(static_cast<DpState::T>(STest::Pick::startLength(0, DpState::NUM_CONSTANTS)));
container.setDpState(dpState);
// Set the data size
container.setDataSize(DATA_SIZE);
// Test serialization: Serialize the header
container.serializeHeader();
TestUtil::DpContainerHeader header;
// Update the data hash
container.updateDataHash();
// Deserialize the header and check the hashes
header.deserialize(__FILE__, __LINE__, buffer);
// Check the deserialized header fields
header.check(__FILE__, __LINE__, buffer, id, priority, timeTag, procTypes, userData, dpState, DATA_SIZE);
// Test deserialization: Deserialize the header into a new container
DpContainer deserContainer;
deserContainer.setBuffer(container.getBuffer());
const Fw::SerializeStatus serialStatus = deserContainer.deserializeHeader();
ASSERT_EQ(serialStatus, Fw::FW_SERIALIZE_OK);
// Clear out the header in the buffer
FW_ASSERT(buffer.isValid());
::memset(buffer.getData(), 0, DpContainer::Header::SIZE);
// Serialize the header from the new container
deserContainer.serializeHeader();
// Deserialize and check the header
header.deserialize(__FILE__, __LINE__, buffer);
header.check(__FILE__, __LINE__, buffer, id, priority, timeTag, procTypes, userData, dpState, DATA_SIZE);
// Test the flight code that checks the hashes
Utils::HashBuffer storedHash;
Utils::HashBuffer computedHash;
Fw::Success status = deserContainer.checkHeaderHash(storedHash, computedHash);
ASSERT_EQ(status, Fw::Success::SUCCESS);
ASSERT_EQ(storedHash, computedHash);
status = deserContainer.checkDataHash(storedHash, computedHash);
ASSERT_EQ(status, Fw::Success::SUCCESS);
ASSERT_EQ(storedHash, computedHash);
}
void checkBuffers(DpContainer& container, FwSizeType bufferSize) {
// Check the packet buffer
ASSERT_EQ(container.m_buffer.getSize(), bufferSize);
// Check the data buffer
U8* const buffPtr = container.m_buffer.getData();
U8* const dataPtr = &buffPtr[Fw::DpContainer::DATA_OFFSET];
const FwSizeType dataCapacity = container.m_buffer.getSize() - Fw::DpContainer::MIN_PACKET_SIZE;
ASSERT_EQ(container.m_dataBuffer.getBuffAddr(), dataPtr);
ASSERT_EQ(container.m_dataBuffer.getBuffCapacity(), dataCapacity);
}
void fillWithData(Fw::Buffer& buffer) {
U8* const buffAddrBase = buffer.getData();
U8* const dataAddr = &buffAddrBase[DpContainer::DATA_OFFSET];
for (FwSizeType i = 0; i < DATA_SIZE; i++) {
dataAddr[i] = static_cast<U8>(STest::Pick::any());
}
}
TEST(Header, BufferInConstructor) {
COMMENT("Test header serialization with buffer in constructor");
// Create a buffer
Fw::Buffer buffer(bufferData, sizeof bufferData);
// Fill with data
fillWithData(buffer);
// Use the buffer to create a container
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
DpContainer container(id, buffer);
// Check the header
checkHeader(id, buffer, container);
// Check the buffers
checkBuffers(container, sizeof bufferData);
// Perturb the header hash
Utils::HashBuffer goodHash = container.getHeaderHash();
Utils::HashBuffer badHash = goodHash;
++(badHash.getBuffAddr()[0]);
container.setHeaderHash(badHash);
// Check that the hashes don't match
Utils::HashBuffer storedHash;
Utils::HashBuffer computedHash;
Fw::Success status = container.checkHeaderHash(storedHash, computedHash);
ASSERT_EQ(status, Fw::Success::FAILURE);
ASSERT_EQ(storedHash, badHash);
ASSERT_EQ(computedHash, goodHash);
// Perturb the data hash
goodHash = container.getDataHash();
badHash = goodHash;
++(badHash.getBuffAddr()[0]);
container.setDataHash(badHash);
// Check that the hashes don't match
status = container.checkDataHash(storedHash, computedHash);
ASSERT_EQ(status, Fw::Success::FAILURE);
ASSERT_EQ(storedHash, badHash);
ASSERT_EQ(computedHash, goodHash);
}
TEST(Header, BufferSet) {
COMMENT("Test header serialization with buffer set");
// Create a buffer
Fw::Buffer buffer(bufferData, sizeof bufferData);
// Fill with data
fillWithData(buffer);
// Use the buffer to create a container
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
DpContainer container;
container.setId(id);
container.setBuffer(buffer);
// Check the header
checkHeader(id, buffer, container);
// Check the buffers
checkBuffers(container, sizeof bufferData);
}
TEST(Header, BadPacketDescriptor) {
COMMENT("Test header serialization with bad packet descriptor");
// Create a buffer
Fw::Buffer buffer(bufferData, sizeof bufferData);
// Set the packet descriptor to a bad value
Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr();
const FwPacketDescriptorType badPacketDescriptor = Fw::ComPacket::FW_PACKET_DP + 1;
Fw::SerializeStatus status = serialRepr.serialize(badPacketDescriptor);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
// Use the buffer to create a container
DpContainer container;
container.setBuffer(buffer);
// Deserialize the header
const Fw::SerializeStatus serialStatus = container.deserializeHeader();
// Check the error
ASSERT_EQ(serialStatus, Fw::FW_SERIALIZE_FORMAT_ERROR);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Tlm/TlmString.cpp | #include <Fw/Tlm/TlmString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
TlmString::TlmString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
TlmString::TlmString(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
TlmString::TlmString(const TlmString& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
TlmString::TlmString() : StringBase() {
this->m_buf[0] = 0;
}
TlmString& TlmString::operator=(const TlmString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
TlmString& TlmString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
TlmString& TlmString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
TlmString::~TlmString() {
}
const char* TlmString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE TlmString::getCapacity() const {
return FW_TLM_STRING_MAX_SIZE;
}
SerializeStatus TlmString::serialize(SerializeBufferBase& buffer) const {
return this->serialize(buffer, this->length());
}
SerializeStatus TlmString::serialize(SerializeBufferBase& buffer, NATIVE_UINT_TYPE maxLength) const {
NATIVE_INT_TYPE len = FW_MIN(maxLength,this->length());
#if FW_AMPCS_COMPATIBLE
// serialize 8-bit size with null terminator removed
U8 strSize = len - 1;
SerializeStatus stat = buffer.serialize(strSize);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
return buffer.serialize(reinterpret_cast<const U8*>(this->toChar()),strSize, true);
#else
return buffer.serialize(reinterpret_cast<const U8*>(this->toChar()),len);
#endif
}
SerializeStatus TlmString::deserialize(SerializeBufferBase& buffer) {
NATIVE_UINT_TYPE maxSize = this->getCapacity() - 1;
CHAR* raw = const_cast<CHAR*>(this->toChar());
#if FW_AMPCS_COMPATIBLE
// AMPCS encodes 8-bit string size
U8 strSize;
SerializeStatus stat = buffer.deserialize(strSize);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
strSize = FW_MIN(maxSize,strSize);
stat = buffer.deserialize(reinterpret_cast<U8*>(raw),strSize,true);
// AMPCS Strings not null terminated
if(strSize < maxSize) {
raw[strSize] = 0;
}
#else
SerializeStatus stat = buffer.deserialize(reinterpret_cast<U8*>(raw),maxSize);
#endif
// Null terminate deserialized string
raw[maxSize] = 0;
return stat;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Tlm/TlmBuffer.cpp | #include <Fw/Tlm/TlmBuffer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
TlmBuffer::TlmBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
SerializeStatus stat = SerializeBufferBase::setBuff(args,size);
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
TlmBuffer::TlmBuffer() {
}
TlmBuffer::~TlmBuffer() {
}
TlmBuffer::TlmBuffer(const TlmBuffer& other) : Fw::SerializeBufferBase() {
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
TlmBuffer& TlmBuffer::operator=(const TlmBuffer& other) {
if(this == &other) {
return *this;
}
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
NATIVE_UINT_TYPE TlmBuffer::getBuffCapacity() const {
return sizeof(this->m_bufferData);
}
const U8* TlmBuffer::getBuffAddr() const {
return this->m_bufferData;
}
U8* TlmBuffer::getBuffAddr() {
return this->m_bufferData;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Tlm/TlmPacket.cpp | /*
* TlmPacket.cpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#include <Fw/Types/Serializable.hpp>
#include <Fw/Tlm/TlmPacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
TlmPacket::TlmPacket() : m_numEntries(0) {
this->m_type = FW_PACKET_TELEM;
this->m_tlmBuffer.resetSer();
}
TlmPacket::~TlmPacket() {
}
SerializeStatus TlmPacket::resetPktSer() {
this->m_tlmBuffer.resetSer();
// reset packet count
this->m_numEntries = 0;
// make sure packet type is correct before serializing. It should
// never be anything but FW_PACKET_TELEM, so assert.
FW_ASSERT(FW_PACKET_TELEM == this->m_type,this->m_type);
// serialize descriptor
// The function serializeBase inherited from ComPacket converts this->m_type
// to type FwPacketDescriptorType and serializes the result into this->m_tlmBuffer.
return this->serializeBase(this->m_tlmBuffer);
}
SerializeStatus TlmPacket::resetPktDeser() {
this->m_tlmBuffer.resetDeser();
// deserialize descriptor
// The function deserializeBase inherited from ComPacket deserializes a
// value of type FwPacketDescriptorType from this->m_tlmBuffer and stores it
// into this->m_type.
Fw::SerializeStatus stat = this->deserializeBase(this->m_tlmBuffer);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// make sure that this->m_tlmBuffer stores a telemetry packet
if (this->m_type != FW_PACKET_TELEM) {
return Fw::FW_DESERIALIZE_TYPE_MISMATCH;
}
return Fw::FW_SERIALIZE_OK;
}
NATIVE_UINT_TYPE TlmPacket::getNumEntries() {
return this->m_numEntries;
}
Fw::ComBuffer& TlmPacket::getBuffer() {
return this->m_tlmBuffer;
}
void TlmPacket::setBuffer(Fw::ComBuffer& buffer) {
this->m_tlmBuffer = buffer;
}
SerializeStatus TlmPacket::addValue(FwChanIdType id, Time& timeTag, TlmBuffer& buffer) {
// check to make sure there is room for all the fields
NATIVE_UINT_TYPE left = this->m_tlmBuffer.getBuffCapacity()-this->m_tlmBuffer.getBuffLength();
if (
(sizeof(FwChanIdType) + Time::SERIALIZED_SIZE + buffer.getBuffLength()) > left
) {
return Fw::FW_SERIALIZE_NO_ROOM_LEFT;
}
// serialize items into buffer
// id
SerializeStatus stat = this->m_tlmBuffer.serialize(id);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// time tag
stat = this->m_tlmBuffer.serialize(timeTag);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// telemetry buffer
stat = this->m_tlmBuffer.serialize(buffer.getBuffAddr(),buffer.getBuffLength(),true);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// increment number of packets
this->m_numEntries++;
return Fw::FW_SERIALIZE_OK;
}
// extract telemetry value
SerializeStatus TlmPacket::extractValue(FwChanIdType &id, Time& timeTag, TlmBuffer& buffer, NATIVE_UINT_TYPE bufferSize) {
// deserialize items out of buffer
// id
SerializeStatus stat = this->m_tlmBuffer.deserialize(id);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// time tag
stat = this->m_tlmBuffer.deserialize(timeTag);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// telemetry buffer
stat = this->m_tlmBuffer.deserialize(buffer.getBuffAddr(),bufferSize,true);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// set buffer size
stat = buffer.setBuffLen(bufferSize);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
return Fw::FW_SERIALIZE_OK;
}
SerializeStatus TlmPacket::serialize(SerializeBufferBase& buffer) const {
// serialize the number of packets
SerializeStatus stat = buffer.serialize(this->m_numEntries);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// Serialize the ComBuffer
return buffer.serialize(this->m_tlmBuffer.getBuffAddr(),m_tlmBuffer.getBuffLength(),true);
}
SerializeStatus TlmPacket::deserialize(SerializeBufferBase& buffer) {
// deserialize the number of packets
SerializeStatus stat = buffer.deserialize(this->m_numEntries);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
// deserialize the channel value entry buffers
NATIVE_UINT_TYPE size = buffer.getBuffLeft();
stat = buffer.deserialize(this->m_tlmBuffer.getBuffAddr(),size,true);
if (stat == FW_SERIALIZE_OK) {
// Shouldn't fail
stat = this->m_tlmBuffer.setBuffLen(size);
FW_ASSERT(stat == FW_SERIALIZE_OK,static_cast<NATIVE_INT_TYPE>(stat));
}
return stat;
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Tlm/TlmPacket.hpp | /*
* TlmPacket.hpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#ifndef TLMPACKET_HPP_
#define TLMPACKET_HPP_
#include <Fw/Com/ComPacket.hpp>
#include <Fw/Tlm/TlmBuffer.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Fw/Time/Time.hpp>
namespace Fw {
class TlmPacket : public ComPacket {
public:
//! Constructor
TlmPacket();
//! Destructor
virtual ~TlmPacket();
//! Serialize the packet before sending. For use internally in software. To send to the ground, use getBuffer() below.
SerializeStatus serialize(SerializeBufferBase& buffer) const; //!< serialize contents
//! Deserialize the packet. For use internally in software. To extract channels, use setBuffer() and extractValue() below. This is NOT typically used.
SerializeStatus deserialize(SerializeBufferBase& buffer);
//! Add telemetry value to buffer.
SerializeStatus addValue(FwChanIdType id, Time& timeTag, TlmBuffer& buffer);
//! extract telemetry value - since there are potentially multiple channel values in the packet,
//! the size of the entry must be known
SerializeStatus extractValue(FwChanIdType &id, Time& timeTag, TlmBuffer& buffer, NATIVE_UINT_TYPE bufferSize);
//! Reset serialization of values. This should be done when starting to accumulate a new set of values.
SerializeStatus resetPktSer();
//! Reset deserialization. This should be done before extracting values.
SerializeStatus resetPktDeser();
//! get buffer to send to the ground
Fw::ComBuffer& getBuffer();
//! set the internal buffer for deserializing values
void setBuffer(Fw::ComBuffer& buffer);
//! get the number of packets added via addValue()
NATIVE_UINT_TYPE getNumEntries();
PRIVATE:
ComBuffer m_tlmBuffer; //!< serialized data
NATIVE_UINT_TYPE m_numEntries; //!< number of entries stored during addValue()
};
} /* namespace Fw */
#endif /* TLMPACKET_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Tlm/TlmString.hpp | #ifndef FW_TLM_STRING_TYPE_HPP
#define FW_TLM_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class TlmString : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_TLM_STR,
SERIALIZED_SIZE = FW_TLM_STRING_MAX_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of size word
};
TlmString();
TlmString(const TlmString& src); //!< TlmString string constructor
TlmString(const StringBase& src); //!< other string constructor
TlmString(const char* src); //!< char* source constructor
TlmString& operator=(const TlmString& other); //!< assignment operator
TlmString& operator=(const StringBase& other); //!< other string assignment operator
TlmString& operator=(const char* other); //!< char* assignment operator
~TlmString();
const char* toChar() const override;
NATIVE_UINT_TYPE getCapacity() const override;
SerializeStatus serialize(SerializeBufferBase& buffer) const override; //!< serialization function
SerializeStatus serialize(SerializeBufferBase& buffer, NATIVE_UINT_TYPE maxLen) const override; //!< serialization function
SerializeStatus deserialize(SerializeBufferBase& buffer) override; //!< deserialization function
private:
char m_buf[FW_TLM_STRING_MAX_SIZE];
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Tlm/TlmBuffer.hpp | /*
* TlmBuffer.hpp
*
* Author: tcanham
*/
/*
* Description:
* This object contains the TlmBuffer type, used for storing telemetry
*/
#ifndef FW_TLM_BUFFER_HPP
#define FW_TLM_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class TlmBuffer : public SerializeBufferBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_TLM_BUFF,
SERIALIZED_SIZE = FW_TLM_BUFFER_MAX_SIZE + sizeof(FwBuffSizeType)
};
TlmBuffer(const U8 *args, NATIVE_UINT_TYPE size);
TlmBuffer();
TlmBuffer(const TlmBuffer& other);
virtual ~TlmBuffer();
TlmBuffer& operator=(const TlmBuffer& other);
NATIVE_UINT_TYPE getBuffCapacity() const; // !< returns capacity, not current size, of buffer
U8* getBuffAddr();
const U8* getBuffAddr() const;
PRIVATE:
U8 m_bufferData[FW_TLM_BUFFER_MAX_SIZE]; // command argument buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Tlm/test/ut/TlmTest.cpp | #include <gtest/gtest.h>
#include <Fw/Tlm/TlmPacket.hpp>
#include <Fw/Com/ComBuffer.hpp>
TEST(FwTlmTest,TlmPacketSerializeSingle) {
// Serialize data
Fw::TlmPacket pktIn;
Fw::TlmBuffer buffIn;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffIn.serialize(static_cast<U32>(12)));
Fw::Time timeIn(TB_WORKSTATION_TIME,10,11);
U32 id = 10;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktIn.resetPktSer());
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktIn.addValue(id,timeIn,buffIn));
Fw::ComBuffer comBuff = pktIn.getBuffer();
// Deserialize data
Fw::TlmPacket pktOut;
Fw::TlmBuffer buffOut;
Fw::Time timeOut(TB_WORKSTATION_TIME,10,11);
pktOut.setBuffer(comBuff);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktOut.resetPktDeser());
// extract values
id = 0;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktOut.extractValue(id,timeOut,buffOut,sizeof(U32)));
ASSERT_EQ(10u,id);
U32 valOut = 0;
buffOut.resetDeser();
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffOut.deserialize(valOut));
ASSERT_EQ(valOut,12u);
}
TEST(FwTlmTest,TlmPacketSerializeFill) {
// compute a single entry size assuming for the test that the value of the telemetry channel
// is a U32
static const NATIVE_UINT_TYPE SIZE_OF_ENTRY = sizeof(FwChanIdType) + Fw::Time::SERIALIZED_SIZE + sizeof(U32);
// compute the number of entries that should fit - will equal rounded down value of
// ComBuffer size - size of telemetry packet id / size of an entry
static const NATIVE_UINT_TYPE NUM_ENTRIES = (FW_COM_BUFFER_MAX_SIZE - sizeof(FwPacketDescriptorType))/SIZE_OF_ENTRY;
Fw::TlmPacket pktIn;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktIn.resetPktSer());
// fill a telemetry packet
for (NATIVE_UINT_TYPE entry = 0; entry < NUM_ENTRIES; entry++) {
// Serialize data
Fw::TlmBuffer buffIn;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffIn.serialize(static_cast<U32>(entry)));
Fw::Time timeIn(TB_WORKSTATION_TIME,entry+1,entry+2);
U32 id = NUM_ENTRIES-entry;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktIn.addValue(id,timeIn,buffIn));
}
// Next one should fail because it's full
{
Fw::TlmBuffer buffIn;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffIn.serialize(static_cast<U32>(12)));
Fw::Time timeIn(TB_WORKSTATION_TIME,10,11);
U32 id = 10;
ASSERT_EQ(Fw::FW_SERIALIZE_NO_ROOM_LEFT,pktIn.addValue(id,timeIn,buffIn));
}
// Create a new packet from the ComBuffer
Fw::ComBuffer comBuff = pktIn.getBuffer();
Fw::TlmPacket pktOut;
pktOut.setBuffer(comBuff);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktOut.resetPktDeser());
// empty the packet of entries
for (NATIVE_UINT_TYPE entry = 0; entry < NUM_ENTRIES; entry++) {
// Deserialize data
Fw::TlmBuffer buffOut;
Fw::Time timeOut;
U32 id = 0;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,pktOut.extractValue(id,timeOut,buffOut,sizeof(U32)));
ASSERT_EQ(NUM_ENTRIES-entry,id);
Fw::Time expTime(TB_WORKSTATION_TIME,entry+1,entry+2);
ASSERT_EQ(expTime,timeOut);
U32 val = 0;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffOut.deserialize(val));
ASSERT_EQ(entry,val);
}
// try to extract one more, should fail
{
Fw::TlmBuffer buffOut;
Fw::Time timeOut;
U32 id = 0;
ASSERT_EQ(Fw::FW_DESERIALIZE_BUFFER_EMPTY,pktOut.extractValue(id,timeOut,buffOut,sizeof(U32)));
}
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Types/MemAllocator.cpp | /**
* \file
* \author
* \brief
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#include <Fw/Types/MemAllocator.hpp>
namespace Fw {
MemAllocator::MemAllocator() {
}
MemAllocator::~MemAllocator() {
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Types/ObjectName.hpp | #ifndef FW_OBJECT_NAME_TYPE_HPP
#define FW_OBJECT_NAME_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class ObjectName : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_OBJECT_NAME, //!< typeid for string type
STRING_SIZE = FW_OBJ_NAME_MAX_SIZE, //!< Storage for string
SERIALIZED_SIZE = STRING_SIZE + sizeof(FwBuffSizeType) //!< Serialized size is size of buffer + size field
};
explicit ObjectName(const CHAR* src); //!< char* source constructor
explicit ObjectName(const StringBase& src); //!< StringBase string constructor
ObjectName(const ObjectName& src); //!< ObjectName string constructor
ObjectName(); //!< default constructor
ObjectName& operator=(const ObjectName& other); //!< assignment operator
ObjectName& operator=(const StringBase& other); //!< StringBase string assignment operator
ObjectName& operator=(const CHAR* other); //!< char* assignment operator
~ObjectName(); //!< destructor
const CHAR* toChar() const; //!< gets char buffer
NATIVE_UINT_TYPE getCapacity() const; //!< return buffer size
private:
CHAR m_buf[STRING_SIZE]; //!< storage for string data
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/CAssert.h | /*
* FwCAssert.hpp
*
* Created on: Jun 8, 2014
* Author: tcanham
*/
#ifndef FWCASSERT_HPP_
#define FWCASSERT_HPP_
#include <FpConfig.h>
#if FW_ASSERT_LEVEL == FW_NO_ASSERT
#define FW_CASSERT(...)
#else // ASSERT is defined
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
#define FILE_NAME_ARG NATIVE_UINT_TYPE
#define FW_CASSERT(cond) ((void)((cond) ? (0) : (CAssert0(ASSERT_FILE_ID, __LINE__))))
#else
#define FILE_NAME_ARG const CHAR*
#define FW_CASSERT(cond) ((void)((cond) ? (0) : (CAssert0((FILE_NAME_ARG)(__FILE__), __LINE__))))
#endif
I32 CAssert0(FILE_NAME_ARG file, U32 lineNo); //!< C assert function
I32 CAssert1(FILE_NAME_ARG file, U32 lineNo, NATIVE_INT_TYPE arg1); //!< C assert function 1
#endif // ASSERT is defined
#endif /* FWCASSERT_HPP_ */
| h |
fprime | data/projects/fprime/Fw/Types/BasicTypes.hpp | /**
* \file: BasicTypes.hpp
* \author mstarch
* \brief C++ header for working with basic fprime types
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#include <limits>
// Use C linkage for the basic items
extern "C" {
#include "BasicTypes.h"
}
#ifndef FW_BASIC_TYPES_HPP
#define FW_BASIC_TYPES_HPP
// IEEE compliance checks must occur in C++ code
#if !defined(SKIP_FLOAT_IEEE_754_COMPLIANCE) || !SKIP_FLOAT_IEEE_754_COMPLIANCE
static_assert((std::numeric_limits<float>::is_iec559 == true) && (std::numeric_limits<float>::radix == 2) &&
(std::numeric_limits<float>::digits == 24) && (std::numeric_limits<float>::max_exponent == 128),
"The 32-bit floating point type does not conform to the IEEE-754 standard.");
#if FW_HAS_F64
static_assert((std::numeric_limits<double>::is_iec559 == true) && (std::numeric_limits<double>::radix == 2) &&
(std::numeric_limits<double>::digits == 53) && (std::numeric_limits<double>::max_exponent == 1024),
"The 64-bit floating point type does not conform to the IEEE-754 standard.");
#endif
#endif
#endif // End FW_BASIC_TYPES_HPP
| hpp |
fprime | data/projects/fprime/Fw/Types/ConstByteArray.hpp | // ======================================================================
// \title ConstByteArray.hpp
// \author bocchino
// \brief hpp file for ConstByteArray type
//
// \copyright
// Copyright (C) 2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_ConstByteArray_HPP
#define Fw_ConstByteArray_HPP
#include <FpConfig.hpp>
namespace Fw {
//! \class ConstByteArray
//! \brief A variable-length byte array with constant access
//!
struct ConstByteArray {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Construct a ConstByteArray
//!
ConstByteArray(
const U8 *const bytes, //!< Pointer to the bytes
const U32 size //!< The array size
) :
bytes(bytes),
size(size)
{
}
// ----------------------------------------------------------------------
// Data
// ----------------------------------------------------------------------
//! The bytes
const U8 *const bytes;
//! The size
const U32 size;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/String.cpp | #include <Fw/Types/String.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
String::String(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
String::String(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
String::String(const String& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
String::String() : StringBase() {
this->m_buf[0] = 0;
}
String& String::operator=(const String& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
String& String::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
String& String::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
String::~String() {
}
const char* String::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE String::getCapacity() const {
return STRING_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/EightyCharString.cpp | #include <Fw/Types/EightyCharString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
EightyCharString::EightyCharString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
EightyCharString::EightyCharString(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
EightyCharString::EightyCharString(const EightyCharString& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
EightyCharString::EightyCharString() : StringBase() {
this->m_buf[0] = 0;
}
EightyCharString& EightyCharString::operator=(const EightyCharString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
EightyCharString& EightyCharString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
EightyCharString& EightyCharString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
EightyCharString::~EightyCharString() {
}
const char* EightyCharString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE EightyCharString::getCapacity() const {
return STRING_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/Assert.cpp | #include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <cassert>
#include <cstdio>
#define FW_ASSERT_DFL_MSG_LEN 256
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
#define fileIdFs "Assert: 0x%08" PRIx32 ":%" PRI_PlatformUIntType
#else
#define fileIdFs "Assert: \"%s:%" PRI_PlatformUIntType "\""
#endif
namespace Fw {
void defaultPrintAssert(const CHAR* msg) {
(void)fprintf(stderr,"%s\n", msg);
}
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
) {
switch (numArgs) {
case 0:
(void) snprintf(destBuffer, buffSize, fileIdFs, file, lineNo);
break;
case 1:
(void) snprintf(
destBuffer,
buffSize,
fileIdFs " %" PRI_FwAssertArgType,
file,
lineNo,
arg1
);
break;
case 2:
(void) snprintf(
destBuffer,
buffSize,
fileIdFs " %" PRI_FwAssertArgType " %" PRI_FwAssertArgType,
file,
lineNo,
arg1, arg2
);
break;
case 3:
(void) snprintf(
destBuffer,
buffSize,
fileIdFs " %" PRI_FwAssertArgType " %" PRI_FwAssertArgType
" %" PRI_FwAssertArgType,
file,
lineNo,
arg1, arg2, arg3
);
break;
case 4:
(void) snprintf(
destBuffer,
buffSize,
fileIdFs " %" PRI_FwAssertArgType " %" PRI_FwAssertArgType
" %" PRI_FwAssertArgType " %" PRI_FwAssertArgType,
file,
lineNo,
arg1, arg2, arg3, arg4);
break;
case 5:
(void) snprintf(
destBuffer,
buffSize,
fileIdFs " %" PRI_FwAssertArgType " %" PRI_FwAssertArgType
" %" PRI_FwAssertArgType " %" PRI_FwAssertArgType
" %" PRI_FwAssertArgType,
file,
lineNo,
arg1, arg2, arg3, arg4, arg5
);
break;
case 6:
(void) snprintf(
destBuffer,
buffSize,
fileIdFs " %" PRI_FwAssertArgType " %" PRI_FwAssertArgType
" %" PRI_FwAssertArgType " %" PRI_FwAssertArgType
" %" PRI_FwAssertArgType " %" PRI_FwAssertArgType,
file,
lineNo,
arg1, arg2, arg3, arg4, arg5, arg6
);
break;
default: // in an assert already, what can we do?
break;
}
// null terminate
destBuffer[buffSize-1] = 0;
}
void AssertHook::printAssert(const CHAR* msg) {
defaultPrintAssert(msg);
}
void AssertHook::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
)
{
CHAR destBuffer[FW_ASSERT_DFL_MSG_LEN];
defaultReportAssert
(
file,
lineNo,
numArgs,
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
destBuffer,
sizeof(destBuffer)
);
// print message
this->printAssert(destBuffer);
}
void AssertHook::doAssert() {
assert(0);
}
STATIC AssertHook* s_assertHook = nullptr;
void AssertHook::registerHook() {
this->previousHook = s_assertHook;
s_assertHook = this;
}
void AssertHook::deregisterHook() {
s_assertHook = this->previousHook;
}
// Default handler of SwAssert functions
NATIVE_INT_TYPE defaultSwAssert(
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 (nullptr == s_assertHook) {
CHAR assertMsg[FW_ASSERT_DFL_MSG_LEN];
defaultReportAssert(
file,
lineNo,
numArgs,
arg1,arg2,arg3,arg4,arg5,arg6,
assertMsg,sizeof(assertMsg));
defaultPrintAssert(assertMsg);
assert(0);
}
else {
s_assertHook->reportAssert(
file,
lineNo,
numArgs,
arg1,arg2,arg3,arg4,arg5,arg6);
s_assertHook->doAssert();
}
return 0;
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 0, 0, 0, 0, 0, 0, 0);
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 1, arg1, 0, 0, 0, 0, 0);
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 2, arg1, arg2, 0, 0, 0, 0);
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 3, arg1, arg2, arg3, 0, 0, 0);
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 4, arg1, arg2, arg3, arg4, 0, 0);
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
FwAssertArgType arg5,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 5, arg1, arg2, arg3, arg4, arg5, 0);
}
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
FwAssertArgType arg5,
FwAssertArgType arg6,
NATIVE_UINT_TYPE lineNo) {
return defaultSwAssert(file, lineNo, 6, arg1, arg2, arg3, arg4, arg5, arg6);
}
}
// define C asserts.
extern "C" {
NATIVE_INT_TYPE CAssert0(FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo);
}
NATIVE_INT_TYPE CAssert0(FILE_NAME_ARG file, NATIVE_UINT_TYPE lineNo) {
if (nullptr == Fw::s_assertHook) {
CHAR assertMsg[FW_ASSERT_DFL_MSG_LEN];
Fw::defaultReportAssert(
file,
lineNo,
0,
0,0,0,0,0,0,
assertMsg,sizeof(assertMsg));
}
else {
Fw::s_assertHook->reportAssert(
file,
lineNo,
0,
0,0,0,0,0,0);
Fw::s_assertHook->doAssert();
}
return 0;
}
| cpp |
fprime | data/projects/fprime/Fw/Types/InternalInterfaceString.cpp | #include <Fw/Types/InternalInterfaceString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
InternalInterfaceString::InternalInterfaceString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
InternalInterfaceString::InternalInterfaceString(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
InternalInterfaceString::InternalInterfaceString(const InternalInterfaceString& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
InternalInterfaceString::InternalInterfaceString() : StringBase() {
this->m_buf[0] = 0;
}
InternalInterfaceString& InternalInterfaceString::operator=(const InternalInterfaceString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
InternalInterfaceString& InternalInterfaceString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
InternalInterfaceString& InternalInterfaceString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
InternalInterfaceString::~InternalInterfaceString() {
}
const char* InternalInterfaceString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE InternalInterfaceString::getCapacity() const {
return FW_INTERNAL_INTERFACE_STRING_MAX_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/MallocAllocator.hpp | /**
* \file
* \author T. Canham
* \brief A MemAllocator implementation class that uses malloc.
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef TYPES_MALLOCALLOCATOR_HPP_
#define TYPES_MALLOCALLOCATOR_HPP_
#include <Fw/Types/MemAllocator.hpp>
namespace Fw {
/*!
*
* This class is an implementation of the MemAllocator base class.
* It uses the heap as the memory source.
*
* Since it is heap space, the identifier is unused, and memory is never recoverable.
*
*/
class MallocAllocator: public MemAllocator {
public:
MallocAllocator();
virtual ~MallocAllocator();
//! Allocate memory
/*!
* \param identifier the memory segment identifier (not used)
* \param size the requested size (not changed)
* \param recoverable - flag to indicate the memory could be recoverable (always set to false)
* \return the pointer to memory. Zero if unable to allocate.
*/
void *allocate(
const NATIVE_UINT_TYPE identifier,
NATIVE_UINT_TYPE &size,
bool& recoverable);
//! Deallocate memory
/*!
* \param identifier the memory segment identifier (not used)
* \param ptr the pointer to memory returned by allocate()
*/
void deallocate(
const NATIVE_UINT_TYPE identifier,
void* ptr);
};
} /* namespace Fw */
#endif /* TYPES_MALLOCALLOCATOR_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Types/MmapAllocator.cpp | /**
* \file
* \author Gene Merewether
* \brief Implementation of mmap based allocator
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#include <Fw/Types/MmapAllocator.hpp>
#include <cstdlib>
#include <sys/mman.h>
#include <Fw/Types/Assert.hpp>
namespace Fw {
MmapAllocator::MmapAllocator() : m_length(0) {
}
MmapAllocator::~MmapAllocator() {
}
void *MmapAllocator::allocate(const NATIVE_UINT_TYPE identifier, NATIVE_UINT_TYPE &size, bool& recoverable) {
void* addr = mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
size = 0;
return nullptr;
}
this->m_length = size;
// mmap memory is never recoverable
recoverable = false;
return addr;
}
void MmapAllocator::deallocate(const NATIVE_UINT_TYPE identifier, void* ptr) {
if (this->m_length) {
int stat = munmap(ptr, this->m_length);
FW_ASSERT(stat == 0, stat);
}
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Types/EightyCharString.hpp | #ifndef FW_EIGHTY_CHAR_STRING_TYPE_HPP
#define FW_EIGHTY_CHAR_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class EightyCharString : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_EIGHTY_CHAR_STRING, //!< typeid for string type
STRING_SIZE = 80, //!< Storage for string
SERIALIZED_SIZE = STRING_SIZE + sizeof(FwBuffSizeType) //!< Serialized size is size of buffer + size field
};
EightyCharString(const char* src); //!< char* source constructor
EightyCharString(const StringBase& src); //!< other string constructor
EightyCharString(const EightyCharString& src); //!< EightyCharString string constructor
EightyCharString(); //!< default constructor
EightyCharString& operator=(const EightyCharString& other); //!< assignment operator
EightyCharString& operator=(const StringBase& other); //!< other string assignment operator
EightyCharString& operator=(const char* other); //!< char* assignment operator
~EightyCharString(); //!< destructor
const char* toChar() const; //!< gets char buffer
NATIVE_UINT_TYPE getCapacity() const; //!< return buffer size
private:
char m_buf[STRING_SIZE]; //!< storage for string data
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/StringType.cpp | /**
* \file
* \author T. Canham
* \brief Implements ISF string base class
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#include <Fw/Types/StringType.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/StringUtils.hpp>
#include <cstring>
#include <cstdio>
#include <cstdarg>
namespace Fw {
StringBase::StringBase() {
}
StringBase::~StringBase() {
}
const CHAR* StringBase::operator+=(const CHAR* src) {
this->appendBuff(src, StringUtils::string_length(src, this->getCapacity()));
return this->toChar();
}
const StringBase& StringBase::operator+=(const StringBase& src) {
this->appendBuff(src.toChar(), src.length());
return *this;
}
bool StringBase::operator==(const StringBase& other) const {
SizeType len = this->length();
if (len != other.length()) {
return false;
} else {
return this->operator==(other.toChar());
}
}
bool StringBase::operator==(const CHAR* other) const {
const CHAR *const us = this->toChar();
if ((us == nullptr) or (other == nullptr)) {
return false;
}
const SizeType capacity = this->getCapacity();
const size_t result = strncmp(us, other, capacity);
return (result == 0);
}
void StringBase::format(const CHAR* formatString, ...) {
CHAR* us = const_cast<CHAR*>(this->toChar());
SizeType cap = this->getCapacity();
FW_ASSERT(us);
va_list args;
va_start(args, formatString);
(void) vsnprintf(us, cap, formatString, args);
va_end(args);
// null terminate
us[cap - 1] = 0;
}
bool StringBase::operator!=(const StringBase& other) const {
return !operator==(other);
}
bool StringBase::operator!=(const CHAR* other) const {
return !operator==(other);
}
#if FW_SERIALIZABLE_TO_STRING || BUILD_UT
void StringBase::toString(StringBase& text) const {
text = *this;
}
#endif
#ifdef BUILD_UT
std::ostream& operator<<(std::ostream& os, const StringBase& str)
{
os << str.toChar();
return os;
}
#endif
StringBase& StringBase::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(const_cast<char *>(this->toChar()), other.toChar(), this->getCapacity());
return *this;
}
// Copy constructor doesn't make sense in this virtual class as there is nothing to copy. Derived classes should
// call the empty constructor and then call their own copy function
StringBase& StringBase::operator=(const CHAR* other) { // lgtm[cpp/rule-of-two]
(void) Fw::StringUtils::string_copy(const_cast<char *>(this->toChar()), other, this->getCapacity());
return *this;
}
void StringBase::appendBuff(const CHAR* buff, SizeType size) {
const SizeType capacity = this->getCapacity();
const SizeType length = this->length();
FW_ASSERT(capacity > length, capacity, length);
// Subtract 1 to leave space for null terminator
SizeType remaining = capacity - length - 1;
if(size < remaining) {
remaining = size;
}
FW_ASSERT(remaining < capacity, remaining, capacity);
(void) strncat(const_cast<CHAR*>(this->toChar()), buff, remaining);
}
StringBase::SizeType StringBase::length() const {
return static_cast<SizeType>(StringUtils::string_length(this->toChar(),this->getCapacity()));
}
SerializeStatus StringBase::serialize(SerializeBufferBase& buffer) const {
return buffer.serialize(reinterpret_cast<const U8*>(this->toChar()),this->length());
}
SerializeStatus StringBase::serialize(SerializeBufferBase& buffer, SizeType maxLength) const {
SizeType len = FW_MIN(maxLength,this->length());
return buffer.serialize(reinterpret_cast<const U8*>(this->toChar()), len);
}
SerializeStatus StringBase::deserialize(SerializeBufferBase& buffer) {
SizeType maxSize = this->getCapacity() - 1;
CHAR* raw = const_cast<CHAR*>(this->toChar());
SerializeStatus stat = buffer.deserialize(reinterpret_cast<U8*>(raw),maxSize);
// Null terminate deserialized string
raw[maxSize] = 0;
return stat;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/InternalInterfaceString.hpp | #ifndef FW_INTERNAL_INTERFACE_STRING_TYPE_HPP
#define FW_INTERNAL_INTERFACE_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class InternalInterfaceString : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_INTERNAL_INTERFACE_STRING, //!< typeid for string type
SERIALIZED_SIZE = FW_INTERNAL_INTERFACE_STRING_MAX_SIZE + sizeof(FwBuffSizeType) //!< Serialized size is size of buffer + size field
};
InternalInterfaceString(const char* src); //!< char* source constructor
InternalInterfaceString(const StringBase& src); //!< other string constructor
InternalInterfaceString(const InternalInterfaceString& src); //!< other string constructor
InternalInterfaceString(); //!< default constructor
InternalInterfaceString& operator=(const InternalInterfaceString& other); //!< assignment operator
InternalInterfaceString& operator=(const StringBase& other); //!< other string assignment operator
InternalInterfaceString& operator=(const char* other); //!< char* assignment operator
~InternalInterfaceString(); //!< destructor
const char* toChar() const; //!< gets char buffer
NATIVE_UINT_TYPE getCapacity() const; //!< return buffer size
private:
char m_buf[FW_INTERNAL_INTERFACE_STRING_MAX_SIZE]; //!< storage for string data
};
}
#endif // FW_INTERNAL_INTERFACE_STRING_TYPE_HPP
| hpp |
fprime | data/projects/fprime/Fw/Types/MallocAllocator.cpp | /**
* \file
* \author T. Canham
* \brief Implementation of malloc based allocator
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#include <Fw/Types/MallocAllocator.hpp>
#include <cstdlib>
namespace Fw {
MallocAllocator::MallocAllocator() {
}
MallocAllocator::~MallocAllocator() {
}
void *MallocAllocator::allocate(const NATIVE_UINT_TYPE identifier, NATIVE_UINT_TYPE &size, bool& recoverable) {
// don't use identifier
// heap memory is never recoverable
recoverable = false;
void *mem = ::malloc(size);
if (nullptr == mem) {
size = 0; // set to zero if can't get memory
}
return mem;
}
void MallocAllocator::deallocate(const NATIVE_UINT_TYPE identifier, void* ptr) {
::free(ptr);
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Types/MmapAllocator.hpp | /**
* \file
* \author Gene Merewether
* \brief A MemAllocator implementation class that uses mmap.
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef TYPES_MMAPALLOCATOR_HPP_
#define TYPES_MMAPALLOCATOR_HPP_
#include <Fw/Types/MemAllocator.hpp>
namespace Fw {
//! Fw::MmapAllocator is an implementation of the Fw::MemAllocator interface that back memory with a read and write
//! capable anonymous memory mapped region. This class is currently not useful for mapping to a file.
class MmapAllocator: public MemAllocator {
public:
//! Constructor with no arguments
//!
MmapAllocator();
//! Destructor with no arguments
virtual ~MmapAllocator();
//! Allocate memory using the mmap allocator
//! \param identifier: identifier to use with allocation
//! \param size: size of memory to be allocated
//! \param recoverable: (output) is this memory recoverable after a reset. Always false for mmap.
void *allocate(const NATIVE_UINT_TYPE identifier, NATIVE_UINT_TYPE &size, bool& recoverable);
//! Deallocation of memory using the mmap allocator
//! \param identifier: identifier used at allocation
//! \param ptr: pointer to memory being deallocated
void deallocate(const NATIVE_UINT_TYPE identifier, void* ptr);
private:
NATIVE_UINT_TYPE m_length;
};
} /* namespace Fw */
#endif /* TYPES_MMAPALLOCATOR_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Types/StringUtils.hpp | #ifndef FW_STRINGUTILS_HPP
#define FW_STRINGUTILS_HPP
#include <FpConfig.hpp>
namespace Fw {
namespace StringUtils {
/**
* \brief copy string with null-termination guaranteed
*
* Standard implementations of strncpy fail to guarantee the termination of a
* string with the null terminator. This implementation guarantees the string is
* properly null-terminated at the possible expense of the last character of the
* copied string being lost. The user is responsible for providing a destination
* large enough for the content and a null-character. Other behavior retains the
* behavior of strncpy.
*
* \param destination: destination buffer to hold copied contents
* \param source: source buffer to read content to copy
* \param num: length of destination buffer
* \return destination buffer
*/
char* string_copy(char* destination, const char* source, U32 num);
/**
* \brief get the length of the source string or max_len if the string is
* longer than max_len.
*
* \param source: string to calculate the length
* \param max_len: the maximum length of the source string
* \return length of the source string or max_len
*/
U32 string_length(const CHAR* source, U32 max_len);
} // namespace StringUtils
} // namespace Fw
#endif // FW_STRINGUTILS_HPP
| hpp |
fprime | data/projects/fprime/Fw/Types/StringType.hpp | /**
* \file
* \author T. Canham
* \brief Declares ISF string base class
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef FW_STRING_TYPE_HPP
#define FW_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#ifdef BUILD_UT
#include <iostream>
#endif
namespace Fw {
class StringBase : public Serializable {
public:
using SizeType = NATIVE_UINT_TYPE;
virtual const CHAR* toChar() const = 0; //<! Convert to a C-style char*
virtual SizeType getCapacity() const = 0; //!< return size of buffer
SizeType length() const; //!< Get length of string
const CHAR* operator+=(const CHAR* src); //!< Concatenate a CHAR*
const StringBase& operator+=(const StringBase& src); //!< Concatenate a StringBase
bool operator==(const StringBase& other) const; //!< Check for equality with StringBase
bool operator==(const CHAR* other) const; //!< Check for equality with CHAR*
bool operator!=(const StringBase& other) const; //!< Inequality with StringBase
bool operator!=(const CHAR* other) const; //!< Inequality with CHAR*
StringBase& operator=(const CHAR* src); //!< Assign CHAR*
StringBase& operator=(const StringBase& src); //!< Assign another StringBase
void format(const CHAR* formatString, ...); //!< write formatted string to buffer
virtual SerializeStatus serialize(SerializeBufferBase& buffer) const; //!< serialization function
virtual SerializeStatus serialize(SerializeBufferBase& buffer, SizeType maxLen) const; //!< serialization function
virtual SerializeStatus deserialize(SerializeBufferBase& buffer); //!< deserialization function
#ifdef BUILD_UT
// to support GoogleTest framework in unit tests
friend std::ostream& operator<<(std::ostream& os, const StringBase& str);
#endif
#if FW_SERIALIZABLE_TO_STRING || BUILD_UT
void toString(StringBase& text) const; //!< write string with contents
#endif
protected:
StringBase();
virtual ~StringBase();
void appendBuff(const CHAR* buff, SizeType size);
private:
// A no-implementation copy constructor here will prevent the default copy constructor from being called
// accidentally, and without an implementation it will create an error for the developer instead.
StringBase(const StringBase &src); //!< constructor with buffer as source
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/SerialBuffer.cpp | // ======================================================================
// \title SerialBuffer.cpp
// \author bocchino
// \brief cpp file for SerialBuffer type
//
// \copyright
// Copyright (C) 2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Fw/Types/SerialBuffer.hpp"
#include "Fw/Types/Assert.hpp"
namespace Fw {
SerialBuffer ::
SerialBuffer(
U8 *const data,
const U32 capacity
) :
m_data(data),
m_capacity(capacity)
{
}
NATIVE_UINT_TYPE SerialBuffer ::
getBuffCapacity() const
{
return m_capacity;
}
U8* SerialBuffer ::
getBuffAddr()
{
return m_data;
}
const U8* SerialBuffer ::
getBuffAddr() const
{
return m_data;
}
void SerialBuffer ::
fill()
{
const SerializeStatus status = this->setBuffLen(this->m_capacity);
FW_ASSERT(status == FW_SERIALIZE_OK);
}
SerializeStatus SerialBuffer ::
pushBytes(const U8 *const addr, const NATIVE_UINT_TYPE n)
{
// "true" means "just push the bytes"
return this->serialize(const_cast<U8*>(addr), n, true);
}
SerializeStatus SerialBuffer ::
popBytes(U8 *const addr, NATIVE_UINT_TYPE n)
{
// "true" means "just pop the bytes"
return this->deserialize(addr, n, true);
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/ObjectName.cpp | #include <Fw/Types/ObjectName.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
ObjectName::ObjectName(const CHAR* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
ObjectName::ObjectName(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
ObjectName::ObjectName(const ObjectName& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
ObjectName::ObjectName() : StringBase() {
this->m_buf[0] = 0;
}
ObjectName& ObjectName::operator=(const ObjectName& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
ObjectName& ObjectName::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
ObjectName& ObjectName::operator=(const CHAR* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
ObjectName::~ObjectName() {
}
const CHAR* ObjectName::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE ObjectName::getCapacity() const {
return STRING_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/String.hpp | #ifndef FW_FIXED_LENGTH_STRING_TYPE_HPP
#define FW_FIXED_LENGTH_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class String : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_FIXED_LENGTH_STRING, //!< typeid for string type
STRING_SIZE = FW_FIXED_LENGTH_STRING_SIZE, //!< Storage for string
SERIALIZED_SIZE = STRING_SIZE + sizeof(FwBuffSizeType) //!< Serialized size is size of buffer + size field
};
String(const char* src); //!< char* source constructor
String(const StringBase& src); //!< other string constructor
String(const String& src); //!< String string constructor
String(); //!< default constructor
String& operator=(const String& other); //!< assignment operator
String& operator=(const StringBase& other); //!< other string assignment operator
String& operator=(const char* other); //!< char* assignment operator
~String(); //!< destructor
const char* toChar() const; //!< gets char buffer
NATIVE_UINT_TYPE getCapacity() const ; //!< return buffer size
private:
char m_buf[STRING_SIZE]; //!< storage for string data
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/Serializable.hpp | #ifndef SERIALIZABLE_HPP
#define SERIALIZABLE_HPP
#ifdef BUILD_UT
#include <iostream>
#endif
#include <FpConfig.hpp>
#include "Fw/Deprecate.hpp"
namespace Fw {
class StringBase; //!< forward declaration for string
typedef enum {
FW_SERIALIZE_OK, //!< Serialization/Deserialization operation was successful
FW_SERIALIZE_FORMAT_ERROR, //!< Data was the wrong format (e.g. wrong packet type)
FW_SERIALIZE_NO_ROOM_LEFT, //!< No room left in the buffer to serialize data
FW_DESERIALIZE_BUFFER_EMPTY, //!< Deserialization buffer was empty when trying to read more data
FW_DESERIALIZE_FORMAT_ERROR, //!< Deserialization data had incorrect values (unexpected data types)
FW_DESERIALIZE_SIZE_MISMATCH, //!< Data was left in the buffer, but not enough to deserialize
FW_DESERIALIZE_TYPE_MISMATCH //!< Deserialized type ID didn't match
} SerializeStatus;
class SerializeBufferBase; //!< forward declaration
class Serializable {
public:
// Size type for backwards compatibility
using SizeType = NATIVE_UINT_TYPE;
public:
virtual SerializeStatus serialize(SerializeBufferBase& buffer) const = 0; //!< serialize contents
virtual SerializeStatus deserialize(SerializeBufferBase& buffer) = 0; //!< deserialize to contents
#if FW_SERIALIZABLE_TO_STRING || FW_ENABLE_TEXT_LOGGING || BUILD_UT
virtual void toString(StringBase& text) const; //!< generate text from serializable
#endif
#ifdef BUILD_UT
friend std::ostream& operator<<(std::ostream& os, const Serializable& val);
#endif
protected:
Serializable(); //!< Default constructor
virtual ~Serializable(); //!< destructor
};
class Serialization {
public:
enum t {
INCLUDE_LENGTH, //!< Include length as first token in serialization
OMIT_LENGTH //!< Omit length from serialization
};
};
class SerializeBufferBase {
public:
SerializeBufferBase& operator=(const SerializeBufferBase &src); //!< equal operator
virtual ~SerializeBufferBase(); //!< destructor
// Serialization for built-in types
SerializeStatus serialize(U8 val); //!< serialize 8-bit unsigned int
SerializeStatus serialize(I8 val); //!< serialize 8-bit signed int
#if FW_HAS_16_BIT==1
SerializeStatus serialize(U16 val); //!< serialize 16-bit unsigned int
SerializeStatus serialize(I16 val); //!< serialize 16-bit signed int
#endif
#if FW_HAS_32_BIT==1
SerializeStatus serialize(U32 val); //!< serialize 32-bit unsigned int
SerializeStatus serialize(I32 val); //!< serialize 32-bit signed int
#endif
#if FW_HAS_64_BIT==1
SerializeStatus serialize(U64 val); //!< serialize 64-bit unsigned int
SerializeStatus serialize(I64 val); //!< serialize 64-bit signed int
#endif
SerializeStatus serialize(F32 val); //!< serialize 32-bit floating point
#if FW_HAS_F64
SerializeStatus serialize(F64 val); //!< serialize 64-bit floating point
#endif
SerializeStatus serialize(bool val); //!< serialize boolean
SerializeStatus serialize(const void* val); //!< serialize pointer (careful, only pointer value, not contents are serialized)
//! serialize data buffer
SerializeStatus serialize(const U8* buff, NATIVE_UINT_TYPE length, bool noLength);
//! serialize data buffer
SerializeStatus serialize(const U8* buff, NATIVE_UINT_TYPE length);
//! \brief serialize a byte buffer of a given length
//!
//! Serialize bytes from `buff` up to `length`. If `serializationMode` is set to `INCLUDE_LENGTH` then the
//! length is included as the first token. Length may be omitted with `OMIT_LENGTH`.
//!
//! \param buff: buffer to serialize
//! \param length: length of data to serialize
//! \param mode: serialization type
//! \return status of serialization
SerializeStatus serialize(const U8* buff, FwSizeType length, Serialization::t mode);
SerializeStatus serialize(const SerializeBufferBase& val); //!< serialize a serialized buffer
SerializeStatus serialize(const Serializable &val); //!< serialize an object derived from serializable base class
SerializeStatus serializeSize(const FwSizeType size); //!< serialize a size value
// Deserialization for built-in types
SerializeStatus deserialize(U8 &val); //!< deserialize 8-bit unsigned int
SerializeStatus deserialize(I8 &val); //!< deserialize 8-bit signed int
#if FW_HAS_16_BIT==1
SerializeStatus deserialize(U16 &val); //!< deserialize 16-bit unsigned int
SerializeStatus deserialize(I16 &val); //!< deserialize 16-bit signed int
#endif
#if FW_HAS_32_BIT==1
SerializeStatus deserialize(U32 &val); //!< deserialize 32-bit unsigned int
SerializeStatus deserialize(I32 &val); //!< deserialize 32-bit signed int
#endif
#if FW_HAS_64_BIT==1
SerializeStatus deserialize(U64 &val); //!< deserialize 64-bit unsigned int
SerializeStatus deserialize(I64 &val); //!< deserialize 64-bit signed int
#endif
SerializeStatus deserialize(F32 &val); //!< deserialize 32-bit floating point
#if FW_HAS_F64
SerializeStatus deserialize(F64 &val); //!< deserialize 64-bit floating point
#endif
SerializeStatus deserialize(bool &val); //!< deserialize boolean
SerializeStatus deserialize(void*& val); //!< deserialize point value (careful, pointer value only, not contents)
//! deserialize data buffer
SerializeStatus deserialize(U8* buff, NATIVE_UINT_TYPE& length, bool noLength);
//! deserialize data buffer
SerializeStatus deserialize(U8* buff, NATIVE_UINT_TYPE& length);
//! \brief deserialize a byte buffer of a given length
//!
//! Deserialize bytes into `buff` of `length` bytes. If `serializationMode` is set to `INCLUDE_LENGTH` then
//! the length is deserialized first followed by the bytes. Length may be omitted with `OMIT_LENGTH` and
//! in this case `length` bytes will be deserialized. `length` will be filled with the amount of data
//! deserialized.
//!
//! \param buff: buffer to hold deserialized data
//! \param length: length of data to deserialize length is filled with deserialized length
//! \param mode: deserialization type
//! \return status of serialization
SerializeStatus deserialize(U8* buff, FwSizeType& length, Serialization::t mode);
SerializeStatus deserialize(Serializable &val); //!< deserialize an object derived from serializable base class
SerializeStatus deserialize(SerializeBufferBase& val); //!< serialize a serialized buffer
SerializeStatus deserializeSize(FwSizeType& size); //!< deserialize a size value
void resetSer(); //!< reset to beginning of buffer to reuse for serialization
void resetDeser(); //!< reset deserialization to beginning
SerializeStatus moveSerToOffset(FwSizeType offset); //!< Moves serialization to the specified offset
SerializeStatus moveDeserToOffset(FwSizeType offset); //!< Moves deserialization to the specified offset
SerializeStatus serializeSkip(FwSizeType numBytesToSkip); //!< Skips the number of specified bytes for serialization
SerializeStatus deserializeSkip(FwSizeType numBytesToSkip); //!< Skips the number of specified bytes for deserialization
virtual Serializable::SizeType getBuffCapacity() const = 0; //!< returns capacity, not current size, of buffer
Serializable::SizeType getBuffLength() const; //!< returns current buffer size
Serializable::SizeType getBuffLeft() const; //!< returns how much deserialization buffer is left
virtual U8* getBuffAddr() = 0; //!< gets buffer address for data filling
virtual const U8* getBuffAddr() const = 0; //!< gets buffer address for data reading, const version
const U8* getBuffAddrLeft() const; //!< gets address of remaining non-deserialized data.
U8* getBuffAddrSer(); //!< gets address of end of serialization. DANGEROUS! Need to know max buffer size and adjust when done
SerializeStatus setBuff(const U8* src, Serializable::SizeType length); //!< sets buffer contents and size
SerializeStatus setBuffLen(Serializable::SizeType length); //!< sets buffer length manually after filling with data
SerializeStatus copyRaw(SerializeBufferBase& dest, Serializable::SizeType size); //!< directly copies buffer without looking for a size in the stream.
// Will increment deserialization pointer
SerializeStatus copyRawOffset(SerializeBufferBase& dest, Serializable::SizeType size); //!< directly copies buffer without looking for a size in the stream.
// Will increment deserialization pointer
#ifdef BUILD_UT
bool operator==(const SerializeBufferBase& other) const;
friend std::ostream& operator<<(std::ostream& os, const SerializeBufferBase& buff);
#endif
PROTECTED:
SerializeBufferBase(); //!< default constructor
PRIVATE:
// A no-implementation copy constructor here will prevent the default copy constructor from being called
// accidentally, and without an implementation it will create an error for the developer instead.
SerializeBufferBase(const SerializeBufferBase &src); //!< constructor with buffer as source
void copyFrom(const SerializeBufferBase& src); //!< copy data from source buffer
Serializable::SizeType m_serLoc; //!< current offset in buffer of serialized data
Serializable::SizeType m_deserLoc; //!< current offset for deserialization
};
// Helper class for building buffers with external storage
class ExternalSerializeBuffer : public SerializeBufferBase {
public:
ExternalSerializeBuffer(U8* buffPtr, Serializable::SizeType size); //!< construct with external buffer
ExternalSerializeBuffer(); //!< default constructor
void setExtBuffer(U8* buffPtr, Serializable::SizeType size); //!< Set the external buffer
void clear(); //!< clear external buffer
// pure virtual functions
Serializable::SizeType getBuffCapacity() const;
U8* getBuffAddr();
const U8* getBuffAddr() const ;
PRIVATE:
// no copying
ExternalSerializeBuffer(ExternalSerializeBuffer& other);
ExternalSerializeBuffer(ExternalSerializeBuffer* other);
// private data
U8* m_buff; //!< pointer to external buffer
Serializable::SizeType m_buffSize; //!< size of external buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/Assert.hpp | #ifndef FW_ASSERT_HPP
#define FW_ASSERT_HPP
#include <FpConfig.hpp>
// Return only the first argument passed to the macro.
#define FW_ASSERT_FIRST_ARG(ARG_0, ...) ARG_0
// Return all the arguments of the macro, but the first one
#define FW_ASSERT_NO_FIRST_ARG(ARG_0, ...) __VA_ARGS__
#if FW_ASSERT_LEVEL == FW_NO_ASSERT
// Users may override the NO_ASSERT case should they choose
#ifndef FW_ASSERT
#define FW_ASSERT(...) ((void)(FW_ASSERT_FIRST_ARG(__VA_ARGS__)))
#endif
#define FILE_NAME_ARG const CHAR*
#else // ASSERT is defined
// Passing the __LINE__ argument at the end of the function ensures that
// the FW_ASSERT_NO_FIRST_ARG macro will never have an empty variadic variable
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
#define FILE_NAME_ARG U32
#define FW_ASSERT(...) \
((void) ((FW_ASSERT_FIRST_ARG(__VA_ARGS__, 0)) ? (0) : \
(Fw::SwAssert(ASSERT_FILE_ID, FW_ASSERT_NO_FIRST_ARG(__VA_ARGS__, __LINE__)))))
#elif FW_ASSERT_LEVEL == FW_RELATIVE_PATH_ASSERT
#define FILE_NAME_ARG const CHAR*
#define FW_ASSERT(...) \
((void) ((FW_ASSERT_FIRST_ARG(__VA_ARGS__, 0)) ? (0) : \
(Fw::SwAssert(ASSERT_RELATIVE_PATH, FW_ASSERT_NO_FIRST_ARG(__VA_ARGS__, __LINE__)))))
#else
#define FILE_NAME_ARG const CHAR*
#define FW_ASSERT(...) \
((void) ((FW_ASSERT_FIRST_ARG(__VA_ARGS__, 0)) ? (0) : \
(Fw::SwAssert(__FILE__, FW_ASSERT_NO_FIRST_ARG(__VA_ARGS__, __LINE__)))))
#endif
#endif // if ASSERT is defined
// F' Assertion functions can technically return even though the intention is for the assertion to terminate the program.
// This breaks static analysis depending on assertions, since the analyzer has to assume the assertion will return.
// When supported, annotate assertion functions as noreturn when statically analyzing.
#ifndef CLANG_ANALYZER_NORETURN
#ifndef __has_feature
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
#if __has_feature(attribute_analyzer_noreturn)
#define CLANG_ANALYZER_NORETURN __attribute__((analyzer_noreturn))
#else
#define CLANG_ANALYZER_NORETURN
#endif
#endif
namespace Fw {
//! Assert with no arguments
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
//! Assert with one argument
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
//! Assert with two arguments
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
//! Assert with three arguments
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
//! Assert with four arguments
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
//! Assert with five arguments
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
FwAssertArgType arg5,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
//! Assert with six arguments
NATIVE_INT_TYPE SwAssert(
FILE_NAME_ARG file,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
FwAssertArgType arg5,
FwAssertArgType arg6,
NATIVE_UINT_TYPE lineNo) CLANG_ANALYZER_NORETURN;
}
// Base class for declaring an assert hook
// Each of the base class functions can be overridden
// or used by derived classes.
namespace Fw {
// Base class for declaring an assert hook
class AssertHook {
public:
AssertHook() : previousHook(nullptr) {}; //!< constructor
virtual ~AssertHook() {}; //!< destructor
// override this function to intercept asserts
virtual 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
);
// default reportAssert() will call this when the message is built
// override it to do another kind of print. printf by default
virtual void printAssert(const CHAR* msg);
// do assert action. By default, calls assert.
// Called after reportAssert()
virtual void doAssert();
// register the hook
void registerHook();
// deregister the hook
void deregisterHook();
protected:
private:
// the previous assert hook
AssertHook *previousHook;
};
}
#endif // FW_ASSERT_HPP
| hpp |
fprime | data/projects/fprime/Fw/Types/BasicTypes.h | /**
* \file: BasicType.h
* \author mstarch
* \brief Declares fprime basic types for usage within C language files
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#include <PlatformTypes.h>
#ifndef FW_BASIC_TYPES_H
#define FW_BASIC_TYPES_H
// Compiler checks
#if defined(__GNUC__) || defined(__llvm__) || defined(PLATFORM_OVERRIDE_GCC_CLANG_CHECK)
#else
#error Unsupported compiler!
#endif
/*----------------------------------------------------------------------------*/
/* Type definitions: I8, U8, I16, U16, ..., I64, U64, F32, and F64 */
/*----------------------------------------------------------------------------*/
typedef int8_t I8; //!< 8-bit signed integer
typedef uint8_t U8; //!< 8-bit unsigned integer
typedef U8 BYTE; //!< byte type
typedef char CHAR;
#if FW_HAS_16_BIT
typedef int16_t I16; //!< 16-bit signed integer
typedef uint16_t U16; //!< 16-bit unsigned integer
#endif
#if FW_HAS_32_BIT
typedef int32_t I32; //!< 32-bit signed integer
typedef uint32_t U32; //!< 32-bit unsigned integer
#endif
#if FW_HAS_64_BIT
typedef int64_t I64; //!< 64-bit signed integer
typedef uint64_t U64; //!< 64-bit unsigned integer
#endif
typedef float F32; //!< 32-bit floating point
#if FW_HAS_F64
typedef double F64; //!< 64-bit floating point
#endif
// Backwards-compatibility definitions
typedef PlatformIntType NATIVE_INT_TYPE;
typedef PlatformUIntType NATIVE_UINT_TYPE;
typedef PlatformPointerCastType POINTER_CAST;
/*----------------------------------------------------------------------------*/
/* Useful macro definitions */
/*----------------------------------------------------------------------------*/
#define FW_NO_ASSERT 1 //!< Asserts turned off
#define FW_FILEID_ASSERT \
2 //!< File ID used - requires -DASSERT_FILE_ID=somevalue to be set on the compile command line
#define FW_FILENAME_ASSERT 3 //!< Uses the file path in the assert - image stores filenames
#define FW_RELATIVE_PATH_ASSERT \
4 //!< Uses a relative file path (within fprime/fprime library) for assert. - requires -DASSERT_RELATIVE_PATH=path
//!< to be set on the compile command line
#define FW_NUM_ARRAY_ELEMENTS(a) (sizeof(a) / sizeof((a)[0])) //!< number of elements in an array
#define FW_MAX(a, b) (((a) > (b)) ? (a) : (b)) //!< MAX macro
#define FW_MIN(a, b) (((a) < (b)) ? (a) : (b)) //!< MIN macro
#ifndef STATIC
#define STATIC static //!< static for non unit-test code
#endif
#ifndef PROTECTED
#define PROTECTED protected //!< overridable protected for unit testing
#endif
#ifndef PRIVATE
#define PRIVATE private //!< overridable private for unit testing
#endif
#endif // FW_BASIC_TYPES_H
| h |