repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/Errors.hpp | // ======================================================================
// \title Errors.hpp
// \author bocchino, mereweth
// \brief Test errors
//
// \copyright
// Copyright (c) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Svc_Errors_HPP
#define Svc_Errors_HPP
#include "BufferAccumulatorTester.hpp"
namespace Svc {
namespace Errors {
class BufferAccumulatorTester : public Svc::BufferAccumulatorTester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Queue full
void QueueFull(void);
//! Run PartialDrain command in off-nominal ways
void PartialDrain(void);
};
} // namespace Errors
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/Drain.hpp | // ======================================================================
// \title Drain.hpp
// \author bocchino, mereweth
// \brief Test drain mode
//
// \copyright
// Copyright (c) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Svc_Drain_HPP
#define Svc_Drain_HPP
#include "BufferAccumulatorTester.hpp"
namespace Svc {
namespace Drain {
class BufferAccumulatorTester : public Svc::BufferAccumulatorTester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Send some buffers
void OK(void);
//! Run PartialDrain command in nominal way
void PartialDrainOK(void);
};
} // namespace Drain
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/BufferAccumulatorTester.hpp | // ======================================================================
// \title BufferAccumulatorTester.hpp
// \author bocchino, mereweth
// \brief BufferAccumulator test harness interface
//
// \copyright
// Copyright 2009-2017, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "BufferAccumulatorGTestBase.hpp"
#include "Svc/BufferAccumulator/BufferAccumulator.hpp"
#define MAX_NUM_BUFFERS 10
namespace Svc {
class BufferAccumulatorTester : public BufferAccumulatorGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object BufferAccumulatorTester
//!
explicit BufferAccumulatorTester(bool doAllocateQueue = true);
//! Destroy object BufferAccumulatorTester
//!
~BufferAccumulatorTester(void);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_bufferSendOutDrain
//!
void from_bufferSendOutDrain_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer& fwBuffer);
//! Handler for from_bufferSendOutReturn
//!
void from_bufferSendOutReturn_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
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts(void);
//! Initialize components
//!
void initComponents(void);
protected:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
BufferAccumulator component;
//! Whether to allocate/deallocate a queue for the user
bool doAllocateQueue;
};
} // end namespace Svc
#endif //#ifndef TESTER_HPP
| hpp |
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/Health.hpp | // ======================================================================
// \title Health.hpp
// \author bocchino, mereweth
// \brief Interface for Buffer Accumulator 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 "BufferAccumulatorTester.hpp"
namespace Svc {
namespace Health {
class BufferAccumulatorTester : public Svc::BufferAccumulatorTester {
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Health ping test
void Ping(void);
};
} // namespace Health
} // namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/Drain.cpp | // ======================================================================
// \title Drain.hpp
// \author bocchino, mereweth
// \brief Test drain mode
//
// \copyright
// Copyright (c) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Drain.hpp"
#include <cstring>
#include <sys/time.h>
namespace Svc {
namespace Drain {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void BufferAccumulatorTester ::OK() {
ASSERT_EQ(BufferAccumulator_OpState::DRAIN, this->component.mode.e);
Fw::Buffer buffers[MAX_NUM_BUFFERS];
// Buffer needs a valid pointer
U8* data = new U8[10];
const U32 size = 10;
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
ASSERT_from_bufferSendOutDrain_SIZE(i);
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
this->invoke_to_bufferSendInFill(0, buffers[i]);
this->component.doDispatch();
ASSERT_from_bufferSendOutDrain_SIZE(i + 1);
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
this->invoke_to_bufferSendInReturn(0, buffers[i]);
this->component.doDispatch();
ASSERT_from_bufferSendOutReturn(i, buffers[i]);
}
delete[] data;
}
void BufferAccumulatorTester ::PartialDrainOK() {
this->sendCmd_BA_SetMode(0, 0, BufferAccumulator_OpState::ACCUMULATE);
this->component.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, BufferAccumulator::OPCODE_BA_SETMODE, 0,
Fw::CmdResponse::OK);
ASSERT_EQ(BufferAccumulator_OpState::ACCUMULATE, this->component.mode.e);
ASSERT_FROM_PORT_HISTORY_SIZE(0);
Fw::Buffer buffers[MAX_NUM_BUFFERS];
U8* data = new U8[10];
const U32 size = 10;
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
this->invoke_to_bufferSendInFill(0, buffers[i]);
this->component.doDispatch();
this->sendCmd_BA_DrainBuffers(0, 0, 1, BufferAccumulator_BlockMode::BLOCK);
this->component.doDispatch();
ASSERT_EVENTS_BA_PartialDrainDone_SIZE(i + 1);
ASSERT_EVENTS_BA_PartialDrainDone(i, 1u);
// + 1 for first BufferAccumulator_OpState::ACCUMULATE command; + 1 for
// buffer drained immediately
ASSERT_CMD_RESPONSE_SIZE(i + 2);
ASSERT_CMD_RESPONSE(i + 1, BufferAccumulator::OPCODE_BA_DRAINBUFFERS, 0,
Fw::CmdResponse::OK);
// check that one buffer drained
ASSERT_from_bufferSendOutDrain_SIZE(i + 1);
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
this->invoke_to_bufferSendInReturn(0, buffers[i]);
this->component.doDispatch();
ASSERT_from_bufferSendOutReturn(i, buffers[i]);
ASSERT_EVENTS_BA_PartialDrainDone_SIZE(i + 1);
ASSERT_EVENTS_BA_PartialDrainDone(i, 1u);
// + 1 for first BufferAccumulator_OpState::ACCUMULATE command; + 1 for
// buffer drained immediately
ASSERT_CMD_RESPONSE_SIZE(i + 2);
// check that ONLY one buffer drained
ASSERT_from_bufferSendOutDrain_SIZE(i + 1);
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
}
this->clearHistory();
// refill buffers
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
this->invoke_to_bufferSendInFill(0, buffers[i]);
this->component.doDispatch();
ASSERT_FROM_PORT_HISTORY_SIZE(0);
}
ASSERT_CMD_RESPONSE_SIZE(0);
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
ASSERT_from_bufferSendOutDrain_SIZE(i);
this->sendCmd_BA_DrainBuffers(0, 0, 1, BufferAccumulator_BlockMode::BLOCK);
this->component.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(i + 1);
ASSERT_CMD_RESPONSE(i, BufferAccumulator::OPCODE_BA_DRAINBUFFERS, 0,
Fw::CmdResponse::OK);
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
// check that one buffer drained
ASSERT_from_bufferSendOutDrain_SIZE(i + 1);
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
this->invoke_to_bufferSendInReturn(0, buffers[i]);
this->component.doDispatch();
ASSERT_from_bufferSendOutReturn(i, buffers[i]);
ASSERT_EVENTS_BA_PartialDrainDone_SIZE(i + 1);
ASSERT_EVENTS_BA_PartialDrainDone(i, 1u);
// check that ONLY one buffer drained
ASSERT_from_bufferSendOutDrain_SIZE(i + 1);
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
ASSERT_CMD_RESPONSE_SIZE(i + 1);
}
this->clearHistory();
// refill buffers
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
this->invoke_to_bufferSendInFill(0, buffers[i]);
this->component.doDispatch();
ASSERT_FROM_PORT_HISTORY_SIZE(0);
}
ASSERT_EQ(BufferAccumulator_OpState::ACCUMULATE, this->component.mode.e);
ASSERT_FROM_PORT_HISTORY_SIZE(0);
ASSERT_EQ(0u, this->component.numDrained);
ASSERT_EQ(0u, this->component.numToDrain);
ASSERT_EVENTS_BA_PartialDrainDone_SIZE(0);
this->sendCmd_BA_DrainBuffers(0, 0, MAX_NUM_BUFFERS,
BufferAccumulator_BlockMode::BLOCK);
this->component.doDispatch();
ASSERT_CMD_RESPONSE_SIZE(0);
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
if (i + 1 < MAX_NUM_BUFFERS) {
ASSERT_EQ(i + 1, this->component.numDrained);
ASSERT_EQ(MAX_NUM_BUFFERS, this->component.numToDrain);
ASSERT_EVENTS_BA_PartialDrainDone_SIZE(0);
}
// check that one buffer drained
ASSERT_from_bufferSendOutDrain_SIZE(i + 1);
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
this->invoke_to_bufferSendInReturn(0, buffers[i]);
this->component.doDispatch();
ASSERT_from_bufferSendOutReturn(i, buffers[i]);
}
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, BufferAccumulator::OPCODE_BA_DRAINBUFFERS, 0,
Fw::CmdResponse::OK);
ASSERT_EVENTS_BA_PartialDrainDone_SIZE(1);
ASSERT_EVENTS_BA_PartialDrainDone(0, MAX_NUM_BUFFERS);
delete[] data;
}
} // namespace Drain
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/BufferAccumulatorMain.cpp | // ======================================================================
// \title Main.cpp
// \author bocchino, mereweth
// \brief Test drain mode
//
// \copyright
// Copyright (c) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Accumulate.hpp"
#include "Drain.hpp"
#include "Errors.hpp"
#include "Health.hpp"
#include "BufferAccumulatorTester.hpp"
// ----------------------------------------------------------------------
// Test Errors
// ----------------------------------------------------------------------
TEST(TestErrors, QueueFull) {
Svc::Errors::BufferAccumulatorTester tester;
tester.QueueFull();
}
TEST(TestErrors, PartialDrain) {
Svc::Errors::BufferAccumulatorTester tester;
tester.PartialDrain();
}
// ----------------------------------------------------------------------
// Test Accumulate
// ----------------------------------------------------------------------
TEST(TestAccumulate, OK) {
Svc::Accumulate::BufferAccumulatorTester tester;
tester.OK();
}
// ----------------------------------------------------------------------
// Test Drain
// ----------------------------------------------------------------------
TEST(TestDrain, OK) {
Svc::Drain::BufferAccumulatorTester tester;
tester.OK();
}
TEST(TestPartialDrain, OK) {
Svc::Drain::BufferAccumulatorTester tester;
tester.PartialDrainOK();
}
// ----------------------------------------------------------------------
// Test Health
// ----------------------------------------------------------------------
TEST(TestHealth, Ping) {
Svc::Health::BufferAccumulatorTester tester;
tester.Ping();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/BufferAccumulator/test/ut/Accumulate.cpp | // ======================================================================
// \title Accumulate.hpp
// \author bocchino, mereweth
// \brief Test drain mode
//
// \copyright
// Copyright (c) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Accumulate.hpp"
namespace Svc {
namespace Accumulate {
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void BufferAccumulatorTester ::OK() {
ASSERT_EQ(BufferAccumulator_OpState::DRAIN, this->component.mode.e);
this->sendCmd_BA_SetMode(0, 0, BufferAccumulator_OpState::ACCUMULATE);
this->component.doDispatch();
ASSERT_EQ(BufferAccumulator_OpState::ACCUMULATE, this->component.mode.e);
ASSERT_FROM_PORT_HISTORY_SIZE(0);
Fw::Buffer buffers[MAX_NUM_BUFFERS];
U8* data = new U8[10];
const U32 size = 10;
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
const U32 bufferID = i;
Fw::Buffer b(data, size, bufferID);
buffers[i] = b;
this->invoke_to_bufferSendInFill(0, buffers[i]);
this->component.doDispatch();
ASSERT_FROM_PORT_HISTORY_SIZE(0);
}
this->sendCmd_BA_SetMode(0, 0, BufferAccumulator_OpState::DRAIN);
this->component.doDispatch();
ASSERT_EQ(BufferAccumulator_OpState::DRAIN, this->component.mode.e);
ASSERT_FROM_PORT_HISTORY_SIZE(1);
ASSERT_from_bufferSendOutDrain_SIZE(1);
ASSERT_from_bufferSendOutDrain(0, buffers[0]);
U32 expectedNumBuffers = 1;
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
this->invoke_to_bufferSendInReturn(0, buffers[i]);
this->component.doDispatch();
++expectedNumBuffers;
if (i + 1 < MAX_NUM_BUFFERS) {
++expectedNumBuffers;
ASSERT_from_bufferSendOutDrain_SIZE(i + 2);
ASSERT_from_bufferSendOutDrain(i + 1, buffers[i + 1]);
}
ASSERT_FROM_PORT_HISTORY_SIZE(expectedNumBuffers);
ASSERT_from_bufferSendOutReturn_SIZE(i + 1);
ASSERT_from_bufferSendOutReturn(i, buffers[i]);
}
ASSERT_EQ(2U * MAX_NUM_BUFFERS, expectedNumBuffers);
ASSERT_FROM_PORT_HISTORY_SIZE(expectedNumBuffers);
ASSERT_from_bufferSendOutDrain_SIZE(MAX_NUM_BUFFERS);
ASSERT_from_bufferSendOutReturn_SIZE(MAX_NUM_BUFFERS);
for (U32 i = 0; i < MAX_NUM_BUFFERS; ++i) {
ASSERT_from_bufferSendOutDrain(i, buffers[i]);
ASSERT_from_bufferSendOutReturn(i, buffers[i]);
}
delete[] data;
}
} // namespace Accumulate
} // namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/ComQueue/ComQueue.cpp | // ======================================================================
// \title ComQueue.cpp
// \author vbai
// \brief cpp file for ComQueue component implementation class
// ======================================================================
#include <Fw/Types/Assert.hpp>
#include <Svc/ComQueue/ComQueue.hpp>
#include "Fw/Types/BasicTypes.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
ComQueue ::QueueConfigurationTable ::QueueConfigurationTable() {
for (NATIVE_UINT_TYPE i = 0; i < FW_NUM_ARRAY_ELEMENTS(this->entries); i++) {
this->entries[i].priority = 0;
this->entries[i].depth = 0;
}
}
ComQueue ::ComQueue(const char* const compName)
: ComQueueComponentBase(compName),
m_state(WAITING),
m_allocationId(-1),
m_allocator(nullptr),
m_allocation(nullptr) {
// Initialize throttles to "off"
for (NATIVE_UINT_TYPE i = 0; i < TOTAL_PORT_COUNT; i++) {
this->m_throttle[i] = false;
}
}
ComQueue ::~ComQueue() {}
void ComQueue ::init(const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE instance) {
ComQueueComponentBase::init(queueDepth, instance);
}
void ComQueue ::cleanup() {
// Deallocate memory ignoring error conditions
if ((this->m_allocator != nullptr) && (this->m_allocation != nullptr)) {
this->m_allocator->deallocate(this->m_allocationId, this->m_allocation);
}
}
void ComQueue::configure(QueueConfigurationTable queueConfig,
NATIVE_UINT_TYPE allocationId,
Fw::MemAllocator& allocator) {
FwIndexType currentPriorityIndex = 0;
NATIVE_UINT_TYPE totalAllocation = 0;
// Store/initialize allocator members
this->m_allocator = &allocator;
this->m_allocationId = allocationId;
this->m_allocation = nullptr;
// Initializes the sorted queue metadata list in priority (sorted) order. This is accomplished by walking the
// priority values in priority order from 0 to TOTAL_PORT_COUNT. At each priory value, the supplied queue
// configuration table is walked and any entry matching the current priority values is used to add queue metadata to
// the prioritized list. This results in priority-sorted queue metadata objects that index back into the unsorted
// queue data structures.
//
// The total allocation size is tracked for passing to the allocation call and is a summation of
// (depth * message size) for each prioritized metadata object of (depth * message size)
for (FwIndexType currentPriority = 0; currentPriority < TOTAL_PORT_COUNT; currentPriority++) {
// Walk each queue configuration entry and add them into the prioritized metadata list when matching the current
// priority value
for (NATIVE_UINT_TYPE entryIndex = 0; entryIndex < FW_NUM_ARRAY_ELEMENTS(queueConfig.entries); entryIndex++) {
// Check for valid configuration entry
FW_ASSERT(queueConfig.entries[entryIndex].priority < TOTAL_PORT_COUNT,
queueConfig.entries[entryIndex].priority, TOTAL_PORT_COUNT, entryIndex);
if (currentPriority == queueConfig.entries[entryIndex].priority) {
// Set up the queue metadata object in order to track priority, depth, index into the queue list of the
// backing queue object, and message size. Both index and message size are calculated where priority and
// depth are copied from the configuration object.
QueueMetadata& entry = this->m_prioritizedList[currentPriorityIndex];
entry.priority = queueConfig.entries[entryIndex].priority;
entry.depth = queueConfig.entries[entryIndex].depth;
entry.index = entryIndex;
// Message size is determined by the type of object being stored, which in turn is determined by the
// index of the entry. Those lower than COM_PORT_COUNT are Fw::ComBuffers and those larger Fw::Buffer.
entry.msgSize = (entryIndex < COM_PORT_COUNT) ? sizeof(Fw::ComBuffer) : sizeof(Fw::Buffer);
totalAllocation += entry.depth * entry.msgSize;
currentPriorityIndex++;
}
}
}
// Allocate a single chunk of memory from the memory allocator. Memory recover is neither needed nor used.
bool recoverable = false;
this->m_allocation = this->m_allocator->allocate(this->m_allocationId, totalAllocation, recoverable);
// Each of the backing queue objects must be supplied memory to store the queued messages. These data regions are
// sub-portions of the total allocated data. This memory is passed out by looping through each queue in prioritized
// order and passing out the memory to each queue's setup method.
FwSizeType allocationOffset = 0;
for (FwIndexType i = 0; i < TOTAL_PORT_COUNT; i++) {
// Get current queue's allocation size and safety check the values
FwSizeType allocationSize = this->m_prioritizedList[i].depth * this->m_prioritizedList[i].msgSize;
FW_ASSERT(this->m_prioritizedList[i].index < static_cast<FwIndexType>(FW_NUM_ARRAY_ELEMENTS(this->m_queues)),
this->m_prioritizedList[i].index);
FW_ASSERT((allocationSize + allocationOffset) <= totalAllocation, allocationSize, allocationOffset,
totalAllocation);
// Setup queue's memory allocation, depth, and message size. Setup is skipped for a depth 0 queue
if (allocationSize > 0) {
this->m_queues[this->m_prioritizedList[i].index].setup(
reinterpret_cast<U8*>(this->m_allocation) + allocationOffset, allocationSize,
this->m_prioritizedList[i].depth, this->m_prioritizedList[i].msgSize);
}
allocationOffset += allocationSize;
}
// Safety check that all memory was used as expected
FW_ASSERT(allocationOffset == totalAllocation, allocationOffset, totalAllocation);
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void ComQueue::comQueueIn_handler(const NATIVE_INT_TYPE portNum, Fw::ComBuffer& data, U32 context) {
// Ensure that the port number of comQueueIn is consistent with the expectation
FW_ASSERT(portNum >= 0 && portNum < COM_PORT_COUNT, portNum);
this->enqueue(portNum, QueueType::COM_QUEUE, reinterpret_cast<const U8*>(&data), sizeof(Fw::ComBuffer));
}
void ComQueue::buffQueueIn_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
const NATIVE_INT_TYPE queueNum = portNum + COM_PORT_COUNT;
// Ensure that the port number of buffQueueIn is consistent with the expectation
FW_ASSERT(portNum >= 0 && portNum < BUFFER_PORT_COUNT, portNum);
FW_ASSERT(queueNum < TOTAL_PORT_COUNT);
this->enqueue(queueNum, QueueType::BUFFER_QUEUE, reinterpret_cast<const U8*>(&fwBuffer), sizeof(Fw::Buffer));
}
void ComQueue::comStatusIn_handler(const NATIVE_INT_TYPE portNum, Fw::Success& condition) {
switch (this->m_state) {
// On success, the queue should be processed. On failure, the component should still wait.
case WAITING:
if (condition.e == Fw::Success::SUCCESS) {
this->m_state = READY;
this->processQueue();
// A message may or may not be sent. Thus, READY or WAITING are acceptable final states.
FW_ASSERT((this->m_state == WAITING || this->m_state == READY), this->m_state);
} else {
this->m_state = WAITING;
}
break;
// Both READY and unknown states should not be possible at this point. To receive a status message we must be
// one of the WAITING or RETRY states.
default:
FW_ASSERT(0, this->m_state);
break;
}
}
void ComQueue::run_handler(const NATIVE_INT_TYPE portNum, U32 context) {
// Downlink the high-water marks for the Fw::ComBuffer array types
ComQueueDepth comQueueDepth;
for (FwSizeType i = 0; i < comQueueDepth.SIZE; i++) {
comQueueDepth[i] = this->m_queues[i].get_high_water_mark();
this->m_queues[i].clear_high_water_mark();
}
this->tlmWrite_comQueueDepth(comQueueDepth);
// Downlink the high-water marks for the Fw::Buffer array types
BuffQueueDepth buffQueueDepth;
for (FwSizeType i = 0; i < buffQueueDepth.SIZE; i++) {
buffQueueDepth[i] = this->m_queues[i + COM_PORT_COUNT].get_high_water_mark();
this->m_queues[i + COM_PORT_COUNT].clear_high_water_mark();
}
this->tlmWrite_buffQueueDepth(buffQueueDepth);
}
// ----------------------------------------------------------------------
// Private helper methods
// ----------------------------------------------------------------------
void ComQueue::enqueue(const FwIndexType queueNum, QueueType queueType, const U8* data, const FwSizeType size) {
// Enqueue the given message onto the matching queue. When no space is available then emit the queue overflow event,
// set the appropriate throttle, and move on. Will assert if passed a message for a depth 0 queue.
const FwSizeType expectedSize = (queueType == QueueType::COM_QUEUE) ? sizeof(Fw::ComBuffer) : sizeof(Fw::Buffer);
const FwIndexType portNum = queueNum - ((queueType == QueueType::COM_QUEUE) ? 0 : COM_PORT_COUNT);
FW_ASSERT(expectedSize == size, size, expectedSize);
FW_ASSERT(portNum >= 0, portNum);
Fw::SerializeStatus status = this->m_queues[queueNum].enqueue(data, size);
if (status == Fw::FW_SERIALIZE_NO_ROOM_LEFT && !this->m_throttle[queueNum]) {
this->log_WARNING_HI_QueueOverflow(queueType, portNum);
this->m_throttle[queueNum] = true;
}
// When the component is already in READY state process the queue to send out the next available message immediately
if (this->m_state == READY) {
this->processQueue();
}
}
void ComQueue::sendComBuffer(Fw::ComBuffer& comBuffer) {
FW_ASSERT(this->m_state == READY);
this->comQueueSend_out(0, comBuffer, 0);
this->m_state = WAITING;
}
void ComQueue::sendBuffer(Fw::Buffer& buffer) {
// Retry buffer expected to be cleared as we are either transferring ownership or have already deallocated it.
FW_ASSERT(this->m_state == READY);
this->buffQueueSend_out(0, buffer);
this->m_state = WAITING;
}
void ComQueue::processQueue() {
FwIndexType priorityIndex = 0;
FwIndexType sendPriority = 0;
// Check that we are in the appropriate state
FW_ASSERT(this->m_state == READY);
// Walk all the queues in priority order. Send the first message that is available in priority order. No balancing
// is done within this loop.
for (priorityIndex = 0; priorityIndex < TOTAL_PORT_COUNT; priorityIndex++) {
QueueMetadata& entry = this->m_prioritizedList[priorityIndex];
Types::Queue& queue = this->m_queues[entry.index];
// Continue onto next prioritized queue if there is no items in the current queue
if (queue.getQueueSize() == 0) {
continue;
}
// Send out the message based on the type
if (entry.index < COM_PORT_COUNT) {
Fw::ComBuffer comBuffer;
queue.dequeue(reinterpret_cast<U8*>(&comBuffer), sizeof(comBuffer));
this->sendComBuffer(comBuffer);
} else {
Fw::Buffer buffer;
queue.dequeue(reinterpret_cast<U8*>(&buffer), sizeof(buffer));
this->sendBuffer(buffer);
}
// Update the throttle and the index that was just sent
this->m_throttle[entry.index] = false;
// Priority used in the next loop
sendPriority = entry.priority;
break;
}
// Starting on the priority entry after the one dispatched and continuing through the end of the set of entries that
// share the same priority, rotate those entries such that the currently dispatched queue is last and the rest are
// shifted up by one. This effectively round-robins the queues of the same priority.
for (priorityIndex++;
priorityIndex < TOTAL_PORT_COUNT && (this->m_prioritizedList[priorityIndex].priority == sendPriority);
priorityIndex++) {
// Swap the previous entry with this one.
QueueMetadata temp = this->m_prioritizedList[priorityIndex];
this->m_prioritizedList[priorityIndex] = this->m_prioritizedList[priorityIndex - 1];
this->m_prioritizedList[priorityIndex - 1] = temp;
}
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/ComQueue/ComQueue.hpp | // ======================================================================
// \title ComQueue.hpp
// \author vbai
// \brief hpp file for ComQueue component implementation class
// ======================================================================
#ifndef Svc_ComQueue_HPP
#define Svc_ComQueue_HPP
#include <Fw/Buffer/Buffer.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Svc/ComQueue/ComQueueComponentAc.hpp>
#include <Utils/Types/Queue.hpp>
#include "Fw/Types/MemAllocator.hpp"
#include "Os/Mutex.hpp"
namespace Svc {
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
class ComQueue : public ComQueueComponentBase {
public:
//!< Count of Fw::Com input ports and thus Fw::Com queues
static const FwIndexType COM_PORT_COUNT = ComQueueComponentBase::NUM_COMQUEUEIN_INPUT_PORTS;
//!< Count of Fw::Buffer input ports and thus Fw::Buffer queues
static const FwIndexType BUFFER_PORT_COUNT = ComQueueComponentBase::NUM_BUFFQUEUEIN_INPUT_PORTS;
//!< Total count of input buffer ports and thus total queues
static const FwIndexType TOTAL_PORT_COUNT = COM_PORT_COUNT + BUFFER_PORT_COUNT;
/**
* \brief configuration data for each queue
*
* Each queue must be configured to specify the depth of the queue and the priority of the queue. Depth must be a
* non-negative integer indicating the number of messages before overflow. A depth of 0 disables the given queue and
* any message sent to it will overflow.
*
* Priority is an integer between 0 (inclusive) and TOTAL_PORT_COUNT (exclusive). Queues with lower priority values
* will be serviced first. Priorities may be repeated and queues sharing priorities will be serviced in a balanced
* manner.
*/
struct QueueConfigurationEntry {
FwSizeType depth; //!< Depth of the queue [0, infinity)
FwIndexType priority; //!< Priority of the queue [0, TOTAL_PORT_COUNT)
};
/**
* \brief configuration table for each queue
*
* This table should be filled-out and passed to the configure method of this component. It represents the
* port-by-port configuration information for the associated queue. Each entry specifies the queue's depth and
* priority.
*
* Entries are specified in-order first addressing Fw::Com ports then Fw::Buffer ports.
*/
struct QueueConfigurationTable {
QueueConfigurationEntry entries[TOTAL_PORT_COUNT];
/**
* \brief constructs a basic un-prioritized table with depth 0
*/
QueueConfigurationTable();
};
private:
// ----------------------------------------------------------------------
// Internal data structures
// ----------------------------------------------------------------------
/**
* Storage for internal queue metadata. This is stored in the prioritized list and contains indices to the the
* un-prioritized queue objects. Depth and priority is copied from the configuration supplied by the configure
* method. Index and message size are calculated by the configuration call.
*/
struct QueueMetadata {
FwSizeType depth; //!< Depth of the queue in messages
FwIndexType priority; //!< Priority of the queue
FwIndexType index; //!< Index of this queue in the prioritized list
FwSizeType msgSize; //!< Message size of messages in this queue
};
/**
* State of the component.
*/
enum SendState {
READY, //!< Component is ready to send next priority message
WAITING //!< Component is waiting for status of the last sent message
};
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object ComQueue
//!
ComQueue(const char* const compName /*!< The component name */
);
//! Initialize object ComQueue
//!
void init(const NATIVE_INT_TYPE queueDepth, /*!< The queue depth */
const NATIVE_INT_TYPE instance = 0 /*!< The instance number */
);
//! Destroy object ComQueue
//!
~ComQueue();
//! Configure the queue depths, priorities, and memory allocation for the component
//!
//! Takes in the queue depth and priority per-port in order from Fw::Com through Fw::Buffer ports. Calculates the
//! queue metadata stored `m_prioritizedList` and then sorts that list by priority.
void configure(QueueConfigurationTable queueConfig, //!< Table of the configuration properties for the component
NATIVE_UINT_TYPE allocationId, //!< Identifier used when dealing with the Fw::MemAllocator
Fw::MemAllocator& allocator //!< Fw::MemAllocator used to acquire memory
);
//! Deallocate resources and cleanup ComQueue
//!
void cleanup();
private:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Receive and queue a Fw::Buffer
//!
void buffQueueIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer& fwBuffer /*!< Buffer containing packet data*/);
//! Receive and queue a Fw::ComBuffer
//!
void comQueueIn_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*/
);
//! Handle the status of the last sent message
//!
void comStatusIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Success& condition /*!<Status of communication state*/
);
//! Schedules the transmission of telemetry
//!
void run_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!<The call order*/
);
// ----------------------------------------------------------------------
// Helper Functions
// ----------------------------------------------------------------------
//! Enqueues a message on the appropriate queue
//!
void enqueue(const FwIndexType queueNum, //!< Index of the queue to enqueue the message
QueueType queueType, //!< Type of the queue and message data
const U8* data, //!< Pointer to the message data
const FwSizeType size //!< Size of the message
);
//! Send a chosen Fw::ComBuffer
//!
void sendComBuffer(Fw::ComBuffer& comBuffer //!< Reference to buffer to send
);
//! Send a chosen Fw::Buffer
//!
void sendBuffer(Fw::Buffer& buffer //!< Reference to buffer to send
);
//! Process the queues to select the next priority message
//!
void processQueue();
// ----------------------------------------------------------------------
// Member variables
// ----------------------------------------------------------------------
Types::Queue m_queues[TOTAL_PORT_COUNT]; //!< Stores queued data waiting for transmission
QueueMetadata m_prioritizedList[TOTAL_PORT_COUNT]; //!< Priority sorted list of queue metadata
bool m_throttle[TOTAL_PORT_COUNT]; //!< Per-queue EVR throttles
SendState m_state; //!< State of the component
// Storage for Fw::MemAllocator properties
NATIVE_UINT_TYPE m_allocationId; //!< Component's allocation ID
Fw::MemAllocator* m_allocator; //!< Pointer to Fw::MemAllocator instance for deallocation
void* m_allocation; //!< Pointer to allocated memory
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/ComQueue/test/ut/ComQueueTester.cpp | // ======================================================================
// \title ComQueue.hpp
// \author vbai
// \brief cpp file for ComQueue test harness implementation class
// ======================================================================
#include "ComQueueTester.hpp"
#include "Fw/Types/MallocAllocator.hpp"
using namespace std;
Fw::MallocAllocator mallocAllocator;
#define INSTANCE 0
#define MAX_HISTORY_SIZE 100
#define QUEUE_DEPTH 100
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
ComQueueTester ::ComQueueTester() : ComQueueGTestBase("Tester", MAX_HISTORY_SIZE), component("ComQueue") {
this->initComponents();
this->connectPorts();
}
ComQueueTester ::~ComQueueTester() {}
void ComQueueTester ::dispatchAll() {
while (this->component.m_queue.getNumMsgs() > 0) {
this->component.doDispatch();
}
}
void ComQueueTester ::configure() {
ComQueue::QueueConfigurationTable configurationTable;
for (NATIVE_UINT_TYPE i = 0; i < ComQueue::TOTAL_PORT_COUNT; i++){
configurationTable.entries[i].priority = i;
configurationTable.entries[i].depth = 3;
}
component.configure(configurationTable, 0, mallocAllocator);
}
void ComQueueTester ::sendByQueueNumber(NATIVE_INT_TYPE queueNum, NATIVE_INT_TYPE& portNum, QueueType& queueType) {
U8 data[BUFFER_LENGTH] = {0xde, 0xad, 0xbe};
Fw::ComBuffer comBuffer(&data[0], sizeof(data));
Fw::Buffer buffer(&data[0], sizeof(data));
if (queueNum < ComQueue::COM_PORT_COUNT) {
portNum = queueNum;
queueType = QueueType::COM_QUEUE;
invoke_to_comQueueIn(portNum, comBuffer, 0);
} else {
portNum = queueNum - ComQueue::COM_PORT_COUNT;
queueType = QueueType::BUFFER_QUEUE;
invoke_to_buffQueueIn(portNum, buffer);
}
}
void ComQueueTester ::emitOne() {
Fw::Success state = Fw::Success::SUCCESS;
invoke_to_comStatusIn(0, state);
dispatchAll();
}
void ComQueueTester ::emitOneAndCheck(NATIVE_UINT_TYPE expectedIndex,
QueueType expectedType,
Fw::ComBuffer& expectedCom,
Fw::Buffer& expectedBuff) {
emitOne();
if (expectedType == QueueType::COM_QUEUE) {
ASSERT_from_comQueueSend(expectedIndex, expectedCom, 0);
} else {
ASSERT_from_buffQueueSend(expectedIndex, expectedBuff);
}
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void ComQueueTester ::testQueueSend() {
U8 data[BUFFER_LENGTH] = {0xde, 0xad, 0xbe};
Fw::ComBuffer comBuffer(&data[0], sizeof(data));
Fw::Buffer buffer(&data[0], sizeof(data));
configure();
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::COM_PORT_COUNT; portNum++){
invoke_to_comQueueIn(portNum, comBuffer, 0);
emitOneAndCheck(portNum, QueueType::COM_QUEUE, comBuffer, buffer);
}
clearFromPortHistory();
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::BUFFER_PORT_COUNT; portNum++){
invoke_to_buffQueueIn(portNum, buffer);
emitOneAndCheck(portNum, QueueType::BUFFER_QUEUE, comBuffer, buffer);
}
clearFromPortHistory();
component.cleanup();
}
void ComQueueTester ::testQueuePause() {
U8 data[BUFFER_LENGTH] = {0xde, 0xad, 0xbe};
Fw::ComBuffer comBuffer(&data[0], sizeof(data));
Fw::Buffer buffer(&data[0], sizeof(data));
configure();
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::COM_PORT_COUNT; portNum++){
invoke_to_comQueueIn(portNum, comBuffer, 0);
// Send a bunch of failures
Fw::Success state = Fw::Success::FAILURE;
invoke_to_comStatusIn(0, state);
invoke_to_comStatusIn(0, state);
invoke_to_comStatusIn(0, state);
emitOneAndCheck(portNum, QueueType::COM_QUEUE, comBuffer, buffer);
}
clearFromPortHistory();
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::BUFFER_PORT_COUNT; portNum++){
invoke_to_buffQueueIn(portNum, buffer);
// Send a bunch of failures
Fw::Success state = Fw::Success::FAILURE;
invoke_to_comStatusIn(0, state);
invoke_to_comStatusIn(0, state);
invoke_to_comStatusIn(0, state);
emitOneAndCheck(portNum, QueueType::BUFFER_QUEUE, comBuffer, buffer);
}
clearFromPortHistory();
component.cleanup();
}
void ComQueueTester ::testPrioritySend() {
U8 data[ComQueue::TOTAL_PORT_COUNT][BUFFER_LENGTH];
ComQueue::QueueConfigurationTable configurationTable;
for (NATIVE_UINT_TYPE i = 0; i < ComQueue::TOTAL_PORT_COUNT; i++) {
configurationTable.entries[i].priority = ComQueue::TOTAL_PORT_COUNT - i - 1;
configurationTable.entries[i].depth = 3;
data[i][0] = ComQueue::TOTAL_PORT_COUNT - i - 1;
}
// Make the last message have the same priority as the second message
configurationTable.entries[ComQueue::TOTAL_PORT_COUNT - 1].priority = 1;
data[ComQueue::TOTAL_PORT_COUNT - 2][0] = 0;
data[ComQueue::TOTAL_PORT_COUNT - 1][0] = 1;
component.configure(configurationTable, 0, mallocAllocator);
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::COM_PORT_COUNT; portNum++){
Fw::ComBuffer comBuffer(&data[portNum][0], BUFFER_LENGTH);
invoke_to_comQueueIn(portNum, comBuffer, 0);
}
for (NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::BUFFER_PORT_COUNT; portNum++) {
Fw::Buffer buffer(&data[portNum + ComQueue::COM_PORT_COUNT][0], BUFFER_LENGTH);
invoke_to_buffQueueIn(portNum, buffer);
}
// Check that nothing has yet been sent
ASSERT_from_buffQueueSend_SIZE(0);
ASSERT_from_comQueueSend_SIZE(0);
for (NATIVE_INT_TYPE index = 0; index < ComQueue::TOTAL_PORT_COUNT; index++) {
U8 orderKey;
U32 previousComSize = fromPortHistory_comQueueSend->size();
U32 previousBufSize = fromPortHistory_buffQueueSend->size();
emitOne();
ASSERT_EQ(fromPortHistory_comQueueSend->size() + fromPortHistory_buffQueueSend->size(), (index + 1));
// Check that the sizes changed by exactly one
ASSERT_TRUE((previousComSize == fromPortHistory_comQueueSend->size()) ^
(previousBufSize == fromPortHistory_buffQueueSend->size()));
// Look for which type had arrived
if (fromPortHistory_comQueueSend->size() > previousComSize) {
orderKey = fromPortHistory_comQueueSend->at(fromPortHistory_comQueueSend->size() - 1).data.getBuffAddr()[0];
} else {
orderKey =
fromPortHistory_buffQueueSend->at(fromPortHistory_buffQueueSend->size() - 1).fwBuffer.getData()[0];
}
ASSERT_EQ(orderKey, index);
}
clearFromPortHistory();
component.cleanup();
}
void ComQueueTester::testQueueOverflow(){
ComQueue::QueueConfigurationTable configurationTable;
ComQueueDepth expectedComDepth;
BuffQueueDepth expectedBuffDepth;
for (NATIVE_UINT_TYPE i = 0; i < ComQueue::TOTAL_PORT_COUNT; i++){
configurationTable.entries[i].priority = i;
configurationTable.entries[i].depth = 2;
// Expected depths
if (i < ComQueue::COM_PORT_COUNT) {
expectedComDepth[i] = configurationTable.entries[i].depth;
} else {
expectedBuffDepth[i - ComQueue::COM_PORT_COUNT] = configurationTable.entries[i].depth;
}
}
component.configure(configurationTable, 0, mallocAllocator);
for(NATIVE_INT_TYPE queueNum = 0; queueNum < ComQueue::TOTAL_PORT_COUNT; queueNum++) {
QueueType overflow_type;
NATIVE_INT_TYPE portNum;
// queue[portNum].depth + 2 to deliberately cause overflow and check throttle of exactly 1
for (NATIVE_UINT_TYPE msgCount = 0; msgCount < configurationTable.entries[queueNum].depth + 2; msgCount++) {
sendByQueueNumber(queueNum, portNum, overflow_type);
dispatchAll();
}
ASSERT_EVENTS_QueueOverflow_SIZE(1);
ASSERT_EVENTS_QueueOverflow(0, overflow_type, portNum);
// Drain a message, and see if throttle resets
emitOne();
// Force another overflow by filling then deliberately overflowing the queue
sendByQueueNumber(queueNum, portNum, overflow_type);
sendByQueueNumber(queueNum, portNum, overflow_type);
dispatchAll();
ASSERT_EVENTS_QueueOverflow_SIZE(2);
ASSERT_EVENTS_QueueOverflow(1, overflow_type, portNum);
// Drain the queue again such that we have a clean slate before the next queue
for (NATIVE_UINT_TYPE msgCount = 0; msgCount < configurationTable.entries[queueNum].depth; msgCount++) {
emitOne();
}
clearEvents();
}
// Check max seen queue-depths
invoke_to_run(0, 0);
dispatchAll();
ASSERT_TLM_comQueueDepth_SIZE(1);
ASSERT_TLM_buffQueueDepth_SIZE(1);
ASSERT_TLM_comQueueDepth(0, expectedComDepth);
ASSERT_TLM_buffQueueDepth(0, expectedBuffDepth);
component.cleanup();
}
void ComQueueTester ::testReadyFirst() {
U8 data[BUFFER_LENGTH] = {0xde, 0xad, 0xbe};
Fw::ComBuffer comBuffer(&data[0], sizeof(data));
Fw::Buffer buffer(&data[0], sizeof(data));
configure();
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::COM_PORT_COUNT; portNum++){
emitOne();
invoke_to_comQueueIn(portNum, comBuffer, 0);
dispatchAll();
ASSERT_from_comQueueSend(portNum, comBuffer, 0);
}
clearFromPortHistory();
for(NATIVE_INT_TYPE portNum = 0; portNum < ComQueue::BUFFER_PORT_COUNT; portNum++){
emitOne();
invoke_to_buffQueueIn(portNum, buffer);
dispatchAll();
ASSERT_from_buffQueueSend(portNum, buffer);
}
clearFromPortHistory();
component.cleanup();
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void ComQueueTester ::from_buffQueueSend_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
this->pushFromPortEntry_buffQueueSend(fwBuffer);
}
void ComQueueTester ::from_comQueueSend_handler(const NATIVE_INT_TYPE portNum, Fw::ComBuffer& data, U32 context) {
this->pushFromPortEntry_comQueueSend(data, context);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void ComQueueTester ::connectPorts() {
// buffQueueIn
for (NATIVE_INT_TYPE i = 0; i < ComQueue::BUFFER_PORT_COUNT; ++i) {
this->connect_to_buffQueueIn(i, this->component.get_buffQueueIn_InputPort(i));
}
// comQueueIn
for (NATIVE_INT_TYPE i = 0; i < ComQueue::COM_PORT_COUNT; ++i) {
this->connect_to_comQueueIn(i, this->component.get_comQueueIn_InputPort(i));
}
// comStatusIn
this->connect_to_comStatusIn(0, this->component.get_comStatusIn_InputPort(0));
// run
this->connect_to_run(0, this->component.get_run_InputPort(0));
// Log
this->component.set_Log_OutputPort(0, this->get_from_Log(0));
// LogText
this->component.set_LogText_OutputPort(0, this->get_from_LogText(0));
// Time
this->component.set_Time_OutputPort(0, this->get_from_Time(0));
// Tlm
this->component.set_Tlm_OutputPort(0, this->get_from_Tlm(0));
// buffQueueSend
this->component.set_buffQueueSend_OutputPort(0, this->get_from_buffQueueSend(0));
// comQueueSend
this->component.set_comQueueSend_OutputPort(0, this->get_from_comQueueSend(0));
}
void ComQueueTester ::initComponents() {
this->init();
this->component.init(QUEUE_DEPTH, INSTANCE);
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/ComQueue/test/ut/ComQueueTester.hpp | // ======================================================================
// \title ComQueue/test/ut/Tester.hpp
// \author vbai
// \brief hpp file for ComQueue test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "ComQueueGTestBase.hpp"
#include "Svc/ComQueue/ComQueue.hpp"
#define BUFFER_LENGTH 3u
namespace Svc {
class ComQueueTester : public ComQueueGTestBase {
private:
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object ComQueueTester
//!
ComQueueTester();
//! Destroy object ComQueueTester
//!
~ComQueueTester();
//! Dispatch all component messages
//!
void dispatchAll();
public:
// ----------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------
void configure();
void sendByQueueNumber(NATIVE_INT_TYPE queueNumber, NATIVE_INT_TYPE& portNum, QueueType& queueType);
void emitOne();
void emitOneAndCheck(NATIVE_UINT_TYPE expectedIndex,
QueueType expectedType,
Fw::ComBuffer& expectedCom,
Fw::Buffer& expectedBuff);
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void testQueueSend();
void testQueuePause();
void testPrioritySend();
void testQueueOverflow();
void testReadyFirst();
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_buffQueueSend
//!
void from_buffQueueSend_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer& fwBuffer);
//! Handler for from_comQueueSend
//!
void from_comQueueSend_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*/
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
ComQueue component;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/ComQueue/test/ut/ComQueueTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "ComQueueTester.hpp"
TEST(Nominal, Send) {
Svc::ComQueueTester tester;
tester.testQueueSend();
}
TEST(Nominal, Pause) {
Svc::ComQueueTester tester;
tester.testQueuePause();
}
TEST(Nominal, Priority) {
Svc::ComQueueTester tester;
tester.testPrioritySend();
}
TEST(Nominal, Full) {
Svc::ComQueueTester tester;
tester.testQueueOverflow();
}
TEST(Nominal, ReadyFirst) {
Svc::ComQueueTester tester;
tester.testReadyFirst();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Svc/FileDownlink/Warnings.cpp | // ======================================================================
// \title Warnings.cpp
// \author bocchino
// \brief cpp file for FileDownlink::Warnings
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <Svc/FileDownlink/FileDownlink.hpp>
namespace Svc {
void FileDownlink::Warnings ::
fileOpenError()
{
this->m_fileDownlink->log_WARNING_HI_FileOpenError(
this->m_fileDownlink->m_file.getSourceName()
);
this->warning();
}
void FileDownlink::Warnings ::
fileRead(const Os::File::Status status)
{
this->m_fileDownlink->log_WARNING_HI_FileReadError(
this->m_fileDownlink->m_file.getSourceName(),
status
);
this->warning();
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileDownlink/File.cpp | // ======================================================================
// \title File.cpp
// \author bocchino
// \brief cpp file for FileDownlink::File
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Svc/FileDownlink/FileDownlink.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <Os/FileSystem.hpp>
namespace Svc {
Os::File::Status FileDownlink::File ::
open(
const char *const sourceFileName,
const char *const destFileName
)
{
// Set source name
Fw::LogStringArg sourceLogStringArg(sourceFileName);
this->m_sourceName = sourceLogStringArg;
// Set dest name
Fw::LogStringArg destLogStringArg(destFileName);
this->m_destName = destLogStringArg;
// Set size
FwSignedSizeType file_size;
const Os::FileSystem::Status status =
Os::FileSystem::getFileSize(sourceFileName, file_size);
if (status != Os::FileSystem::OP_OK)
return Os::File::BAD_SIZE;
// If the size does not cast cleanly to the desired U32 type, return size error
if (static_cast<FwSignedSizeType>(static_cast<U32>(file_size)) != file_size) {
return Os::File::BAD_SIZE;
}
this->m_size = static_cast<U32>(file_size);
// Initialize checksum
CFDP::Checksum checksum;
this->m_checksum = checksum;
// Open osFile for reading
return this->m_osFile.open(sourceFileName, Os::File::OPEN_READ);
}
Os::File::Status FileDownlink::File ::
read(
U8 *const data,
const U32 byteOffset,
const U32 size
)
{
Os::File::Status status;
status = this->m_osFile.seek(byteOffset, Os::File::SeekType::ABSOLUTE);
if (status != Os::File::OP_OK) {
return status;
}
FwSignedSizeType intSize = size;
status = this->m_osFile.read(data, intSize);
if (status != Os::File::OP_OK) {
return status;
}
// Force a bad size error when the U32 carrying size is bad
if (static_cast<U32>(intSize) != size) {
return Os::File::BAD_SIZE;
}
this->m_checksum.update(data, byteOffset, size);
return Os::File::OP_OK;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileDownlink/FileDownlink.cpp | // ======================================================================
// \title FileDownlink.hpp
// \author bocchino, mstarch
// \brief hpp file for FileDownlink component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <Svc/FileDownlink/FileDownlink.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/StringUtils.hpp>
#include <Os/QueueString.hpp>
#include <limits>
namespace Svc {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
FileDownlink ::
FileDownlink(
const char *const name
) :
FileDownlinkComponentBase(name),
m_configured(false),
m_filesSent(this),
m_packetsSent(this),
m_warnings(this),
m_sequenceIndex(0),
m_curTimer(0),
m_bufferSize(0),
m_byteOffset(0),
m_endOffset(0),
m_lastCompletedType(Fw::FilePacket::T_NONE),
m_lastBufferId(0),
m_curEntry(),
m_cntxId(0)
{
}
void FileDownlink ::
init(
const NATIVE_INT_TYPE queueDepth,
const NATIVE_INT_TYPE instance
)
{
FileDownlinkComponentBase::init(queueDepth, instance);
}
void FileDownlink ::
configure(
U32 timeout,
U32 cooldown,
U32 cycleTime,
U32 fileQueueDepth
)
{
this->m_timeout = timeout;
this->m_cooldown = cooldown;
this->m_cycleTime = cycleTime;
this->m_configured = true;
Os::Queue::QueueStatus stat = m_fileQueue.create(
Os::QueueString("fileDownlinkQueue"),
fileQueueDepth,
sizeof(struct FileEntry)
);
FW_ASSERT(stat == Os::Queue::QUEUE_OK, stat);
}
void FileDownlink ::
preamble()
{
FW_ASSERT(this->m_configured == true);
}
FileDownlink ::
~FileDownlink()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void FileDownlink ::
Run_handler(
const NATIVE_INT_TYPE portNum,
U32 context
)
{
switch(this->m_mode.get())
{
case Mode::IDLE: {
NATIVE_INT_TYPE real_size = 0;
NATIVE_INT_TYPE prio = 0;
Os::Queue::QueueStatus stat = m_fileQueue.receive(
reinterpret_cast<U8*>(&this->m_curEntry),
sizeof(this->m_curEntry),
real_size,
prio,
Os::Queue::QUEUE_NONBLOCKING
);
if(stat != Os::Queue::QUEUE_OK || sizeof(this->m_curEntry) != real_size) {
return;
}
sendFile(
this->m_curEntry.srcFilename,
this->m_curEntry.destFilename,
this->m_curEntry.offset,
this->m_curEntry.length
);
break;
}
case Mode::COOLDOWN: {
if (this->m_curTimer >= this->m_cooldown) {
this->m_curTimer = 0;
this->m_mode.set(Mode::IDLE);
} else {
this->m_curTimer += m_cycleTime;
}
break;
}
case Mode::WAIT: {
//If current timeout is too-high and we are waiting for a packet, issue a timeout
if (this->m_curTimer >= this->m_timeout) {
this->m_curTimer = 0;
this->log_WARNING_HI_DownlinkTimeout(this->m_file.getSourceName(), this->m_file.getDestName());
this->enterCooldown();
this->sendResponse(FILEDOWNLINK_COMMAND_FAILURES_DISABLED ? SendFileStatus::STATUS_OK : SendFileStatus::STATUS_ERROR);
} else { //Otherwise update the current counter
this->m_curTimer += m_cycleTime;
}
break;
}
default:
break;
}
}
Svc::SendFileResponse FileDownlink ::
SendFile_handler(
const NATIVE_INT_TYPE portNum,
const sourceFileNameString& sourceFilename, // lgtm[cpp/large-parameter] dictated by command architecture
const destFileNameString& destFilename, // lgtm[cpp/large-parameter] dictated by command architecture
U32 offset,
U32 length
)
{
struct FileEntry entry;
entry.srcFilename[0] = 0;
entry.destFilename[0] = 0;
entry.offset = offset;
entry.length = length;
entry.source = FileDownlink::PORT;
entry.opCode = 0;
entry.cmdSeq = 0;
entry.context = m_cntxId++;
FW_ASSERT(sourceFilename.length() < sizeof(entry.srcFilename));
FW_ASSERT(destFilename.length() < sizeof(entry.destFilename));
(void) Fw::StringUtils::string_copy(entry.srcFilename, sourceFilename.toChar(), sizeof(entry.srcFilename));
(void) Fw::StringUtils::string_copy(entry.destFilename, destFilename.toChar(), sizeof(entry.destFilename));
Os::Queue::QueueStatus status = m_fileQueue.send(reinterpret_cast<U8*>(&entry), sizeof(entry), 0, Os::Queue::QUEUE_NONBLOCKING);
if(status != Os::Queue::QUEUE_OK) {
return SendFileResponse(SendFileStatus::STATUS_ERROR, std::numeric_limits<U32>::max());
}
return SendFileResponse(SendFileStatus::STATUS_OK, entry.context);
}
void FileDownlink ::
pingIn_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
this->pingOut_out(0,key);
}
void FileDownlink ::
bufferReturn_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
//If this is a stale buffer (old, timed-out, or both), then ignore its return.
//File downlink actions only respond to the return of the most-recently-sent buffer.
if (this->m_lastBufferId != fwBuffer.getContext() + 1 ||
this->m_mode.get() == Mode::IDLE) {
return;
}
//Non-ignored buffers cannot be returned in "DOWNLINK" and "IDLE" state. Only in "WAIT", "CANCEL" state.
FW_ASSERT(this->m_mode.get() == Mode::WAIT || this->m_mode.get() == Mode::CANCEL, this->m_mode.get());
//If the last packet has been sent (and is returning now) then finish the file
if (this->m_lastCompletedType == Fw::FilePacket::T_END ||
this->m_lastCompletedType == Fw::FilePacket::T_CANCEL) {
finishHelper(this->m_lastCompletedType == Fw::FilePacket::T_CANCEL);
return;
}
//If waiting and a buffer is in-bound, then switch to downlink mode
else if (this->m_mode.get() == Mode::WAIT) {
this->m_mode.set(Mode::DOWNLINK);
}
this->downlinkPacket();
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void FileDownlink ::
SendFile_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& sourceFilename,
const Fw::CmdStringArg& destFilename
)
{
struct FileEntry entry;
entry.srcFilename[0] = 0;
entry.destFilename[0] = 0;
entry.offset = 0;
entry.length = 0;
entry.source = FileDownlink::COMMAND;
entry.opCode = opCode;
entry.cmdSeq = cmdSeq;
entry.context = std::numeric_limits<U32>::max();
FW_ASSERT(sourceFilename.length() < sizeof(entry.srcFilename));
FW_ASSERT(destFilename.length() < sizeof(entry.destFilename));
(void) Fw::StringUtils::string_copy(entry.srcFilename, sourceFilename.toChar(), sizeof(entry.srcFilename));
(void) Fw::StringUtils::string_copy(entry.destFilename, destFilename.toChar(), sizeof(entry.destFilename));
Os::Queue::QueueStatus status = m_fileQueue.send(reinterpret_cast<U8*>(&entry), sizeof(entry), 0, Os::Queue::QUEUE_NONBLOCKING);
if(status != Os::Queue::QUEUE_OK) {
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR);
}
}
void FileDownlink ::
SendPartial_cmdHandler(
FwOpcodeType opCode,
U32 cmdSeq,
const Fw::CmdStringArg& sourceFilename,
const Fw::CmdStringArg& destFilename,
U32 startOffset,
U32 length
)
{
struct FileEntry entry;
entry.srcFilename[0] = 0;
entry.destFilename[0] = 0;
entry.offset = startOffset;
entry.length = length;
entry.source = FileDownlink::COMMAND;
entry.opCode = opCode;
entry.cmdSeq = cmdSeq;
entry.context = std::numeric_limits<U32>::max();
FW_ASSERT(sourceFilename.length() < sizeof(entry.srcFilename));
FW_ASSERT(destFilename.length() < sizeof(entry.destFilename));
(void) Fw::StringUtils::string_copy(entry.srcFilename, sourceFilename.toChar(), sizeof(entry.srcFilename));
(void) Fw::StringUtils::string_copy(entry.destFilename, destFilename.toChar(), sizeof(entry.destFilename));
Os::Queue::QueueStatus status = m_fileQueue.send(reinterpret_cast<U8*>(&entry), sizeof(entry), 0, Os::Queue::QUEUE_NONBLOCKING);
if(status != Os::Queue::QUEUE_OK) {
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::EXECUTION_ERROR);
}
}
void FileDownlink ::
Cancel_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq
)
{
//Must be able to cancel in both downlink and waiting states
if (this->m_mode.get() == Mode::DOWNLINK || this->m_mode.get() == Mode::WAIT) {
this->m_mode.set(Mode::CANCEL);
}
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
// ----------------------------------------------------------------------
// Private helper methods
// ----------------------------------------------------------------------
Fw::CmdResponse FileDownlink ::
statusToCmdResp(SendFileStatus status)
{
switch(status.e) {
case SendFileStatus::STATUS_OK:
return Fw::CmdResponse::OK;
case SendFileStatus::STATUS_ERROR:
return Fw::CmdResponse::EXECUTION_ERROR;
case SendFileStatus::STATUS_INVALID:
return Fw::CmdResponse::VALIDATION_ERROR;
case SendFileStatus::STATUS_BUSY:
return Fw::CmdResponse::BUSY;
default:
// Trigger assertion if given unknown status
FW_ASSERT(false);
}
// It's impossible to reach this, but added to suppress gcc missing return warning
return Fw::CmdResponse::EXECUTION_ERROR;
}
void FileDownlink ::
sendResponse(SendFileStatus resp)
{
if(this->m_curEntry.source == FileDownlink::COMMAND) {
this->cmdResponse_out(this->m_curEntry.opCode, this->m_curEntry.cmdSeq, statusToCmdResp(resp));
} else {
for(NATIVE_INT_TYPE i = 0; i < this->getNum_FileComplete_OutputPorts(); i++) {
if(this->isConnected_FileComplete_OutputPort(i)) {
this->FileComplete_out(i, Svc::SendFileResponse(resp, this->m_curEntry.context));
}
}
}
}
void FileDownlink ::
sendFile(
const char* sourceFilename,
const char* destFilename,
U32 startOffset,
U32 length
)
{
// Open file for downlink
Os::File::Status status = this->m_file.open(
sourceFilename,
destFilename
);
// Reject command if error when opening file
if (status != Os::File::OP_OK) {
this->m_mode.set(Mode::IDLE);
this->m_warnings.fileOpenError();
sendResponse(FILEDOWNLINK_COMMAND_FAILURES_DISABLED ? SendFileStatus::STATUS_OK : SendFileStatus::STATUS_ERROR);
return;
}
if (startOffset >= this->m_file.getSize()) {
this->enterCooldown();
this->log_WARNING_HI_DownlinkPartialFail(this->m_file.getSourceName(), this->m_file.getDestName(), startOffset, this->m_file.getSize());
sendResponse(FILEDOWNLINK_COMMAND_FAILURES_DISABLED ? SendFileStatus::STATUS_OK : SendFileStatus::STATUS_INVALID);
return;
} else if (startOffset + length > this->m_file.getSize()) {
// If the amount to downlink is greater than the file size, emit a Warning and then allow
// the file to be downlinked anyway
this->log_WARNING_LO_DownlinkPartialWarning(startOffset, length, this->m_file.getSize(), this->m_file.getSourceName(), this->m_file.getDestName());
length = this->m_file.getSize() - startOffset;
}
// Send file and switch to WAIT mode
this->getBuffer(this->m_buffer, FILE_PACKET);
this->sendStartPacket();
this->m_mode.set(Mode::WAIT);
this->m_sequenceIndex = 1;
this->m_curTimer = 0;
this->m_byteOffset = startOffset;
this->m_lastCompletedType = Fw::FilePacket::T_START;
// zero length means read until end of file
if (length > 0) {
this->log_ACTIVITY_HI_SendStarted(length, this->m_file.getSourceName(), this->m_file.getDestName());
this->m_endOffset = startOffset + length;
}
else {
this->log_ACTIVITY_HI_SendStarted(this->m_file.getSize() - startOffset, this->m_file.getSourceName(), this->m_file.getDestName());
this->m_endOffset = this->m_file.getSize();
}
}
Os::File::Status FileDownlink ::
sendDataPacket(U32 &byteOffset)
{
FW_ASSERT(byteOffset < this->m_endOffset);
const U32 maxDataSize = FILEDOWNLINK_INTERNAL_BUFFER_SIZE - Fw::FilePacket::DataPacket::HEADERSIZE;
const U32 dataSize = (byteOffset + maxDataSize > this->m_endOffset) ? (this->m_endOffset - byteOffset) : maxDataSize;
U8 buffer[FILEDOWNLINK_INTERNAL_BUFFER_SIZE - Fw::FilePacket::DataPacket::HEADERSIZE];
//This will be last data packet sent
if (dataSize + byteOffset == this->m_endOffset) {
this->m_lastCompletedType = Fw::FilePacket::T_DATA;
}
const Os::File::Status status =
this->m_file.read(buffer, byteOffset, dataSize);
if (status != Os::File::OP_OK) {
this->m_warnings.fileRead(status);
return status;
}
Fw::FilePacket::DataPacket dataPacket;
dataPacket.initialize(
this->m_sequenceIndex,
byteOffset,
static_cast<U16>(dataSize),
buffer);
++this->m_sequenceIndex;
Fw::FilePacket filePacket;
filePacket.fromDataPacket(dataPacket);
this->sendFilePacket(filePacket);
byteOffset += dataSize;
return Os::File::OP_OK;
}
void FileDownlink ::
sendCancelPacket()
{
Fw::Buffer buffer;
Fw::FilePacket::CancelPacket cancelPacket;
cancelPacket.initialize(this->m_sequenceIndex);
Fw::FilePacket filePacket;
filePacket.fromCancelPacket(cancelPacket);
this->getBuffer(buffer, CANCEL_PACKET);
const Fw::SerializeStatus status = filePacket.toBuffer(buffer);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
this->bufferSendOut_out(0, buffer);
this->m_packetsSent.packetSent();
}
void FileDownlink ::
sendEndPacket()
{
CFDP::Checksum checksum;
this->m_file.getChecksum(checksum);
Fw::FilePacket::EndPacket endPacket;
endPacket.initialize(this->m_sequenceIndex, checksum);
Fw::FilePacket filePacket;
filePacket.fromEndPacket(endPacket);
this->sendFilePacket(filePacket);
}
void FileDownlink ::
sendStartPacket()
{
Fw::FilePacket::StartPacket startPacket;
startPacket.initialize(
this->m_file.getSize(),
this->m_file.getSourceName().toChar(),
this->m_file.getDestName().toChar()
);
Fw::FilePacket filePacket;
filePacket.fromStartPacket(startPacket);
this->sendFilePacket(filePacket);
}
void FileDownlink ::
sendFilePacket(const Fw::FilePacket& filePacket)
{
const U32 bufferSize = filePacket.bufferSize();
FW_ASSERT(this->m_buffer.getData() != nullptr);
FW_ASSERT(this->m_buffer.getSize() >= bufferSize, bufferSize, this->m_buffer.getSize());
const Fw::SerializeStatus status = filePacket.toBuffer(this->m_buffer);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
// set the buffer size to the packet size
this->m_buffer.setSize(bufferSize);
this->bufferSendOut_out(0, this->m_buffer);
// restore buffer size to max
this->m_buffer.setSize(FILEDOWNLINK_INTERNAL_BUFFER_SIZE);
this->m_packetsSent.packetSent();
}
void FileDownlink ::
enterCooldown()
{
this->m_file.getOsFile().close();
this->m_mode.set(Mode::COOLDOWN);
this->m_lastCompletedType = Fw::FilePacket::T_NONE;
this->m_curTimer = 0;
}
void FileDownlink ::
downlinkPacket()
{
FW_ASSERT(this->m_lastCompletedType != Fw::FilePacket::T_NONE, this->m_lastCompletedType);
FW_ASSERT(this->m_mode.get() == Mode::CANCEL || this->m_mode.get() == Mode::DOWNLINK, this->m_mode.get());
//If canceled mode and currently downlinking data then send a cancel packet
if (this->m_mode.get() == Mode::CANCEL && this->m_lastCompletedType == Fw::FilePacket::T_START) {
this->sendCancelPacket();
this->m_lastCompletedType = Fw::FilePacket::T_CANCEL;
}
//If in downlink mode and currently downlinking data then continue with the next packer
else if (this->m_mode.get() == Mode::DOWNLINK && this->m_lastCompletedType == Fw::FilePacket::T_START) {
//Send the next packet, or fail doing so
const Os::File::Status status = this->sendDataPacket(this->m_byteOffset);
if (status != Os::File::OP_OK) {
this->log_WARNING_HI_SendDataFail(this->m_file.getSourceName(), this->m_byteOffset);
this->enterCooldown();
this->sendResponse(FILEDOWNLINK_COMMAND_FAILURES_DISABLED ? SendFileStatus::STATUS_OK : SendFileStatus::STATUS_ERROR);
//Don't go to wait state
return;
}
}
//If in downlink mode or cancel and finished downlinking data then send the last packet
else if (this->m_lastCompletedType == Fw::FilePacket::T_DATA) {
this->sendEndPacket();
this->m_lastCompletedType = Fw::FilePacket::T_END;
}
this->m_mode.set(Mode::WAIT);
this->m_curTimer = 0;
}
void FileDownlink ::
finishHelper(bool cancel)
{
//Complete command and switch to IDLE
if (not cancel) {
this->m_filesSent.fileSent();
this->log_ACTIVITY_HI_FileSent(this->m_file.getSourceName(), this->m_file.getDestName());
} else {
this->log_ACTIVITY_HI_DownlinkCanceled(this->m_file.getSourceName(), this->m_file.getDestName());
}
this->enterCooldown();
sendResponse(SendFileStatus::STATUS_OK);
}
void FileDownlink ::
getBuffer(Fw::Buffer& buffer, PacketType type)
{
//Check type is correct
FW_ASSERT(type < COUNT_PACKET_TYPE && type >= 0, type);
// Wrap the buffer around our indexed memory.
buffer.setData(this->m_memoryStore[type]);
buffer.setSize(FILEDOWNLINK_INTERNAL_BUFFER_SIZE);
//Set a known ID to look for later
buffer.setContext(m_lastBufferId);
m_lastBufferId++;
}
} // end namespace Svc
| cpp |
fprime | data/projects/fprime/Svc/FileDownlink/FileDownlink.hpp | // ======================================================================
// \title FileDownlink.hpp
// \author bocchino, mstarch
// \brief hpp file for FileDownlink component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef Svc_FileDownlink_HPP
#define Svc_FileDownlink_HPP
#include <FileDownlinkCfg.hpp>
#include <Svc/FileDownlink/FileDownlinkComponentAc.hpp>
#include <Fw/FilePacket/FilePacket.hpp>
#include <Os/File.hpp>
#include <Os/Mutex.hpp>
#include <Os/Queue.hpp>
namespace Svc {
class FileDownlink :
public FileDownlinkComponentBase
{
PRIVATE:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
//! The Mode class
class Mode {
public:
//! The Mode type
typedef enum { IDLE, DOWNLINK, CANCEL, WAIT, COOLDOWN } Type;
public:
//! Constructor
Mode() : m_value(IDLE) { }
public:
//! Set the Mode value
void set(const Type value) {
this->m_mutex.lock();
this->m_value = value;
this->m_mutex.unLock();
}
//! Get the Mode value
Type get() {
this->m_mutex.lock();
const Type value = this->m_value;
this->m_mutex.unLock();
return value;
}
private:
//! The Mode value
Type m_value;
//! The Mode mutex
Os::Mutex m_mutex;
};
//! Class representing an outgoing file
class File {
public:
//! Constructor
File() : m_size(0) { }
PRIVATE:
//! The source file name
Fw::LogStringArg m_sourceName;
//! The destination file name
Fw::LogStringArg m_destName;
//! The underlying OS file
Os::File m_osFile;
//! The file size
U32 m_size;
//! The checksum for the file
CFDP::Checksum m_checksum;
public:
//! Open the OS file for reading and initialize the checksum
Os::File::Status open(
const char *const sourceFileName, //!< The source file name
const char *const destFileName //!< The destination file name
);
//! Read bytes from the OS file and update the checksum
Os::File::Status read(
U8 *const data,
const U32 byteOffset,
const U32 size
);
//! Get the checksum
void getChecksum(CFDP::Checksum& checksum) {
checksum = this->m_checksum;
}
//! Get the source file name
Fw::LogStringArg& getSourceName(void) {
return this->m_sourceName;
}
//! Get the destination file name
Fw::LogStringArg& getDestName(void) {
return this->m_destName;
}
//! Get the underlying OS file
Os::File& getOsFile(void) {
return this->m_osFile;
}
//! Get the file size
U32 getSize(void) {
return this->m_size;
}
};
//! Class to record files sent
class FilesSent {
public:
//! Construct a FilesSent object
FilesSent(FileDownlink *const fileDownlink) :
m_sent_file_count(0),
m_fileDownlink(fileDownlink)
{ }
public:
//! Record a file sent
void fileSent() {
++this->m_sent_file_count;
this->m_fileDownlink->tlmWrite_FilesSent(m_sent_file_count);
}
PRIVATE:
//! The total number of file sent
U32 m_sent_file_count;
//! The enclosing FileDownlink object
FileDownlink *const m_fileDownlink;
};
//! Class to record packets sent
class PacketsSent {
public:
//! Construct a PacketsSent object
PacketsSent(FileDownlink *const fileDownlink) :
m_sent_packet_count(0),
m_fileDownlink(fileDownlink)
{ }
public:
//! Record a packet sent
void packetSent() {
++this->m_sent_packet_count;
this->m_fileDownlink->tlmWrite_PacketsSent(m_sent_packet_count);
}
PRIVATE:
//! The total number of downlinked packets
U32 m_sent_packet_count;
//! The enclosing FileDownlink object
FileDownlink *const m_fileDownlink;
};
//! Class to record warnings
class Warnings {
public:
//! Construct a Warnings object
Warnings(FileDownlink *const fileDownlink) :
m_warning_count(0),
m_fileDownlink(fileDownlink)
{ }
public:
//! Issue a File Open Error warning
void fileOpenError();
//! Issue a File Read Error warning
void fileRead(const Os::File::Status status);
PRIVATE:
//! Record a warning
void warning() {
++this->m_warning_count;
this->m_fileDownlink->tlmWrite_Warnings(m_warning_count);
}
PRIVATE:
//! The total number of warnings
U32 m_warning_count;
//! The enclosing FileDownlink object
FileDownlink *const m_fileDownlink;
};
//! Sources of send file requests
enum CallerSource { COMMAND, PORT };
#define FILE_ENTRY_FILENAME_LEN 101
//! Used to track a single file downlink request
struct FileEntry {
char srcFilename[FILE_ENTRY_FILENAME_LEN]; // Name of requested file
char destFilename[FILE_ENTRY_FILENAME_LEN]; // Name of requested file
U32 offset;
U32 length;
CallerSource source; // Source of the downlink request
FwOpcodeType opCode; // Op code of command, only set for CMD sources.
U32 cmdSeq; // CmdSeq number, only set for CMD sources.
U32 context; // Context id of request, only set for PORT sources.
};
//! Enumeration for packet types
//! Each type has a buffer to store it.
enum PacketType {
FILE_PACKET,
CANCEL_PACKET,
COUNT_PACKET_TYPE
};
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object FileDownlink
//!
FileDownlink(
const char *const compName //!< The component name
);
//! Initialize object FileDownlink
//!
void init(
const NATIVE_INT_TYPE queueDepth, //!< The queue depth
const NATIVE_INT_TYPE instance //!< The instance number
);
//! Configure FileDownlink component
//!
void configure(
U32 timeout, //!< Timeout threshold (milliseconds) while in WAIT state
U32 cooldown, //!< Cooldown (in ms) between finishing a downlink and starting the next file.
U32 cycleTime, //!< Rate at which we are running
U32 fileQueueDepth //!< Max number of items in file downlink queue
);
//! Start FileDownlink component
//! The component must be configured with configure() before starting.
//!
void preamble();
//! Destroy object FileDownlink
//!
~FileDownlink();
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
);
//! Handler implementation for SendFile
//!
Svc::SendFileResponse SendFile_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
const sourceFileNameString& sourceFilename, /*!< Path of file to downlink*/
const destFileNameString& destFilename, /*!< Path to store downlinked file at*/
U32 offset, /*!< Amount of data in bytes to downlink from file. 0 to read until end of file*/
U32 length /*!< Amount of data in bytes to downlink from file. 0 to read until end of file*/
);
//! Handler implementation for bufferReturn
//!
void bufferReturn_handler(
const NATIVE_INT_TYPE portNum, //!< The port number
Fw::Buffer &fwBuffer
);
//! Handler implementation for pingIn
//!
void pingIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
PRIVATE:
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
//! Implementation for FileDownlink_SendFile command handler
//!
void SendFile_cmdHandler(
const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& sourceFilename, //!< The name of the on-board file to send
const Fw::CmdStringArg& destFilename //!< The name of the destination file on the ground
);
//! Implementation for FileDownlink_Cancel command handler
//!
void Cancel_cmdHandler(
const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq //!< The command sequence number
);
//! Implementation for FILE_DWN_SEND_PARTIAL command handler
//!
void SendPartial_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& sourceFilename, //!< The name of the on-board file to send
const Fw::CmdStringArg& destFilename, //!< The name of the destination file on the ground
U32 startOffset, //!< Starting offset of the source file
U32 length //!< Number of bytes to send from starting offset. Length of 0 implies until the end of the file
);
PRIVATE:
// ----------------------------------------------------------------------
// Private helper methods
// ----------------------------------------------------------------------
void sendFile(
const char* sourceFilename, //!< The name of the on-board file to send
const char* destFilename, //!< The name of the destination file on the ground
U32 startOffset, //!< Starting offset of the source file
U32 length //!< Number of bytes to send from starting offset. Length of 0 implies until the end of the file
);
//Individual packet transfer functions
Os::File::Status sendDataPacket(U32 &byteOffset);
void sendCancelPacket();
void sendEndPacket();
void sendStartPacket();
void sendFilePacket(const Fw::FilePacket& filePacket);
//State-helper functions
void exitFileTransfer();
void enterCooldown();
//Function to acquire a buffer internally
void getBuffer(Fw::Buffer& buffer, PacketType type);
//Downlink the "next" packet
void downlinkPacket();
//Finish the file transfer
void finishHelper(bool is_cancel);
// Convert internal status enum to a command response;
Fw::CmdResponse statusToCmdResp(SendFileStatus status);
//Send response after completing file downlink
void sendResponse(SendFileStatus resp);
PRIVATE:
// ----------------------------------------------------------------------
// Member variables
// ----------------------------------------------------------------------
//! Whether the configuration function has been called.
bool m_configured;
//! File downlink queue
Os::Queue m_fileQueue;
//!Buffer's memory backing
U8 m_memoryStore[COUNT_PACKET_TYPE][FILEDOWNLINK_INTERNAL_BUFFER_SIZE];
//! The mode
Mode m_mode;
//! The file
File m_file;
//! Files sent
FilesSent m_filesSent;
//! Packets sent
PacketsSent m_packetsSent;
//! Warnings
Warnings m_warnings;
//! The current sequence index
U32 m_sequenceIndex;
//! Timeout threshold (milliseconds) while in WAIT state
U32 m_timeout;
//! Cooldown (in ms) between finishing a downlink and starting the next file.
U32 m_cooldown;
//! current time residing in WAIT state
U32 m_curTimer;
//! rate (milliseconds) at which we are running
U32 m_cycleTime;
////! Buffer for sending file data
Fw::Buffer m_buffer;
//! Buffer size for file data
U32 m_bufferSize;
//! Current byte offset in file
U32 m_byteOffset;
//! Amount of bytes left to read
U32 m_endOffset;
//! Set to true when all data packets have been sent
Fw::FilePacket::Type m_lastCompletedType;
//! Last buffer used
U32 m_lastBufferId;
//! Current in progress file entry from queue
struct FileEntry m_curEntry;
//! Incrementing context id used to unique identify a specific downlink request
U32 m_cntxId;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/FileDownlink/test/ut/FileDownlinkTester.cpp | // ======================================================================
// \title FileDownlinkTester.cpp
// \author bocchino
// \brief cpp file for FileDownlink test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <cerrno>
#include <unistd.h>
#include "FileDownlinkTester.hpp"
#define INSTANCE 0
#define CMD_SEQ 0
#define QUEUE_DEPTH 10
#define TIMEOUT_MS 1000
#define COOLDOWN_MS 500
#define CYCLE_MS 100
#define MAX_ALLOCATED 100
namespace Svc {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
FileDownlinkTester ::
FileDownlinkTester() :
FileDownlinkGTestBase("Tester", MAX_HISTORY_SIZE),
component("FileDownlink"),
buffers_index(0)
{
this->component.configure(TIMEOUT_MS, COOLDOWN_MS, CYCLE_MS, 10);
this->connectPorts();
this->initComponents();
}
FileDownlinkTester ::
~FileDownlinkTester()
{
for (U32 i = 0; i < buffers_index; i++) {
delete [] buffers[i];
}
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void FileDownlinkTester ::
downlink()
{
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
// Create a file
const char *const sourceFileName = "source.bin";
const char *const destFileName = "dest.bin";
U8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
FileBuffer fileBufferOut(data, sizeof(data));
fileBufferOut.write(sourceFileName);
// Send the file and assert COMMAND_OK
this->sendFile(sourceFileName, destFileName, Fw::CmdResponse::OK);
// Assert telemetry
ASSERT_TLM_SIZE(4);
ASSERT_TLM_PacketsSent_SIZE(3);
for (size_t i = 0; i < 3; ++i) {
ASSERT_TLM_PacketsSent(i, i + 1);
}
ASSERT_TLM_FilesSent_SIZE(1);
ASSERT_TLM_FilesSent(0, 1);
// Assert events
ASSERT_EVENTS_SIZE(2);
ASSERT_EVENTS_FileSent_SIZE(1);
ASSERT_EVENTS_SendStarted_SIZE(1);
// printTextLogHistory(stdout);
ASSERT_EVENTS_SendStarted(0, 10, sourceFileName, destFileName);
ASSERT_EVENTS_FileSent(0, sourceFileName, destFileName);
// Validate the packet history
History<Fw::FilePacket::DataPacket> dataPackets(MAX_HISTORY_SIZE);
CFDP::Checksum checksum;
fileBufferOut.getChecksum(checksum);
validatePacketHistory(
*this->fromPortHistory_bufferSendOut,
dataPackets,
Fw::FilePacket::T_END,
3,
checksum,
0
);
// Compare the outgoing and incoming files
FileBuffer fileBufferIn(dataPackets);
ASSERT_EQ(true, FileBuffer::compare(fileBufferIn, fileBufferOut));
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
// Remove the outgoing file
this->removeFile(sourceFileName);
}
void FileDownlinkTester ::
fileOpenError()
{
const char *const sourceFileName = "missing_directory/source.bin";
const char *const destFileName = "dest.bin";
// Send the file and assert CmdResponse::EXECUTION_ERROR
this->sendFile(
sourceFileName,
destFileName,
(FILEDOWNLINK_COMMAND_FAILURES_DISABLED) ? Fw::CmdResponse::OK : Fw::CmdResponse::EXECUTION_ERROR
);
// Assert telemetry
ASSERT_TLM_SIZE(1);
ASSERT_TLM_Warnings(0, 1);
// Assert events
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_FileOpenError_SIZE(1);
// ASSERT_EVENTS_FileDownlink_FileOpenError(0, sourceFileName);
}
void FileDownlinkTester ::
cancelDownlink()
{
// Create a file
const char *const sourceFileName = "source.bin";
const char *const destFileName = "dest.bin";
U8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
FileBuffer fileBufferOut(data, sizeof(data));
fileBufferOut.write(sourceFileName);
// Send a file
Fw::CmdStringArg sourceCmdStringArg(sourceFileName);
Fw::CmdStringArg destCmdStringArg(destFileName);
this->sendCmd_SendFile(
INSTANCE,
CMD_SEQ,
sourceCmdStringArg,
destCmdStringArg
);
this->sendCmd_Cancel(INSTANCE, CMD_SEQ);
this->component.doDispatch(); // Dispatch start command
this->component.Run_handler(0,0); // Enqueue and start processing file
this->component.doDispatch(); // Dispatch cancel command
// Assert cancelation response
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, FileDownlink::OPCODE_CANCEL, CMD_SEQ, Fw::CmdResponse::OK);
this->cmdResponseHistory->clear();
ASSERT_EQ(FileDownlink::Mode::CANCEL, this->component.m_mode.get());
this->component.doDispatch(); // Process return of original buffer and send cancel packet
this->component.doDispatch(); // Process return of cancel packet
// Ensure initial send file command also receives a response.
Fw::CmdResponse resp = (FILEDOWNLINK_COMMAND_FAILURES_DISABLED) ? Fw::CmdResponse::OK : Fw::CmdResponse::EXECUTION_ERROR;
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, FileDownlink::OPCODE_SENDFILE, CMD_SEQ, resp);
// Assert telemetry
ASSERT_TLM_SIZE(2);
// Assert cancel event
ASSERT_EVENTS_SIZE(2); // Started and cancel
ASSERT_EVENTS_DownlinkCanceled_SIZE(1);
ASSERT_EQ(FileDownlink::Mode::COOLDOWN, this->component.m_mode.get());
this->removeFile(sourceFileName);
}
void FileDownlinkTester ::
cancelInIdleMode()
{
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
// Send a cancel command
this->cancel(Fw::CmdResponse::OK);
this->component.Run_handler(0,0);
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
}
void FileDownlinkTester ::
downlinkPartial()
{
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
// Create a file
const char *const sourceFileName = "source.bin";
const char *const destFileName = "dest.bin";
U8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
U8 dataSubset[] = { 1, 2, 3, 4 };
U32 offset = 1;
U32 length = 4;
FileBuffer fileBufferOut(data, sizeof(data));
fileBufferOut.write(sourceFileName);
FileBuffer fileBufferOutSubset(dataSubset, sizeof(dataSubset));
// Test send partial past end of file, should return COMMAND_OK but raise a warning event.
Fw::CmdResponse expResp = FILEDOWNLINK_COMMAND_FAILURES_DISABLED ? Fw::CmdResponse::OK : Fw::CmdResponse::VALIDATION_ERROR;
this->sendFilePartial(sourceFileName, destFileName, expResp, sizeof(data), length);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_DownlinkPartialFail(0, sourceFileName, destFileName, sizeof(data), sizeof(data));
this->cmdResponseHistory->clear();
this->clearEvents();
// Send the file and assert COMMAND_OK
this->sendFilePartial(sourceFileName, destFileName, Fw::CmdResponse::OK, offset, length);
// Assert telemetry
ASSERT_TLM_SIZE(4);
ASSERT_TLM_PacketsSent_SIZE(3);
for (size_t i = 0; i < 3; ++i) {
ASSERT_TLM_PacketsSent(i, i + 1);
}
ASSERT_TLM_FilesSent_SIZE(1);
ASSERT_TLM_FilesSent(0, 1);
// Assert events
ASSERT_EVENTS_SIZE(2); // Start and sent
ASSERT_EVENTS_SendStarted_SIZE(1);
ASSERT_EVENTS_FileSent_SIZE(1);
// printTextLogHistory(stdout);
ASSERT_EVENTS_FileSent(0, sourceFileName, destFileName);
ASSERT_EVENTS_SendStarted(0, length, sourceFileName, destFileName);
// Validate the packet history
History<Fw::FilePacket::DataPacket> dataPackets(MAX_HISTORY_SIZE);
CFDP::Checksum checksum;
checksum.update(dataSubset, offset, length);
validatePacketHistory(
*this->fromPortHistory_bufferSendOut,
dataPackets,
Fw::FilePacket::T_END,
3,
checksum,
1
);
// Compare the outgoing and incoming files
FileBuffer fileBufferIn(dataPackets);
ASSERT_EQ(true, FileBuffer::compare(fileBufferIn, fileBufferOutSubset));
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
// Remove the outgoing file
this->removeFile(sourceFileName);
}
void FileDownlinkTester ::
timeout()
{
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::IDLE, this->component.m_mode.get());
// Create a file
const char *const sourceFileName = "source.bin";
const char *const destFileName = "dest.bin";
U8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
FileBuffer fileBufferOut(data, sizeof(data));
fileBufferOut.write(sourceFileName);
Fw::CmdStringArg sourceCmdStringArg(sourceFileName);
Fw::CmdStringArg destCmdStringArg(destFileName);
this->sendCmd_SendFile(
INSTANCE,
CMD_SEQ,
sourceCmdStringArg,
destCmdStringArg
);
this->component.doDispatch(); // Dispatch sendfile command
this->component.Run_handler(0,0); // Pull file from queue
// Continue running the component without dispatching the responses
for (U32 i = 0; i < TIMEOUT_MS/CYCLE_MS; i++) {
this->component.Run_handler(0,0);
ASSERT_CMD_RESPONSE_SIZE(0);
}
this->component.Run_handler(0,0);
ASSERT_CMD_RESPONSE_SIZE(1);
Fw::CmdResponse expResp = FILEDOWNLINK_COMMAND_FAILURES_DISABLED ? Fw::CmdResponse::OK : Fw::CmdResponse::EXECUTION_ERROR;
ASSERT_CMD_RESPONSE(0, FileDownlink::OPCODE_SENDFILE, CMD_SEQ, expResp);
// Assert telemetry
ASSERT_TLM_SIZE(1);
ASSERT_TLM_PacketsSent_SIZE(1);
// Assert events
ASSERT_EVENTS_SIZE(2);
ASSERT_EVENTS_DownlinkTimeout_SIZE(1);
ASSERT_EVENTS_SendStarted_SIZE(1);
// printTextLogHistory(stdout);
ASSERT_EVENTS_SendStarted(0, 10, sourceFileName, destFileName);
ASSERT_EVENTS_DownlinkTimeout(0, sourceFileName, destFileName);
// Assert idle mode
ASSERT_EQ(FileDownlink::Mode::COOLDOWN, this->component.m_mode.get());
// Remove the outgoing file
this->removeFile(sourceFileName);
}
void FileDownlinkTester ::
sendFilePort()
{
// Create a file
const char *const sourceFileName = "source.bin";
const char *const destFileName = "dest.bin";
U8 data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
FileBuffer fileBufferOut(data, sizeof(data));
fileBufferOut.write(sourceFileName);
sourceFileNameString srcFileArg(sourceFileName);
destFileNameString destFileArg(destFileName);
Svc::SendFileResponse resp = this->invoke_to_SendFile(0, srcFileArg, destFileArg, 0, 0);
ASSERT_EQ(resp.getstatus(), SendFileStatus::STATUS_OK);
ASSERT_EQ(resp.getcontext(), 0);
this->component.Run_handler(0,0); // Dequeue file downlink request
while (this->component.m_mode.get() != FileDownlink::Mode::IDLE) {
if(this->component.m_mode.get() != FileDownlink::Mode::COOLDOWN) {
this->component.doDispatch();
}
this->component.Run_handler(0,0);
}
ASSERT_from_FileComplete_SIZE(1);
ASSERT_from_FileComplete(0, Svc::SendFileResponse(SendFileStatus(SendFileStatus::STATUS_OK), 0));
// Assert telemetry
ASSERT_TLM_SIZE(4);
ASSERT_TLM_PacketsSent_SIZE(3);
for (size_t i = 0; i < 3; ++i) {
ASSERT_TLM_PacketsSent(i, i + 1);
}
ASSERT_TLM_FilesSent_SIZE(1);
ASSERT_TLM_FilesSent(0, 1);
// Assert events
ASSERT_EVENTS_SIZE(2);
ASSERT_EVENTS_FileSent_SIZE(1);
ASSERT_EVENTS_SendStarted_SIZE(1);
ASSERT_EVENTS_SendStarted(0, 10, sourceFileName, destFileName);
ASSERT_EVENTS_FileSent(0, sourceFileName, destFileName);
// Validate the packet history
History<Fw::FilePacket::DataPacket> dataPackets(MAX_HISTORY_SIZE);
CFDP::Checksum checksum;
fileBufferOut.getChecksum(checksum);
validatePacketHistory(
*this->fromPortHistory_bufferSendOut,
dataPackets,
Fw::FilePacket::T_END,
3,
checksum,
0
);
// Compare the outgoing and incoming files
FileBuffer fileBufferIn(dataPackets);
ASSERT_EQ(true, FileBuffer::compare(fileBufferIn, fileBufferOut));
// Remove the outgoing file
this->removeFile(sourceFileName);
}
// ----------------------------------------------------------------------
// Handlers for from ports
// ----------------------------------------------------------------------
void FileDownlinkTester ::
from_bufferSendOut_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer& buffer
)
{
ASSERT_LT(buffers_index, FW_NUM_ARRAY_ELEMENTS(this->buffers));
// Copy buffer before recycling
U8* data = new U8[buffer.getSize()];
this->buffers[buffers_index] = data;
buffers_index++;
::memcpy(data, buffer.getData(), buffer.getSize());
Fw::Buffer buffer_new = buffer;
buffer_new.setData(data);
pushFromPortEntry_bufferSendOut(buffer_new);
invoke_to_bufferReturn(0, buffer);
}
void FileDownlinkTester ::
from_pingOut_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
pushFromPortEntry_pingOut(key);
}
void FileDownlinkTester ::
from_FileComplete_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
const Svc::SendFileResponse& response
)
{
pushFromPortEntry_FileComplete(response);
}
// ----------------------------------------------------------------------
// Private instance methods
// ----------------------------------------------------------------------
void FileDownlinkTester ::
connectPorts()
{
// cmdIn
this->connect_to_cmdIn(
0,
this->component.get_cmdIn_InputPort(0)
);
// Run
this->connect_to_Run(
0,
this->component.get_Run_InputPort(0)
);
// bufferReturn
this->connect_to_bufferReturn(
0,
this->component.get_bufferReturn_InputPort(0)
);
// Sendfile
this->connect_to_SendFile(
0,
this->component.get_SendFile_InputPort(0)
);
// timeCaller
this->component.set_timeCaller_OutputPort(
0,
this->get_from_timeCaller(0)
);
// cmdRegOut
this->component.set_cmdRegOut_OutputPort(
0,
this->get_from_cmdRegOut(0)
);
// eventOut
this->component.set_eventOut_OutputPort(
0,
this->get_from_eventOut(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)
);
// cmdResponseOut
this->component.set_cmdResponseOut_OutputPort(
0,
this->get_from_cmdResponseOut(0)
);
// LogText
this->component.set_textEventOut_OutputPort(
0,
this->get_from_textEventOut(0)
);
// FileComplete
this->component.set_FileComplete_OutputPort(
0,
this->get_from_FileComplete(0)
);
}
void FileDownlinkTester ::
initComponents()
{
this->init();
this->component.init(
QUEUE_DEPTH,
INSTANCE
);
}
void FileDownlinkTester ::
sendFile(
const char *const sourceFileName,
const char *const destFileName,
const Fw::CmdResponse response
)
{
Fw::CmdStringArg sourceCmdStringArg(sourceFileName);
Fw::CmdStringArg destCmdStringArg(destFileName);
this->sendCmd_SendFile(
INSTANCE,
CMD_SEQ,
sourceCmdStringArg,
destCmdStringArg
);
this->component.doDispatch();
this->component.Run_handler(0,0);
while (this->component.m_mode.get() != FileDownlink::Mode::IDLE) {
if(this->component.m_mode.get() != FileDownlink::Mode::COOLDOWN) {
this->component.doDispatch();
}
this->component.Run_handler(0,0);
}
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, FileDownlink::OPCODE_SENDFILE, CMD_SEQ, response);
}
void FileDownlinkTester ::
sendFilePartial(
const char *const sourceFileName, //!< The source file name
const char *const destFileName, //!< The destination file name
const Fw::CmdResponse response, //!< The expected command response
U32 startIndex, //!< The starting index
U32 length //!< The amount of bytes to downlink
)
{
Fw::CmdStringArg sourceCmdStringArg(sourceFileName);
Fw::CmdStringArg destCmdStringArg(destFileName);
this->sendCmd_SendPartial(
INSTANCE,
CMD_SEQ,
sourceCmdStringArg,
destCmdStringArg,
startIndex,
length
);
this->component.doDispatch();
this->component.Run_handler(0,0);
while (this->component.m_mode.get() != FileDownlink::Mode::IDLE) {
if(this->component.m_mode.get() != FileDownlink::Mode::COOLDOWN) {
this->component.doDispatch();
}
this->component.Run_handler(0,0);
}
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, FileDownlink::OPCODE_SENDPARTIAL, CMD_SEQ, response);
}
void FileDownlinkTester ::
cancel(const Fw::CmdResponse response)
{
// Command the File Downlink component to cancel a file downlink
this->sendCmd_Cancel(INSTANCE, CMD_SEQ);
this->component.doDispatch(); // Cancel command processes here
// Assert command response
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(
0,
FileDownlink::OPCODE_CANCEL,
CMD_SEQ,
response
);
}
void FileDownlinkTester ::
removeFile(const char *const name)
{
const NATIVE_INT_TYPE status = ::unlink(name);
if (status != 0) {
// OK if file is not there
ASSERT_EQ(ENOENT, errno);
}
}
// ----------------------------------------------------------------------
// Private static methods
// ----------------------------------------------------------------------
void FileDownlinkTester ::
validatePacketHistory(
const History<FromPortEntry_bufferSendOut>& historyIn,
History<Fw::FilePacket::DataPacket>& historyOut,
const Fw::FilePacket::Type finalPacketType,
const size_t numPackets,
const CFDP::Checksum& checksum,
U32 startOffset
)
{
FW_ASSERT(numPackets > 0);
const size_t size = historyIn.size();
ASSERT_EQ(numPackets, size);
{
const Fw::Buffer& buffer = historyIn.at(0).fwBuffer;
validateStartPacket(buffer);
}
for (size_t i = 1; i < size - 1; ++i) {
const Fw::Buffer& buffer = historyIn.at(i).fwBuffer;
Fw::FilePacket::DataPacket dataPacket;
validateDataPacket(
buffer,
dataPacket,
i,
startOffset
);
historyOut.push_back(dataPacket);
}
const size_t index = size - 1;
const Fw::Buffer& buffer = historyIn.at(index).fwBuffer;
switch (finalPacketType) {
case Fw::FilePacket::T_END: {
validateEndPacket(buffer, index, checksum);
break;
}
case Fw::FilePacket::T_CANCEL: {
validateCancelPacket(buffer, index);
break;
}
default:
FW_ASSERT(0);
}
}
void FileDownlinkTester ::
validateFilePacket(
const Fw::Buffer& buffer,
Fw::FilePacket& filePacket
)
{
const Fw::SerializeStatus status = filePacket.fromBuffer(buffer);
ASSERT_EQ(Fw::FW_SERIALIZE_OK, status);
}
void FileDownlinkTester ::
validateStartPacket(const Fw::Buffer& buffer)
{
Fw::FilePacket filePacket;
validateFilePacket(buffer, filePacket);
const Fw::FilePacket::Header& header = filePacket.asHeader();
ASSERT_EQ(0U, header.m_sequenceIndex);
ASSERT_EQ(Fw::FilePacket::T_START, header.m_type);
}
void FileDownlinkTester ::
validateDataPacket(
const Fw::Buffer& buffer,
Fw::FilePacket::DataPacket& dataPacket,
const U32 sequenceIndex,
U32& byteOffset
)
{
Fw::FilePacket filePacket;
validateFilePacket(buffer, filePacket);
const Fw::FilePacket::Header& header = filePacket.asHeader();
ASSERT_EQ(sequenceIndex, header.m_sequenceIndex);
ASSERT_EQ(Fw::FilePacket::T_DATA, header.m_type);
dataPacket = filePacket.asDataPacket();
ASSERT_EQ(byteOffset, dataPacket.m_byteOffset);
byteOffset += dataPacket.m_dataSize;
}
void FileDownlinkTester ::
validateEndPacket(
const Fw::Buffer& buffer,
const U32 sequenceIndex,
const CFDP::Checksum& checksum
)
{
Fw::FilePacket filePacket;
validateFilePacket(buffer, filePacket);
const Fw::FilePacket::Header& header = filePacket.asHeader();
ASSERT_EQ(sequenceIndex, header.m_sequenceIndex);
ASSERT_EQ(Fw::FilePacket::T_END, header.m_type);
const Fw::FilePacket::EndPacket endPacket = filePacket.asEndPacket();
CFDP::Checksum computedChecksum;
endPacket.getChecksum(computedChecksum);
ASSERT_EQ(true, checksum == computedChecksum);
}
void FileDownlinkTester ::
validateCancelPacket(
const Fw::Buffer& buffer,
const U32 sequenceIndex
)
{
Fw::FilePacket filePacket;
validateFilePacket(buffer, filePacket);
const Fw::FilePacket::Header& header = filePacket.asHeader();
ASSERT_EQ(sequenceIndex, header.m_sequenceIndex);
ASSERT_EQ(Fw::FilePacket::T_CANCEL, header.m_type);
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileDownlink/test/ut/FileBuffer.cpp | // ======================================================================
// \title FileBuffer.hpp
// \author bocchino
// \brief cpp file for FileDownlinkTester::FileBuffer
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#include <cstring>
#include "FileDownlinkTester.hpp"
namespace Svc {
FileDownlinkTester::FileBuffer ::
FileBuffer(
const U8 *const data,
const size_t size
) :
index(0)
{
this->push(data, size);
FW_ASSERT(this->index == size);
}
FileDownlinkTester::FileBuffer ::
FileBuffer(
const History<Fw::FilePacket::DataPacket>& dataPackets
) :
index(0)
{
size_t numPackets = dataPackets.size();
for (size_t i = 0; i < numPackets; ++i) {
const Fw::FilePacket::DataPacket& dataPacket = dataPackets.at(i);
this->push(dataPacket.m_data, dataPacket.m_dataSize);
}
}
void FileDownlinkTester::FileBuffer ::
push(
const U8 *const data,
const size_t size
)
{
FW_ASSERT(this->index + size <= FILE_BUFFER_CAPACITY);
memcpy(&this->data[index], data, size);
this->index += size;
}
void FileDownlinkTester::FileBuffer ::
write(const char *const fileName)
{
Os::File::Status status;
Os::File file;
status = file.open(fileName, Os::File::OPEN_WRITE);
FW_ASSERT(status == Os::File::OP_OK);
const U32 size = this->index;
FwSignedSizeType intSize = size;
status = file.write(this->data, intSize);
FW_ASSERT(status == Os::File::OP_OK);
FW_ASSERT(static_cast<U32>(intSize) == size);
file.close();
}
void FileDownlinkTester::FileBuffer ::
getChecksum(CFDP::Checksum& checksum)
{
CFDP::Checksum c;
c.update(this->data, 0, this->index);
checksum = c;
}
bool FileDownlinkTester::FileBuffer ::
compare(const FileBuffer& fb1, const FileBuffer& fb2)
{
if (fb1.index != fb2.index) {
fprintf(
stderr,
"FileBuffer: sizes do not match (%lu vs %lu)\n",
fb1.index,
fb2.index
);
return false;
}
FW_ASSERT(fb1.index <= FILE_BUFFER_CAPACITY);
if (memcmp(fb1.data, fb2.data, fb1.index) != 0) {
fprintf(stderr, "FileBuffer: data does not match\n");
return false;
}
return true;
}
}
| cpp |
fprime | data/projects/fprime/Svc/FileDownlink/test/ut/FileDownlinkTester.hpp | // ======================================================================
// \title FileDownlink/test/ut/Tester.hpp
// \author bocchino
// \brief hpp file for FileDownlink 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 <Svc/FileDownlink/FileDownlink.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Test/UnitTest.hpp>
#include "FileDownlinkGTestBase.hpp"
#define MAX_HISTORY_SIZE 10
#define FILE_BUFFER_CAPACITY 100
namespace Svc {
class FileDownlinkTester :
public FileDownlinkGTestBase
{
private:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
// A buffer for assembling files
class FileBuffer {
public:
//! Construct a FileBuffer from raw data
FileBuffer(
const U8 *const data,
const size_t size
);
//! Construct a FileBuffer from a history of data packets
FileBuffer(
const History<Fw::FilePacket::DataPacket>& dataPackets
);
public:
//! Write the buffer to file
void write(const char *const fileName);
//! Get the checksum for the file
void getChecksum(CFDP::Checksum& checksum);
public:
//! Compare two file buffers
static bool compare(
const FileBuffer& fb1,
const FileBuffer& fb2
);
private:
//! Push data onto the buffer
void push(
const U8 *const data,
const size_t size
);
private:
//! The data
U8 data[FILE_BUFFER_CAPACITY];
//! The index into the buffer
size_t index;
};
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object FileDownlinkTester
//!
FileDownlinkTester();
//! Destroy object FileDownlinkTester
//!
~FileDownlinkTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Create a file F
//! Downlink F
//! Verify that the downlinked file matches F
//!
void downlink();
//! Cause a file open error
//!
void fileOpenError();
//! Start and then cancel a downlink
//!
void cancelDownlink();
//! Send a cancel command in idle mode
//!
void cancelInIdleMode();
//! Create a file F
//! Downlink partial F
//! Verify that the downlinked file matches F
//!
void downlinkPartial();
//! Timeout
//!
void timeout();
//! sendFilePort
//! Test downlinking a file via a port
//!
void sendFilePort();
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_bufferSendOut
//!
void from_pingOut_handler(
const NATIVE_INT_TYPE portNum,
U32 key
);
//! Handler for from_FileComplete
//!
void from_FileComplete_handler(
const NATIVE_INT_TYPE portNum,
const Svc::SendFileResponse& resp
);
private:
// ----------------------------------------------------------------------
// Private instance methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
//! Command the FileDownlink component to send a file
//! Assert a command response
//!
void sendFile(
const char *const sourceFileName, //!< The source file name
const char *const destFileName, //!< The destination file name
const Fw::CmdResponse response //!< The expected command response
);
//! Command the FileDownlink component to send a file
//! Assert a command response
//!
void sendFilePartial(
const char *const sourceFileName, //!< The source file name
const char *const destFileName, //!< The destination file name
const Fw::CmdResponse response, //!< The expected command response
U32 startIndex, //!< The starting index
U32 length //!< The amount of bytes to downlink
);
//! Command the FileDownlink component to cancel a file downlink
//! Assert a command response
//!
void cancel(
const Fw::CmdResponse response //!< The expected command response
);
//! Remove a file
//!
void removeFile(
const char *const name //!< The file name
);
// ----------------------------------------------------------------------
// Private static methods
// ----------------------------------------------------------------------
//! Validate a packet history and accumulate the data packets
//!
static void validatePacketHistory(
const History<FromPortEntry_bufferSendOut>& historyIn, //!< The incoming history
History<Fw::FilePacket::DataPacket>& historyOut, //!< The outgoing history
const Fw::FilePacket::Type endPacketType, //!< The expected ending packet type
const size_t numPackets, //!< The expected number of packets
const CFDP::Checksum& checksum, //!< The expected checksum,
U32 startOffset //!< Starting byte offset
);
//! Validate a file packet buffer and convert it to a file packet
//!
static void validateFilePacket(
const Fw::Buffer& buffer, //!< The buffer
Fw::FilePacket& filePacket //!< The buffer as a FilePacket
);
//! Validate a start packet buffer
//!
static void validateStartPacket(
const Fw::Buffer& buffer //!< The buffer
);
//! Validate a data packet buffer, convert it to a data packet,
//! and update the byte offset
//!
static void validateDataPacket(
const Fw::Buffer& buffer, //!< The buffer
Fw::FilePacket::DataPacket& dataPacket, //!< The buffer as a data packet
const U32 sequenceIndex, //!< The expected sequence index
U32& byteOffset //!< The expected byte offset
);
//! Validate an end data packet buffer
//!
static void validateEndPacket(
const Fw::Buffer& buffer, //!< The buffer
const U32 sequenceIndex, //!< The expected sequence index
const CFDP::Checksum& checksum //!< The expected checksum
);
//! Validate a cancel packet buffer
//!
static void validateCancelPacket(
const Fw::Buffer& buffer, //!< The buffer
const U32 sequenceIndex //!< The expected sequence index
);
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
FileDownlink component;
// Allocated buffers storage
U8* buffers[1000];
//! Buffers index
//!
U32 buffers_index;
//! The current sequence index
//!
U32 sequenceIndex;
};
} // end namespace Svc
#endif
| hpp |
fprime | data/projects/fprime/Svc/FileDownlink/test/ut/FileDownlinkMain.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include "FileDownlinkTester.hpp"
TEST(FileDownlink, Downlink) {
Svc::FileDownlinkTester tester;
tester.downlink();
}
TEST(FileDownlink, FileOpenError) {
Svc::FileDownlinkTester tester;
tester.fileOpenError();
}
TEST(FileDownlink, CancelDownlink) {
Svc::FileDownlinkTester tester;
tester.cancelDownlink();
}
TEST(FileDownlink, CancelInIdleMode) {
Svc::FileDownlinkTester tester;
tester.cancelInIdleMode();
}
TEST(FileDownlink, DownlinkPartial) {
Svc::FileDownlinkTester tester;
tester.downlinkPartial();
}
TEST(FileDownlink, DownlinkTimeout) {
Svc::FileDownlinkTester tester;
tester.timeout();
}
TEST(FileDownlink, SendFilePort) {
Svc::FileDownlinkTester tester;
tester.sendFilePort();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/TestUtils/OnChangeChannel.hpp | // ======================================================================
// \title OnChangeChannel.hpp
// \author Rob Bocchino
// \brief A model of an on-change channel for testing
//
// \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 TestUtils_OnChangeChannel_HPP
#define TestUtils_OnChangeChannel_HPP
#include <cstring>
#include "TestUtils/Option.hpp"
#include "config/FpConfig.hpp"
namespace TestUtils {
//! The status of an on-change telemetry channel
enum class OnChangeStatus { CHANGED, NOT_CHANGED };
//! A model of an on-change telemetry channel
template <typename T>
class OnChangeChannel {
public:
//! Constructor
explicit OnChangeChannel(T value) : value(value) {}
//! Update the previous value
OnChangeStatus updatePrev() {
const auto status = ((!this->prev.hasValue()) || (this->value != this->prev.get()))
? OnChangeStatus::CHANGED
: OnChangeStatus::NOT_CHANGED;
this->prev.set(this->value);
return status;
}
public:
//! The current value
T value;
private:
//! The previous value
Option<T> prev;
};
} // namespace TestUtils
#endif
| hpp |
fprime | data/projects/fprime/TestUtils/Option.hpp | // ======================================================================
// \title Option.hpp
// \author Rob Bocchino
// \brief An option type for unit testing
//
// \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 TestUtils_Option_HPP
#define TestUtils_Option_HPP
namespace TestUtils {
//! An optional value
template <typename T, T noValue = T()>
class Option {
private:
enum class State { VALUE, NO_VALUE };
public:
explicit Option(T value) : state(State::VALUE), value(value) {}
Option() : state(State::NO_VALUE), value(noValue) {}
public:
static Option<T> some(T value) { return Option(value); }
static constexpr Option<T> none() { return Option(); }
public:
bool hasValue() const { return this->state == State::VALUE; }
void set(T value) {
this->state = State::VALUE;
this->value = value;
}
void clear() { this->state = State::NO_VALUE; }
T get() const {
FW_ASSERT(this->hasValue());
return this->value;
}
T getOrElse(T value) const {
T result = value;
if (this->hasValue()) {
result = this->value;
}
return result;
}
private:
State state;
T value;
};
} // namespace TestUtils
#endif
| hpp |
fprime | data/projects/fprime/Ref/Main.cpp | // ======================================================================
// \title Main.cpp
// \author mstarch
// \brief main program for reference application. Intended for CLI-based systems (Linux, macOS)
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
// Used to access topology functions
#include <Ref/Top/RefTopology.hpp>
// Used for signal handling shutdown
#include <signal.h>
// Used for command line argument processing
#include <getopt.h>
// Used for printf functions
#include <cstdlib>
/**
* \brief print commandline help message
*
* This will print a command line help message including the available command line arguments.
*
* @param app: name of application
*/
void print_usage(const char* app) {
(void)printf("Usage: ./%s [options]\n-a\thostname/IP address\n-p\tport_number\n", app);
}
/**
* \brief shutdown topology cycling on signal
*
* The reference topology allows for a simulated cycling of the rate groups. This simulated cycling needs to be stopped
* in order for the program to shutdown. This is done via handling signals such that it is performed via Ctrl-C
*
* @param signum
*/
static void signalHandler(int signum) {
Ref::stopSimulatedCycle();
}
/**
* \brief execute the program
*
* This F´ program is designed to run in standard environments (e.g. Linux/macOs running on a laptop). Thus it uses
* command line inputs to specify how to connect.
*
* @param argc: argument count supplied to program
* @param argv: argument values supplied to program
* @return: 0 on success, something else on failure
*/
int main(int argc, char* argv[]) {
U32 port_number = 0;
I32 option = 0;
char* hostname = nullptr;
// Loop while reading the getopt supplied options
while ((option = getopt(argc, argv, "hp:a:")) != -1) {
switch (option) {
// Handle the -a argument for address/hostname
case 'a':
hostname = optarg;
break;
// Handle the -p port number argument
case 'p':
port_number = static_cast<U32>(atoi(optarg));
break;
// Cascade intended: help output
case 'h':
// Cascade intended: help output
case '?':
// Default case: output help and exit
default:
print_usage(argv[0]);
return (option == 'h') ? 0 : 1;
}
}
// Object for communicating state to the reference topology
Ref::TopologyState inputs;
inputs.hostname = hostname;
inputs.port = port_number;
// Setup program shutdown via Ctrl-C
signal(SIGINT, signalHandler);
signal(SIGTERM, signalHandler);
(void)printf("Hit Ctrl-C to quit\n");
// Setup, cycle, and teardown topology
Ref::setupTopology(inputs);
Ref::startSimulatedCycle(1000); // Program loop cycling rate groups at 1Hz
Ref::teardownTopology(inputs);
(void)printf("Exiting...\n");
return 0;
}
| cpp |
fprime | data/projects/fprime/Ref/TypeDemo/TypeDemo.hpp | // ======================================================================
// \title TypeDemo.hpp
// \author mstarch
// \brief hpp file for TypeDemo component implementation class
// ======================================================================
#ifndef TypeDemo_HPP
#define TypeDemo_HPP
#include "Ref/TypeDemo/TypeDemoComponentAc.hpp"
namespace Ref {
class TypeDemo : public TypeDemoComponentBase {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object TypeDemo
//!
TypeDemo(const char* const compName //!< The component name
);
//! Initialize object TypeDemo
//!
void init(const NATIVE_INT_TYPE instance = 0 //!< The instance number
);
//! Destroy object TypeDemo
//!
~TypeDemo() = default;
PRIVATE:
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
//! Implementation for CHOICE command handler
//! Single choice command
void CHOICE_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
Ref::Choice choice);
//! Implementation for CHOICES command handler
//! Multiple choice command via Array
void CHOICES_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
Ref::ManyChoices choices);
//! Implementation for CHOICES_WITH_FRIENDS command handler
//! Multiple choice command via Array with a preceding and following argument
void CHOICES_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
U8 repeat,
Ref::ManyChoices choices,
U8 repeat_max);
//! Implementation for EXTRA_CHOICES command handler
//! Multiple choice command via Array
void EXTRA_CHOICES_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
Ref::TooManyChoices choices);
//! Implementation for EXTRA_CHOICES_WITH_FRIENDS command handler
//! Too many choices command via Array with a preceding and following argument
void EXTRA_CHOICES_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
U8 repeat,
Ref::TooManyChoices choices,
U8 repeat_max);
//! Implementation for CHOICE_PAIR command handler
//! Multiple choice command via Structure
void CHOICE_PAIR_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
Ref::ChoicePair choices);
//! Implementation for CHOICE_PAIR_WITH_FRIENDS command handler
//! Multiple choices command via Structure with a preceding and following argument
void CHOICE_PAIR_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
U8 repeat,
Ref::ChoicePair choices,
U8 repeat_max);
//! Implementation for GLUTTON_OF_CHOICE command handler
//! Multiple choice command via Complex Structure
void GLUTTON_OF_CHOICE_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
Ref::ChoiceSlurry choices //!< A phenomenal amount of choice
);
//! Implementation for GLUTTON_OF_CHOICE_WITH_FRIENDS command handler
//! Multiple choices command via Complex Structure with a preceding and following argument
void GLUTTON_OF_CHOICE_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq, //!< The command sequence number
U8 repeat, //!< Number of times to repeat the choices
Ref::ChoiceSlurry choices, //!< A phenomenal amount of choice
U8 repeat_max //!< Limit to the number of repetitions
);
//! Implementation for DUMP_TYPED_PARAMETERS command handler
//! Dump the typed parameters
void DUMP_TYPED_PARAMETERS_cmdHandler(const FwOpcodeType opCode, //!< The opcode
const U32 cmdSeq //!< The command sequence number
);
//! Implementation for DUMP_FLOATS command handler
//!
void DUMP_FLOATS_cmdHandler(const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq /*!< The command sequence number*/
);
//! Implementation for SEND_SCALARS command handler
//! Send scalars
void SEND_SCALARS_cmdHandler(const FwOpcodeType opCode, /*!< The opcode*/
const U32 cmdSeq, /*!< The command sequence number*/
Ref::ScalarStruct scalar_input);
};
} // end namespace Ref
#endif
| hpp |
fprime | data/projects/fprime/Ref/TypeDemo/TypeDemo.cpp | // ======================================================================
// \title TypeDemo.cpp
// \author mstarch
// \brief cpp file for TypeDemo component implementation class
// ======================================================================
#include <FpConfig.hpp>
#include <Ref/TypeDemo/TypeDemo.hpp>
#include <limits>
namespace Ref {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
TypeDemo ::TypeDemo(const char* const compName) : TypeDemoComponentBase(compName) {}
void TypeDemo ::init(const NATIVE_INT_TYPE instance) {
TypeDemoComponentBase::init(instance);
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void TypeDemo ::CHOICE_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq, Ref::Choice choice) {
this->tlmWrite_ChoiceCh(choice);
this->log_ACTIVITY_HI_ChoiceEv(choice);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::CHOICES_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq, Ref::ManyChoices choices) {
this->tlmWrite_ChoicesCh(choices);
this->log_ACTIVITY_HI_ChoicesEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::CHOICES_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode,
const U32 cmdSeq,
U8 repeat,
Ref::ManyChoices choices,
U8 repeat_max) {
for (U32 i = 0; (i < repeat) && (i < std::numeric_limits<U8>::max()) && (i < repeat_max); i++) {
this->tlmWrite_ChoicesCh(choices);
}
this->log_ACTIVITY_HI_ChoicesEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::EXTRA_CHOICES_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq, Ref::TooManyChoices choices) {
this->tlmWrite_ExtraChoicesCh(choices);
this->log_ACTIVITY_HI_ExtraChoicesEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::EXTRA_CHOICES_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode,
const U32 cmdSeq,
U8 repeat,
Ref::TooManyChoices choices,
U8 repeat_max) {
for (U32 i = 0; (i < repeat) && (i < std::numeric_limits<U8>::max()) && (i < repeat_max); i++) {
this->tlmWrite_ExtraChoicesCh(choices);
}
this->log_ACTIVITY_HI_ExtraChoicesEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::CHOICE_PAIR_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq, Ref::ChoicePair choices) {
this->tlmWrite_ChoicePairCh(choices);
this->log_ACTIVITY_HI_ChoicePairEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::CHOICE_PAIR_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode,
const U32 cmdSeq,
U8 repeat,
Ref::ChoicePair choices,
U8 repeat_max) {
for (U32 i = 0; (i < repeat) && (i < std::numeric_limits<U8>::max()) && (i < repeat_max); i++) {
this->tlmWrite_ChoicePairCh(choices);
}
this->log_ACTIVITY_HI_ChoicePairEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::GLUTTON_OF_CHOICE_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq, Ref::ChoiceSlurry choices) {
this->tlmWrite_ChoiceSlurryCh(choices);
this->log_ACTIVITY_HI_ChoiceSlurryEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::GLUTTON_OF_CHOICE_WITH_FRIENDS_cmdHandler(const FwOpcodeType opCode,
const U32 cmdSeq,
U8 repeat,
Ref::ChoiceSlurry choices,
U8 repeat_max) {
for (U32 i = 0; (i < repeat) && (i < std::numeric_limits<U8>::max()) && (i < repeat_max); i++) {
this->tlmWrite_ChoiceSlurryCh(choices);
}
this->log_ACTIVITY_HI_ChoiceSlurryEv(choices);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::DUMP_TYPED_PARAMETERS_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq) {
Fw::ParamValid validity;
Ref::Choice choice = this->paramGet_CHOICE_PRM(validity);
this->log_ACTIVITY_HI_ChoicePrmEv(choice, validity);
Ref::ManyChoices choices = this->paramGet_CHOICES_PRM(validity);
this->log_ACTIVITY_HI_ChoicesPrmEv(choices, validity);
Ref::TooManyChoices tooManyChoices = this->paramGet_EXTRA_CHOICES_PRM(validity);
this->log_ACTIVITY_HI_ExtraChoicesPrmEv(tooManyChoices, validity);
Ref::ChoicePair choicePair = this->paramGet_CHOICE_PAIR_PRM(validity);
this->log_ACTIVITY_HI_ChoicePairPrmEv(choicePair, validity);
Ref::ChoiceSlurry choiceSlurry = this->paramGet_GLUTTON_OF_CHOICE_PRM(validity);
this->log_ACTIVITY_HI_ChoiceSlurryPrmEv(choiceSlurry, validity);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::DUMP_FLOATS_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq) {
Ref::FloatSet invalid;
invalid[0] = std::numeric_limits<float>::infinity();
invalid[1] = -1 * std::numeric_limits<float>::infinity();
invalid[2] = (std::numeric_limits<float>::has_quiet_NaN) ? std::numeric_limits<float>::quiet_NaN() : 0.0f;
this->log_ACTIVITY_HI_FloatEv(invalid[0], invalid[1], invalid[2], invalid);
this->tlmWrite_Float1Ch(invalid[0]);
this->tlmWrite_Float2Ch(invalid[1]);
this->tlmWrite_Float3Ch(invalid[2]);
this->tlmWrite_FloatSet(invalid);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void TypeDemo ::SEND_SCALARS_cmdHandler(const FwOpcodeType opCode, const U32 cmdSeq, Ref::ScalarStruct scalar_input) {
this->log_ACTIVITY_HI_ScalarStructEv(scalar_input);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
} // end namespace Ref
| cpp |
fprime | data/projects/fprime/Ref/SignalGen/SignalGen.cpp | // ======================================================================
// \title SequenceFileLoader.cpp
// \author bocchino
// \brief cpp file for SequenceFileLoader component implementation class
//
// \copyright
// Copyright (C) 2009-2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/Types/Assert.hpp>
#include <Ref/SignalGen/SignalGen.hpp>
#include <cmath>
#include <cstdlib>
// TKC - don't know why it's undefined in VxWorks
#ifdef TGT_OS_TYPE_VXWORKS
#define M_PI (22.0/7.0)
#endif
namespace Ref {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
SignalGen ::
SignalGen(const char* name) :
SignalGenComponentBase(name),
sampleFrequency(25),
signalFrequency(1),
signalAmplitude(0.0f),
signalPhase(0.0f),
ticks(0),
sigType(SignalType::SINE),
sigHistory(),
sigPairHistory(),
running(false),
skipOne(false)
{}
void SignalGen ::
init(
const NATIVE_INT_TYPE queueDepth,
const NATIVE_INT_TYPE instance
)
{
SignalGenComponentBase::init(queueDepth, instance);
}
SignalGen :: ~SignalGen() { }
// ----------------------------------------------------------------------
// Handler implementations
// ----------------------------------------------------------------------
F32 SignalGen :: generateSample(U32 ticks) {
F32 val = 0.0f;
if (this->skipOne) {
return val;
}
// Samples per period
F32 samplesPerPeriod = static_cast<F32>(this->sampleFrequency)/static_cast<F32>(this->signalFrequency);
U32 halfSamplesPerPeriod = samplesPerPeriod/2;
/* Signals courtesy of the open source Aquila DSP Library */
switch(this->sigType.e) {
case SignalType::TRIANGLE:
{
F32 m = this->signalAmplitude / static_cast<F32>(halfSamplesPerPeriod);
val = m * static_cast<F32>(ticks % halfSamplesPerPeriod);
break;
}
case SignalType::SINE:
{
F32 normalizedFrequency = 1.0f / samplesPerPeriod;
val = this->signalAmplitude * std::sin((2.0 * M_PI * normalizedFrequency *
static_cast<F32>(ticks)) + (this->signalPhase * 2.0 * M_PI));
break;
}
case SignalType::SQUARE:
{
val = this->signalAmplitude * ((ticks % static_cast<U32>(samplesPerPeriod) < halfSamplesPerPeriod) ? 1.0f : -1.0f);
break;
}
case SignalType::NOISE:
{
val = this->signalAmplitude * (std::rand() / static_cast<double>(RAND_MAX));
break;
}
default:
FW_ASSERT(0); // Should never happen
}
return val;
}
void SignalGen :: schedIn_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!< The call order*/
)
{
F32 value = 0.0f;
// This is a queued component, so it must intentionally run the dispatch of commands and queue processing on this
// synchronous scheduled call
this->doDispatch();
// This short-circuits when the signal generator is not running
if (not this->running) {
return;
}
// Allows for skipping a single reading of the signal
if (not this->skipOne) {
value = this->generateSample(this->ticks);
}
this->skipOne = false;
// Build our new types
SignalPair pair = SignalPair(this->ticks, value);
// Shift and assign our array types
for (U32 i = 1; i < this->sigHistory.SIZE; i++) {
this->sigHistory[i - 1] = this->sigHistory[i];
this->sigPairHistory[i - 1] = this->sigPairHistory[i];
}
this->sigHistory[this->sigHistory.SIZE - 1] = value;
this->sigPairHistory[this->sigPairHistory.SIZE - 1] = pair;
// Composite structure
SignalInfo sigInfo(this->sigType, this->sigHistory, this->sigPairHistory);
// Write all signals
this->tlmWrite_Type(this->sigType);
this->tlmWrite_Output(value);
this->tlmWrite_PairOutput(pair);
this->tlmWrite_History(this->sigHistory);
this->tlmWrite_PairHistory(this->sigPairHistory);
this->tlmWrite_Info(sigInfo);
this->ticks += 1;
}
void SignalGen :: SignalGen_Settings_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq, /*!< The command sequence number*/
U32 Frequency,
F32 Amplitude,
F32 Phase,
Ref::SignalType SigType
)
{
this->signalFrequency = Frequency;
this->signalAmplitude = Amplitude;
this->signalPhase = Phase;
this->sigType = SigType;
// When the settings change, reset the history values
for (U32 i = 0; i < SignalSet::SIZE; i++) {
this->sigHistory[i] = 0.0f;
}
for (U32 i = 0; i < SignalPairSet::SIZE; i++) {
this->sigPairHistory[i].settime(0.0f);
this->sigPairHistory[i].setvalue(0.0f);
}
this->log_ACTIVITY_LO_SignalGen_SettingsChanged(this->signalFrequency, this->signalAmplitude, this->signalPhase, this->sigType);
this->tlmWrite_Type(SigType);
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void SignalGen :: SignalGen_Toggle_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
)
{
this->running = !this->running;
this->ticks = 0;
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
void SignalGen :: SignalGen_Skip_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
)
{
this->skipOne = true;
this->cmdResponse_out(opCode, cmdSeq, Fw::CmdResponse::OK);
}
};
| cpp |
fprime | data/projects/fprime/Ref/SignalGen/SignalGen.hpp | // ======================================================================
// \title SignalGen.hpp
// \author bocchino
// \brief hpp file for SequenceFileLoader component implementation class
//
// \copyright
// Copyright (C) 2009-2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Svc_SignalGen_HPP
#define Svc_SignalGen_HPP
#include <Fw/Types/ByteArray.hpp>
#include <Fw/Types/ConstByteArray.hpp>
#include <Os/File.hpp>
#include <Os/ValidateFile.hpp>
#include <Ref/SignalGen/SignalGenComponentAc.hpp>
#include <cmath>
namespace Ref {
class SignalGen :
public SignalGenComponentBase
{
private:
void schedIn_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 context /*!< The call order*/
);
void SignalGen_Settings_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq, /*!< The command sequence number*/
U32 Frequency,
F32 Amplitude,
F32 Phase,
Ref::SignalType SigType
);
void SignalGen_Toggle_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
);
void SignalGen_Skip_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
);
void SignalGen_GenerateArray_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
);
public:
//! Construct a SignalGen
SignalGen(
const char* compName //!< The component name
);
//! Initialize a SignalGen
void init(
const NATIVE_INT_TYPE queueDepth, //!< The queue depth
const NATIVE_INT_TYPE instance //!< The instance number
);
//! Destroy a SignalGen
~SignalGen();
private:
// Generate the next sample internal helper
F32 generateSample(U32 ticks);
// Member variables
U32 sampleFrequency;
U32 signalFrequency;
F32 signalAmplitude;
F32 signalPhase;
U32 ticks;
SignalType sigType;
SignalSet sigHistory;
SignalPairSet sigPairHistory;
bool running;
bool skipOne;
};
};
#endif
| hpp |
fprime | data/projects/fprime/Ref/SignalGen/test/ut/SignalGenTester.cpp | // ======================================================================
// \title SignalGen.hpp
// \author mstarch
// \brief cpp file for SignalGen test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "SignalGenTester.hpp"
namespace Ref {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
SignalGenTester ::
SignalGenTester() :
SignalGenGTestBase("Tester", MAX_HISTORY_SIZE),
component("SignalGen")
{
this->initComponents();
this->connectPorts();
}
SignalGenTester ::
~SignalGenTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void SignalGenTester ::
test_start()
{
ASSERT_TLM_Output_SIZE(0);
sendCmd_SignalGen_Toggle(0, 0);
component.doDispatch();
invoke_to_schedIn(0, 0);
component.doDispatch();
ASSERT_TLM_Output_SIZE(1);
}
} // end namespace Ref
| cpp |
fprime | data/projects/fprime/Ref/SignalGen/test/ut/SignalGenTester.hpp | // ======================================================================
// \title SignalGen/test/ut/Tester.hpp
// \author mstarch
// \brief hpp file for SignalGen 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 "SignalGenGTestBase.hpp"
#include "Ref/SignalGen/SignalGen.hpp"
namespace Ref {
class SignalGenTester :
public SignalGenGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// 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 SignalGenTester
//!
SignalGenTester();
//! Destroy object SignalGenTester
//!
~SignalGenTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! To do
//!
void test_start();
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
SignalGen component;
};
} // end namespace Ref
#endif
| hpp |
fprime | data/projects/fprime/Ref/SignalGen/test/ut/SignalGenTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "SignalGenTester.hpp"
TEST(Nominal, TestStart) {
Ref::SignalGenTester tester;
tester.test_start();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Ref/PingReceiver/PingReceiverComponentImpl.cpp | // ======================================================================
// \title PingReceiverImpl.cpp
// \author tim
// \brief cpp file for PingReceiver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Ref/PingReceiver/PingReceiverComponentImpl.hpp>
#include <FpConfig.hpp>
namespace Ref {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
PingReceiverComponentImpl ::
PingReceiverComponentImpl(
const char *const compName
) : PingReceiverComponentBase(compName), m_inhibitPings(false), m_pingsRecvd(0)
{
}
void PingReceiverComponentImpl ::
init(
const NATIVE_INT_TYPE queueDepth,
const NATIVE_INT_TYPE instance
)
{
PingReceiverComponentBase::init(queueDepth, instance);
}
PingReceiverComponentImpl ::
~PingReceiverComponentImpl()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void PingReceiverComponentImpl ::
PingIn_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
//this->log_DIAGNOSTIC_PR_PingReceived(key);
this->tlmWrite_PR_NumPings(this->m_pingsRecvd++);
if (not this->m_inhibitPings) {
PingOut_out(0,key);
}
}
void PingReceiverComponentImpl::PR_StopPings_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
) {
this->m_inhibitPings = true;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
} // end namespace Ref
| cpp |
fprime | data/projects/fprime/Ref/PingReceiver/PingReceiver.hpp | // ======================================================================
// PingReceiver.hpp
// Standardization header for PingReceiver
// ======================================================================
#ifndef Ref_PingReceiver_HPP
#define Ref_PingReceiver_HPP
#include "Ref/PingReceiver/PingReceiverComponentImpl.hpp"
namespace Ref {
typedef PingReceiverComponentImpl PingReceiver;
}
#endif
| hpp |
fprime | data/projects/fprime/Ref/PingReceiver/PingReceiverComponentImpl.hpp | // ======================================================================
// \title PingReceiverImpl.hpp
// \author tim
// \brief hpp file for PingReceiver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef PingReceiver_HPP
#define PingReceiver_HPP
#include "Ref/PingReceiver/PingReceiverComponentAc.hpp"
namespace Ref {
class PingReceiverComponentImpl :
public PingReceiverComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object PingReceiver
//!
PingReceiverComponentImpl(
const char *const compName /*!< The component name*/
);
//! Initialize object PingReceiver
//!
void init(
const NATIVE_INT_TYPE queueDepth, /*!< The queue depth*/
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object PingReceiver
//!
~PingReceiverComponentImpl();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for PingIn
//!
void PingIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 key /*!< Value to return to pinger*/
);
void PR_StopPings_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq /*!< The command sequence number*/
);
bool m_inhibitPings;
U32 m_pingsRecvd;
};
} // end namespace Ref
#endif
| hpp |
fprime | data/projects/fprime/Ref/SendBuffApp/SendBuffComponentImpl.cpp | #include <Ref/SendBuffApp/SendBuffComponentImpl.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/Log.hpp>
#include <cstring>
#include <cstdio>
#define DEBUG_LEVEL 1
namespace Ref {
SendBuffImpl::SendBuffImpl(const char* compName) :
SendBuffComponentBase(compName) {
this->m_currPacketId = 0;
this->m_invocations = 0;
this->m_buffsSent = 0;
this->m_errorsInjected = 0;
this->m_injectError = false;
this->m_sendPackets = false;
this->m_currPacketId = 0;
this->m_firstPacketSent = false;
this->m_state = SendBuff_ActiveState::SEND_IDLE;
}
SendBuffImpl::~SendBuffImpl() {
}
void SendBuffImpl::init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance) {
SendBuffComponentBase::init(queueDepth,instance);
}
void SendBuffImpl::SchedIn_handler(NATIVE_INT_TYPE portNum, U32 context) {
// first, dequeue any messages
MsgDispatchStatus stat = MSG_DISPATCH_OK;
while (MSG_DISPATCH_OK == stat) {
stat = this->doDispatch();
FW_ASSERT(stat != MSG_DISPATCH_ERROR);
}
if (this->m_sendPackets) {
// check to see if first
if (this->m_firstPacketSent) {
this->m_firstPacketSent = false;
this->log_ACTIVITY_HI_FirstPacketSent(this->m_currPacketId);
this->tlmWrite_NumErrorsInjected(this->m_errorsInjected);
}
// reset buffer
this->m_testBuff.resetSer();
// serialize packet id
Fw::SerializeStatus serStat = this->m_testBuff.serialize(this->m_currPacketId);
FW_ASSERT(serStat == Fw::FW_SERIALIZE_OK);
// increment packet id
this->m_currPacketId++;
this->m_buffsSent++;
// set telemetry
this->tlmWrite_PacketsSent(this->m_buffsSent);
// write data
U8 testData[24];
NATIVE_UINT_TYPE dataSize = sizeof(testData);
memset(testData,0xFF,dataSize);
// compute checksum
U32 csum = 0;
for (U32 byte = 0; byte < dataSize; byte++) {
csum += testData[byte];
}
// inject error, if requested
if (this->m_injectError) {
this->m_injectError = false;
this->m_errorsInjected++;
testData[5] = 0;
this->log_WARNING_HI_PacketErrorInserted(this->m_currPacketId-1);
}
// serialize data
serStat = this->m_testBuff.serialize(testData,dataSize);
FW_ASSERT(serStat == Fw::FW_SERIALIZE_OK);
// serialize checksum
serStat = this->m_testBuff.serialize(csum);
FW_ASSERT(serStat == Fw::FW_SERIALIZE_OK);
// send data
this->Data_out(0,this->m_testBuff);
}
this->m_invocations++;
this->tlmWrite_SendState(this->m_state);
}
void SendBuffImpl::toString(char* str, I32 buffer_size) {
#if FW_OBJECT_NAMES == 1
(void) snprintf(str, buffer_size, "Send Buff Component: %s: count: %d Buffs: %d", this->m_objName.toChar(),
(int) this->m_invocations, (int) this->m_buffsSent);
str[buffer_size-1] = 0;
#else
(void) snprintf(str, buffer_size, "Lps Atm Component: count: %d ATMs: %d",
(int) this->m_invocations, (int) this->m_buffsSent);
#endif
}
void SendBuffImpl::SB_START_PKTS_cmdHandler(FwOpcodeType opCode, U32 cmdSeq) {
this->m_sendPackets = true;
this->m_state = SendBuff_ActiveState::SEND_ACTIVE;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void SendBuffImpl::SB_INJECT_PKT_ERROR_cmdHandler(FwOpcodeType opCode, U32 cmdSeq) {
this->m_injectError = true;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void SendBuffImpl::SB_GEN_FATAL_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq, /*!< The command sequence number*/
U32 arg1, /*!< First FATAL Argument*/
U32 arg2, /*!< Second FATAL Argument*/
U32 arg3 /*!< Third FATAL Argument*/
) {
this->log_FATAL_SendBuffFatal(arg1,arg2,arg3);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
//! Handler for command SB_GEN_ASSERT
/* Generate an ASSERT */
void SendBuffImpl::SB_GEN_ASSERT_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq, /*!< The command sequence number*/
U32 arg1, /*!< First ASSERT Argument*/
U32 arg2, /*!< Second ASSERT Argument*/
U32 arg3, /*!< Third ASSERT Argument*/
U32 arg4, /*!< Fourth ASSERT Argument*/
U32 arg5, /*!< Fifth ASSERT Argument*/
U32 arg6 /*!< Sixth ASSERT Argument*/
) {
FW_ASSERT(0,arg1,arg2,arg3,arg4,arg5,arg6);
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void SendBuffImpl::parameterUpdated(FwPrmIdType id) {
this->log_ACTIVITY_LO_BuffSendParameterUpdated(id);
Fw::ParamValid valid;
switch(id) {
case PARAMID_PARAMETER3: {
U8 val = this->paramGet_parameter3(valid);
this->tlmWrite_Parameter3(val);
break;
}
case PARAMID_PARAMETER4: {
F32 val = this->paramGet_parameter4(valid);
this->tlmWrite_Parameter4(val);
break;
}
default:
FW_ASSERT(0,id);
break;
}
}
}
| cpp |
fprime | data/projects/fprime/Ref/SendBuffApp/SendBuffComponentImpl.hpp | #ifndef REF_LPS_ATM_IMPL_HPP
#define REF_LPS_ATM_IMPL_HPP
#include <Ref/SendBuffApp/SendBuffComponentAc.hpp>
namespace Ref {
/// This component sends a data buffer to a driver each time it is invoked by a scheduler
class SendBuffImpl : public SendBuffComponentBase {
public:
// Only called by derived class
SendBuffImpl(const char* compName); //!< constructor
void init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance = 0); //!< initialization function
~SendBuffImpl(); //!< destructor
private:
void SchedIn_handler(NATIVE_INT_TYPE portNum, U32 context); //!< downcall for input port
void SB_START_PKTS_cmdHandler(FwOpcodeType opcode, U32 cmdSeq); //!< START_PKTS command handler
void SB_INJECT_PKT_ERROR_cmdHandler(FwOpcodeType opcode, U32 cmdSeq); //!< START_PKTS command handler
void SB_GEN_FATAL_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq, /*!< The command sequence number*/
U32 arg1, /*!< First FATAL Argument*/
U32 arg2, /*!< Second FATAL Argument*/
U32 arg3 /*!< Third FATAL Argument*/
);
//! Handler for command SB_GEN_ASSERT
/* Generate an ASSERT */
void SB_GEN_ASSERT_cmdHandler(
FwOpcodeType opCode, /*!< The opcode*/
U32 cmdSeq, /*!< The command sequence number*/
U32 arg1, /*!< First ASSERT Argument*/
U32 arg2, /*!< Second ASSERT Argument*/
U32 arg3, /*!< Third ASSERT Argument*/
U32 arg4, /*!< Fourth ASSERT Argument*/
U32 arg5, /*!< Fifth ASSERT Argument*/
U32 arg6 /*!< Sixth ASSERT Argument*/
);
U32 m_invocations; //!< number of times component has been called by the scheduler
U32 m_buffsSent; //!< number of buffers sent
U32 m_errorsInjected; //!< number of errors injected
bool m_injectError; //!< flag to inject error on next packet
bool m_sendPackets; //!< If true, send packets
U32 m_currPacketId; //!< current packet ID to be sent
bool m_firstPacketSent; //!< set if first packet
void toString(char* str, I32 buffer_size); //!< writes a string representation of the object
// buffer data
Drv::DataBuffer m_testBuff; //!< data buffer to send
// parameter update notification
void parameterUpdated(FwPrmIdType id); //!< Notification function for changed parameters
// send state
SendBuff_ActiveState m_state;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Ref/SendBuffApp/SendBuff.hpp | // ======================================================================
// SendBuff.hpp
// Standardization header for SendBuff
// ======================================================================
#ifndef Ref_SendBuff_HPP
#define Ref_SendBuff_HPP
#include "Ref/SendBuffApp/SendBuffComponentImpl.hpp"
namespace Ref {
typedef SendBuffImpl SendBuff;
}
#endif
| hpp |
fprime | data/projects/fprime/Ref/Top/RefTopology.hpp | // ======================================================================
// \title Topology.hpp
// \author mstarch
// \brief header file containing the topology instantiation definitions
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef REF_REFTOPOLOGY_HPP
#define REF_REFTOPOLOGY_HPP
// Included for access to Ref::TopologyState and Ref::ConfigObjects::pingEntries. These definitions are required by the
// autocoder, but are also used in this hand-coded topology.
#include <Ref/Top/RefTopologyDefs.hpp>
// Remove unnecessary Ref:: qualifications
using namespace Ref;
namespace Ref {
/**
* \brief initialize and run the F´ topology
*
* Initializes, configures, and runs the F´ topology. This is performed through a series of steps, some provided via
* autocoded functions, and others provided via the functions implementation. These steps are:
*
* 1. Call the autocoded `initComponents()` function initializing each component via the `component.init` method
* 2. Call the autocoded `setBaseIds()` function to set the base IDs (offset) for each component instance
* 3. Call the autocoded `connectComponents()` function to wire-together the topology of components
* 4. Configure components requiring custom configuration
* 5. Call the autocoded `loadParameters()` function to cause each component to load initial parameter values
* 6. Call the autocoded `startTasks()` function to start the active component tasks
* 7. Start tasks not owned by active components
*
* Step 4 and step 7 are custom and supplied by the project. The ordering of steps 1, 2, 3, 5, and 6 are critical for
* F´ topologies to function. Configuration (step 4) typically assumes a connect but not started topology and is thus
* inserted between step 3 and 5. Step 7 may come before or after the active component initializations. Since these
* custom tasks often start radio communication it is convenient to start them last.
*
* The state argument carries command line inputs used to setup the topology. For an explanation of the required type
* Ref::TopologyState see: RefTopologyDefs.hpp.
*
* \param state: object shuttling CLI arguments (hostname, port) needed to construct the topology
*/
void setupTopology(const TopologyState& state);
/**
* \brief teardown the F´ topology
*
* Tears down the F´ topology in preparation for shutdown. This is done via a series of steps, some provided by
* autocoded functions, and others provided via the function implementation. These steps are:
*
* 1. Call the autocoded `stopTasks()` function to stop the tasks started by `startTasks()` (active components)
* 2. Call the autocoded `freeThreads()` function to join to the tasks started by `startTasks()`
* 3. Stop the tasks not owned by active components
* 4. Join to the tasks not owned by active components
* 5. Deallocate other resources
*
* Step 1, 2, 3, and 4 must occur in-order as the tasks must be stopped before being joined. These tasks must be stopped
* and joined before any active resources may be deallocated.
*
* For an explanation of the required type Ref::TopologyState see: RefTopologyDefs.hpp.
*
* \param state: state object provided to setupTopology
*/
void teardownTopology(const TopologyState& state);
/**
* \brief cycle the rate group driver at a crude rate
*
* The reference topology does not have a true 1Hz input clock for the rate group driver because it is designed to
* operate across various computing endpoints (e.g. laptops) where a clear 1Hz source may not be easily and generically
* achieved. This function mimics the cycling via a Task::delay(milliseconds) loop that manually invokes the ISR call
* to the example block driver.
*
* This loop is stopped via a startSimulatedCycle call.
*
* Note: projects should replace this with a component that produces an output port call at the appropriate frequency.
*
* \param milliseconds: milliseconds to delay for each cycle. Default: 1000 or 1Hz.
*/
void startSimulatedCycle(U32 milliseconds = 1000);
/**
* \brief stop the simulated cycle started by startSimulatedCycle
*
* This stops the cycle started by startSimulatedCycle.
*/
void stopSimulatedCycle();
} // namespace Ref
#endif
| hpp |
fprime | data/projects/fprime/Ref/Top/RefTopologyDefs.hpp | // ======================================================================
// \title RefTopologyDefs.hpp
// \author mstarch
// \brief required header file containing the required definitions for the topology autocoder
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef REF_REFTOPOLOGYDEFS_HPP
#define REF_REFTOPOLOGYDEFS_HPP
#include "Drv/BlockDriver/BlockDriver.hpp"
#include "Fw/Types/MallocAllocator.hpp"
#include "Ref/Top/FppConstantsAc.hpp"
#include "Svc/FramingProtocol/FprimeProtocol.hpp"
#include "Svc/Health/Health.hpp"
// Definitions are placed within a namespace named after the deployment
namespace Ref {
/**
* \brief required type definition to carry state
*
* The topology autocoder requires an object that carries state with the name `Ref::TopologyState`. Only the type
* definition is required by the autocoder and the contents of this object are otherwise opaque to the autocoder. The
* contents are entirely up to the definition of the project. This reference application specifies hostname and port
* fields, which are derived by command line inputs.
*/
struct TopologyState {
const char* hostname;
U32 port;
};
/**
* \brief required ping constants
*
* The topology autocoder requires a WARN and FATAL constant definition for each component that supports the health-ping
* interface. These are expressed as enum constants placed in a namespace named for the component instance. These
* are all placed in the PingEntries namespace.
*
* Each constant specifies how many missed pings are allowed before a WARNING_HI/FATAL event is triggered. In the
* following example, the health component will emit a WARNING_HI event if the component instance cmdDisp does not
* respond for 3 pings and will FATAL if responses are not received after a total of 5 pings.
*
* ```c++
* namespace PingEntries {
* namespace cmdDisp {
* enum { WARN = 3, FATAL = 5 };
* }
* }
* ```
*/
namespace PingEntries {
namespace blockDrv {
enum { WARN = 3, FATAL = 5 };
}
namespace tlmSend {
enum { WARN = 3, FATAL = 5 };
}
namespace cmdDisp {
enum { WARN = 3, FATAL = 5 };
}
namespace cmdSeq {
enum { WARN = 3, FATAL = 5 };
}
namespace eventLogger {
enum { WARN = 3, FATAL = 5 };
}
namespace fileDownlink {
enum { WARN = 3, FATAL = 5 };
}
namespace fileManager {
enum { WARN = 3, FATAL = 5 };
}
namespace fileUplink {
enum { WARN = 3, FATAL = 5 };
}
namespace pingRcvr {
enum { WARN = 3, FATAL = 5 };
}
namespace prmDb {
enum { WARN = 3, FATAL = 5 };
}
namespace rateGroup1Comp {
enum { WARN = 3, FATAL = 5 };
}
namespace rateGroup2Comp {
enum { WARN = 3, FATAL = 5 };
}
namespace rateGroup3Comp {
enum { WARN = 3, FATAL = 5 };
}
} // namespace PingEntries
} // namespace Ref
#endif
| hpp |
fprime | data/projects/fprime/Ref/Top/RefTopology.cpp | // ======================================================================
// \title Topology.cpp
// \author mstarch
// \brief cpp file containing the topology instantiation code
//
// \copyright
// Copyright 2009-2022, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
// Provides access to autocoded functions
#include <Ref/Top/RefTopologyAc.hpp>
#include <Ref/Top/RefPacketsAc.hpp>
// Necessary project-specified types
#include <Fw/Types/MallocAllocator.hpp>
#include <Os/Log.hpp>
#include <Svc/FramingProtocol/FprimeProtocol.hpp>
// Used for 1Hz synthetic cycling
#include <Os/Mutex.hpp>
// Allows easy reference to objects in FPP/autocoder required namespaces
using namespace Ref;
// Instantiate a system logger that will handle Fw::Logger::logMsg calls
Os::Log logger;
// The reference topology uses a malloc-based allocator for components that need to allocate memory during the
// initialization phase.
Fw::MallocAllocator mallocator;
// The reference topology uses the F´ packet protocol when communicating with the ground and therefore uses the F´
// framing and deframing implementations.
Svc::FprimeFraming framing;
Svc::FprimeDeframing deframing;
// The reference topology divides the incoming clock signal (1Hz) into sub-signals: 1Hz, 1/2Hz, and 1/4Hz and
// zero offset for all the dividers
Svc::RateGroupDriver::DividerSet rateGroupDivisorsSet{{{1, 0}, {2, 0}, {4, 0}}};
// Rate groups may supply a context token to each of the attached children whose purpose is set by the project. The
// reference topology sets each token to zero as these contexts are unused in this project.
NATIVE_INT_TYPE rateGroup1Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = {};
NATIVE_INT_TYPE rateGroup2Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = {};
NATIVE_INT_TYPE rateGroup3Context[Svc::ActiveRateGroup::CONNECTION_COUNT_MAX] = {};
// A number of constants are needed for construction of the topology. These are specified here.
enum TopologyConstants {
CMD_SEQ_BUFFER_SIZE = 5 * 1024,
FILE_DOWNLINK_TIMEOUT = 1000,
FILE_DOWNLINK_COOLDOWN = 1000,
FILE_DOWNLINK_CYCLE_TIME = 1000,
FILE_DOWNLINK_FILE_QUEUE_DEPTH = 10,
HEALTH_WATCHDOG_CODE = 0x123,
COMM_PRIORITY = 100,
UPLINK_BUFFER_MANAGER_STORE_SIZE = 3000,
UPLINK_BUFFER_MANAGER_QUEUE_SIZE = 30,
UPLINK_BUFFER_MANAGER_ID = 200
};
// Ping entries are autocoded, however; this code is not properly exported. Thus, it is copied here.
Svc::Health::PingEntry pingEntries[] = {
{PingEntries::blockDrv::WARN, PingEntries::blockDrv::FATAL, "blockDrv"},
{PingEntries::tlmSend::WARN, PingEntries::tlmSend::FATAL, "chanTlm"},
{PingEntries::cmdDisp::WARN, PingEntries::cmdDisp::FATAL, "cmdDisp"},
{PingEntries::cmdSeq::WARN, PingEntries::cmdSeq::FATAL, "cmdSeq"},
{PingEntries::eventLogger::WARN, PingEntries::eventLogger::FATAL, "eventLogger"},
{PingEntries::fileDownlink::WARN, PingEntries::fileDownlink::FATAL, "fileDownlink"},
{PingEntries::fileManager::WARN, PingEntries::fileManager::FATAL, "fileManager"},
{PingEntries::fileUplink::WARN, PingEntries::fileUplink::FATAL, "fileUplink"},
{PingEntries::pingRcvr::WARN, PingEntries::pingRcvr::FATAL, "pingRcvr"},
{PingEntries::prmDb::WARN, PingEntries::prmDb::FATAL, "prmDb"},
{PingEntries::rateGroup1Comp::WARN, PingEntries::rateGroup1Comp::FATAL, "rateGroup1Comp"},
{PingEntries::rateGroup2Comp::WARN, PingEntries::rateGroup2Comp::FATAL, "rateGroup2Comp"},
{PingEntries::rateGroup3Comp::WARN, PingEntries::rateGroup3Comp::FATAL, "rateGroup3Comp"},
};
/**
* \brief configure/setup components in project-specific way
*
* This is a *helper* function which configures/sets up each component requiring project specific input. This includes
* allocating resources, passing-in arguments, etc. This function may be inlined into the topology setup function if
* desired, but is extracted here for clarity.
*/
void configureTopology() {
// Command sequencer needs to allocate memory to hold contents of command sequences
cmdSeq.allocateBuffer(0, mallocator, CMD_SEQ_BUFFER_SIZE);
// Rate group driver needs a divisor list
rateGroupDriverComp.configure(rateGroupDivisorsSet);
// Rate groups require context arrays. Empty for Reference example.
rateGroup1Comp.configure(rateGroup1Context, FW_NUM_ARRAY_ELEMENTS(rateGroup1Context));
rateGroup2Comp.configure(rateGroup2Context, FW_NUM_ARRAY_ELEMENTS(rateGroup2Context));
rateGroup3Comp.configure(rateGroup3Context, FW_NUM_ARRAY_ELEMENTS(rateGroup3Context));
// File downlink requires some project-derived properties.
fileDownlink.configure(FILE_DOWNLINK_TIMEOUT, FILE_DOWNLINK_COOLDOWN, FILE_DOWNLINK_CYCLE_TIME,
FILE_DOWNLINK_FILE_QUEUE_DEPTH);
// Parameter database is configured with a database file name, and that file must be initially read.
prmDb.configure("PrmDb.dat");
prmDb.readParamFile();
// Health is supplied a set of ping entires.
health.setPingEntries(pingEntries, FW_NUM_ARRAY_ELEMENTS(pingEntries), HEALTH_WATCHDOG_CODE);
// Buffer managers need a configured set of buckets and an allocator used to allocate memory for those buckets.
Svc::BufferManager::BufferBins upBuffMgrBins;
memset(&upBuffMgrBins, 0, sizeof(upBuffMgrBins));
upBuffMgrBins.bins[0].bufferSize = UPLINK_BUFFER_MANAGER_STORE_SIZE;
upBuffMgrBins.bins[0].numBuffers = UPLINK_BUFFER_MANAGER_QUEUE_SIZE;
fileUplinkBufferManager.setup(UPLINK_BUFFER_MANAGER_ID, 0, mallocator, upBuffMgrBins);
// Framer and Deframer components need to be passed a protocol handler
downlink.setup(framing);
uplink.setup(deframing);
// Note: Uncomment when using Svc:TlmPacketizer
//tlmSend.setPacketList(RefPacketsPkts, RefPacketsIgnore, 1);
}
// Public functions for use in main program are namespaced with deployment name Ref
namespace Ref {
void setupTopology(const TopologyState& state) {
// Autocoded initialization. Function provided by autocoder.
initComponents(state);
// Autocoded id setup. Function provided by autocoder.
setBaseIds();
// Autocoded connection wiring. Function provided by autocoder.
connectComponents();
// Autocoded command registration. Function provided by autocoder.
regCommands();
// Project-specific component configuration. Function provided above. May be inlined, if desired.
configureTopology();
// Autocoded parameter loading. Function provided by autocoder.
loadParameters();
// Autocoded task kick-off (active components). Function provided by autocoder.
startTasks(state);
// Initialize socket client communication if and only if there is a valid specification
if (state.hostname != nullptr && state.port != 0) {
Os::TaskString name("ReceiveTask");
// Uplink is configured for receive so a socket task is started
comm.configure(state.hostname, state.port);
comm.startSocketTask(name, true, COMM_PRIORITY, Default::STACK_SIZE);
}
}
// Variables used for cycle simulation
Os::Mutex cycleLock;
volatile bool cycleFlag = true;
void startSimulatedCycle(U32 milliseconds) {
cycleLock.lock();
bool cycling = cycleFlag;
cycleLock.unLock();
// Main loop
while (cycling) {
Ref::blockDrv.callIsr();
Os::Task::delay(milliseconds);
cycleLock.lock();
cycling = cycleFlag;
cycleLock.unLock();
}
}
void stopSimulatedCycle() {
cycleLock.lock();
cycleFlag = false;
cycleLock.unLock();
}
void teardownTopology(const TopologyState& state) {
// Autocoded (active component) task clean-up. Functions provided by topology autocoder.
stopTasks(state);
freeThreads(state);
// Other task clean-up.
comm.stopSocketTask();
(void)comm.joinSocketTask(nullptr);
// Resource deallocation
cmdSeq.deallocateBuffer(mallocator);
fileUplinkBufferManager.cleanup();
}
}; // namespace Ref
| cpp |
fprime | data/projects/fprime/Ref/RecvBuffApp/RecvBuffComponentImpl.hpp | #ifndef REF_LPR_ATM_IMPL_HPP
#define REF_LPR_ATM_IMPL_HPP
#include <Ref/RecvBuffApp/RecvBuffComponentAc.hpp>
namespace Ref {
class RecvBuffImpl : public RecvBuffComponentBase {
public:
// Only called by derived class
RecvBuffImpl(const char* compName);
void init(NATIVE_INT_TYPE instanceId = 0);
~RecvBuffImpl();
private:
// downcall for input port
void Data_handler(NATIVE_INT_TYPE portNum, Drv::DataBuffer &buff);
Ref::PacketStat m_stats;
U32 m_buffsReceived; // !< number of buffers received
bool m_firstBuffReceived; // !< first buffer received or not
U32 m_errBuffs; // !< number of buffers with errors received
F32 m_sensor1;
F32 m_sensor2;
void toString(char* str, I32 buffer_size);
// parameter update notification
void parameterUpdated(FwPrmIdType id);
};
}
#endif
| hpp |
fprime | data/projects/fprime/Ref/RecvBuffApp/RecvBuffComponentImpl.cpp | #include <Ref/RecvBuffApp/RecvBuffComponentImpl.hpp>
#include <FpConfig.hpp>
#include <Os/Log.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#define DEBUG_LVL 1
namespace Ref {
RecvBuffImpl::RecvBuffImpl(const char* compName) :
RecvBuffComponentBase(compName) {
this->m_firstBuffReceived = 0;
this->m_sensor1 = 1000.0;
this->m_sensor2 = 10.0;
this->m_stats.setBuffRecv(0);
this->m_stats.setBuffErr(0);
this->m_stats.setPacketStatus(PacketRecvStatus::PACKET_STATE_NO_PACKETS);
}
void RecvBuffImpl::init(NATIVE_INT_TYPE instanceId) {
RecvBuffComponentBase::init(instanceId);
}
RecvBuffImpl::~RecvBuffImpl() {
}
void RecvBuffImpl::Data_handler(NATIVE_INT_TYPE portNum, Drv::DataBuffer &buff) {
this->m_stats.setBuffRecv(++this->m_buffsReceived);
// reset deserialization of buffer
buff.resetDeser();
// deserialize packet ID
U32 id = 0;
Fw::SerializeStatus stat = buff.deserialize(id);
FW_ASSERT(stat == Fw::FW_SERIALIZE_OK,static_cast<NATIVE_INT_TYPE>(stat));
// deserialize data
U8 testData[24] = {0};
NATIVE_UINT_TYPE size = sizeof(testData);
stat = buff.deserialize(testData,size);
FW_ASSERT(stat == Fw::FW_SERIALIZE_OK,static_cast<NATIVE_INT_TYPE>(stat));
// deserialize checksum
U32 csum = 0;
stat = buff.deserialize(csum);
FW_ASSERT(stat == Fw::FW_SERIALIZE_OK,static_cast<NATIVE_INT_TYPE>(stat));
// if first packet, send event
if (not this->m_firstBuffReceived) {
this->log_ACTIVITY_LO_FirstPacketReceived(id);
this->m_stats.setPacketStatus(PacketRecvStatus::PACKET_STATE_OK);
this->m_firstBuffReceived = true;
}
// compute checksum
U32 sum = 0;
for (U32 byte = 0; byte < size; byte++) {
sum += testData[byte];
}
// check checksum
if (sum != csum) {
// increment error count
this->m_stats.setBuffErr(++this->m_errBuffs);
// send error event
this->log_WARNING_HI_PacketChecksumError(id);
// update stats
this->m_stats.setPacketStatus(PacketRecvStatus::PACKET_STATE_ERRORS);
}
// update sensor values
this->m_sensor1 += 5.0;
this->m_sensor2 += 1.2;
// update channels
this->tlmWrite_Sensor1(this->m_sensor1);
this->tlmWrite_Sensor2(this->m_sensor2);
this->tlmWrite_PktState(this->m_stats);
}
void RecvBuffImpl::toString(char* str, I32 buffer_size) {
#if FW_OBJECT_NAMES == 1
(void)snprintf(str, buffer_size, "RecvBuffImpl: %s: ATM recd count: %d", this->m_objName.toChar(),
(int) this->m_buffsReceived);
#else
(void)snprintf(str, buffer_size, "RecvBuffImpl: ATM recd count: %d",
(int) this->m_buffsReceived);
#endif
}
void RecvBuffImpl::parameterUpdated(FwPrmIdType id) {
this->log_ACTIVITY_LO_BuffRecvParameterUpdated(id);
Fw::ParamValid valid;
switch(id) {
case PARAMID_PARAMETER1: {
U32 val = this->paramGet_parameter1(valid);
this->tlmWrite_Parameter1(val);
break;
}
case PARAMID_PARAMETER2: {
I16 val = this->paramGet_parameter2(valid);
this->tlmWrite_Parameter2(val);
break;
}
default:
FW_ASSERT(0,id);
break;
}
}
}
| cpp |
fprime | data/projects/fprime/Ref/RecvBuffApp/RecvBuff.hpp | // ======================================================================
// RecvBuff.hpp
// Standardization header for RecvBuff
// ======================================================================
#ifndef Ref_RecvBuff_HPP
#define Ref_RecvBuff_HPP
#include "Ref/RecvBuffApp/RecvBuffComponentImpl.hpp"
namespace Ref {
typedef RecvBuffImpl RecvBuff;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/Ip/TcpServerSocket.cpp | // ======================================================================
// \title TcpServerSocket.cpp
// \author mstarch
// \brief cpp file for TcpServerSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/Ip/TcpServerSocket.hpp>
#include <Fw/Logger/Logger.hpp>
#include <FpConfig.hpp>
#ifdef TGT_OS_TYPE_VXWORKS
#include <socket.h>
#include <inetLib.h>
#include <fioLib.h>
#include <hostLib.h>
#include <ioLib.h>
#include <vxWorks.h>
#include <sockLib.h>
#include <taskLib.h>
#include <sysLib.h>
#include <errnoLib.h>
#include <cstring>
#elif defined TGT_OS_TYPE_LINUX || TGT_OS_TYPE_DARWIN
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#else
#error OS not supported for IP Socket Communications
#endif
#include <cstring>
namespace Drv {
TcpServerSocket::TcpServerSocket() : IpSocket(), m_base_fd(-1) {}
SocketIpStatus TcpServerSocket::startup() {
NATIVE_INT_TYPE serverFd = -1;
struct sockaddr_in address;
this->close();
// Acquire a socket, or return error
if ((serverFd = ::socket(AF_INET, SOCK_STREAM, 0)) == -1) {
return SOCK_FAILED_TO_GET_SOCKET;
}
// Set up the address port and name
address.sin_family = AF_INET;
address.sin_port = htons(this->m_port);
// OS specific settings
#if defined TGT_OS_TYPE_VXWORKS || TGT_OS_TYPE_DARWIN
address.sin_len = static_cast<U8>(sizeof(struct sockaddr_in));
#endif
// First IP address to socket sin_addr
if (IpSocket::addressToIp4(m_hostname, &(address.sin_addr)) != SOCK_SUCCESS) {
::close(serverFd);
return SOCK_INVALID_IP_ADDRESS;
};
// TCP requires bind to an address to the socket
if (::bind(serverFd, reinterpret_cast<struct sockaddr*>(&address), sizeof(address)) < 0) {
::close(serverFd);
return SOCK_FAILED_TO_BIND;
}
Fw::Logger::logMsg("Listening for single client at %s:%hu\n", reinterpret_cast<POINTER_CAST>(m_hostname), m_port);
// TCP requires listening on a the socket. Second argument prevents queueing of anything more than a single client.
if (::listen(serverFd, 0) < 0) {
::close(serverFd);
return SOCK_FAILED_TO_LISTEN; // What we have here is a failure to communicate
}
this->m_lock.lock();
m_base_fd = serverFd;
this->m_lock.unLock();
return this->IpSocket::startup();
}
void TcpServerSocket::shutdown() {
this->m_lock.lock();
if (this->m_base_fd != -1) {
(void)::shutdown(this->m_base_fd, SHUT_RDWR);
(void)::close(this->m_base_fd);
this->m_base_fd = -1;
}
this->m_lock.unLock();
this->IpSocket::shutdown();
}
SocketIpStatus TcpServerSocket::openProtocol(NATIVE_INT_TYPE& fd) {
NATIVE_INT_TYPE clientFd = -1;
NATIVE_INT_TYPE serverFd = -1;
// Check started before allowing open
if (not this->isStarted()) {
return SOCK_NOT_STARTED;
}
this->m_lock.lock();
serverFd = this->m_base_fd;
this->m_lock.unLock();
// TCP requires accepting on a the socket to get the client socket file descriptor.
clientFd = ::accept(serverFd, nullptr, nullptr);
if (clientFd < 0) {
return SOCK_FAILED_TO_ACCEPT; // What we have here is a failure to communicate
}
// Setup client send timeouts
if (IpSocket::setupTimeouts(clientFd) != SOCK_SUCCESS) {
::close(clientFd);
return SOCK_FAILED_TO_SET_SOCKET_OPTIONS;
}
Fw::Logger::logMsg("Accepted client at %s:%hu\n", reinterpret_cast<POINTER_CAST>(m_hostname), m_port);
fd = clientFd;
return SOCK_SUCCESS;
}
I32 TcpServerSocket::sendProtocol(const U8* const data, const U32 size) {
return ::send(this->m_fd, data, size, SOCKET_IP_SEND_FLAGS);
}
I32 TcpServerSocket::recvProtocol(U8* const data, const U32 size) {
return ::recv(this->m_fd, data, size, SOCKET_IP_RECV_FLAGS);
}
} // namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/Ip/TcpClientSocket.cpp | // ======================================================================
// \title TcpClientSocket.cpp
// \author mstarch
// \brief cpp file for TcpClientSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/Ip/TcpClientSocket.hpp>
#include <Fw/Logger/Logger.hpp>
#include <FpConfig.hpp>
#ifdef TGT_OS_TYPE_VXWORKS
#include <socket.h>
#include <inetLib.h>
#include <fioLib.h>
#include <hostLib.h>
#include <ioLib.h>
#include <vxWorks.h>
#include <sockLib.h>
#include <taskLib.h>
#include <sysLib.h>
#include <errnoLib.h>
#include <cstring>
#elif defined TGT_OS_TYPE_LINUX || TGT_OS_TYPE_DARWIN
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#else
#error OS not supported for IP Socket Communications
#endif
#include <cstdio>
#include <cstring>
namespace Drv {
TcpClientSocket::TcpClientSocket() : IpSocket() {}
SocketIpStatus TcpClientSocket::openProtocol(NATIVE_INT_TYPE& fd) {
NATIVE_INT_TYPE socketFd = -1;
struct sockaddr_in address;
// Acquire a socket, or return error
if ((socketFd = ::socket(AF_INET, SOCK_STREAM, 0)) == -1) {
return SOCK_FAILED_TO_GET_SOCKET;
}
// Set up the address port and name
address.sin_family = AF_INET;
address.sin_port = htons(this->m_port);
// OS specific settings
#if defined TGT_OS_TYPE_VXWORKS || TGT_OS_TYPE_DARWIN
address.sin_len = static_cast<U8>(sizeof(struct sockaddr_in));
#endif
// First IP address to socket sin_addr
if (IpSocket::addressToIp4(m_hostname, &(address.sin_addr)) != SOCK_SUCCESS) {
::close(socketFd);
return SOCK_INVALID_IP_ADDRESS;
};
// Now apply timeouts
if (IpSocket::setupTimeouts(socketFd) != SOCK_SUCCESS) {
::close(socketFd);
return SOCK_FAILED_TO_SET_SOCKET_OPTIONS;
}
// TCP requires connect to the socket to allow for communication
if (::connect(socketFd, reinterpret_cast<struct sockaddr*>(&address), sizeof(address)) < 0) {
::close(socketFd);
return SOCK_FAILED_TO_CONNECT;
}
fd = socketFd;
Fw::Logger::logMsg("Connected to %s:%hu as a tcp client\n", reinterpret_cast<POINTER_CAST>(m_hostname), m_port);
return SOCK_SUCCESS;
}
I32 TcpClientSocket::sendProtocol(const U8* const data, const U32 size) {
return ::send(this->m_fd, data, size, SOCKET_IP_SEND_FLAGS);
}
I32 TcpClientSocket::recvProtocol(U8* const data, const U32 size) {
return ::recv(this->m_fd, data, size, SOCKET_IP_RECV_FLAGS);
}
} // namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/Ip/SocketReadTask.hpp | // ======================================================================
// \title SocketReadTask.hpp
// \author mstarch
// \brief hpp file for SocketReadTask implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef DRV_SOCKETREADTASK_HPP
#define DRV_SOCKETREADTASK_HPP
#include <Fw/Buffer/Buffer.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <Os/Task.hpp>
namespace Drv {
/**
* \brief supports a task to read a given socket adaptation
*
* Defines an Os::Task task to read a socket and send out the data. This represents the task itself, which is capable of
* reading the data from the socket, sending the data out, and reopening the connection should a non-retry error occur.
*
*/
class SocketReadTask {
public:
/**
* \brief constructs the socket read task
*/
SocketReadTask();
/**
* \brief destructor of the socket read task
*/
virtual ~SocketReadTask();
/**
* \brief start the socket read task to start producing data
*
* Starts up the socket reading task and opens socket. This should be called before send calls are expected to
* work. Will connect to the previously configured port and host. priority, stack, and cpuAffinity are provided
* to the Os::Task::start call.
*
* \param name: name of the task
* \param reconnect: automatically reconnect socket when closed. Default: true.
* \param priority: priority of the started task. See: Os::Task::start. Default: TASK_DEFAULT, not prioritized
* \param stack: stack size provided to the task. See: Os::Task::start. Default: TASK_DEFAULT, posix threads default
* \param cpuAffinity: cpu affinity provided to task. See: Os::Task::start. Default: TASK_DEFAULT, don't care
*/
void startSocketTask(const Fw::StringBase &name,
const bool reconnect = true,
const Os::Task::ParamType priority = Os::Task::TASK_DEFAULT,
const Os::Task::ParamType stack = Os::Task::TASK_DEFAULT,
const Os::Task::ParamType cpuAffinity = Os::Task::TASK_DEFAULT);
/**
* \brief startup the socket for communications
*
* Status of the socket handler.
*
* Note: this just delegates to the handler
*
* \return status of open, SOCK_SUCCESS for success, something else on error
*/
SocketIpStatus startup();
/**
* \brief open the socket for communications
*
* Typically the socket read task will open the connection and keep it open. However, in cases where the read task
* will not be started, this function may be used to open the socket.
*
* Note: this just delegates to the handler
*
* \return status of open, SOCK_SUCCESS for success, something else on error
*/
SocketIpStatus open();
/**
* \brief close the socket communications
*
* Typically stopping the socket read task will shutdown the connection. However, in cases where the read task
* will not be started, this function may be used to close the socket. This calls a full `close` on the client
* socket.
*
* Note: this just delegates to the handler
*/
void close();
/**
* \brief shutdown the socket communications
*
* Typically stopping the socket read task will shutdown the connection. However, in cases where the read task
* will not be started, this function may be used to close the socket. This calls a full `shutdown` on the client
* socket.
*
* Note: this just delegates to the handler
*/
void shutdown();
/**
* \brief stop the socket read task and close the associated socket.
*
* Called to stop the socket read task. It is an error to call this before the thread has been started using the
* startSocketTask call. This will stop the read task and close the client socket.
*/
void stopSocketTask();
/**
* \brief joins to the stopping read task to wait for it to close
*
* Called to join with the read socket task. This will block and return after the task has been stopped with a call
* to the stopSocketTask method.
* \param value_ptr: a pointer to fill with data. Passed to the Os::Task::join call. NULL to ignore.
* \return: Os::Task::TaskStatus passed back from the Os::Task::join call.
*/
Os::Task::TaskStatus joinSocketTask(void** value_ptr);
PROTECTED:
/**
* \brief returns a reference to the socket handler
*
* Gets a reference to the current socket handler in order to operate generically on the IpSocket instance. Used for
* receive, and open calls.
*
* Note: this must be implemented by the inheritor
*
* \return IpSocket reference
*/
virtual IpSocket& getSocketHandler() = 0;
/**
* \brief returns a buffer to fill with data
*
* Gets a reference to a buffer to fill with data. This allows the component to determine how to provide a
* buffer and the socket read task just fills said buffer.
*
* Note: this must be implemented by the inheritor
*
* \return Fw::Buffer to fill with data
*/
virtual Fw::Buffer getBuffer() = 0;
/**
* \brief sends a buffer to be filled with data
*
* Sends the buffer gotten by getBuffer that has now been filled with data. This is used to delegate to the
* component how to send back the buffer.
*
* Note: this must be implemented by the inheritor
*
* \return Fw::Buffer filled with data to send out
*/
virtual void sendBuffer(Fw::Buffer buffer, SocketIpStatus status) = 0;
/**
* \brief called when the IPv4 system has been connected
*/
virtual void connected() = 0;
/**
* \brief a task designed to read from the socket and output incoming data
*
* \param pointer: pointer to "this" component
*/
static void readTask(void* pointer);
Os::Task m_task;
bool m_reconnect; //!< Force reconnection
bool m_stop; //!< Stops the task when set to true
};
}
#endif // DRV_SOCKETREADTASK_HPP
| hpp |
fprime | data/projects/fprime/Drv/Ip/UdpSocket.hpp | // ======================================================================
// \title UdpSocket.hpp
// \author mstarch
// \brief hpp file for UdpSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef DRV_IP_UDPSOCKET_HPP_
#define DRV_IP_UDPSOCKET_HPP_
#include <FpConfig.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <IpCfg.hpp>
namespace Drv {
/**
* \brief a structure used to hold the encapsulated socket state to prevent namespace collision
*/
struct SocketState;
/**
* \brief Helper for setting up Udp using Berkeley sockets as a client
*
* Certain IP headers have conflicting definitions with the m_data member of various types in fprime. UdpSocket
* separates the ip setup from the incoming Fw::Buffer in the primary component class preventing this collision.
*/
class UdpSocket : public IpSocket {
public:
/**
* \brief Constructor for client socket udp implementation
*/
UdpSocket();
/**
* \brief to cleanup state created at instantiation
*/
virtual ~UdpSocket();
/**
* \brief configure the udp socket for outgoing transmissions
*
* Configures the UDP handler to use the given hostname and port for outgoing transmissions. Incoming hostname
* and port are configured using the `configureRecv` function call for UDP as it requires separate host/port pairs
* for outgoing and incoming transmissions. Hostname DNS translation is left up to the caller and thus hostname must
* be an IP address in dot-notation of the form "x.x.x.x". Port cannot be set to 0 as dynamic port assignment is not
* supported. It is possible to configure the UDP port as a single-direction send port only.
*
* Note: delegates to `IpSocket::configure`
*
* \param hostname: socket uses for outgoing transmissions. Must be of form x.x.x.x
* \param port: port socket uses for outgoing transmissions. Must NOT be 0.
* \param send_timeout_seconds: send timeout seconds portion
* \param send_timeout_microseconds: send timeout microseconds portion. Must be less than 1000000
* \return status of configure
*/
SocketIpStatus configureSend(const char* hostname, const U16 port, const U32 send_timeout_seconds,
const U32 send_timeout_microseconds);
/**
* \brief configure the udp socket for incoming transmissions
*
* Configures the UDP handler to use the given hostname and port for incoming transmissions. Outgoing hostname
* and port are configured using the `configureSend` function call for UDP as it requires separate host/port pairs
* for outgoing and incoming transmissions. Hostname DNS translation is left up to the caller and thus hostname must
* be an IP address in dot-notation of the form "x.x.x.x". Port cannot be set to 0 as dynamic port assignment is not
* supported. It is possible to configure the UDP port as a single-direction receive port only.
*
* \param hostname: socket uses for incoming transmissions. Must be of form x.x.x.x
* \param port: port socket uses for incoming transmissions. Must NOT be 0.
* \return status of configure
*/
SocketIpStatus configureRecv(const char* hostname, const U16 port);
PROTECTED:
/**
* \brief bind the UDP to a port such that it can receive packets at the previously configured port
* \param fd: socket file descriptor used in bind
* \return status of the bind
*/
SocketIpStatus bind(NATIVE_INT_TYPE fd);
/**
* \brief udp specific implementation for opening a socket.
* \param fd: (output) file descriptor opened. Only valid on SOCK_SUCCESS. Otherwise will be invalid
* \return status of open
*/
SocketIpStatus openProtocol(NATIVE_INT_TYPE& fd);
/**
* \brief Protocol specific implementation of send. Called directly with retry from send.
* \param data: data to send
* \param size: size of data to send
* \return: size of data sent, or -1 on error.
*/
I32 sendProtocol(const U8* const data, const U32 size);
/**
* \brief Protocol specific implementation of recv. Called directly with error handling from recv.
* \param data: data pointer to fill
* \param size: size of data buffer
* \return: size of data received, or -1 on error.
*/
I32 recvProtocol( U8* const data, const U32 size);
private:
SocketState* m_state; //!< State storage
U16 m_recv_port; //!< IP address port used
char m_recv_hostname[SOCKET_MAX_HOSTNAME_SIZE]; //!< Hostname to supply
};
} // namespace Drv
#endif /* DRV_IP_UDPSOCKET_HPP_ */
| hpp |
fprime | data/projects/fprime/Drv/Ip/IpSocket.hpp | // ======================================================================
// \title IpSocket.hpp
// \author mstarch
// \brief hpp file for IpSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef DRV_IP_IPHELPER_HPP_
#define DRV_IP_IPHELPER_HPP_
#include <FpConfig.hpp>
#include <IpCfg.hpp>
#include <Os/Mutex.hpp>
namespace Drv {
/**
* \brief Status enumeration for socket return values
*/
enum SocketIpStatus {
SOCK_SUCCESS = 0, //!< Socket operation successful
SOCK_FAILED_TO_GET_SOCKET = -1, //!< Socket open failed
SOCK_FAILED_TO_GET_HOST_IP = -2, //!< Host IP lookup failed
SOCK_INVALID_IP_ADDRESS = -3, //!< Bad IP address supplied
SOCK_FAILED_TO_CONNECT = -4, //!< Failed to connect socket
SOCK_FAILED_TO_SET_SOCKET_OPTIONS = -5, //!< Failed to configure socket
SOCK_INTERRUPTED_TRY_AGAIN = -6, //!< Interrupted status for retries
SOCK_READ_ERROR = -7, //!< Failed to read socket
SOCK_DISCONNECTED = -8, //!< Failed to read socket with disconnect
SOCK_FAILED_TO_BIND = -9, //!< Failed to bind to socket
SOCK_FAILED_TO_LISTEN = -10, //!< Failed to listen on socket
SOCK_FAILED_TO_ACCEPT = -11, //!< Failed to accept connection
SOCK_SEND_ERROR = -13, //!< Failed to send after configured retries
SOCK_NOT_STARTED = -14, //!< Socket has not been started
};
/**
* \brief Helper base-class for setting up Berkeley sockets
*
* Certain IP headers have conflicting definitions with the m_data member of various types in fprime. TcpHelper
* separates the ip setup from the incoming Fw::Buffer in the primary component class preventing this collision.
*/
class IpSocket {
public:
IpSocket();
virtual ~IpSocket(){};
/**
* \brief configure the ip socket with host and transmission timeouts
*
* Configures the IP handler (Tcp, Tcp server, and Udp) to use the given hostname and port. When multiple ports are
* used for send/receive these settings affect the send direction (as is the case for udp). Hostname DNS translation
* is left up to the caller and thus hostname must be an IP address in dot-notation of the form "x.x.x.x". Port
* cannot be set to 0 as dynamic port assignment is not supported.
*
* Note: for UDP sockets this is equivalent to `configureSend` and only sets up the transmission direction of the
* socket. A separate call to `configureRecv` is required to receive on the socket and should be made before the
* `open` call has been made.
*
* \param hostname: socket uses for outgoing transmissions (and incoming when tcp). Must be of form x.x.x.x
* \param port: port socket uses for outgoing transmissions (and incoming when tcp). Must NOT be 0.
* \param send_timeout_seconds: send timeout seconds portion
* \param send_timeout_microseconds: send timeout microseconds portion. Must be less than 1000000
* \return status of configure
*/
SocketIpStatus configure(const char* hostname, const U16 port, const U32 send_timeout_seconds,
const U32 send_timeout_microseconds);
/**
* \brief Returns true when the socket is started
*
* Returns true when the socket is started up sufficiently to be actively listening to clients. Returns false
* otherwise. This means `startup()` was called and returned success.
*/
bool isStarted();
/**
* \brief check if IP socket has previously been opened
*
* Check if this IpSocket has previously been opened. In the case of Udp this will check for outgoing transmissions
* and (if configured) incoming transmissions as well. This does not guarantee errors will not occur when using this
* socket as the remote component may have disconnected.
*
* \return true if socket is open, false otherwise
*/
bool isOpened();
/**
* \brief startup the socket, a no-op on unless this is server
*
* This will start-up the socket. In the case of most sockets, this is a no-op. On server sockets this binds to the
* server address and progresses through the `listen` step such that on `open` new clients may be accepted.
*
* \return status of startup
*/
virtual SocketIpStatus startup();
/**
* \brief open the IP socket for communications
*
* This will open the IP socket for communication. This method error checks and validates properties set using the
* `configure` method. Tcp sockets will open bidirectional communication assuming the `configure` function was
* previously called. Udp sockets allow `configureRecv` and `configure`/`configureSend` calls to configure for
* each direction separately and may be operated in a single-direction or bidirectional mode. This call returns a
* status of SOCK_SEND means the port is ready for transmissions and any other status should be treated as an error
* with the socket not capable of sending nor receiving. This method will properly close resources on any
* unsuccessful status.
*
* In the case of server components (TcpServer) this function will block until a client has connected.
*
* Note: delegates to openProtocol for protocol specific implementation
*
* \return status of open
*/
SocketIpStatus open();
/**
* \brief send data out the IP socket from the given buffer
*
* Sends data out of the IpSocket. This outgoing transmission will be retried several times if the transmission
* fails to send all the data. Retries are globally configured in the `IpCfg.hpp` header. Should the
* socket be unavailable, SOCK_DISCONNECTED is returned and the socket should be reopened using the `open` call.
* This can happen even when the socket has already been opened should a transmission error/closure be detected.
* Unless an error is received, all data will have been transmitted.
*
* Note: delegates to `sendProtocol` to send the data
*
* \param data: pointer to data to send
* \param size: size of data to send
* \return status of the send, SOCK_DISCONNECTED to reopen, SOCK_SUCCESS on success, something else on error
*/
SocketIpStatus send(const U8* const data, const U32 size);
/**
* \brief receive data from the IP socket from the given buffer
*
* Receives data from the IpSocket. Should the socket be unavailable, SOCK_DISCONNECTED will be returned and
* the socket should be reopened using the `open` call. This can happen even when the socket has already been opened
* should a transmission error/closure be detected. Since this blocks until data is available, it will retry as long
* as EINTR is set and less than a max number of iterations has passed. This function will block to receive data and
* will retry (up to a configured set of retries) as long as EINTR is returned.
*
* Note: delegates to `recvProtocol` to send the data
*
* \param data: pointer to data to fill with received data
* \param size: maximum size of data buffer to fill
* \return status of the send, SOCK_DISCONNECTED to reopen, SOCK_SUCCESS on success, something else on error
*/
SocketIpStatus recv(U8* const data, I32& size);
/**
* \brief closes the socket
*
* Closes the socket opened by the open call. In this case of the TcpServer, this does NOT close server's listening
* port (call `shutdown`) but will close the active client connection.
*/
void close();
/**
* \brief shutdown the socket
*
* Closes the socket opened by the open call. In this case of the TcpServer, this does close server's listening
* port. This will shutdown all clients.
*/
virtual void shutdown();
PROTECTED:
/**
* \brief setup the socket timeout properties of the opened outgoing socket
* \param socketFd: file descriptor to setup
* \return status of timeout setup
*/
SocketIpStatus setupTimeouts(NATIVE_INT_TYPE socketFd);
/**
* \brief converts a given address in dot form x.x.x.x to an ip address. ONLY works for IPv4.
* \param address: address to convert
* \param ip4: IPv4 representation structure to fill
* \return: status of conversion
*/
static SocketIpStatus addressToIp4(const char* address, void* ip4);
/**
* \brief Protocol specific open implementation, called from open.
* \param fd: (output) file descriptor opened. Only valid on SOCK_SUCCESS. Otherwise will be invalid
* \return status of open
*/
virtual SocketIpStatus openProtocol(NATIVE_INT_TYPE& fd) = 0;
/**
* \brief Protocol specific implementation of send. Called directly with retry from send.
* \param data: data to send
* \param size: size of data to send
* \return: size of data sent, or -1 on error.
*/
virtual I32 sendProtocol(const U8* const data, const U32 size) = 0;
/**
* \brief Protocol specific implementation of recv. Called directly with error handling from recv.
* \param data: data pointer to fill
* \param size: size of data buffer
* \return: size of data received, or -1 on error.
*/
virtual I32 recvProtocol( U8* const data, const U32 size) = 0;
Os::Mutex m_lock;
NATIVE_INT_TYPE m_fd;
U32 m_timeoutSeconds;
U32 m_timeoutMicroseconds;
U16 m_port; //!< IP address port used
bool m_open; //!< Have we successfully opened
bool m_started; //!< Have we successfully started the socket
char m_hostname[SOCKET_MAX_HOSTNAME_SIZE]; //!< Hostname to supply
};
} // namespace Drv
#endif /* DRV_SOCKETIPDRIVER_SOCKETHELPER_HPP_ */
| hpp |
fprime | data/projects/fprime/Drv/Ip/TcpServerSocket.hpp | // ======================================================================
// \title TcpServerSocket.hpp
// \author mstarch
// \brief hpp file for TcpServerSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef DRV_TCPSERVER_TCPHELPER_HPP_
#define DRV_TCPSERVER_TCPHELPER_HPP_
#include <FpConfig.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <IpCfg.hpp>
namespace Drv {
/**
* \brief Helper for setting up Tcp using Berkeley sockets as a server
*
* Certain IP headers have conflicting definitions with the m_data member of various types in fprime. TcpServerSocket
* separates the ip setup from the incoming Fw::Buffer in the primary component class preventing this collision.
*/
class TcpServerSocket : public IpSocket {
public:
/**
* \brief Constructor for client socket tcp implementation
*/
TcpServerSocket();
/**
* \brief Opens the server socket and listens, does not block.
*
* Opens the server's listening socket such that this server can listen for incoming client requests. Given the
* nature of this component, only one (1) client can be handled at a time. After this call succeeds, clients may
* connect. This call does not block, block occurs on `open` while waiting to accept incoming clients.
* \return status of the server socket setup.
*/
SocketIpStatus startup() override;
/**
* \brief Shutdown and close the server socket followed by the open client
*
* First, this calls `shutdown` and `close` on the server socket and then calls the close method to `shutdown` and
* `close` the client.
*/
void shutdown() override;
PROTECTED:
/**
* \brief Tcp specific implementation for opening a client socket connected to this server.
* \param fd: (output) file descriptor opened. Only valid on SOCK_SUCCESS. Otherwise will be invalid
* \return status of open
*/
SocketIpStatus openProtocol(NATIVE_INT_TYPE& fd) override;
/**
* \brief Protocol specific implementation of send. Called directly with retry from send.
* \param data: data to send
* \param size: size of data to send
* \return: size of data sent, or -1 on error.
*/
I32 sendProtocol(const U8* const data, const U32 size) override;
/**
* \brief Protocol specific implementation of recv. Called directly with error handling from recv.
* \param data: data pointer to fill
* \param size: size of data buffer
* \return: size of data received, or -1 on error.
*/
I32 recvProtocol( U8* const data, const U32 size) override;
private:
NATIVE_INT_TYPE m_base_fd; //!< File descriptor of the listening socket
};
} // namespace Drv
#endif /* DRV_TCPSERVER_TCPHELPER_HPP_ */
| hpp |
fprime | data/projects/fprime/Drv/Ip/TcpClientSocket.hpp | // ======================================================================
// \title TcpClientSocket.hpp
// \author mstarch
// \brief cpp file for TcpClientSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef DRV_TCPCLIENT_TCPHELPER_HPP_
#define DRV_TCPCLIENT_TCPHELPER_HPP_
#include <FpConfig.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <IpCfg.hpp>
namespace Drv {
/**
* \brief Helper for setting up Tcp using Berkeley sockets as a client
*
* Certain IP headers have conflicting definitions with the m_data member of various types in fprime. TcpClientSocket
* separates the ip setup from the incoming Fw::Buffer in the primary component class preventing this collision.
*/
class TcpClientSocket : public IpSocket {
public:
/**
* \brief Constructor for client socket tcp implementation
*/
TcpClientSocket();
PROTECTED:
/**
* \brief Tcp specific implementation for opening a client socket.
* \param fd: (output) file descriptor opened. Only valid on SOCK_SUCCESS. Otherwise will be invalid
* \return status of open
*/
SocketIpStatus openProtocol(NATIVE_INT_TYPE& fd) override;
/**
* \brief Protocol specific implementation of send. Called directly with retry from send.
* \param data: data to send
* \param size: size of data to send
* \return: size of data sent, or -1 on error.
*/
I32 sendProtocol(const U8* const data, const U32 size) override;
/**
* \brief Protocol specific implementation of recv. Called directly with error handling from recv.
* \param data: data pointer to fill
* \param size: size of data buffer
* \return: size of data received, or -1 on error.
*/
I32 recvProtocol( U8* const data, const U32 size) override;
};
} // namespace Drv
#endif /* DRV_TCPCLIENT_TCPHELPER_HPP_ */
| hpp |
fprime | data/projects/fprime/Drv/Ip/IpSocket.cpp | // ======================================================================
// \title IpSocket.cpp
// \author mstarch
// \brief cpp file for IpSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <cstring>
#include <Drv/Ip/IpSocket.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/StringUtils.hpp>
#include <sys/time.h>
// This implementation has primarily implemented to isolate
// the socket interface from the F' Fw::Buffer class.
// There is a macro in VxWorks (m_data) that collides with
// the m_data member in Fw::Buffer.
#ifdef TGT_OS_TYPE_VXWORKS
#include <socket.h>
#include <inetLib.h>
#include <fioLib.h>
#include <hostLib.h>
#include <ioLib.h>
#include <vxWorks.h>
#include <sockLib.h>
#include <fioLib.h>
#include <taskLib.h>
#include <sysLib.h>
#include <errnoLib.h>
#include <cstring>
#elif defined TGT_OS_TYPE_LINUX || TGT_OS_TYPE_DARWIN
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <arpa/inet.h>
#else
#error OS not supported for IP Socket Communications
#endif
namespace Drv {
IpSocket::IpSocket() : m_fd(-1), m_timeoutSeconds(0), m_timeoutMicroseconds(0), m_port(0), m_open(false), m_started(false) {
::memset(m_hostname, 0, sizeof(m_hostname));
}
SocketIpStatus IpSocket::configure(const char* const hostname, const U16 port, const U32 timeout_seconds, const U32 timeout_microseconds) {
FW_ASSERT(timeout_microseconds < 1000000, timeout_microseconds);
FW_ASSERT(port != 0, port);
this->m_timeoutSeconds = timeout_seconds;
this->m_timeoutMicroseconds = timeout_microseconds;
this->m_port = port;
(void) Fw::StringUtils::string_copy(this->m_hostname, hostname, SOCKET_MAX_HOSTNAME_SIZE);
return SOCK_SUCCESS;
}
SocketIpStatus IpSocket::setupTimeouts(NATIVE_INT_TYPE socketFd) {
// Get the IP address from host
#ifdef TGT_OS_TYPE_VXWORKS
// No timeouts set on Vxworks
#else
// Set timeout socket option
struct timeval timeout;
timeout.tv_sec = this->m_timeoutSeconds;
timeout.tv_usec = this->m_timeoutMicroseconds;
// set socket write to timeout after 1 sec
if (setsockopt(socketFd, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char *>(&timeout), sizeof(timeout)) < 0) {
return SOCK_FAILED_TO_SET_SOCKET_OPTIONS;
}
#endif
return SOCK_SUCCESS;
}
SocketIpStatus IpSocket::addressToIp4(const char* address, void* ip4) {
FW_ASSERT(address != nullptr);
FW_ASSERT(ip4 != nullptr);
// Get the IP address from host
#ifdef TGT_OS_TYPE_VXWORKS
NATIVE_INT_TYPE ip = inet_addr(address);
if (ip == ERROR) {
return SOCK_INVALID_IP_ADDRESS;
}
// from sin_addr, which has one struct
// member s_addr, which is unsigned int
*reinterpret_cast<unsigned long*>(ip4) = ip;
#else
// First IP address to socket sin_addr
if (not ::inet_pton(AF_INET, address, ip4)) {
return SOCK_INVALID_IP_ADDRESS;
};
#endif
return SOCK_SUCCESS;
}
bool IpSocket::isStarted() {
bool is_started = false;
this->m_lock.lock();
is_started = this->m_started;
this->m_lock.unLock();
return is_started;
}
bool IpSocket::isOpened() {
bool is_open = false;
this->m_lock.lock();
is_open = this->m_open;
this->m_lock.unLock();
return is_open;
}
void IpSocket::close() {
this->m_lock.lock();
if (this->m_fd != -1) {
(void)::shutdown(this->m_fd, SHUT_RDWR);
(void)::close(this->m_fd);
this->m_fd = -1;
}
this->m_open = false;
this->m_lock.unLock();
}
void IpSocket::shutdown() {
this->close();
this->m_lock.lock();
this->m_started = false;
this->m_lock.unLock();
}
SocketIpStatus IpSocket::startup() {
this->m_lock.lock();
this->m_started = true;
this->m_lock.unLock();
return SOCK_SUCCESS;
}
SocketIpStatus IpSocket::open() {
NATIVE_INT_TYPE fd = -1;
SocketIpStatus status = SOCK_SUCCESS;
FW_ASSERT(m_fd == -1 and not m_open); // Ensure we are not opening an opened socket
// Open a TCP socket for incoming commands, and outgoing data if not using UDP
status = this->openProtocol(fd);
if (status != SOCK_SUCCESS) {
FW_ASSERT(m_fd == -1); // Ensure we properly kept closed on error
return status;
}
// Lock to update values and "officially open"
this->m_lock.lock();
this->m_fd = fd;
this->m_open = true;
this->m_lock.unLock();
return status;
}
SocketIpStatus IpSocket::send(const U8* const data, const U32 size) {
U32 total = 0;
I32 sent = 0;
// Prevent transmission before connection, or after a disconnect
if (this->m_fd == -1) {
return SOCK_DISCONNECTED;
}
// Attempt to send out data and retry as necessary
for (U32 i = 0; (i < SOCKET_MAX_ITERATIONS) && (total < size); i++) {
// Send using my specific protocol
sent = this->sendProtocol(data + total, size - total);
// Error is EINTR or timeout just try again
if (((sent == -1) && (errno == EINTR)) || (sent == 0)) {
continue;
}
// Error bad file descriptor is a close along with reset
else if ((sent == -1) && ((errno == EBADF) || (errno == ECONNRESET))) {
this->close();
return SOCK_DISCONNECTED;
}
// Error returned, and it wasn't an interrupt nor a disconnect
else if (sent == -1) {
return SOCK_SEND_ERROR;
}
FW_ASSERT(sent > 0, sent);
total += sent;
}
// Failed to retry enough to send all data
if (total < size) {
return SOCK_INTERRUPTED_TRY_AGAIN;
}
FW_ASSERT(total == size, total, size); // Ensure we sent everything
return SOCK_SUCCESS;
}
SocketIpStatus IpSocket::recv(U8* data, I32& req_read) {
I32 size = 0;
// Check for previously disconnected socket
if (m_fd == -1) {
return SOCK_DISCONNECTED;
}
// Try to read until we fail to receive data
for (U32 i = 0; (i < SOCKET_MAX_ITERATIONS) && (size <= 0); i++) {
// Attempt to recv out data
size = this->recvProtocol(data, req_read);
// Error is EINTR, just try again
if (size == -1 && ((errno == EINTR) || errno == EAGAIN)) {
continue;
}
// Zero bytes read reset or bad ef means we've disconnected
else if (size == 0 || ((size == -1) && ((errno == ECONNRESET) || (errno == EBADF)))) {
this->close();
req_read = size;
return SOCK_DISCONNECTED;
}
// Error returned, and it wasn't an interrupt, nor a disconnect
else if (size == -1) {
req_read = size;
return SOCK_READ_ERROR; // Stop recv task on error
}
}
req_read = size;
// Prevent interrupted socket being viewed as success
if (size == -1) {
return SOCK_INTERRUPTED_TRY_AGAIN;
}
return SOCK_SUCCESS;
}
} // namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/Ip/UdpSocket.cpp | // ======================================================================
// \title UdpSocket.cpp
// \author mstarch
// \brief cpp file for UdpSocket core implementation classes
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/Ip/UdpSocket.hpp>
#include <Fw/Logger/Logger.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/StringUtils.hpp>
#ifdef TGT_OS_TYPE_VXWORKS
#include <socket.h>
#include <inetLib.h>
#include <fioLib.h>
#include <hostLib.h>
#include <ioLib.h>
#include <vxWorks.h>
#include <sockLib.h>
#include <taskLib.h>
#include <sysLib.h>
#include <errnoLib.h>
#include <cstring>
#elif defined TGT_OS_TYPE_LINUX || TGT_OS_TYPE_DARWIN
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#else
#error OS not supported for IP Socket Communications
#endif
#include <cstring>
#include <new>
namespace Drv {
struct SocketState {
struct sockaddr_in m_addr_send; //!< UDP server address, maybe unused
struct sockaddr_in m_addr_recv; //!< UDP server address, maybe unused
SocketState() {
::memset(&m_addr_send, 0, sizeof(m_addr_send));
::memset(&m_addr_recv, 0, sizeof(m_addr_recv));
}
};
UdpSocket::UdpSocket() : IpSocket(), m_state(new(std::nothrow) SocketState), m_recv_port(0) {
FW_ASSERT(m_state != nullptr);
}
UdpSocket::~UdpSocket() {
FW_ASSERT(m_state);
delete m_state;
}
SocketIpStatus UdpSocket::configureSend(const char* const hostname, const U16 port, const U32 timeout_seconds, const U32 timeout_microseconds) {
//Timeout is for the send, so configure send will work with the base class
return this->IpSocket::configure(hostname, port, timeout_seconds, timeout_microseconds);
}
SocketIpStatus UdpSocket::configureRecv(const char* hostname, const U16 port) {
this->m_recv_port = port;
(void) Fw::StringUtils::string_copy(this->m_recv_hostname, hostname, SOCKET_MAX_HOSTNAME_SIZE);
return SOCK_SUCCESS;
}
SocketIpStatus UdpSocket::bind(NATIVE_INT_TYPE fd) {
struct sockaddr_in address;
FW_ASSERT(-1 != fd);
FW_ASSERT(0 != m_recv_port);
// Set up the address port and name
address.sin_family = AF_INET;
address.sin_port = htons(m_recv_port);
// OS specific settings
#if defined TGT_OS_TYPE_VXWORKS || TGT_OS_TYPE_DARWIN
address.sin_len = static_cast<U8>(sizeof(struct sockaddr_in));
#endif
// First IP address to socket sin_addr
if (IpSocket::addressToIp4(m_recv_hostname, &address.sin_addr) != SOCK_SUCCESS) {
return SOCK_INVALID_IP_ADDRESS;
};
// UDP (for receiving) requires bind to an address to the socket
if (::bind(fd, reinterpret_cast<struct sockaddr*>(&address), sizeof(address)) < 0) {
return SOCK_FAILED_TO_BIND;
}
FW_ASSERT(sizeof(this->m_state->m_addr_recv) == sizeof(address), sizeof(this->m_state->m_addr_recv), sizeof(address));
memcpy(&this->m_state->m_addr_recv, &address, sizeof(this->m_state->m_addr_recv));
return SOCK_SUCCESS;
}
SocketIpStatus UdpSocket::openProtocol(NATIVE_INT_TYPE& fd) {
SocketIpStatus status = SOCK_SUCCESS;
NATIVE_INT_TYPE socketFd = -1;
struct sockaddr_in address;
// Ensure configured for at least send or receive
if (m_port == 0 && m_recv_port == 0) {
return SOCK_INVALID_IP_ADDRESS; // Consistent with port = 0 behavior in TCP
}
// Acquire a socket, or return error
if ((socketFd = ::socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
return SOCK_FAILED_TO_GET_SOCKET;
}
// May not be sending in all cases
if (this->m_port != 0) {
// Set up the address port and name
address.sin_family = AF_INET;
address.sin_port = htons(this->m_port);
// OS specific settings
#if defined TGT_OS_TYPE_VXWORKS || TGT_OS_TYPE_DARWIN
address.sin_len = static_cast<U8>(sizeof(struct sockaddr_in));
#endif
// First IP address to socket sin_addr
if ((status = IpSocket::addressToIp4(m_hostname, &(address.sin_addr))) != SOCK_SUCCESS) {
::close(socketFd);
return status;
};
// Now apply timeouts
if ((status = IpSocket::setupTimeouts(socketFd)) != SOCK_SUCCESS) {
::close(socketFd);
return status;
}
FW_ASSERT(sizeof(this->m_state->m_addr_send) == sizeof(address), sizeof(this->m_state->m_addr_send),
sizeof(address));
memcpy(&this->m_state->m_addr_send, &address, sizeof(this->m_state->m_addr_send));
}
// When we are setting up for receiving as well, then we must bind to a port
if ((m_recv_port != 0) && ((status = this->bind(socketFd)) != SOCK_SUCCESS)) {
::close(socketFd);
return status; // Not closing FD as it is still a valid send FD
}
const char* actions = (m_recv_port != 0 && m_port != 0) ? "send and receive" : ((m_port != 0) ? "send": "receive");
Fw::Logger::logMsg("Setup to %s udp to %s:%hu\n", reinterpret_cast<POINTER_CAST>(actions),
reinterpret_cast<POINTER_CAST>(m_hostname), m_port);
FW_ASSERT(status == SOCK_SUCCESS, status);
fd = socketFd;
return status;
}
I32 UdpSocket::sendProtocol(const U8* const data, const U32 size) {
FW_ASSERT(this->m_state->m_addr_send.sin_family != 0); // Make sure the address was previously setup
return ::sendto(this->m_fd, data, size, SOCKET_IP_SEND_FLAGS,
reinterpret_cast<struct sockaddr *>(&this->m_state->m_addr_send), sizeof(this->m_state->m_addr_send));
}
I32 UdpSocket::recvProtocol(U8* const data, const U32 size) {
FW_ASSERT(this->m_state->m_addr_recv.sin_family != 0); // Make sure the address was previously setup
return ::recvfrom(this->m_fd, data, size, SOCKET_IP_RECV_FLAGS, nullptr, nullptr);
}
} // namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/Ip/SocketReadTask.cpp | // ======================================================================
// \title SocketReadTask.cpp
// \author mstarch
// \brief cpp file for SocketReadTask implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/Ip/SocketReadTask.hpp>
#include <Fw/Logger/Logger.hpp>
#include <Fw/Types/Assert.hpp>
#include <cerrno>
#define MAXIMUM_SIZE 0x7FFFFFFF
namespace Drv {
SocketReadTask::SocketReadTask() : m_reconnect(false), m_stop(false) {}
SocketReadTask::~SocketReadTask() {}
void SocketReadTask::startSocketTask(const Fw::StringBase &name,
const bool reconnect,
const Os::Task::ParamType priority,
const Os::Task::ParamType stack,
const Os::Task::ParamType cpuAffinity) {
FW_ASSERT(not m_task.isStarted()); // It is a coding error to start this task multiple times
FW_ASSERT(not this->m_stop); // It is a coding error to stop the thread before it is started
m_reconnect = reconnect;
// Note: the first step is for the IP socket to open the port
Os::Task::TaskStatus stat = m_task.start(name, SocketReadTask::readTask, this, priority, stack, cpuAffinity);
FW_ASSERT(Os::Task::TASK_OK == stat, static_cast<NATIVE_INT_TYPE>(stat));
}
SocketIpStatus SocketReadTask::startup() {
return this->getSocketHandler().startup();
}
SocketIpStatus SocketReadTask::open() {
SocketIpStatus status = this->getSocketHandler().open();
// Call connected any time the open is successful
if (Drv::SOCK_SUCCESS == status) {
this->connected();
}
return status;
}
void SocketReadTask::shutdown() {
this->getSocketHandler().shutdown();
}
void SocketReadTask::close() {
this->getSocketHandler().close();
}
Os::Task::TaskStatus SocketReadTask::joinSocketTask(void** value_ptr) {
return m_task.join(value_ptr);
}
void SocketReadTask::stopSocketTask() {
this->m_stop = true;
this->getSocketHandler().shutdown(); // Break out of any receives and fully shutdown
}
void SocketReadTask::readTask(void* pointer) {
FW_ASSERT(pointer);
SocketIpStatus status = SOCK_SUCCESS;
SocketReadTask* self = reinterpret_cast<SocketReadTask*>(pointer);
do {
// Open a network connection if it has not already been open
if ((not self->getSocketHandler().isStarted()) and (not self->m_stop) and
((status = self->startup()) != SOCK_SUCCESS)) {
Fw::Logger::logMsg("[WARNING] Failed to open port with status %d and errno %d\n", status, errno);
(void) Os::Task::delay(SOCKET_RETRY_INTERVAL_MS);
continue;
}
// Open a network connection if it has not already been open
if ((not self->getSocketHandler().isOpened()) and (not self->m_stop) and
((status = self->open()) != SOCK_SUCCESS)) {
Fw::Logger::logMsg("[WARNING] Failed to open port with status %d and errno %d\n", status, errno);
(void) Os::Task::delay(SOCKET_RETRY_INTERVAL_MS);
continue;
}
// If the network connection is open, read from it
if (self->getSocketHandler().isStarted() and self->getSocketHandler().isOpened() and (not self->m_stop)) {
Fw::Buffer buffer = self->getBuffer();
U8* data = buffer.getData();
FW_ASSERT(data);
I32 size = static_cast<I32>(buffer.getSize());
size = (size >= 0) ? size : MAXIMUM_SIZE; // Handle max U32 edge case
status = self->getSocketHandler().recv(data, size);
if ((status != SOCK_SUCCESS) && (status != SOCK_INTERRUPTED_TRY_AGAIN)) {
Fw::Logger::logMsg("[WARNING] Failed to recv from port with status %d and errno %d\n", status, errno);
self->getSocketHandler().close();
buffer.setSize(0);
} else {
// Send out received data
buffer.setSize(size);
}
self->sendBuffer(buffer, status);
}
}
// As long as not told to stop, and we are successful interrupted or ordered to retry, keep receiving
while (not self->m_stop &&
(status == SOCK_SUCCESS || status == SOCK_INTERRUPTED_TRY_AGAIN || self->m_reconnect));
self->getSocketHandler().shutdown(); // Shutdown the port entirely
}
} // namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/Ip/test/ut/PortSelector.hpp | //
// Created by mstarch on 12/10/20.
//
#include <FpConfig.hpp>
#ifndef DRV_TEST_PORTSELECTOR_HPP
#define DRV_TEST_PORTSELECTOR_HPP
namespace Drv {
namespace Test {
/**
* \brief returns a (currently) unused port
*
* Tests working with TCP often need ports to be unused. This presents a problem when looking to bind to a port that has
* not been used anywhere on the system. This function will walk the process through to the point of getting a bind,
* and use the port 0 to have the OS assign one. At this point, the assigned port will be inspected and the fd will be
* closed without a connection allowing something else to bind to it e.g the test code.
*
* Note: this is test code only as there is a known race condition from the moment of closing the port, to when the
* recipient binds it again.
*
* \param is_udp: is this a UDP port
* \return 0 on error, or a free port on success
*/
U16 get_free_port(bool is_udp = false);
};
};
#endif // DRV_TEST_PORTSELECTOR_HPP
| hpp |
fprime | data/projects/fprime/Drv/Ip/test/ut/SocketTestHelper.cpp | //
// Created by mstarch on 12/10/20.
//
#include <Os/Task.hpp>
#include <Drv/Ip/test/ut/SocketTestHelper.hpp>
#include "STest/Pick/Pick.hpp"
#include <gtest/gtest.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <arpa/inet.h>
namespace Drv {
namespace Test {
const U32 MAX_DRV_TEST_MESSAGE_SIZE = 1024;
void force_recv_timeout(Drv::IpSocket& socket) {
// Set timeout socket option
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50; // 50ms max before test failure
setsockopt(socket.m_fd, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char *>(&timeout), sizeof(timeout));
}
void validate_random_data(U8 *data, U8 *truth, U32 size) {
for (U32 i = 0; i < size; i++) {
ASSERT_EQ(data[i], truth[i]);
}
}
void fill_random_data(U8 *data, U32 size) {
ASSERT_NE(size, 0u) << "Trying to fill random data of size 0";
for (U32 i = 0; i < size; i++) {
data[i] = static_cast<U8>(STest::Pick::any());
}
}
void validate_random_buffer(Fw::Buffer &buffer, U8 *data) {
validate_random_data(buffer.getData(), data, buffer.getSize());
buffer.setSize(0);
}
void fill_random_buffer(Fw::Buffer &buffer) {
buffer.setSize(STest::Pick::lowerUpper(1, buffer.getSize()));
fill_random_data(buffer.getData(), buffer.getSize());
}
void send_recv(Drv::IpSocket& sender, Drv::IpSocket& receiver) {
I32 size = MAX_DRV_TEST_MESSAGE_SIZE;
U8 buffer_out[MAX_DRV_TEST_MESSAGE_SIZE] = {0};
U8 buffer_in[MAX_DRV_TEST_MESSAGE_SIZE] = {0};
// Send receive validate block
Drv::Test::fill_random_data(buffer_out, MAX_DRV_TEST_MESSAGE_SIZE);
EXPECT_EQ(sender.send(buffer_out, MAX_DRV_TEST_MESSAGE_SIZE), Drv::SOCK_SUCCESS);
EXPECT_EQ(receiver.recv(buffer_in, size), Drv::SOCK_SUCCESS);
EXPECT_EQ(size, static_cast<I32>(MAX_DRV_TEST_MESSAGE_SIZE));
Drv::Test::validate_random_data(buffer_out, buffer_in, MAX_DRV_TEST_MESSAGE_SIZE);
}
bool wait_on_change(Drv::IpSocket &socket, bool open, U32 iterations) {
for (U32 i = 0; i < iterations; i++) {
if (open == socket.isOpened()) {
return true;
}
Os::Task::delay(10);
}
return false;
}
bool wait_on_started(Drv::IpSocket &socket, bool open, U32 iterations) {
for (U32 i = 0; i < iterations; i++) {
if (open == socket.isStarted()) {
return true;
}
Os::Task::delay(10);
}
return false;
}
};
};
| cpp |
fprime | data/projects/fprime/Drv/Ip/test/ut/SocketTestHelper.hpp | //
// Created by mstarch on 12/10/20.
//
#include <FpConfig.hpp>
#include <Fw//Buffer/Buffer.hpp>
#include <Drv/Ip/IpSocket.hpp>
#ifndef DRV_TEST_SOCKETHELPER_HPP
#define DRV_TEST_SOCKETHELPER_HPP
// Drv::Test namespace
namespace Drv {
namespace Test {
/**
* Force a receive timeout on a socket such that it will not hang our testing despite the normal recv behavior of
* "block forever" until it gets data.
* @param socket: socket to make timeout
*/
void force_recv_timeout(Drv::IpSocket &socket);
/**
* Validate random data from data against truth
* @param data: data to validate
* @param truth: truth data to validate
* @param size: size to validate
*/
void validate_random_data(U8 *data, U8 *truth, U32 size);
/**
* Fills in the given data buffer with randomly picked data.
* @param data: data to file
* @param size: size of fill
*/
void fill_random_data(U8 *data, U32 size);
/**
* Validates a given buffer against the data provided.
* @param buffer: buffer to validate
* @param truth: correct data to validate against
*/
void validate_random_buffer(Fw::Buffer &buffer, U8 *data);
/**
* Fill random data into the buffer (using a random length).
* @param buffer: buffer to fill.
*/
void fill_random_buffer(Fw::Buffer &buffer);
/**
* Send/receive pair.
* @param sender: sender of the pair
* @param receiver: receiver of pair
*/
void send_recv(Drv::IpSocket& sender, Drv::IpSocket& receiver);
/**
* Wait on socket change.
*/
bool wait_on_change(Drv::IpSocket &socket, bool open, U32 iterations);
/**
* Wait on started
*/
bool wait_on_started(Drv::IpSocket &socket, bool open, U32 iterations);
};
};
#endif
| hpp |
fprime | data/projects/fprime/Drv/Ip/test/ut/TestUdp.cpp | //
// Created by mstarch on 12/7/20.
//
#include <gtest/gtest.h>
#include <Drv/Ip/UdpSocket.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <Os/Log.hpp>
#include <Fw/Logger/Logger.hpp>
#include <Drv/Ip/test/ut/PortSelector.hpp>
#include <Drv/Ip/test/ut/SocketTestHelper.hpp>
Os::Log logger;
void test_with_loop(U32 iterations, bool duplex) {
Drv::SocketIpStatus status1 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus status2 = Drv::SOCK_SUCCESS;
U16 port1 = Drv::Test::get_free_port();
ASSERT_NE(0, port1);
U16 port2 = Drv::Test::get_free_port();
ASSERT_NE(0, port2);
// Loop through a bunch of client disconnects
for (U32 i = 0; i < iterations; i++) {
Drv::UdpSocket udp1;
Drv::UdpSocket udp2;
udp1.configureSend("127.0.0.1", port1, 0, 100);
// If simplex, test only half the channel
if (duplex) {
udp1.configureRecv("127.0.0.1", port2);
}
status1 = udp1.open();
// If simplex, test only half the channel
if (duplex) {
udp2.configureSend("127.0.0.1", port2, 0, 100);
}
udp2.configureRecv("127.0.0.1", port1);
status2 = udp2.open();;
EXPECT_EQ(status1, Drv::SOCK_SUCCESS);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
// If all the opens worked, then run this
if (Drv::SOCK_SUCCESS == status1 && Drv::SOCK_SUCCESS == status2) {
// Force the sockets not to hang, if at all possible
Drv::Test::force_recv_timeout(udp1);
Drv::Test::force_recv_timeout(udp2);
Drv::Test::send_recv(udp1, udp2);
// Allow duplex connections
if (duplex) {
Drv::Test::send_recv(udp2, udp1);
}
}
udp1.close();
udp2.close();
}
}
TEST(Nominal, TestNominalUdp) {
test_with_loop(1, false);
}
TEST(Nominal, TestMultipleUdp) {
test_with_loop(100, false);
}
TEST(SingleSide, TestSingleSideUdp) {
test_with_loop(1, true);
}
TEST(SingleSide, TestSingleSideMultipleUdp) {
test_with_loop(100, true);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Drv/Ip/test/ut/TestTcp.cpp | //
// Created by mstarch on 12/7/20.
//
#include <gtest/gtest.h>
#include <Drv/Ip/TcpClientSocket.hpp>
#include <Drv/Ip/TcpServerSocket.hpp>
#include <Drv/Ip/IpSocket.hpp>
#include <Os/Log.hpp>
#include <Fw/Logger/Logger.hpp>
#include <Drv/Ip/test/ut/PortSelector.hpp>
#include <Drv/Ip/test/ut/SocketTestHelper.hpp>
Os::Log logger;
void test_with_loop(U32 iterations) {
Drv::SocketIpStatus status1 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus status2 = Drv::SOCK_SUCCESS;
U16 port = Drv::Test::get_free_port();
ASSERT_NE(0, port);
Drv::TcpServerSocket server;
server.configure("127.0.0.1", port, 0, 100);
EXPECT_EQ(server.startup(), Drv::SOCK_SUCCESS);
Drv::Test::force_recv_timeout(server);
// Loop through a bunch of client disconnects
for (U32 i = 0; i < iterations; i++) {
Drv::TcpClientSocket client;
ASSERT_NE(port, 0);
client.configure("127.0.0.1",port,0,100);
status1 = client.open();
EXPECT_EQ(status1, Drv::SOCK_SUCCESS);
status2 = server.open();
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
// If all the opens worked, then run this
if (Drv::SOCK_SUCCESS == status1 && Drv::SOCK_SUCCESS == status2) {
// Force the sockets not to hang, if at all possible
Drv::Test::force_recv_timeout(client);
Drv::Test::force_recv_timeout(server);
Drv::Test::send_recv(server, client);
Drv::Test::send_recv(client, server);
}
client.close();
server.close();
}
server.shutdown();
}
TEST(Nominal, TestNominalTcp) {
test_with_loop(1);
}
TEST(Nominal, TestMultipleTcp) {
test_with_loop(100);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Drv/Ip/test/ut/PortSelector.cpp | //
// Created by mstarch on 12/10/20.
//
#include "PortSelector.hpp"
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <arpa/inet.h>
namespace Drv {
namespace Test {
U16 get_free_port(bool udp) {
struct sockaddr_in address;
NATIVE_INT_TYPE socketFd = -1;
// Acquire a socket, or return error
if ((socketFd = ::socket(AF_INET, (udp) ? SOCK_DGRAM : SOCK_STREAM, 0)) == -1) {
return 0;
}
// Set up the address port and name
address.sin_family = AF_INET;
address.sin_port = htons(0);
// First IP address to socket sin_addr
if (not ::inet_pton(AF_INET, "127.0.0.1", &(address.sin_addr))) {
::close(socketFd);
return 0;
};
// When we are setting up for receiving as well, then we must bind to a port
if (::bind(socketFd, reinterpret_cast<struct sockaddr *>(&address), sizeof(address)) == -1) {
::close(socketFd);
return 0;
}
socklen_t size = sizeof(address);
if (::getsockname(socketFd, reinterpret_cast<struct sockaddr *>(&address), &size) == -1) {
::close(socketFd);
return 0;
}
U16 port = address.sin_port;
// Check for root-only-port. If so, recursively try again.
if (port < 1024) {
port = get_free_port(udp);
}
::close(socketFd); // Close this recursion's port again, such that we don't infinitely loop
return port;
}
};
};
| cpp |
fprime | data/projects/fprime/Drv/Udp/UdpComponentImpl.hpp | // ======================================================================
// \title UdpComponentImpl.hpp
// \author mstarch
// \brief hpp file for UdpComponentImpl component implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef UdpComponentImpl_HPP
#define UdpComponentImpl_HPP
#include <Drv/Ip/IpSocket.hpp>
#include <Drv/Ip/SocketReadTask.hpp>
#include <Drv/Ip/UdpSocket.hpp>
#include "Drv/Udp/UdpComponentAc.hpp"
namespace Drv {
class UdpComponentImpl : public UdpComponentBase, public SocketReadTask {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
/**
* \brief construct the TcpClient component.
* \param compName: name of this component
*/
UdpComponentImpl(const char* const compName);
/**
* \brief Destroy the component
*/
~UdpComponentImpl();
// ----------------------------------------------------------------------
// Helper methods to start and stop socket
// ----------------------------------------------------------------------
/**
* \brief Configures the Udp send settings but does not open the connection
*
* The UdpComponent may need to send to a remote UDP port. This call configures the hostname, port and send
* timeouts for that socket connection. This call should be performed on system startup before send is called.
* Note: hostname must be a dot-notation IP address of the form "x.x.x.x". DNS translation is left up
* to the user.
*
* \param hostname: ip address of remote tcp server in the form x.x.x.x
* \param port: port of remote tcp server
* \param send_timeout_seconds: send timeout seconds component. Defaults to: SOCKET_TIMEOUT_SECONDS
* \param send_timeout_microseconds: send timeout microseconds component. Must be less than 1000000. Defaults to:
* SOCKET_TIMEOUT_MICROSECONDS
* \return status of the configure
*/
SocketIpStatus configureSend(const char* hostname,
const U16 port,
const U32 send_timeout_seconds = SOCKET_SEND_TIMEOUT_SECONDS,
const U32 send_timeout_microseconds = SOCKET_SEND_TIMEOUT_MICROSECONDS);
/**
* \brief Configures the Udp receive settings but does not open the connection
*
* The UdpComponent may need to receive from a remote udp port. This call configures the hostname and port of that
* source. This call should be performed on system startup before recv or send are called. Note: hostname must be a
* dot-notation IP address of the form "x.x.x.x". DNS translation is left up to the user.
*
* \param hostname: ip address of remote tcp server in the form x.x.x.x
* \param port: port of remote tcp server
* \return status of the configure
*/
SocketIpStatus configureRecv(const char* hostname, const U16 port);
PROTECTED:
// ----------------------------------------------------------------------
// Implementations for socket read task virtual methods
// ----------------------------------------------------------------------
/**
* \brief returns a reference to the socket handler
*
* Gets a reference to the current socket handler in order to operate generically on the IpSocket instance. Used for
* receive, and open calls. This socket handler will be a TcpClient.
*
* \return IpSocket reference
*/
IpSocket& getSocketHandler();
/**
* \brief returns a buffer to fill with data
*
* Gets a reference to a buffer to fill with data. This allows the component to determine how to provide a
* buffer and the socket read task just fills said buffer.
*
* \return Fw::Buffer to fill with data
*/
Fw::Buffer getBuffer();
/**
* \brief sends a buffer to be filled with data
*
* Sends the buffer gotten by getBuffer that has now been filled with data. This is used to delegate to the
* component how to send back the buffer. Ignores buffers with error status error.
*
* \return Fw::Buffer filled with data to send out
*/
void sendBuffer(Fw::Buffer buffer, SocketIpStatus status);
/**
* \brief called when the IPv4 system has been connected
*/
void connected();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
/**
* \brief Send data out of the TcpClient
*
* Passing data to this port will send data from the TcpClient to whatever TCP server this component has connected
* to. Should the socket not be opened or was disconnected, then this port call will return SEND_RETRY and critical
* transmissions should be retried. SEND_ERROR indicates an unresolvable error. SEND_OK is returned when the data
* has been sent.
*
* Note: this component delegates the reopening of the socket to the read thread and thus the caller should retry
* after the read thread has attempted to reopen the port but does not need to reopen the port manually.
*
* \param portNum: fprime port number of the incoming port call
* \param fwBuffer: buffer containing data to be sent
* \return SEND_OK on success, SEND_RETRY when critical data should be retried and SEND_ERROR upon error
*/
Drv::SendStatus send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer);
Drv::UdpSocket m_socket; //!< Socket implementation
};
} // end namespace Drv
#endif // end UdpComponentImpl
| hpp |
fprime | data/projects/fprime/Drv/Udp/UdpComponentImpl.cpp | // ======================================================================
// \title UdpComponentImpl.cpp
// \author mstarch
// \brief cpp file for UdpComponentImpl component implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/Udp/UdpComponentImpl.hpp>
#include <IpCfg.hpp>
#include <FpConfig.hpp>
#include "Fw/Types/Assert.hpp"
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
UdpComponentImpl::UdpComponentImpl(const char* const compName)
: UdpComponentBase(compName),
SocketReadTask() {}
SocketIpStatus UdpComponentImpl::configureSend(const char* hostname,
const U16 port,
const U32 send_timeout_seconds,
const U32 send_timeout_microseconds) {
return m_socket.configureSend(hostname, port, send_timeout_seconds, send_timeout_microseconds);
}
SocketIpStatus UdpComponentImpl::configureRecv(const char* hostname, const U16 port) {
return m_socket.configureRecv(hostname, port);
}
UdpComponentImpl::~UdpComponentImpl() {}
// ----------------------------------------------------------------------
// Implementations for socket read task virtual methods
// ----------------------------------------------------------------------
IpSocket& UdpComponentImpl::getSocketHandler() {
return m_socket;
}
Fw::Buffer UdpComponentImpl::getBuffer() {
return allocate_out(0, 1024);
}
void UdpComponentImpl::sendBuffer(Fw::Buffer buffer, SocketIpStatus status) {
Drv::RecvStatus recvStatus = (status == SOCK_SUCCESS) ? RecvStatus::RECV_OK : RecvStatus::RECV_ERROR;
this->recv_out(0, buffer, recvStatus);
}
void UdpComponentImpl::connected() {
if (isConnected_ready_OutputPort(0)) {
this->ready_out(0);
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
Drv::SendStatus UdpComponentImpl::send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
Drv::SocketIpStatus status = m_socket.send(fwBuffer.getData(), fwBuffer.getSize());
// Always return the buffer
deallocate_out(0, fwBuffer);
if ((status == SOCK_DISCONNECTED) || (status == SOCK_INTERRUPTED_TRY_AGAIN)) {
return SendStatus::SEND_RETRY;
} else if (status != SOCK_SUCCESS) {
return SendStatus::SEND_ERROR;
}
return SendStatus::SEND_OK;
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/Udp/Udp.hpp | // ======================================================================
// Udp.hpp
// Standardization header for Udp
// ======================================================================
#ifndef Drv_Udp_HPP
#define Drv_Udp_HPP
#include "Drv/Udp/UdpComponentImpl.hpp"
namespace Drv {
typedef UdpComponentImpl Udp;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/Udp/test/ut/UdpTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "UdpTester.hpp"
TEST(Nominal, BasicMessaging) {
Drv::UdpTester tester;
tester.test_basic_messaging();
}
TEST(Nominal, BasicReceiveThread) {
Drv::UdpTester tester;
tester.test_receive_thread();
}
TEST(Reconnect, MultiMessaging) {
Drv::UdpTester tester;
tester.test_multiple_messaging();
}
TEST(Reconnect, ReceiveThreadReconnect) {
Drv::UdpTester tester;
tester.test_advanced_reconnect();
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Drv/Udp/test/ut/UdpTester.hpp | // ======================================================================
// \title TcpClient/test/ut/Tester.hpp
// \author mstarch
// \brief hpp file for ByteStreamDriverModel 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 "UdpGTestBase.hpp"
#include "Drv/Udp/UdpComponentImpl.hpp"
#include "Drv/Ip/TcpServerSocket.hpp"
#define SEND_DATA_BUFFER_SIZE 1024
namespace Drv {
class UdpTester :
public UdpGTestBase
{
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 1000;
// 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 = 100;
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object UdpTester
//!
UdpTester();
void initSetup();
//! Destroy object UdpTester
//!
~UdpTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Test basic messaging
//!
void test_basic_messaging();
//! Test basic reconnection behavior
//!
void test_multiple_messaging();
//! Test receive via thread
//!
void test_receive_thread();
//! Test advanced (duration) reconnect
//!
void test_advanced_reconnect();
// Helpers
void test_with_loop(U32 iterations, bool recv_thread=false);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_recv
//!
void from_recv_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &recvBuffer,
const RecvStatus &recvStatus
);
//! Handler for from_ready
//!
void from_ready_handler(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_allocate
//!
Fw::Buffer from_allocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 size
);
//! Handler for from_deallocate
//!
void from_deallocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
UdpComponentImpl component;
Fw::Buffer m_data_buffer;
Fw::Buffer m_data_buffer2;
U8 m_data_storage[SEND_DATA_BUFFER_SIZE];
std::atomic<bool> m_spinner;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/Udp/test/ut/UdpTester.cpp | // ======================================================================
// \title UdpTester.cpp
// \author mstarch
// \brief cpp file for UdpTester for Udp
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "UdpTester.hpp"
#include "STest/Pick/Pick.hpp"
#include <Drv/Ip/test/ut/PortSelector.hpp>
#include <Drv/Ip/test/ut/SocketTestHelper.hpp>
#include "Os/Log.hpp"
#include <sys/socket.h>
Os::Log logger;
namespace Drv {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
void UdpTester::test_with_loop(U32 iterations, bool recv_thread) {
U8 buffer[sizeof(m_data_storage)] = {};
Drv::SocketIpStatus status1 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus status2 = Drv::SOCK_SUCCESS;
U16 port1 = Drv::Test::get_free_port();
ASSERT_NE(0, port1);
U16 port2 = Drv::Test::get_free_port();
ASSERT_NE(0, port2);
// Configure the component
this->component.configureSend("127.0.0.1", port1, 0, 100);
this->component.configureRecv("127.0.0.1", port2);
// Start up a receive thread
if (recv_thread) {
Os::TaskString name("receiver thread");
this->component.startSocketTask(name, true, Os::Task::TASK_DEFAULT, Os::Task::TASK_DEFAULT);
}
// Loop through a bunch of client disconnects
for (U32 i = 0; i < iterations; i++) {
Drv::UdpSocket udp2;
I32 size = sizeof(m_data_storage);
// Not testing with reconnect thread, we will need to open ourselves
if (not recv_thread) {
status1 = this->component.open();
} else {
EXPECT_TRUE(Drv::Test::wait_on_change(this->component.getSocketHandler(), true, SOCKET_RETRY_INTERVAL_MS/10 + 1));
}
EXPECT_TRUE(this->component.getSocketHandler().isOpened());
udp2.configureSend("127.0.0.1", port2, 0, 100);
udp2.configureRecv("127.0.0.1", port1);
status2 = udp2.open();;
EXPECT_EQ(status1, Drv::SOCK_SUCCESS);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
// If all the opens worked, then run this
if ((Drv::SOCK_SUCCESS == status1) && (Drv::SOCK_SUCCESS == status2) &&
(this->component.getSocketHandler().isOpened())) {
// Force the sockets not to hang, if at all possible
Drv::Test::force_recv_timeout(this->component.getSocketHandler());
Drv::Test::force_recv_timeout(udp2);
m_data_buffer.setSize(sizeof(m_data_storage));
Drv::Test::fill_random_buffer(m_data_buffer);
Drv::SendStatus status = invoke_to_send(0, m_data_buffer);
EXPECT_EQ(status, SendStatus::SEND_OK);
status2 = udp2.recv(buffer, size);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
EXPECT_EQ(size, m_data_buffer.getSize());
Drv::Test::validate_random_buffer(m_data_buffer, buffer);
// If receive thread is live, try the other way
if (recv_thread) {
m_spinner = false;
m_data_buffer.setSize(sizeof(m_data_storage));
udp2.send(m_data_buffer.getData(), m_data_buffer.getSize());
while (not m_spinner) {}
}
}
// Properly stop the client on the last iteration
if ((1 + i) == iterations && recv_thread) {
this->component.stopSocketTask();
this->component.joinSocketTask(nullptr);
} else {
this->component.close();
}
udp2.close();
}
ASSERT_from_ready_SIZE(iterations);
}
UdpTester ::UdpTester()
: UdpGTestBase("Tester", MAX_HISTORY_SIZE),
component("Udp"),
m_data_buffer(m_data_storage, 0), m_spinner(true) {
this->initComponents();
this->connectPorts();
::memset(m_data_storage, 0, sizeof(m_data_storage));
}
UdpTester ::~UdpTester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void UdpTester ::test_basic_messaging() {
test_with_loop(1);
}
void UdpTester ::test_multiple_messaging() {
test_with_loop(100);
}
void UdpTester ::test_receive_thread() {
test_with_loop(1, true);
}
void UdpTester ::test_advanced_reconnect() {
test_with_loop(10, true); // Up to 10 * RECONNECT_MS
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void UdpTester ::from_recv_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& recvBuffer, const RecvStatus& recvStatus) {
this->pushFromPortEntry_recv(recvBuffer, recvStatus);
// Make sure we can get to unblocking the spinner
EXPECT_EQ(m_data_buffer.getSize(), recvBuffer.getSize()) << "Invalid transmission size";
Drv::Test::validate_random_buffer(m_data_buffer, recvBuffer.getData());
m_spinner = true;
delete[] recvBuffer.getData();
}
void UdpTester ::from_ready_handler(const NATIVE_INT_TYPE portNum) {
this->pushFromPortEntry_ready();
}
Fw::Buffer UdpTester ::
from_allocate_handler(
const NATIVE_INT_TYPE portNum,
U32 size
)
{
this->pushFromPortEntry_allocate(size);
Fw::Buffer buffer(new U8[size], size);
m_data_buffer2 = buffer;
return buffer;
}
void UdpTester ::
from_deallocate_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_deallocate(fwBuffer);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxUartDriver/LinuxUartDriver.hpp | // ======================================================================
// \title LinuxUartDriverImpl.hpp
// \author tcanham
// \brief hpp file for LinuxUartDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef LinuxUartDriver_HPP
#define LinuxUartDriver_HPP
#include <Drv/LinuxUartDriver/LinuxUartDriverComponentAc.hpp>
#include <Os/Mutex.hpp>
#include <Os/Task.hpp>
#include <termios.h>
namespace Drv {
class LinuxUartDriver : public LinuxUartDriverComponentBase {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object LinuxUartDriver
//!
LinuxUartDriver(const char* const compName /*!< The component name*/
);
//! Initialize object LinuxUartDriver
//!
void init(const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Configure UART parameters
enum UartBaudRate {
BAUD_9600=9600,
BAUD_19200=19200,
BAUD_38400=38400,
BAUD_57600=57600,
BAUD_115K=115200,
BAUD_230K=230400,
#ifdef TGT_OS_TYPE_LINUX
BAUD_460K=460800,
BAUD_921K=921600,
BAUD_1000K=1000000000,
BAUD_1152K=1152000000,
BAUD_1500K=1500000000,
BAUD_2000K=2000000000,
#ifdef B2500000
BAUD_2500K=2500000000,
#endif
#ifdef B3000000
BAUD_3000K=3000000000,
#endif
#ifdef B3500000
BAUD_3500K=3500000000,
#endif
#ifdef B4000000
BAUD_4000K=4000000000
#endif
#endif
};
enum UartFlowControl { NO_FLOW, HW_FLOW };
enum UartParity { PARITY_NONE, PARITY_ODD, PARITY_EVEN };
// Open device with specified baud and flow control.
bool open(const char* const device, UartBaudRate baud, UartFlowControl fc, UartParity parity, NATIVE_INT_TYPE allocationSize);
//! start the serial poll thread.
//! buffSize is the max receive buffer size
//!
void startReadThread(NATIVE_UINT_TYPE priority = Os::Task::TASK_DEFAULT,
NATIVE_UINT_TYPE stackSize = Os::Task::TASK_DEFAULT,
NATIVE_UINT_TYPE cpuAffinity = Os::Task::TASK_DEFAULT);
//! Quit thread
void quitReadThread();
//! Join thread
Os::Task::TaskStatus join(void** value_ptr);
//! Destroy object LinuxUartDriver
//!
~LinuxUartDriver();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for serialSend
//!
Drv::SendStatus send_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer& serBuffer);
NATIVE_INT_TYPE m_fd; //!< file descriptor returned for I/O device
NATIVE_INT_TYPE m_allocationSize; //!< size of allocation request to memory manager
const char* m_device; //!< original device path
//! This method will be called by the new thread to wait for input on the serial port.
static void serialReadTaskEntry(void* ptr);
Os::Task m_readTask; //!< task instance for thread to read serial port
bool m_quitReadThread; //!< flag to quit thread
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxUartDriver/LinuxUartDriver.cpp | // ======================================================================
// \title LinuxUartDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxUartDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <unistd.h>
#include <Drv/LinuxUartDriver/LinuxUartDriver.hpp>
#include <Os/TaskString.hpp>
#include "Fw/Types/BasicTypes.hpp"
#include <fcntl.h>
#include <termios.h>
#include <cerrno>
//#include <cstdlib>
//#include <cstdio>
//#define DEBUG_PRINT(...) printf(##__VA_ARGS__); fflush(stdout)
#define DEBUG_PRINT(...)
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
LinuxUartDriver ::LinuxUartDriver(const char* const compName)
: LinuxUartDriverComponentBase(compName), m_fd(-1), m_allocationSize(-1), m_device("NOT_EXIST"), m_quitReadThread(false) {
}
void LinuxUartDriver ::init(const NATIVE_INT_TYPE instance) {
LinuxUartDriverComponentBase::init(instance);
}
bool LinuxUartDriver::open(const char* const device,
UartBaudRate baud,
UartFlowControl fc,
UartParity parity,
NATIVE_INT_TYPE allocationSize) {
FW_ASSERT(device != nullptr);
NATIVE_INT_TYPE fd = -1;
NATIVE_INT_TYPE stat = -1;
this->m_allocationSize = allocationSize;
this->m_device = device;
DEBUG_PRINT("Opening UART device %s\n", device);
/*
The O_NOCTTY flag tells UNIX that this program doesn't want to be the "controlling terminal" for that port. If you
don't specify this then any input (such as keyboard abort signals and so forth) will affect your process. Programs
like getty(1M/8) use this feature when starting the login process, but normally a user program does not want this
behavior.
*/
fd = ::open(device, O_RDWR | O_NOCTTY);
if (fd == -1) {
DEBUG_PRINT("open UART device %s failed.\n", device);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, this->m_fd, _err);
return false;
} else {
DEBUG_PRINT("Successfully opened UART device %s fd %d\n", device, fd);
}
this->m_fd = fd;
// Configure blocking reads
struct termios cfg;
stat = tcgetattr(fd, &cfg);
if (-1 == stat) {
DEBUG_PRINT("tcgetattr failed: (%d): %s\n", stat, strerror(errno));
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
} else {
DEBUG_PRINT("tcgetattr passed.\n");
}
/*
If MIN > 0 and TIME = 0, MIN sets the number of characters to receive before the read is satisfied. As TIME is
zero, the timer is not used.
If MIN = 0 and TIME > 0, TIME serves as a timeout value. The read will be satisfied if a single character is read,
or TIME is exceeded (t = TIME *0.1 s). If TIME is exceeded, no character will be returned.
If MIN > 0 and TIME > 0, TIME serves as an inter-character timer. The read will be satisfied if MIN characters are
received, or the time between two characters exceeds TIME. The timer is restarted every time a character is
received and only becomes active after the first character has been received.
If MIN = 0 and TIME = 0, read will be satisfied immediately. The number of characters currently available, or the
number of characters requested will be returned. According to Antonino (see contributions), you could issue a
fcntl(fd, F_SETFL, FNDELAY); before reading to get the same result.
*/
cfg.c_cc[VMIN] = 0;
cfg.c_cc[VTIME] = 10; // 1 sec timeout on no-data
stat = tcsetattr(fd, TCSANOW, &cfg);
if (-1 == stat) {
DEBUG_PRINT("tcsetattr failed: (%d): %s\n", stat, strerror(errno));
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
} else {
DEBUG_PRINT("tcsetattr passed.\n");
}
// Set flow control
if (fc == HW_FLOW) {
struct termios t;
stat = tcgetattr(fd, &t);
if (-1 == stat) {
DEBUG_PRINT("tcgetattr UART fd %d failed\n", fd);
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
}
// modify flow control flags
t.c_cflag |= CRTSCTS;
stat = tcsetattr(fd, TCSANOW, &t);
if (-1 == stat) {
DEBUG_PRINT("tcsetattr UART fd %d failed\n", fd);
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
}
}
NATIVE_INT_TYPE relayRate = B0;
switch (baud) {
case BAUD_9600:
relayRate = B9600;
break;
case BAUD_19200:
relayRate = B19200;
break;
case BAUD_38400:
relayRate = B38400;
break;
case BAUD_57600:
relayRate = B57600;
break;
case BAUD_115K:
relayRate = B115200;
break;
case BAUD_230K:
relayRate = B230400;
break;
#if defined TGT_OS_TYPE_LINUX
case BAUD_460K:
relayRate = B460800;
break;
case BAUD_921K:
relayRate = B921600;
break;
case BAUD_1000K:
relayRate = B1000000;
break;
case BAUD_1152K:
relayRate = B1152000;
break;
case BAUD_1500K:
relayRate = B1500000;
break;
case BAUD_2000K:
relayRate = B2000000;
break;
#ifdef B2500000
case BAUD_2500K:
relayRate = B2500000;
break;
#endif
#ifdef B3000000
case BAUD_3000K:
relayRate = B3000000;
break;
#endif
#ifdef B3500000
case BAUD_3500K:
relayRate = B3500000;
break;
#endif
#ifdef B4000000
case BAUD_4000K:
relayRate = B4000000;
break;
#endif
#endif
default:
FW_ASSERT(0, baud);
break;
}
struct termios newtio;
stat = tcgetattr(fd, &newtio);
if (-1 == stat) {
DEBUG_PRINT("tcgetattr UART fd %d failed\n", fd);
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
}
// CS8 = 8 data bits, CLOCAL = Local line, CREAD = Enable Receiver
/*
Even parity (7E1):
options.c_cflag |= PARENB
options.c_cflag &= ~PARODD
options.c_cflag &= ~CSTOPB
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
Odd parity (7O1):
options.c_cflag |= PARENB
options.c_cflag |= PARODD
options.c_cflag &= ~CSTOPB
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS7;
*/
newtio.c_cflag |= CS8 | CLOCAL | CREAD;
switch (parity) {
case PARITY_ODD:
newtio.c_cflag |= (PARENB | PARODD);
break;
case PARITY_EVEN:
newtio.c_cflag |= PARENB;
break;
case PARITY_NONE:
newtio.c_cflag &= ~PARENB;
break;
default:
FW_ASSERT(0, parity);
break;
}
// Set baud rate:
stat = cfsetispeed(&newtio, relayRate);
if (stat) {
DEBUG_PRINT("cfsetispeed failed\n");
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
}
stat = cfsetospeed(&newtio, relayRate);
if (stat) {
DEBUG_PRINT("cfsetospeed failed\n");
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
}
// Raw output:
newtio.c_oflag = 0;
// set input mode (non-canonical, no echo,...)
newtio.c_lflag = 0;
newtio.c_iflag = INPCK;
// Flush old data:
(void)tcflush(fd, TCIFLUSH);
// Set attributes:
stat = tcsetattr(fd, TCSANOW, &newtio);
if (-1 == stat) {
DEBUG_PRINT("tcsetattr UART fd %d failed\n", fd);
close(fd);
Fw::LogStringArg _arg = device;
Fw::LogStringArg _err = strerror(errno);
this->log_WARNING_HI_OpenError(_arg, fd, _err);
return false;
}
// All done!
Fw::LogStringArg _arg = device;
this->log_ACTIVITY_HI_PortOpened(_arg);
if (this->isConnected_ready_OutputPort(0)) {
this->ready_out(0); // Indicate the driver is connected
}
return true;
}
LinuxUartDriver ::~LinuxUartDriver() {
if (this->m_fd != -1) {
DEBUG_PRINT("Closing UART device %d\n", this->m_fd);
(void)close(this->m_fd);
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
Drv::SendStatus LinuxUartDriver ::send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& serBuffer) {
Drv::SendStatus status = Drv::SendStatus::SEND_OK;
if (this->m_fd == -1 || serBuffer.getData() == nullptr || serBuffer.getSize() == 0) {
status = Drv::SendStatus::SEND_ERROR;
} else {
unsigned char *data = serBuffer.getData();
NATIVE_INT_TYPE xferSize = serBuffer.getSize();
NATIVE_INT_TYPE stat = ::write(this->m_fd, data, xferSize);
if (-1 == stat || stat != xferSize) {
Fw::LogStringArg _arg = this->m_device;
this->log_WARNING_HI_WriteError(_arg, stat);
status = Drv::SendStatus::SEND_ERROR;
}
}
// Deallocate when necessary
if (isConnected_deallocate_OutputPort(0)) {
deallocate_out(0, serBuffer);
}
return status;
}
void LinuxUartDriver ::serialReadTaskEntry(void* ptr) {
FW_ASSERT(ptr != nullptr);
Drv::RecvStatus status = RecvStatus::RECV_ERROR; // added by m.chase 03.06.2017
LinuxUartDriver* comp = reinterpret_cast<LinuxUartDriver*>(ptr);
while (!comp->m_quitReadThread) {
Fw::Buffer buff = comp->allocate_out(0, comp->m_allocationSize);
// On failed allocation, error and deallocate
if (buff.getData() == nullptr) {
Fw::LogStringArg _arg = comp->m_device;
comp->log_WARNING_HI_NoBuffers(_arg);
status = RecvStatus::RECV_ERROR;
comp->recv_out(0, buff, status);
// to avoid spinning, wait 50 ms
Os::Task::delay(50);
continue;
}
// timespec stime;
// (void)clock_gettime(CLOCK_REALTIME,&stime);
// DEBUG_PRINT("<<< Calling dsp_relay_uart_relay_read() at %d %d\n", stime.tv_sec, stime.tv_nsec);
int stat = 0;
// Read until something is received or an error occurs. Only loop when
// stat == 0 as this is the timeout condition and the read should spin
while ((stat == 0) && !comp->m_quitReadThread) {
stat = ::read(comp->m_fd, buff.getData(), buff.getSize());
}
buff.setSize(0);
// On error stat (-1) must mark the read as error
// On normal stat (>0) pass a recv ok
// On timeout stat (0) and m_quitReadThread, error to return the buffer
if (stat == -1) {
Fw::LogStringArg _arg = comp->m_device;
comp->log_WARNING_HI_ReadError(_arg, stat);
status = RecvStatus::RECV_ERROR;
} else if (stat > 0) {
buff.setSize(stat);
status = RecvStatus::RECV_OK; // added by m.chase 03.06.2017
} else {
status = RecvStatus::RECV_ERROR; // Simply to return the buffer
}
comp->recv_out(0, buff, status); // added by m.chase 03.06.2017
}
}
void LinuxUartDriver ::startReadThread(NATIVE_UINT_TYPE priority,
NATIVE_UINT_TYPE stackSize,
NATIVE_UINT_TYPE cpuAffinity) {
Os::TaskString task("SerReader");
Os::Task::TaskStatus stat =
this->m_readTask.start(task, serialReadTaskEntry, this, priority, stackSize, cpuAffinity);
FW_ASSERT(stat == Os::Task::TASK_OK, stat);
}
void LinuxUartDriver ::quitReadThread() {
this->m_quitReadThread = true;
}
Os::Task::TaskStatus LinuxUartDriver ::join(void** value_ptr) {
return m_readTask.join(value_ptr);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxI2cDriver/LinuxI2cDriver.cpp | // ======================================================================
// \title LinuxI2cDriverComponentImpl.cpp
// \author tcanham
// \brief cpp file for LinuxI2cDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Fw/Types/Assert.hpp"
#include <FpConfig.hpp>
#include <Drv/LinuxI2cDriver/LinuxI2cDriver.hpp>
#include <Fw/Logger/Logger.hpp>
#include <unistd.h> // required for I2C device access
#include <fcntl.h> // required for I2C device configuration
#include <sys/ioctl.h> // required for I2C device usage
#include <linux/i2c.h> // required for struct / constant definitions
#include <linux/i2c-dev.h> // required for constant definitions
#include <cerrno>
#define DEBUG_PRINT 0
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
LinuxI2cDriver ::
LinuxI2cDriver(
const char *const compName
) : LinuxI2cDriverComponentBase(compName),
m_fd(-1)
{
}
void LinuxI2cDriver ::
init(
const NATIVE_INT_TYPE instance
)
{
LinuxI2cDriverComponentBase::init(instance);
}
LinuxI2cDriver::
~LinuxI2cDriver()
{
if (-1 != this->m_fd) { // check if file is open
::close(this->m_fd);
}
}
bool LinuxI2cDriver::open(const char* device) {
FW_ASSERT(device);
this->m_fd = ::open(device, O_RDWR);
return (-1 != this->m_fd);
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
// Note this port handler is guarded, so we can make the ioctl call
Drv::I2cStatus LinuxI2cDriver ::
write_handler(
const NATIVE_INT_TYPE portNum,
U32 addr,
Fw::Buffer &serBuffer
)
{
// Make sure file has been opened
if (-1 == this->m_fd) {
return I2cStatus::I2C_OPEN_ERR;
}
#if DEBUG_PRINT
Fw::Logger::logMsg("I2c addr: 0x%02X\n",addr);
for (U32 byte = 0; byte < serBuffer.getSize(); byte++) {
Fw::Logger::logMsg("0x%02X ",serBuffer.getData()[byte]);
}
Fw::Logger::logMsg("\n");
#endif
// select slave address
int stat = ioctl(this->m_fd, I2C_SLAVE, addr);
if (stat == -1) {
#if DEBUG_PRINT
Fw::Logger::logMsg("Status: %d Errno: %d\n", stat, errno);
#endif
return I2cStatus::I2C_ADDRESS_ERR;
}
// make sure it isn't a null pointer
FW_ASSERT(serBuffer.getData());
// write data
stat = write(this->m_fd, serBuffer.getData(), serBuffer.getSize());
if (stat == -1) {
#if DEBUG_PRINT
Fw::Logger::logMsg("Status: %d Errno: %d\n", stat, errno);
#endif
return I2cStatus::I2C_WRITE_ERR;
}
return I2cStatus::I2C_OK;
}
Drv::I2cStatus LinuxI2cDriver ::
read_handler(
const NATIVE_INT_TYPE portNum,
U32 addr,
Fw::Buffer &serBuffer
)
{
// Make sure file has been opened
if (-1 == this->m_fd) {
return I2cStatus::I2C_OPEN_ERR;
}
#if DEBUG_PRINT
Fw::Logger::logMsg("I2c addr: 0x%02X\n",addr);
#endif
// select slave address
int stat = ioctl(this->m_fd, I2C_SLAVE, addr);
if (stat == -1) {
#if DEBUG_PRINT
Fw::Logger::logMsg("Status: %d Errno: %d\n", stat, errno);
#endif
return I2cStatus::I2C_ADDRESS_ERR;
}
// make sure it isn't a null pointer
FW_ASSERT(serBuffer.getData());
// read data
stat = read(this->m_fd, serBuffer.getData(), serBuffer.getSize());
if (stat == -1) {
#if DEBUG_PRINT
Fw::Logger::logMsg("Status: %d Errno: %d\n", stat, errno);
#endif
return I2cStatus::I2C_READ_ERR;
}
#if DEBUG_PRINT
for (U32 byte = 0; byte < serBuffer.getSize(); byte++) {
Fw::Logger::logMsg("0x%02X ",serBuffer.getData()[byte]);
}
Fw::Logger::logMsg("\n");
#endif
return I2cStatus::I2C_OK;
}
Drv::I2cStatus LinuxI2cDriver ::
writeRead_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 addr,
Fw::Buffer &writeBuffer,
Fw::Buffer &readBuffer
){
// Make sure file has been opened
if (-1 == this->m_fd) {
return I2cStatus::I2C_OPEN_ERR;
}
FW_ASSERT(-1 != this->m_fd);
// make sure they are not null pointers
FW_ASSERT(writeBuffer.getData());
FW_ASSERT(readBuffer.getData());
#if DEBUG_PRINT
Fw::Logger::logMsg("I2c addr: 0x%02X\n",addr);
#endif
struct i2c_msg rdwr_msgs[2];
// Start address
rdwr_msgs[0].addr = static_cast<U16>(addr);
rdwr_msgs[0].flags = 0; // write
rdwr_msgs[0].len = static_cast<U16>(writeBuffer.getSize());
rdwr_msgs[0].buf = writeBuffer.getData();
// Read buffer
rdwr_msgs[1].addr = static_cast<U16>(addr);
rdwr_msgs[1].flags = I2C_M_RD; // read
rdwr_msgs[1].len = static_cast<U16>(readBuffer.getSize());
rdwr_msgs[1].buf = readBuffer.getData();
struct i2c_rdwr_ioctl_data rdwr_data;
rdwr_data.msgs = rdwr_msgs;
rdwr_data.nmsgs = 2;
//Use ioctl to perform the combined write/read transaction
NATIVE_INT_TYPE stat = ioctl(this->m_fd, I2C_RDWR, &rdwr_data);
if(stat == -1){
#if DEBUG_PRINT
Fw::Logger::logMsg("Status: %d Errno: %d\n", stat, errno);
#endif
//Because we're using ioctl to perform the transaction we dont know exactly the type of error that occurred
return I2cStatus::I2C_OTHER_ERR;
}
#if DEBUG_PRINT
Fw::Logger::logMsg("Wrote:\n");
for (U32 byte = 0; byte < writeBuffer.getSize(); byte++) {
Fw::Logger::logMsg("0x%02X ",writeBuffer.getData()[byte]);
}
Fw::Logger::logMsg("\n");
Fw::Logger::logMsg("Read:\n");
for (U32 byte = 0; byte < readBuffer.getSize(); byte++) {
Fw::Logger::logMsg("0x%02X ",readBuffer.getData()[byte]);
}
Fw::Logger::logMsg("\n");
#endif
return I2cStatus::I2C_OK;
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxI2cDriver/LinuxI2cDriver.hpp | // ======================================================================
// \title LinuxI2cDriver.hpp
// \author tcanham
// \brief hpp file for LinuxI2cDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef LinuxI2cDriver_HPP
#define LinuxI2cDriver_HPP
#include "Drv/LinuxI2cDriver/LinuxI2cDriverComponentAc.hpp"
namespace Drv {
class LinuxI2cDriver :
public LinuxI2cDriverComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object LinuxI2cDriver
//!
LinuxI2cDriver(const char *const compName);
//! Initialize object LinuxI2cDriver
//!
void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
bool open(const char* device);
//! Destroy object LinuxI2cDriver
//!
~LinuxI2cDriver();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for write
//!
I2cStatus write_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 addr,
Fw::Buffer &serBuffer
);
//! Handler implementation for read
//!
I2cStatus read_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 addr,
Fw::Buffer &serBuffer
);
//! Handler implementation for writeRead
//!
I2cStatus writeRead_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 addr,
Fw::Buffer &writeBuffer,
Fw::Buffer &readBuffer
);
// Prevent unused field error when using stub
#ifndef STUBBED_LINUX_I2C_DRIVER
NATIVE_INT_TYPE m_fd; //!< i2c file descriptor
#endif
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxI2cDriver/LinuxI2cDriverStub.cpp | // ======================================================================
// \title LinuxI2cDriver.cpp
// \author tcanham
// \brief cpp file for LinuxI2cDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Fw/Types/Assert.hpp"
#include <FpConfig.hpp>
#include <Drv/LinuxI2cDriver/LinuxI2cDriver.hpp>
#define DEBUG_PRINT 0
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
LinuxI2cDriver ::LinuxI2cDriver(
const char *const compName
) : LinuxI2cDriverComponentBase(compName)
{
}
void LinuxI2cDriver ::
init(
const NATIVE_INT_TYPE instance
)
{
LinuxI2cDriverComponentBase::init(instance);
}
LinuxI2cDriver ::
~LinuxI2cDriver()
{
}
bool LinuxI2cDriver::open(const char* device) {
return true;
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
// Note this port handler is guarded, so we can make the ioctl call
I2cStatus LinuxI2cDriver ::
write_handler(
const NATIVE_INT_TYPE portNum,
U32 addr,
Fw::Buffer &serBuffer
)
{
return I2cStatus::I2C_OK;
}
Drv::I2cStatus LinuxI2cDriver ::
read_handler(
const NATIVE_INT_TYPE portNum,
U32 addr,
Fw::Buffer &serBuffer
)
{
return I2cStatus::I2C_OK;
}
Drv::I2cStatus LinuxI2cDriver ::
writeRead_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 addr,
Fw::Buffer &writeBuffer,
Fw::Buffer &readBuffer
){
return I2cStatus::I2C_OK;
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxI2cDriver/test/ut/main.cpp | #include <Fw/Types/StringUtils.hpp>
#include <LinuxI2cDriverTester.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
TEST(TestNominal,Nominal) {
Drv::LinuxI2cDriverTester tester;
}
const char* help = "[-h] -d <I2C device> -a <I2C address> <byte 0> <byte1> ... <byteN>";
int main(int argc, char* argv[]) {
int c;
U32 addr = 0;
char device[80];
device[0] = 0;
while ((c = getopt (argc, argv, "hd:a:")) != -1) {
switch (c) {
case 'h':
printf("test_ut %s\n",argv[0],help);
return 0;
case 'a':
addr = strtoul(optarg,0,0);
break;
case 'd':
(void) Fw::StringUtils::string_copy(device, optarg, sizeof(device));
break;
default:
printf("test_ut %s\n",argv[0],help);
return -1;
}
}
printf("Address: %d (0x%02X) Device: %s\n",addr,addr,device);
U8 data[12];
for (int i = optind; i < argc; i++) {
data[optind-i] = strtoul(argv[i],0,0);
printf("Data: %s 0x%02X\n",argv[i],data[optind-i]);
}
Drv::LinuxI2cDriverTester tester;
tester.open(device);
tester.sendData(addr,data,argc-optind);
return 0;
}
| cpp |
fprime | data/projects/fprime/Drv/LinuxI2cDriver/test/ut/LinuxI2cDriverTester.cpp | // ======================================================================
// \title LinuxI2cDriver.hpp
// \author tcanham
// \brief cpp file for LinuxI2cDriver test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "LinuxI2cDriverTester.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
namespace Drv {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
LinuxI2cDriverTester ::
LinuxI2cDriverTester() :
LinuxI2cDriverGTestBase("Tester", MAX_HISTORY_SIZE),
component("LinuxI2cDriver")
{
this->initComponents();
this->connectPorts();
}
LinuxI2cDriverTester ::
~LinuxI2cDriverTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void LinuxI2cDriverTester ::
sendData(U32 addr, U8* data, NATIVE_INT_TYPE size)
{
Fw::Buffer dataBuff;
dataBuff.setdata(static_cast<POINTER_CAST>(data));
dataBuff.setsize(size);
this->invoke_to_write(0,addr,dataBuff);
}
void LinuxI2cDriverTester::open(const char* device) {
this->component.open(device);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void LinuxI2cDriverTester ::
connectPorts()
{
// write
this->connect_to_write(
0,
this->component.get_write_InputPort(0)
);
}
void LinuxI2cDriverTester ::
initComponents()
{
this->init();
this->component.init(
INSTANCE
);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxI2cDriver/test/ut/LinuxI2cDriverTester.hpp | // ======================================================================
// \title LinuxI2cDriver/test/ut/Tester.hpp
// \author tcanham
// \brief hpp file for LinuxI2cDriver 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 "Drv/LinuxI2cDriver/LinuxI2cDriver.hpp"
#include "LinuxI2cDriverGTestBase.hpp"
namespace Drv {
class LinuxI2cDriverTester :
public LinuxI2cDriverGTestBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object LinuxI2cDriverTester
//!
LinuxI2cDriverTester();
//! Destroy object LinuxI2cDriverTester
//!
~LinuxI2cDriverTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! To do
//!
void sendData(U32 addr, U8* data, NATIVE_INT_TYPE size);
void open(const char* device);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
LinuxI2cDriver component;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/BlockDriver/BlockDriverImpl.cpp | #include <Drv/BlockDriver/BlockDriverImpl.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
namespace Drv {
BlockDriverImpl::BlockDriverImpl(const char* compName) :
BlockDriverComponentBase(compName), m_cycles(0)
{
}
void BlockDriverImpl::init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instanceId) {
BlockDriverComponentBase::init(queueDepth, instanceId);
}
BlockDriverImpl::~BlockDriverImpl() {
}
void BlockDriverImpl::InterruptReport_internalInterfaceHandler(U32 ip) {
// get time
Svc::TimerVal timer;
timer.take();
// call output timing signal
this->CycleOut_out(0,timer);
// increment cycles and write channel
this->tlmWrite_BD_Cycles(this->m_cycles);
this->m_cycles++;
}
void BlockDriverImpl::BufferIn_handler(NATIVE_INT_TYPE portNum, Drv::DataBuffer& buffer) {
// just a pass-through
this->BufferOut_out(0,buffer);
}
void BlockDriverImpl::Sched_handler(NATIVE_INT_TYPE portNum, U32 context) {
}
void BlockDriverImpl::callIsr() {
s_driverISR(this);
}
void BlockDriverImpl::s_driverISR(void* arg) {
FW_ASSERT(arg);
// cast argument to component instance
BlockDriverImpl* compPtr = static_cast<BlockDriverImpl*>(arg);
compPtr->InterruptReport_internalInterfaceHandler(0);
}
void BlockDriverImpl::PingIn_handler(
const NATIVE_INT_TYPE portNum,
U32 key
)
{
// call ping output port
this->PingOut_out(0,key);
}
}
| cpp |
fprime | data/projects/fprime/Drv/BlockDriver/BlockDriver.hpp | // ======================================================================
// BlockDriver.hpp
// Standardization header for BlockDriver
// ======================================================================
#ifndef Drv_BlockDriver_HPP
#define Drv_BlockDriver_HPP
#include "Drv/BlockDriver/BlockDriverImpl.hpp"
namespace Drv {
typedef BlockDriverImpl BlockDriver;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/BlockDriver/BlockDriverImpl.hpp | #ifndef DRV_BLOCK_DRIVER_IMPL_HPP
#define DRV_BLOCK_DRIVER_IMPL_HPP
#include <Drv/BlockDriver/BlockDriverComponentAc.hpp>
namespace Drv {
class BlockDriverImpl : public BlockDriverComponentBase {
public:
// Only called by derived class
BlockDriverImpl(const char* compName);
void init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instanceId = 0);
~BlockDriverImpl();
// a little hack to get the reference running
void callIsr();
private:
// downcalls for input ports
void InterruptReport_internalInterfaceHandler(U32 ip);
void BufferIn_handler(NATIVE_INT_TYPE portNum, Drv::DataBuffer& buffer);
void Sched_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*/
);
// static ISR callback
static void s_driverISR(void* arg);
// cycle count
U32 m_cycles;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.cpp | // ======================================================================
// \title LinuxGpioDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxGpioDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp>
#include <FpConfig.hpp>
#include <Os/TaskString.hpp>
// TODO make proper static constants for these
#define SYSFS_GPIO_DIR "/sys/class/gpio"
#define MAX_BUF 64
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
//#define DEBUG_PRINT(...) printf(##__VA_ARGS__); fflush(stdout)
#define DEBUG_PRINT(...)
namespace Drv {
// Code modified from https://developer.ridgerun.com/wiki/index.php?title=Gpio-int-test.c
/****************************************************************
* gpio_export
****************************************************************/
int gpio_export(unsigned int gpio)
{
int fd, len;
char buf[MAX_BUF];
fd = open(SYSFS_GPIO_DIR "/export", O_WRONLY);
if (fd < 0) {
DEBUG_PRINT("gpio/export error!\n");
return -1;
}
// TODO check value of len
len = snprintf(buf, sizeof(buf), "%u", gpio);
if(write(fd, buf, len) != len) {
(void) close(fd);
DEBUG_PRINT("gpio/export error!\n");
return -1;
}
(void) close(fd);
/* NOTE(mereweth) - this is to allow systemd udev to make
* necessary filesystem changes after exporting
*/
usleep(100 * 1000);
return 0;
}
/****************************************************************
* gpio_unexport
****************************************************************/
int gpio_unexport(unsigned int gpio)
{
int fd, len;
char buf[MAX_BUF];
fd = open(SYSFS_GPIO_DIR "/unexport", O_WRONLY);
if (fd < 0) {
DEBUG_PRINT("gpio/unexport error!\n");
return -1;
}
// TODO check value of len
len = snprintf(buf, sizeof(buf), "%u", gpio);
if(write(fd, buf, len) != len) {
(void) close(fd);
DEBUG_PRINT("gpio/unexport error!\n");
return -1;
}
(void) close(fd);
/* NOTE(mereweth) - this is to allow systemd udev to make
* necessary filesystem changes after unexporting
*/
usleep(100 * 1000);
return 0;
}
/****************************************************************
* gpio_set_dir
****************************************************************/
int gpio_set_dir(unsigned int gpio, unsigned int out_flag)
{
int fd, len;
char buf[MAX_BUF];
len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%u/direction", gpio);
FW_ASSERT(len > 0, len);
fd = open(buf, O_WRONLY);
if (fd < 0) {
DEBUG_PRINT("gpio/direction error!\n");
return -1;
}
const char *dir = out_flag ? "out" : "in";
len = strlen(dir);
if (write(fd, dir, len) != len) {
(void) close(fd);
DEBUG_PRINT("gpio/direction error!\n");
return -1;
}
(void) close(fd);
return 0;
}
/****************************************************************
* gpio_set_value
****************************************************************/
int gpio_set_value(int fd, unsigned int value)
{
FW_ASSERT(fd != -1);
// TODO make value an enum or check its value
const char *val = value ? "1" : "0";
const int len = 1;
if(write(fd, val, len) != len) {
DEBUG_PRINT("gpio/set value error!\n");
return -1;
}
DEBUG_PRINT("GPIO fd %d value %d written\n",fd,value);
return 0;
}
/****************************************************************
* gpio_get_value
****************************************************************/
int gpio_get_value(int fd, unsigned int *value)
{
char ch = '0';
FW_ASSERT(fd != -1);
NATIVE_INT_TYPE stat1 = lseek(fd, 0, SEEK_SET); // Must seek back to the starting
NATIVE_INT_TYPE stat2 = read(fd, &ch, 1);
if (stat1 == -1 || stat2 != 1) {
DEBUG_PRINT("GPIO read failure: %d %d!\n",stat1,stat2);
return -1;
}
// TODO could use atoi instead to get the value
if (ch != '0') {
*value = 1;
} else {
*value = 0;
}
DEBUG_PRINT("GPIO fd %d value %c read\n",fd,ch);
return 0;
}
/****************************************************************
* gpio_set_edge
****************************************************************/
int gpio_set_edge(unsigned int gpio, const char *edge)
{
int fd, len;
char buf[MAX_BUF];
FW_ASSERT(edge != nullptr);
// TODO check that edge has correct values of "none", "rising", or "falling"
len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%u/edge", gpio);
FW_ASSERT(len > 0, len);
fd = open(buf, O_WRONLY);
if (fd < 0) {
DEBUG_PRINT("gpio/set-edge error!\n");
return -1;
}
len = strlen(edge) + 1;
if(write(fd, edge, len) != len) {
(void) close(fd);
DEBUG_PRINT("gpio/set-edge error!\n");
return -1;
}
(void) close(fd);
return 0;
}
/****************************************************************
* gpio_fd_open
****************************************************************/
int gpio_fd_open(unsigned int gpio)
{
int fd, len;
char buf[MAX_BUF];
len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%u/value", gpio);
FW_ASSERT(len > 0, len);
fd = open(buf, O_RDWR | O_NONBLOCK );
if (fd < 0) {
DEBUG_PRINT("gpio/fd_open error!\n");
return -1;
}
return fd;
}
/****************************************************************
* gpio_fd_close
****************************************************************/
int gpio_fd_close(int fd, unsigned int gpio)
{
// TODO is this needed? w/o this the edge file and others can retain the state from
// previous settings.
(void) gpio_unexport(gpio); // TODO check return value
return close(fd);
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void LinuxGpioDriverComponentImpl ::
gpioRead_handler(
const NATIVE_INT_TYPE portNum,
Fw::Logic &state
)
{
FW_ASSERT(this->m_fd != -1);
NATIVE_UINT_TYPE val;
NATIVE_INT_TYPE stat = gpio_get_value(this->m_fd, &val);
if (-1 == stat) {
this->log_WARNING_HI_GP_ReadError(this->m_gpio,stat);
return;
} else {
state = val ? Fw::Logic::HIGH : Fw::Logic::LOW;
}
}
void LinuxGpioDriverComponentImpl ::
gpioWrite_handler(
const NATIVE_INT_TYPE portNum,
const Fw::Logic& state
)
{
FW_ASSERT(this->m_fd != -1);
NATIVE_INT_TYPE stat;
stat = gpio_set_value(this->m_fd,(state == Fw::Logic::HIGH) ? 1 : 0);
if (0 != stat) {
this->log_WARNING_HI_GP_WriteError(this->m_gpio,stat);
return;
}
}
bool LinuxGpioDriverComponentImpl ::
open(NATIVE_INT_TYPE gpio, GpioDirection direction) {
// TODO check for invalid gpio?
NATIVE_INT_TYPE stat;
// Configure:
stat = gpio_export(gpio);
if (-1 == stat) {
Fw::LogStringArg arg = strerror(errno);
this->log_WARNING_HI_GP_OpenError(gpio,stat,arg);
return false;
}
stat = gpio_set_dir(gpio, direction == GPIO_OUT ? 1 : 0);
if (-1 == stat) {
Fw::LogStringArg arg = strerror(errno);
this->log_WARNING_HI_GP_OpenError(gpio,stat,arg);
return false;
}
// If needed, set edge to rising in intTaskEntry()
// Open:
this->m_fd = gpio_fd_open(gpio);
if (-1 == this->m_fd) {
Fw::LogStringArg arg = strerror(errno);
this->log_WARNING_HI_GP_OpenError(gpio,errno,arg);
} else {
this->m_gpio = gpio;
}
return true;
}
//! Entry point for task waiting for RTI
void LinuxGpioDriverComponentImpl ::
intTaskEntry(void * ptr) {
FW_ASSERT(ptr);
LinuxGpioDriverComponentImpl* compPtr = static_cast<LinuxGpioDriverComponentImpl*>(ptr);
FW_ASSERT(compPtr->m_fd != -1);
// start GPIO interrupt
NATIVE_INT_TYPE stat;
stat = gpio_set_edge(compPtr->m_gpio, "rising");
if (-1 == stat) {
compPtr->log_WARNING_HI_GP_IntStartError(compPtr->m_gpio);
return;
}
// spin waiting for interrupt
while(not compPtr->m_quitThread) {
pollfd fdset[1];
NATIVE_INT_TYPE nfds = 1;
NATIVE_INT_TYPE timeout = 10000; // Timeout of 10 seconds
memset(fdset, 0, sizeof(fdset));
fdset[0].fd = compPtr->m_fd;
fdset[0].events = POLLPRI;
stat = poll(fdset, nfds, timeout);
/*
* According to this link, poll will always have POLLERR set for the sys/class/gpio subsystem
* so can't check for it to look for error:
* http://stackoverflow.com/questions/27411013/poll-returns-both-pollpri-pollerr
*/
if (stat < 0) {
DEBUG_PRINT("stat: %d, revents: 0x%x, POLLERR: 0x%x, POLLIN: 0x%x, POLLPRI: 0x%x\n",
stat, fdset[0].revents, POLLERR, POLLIN, POLLPRI); // TODO remove
compPtr->log_WARNING_HI_GP_IntWaitError(compPtr->m_gpio);
return;
}
if (stat == 0) {
// continue to poll
DEBUG_PRINT("Krait timed out waiting for GPIO interrupt\n");
continue;
}
// Asserting that number of fds w/ revents is 1:
FW_ASSERT(stat == 1, stat); // TODO should i bother w/ this assert?
// TODO what to do if POLLPRI not set?
// TODO: if I take out the read then the poll just continually interrupts
// Read is only taking 22 usecs each time, so it is not blocking for long
if (fdset[0].revents & POLLPRI) {
char buf[MAX_BUF];
(void) lseek(fdset[0].fd, 0, SEEK_SET); // Must seek back to the starting
if(read(fdset[0].fd, buf, MAX_BUF) > 0) {
DEBUG_PRINT("\npoll() GPIO interrupt occurred w/ value: %c\n", buf[0]);
}
}
// call interrupt ports
Svc::TimerVal timerVal;
timerVal.take();
for (NATIVE_INT_TYPE port = 0; port < compPtr->getNum_intOut_OutputPorts(); port++) {
if (compPtr->isConnected_intOut_OutputPort(port)) {
compPtr->intOut_out(port,timerVal);
}
}
}
}
Os::Task::TaskStatus LinuxGpioDriverComponentImpl ::
startIntTask(NATIVE_UINT_TYPE priority, NATIVE_UINT_TYPE stackSize, NATIVE_UINT_TYPE cpuAffinity) {
Os::TaskString name;
name.format("GPINT_%s",this->getObjName()); // The task name can only be 16 chars including null
Os::Task::TaskStatus stat = this->m_intTask.start(name, LinuxGpioDriverComponentImpl::intTaskEntry, this, priority, stackSize, cpuAffinity);
if (stat != Os::Task::TASK_OK) {
DEBUG_PRINT("Task start error: %d\n",stat);
}
return stat;
}
void LinuxGpioDriverComponentImpl ::
exitThread() {
this->m_quitThread = true;
}
LinuxGpioDriverComponentImpl ::
~LinuxGpioDriverComponentImpl()
{
if (this->m_fd != -1) {
DEBUG_PRINT("Closing GPIO %d fd %d\n",this->m_gpio, this->m_fd);
(void) gpio_fd_close(this->m_fd, this->m_gpio);
}
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/LinuxGpioDriver.hpp | // ======================================================================
// LinuxGpioDriver.hpp
// Standardization header for LinuxGpioDriver
// ======================================================================
#ifndef Drv_LinuxGpioDriver_HPP
#define Drv_LinuxGpioDriver_HPP
#include "Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp"
namespace Drv {
using LinuxGpioDriver = LinuxGpioDriverComponentImpl;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/LinuxGpioDriverComponentImplCommon.cpp | // ======================================================================
// \title LinuxGpioDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxGpioDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp>
#include <FpConfig.hpp>
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
LinuxGpioDriverComponentImpl ::
LinuxGpioDriverComponentImpl(
const char *const compName
) : LinuxGpioDriverComponentBase(compName),
m_gpio(-1),
m_direction(GPIO_IN),
m_fd(-1),
m_quitThread(false)
{
}
void LinuxGpioDriverComponentImpl ::
init(
const NATIVE_INT_TYPE instance
)
{
LinuxGpioDriverComponentBase::init(instance);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp | // ======================================================================
// \title LinuxGpioDriverImpl.hpp
// \author tcanham
// \brief hpp file for LinuxGpioDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef LinuxGpioDriver_HPP
#define LinuxGpioDriver_HPP
#include "Drv/LinuxGpioDriver/LinuxGpioDriverComponentAc.hpp"
#include <Os/Task.hpp>
namespace Drv {
class LinuxGpioDriverComponentImpl :
public LinuxGpioDriverComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object LinuxGpioDriver
//!
LinuxGpioDriverComponentImpl(
const char *const compName /*!< The component name*/
);
//! Initialize object LinuxGpioDriver
//!
void init(
const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object LinuxGpioDriver
//!
~LinuxGpioDriverComponentImpl();
//! Start interrupt task
Os::Task::TaskStatus startIntTask(NATIVE_UINT_TYPE priority = Os::Task::TASK_DEFAULT,
NATIVE_UINT_TYPE stackSize = Os::Task::TASK_DEFAULT,
NATIVE_UINT_TYPE cpuAffinity = Os::Task::TASK_DEFAULT);
//! configure GPIO
enum GpioDirection {
GPIO_IN, //!< input
GPIO_OUT, //!< output
GPIO_INT //!< interrupt
};
//! open GPIO
bool open(NATIVE_INT_TYPE gpio, GpioDirection direction);
//! exit thread
void exitThread();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for gpioRead
//!
void gpioRead_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Logic &state
);
//! Handler implementation for gpioWrite
//!
void gpioWrite_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
const Fw::Logic& state
);
//! keep GPIO ID
NATIVE_INT_TYPE m_gpio;
//! device direction
GpioDirection m_direction;
//! Entry point for task waiting for interrupt
static void intTaskEntry(void * ptr);
//! Task object for RTI task
Os::Task m_intTask;
//! file descriptor for GPIO
NATIVE_INT_TYPE m_fd;
//! flag to quit thread
bool m_quitThread;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/LinuxGpioDriverComponentImplStub.cpp | // ======================================================================
// \title LinuxGpioDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxGpioDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp>
#include <FpConfig.hpp>
namespace Drv {
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void LinuxGpioDriverComponentImpl ::
gpioRead_handler(
const NATIVE_INT_TYPE portNum,
Fw::Logic &state
)
{
// TODO
}
void LinuxGpioDriverComponentImpl ::
gpioWrite_handler(
const NATIVE_INT_TYPE portNum,
const Fw::Logic& state
)
{
// TODO
}
bool LinuxGpioDriverComponentImpl ::
open(NATIVE_INT_TYPE gpio, GpioDirection direction) {
return false;
}
Os::Task::TaskStatus LinuxGpioDriverComponentImpl ::
startIntTask(NATIVE_UINT_TYPE priority, NATIVE_UINT_TYPE stackSize, NATIVE_UINT_TYPE cpuAffinity) {
return Os::Task::TASK_OK;
}
LinuxGpioDriverComponentImpl ::
~LinuxGpioDriverComponentImpl()
{
}
void LinuxGpioDriverComponentImpl ::
exitThread() {
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/test/ut/main.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include "LinuxGpioDriverTester.hpp"
#include <cstdlib>
// TEST(Test, NominalTlm) {
// Svc::LinuxGpioDriverTester tester;
// tester.nominalTlm();
// }
void usage(char* prog) {
printf("Usage: %s <gpio> <mode, 0=input, 1=output, 2=interrupt>\n",prog);
}
int main(int argc, char **argv) {
if (argc != 3) {
usage(argv[0]);
return -1;
}
Drv::LinuxGpioDriverTester tester;
int gpio = atoi(argv[1]);
int output = atoi(argv[2]);
if (0 == output) {
printf("Testing GPIO %d input\n",gpio);
tester.testInput(gpio,10);
}
else if (1 == output){
printf("Testing GPIO %d output\n",gpio);
tester.testOutput(gpio,10);
} else if (2 == output) {
printf("Testing GPIO %d interrupts\n",gpio);
tester.testInterrupt(gpio,10);
} else {
usage(argv[0]);
}
}
| cpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/test/ut/LinuxGpioDriverTester.cpp | // ======================================================================
// \title LinuxGpioDriver.hpp
// \author tcanham
// \brief cpp file for LinuxGpioDriver test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "LinuxGpioDriverTester.hpp"
#include <Os/IntervalTimer.hpp>
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
namespace Drv {
Os::IntervalTimer timer;
U32 timerDiffList[100];
U32 timerDiffIdx = 0;
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
LinuxGpioDriverTester ::
LinuxGpioDriverTester() :
LinuxGpioDriverTesterBase("Tester", MAX_HISTORY_SIZE),
component("GP")
,m_cycles(0)
,m_currCycle(0)
{
this->initComponents();
this->connectPorts();
}
LinuxGpioDriverTester ::
~LinuxGpioDriverTester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void LinuxGpioDriverTester ::
testInterrupt(NATIVE_INT_TYPE gpio, NATIVE_INT_TYPE cycles)
{
// initialize the driver
if (not this->component.open(gpio,LinuxGpioDriverComponentImpl::GPIO_INT)) {
return;
}
this->m_cycles = cycles;
this->m_currCycle = 0;
// start the thread
Os::Task::TaskStatus stat = this->component.startIntTask(99);
if (stat != Os::Task::TASK_OK) {
return;
}
// delay waiting for cycles to complete
NATIVE_INT_TYPE maxCycles = 10;
while (true) {
Os::Task::delay(500);
bool state;
//this->invoke_to_gpioRead(0,state);
printf("Wait %d %s\n",this->m_currCycle,state?"ON":"OFF");
if ((this->m_currCycle >= this->m_cycles) or (maxCycles-- == 0)) {
#if 0
printf("Interrupt cycle time diffs: \n");
for (U32 i = 0; i < timerDiffIdx; ++i) {
printf("Diff number %d: %d\n",i,timerDiffList[i]);
}
#endif
this->component.exitThread();
Os::Task::delay(500);
return;
}
}
}
void LinuxGpioDriverTester ::
testOutput(NATIVE_INT_TYPE gpio, NATIVE_INT_TYPE cycles) {
this->component.open(gpio,LinuxGpioDriverComponentImpl::GPIO_OUT);
bool state = true;
for (NATIVE_INT_TYPE cycle = 0; cycle < cycles; cycle++) {
printf("Cycle: %d\n",cycle);
this->invoke_to_gpioWrite(0,state);
if (state) {
state = false;
} else {
state = true;
}
Os::Task::delay(500);
}
}
void LinuxGpioDriverTester ::
testInput(NATIVE_INT_TYPE gpio, NATIVE_INT_TYPE cycles) {
this->component.open(gpio,LinuxGpioDriverComponentImpl::GPIO_IN);
bool state = true;
for (NATIVE_INT_TYPE cycle = 0; cycle < cycles; cycle++) {
printf("Cycle: %d\n",cycle);
this->invoke_to_gpioRead(0,state);
if (state) {
printf("1\n");
} else {
printf("0\n");
}
Os::Task::delay(500);
}
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void LinuxGpioDriverTester ::
from_intOut_handler(
const NATIVE_INT_TYPE portNum,
Svc::TimerVal &cycleStart
)
{
timer.stop();
U32 timeDiff = timer.getDiffUsec();
timerDiffList[timerDiffIdx++] = timeDiff;
timer.start();
//printf("Cycle %d, time diff (usec): %d\n",this->m_currCycle,timeDiff);
this->m_currCycle++;
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void LinuxGpioDriverTester ::
connectPorts()
{
// gpioRead
this->connect_to_gpioRead(
0,
this->component.get_gpioRead_InputPort(0)
);
// gpioWrite
this->connect_to_gpioWrite(
0,
this->component.get_gpioWrite_InputPort(0)
);
// intOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_intOut_OutputPort(
i,
this->get_from_intOut(i)
);
}
// Time
this->component.set_Time_OutputPort(
0,
this->get_from_Time(0)
);
// Log
this->component.set_Log_OutputPort(
0,
this->get_from_Log(0)
);
// LogText
this->component.set_LogText_OutputPort(
0,
this->get_from_LogText(0)
);
}
void LinuxGpioDriverTester ::
initComponents()
{
this->init();
this->component.init(
INSTANCE
);
}
void LinuxGpioDriverTester::textLogIn(
const FwEventIdType id, //!< The event ID
Fw::Time& timeTag, //!< The time
const Fw::TextLogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
) {
TextLogEntry e = { id, timeTag, severity, text };
printTextLogHistoryEntry(e,stdout);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxGpioDriver/test/ut/LinuxGpioDriverTester.hpp | // ======================================================================
// \title LinuxGpioDriver/test/ut/Tester.hpp
// \author tcanham
// \brief hpp file for LinuxGpioDriver 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 "TesterBase.hpp"
#include "Drv/LinuxGpioDriver/LinuxGpioDriverComponentImpl.hpp"
namespace Drv {
class LinuxGpioDriverTester :
public LinuxGpioDriverTesterBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object LinuxGpioDriverTester
//!
LinuxGpioDriverTester();
//! Destroy object LinuxGpioDriverTester
//!
~LinuxGpioDriverTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! Interrupt testing
//!
void testInterrupt(NATIVE_INT_TYPE gpio, NATIVE_INT_TYPE cycles);
//! Test output
void testOutput(NATIVE_INT_TYPE gpio, NATIVE_INT_TYPE cycles);
//! Test input
void testInput(NATIVE_INT_TYPE gpio, NATIVE_INT_TYPE cycles);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_intOut
//!
void from_intOut_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Svc::TimerVal &cycleStart /*!< Cycle start timer value*/
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
LinuxGpioDriverComponentImpl component;
void textLogIn(
const FwEventIdType id, //!< The event ID
Fw::Time& timeTag, //!< The time
const Fw::TextLogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
);
NATIVE_INT_TYPE m_cycles; //!< cycles to wait
NATIVE_INT_TYPE m_currCycle; //!< curr cycle in test
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/LinuxSpiDriver.hpp | // ======================================================================
// LinuxSpiDriver.hpp
// Standardization header for LinuxSpiDriver
// ======================================================================
#ifndef Drv_LinuxSpiDriver_HPP
#define Drv_LinuxSpiDriver_HPP
#include "Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp"
namespace Drv {
using LinuxSpiDriver = LinuxSpiDriverComponentImpl;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp | // ======================================================================
// \title LinuxSpiDriverImpl.hpp
// \author tcanham
// \brief hpp file for LinuxSpiDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef LinuxSpiDriver_HPP
#define LinuxSpiDriver_HPP
#include "Drv/LinuxSpiDriver/LinuxSpiDriverComponentAc.hpp"
namespace Drv {
/**
* This was taken from the dspal_tester example
*
* Supported SPI frequency to talk to MPU9x50 slave device
* MPU9x50 SPI interface supports upto 20MHz frequency. However 20MHz is not
* reliable in our test and corrupted data is observed.
*/
enum SpiFrequency
{
SPI_FREQUENCY_1MHZ = 1000000UL,
SPI_FREQUENCY_5MHZ = 5000000UL,
SPI_FREQUENCY_10MHZ = 10000000UL,
SPI_FREQUENCY_15MHZ = 15000000UL,
SPI_FREQUENCY_20MHZ = 20000000UL,
};
/**
* SPI Mode Select
*
* Defines the SPI Clock Polarity and Phase for each SPI Transaction.
*
* SPI Clock Polarity(CPOL): Defines clock polarity as idle low (CPOL = 0) or idle high(CPOL = 1)
* SPI Clock Phase(CPHA): Defines if data is shifted out on the rising clock edge and sampled
* on the falling clock edge(CPHA = 0) or if data is shifted out on the
* falling clock edge and sampled on the rising clock edge(CPHA=1)
*
*/
enum SpiMode
{
SPI_MODE_CPOL_LOW_CPHA_LOW, ///< (CPOL = 0, CPHA = 0)
SPI_MODE_CPOL_LOW_CPHA_HIGH,///< (CPOL = 0, CPHA = 1)
SPI_MODE_CPOL_HIGH_CPHA_LOW,///< (CPOL = 1, CPHA = 0)
SPI_MODE_CPOL_HIGH_CPHA_HIGH,///< (CPOL = 1, CPHA = 1)
};
class LinuxSpiDriverComponentImpl: public LinuxSpiDriverComponentBase {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object LinuxSpiDriver
//!
LinuxSpiDriverComponentImpl(
const char * const compName /*!< The component name*/
);
//! Initialize object LinuxSpiDriver
//!
void init(const NATIVE_INT_TYPE instance = 0 /*!< The instance number*/
);
//! Destroy object LinuxSpiDriver
//!
~LinuxSpiDriverComponentImpl();
//! Open device
bool open(NATIVE_INT_TYPE device,
NATIVE_INT_TYPE select,
SpiFrequency clock,
SpiMode spiMode = SpiMode::SPI_MODE_CPOL_LOW_CPHA_LOW);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for SpiReadWrite
//!
void SpiReadWrite_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &WriteBuffer, Fw::Buffer &readBuffer);
NATIVE_INT_TYPE m_fd;
NATIVE_INT_TYPE m_device;
NATIVE_INT_TYPE m_select;
U32 m_bytes;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.cpp | // ======================================================================
// \title LinuxSpiDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxSpiDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdint>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#include <cerrno>
//#define DEBUG_PRINT(...) printf(##__VA_ARGS__); fflush(stdout)
#define DEBUG_PRINT(...)
namespace Drv {
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void LinuxSpiDriverComponentImpl::SpiReadWrite_handler(
const NATIVE_INT_TYPE portNum, Fw::Buffer &writeBuffer,
Fw::Buffer &readBuffer) {
if (this->m_fd == -1) {
return;
}
DEBUG_PRINT("Writing %d bytes to SPI\n",writeBuffer.getSize());
spi_ioc_transfer tr;
// Zero for unused fields:
memset(&tr, 0, sizeof(tr));
tr.tx_buf = reinterpret_cast<__u64>(writeBuffer.getData());
tr.rx_buf = reinterpret_cast<__u64>(readBuffer.getData());
tr.len = writeBuffer.getSize();
/*
.speed_hz = 0,
.delay_usecs = 0,
.bits_per_word = 0,
.cs_change = 0,
.tx_nbits = 0, // on more-recent kernel versions;
.rx_nbits = 0, // on more-recent kernel versions;
.pad = 0
*/
NATIVE_INT_TYPE stat = ioctl(this->m_fd, SPI_IOC_MESSAGE(1), &tr);
if (stat < 1) {
this->log_WARNING_HI_SPI_WriteError(this->m_device,this->m_select,stat);
}
this->m_bytes += readBuffer.getSize();
this->tlmWrite_SPI_Bytes(this->m_bytes);
}
bool LinuxSpiDriverComponentImpl::open(NATIVE_INT_TYPE device,
NATIVE_INT_TYPE select,
SpiFrequency clock,
SpiMode spiMode) {
this->m_device = device;
this->m_select = select;
NATIVE_INT_TYPE fd;
NATIVE_INT_TYPE ret;
// Open:
char devName[256];
snprintf(devName,sizeof(devName),"/dev/spidev%d.%d",device,select);
// null terminate
devName[sizeof(devName)-1] = 0;
DEBUG_PRINT("Opening SPI device %s\n",devName);
fd = ::open(devName, O_RDWR);
if (fd == -1) {
DEBUG_PRINT("open SPI device %d.%d failed. %d\n",device,select,errno);
this->log_WARNING_HI_SPI_OpenError(device,select,fd);
return false;
} else {
DEBUG_PRINT("Successfully opened SPI device %s fd %d\n",devName,fd);
}
this->m_fd = fd;
// Configure:
/*
* SPI Mode 0, 1, 2, 3
*/
U8 mode; // Mode Select (CPOL = 0/1, CPHA = 0/1)
switch(spiMode) {
case SpiMode::SPI_MODE_CPOL_LOW_CPHA_LOW:
mode = SPI_MODE_0;
break;
case SpiMode::SPI_MODE_CPOL_LOW_CPHA_HIGH:
mode = SPI_MODE_1;
break;
case SpiMode::SPI_MODE_CPOL_HIGH_CPHA_LOW:
mode = SPI_MODE_2;
break;
case SpiMode::SPI_MODE_CPOL_HIGH_CPHA_HIGH:
mode = SPI_MODE_3;
break;
default:
//Assert if the device SPI Mode is not in the correct range
FW_ASSERT(0, spiMode);
break;
}
ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
if (ret == -1) {
DEBUG_PRINT("ioctl SPI_IOC_WR_MODE fd %d failed. %d\n",fd,errno);
this->log_WARNING_HI_SPI_ConfigError(device,select,ret);
return false;
} else {
DEBUG_PRINT("SPI fd %d WR mode successfully configured to %d\n",fd,mode);
}
ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
if (ret == -1) {
DEBUG_PRINT("ioctl SPI_IOC_RD_MODE fd %d failed. %d\n",fd,errno);
this->log_WARNING_HI_SPI_ConfigError(device,select,ret);
return false;
} else {
DEBUG_PRINT("SPI fd %d RD mode successfully configured to %d\n",fd,mode);
}
/*
* 8 bits per word
*/
U8 bits = 8;
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
if (ret == -1) {
DEBUG_PRINT("ioctl SPI_IOC_WR_BITS_PER_WORD fd %d failed. %d\n",fd,errno);
this->log_WARNING_HI_SPI_ConfigError(device,select,ret);
return false;
} else {
DEBUG_PRINT("SPI fd %d WR bits per word successfully configured to %d\n",fd,bits);
}
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
if (ret == -1) {
DEBUG_PRINT("ioctl SPI_IOC_RD_BITS_PER_WORD fd %d failed. %d\n",fd,errno);
this->log_WARNING_HI_SPI_ConfigError(device,select,ret);
return false;
} else {
DEBUG_PRINT("SPI fd %d RD bits per word successfully configured to %d\n",fd,bits);
}
/*
* Max speed in Hz
*/
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &clock);
if (ret == -1) {
DEBUG_PRINT("ioctl SPI_IOC_WR_MAX_SPEED_HZ fd %d failed. %d\n",fd,errno);
this->log_WARNING_HI_SPI_ConfigError(device,select,ret);
return false;
} else {
DEBUG_PRINT("SPI fd %d WR freq successfully configured to %d\n",fd,clock);
}
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &clock);
if (ret == -1) {
DEBUG_PRINT("ioctl SPI_IOC_RD_MAX_SPEED_HZ fd %d failed. %d\n",fd,errno);
this->log_WARNING_HI_SPI_ConfigError(device,select,ret);
return false;
} else {
DEBUG_PRINT("SPI fd %d RD freq successfully configured to %d\n",fd,clock);
}
return true;
}
LinuxSpiDriverComponentImpl::~LinuxSpiDriverComponentImpl() {
DEBUG_PRINT("Closing SPI device %d\n",this->m_fd);
(void) close(this->m_fd);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/LinuxSpiDriverComponentImplCommon.cpp | // ======================================================================
// \title LinuxSpiDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxSpiDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp>
#include <FpConfig.hpp>
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
LinuxSpiDriverComponentImpl::
LinuxSpiDriverComponentImpl(const char * const compName) :
LinuxSpiDriverComponentBase(compName),
m_fd(-1),
m_device(-1),
m_select(-1),
m_bytes(0)
{
}
void LinuxSpiDriverComponentImpl::init(const NATIVE_INT_TYPE instance) {
LinuxSpiDriverComponentBase::init(instance);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/LinuxSpiDriverComponentImplStub.cpp | // ======================================================================
// \title LinuxSpiDriverImpl.cpp
// \author tcanham
// \brief cpp file for LinuxSpiDriver component implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp>
#include <FpConfig.hpp>
namespace Drv {
bool LinuxSpiDriverComponentImpl::open(NATIVE_INT_TYPE device,
NATIVE_INT_TYPE select,
SpiFrequency clock,
SpiMode spiMode) {
//TODO: fill this function out
return false;
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void LinuxSpiDriverComponentImpl::SpiReadWrite_handler(
const NATIVE_INT_TYPE portNum, Fw::Buffer &WriteBuffer,
Fw::Buffer &readBuffer) {
// TODO
}
LinuxSpiDriverComponentImpl::~LinuxSpiDriverComponentImpl() {
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/test/ut/main.cpp | // ----------------------------------------------------------------------
// Main.cpp
// ----------------------------------------------------------------------
#include "LinuxSpiDriverTester.hpp"
#include <cstdlib>
//TEST(Test, NominalTlm) {
// Svc::LinuxSpiDriverTester tester;
// tester.nominalTlm();
//}
int main(int argc, char **argv) {
Drv::LinuxSpiDriverTester tester;
U8 buffer[argc-1];
// scan args for bytes
for (NATIVE_INT_TYPE byte = 0; byte < argc-1; byte++) {
buffer[byte] = strtol(argv[1+byte],0,0);
}
tester.sendBuffer(buffer,sizeof(buffer));
}
| cpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/test/ut/LinuxSpiDriverTester.hpp | // ======================================================================
// \title LinuxSpiDriver/test/ut/Tester.hpp
// \author tcanham
// \brief hpp file for LinuxSpiDriver 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 "LinuxSpiDriverGTestBase.hpp"
#include "Drv/LinuxSpiDriver/LinuxSpiDriverComponentImpl.hpp"
namespace Drv {
class LinuxSpiDriverTester :
public LinuxSpiDriverTesterBase
{
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object LinuxSpiDriverTester
//!
LinuxSpiDriverTester();
//! Destroy object LinuxSpiDriverTester
//!
~LinuxSpiDriverTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! To do
//!
void sendBuffer(U8* buffer, NATIVE_INT_TYPE size);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
void textLogIn(const FwEventIdType id, //!< The event ID
Fw::Time& timeTag, //!< The time
const Fw::TextLogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
);
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
LinuxSpiDriverComponentImpl component;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/LinuxSpiDriver/test/ut/LinuxSpiDriverTester.cpp | // ======================================================================
// \title LinuxSpiDriver.hpp
// \author tcanham
// \brief cpp file for LinuxSpiDriver test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "LinuxSpiDriverTester.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
namespace Drv {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
LinuxSpiDriverTester ::
LinuxSpiDriverTester() :
LinuxSpiDriverTesterBase("Tester", MAX_HISTORY_SIZE),
component("LinuxSpiDriver")
{
this->initComponents();
this->connectPorts();
}
LinuxSpiDriverTester ::
~LinuxSpiDriverTester()
{
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void LinuxSpiDriverTester ::
connectPorts()
{
// SpiReadWrite
this->connect_to_SpiReadWrite(
0,
this->component.get_SpiReadWrite_InputPort(0)
);
// Tlm
this->component.set_Tlm_OutputPort(
0,
this->get_from_Tlm(0)
);
// Time
this->component.set_Time_OutputPort(
0,
this->get_from_Time(0)
);
// Log
this->component.set_Log_OutputPort(
0,
this->get_from_Log(0)
);
// LogText
this->component.set_LogText_OutputPort(
0,
this->get_from_LogText(0)
);
}
void LinuxSpiDriverTester ::
initComponents()
{
this->init();
this->component.init(
INSTANCE
);
this->component.open(8,0,SPI_FREQUENCY_1MHZ);
}
void LinuxSpiDriverTester::textLogIn(const FwEventIdType id, //!< The event ID
Fw::Time& timeTag, //!< The time
const Fw::TextLogSeverity severity, //!< The severity
const Fw::TextLogString& text //!< The event string
) {
TextLogEntry e = { id, timeTag, severity, text };
printTextLogHistoryEntry(e, stdout);
}
void LinuxSpiDriverTester::sendBuffer(BYTE* buffer, NATIVE_INT_TYPE size) {
Fw::Buffer w;
w.setdata(reinterpret_cast<POINTER_CAST>(buffer));
w.setsize(size);
printf("WRITE: ");
for (NATIVE_INT_TYPE byte = 0; byte < size; byte++) {
printf("0x%02X ",buffer[byte]);
}
printf("\n");
BYTE* rb = 0;
rb = new BYTE[size];
FW_ASSERT(rb);
Fw::Buffer r(0,0, reinterpret_cast<POINTER_CAST>(rb),size);
this->invoke_to_SpiReadWrite(0,w,r);
BYTE* d = (BYTE*)r.getdata();
printf("READ: ");
for (NATIVE_INT_TYPE byte = 0; byte < size; byte++) {
printf("0x%02X ",d[byte]);
}
printf("\n");
delete[] rb;
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/TcpClient/TcpClientComponentImpl.hpp | // ======================================================================
// \title TcpClientComponentImpl.hpp
// \author mstarch
// \brief hpp file for TcpClientComponentImpl component implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef TcpClientComponentImpl_HPP
#define TcpClientComponentImpl_HPP
#include <Drv/Ip/IpSocket.hpp>
#include <Drv/Ip/SocketReadTask.hpp>
#include <Drv/Ip/TcpClientSocket.hpp>
#include "Drv/TcpClient/TcpClientComponentAc.hpp"
namespace Drv {
class TcpClientComponentImpl : public TcpClientComponentBase, public SocketReadTask {
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
/**
* \brief construct the TcpClient component.
* \param compName: name of this component
*/
TcpClientComponentImpl(const char* const compName);
/**
* \brief Destroy the component
*/
~TcpClientComponentImpl();
// ----------------------------------------------------------------------
// Helper methods to start and stop socket
// ----------------------------------------------------------------------
/**
* \brief Configures the TcpClient settings but does not open the connection
*
* The TcpClientComponent needs to connect to a remote TCP server. This call configures the hostname, port and send
* timeouts for that socket connection. This call should be performed on system startup before recv or send
* are called. Note: hostname must be a dot-notation IP address of the form "x.x.x.x". DNS translation is left up
* to the user.
*
* \param hostname: ip address of remote tcp server in the form x.x.x.x
* \param port: port of remote tcp server
* \param send_timeout_seconds: send timeout seconds component. Defaults to: SOCKET_TIMEOUT_SECONDS
* \param send_timeout_microseconds: send timeout microseconds component. Must be less than 1000000. Defaults to:
* SOCKET_TIMEOUT_MICROSECONDS
* \return status of the configure
*/
SocketIpStatus configure(const char* hostname,
const U16 port,
const U32 send_timeout_seconds = SOCKET_SEND_TIMEOUT_SECONDS,
const U32 send_timeout_microseconds = SOCKET_SEND_TIMEOUT_MICROSECONDS);
PROTECTED:
// ----------------------------------------------------------------------
// Implementations for socket read task virtual methods
// ----------------------------------------------------------------------
/**
* \brief returns a reference to the socket handler
*
* Gets a reference to the current socket handler in order to operate generically on the IpSocket instance. Used for
* receive, and open calls. This socket handler will be a TcpClient.
*
* \return IpSocket reference
*/
IpSocket& getSocketHandler();
/**
* \brief returns a buffer to fill with data
*
* Gets a reference to a buffer to fill with data. This allows the component to determine how to provide a
* buffer and the socket read task just fills said buffer.
*
* \return Fw::Buffer to fill with data
*/
Fw::Buffer getBuffer();
/**
* \brief sends a buffer to be filled with data
*
* Sends the buffer gotten by getBuffer that has now been filled with data. This is used to delegate to the
* component how to send back the buffer. Ignores buffers with error status error.
*
* \return Fw::Buffer filled with data to send out
*/
void sendBuffer(Fw::Buffer buffer, SocketIpStatus status);
/**
* \brief called when the IPv4 system has been connected
*/
void connected();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
/**
* \brief Send data out of the TcpClient
*
* Passing data to this port will send data from the TcpClient to whatever TCP server this component has connected
* to. Should the socket not be opened or was disconnected, then this port call will return SEND_RETRY and critical
* transmissions should be retried. SEND_ERROR indicates an unresolvable error. SEND_OK is returned when the data
* has been sent.
*
* Note: this component delegates the reopening of the socket to the read thread and thus the caller should retry
* after the read thread has attempted to reopen the port but does not need to reopen the port manually.
*
* \param portNum: fprime port number of the incoming port call
* \param fwBuffer: buffer containing data to be sent
* \return SEND_OK on success, SEND_RETRY when critical data should be retried and SEND_ERROR upon error
*/
Drv::SendStatus send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer);
Drv::TcpClientSocket m_socket; //!< Socket implementation
};
} // end namespace Drv
#endif // end TcpClientComponentImpl
| hpp |
fprime | data/projects/fprime/Drv/TcpClient/TcpClient.hpp | // ======================================================================
// TcpClient.hpp
// Standardization header for TcpClient
// ======================================================================
#ifndef Drv_TcpClient_HPP
#define Drv_TcpClient_HPP
#include "Drv/TcpClient/TcpClientComponentImpl.hpp"
namespace Drv {
typedef TcpClientComponentImpl TcpClient;
}
#endif
| hpp |
fprime | data/projects/fprime/Drv/TcpClient/TcpClientComponentImpl.cpp | // ======================================================================
// \title TcpClientComponentImpl.cpp
// \author mstarch
// \brief cpp file for TcpClientComponentImpl component implementation class
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Drv/TcpClient/TcpClientComponentImpl.hpp>
#include <FpConfig.hpp>
#include "Fw/Types/Assert.hpp"
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
TcpClientComponentImpl::TcpClientComponentImpl(const char* const compName)
: TcpClientComponentBase(compName),
SocketReadTask() {}
SocketIpStatus TcpClientComponentImpl::configure(const char* hostname,
const U16 port,
const U32 send_timeout_seconds,
const U32 send_timeout_microseconds) {
return m_socket.configure(hostname, port, send_timeout_seconds, send_timeout_microseconds);
}
TcpClientComponentImpl::~TcpClientComponentImpl() {}
// ----------------------------------------------------------------------
// Implementations for socket read task virtual methods
// ----------------------------------------------------------------------
IpSocket& TcpClientComponentImpl::getSocketHandler() {
return m_socket;
}
Fw::Buffer TcpClientComponentImpl::getBuffer() {
return allocate_out(0, 1024);
}
void TcpClientComponentImpl::sendBuffer(Fw::Buffer buffer, SocketIpStatus status) {
Drv::RecvStatus recvStatus = (status == SOCK_SUCCESS) ? RecvStatus::RECV_OK : RecvStatus::RECV_ERROR;
this->recv_out(0, buffer, recvStatus);
}
void TcpClientComponentImpl::connected() {
if (isConnected_ready_OutputPort(0)) {
this->ready_out(0);
}
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
Drv::SendStatus TcpClientComponentImpl::send_handler(const NATIVE_INT_TYPE portNum, Fw::Buffer& fwBuffer) {
Drv::SocketIpStatus status = m_socket.send(fwBuffer.getData(), fwBuffer.getSize());
// Only deallocate buffer when the caller is not asked to retry
if (status == SOCK_INTERRUPTED_TRY_AGAIN) {
return SendStatus::SEND_RETRY;
} else if (status != SOCK_SUCCESS) {
deallocate_out(0, fwBuffer);
return SendStatus::SEND_ERROR;
}
deallocate_out(0, fwBuffer);
return SendStatus::SEND_OK;
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/TcpClient/test/ut/TcpClientTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "TcpClientTester.hpp"
TEST(Nominal, BasicMessaging) {
Drv::TcpClientTester tester;
tester.test_basic_messaging();
}
TEST(Nominal, BasicReceiveThread) {
Drv::TcpClientTester tester;
tester.test_receive_thread();
}
TEST(Reconnect, MultiMessaging) {
Drv::TcpClientTester tester;
tester.test_multiple_messaging();
}
TEST(Reconnect, ReceiveThreadReconnect) {
Drv::TcpClientTester tester;
tester.test_advanced_reconnect();
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Drv/TcpClient/test/ut/TcpClientTester.hpp | // ======================================================================
// \title TcpClient/test/ut/Tester.hpp
// \author mstarch
// \brief hpp file for ByteStreamDriverModel 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 "TcpClientGTestBase.hpp"
#include "Drv/TcpClient/TcpClientComponentImpl.hpp"
#include "Drv/Ip/TcpServerSocket.hpp"
#define SEND_DATA_BUFFER_SIZE 1024
namespace Drv {
class TcpClientTester :
public TcpClientGTestBase
{
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 1000;
// 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 = 100;
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
//! Construct object TcpClientTester
//!
TcpClientTester();
//! Destroy object TcpClientTester
//!
~TcpClientTester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void test_basic_messaging();
void test_multiple_messaging();
void test_receive_thread();
void test_advanced_reconnect();
void test_with_loop(U32 iterations, bool recv_thread=false);
private:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_recv
//!
void from_recv_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &recvBuffer,
const RecvStatus &recvStatus
);
//! Handler for from_ready
//!
void from_ready_handler(
const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_allocate
//!
Fw::Buffer from_allocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 size
);
//! Handler for from_deallocate
//!
void from_deallocate_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &fwBuffer
);
private:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
private:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
TcpClientComponentImpl component;
Fw::Buffer m_data_buffer;
Fw::Buffer m_data_buffer2;
U8 m_data_storage[SEND_DATA_BUFFER_SIZE];
std::atomic<bool> m_spinner;
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/TcpClient/test/ut/TcpClientTester.cpp | // ======================================================================
// \title TcpClientTester.cpp
// \author mstarch
// \brief cpp file for TcpClientTester of TcpClient
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "TcpClientTester.hpp"
#include "STest/Pick/Pick.hpp"
#include <Os/Log.hpp>
#include <Drv/Ip/test/ut/PortSelector.hpp>
#include <Drv/Ip/test/ut/SocketTestHelper.hpp>
Os::Log logger;
namespace Drv {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
void TcpClientTester ::test_with_loop(U32 iterations, bool recv_thread) {
U8 buffer[sizeof(m_data_storage)] = {};
Drv::SocketIpStatus status1 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus status2 = Drv::SOCK_SUCCESS;
Drv::SocketIpStatus serverStat = Drv::SOCK_SUCCESS;
U16 port = Drv::Test::get_free_port();
ASSERT_NE(0, port);
Drv::TcpServerSocket server;
server.configure("127.0.0.1", port, 0, 100);
this->component.configure("127.0.0.1", port, 0, 100);
serverStat = server.startup();
ASSERT_EQ(serverStat, SOCK_SUCCESS);
// Start up a receive thread
if (recv_thread) {
Os::TaskString name("receiver thread");
this->component.startSocketTask(name, true, Os::Task::TASK_DEFAULT, Os::Task::TASK_DEFAULT);
}
// Loop through a bunch of client disconnects
for (U32 i = 0; i < iterations; i++) {
I32 size = sizeof(m_data_storage);
// Not testing with reconnect thread, we will need to open ourselves
if (not recv_thread) {
status1 = this->component.open();
} else {
EXPECT_TRUE(Drv::Test::wait_on_change(this->component.getSocketHandler(), true, SOCKET_RETRY_INTERVAL_MS/10 + 1));
}
EXPECT_TRUE(this->component.getSocketHandler().isOpened());
status2 = server.open();
EXPECT_EQ(status1, Drv::SOCK_SUCCESS);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
// If all the opens worked, then run this
if ((Drv::SOCK_SUCCESS == status1) && (Drv::SOCK_SUCCESS == status2) &&
(this->component.getSocketHandler().isOpened())) {
// Force the sockets not to hang, if at all possible
Drv::Test::force_recv_timeout(this->component.getSocketHandler());
Drv::Test::force_recv_timeout(server);
m_data_buffer.setSize(sizeof(m_data_storage));
Drv::Test::fill_random_buffer(m_data_buffer);
Drv::SendStatus status = invoke_to_send(0, m_data_buffer);
EXPECT_EQ(status, SendStatus::SEND_OK);
status2 = server.recv(buffer, size);
EXPECT_EQ(status2, Drv::SOCK_SUCCESS);
EXPECT_EQ(size, m_data_buffer.getSize());
Drv::Test::validate_random_buffer(m_data_buffer, buffer);
// If receive thread is live, try the other way
if (recv_thread) {
m_spinner = false;
m_data_buffer.setSize(sizeof(m_data_storage));
server.send(m_data_buffer.getData(), m_data_buffer.getSize());
while (not m_spinner) {}
}
}
// Properly stop the client on the last iteration
if ((1 + i) == iterations && recv_thread) {
this->component.stopSocketTask();
this->component.joinSocketTask(nullptr);
} else {
this->component.close();
}
server.close();
}
server.shutdown();
ASSERT_from_ready_SIZE(iterations);
}
TcpClientTester ::TcpClientTester()
: TcpClientGTestBase("Tester", MAX_HISTORY_SIZE),
component("TcpClient"),
m_data_buffer(m_data_storage, 0), m_spinner(true) {
this->initComponents();
this->connectPorts();
::memset(m_data_storage, 0, sizeof(m_data_storage));
}
TcpClientTester ::~TcpClientTester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void TcpClientTester ::test_basic_messaging() {
test_with_loop(1);
}
void TcpClientTester ::test_multiple_messaging() {
test_with_loop(100);
}
void TcpClientTester ::test_receive_thread() {
test_with_loop(1, true);
}
void TcpClientTester ::test_advanced_reconnect() {
test_with_loop(10, true); // Up to 10 * RECONNECT_MS
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void TcpClientTester ::
from_recv_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &recvBuffer,
const RecvStatus &recvStatus
)
{
this->pushFromPortEntry_recv(recvBuffer, recvStatus);
// Make sure we can get to unblocking the spinner
EXPECT_EQ(m_data_buffer.getSize(), recvBuffer.getSize()) << "Invalid transmission size";
Drv::Test::validate_random_buffer(m_data_buffer, recvBuffer.getData());
m_spinner = true;
delete[] recvBuffer.getData();
}
void TcpClientTester ::from_ready_handler(const NATIVE_INT_TYPE portNum) {
this->pushFromPortEntry_ready();
}
Fw::Buffer TcpClientTester ::
from_allocate_handler(
const NATIVE_INT_TYPE portNum,
U32 size
)
{
this->pushFromPortEntry_allocate(size);
Fw::Buffer buffer(new U8[size], size);
m_data_buffer2 = buffer;
return buffer;
}
void TcpClientTester ::
from_deallocate_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &fwBuffer
)
{
this->pushFromPortEntry_deallocate(fwBuffer);
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/StreamCrossover/StreamCrossover.hpp | // ======================================================================
// \title StreamCrossover.hpp
// \author ethanchee
// \brief hpp file for StreamCrossover component implementation class
// ======================================================================
#ifndef StreamCrossover_HPP
#define StreamCrossover_HPP
#include "Drv/StreamCrossover/StreamCrossoverComponentAc.hpp"
namespace Drv {
class StreamCrossover :
public StreamCrossoverComponentBase
{
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object StreamCrossover
//!
StreamCrossover(
const char *const compName /*!< The component name*/
);
//! Destroy object StreamCrossover
//!
~StreamCrossover();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for streamIn
//!
void streamIn_handler(
const NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer &recvBuffer,
const Drv::RecvStatus &recvStatus
);
};
} // end namespace Drv
#endif
| hpp |
fprime | data/projects/fprime/Drv/StreamCrossover/StreamCrossover.cpp | // ======================================================================
// \title StreamCrossover.cpp
// \author ethanchee
// \brief cpp file for StreamCrossover component implementation class
// ======================================================================
#include <Drv/StreamCrossover/StreamCrossover.hpp>
#include <FpConfig.hpp>
namespace Drv {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
StreamCrossover ::
StreamCrossover(
const char *const compName
) : StreamCrossoverComponentBase(compName)
{
}
StreamCrossover ::
~StreamCrossover()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void StreamCrossover ::
streamIn_handler(
const NATIVE_INT_TYPE portNum,
Fw::Buffer &recvBuffer,
const Drv::RecvStatus &recvStatus
)
{
if(recvStatus == Drv::RecvStatus::RECV_ERROR || recvBuffer.getSize() == 0)
{
this->log_WARNING_HI_StreamOutError(Drv::SendStatus::SEND_ERROR);
this->errorDeallocate_out(0, recvBuffer);
return;
}
Drv::SendStatus sendStatus = this->streamOut_out(0, recvBuffer);
if(sendStatus != Drv::SendStatus::SEND_OK)
{
this->log_WARNING_HI_StreamOutError(sendStatus);
}
}
} // end namespace Drv
| cpp |
fprime | data/projects/fprime/Drv/StreamCrossover/test/ut/StreamCrossoverTestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "StreamCrossoverTester.hpp"
TEST(Nominal, TestBuffer) {
Drv::StreamCrossoverTester tester;
tester.sendTestBuffer();
}
TEST(Nominal, TestFail) {
Drv::StreamCrossoverTester tester;
tester.testFail();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
Subsets and Splits