repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
fprime | data/projects/fprime/Svc/BufferLogger/test/ut/Health.hpp | // ======================================================================
// \title Health.hpp
// \author bocchino
// \brief Interface for BufferLogger health tests
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Svc_Health_HPP
#define Svc_Health_HPP
#include "BufferLoggerTester.hpp"
namespace Svc {
namespace Health {
class BufferLoggerTester :
public Svc::BufferLoggerTester
{
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Health ping test
void Ping();
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferLogger/test/ut/BufferLoggerTester.hpp | // ======================================================================
// \title BufferLogger/test/ut/Tester.hpp
// \author bocchino, mereweth
// \brief hpp file for BufferLogger test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "BufferLoggerGTestBase.hpp"
#include "Svc/BufferLogger/BufferLogger.hpp"
#define COM_BUFFER_LENGTH 4
#define MAX_ENTRIES_PER_FILE 5
#define SIZE_TYPE U32
#define MAX_BYTES_PER_FILE \
(MAX_ENTRIES_PER_FILE*COM_BUFFER_LENGTH + MAX_ENTRIES_PER_FILE*sizeof(SIZE_TYPE))
namespace Svc {
class BufferLoggerTester :
public BufferLoggerGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object BufferLoggerTester
//!
BufferLoggerTester(
bool doInitLog = true
);
//! Destroy object BufferLoggerTester
//!
~BufferLoggerTester();
// ----------------------------------------------------------------------
// Tests (rest are in Errors, Health, and Logging classes)
// ----------------------------------------------------------------------
public:
//! No-one called initLog
void LogNoInit();
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_bufferSendOut
//!
void from_bufferSendOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer& fwBuffer
);
//! Handler for from_pingOut
//!
void from_pingOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
protected:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Dispatch one message on the queue
void dispatchOne();
//! Dispatch all messages on the queue
void dispatchAll();
//! Generate a test time
Fw::Time generateTestTime(
const U32 seconds //!< The seconds value
);
//! Set test time seconds
void setTestTimeSeconds(
const U32 seconds //!< The seconds value
);
//! Send com buffers to comIn
void sendComBuffers(
const U32 n //!< The number of buffers to send
);
//! Send managed buffers to bufferSendIn
void sendManagedBuffers(
const U32 n //!< The number of buffers to send
);
//! Check that file exists
void checkFileExists(
const Fw::StringBase& fileName //!< The file name
);
//! Check that hash file exists
void checkHashFileExists(
const Fw::StringBase& fileName //!< The file name
);
//! Check the integrity of a log file
void checkLogFileIntegrity(
const char *const fileName, //!< The file name
const U32 expectedSize, //!< The expected file size in bytes
const U32 expectedNumBuffers //!< The expected number of buffers
);
//! Check file validation
void checkFileValidation(
const char *const fileName //!< The file name
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
protected:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
BufferLogger component;
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! Data for input buffers
static U8 data[COM_BUFFER_LENGTH];
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferLogger/test/ut/BufferLoggerTester.cpp | // ======================================================================
// \title BufferLogger.hpp
// \author bocchino, mereweth
// \brief cpp file for BufferLogger test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "BufferLoggerTester.hpp"
#include "Fw/Types/SerialBuffer.hpp"
#include "Os/ValidatedFile.hpp"
#include "Os/FileSystem.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 30
#define QUEUE_DEPTH 10
namespace Svc {
// ----------------------------------------------------------------------
// Instance variables
// ----------------------------------------------------------------------
U8 BufferLoggerTester::data[COM_BUFFER_LENGTH] = { 0xDE, 0xAD, 0xBE, 0xEF };
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
BufferLoggerTester ::
BufferLoggerTester(bool doInitLog) :
BufferLoggerGTestBase("Tester", MAX_HISTORY_SIZE),
component("BufferLogger")
{
(void) system("rm -rf buf");
(void) system("mkdir buf");
this->initComponents();
this->connectPorts();
if (doInitLog) {
this->component.initLog(
"buf/log",
".buf",
static_cast<U32>(MAX_BYTES_PER_FILE),
sizeof(SIZE_TYPE)
);
}
}
BufferLoggerTester ::
~BufferLoggerTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void BufferLoggerTester ::
LogNoInit()
{
this->component.m_file.m_baseName = Fw::String("LogNoInit");
// NOTE (mereweth) - make something sensible happen when no-one calls initLog()
// Send data
this->sendComBuffers(3);
ASSERT_EVENTS_SIZE(3);
ASSERT_EVENTS_BL_NoLogFileOpenInitError_SIZE(3);
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void BufferLoggerTester ::
from_bufferSendOut_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer& fwBuffer
)
{
this->pushFromPortEntry_bufferSendOut(fwBuffer);
}
void BufferLoggerTester ::
from_pingOut_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
this->pushFromPortEntry_pingOut(key);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void BufferLoggerTester ::
connectPorts()
{
// bufferSendIn
this->connect_to_bufferSendIn(
0,
this->component.get_bufferSendIn_InputPort(0)
);
// cmdIn
this->connect_to_cmdIn(
0,
this->component.get_cmdIn_InputPort(0)
);
// comIn
this->connect_to_comIn(
0,
this->component.get_comIn_InputPort(0)
);
// pingIn
this->connect_to_pingIn(
0,
this->component.get_pingIn_InputPort(0)
);
// schedIn
this->connect_to_schedIn(
0,
this->component.get_schedIn_InputPort(0)
);
// bufferSendOut
this->component.set_bufferSendOut_OutputPort(
0,
this->get_from_bufferSendOut(0)
);
// cmdRegOut
this->component.set_cmdRegOut_OutputPort(
0,
this->get_from_cmdRegOut(0)
);
// cmdResponseOut
this->component.set_cmdResponseOut_OutputPort(
0,
this->get_from_cmdResponseOut(0)
);
// eventOut
this->component.set_eventOut_OutputPort(
0,
this->get_from_eventOut(0)
);
// eventOutText
this->component.set_eventOutText_OutputPort(
0,
this->get_from_eventOutText(0)
);
// pingOut
this->component.set_pingOut_OutputPort(
0,
this->get_from_pingOut(0)
);
// timeCaller
this->component.set_timeCaller_OutputPort(
0,
this->get_from_timeCaller(0)
);
// tlmOut
this->component.set_tlmOut_OutputPort(
0,
this->get_from_tlmOut(0)
);
}
void BufferLoggerTester ::
initComponents()
{
this->init();
this->component.init(
QUEUE_DEPTH, INSTANCE
);
}
void BufferLoggerTester ::
dispatchOne()
{
this->component.doDispatch();
}
void BufferLoggerTester ::
dispatchAll()
{
while(this->component.m_queue.getNumMsgs() > 0)
this->dispatchOne();
}
Fw::Time BufferLoggerTester ::
generateTestTime(const U32 seconds)
{
Fw::Time time(TB_DONT_CARE, FW_CONTEXT_DONT_CARE, 234567, seconds);
return time;
}
void BufferLoggerTester ::
setTestTimeSeconds(const U32 seconds)
{
Fw::Time time = this->generateTestTime(seconds);
this->setTestTime(time);
}
void BufferLoggerTester ::
sendComBuffers(const U32 n)
{
Fw::ComBuffer buffer(data, sizeof(data));
for (U32 i = 0; i < n; ++i) {
this->invoke_to_comIn(0, buffer, 0);
this->dispatchOne();
}
}
void BufferLoggerTester ::
sendManagedBuffers(const U32 n)
{
Fw::Buffer buffer(data, sizeof(data));
for (U32 i = 0; i < n; ++i) {
this->invoke_to_bufferSendIn(0, buffer);
this->dispatchOne();
}
}
void BufferLoggerTester ::
checkFileExists(const Fw::StringBase& fileName)
{
Fw::String command;
command.format("test -f %s", fileName.toChar());
const int status = system(command.toChar());
ASSERT_EQ(0, status);
}
void BufferLoggerTester ::
checkHashFileExists(const Fw::StringBase& fileName)
{
Os::ValidatedFile validatedFile(fileName.toChar());
const Fw::String& hashFileName = validatedFile.getHashFileName();
this->checkFileExists(hashFileName);
}
void BufferLoggerTester ::
checkLogFileIntegrity(
const char *const fileName,
const U32 expectedSize,
const U32 expectedNumBuffers
)
{
{
// Make sure the file size is within bounds
FwSignedSizeType actualSize = 0;
const Os::FileSystem::Status status =
Os::FileSystem::getFileSize(fileName, actualSize);
ASSERT_EQ(Os::FileSystem::OP_OK, status);
ASSERT_LE(expectedSize, actualSize);
}
// Open the file
Os::File file;
{
const Os::File::Status status =
file.open(fileName, Os::File::OPEN_READ);
ASSERT_EQ(Os::File::OP_OK, status);
}
// Check the data
U8 buf[expectedSize];
for (U32 i = 0; i < expectedNumBuffers; ++i) {
// Get length of buffer to read
FwSignedSizeType length = sizeof(SIZE_TYPE);
Os::File::Status status = file.read(buf, length);
ASSERT_EQ(Os::File::OP_OK, status);
ASSERT_EQ(sizeof(SIZE_TYPE), static_cast<U32>(length));
Fw::SerialBuffer comBuffLength(buf, length);
comBuffLength.fill();
SIZE_TYPE bufferSize;
const Fw::SerializeStatus serializeStatus =
comBuffLength.deserialize(bufferSize);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, serializeStatus);
ASSERT_EQ(sizeof(data), bufferSize);
// Read and check the buffer
length = bufferSize;
status = file.read(buf, length);
ASSERT_EQ(Os::File::OP_OK, status);
ASSERT_EQ(bufferSize, static_cast<U32>(length));
ASSERT_EQ(memcmp(buf, data, sizeof(data)), 0);
}
// Make sure we reached the end of the file
{
FwSignedSizeType length = 10;
const Os::File::Status status = file.read(buf, length);
ASSERT_EQ(Os::File::OP_OK, status);
ASSERT_EQ(0, length);
}
}
void BufferLoggerTester ::
checkFileValidation(const char *const fileName)
{
Os::ValidatedFile validatedFile(fileName);
const Os::ValidateFile::Status status = validatedFile.validate();
ASSERT_EQ(Os::ValidateFile::VALIDATION_OK, status);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/Framer/Framer.hpp | // ======================================================================
// \title Framer.hpp
// \author mstarch, bocchino
// \brief hpp file for Framer component implementation class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Svc_Framer_HPP
#define Svc_Framer_HPP
#include "Svc/Framer/FramerComponentAc.hpp"
#include "Svc/FramingProtocol/FramingProtocol.hpp"
#include "Svc/FramingProtocol/FramingProtocolInterface.hpp"
namespace Svc {
/**
* \brief Generic framing component using FramingProtocol implementation for actual framing
*
* Framing component used to take Com and File packets and frame serialize them using a
* framing protocol specified in a FramingProtocol instance. The instance must be supplied
* using the `setup` method.
*
* Using this component, projects can implement and supply a fresh FramingProtocol implementation
* without changing the reference topology.
*/
class Framer : public FramerComponentBase, public FramingProtocolInterface {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object Framer
//!
Framer(const char* const compName /*!< The component name*/
);
//! Initialize object Framer
//!
void init(const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! \brief Setup this component with a supplied framing protocol
//!
void setup(FramingProtocol& protocol /*!< Protocol used in framing */);
//! Destroy object Framer
//!
~Framer();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for comIn
//!
void comIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::ComBuffer& data, /*!< Buffer containing packet data*/
U32 context /*!< Call context value; meaning chosen by user*/
);
//! Handler implementation for bufferIn
//!
void bufferIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer& fwBuffer /*!< The buffer*/
);
//! Handler implementation for comStatusIn
//!
void comStatusIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Success& condition /*!< The condition*/);
// ----------------------------------------------------------------------
// Implementation of FramingProtocolInterface
// ----------------------------------------------------------------------
//! \brief Allocation callback used to request memory for the framer
//!
//! Method used by the FramingProtocol to allocate memory for the framed buffer. Framing
//! typically adds tokens on the beginning and end of the raw data so it must allocate new space
//! to place those and a copy of the data in.
//!
//! \param size: size of allocation
//! \return Fw::Buffer containing allocation to write into
Fw::Buffer allocate(const U32 size);
//! Send implementation
//!
void send(Fw::Buffer& outgoing //!< The buffer to send
);
// ----------------------------------------------------------------------
// Helper functions
// ----------------------------------------------------------------------
//! \brief helper function to handle framing of the raw data
//!
void handle_framing(const U8* const data, const U32 size, Fw::ComPacket::ComPacketType packet_type);
// ----------------------------------------------------------------------
// Member variables
// ----------------------------------------------------------------------
//! The FramingProtocol implementation
FramingProtocol* m_protocol;
//! Flag determining if at least one frame was sent during framing
bool m_frame_sent;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/Framer/Framer.cpp | // ======================================================================
// \title Framer.cpp
// \author mstarch
// \brief cpp file for Framer component implementation class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <FpConfig.hpp>
#include <Svc/Framer/Framer.hpp>
#include "Fw/Logger/Logger.hpp"
#include "Utils/Hash/Hash.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
Framer ::Framer(const char* const compName)
: FramerComponentBase(compName), FramingProtocolInterface(), m_protocol(nullptr), m_frame_sent(false) {}
void Framer ::init(const NATIVE_INT_TYPE instance) {
FramerComponentBase::init(instance);
}
Framer ::~Framer() {}
void Framer ::setup(FramingProtocol& protocol) {
FW_ASSERT(this->m_protocol == nullptr);
this->m_protocol = &protocol;
protocol.setup(*this);
}
void Framer ::handle_framing(const U8* const data, const U32 size, Fw::ComPacket::ComPacketType packet_type) {
FW_ASSERT(this->m_protocol != nullptr);
this->m_frame_sent = false; // Clear the flag to detect if frame was sent
this->m_protocol->frame(data, size, packet_type);
// If no frame was sent, Framer has the obligation to report success
if (this->isConnected_comStatusOut_OutputPort(0) && (!this->m_frame_sent)) {
Fw::Success status = Fw::Success::SUCCESS;
this->comStatusOut_out(0, status);
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void Framer ::comIn_handler(const NATIVE_INT_TYPE portNum, Fw::ComBuffer& data, U32 context) {
this->handle_framing(data.getBuffAddr(), data.getBuffLength(), Fw::ComPacket::FW_PACKET_UNKNOWN);
}
void Framer ::bufferIn_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
this->handle_framing(fwBuffer.getData(), fwBuffer.getSize(), Fw::ComPacket::FW_PACKET_FILE);
// Deallocate the buffer after it was processed by the framing protocol
this->bufferDeallocate_out(0, fwBuffer);
}
void Framer ::comStatusIn_handler(const NATIVE_INT_TYPE portNum, Fw::Success& condition) {
if (this->isConnected_comStatusOut_OutputPort(portNum)) {
this->comStatusOut_out(portNum, condition);
}
}
// ----------------------------------------------------------------------
// Framing protocol implementations
// ----------------------------------------------------------------------
void Framer ::send(Fw::Buffer& outgoing) {
FW_ASSERT(!this->m_frame_sent); // Prevent multiple sends per-packet
const Drv::SendStatus sendStatus = this->framedOut_out(0, outgoing);
if (sendStatus.e != Drv::SendStatus::SEND_OK) {
// Note: if there is a data sending problem, an EVR likely wouldn't
// make it down. Log the issue in hopes that
// someone will see it.
Fw::Logger::logMsg("[ERROR] Failed to send framed data: %d\n", sendStatus.e);
}
this->m_frame_sent = true; // A frame was sent
}
Fw::Buffer Framer ::allocate(const U32 size) {
return this->framedAllocate_out(0, size);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/Framer/test/ut/FramerTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "Fw/Test/UnitTest.hpp"
#include "Os/Log.hpp"
#include "FramerTester.hpp"
// Enable the console logging provided by Os::Log
Os::Log logger;
TEST(Nominal, Com) {
COMMENT("Send one Fw::Com buffer to the framer (nominal behavior)");
REQUIREMENT("SVC-FRAMER-001");
REQUIREMENT("SVC-FRAMER-003");
Svc::FramerTester tester;
tester.test_com();
}
TEST(Nominal, Buffer) {
COMMENT("Send one Fw::Buffer to the framer (nominal behavior)");
REQUIREMENT("SVC-FRAMER-002");
REQUIREMENT("SVC-FRAMER-003");
Svc::FramerTester tester;
tester.test_buffer();
}
TEST(Nominal, ManySends) {
COMMENT("Send several buffers");
REQUIREMENT("SVC-FRAMER-001");
REQUIREMENT("SVC-FRAMER-002");
REQUIREMENT("SVC-FRAMER-003");
Svc::FramerTester tester;
tester.test_com(27);
tester.test_buffer(27);
tester.test_com(31);
tester.test_buffer(31);
}
TEST(Nominal, StatusPassThrough) {
COMMENT("Ensure status pass-through");
REQUIREMENT("SVC-FRAMER-004");
Svc::FramerTester tester;
tester.test_status_pass_through();
}
TEST(Nominal, NoSendStatus) {
COMMENT("Ensure status on no-send");
REQUIREMENT("SVC-FRAMER-003");
Svc::FramerTester tester;
tester.test_no_send_status();
}
TEST(SendError, Buffer) {
COMMENT("Send one Fw::Buffer to the framer (send error)");
REQUIREMENT("SVC-FRAMER-002");
REQUIREMENT("SVC-FRAMER-003");
Svc::FramerTester tester;
tester.setSendStatus(Drv::SendStatus::SEND_ERROR);
tester.test_buffer();
}
TEST(SendError, Com) {
COMMENT("Send one Fw::Com buffer to the framer (send error)");
REQUIREMENT("SVC-FRAMER-001");
REQUIREMENT("SVC-FRAMER-003");
Svc::FramerTester tester;
tester.setSendStatus(Drv::SendStatus::SEND_ERROR);
tester.test_com();
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/Framer/test/ut/FramerTester.cpp | // ======================================================================
// \title Framer.hpp
// \author mstarch, bocchino
// \brief cpp file for Framer test harness implementation class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FramerTester.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 1000
namespace Svc {
FramerTester::MockFramer::MockFramer(FramerTester& parent) : m_parent(parent), m_do_not_send(false) {}
void FramerTester::MockFramer::frame(const U8* const data, const U32 size, Fw::ComPacket::ComPacketType packet_type) {
// When testing without the send case, disable all mock functions
if (!m_do_not_send) {
Fw::Buffer buffer(const_cast<U8*>(data), size);
m_parent.check_last_buffer(buffer);
Fw::Buffer allocated = m_interface->allocate(size);
m_interface->send(allocated);
}
}
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
FramerTester ::FramerTester()
: FramerGTestBase("Tester", MAX_HISTORY_SIZE),
component("Framer"),
m_mock(*this),
m_framed(false),
m_sent(false),
m_returned(false),
m_sendStatus(Drv::SendStatus::SEND_OK)
{
this->initComponents();
this->connectPorts();
component.setup(this->m_mock);
}
FramerTester ::~FramerTester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void FramerTester ::test_com(U32 iterations) {
for (U32 i = 0; i < iterations; i++) {
Fw::ComBuffer com;
m_buffer.set(com.getBuffAddr(), com.getBuffLength());
m_framed = false;
m_sent = false;
m_returned = false;
invoke_to_comIn(0, com, 0);
ASSERT_TRUE(m_framed);
if (m_sendStatus == Drv::SendStatus::SEND_OK) {
ASSERT_TRUE(m_sent);
} else {
ASSERT_FALSE(m_sent);
}
ASSERT_FALSE(m_returned);
}
}
void FramerTester ::test_buffer(U32 iterations) {
for (U32 i = 0; i < iterations; i++) {
Fw::Buffer buffer(new U8[3412], 3412);
m_framed = false;
m_sent = false;
m_returned = false;
m_buffer = buffer;
invoke_to_bufferIn(0, buffer);
ASSERT_TRUE(m_framed);
if (m_sendStatus == Drv::SendStatus::SEND_OK) {
ASSERT_TRUE(m_sent);
} else {
ASSERT_FALSE(m_sent);
}
ASSERT_TRUE(m_returned);
}
}
void FramerTester ::test_status_pass_through() {
// Check not always success
Fw::Success status = Fw::Success::FAILURE;
invoke_to_comStatusIn(0, status);
ASSERT_from_comStatusOut(0, status);
// Check a success
status = Fw::Success::SUCCESS;
invoke_to_comStatusIn(0, status);
ASSERT_from_comStatusOut(1, status);
}
void FramerTester ::test_no_send_status() {
Fw::Success status = Fw::Success::SUCCESS;
m_mock.m_do_not_send = true;
// Send com buffer and check no send and a status
Fw::ComBuffer com;
invoke_to_comIn(0, com, 0);
ASSERT_from_framedOut_SIZE(0);
ASSERT_from_comStatusOut(0, status);
Fw::Buffer buffer(new U8[3412], 3412);
invoke_to_bufferIn(0, buffer);
ASSERT_from_framedOut_SIZE(0);
ASSERT_from_comStatusOut(0, status);
clearFromPortHistory();
// Make sure it still does pass-through
test_status_pass_through();
}
void FramerTester ::check_last_buffer(Fw::Buffer buffer) {
ASSERT_EQ(buffer, m_buffer);
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void FramerTester ::from_bufferDeallocate_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
this->pushFromPortEntry_bufferDeallocate(fwBuffer);
m_returned = true;
delete[] fwBuffer.getData();
}
Fw::Buffer FramerTester ::from_framedAllocate_handler(const NATIVE_INT_TYPE portNum, U32 size) {
this->pushFromPortEntry_framedAllocate(size);
Fw::Buffer buffer(new U8[size], size);
m_buffer = buffer;
return buffer;
}
Drv::SendStatus FramerTester ::from_framedOut_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& sendBuffer) {
this->pushFromPortEntry_framedOut(sendBuffer);
this->check_last_buffer(sendBuffer);
delete[] sendBuffer.getData();
m_framed = true;
if (m_sendStatus == Drv::SendStatus::SEND_OK) {
m_sent = true;
}
return m_sendStatus;
}
void FramerTester ::from_comStatusOut_handler(const NATIVE_INT_TYPE portNum, Fw::Success& condition) {
this->pushFromPortEntry_comStatusOut(condition);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void FramerTester ::connectPorts() {
// comIn
this->connect_to_comIn(0, this->component.get_comIn_InputPort(0));
// bufferIn
this->connect_to_bufferIn(0, this->component.get_bufferIn_InputPort(0));
// bufferDeallocate
this->component.set_bufferDeallocate_OutputPort(0, this->get_from_bufferDeallocate(0));
// framedAllocate
this->component.set_framedAllocate_OutputPort(0, this->get_from_framedAllocate(0));
// framedOut
this->component.set_framedOut_OutputPort(0, this->get_from_framedOut(0));
// comStatusIn
this->connect_to_comStatusIn(0, this->component.get_comStatusIn_InputPort(0));
// comStatusOut
this->component.set_comStatusOut_OutputPort(0, this->get_from_comStatusOut(0));
}
void FramerTester ::initComponents() {
this->init();
this->component.init(INSTANCE);
}
void FramerTester ::setSendStatus(Drv::SendStatus sendStatus) {
m_sendStatus = sendStatus;
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/Framer/test/ut/FramerTester.hpp | // ======================================================================
// \title Framer/test/ut/Tester.hpp
// \author mstarch, bocchino
// \brief hpp file for Framer test harness implementation class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "FramerGTestBase.hpp"
#include "Svc/Framer/Framer.hpp"
namespace Svc {
class FramerTester : public FramerGTestBase {
public:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
//! Mock framing protocol
class MockFramer : public FramingProtocol {
public:
MockFramer(FramerTester& parent);
void frame(
const U8* const data,
const U32 size,
Fw::ComPacket::ComPacketType packet_type
);
FramerTester& m_parent;
bool m_do_not_send;
};
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object FramerTester
FramerTester();
//! Destroy object FramerTester
~FramerTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Test incoming Fw::Com data to the framer
void test_com(U32 iterations = 1);
//! Test incoming Fw::Buffer data to the framer
void test_buffer(U32 iterations = 1);
//! Tests statuses pass-through
void test_status_pass_through();
//! Tests statuses on no-send
void test_no_send_status();
//! Check that buffer is equal to the last buffer allocated
void check_last_buffer(Fw::Buffer buffer);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_bufferDeallocate
void from_bufferDeallocate_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer& fwBuffer //!< The buffer
);
//! Handler for from_framedAllocate
Fw::Buffer from_framedAllocate_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
U32 size //!< The size
);
//! Handler for from_framedOut
Drv::SendStatus from_framedOut_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer& sendBuffer //!< The buffer containing framed data
);
//! Handler for from_comStatusOut
//!
void from_comStatusOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Success &condition /*!< Condition success/failure */
);
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Set the send status
void setSendStatus(Drv::SendStatus sendStatus);
private:
// ----------------------------------------------------------------------
// Private instance methods
// ----------------------------------------------------------------------
//! Connect ports
void connectPorts();
//! Initialize components
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
Framer component;
//! Buffer for sending unframed data
Fw::Buffer m_buffer;
//! Mock framing protocol
MockFramer m_mock;
//! Whether framing succeeded
bool m_framed;
//! Whether sending succeeded
bool m_sent;
//! Whether the frame buffer was deallocated
bool m_returned;
//! Send status for error injection
Drv::SendStatus m_sendStatus;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/PosixTime/PosixTime.hpp | /*
* TestTelemRecvImpl.hpp
*
* Created on: Mar 28, 2014
* Author: tcanham
*/
#ifndef POSIX_TIME_HPP_
#define POSIX_TIME_HPP_
#include <Svc/PosixTime/PosixTimeComponentAc.hpp>
namespace Svc {
class PosixTime: public PosixTimeComponentBase {
public:
explicit PosixTime(const char* compName);
virtual ~PosixTime();
protected:
void timeGetPort_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Time &time /*!< The U32 cmd argument*/
);
private:
};
}
#endif /* POSIX_TIME_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/PosixTime/PosixTime.cpp | /*
* TestCommand1Impl.cpp
*
* Created on: Mar 28, 2014
* Author: tcanham
*/
#include <Svc/PosixTime/PosixTime.hpp>
#include <Fw/Time/Time.hpp>
#include <ctime>
namespace Svc {
PosixTime::PosixTime(const char* name) : PosixTimeComponentBase(name)
{
}
PosixTime::~PosixTime() {
}
void PosixTime::timeGetPort_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Time &time /*!< The U32 cmd argument*/
) {
timespec stime;
(void)clock_gettime(CLOCK_REALTIME,&stime);
time.set(TB_WORKSTATION_TIME,0, stime.tv_sec, stime.tv_nsec/1000);
}
}
| cpp |
fprime | data/projects/fprime/Svc/PosixTime/test/ut/PosixTimeTester.hpp | // ----------------------------------------------------------------------
// PosixTimeTester.hpp
// ----------------------------------------------------------------------
#ifndef POSIX_TIME_TESTER_HPP
#define POSIX_TIME_TESTER_HPP
#include "Svc/PosixTime/PosixTime.hpp"
#include "PosixTimeGTestBase.hpp"
namespace Svc {
class PosixTimeTester :
public PosixTimeGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
explicit PosixTimeTester(const char *const compName);
~PosixTimeTester();
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
public:
void getTime();
// ----------------------------------------------------------------------
// The component under test
// ----------------------------------------------------------------------
private:
PosixTime component;
};
};
#endif
| hpp |
fprime | data/projects/fprime/Svc/PosixTime/test/ut/PosixTimeMain.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include "PosixTimeTester.hpp"
TEST(Test, GetTime) {
Svc::PosixTimeTester tester("Tester");
tester.getTime();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/PosixTime/test/ut/PosixTimeTester.cpp | // ----------------------------------------------------------------------
// PosixTime/test/ut/Tester.cpp
// ----------------------------------------------------------------------
#include <cstdio>
#include <strings.h>
#include "PosixTimeTester.hpp"
#define INSTANCE 0
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
PosixTimeTester ::
PosixTimeTester(const char *const compName) :
PosixTimeGTestBase(compName, 0),
component("PosixTime")
{
this->init();
this->component.init(INSTANCE);
this->connect_to_timeGetPort(
0,
this->component.get_timeGetPort_InputPort(0)
);
}
PosixTimeTester ::
~PosixTimeTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void PosixTimeTester ::
getTime()
{
Fw::Time time;
this->invoke_to_timeGetPort(0,time);
ASSERT_GT(time.getSeconds(), 0U);
ASSERT_GE(time.getUSeconds(), 0U);
ASSERT_LE(time.getUSeconds(), 999999U);
}
};
| cpp |
fprime | data/projects/fprime/Svc/GroundInterface/GroundInterface.cpp | // ======================================================================
// \title GroundInterface.cpp
// \author lestarch
// \brief cpp file for GroundInterface component implementation class
// ======================================================================
#include <Fw/Com/ComPacket.hpp>
#include <Svc/GroundInterface/GroundInterface.hpp>
#include <FpConfig.hpp>
#include <cstring>
namespace Svc {
const U32 GroundInterfaceComponentImpl::MAX_DATA_SIZE = 2048;
const TOKEN_TYPE GroundInterfaceComponentImpl::START_WORD = static_cast<TOKEN_TYPE>(0xdeadbeef);
const U32 GroundInterfaceComponentImpl::END_WORD = static_cast<U32>(0xcafecafe);
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
GroundInterfaceComponentImpl ::
GroundInterfaceComponentImpl(
const char *const compName
) : GroundInterfaceComponentBase(compName),
m_ext_buffer(m_buffer, GND_BUFFER_SIZE),
m_data_size(0),
m_in_ring(m_in_buffer, GND_BUFFER_SIZE)
{
}
void GroundInterfaceComponentImpl ::
init(
const NATIVE_INT_TYPE instance
)
{
GroundInterfaceComponentBase::init(instance);
}
GroundInterfaceComponentImpl ::
~GroundInterfaceComponentImpl()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void GroundInterfaceComponentImpl ::
downlinkPort_handler(
const NATIVE_INT_TYPE portNum,
Fw::ComBuffer &data,
U32 context
)
{
FW_ASSERT(data.getBuffLength() <= MAX_DATA_SIZE);
frame_send(data.getBuffAddr(), data.getBuffLength());
}
void GroundInterfaceComponentImpl ::
fileDownlinkBufferSendIn_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
FW_ASSERT(fwBuffer.getSize() <= MAX_DATA_SIZE);
frame_send(fwBuffer.getData(), fwBuffer.getSize(), Fw::ComPacket::FW_PACKET_FILE);
fileDownlinkBufferSendOut_out(0, fwBuffer);
}
void GroundInterfaceComponentImpl ::
readCallback_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &buffer
)
{
processBuffer(buffer);
}
void GroundInterfaceComponentImpl ::
schedIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!< The call order*/
)
{
// TODO: replace with a call to a buffer manager
Fw::Buffer buffer = m_ext_buffer;
// Call read poll if it is hooked up
if (isConnected_readPoll_OutputPort(0)) {
readPoll_out(0, buffer);
processBuffer(buffer);
}
}
void GroundInterfaceComponentImpl::frame_send(U8 *data, TOKEN_TYPE size, TOKEN_TYPE packet_type) {
// TODO: replace with a call to a buffer manager
Fw::Buffer buffer = m_ext_buffer;
Fw::SerializeBufferBase& buffer_wrapper = buffer.getSerializeRepr();
buffer_wrapper.resetSer();
// True size is supplied size plus sizeof(TOKEN_TYPE) if a packet_type other than "UNKNOWN" was supplied.
// This is because if not UNKNOWN, the packet_type is serialized too. Otherwise it is assumed the PACKET_TYPE is
// already the first token in the UNKNOWN typed buffer.
U32 true_size = (packet_type != Fw::ComPacket::FW_PACKET_UNKNOWN) ? size + sizeof(TOKEN_TYPE) : size;
U32 total_size = sizeof(TOKEN_TYPE) + sizeof(TOKEN_TYPE) + true_size + sizeof(U32);
// Serialize data
FW_ASSERT(GND_BUFFER_SIZE >= total_size, GND_BUFFER_SIZE, total_size);
buffer_wrapper.serialize(START_WORD);
buffer_wrapper.serialize(static_cast<TOKEN_TYPE>(true_size));
// Explicitly set the packet type, if it didn't come with the data already
if (packet_type != Fw::ComPacket::FW_PACKET_UNKNOWN) {
buffer_wrapper.serialize(packet_type);
}
buffer_wrapper.serialize(data, size, true);
buffer_wrapper.serialize(static_cast<TOKEN_TYPE>(END_WORD));
// Setup for sending by truncating unused data
buffer.setSize(buffer_wrapper.getBuffLength());
FW_ASSERT(buffer.getSize() == total_size, buffer.getSize(), total_size);
write_out(0, buffer);
}
void GroundInterfaceComponentImpl ::
routeComData()
{
// Read the packet type from the data buffer
FwPacketDescriptorType packet_type = Fw::ComPacket::FW_PACKET_UNKNOWN;
//read packet descriptor in size agnostic way
U8 packet_descriptor_size = sizeof(FwPacketDescriptorType);
U8 packet_type_bytes[sizeof(FwPacketDescriptorType)];
Fw::SerializeStatus stat = m_in_ring.peek(packet_type_bytes, packet_descriptor_size, HEADER_SIZE);
//m_in_ring.peek(packet_type, HEADER_SIZE); // this way is only valid for 4byte packet descriptors
if(stat == Fw::FW_SERIALIZE_OK)
{
// unpack Big Endian encoded bytes
packet_type = 0;
for(int i = 0; i < packet_descriptor_size; i++)
{
packet_type <<= 8;
packet_type |= packet_type_bytes[i];
}
}
// Process variable type
switch (packet_type) {
case Fw::ComPacket::FW_PACKET_COMMAND: {
Fw::ComBuffer com;
m_in_ring.peek(com.getBuffAddr(), m_data_size, HEADER_SIZE);
// Reset com buffer for sending out data
com.setBuffLen(m_data_size);
uplinkPort_out(0, com, 0);
break;
}
case Fw::ComPacket::FW_PACKET_FILE: {
// If file uplink is possible, handle files. Otherwise ignore.
if (isConnected_fileUplinkBufferGet_OutputPort(0) &&
isConnected_fileDownlinkBufferSendOut_OutputPort(0)) {
Fw::Buffer buffer = fileUplinkBufferGet_out(0, m_data_size);
m_in_ring.peek(buffer.getData(), m_data_size - sizeof(packet_type), HEADER_SIZE + sizeof(packet_type));
buffer.setSize(m_data_size - sizeof(packet_type));
fileUplinkBufferSendOut_out(0, buffer);
}
break;
}
default:
return;
}
}
void GroundInterfaceComponentImpl ::
processRing()
{
// Header items for the packet
TOKEN_TYPE start;
U32 checksum; //TODO: make this run a CRC32
// Inner-loop, process ring buffer looking for at least the header
while (m_in_ring.get_allocated_size() >= HEADER_SIZE) {
m_data_size = 0;
// Peek into the header and read out values
Fw::SerializeStatus status = m_in_ring.peek(start, 0);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
status = m_in_ring.peek(m_data_size, sizeof(TOKEN_TYPE));
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
// Check the header for correctness
if (start != START_WORD || m_data_size >= MAX_DATA_SIZE) {
m_in_ring.rotate(1);
continue;
}
// Check for enough data to deserialize everything otherwise break and wait for more.
else if (m_in_ring.get_allocated_size() < (HEADER_SIZE + m_data_size + sizeof(END_WORD))) {
break;
}
// Continue with the data portion and checksum
m_in_ring.peek(checksum, HEADER_SIZE + m_data_size);
// Check checksum
if (checksum == END_WORD) {
routeComData();
m_in_ring.rotate(HEADER_SIZE + m_data_size + sizeof(U32));
}
// Failed checksum, keep looking for valid message
else {
m_in_ring.rotate(1);
}
}
}
void GroundInterfaceComponentImpl ::
processBuffer(Fw::Buffer& buffer)
{
NATIVE_UINT_TYPE buffer_offset = 0;
while (buffer_offset < buffer.getSize()) {
NATIVE_UINT_TYPE ser_size = (buffer.getSize() >= m_in_ring.get_free_size()) ?
m_in_ring.get_free_size() : static_cast<NATIVE_UINT_TYPE>(buffer.getSize());
m_in_ring.serialize(buffer.getData() + buffer_offset, ser_size);
buffer_offset = buffer_offset + ser_size;
processRing();
}
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/GroundInterface/GroundInterface.hpp | // ======================================================================
// \title GroundInterfaceImpl.hpp
// \author lestarch
// \brief hpp file for GroundInterface component implementation class
// ======================================================================
#include <Fw/Types/Serializable.hpp>
#include "Svc/GroundInterface/GroundInterfaceComponentAc.hpp"
#include "Utils/Types/CircularBuffer.hpp"
#ifndef GroundInterface_HPP
#define GroundInterface_HPP
#define GND_BUFFER_SIZE 1024
#define TOKEN_TYPE U32
#define HEADER_SIZE (2 * sizeof(TOKEN_TYPE))
namespace Svc {
class GroundInterfaceComponentImpl :
public GroundInterfaceComponentBase
{
public:
static const U32 MAX_DATA_SIZE;
static const TOKEN_TYPE START_WORD;
static const U32 END_WORD;
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object GroundInterface
//!
GroundInterfaceComponentImpl(
const char *const compName /*!< The component name*/
);
//! Initialize object GroundInterface
//!
void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object GroundInterface
//!
~GroundInterfaceComponentImpl();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for downlinkPort
//!
void downlinkPort_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::ComBuffer &data, /*!< Buffer containing packet data*/
U32 context /*!< Call context value; meaning chosen by user*/
);
//! Handler implementation for fileDownlinkBufferSendIn
//!
void fileDownlinkBufferSendIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
//! Handler implementation for readCallback
//!
void readCallback_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
//! Handler implementation for schedIn
//!
void schedIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!< The call order*/
);
//! Frame and send some data
//!
void frame_send(
U8* data, /*!< Data to be framed and sent out */
TOKEN_TYPE size, /*!< Size of data in typed format */
TOKEN_TYPE packet_type = Fw::ComPacket::FW_PACKET_UNKNOWN /*!< Packet type override for anonymous data i.e. file downlink */
);
//! Processes the out-going data into coms order
void routeComData();
//! Process all the data in the ring
void processRing();
//! Process a data buffer containing a read from the serial port
void processBuffer(Fw::Buffer& data /*!< Data to process */);
// Basic data movement variables
Fw::Buffer m_ext_buffer;
U8 m_buffer[GND_BUFFER_SIZE];
// Input variables
TOKEN_TYPE m_data_size; //!< Data size expected in incoming data
U8 m_in_buffer[GND_BUFFER_SIZE];
Types::CircularBuffer m_in_ring;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/GroundInterface/test/ut/GroundInterfaceTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "GroundInterfaceTester.hpp"
#include <gtest/gtest.h>
#include <Svc/GroundInterface/test/ut/GroundInterfaceRules.hpp>
#include <STest/Scenario/Scenario.hpp>
#include <STest/Scenario/RandomScenario.hpp>
#include <STest/Scenario/BoundedScenario.hpp>
#define STEP_COUNT 10000
/**
* A random hopper for rules. Apply STEP_COUNT times.
*/
TEST(Nominal, RandomizedGroundIf) {
Svc::GroundInterfaceTester tester;
// Create rules, and assign them into the array
Svc::RandomizeRule randomize("Randomize");
Svc::DownlinkRule downlink("Downlink");
Svc::FileDownlinkRule filedown("File Down");
Svc::SendAvailableRule sendup("");
// Setup a list of rules to choose from
STest::Rule<Svc::GroundInterfaceTester>* rules[] = {
&randomize,
&downlink,
&filedown,
&sendup
};
// Construct the random scenario and run it with the defined bounds
STest::RandomScenario<Svc::GroundInterfaceTester> random("Random Rules", rules, FW_NUM_ARRAY_ELEMENTS(rules));
// Setup a bounded scenario to run rules a set number of times
STest::BoundedScenario<Svc::GroundInterfaceTester> bounded("Bounded Random Rules Scenario", random, STEP_COUNT);
// Run!
const U32 numSteps = bounded.run(tester);
printf("Ran %u steps.\n", numSteps);
}
TEST(Nominal, BasicUplink) {
Svc::GroundInterfaceTester tester;
Svc::SendAvailableRule rule("Uplink Rule");
rule.apply(tester);
}
TEST(Nominal, BasicDownlink) {
Svc::GroundInterfaceTester tester;
Svc::DownlinkRule rule("Downlink Rule");
rule.apply(tester);
}
TEST(Nominal, FileDownlink) {
Svc::GroundInterfaceTester tester;
Svc::FileDownlinkRule rule("File Down Rule");
rule.apply(tester);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/GroundInterface/test/ut/GroundInterfaceTester.hpp | // ======================================================================
// \title GroundInterface/test/ut/Tester.hpp
// \author mstarch
// \brief hpp file for GroundInterface test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include <Fw/Com/ComPacket.hpp>
#include "GroundInterfaceGTestBase.hpp"
#include "Svc/GroundInterface/GroundInterface.hpp"
namespace Svc {
class GroundInterfaceTester :
public GroundInterfaceGTestBase
{
private:
friend struct RandomizeRule;
friend struct DownlinkRule;
friend struct FileDownlinkRule;
friend struct SendAvailableRule;
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object GroundInterfaceTester
//!
GroundInterfaceTester();
//! Destroy object GroundInterfaceTester
//!
~GroundInterfaceTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void update_header_info();
void setInputParams(TOKEN_TYPE size, U8* buffer, TOKEN_TYPE packet_type = Fw::ComPacket::FW_PACKET_UNKNOWN);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_fileUplinkBufferSendOut
//!
void from_fileUplinkBufferSendOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
//! Handler for from_uplinkPort
//!
void from_uplinkPort_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::ComBuffer &data, /*!< Buffer containing packet data*/
U32 context /*!< Call context value; meaning chosen by user*/
);
//! Handler for from_fileDownlinkBufferSendOut
//!
void from_fileDownlinkBufferSendOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
//! Handler for from_fileUplinkBufferGet
//!
Fw::Buffer from_fileUplinkBufferGet_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 size
);
//! Handler for from_write
//!
void from_write_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
//! Handler for from_readPoll
//!
void from_readPoll_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
GroundInterfaceComponentImpl component;
//! Expected buffer, for checking of the interface
TOKEN_TYPE m_size;
TOKEN_TYPE m_packet;
Fw::Buffer m_incoming_buffer;
Fw::Buffer m_incoming_file_buffer;
U8* m_buffer;
U32 m_uplink_type;
U32 m_uplink_used;
U32 m_uplink_size;
U32 m_uplink_point;
Fw::ComPacket::ComPacketType m_uplink_com_type;
// Initialize to empty list to appease valgrind
U8 m_uplink_data[(sizeof(TOKEN_TYPE) * 3) + FW_COM_BUFFER_MAX_SIZE] = {};
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/GroundInterface/test/ut/GroundInterfaceRules.hpp | /**
* GroundInterfaceRules.hpp:
*
* This file specifies Rule classes for testing of the Svc::GroundInterface. These rules can then be used by the main
* testing program to test the code. These rules support rule-based random testing.
*
* GroundInterface rules:
*
* 1. On read-callback of sufficient parts, an uplink-out is produced
* 2. On schedIn a sufficient number of times, an uplink-out is produced
* 3. On a call to Log, TextLog, downlink, a framed call to write is produced.
*
* @author mstarch
*/
#ifndef FPRIME_SVC_GROUND_INTERFACE_HPP
#define FPRIME_SVC_GROUND_INTERFACE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/String.hpp>
#include "GroundInterfaceTester.hpp"
#include <STest/STest/Rule/Rule.hpp>
#include <STest/STest/Pick/Pick.hpp>
namespace Svc {
/**
* RandomizeRule:
*
* This rule sets up random state
*/
struct RandomizeRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
RandomizeRule(const Fw::String& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
struct DownlinkRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
DownlinkRule(const Fw::String& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
struct FileDownlinkRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
FileDownlinkRule(const Fw::String& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
struct SendAvailableRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
SendAvailableRule(const Fw::String& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
};
#endif //FPRIME_SVC_GROUND_INTERFACE_HPP
| hpp |
fprime | data/projects/fprime/Svc/GroundInterface/test/ut/DeframerRules.hpp | /**
* GroundInterfaceRules.hpp:
*
* This file specifies Rule classes for testing of the Svc::GroundInterface. These rules can then be used by the main
* testing program to test the code. These rules support rule-based random testing.
*
* GroundInterface rules:
*
* 1. On read-callback of sufficient parts, an uplink-out is produced
* 2. On schedIn a sufficient number of times, an uplink-out is produced
* 3. On a call to Log, TextLog, downlink, a framed call to write is produced.
*
* @author mstarch
*/
#ifndef FPRIME_SVC_GROUND_INTERFACE_HPP
#define FPRIME_SVC_GROUND_INTERFACE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/EightyCharString.hpp>
#include "GroundInterfaceTester.hpp"
#include <STest/STest/Rule/Rule.hpp>
#include <STest/STest/Pick/Pick.hpp>
namespace Svc {
/**
* RandomizeRule:
*
* This rule sets up random state
*/
struct RandomizeRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
RandomizeRule(const Fw::EightyCharString& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
struct DownlinkRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
DownlinkRule(const Fw::EightyCharString& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
struct FileDownlinkRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
FileDownlinkRule(const Fw::EightyCharString& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
struct SendAvailableRule : public STest::Rule<GroundInterfaceTester> {
// Constructor
SendAvailableRule(const Fw::EightyCharString& name);
// Always valid
bool precondition(const GroundInterfaceTester& state);
// Will randomize the test state
void action(GroundInterfaceTester& truth);
};
};
#endif //FPRIME_SVC_GROUND_INTERFACE_HPP
| hpp |
fprime | data/projects/fprime/Svc/GroundInterface/test/ut/GroundInterfaceRules.cpp | /**
* GroundInterfaceRules.cpp:
*
* This file specifies Rule classes for testing of the Svc::GroundInterface. These rules can then be used by the main
* testing program to test the code.
*
*
* @author mstarch
*/
#include "GroundInterfaceRules.hpp"
#include <STest/Pick/Pick.hpp>
namespace Svc {
// Constructor
RandomizeRule :: RandomizeRule(const Fw::String& name) : STest::Rule<GroundInterfaceTester>(name.toChar()) {}
// Can always randomize
bool RandomizeRule :: precondition(const Svc::GroundInterfaceTester &state) {
return true;
}
// Randomize
void RandomizeRule :: action(Svc::GroundInterfaceTester &state) {
state.m_uplink_type = STest::Pick::lowerUpper(0, 1);
state.m_uplink_size = STest::Pick::lowerUpper(0, sizeof(state.m_uplink_data) - 1);
// Reset or not sent allows randomization
if (state.m_uplink_type == 2 || state.m_uplink_point == 0) {
state.m_uplink_type = STest::Pick::lowerUpper(0, 1);
state.m_uplink_used = STest::Pick::lowerUpper(4, FW_COM_BUFFER_MAX_SIZE);
state.m_uplink_com_type = static_cast<Fw::ComPacket::ComPacketType>(
STest::Pick::lowerUpper(Fw::ComPacket::FW_PACKET_COMMAND,Fw::ComPacket::FW_PACKET_FILE));
for (U32 i = 0; i < state.m_uplink_used; i++) {
state.m_uplink_data[(sizeof(TOKEN_TYPE) * 2) + i] =
static_cast<U8>(STest::Pick::lowerUpper(0, 255));
}
}
// Correct header info for items
state.update_header_info();
}
// Constructor
DownlinkRule :: DownlinkRule(const Fw::String& name) : STest::Rule<GroundInterfaceTester>(name.toChar()) {}
// Can always downlink
bool DownlinkRule :: precondition(const Svc::GroundInterfaceTester &state) {
return true;
}
// Pick a rule and downlink
void DownlinkRule :: action(Svc::GroundInterfaceTester &state) {
Fw::ComBuffer buffer;
// Force a U32 to know the size
buffer.serialize(static_cast<U32>(0xdeadbeef));
state.setInputParams(sizeof(U32), buffer.getBuffAddr());
state.invoke_to_downlinkPort(0, buffer, 0);
state.assert_from_write_size(__FILE__, __LINE__, 1);
state.clearFromPortHistory();
}
// Constructor
FileDownlinkRule :: FileDownlinkRule(const Fw::String& name) : STest::Rule<GroundInterfaceTester>(name.toChar()) {}
// Can always downlink
bool FileDownlinkRule :: precondition(const Svc::GroundInterfaceTester &state) {
return true;
}
// Pick a rule and downlink
void FileDownlinkRule :: action(Svc::GroundInterfaceTester &state) {
U8 data_holder[2048];
Fw::Buffer buffer(data_holder, sizeof(data_holder));
Fw::ExternalSerializeBuffer buffer_wrapper(buffer.getData(), buffer.getSize());
// Force a U32 to know the size
buffer_wrapper.serialize(static_cast<U32>(0xdeadbeef));
buffer.setSize(buffer_wrapper.getBuffLength());
state.setInputParams(sizeof(U32) + sizeof(TOKEN_TYPE), buffer.getData(),
Fw::ComPacket::FW_PACKET_FILE);
state.invoke_to_fileDownlinkBufferSendIn(0, buffer);
state.assert_from_write_size(__FILE__, __LINE__, 1);
state.assert_from_fileDownlinkBufferSendOut_size(__FILE__, __LINE__, 1);
state.clearFromPortHistory();
}
// Constructor
SendAvailableRule :: SendAvailableRule(const Fw::String& name) : STest::Rule<GroundInterfaceTester>(name.toChar()) {}
// Can always downlink
bool SendAvailableRule :: precondition(const Svc::GroundInterfaceTester &state) {
return true;
}
// Pick a rule and downlink
void SendAvailableRule :: action(Svc::GroundInterfaceTester &state) {
U32 total_used = state.m_uplink_used + HEADER_SIZE + sizeof(U32);
U8* up_ptr = state.m_uplink_data + state.m_uplink_point;
U32 size = ((state.m_uplink_point + state.m_uplink_size) >= total_used) ?
(total_used - state.m_uplink_point) : state.m_uplink_size;
state.m_uplink_point = (state.m_uplink_point + size >= total_used) ? 0 : (state.m_uplink_point + size);
Fw::Buffer buffer(up_ptr, size);
// Uplink based on uplink type
if (state.m_uplink_type) {
state.invoke_to_readCallback(0,buffer);
} else {
state.m_incoming_buffer = buffer;
state.invoke_to_schedIn(0, 0);
}
// Finished current uplink, check that the uplink was handled
if (state.m_uplink_point == 0 && size > 0) {
// Check uplink type
if (state.m_uplink_com_type == Fw::ComPacket::FW_PACKET_COMMAND) {
state.assert_from_uplinkPort_size(__FILE__, __LINE__, 1);
} else if (state.m_uplink_com_type == Fw::ComPacket::FW_PACKET_FILE) {
state.assert_from_fileUplinkBufferSendOut_size(__FILE__, __LINE__, 1);
}
state.clearFromPortHistory();
} else {
state.assert_from_uplinkPort_size(__FILE__, __LINE__, 0);
}
}
};
| cpp |
fprime | data/projects/fprime/Svc/GroundInterface/test/ut/GroundInterfaceTester.cpp | // ======================================================================
// \title GroundInterface.hpp
// \author mstarch
// \brief cpp file for GroundInterface test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "GroundInterfaceTester.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
U8 file_back_buffer[10240];
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
GroundInterfaceTester ::
GroundInterfaceTester() :
GroundInterfaceGTestBase("Tester", MAX_HISTORY_SIZE),
component("GroundInterface")
,
m_buffer(nullptr),
m_uplink_type(1),
m_uplink_used(30),
m_uplink_size(sizeof(TOKEN_TYPE) * 3 + m_uplink_used),
m_uplink_point(0),
m_uplink_com_type(Fw::ComPacket::FW_PACKET_COMMAND)
{
this->initComponents();
this->connectPorts();
update_header_info();
}
GroundInterfaceTester ::
~GroundInterfaceTester()
{
}
// ----------------------------------------------------------------------
// Tests State Adjustments
// ----------------------------------------------------------------------
void GroundInterfaceTester :: update_header_info() {
// Write token types
for (U32 i = 0; i < sizeof(TOKEN_TYPE); i++) {
m_uplink_data[i] = (GroundInterfaceComponentImpl::START_WORD >> ((sizeof(TOKEN_TYPE) - 1 - i) * 8)) & 0xFF;
m_uplink_data[i + sizeof(TOKEN_TYPE)] =
(m_uplink_used >> ((sizeof(TOKEN_TYPE) - 1 - i) * 8)) & 0xFF;
m_uplink_data[i + 2 * sizeof(TOKEN_TYPE) + m_uplink_used] =
(GroundInterfaceComponentImpl::END_WORD >> ((sizeof(TOKEN_TYPE) - 1 - i) * 8)) & 0xFF;
}
// Packet type
m_uplink_data[2 * sizeof(TOKEN_TYPE) + 0] = (static_cast<U32>(m_uplink_com_type) >> 24) & 0xFF;
m_uplink_data[2 * sizeof(TOKEN_TYPE) + 1] = (static_cast<U32>(m_uplink_com_type) >> 16) & 0xFF;
m_uplink_data[2 * sizeof(TOKEN_TYPE) + 2] = (static_cast<U32>(m_uplink_com_type) >> 8) & 0xFF;
m_uplink_data[2 * sizeof(TOKEN_TYPE) + 3] = (static_cast<U32>(m_uplink_com_type) >> 0) & 0xFF;
}
void GroundInterfaceTester :: setInputParams(TOKEN_TYPE size, U8* buffer, TOKEN_TYPE packet_type) {
m_size = size;
m_buffer = buffer;
m_packet = packet_type;
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void GroundInterfaceTester ::
from_fileUplinkBufferSendOut_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_fileUplinkBufferSendOut(fwBuffer);
for (U32 i = 0; i < fwBuffer.getSize(); i++) {
// File uplink strips type before outputting to FileUplink
ASSERT_EQ(fwBuffer.getData()[i], m_uplink_data[i + HEADER_SIZE + sizeof(TOKEN_TYPE)]);
}
}
void GroundInterfaceTester ::
from_uplinkPort_handler(
const NATIVE_INT_TYPE portNum,
Fw::ComBuffer &data,
U32 context
)
{
this->pushFromPortEntry_uplinkPort(data, context);
for (U32 i = 0; i < data.getBuffLength(); i++) {
ASSERT_EQ(data.getBuffAddr()[i], m_uplink_data[i + HEADER_SIZE]);
}
}
void GroundInterfaceTester ::
from_fileDownlinkBufferSendOut_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_fileDownlinkBufferSendOut(fwBuffer);
}
Fw::Buffer GroundInterfaceTester ::
from_fileUplinkBufferGet_handler(
const NATIVE_INT_TYPE portNum,
U32 size
)
{
this->pushFromPortEntry_fileUplinkBufferGet(size);
m_incoming_file_buffer.setData(file_back_buffer);
m_incoming_file_buffer.setSize(size);
return m_incoming_file_buffer;
}
void GroundInterfaceTester ::
from_write_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_write(fwBuffer);
// All writes can be processed here
TOKEN_TYPE start = 0;
TOKEN_TYPE size = 0;
TOKEN_TYPE packet = 0;
U32 end = 0;
Fw::ExternalSerializeBuffer buffer_wrapper(fwBuffer.getData(), fwBuffer.getSize());
buffer_wrapper.setBuffLen(fwBuffer.getSize());
// Check basic deserialization
ASSERT_EQ(buffer_wrapper.deserialize(start), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(buffer_wrapper.deserialize(size), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(start, GroundInterfaceComponentImpl::START_WORD);
ASSERT_EQ(size, m_size);
// Deserialize the packet type, if know. This handles the different paths for FilePackets and homogenized packets
if (m_packet != Fw::ComPacket::FW_PACKET_UNKNOWN) {
ASSERT_EQ(buffer_wrapper.deserialize(packet), Fw::FW_SERIALIZE_OK);
// For now, only FilePackets take this path
ASSERT_EQ(packet, Fw::ComPacket::FW_PACKET_FILE);
m_size -= sizeof(packet);
}
// Note: no checking for symmetric errors, as we are depending on ExternalSerializeBuffer's correctness here
for (U32 i = 0; i < m_size; i++) {
U8 byte_data;
ASSERT_EQ(buffer_wrapper.deserialize(byte_data), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(byte_data, m_buffer[i]);
}
// Look at end work
ASSERT_EQ(buffer_wrapper.deserialize(end), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(end, GroundInterfaceComponentImpl::END_WORD);
ASSERT_from_write_SIZE(1);
}
void GroundInterfaceTester ::
from_readPoll_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_readPoll(fwBuffer);
U8* incoming = m_incoming_buffer.getData();
U8* outgoing = fwBuffer.getData();
for (U32 i = 0; i < m_incoming_buffer.getSize(); i++) {
outgoing[i] = incoming[i];
}
fwBuffer.setSize(m_incoming_buffer.getSize());
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void GroundInterfaceTester ::
connectPorts()
{
// downlinkPort
this->connect_to_downlinkPort(
0,
this->component.get_downlinkPort_InputPort(0)
);
// fileDownlinkBufferSendIn
this->connect_to_fileDownlinkBufferSendIn(
0,
this->component.get_fileDownlinkBufferSendIn_InputPort(0)
);
// readCallback
this->connect_to_readCallback(
0,
this->component.get_readCallback_InputPort(0)
);
// schedIn
this->connect_to_schedIn(
0,
this->component.get_schedIn_InputPort(0)
);
// fileUplinkBufferSendOut
this->component.set_fileUplinkBufferSendOut_OutputPort(
0,
this->get_from_fileUplinkBufferSendOut(0)
);
// Log
this->component.set_Log_OutputPort(
0,
this->get_from_Log(0)
);
// LogText
this->component.set_LogText_OutputPort(
0,
this->get_from_LogText(0)
);
// Time
this->component.set_Time_OutputPort(
0,
this->get_from_Time(0)
);
// uplinkPort
this->component.set_uplinkPort_OutputPort(
0,
this->get_from_uplinkPort(0)
);
// fileDownlinkBufferSendOut
this->component.set_fileDownlinkBufferSendOut_OutputPort(
0,
this->get_from_fileDownlinkBufferSendOut(0)
);
// fileUplinkBufferGet
this->component.set_fileUplinkBufferGet_OutputPort(
0,
this->get_from_fileUplinkBufferGet(0)
);
// write
this->component.set_write_OutputPort(
0,
this->get_from_write(0)
);
// readPoll
this->component.set_readPoll_OutputPort(
0,
this->get_from_readPoll(0)
);
}
void GroundInterfaceTester ::
initComponents()
{
this->init();
this->component.init(
INSTANCE
);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/ActiveLogger/ActiveLoggerImpl.hpp | /*
* ActiveLoggerImpl.hpp
*
* Created on: Mar 28, 2014
* Author: tcanham
*/
#ifndef ACTIVELOGGERIMPL_HPP_
#define ACTIVELOGGERIMPL_HPP_
#include <Svc/ActiveLogger/ActiveLoggerComponentAc.hpp>
#include <Fw/Log/LogPacket.hpp>
#include <ActiveLoggerImplCfg.hpp>
namespace Svc {
class ActiveLoggerImpl: public ActiveLoggerComponentBase {
public:
ActiveLoggerImpl(const char* compName); //!< constructor
virtual ~ActiveLoggerImpl(); //!< destructor
void init(
NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
NATIVE_INT_TYPE instance /*!< The instance number*/
); //!< initialization function
PROTECTED:
PRIVATE:
void LogRecv_handler(NATIVE_INT_TYPE portNum, FwEventIdType id, Fw::Time &timeTag, const Fw::LogSeverity& severity, Fw::LogBuffer &args);
void loqQueue_internalInterfaceHandler(FwEventIdType id, const Fw::Time &timeTag, const Fw::LogSeverity& severity, const Fw::LogBuffer &args);
void SET_EVENT_FILTER_cmdHandler(
FwOpcodeType opCode,
U32 cmdSeq,
ActiveLogger_FilterSeverity filterLevel,
ActiveLogger_Enabled filterEnabled);
void SET_ID_FILTER_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 ID,
ActiveLogger_Enabled idFilterEnabled //!< ID filter state
);
void DUMP_FILTER_STATE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
);
//! Handler implementation for pingIn
//!
void pingIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
// Filter state
struct t_filterState {
ActiveLogger_Enabled enabled; //<! filter is enabled
} m_filterState[ActiveLogger_FilterSeverity::NUM_CONSTANTS];
// Working members
Fw::LogPacket m_logPacket; //!< packet buffer for assembling log packets
Fw::ComBuffer m_comBuffer; //!< com buffer for sending event buffers
// array of filtered event IDs.
// value of 0 means no entry
FwEventIdType m_filteredIDs[TELEM_ID_FILTER_SIZE];
};
}
#endif /* ACTIVELOGGERIMPL_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/ActiveLogger/ActiveLogger.hpp | // ======================================================================
// ActiveLogger.hpp
// Standardization header for ActiveLogger
// ======================================================================
#ifndef Svc_ActiveLogger_HPP
#define Svc_ActiveLogger_HPP
#include "Svc/ActiveLogger/ActiveLoggerImpl.hpp"
namespace Svc {
typedef ActiveLoggerImpl ActiveLogger;
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/ActiveLogger/ActiveLoggerImpl.cpp | /*
* TestCommand1Impl.cpp
*
* Created on: Mar 28, 2014
* Author: tcanham
*/
#include <cstdio>
#include <Svc/ActiveLogger/ActiveLoggerImpl.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/File.hpp>
namespace Svc {
typedef ActiveLogger_Enabled Enabled;
typedef ActiveLogger_FilterSeverity FilterSeverity;
ActiveLoggerImpl::ActiveLoggerImpl(const char* name) :
ActiveLoggerComponentBase(name)
{
// set filter defaults
this->m_filterState[FilterSeverity::WARNING_HI].enabled =
FILTER_WARNING_HI_DEFAULT?Enabled::ENABLED:Enabled::DISABLED;
this->m_filterState[FilterSeverity::WARNING_LO].enabled =
FILTER_WARNING_LO_DEFAULT?Enabled::ENABLED:Enabled::DISABLED;
this->m_filterState[FilterSeverity::COMMAND].enabled =
FILTER_COMMAND_DEFAULT?Enabled::ENABLED:Enabled::DISABLED;
this->m_filterState[FilterSeverity::ACTIVITY_HI].enabled =
FILTER_ACTIVITY_HI_DEFAULT?Enabled::ENABLED:Enabled::DISABLED;
this->m_filterState[FilterSeverity::ACTIVITY_LO].enabled =
FILTER_ACTIVITY_LO_DEFAULT?Enabled::ENABLED:Enabled::DISABLED;
this->m_filterState[FilterSeverity::DIAGNOSTIC].enabled =
FILTER_DIAGNOSTIC_DEFAULT?Enabled::ENABLED:Enabled::DISABLED;
memset(m_filteredIDs,0,sizeof(m_filteredIDs));
}
ActiveLoggerImpl::~ActiveLoggerImpl() {
}
void ActiveLoggerImpl::init(
NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
NATIVE_INT_TYPE instance /*!< The instance number*/
) {
ActiveLoggerComponentBase::init(queueDepth,instance);
}
void ActiveLoggerImpl::LogRecv_handler(NATIVE_INT_TYPE portNum, FwEventIdType id, Fw::Time &timeTag, const Fw::LogSeverity& severity, Fw::LogBuffer &args) {
// make sure ID is not zero. Zero is reserved for ID filter.
FW_ASSERT(id != 0);
switch (severity.e) {
case Fw::LogSeverity::FATAL: // always pass FATAL
break;
case Fw::LogSeverity::WARNING_HI:
if (this->m_filterState[FilterSeverity::WARNING_HI].enabled == Enabled::DISABLED) {
return;
}
break;
case Fw::LogSeverity::WARNING_LO:
if (this->m_filterState[FilterSeverity::WARNING_LO].enabled == Enabled::DISABLED) {
return;
}
break;
case Fw::LogSeverity::COMMAND:
if (this->m_filterState[FilterSeverity::COMMAND].enabled == Enabled::DISABLED) {
return;
}
break;
case Fw::LogSeverity::ACTIVITY_HI:
if (this->m_filterState[FilterSeverity::ACTIVITY_HI].enabled == Enabled::DISABLED) {
return;
}
break;
case Fw::LogSeverity::ACTIVITY_LO:
if (this->m_filterState[FilterSeverity::ACTIVITY_LO].enabled == Enabled::DISABLED) {
return;
}
break;
case Fw::LogSeverity::DIAGNOSTIC:
if (this->m_filterState[FilterSeverity::DIAGNOSTIC].enabled == Enabled::DISABLED) {
return;
}
break;
default:
FW_ASSERT(0,static_cast<NATIVE_INT_TYPE>(severity.e));
return;
}
// check ID filters
for (NATIVE_INT_TYPE entry = 0; entry < TELEM_ID_FILTER_SIZE; entry++) {
if (
(m_filteredIDs[entry] == id) &&
(severity != Fw::LogSeverity::FATAL)
) {
return;
}
}
// send event to the logger thread
this->loqQueue_internalInterfaceInvoke(id,timeTag,severity,args);
// if connected, announce the FATAL
if (Fw::LogSeverity::FATAL == severity.e) {
if (this->isConnected_FatalAnnounce_OutputPort(0)) {
this->FatalAnnounce_out(0,id);
}
}
}
void ActiveLoggerImpl::loqQueue_internalInterfaceHandler(FwEventIdType id, const Fw::Time &timeTag, const Fw::LogSeverity& severity, const Fw::LogBuffer &args) {
// Serialize event
this->m_logPacket.setId(id);
this->m_logPacket.setTimeTag(timeTag);
this->m_logPacket.setLogBuffer(args);
this->m_comBuffer.resetSer();
Fw::SerializeStatus stat = this->m_logPacket.serialize(this->m_comBuffer);
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
if (this->isConnected_PktSend_OutputPort(0)) {
this->PktSend_out(0, this->m_comBuffer,0);
}
}
void ActiveLoggerImpl::SET_EVENT_FILTER_cmdHandler(FwOpcodeType opCode, U32 cmdSeq, FilterSeverity filterLevel, Enabled filterEnable) {
this->m_filterState[filterLevel.e].enabled = filterEnable;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveLoggerImpl::SET_ID_FILTER_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 ID,
Enabled idEnabled //!< ID filter state
) {
if (Enabled::ENABLED == idEnabled.e) { // add ID
// search list for existing entry
for (NATIVE_INT_TYPE entry = 0; entry < TELEM_ID_FILTER_SIZE; entry++) {
if (this->m_filteredIDs[entry] == ID) {
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
this->log_ACTIVITY_HI_ID_FILTER_ENABLED(ID);
return;
}
}
// if not already a match, search for an open slot
for (NATIVE_INT_TYPE entry = 0; entry < TELEM_ID_FILTER_SIZE; entry++) {
if (this->m_filteredIDs[entry] == 0) {
this->m_filteredIDs[entry] = ID;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
this->log_ACTIVITY_HI_ID_FILTER_ENABLED(ID);
return;
}
}
// if an empty slot was not found, send an error event
this->log_WARNING_LO_ID_FILTER_LIST_FULL(ID);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
} else { // remove ID
// search list for existing entry
for (NATIVE_INT_TYPE entry = 0; entry < TELEM_ID_FILTER_SIZE; entry++) {
if (this->m_filteredIDs[entry] == ID) {
this->m_filteredIDs[entry] = 0; // zero entry
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
this->log_ACTIVITY_HI_ID_FILTER_REMOVED(ID);
return;
}
}
// if it gets here, wasn't found
this->log_WARNING_LO_ID_FILTER_NOT_FOUND(ID);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
}
}
void ActiveLoggerImpl::DUMP_FILTER_STATE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
) {
// first, iterate through severity filters
for (NATIVE_UINT_TYPE filter = 0; filter < FilterSeverity::NUM_CONSTANTS; filter++) {
FilterSeverity filterState(static_cast<FilterSeverity::t>(filter));
this->log_ACTIVITY_LO_SEVERITY_FILTER_STATE(
filterState,
Enabled::ENABLED == this->m_filterState[filter].enabled.e
);
}
// iterate through ID filter
for (NATIVE_INT_TYPE entry = 0; entry < TELEM_ID_FILTER_SIZE; entry++) {
if (this->m_filteredIDs[entry] != 0) {
this->log_ACTIVITY_HI_ID_FILTER_ENABLED(this->m_filteredIDs[entry]);
}
}
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveLoggerImpl::pingIn_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
// return key
this->pingOut_out(0,key);
}
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/ActiveLogger/test/ut/ActiveLoggerTester.cpp | /*
* PrmDbTester.cpp
*
* Created on: Mar 18, 2015
* Author: tcanham
*/
#include <Svc/ActiveLogger/test/ut/ActiveLoggerImplTester.hpp>
#include <Svc/ActiveLogger/ActiveLoggerImpl.hpp>
#include <Fw/Obj/SimpleObjRegistry.hpp>
#include <Fw/Test/UnitTest.hpp>
#include <gtest/gtest.h>
#if FW_OBJECT_REGISTRATION == 1
static Fw::SimpleObjRegistry simpleReg;
#endif
void connectPorts(Svc::ActiveLoggerImpl& impl, Svc::ActiveLoggerImplTester& tester) {
tester.connect_to_CmdDisp(0,impl.get_CmdDisp_InputPort(0));
impl.set_CmdStatus_OutputPort(0,tester.get_from_CmdStatus(0));
impl.set_FatalAnnounce_OutputPort(0,tester.get_from_FatalAnnounce(0));
tester.connect_to_LogRecv(0,impl.get_LogRecv_InputPort(0));
impl.set_Log_OutputPort(0,tester.get_from_Log(0));
impl.set_LogText_OutputPort(0,tester.get_from_LogText(0));
impl.set_PktSend_OutputPort(0,tester.get_from_PktSend(0));
#if FW_PORT_TRACING
// Fw::PortBase::setTrace(true);
#endif
// simpleReg.dump();
}
TEST(ActiveLoggerTest,NominalEventSend) {
TEST_CASE(100.1.1,"Nominal Event Logging");
Svc::ActiveLoggerImpl impl("ActiveLoggerImpl");
impl.init(10,0);
Svc::ActiveLoggerImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
tester.runEventNominal();
}
TEST(ActiveLoggerTest,FilteredEventSend) {
TEST_CASE(100.1.2,"Nominal Event Filtering");
Svc::ActiveLoggerImpl impl("ActiveLoggerImpl");
impl.init(10,0);
Svc::ActiveLoggerImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
tester.runFilterEventNominal();
}
TEST(ActiveLoggerTest,FilterIdTest) {
TEST_CASE(100.1.3,"Filter events by ID");
Svc::ActiveLoggerImpl impl("ActiveLoggerImpl");
impl.init(10,0);
Svc::ActiveLoggerImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
tester.runFilterIdNominal();
}
TEST(ActiveLoggerTest,FilterDumpTest) {
TEST_CASE(100.1.3,"Dump filter values");
Svc::ActiveLoggerImpl impl("ActiveLoggerImpl");
impl.init(10,0);
Svc::ActiveLoggerImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
tester.runFilterDump();
}
TEST(ActiveLoggerTest,InvalidCommands) {
TEST_CASE(100.2.1,"Off-Nominal Invalid Commands");
Svc::ActiveLoggerImpl impl("ActiveLoggerImpl");
impl.init(10,0);
Svc::ActiveLoggerImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
tester.runFilterInvalidCommands();
}
TEST(ActiveLoggerTest,FatalTesting) {
TEST_CASE(100.2.2,"Off-Nominal FATAL processing");
Svc::ActiveLoggerImpl impl("ActiveLoggerImpl");
impl.init(10,0);
Svc::ActiveLoggerImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
tester.runEventFatal();
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/ActiveLogger/test/ut/ActiveLoggerImplTester.cpp | /*
* ActiveLoggerImplTester.cpp
*
* Created on: Mar 18, 2015
* Author: tcanham
*/
#include <Svc/ActiveLogger/test/ut/ActiveLoggerImplTester.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Fw/Com/ComPacket.hpp>
#include <Os/IntervalTimer.hpp>
#include <gtest/gtest.h>
#include <Fw/Test/UnitTest.hpp>
#include <cstdio>
namespace Svc {
typedef ActiveLogger_Enabled Enabled;
typedef ActiveLogger_FilterSeverity FilterSeverity;
void ActiveLoggerImplTester::init(NATIVE_INT_TYPE instance) {
Svc::ActiveLoggerGTestBase::init();
}
ActiveLoggerImplTester::ActiveLoggerImplTester(Svc::ActiveLoggerImpl& inst) :
Svc::ActiveLoggerGTestBase("testerbase",100),
m_impl(inst),
m_receivedPacket(false),
m_receivedFatalEvent(false) {
}
ActiveLoggerImplTester::~ActiveLoggerImplTester() {
}
void ActiveLoggerImplTester::from_PktSend_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::ComBuffer &data, //!< Buffer containing packet data
U32 context //!< context; not used
) {
this->m_sentPacket = data;
this->m_receivedPacket = true;
}
void ActiveLoggerImplTester::from_FatalAnnounce_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
FwEventIdType Id //!< The ID of the FATAL event
) {
this->m_receivedFatalEvent = true;
this->m_fatalID = Id;
}
void ActiveLoggerImplTester::runEventNominal() {
REQUIREMENT("AL-001");
this->writeEvent(29,Fw::LogSeverity::WARNING_HI,10);
}
void ActiveLoggerImplTester::runWithFilters(Fw::LogSeverity filter) {
REQUIREMENT("AL-002");
Fw::LogBuffer buff;
U32 val = 10;
FwEventIdType id = 29;
Fw::SerializeStatus stat = buff.serialize(val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
Fw::Time timeTag(TB_NONE,0,0);
U32 cmdSeq = 21;
// enable report filter
this->clearHistory();
FilterSeverity reportFilterLevel = FilterSeverity::WARNING_HI;
switch (filter.e) {
case Fw::LogSeverity::WARNING_HI:
reportFilterLevel = FilterSeverity::WARNING_HI;
break;
case Fw::LogSeverity::WARNING_LO:
reportFilterLevel = FilterSeverity::WARNING_LO;
break;
case Fw::LogSeverity::COMMAND:
reportFilterLevel = FilterSeverity::COMMAND;
break;
case Fw::LogSeverity::ACTIVITY_HI:
reportFilterLevel = FilterSeverity::ACTIVITY_HI;
break;
case Fw::LogSeverity::ACTIVITY_LO:
reportFilterLevel = FilterSeverity::ACTIVITY_LO;
break;
case Fw::LogSeverity::DIAGNOSTIC:
reportFilterLevel = FilterSeverity::DIAGNOSTIC;
break;
default:
ASSERT_TRUE(false);
break;
}
this->clearHistory();
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,reportFilterLevel,Enabled::ENABLED);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::OK
);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,filter,buff);
// should not have received packet
ASSERT_FALSE(this->m_receivedPacket);
// dispatch message
this->m_impl.doDispatch();
// should have received packet
ASSERT_TRUE(this->m_receivedPacket);
// verify contents
// first piece should be log packet descriptor
FwPacketDescriptorType desc;
stat = this->m_sentPacket.deserialize(desc);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(desc,static_cast<FwPacketDescriptorType>(Fw::ComPacket::FW_PACKET_LOG));
// next piece should be event ID
FwEventIdType sentId;
stat = this->m_sentPacket.deserialize(sentId);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(sentId,id);
// next piece is time tag
Fw::Time recTimeTag(TB_NONE,0,0);
stat = this->m_sentPacket.deserialize(recTimeTag);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_TRUE(timeTag == recTimeTag);
// next piece is event argument
U32 readVal;
stat = this->m_sentPacket.deserialize(readVal);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(readVal, val);
// packet should be empty
ASSERT_EQ(this->m_sentPacket.getBuffLeft(),0u);
// Disable severity filter
this->clearHistory();
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,reportFilterLevel,Enabled::DISABLED);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::OK
);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,filter,buff);
// should not have received packet - all we can check since no message is dispatched.
ASSERT_FALSE(this->m_receivedPacket);
}
void ActiveLoggerImplTester::runFilterInvalidCommands() {
U32 cmdSeq = 21;
this->clearHistory();
FilterSeverity reportFilterLevel = FilterSeverity::WARNING_HI;
Enabled filterEnabled(static_cast<Enabled::t>(10));
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,reportFilterLevel,filterEnabled);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::FORMAT_ERROR
);
this->clearHistory();
reportFilterLevel = FilterSeverity::WARNING_HI;
filterEnabled.e = static_cast<Enabled::t>(-2);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,reportFilterLevel,filterEnabled);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::FORMAT_ERROR
);
FilterSeverity eventLevel;
this->clearHistory();
Enabled reportEnable = Enabled::ENABLED;
eventLevel.e = static_cast<FilterSeverity::t>(-1);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,eventLevel,reportEnable);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::FORMAT_ERROR
);
this->clearHistory();
reportEnable = Enabled::ENABLED;
eventLevel.e = static_cast<FilterSeverity::t>(100);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,eventLevel,reportEnable);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::FORMAT_ERROR
);
}
void ActiveLoggerImplTester::runFilterEventNominal() {
for (Fw::LogSeverity::t sev = Fw::LogSeverity::WARNING_HI; sev <= Fw::LogSeverity::DIAGNOSTIC; sev = static_cast<Fw::LogSeverity::t>(sev + 1)) {
this->runWithFilters(sev);
}
}
void ActiveLoggerImplTester::runFilterIdNominal() {
U32 cmdSeq = 21;
// for a set of IDs, fill filter
REQUIREMENT("AL-003");
for (NATIVE_INT_TYPE filterID = 1; filterID <= TELEM_ID_FILTER_SIZE; filterID++) {
this->clearHistory();
this->clearEvents();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,filterID,Enabled::ENABLED);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_ID_FILTER,
cmdSeq,
Fw::CmdResponse::OK
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_ID_FILTER_ENABLED_SIZE(1);
ASSERT_EVENTS_ID_FILTER_ENABLED(0,filterID);
// send it again, to verify it will accept a second add
this->clearHistory();
this->clearEvents();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,filterID,Enabled::ENABLED);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_ID_FILTER,
cmdSeq,
Fw::CmdResponse::OK
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_ID_FILTER_ENABLED_SIZE(1);
ASSERT_EVENTS_ID_FILTER_ENABLED(0,filterID);
}
// Try to send the IDs that are filtered
for (NATIVE_INT_TYPE filterID = 1; filterID <= TELEM_ID_FILTER_SIZE; filterID++) {
this->clearHistory();
this->clearEvents();
Fw::LogBuffer buff;
U32 val = 10;
FwEventIdType id = filterID;
Fw::SerializeStatus stat = buff.serialize(val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
Fw::Time timeTag(TB_NONE,0,0);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,Fw::LogSeverity::ACTIVITY_HI,buff);
// should not get a packet
ASSERT_FALSE(this->m_receivedPacket);
}
// send one of the IDs as a FATAL, it should not be filtered event thought the ID is in the filter
this->clearHistory();
this->clearEvents();
Fw::LogBuffer buff;
U32 val = 10;
FwEventIdType id = 1;
Fw::SerializeStatus stat = buff.serialize(val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
Fw::Time timeTag(TB_NONE,0,0);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,Fw::LogSeverity::FATAL,buff);
this->m_impl.doDispatch();
// should get a packet anyway
ASSERT_TRUE(this->m_receivedPacket);
// Try to add to the full filter. It should be rejected
this->clearHistory();
this->clearEvents();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,TELEM_ID_FILTER_SIZE+1,Enabled::ENABLED);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_ID_FILTER,
cmdSeq,
Fw::CmdResponse::EXECUTION_ERROR
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_ID_FILTER_LIST_FULL_SIZE(1);
ASSERT_EVENTS_ID_FILTER_LIST_FULL(0,TELEM_ID_FILTER_SIZE+1);
// Now clear them
for (NATIVE_INT_TYPE filterID = 1; filterID <= TELEM_ID_FILTER_SIZE; filterID++) {
this->clearHistory();
this->clearEvents();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,filterID,Enabled::DISABLED);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_ID_FILTER,
cmdSeq,
Fw::CmdResponse::OK
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_ID_FILTER_REMOVED_SIZE(1);
ASSERT_EVENTS_ID_FILTER_REMOVED(0,filterID);
}
// Try to clear one that doesn't exist
this->clearHistory();
this->clearEvents();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,10,Enabled::DISABLED);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_ID_FILTER,
cmdSeq,
Fw::CmdResponse::EXECUTION_ERROR
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_ID_FILTER_NOT_FOUND_SIZE(1);
ASSERT_EVENTS_ID_FILTER_NOT_FOUND(0,10);
// Send an invalid argument
this->clearHistory();
this->clearEvents();
Enabled idEnabled(static_cast<Enabled::t>(10));
this->sendCmd_SET_ID_FILTER(0,cmdSeq,10,idEnabled);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_ID_FILTER,
cmdSeq,
Fw::CmdResponse::FORMAT_ERROR
);
ASSERT_EVENTS_SIZE(0);
}
void ActiveLoggerImplTester::runFilterDump() {
U32 cmdSeq = 21;
// set random set of filters
this->sendCmd_SET_EVENT_FILTER(0,0,FilterSeverity::WARNING_HI,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,0,FilterSeverity::WARNING_LO,Enabled::DISABLED);
this->sendCmd_SET_EVENT_FILTER(0,0,FilterSeverity::COMMAND,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,0,FilterSeverity::ACTIVITY_HI,Enabled::DISABLED);
this->sendCmd_SET_EVENT_FILTER(0,0,FilterSeverity::ACTIVITY_LO,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,0,FilterSeverity::DIAGNOSTIC,Enabled::ENABLED);
this->sendCmd_SET_ID_FILTER(0,cmdSeq,4,Enabled::ENABLED);
// dispatch message
this->m_impl.doDispatch();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,13,Enabled::ENABLED);
// dispatch message
this->m_impl.doDispatch();
this->sendCmd_SET_ID_FILTER(0,cmdSeq,4000,Enabled::ENABLED);
// dispatch message
this->m_impl.doDispatch();
// send command to dump the filters
this->clearHistory();
this->clearEvents();
this->sendCmd_DUMP_FILTER_STATE(0,cmdSeq);
// dispatch message
this->m_impl.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_DUMP_FILTER_STATE,
cmdSeq,
Fw::CmdResponse::OK
);
ASSERT_EVENTS_SIZE(6+3);
ASSERT_EVENTS_SEVERITY_FILTER_STATE_SIZE(6);
ASSERT_EVENTS_SEVERITY_FILTER_STATE(0,FilterSeverity::WARNING_HI,true);
ASSERT_EVENTS_SEVERITY_FILTER_STATE(1,FilterSeverity::WARNING_LO,false);
ASSERT_EVENTS_SEVERITY_FILTER_STATE(2,FilterSeverity::COMMAND,true);
ASSERT_EVENTS_SEVERITY_FILTER_STATE(3,FilterSeverity::ACTIVITY_HI,false);
ASSERT_EVENTS_SEVERITY_FILTER_STATE(4,FilterSeverity::ACTIVITY_LO,true);
ASSERT_EVENTS_SEVERITY_FILTER_STATE(5,FilterSeverity::DIAGNOSTIC,true);
}
void ActiveLoggerImplTester::runEventFatal() {
Fw::LogBuffer buff;
U32 val = 10;
FwEventIdType id = 29;
U32 cmdSeq = 21;
REQUIREMENT("AL-004");
Fw::SerializeStatus stat = buff.serialize(val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
Fw::Time timeTag(TB_NONE,0,0);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,Fw::LogSeverity::FATAL,buff);
// should not have received packet
ASSERT_FALSE(this->m_receivedPacket);
// should have seen event port
ASSERT_TRUE(this->m_receivedFatalEvent);
ASSERT_EQ(this->m_fatalID,id);
// dispatch message
this->m_impl.doDispatch();
// should have received packet
ASSERT_TRUE(this->m_receivedPacket);
// verify contents
// first piece should be log packet descriptor
FwPacketDescriptorType desc;
stat = this->m_sentPacket.deserialize(desc);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(desc,static_cast<FwPacketDescriptorType>(Fw::ComPacket::FW_PACKET_LOG));
// next piece should be event ID
FwEventIdType sentId;
stat = this->m_sentPacket.deserialize(sentId);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(sentId,id);
// next piece is time tag
Fw::Time recTimeTag(TB_NONE,0,0);
stat = this->m_sentPacket.deserialize(recTimeTag);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_TRUE(timeTag == recTimeTag);
// next piece is event argument
U32 readVal;
stat = this->m_sentPacket.deserialize(readVal);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(readVal, val);
// packet should be empty
ASSERT_EQ(this->m_sentPacket.getBuffLeft(),0u);
// Turn on all filters and make sure FATAL still gets through
this->clearHistory();
this->clearEvents();
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::WARNING_HI,Enabled::DISABLED);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
ActiveLoggerImpl::OPCODE_SET_EVENT_FILTER,
cmdSeq,
Fw::CmdResponse::OK
);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::WARNING_LO,Enabled::DISABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::COMMAND,Enabled::DISABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::ACTIVITY_HI,Enabled::DISABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::ACTIVITY_LO,Enabled::DISABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::DIAGNOSTIC,Enabled::DISABLED);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,Fw::LogSeverity::FATAL,buff);
// should not have received packet
ASSERT_FALSE(this->m_receivedPacket);
// dispatch message
this->m_impl.doDispatch();
// should have received packet
ASSERT_TRUE(this->m_receivedPacket);
// verify contents
// first piece should be log packet descriptor
stat = this->m_sentPacket.deserialize(desc);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(desc,static_cast<FwPacketDescriptorType>(Fw::ComPacket::FW_PACKET_LOG));
// next piece should be event ID
stat = this->m_sentPacket.deserialize(sentId);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(sentId,id);
// next piece is time tag
stat = this->m_sentPacket.deserialize(recTimeTag);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_TRUE(timeTag == recTimeTag);
// next piece is event argument
stat = this->m_sentPacket.deserialize(readVal);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(readVal, val);
// packet should be empty
ASSERT_EQ(this->m_sentPacket.getBuffLeft(),0u);
// turn off filters
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::WARNING_HI,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::WARNING_LO,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::COMMAND,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::ACTIVITY_HI,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::ACTIVITY_LO,Enabled::ENABLED);
this->sendCmd_SET_EVENT_FILTER(0,cmdSeq,FilterSeverity::DIAGNOSTIC,Enabled::ENABLED);
}
void ActiveLoggerImplTester::writeEvent(FwEventIdType id, Fw::LogSeverity severity, U32 value) {
Fw::LogBuffer buff;
Fw::SerializeStatus stat = buff.serialize(value);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
Fw::Time timeTag(TB_NONE,1,2);
this->m_receivedPacket = false;
this->invoke_to_LogRecv(0,id,timeTag,severity,buff);
// should not have received packet
ASSERT_FALSE(this->m_receivedPacket);
// dispatch message
this->m_impl.doDispatch();
// should have received packet
ASSERT_TRUE(this->m_receivedPacket);
// verify contents
// first piece should be log packet descriptor
FwPacketDescriptorType desc;
stat = this->m_sentPacket.deserialize(desc);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(desc,static_cast<FwPacketDescriptorType>(Fw::ComPacket::FW_PACKET_LOG));
// next piece should be event ID
FwEventIdType sentId;
stat = this->m_sentPacket.deserialize(sentId);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(sentId,id);
// next piece is time tag
Fw::Time recTimeTag(TB_NONE,1,2);
stat = this->m_sentPacket.deserialize(recTimeTag);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_TRUE(timeTag == recTimeTag);
// next piece is event argument
U32 readVal;
stat = this->m_sentPacket.deserialize(readVal);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat);
ASSERT_EQ(readVal, value);
// packet should be empty
ASSERT_EQ(this->m_sentPacket.getBuffLeft(),0u);
}
void ActiveLoggerImplTester::readEvent(FwEventIdType id, Fw::LogSeverity severity, U32 value, Os::File& file) {
static const BYTE delimiter = 0xA5;
// first read should be delimiter
BYTE de;
FwSignedSizeType readSize = sizeof(de);
ASSERT_EQ(file.read(&de,readSize,Os::File::WaitType::WAIT),Os::File::OP_OK);
ASSERT_EQ(delimiter,de);
// next is LogPacket
Fw::ComBuffer comBuff;
// size is specific to this test
readSize = sizeof(FwPacketDescriptorType) + sizeof(FwEventIdType) + Fw::Time::SERIALIZED_SIZE + sizeof(U32);
ASSERT_EQ(file.read(comBuff.getBuffAddr(),readSize,Os::File::WaitType::WAIT),Os::File::OP_OK);
comBuff.setBuffLen(readSize);
// deserialize LogPacket
Fw::LogPacket packet;
Fw::Time time(TB_NONE,1,2);
Fw::LogBuffer logBuff;
ASSERT_EQ(comBuff.deserialize(packet),Fw::FW_SERIALIZE_OK);
// read back values
ASSERT_EQ(id,packet.getId());
ASSERT_EQ(time,packet.getTimeTag());
logBuff = packet.getLogBuffer();
U32 readValue;
ASSERT_EQ(logBuff.deserialize(readValue),Fw::FW_SERIALIZE_OK);
ASSERT_EQ(value,readValue);
}
void ActiveLoggerImplTester::textLogIn(const FwEventIdType id, //!< The event ID
const Fw::Time& timeTag, //!< The time
const Fw::LogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
) {
TextLogEntry e = { id, timeTag, severity, text };
printTextLogHistoryEntry(e, stdout);
}
void ActiveLoggerImplTester ::
from_pingOut_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
this->pushFromPortEntry_pingOut(key);
}
} /* namespace SvcTest */
| cpp |
fprime | data/projects/fprime/Svc/ActiveLogger/test/ut/ActiveLoggerImplTester.hpp | /*
* ActiveLoggerImplTester.hpp
*
* Created on: Mar 18, 2015
* Author: tcanham
*/
#ifndef ACTIVELOGGER_TEST_UT_ACTIVELOGGERIMPLTESTER_HPP_
#define ACTIVELOGGER_TEST_UT_ACTIVELOGGERIMPLTESTER_HPP_
#include <ActiveLoggerGTestBase.hpp>
#include <Svc/ActiveLogger/ActiveLoggerImpl.hpp>
#include <Os/File.hpp>
namespace Svc {
class ActiveLoggerImplTester: public Svc::ActiveLoggerGTestBase {
public:
ActiveLoggerImplTester(Svc::ActiveLoggerImpl& inst);
virtual ~ActiveLoggerImplTester();
void init(NATIVE_INT_TYPE instance = 0) override;
void runEventNominal();
void runFilterEventNominal();
void runFilterIdNominal();
void runFilterDump();
void runFilterInvalidCommands();
void runEventFatal();
void runFileDump();
void runFileDumpErrors();
private:
void from_PktSend_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::ComBuffer &data, //!< Buffer containing packet data
U32 context //!< context (not used)
) override;
void from_FatalAnnounce_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
FwEventIdType Id //!< The ID of the FATAL event
) override;
Svc::ActiveLoggerImpl& m_impl;
bool m_receivedPacket;
Fw::ComBuffer m_sentPacket;
bool m_receivedFatalEvent;
FwEventIdType m_fatalID;
void runWithFilters(Fw::LogSeverity filter);
void writeEvent(FwEventIdType id, Fw::LogSeverity severity, U32 value);
void readEvent(FwEventIdType id, Fw::LogSeverity severity, U32 value, Os::File& file);
// open call modifiers
static bool OpenInterceptor(Os::File::Status &stat, const char* fileName, Os::File::Mode mode, void* ptr);
Os::File::Status m_testOpenStatus;
// write call modifiers
static bool WriteInterceptor(Os::File::Status &status, const void * buffer, NATIVE_INT_TYPE &size, bool waitForDone, void* ptr);
Os::File::Status m_testWriteStatus;
// How many read calls to let pass before modifying
NATIVE_INT_TYPE m_writesToWait;
// enumeration to tell what kind of error to inject
typedef enum {
FILE_WRITE_WRITE_ERROR, // return a bad read status
FILE_WRITE_SIZE_ERROR, // return a bad size
} FileWriteTestType;
FileWriteTestType m_writeTestType;
NATIVE_INT_TYPE m_writeSize;
void textLogIn(const FwEventIdType id, //!< The event ID
const Fw::Time& timeTag, //!< The time
const Fw::LogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
) override;
//! Handler for from_pingOut
//!
void from_pingOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
) override;
};
} /* namespace Svc */
#endif /* ACTIVELOGGER_TEST_UT_ACTIVELOGGERIMPLTESTER_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/FileUplink/Warnings.cpp | // ======================================================================
// \title Warnings.cpp
// \author bocchino
// \brief cpp file for FileUplink::Warnings
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Svc/FileUplink/FileUplink.hpp>
namespace Svc {
void FileUplink::Warnings ::
invalidReceiveMode(const Fw::FilePacket::Type packetType)
{
this->m_fileUplink->log_WARNING_HI_InvalidReceiveMode(
static_cast<U32>(packetType),
static_cast<U32>(m_fileUplink->m_receiveMode)
);
this->warning();
}
void FileUplink::Warnings ::
fileOpen(Fw::LogStringArg& fileName)
{
this->m_fileUplink->log_WARNING_HI_FileOpenError(fileName);
this->warning();
}
void FileUplink::Warnings ::
packetOutOfBounds(
const U32 sequenceIndex,
Fw::LogStringArg& fileName
)
{
this->m_fileUplink->log_WARNING_HI_PacketOutOfBounds(
sequenceIndex,
fileName
);
this->warning();
}
void FileUplink::Warnings ::
packetOutOfOrder(
const U32 sequenceIndex,
const U32 lastSequenceIndex
)
{
this->m_fileUplink->log_WARNING_HI_PacketOutOfOrder(
sequenceIndex,
lastSequenceIndex
);
this->warning();
}
void FileUplink::Warnings ::
fileWrite(Fw::LogStringArg& fileName)
{
this->m_fileUplink->log_WARNING_HI_FileWriteError(fileName);
this->warning();
}
void FileUplink::Warnings ::
badChecksum(
const U32 computed,
const U32 read
)
{
this->m_fileUplink->log_WARNING_HI_BadChecksum(
this->m_fileUplink->m_file.name,
computed,
read
);
this->warning();
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileUplink/File.cpp | // ======================================================================
// \title File.cpp
// \author bocchino
// \brief cpp file for FileUplink::File
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Svc/FileUplink/FileUplink.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Svc {
Os::File::Status FileUplink::File ::
open(const Fw::FilePacket::StartPacket& startPacket)
{
const U32 length = startPacket.getDestinationPath().getLength();
char path[Fw::FilePacket::PathName::MAX_LENGTH + 1];
memcpy(path, startPacket.getDestinationPath().getValue(), length);
path[length] = 0;
Fw::LogStringArg logStringArg(path);
this->name = logStringArg;
this->size = startPacket.getFileSize();
CFDP::Checksum checksum;
this->m_checksum = checksum;
return this->osFile.open(path, Os::File::OPEN_WRITE);
}
Os::File::Status FileUplink::File ::
write(
const U8 *const data,
const U32 byteOffset,
const U32 length
)
{
Os::File::Status status;
status = this->osFile.seek(byteOffset, Os::File::SeekType::ABSOLUTE);
if (status != Os::File::OP_OK) {
return status;
}
FwSignedSizeType intLength = length;
//Note: not waiting for the file write to finish
status = this->osFile.write(data, intLength, Os::File::WaitType::NO_WAIT);
if (status != Os::File::OP_OK) {
return status;
}
FW_ASSERT(static_cast<U32>(intLength) == length, intLength);
this->m_checksum.update(data, byteOffset, length);
return Os::File::OP_OK;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileUplink/FileUplink.cpp | // ======================================================================
// \title FileUplink.cpp
// \author bocchino
// \brief cpp file for FileUplink component implementation class
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Svc/FileUplink/FileUplink.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
FileUplink ::
FileUplink(const char *const name) :
FileUplinkComponentBase(name),
m_receiveMode(START),
m_lastSequenceIndex(0),
m_filesReceived(this),
m_packetsReceived(this),
m_warnings(this)
{
}
void FileUplink ::
init(
const NATIVE_INT_TYPE queueDepth,
const NATIVE_INT_TYPE instance
)
{
FileUplinkComponentBase::init(queueDepth, instance);
}
FileUplink ::
~FileUplink()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void FileUplink ::
bufferSendIn_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer& buffer
)
{
Fw::FilePacket filePacket;
const Fw::SerializeStatus status = filePacket.fromBuffer(buffer);
if (status != Fw::FW_SERIALIZE_OK) {
this->log_WARNING_HI_DecodeError(status);
} else {
Fw::FilePacket::Type header_type = filePacket.asHeader().getType();
switch (header_type) {
case Fw::FilePacket::T_START:
this->handleStartPacket(filePacket.asStartPacket());
break;
case Fw::FilePacket::T_DATA:
this->handleDataPacket(filePacket.asDataPacket());
break;
case Fw::FilePacket::T_END:
this->handleEndPacket(filePacket.asEndPacket());
break;
case Fw::FilePacket::T_CANCEL:
this->handleCancelPacket();
break;
default:
FW_ASSERT(0);
break;
}
}
this->bufferSendOut_out(0, buffer);
}
void FileUplink ::
pingIn_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
// return key
this->pingOut_out(0,key);
}
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
void FileUplink ::
handleStartPacket(const Fw::FilePacket::StartPacket& startPacket)
{
// Clear all event throttles in preparation for new start packet
this->log_WARNING_HI_FileWriteError_ThrottleClear();
this->log_WARNING_HI_InvalidReceiveMode_ThrottleClear();
this->log_WARNING_HI_PacketOutOfBounds_ThrottleClear();
this->log_WARNING_HI_PacketOutOfOrder_ThrottleClear();
this->m_packetsReceived.packetReceived();
if (this->m_receiveMode != START) {
this->m_file.osFile.close();
this->m_warnings.invalidReceiveMode(Fw::FilePacket::T_START);
}
const Os::File::Status status = this->m_file.open(startPacket);
if (status == Os::File::OP_OK) {
this->goToDataMode();
}
else {
this->m_warnings.fileOpen(this->m_file.name);
this->goToStartMode();
}
}
void FileUplink ::
handleDataPacket(const Fw::FilePacket::DataPacket& dataPacket)
{
this->m_packetsReceived.packetReceived();
if (this->m_receiveMode != DATA) {
this->m_warnings.invalidReceiveMode(Fw::FilePacket::T_DATA);
return;
}
const U32 sequenceIndex = dataPacket.asHeader().getSequenceIndex();
this->checkSequenceIndex(sequenceIndex);
const U32 byteOffset = dataPacket.getByteOffset();
const U32 dataSize = dataPacket.getDataSize();
if (byteOffset + dataSize > this->m_file.size) {
this->m_warnings.packetOutOfBounds(sequenceIndex, this->m_file.name);
return;
}
const Os::File::Status status = this->m_file.write(
dataPacket.getData(),
byteOffset,
dataSize
);
if (status != Os::File::OP_OK) {
this->m_warnings.fileWrite(this->m_file.name);
}
}
void FileUplink ::
handleEndPacket(const Fw::FilePacket::EndPacket& endPacket)
{
this->m_packetsReceived.packetReceived();
if (this->m_receiveMode == DATA) {
this->m_filesReceived.fileReceived();
this->checkSequenceIndex(endPacket.asHeader().getSequenceIndex());
this->compareChecksums(endPacket);
this->log_ACTIVITY_HI_FileReceived(this->m_file.name);
}
else {
this->m_warnings.invalidReceiveMode(Fw::FilePacket::T_END);
}
this->goToStartMode();
}
void FileUplink ::
handleCancelPacket()
{
this->m_packetsReceived.packetReceived();
this->log_ACTIVITY_HI_UplinkCanceled();
this->goToStartMode();
}
void FileUplink ::
checkSequenceIndex(const U32 sequenceIndex)
{
if (sequenceIndex != this->m_lastSequenceIndex + 1) {
this->m_warnings.packetOutOfOrder(
sequenceIndex,
this->m_lastSequenceIndex
);
}
this->m_lastSequenceIndex = sequenceIndex;
}
void FileUplink ::
compareChecksums(const Fw::FilePacket::EndPacket& endPacket)
{
CFDP::Checksum computed, stored;
this->m_file.getChecksum(computed);
endPacket.getChecksum(stored);
if (computed != stored) {
this->m_warnings.badChecksum(
computed.getValue(),
stored.getValue()
);
}
}
void FileUplink ::
goToStartMode()
{
this->m_file.osFile.close();
this->m_receiveMode = START;
this->m_lastSequenceIndex = 0;
}
void FileUplink ::
goToDataMode()
{
this->m_receiveMode = DATA;
this->m_lastSequenceIndex = 0;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileUplink/FileUplink.hpp | // ======================================================================
// \title FileUplink.hpp
// \author bocchino
// \brief hpp file for FileUplink component implementation class
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Svc_FileUplink_HPP
#define Svc_FileUplink_HPP
#include <Svc/FileUplink/FileUplinkComponentAc.hpp>
#include <Fw/FilePacket/FilePacket.hpp>
#include <Os/File.hpp>
namespace Svc {
class FileUplink :
public FileUplinkComponentBase
{
PRIVATE:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
//! The ReceiveMode type
typedef enum { START, DATA } ReceiveMode;
//! An object representing an incoming file
class File {
public:
//! The file size
U32 size;
//! The file name
Fw::LogStringArg name;
//! The underlying OS file
Os::File osFile;
PRIVATE:
//! The checksum for the file
::CFDP::Checksum m_checksum;
public:
//! Open the OS file for writing and initialize the checksum
Os::File::Status open(
const Fw::FilePacket::StartPacket& startPacket
);
//! Write bytes into the OS file and update the checksum
Os::File::Status write(
const U8 *const data,
const U32 byteOffset,
const U32 length
);
//! Get the checksum
void getChecksum(::CFDP::Checksum& checksum) {
checksum = this->m_checksum;
}
};
//! Object to record files received
class FilesReceived {
public:
//! Construct a FilesReceived object
FilesReceived(FileUplink *const fileUplink) :
m_received_files_counter(0),
m_fileUplink(fileUplink)
{ }
public:
//! Record a received file
void fileReceived() {
++this->m_received_files_counter;
this->m_fileUplink->tlmWrite_FilesReceived(m_received_files_counter);
}
PRIVATE:
//! The total number of files received
U32 m_received_files_counter;
//! The enclosing FileUplink object
FileUplink *const m_fileUplink;
};
//! Object to record packets received
class PacketsReceived {
public:
//! Construct a PacketsReceived object
PacketsReceived(FileUplink *const fileUplink) :
m_received_packet_count(0),
m_fileUplink(fileUplink)
{ }
public:
//! Record a packet received
void packetReceived() {
++this->m_received_packet_count;
this->m_fileUplink->tlmWrite_PacketsReceived(m_received_packet_count);
}
PRIVATE:
//! The total number of received packets
U32 m_received_packet_count;
//! The enclosing FileUplink object
FileUplink *const m_fileUplink;
};
//! Object to record warnings
class Warnings {
public:
//! Construct a Warnings object
Warnings(FileUplink *const fileUplink) :
m_warning_count(0),
m_fileUplink(fileUplink)
{ }
public:
//! Record an Invalid Receive Mode warning
void invalidReceiveMode(const Fw::FilePacket::Type packetType);
//! Record a File Open warning
void fileOpen(Fw::LogStringArg& fileName);
//! Record a Packet Out of Bounds warning
void packetOutOfBounds(
const U32 sequenceIndex,
Fw::LogStringArg& fileName
);
//! Record a Packet Out of Order warning
void packetOutOfOrder(
const U32 sequenceIndex,
const U32 lastSequenceIndex
);
//! Record a File Write warning
void fileWrite(Fw::LogStringArg& fileName);
//! Record a Bad Checksum warning
void badChecksum(
const U32 computed,
const U32 read
);
PRIVATE:
//! Record a warning
void warning() {
++this->m_warning_count;
this->m_fileUplink->tlmWrite_Warnings(m_warning_count);
}
PRIVATE:
//! The total number of warnings
U32 m_warning_count;
//! The enclosing FileUplink object
FileUplink *const m_fileUplink;
};
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object FileUplink
//!
FileUplink(
const char *const name //!< The component name
);
//! Initialize object FileUplink
//!
void init(
const NATIVE_INT_TYPE queueDepth, //!< The queue depth
const NATIVE_INT_TYPE instance //!< The instance number
);
//! Destroy object FileUplink
//!
~FileUplink();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for bufferSendIn
//!
void bufferSendIn_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer& buffer //!< Buffer wrapping data
);
//! Handler implementation for pingIn
//!
void pingIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
PRIVATE:
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
//! Handle a start packet
void handleStartPacket(const Fw::FilePacket::StartPacket& startPacket);
//! Handle a data packet
void handleDataPacket(const Fw::FilePacket::DataPacket& dataPacket);
//! Handle an end packet
void handleEndPacket(const Fw::FilePacket::EndPacket& endPacket);
//! Handle a cancel packet
void handleCancelPacket();
//! Check sequence index
void checkSequenceIndex(const U32 sequenceIndex);
//! Compare checksums
void compareChecksums(const Fw::FilePacket::EndPacket& endPacket);
//! Go to START mode
void goToStartMode();
//! Go to DATA mode
void goToDataMode();
PRIVATE:
// ----------------------------------------------------------------------
// Member variables
// ----------------------------------------------------------------------
//! The receive mode
ReceiveMode m_receiveMode;
//! The sequence index of the last packet received
U32 m_lastSequenceIndex;
//! The file being assembled
File m_file;
//! The total number of files received
FilesReceived m_filesReceived;
//! The total number of cancel packets
PacketsReceived m_packetsReceived;
//! The total number of warnings
Warnings m_warnings;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/FileUplink/test/ut/FileUplinkTester.cpp | // ======================================================================
// \title FileUplink.hpp
// \author bocchino
// \brief cpp file for FileUplink test harness implementation class
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <cerrno>
#include <cstring>
#include "FileUplinkTester.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
#define QUEUE_DEPTH 10
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
FileUplinkTester ::
FileUplinkTester() :
FileUplinkGTestBase("Tester", MAX_HISTORY_SIZE),
component("FileUplink"),
expectedPacketsReceived(0),
sequenceIndex(0)
{
this->connectPorts();
this->initComponents();
}
FileUplinkTester ::
~FileUplinkTester()
{
this->component.m_file.osFile.close();
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void FileUplinkTester ::
sendFile()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
const U32 numPackets = 2;
U8 packetData[numPackets][5] = {
{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 }
};
const U8 *const linearPacketData = reinterpret_cast<U8*>(packetData);
const size_t fileSize = sizeof(packetData);
// Send the start packet
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Send the data packets
for (size_t i = 0; i < numPackets; ++i) {
const size_t byteOffset = i * PACKET_SIZE;
this->sendDataPacket(byteOffset, packetData[i]);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
}
// Send the end packet
CFDP::Checksum checksum;
checksum.update(linearPacketData, 0, fileSize);
this->sendEndPacket(checksum);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_FilesReceived(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_FileReceived(0, destPath);
// Assert we are back in START mode
ASSERT_EQ(FileUplink::START, this->component.m_receiveMode);
// Verify the file data
this->verifyFileData(destPath, linearPacketData, fileSize);
// Remove the file
this->removeFile(destPath);
}
void FileUplinkTester ::
badChecksum()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
const U32 numPackets = 2;
U8 packetData[numPackets][5] = {
{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 }
};
const U8 *const linearPacketData = reinterpret_cast<U8*>(packetData);
const size_t fileSize = sizeof(packetData);
// Send the start packet
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Send the data packets
for (size_t i = 0; i < numPackets; ++i) {
const size_t byteOffset = i * PACKET_SIZE;
this->sendDataPacket(byteOffset, packetData[i]);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
}
// Send the end packet
CFDP::Checksum checksum;
// Perturb the packet data to alter the checksum
++packetData[0][0];
checksum.update(linearPacketData, 0, fileSize);
this->sendEndPacket(checksum);
ASSERT_TLM_SIZE(3);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_FilesReceived(0, 1);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(2);
ASSERT_EVENTS_FileReceived(0, destPath);
ASSERT_EVENTS_BadChecksum(0, destPath, 202311690, 219088906);
// Remove the file
this->removeFile(destPath);
}
void FileUplinkTester ::
fileOpenError()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "missing_directory/test.bin";
this->sendStartPacket(sourcePath, destPath, 0);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_FileOpenError(0, destPath);
ASSERT_EQ(FileUplink::START, this->component.m_receiveMode);
}
void FileUplinkTester ::
fileWriteError()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
U8 packetData[] = { 0, 1, 2, 3, 4 };
const size_t fileSize = 2 * PACKET_SIZE;
// Send the start packet (packet 0)
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Close the file so writing will fail
this->component.m_file.osFile.close();
// Send the data packet (packet 1)
const size_t byteOffset = PACKET_SIZE;
this->sendDataPacket(byteOffset, packetData);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_FileWriteError(0, destPath);
}
void FileUplinkTester ::
startPacketInDataMode()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
const size_t fileSize = 0;
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_InvalidReceiveMode(
0,
Fw::FilePacket::T_START,
FileUplink::DATA
);
ASSERT_EQ(FileUplink::DATA, this->component.m_receiveMode);
this->removeFile(destPath);
}
void FileUplinkTester ::
dataPacketInStartMode()
{
U8 packetData[PACKET_SIZE];
const size_t byteOffset = 0;
this->sendDataPacket(byteOffset, packetData);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_InvalidReceiveMode(
0,
Fw::FilePacket::T_DATA,
FileUplink::START
);
}
void FileUplinkTester ::
endPacketInStartMode()
{
CFDP::Checksum checksum;
this->sendEndPacket(checksum);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_InvalidReceiveMode(
0,
Fw::FilePacket::T_END,
FileUplink::START
);
ASSERT_EQ(FileUplink::START, this->component.m_receiveMode);
}
void FileUplinkTester ::
packetOutOfBounds()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
const size_t fileSize = 0;
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
const size_t byteOffset = 0;
U8 packetData[PACKET_SIZE];
this->sendDataPacket(byteOffset, packetData);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PacketOutOfBounds(
0, 1, destPath
);
this->removeFile(destPath);
}
void FileUplinkTester ::
packetOutOfOrder()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
U8 packetData[] = { 5, 6, 7, 8, 9 };
const size_t fileSize = 2 * PACKET_SIZE;
// Send the start packet (packet 0)
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Simulate dropping of packet 1
++this->sequenceIndex;
// Send the data packet (packet 2)
const size_t byteOffset = PACKET_SIZE;
this->sendDataPacket(byteOffset, packetData);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_TLM_Warnings(0, 1);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PacketOutOfOrder(0, 2, 0);
this->removeFile("test.bin");
}
void FileUplinkTester ::
cancelPacketInStartMode()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
const size_t fileSize = 0;
// Send the start packet (packet 0)
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Send a cancel packet
this->sendCancelPacket();
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_UplinkCanceled_SIZE(1);
// Check component state
ASSERT_EQ(0U, this->component.m_lastSequenceIndex);
ASSERT_EQ(FileUplink::START, this->component.m_receiveMode);
// Remove the file
this->removeFile("test.bin");
}
void FileUplinkTester ::
cancelPacketInDataMode()
{
const char *const sourcePath = "source.bin";
const char *const destPath = "dest.bin";
U8 packetData[] = { 0, 1, 2, 3, 4 };
const size_t fileSize = 2 * PACKET_SIZE;
// Send the start packet (packet 0)
this->sendStartPacket(sourcePath, destPath, fileSize);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Send the data packet (packet 1)
const size_t byteOffset = PACKET_SIZE;
this->sendDataPacket(byteOffset, packetData);
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(0);
// Send a cancel packet
this->sendCancelPacket();
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsReceived(
0,
++this->expectedPacketsReceived
);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_UplinkCanceled_SIZE(1);
// Check component state
ASSERT_EQ(0U, this->component.m_lastSequenceIndex);
ASSERT_EQ(FileUplink::START, this->component.m_receiveMode);
// Remove the file
this->removeFile("test.bin");
}
// ----------------------------------------------------------------------
// Handlers for from ports
// ----------------------------------------------------------------------
void FileUplinkTester ::
from_bufferSendOut_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer& buffer
)
{
this->pushFromPortEntry_bufferSendOut(buffer);
}
void FileUplinkTester ::
from_pingOut_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
this->pushFromPortEntry_pingOut(key);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void FileUplinkTester ::
connectPorts()
{
// bufferSendIn
this->connect_to_bufferSendIn(
0,
this->component.get_bufferSendIn_InputPort(0)
);
// timeCaller
this->component.set_timeCaller_OutputPort(
0,
this->get_from_timeCaller(0)
);
// bufferSendOut
this->component.set_bufferSendOut_OutputPort(
0,
this->get_from_bufferSendOut(0)
);
// tlmOut
this->component.set_tlmOut_OutputPort(
0,
this->get_from_tlmOut(0)
);
// eventOut
this->component.set_eventOut_OutputPort(
0,
this->get_from_eventOut(0)
);
// LogText
this->component.set_LogText_OutputPort(
0,
this->get_from_LogText(0)
);
// pingIn
this->connect_to_pingIn(
0,
this->component.get_pingIn_InputPort(0)
);
// pingOut
this->component.set_pingOut_OutputPort(
0,
this->get_from_pingOut(0)
);
}
void FileUplinkTester ::
initComponents()
{
this->init();
this->component.init(QUEUE_DEPTH, INSTANCE);
}
void FileUplinkTester ::
sendFilePacket(const Fw::FilePacket& filePacket)
{
this->clearHistory();
const size_t bufferSize = filePacket.bufferSize();
U8 bufferData[bufferSize];
Fw::Buffer buffer(bufferData, bufferSize);
const Fw::SerializeStatus status = filePacket.toBuffer(buffer);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, status);
this->invoke_to_bufferSendIn(0, buffer);
this->component.doDispatch();
ASSERT_from_bufferSendOut_SIZE(1);
ASSERT_from_bufferSendOut(0, buffer);
}
void FileUplinkTester ::
sendStartPacket(
const char *const sourcePath,
const char *const destPath,
const size_t fileSize
)
{
Fw::FilePacket::StartPacket startPacket;
startPacket.initialize(fileSize, sourcePath, destPath);
Fw::FilePacket filePacket;
filePacket.fromStartPacket(startPacket);
this->sendFilePacket(filePacket);
this->sequenceIndex = 1;
}
void FileUplinkTester ::
sendDataPacket(
const size_t byteOffset,
U8 *const packetData
)
{
const Fw::FilePacket::DataPacket dataPacket = {
{ Fw::FilePacket::T_DATA, this->sequenceIndex++ },
static_cast<U32>(byteOffset),
PACKET_SIZE,
packetData
};
Fw::FilePacket filePacket;
filePacket.fromDataPacket(dataPacket);
this->sendFilePacket(filePacket);
}
void FileUplinkTester ::
sendEndPacket(const CFDP::Checksum& checksum)
{
const Fw::FilePacket::Header header = {
Fw::FilePacket::T_END,
this->sequenceIndex++
};
Fw::FilePacket::EndPacket endPacket;
endPacket.m_header = header;
endPacket.setChecksum(checksum);
Fw::FilePacket filePacket;
filePacket.fromEndPacket(endPacket);
this->sendFilePacket(filePacket);
}
void FileUplinkTester ::
sendCancelPacket()
{
const Fw::FilePacket::Header header = {
Fw::FilePacket::T_CANCEL,
this->sequenceIndex++
};
const Fw::FilePacket::CancelPacket cancelPacket = { header };
Fw::FilePacket filePacket;
filePacket.fromCancelPacket(cancelPacket);
this->sendFilePacket(filePacket);
}
void FileUplinkTester ::
verifyFileData(
const char *const path,
const U8 *const sentData,
const size_t dataSize
)
{
Os::File file;
U8 fileData[dataSize];
file.open(path, Os::File::OPEN_READ);
FwSignedSizeType intSize = static_cast<FwSignedSizeType>(dataSize);
const Os::File::Status status = file.read(fileData, intSize);
ASSERT_EQ(Os::File::OP_OK, status);
ASSERT_EQ(static_cast<size_t>(intSize), dataSize);
for (size_t i = 0; i < dataSize; ++i) {
ASSERT_EQ(sentData[i], fileData[i]);
}
}
void FileUplinkTester ::
removeFile(const char *const path)
{
const NATIVE_INT_TYPE status = ::unlink(path);
if (status != 0) {
ASSERT_EQ(ENOENT, errno);
}
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileUplink/test/ut/FileUplinkTester.hpp | // ======================================================================
// \title FileUplink/test/ut/Tester.hpp
// \author bocchino
// \brief hpp file for FileUplink test harness implementation class
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include <Svc/FileUplink/FileUplink.hpp>
#include "FileUplinkGTestBase.hpp"
#define PACKET_SIZE 5
namespace Svc {
class FileUplinkTester :
public FileUplinkGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object FileUplinkTester
//!
FileUplinkTester();
//! Destroy object FileUplinkTester
//!
~FileUplinkTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Send a file
//!
void sendFile();
//! Send a file with a bad checksum value
//!
void badChecksum();
//! Cause a file open error
//!
void fileOpenError();
//! Cause a file write error
//!
void fileWriteError();
//! Send a START packet in DATA mode
//!
void startPacketInDataMode();
//! Send a DATA packet in START mode
//!
void dataPacketInStartMode();
//! Send an END packet in START mode
//!
void endPacketInStartMode();
//! Send a file with an out-of-bounds packet
//!
void packetOutOfBounds();
//! Send a file with an out-of-order packet
//!
void packetOutOfOrder();
//! Send a CANCEL packet in START mode
//!
void cancelPacketInStartMode();
//! Send a CANCEL packet in DATA mode
//!
void cancelPacketInDataMode();
private:
// ----------------------------------------------------------------------
// Handlers for from ports
// ----------------------------------------------------------------------
//! Handler for from_bufferSendOut
//!
void from_bufferSendOut_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer& buffer
);
//! Handler for from_pingOut
//!
void from_pingOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
//! Send a FilePacket
//!
void sendFilePacket(const Fw::FilePacket& filePacket);
//! Send a StartPacket
//!
void sendStartPacket(
const char *const sourcePath, //!< The source path
const char *const destPath, //!< The destination path
const size_t fileSize //!< The file size
);
//! Send a DataPacket
//!
void sendDataPacket(
const size_t byteOffset,
U8 *const packetData
);
//! Send an EndPacket
//!
void sendEndPacket(const CFDP::Checksum& checksum);
//! Send a CancelPacket
//!
void sendCancelPacket();
//! Verify file data
//!
void verifyFileData(
const char *const path,
const U8 *const sentData,
const size_t sentDataSize
);
//! Remove a file
//!
void removeFile(const char *const path);
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
FileUplink component;
//! The expected number of packets received so far
//!
U32 expectedPacketsReceived;
//! The current sequence index
//!
U32 sequenceIndex;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/FileUplink/test/ut/FileUplinkMain.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include "FileUplinkTester.hpp"
TEST(FileUplink, SendFile) {
Svc::FileUplinkTester tester;
tester.sendFile();
}
TEST(FileUplink, BadChecksum) {
Svc::FileUplinkTester tester;
tester.badChecksum();
}
TEST(FileUplink, FileOpenError) {
Svc::FileUplinkTester tester;
tester.fileOpenError();
}
TEST(FileUplink, FileWriteError) {
Svc::FileUplinkTester tester;
tester.fileWriteError();
}
TEST(FileUplink, StartPacketInDataMode) {
Svc::FileUplinkTester tester;
tester.startPacketInDataMode();
}
TEST(FileUplink, DataPacketInStartMode) {
Svc::FileUplinkTester tester;
tester.dataPacketInStartMode();
}
TEST(FileUplink, EndPacketInStartMode) {
Svc::FileUplinkTester tester;
tester.endPacketInStartMode();
}
TEST(FileUplink, PacketOutOfBounds) {
Svc::FileUplinkTester tester;
tester.packetOutOfBounds();
}
TEST(FileUplink, PacketOutOfOrder) {
Svc::FileUplinkTester tester;
tester.packetOutOfOrder();
}
TEST(FileUplink, CancelPacketInStartMode) {
Svc::FileUplinkTester tester;
tester.cancelPacketInStartMode();
}
TEST(FileUplink, CancelPacketInDataMode) {
Svc::FileUplinkTester tester;
tester.cancelPacketInDataMode();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/FramingProtocol/DeframingProtocol.cpp | // ======================================================================
// \title DeframingProtocol.cpp
// \author mstarch
// \brief cpp file for DeframingProtocol class
//
// \copyright
// Copyright 2009-2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "DeframingProtocol.hpp"
#include "DeframingProtocolInterface.hpp"
namespace Svc {
DeframingProtocol::DeframingProtocol() : m_interface(nullptr) {}
void DeframingProtocol::setup(DeframingProtocolInterface& interface) {
FW_ASSERT(m_interface == nullptr);
m_interface = &interface;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FramingProtocol/FramingProtocol.hpp | // ======================================================================
// \title FramingProtocol.hpp
// \author mstarch
// \brief hpp file for FramingProtocol class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef SVC_FRAMING_PROTOCOL_HPP
#define SVC_FRAMING_PROTOCOL_HPP
#include "Svc/FramingProtocol/FramingProtocolInterface.hpp"
#include "Fw/Com/ComPacket.hpp"
namespace Svc {
/**
* \brief abstract class representing a framing protocol
*
* This class defines the methods used to create a framed packet from Com and Fw::Buffers. The
* framing protocol `frame` method is called with data and it in turn is expected to call the
* `send` method of m_interface once a packet is constructed.
*
* There is no requirement that this be one-to-one and thus packetization, aggregation may all
* be performed. A call to `m_interface.allocate` can allocate memory such that framing tokens
* may be added.
*/
class FramingProtocol {
public:
//! \brief constructor
//!
FramingProtocol();
virtual ~FramingProtocol(){};
//! \brief setup function called to supply the interface used for allocation and sending
//! \param interface: interface implementation, normally FramerComponentImpl
void setup(FramingProtocolInterface& interface);
//! \brief frame a given set of bytes
//! \param data: pointer to a set of bytes to be framed
//! \param size: size of data pointed to by `data`
//! \param packet_type: type of data supplied for File downlink packets
virtual void frame(const U8* const data, const U32 size, Fw::ComPacket::ComPacketType packet_type) = 0;
PROTECTED:
FramingProtocolInterface* m_interface;
};
}
#endif // SVC_FRAMING_PROTOCOL_HPP
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/FprimeProtocol.cpp | // ======================================================================
// \title FprimeProtocol.cpp
// \author mstarch
// \brief cpp file for FprimeProtocol class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FprimeProtocol.hpp"
#include "FpConfig.hpp"
#include "Utils/Hash/Hash.hpp"
namespace Svc {
FprimeFraming::FprimeFraming(): FramingProtocol() {}
FprimeDeframing::FprimeDeframing(): DeframingProtocol() {}
void FprimeFraming::frame(const U8* const data, const U32 size, Fw::ComPacket::ComPacketType packet_type) {
FW_ASSERT(data != nullptr);
FW_ASSERT(m_interface != nullptr);
// Use of I32 size is explicit as ComPacketType will be specifically serialized as an I32
FpFrameHeader::TokenType real_data_size = size + ((packet_type != Fw::ComPacket::FW_PACKET_UNKNOWN) ? sizeof(I32) : 0);
FpFrameHeader::TokenType total = real_data_size + FpFrameHeader::SIZE + HASH_DIGEST_LENGTH;
Fw::Buffer buffer = m_interface->allocate(total);
Fw::SerializeBufferBase& serializer = buffer.getSerializeRepr();
Utils::HashBuffer hash;
// Serialize data
Fw::SerializeStatus status;
status = serializer.serialize(FpFrameHeader::START_WORD);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
status = serializer.serialize(real_data_size);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
// Serialize packet type if supplied, otherwise it *must* be present in the data
if (packet_type != Fw::ComPacket::FW_PACKET_UNKNOWN) {
status = serializer.serialize(static_cast<I32>(packet_type)); // I32 used for enum storage
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
}
status = serializer.serialize(data, size, true); // Serialize without length
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
// Calculate and add transmission hash
Utils::Hash::hash(buffer.getData(), total - HASH_DIGEST_LENGTH, hash);
status = serializer.serialize(hash.getBuffAddr(), HASH_DIGEST_LENGTH, true);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
buffer.setSize(total);
m_interface->send(buffer);
}
bool FprimeDeframing::validate(Types::CircularBuffer& ring, U32 size) {
Utils::Hash hash;
Utils::HashBuffer hashBuffer;
// Initialize the checksum and loop through all bytes calculating it
hash.init();
for (U32 i = 0; i < size; i++) {
U8 byte;
const Fw::SerializeStatus status = ring.peek(byte, i);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
hash.update(&byte, 1);
}
hash.final(hashBuffer);
// Now loop through the hash digest bytes and check for equality
for (U32 i = 0; i < HASH_DIGEST_LENGTH; i++) {
U8 calc = static_cast<char>(hashBuffer.getBuffAddr()[i]);
U8 sent = 0;
const Fw::SerializeStatus status = ring.peek(sent, size + i);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
if (calc != sent) {
return false;
}
}
return true;
}
DeframingProtocol::DeframingStatus FprimeDeframing::deframe(Types::CircularBuffer& ring, U32& needed) {
FpFrameHeader::TokenType start = 0;
FpFrameHeader::TokenType size = 0;
FW_ASSERT(m_interface != nullptr);
// Check for header or ask for more data
if (ring.get_allocated_size() < FpFrameHeader::SIZE) {
needed = FpFrameHeader::SIZE;
return DeframingProtocol::DEFRAMING_MORE_NEEDED;
}
// Read start value from header
Fw::SerializeStatus status = ring.peek(start, 0);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
if (start != FpFrameHeader::START_WORD) {
// Start word must be valid
return DeframingProtocol::DEFRAMING_INVALID_FORMAT;
}
// Read size from header
status = ring.peek(size, sizeof(FpFrameHeader::TokenType));
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
const U32 maxU32 = std::numeric_limits<U32>::max();
if (size > maxU32 - (FpFrameHeader::SIZE + HASH_DIGEST_LENGTH)) {
// Size is too large to process: needed would overflow
return DeframingProtocol::DEFRAMING_INVALID_SIZE;
}
needed = (FpFrameHeader::SIZE + size + HASH_DIGEST_LENGTH);
// Check frame size
const U32 frameSize = size + FpFrameHeader::SIZE + HASH_DIGEST_LENGTH;
if (frameSize > ring.get_capacity()) {
// Frame size is too large for ring buffer
return DeframingProtocol::DEFRAMING_INVALID_SIZE;
}
// Check for enough data to deserialize everything;
// otherwise break and wait for more.
else if (ring.get_allocated_size() < needed) {
return DeframingProtocol::DEFRAMING_MORE_NEEDED;
}
// Check the checksum
if (not this->validate(ring, needed - HASH_DIGEST_LENGTH)) {
return DeframingProtocol::DEFRAMING_INVALID_CHECKSUM;
}
Fw::Buffer buffer = m_interface->allocate(size);
// Some allocators may return buffers larger than requested.
// That causes issues in routing; adjust size.
FW_ASSERT(buffer.getSize() >= size);
buffer.setSize(size);
status = ring.peek(buffer.getData(), size, FpFrameHeader::SIZE);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
m_interface->route(buffer);
return DeframingProtocol::DEFRAMING_STATUS_SUCCESS;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FramingProtocol/DeframingProtocolInterface.hpp | // ======================================================================
// \title DeframingProtocolInterface.hpp
// \author mstarch
// \brief hpp file for deframing protocol interface
//
// \copyright
// Copyright 2009-2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef SVC_DEFRAMING_PROTOCOL_INTERFACE_HPP
#define SVC_DEFRAMING_PROTOCOL_INTERFACE_HPP
#include <Fw/Buffer/Buffer.hpp>
#include <Fw/Time/Time.hpp>
namespace Svc {
/**
* \brief interface supplied to the deframing protocol
*
* In order to supply necessary fprime actions to deframing implementations this class provides
* the necessary functions. Typically the DeframerComponentImpl is the concrete implementor of this
* interface.
*/
class DeframingProtocolInterface {
public:
virtual ~DeframingProtocolInterface(){};
/**
* \brief called to allocate memory, typically delegating to an allocate port call
* \param size: size of the allocation request
* \return Fw::Buffer wrapping allocated memory
*/
virtual Fw::Buffer allocate(const U32 size) = 0;
/**
* \brief send deframed data into the system
* \param data: deframed buffer
*/
virtual void route(Fw::Buffer& data) = 0;
};
}
#endif // SVC_DEFRAMING_PROTOCOL_INTERFACE_HPP
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/FramingProtocol.cpp | // ======================================================================
// \title FramingProtocol.cpp
// \author mstarch
// \brief cpp file for FramingProtocol class
//
// \copyright
// Copyright 2009-2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FramingProtocol.hpp"
#include "FramingProtocolInterface.hpp"
namespace Svc {
FramingProtocol::FramingProtocol() : m_interface(nullptr) {}
void FramingProtocol::setup(FramingProtocolInterface& interface) {
FW_ASSERT(m_interface == nullptr);
m_interface = &interface;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FramingProtocol/FprimeProtocol.hpp | // ======================================================================
// \title FprimeProtocol.hpp
// \author mstarch
// \brief hpp file for FprimeProtocol class
//
// \copyright
// Copyright 2009-2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef SVC_FPRIME_PROTOCOL_HPP
#define SVC_FPRIME_PROTOCOL_HPP
#include <Svc/FramingProtocol/FramingProtocol.hpp>
#include <Svc/FramingProtocol/DeframingProtocol.hpp>
namespace Svc {
// Definitions for the F Prime frame header
namespace FpFrameHeader {
//! Token type for F Prime frame header
typedef U32 TokenType;
enum {
//! Header size for F Prime frame header
SIZE = sizeof(TokenType) * 2
};
//! The start word for F Prime framing
const TokenType START_WORD = static_cast<TokenType>(0xdeadbeef);
}
//! \brief Implements the F Prime framing protocol
class FprimeFraming: public FramingProtocol {
public:
//! Constructor
FprimeFraming();
//! Implements the frame method
void frame(
const U8* const data, //!< The data
const U32 size, //!< The data size in bytes
Fw::ComPacket::ComPacketType packet_type //!< The packet type
) override;
};
//! \brief Implements the F Prime deframing protocol
class FprimeDeframing : public DeframingProtocol {
public:
//! Constructor
FprimeDeframing();
//! Validates data against the stored hash value
//! 1. Computes the hash value V of bytes [0,size-1] in the circular buffer
//! 2. Compares V against bytes [size, size + HASH_DIGEST_LENGTH - 1] of
//! the circular buffer, which are expected to be the stored hash value.
bool validate(
Types::CircularBuffer& buffer, //!< The circular buffer
U32 size //!< The data size in bytes
);
//! Implements the deframe method
//! \return Status
DeframingStatus deframe(
Types::CircularBuffer& buffer, //!< The circular buffer
U32& needed //!< The number of bytes needed, updated by the caller
) override;
};
}
#endif // SVC_FPRIME_PROTOCOL_HPP
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/FramingProtocolInterface.hpp | // ======================================================================
// \title FramingProtocolInterface.hpp
// \author mstarch
// \brief hpp file for framing protocol interface
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef SVC_FRAMING_PROTOCOL_INTERFACE_HPP
#define SVC_FRAMING_PROTOCOL_INTERFACE_HPP
#include <Fw/Buffer/Buffer.hpp>
#include <Fw/Time/Time.hpp>
namespace Svc {
/**
* \brief interface supplied to the framing protocol
*
* In order to supply necessary fprime actions to framing implementations this allows the framing
* implementation to call the functions to delegate the actions. Typically the FramerComponentImpl
* is the concrete implementor of this interface.
*/
class FramingProtocolInterface {
public:
virtual ~FramingProtocolInterface(){};
//! \brief allocation callback to allocate memory when framing
//! \param size: size of the allocation request
//! \return buffer wrapping allocated memory
virtual Fw::Buffer allocate(const U32 size) = 0;
//! \brief send framed data out of the framer
//! \param outgoing: framed data wrapped in an Fw::Buffer
virtual void send(Fw::Buffer& outgoing) = 0;
};
}
#endif // SVC_FRAMING_PROTOCOL_INTERFACE_HPP
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/DeframingProtocol.hpp | // ======================================================================
// \title DeframingProtocol.hpp
// \author mstarch
// \brief hpp file for DeframingProtocol class
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Svc/FramingProtocol/DeframingProtocolInterface.hpp"
#include "Fw/Com/ComPacket.hpp"
#include "Utils/Types/CircularBuffer.hpp"
#ifndef SVC_DEFRAMING_PROTOCOL_HPP
#define SVC_DEFRAMING_PROTOCOL_HPP
namespace Svc {
/**
* \brief Abstract base class representing a deframing protocol
*
* This class represents the basic interface for writing a deframing protocol. This class may be
* subclassed to provide concrete implementations for the protocol. A DeframingProtocolInterface is
* be supplied using the `setup` call. This instance is usually the DeframingComponentImpl.
*
* Implementations are expected to call `m_interface.route` to send the deframed data and may call
* `m_interface.allocate` to allocate new memory.
*/
class DeframingProtocol {
public:
virtual ~DeframingProtocol(){};
/**
* \brief Status of the deframing call
*/
enum DeframingStatus {
DEFRAMING_STATUS_SUCCESS, /*!< Successful deframing */
DEFRAMING_INVALID_SIZE, /*!< Invalid size found */
DEFRAMING_INVALID_CHECKSUM, /*!< Invalid checksum */
DEFRAMING_MORE_NEEDED, /*!< Successful deframing likely with more data */
DEFRAMING_INVALID_FORMAT, /*!< Invalid format */
DEFRAMING_MAX_STATUS /*!< The number of status enumerations */
};
//! Constructor
//!
DeframingProtocol();
//! Setup the deframing protocol with the deframing interface
//!
void setup(DeframingProtocolInterface& interface /*!< Deframing interface */
);
//! Deframe packets from within the circular buffer
//! \return deframing status of this deframe attempt
virtual DeframingStatus deframe(Types::CircularBuffer& buffer, /*!< Deframe from circular buffer */
U32& needed /*!< Return needed number of bytes */
) = 0;
PROTECTED:
DeframingProtocolInterface* m_interface;
};
}
#endif // SVC_DEFRAMING_PROTOCOL_HPP
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/test/ut/main.cpp | #include <limits>
#include "Fw/Test/UnitTest.hpp"
#include "STest/Pick/Pick.hpp"
#include "STest/Random/Random.hpp"
#include "Svc/FramingProtocol/test/ut/DeframingTester.hpp"
#include "Svc/FramingProtocol/test/ut/FramingTester.hpp"
#include "gtest/gtest.h"
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
TEST(Deframing, IncompleteHeader) {
COMMENT("Apply deframing to a frame with an incomplete header");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
// Start word
tester.serializeTokenType(Svc::FpFrameHeader::START_WORD);
U32 needed = 0;
const Svc::DeframingProtocol::DeframingStatus status =
tester.deframe(needed);
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_MORE_NEEDED);
}
TEST(Deframing, InvalidStartWord) {
COMMENT("Apply deframing to a frame with an invalid start word");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
// Start word
tester.serializeTokenType(Svc::FpFrameHeader::START_WORD + 1);
// Packet size
tester.serializeTokenType(0);
U32 needed = 0;
const Svc::DeframingProtocol::DeframingStatus status =
tester.deframe(needed);
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_INVALID_FORMAT);
}
TEST(Deframing, InvalidSizeIntegerOverflow) {
COMMENT("Apply deframing to a frame with an invalid packet size due to integer overflow");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
// Start word
tester.serializeTokenType(Svc::FpFrameHeader::START_WORD);
// Packet size
const U32 maxU32 = std::numeric_limits<U32>::max();
const U32 maxSize = maxU32 - (Svc::FpFrameHeader::SIZE + HASH_DIGEST_LENGTH);
// Make size too big
tester.serializeTokenType(maxSize + 1);
U32 needed = 0;
const Svc::DeframingProtocol::DeframingStatus status =
tester.deframe(needed);
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_INVALID_SIZE);
}
TEST(Deframing, InvalidSizeBufferOverflow) {
COMMENT("Apply deframing to a frame with an invalid packet size due to buffer overflow");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
const Svc::FpFrameHeader::TokenType packetSize = 10;
const U32 frameSize =
Svc::FpFrameHeader::SIZE + packetSize + HASH_DIGEST_LENGTH;
// Make the circular buffer too small to hold the frame
Svc::DeframingTester tester(frameSize - 1);
// Start word
tester.serializeTokenType(Svc::FpFrameHeader::START_WORD);
// Packet size
tester.serializeTokenType(packetSize);
U32 needed = 0;
const Svc::DeframingProtocol::DeframingStatus status =
tester.deframe(needed);
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_INVALID_SIZE);
ASSERT_EQ(needed, frameSize);
}
TEST(Deframing, IncompleteFrame) {
COMMENT("Apply deframing to an incomplete frame");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
const Svc::FpFrameHeader::TokenType packetSize = 1;
Svc::DeframingTester tester;
// Start word
tester.serializeTokenType(Svc::FpFrameHeader::START_WORD);
// Packet size
tester.serializeTokenType(packetSize);
U32 needed = 0;
// Deframe
const Svc::DeframingProtocol::DeframingStatus status =
tester.deframe(needed);
// Check results
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_MORE_NEEDED);
const U32 expectedFrameSize =
Svc::FpFrameHeader::SIZE + packetSize + HASH_DIGEST_LENGTH;
ASSERT_EQ(needed, expectedFrameSize);
}
TEST(Deframing, ZeroPacketSize) {
COMMENT("Apply deframing to a valid frame with packet size zero");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
const U32 packetSize = 0;
tester.testNominalDeframing(packetSize);
}
TEST(Deframing, RandomPacketSize) {
COMMENT("Apply deframing to a valid frame with a random packet size");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
const U32 packetSize = STest::Pick::lowerUpper(
0,
Svc::DeframingTester::MAX_PACKET_SIZE
);
tester.testNominalDeframing(packetSize);
}
TEST(Deframing, MaxPacketSize) {
COMMENT("Apply deframing to a valid frame with maximum packet size for the test buffer");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
const U32 packetSize = Svc::DeframingTester::MAX_PACKET_SIZE;
tester.testNominalDeframing(packetSize);
}
TEST(Deframing, BadChecksum) {
COMMENT("Apply deframing to a frame with a bad checksum");
REQUIREMENT("Svc-FramingProtocol-002");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::DeframingTester tester;
const U32 packetSize = STest::Pick::lowerUpper(
0,
Svc::DeframingTester::MAX_PACKET_SIZE
);
tester.testBadChecksum(packetSize);
}
TEST(Framing, CommandPacket) {
COMMENT("Apply framing to a command packet");
REQUIREMENT("Svc-FramingProtocol-001");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::FramingTester tester(Fw::ComPacket::FW_PACKET_COMMAND);
tester.check();
}
TEST(Framing, FilePacket) {
COMMENT("Apply framing to a file packet");
REQUIREMENT("Svc-FramingProtocol-001");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::FramingTester tester(Fw::ComPacket::FW_PACKET_FILE);
tester.check();
}
TEST(Framing, UnknownPacket) {
COMMENT("Apply framing to a packet of unknown type");
REQUIREMENT("Svc-FramingProtocol-001");
REQUIREMENT("Svc-FramingProtocol-003");
Svc::FramingTester tester(Fw::ComPacket::FW_PACKET_UNKNOWN);
tester.check();
}
// ----------------------------------------------------------------------
// Main function
// ----------------------------------------------------------------------
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/FramingProtocol/test/ut/DeframingTester.cpp | // ======================================================================
// \title DeframingTester.cpp
// \author bocchino
// \brief cpp file for DeframingTester class
// ======================================================================
#include <cstring>
#include "Fw/Types/SerialBuffer.hpp"
#include "STest/Pick/Pick.hpp"
#include "Svc/FramingProtocol/test/ut/DeframingTester.hpp"
#include "Utils/Hash/Hash.hpp"
#include "gtest/gtest.h"
namespace Svc {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
DeframingTester ::
DeframingTester(U32 cbStoreSize) :
frameSize(0),
cbStorage(new U8[cbStoreSize]),
circularBuffer(this->cbStorage, cbStoreSize),
interface(*this)
{
this->fprimeDeframing.setup(this->interface);
memset(this->bufferStorage, 0, sizeof this->bufferStorage);
memset(this->frameData, 0, sizeof this->frameData);
memset(this->cbStorage, 0, cbStoreSize);
}
DeframingTester ::
~DeframingTester()
{
delete[](this->cbStorage);
}
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
DeframingProtocol::DeframingStatus DeframingTester ::
deframe(U32& needed)
{
return this->fprimeDeframing.deframe(this->circularBuffer, needed);
}
void DeframingTester ::
serializeTokenType(FpFrameHeader::TokenType v)
{
U8 buffer[sizeof v];
Fw::SerialBuffer sb(buffer, sizeof buffer);
{
const Fw::SerializeStatus status = sb.serialize(v);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
}
{
const Fw::SerializeStatus status =
this->circularBuffer.serialize(buffer, sizeof buffer);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
}
}
Fw::ByteArray DeframingTester ::
constructRandomFrame(U32 packetSize)
{
FW_ASSERT(packetSize <= MAX_PACKET_SIZE, packetSize, MAX_PACKET_SIZE);
Fw::SerialBuffer sb(this->frameData, sizeof this->frameData);
Fw::SerializeStatus status = Fw::FW_SERIALIZE_OK;
// Serialize the start word
status = sb.serialize(Svc::FpFrameHeader::START_WORD);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
// Serialize the packet size
status = sb.serialize(static_cast<FpFrameHeader::TokenType>(packetSize));
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
// Construct the packet data
for (U32 i = 0; i < packetSize; ++i) {
const U8 byte = static_cast<U8>(STest::Pick::lowerUpper(0, 0xFF));
status = sb.serialize(byte);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
}
const U32 buffLength = sb.getBuffLength();
const U32 dataSize = FpFrameHeader::SIZE + packetSize;
FW_ASSERT(buffLength == dataSize, buffLength, dataSize);
// Compute the hash value
Utils::Hash hash;
Utils::HashBuffer hashBuffer;
hash.init();
hash.update(&this->frameData, dataSize);
hash.final(hashBuffer);
// Copy the hash value into place
const U8 *const buffAddr = hashBuffer.getBuffAddr();
this->frameSize = dataSize + HASH_DIGEST_LENGTH;
FW_ASSERT(this->frameSize <= MAX_FRAME_SIZE);
memcpy(&this->frameData[dataSize], buffAddr, HASH_DIGEST_LENGTH);
// Return the byte array
return Fw::ByteArray(this->frameData, this->frameSize);
}
void DeframingTester ::
pushFrameOntoCB(Fw::ByteArray frame)
{
const Fw::SerializeStatus status =
this->circularBuffer.serialize(frame.bytes, frame.size);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
}
Fw::ByteArray DeframingTester ::
getFrame()
{
return Fw::ByteArray(this->frameData, this->frameSize);
}
void DeframingTester ::
checkPacketData()
{
FW_ASSERT(
this->frameSize <= MAX_FRAME_SIZE,
this->frameSize,
MAX_FRAME_SIZE
);
FW_ASSERT(
this->frameSize >= NON_PACKET_DATA_SIZE,
this->frameSize,
NON_PACKET_DATA_SIZE
);
const U32 packetSize = this->frameSize - NON_PACKET_DATA_SIZE;
Fw::Buffer buffer = this->interface.getRoutedBuffer();
ASSERT_EQ(buffer.getSize(), packetSize);
const int result = memcmp(
&this->frameData[FpFrameHeader::SIZE],
buffer.getData(),
packetSize
);
ASSERT_EQ(result, 0);
}
void DeframingTester ::
testNominalDeframing(U32 packetSize)
{
const Fw::ByteArray frame = this->constructRandomFrame(packetSize);
this->pushFrameOntoCB(frame);
U32 needed;
const Svc::DeframingProtocol::DeframingStatus status =
this->deframe(needed);
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_STATUS_SUCCESS);
ASSERT_EQ(needed, frame.size);
this->checkPacketData();
}
void DeframingTester ::
testBadChecksum(U32 packetSize)
{
const Fw::ByteArray frame = this->constructRandomFrame(packetSize);
const U32 hashOffset = FpFrameHeader::SIZE + packetSize;
++frame.bytes[hashOffset];
this->pushFrameOntoCB(frame);
U32 needed;
const Svc::DeframingProtocol::DeframingStatus status =
this->deframe(needed);
ASSERT_EQ(status, Svc::DeframingProtocol::DEFRAMING_INVALID_CHECKSUM);
}
}
| cpp |
fprime | data/projects/fprime/Svc/FramingProtocol/test/ut/FramingTester.hpp | // ======================================================================
// \title FramingTester.hpp
// \author bocchino
// \brief hpp file for FramingTester class
// ======================================================================
#include "Fw/Types/Assert.hpp"
#include "Fw/Types/SerialBuffer.hpp"
#include "Svc/FramingProtocol/FprimeProtocol.hpp"
#include "Svc/FramingProtocol/FramingProtocol.hpp"
#include "Utils/Hash/Hash.hpp"
namespace Svc {
//! A harness for checking framing
class FramingTester {
private:
// ----------------------------------------------------------------------
// Constants and types
// ----------------------------------------------------------------------
//! The serialized packet type
typedef I32 SerialPacketType;
//! Constants
enum Constants {
//! The maximum buffer size
MAX_BUFFER_SIZE = 1024,
//! The maximum allowed data size
MAX_DATA_SIZE = MAX_BUFFER_SIZE -
FpFrameHeader::SIZE -
sizeof(SerialPacketType) -
HASH_DIGEST_LENGTH,
//! The offset of the start word in an F Prime protocol frame
START_WORD_OFFSET = 0,
//! The offset of the packet size in an F Prime protocol frame
PACKET_SIZE_OFFSET = START_WORD_OFFSET +
sizeof FpFrameHeader::START_WORD,
//! The offset of the packet type in an F Prime protocol frame
PACKET_TYPE_OFFSET = FpFrameHeader::SIZE,
};
//! The framing protocol interface
class Interface :
public FramingProtocolInterface
{
public:
//! Construct an Interface
Interface(
FramingTester& framingTester //!< The enclosing FramingTester
) :
framingTester(framingTester),
sentBuffer(nullptr)
{
}
public:
//! Allocate the buffer
Fw::Buffer allocate(const U32 size) {
FW_ASSERT(size <= MAX_BUFFER_SIZE, size, MAX_BUFFER_SIZE);
Fw::Buffer buffer(this->framingTester.bufferStorage, size);
return buffer;
}
//! Send the buffer
void send(Fw::Buffer& outgoing) {
this->sentBuffer = &outgoing;
}
//! Get the sent buffer
Fw::Buffer *getSentBuffer() {
return this->sentBuffer;
}
private:
//! The enclosing FramingTester
FramingTester& framingTester;
//! The sent buffer
Fw::Buffer *sentBuffer;
};
public:
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Construct a FramingTester
FramingTester(
Fw::ComPacket::ComPacketType packetType //!< The packet type
);
public:
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Check framing
void check();
// ----------------------------------------------------------------------
// Private member functions
// ----------------------------------------------------------------------
private:
//! Get the packet size from the buffer
FpFrameHeader::TokenType getPacketSize();
//! Check the packet size in the buffer
void checkPacketSize(
FpFrameHeader::TokenType packetSize //!< The packet size
);
//! Check the packet type in the buffer
void checkPacketType();
//! Check the start word in the buffer
void checkStartWord();
//! Check the data in the buffer
void checkData();
//! Check the hash value in the buffer
void checkHash(
FpFrameHeader::TokenType packetSize //!< The packet size
);
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The data to frame
U8 data[MAX_DATA_SIZE];
//! The data size in bytes
const U32 dataSize;
//! The packet type
Fw::ComPacket::ComPacketType packetType;
//! Storage for the buffer
U8 bufferStorage[MAX_BUFFER_SIZE];
//! The framing protocol interface
Interface interface;
//! The F Prime framing protocol
FprimeFraming fprimeFraming;
};
}
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/test/ut/DeframingTester.hpp | // ======================================================================
// \title DeframingTester.hpp
// \author bocchino
// \brief hpp file for DeframingTester class
// ======================================================================
#include "Fw/Types/Assert.hpp"
#include "Fw/Types/ByteArray.hpp"
#include "Fw/Types/SerialBuffer.hpp"
#include "Svc/FramingProtocol/FprimeProtocol.hpp"
#include "Svc/FramingProtocol/DeframingProtocol.hpp"
#include "Utils/Hash/Hash.hpp"
#include "Utils/Types/CircularBuffer.hpp"
namespace Svc {
//! A harness for checking deframing
class DeframingTester {
public:
// ----------------------------------------------------------------------
// Constants and types
// ----------------------------------------------------------------------
//! Constants
enum Constants {
//! The maximum frame size
MAX_FRAME_SIZE = 1024,
//! The size of non-packet data in a frame
NON_PACKET_DATA_SIZE = FpFrameHeader::SIZE + HASH_DIGEST_LENGTH,
//! The maximum allowed packet size
MAX_PACKET_SIZE = MAX_FRAME_SIZE - NON_PACKET_DATA_SIZE,
//! The offset of the start word in an F Prime protocol frame
START_WORD_OFFSET = 0,
//! The offset of the packet size in an F Prime protocol frame
PACKET_SIZE_OFFSET = START_WORD_OFFSET +
sizeof FpFrameHeader::START_WORD,
};
//! The deframing protocol interface
class Interface :
public DeframingProtocolInterface
{
public:
//! Construct an Interface
Interface(
DeframingTester& deframingTester //!< The enclosing DeframingTester
) :
deframingTester(deframingTester)
{
}
public:
//! Allocate the buffer
Fw::Buffer allocate(const U32 size) {
FW_ASSERT(size <= MAX_FRAME_SIZE);
Fw::Buffer buffer(this->deframingTester.bufferStorage, size);
return buffer;
}
//! Route the buffer
void route(Fw::Buffer& data) {
this->routedBuffer = data;
}
//! Get the routed buffer
Fw::Buffer getRoutedBuffer() {
return this->routedBuffer;
}
private:
//! The enclosing DeframingTester
DeframingTester& deframingTester;
//! The routed buffer
Fw::Buffer routedBuffer;
};
public:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
//! Construct a DeframingTester
DeframingTester(
U32 cbStoreSize = MAX_FRAME_SIZE //!< The circular buffer store size
);
//! Destroy a DeframingTester
~DeframingTester();
public:
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Call the deframe function of the deframer
DeframingProtocol::DeframingStatus deframe(
U32& needed //!< The number of bytes needed (output)
);
//! Serialize a value of token type into the circular buffer
void serializeTokenType(
FpFrameHeader::TokenType v //!< The value
);
//! Construct a random frame
//! \return An array pointing to frame data owned by DeframingTester.
Fw::ByteArray constructRandomFrame(
U32 packetSize //!< The packet size
);
//! Push a frame onto the circular buffer
void pushFrameOntoCB(
Fw::ByteArray frame //!< The frame
);
//! Get the stored frame
//! \return The frame
Fw::ByteArray getFrame();
//! Check the packet data
void checkPacketData();
//! Test nominal deframing with a valid frame containing random
//! packet data
void testNominalDeframing(
U32 packetSize //!< The packet size
);
//! Test deframing with a frame containing a bad checksum
void testBadChecksum(
U32 packetSize //!< The packet size
);
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! Storage for the buffer
U8 bufferStorage[MAX_FRAME_SIZE];
//! The frame data
U8 frameData[MAX_FRAME_SIZE];
//! The frame size
U32 frameSize;
//! Storage for the circular buffer
U8* cbStorage;
//! The circular buffer
Types::CircularBuffer circularBuffer;
//! The framing protocol interface
Interface interface;
//! The F Prime framing protocol
FprimeDeframing fprimeDeframing;
};
}
| hpp |
fprime | data/projects/fprime/Svc/FramingProtocol/test/ut/FramingTester.cpp | // ======================================================================
// \title FramingTester.cpp
// \author bocchino
// \brief cpp file for FramingTester class
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Svc/FramingProtocol/test/ut/FramingTester.hpp"
#include "gtest/gtest.h"
namespace Svc {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
FramingTester ::
FramingTester(Fw::ComPacket::ComPacketType packetType) :
// Pick a random data size
dataSize(STest::Pick::lowerUpper(1, MAX_DATA_SIZE)),
packetType(packetType),
interface(*this)
{
FW_ASSERT(this->dataSize <= MAX_DATA_SIZE);
this->fprimeFraming.setup(this->interface);
// Fill in random data
for (U32 i = 0; i < sizeof(this->data); ++i) {
this->data[i] = STest::Pick::lowerUpper(0, 0xFF);
}
memset(this->bufferStorage, 0, sizeof this->bufferStorage);
}
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
void FramingTester ::
check()
{
this->fprimeFraming.frame(
this->data,
this->dataSize,
this->packetType
);
// Check that we received a buffer
Fw::Buffer *const sentBuffer = this->interface.getSentBuffer();
ASSERT_NE(sentBuffer, nullptr);
if (sentBuffer != nullptr) {
// Check the start word
this->checkStartWord();
// Check the packet size
const U32 packetSize = this->getPacketSize();
this->checkPacketSize(packetSize);
// Check the packet type
if (this->packetType != Fw::ComPacket::FW_PACKET_UNKNOWN) {
this->checkPacketType();
}
// Check the data
this->checkData();
// Check the hash value
this->checkHash(packetSize);
}
}
// ----------------------------------------------------------------------
// Private member functions
// ----------------------------------------------------------------------
FpFrameHeader::TokenType FramingTester ::
getPacketSize()
{
FpFrameHeader::TokenType packetSize = 0;
Fw::SerialBuffer sb(
&this->bufferStorage[PACKET_SIZE_OFFSET],
sizeof packetSize
);
sb.fill();
const Fw::SerializeStatus status = sb.deserialize(packetSize);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
return packetSize;
}
void FramingTester ::
checkPacketSize(FpFrameHeader::TokenType packetSize)
{
U32 expectedPacketSize = this->dataSize;
if (this->packetType != Fw::ComPacket::FW_PACKET_UNKNOWN) {
// Packet type is stored in header
expectedPacketSize += sizeof(SerialPacketType);
}
ASSERT_EQ(packetSize, expectedPacketSize);
}
void FramingTester ::
checkPacketType()
{
SerialPacketType serialPacketType = 0;
Fw::SerialBuffer sb(
&this->bufferStorage[PACKET_TYPE_OFFSET],
sizeof serialPacketType
);
sb.fill();
const Fw::SerializeStatus status = sb.deserialize(serialPacketType);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
typedef Fw::ComPacket::ComPacketType PacketType;
const PacketType pt = static_cast<PacketType>(serialPacketType);
ASSERT_EQ(pt, this->packetType);
}
void FramingTester ::
checkStartWord()
{
FpFrameHeader::TokenType startWord = 0;
Fw::SerialBuffer sb(
&this->bufferStorage[START_WORD_OFFSET],
sizeof startWord
);
sb.fill();
const Fw::SerializeStatus status = sb.deserialize(startWord);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK, status);
ASSERT_EQ(startWord, FpFrameHeader::START_WORD);
}
void FramingTester ::
checkData()
{
U32 dataOffset = PACKET_TYPE_OFFSET;
if (this->packetType != Fw::ComPacket::FW_PACKET_UNKNOWN) {
// Packet type is stored in header
dataOffset += sizeof(SerialPacketType);
}
const I32 result = memcmp(
this->data,
&this->bufferStorage[dataOffset],
this->dataSize
);
ASSERT_EQ(result, 0);
}
void FramingTester ::
checkHash(FpFrameHeader::TokenType packetSize)
{
Utils::Hash hash;
Utils::HashBuffer hashBuffer;
const U32 dataSize = FpFrameHeader::SIZE + packetSize;
hash.update(this->bufferStorage, dataSize);
hash.final(hashBuffer);
const U8 *const hashAddr = hashBuffer.getBuffAddr();
const I32 result = memcmp(
&this->bufferStorage[dataSize],
hashAddr,
HASH_DIGEST_LENGTH
);
ASSERT_EQ(result, 0);
}
}
| cpp |
fprime | data/projects/fprime/Svc/TlmChan/TlmChan.cpp | /**
* \file
* \author T. Canham
* \brief Implementation file for channelized telemetry storage component
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
* <br /><br />
*/
#include <FpConfig.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Fw/Types/Assert.hpp>
#include <Svc/TlmChan/TlmChan.hpp>
namespace Svc {
TlmChan::TlmChan(const char* name) : TlmChanComponentBase(name), m_activeBuffer(0) {
// clear slot pointers
for (NATIVE_UINT_TYPE entry = 0; entry < TLMCHAN_NUM_TLM_HASH_SLOTS; entry++) {
this->m_tlmEntries[0].slots[entry] = nullptr;
this->m_tlmEntries[1].slots[entry] = nullptr;
}
// clear buckets
for (NATIVE_UINT_TYPE entry = 0; entry < TLMCHAN_HASH_BUCKETS; entry++) {
this->m_tlmEntries[0].buckets[entry].used = false;
this->m_tlmEntries[0].buckets[entry].updated = false;
this->m_tlmEntries[0].buckets[entry].bucketNo = entry;
this->m_tlmEntries[0].buckets[entry].next = nullptr;
this->m_tlmEntries[0].buckets[entry].id = 0;
this->m_tlmEntries[1].buckets[entry].used = false;
this->m_tlmEntries[1].buckets[entry].updated = false;
this->m_tlmEntries[1].buckets[entry].bucketNo = entry;
this->m_tlmEntries[1].buckets[entry].next = nullptr;
this->m_tlmEntries[1].buckets[entry].id = 0;
}
// clear free index
this->m_tlmEntries[0].free = 0;
this->m_tlmEntries[1].free = 0;
}
TlmChan::~TlmChan() {}
void TlmChan::init(NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
NATIVE_INT_TYPE instance /*!< The instance number*/
) {
TlmChanComponentBase::init(queueDepth, instance);
}
NATIVE_UINT_TYPE TlmChan::doHash(FwChanIdType id) {
return (id % TLMCHAN_HASH_MOD_VALUE) % TLMCHAN_NUM_TLM_HASH_SLOTS;
}
void TlmChan::pingIn_handler(const NATIVE_INT_TYPE portNum, U32 key) {
// return key
this->pingOut_out(0, key);
}
void TlmChan::TlmGet_handler(NATIVE_INT_TYPE portNum, FwChanIdType id, Fw::Time& timeTag, Fw::TlmBuffer& val) {
// Compute index for entry
NATIVE_UINT_TYPE index = this->doHash(id);
// Search to see if channel has been stored
TlmEntry* entryToUse = this->m_tlmEntries[this->m_activeBuffer].slots[index];
for (NATIVE_UINT_TYPE bucket = 0; bucket < TLMCHAN_HASH_BUCKETS; bucket++) {
if (entryToUse) { // If bucket exists, check id
if (entryToUse->id == id) {
break;
} else { // otherwise go to next bucket
entryToUse = entryToUse->next;
}
} else { // no buckets left to search
break;
}
}
if (entryToUse) {
val = entryToUse->buffer;
timeTag = entryToUse->lastUpdate;
} else { // requested entry may not be written yet; empty buffer
val.resetSer();
}
}
void TlmChan::TlmRecv_handler(NATIVE_INT_TYPE portNum, FwChanIdType id, Fw::Time& timeTag, Fw::TlmBuffer& val) {
// Compute index for entry
NATIVE_UINT_TYPE index = this->doHash(id);
TlmEntry* entryToUse = nullptr;
TlmEntry* prevEntry = nullptr;
// Search to see if channel has already been stored or a bucket needs to be added
if (this->m_tlmEntries[this->m_activeBuffer].slots[index]) {
entryToUse = this->m_tlmEntries[this->m_activeBuffer].slots[index];
for (NATIVE_UINT_TYPE bucket = 0; bucket < TLMCHAN_HASH_BUCKETS; bucket++) {
if (entryToUse) {
if (entryToUse->id == id) { // found the matching entry
break;
} else { // try next entry
prevEntry = entryToUse;
entryToUse = entryToUse->next;
}
} else {
// Make sure that we haven't run out of buckets
FW_ASSERT(this->m_tlmEntries[this->m_activeBuffer].free < TLMCHAN_HASH_BUCKETS);
// add new bucket from free list
entryToUse =
&this->m_tlmEntries[this->m_activeBuffer].buckets[this->m_tlmEntries[this->m_activeBuffer].free++];
FW_ASSERT(prevEntry);
prevEntry->next = entryToUse;
// clear next pointer
entryToUse->next = nullptr;
break;
}
}
} else {
// Make sure that we haven't run out of buckets
FW_ASSERT(this->m_tlmEntries[this->m_activeBuffer].free < TLMCHAN_HASH_BUCKETS);
// create new entry at slot head
this->m_tlmEntries[this->m_activeBuffer].slots[index] =
&this->m_tlmEntries[this->m_activeBuffer].buckets[this->m_tlmEntries[this->m_activeBuffer].free++];
entryToUse = this->m_tlmEntries[this->m_activeBuffer].slots[index];
entryToUse->next = nullptr;
}
// copy into entry
FW_ASSERT(entryToUse);
entryToUse->used = true;
entryToUse->id = id;
entryToUse->updated = true;
entryToUse->lastUpdate = timeTag;
entryToUse->buffer = val;
}
void TlmChan::Run_handler(NATIVE_INT_TYPE portNum, U32 context) {
// Only write packets if connected
if (not this->isConnected_PktSend_OutputPort(0)) {
return;
}
// lock mutex long enough to modify active telemetry buffer
// so the data can be read without worrying about updates
this->lock();
this->m_activeBuffer = 1 - this->m_activeBuffer;
// set activeBuffer to not updated
for (U32 entry = 0; entry < TLMCHAN_HASH_BUCKETS; entry++) {
this->m_tlmEntries[this->m_activeBuffer].buckets[entry].updated = false;
}
this->unLock();
// go through each entry and send a packet if it has been updated
Fw::TlmPacket pkt;
pkt.resetPktSer();
for (U32 entry = 0; entry < TLMCHAN_HASH_BUCKETS; entry++) {
TlmEntry* p_entry = &this->m_tlmEntries[1 - this->m_activeBuffer].buckets[entry];
if ((p_entry->updated) && (p_entry->used)) {
Fw::SerializeStatus stat = pkt.addValue(p_entry->id, p_entry->lastUpdate, p_entry->buffer);
// check to see if this packet is full, if so, send it
if (Fw::FW_SERIALIZE_NO_ROOM_LEFT == stat) {
this->PktSend_out(0, pkt.getBuffer(), 0);
// reset packet for more entries
pkt.resetPktSer();
// add entry to new packet
stat = pkt.addValue(p_entry->id, p_entry->lastUpdate, p_entry->buffer);
// if this doesn't work, that means packet isn't big enough for
// even one channel, so assert
FW_ASSERT(Fw::FW_SERIALIZE_OK == stat, static_cast<NATIVE_INT_TYPE>(stat));
} else if (Fw::FW_SERIALIZE_OK == stat) {
// if there was still room, do nothing move on to the next channel in the packet
} else // any other status is an assert, since it shouldn't happen
{
FW_ASSERT(0, static_cast<NATIVE_INT_TYPE>(stat));
}
// flag as updated
p_entry->updated = false;
} // end if entry was updated
} // end for each entry
// send remnant entries
if (pkt.getNumEntries() > 0) {
this->PktSend_out(0, pkt.getBuffer(), 0);
}
} // end run handler
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/TlmChan/TlmChan.hpp | /**
* \file
* \author T. Canham
* \brief Component that stores telemetry channel values
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
* <br /><br />
*/
#ifndef TELEMCHANIMPL_HPP_
#define TELEMCHANIMPL_HPP_
#include <Fw/Tlm/TlmPacket.hpp>
#include <Svc/TlmChan/TlmChanComponentAc.hpp>
#include <TlmChanImplCfg.hpp>
namespace Svc {
class TlmChan : public TlmChanComponentBase {
public:
TlmChan(const char* compName);
virtual ~TlmChan();
void init(NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
NATIVE_INT_TYPE instance /*!< The instance number*/
);
PROTECTED:
// can be overridden for alternate algorithms
virtual NATIVE_UINT_TYPE doHash(FwChanIdType id);
PRIVATE:
// Port functions
void TlmRecv_handler(NATIVE_INT_TYPE portNum, FwChanIdType id, Fw::Time& timeTag, Fw::TlmBuffer& val);
void TlmGet_handler(NATIVE_INT_TYPE portNum, FwChanIdType id, Fw::Time& timeTag, Fw::TlmBuffer& val);
void Run_handler(NATIVE_INT_TYPE portNum, U32 context);
//! Handler implementation for pingIn
//!
void pingIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
typedef struct tlmEntry {
FwChanIdType id; //!< telemetry id stored in slot
bool updated; //!< set whenever a value has been written. Used to skip if writing out values for downlinking
Fw::Time lastUpdate; //!< last updated time
Fw::TlmBuffer buffer; //!< buffer to store serialized telemetry
tlmEntry* next; //!< pointer to next bucket in table
bool used; //!< if entry has been used
NATIVE_UINT_TYPE bucketNo; //!< for testing
} TlmEntry;
struct TlmSet {
TlmEntry* slots[TLMCHAN_NUM_TLM_HASH_SLOTS]; //!< set of hash slots in hash table
TlmEntry buckets[TLMCHAN_HASH_BUCKETS]; //!< set of buckets used in hash table
NATIVE_INT_TYPE free; //!< next free bucket
} m_tlmEntries[2];
U32 m_activeBuffer; // !< which buffer is active for storing telemetry
};
} // namespace Svc
#endif /* TELEMCHANIMPL_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/TlmChan/test/ut/TlmChanMain.cpp | /*
* Main.cpp
*
* Created on: Mar 18, 2015
* Updated: 6/22/2022
* Author: tcanham
*/
#include <gtest/gtest.h>
#include <Fw/Test/UnitTest.hpp>
#include <Svc/TlmChan/TlmChan.hpp>
#include "TlmChanTester.hpp"
TEST(TlmChanTest, InitTest) {
Svc::TlmChanTester tester;
}
TEST(TlmChanTest, NominalChannelTest) {
TEST_CASE(107.1.1, "Nominal channelized telemetry");
COMMENT("Write a single channel and verify it is read back and pushed correctly.");
Svc::TlmChanTester tester;
// run test
tester.runNominalChannel();
}
TEST(TlmChanTest, MultiChannelTest) {
TEST_CASE(107.1.2, "Nominal Multi-channel channelized telemetry");
COMMENT("Write multiple channels and verify they are read back and pushed correctly.");
Svc::TlmChanTester tester;
// run test
tester.runMultiChannel();
}
TEST(TlmChanTest, OffNominal) {
TEST_CASE(107.2.1, "Off-nominal channelized telemetry");
COMMENT("Attempt to read a channel that hasn't been written.");
Svc::TlmChanTester tester;
// run test
tester.runOffNominal();
}
// TEST(TlmChanTest,TooManyChannels) {
// COMMENT("Too Many Channel Test");
// Svc::TlmChanImpl impl("TlmChanImpl");
// impl.init(10,0);
// Svc::TlmChanImplTester tester(impl);
// tester.init();
// // connect ports
// connectPorts(impl,tester);
// // run test
// tester.runTooManyChannels();
// }
| cpp |
fprime | data/projects/fprime/Svc/TlmChan/test/ut/TlmChanTester.cpp | // ======================================================================
// \title TlmChan.hpp
// \author tcanham
// \brief cpp file for TlmChan test harness implementation class
// ======================================================================
#include "TlmChanTester.hpp"
#include <Fw/Test/UnitTest.hpp>
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
#define QUEUE_DEPTH 10
static const NATIVE_UINT_TYPE TEST_CHAN_SIZE = sizeof(FwChanIdType) + Fw::Time::SERIALIZED_SIZE + sizeof(U32);
static const NATIVE_UINT_TYPE CHANS_PER_COMBUFFER =
(FW_COM_BUFFER_MAX_SIZE - sizeof(FwPacketDescriptorType)) / TEST_CHAN_SIZE;
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
TlmChanTester ::TlmChanTester()
: TlmChanGTestBase("Tester", MAX_HISTORY_SIZE), component("TlmChan"), m_numBuffs(0), m_bufferRecv(false) {
this->initComponents();
this->connectPorts();
}
TlmChanTester ::~TlmChanTester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void TlmChanTester::runNominalChannel() {
this->clearBuffs();
// send first buffer
this->sendBuff(27, 10);
this->doRun(true);
this->checkBuff(0, 1, 27, 10);
this->clearBuffs();
// send again to other buffer
this->sendBuff(27, 10);
static bool tlc003 = false;
if (not tlc003) {
REQUIREMENT("TLC-003");
tlc003 = true;
}
this->doRun(true);
this->checkBuff(0, 1, 27, 10);
// do an update to make sure it gets updated and returned correctly
this->clearBuffs();
this->sendBuff(27, 20);
}
void TlmChanTester::runMultiChannel() {
FwChanIdType ID_0[] = {// Test channel IDs
0x1000, 0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x1100, 0x1101, 0x1102, 0x1103, 0x300,
0x301, 0x400, 0x401, 0x402, 0x100, 0x101, 0x102, 0x103, 0x104, 0x105};
this->clearBuffs();
// send all updates
for (NATIVE_UINT_TYPE n = 0; n < FW_NUM_ARRAY_ELEMENTS(ID_0); n++) {
this->sendBuff(ID_0[n], n);
}
ASSERT_EQ(0, this->component.m_activeBuffer);
// do a run, and all the packets should be sent
this->doRun(true);
ASSERT_TRUE(this->m_bufferRecv);
ASSERT_EQ((FW_NUM_ARRAY_ELEMENTS(ID_0) / CHANS_PER_COMBUFFER) + 1, this->m_numBuffs);
ASSERT_EQ(1, this->component.m_activeBuffer);
// verify packets
for (NATIVE_UINT_TYPE n = 0; n < FW_NUM_ARRAY_ELEMENTS(ID_0); n++) {
// printf("#: %d\n",n);
this->checkBuff(n, FW_NUM_ARRAY_ELEMENTS(ID_0), ID_0[n], n);
}
// send another set
FwChanIdType ID_1[] = {// Test channel IDs
0x5000, 0x5001, 0x5002, 0x5003, 0x5004, 0x5005, 0x5100, 0x5101, 0x5102,
0x5103, 0x6300, 0x6301, 0x6400, 0x6401, 0x6402, 0x6100, 0x6101, 0x6102,
0x6103, 0x6104, 0x6105, 0x8101, 0x8102, 0x8103, 0x8104, 0x8105};
this->clearBuffs();
// send all updates
for (NATIVE_UINT_TYPE n = 0; n < FW_NUM_ARRAY_ELEMENTS(ID_1); n++) {
this->sendBuff(ID_1[n], n);
}
ASSERT_EQ(1, this->component.m_activeBuffer);
// do a run, and all the packets should be sent
this->doRun(true);
ASSERT_TRUE(this->m_bufferRecv);
ASSERT_EQ((FW_NUM_ARRAY_ELEMENTS(ID_1) / CHANS_PER_COMBUFFER) + 1, this->m_numBuffs);
ASSERT_EQ(0, this->component.m_activeBuffer);
// verify packets
for (NATIVE_UINT_TYPE n = 0; n < FW_NUM_ARRAY_ELEMENTS(ID_1); n++) {
// printf("#: %d\n",n);
this->checkBuff(n, FW_NUM_ARRAY_ELEMENTS(ID_1), ID_1[n], n);
}
}
void TlmChanTester::runOffNominal() {
// Ask for a packet that isn't written yet
Fw::TlmBuffer buff;
Fw::SerializeStatus stat;
Fw::Time timeTag;
U32 val = 10;
// create Telemetry item and put dummy data in to make sure it gets erased
buff.resetSer();
stat = buff.serialize(val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, stat);
// Read back value
this->invoke_to_TlmGet(0, 10, timeTag, buff);
ASSERT_EQ(0u, buff.getBuffLength());
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void TlmChanTester ::from_PktSend_handler(const NATIVE_INT_TYPE portNum, Fw::ComBuffer& data, U32 context) {
this->pushFromPortEntry_PktSend(data, context);
this->m_bufferRecv = true;
this->m_rcvdBuffer[this->m_numBuffs] = data;
this->m_numBuffs++;
}
void TlmChanTester ::from_pingOut_handler(const NATIVE_INT_TYPE portNum, U32 key) {
this->pushFromPortEntry_pingOut(key);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
bool TlmChanTester::doRun(bool check) {
// execute run port to send packet
this->invoke_to_Run(0, 0);
// dispatch run message
this->m_bufferRecv = false;
this->component.doDispatch();
if (check) {
EXPECT_TRUE(this->m_bufferRecv);
}
return this->m_bufferRecv;
}
void TlmChanTester::checkBuff(NATIVE_UINT_TYPE chanNum, NATIVE_UINT_TYPE totalChan, FwChanIdType id, U32 val) {
Fw::Time timeTag;
// deserialize packet
Fw::SerializeStatus stat;
static bool tlc004 = false;
if (not tlc004) {
REQUIREMENT("TLC-004");
tlc004 = true;
}
NATIVE_UINT_TYPE currentChan = 0;
// Search for channel ID
for (NATIVE_UINT_TYPE packet = 0; packet < this->m_numBuffs; packet++) {
// Look at packet descriptor for current packet
this->m_rcvdBuffer[packet].resetDeser();
// first piece should be tlm packet descriptor
FwPacketDescriptorType desc;
stat = this->m_rcvdBuffer[packet].deserialize(desc);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, stat);
ASSERT_EQ(desc, static_cast<FwPacketDescriptorType>(Fw::ComPacket::FW_PACKET_TELEM));
for (NATIVE_UINT_TYPE chan = 0; chan < CHANS_PER_COMBUFFER; chan++) {
// decode channel ID
FwEventIdType sentId;
stat = this->m_rcvdBuffer[packet].deserialize(sentId);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, stat);
// next piece is time tag
Fw::Time recTimeTag(TB_NONE, 0, 0);
stat = this->m_rcvdBuffer[packet].deserialize(recTimeTag);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, stat);
ASSERT_TRUE(timeTag == recTimeTag);
// next piece is event argument
U32 readVal;
stat = this->m_rcvdBuffer[packet].deserialize(readVal);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, stat);
if (chanNum == currentChan) {
ASSERT_EQ(id, sentId);
ASSERT_EQ(val, readVal);
}
// quit if we are at max channel entry
if (currentChan == (totalChan - 1)) {
break;
}
currentChan++;
}
// packet should be empty
ASSERT_EQ(0, this->m_rcvdBuffer[packet].getBuffLeft());
}
}
void TlmChanTester::sendBuff(FwChanIdType id, U32 val) {
Fw::TlmBuffer buff;
Fw::TlmBuffer readBack;
Fw::SerializeStatus stat;
Fw::Time timeTag;
U32 retestVal;
// create telemetry item
buff.resetSer();
stat = buff.serialize(val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, stat);
static bool tlc001 = false;
if (not tlc001) {
REQUIREMENT("TLC-001");
tlc001 = true;
}
this->invoke_to_TlmRecv(0, id, timeTag, buff);
// Read back value
static bool tlc002 = false;
if (not tlc002) {
REQUIREMENT("TLC-002");
tlc002 = true;
}
this->invoke_to_TlmGet(0, id, timeTag, readBack);
// deserialize value
retestVal = 0;
readBack.deserialize(retestVal);
ASSERT_EQ(retestVal, val);
}
void TlmChanTester::clearBuffs() {
this->m_numBuffs = 0;
for (NATIVE_INT_TYPE n = 0; n < TLMCHAN_HASH_BUCKETS; n++) {
this->m_rcvdBuffer[n].resetSer();
}
}
void TlmChanTester::dumpTlmEntry(TlmChan::TlmEntry* entry) {
printf(
"Entry "
" Ptr: %p"
" id: 0x%08X"
" bucket: %d"
" next: %p\n",
static_cast<void*>(entry), entry->id, entry->bucketNo, static_cast<void*>(entry->next));
}
void TlmChanTester::dumpHash() {
// printf("**Buffer 0\n");
for (NATIVE_INT_TYPE slot = 0; slot < TLMCHAN_NUM_TLM_HASH_SLOTS; slot++) {
printf("Slot: %d\n", slot);
if (this->component.m_tlmEntries[0].slots[slot]) {
TlmChan::TlmEntry* entry = component.m_tlmEntries[0].slots[slot];
for (NATIVE_INT_TYPE bucket = 0; bucket < TLMCHAN_HASH_BUCKETS; bucket++) {
dumpTlmEntry(entry);
if (entry->next == nullptr) {
break;
} else {
entry = entry->next;
}
}
} else {
printf("EMPTY\n");
}
}
printf("\n");
// for (NATIVE_INT_TYPE bucket = 0; bucket < TLMCHAN_HASH_BUCKETS; bucket++) {
// printf("Bucket: %d ",bucket);
// dumpTlmEntry(&m_impl.m_tlmEntries[0].buckets[bucket]);
// }
// printf("**Buffer 1\n");
// for (NATIVE_INT_TYPE slot = 0; slot < TLMCHAN_NUM_TLM_HASH_SLOTS; slot++) {
// printf("Slot: %d\n",slot);
// if (m_impl.m_tlmEntries[1].slots[slot]) {
// TlmChanImpl::TlmEntry* entry = m_impl.m_tlmEntries[1].slots[slot];
// for (NATIVE_INT_TYPE bucket = 0; bucket < TLMCHAN_HASH_BUCKETS; bucket++) {
// dumpTlmEntry(entry);
// if (entry->next == 0) {
// break;
// } else {
// entry = entry->next;
// }
// }
// } else {
// printf("EMPTY\n");
// }
// }
// printf("\n");
// for (NATIVE_INT_TYPE bucket = 0; bucket < TLMCHAN_HASH_BUCKETS; bucket++) {
// printf("Bucket: %d\n",bucket);
// dumpTlmEntry(&m_impl.m_tlmEntries[1].buckets[bucket]);
// }
}
void TlmChanTester ::connectPorts() {
// Run
this->connect_to_Run(0, this->component.get_Run_InputPort(0));
// TlmGet
this->connect_to_TlmGet(0, this->component.get_TlmGet_InputPort(0));
// TlmRecv
this->connect_to_TlmRecv(0, this->component.get_TlmRecv_InputPort(0));
// pingIn
this->connect_to_pingIn(0, this->component.get_pingIn_InputPort(0));
// PktSend
this->component.set_PktSend_OutputPort(0, this->get_from_PktSend(0));
// pingOut
this->component.set_pingOut_OutputPort(0, this->get_from_pingOut(0));
}
void TlmChanTester ::initComponents() {
this->init();
this->component.init(QUEUE_DEPTH, INSTANCE);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/TlmChan/test/ut/TlmChanTester.hpp | // ======================================================================
// \title TlmChan/test/ut/Tester.hpp
// \author tcanham
// \brief hpp file for TlmChan test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "TlmChanGTestBase.hpp"
#include "Svc/TlmChan/TlmChan.hpp"
namespace Svc {
class TlmChanTester : public TlmChanGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object TlmChanTester
//!
TlmChanTester();
//! Destroy object TlmChanTester
//!
~TlmChanTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void runNominalChannel();
void runMultiChannel();
void runOffNominal();
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_PktSend
//!
void from_PktSend_handler(const NATIVE_INT_TYPE portNum, //!< The port number
Fw::ComBuffer& data, //!< Buffer containing packet data
U32 context //!< Call context value; meaning chosen by user
);
//! Handler for from_pingOut
//!
void from_pingOut_handler(const NATIVE_INT_TYPE portNum, //!< The port number
U32 key //!< Value to return to pinger
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
void sendBuff(FwChanIdType id, U32 val);
bool doRun(bool check);
void checkBuff(NATIVE_UINT_TYPE chanNum, NATIVE_UINT_TYPE totalChan, FwChanIdType id, U32 val);
void clearBuffs();
// dump functions
void dumpHash();
static void dumpTlmEntry(TlmChan::TlmEntry* entry);
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
TlmChan component;
// Keep a history
NATIVE_UINT_TYPE m_numBuffs;
Fw::ComBuffer m_rcvdBuffer[TLMCHAN_HASH_BUCKETS];
bool m_bufferRecv;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferManager/BufferManagerComponentImpl.hpp | // ======================================================================
// \title BufferManagerComponentImpl.hpp
// \author tcanham
// \brief hpp file for BufferManager component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef BufferManager_HPP
#define BufferManager_HPP
#include "Svc/BufferManager/BufferManagerComponentAc.hpp"
#include <Fw/Types/MemAllocator.hpp>
#include "BufferManagerComponentImplCfg.hpp"
namespace Svc
{
// To use the class, instantiate an instance of the BufferBins struct below. This
// table specifies N buffers of M size per bin. Up to MAX_NUM_BINS bins can be specified.
// The table is copied when setup() is called, so it does not need to be retained after
// the call.
//
// The rules for specifying bins:
// 1. For each bin (BufferBins.bins[n]), specify the size of the buffers (bufferSize) in the
// bin and how many buffers for that bin (numBuffers).
// 2. The bins should be ordered based on an increasing bufferSize to allow BufferManager to
// search for available buffers. When receiving a request for a buffer, the component will
// search for the first buffer from the bins that is equal to or greater
// than the requested size, starting at the beginning of the table.
// 3. Any unused bins should have numBuffers set to 0.
// 4. A single bin can be specified if a single size is needed.
//
// If a buffer is requested that can't be found among available buffers, the call will
// return an Fw::Buffer with a size of zero. It is expected that the user will notice
// and have the appropriate response for the design. If an empty buffer is returned to
// the BufferManager instance, a warning event will be issued but no other action will
// be taken.
//
// Buffer manager will assert under the following conditions:
// 1. A returned buffer has the incorrect manager ID.
// 2. A returned buffer has an incorrect buffer ID.
// 3. A returned buffer is returned with a correct buffer ID, but it isn't already allocated.
// 4. A returned buffer has an indicated size larger than originally allocated.
// 5. A returned buffer has a pointer different than the one originally allocated.
//
// Note that a pointer to the Fw::MemAllocator used in setup() is stored for later memory cleanup.
// The instance of the allocator must persist beyond calling the cleanup() function or the
// destructor of BufferManager if cleanup() is not called. If a project-specific manual memory
// allocator is not needed, Fw::MallocAllocator can be used.
class BufferManagerComponentImpl : public BufferManagerComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object BufferManager
//!
BufferManagerComponentImpl(
const char *const compName /*!< The component name*/
);
//! Initialize object BufferManager
//!
void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
// Defines a buffer bin
struct BufferBin
{
NATIVE_UINT_TYPE bufferSize; //!< size of the buffers in this bin. Set to zero for unused bins.
NATIVE_UINT_TYPE numBuffers; //!< number of buffers in this bin. Set to zero for unused bins.
};
// Set of bins for the BufferManager
struct BufferBins
{
BufferBin bins[BUFFERMGR_MAX_NUM_BINS]; //!< set of bins to define buffers
};
//! set up configuration
void setup(
NATIVE_UINT_TYPE mgrID, //!< ID of manager for buffer checking
NATIVE_UINT_TYPE memID, //!< Memory segment identifier
Fw::MemAllocator &allocator, //!< memory allocator. MUST be persistent for later deallocation.
//! MUST persist past destructor if cleanup() not called explicitly.
const BufferBins &bins //!< Set of user bins
);
void cleanup(); // Free memory prior to end of program if desired. Otherwise,
// will be deleted in destructor
//! Destroy object BufferManager
//!
~BufferManagerComponentImpl();
PRIVATE :
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for bufferSendIn
//!
void
bufferSendIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer);
//! Handler implementation for bufferGetCallee
//!
Fw::Buffer bufferGetCallee_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 size);
//! Handler implementation for schedIn
//!
void schedIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!< The call order*/
);
bool m_setup; //!< flag to indicate component has been setup
bool m_cleaned; //!< flag to indicate memory has been cleaned up
NATIVE_UINT_TYPE m_mgrId; //!< stored manager ID for buffer checking
BufferBins m_bufferBins; //!< copy of bins supplied by user
struct AllocatedBuffer
{
Fw::Buffer buff; //!< Buffer class to give to user
U8 *memory; //!< pointer to memory buffer
U32 size; //!< size of the buffer
bool allocated; //!< this buffer has been allocated
};
AllocatedBuffer *m_buffers; //!< pointer to allocated buffer space
Fw::MemAllocator *m_allocator; //!< allocator for memory
NATIVE_UINT_TYPE m_memId; //!< identifier for allocator
NATIVE_UINT_TYPE m_numStructs; //!< number of allocated structs
// stats
U32 m_highWater; //!< high watermark for allocations
U32 m_currBuffs; //!< number of currently allocated buffers
U32 m_noBuffs; //!< number of failures to allocate a buffer
U32 m_emptyBuffs; //!< number of empty buffers returned
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferManager/BufferManagerComponentImpl.cpp | // ======================================================================
// \title BufferManagerComponentImpl.cpp
// \author tcanham
// \brief cpp file for BufferManager component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Svc/BufferManager/BufferManagerComponentImpl.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Buffer/Buffer.hpp>
#include <new>
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
BufferManagerComponentImpl ::
BufferManagerComponentImpl(
const char *const compName
) : BufferManagerComponentBase(compName)
,m_setup(false)
,m_cleaned(false)
,m_mgrId(0)
,m_buffers(nullptr)
,m_allocator(nullptr)
,m_memId(0)
,m_numStructs(0)
,m_highWater(0)
,m_currBuffs(0)
,m_noBuffs(0)
,m_emptyBuffs(0)
{
}
void BufferManagerComponentImpl ::
init(
const NATIVE_INT_TYPE instance
)
{
BufferManagerComponentBase::init(instance);
}
BufferManagerComponentImpl ::
~BufferManagerComponentImpl()
{
if (m_setup) {
this->cleanup();
}
}
void BufferManagerComponentImpl ::
cleanup()
{
FW_ASSERT(this->m_buffers);
FW_ASSERT(this->m_allocator);
if (not this->m_cleaned) {
// walk through Fw::Buffer instances and delete them
for (NATIVE_UINT_TYPE entry = 0; entry < this->m_numStructs; entry++) {
this->m_buffers[entry].buff.~Buffer();
}
this->m_cleaned = true;
// release memory
this->m_allocator->deallocate(this->m_memId,this->m_buffers);
this->m_setup = false;
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void BufferManagerComponentImpl ::
bufferSendIn_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
// make sure component has been set up
FW_ASSERT(this->m_setup);
FW_ASSERT(m_buffers);
// check for empty buffers - this is just a warning since this component returns
// empty buffers if it can't allocate one.
if (fwBuffer.getSize() == 0) {
this->log_WARNING_HI_ZeroSizeBuffer();
this->m_emptyBuffs++;
return;
}
// use the bufferID member field to find the original slot
U32 context = fwBuffer.getContext();
U32 id = context & 0xFFFF;
U32 mgrId = context >> 16;
// check some things
FW_ASSERT(id < this->m_numStructs,id,this->m_numStructs);
FW_ASSERT(mgrId == this->m_mgrId,mgrId,id,this->m_mgrId);
FW_ASSERT(true == this->m_buffers[id].allocated,id,this->m_mgrId);
FW_ASSERT(reinterpret_cast<U8*>(fwBuffer.getData()) >= this->m_buffers[id].memory,id,this->m_mgrId);
FW_ASSERT(reinterpret_cast<U8*>(fwBuffer.getData()) < (this->m_buffers[id].memory + this->m_buffers[id].size),id,this->m_mgrId);
// user can make smaller for their own purposes, but it shouldn't be bigger
FW_ASSERT(fwBuffer.getSize() <= this->m_buffers[id].size,id,this->m_mgrId);
// clear the allocated flag
this->m_buffers[id].allocated = false;
this->m_currBuffs--;
}
Fw::Buffer BufferManagerComponentImpl ::
bufferGetCallee_handler(
const NATIVE_INT_TYPE portNum,
U32 size
)
{
// make sure component has been set up
FW_ASSERT(this->m_setup);
FW_ASSERT(m_buffers);
// find smallest buffer based on size.
for (NATIVE_UINT_TYPE buff = 0; buff < this->m_numStructs; buff++) {
if ((not this->m_buffers[buff].allocated) and (size <= this->m_buffers[buff].size)) {
this->m_buffers[buff].allocated = true;
this->m_currBuffs++;
if (this->m_currBuffs > this->m_highWater) {
this->m_highWater = this->m_currBuffs;
}
Fw::Buffer copy = this->m_buffers[buff].buff;
// change size to match request
copy.setSize(size);
return copy;
}
}
// if no buffers found, return empty buffer
this->log_WARNING_HI_NoBuffsAvailable(size);
this->m_noBuffs++;
return Fw::Buffer();
}
void BufferManagerComponentImpl::setup(
NATIVE_UINT_TYPE mgrId, //!< manager ID
NATIVE_UINT_TYPE memId, //!< Memory segment identifier
Fw::MemAllocator& allocator, //!< memory allocator
const BufferBins& bins //!< Set of user bins
) {
this->m_mgrId = mgrId;
this->m_memId = memId;
this->m_allocator = &allocator;
// clear bins
memset(&this->m_bufferBins,0,sizeof(this->m_bufferBins));
this->m_bufferBins = bins;
// compute the amount of memory needed
NATIVE_UINT_TYPE memorySize = 0; // track needed memory
this->m_numStructs = 0; // size the number of tracking structs
// walk through bins and add up the sizes
for (NATIVE_UINT_TYPE bin = 0; bin < BUFFERMGR_MAX_NUM_BINS; bin++) {
if (this->m_bufferBins.bins[bin].numBuffers) {
memorySize +=
(this->m_bufferBins.bins[bin].bufferSize * this->m_bufferBins.bins[bin].numBuffers) + // allocate each set of buffer memory
(static_cast<NATIVE_UINT_TYPE>(sizeof(AllocatedBuffer)) * this->m_bufferBins.bins[bin].numBuffers); // allocate the structs to track the buffers
this->m_numStructs += this->m_bufferBins.bins[bin].numBuffers;
}
}
NATIVE_UINT_TYPE allocatedSize = memorySize;
bool recoverable = false; //!< don't care if it is recoverable since they are a pool of user buffers
// allocate memory
void *memory = allocator.allocate(memId,allocatedSize,recoverable);
// make sure the memory returns was non-zero and the size requested
FW_ASSERT(memory);
FW_ASSERT(memorySize == allocatedSize,memorySize,allocatedSize);
// structs will be at beginning of memory
this->m_buffers = static_cast<AllocatedBuffer*>(memory);
// memory buffers will be at end of structs in memory, so compute that memory as the beginning of the
// struct past the number of structs
U8* bufferMem = reinterpret_cast<U8*>(&this->m_buffers[this->m_numStructs]);
// walk through entries and initialize them
NATIVE_UINT_TYPE currStruct = 0;
for (NATIVE_UINT_TYPE bin = 0; bin < BUFFERMGR_MAX_NUM_BINS; bin++) {
if (this->m_bufferBins.bins[bin].numBuffers) {
for (NATIVE_UINT_TYPE binEntry = 0; binEntry < this->m_bufferBins.bins[bin].numBuffers; binEntry++) {
// placement new for Fw::Buffer instance. We don't need the new() return value,
// because we know where the Fw::Buffer instance is
U32 context = (this->m_mgrId << 16) | currStruct;
(void) new(&this->m_buffers[currStruct].buff) Fw::Buffer(bufferMem,this->m_bufferBins.bins[bin].bufferSize,context);
this->m_buffers[currStruct].allocated = false;
this->m_buffers[currStruct].memory = bufferMem;
this->m_buffers[currStruct].size = this->m_bufferBins.bins[bin].bufferSize;
bufferMem += this->m_bufferBins.bins[bin].bufferSize;
currStruct++;
}
}
}
// check that the initiation pointer made it to the end of allocated space
U8* const CURR_PTR = bufferMem;
U8* const END_PTR = static_cast<U8*>(memory) + memorySize;
FW_ASSERT(CURR_PTR == END_PTR,
reinterpret_cast<POINTER_CAST>(CURR_PTR), reinterpret_cast<POINTER_CAST>(END_PTR));
// secondary init verification
FW_ASSERT(currStruct == this->m_numStructs,currStruct,this->m_numStructs);
// indicate setup is done
this->m_setup = true;
}
void BufferManagerComponentImpl ::
schedIn_handler(
const NATIVE_INT_TYPE portNum,
U32 context
)
{
// write telemetry values
this->tlmWrite_HiBuffs(this->m_highWater);
this->tlmWrite_CurrBuffs(this->m_currBuffs);
this->tlmWrite_TotalBuffs(this->m_numStructs);
this->tlmWrite_NoBuffs(this->m_noBuffs);
this->tlmWrite_EmptyBuffs(this->m_emptyBuffs);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/BufferManager/BufferManager.hpp | // ======================================================================
// BufferManager.hpp
// Standardization header for BufferManager
// ======================================================================
#ifndef Svc_BufferManager_HPP
#define Svc_BufferManager_HPP
#include "Svc/BufferManager/BufferManagerComponentImpl.hpp"
namespace Svc {
typedef BufferManagerComponentImpl BufferManager;
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferManager/test/ut/BufferManagerTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "BufferManagerTester.hpp"
TEST(Nominal, Setup) {
Svc::BufferManagerTester tester;
tester.testSetup();
}
TEST(Nominal, OneSize) {
Svc::BufferManagerTester tester;
tester.oneBufferSize();
}
TEST(Nominal, MultSize) {
Svc::BufferManagerTester tester;
tester.multBuffSize();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/BufferManager/test/ut/BufferManagerTester.hpp | // ======================================================================
// \title BufferManager/test/ut/Tester.hpp
// \author tcanham
// \brief hpp file for BufferManager test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "BufferManagerGTestBase.hpp"
#include "Svc/BufferManager/BufferManagerComponentImpl.hpp"
namespace Svc {
class BufferManagerTester :
public BufferManagerGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object BufferManagerTester
//!
BufferManagerTester();
//! Destroy object BufferManagerTester
//!
~BufferManagerTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Test Setup
//!
void testSetup();
//! One buffer size
void oneBufferSize();
//! Multiple buffer sizes
void multBuffSize();
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
BufferManagerComponentImpl component;
void textLogIn(
const FwEventIdType id, //!< The event ID
const Fw::Time& timeTag, //!< The time
const Fw::LogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
) override;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferManager/test/ut/BufferManagerTester.cpp | // ======================================================================
// \title BufferManager.hpp
// \author tcanham
// \brief cpp file for BufferManager test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "BufferManagerTester.hpp"
#include <Fw/Types/MallocAllocator.hpp>
#include <Fw/Test/UnitTest.hpp>
#include <cstdlib>
#define INSTANCE 0
#define MAX_HISTORY_SIZE 100
// Bin buffer sizes/numbers
static const NATIVE_UINT_TYPE BIN0_BUFFER_SIZE = 10;
static const NATIVE_UINT_TYPE BIN0_NUM_BUFFERS = 2;
static const NATIVE_UINT_TYPE BIN1_BUFFER_SIZE = 12;
static const NATIVE_UINT_TYPE BIN1_NUM_BUFFERS = 4;
static const NATIVE_UINT_TYPE BIN2_BUFFER_SIZE = 100;
static const NATIVE_UINT_TYPE BIN2_NUM_BUFFERS = 3;
// Other constants
static const NATIVE_UINT_TYPE MEM_ID = 49;
static const NATIVE_UINT_TYPE MGR_ID = 32;
// Define our own instrumented allocator for testing
class TestAllocator: public Fw::MemAllocator {
public:
TestAllocator(){};
virtual ~TestAllocator(){};
//! 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) {
this->m_reqId = identifier;
this->m_reqSize = size;
this->m_mem = this->m_alloc.allocate(identifier,size,recoverable);
return this->m_mem;
}
//! Deallocate memory
/*!
* \param identifier the memory segment identifier (not used)
* \ptr the pointer to memory returned by allocate()
*/
void deallocate(
const NATIVE_UINT_TYPE identifier,
void* ptr) {
this->m_alloc.deallocate(identifier,ptr);
}
NATIVE_UINT_TYPE getId() {
return this->m_reqId;
}
NATIVE_UINT_TYPE getSize() {
return this->m_reqSize;
}
void* getMem() {
return this->m_mem;
}
private:
Fw::MallocAllocator m_alloc;
NATIVE_UINT_TYPE m_reqId;
NATIVE_UINT_TYPE m_reqSize;
void* m_mem;
};
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
BufferManagerTester ::
BufferManagerTester() :
BufferManagerGTestBase("Tester", MAX_HISTORY_SIZE),
component("BufferManager")
{
this->initComponents();
this->connectPorts();
}
BufferManagerTester ::
~BufferManagerTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void BufferManagerTester ::
testSetup()
{
REQUIREMENT("FPRIME-BM-001");
BufferManagerComponentImpl::BufferBins bins;
memset(&bins,0,sizeof(bins));
bins.bins[0].bufferSize = BIN0_BUFFER_SIZE;
bins.bins[0].numBuffers = BIN0_NUM_BUFFERS;
bins.bins[1].bufferSize = BIN1_BUFFER_SIZE;
bins.bins[1].numBuffers = BIN1_NUM_BUFFERS;
bins.bins[2].bufferSize = BIN2_BUFFER_SIZE;
bins.bins[2].numBuffers = BIN2_NUM_BUFFERS;
TestAllocator alloc;
this->component.setup(MGR_ID,MEM_ID,alloc,bins);
ASSERT_EQ(MEM_ID,this->component.m_memId);
ASSERT_EQ(MGR_ID,this->component.m_mgrId);
// check allocation state
// Check that enough buffers were created
ASSERT_EQ(
BIN0_NUM_BUFFERS +
BIN1_NUM_BUFFERS +
BIN2_NUM_BUFFERS,
this->component.m_numStructs
);
REQUIREMENT("FPRIME-BM-005");
// check that enough memory was requested
NATIVE_UINT_TYPE memSize =
(BIN0_NUM_BUFFERS + BIN1_NUM_BUFFERS + BIN2_NUM_BUFFERS)*sizeof(Svc::BufferManagerComponentImpl::AllocatedBuffer) +
(BIN0_NUM_BUFFERS*BIN0_BUFFER_SIZE + BIN1_NUM_BUFFERS*BIN1_BUFFER_SIZE + BIN2_NUM_BUFFERS*BIN2_BUFFER_SIZE);
ASSERT_EQ(memSize,alloc.getSize());
// check that correct ID was requested
ASSERT_EQ(MEM_ID,alloc.getId());
// first buffer should point at location just past buffer structs
U8 *mem = reinterpret_cast<U8*>(alloc.getMem()) + this->component.m_numStructs*sizeof(Svc::BufferManagerComponentImpl::AllocatedBuffer); ;
// check the buffer properties
for (NATIVE_UINT_TYPE entry = 0; entry < this->component.m_numStructs; entry++) {
// check context ID
ASSERT_EQ(this->component.m_buffers[entry].buff.getContext(),((MGR_ID << 16)| entry));
// check allocation state
ASSERT_FALSE(this->component.m_buffers[entry].allocated);
// check buffer sizes
if (entry < BIN0_NUM_BUFFERS) {
ASSERT_EQ(BIN0_BUFFER_SIZE,this->component.m_buffers[entry].size);
ASSERT_EQ(mem,this->component.m_buffers[entry].memory);
mem += BIN0_BUFFER_SIZE;
} else if (entry < BIN0_NUM_BUFFERS + BIN1_NUM_BUFFERS) {
ASSERT_EQ(BIN1_BUFFER_SIZE,this->component.m_buffers[entry].size);
ASSERT_EQ(mem,this->component.m_buffers[entry].memory);
mem += BIN1_BUFFER_SIZE;
} else if (entry < BIN0_NUM_BUFFERS + BIN1_NUM_BUFFERS + BIN2_NUM_BUFFERS) {
ASSERT_EQ(BIN2_BUFFER_SIZE,this->component.m_buffers[entry].size);
ASSERT_EQ(mem,this->component.m_buffers[entry].memory);
mem += BIN2_BUFFER_SIZE;
} else {
// just in case the logic is wrong
ASSERT_TRUE(false);
}
}
// memory location should be at end of allocated memory
ASSERT_EQ(mem,reinterpret_cast<U8*>(alloc.getMem()) + alloc.getSize());
this->component.cleanup();
ASSERT_TRUE(this->component.m_cleaned);
ASSERT_FALSE(this->component.m_setup);
}
void BufferManagerTester::oneBufferSize() {
BufferManagerComponentImpl::BufferBins bins;
memset(&bins,0,sizeof(bins));
bins.bins[0].bufferSize = BIN1_BUFFER_SIZE;
bins.bins[0].numBuffers = BIN1_NUM_BUFFERS;
TestAllocator alloc;
this->component.setup(MGR_ID,MEM_ID,alloc,bins);
Fw::Buffer buffs[BIN1_NUM_BUFFERS];
for (NATIVE_UINT_TYPE b=0; b<BIN1_NUM_BUFFERS; b++) {
// Get the buffers
buffs[b] = this->invoke_to_bufferGetCallee(0,BIN1_BUFFER_SIZE);
// check allocation state
ASSERT_TRUE(this->component.m_buffers[b].allocated);
// check stats
ASSERT_EQ(b+1,this->component.m_currBuffs);
// check stats
ASSERT_EQ(b+1,this->component.m_highWater);
}
// should send back empty buffer
Fw::Buffer noBuff = this->invoke_to_bufferGetCallee(0,BIN1_BUFFER_SIZE);
ASSERT_EQ(1,this->component.m_noBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(5);
ASSERT_TLM_TotalBuffs_SIZE(1);
ASSERT_TLM_TotalBuffs(0,BIN1_NUM_BUFFERS);
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,BIN1_NUM_BUFFERS);
ASSERT_TLM_HiBuffs_SIZE(1);
ASSERT_TLM_HiBuffs(0,BIN1_NUM_BUFFERS);
ASSERT_TLM_NoBuffs_SIZE(1);
ASSERT_TLM_NoBuffs(0,1);
ASSERT_TLM_EmptyBuffs_SIZE(1);
ASSERT_TLM_EmptyBuffs(0,0);
// clear histories
this->clearHistory();
REQUIREMENT("FPRIME-BM-006");
// randomly return buffers
time_t t;
srand(static_cast<unsigned>(time(&t)));
bool returned[BIN1_NUM_BUFFERS] = {false};
for (NATIVE_UINT_TYPE b=0; b<BIN1_NUM_BUFFERS; b++) {
NATIVE_UINT_TYPE entry;
while (true) {
entry = rand() % BIN1_NUM_BUFFERS;
if (not returned[entry]) {
returned[entry] = true;
break;
}
}
// return the buffer
printf("Returning buffer %d\n",entry);
this->invoke_to_bufferSendIn(0,buffs[entry]);
// check allocation state
ASSERT_FALSE(this->component.m_buffers[entry].allocated);
ASSERT_EQ(BIN1_NUM_BUFFERS-b-1,this->component.m_currBuffs);
ASSERT_EQ(BIN1_NUM_BUFFERS,this->component.m_highWater);
}
// should reject empty buffer
this->invoke_to_bufferSendIn(0,noBuff);
ASSERT_EQ(1,this->component.m_emptyBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(2);
// No total buffs or no buffs since only on update
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,0);
ASSERT_TLM_NoBuffs_SIZE(0);
ASSERT_TLM_EmptyBuffs_SIZE(1);
ASSERT_TLM_EmptyBuffs(0,1);
// all buffers should be deallocated
for (NATIVE_UINT_TYPE b=0; b<this->component.m_numStructs; b++) {
ASSERT_FALSE(this->component.m_buffers[b].allocated);
}
// cleanup BufferManager memory
this->component.cleanup();
}
void BufferManagerTester::multBuffSize() {
BufferManagerComponentImpl::BufferBins bins;
memset(&bins,0,sizeof(bins));
bins.bins[0].bufferSize = BIN0_BUFFER_SIZE;
bins.bins[0].numBuffers = BIN0_NUM_BUFFERS;
bins.bins[1].bufferSize = BIN1_BUFFER_SIZE;
bins.bins[1].numBuffers = BIN1_NUM_BUFFERS;
bins.bins[2].bufferSize = BIN2_BUFFER_SIZE;
bins.bins[2].numBuffers = BIN2_NUM_BUFFERS;
TestAllocator alloc;
this->component.setup(MGR_ID,MEM_ID,alloc,bins);
Fw::Buffer buffs[BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS];
REQUIREMENT("FPRIME-BM-002");
// BufferManager should be able to provide the whole pool worth of buffers
// for a requested size smaller than the smallest bin.
for (NATIVE_UINT_TYPE b=0; b<BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS; b++) {
// Get the buffers
buffs[b] = this->invoke_to_bufferGetCallee(0,BIN0_BUFFER_SIZE);
// check allocation state
ASSERT_TRUE(this->component.m_buffers[b].allocated);
// check stats
ASSERT_EQ(b+1,this->component.m_currBuffs);
// check stats
ASSERT_EQ(b+1,this->component.m_highWater);
}
REQUIREMENT("FPRIME-BM-003");
// should send back empty buffer
Fw::Buffer noBuff = this->invoke_to_bufferGetCallee(0,BIN1_BUFFER_SIZE);
ASSERT_EQ(1,this->component.m_noBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(5);
ASSERT_TLM_TotalBuffs_SIZE(1);
ASSERT_TLM_TotalBuffs(0,BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS);
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS);
ASSERT_TLM_HiBuffs_SIZE(1);
ASSERT_TLM_HiBuffs(0,BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS);
ASSERT_TLM_NoBuffs_SIZE(1);
ASSERT_TLM_NoBuffs(0,1);
ASSERT_TLM_EmptyBuffs_SIZE(1);
ASSERT_TLM_EmptyBuffs(0,0);
// clear histories
this->clearHistory();
for (NATIVE_UINT_TYPE b=0; b<BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS; b++) {
// return the buffer
this->invoke_to_bufferSendIn(0,buffs[b]);
// check allocation state
ASSERT_FALSE(this->component.m_buffers[b].allocated);
ASSERT_EQ(BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS-b-1,this->component.m_currBuffs);
ASSERT_EQ(BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS,this->component.m_highWater);
}
REQUIREMENT("FPRIME-BM-004");
// should reject empty buffer
this->invoke_to_bufferSendIn(0,noBuff);
ASSERT_EQ(1,this->component.m_emptyBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(2);
// No total buffs or no buffs since only on update
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,0);
ASSERT_TLM_NoBuffs_SIZE(0);
ASSERT_TLM_EmptyBuffs_SIZE(1);
ASSERT_TLM_EmptyBuffs(0,1);
// clear histories
this->clearHistory();
// all buffers should be deallocated
for (NATIVE_UINT_TYPE b=0; b<this->component.m_numStructs; b++) {
ASSERT_FALSE(this->component.m_buffers[b].allocated);
}
// clear histories
this->clearEvents();
// BufferManager should be able to provide the BIN1 and BIN2 worth of buffers
// for a requested size just smaller than the BIN1 size
for (NATIVE_UINT_TYPE b=0; b<BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS; b++) {
// Get the buffers
buffs[b] = this->invoke_to_bufferGetCallee(0,BIN1_BUFFER_SIZE);
// check allocation state - should be allocating from bin 1
ASSERT_TRUE(this->component.m_buffers[b+BIN0_NUM_BUFFERS].allocated);
// check stats
ASSERT_EQ(b+1,this->component.m_currBuffs);
}
// should send back empty buffer
noBuff = this->invoke_to_bufferGetCallee(0,BIN1_BUFFER_SIZE);
ASSERT_EQ(2,this->component.m_noBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_TotalBuffs_SIZE(0);
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS);
ASSERT_TLM_NoBuffs_SIZE(1);
ASSERT_TLM_NoBuffs(0,2);
ASSERT_TLM_EmptyBuffs_SIZE(0);
// clear histories
this->clearHistory();
for (NATIVE_UINT_TYPE b=0; b<BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS; b++) {
// return the buffer
this->invoke_to_bufferSendIn(0,buffs[b]);
// check allocation state - should be freeing from bin 1
ASSERT_FALSE(this->component.m_buffers[b+BIN0_NUM_BUFFERS].allocated);
ASSERT_EQ(BIN1_NUM_BUFFERS+BIN2_NUM_BUFFERS-b-1,this->component.m_currBuffs);
}
// should reject empty buffer
this->invoke_to_bufferSendIn(0,noBuff);
ASSERT_EQ(2,this->component.m_emptyBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(2);
// No total buffs or no buffs since only on update
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,0);
ASSERT_TLM_NoBuffs_SIZE(0);
ASSERT_TLM_EmptyBuffs_SIZE(1);
ASSERT_TLM_EmptyBuffs(0,2);
// clear histories
this->clearHistory();
// all buffers should be deallocated
for (NATIVE_UINT_TYPE b=0; b<this->component.m_numStructs; b++) {
ASSERT_FALSE(this->component.m_buffers[b].allocated);
}
// BufferManager should be able to provide the BIN2 worth of buffers
// for a requested size just smaller than the BIN2 size
for (NATIVE_UINT_TYPE b=0; b<BIN2_NUM_BUFFERS; b++) {
// Get the buffers
buffs[b] = this->invoke_to_bufferGetCallee(0,BIN2_BUFFER_SIZE);
// check allocation state - should be allocating from bin 1
ASSERT_TRUE(this->component.m_buffers[b+BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS].allocated);
// check stats
ASSERT_EQ(b+1,this->component.m_currBuffs);
}
// should send back empty buffer
noBuff = this->invoke_to_bufferGetCallee(0,BIN2_BUFFER_SIZE);
ASSERT_EQ(3,this->component.m_noBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(2);
ASSERT_TLM_TotalBuffs_SIZE(0);
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,BIN2_NUM_BUFFERS);
ASSERT_TLM_NoBuffs_SIZE(1);
ASSERT_TLM_NoBuffs(0,3);
ASSERT_TLM_EmptyBuffs_SIZE(0);
// clear histories
this->clearHistory();
for (NATIVE_UINT_TYPE b=0; b<BIN2_NUM_BUFFERS; b++) {
// return the buffer
this->invoke_to_bufferSendIn(0,buffs[b]);
// check allocation state - should be freeing from bin 1
ASSERT_FALSE(this->component.m_buffers[b+BIN0_NUM_BUFFERS+BIN1_NUM_BUFFERS].allocated);
ASSERT_EQ(BIN2_NUM_BUFFERS-b-1,this->component.m_currBuffs);
}
// should reject empty buffer
this->invoke_to_bufferSendIn(0,noBuff);
ASSERT_EQ(3,this->component.m_emptyBuffs);
// check telemetry
this->invoke_to_schedIn(0,0);
ASSERT_TLM_SIZE(2);
// No total buffs or no buffs since only on update
ASSERT_TLM_CurrBuffs_SIZE(1);
ASSERT_TLM_CurrBuffs(0,0);
ASSERT_TLM_NoBuffs_SIZE(0);
ASSERT_TLM_EmptyBuffs_SIZE(1);
ASSERT_TLM_EmptyBuffs(0,3);
// all buffers should be deallocated
for (NATIVE_UINT_TYPE b=0; b<this->component.m_numStructs; b++) {
ASSERT_FALSE(this->component.m_buffers[b].allocated);
}
// cleanup BufferManager memory
this->component.cleanup();
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void BufferManagerTester ::
connectPorts()
{
// bufferSendIn
this->connect_to_bufferSendIn(
0,
this->component.get_bufferSendIn_InputPort(0)
);
// bufferGetCallee
this->connect_to_bufferGetCallee(
0,
this->component.get_bufferGetCallee_InputPort(0)
);
// timeCaller
this->component.set_timeCaller_OutputPort(
0,
this->get_from_timeCaller(0)
);
// eventOut
this->component.set_eventOut_OutputPort(
0,
this->get_from_eventOut(0)
);
// textEventOut
this->component.set_textEventOut_OutputPort(
0,
this->get_from_textEventOut(0)
);
// tlmOut
this->component.set_tlmOut_OutputPort(
0,
this->get_from_tlmOut(0)
);
// schedIn
this->connect_to_schedIn(
0,
this->component.get_schedIn_InputPort(0)
);
}
void BufferManagerTester ::
initComponents()
{
this->init();
this->component.init(
INSTANCE
);
}
void BufferManagerTester::textLogIn(const FwEventIdType id, //!< The event ID
const Fw::Time& timeTag, //!< The time
const Fw::LogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
) {
TextLogEntry e = { id, timeTag, severity, text };
printTextLogHistoryEntry(e, stdout);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/DpManager.hpp | // ======================================================================
// \title DpManager.hpp
// \author bocchino
// \brief hpp file for DpManager component implementation class
// ======================================================================
#ifndef Svc_DpManager_HPP
#define Svc_DpManager_HPP
#include <atomic>
#include "Svc/DpManager/DpManagerComponentAc.hpp"
#include "config/FppConstantsAc.hpp"
namespace Svc {
class DpManager : public DpManagerComponentBase {
private:
// ----------------------------------------------------------------------
// Static assertions against the assumptions about the model
// ----------------------------------------------------------------------
static_assert(
DpManager::NUM_PRODUCTGETIN_INPUT_PORTS == static_cast<FwSizeType>(DpManagerNumPorts),
"Number of product get in ports must equal DpManagerNumPorts"
);
static_assert(
DpManager::NUM_PRODUCTREQUESTIN_INPUT_PORTS == static_cast<FwSizeType>(DpManagerNumPorts),
"Number of product request in ports must equal DpManagerNumPorts"
);
static_assert(
DpManager::NUM_PRODUCTRESPONSEOUT_OUTPUT_PORTS == static_cast<FwSizeType>(DpManagerNumPorts),
"Number of product response out ports must equal DpManagerNumPorts"
);
static_assert(
DpManager::NUM_BUFFERGETOUT_OUTPUT_PORTS == static_cast<FwSizeType>(DpManagerNumPorts),
"Number of buffer get out ports must equal DpManagerNumPorts"
);
static_assert(
DpManager::NUM_PRODUCTSENDIN_INPUT_PORTS == static_cast<FwSizeType>(DpManagerNumPorts),
"Number of product send in ports must equal DpManagerNumPorts"
);
static_assert(
DpManager::NUM_PRODUCTSENDOUT_OUTPUT_PORTS == static_cast<FwSizeType>(DpManagerNumPorts),
"Number of product send out ports must equal DpManagerNumPorts"
);
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct a DpManager
explicit DpManager(const char* const compName //!< The component name
);
//! Destroy the DpManager
~DpManager();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for productGetIn
Fw::Success productGetIn_handler(const NATIVE_INT_TYPE portNum, //!< The port number
FwDpIdType id, //!< The container ID
FwSizeType size, //!< The size of the requested buffer
Fw::Buffer& buffer //!< The buffer
) final;
//! Handler implementation for productRequestIn
void productRequestIn_handler(const NATIVE_INT_TYPE portNum, //!< The port number
FwDpIdType id, //!< The container ID
FwSizeType size //!< The size of the requested buffer
) final;
//! Handler implementation for productSendIn
void productSendIn_handler(const NATIVE_INT_TYPE portNum, //!< The port number
FwDpIdType id, //!< The container ID
const Fw::Buffer& buffer //!< The buffer
) final;
//! Handler implementation for schedIn
void schedIn_handler(const NATIVE_INT_TYPE portNum, //!< The port number
NATIVE_UINT_TYPE context //!< The call order
) final;
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for commands
// ----------------------------------------------------------------------
//! Handler implementation for command CLEAR_EVENT_THROTTLE
//!
//! Clear event throttling
void CLEAR_EVENT_THROTTLE_cmdHandler(FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
) override;
PRIVATE:
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
//! Get a buffer
//! \return Status
Fw::Success getBuffer(FwIndexType portNum, //!< The port number
FwDpIdType id, //!< The container ID (input)
FwSizeType size, //!< The requested size (input)
Fw::Buffer& buffer //!< The buffer (output)
);
PRIVATE:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The number of successful buffer allocations
std::atomic<U32> numSuccessfulAllocations;
//! The number of failed buffer allocations
std::atomic<U32> numFailedAllocations;
//! The number of data products handled
U32 numDataProducts;
//! The number of bytes handled
U64 numBytes;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/DpManager.cpp | // ======================================================================
// \title DpManager.cpp
// \author bocchino
// \brief cpp file for DpManager component implementation class
// ======================================================================
#include "FpConfig.hpp"
#include "Svc/DpManager/DpManager.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
DpManager::DpManager(const char* const compName)
: DpManagerComponentBase(compName),
numSuccessfulAllocations(0),
numFailedAllocations(0),
numDataProducts(0),
numBytes(0) {}
DpManager::~DpManager() {}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
Fw::Success DpManager::productGetIn_handler(const NATIVE_INT_TYPE portNum,
FwDpIdType id,
FwSizeType size,
Fw::Buffer& buffer) {
return this->getBuffer(portNum, id, size, buffer);
}
void DpManager::productRequestIn_handler(const NATIVE_INT_TYPE portNum, FwDpIdType id, FwSizeType size) {
// Get a buffer
Fw::Buffer buffer;
const Fw::Success status = this->getBuffer(portNum, id, size, buffer);
// Send buffer on productResponseOut
this->productResponseOut_out(portNum, id, buffer, status);
}
void DpManager::productSendIn_handler(const NATIVE_INT_TYPE portNum, FwDpIdType id, const Fw::Buffer& buffer) {
// id is unused
(void)id;
// Update state variables
++this->numDataProducts;
this->numBytes += buffer.getSize();
// Send the buffer on productSendOut
Fw::Buffer sendBuffer = buffer;
this->productSendOut_out(portNum, sendBuffer);
}
void DpManager::schedIn_handler(const NATIVE_INT_TYPE portNum, NATIVE_UINT_TYPE context) {
// Emit telemetry
this->tlmWrite_NumSuccessfulAllocations(this->numSuccessfulAllocations);
this->tlmWrite_NumFailedAllocations(this->numFailedAllocations);
this->tlmWrite_NumDataProducts(this->numDataProducts);
this->tlmWrite_NumBytes(this->numBytes);
}
// ----------------------------------------------------------------------
// Handler implementations for commands
// ----------------------------------------------------------------------
void DpManager ::CLEAR_EVENT_THROTTLE_cmdHandler(FwOpcodeType opCode, U32 cmdSeq) {
this->log_WARNING_HI_BufferAllocationFailed_ThrottleClear();
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
Fw::Success DpManager::getBuffer(FwIndexType portNum, FwDpIdType id, FwSizeType size, Fw::Buffer& buffer) {
// Set status
Fw::Success status(Fw::Success::FAILURE);
// Get a buffer
buffer = this->bufferGetOut_out(portNum, size);
if (buffer.isValid()) {
// Buffer is valid
++this->numSuccessfulAllocations;
status = Fw::Success::SUCCESS;
} else {
// Buffer is invalid
++this->numFailedAllocations;
this->log_WARNING_HI_BufferAllocationFailed(id);
}
return status;
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/AbstractState.hpp | // ======================================================================
// \title AbstractState.hpp
// \author Rob Bocchino
// \brief Header file for abstract state
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_AbstractState_HPP
#define Svc_AbstractState_HPP
#include <cstring>
#include "Fw/Types/Assert.hpp"
#include "STest/Pick/Pick.hpp"
#include "Svc/DpManager/DpManager.hpp"
#include "TestUtils/OnChangeChannel.hpp"
#include "TestUtils/Option.hpp"
namespace Svc {
class AbstractState {
public:
// ----------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------
//! The minimum buffer size
static constexpr FwSizeType MIN_BUFFER_SIZE = 1;
//! The maximum buffer size
static constexpr FwSizeType MAX_BUFFER_SIZE = 1024;
public:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
//! The type of the buffer get status
enum class BufferGetStatus {
//! Valid
VALID,
//! Invalid
INVALID
};
public:
// ----------------------------------------------------------------------
// Constructors
// ----------------------------------------------------------------------
//! Construct an AbstractState object
AbstractState()
: bufferSizeOpt(),
bufferGetStatus(BufferGetStatus::VALID),
NumSuccessfulAllocations(0),
NumFailedAllocations(0),
NumDataProducts(0),
NumBytes(0),
bufferGetOutPortNumOpt(),
productResponseOutPortNumOpt(),
productSendOutPortNumOpt(),
bufferAllocationFailedEventCount(0) {}
public:
// ----------------------------------------------------------------------
// Accessor methods
// ----------------------------------------------------------------------
//! Get the buffer size
FwSizeType getBufferSize() const {
return this->bufferSizeOpt.getOrElse(STest::Pick::lowerUpper(MIN_BUFFER_SIZE, MAX_BUFFER_SIZE));
}
//! Set the buffer size
void setBufferSize(FwSizeType bufferSize) { this->bufferSizeOpt.set(bufferSize); }
private:
// ----------------------------------------------------------------------
// Private state variables
// ----------------------------------------------------------------------
//! The current buffer size
TestUtils::Option<FwSizeType> bufferSizeOpt;
public:
// ----------------------------------------------------------------------
// Public state variables
// ----------------------------------------------------------------------
//! The buffer get status
BufferGetStatus bufferGetStatus;
//! The number of successful buffer allocations
TestUtils::OnChangeChannel<U32> NumSuccessfulAllocations;
//! The number of failed buffer allocations
TestUtils::OnChangeChannel<U32> NumFailedAllocations;
//! The number of data products handled
TestUtils::OnChangeChannel<U32> NumDataProducts;
//! The number of bytes handled
TestUtils::OnChangeChannel<U64> NumBytes;
//! Data for buffers
U8 bufferData[MAX_BUFFER_SIZE];
//! The last port number used for bufferGetOut
TestUtils::Option<FwIndexType> bufferGetOutPortNumOpt;
//! The last port number used for productResponseOut
TestUtils::Option<FwIndexType> productResponseOutPortNumOpt;
//! The last port number used for productSendOut
TestUtils::Option<FwIndexType> productSendOutPortNumOpt;
//! The number of buffer allocation failed events since the last throttle clear
FwSizeType bufferAllocationFailedEventCount;
};
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/DpManagerTester.hpp | // ======================================================================
// \title DpManager/test/ut/DpManagerTester.hpp
// \author Rob Bocchino
// \brief hpp file for DpManager test harness implementation
// ======================================================================
#ifndef Svc_Tester_HPP
#define Svc_Tester_HPP
#include "DpManagerGTestBase.hpp"
#include "Svc/DpManager/DpManager.hpp"
#include "Svc/DpManager/test/ut/AbstractState.hpp"
namespace Svc {
class DpManagerTester : public DpManagerGTestBase {
public:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 10;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
// Queue depth supplied to component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_QUEUE_DEPTH = 10;
//! Construct object DpManagerTester
DpManagerTester();
//! Destroy object DpManagerTester
~DpManagerTester();
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_bufferGetOut
Fw::Buffer from_bufferGetOut_handler(const NATIVE_INT_TYPE portNum, //!< The port number
U32 size //!< The size
);
//! Handler for from_productResponseOut
void from_productResponseOut_handler(const NATIVE_INT_TYPE portNum, //!< The port number
FwDpIdType id, //!< The container ID
const Fw::Buffer& buffer, //!< The buffer
const Fw::Success& status //!< The status
);
//! Handler for from_productSendOut
void from_productSendOut_handler(const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer& fwBuffer //!< The buffer
);
protected:
// ----------------------------------------------------------------------
// Protected instance methods
// ----------------------------------------------------------------------
//! Check telemetry
void checkTelemetry();
private:
// ----------------------------------------------------------------------
// Private helper methods
// ----------------------------------------------------------------------
//! Connect ports
void connectPorts();
//! Initialize components
void initComponents();
public:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The abstract state for testing
AbstractState abstractState;
//! The component under test
DpManager component;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/DpManagerTestMain.cpp | // ======================================================================
// TestMain.cpp
// ======================================================================
#include "Fw/Test/UnitTest.hpp"
#include "STest/Random/Random.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
#include "Svc/DpManager/test/ut/Scenarios/Random.hpp"
namespace Svc {
TEST(BufferGetStatus, Invalid) {
COMMENT("Set the buffer get status to INVALID.");
BufferGetStatus::Tester tester;
tester.Invalid();
}
TEST(BufferGetStatus, Valid) {
COMMENT("Set the buffer get status to VALID.");
BufferGetStatus::Tester tester;
tester.Valid();
}
TEST(ProductGetIn, BufferInvalid) {
COMMENT("Invoke productGetIn in a state where the test harness returns an invalid buffer.");
REQUIREMENT("SVC-DPMANAGER-001");
REQUIREMENT("SVC-DPMANAGER-004");
ProductGetIn::Tester tester;
tester.BufferInvalid();
}
TEST(ProductGetIn, BufferValid) {
COMMENT("Invoke productGetIn in a state where the test harness returns a valid buffer.");
REQUIREMENT("SVC-DPMANAGER-001");
REQUIREMENT("SVC-DPMANAGER-004");
ProductGetIn::Tester tester;
tester.BufferValid();
}
TEST(ProductRequestIn, BufferInvalid) {
COMMENT("Invoke productRequestIn in a state where the test harness returns an invalid buffer.");
REQUIREMENT("SVC-DPMANAGER-002");
REQUIREMENT("SVC-DPMANAGER-004");
ProductRequestIn::Tester tester;
tester.BufferInvalid();
}
TEST(ProductRequestIn, BufferValid) {
COMMENT("Invoke productRequestIn in a state where the test harness returns a valid buffer.");
REQUIREMENT("SVC-DPMANAGER-002");
REQUIREMENT("SVC-DPMANAGER-004");
ProductRequestIn::Tester tester;
tester.BufferValid();
}
TEST(ProductSendIn, OK) {
COMMENT("Invoke productSendIn with nominal input.");
REQUIREMENT("SVC-DPMANAGER-003");
REQUIREMENT("SVC-DPMANAGER-004");
ProductSendIn::Tester tester;
tester.OK();
}
TEST(SchedIn, OK) {
COMMENT("Invoke schedIn with nominal input.");
REQUIREMENT("SVC-DPMANAGER-004");
SchedIn::Tester tester;
tester.OK();
}
TEST(CLEAR_EVENT_THROTTLE, OK) {
COMMENT("Send command CLEAR_EVENT_THROTTLE.");
CLEAR_EVENT_THROTTLE::Tester tester;
tester.OK();
}
TEST(Scenarios, Random) {
COMMENT("Random scenario with all rules.");
REQUIREMENT("SVC-DPMANAGER-002");
REQUIREMENT("SVC-DPMANAGER-003");
REQUIREMENT("SVC-DPMANAGER-004");
const FwSizeType numSteps = 10000;
Scenarios::Random::Tester tester;
tester.run(numSteps);
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/DpManagerTester.cpp | // ======================================================================
// \title DpManagerTester.hpp
// \author Rob Bocchino
// \brief cpp file for DpManager test harness implementation
// ======================================================================
#include "Svc/DpManager/test/ut/DpManagerTester.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
DpManagerTester ::DpManagerTester()
: DpManagerGTestBase("DpManagerTester", DpManagerTester::MAX_HISTORY_SIZE), component("DpManager") {
this->initComponents();
this->connectPorts();
}
DpManagerTester ::~DpManagerTester() {}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
Fw::Buffer DpManagerTester::from_bufferGetOut_handler(const NATIVE_INT_TYPE portNum, U32 size) {
this->abstractState.bufferGetOutPortNumOpt = TestUtils::Option<FwIndexType>::some(portNum);
this->pushFromPortEntry_bufferGetOut(size);
Fw::Buffer buffer;
switch (this->abstractState.bufferGetStatus) {
case AbstractState::BufferGetStatus::VALID:
// Construct a valid buffer
buffer.setData(this->abstractState.bufferData);
FW_ASSERT(size <= AbstractState::MAX_BUFFER_SIZE);
buffer.setSize(size);
break;
case AbstractState::BufferGetStatus::INVALID:
// Leave buffer in invalid state
break;
default:
FW_ASSERT(0);
break;
}
return buffer;
}
void DpManagerTester::from_productResponseOut_handler(const NATIVE_INT_TYPE portNum,
FwDpIdType id,
const Fw::Buffer& buffer,
const Fw::Success& status) {
this->abstractState.productResponseOutPortNumOpt = TestUtils::Option<FwIndexType>::some(portNum);
this->pushFromPortEntry_productResponseOut(id, buffer, status);
}
void DpManagerTester::from_productSendOut_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
this->abstractState.productSendOutPortNumOpt = TestUtils::Option<FwIndexType>::some(portNum);
this->pushFromPortEntry_productSendOut(fwBuffer);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
#define TESTER_CHECK_CHANNEL(NAME) \
{ \
const auto changeStatus = this->abstractState.NAME.updatePrev(); \
if (changeStatus == TestUtils::OnChangeStatus::CHANGED) { \
ASSERT_TLM_##NAME##_SIZE(1); \
ASSERT_TLM_##NAME(0, this->abstractState.NAME.value); \
} else { \
ASSERT_TLM_##NAME##_SIZE(0); \
} \
}
void DpManagerTester::checkTelemetry() {
TESTER_CHECK_CHANNEL(NumSuccessfulAllocations);
TESTER_CHECK_CHANNEL(NumFailedAllocations);
TESTER_CHECK_CHANNEL(NumDataProducts);
TESTER_CHECK_CHANNEL(NumBytes);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/ProductGetIn.cpp | // ======================================================================
// \title ProductGetIn.cpp
// \author Rob Bocchino
// \brief ProductGetIn class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include <limits>
#include "STest/Pick/Pick.hpp"
#include "Svc/DpManager/test/ut/Rules/ProductGetIn.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
#include "config/FppConstantsAc.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
bool TestState::precondition__ProductGetIn__BufferValid() const {
return this->abstractState.bufferGetStatus == AbstractState::BufferGetStatus::VALID;
}
void TestState::action__ProductGetIn__BufferValid() {
// Clear history
this->clearHistory();
// Send the invocation
const FwIndexType portNum = STest::Pick::startLength(0, DpManagerNumPorts);
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
const FwSizeType size = this->abstractState.getBufferSize();
Fw::Buffer buffer;
const auto status = this->invoke_to_productGetIn(portNum, id, size, buffer);
ASSERT_EQ(status, Fw::Success::SUCCESS);
// Check events
ASSERT_EVENTS_SIZE(0);
// Update test state
++this->abstractState.NumSuccessfulAllocations.value;
// Check port history
ASSERT_FROM_PORT_HISTORY_SIZE(1);
// Check buffer get out
ASSERT_from_bufferGetOut_SIZE(1);
ASSERT_from_bufferGetOut(0, size);
ASSERT_EQ(this->abstractState.bufferGetOutPortNumOpt.get(), portNum);
// Check the buffer
const Fw::Buffer expectedBuffer(this->abstractState.bufferData, size);
ASSERT_EQ(buffer, expectedBuffer);
}
bool TestState::precondition__ProductGetIn__BufferInvalid() const {
return this->abstractState.bufferGetStatus == AbstractState::BufferGetStatus::INVALID;
}
void TestState ::action__ProductGetIn__BufferInvalid() {
// Clear history
this->clearHistory();
// Send the invocation
const FwIndexType portNum = STest::Pick::startLength(0, DpManagerNumPorts);
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
const FwSizeType size = this->abstractState.getBufferSize();
Fw::Buffer buffer;
const auto status = this->invoke_to_productGetIn(portNum, id, size, buffer);
ASSERT_EQ(status, Fw::Success::FAILURE);
// Check events
if (this->abstractState.bufferAllocationFailedEventCount <
DpManagerComponentBase::EVENTID_BUFFERALLOCATIONFAILED_THROTTLE) {
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_BufferAllocationFailed(0, id);
++this->abstractState.bufferAllocationFailedEventCount;
} else {
ASSERT_EVENTS_SIZE(0);
}
// Update test state
++this->abstractState.NumFailedAllocations.value;
// Check port history
ASSERT_FROM_PORT_HISTORY_SIZE(1);
// Check buffer get out
ASSERT_from_bufferGetOut_SIZE(1);
ASSERT_from_bufferGetOut(0, size);
ASSERT_EQ(this->abstractState.bufferGetOutPortNumOpt.get(), portNum);
}
namespace ProductGetIn {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::BufferValid() {
this->testState.abstractState.setBufferSize(Svc::AbstractState::MIN_BUFFER_SIZE);
this->ruleBufferValid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MAX_BUFFER_SIZE);
this->ruleBufferValid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
}
void Tester ::BufferInvalid() {
Testers::bufferGetStatus.ruleInvalid.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MIN_BUFFER_SIZE);
this->ruleBufferInvalid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MAX_BUFFER_SIZE);
this->ruleBufferInvalid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
}
} // namespace ProductGetIn
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/Testers.hpp | // ======================================================================
// \title Testers.hpp
// \author Rob Bocchino
// \brief Testers class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_Testers_HPP
#define Svc_Testers_HPP
#include "Svc/DpManager/test/ut/Rules/BufferGetStatus.hpp"
#include "Svc/DpManager/test/ut/Rules/CLEAR_EVENT_THROTTLE.hpp"
#include "Svc/DpManager/test/ut/Rules/ProductGetIn.hpp"
#include "Svc/DpManager/test/ut/Rules/ProductRequestIn.hpp"
#include "Svc/DpManager/test/ut/Rules/ProductSendIn.hpp"
#include "Svc/DpManager/test/ut/Rules/SchedIn.hpp"
namespace Svc {
namespace Testers {
extern BufferGetStatus::Tester bufferGetStatus;
extern CLEAR_EVENT_THROTTLE::Tester clearEventThrottle;
extern ProductGetIn::Tester productGetIn;
extern ProductRequestIn::Tester productRequestIn;
extern ProductSendIn::Tester productSendIn;
extern SchedIn::Tester schedIn;
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/ProductGetIn.hpp | // ======================================================================
// \title ProductGetIn.hpp
// \author Rob Bocchino
// \brief ProductGetIn class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_ProductGetIn_HPP
#define Svc_ProductGetIn_HPP
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace ProductGetIn {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! BufferValid
void BufferValid();
//! BufferInvalid
void BufferInvalid();
public:
// ----------------------------------------------------------------------
// Rules
// ----------------------------------------------------------------------
//! Rule ProductGetIn::BufferValid
Rules::ProductGetIn::BufferValid ruleBufferValid;
//! Rule ProductGetIn::BufferInvalid
Rules::ProductGetIn::BufferInvalid ruleBufferInvalid;
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/ProductRequestIn.hpp | // ======================================================================
// \title ProductRequestIn.hpp
// \author Rob Bocchino
// \brief ProductRequestIn class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_ProductRequestIn_HPP
#define Svc_ProductRequestIn_HPP
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace ProductRequestIn {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! BufferValid
void BufferValid();
//! BufferInvalid
void BufferInvalid();
public:
// ----------------------------------------------------------------------
// Rules
// ----------------------------------------------------------------------
//! Rule ProductRequestIn::BufferValid
Rules::ProductRequestIn::BufferValid ruleBufferValid;
//! Rule ProductRequestIn::BufferInvalid
Rules::ProductRequestIn::BufferInvalid ruleBufferInvalid;
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/BufferGetStatus.cpp | // ======================================================================
// \title BufferGetStatus.cpp
// \author Rob Bocchino
// \brief BufferGetStatus class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include "Svc/DpManager/test/ut/Rules/BufferGetStatus.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
bool TestState ::precondition__BufferGetStatus__Valid() const {
bool result = (this->abstractState.bufferGetStatus != AbstractState::BufferGetStatus::VALID);
return result;
}
void TestState ::action__BufferGetStatus__Valid() {
this->abstractState.bufferGetStatus = AbstractState::BufferGetStatus::VALID;
}
bool TestState ::precondition__BufferGetStatus__Invalid() const {
bool result = (this->abstractState.bufferGetStatus != AbstractState::BufferGetStatus::INVALID);
return result;
}
void TestState ::action__BufferGetStatus__Invalid() {
this->abstractState.bufferGetStatus = AbstractState::BufferGetStatus::INVALID;
}
namespace BufferGetStatus {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::Valid() {
this->ruleInvalid.apply(this->testState);
this->ruleValid.apply(this->testState);
}
void Tester ::Invalid() {
this->ruleInvalid.apply(this->testState);
}
} // namespace BufferGetStatus
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/ProductRequestIn.cpp | // ======================================================================
// \title ProductRequestIn.cpp
// \author Rob Bocchino
// \brief ProductRequestIn class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include <limits>
#include "STest/Pick/Pick.hpp"
#include "Svc/DpManager/test/ut/Rules/ProductRequestIn.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
#include "config/FppConstantsAc.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
bool TestState::precondition__ProductRequestIn__BufferValid() const {
return this->abstractState.bufferGetStatus == AbstractState::BufferGetStatus::VALID;
}
void TestState::action__ProductRequestIn__BufferValid() {
// Clear history
this->clearHistory();
// Send the invocation
const FwIndexType portNum = STest::Pick::startLength(0, DpManagerNumPorts);
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
const FwSizeType size = this->abstractState.getBufferSize();
this->invoke_to_productRequestIn(portNum, id, size);
this->component.doDispatch();
// Check events
ASSERT_EVENTS_SIZE(0);
// Update test state
++this->abstractState.NumSuccessfulAllocations.value;
// Check port history
ASSERT_FROM_PORT_HISTORY_SIZE(2);
// Check buffer get out
ASSERT_from_bufferGetOut_SIZE(1);
ASSERT_from_bufferGetOut(0, size);
ASSERT_EQ(this->abstractState.bufferGetOutPortNumOpt.get(), portNum);
// Check product response out
ASSERT_from_productResponseOut_SIZE(1);
const Fw::Success failure(Fw::Success::SUCCESS);
const Fw::Buffer buffer(this->abstractState.bufferData, size);
ASSERT_from_productResponseOut(0, id, buffer, failure);
ASSERT_EQ(this->abstractState.productResponseOutPortNumOpt.get(), portNum);
}
bool TestState::precondition__ProductRequestIn__BufferInvalid() const {
return this->abstractState.bufferGetStatus == AbstractState::BufferGetStatus::INVALID;
}
void TestState ::action__ProductRequestIn__BufferInvalid() {
// Clear history
this->clearHistory();
// Send the invocation
const FwIndexType portNum = STest::Pick::startLength(0, DpManagerNumPorts);
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
const FwSizeType size = this->abstractState.getBufferSize();
this->invoke_to_productRequestIn(portNum, id, size);
this->component.doDispatch();
// Check events
if (this->abstractState.bufferAllocationFailedEventCount <
DpManagerComponentBase::EVENTID_BUFFERALLOCATIONFAILED_THROTTLE) {
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_BufferAllocationFailed(0, id);
++this->abstractState.bufferAllocationFailedEventCount;
} else {
ASSERT_EVENTS_SIZE(0);
}
// Update test state
++this->abstractState.NumFailedAllocations.value;
// Check port history
ASSERT_FROM_PORT_HISTORY_SIZE(2);
// Check buffer get out
ASSERT_from_bufferGetOut_SIZE(1);
ASSERT_from_bufferGetOut(0, size);
ASSERT_EQ(this->abstractState.bufferGetOutPortNumOpt.get(), portNum);
// Check product response out
ASSERT_from_productResponseOut_SIZE(1);
const Fw::Buffer buffer;
const Fw::Success status(Fw::Success::FAILURE);
ASSERT_from_productResponseOut(0, id, buffer, status);
ASSERT_EQ(this->abstractState.productResponseOutPortNumOpt.get(), portNum);
}
namespace ProductRequestIn {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::BufferValid() {
this->testState.abstractState.setBufferSize(Svc::AbstractState::MIN_BUFFER_SIZE);
this->ruleBufferValid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MAX_BUFFER_SIZE);
this->ruleBufferValid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
}
void Tester ::BufferInvalid() {
Testers::bufferGetStatus.ruleInvalid.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MIN_BUFFER_SIZE);
this->ruleBufferInvalid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MAX_BUFFER_SIZE);
this->ruleBufferInvalid.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
}
} // namespace ProductRequestIn
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/Rules.hpp | // ======================================================================
// \title Rules.hpp
// \author Rob Bocchino
// \brief Rules for testing DpManager
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_Rules_HPP
#define Svc_Rules_HPP
#include "STest/Rule/Rule.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
#define RULES_DEF_RULE(GROUP_NAME, RULE_NAME) \
namespace GROUP_NAME { \
\
struct RULE_NAME : public STest::Rule<TestState> { \
RULE_NAME() : Rule<TestState>(#GROUP_NAME "." #RULE_NAME) {} \
\
bool precondition(const TestState& state) { return state.precondition__##GROUP_NAME##__##RULE_NAME(); } \
\
void action(TestState& state) { state.action__##GROUP_NAME##__##RULE_NAME(); } \
}; \
}
namespace Svc {
namespace Rules {
RULES_DEF_RULE(BufferGetStatus, Invalid)
RULES_DEF_RULE(BufferGetStatus, Valid)
RULES_DEF_RULE(CLEAR_EVENT_THROTTLE, OK)
RULES_DEF_RULE(ProductGetIn, BufferInvalid)
RULES_DEF_RULE(ProductGetIn, BufferValid)
RULES_DEF_RULE(ProductRequestIn, BufferInvalid)
RULES_DEF_RULE(ProductRequestIn, BufferValid)
RULES_DEF_RULE(ProductSendIn, OK)
RULES_DEF_RULE(SchedIn, OK)
} // namespace Rules
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/SchedIn.cpp | // ======================================================================
// \title SchedIn.cpp
// \author Rob Bocchino
// \brief SchedIn class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Svc/DpManager/test/ut/Rules/SchedIn.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
bool TestState ::precondition__SchedIn__OK() const {
return true;
}
void TestState ::action__SchedIn__OK() {
// Clear history
this->clearHistory();
// Invoke schedIn port
const U32 context = STest::Pick::any();
this->invoke_to_schedIn(0, context);
this->component.doDispatch();
// Check telemetry
this->checkTelemetry();
}
namespace SchedIn {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::OK() {
this->ruleOK.apply(this->testState);
}
} // namespace SchedIn
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/SchedIn.hpp | // ======================================================================
// \title SchedIn.hpp
// \author Rob Bocchino
// \brief SchedIn class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_SchedIn_HPP
#define Svc_SchedIn_HPP
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace SchedIn {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! OK
void OK();
public:
// ----------------------------------------------------------------------
// Rules
// ----------------------------------------------------------------------
//! Rule SchedIn::OK
Rules::SchedIn::OK ruleOK;
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/CLEAR_EVENT_THROTTLE.cpp | // ======================================================================
// \title CLEAR_EVENT_THROTTLE.cpp
// \author Rob Bocchino
// \brief CLEAR_EVENT_THROTTLE class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Svc/DpManager/test/ut/Rules/CLEAR_EVENT_THROTTLE.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
bool TestState::precondition__CLEAR_EVENT_THROTTLE__OK() const {
return true;
}
void TestState::action__CLEAR_EVENT_THROTTLE__OK() {
// Clear history
this->clearHistory();
// Send the command
const NATIVE_INT_TYPE instance = static_cast<NATIVE_INT_TYPE>(STest::Pick::any());
const U32 cmdSeq = STest::Pick::any();
this->sendCmd_CLEAR_EVENT_THROTTLE(instance, cmdSeq);
this->component.doDispatch();
// Check the command response
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, DpManagerComponentBase::OPCODE_CLEAR_EVENT_THROTTLE, cmdSeq, Fw::CmdResponse::OK);
// Check the state
ASSERT_EQ(this->component.DpManagerComponentBase::m_BufferAllocationFailedThrottle, 0);
this->abstractState.bufferAllocationFailedEventCount = 0;
}
namespace CLEAR_EVENT_THROTTLE {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester::OK() {
Testers::bufferGetStatus.ruleInvalid.apply(this->testState);
for (FwSizeType i = 0; i <= DpManagerComponentBase::EVENTID_BUFFERALLOCATIONFAILED_THROTTLE; ++i) {
Testers::productRequestIn.ruleBufferInvalid.apply(this->testState);
}
this->ruleOK.apply(this->testState);
Testers::productRequestIn.ruleBufferInvalid.apply(this->testState);
}
} // namespace CLEAR_EVENT_THROTTLE
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/BufferGetStatus.hpp | // ======================================================================
// \title BufferGetStatus.hpp
// \author Rob Bocchino
// \brief BufferGetStatus class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_BufferGetStatus_HPP
#define Svc_BufferGetStatus_HPP
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace BufferGetStatus {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Valid
void Valid();
//! Invalid
void Invalid();
public:
// ----------------------------------------------------------------------
// Rules
// ----------------------------------------------------------------------
//! Rule BufferGetStatus::Valid
Rules::BufferGetStatus::Valid ruleValid;
//! Rule BufferGetStatus::Invalid
Rules::BufferGetStatus::Invalid ruleInvalid;
private:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/ProductSendIn.hpp | // ======================================================================
// \title ProductSendIn.hpp
// \author Rob Bocchino
// \brief ProductSendIn class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_ProductSendIn_HPP
#define Svc_ProductSendIn_HPP
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace ProductSendIn {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! OK
void OK();
public:
// ----------------------------------------------------------------------
// Rules
// ----------------------------------------------------------------------
//! Rule ProductSendIn::OK
Rules::ProductSendIn::OK ruleOK;
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/Testers.cpp | // ======================================================================
// \title Testers.cpp
// \author Rob Bocchino
// \brief Testers class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
namespace Svc {
namespace Testers {
BufferGetStatus::Tester bufferGetStatus;
CLEAR_EVENT_THROTTLE::Tester clearEventThrottle;
ProductGetIn::Tester productGetIn;
ProductRequestIn::Tester productRequestIn;
ProductSendIn::Tester productSendIn;
SchedIn::Tester schedIn;
}
}
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/ProductSendIn.cpp | // ======================================================================
// \title ProductSendIn.cpp
// \author Rob Bocchino
// \brief ProductSendIn class implementation
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Svc/DpManager/test/ut/Rules/ProductSendIn.hpp"
#include "Svc/DpManager/test/ut/Rules/Testers.hpp"
#include "config/FppConstantsAc.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
bool TestState ::precondition__ProductSendIn__OK() const {
return true;
}
void TestState ::action__ProductSendIn__OK() {
// Clear history
this->clearHistory();
// Send the invocation
const FwIndexType portNum = STest::Pick::startLength(0, DpManagerNumPorts);
const FwDpIdType id = STest::Pick::lowerUpper(0, std::numeric_limits<FwDpIdType>::max());
const FwSizeType size = this->abstractState.getBufferSize();
const Fw::Buffer buffer(this->abstractState.bufferData, size);
this->invoke_to_productSendIn(portNum, id, buffer);
this->component.doDispatch();
// Check events
ASSERT_EVENTS_SIZE(0);
// Update test state
++this->abstractState.NumDataProducts.value;
this->abstractState.NumBytes.value += size;
// Check port history
ASSERT_FROM_PORT_HISTORY_SIZE(1);
// Check product send out
ASSERT_from_productSendOut_SIZE(1);
ASSERT_from_productSendOut(0, buffer);
ASSERT_EQ(this->abstractState.productSendOutPortNumOpt.get(), portNum);
}
namespace ProductSendIn {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::OK() {
this->testState.abstractState.setBufferSize(Svc::AbstractState::MIN_BUFFER_SIZE);
this->ruleOK.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
this->testState.abstractState.setBufferSize(Svc::AbstractState::MAX_BUFFER_SIZE);
this->ruleOK.apply(this->testState);
Testers::schedIn.ruleOK.apply(this->testState);
}
} // namespace ProductSendIn
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Rules/CLEAR_EVENT_THROTTLE.hpp | // ======================================================================
// \title CLEAR_EVENT_THROTTLE.hpp
// \author Rob Bocchino
// \brief CLEAR_EVENT_THROTTLE class interface
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_CLEAR_EVENT_THROTTLE_HPP
#define Svc_CLEAR_EVENT_THROTTLE_HPP
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace CLEAR_EVENT_THROTTLE {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! OK
void OK();
public:
// ----------------------------------------------------------------------
// Rules
// ----------------------------------------------------------------------
//! Rule CLEAR_EVENT_THROTTLE::OK
Rules::CLEAR_EVENT_THROTTLE::OK ruleOK;
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
}
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/TestState/TestState.hpp | // ======================================================================
// \title TestState.hpp
// \author Rob Bocchino
// \brief Test state for testing DpManager
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_TestState_HPP
#define Svc_TestState_HPP
#include "Svc/DpManager/test/ut/DpManagerTester.hpp"
#define TEST_STATE_DEF_RULE(GROUP_NAME, RULE_NAME) \
bool precondition__##GROUP_NAME##__##RULE_NAME() const; \
void action__##GROUP_NAME##__##RULE_NAME();
namespace Svc {
class TestState : public DpManagerTester {
public:
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
TEST_STATE_DEF_RULE(BufferGetStatus, Invalid)
TEST_STATE_DEF_RULE(BufferGetStatus, Valid)
TEST_STATE_DEF_RULE(CLEAR_EVENT_THROTTLE, OK)
TEST_STATE_DEF_RULE(ProductGetIn, BufferInvalid)
TEST_STATE_DEF_RULE(ProductGetIn, BufferValid)
TEST_STATE_DEF_RULE(ProductRequestIn, BufferInvalid)
TEST_STATE_DEF_RULE(ProductRequestIn, BufferValid)
TEST_STATE_DEF_RULE(ProductSendIn, OK)
TEST_STATE_DEF_RULE(SchedIn, OK)
};
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Scenarios/Random.hpp | // ======================================================================
// \title Random.hpp
// \author Rob Bocchino
// \brief Random scenario
//
// \copyright
// Copyright (C) 2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#ifndef Svc_Random_HPP
#define Svc_Random_HPP
#include "Svc/DpManager/test/ut/TestState/TestState.hpp"
namespace Svc {
namespace Scenarios {
namespace Random {
class Tester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Run the random scenario
void run(FwSizeType maxNumSteps //!< The maximum number of steps
);
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! Test state
TestState testState;
};
} // namespace Random
} // namespace Scenarios
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/DpManager/test/ut/Scenarios/Random.cpp | // ======================================================================
// \title Random.hpp
// \author Rob Bocchino
// \brief Random scenario
//
// \copyright
// Copyright (C) 2021 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
// ======================================================================
#include "STest/Scenario/BoundedScenario.hpp"
#include "STest/Scenario/RandomScenario.hpp"
#include "Svc/DpManager/test/ut/Rules/Rules.hpp"
#include "Svc/DpManager/test/ut/Scenarios/Random.hpp"
namespace Svc {
namespace Scenarios {
namespace Random {
// ----------------------------------------------------------------------
// Rule definitions
// ----------------------------------------------------------------------
Rules::BufferGetStatus::Invalid bufferGetStatusInvalid;
Rules::BufferGetStatus::Valid bufferGetStatusValid;
Rules::CLEAR_EVENT_THROTTLE::OK clearEventThrottleOK;
Rules::ProductRequestIn::BufferInvalid productRequestInBufferInvalid;
Rules::ProductRequestIn::BufferValid productRequestInBufferValid;
Rules::ProductSendIn::OK productSendInOK;
Rules::SchedIn::OK schedInOK;
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::run(FwSizeType maxNumSteps) {
STest::Rule<TestState>* rules[] = {
&bufferGetStatusInvalid,
&bufferGetStatusValid,
&clearEventThrottleOK,
&productRequestInBufferInvalid,
&productRequestInBufferValid,
&productSendInOK,
&schedInOK
};
STest::RandomScenario<TestState> scenario("RandomScenario", rules,
sizeof(rules) / sizeof(STest::RandomScenario<TestState>*));
STest::BoundedScenario<TestState> boundedScenario("BoundedRandomScenario", scenario, maxNumSteps);
const U32 numSteps = boundedScenario.run(this->testState);
printf("Ran %u steps.\n", numSteps);
}
} // namespace Random
} // namespace Scenarios
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/PassiveConsoleTextLogger/ConsoleTextLoggerImpl.hpp | #ifndef SVC_TEXT_LOGGER_IMPL_HPP
#define SVC_TEXT_LOGGER_IMPL_HPP
#include <Svc/PassiveConsoleTextLogger/PassiveTextLoggerComponentAc.hpp>
namespace Svc {
class ConsoleTextLoggerImpl : public PassiveTextLoggerComponentBase {
public:
// Only called by derived class
ConsoleTextLoggerImpl(const char* compName);
void init(NATIVE_INT_TYPE instanceId = 0);
~ConsoleTextLoggerImpl();
private:
// downcalls for input ports
void TextLogger_handler(NATIVE_INT_TYPE portNum, FwEventIdType id, Fw::Time &timeTag, const Fw::LogSeverity& severity, Fw::TextLogString &text);
};
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/PassiveConsoleTextLogger/PassiveTextLogger.hpp | // ======================================================================
// PassiveTextLogger.hpp
// Standardization header for PassiveTextLogger
// ======================================================================
#ifndef Svc_PassiveTextLogger_HPP
#define Svc_PassiveTextLogger_HPP
#include "Svc/PassiveConsoleTextLogger/ConsoleTextLoggerImpl.hpp"
namespace Svc {
typedef ConsoleTextLoggerImpl PassiveTextLogger;
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/PassiveConsoleTextLogger/ConsoleTextLoggerImplCommon.cpp | #include <Svc/PassiveConsoleTextLogger/ConsoleTextLoggerImpl.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Logger/Logger.hpp>
namespace Svc {
ConsoleTextLoggerImpl::ConsoleTextLoggerImpl(const char* compName) :
PassiveTextLoggerComponentBase(compName) {
}
void ConsoleTextLoggerImpl::init(NATIVE_INT_TYPE instanceId) {
PassiveTextLoggerComponentBase::init(instanceId);
}
ConsoleTextLoggerImpl::~ConsoleTextLoggerImpl() {}
void ConsoleTextLoggerImpl::TextLogger_handler(NATIVE_INT_TYPE portNum, FwEventIdType id, Fw::Time &timeTag, const Fw::LogSeverity& severity, Fw::TextLogString &text) {
const char *severityString = "UNKNOWN";
switch (severity.e) {
case Fw::LogSeverity::FATAL:
severityString = "FATAL";
break;
case Fw::LogSeverity::WARNING_HI:
severityString = "WARNING_HI";
break;
case Fw::LogSeverity::WARNING_LO:
severityString = "WARNING_LO";
break;
case Fw::LogSeverity::COMMAND:
severityString = "COMMAND";
break;
case Fw::LogSeverity::ACTIVITY_HI:
severityString = "ACTIVITY_HI";
break;
case Fw::LogSeverity::ACTIVITY_LO:
severityString = "ACTIVITY_LO";
break;
case Fw::LogSeverity::DIAGNOSTIC:
severityString = "DIAGNOSTIC";
break;
default:
severityString = "SEVERITY ERROR";
break;
}
Fw::Logger::logMsg("EVENT: (%" PRI_FwEventIdType ") (%" PRI_FwTimeBaseStoreType ":%" PRIu32 ",%" PRIu32 ") %s: %s\n",
id, static_cast<FwTimeBaseStoreType>(timeTag.getTimeBase()), timeTag.getSeconds(), timeTag.getUSeconds(),
reinterpret_cast<PlatformPointerCastType>(severityString), reinterpret_cast<PlatformPointerCastType>(text.toChar()));
}
}
| cpp |
fprime | data/projects/fprime/Svc/PassiveRateGroup/PassiveRateGroup.cpp | /*
* \author: Tim Canham
* \file:
* \brief
*
* This file implements the PassiveRateGroup component,
* which invokes a set of components the comprise the rate group.
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/Log.hpp>
#include <Svc/PassiveRateGroup/PassiveRateGroup.hpp>
namespace Svc {
PassiveRateGroup::PassiveRateGroup(const char* compName)
: PassiveRateGroupComponentBase(compName), m_cycles(0), m_maxTime(0), m_numContexts(0) {
}
PassiveRateGroup::~PassiveRateGroup() {}
void PassiveRateGroup::configure(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts) {
FW_ASSERT(contexts);
FW_ASSERT(numContexts == this->getNum_RateGroupMemberOut_OutputPorts(),numContexts,this->getNum_RateGroupMemberOut_OutputPorts());
FW_ASSERT(FW_NUM_ARRAY_ELEMENTS(this->m_contexts) == this->getNum_RateGroupMemberOut_OutputPorts(),
FW_NUM_ARRAY_ELEMENTS(this->m_contexts),
this->getNum_RateGroupMemberOut_OutputPorts());
this->m_numContexts = numContexts;
// copy context values
for (NATIVE_INT_TYPE entry = 0; entry < this->m_numContexts; entry++) {
this->m_contexts[entry] = contexts[entry];
}
}
void PassiveRateGroup::CycleIn_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart) {
TimerVal end;
FW_ASSERT(this->m_numContexts);
// invoke any members of the rate group
for (NATIVE_INT_TYPE port = 0; port < this->getNum_RateGroupMemberOut_OutputPorts(); port++) {
if (this->isConnected_RateGroupMemberOut_OutputPort(port)) {
this->RateGroupMemberOut_out(port, this->m_contexts[port]);
}
}
// grab timer for end of cycle
end.take();
// get rate group execution time
U32 cycle_time = end.diffUSec(cycleStart);
// check to see if the time has exceeded the previous maximum
if (cycle_time > this->m_maxTime) {
this->m_maxTime = cycle_time;
}
this->tlmWrite_MaxCycleTime(this->m_maxTime);
this->tlmWrite_CycleTime(cycle_time);
this->tlmWrite_CycleCount(++this->m_cycles);
}
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/PassiveRateGroup/PassiveRateGroup.hpp | /*
* \author: Tim Canham
* \file:
* \brief
*
* This file implements the PassiveRateGroup component,
* which invokes a set of components the comprise the rate group.
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#ifndef SVC_PASSIVERATEGROUP_IMPL_HPP
#define SVC_PASSIVERATEGROUP_IMPL_HPP
#include <Svc/PassiveRateGroup/PassiveRateGroupComponentAc.hpp>
namespace Svc {
//! \class PassiveRateGroupImpl
//! \brief Executes a set of components as part of a rate group
//!
//! PassiveRateGroup takes an input cycle call to begin the rate group cycle.
//! It calls each output port in succession and passes the value in the context
//! array at the index corresponding to the output port number. It keeps track of the execution
//! time of the rate group and detects overruns.
//!
class PassiveRateGroup : public PassiveRateGroupComponentBase {
public:
//! \brief PassiveRateGroupImpl constructor
//!
//! The constructor of the class clears all the flags and copies the
//! contents of the context array to private storage.
//!
//! \param compName Name of the component
explicit PassiveRateGroup(const char* compName); //! \brief PassiveRateGroupImpl initialization function
//! \brief PassiveRateGroup configuration function
//!
//! The configuration function takes an array of context values to pass to
//! members of the rate group.
//!
//! \param contexts Array of integers that contain the context values that will be sent
//! to each member component. The index of the array corresponds to the
//! output port number.
//! \param numContexts The number of elements in the context array.
void configure(NATIVE_INT_TYPE contexts[], NATIVE_INT_TYPE numContexts);
//! \brief PassiveRateGroupImpl destructor
//!
//! The destructor of the class is empty
~PassiveRateGroup();
PRIVATE:
//! \brief Input cycle port handler
//!
//! The cycle port handler calls each component in the rate group in turn,
//! passing the context value. It computes the execution time each cycle,
//! and writes it to a telemetry value if it reaches a maximum time
//!
//! \param portNum incoming port call. For this class, should always be zero
//! \param cycleStart value stored by the cycle driver, used to compute execution time.
void CycleIn_handler(NATIVE_INT_TYPE portNum, Svc::TimerVal& cycleStart);
U32 m_cycles; //!< cycles executed
U32 m_maxTime; //!< maximum execution time in microseconds
NATIVE_INT_TYPE m_numContexts; //!< number of contexts
U32 m_contexts[NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS]; //!< Must match number of output ports
};
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/PassiveRateGroup/test/ut/PassiveRateGroupImplTester.cpp | /*
* \author Tim Canham
* \file
* \brief
*
* This file is the test component for the active rate group unit test.
*
* Code Generated Source Code Header
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#include <gtest/gtest.h>
#include <Fw/Test/UnitTest.hpp>
#include <Svc/PassiveRateGroup/test/ut/PassiveRateGroupTester.hpp>
#include <cstdio>
#include <cstring>
#include <unistd.h>
namespace Svc {
void PassiveRateGroupTester::init(NATIVE_INT_TYPE instance) {
PassiveRateGroupGTestBase::init();
}
PassiveRateGroupTester::PassiveRateGroupTester(Svc::PassiveRateGroup& inst)
: PassiveRateGroupGTestBase("testerbase", 100), m_impl(inst), m_callOrder(0) {
this->clearPortCalls();
}
void PassiveRateGroupTester::clearPortCalls() {
memset(this->m_callLog, 0, sizeof(this->m_callLog));
this->m_callOrder = 0;
}
PassiveRateGroupTester::~PassiveRateGroupTester() {}
void PassiveRateGroupTester::from_RateGroupMemberOut_handler(NATIVE_INT_TYPE portNum, U32 context) {
ASSERT_TRUE(portNum < static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(m_impl.m_RateGroupMemberOut_OutputPort)));
this->m_callLog[portNum].portCalled = true;
this->m_callLog[portNum].contextVal = context;
this->m_callLog[portNum].order = this->m_callOrder++;
// Adding a small sleep to ensure that the cycle time is bigger than 0 us
usleep(1);
}
void PassiveRateGroupTester::runNominal(NATIVE_INT_TYPE contexts[],
NATIVE_UINT_TYPE numContexts,
NATIVE_INT_TYPE instance) {
TEST_CASE(101.1.1, "Run nominal rate group execution");
// clear events
this->clearTlm();
Svc::TimerVal timer;
timer.take();
// clear port call log
this->clearPortCalls();
REQUIREMENT("FPRIME-PRG-001");
// call active rate group with timer val
this->invoke_to_CycleIn(0, timer);
// check calls
REQUIREMENT("FPRIME-PRG-002");
for (NATIVE_UINT_TYPE portNum = 0;
portNum < static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(this->m_impl.m_RateGroupMemberOut_OutputPort)); portNum++) {
ASSERT_TRUE(this->m_callLog[portNum].portCalled);
ASSERT_EQ(this->m_callLog[portNum].contextVal, contexts[portNum]);
ASSERT_EQ(this->m_callLog[portNum].order, portNum);
}
// Cycle times should be non-zero
REQUIREMENT("FPRIME-PRG-003");
ASSERT_TLM_MaxCycleTime_SIZE(1);
ASSERT_TLM_CycleTime_SIZE(1);
ASSERT_TLM_CycleCount_SIZE(1);
ASSERT_GT(this->tlmHistory_MaxCycleTime->at(0).arg, 0);
ASSERT_GT(this->tlmHistory_CycleTime->at(0).arg, 0);
ASSERT_GT(this->tlmHistory_CycleCount->at(0).arg, 0);
}
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/PassiveRateGroup/test/ut/PassiveRateGroupImplTester.hpp | /*
* \author Tim Canham
* \file
* \brief
*
* This file is the test component header for the active rate group unit test.
*
* Code Generated Source Code Header
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#ifndef PASSIVERATEGROUP_TEST_UT_PASSIVERATEGROUPIMPLTESTER_HPP_
#define PASSIVERATEGROUP_TEST_UT_PASSIVERATEGROUPIMPLTESTER_HPP_
#include <PassiveRateGroupGTestBase.hpp>
#include <Svc/PassiveRateGroup/PassiveRateGroup.hpp>
namespace Svc {
class PassiveRateGroupTester: public PassiveRateGroupGTestBase {
public:
PassiveRateGroupTester(Svc::PassiveRateGroup& inst);
virtual ~PassiveRateGroupTester();
void init(NATIVE_INT_TYPE instance = 0);
void runNominal(U32 contexts[], U32 numContexts, NATIVE_INT_TYPE instance);
private:
void from_RateGroupMemberOut_handler(NATIVE_INT_TYPE portNum, U32 context);
Svc::PassiveRateGroup& m_impl;
void clearPortCalls();
struct {
bool portCalled;
U32 contextVal;
NATIVE_UINT_TYPE order;
} m_callLog[Svc::PassiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS];
bool m_causeOverrun; //!< flag to cause an overrun during a rate group member port call
NATIVE_UINT_TYPE m_callOrder; //!< tracks order of port call.
};
} /* namespace Svc */
#endif /* PASSIVERATEGROUP_TEST_UT_PASSIVERATEGROUPIMPLTESTER_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/PassiveRateGroup/test/ut/PassiveRateGroupTester.cpp | /*
* \author Tim Canham
* \file
* \brief
*
* This file is the test driver for the active rate group unit test.
*
* Code Generated Source Code Header
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#include <config/FppConstantsAc.hpp>
#include <Fw/Obj/SimpleObjRegistry.hpp>
#include <Svc/PassiveRateGroup/PassiveRateGroup.hpp>
#include <Svc/PassiveRateGroup/test/ut/PassiveRateGroupTester.hpp>
#include <gtest/gtest.h>
void connectPorts(Svc::PassiveRateGroup& impl, Svc::PassiveRateGroupTester& tester) {
tester.connect_to_CycleIn(0, impl.get_CycleIn_InputPort(0));
for (NATIVE_INT_TYPE portNum = 0;
portNum < static_cast<NATIVE_INT_TYPE>(FW_NUM_ARRAY_ELEMENTS(impl.m_RateGroupMemberOut_OutputPort)); portNum++) {
impl.set_RateGroupMemberOut_OutputPort(portNum, tester.get_from_RateGroupMemberOut(portNum));
}
impl.set_Tlm_OutputPort(0, tester.get_from_Tlm(0));
impl.set_Time_OutputPort(0, tester.get_from_Time(0));
}
TEST(PassiveRateGroupTest, NominalSchedule) {
for (NATIVE_INT_TYPE inst = 0; inst < 3; inst++) {
NATIVE_INT_TYPE contexts[FppConstant_PassiveRateGroupOutputPorts::PassiveRateGroupOutputPorts] = {1, 2, 3, 4, 5};
Svc::PassiveRateGroup impl("PassiveRateGroup");
impl.configure(contexts, FW_NUM_ARRAY_ELEMENTS(contexts));
Svc::PassiveRateGroupTester tester(impl);
tester.init();
impl.init(inst);
// connect ports
connectPorts(impl, tester);
tester.runNominal(contexts, FW_NUM_ARRAY_ELEMENTS(contexts), inst);
}
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/PassiveRateGroup/test/ut/PassiveRateGroupTester.hpp | /*
* \author Tim Canham
* \file
* \brief
*
* This file is the test component header for the active rate group unit test.
*
* Code Generated Source Code Header
*
* Copyright 2014-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*/
#ifndef PASSIVERATEGROUP_TEST_UT_PASSIVERATEGROUPIMPLTESTER_HPP_
#define PASSIVERATEGROUP_TEST_UT_PASSIVERATEGROUPIMPLTESTER_HPP_
#include <PassiveRateGroupGTestBase.hpp>
#include <Svc/PassiveRateGroup/PassiveRateGroup.hpp>
namespace Svc {
class PassiveRateGroupTester: public PassiveRateGroupGTestBase {
public:
PassiveRateGroupTester(Svc::PassiveRateGroup& inst);
virtual ~PassiveRateGroupTester();
void init(NATIVE_INT_TYPE instance = 0);
void runNominal(NATIVE_INT_TYPE contexts[], U32 numContexts, NATIVE_INT_TYPE instance);
private:
void from_RateGroupMemberOut_handler(NATIVE_INT_TYPE portNum, U32 context);
Svc::PassiveRateGroup& m_impl;
void clearPortCalls();
struct {
bool portCalled;
U32 contextVal;
NATIVE_UINT_TYPE order;
} m_callLog[Svc::PassiveRateGroupComponentBase::NUM_RATEGROUPMEMBEROUT_OUTPUT_PORTS];
U32 m_callOrder; //!< tracks order of port call.
};
} /* namespace Svc */
#endif /* PASSIVERATEGROUP_TEST_UT_PASSIVERATEGROUPIMPLTESTER_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/PrmDb/PrmDbImpl.hpp | /**
* \file
* \author T.Canham
* \brief Component for managing parameters
*
* \copyright
* Copyright 2009-2015, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
* <br /><br />
*/
#ifndef PRMDBIMPL_HPP_
#define PRMDBIMPL_HPP_
#include <Svc/PrmDb/PrmDbComponentAc.hpp>
#include <PrmDbImplCfg.hpp>
#include <Fw/Types/String.hpp>
#include <Os/Mutex.hpp>
namespace Svc {
//! \class PrmDbImpl
//! \brief Component class for managing parameters
//!
//! This component supports storing, setting and saving of serialized parameters
//! for components.
//!
class PrmDbImpl : public PrmDbComponentBase {
public:
friend class PrmDbImplTester;
//! \brief PrmDb constructor
//!
//! The constructor for the PrmDbImpl class.
//! The constructor clears the database and stores
//! the file name for opening later.
//!
//! \param name component instance name
PrmDbImpl(const char* name);
//! \brief PrmDb initialization function
//!
//! The initialization function for the component creates the message
//! queue and initializes the component base classes.
//!
//! \param queueDepth queue depth for messages
//! \param instance instance of component, if more than one is needed.
void init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance);
//! \brief PrmDb configure method
//!
//! The configure method stores the file name for opening later.
//!
//! \param file file where parameters are stored.
void configure(const char* file);
//! \brief PrmDb file read function
//!
//! The readFile function reads the set of parameters from the file passed in to
//! the constructor.
//!
void readParamFile(); // NOTE: Assumed to run at initialization time. No guard of data structure.
//! \brief PrmDb destructor
//!
virtual ~PrmDbImpl();
protected:
private:
//! \brief PrmDb parameter get handler
//!
//! This function retrieves a parameter value from the loaded set of stored parameters
//!
//! \param portNum input port number. Should always be zero
//! \param id identifier for parameter being used.
//! \param val buffer where value is placed.
//! \return status of retrieval. PARAM_VALID = successful read, PARAM_INVALID = unsuccessful read
Fw::ParamValid getPrm_handler(NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer &val);
//! \brief PrmDb parameter set handler
//!
//! This function updates the value of the parameter stored in RAM. The PRM_SAVE_FILE
//! must be called to save the value to a file.
//!
//! \param portNum input port number. Should always be zero
//! \param id identifier for parameter being used.
//! \param val buffer where value to be saved is stored.
void setPrm_handler(NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer &val);
//! \brief component ping handler
//!
//! The ping handler responds to messages to verify that the task
//! is still executing. Will call output ping port
//!
//! \param portNum the number of the incoming port.
//! \param opCode the opcode being registered.
//! \param key the key value that is returned with the ping response
void pingIn_handler(NATIVE_INT_TYPE portNum, U32 key);
//! \brief PrmDb PRM_SAVE_FILE command handler
//!
//! This function saves the parameter values stored in RAM to the file
//! specified in the constructor. Any updates to parameters are not saved
//! until this function is called.
//!
//! \param opCode The opcode of this commands
//! \param cmdSeq The sequence number of the command
void PRM_SAVE_FILE_cmdHandler(FwOpcodeType opCode, U32 cmdSeq);
//! \brief PrmDb clear database function
//!
//! This function clears all entries from the RAM database
//!
void clearDb(); //!< clear the parameter database
Fw::String m_fileName; //!< filename for parameter storage
struct t_dbStruct {
bool used; //!< whether slot is being used
FwPrmIdType id; //!< the id being stored in the slot
Fw::ParamBuffer val; //!< the serialized value of the parameter
} m_db[PRMDB_NUM_DB_ENTRIES];
};
}
#endif /* PRMDBIMPL_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/PrmDb/PrmDbImpl.cpp | /*
* PrmDbImpl.cpp
*
* Created on: March 9, 2015
* Author: Timothy Canham
*/
#include <Svc/PrmDb/PrmDbImpl.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/File.hpp>
#include <cstring>
#include <cstdio>
namespace Svc {
typedef PrmDb_PrmWriteError PrmWriteError;
typedef PrmDb_PrmReadError PrmReadError;
// anonymous namespace for buffer declaration
namespace {
class WorkingBuffer : public Fw::SerializeBufferBase {
public:
NATIVE_UINT_TYPE getBuffCapacity() const {
return sizeof(m_buff);
}
U8* getBuffAddr() {
return m_buff;
}
const U8* getBuffAddr() const {
return m_buff;
}
private:
// Set to max of parameter buffer + id
U8 m_buff[FW_PARAM_BUFFER_MAX_SIZE + sizeof(FwPrmIdType)];
};
}
PrmDbImpl::PrmDbImpl(const char* name) : PrmDbComponentBase(name) {
this->clearDb();
}
void PrmDbImpl::configure(const char* file) {
FW_ASSERT(file != nullptr);
this->m_fileName = file;
}
void PrmDbImpl::init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance) {
PrmDbComponentBase::init(queueDepth,instance);
}
void PrmDbImpl::clearDb() {
for (I32 entry = 0; entry < PRMDB_NUM_DB_ENTRIES; entry++) {
this->m_db[entry].used = false;
this->m_db[entry].id = 0;
}
}
// If ports are no longer guarded, these accesses need to be protected from each other
// If there are a lot of accesses, perhaps an interrupt lock could be used instead of guarded ports
Fw::ParamValid PrmDbImpl::getPrm_handler(NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer &val) {
// search for entry
Fw::ParamValid stat = Fw::ParamValid::INVALID;
for (I32 entry = 0; entry < PRMDB_NUM_DB_ENTRIES; entry++) {
if (this->m_db[entry].used) {
if (this->m_db[entry].id == id) {
val = this->m_db[entry].val;
stat = Fw::ParamValid::VALID;
break;
}
}
}
// if unable to find parameter, send error message
if (Fw::ParamValid::INVALID == stat.e) {
this->log_WARNING_LO_PrmIdNotFound(id);
}
return stat;
}
void PrmDbImpl::setPrm_handler(NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer &val) {
this->lock();
// search for existing entry
bool existingEntry = false;
bool noSlots = true;
for (NATIVE_INT_TYPE entry = 0; entry < PRMDB_NUM_DB_ENTRIES; entry++) {
if ((this->m_db[entry].used) && (id == this->m_db[entry].id)) {
this->m_db[entry].val = val;
existingEntry = true;
break;
}
}
// if there is no existing entry, add one
if (!existingEntry) {
for (I32 entry = 0; entry < PRMDB_NUM_DB_ENTRIES; entry++) {
if (!(this->m_db[entry].used)) {
this->m_db[entry].val = val;
this->m_db[entry].id = id;
this->m_db[entry].used = true;
noSlots = false;
break;
}
}
}
this->unLock();
if (existingEntry) {
this->log_ACTIVITY_HI_PrmIdUpdated(id);
} else if (noSlots) {
this->log_FATAL_PrmDbFull(id);
} else {
this->log_ACTIVITY_HI_PrmIdAdded(id);
}
}
void PrmDbImpl::PRM_SAVE_FILE_cmdHandler(FwOpcodeType opCode, U32 cmdSeq) {
FW_ASSERT(this->m_fileName.length() > 0);
Os::File paramFile;
WorkingBuffer buff;
Os::File::Status stat = paramFile.open(this->m_fileName.toChar(),Os::File::OPEN_WRITE);
if (stat != Os::File::OP_OK) {
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::OPEN,0,stat);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
this->lock();
// Traverse the parameter list, saving each entry
U32 numRecords = 0;
for (NATIVE_UINT_TYPE entry = 0; entry < FW_NUM_ARRAY_ELEMENTS(this->m_db); entry++) {
if (this->m_db[entry].used) {
// write delimiter
static const U8 delim = PRMDB_ENTRY_DELIMITER;
FwSignedSizeType writeSize = static_cast<FwSignedSizeType>(sizeof(delim));
stat = paramFile.write(&delim,writeSize,Os::File::WaitType::WAIT);
if (stat != Os::File::OP_OK) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::DELIMITER,numRecords,stat);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
if (writeSize != sizeof(delim)) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::DELIMITER_SIZE,numRecords,writeSize);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
// serialize record size = id field + data
U32 recordSize = sizeof(FwPrmIdType) + this->m_db[entry].val.getBuffLength();
// reset buffer
buff.resetSer();
Fw::SerializeStatus serStat = buff.serialize(recordSize);
// should always work
FW_ASSERT(Fw::FW_SERIALIZE_OK == serStat,static_cast<NATIVE_INT_TYPE>(serStat));
// write record size
writeSize = buff.getBuffLength();
stat = paramFile.write(buff.getBuffAddr(),writeSize,Os::File::WaitType::WAIT);
if (stat != Os::File::OP_OK) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::RECORD_SIZE,numRecords,stat);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
if (writeSize != sizeof(recordSize)) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::RECORD_SIZE_SIZE,numRecords,writeSize);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
// reset buffer
buff.resetSer();
// serialize parameter id
serStat = buff.serialize(this->m_db[entry].id);
// should always work
FW_ASSERT(Fw::FW_SERIALIZE_OK == serStat,static_cast<NATIVE_INT_TYPE>(serStat));
// write parameter ID
writeSize = buff.getBuffLength();
stat = paramFile.write(buff.getBuffAddr(),writeSize,Os::File::WaitType::WAIT);
if (stat != Os::File::OP_OK) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::PARAMETER_ID,numRecords,stat);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
if (writeSize != static_cast<FwSignedSizeType>(buff.getBuffLength())) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::PARAMETER_ID_SIZE,numRecords,writeSize);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
// write serialized parameter value
writeSize = this->m_db[entry].val.getBuffLength();
stat = paramFile.write(this->m_db[entry].val.getBuffAddr(),writeSize,Os::File::WaitType::WAIT);
if (stat != Os::File::OP_OK) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::PARAMETER_VALUE,numRecords,stat);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
if (writeSize != static_cast<FwSignedSizeType>(this->m_db[entry].val.getBuffLength())) {
this->unLock();
this->log_WARNING_HI_PrmFileWriteError(PrmWriteError::PARAMETER_VALUE_SIZE,numRecords,writeSize);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::EXECUTION_ERROR);
return;
}
numRecords++;
} // end if record in use
} // end for each record
this->unLock();
this->log_ACTIVITY_HI_PrmFileSaveComplete(numRecords);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
PrmDbImpl::~PrmDbImpl() {
}
void PrmDbImpl::readParamFile() {
FW_ASSERT(this->m_fileName.length() > 0);
// load file. FIXME: Put more robust file checking, such as a CRC.
Os::File paramFile;
Os::File::Status stat = paramFile.open(this->m_fileName.toChar(),Os::File::OPEN_READ);
if (stat != Os::File::OP_OK) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::OPEN,0,stat);
return;
}
WorkingBuffer buff;
U32 recordNum = 0;
this->clearDb();
for (NATIVE_INT_TYPE entry = 0; entry < PRMDB_NUM_DB_ENTRIES; entry++) {
U8 delimiter;
FwSignedSizeType readSize = static_cast<FwSignedSizeType>(sizeof(delimiter));
// read delimiter
Os::File::Status fStat = paramFile.read(&delimiter,readSize,Os::File::WaitType::WAIT);
// check for end of file (read size 0)
if (0 == readSize) {
break;
}
if (fStat != Os::File::OP_OK) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::DELIMITER,recordNum,fStat);
return;
}
if (sizeof(delimiter) != readSize) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::DELIMITER_SIZE,recordNum,readSize);
return;
}
if (PRMDB_ENTRY_DELIMITER != delimiter) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::DELIMITER_VALUE,recordNum,delimiter);
return;
}
U32 recordSize = 0;
// read record size
readSize = sizeof(recordSize);
fStat = paramFile.read(buff.getBuffAddr(),readSize,Os::File::WaitType::WAIT);
if (fStat != Os::File::OP_OK) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::RECORD_SIZE,recordNum,fStat);
return;
}
if (sizeof(recordSize) != readSize) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::RECORD_SIZE_SIZE,recordNum,readSize);
return;
}
// set serialized size to read size
Fw::SerializeStatus desStat = buff.setBuffLen(readSize);
// should never fail
FW_ASSERT(Fw::FW_SERIALIZE_OK == desStat,static_cast<NATIVE_INT_TYPE>(desStat));
// reset deserialization
buff.resetDeser();
// deserialize, since record size is serialized in file
desStat = buff.deserialize(recordSize);
FW_ASSERT(Fw::FW_SERIALIZE_OK == desStat);
// sanity check value. It can't be larger than the maximum parameter buffer size + id
// or smaller than the record id
if ((recordSize > FW_PARAM_BUFFER_MAX_SIZE + sizeof(U32)) or (recordSize < sizeof(U32))) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::RECORD_SIZE_VALUE,recordNum,recordSize);
return;
}
// read the parameter ID
FwPrmIdType parameterId = 0;
readSize = static_cast<FwSignedSizeType>(sizeof(FwPrmIdType));
fStat = paramFile.read(buff.getBuffAddr(),readSize,Os::File::WaitType::WAIT);
if (fStat != Os::File::OP_OK) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::PARAMETER_ID,recordNum,fStat);
return;
}
if (sizeof(parameterId) != static_cast<FwSizeType>(readSize)) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::PARAMETER_ID_SIZE,recordNum,readSize);
return;
}
// set serialized size to read parameter ID
desStat = buff.setBuffLen(readSize);
// should never fail
FW_ASSERT(Fw::FW_SERIALIZE_OK == desStat,static_cast<NATIVE_INT_TYPE>(desStat));
// reset deserialization
buff.resetDeser();
// deserialize, since parameter ID is serialized in file
desStat = buff.deserialize(parameterId);
FW_ASSERT(Fw::FW_SERIALIZE_OK == desStat);
// copy parameter
this->m_db[entry].used = true;
this->m_db[entry].id = parameterId;
readSize = recordSize-sizeof(parameterId);
fStat = paramFile.read(this->m_db[entry].val.getBuffAddr(),readSize);
if (fStat != Os::File::OP_OK) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::PARAMETER_VALUE,recordNum,fStat);
return;
}
if (static_cast<U32>(readSize) != recordSize-sizeof(parameterId)) {
this->log_WARNING_HI_PrmFileReadError(PrmReadError::PARAMETER_VALUE_SIZE,recordNum,readSize);
return;
}
// set serialized size to read size
desStat = this->m_db[entry].val.setBuffLen(readSize);
// should never fail
FW_ASSERT(Fw::FW_SERIALIZE_OK == desStat,static_cast<NATIVE_INT_TYPE>(desStat));
recordNum++;
}
this->log_ACTIVITY_HI_PrmFileLoadComplete(recordNum);
}
void PrmDbImpl::pingIn_handler(NATIVE_INT_TYPE portNum, U32 key) {
// respond to ping
this->pingOut_out(0,key);
}
}
| cpp |
fprime | data/projects/fprime/Svc/PrmDb/PrmDb.hpp | // ======================================================================
// PrmDb.hpp
// Standardization header for PrmDb
// ======================================================================
#ifndef Svc_PrmDb_HPP
#define Svc_PrmDb_HPP
#include "Svc/PrmDb/PrmDbImpl.hpp"
namespace Svc {
typedef PrmDbImpl PrmDb;
}
#endif
| hpp |
fprime | data/projects/fprime/Svc/PrmDb/test/ut/PrmDbImplTester.cpp | /*
* PrmDbImplTester.cpp
*
* Created on: Mar 18, 2015
* Author: tcanham
*/
#include <Svc/PrmDb/test/ut/PrmDbImplTester.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Fw/Com/ComPacket.hpp>
#include <Os/Stub/test/File.hpp>
#include <cstdio>
#include <gtest/gtest.h>
#include <Fw/Test/UnitTest.hpp>
namespace Svc {
typedef PrmDb_PrmWriteError PrmWriteError;
typedef PrmDb_PrmReadError PrmReadError;
void PrmDbImplTester::runNominalPopulate() {
// clear database
this->m_impl.clearDb();
// build a test parameter value with a simple value
U32 val = 0x10;
FwPrmIdType id = 0x21;
Fw::ParamBuffer pBuff;
Fw::SerializeStatus stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
static bool pdb003 = false;
if (not pdb003) {
REQUIREMENT("PDB-003");
pdb003 = true;
}
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdAdded_SIZE(1);
ASSERT_EVENTS_PrmIdAdded(0,id);
// retrieve it
U32 testVal;
static bool pdb002 = false;
if (not pdb002) {
REQUIREMENT("PDB-002");
pdb002 = true;
}
this->invoke_to_getPrm(0,id,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,val);
// update the value
val = 0x15;
pBuff.resetSer();
stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// retrieve it
pBuff.resetSer();
testVal = 0;
this->invoke_to_getPrm(0,id,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,val);
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdUpdated_SIZE(1);
ASSERT_EVENTS_PrmIdUpdated(0,id);
// add a new entry
id = 0x25;
val = 0x30;
pBuff.resetSer();
stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdAdded_SIZE(1);
ASSERT_EVENTS_PrmIdAdded(0,id);
}
void PrmDbImplTester::runNominalSaveFile() {
Os::Stub::File::Test::StaticData::setWriteResult(m_io_data, sizeof m_io_data);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
// fill with data
this->runNominalPopulate();
// save the data
this->clearEvents();
this->clearHistory();
static bool pdb004 = false;
if (not pdb004) {
REQUIREMENT("PDB-004");
pdb004 = true;
}
this->sendCmd_PRM_SAVE_FILE(0,12);
Fw::QueuedComponentBase::MsgDispatchStatus stat = this->m_impl.doDispatch();
EXPECT_EQ(stat,Fw::QueuedComponentBase::MSG_DISPATCH_OK);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0,PrmDbImpl::OPCODE_PRM_SAVE_FILE,12,Fw::CmdResponse::OK);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmFileSaveComplete_SIZE(1);
ASSERT_EVENTS_PrmFileSaveComplete(0,2);
}
void PrmDbImplTester::runNominalLoadFile() {
// Preconditions to populate the write file
this->runNominalSaveFile();
Os::Stub::File::Test::StaticData::setReadResult(m_io_data, Os::Stub::File::Test::StaticData::data.pointer);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
// save the data
this->clearEvents();
static bool pdb001 = false;
if (not pdb001) {
REQUIREMENT("PDB-001");
pdb001 = true;
}
this->m_impl.readParamFile();
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmFileLoadComplete_SIZE(1);
ASSERT_EVENTS_PrmFileLoadComplete(0,2);
// verify values (populated by runNominalPopulate())
// first
Fw::ParamBuffer pBuff;
U32 testVal;
this->invoke_to_getPrm(0,0x21,pBuff);
// deserialize it
Fw::SerializeStatus stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,0x15u);
// second
pBuff.resetSer();
this->invoke_to_getPrm(0,0x25,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,0x30u);
}
void PrmDbImplTester::runMissingExtraParams() {
// load up database
this->runNominalPopulate();
// ask for ID that isn't present
this->clearEvents();
Fw::ParamBuffer pBuff;
EXPECT_EQ(Fw::ParamValid::INVALID,this->invoke_to_getPrm(0,0x1000,pBuff).e);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdNotFound_SIZE(1);
ASSERT_EVENTS_PrmIdNotFound(0,0x1000);
// clear database
this->m_impl.clearDb();
this->clearEvents();
// write too many entries
for (FwPrmIdType entry = 0; entry <= PRMDB_NUM_DB_ENTRIES; entry++) {
EXPECT_EQ(Fw::FW_SERIALIZE_OK,pBuff.serialize(static_cast<U32>(10)));
this->invoke_to_setPrm(0,entry,pBuff);
// dispatch message
this->m_impl.doDispatch();
}
ASSERT_EVENTS_SIZE(PRMDB_NUM_DB_ENTRIES+1);
ASSERT_EVENTS_PrmIdAdded_SIZE(PRMDB_NUM_DB_ENTRIES);
ASSERT_EVENTS_PrmDbFull_SIZE(1);
ASSERT_EVENTS_PrmDbFull(0,PRMDB_NUM_DB_ENTRIES);
}
void PrmDbImplTester::runRefPrmFile() {
{
// ID = 00x1000
U32 val = 14;
FwPrmIdType id = 0x1000;
Fw::ParamBuffer pBuff;
Fw::SerializeStatus stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdAdded_SIZE(1);
ASSERT_EVENTS_PrmIdAdded(0,id);
// retrieve it
U32 testVal;
this->invoke_to_getPrm(0,id,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,val);
}
{
// ID = 0x1001
I16 val = 15;
FwPrmIdType id = 0x1001;
Fw::ParamBuffer pBuff;
Fw::SerializeStatus stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdAdded_SIZE(1);
ASSERT_EVENTS_PrmIdAdded(0,id);
// retrieve it
I16 testVal;
this->invoke_to_getPrm(0,id,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,val);
}
{
// ID = 0x1100
U8 val = 32;
FwPrmIdType id = 0x1100;
Fw::ParamBuffer pBuff;
Fw::SerializeStatus stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdAdded_SIZE(1);
ASSERT_EVENTS_PrmIdAdded(0,id);
// retrieve it
U8 testVal;
this->invoke_to_getPrm(0,id,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,val);
}
{
// ID = 0x1101
F32 val = 33.34;
FwPrmIdType id = 0x1101;
Fw::ParamBuffer pBuff;
Fw::SerializeStatus stat = pBuff.serialize(val);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
// clear all events
this->clearEvents();
// send it to the database
this->invoke_to_setPrm(0,id,pBuff);
// dispatch message
this->m_impl.doDispatch();
// Verify event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmIdAdded_SIZE(1);
ASSERT_EVENTS_PrmIdAdded(0,id);
// retrieve it
F32 testVal;
this->invoke_to_getPrm(0,id,pBuff);
// deserialize it
stat = pBuff.deserialize(testVal);
EXPECT_EQ(Fw::FW_SERIALIZE_OK,stat);
EXPECT_EQ(testVal,val);
}
this->clearEvents();
this->clearHistory();
this->sendCmd_PRM_SAVE_FILE(0,12);
Fw::QueuedComponentBase::MsgDispatchStatus mstat = this->m_impl.doDispatch();
EXPECT_EQ(mstat,Fw::QueuedComponentBase::MSG_DISPATCH_OK);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0,PrmDbImpl::OPCODE_PRM_SAVE_FILE,12,Fw::CmdResponse::OK);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmFileSaveComplete_SIZE(1);
ASSERT_EVENTS_PrmFileSaveComplete(0,4);
}
void PrmDbImplTester::init(NATIVE_INT_TYPE instance) {
PrmDbGTestBase::init();
}
PrmDbImplTester* PrmDbImplTester::PrmDbTestFile::s_tester = nullptr;
void PrmDbImplTester::PrmDbTestFile::setTester(Svc::PrmDbImplTester *tester) {
ASSERT_NE(tester, nullptr);
s_tester = tester;
}
Os::File::Status PrmDbImplTester::PrmDbTestFile::read(U8 *buffer, FwSignedSizeType &size, Os::File::WaitType wait) {
EXPECT_NE(s_tester, nullptr);
Os::File::Status status = this->Os::Stub::File::Test::TestFile::read(buffer, size, wait);
if (s_tester->m_waits == 0) {
switch (s_tester->m_errorType) {
case FILE_STATUS_ERROR:
status = s_tester->m_status;
break;
case FILE_SIZE_ERROR:
size += 1;
break;
case FILE_DATA_ERROR:
buffer[0] += 1;
break;
default:
break;
}
} else {
s_tester->m_waits -= 1;
}
return status;
}
Os::File::Status PrmDbImplTester::PrmDbTestFile::write(const U8* buffer, FwSignedSizeType &size, Os::File::WaitType wait) {
EXPECT_NE(s_tester, nullptr);
Os::File::Status status = this->Os::Stub::File::Test::TestFile::write(buffer, size, wait);
if (s_tester->m_waits == 0) {
switch (s_tester->m_errorType) {
case FILE_STATUS_ERROR:
status = s_tester->m_status;
break;
case FILE_SIZE_ERROR:
size += 1;
break;
default:
break;
}
} else {
s_tester->m_waits -= 1;
}
return status;
}
void PrmDbImplTester::runFileReadError() {
// Preconditions setup and test
this->runNominalLoadFile();
this->clearEvents();
// Loop through all size errors testing each
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
this->m_errorType = FILE_SIZE_ERROR;
for (FwSizeType i = 0; i < 4; i++) {
clearEvents();
this->m_waits = i;
this->m_impl.readParamFile();
ASSERT_EVENTS_SIZE(1);
switch (i) {
case 0:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::DELIMITER_SIZE, 0, sizeof(U8) + 1);
break;
case 1:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::RECORD_SIZE_SIZE, 0, sizeof(U32) + 1);
break;
case 2:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0,PrmReadError::PARAMETER_ID_SIZE, 0, sizeof(FwPrmIdType) + 1);
break;
case 3:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::PARAMETER_VALUE_SIZE, 0, sizeof(U32) + 1);
break;
default:
FAIL() << "Reached unknown case";
}
}
// Loop through failure statuses
for (FwSizeType i = 0; i < 2; i++) {
this->m_errorType = FILE_STATUS_ERROR;
// Set various file errors
switch (i) {
case 0:
this->m_status = Os::File::Status::DOESNT_EXIST;
break;
case 1:
this->m_status = Os::File::Status::NOT_OPENED;
break;
default:
FAIL() << "Reached unknown case";
}
// Loop through various field reads
for (FwSizeType j = 0; j < 4; j++) {
clearEvents();
this->m_waits = j;
this->m_impl.readParamFile();
ASSERT_EVENTS_SIZE(1);
switch (j) {
case 0:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0,PrmReadError::DELIMITER, 0, this->m_status);
break;
case 1:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::RECORD_SIZE, 0, this->m_status);
break;
case 2:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::PARAMETER_ID, 0, this->m_status);
break;
case 3:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::PARAMETER_VALUE, 0, this->m_status);
break;
default:
FAIL() << "Reached unknown case";
}
}
}
this->m_errorType = FILE_DATA_ERROR;
for (FwSizeType i = 0; i < 2; i++) {
clearEvents();
this->m_waits = i;
this->m_impl.readParamFile();
ASSERT_EVENTS_SIZE(1);
switch (i) {
case 0:
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
// Parameter read error caused by adding one to the expected read
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::DELIMITER_VALUE, 0, PRMDB_ENTRY_DELIMITER + 1);
break;
case 1: {
// Data in this test is corrupted by adding 1 to the first data byte read. Since data is stored in
// big-endian format the highest order byte of the record size (U32) must have one added to it.
// Expected result of '8' inherited from original design of test.
U32 expected_error_value = 8 + (1 << ((sizeof(U32) - 1) * 8));
ASSERT_EVENTS_PrmFileReadError_SIZE(1);
ASSERT_EVENTS_PrmFileReadError(0, PrmReadError::RECORD_SIZE_VALUE, 0, expected_error_value);
break;
}
default:
FAIL() << "Reached unknown case";
}
}
}
void PrmDbImplTester::runFileWriteError() {
// File open error
this->clearEvents();
// register interceptor
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::DOESNT_EXIST);
// dispatch command
this->sendCmd_PRM_SAVE_FILE(0,12);
Fw::QueuedComponentBase::MsgDispatchStatus stat = this->m_impl.doDispatch();
ASSERT_EQ(stat, Fw::QueuedComponentBase::MSG_DISPATCH_OK);
// check for failed event
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0,PrmWriteError::OPEN,0,Os::File::DOESNT_EXIST);
// check command status
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0,PrmDbImpl::OPCODE_PRM_SAVE_FILE,12,Fw::CmdResponse::EXECUTION_ERROR);
this->runNominalPopulate();
// Loop through all size errors testing each
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
this->m_errorType = FILE_SIZE_ERROR;
for (FwSizeType i = 0; i < 4; i++) {
clearEvents();
this->clearHistory();
this->m_waits = i;
this->sendCmd_PRM_SAVE_FILE(0,12);
stat = this->m_impl.doDispatch();
ASSERT_EQ(stat, Fw::QueuedComponentBase::MSG_DISPATCH_OK);
ASSERT_EVENTS_SIZE(1);
switch (i) {
case 0:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::DELIMITER_SIZE, 0, sizeof(U8) + 1);
break;
case 1:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::RECORD_SIZE_SIZE, 0, sizeof(U32) + 1);
break;
case 2:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::PARAMETER_ID_SIZE, 0, sizeof(FwPrmIdType) + 1);
break;
case 3:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::PARAMETER_VALUE_SIZE, 0, sizeof(U32) + 1);
break;
default:
FAIL() << "Reached unknown case";
}
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0,PrmDbImpl::OPCODE_PRM_SAVE_FILE,12,Fw::CmdResponse::EXECUTION_ERROR);
}
// Loop through failure statuses
for (FwSizeType i = 0; i < 2; i++) {
this->m_errorType = FILE_STATUS_ERROR;
// Set various file errors
switch (i) {
case 0:
this->m_status = Os::File::Status::DOESNT_EXIST;
break;
case 1:
this->m_status = Os::File::Status::NOT_OPENED;
break;
default:
FAIL() << "Reached unknown case";
}
// Loop through various field reads
for (FwSizeType j = 0; j < 4; j++) {
clearEvents();
this->clearHistory();
this->m_waits = j;
this->sendCmd_PRM_SAVE_FILE(0,12);
stat = this->m_impl.doDispatch();
ASSERT_EQ(stat, Fw::QueuedComponentBase::MSG_DISPATCH_OK);
ASSERT_EVENTS_SIZE(1);
switch (j) {
case 0:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::DELIMITER, 0, this->m_status);
break;
case 1:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::RECORD_SIZE, 0, this->m_status);
break;
case 2:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::PARAMETER_ID, 0, this->m_status);
break;
case 3:
ASSERT_EVENTS_PrmFileWriteError_SIZE(1);
ASSERT_EVENTS_PrmFileWriteError(0, PrmWriteError::PARAMETER_VALUE, 0, this->m_status);
break;
default:
FAIL() << "Reached unknown case";
}
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0,PrmDbImpl::OPCODE_PRM_SAVE_FILE,12,Fw::CmdResponse::EXECUTION_ERROR);
}
}
}
PrmDbImplTester::PrmDbImplTester(Svc::PrmDbImpl& inst) :
PrmDbGTestBase("testerbase",100), m_impl(inst) {
PrmDbImplTester::PrmDbTestFile::setTester(this);
}
PrmDbImplTester::~PrmDbImplTester() {
}
void PrmDbImplTester ::
from_pingOut_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
this->pushFromPortEntry_pingOut(key);
}
} /* namespace Svc */
namespace Os {
//! Overrides the default delegate function with this one as it is defined in the local compilation archive
//! \param aligned_placement_new_memory: memory to fill
//! \param to_copy: possible copy
//! \return: new interceptor
FileInterface *FileInterface::getDelegate(U8 *aligned_placement_new_memory, const FileInterface* to_copy) {
FW_ASSERT(aligned_placement_new_memory != nullptr);
const Svc::PrmDbImplTester::PrmDbTestFile* copy_me =
reinterpret_cast<const Svc::PrmDbImplTester::PrmDbTestFile*>(to_copy);
// Placement-new the file handle into the opaque file-handle storage
static_assert(sizeof(Svc::PrmDbImplTester::PrmDbTestFile) <= FW_HANDLE_MAX_SIZE, "Handle size not large enough");
static_assert((FW_HANDLE_ALIGNMENT % alignof(Svc::PrmDbImplTester::PrmDbTestFile)) == 0, "Handle alignment invalid");
Svc::PrmDbImplTester::PrmDbTestFile *interface = nullptr;
if (to_copy == nullptr) {
interface = new(aligned_placement_new_memory) Svc::PrmDbImplTester::PrmDbTestFile;
} else {
interface = new(aligned_placement_new_memory) Svc::PrmDbImplTester::PrmDbTestFile(*copy_me);
}
FW_ASSERT(interface != nullptr);
return interface;
}
}
| cpp |
fprime | data/projects/fprime/Svc/PrmDb/test/ut/PrmDbImplTester.hpp | /*
* PrmDbImplTester.hpp
*
* Created on: Mar 18, 2015
* Author: tcanham
*/
#ifndef PRMDB_TEST_UT_PRMDBIMPLTESTER_HPP_
#define PRMDB_TEST_UT_PRMDBIMPLTESTER_HPP_
#include <PrmDbGTestBase.hpp>
#include <PrmDbImplTesterCfg.hpp>
#include <Svc/PrmDb/PrmDbImpl.hpp>
#include <Os/Stub/test/File.hpp>
namespace Svc {
class PrmDbImplTester : public PrmDbGTestBase {
public:
PrmDbImplTester(Svc::PrmDbImpl& inst);
virtual ~PrmDbImplTester();
void runNominalPopulate();
void runNominalSaveFile();
void runNominalLoadFile();
void runMissingExtraParams();
void runFileReadError();
void runFileWriteError();
void runRefPrmFile();
void init(NATIVE_INT_TYPE instance = 0);
private:
//! Handler for from_pingOut
//!
void from_pingOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
Svc::PrmDbImpl& m_impl;
void resetEvents();
// enumeration to tell what kind of error to inject
enum ErrorType {
FILE_STATUS_ERROR, // return a bad read status
FILE_SIZE_ERROR, // return a bad size
FILE_DATA_ERROR, // return unexpected data
FILE_READ_NO_ERROR, // No error
};
Os::File::Status m_status;
FwSizeType m_waits = 0;
ErrorType m_errorType = FILE_READ_NO_ERROR;
BYTE m_io_data[PRMDB_IMPL_TESTER_MAX_READ_BUFFER];
// write call modifiers
Os::File::Status WriteInterceptor();
Os::File::Status m_testWriteStatus;
public:
class PrmDbTestFile : public Os::Stub::File::Test::TestFile {
public:
Status read(U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
Status write(const U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
// Tracks the current tester
static void setTester(PrmDbImplTester* tester);
static PrmDbImplTester* s_tester;
};
};
} /* namespace SvcTest */
#endif /* PRMDB_TEST_UT_PRMDBIMPLTESTER_HPP_ */
| hpp |
fprime | data/projects/fprime/Svc/PrmDb/test/ut/PrmDbTester.cpp | /*
* PrmDbTester.cpp
*
* Created on: Mar 18, 2015
* Author: tcanham
*/
#include <Svc/PrmDb/test/ut/PrmDbImplTester.hpp>
#include <Svc/PrmDb/PrmDbImpl.hpp>
#include <Fw/Obj/SimpleObjRegistry.hpp>
#include <gtest/gtest.h>
#include <Fw/Test/UnitTest.hpp>
#if FW_OBJECT_REGISTRATION == 1
static Fw::SimpleObjRegistry simpleReg;
#endif
void connectPorts(Svc::PrmDbImpl& impl, Svc::PrmDbImplTester& tester) {
// command ports
tester.connect_to_CmdDisp(0,impl.get_CmdDisp_InputPort(0));
impl.set_CmdStatus_OutputPort(0,tester.get_from_CmdStatus(0));
// telemetry ports
impl.set_Time_OutputPort(0,tester.get_from_Time(0));
impl.set_Log_OutputPort(0,tester.get_from_Log(0));
impl.set_LogText_OutputPort(0,tester.get_from_LogText(0));
// parameter ports
tester.connect_to_getPrm(0,impl.get_getPrm_InputPort(0));
tester.connect_to_setPrm(0,impl.get_setPrm_InputPort(0));
#if FW_PORT_TRACING
//Fw::PortBase::setTrace(true);
#endif
//simpleReg.dump();
}
TEST(ParameterDbTest,NominalPopulateTest) {
TEST_CASE(105.1.1,"Nominal populate test");
COMMENT("Write values to the parameter database and verify that they were written correctly");
Svc::PrmDbImpl impl("PrmDbImpl");
impl.init(10,0);
impl.configure("TestFile.prm");
Svc::PrmDbImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
// run nominal tests
tester.runNominalPopulate();
}
TEST(ParameterDbTest,NominalFileSaveTest) {
TEST_CASE(105.1.2,"Nominal file save test");
COMMENT("Write values to the parameter database and save them to a file.");
Svc::PrmDbImpl impl("PrmDbImpl");
impl.init(10,0);
impl.configure("TestFile.prm");
Svc::PrmDbImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
// run nominal save file tests
tester.runNominalSaveFile();
}
TEST(ParameterDbTest,NominalFileLoadTest) {
TEST_CASE(105.1.3,"Nominal file load test");
COMMENT("Read values from the created file and verify they are correct.");
Svc::PrmDbImpl impl("PrmDbImpl");
impl.init(10,0);
impl.configure("TestFile.prm");
Svc::PrmDbImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
// run nominal load file tests
tester.runNominalLoadFile();
}
//TEST(ParameterDbTest,RefPrmFile) {
//
// Svc::PrmDbImpl impl("PrmDbImpl");
//
// impl.init(10);
//
// Svc::PrmDbImplTester tester(impl);
//
// tester.init();
//
// // connect ports
// connectPorts(impl,tester);
//
// // run test to generate parameter file for reference example
// tester.runRefPrmFile();
//
//}
TEST(ParameterDbTest,PrmMissingExtraParamsTest) {
TEST_CASE(105.2.1,"Missing and too many parameters test");
COMMENT("Attempt to read a nonexistent parameter and write too many parameters");
Svc::PrmDbImpl impl("PrmDbImpl");
impl.init(10,0);
impl.configure("TestFile.prm");
Svc::PrmDbImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
// run test with file errors
tester.runMissingExtraParams();
}
TEST(ParameterDbTest,PrmFileReadError) {
TEST_CASE(105.2.2,"File read errors");
COMMENT("Induce errors at various stages of reading the file");
Svc::PrmDbImpl impl("PrmDbImpl");
impl.init(10,0);
impl.configure("TestFile.prm");
Svc::PrmDbImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
// run test with file errors
tester.runFileReadError();
}
TEST(ParameterDbTest,PrmFileWriteError) {
TEST_CASE(105.2.3,"File write errors");
COMMENT("Induce errors at various stages of writing the file");
Svc::PrmDbImpl impl("PrmDbImpl");
impl.init(10,0);
impl.configure("TestFile.prm");
Svc::PrmDbImplTester tester(impl);
tester.init();
// connect ports
connectPorts(impl,tester);
// run test with file errors
tester.runFileWriteError();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/SystemResources/SystemResources.cpp | // ======================================================================
// \title SystemResourcesComponentImpl.cpp
// \author sfregoso
// \brief cpp file for SystemResources component implementation class
//
// \copyright
// Copyright 2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <cmath> //isnan()
#include <Svc/SystemResources/SystemResources.hpp>
#include <version.hpp>
#include <FpConfig.hpp>
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
SystemResources ::SystemResources(const char* const compName)
: SystemResourcesComponentBase(compName), m_cpu_count(0), m_enable(true) {
// Structure initializations
m_mem.used = 0;
m_mem.total = 0;
for (U32 i = 0; i < CPU_COUNT; i++) {
m_cpu[i].used = 0;
m_cpu[i].total = 0;
m_cpu_prev[i].used = 0;
m_cpu_prev[i].total = 0;
}
if (Os::SystemResources::getCpuCount(m_cpu_count) == Os::SystemResources::SYSTEM_RESOURCES_ERROR) {
m_cpu_count = 0;
}
m_cpu_count = (m_cpu_count >= CPU_COUNT) ? CPU_COUNT : m_cpu_count;
m_cpu_tlm_functions[0] = &Svc::SystemResources::tlmWrite_CPU_00;
m_cpu_tlm_functions[1] = &Svc::SystemResources::tlmWrite_CPU_01;
m_cpu_tlm_functions[2] = &Svc::SystemResources::tlmWrite_CPU_02;
m_cpu_tlm_functions[3] = &Svc::SystemResources::tlmWrite_CPU_03;
m_cpu_tlm_functions[4] = &Svc::SystemResources::tlmWrite_CPU_04;
m_cpu_tlm_functions[5] = &Svc::SystemResources::tlmWrite_CPU_05;
m_cpu_tlm_functions[6] = &Svc::SystemResources::tlmWrite_CPU_06;
m_cpu_tlm_functions[7] = &Svc::SystemResources::tlmWrite_CPU_07;
m_cpu_tlm_functions[8] = &Svc::SystemResources::tlmWrite_CPU_08;
m_cpu_tlm_functions[9] = &Svc::SystemResources::tlmWrite_CPU_09;
m_cpu_tlm_functions[10] = &Svc::SystemResources::tlmWrite_CPU_10;
m_cpu_tlm_functions[11] = &Svc::SystemResources::tlmWrite_CPU_11;
m_cpu_tlm_functions[12] = &Svc::SystemResources::tlmWrite_CPU_12;
m_cpu_tlm_functions[13] = &Svc::SystemResources::tlmWrite_CPU_13;
m_cpu_tlm_functions[14] = &Svc::SystemResources::tlmWrite_CPU_14;
m_cpu_tlm_functions[15] = &Svc::SystemResources::tlmWrite_CPU_15;
}
void SystemResources ::init(const NATIVE_INT_TYPE instance) {
SystemResourcesComponentBase::init(instance);
}
SystemResources ::~SystemResources() {}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void SystemResources ::run_handler(const NATIVE_INT_TYPE portNum, U32 tick_time_hz) {
if (m_enable) {
Cpu();
Mem();
PhysMem();
Version();
}
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void SystemResources ::ENABLE_cmdHandler(const FwOpcodeType opCode,
const U32 cmdSeq,
SystemResourceEnabled enable) {
m_enable = (enable == SystemResourceEnabled::ENABLED);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void SystemResources ::VERSION_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq) {
Fw::LogStringArg version_string(FRAMEWORK_VERSION);
this->log_ACTIVITY_LO_FRAMEWORK_VERSION(version_string);
version_string = PROJECT_VERSION;
this->log_ACTIVITY_LO_PROJECT_VERSION(version_string);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
F32 SystemResources::compCpuUtil(Os::SystemResources::CpuTicks current, Os::SystemResources::CpuTicks previous) {
F32 util = 100.0f;
// Prevent divide by zero on fast-sample
if ((current.total - previous.total) != 0) {
// Compute CPU % Utilization
util = (static_cast<F32>(current.used - previous.used) / static_cast<F32>(current.total - previous.total)) *
100.0f;
util = std::isnan(util) ? 100.0f : util;
}
return util;
}
void SystemResources::Cpu() {
U32 count = 0;
F32 cpuAvg = 0;
for (U32 i = 0; i < m_cpu_count && i < CPU_COUNT; i++) {
Os::SystemResources::SystemResourcesStatus status = Os::SystemResources::getCpuTicks(m_cpu[i], i);
// Best-effort calculations and telemetry
if (status == Os::SystemResources::SYSTEM_RESOURCES_OK) {
F32 cpuUtil = compCpuUtil(m_cpu[i], m_cpu_prev[i]);
cpuAvg += cpuUtil;
// Send telemetry using telemetry output table
FW_ASSERT(this->m_cpu_tlm_functions[i]);
(this->*m_cpu_tlm_functions[i])(cpuUtil, Fw::Time());
// Store cpu used and total
m_cpu_prev[i] = m_cpu[i];
count++;
}
}
cpuAvg = (count == 0) ? 0.0f : (cpuAvg / static_cast<F32>(count));
this->tlmWrite_CPU(cpuAvg);
}
void SystemResources::Mem() {
if (Os::SystemResources::getMemUtil(m_mem) == Os::SystemResources::SYSTEM_RESOURCES_OK) {
this->tlmWrite_MEMORY_TOTAL(m_mem.total / 1024);
this->tlmWrite_MEMORY_USED(m_mem.used / 1024);
}
}
void SystemResources::PhysMem() {
FwSizeType total = 0;
FwSizeType free = 0;
if (Os::FileSystem::getFreeSpace("/", total, free) == Os::FileSystem::OP_OK) {
this->tlmWrite_NON_VOLATILE_FREE(free / 1024);
this->tlmWrite_NON_VOLATILE_TOTAL(total / 1024);
}
}
void SystemResources::Version() {
Fw::TlmString version_string(FRAMEWORK_VERSION);
this->tlmWrite_FRAMEWORK_VERSION(version_string);
version_string= PROJECT_VERSION;
this->tlmWrite_PROJECT_VERSION(version_string);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/SystemResources/SystemResources.hpp | // ======================================================================
// \title SystemResourcesComponentImpl.hpp
// \author Santos F. Fregoso
// \brief hpp file for SystemResources component implementation class
//
// \copyright
// Copyright 2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef SystemResources_HPP
#define SystemResources_HPP
#include "Svc/SystemResources/SystemResourcesComponentAc.hpp"
#include "Os/SystemResources.hpp"
#include "Os/FileSystem.hpp"
namespace Svc {
class SystemResources : public SystemResourcesComponentBase {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object SystemResources
//!
SystemResources(const char* const compName /*!< The component name*/
);
//! Initialize object SystemResources
//!
void init(const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object SystemResources
//!
~SystemResources(void);
typedef void (SystemResourcesComponentBase::*cpuTlmFunc)(F32, Fw::Time);
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*/
);
private:
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
//! Implementation for SYS_RES_ENABLE command handler
//! A command to enable or disable system resource telemetry
void ENABLE_cmdHandler(
const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
SystemResourceEnabled enable /*!< whether or not system resource telemetry is enabled*/
);
//! Implementation for VERSION command handler
//! Report version as EVR
void VERSION_cmdHandler(const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq /*!< The command sequence number*/
);
private:
void Cpu();
void Mem();
void PhysMem();
void Version();
F32 compCpuUtil(Os::SystemResources::CpuTicks current, Os::SystemResources::CpuTicks previous);
static const U32 CPU_COUNT = 16; /*!< Maximum number of CPUs to report as telemetry */
cpuTlmFunc m_cpu_tlm_functions[CPU_COUNT]; /*!< Function pointer to specific CPU telemetry */
U32 m_cpu_count; /*!< Number of CPUs used by the system */
Os::SystemResources::MemUtil m_mem; /*!< RAM memory information */
Os::SystemResources::CpuTicks m_cpu[CPU_COUNT]; /*!< CPU information for each CPU on the system */
Os::SystemResources::CpuTicks m_cpu_prev[CPU_COUNT]; /*!< Previous iteration CPU information */
bool m_enable; /*!< Send telemetry when TRUE. Don't send when FALSE */
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/SystemResources/test/ut/SystemResourcesTester.hpp | // ======================================================================
// \title SystemResources/test/ut/Tester.hpp
// \author sfregoso
// \brief hpp file for SystemResources test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "SystemResourcesGTestBase.hpp"
#include "Svc/SystemResources/SystemResources.hpp"
namespace Svc {
class SystemResourcesTester : public SystemResourcesGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object SystemResourcesTester
//!
SystemResourcesTester();
//! Destroy object SystemResourcesTester
//!
~SystemResourcesTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Test the telemetry output
//!
void test_tlm(bool enabled = true);
//! Test the telemetry enable/disable
//!
void test_disable_enable();
//! Test version EVR
//!
void test_version_evr();
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
SystemResources component;
};
} // end namespace Svc
#endif
| hpp |
Subsets and Splits