repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
fprime | data/projects/fprime/Fw/Types/PolyType.cpp | #include <Fw/Types/PolyType.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#define __STDC_FORMAT_MACROS
namespace Fw {
// U8 methods
PolyType::PolyType() {
this->m_dataType = TYPE_NOTYPE;
}
PolyType::PolyType(U8 val) {
this->m_dataType = TYPE_U8;
this->m_val.u8Val = val;
}
PolyType::operator U8() {
FW_ASSERT(TYPE_U8 == this->m_dataType);
return this->m_val.u8Val;
}
void PolyType::get(U8& val) {
FW_ASSERT(TYPE_U8 == this->m_dataType);
val = this->m_val.u8Val;
}
bool PolyType::isU8() {
return (TYPE_U8 == this->m_dataType);
}
PolyType& PolyType::operator=(U8 other) {
this->m_dataType = TYPE_U8;
this->m_val.u8Val = other;
return *this;
}
// I8 methods
PolyType::PolyType(I8 val) {
this->m_dataType = TYPE_I8;
this->m_val.i8Val = val;
}
PolyType::operator I8() {
FW_ASSERT(TYPE_I8 == this->m_dataType);
return this->m_val.i8Val;
}
void PolyType::get(I8& val) {
FW_ASSERT(TYPE_I8 == this->m_dataType);
val = this->m_val.i8Val;
}
bool PolyType::isI8() {
return (TYPE_I8 == this->m_dataType);
}
PolyType& PolyType::operator=(I8 other) {
this->m_dataType = TYPE_I8;
this->m_val.i8Val = other;
return *this;
}
#if FW_HAS_16_BIT
// U16 methods
PolyType::PolyType(U16 val) {
this->m_dataType = TYPE_U16;
this->m_val.u16Val = val;
}
PolyType::operator U16() {
FW_ASSERT(TYPE_U16 == this->m_dataType);
return this->m_val.u16Val;
}
void PolyType::get(U16& val) {
FW_ASSERT(TYPE_U16 == this->m_dataType);
val = this->m_val.u16Val;
}
bool PolyType::isU16() {
return (TYPE_U16 == this->m_dataType);
}
PolyType& PolyType::operator=(U16 other) {
this->m_dataType = TYPE_U16;
this->m_val.u16Val = other;
return *this;
}
// I16 methods
PolyType::PolyType(I16 val) {
this->m_dataType = TYPE_I16;
this->m_val.i16Val = val;
}
PolyType::operator I16() {
FW_ASSERT(TYPE_I16 == this->m_dataType);
return this->m_val.i16Val;
}
void PolyType::get(I16& val) {
FW_ASSERT(TYPE_I16 == this->m_dataType);
val = this->m_val.i16Val;
}
bool PolyType::isI16() {
return (TYPE_I16 == this->m_dataType);
}
PolyType& PolyType::operator=(I16 other) {
this->m_dataType = TYPE_I16;
this->m_val.i16Val = other;
return *this;
}
#endif
#if FW_HAS_32_BIT
// U32 methods
PolyType::PolyType(U32 val) {
this->m_dataType = TYPE_U32;
this->m_val.u32Val = val;
}
PolyType::operator U32() {
FW_ASSERT(TYPE_U32 == this->m_dataType);
return this->m_val.u32Val;
}
void PolyType::get(U32& val) {
FW_ASSERT(TYPE_U32 == this->m_dataType);
val = this->m_val.u32Val;
}
bool PolyType::isU32() {
return (TYPE_U32 == this->m_dataType);
}
PolyType& PolyType::operator=(U32 other) {
this->m_dataType = TYPE_U32;
this->m_val.u32Val = other;
return *this;
}
// I32 methods
PolyType::PolyType(I32 val) {
this->m_dataType = TYPE_I32;
this->m_val.i32Val = val;
}
PolyType::operator I32() {
FW_ASSERT(TYPE_I32 == this->m_dataType);
return this->m_val.i32Val;
}
void PolyType::get(I32& val) {
FW_ASSERT(TYPE_I32 == this->m_dataType);
val = this->m_val.i32Val;
}
bool PolyType::isI32() {
return (TYPE_I32 == this->m_dataType);
}
PolyType& PolyType::operator=(I32 other) {
this->m_dataType = TYPE_I32;
this->m_val.i32Val = other;
return *this;
}
#endif
#if FW_HAS_64_BIT
// U64 methods
PolyType::PolyType(U64 val) {
this->m_dataType = TYPE_U64;
this->m_val.u64Val = val;
}
PolyType::operator U64() {
FW_ASSERT(TYPE_U64 == this->m_dataType);
return this->m_val.u64Val;
}
void PolyType::get(U64& val) {
FW_ASSERT(TYPE_U64 == this->m_dataType);
val = this->m_val.u64Val;
}
bool PolyType::isU64() {
return (TYPE_U64 == this->m_dataType);
}
PolyType& PolyType::operator=(U64 other) {
this->m_dataType = TYPE_U64;
this->m_val.u64Val = other;
return *this;
}
// I64 methods
PolyType::PolyType(I64 val) {
this->m_dataType = TYPE_I64;
this->m_val.u64Val = val;
}
PolyType::operator I64() {
FW_ASSERT(TYPE_I64 == this->m_dataType);
return this->m_val.i64Val;
}
void PolyType::get(I64& val) {
FW_ASSERT(TYPE_I64 == this->m_dataType);
val = this->m_val.i64Val;
}
bool PolyType::isI64() {
return (TYPE_I64 == this->m_dataType);
}
PolyType& PolyType::operator=(I64 other) {
this->m_dataType = TYPE_I64;
this->m_val.i64Val = other;
return *this;
}
#endif
#if FW_HAS_F64
PolyType::PolyType(F64 val) {
this->m_dataType = TYPE_F64;
this->m_val.f64Val = val;
}
PolyType::operator F64() {
FW_ASSERT(TYPE_F64 == this->m_dataType);
return this->m_val.f64Val;
}
void PolyType::get(F64& val) {
FW_ASSERT(TYPE_F64 == this->m_dataType);
val = this->m_val.f64Val;
}
bool PolyType::isF64() {
return (TYPE_F64 == this->m_dataType);
}
PolyType& PolyType::operator=(F64 other) {
this->m_dataType = TYPE_F64;
this->m_val.f64Val = other;
return *this;
}
#endif
PolyType::PolyType(F32 val) {
this->m_dataType = TYPE_F32;
this->m_val.f32Val = val;
}
PolyType::operator F32() {
FW_ASSERT(TYPE_F32 == this->m_dataType);
return this->m_val.f32Val;
}
void PolyType::get(F32& val) {
FW_ASSERT(TYPE_F32 == this->m_dataType);
val = this->m_val.f32Val;
}
bool PolyType::isF32() {
return (TYPE_F32 == this->m_dataType);
}
PolyType& PolyType::operator=(F32 other) {
this->m_dataType = TYPE_F32;
this->m_val.f32Val = other;
return *this;
}
PolyType::PolyType(bool val) {
this->m_dataType = TYPE_BOOL;
this->m_val.boolVal = val;
}
PolyType::operator bool() {
FW_ASSERT(TYPE_BOOL == this->m_dataType);
return this->m_val.boolVal;
}
void PolyType::get(bool& val) {
FW_ASSERT(TYPE_BOOL == this->m_dataType);
val = this->m_val.boolVal;
}
bool PolyType::isBool() {
return (TYPE_BOOL == this->m_dataType);
}
PolyType& PolyType::operator=(bool other) {
this->m_dataType = TYPE_BOOL;
this->m_val.boolVal = other;
return *this;
}
PolyType::PolyType(void* val) {
this->m_dataType = TYPE_PTR;
this->m_val.ptrVal = val;
}
PolyType::operator void*() {
FW_ASSERT(TYPE_PTR == this->m_dataType);
return this->m_val.ptrVal;
}
void PolyType::get(void*& val) {
FW_ASSERT(TYPE_PTR == this->m_dataType);
val = this->m_val.ptrVal;
}
bool PolyType::isPtr() {
return (TYPE_PTR == this->m_dataType);
}
PolyType& PolyType::operator=(void* other) {
this->m_dataType = TYPE_PTR;
this->m_val.ptrVal = other;
return *this;
}
PolyType::PolyType(const PolyType &original) : Fw::Serializable() {
this->m_dataType = original.m_dataType;
this->m_val = original.m_val;
}
PolyType::~PolyType() {
}
PolyType& PolyType::operator=(const PolyType &src) {
this->m_dataType = src.m_dataType;
this->m_val = src.m_val;
return *this;
}
bool PolyType::operator!=(const PolyType &other) const {
return !operator==(other);
}
bool PolyType::operator==(const PolyType &other) const {
// if type doesn't match, not equal
if (this->m_dataType != other.m_dataType) {
return false;
} else {
// check based on type
bool valIsEqual = false;
switch (this->m_dataType) {
case TYPE_U8:
valIsEqual = (this->m_val.u8Val == other.m_val.u8Val);
break;
case TYPE_I8:
valIsEqual = (this->m_val.i8Val == other.m_val.i8Val);
break;
#if FW_HAS_16_BIT
case TYPE_U16:
valIsEqual = (this->m_val.u16Val == other.m_val.u16Val);
break;
case TYPE_I16:
valIsEqual = (this->m_val.i16Val == other.m_val.i16Val);
break;
#endif
#if FW_HAS_32_BIT
case TYPE_U32:
valIsEqual = (this->m_val.u32Val == other.m_val.u32Val);
break;
case TYPE_I32:
valIsEqual = (this->m_val.i32Val == other.m_val.i32Val);
break;
#endif
#if FW_HAS_64_BIT
case TYPE_U64:
valIsEqual = (this->m_val.u64Val == other.m_val.u64Val);
break;
case TYPE_I64:
valIsEqual = (this->m_val.i64Val == other.m_val.i64Val);
break;
#endif
case TYPE_BOOL:
valIsEqual = (this->m_val.boolVal == other.m_val.boolVal);
break;
case TYPE_PTR:
valIsEqual = (this->m_val.ptrVal == other.m_val.ptrVal);
break;
#if FW_HAS_F64
case TYPE_F64: // fall through, shouldn't test floating point
#endif
case TYPE_F32: // fall through, shouldn't test floating point
case TYPE_NOTYPE:
valIsEqual = false;
break;
default:
FW_ASSERT(0,static_cast<FwAssertArgType>(this->m_dataType));
return false; // for compiler
}
return valIsEqual;
}
}
bool PolyType::operator<(const PolyType &other) const {
// if type doesn't match, not equal
if (this->m_dataType != other.m_dataType) {
return false;
} else {
// check based on type
bool result = false;
switch (this->m_dataType) {
case TYPE_U8:
result = (this->m_val.u8Val < other.m_val.u8Val);
break;
case TYPE_I8:
result = (this->m_val.i8Val < other.m_val.i8Val);
break;
#if FW_HAS_16_BIT
case TYPE_U16:
result = (this->m_val.u16Val < other.m_val.u16Val);
break;
case TYPE_I16:
result = (this->m_val.i16Val < other.m_val.i16Val);
break;
#endif
#if FW_HAS_32_BIT
case TYPE_U32:
result = (this->m_val.u32Val < other.m_val.u32Val);
break;
case TYPE_I32:
result = (this->m_val.i32Val < other.m_val.i32Val);
break;
#endif
#if FW_HAS_64_BIT
case TYPE_U64:
result = (this->m_val.u64Val < other.m_val.u64Val);
break;
case TYPE_I64:
result = (this->m_val.i64Val < other.m_val.i64Val);
break;
#endif
#if FW_HAS_F64
case TYPE_F64:
result = (this->m_val.f64Val < other.m_val.f64Val);
break;
#endif
case TYPE_F32:
result = (this->m_val.f32Val < other.m_val.f32Val);
break;
case TYPE_PTR:
result = (this->m_val.ptrVal < other.m_val.ptrVal);
break;
case TYPE_BOOL: // fall through, shouldn't test bool
case TYPE_NOTYPE:
result = false;
break;
default:
FW_ASSERT(0,static_cast<FwAssertArgType>(this->m_dataType));
return false; // for compiler
}
return result;
}
}
bool PolyType::operator>(const PolyType &other) const {
return other.operator<(*this);
}
bool PolyType::operator>=(const PolyType &other) const {
return (this->operator>(other)) || (this->operator==(other));
}
bool PolyType::operator<=(const PolyType &other) const {
return (this->operator<(other)) || (this->operator==(other));
}
SerializeStatus PolyType::serialize(SerializeBufferBase& buffer) const {
// store type
SerializeStatus stat = buffer.serialize(static_cast<FwEnumStoreType> (this->m_dataType));
if(stat != FW_SERIALIZE_OK) {
return stat;
}
// switch on type
switch (this->m_dataType) {
case TYPE_U8:
stat = buffer.serialize(this->m_val.u8Val);
break;
case TYPE_I8:
stat = buffer.serialize(this->m_val.i8Val);
break;
#if FW_HAS_16_BIT
case TYPE_U16:
stat = buffer.serialize(this->m_val.u16Val);
break;
case TYPE_I16:
stat = buffer.serialize(this->m_val.i16Val);
break;
#endif
#if FW_HAS_32_BIT
case TYPE_U32:
stat = buffer.serialize(this->m_val.u32Val);
break;
case TYPE_I32:
stat = buffer.serialize(this->m_val.i32Val);
break;
#endif
#if FW_HAS_64_BIT
case TYPE_U64:
stat = buffer.serialize(this->m_val.u64Val);
break;
case TYPE_I64:
stat = buffer.serialize(this->m_val.i64Val);
break;
#endif
#if FW_HAS_F64
case TYPE_F64:
stat = buffer.serialize(this->m_val.f64Val);
break;
#endif
case TYPE_F32:
stat = buffer.serialize(this->m_val.f32Val);
break;
case TYPE_BOOL:
stat = buffer.serialize(this->m_val.boolVal);
break;
case TYPE_PTR:
stat = buffer.serialize(this->m_val.ptrVal);
break;
default:
stat = FW_SERIALIZE_FORMAT_ERROR;
break;
}
return stat;
}
SerializeStatus PolyType::deserialize(SerializeBufferBase& buffer) {
// get type
FwEnumStoreType des;
SerializeStatus stat = buffer.deserialize(des);
if (stat != FW_SERIALIZE_OK) {
return stat;
} else {
this->m_dataType = static_cast<Type>(des);
// switch on type
switch (this->m_dataType) {
case TYPE_U8:
return buffer.deserialize(this->m_val.u8Val);
case TYPE_I8:
return buffer.deserialize(this->m_val.i8Val);
#if FW_HAS_16_BIT
case TYPE_U16:
return buffer.deserialize(this->m_val.u16Val);
case TYPE_I16:
return buffer.deserialize(this->m_val.i16Val);
#endif
#if FW_HAS_32_BIT
case TYPE_U32:
return buffer.deserialize(this->m_val.u32Val);
case TYPE_I32:
return buffer.deserialize(this->m_val.i32Val);
#endif
#if FW_HAS_64_BIT
case TYPE_U64:
return buffer.deserialize(this->m_val.u64Val);
case TYPE_I64:
return buffer.deserialize(this->m_val.i64Val);
#endif
#if FW_HAS_F64
case TYPE_F64:
return buffer.deserialize(this->m_val.f64Val);
#endif
case TYPE_F32:
return buffer.deserialize(this->m_val.f32Val);
case TYPE_BOOL:
return buffer.deserialize(this->m_val.boolVal);
case TYPE_PTR:
return buffer.deserialize(this->m_val.ptrVal);
default:
return FW_DESERIALIZE_FORMAT_ERROR;
}
}
}
#if FW_SERIALIZABLE_TO_STRING || BUILD_UT
void PolyType::toString(StringBase& dest) const {
this->toString(dest,false);
}
void PolyType::toString(StringBase& dest, bool append) const {
char valString[80];
switch (this->m_dataType) {
case TYPE_U8:
(void) snprintf(valString, sizeof(valString), "%" PRIu8 " ", this->m_val.u8Val);
break;
case TYPE_I8:
(void) snprintf(valString, sizeof(valString), "%" PRId8 " ", this->m_val.i8Val);
break;
#if FW_HAS_16_BIT
case TYPE_U16:
(void) snprintf(valString, sizeof(valString), "%" PRIu16 " ", this->m_val.u16Val);
break;
case TYPE_I16:
(void) snprintf(valString, sizeof(valString), "%" PRId16 " ", this->m_val.i16Val);
break;
#endif
#if FW_HAS_32_BIT
case TYPE_U32:
(void) snprintf(valString, sizeof(valString), "%" PRIu32 " ", this->m_val.u32Val);
break;
case TYPE_I32:
(void) snprintf(valString, sizeof(valString), "%" PRId32 " ", this->m_val.i32Val);
break;
#endif
#if FW_HAS_64_BIT
case TYPE_U64:
(void) snprintf(valString, sizeof(valString), "%" PRIu64 " ", this->m_val.u64Val);
break;
case TYPE_I64:
(void) snprintf(valString, sizeof(valString), "%" PRId64 " ", this->m_val.i64Val);
break;
#endif
#if FW_HAS_F64
case TYPE_F64:
(void) snprintf(valString, sizeof(valString), "%lg ", this->m_val.f64Val);
break;
#endif
case TYPE_F32:
(void) snprintf(valString, sizeof(valString), "%g ", this->m_val.f32Val);
break;
case TYPE_BOOL:
(void) snprintf(valString, sizeof(valString), "%s ", this->m_val.boolVal?"T":"F");
break;
case TYPE_PTR:
(void) snprintf(valString, sizeof(valString), "%p ", this->m_val.ptrVal);
break;
default:
(void) snprintf(valString, sizeof(valString), "%s ", "NT");
break;
}
// NULL terminate
valString[sizeof(valString)-1] = 0;
if (append) {
dest += valString;
} else {
dest = valString;
}
}
#endif
}
| cpp |
fprime | data/projects/fprime/Fw/Types/SerialBuffer.hpp | // ======================================================================
// \title SerialBuffer.hpp
// \author bocchino
// \brief hpp file for SerialBuffer type
//
// \copyright
// Copyright (C) 2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_SerialBuffer_HPP
#define Fw_SerialBuffer_HPP
#include <FpConfig.hpp>
#include "Fw/Types/Serializable.hpp"
namespace Fw {
//! \class SerialBuffer
//! \brief A variable-length serializable buffer
//!
class SerialBuffer :
public SerializeBufferBase
{
public:
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Construct a SerialBuffer
//!
SerialBuffer(
U8 *const data, //!< Pointer to the data
const U32 capacity //!< The buffer capacity
);
public:
// ----------------------------------------------------------------------
// Pure virtual methods from SerializeBufferBase
// ----------------------------------------------------------------------
NATIVE_UINT_TYPE getBuffCapacity() const;
U8* getBuffAddr();
const U8* getBuffAddr() const;
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Fill the buffer to capacity with preexisting data
void fill();
//! Push n bytes onto the buffer
SerializeStatus pushBytes(
const U8 *const addr, //!< Address of bytes to push
const NATIVE_UINT_TYPE n //!< Number of bytes
);
//! Pop n bytes off the buffer
SerializeStatus popBytes(
U8 *const addr, //!< Address of bytes to pop
NATIVE_UINT_TYPE n //!< Number of bytes to pop
);
private:
// ----------------------------------------------------------------------
// Data
// ----------------------------------------------------------------------
//! The data
U8 *const m_data;
//! The capacity
const U32 m_capacity;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/Serializable.cpp | #include <Fw/Types/Serializable.hpp>
#include <cstring> // memcpy
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/StringType.hpp>
#include <cstdio>
#include <FpConfig.hpp>
#ifdef BUILD_UT
#include <iomanip>
#include <Fw/Types/String.hpp>
#endif
// Some macros/functions to optimize for architectures
namespace Fw {
Serializable::Serializable() {
}
Serializable::~Serializable() {
}
#if FW_SERIALIZABLE_TO_STRING || FW_ENABLE_TEXT_LOGGING || BUILD_UT
void Serializable::toString(StringBase& text) const {
text = "NOSPEC"; // set to not specified.
}
#endif
#ifdef BUILD_UT
std::ostream& operator<<(std::ostream& os, const Serializable& val) {
Fw::String out;
val.toString(out);
os << out;
return os;
}
#endif
SerializeBufferBase::SerializeBufferBase() :
m_serLoc(0), m_deserLoc(0) {
}
SerializeBufferBase::~SerializeBufferBase() {
}
void SerializeBufferBase::copyFrom(const SerializeBufferBase& src) {
this->m_serLoc = src.m_serLoc;
this->m_deserLoc = src.m_deserLoc;
FW_ASSERT(src.getBuffAddr());
FW_ASSERT(this->getBuffAddr());
// destination has to be same or bigger
FW_ASSERT(src.getBuffLength() <= this->getBuffCapacity(),src.getBuffLength(),this->getBuffLength());
(void) memcpy(this->getBuffAddr(),src.getBuffAddr(),this->m_serLoc);
}
// Copy constructor doesn't make sense in this virtual class as there is nothing to copy. Derived classes should
// call the empty constructor and then call their own copy function
SerializeBufferBase& SerializeBufferBase::operator=(const SerializeBufferBase &src) { // lgtm[cpp/rule-of-two]
this->copyFrom(src);
return *this;
}
// serialization routines
SerializeStatus SerializeBufferBase::serialize(U8 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
this->getBuffAddr()[this->m_serLoc] = val;
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serialize(I8 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
#if FW_HAS_16_BIT==1
SerializeStatus SerializeBufferBase::serialize(U16 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
// MSB first
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val >> 8);
this->getBuffAddr()[this->m_serLoc + 1] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serialize(I16 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
// MSB first
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val >> 8);
this->getBuffAddr()[this->m_serLoc + 1] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
#endif
#if FW_HAS_32_BIT==1
SerializeStatus SerializeBufferBase::serialize(U32 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
// MSB first
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val >> 24);
this->getBuffAddr()[this->m_serLoc + 1] = static_cast<U8>(val >> 16);
this->getBuffAddr()[this->m_serLoc + 2] = static_cast<U8>(val >> 8);
this->getBuffAddr()[this->m_serLoc + 3] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serialize(I32 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
// MSB first
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val >> 24);
this->getBuffAddr()[this->m_serLoc + 1] = static_cast<U8>(val >> 16);
this->getBuffAddr()[this->m_serLoc + 2] = static_cast<U8>(val >> 8);
this->getBuffAddr()[this->m_serLoc + 3] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
#endif
#if FW_HAS_64_BIT==1
SerializeStatus SerializeBufferBase::serialize(U64 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
// MSB first
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val >> 56);
this->getBuffAddr()[this->m_serLoc + 1] = static_cast<U8>(val >> 48);
this->getBuffAddr()[this->m_serLoc + 2] = static_cast<U8>(val >> 40);
this->getBuffAddr()[this->m_serLoc + 3] = static_cast<U8>(val >> 32);
this->getBuffAddr()[this->m_serLoc + 4] = static_cast<U8>(val >> 24);
this->getBuffAddr()[this->m_serLoc + 5] = static_cast<U8>(val >> 16);
this->getBuffAddr()[this->m_serLoc + 6] = static_cast<U8>(val >> 8);
this->getBuffAddr()[this->m_serLoc + 7] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serialize(I64 val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(val)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
// MSB first
this->getBuffAddr()[this->m_serLoc + 0] = static_cast<U8>(val >> 56);
this->getBuffAddr()[this->m_serLoc + 1] = static_cast<U8>(val >> 48);
this->getBuffAddr()[this->m_serLoc + 2] = static_cast<U8>(val >> 40);
this->getBuffAddr()[this->m_serLoc + 3] = static_cast<U8>(val >> 32);
this->getBuffAddr()[this->m_serLoc + 4] = static_cast<U8>(val >> 24);
this->getBuffAddr()[this->m_serLoc + 5] = static_cast<U8>(val >> 16);
this->getBuffAddr()[this->m_serLoc + 6] = static_cast<U8>(val >> 8);
this->getBuffAddr()[this->m_serLoc + 7] = static_cast<U8>(val);
this->m_serLoc += sizeof(val);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
#endif
#if FW_HAS_F64 && FW_HAS_64_BIT
SerializeStatus SerializeBufferBase::serialize(F64 val) {
// floating point values need to be byte-swapped as well, so copy to U64 and use that routine
U64 u64Val;
(void) memcpy(&u64Val, &val, sizeof(val));
return this->serialize(u64Val);
}
#endif
SerializeStatus SerializeBufferBase::serialize(F32 val) {
// floating point values need to be byte-swapped as well, so copy to U32 and use that routine
U32 u32Val;
(void) memcpy(&u32Val, &val, sizeof(val));
return this->serialize(u32Val);
}
SerializeStatus SerializeBufferBase::serialize(bool val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(U8)) - 1 >= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
FW_ASSERT(this->getBuffAddr());
if (val) {
this->getBuffAddr()[this->m_serLoc + 0] = FW_SERIALIZE_TRUE_VALUE;
} else {
this->getBuffAddr()[this->m_serLoc + 0] = FW_SERIALIZE_FALSE_VALUE;
}
this->m_serLoc += sizeof(U8);
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serialize(const void* val) {
if (this->m_serLoc + static_cast<Serializable::SizeType>(sizeof(void*)) - 1
>= this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
return this->serialize(reinterpret_cast<POINTER_CAST>(val));
}
SerializeStatus SerializeBufferBase::serialize(const U8* buff, Serializable::SizeType length) {
return this->serialize(buff, static_cast<FwSizeType>(length), Serialization::INCLUDE_LENGTH);
}
SerializeStatus SerializeBufferBase::serialize(const U8* buff, Serializable::SizeType length, bool noLength) {
return this->serialize(buff, static_cast<FwSizeType>(length), noLength ? Serialization::OMIT_LENGTH : Serialization::INCLUDE_LENGTH);
}
SerializeStatus SerializeBufferBase::serialize(const U8* buff, FwSizeType length, Fw::Serialization::t mode) {
// First serialize length
SerializeStatus stat;
if (mode == Serialization::INCLUDE_LENGTH) {
stat = this->serialize(static_cast<FwSizeStoreType>(length));
if (stat != FW_SERIALIZE_OK) {
return stat;
}
}
// make sure we have enough space
if (this->m_serLoc + length > this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
// copy buffer to our buffer
(void) memcpy(&this->getBuffAddr()[this->m_serLoc], buff, length);
this->m_serLoc += length;
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serialize(const Serializable &val) {
return val.serialize(*this);
}
SerializeStatus SerializeBufferBase::serialize(
const SerializeBufferBase& val) {
Serializable::SizeType size = val.getBuffLength();
if (this->m_serLoc + size + static_cast<Serializable::SizeType>(sizeof(FwSizeStoreType))
> this->getBuffCapacity()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
// First, serialize size
SerializeStatus stat = this->serialize(static_cast<FwSizeStoreType>(size));
if (stat != FW_SERIALIZE_OK) {
return stat;
}
FW_ASSERT(this->getBuffAddr());
FW_ASSERT(val.getBuffAddr());
// serialize buffer
(void) memcpy(&this->getBuffAddr()[this->m_serLoc], val.getBuffAddr(), size);
this->m_serLoc += size;
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::serializeSize(const FwSizeType size) {
SerializeStatus status = FW_SERIALIZE_OK;
if ((size < std::numeric_limits<FwSizeStoreType>::min()) || (size > std::numeric_limits<FwSizeStoreType>::max())) {
status = FW_SERIALIZE_FORMAT_ERROR;
}
if (status == FW_SERIALIZE_OK) {
status = this->serialize(static_cast<FwSizeStoreType>(size));
}
return status;
}
// deserialization routines
SerializeStatus SerializeBufferBase::deserialize(U8 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
val = this->getBuffAddr()[this->m_deserLoc + 0];
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(I8 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
val = static_cast<I8>(this->getBuffAddr()[this->m_deserLoc + 0]);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
#if FW_HAS_16_BIT==1
SerializeStatus SerializeBufferBase::deserialize(U16 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
// MSB first
val = static_cast<U16>(
((this->getBuffAddr()[this->m_deserLoc + 1]) << 0) |
((this->getBuffAddr()[this->m_deserLoc + 0]) << 8)
);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(I16 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
// MSB first
val = static_cast<I16>(
((this->getBuffAddr()[this->m_deserLoc + 1]) << 0) |
((this->getBuffAddr()[this->m_deserLoc + 0]) << 8)
);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
#endif
#if FW_HAS_32_BIT==1
SerializeStatus SerializeBufferBase::deserialize(U32 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
// MSB first
val = (static_cast<U32>(this->getBuffAddr()[this->m_deserLoc + 3]) << 0)
| (static_cast<U32>(this->getBuffAddr()[this->m_deserLoc + 2]) << 8)
| (static_cast<U32>(this->getBuffAddr()[this->m_deserLoc + 1]) << 16)
| (static_cast<U32>(this->getBuffAddr()[this->m_deserLoc + 0]) << 24);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(I32 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
// MSB first
val = (static_cast<I32>(this->getBuffAddr()[this->m_deserLoc + 3]) << 0)
| (static_cast<I32>(this->getBuffAddr()[this->m_deserLoc + 2]) << 8)
| (static_cast<I32>(this->getBuffAddr()[this->m_deserLoc + 1]) << 16)
| (static_cast<I32>(this->getBuffAddr()[this->m_deserLoc + 0]) << 24);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
#endif
#if FW_HAS_64_BIT==1
SerializeStatus SerializeBufferBase::deserialize(U64 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
// MSB first
val = (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 7]) << 0)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 6]) << 8)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 5]) << 16)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 4]) << 24)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 3]) << 32)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 2]) << 40)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 1]) << 48)
| (static_cast<U64>(this->getBuffAddr()[this->m_deserLoc + 0]) << 56);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(I64 &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(val))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
// MSB first
val = (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 7]) << 0)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 6]) << 8)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 5]) << 16)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 4]) << 24)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 3]) << 32)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 2]) << 40)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 1]) << 48)
| (static_cast<I64>(this->getBuffAddr()[this->m_deserLoc + 0]) << 56);
this->m_deserLoc += sizeof(val);
return FW_SERIALIZE_OK;
}
#endif
#if FW_HAS_F64
SerializeStatus SerializeBufferBase::deserialize(F64 &val) {
// deserialize as 64-bit int to handle endianness
U64 tempVal;
SerializeStatus stat = this->deserialize(tempVal);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// copy to argument
(void) memcpy(&val, &tempVal, sizeof(val));
return FW_SERIALIZE_OK;
}
#endif
SerializeStatus SerializeBufferBase::deserialize(bool &val) {
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < static_cast<Serializable::SizeType>(sizeof(U8))) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// read from current location
FW_ASSERT(this->getBuffAddr());
if (FW_SERIALIZE_TRUE_VALUE == this->getBuffAddr()[this->m_deserLoc + 0]) {
val = true;
} else if (FW_SERIALIZE_FALSE_VALUE == this->getBuffAddr()[this->m_deserLoc + 0]) {
val = false;
} else {
return FW_DESERIALIZE_FORMAT_ERROR;
}
this->m_deserLoc += sizeof(U8);
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(void*& val) {
// Deserialize as pointer cast, then convert to void*
PlatformPointerCastType pointerCastVal = 0;
const SerializeStatus stat = this->deserialize(pointerCastVal);
if (stat == FW_SERIALIZE_OK) {
val = reinterpret_cast<void*>(pointerCastVal);
}
return stat;
}
SerializeStatus SerializeBufferBase::deserialize(F32 &val) {
// deserialize as 64-bit int to handle endianness
U32 tempVal;
SerializeStatus stat = this->deserialize(tempVal);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
(void) memcpy(&val, &tempVal, sizeof(val));
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(U8* buff, Serializable::SizeType& length) {
FwSizeType length_in_out = static_cast<FwSizeType>(length);
SerializeStatus status = this->deserialize(buff, length_in_out, Serialization::INCLUDE_LENGTH);
length = static_cast<Serializable::SizeType>(length_in_out);
return status;
}
SerializeStatus SerializeBufferBase::deserialize(U8* buff, Serializable::SizeType& length, bool noLength) {
FwSizeType length_in_out = static_cast<FwSizeType>(length);
SerializeStatus status = this->deserialize(buff, length_in_out, noLength ? Serialization::OMIT_LENGTH : Serialization::INCLUDE_LENGTH);
length = static_cast<Serializable::SizeType>(length_in_out);
return status;
}
SerializeStatus SerializeBufferBase::deserialize(U8* buff, FwSizeType& length, Serialization::t mode) {
FW_ASSERT(this->getBuffAddr());
if (mode == Serialization::INCLUDE_LENGTH) {
FwSizeStoreType storedLength;
SerializeStatus stat = this->deserialize(storedLength);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// make sure it fits
if ((storedLength > this->getBuffLeft()) or (storedLength > length)) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
(void) memcpy(buff, &this->getBuffAddr()[this->m_deserLoc], storedLength);
length = static_cast<FwSizeType>(storedLength);
} else {
// make sure enough is left
if (length > this->getBuffLeft()) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
(void) memcpy(buff, &this->getBuffAddr()[this->m_deserLoc], length);
}
this->m_deserLoc += length;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserialize(Serializable &val) {
return val.deserialize(*this);
}
SerializeStatus SerializeBufferBase::deserialize(SerializeBufferBase& val) {
FW_ASSERT(val.getBuffAddr());
SerializeStatus stat = FW_SERIALIZE_OK;
FwSizeStoreType storedLength;
stat = this->deserialize(storedLength);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// make sure destination has enough room
if ((storedLength > val.getBuffCapacity()) or (storedLength > this->getBuffLeft()) ) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
FW_ASSERT(this->getBuffAddr());
(void) memcpy(val.getBuffAddr(), &this->getBuffAddr()[this->m_deserLoc],
storedLength);
stat = val.setBuffLen(storedLength);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
this->m_deserLoc += storedLength;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::deserializeSize(FwSizeType& size) {
FwSizeStoreType storedSize = 0;
Fw::SerializeStatus status = this->deserialize(storedSize);
if (status == FW_SERIALIZE_OK) {
size = static_cast<FwSizeType>(storedSize);
}
return status;
}
void SerializeBufferBase::resetSer() {
this->m_deserLoc = 0;
this->m_serLoc = 0;
}
void SerializeBufferBase::resetDeser() {
this->m_deserLoc = 0;
}
SerializeStatus SerializeBufferBase::serializeSkip(FwSizeType numBytesToSkip)
{
Fw::SerializeStatus status = FW_SERIALIZE_OK;
// compute new deser loc
const FwSizeType newSerLoc = this->m_serLoc + numBytesToSkip;
// check for room
if (newSerLoc <= this->getBuffCapacity()) {
// update deser loc
this->m_serLoc = newSerLoc;
}
else {
status = FW_SERIALIZE_NO_ROOM_LEFT;
}
return status;
}
SerializeStatus SerializeBufferBase::deserializeSkip(FwSizeType numBytesToSkip)
{
// check for room
if (this->getBuffLength() == this->m_deserLoc) {
return FW_DESERIALIZE_BUFFER_EMPTY;
} else if (this->getBuffLength() - this->m_deserLoc < numBytesToSkip) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// update location in buffer to skip the value
this->m_deserLoc += numBytesToSkip;
return FW_SERIALIZE_OK;
}
SerializeStatus SerializeBufferBase::moveSerToOffset(FwSizeType offset) {
// Reset serialization
this->resetSer();
// Advance to offset
return this->serializeSkip(offset);
}
SerializeStatus SerializeBufferBase::moveDeserToOffset(FwSizeType offset) {
// Reset deserialization
this->resetDeser();
// Advance to offset
return this->deserializeSkip(offset);
}
Serializable::SizeType SerializeBufferBase::getBuffLength() const {
return this->m_serLoc;
}
SerializeStatus SerializeBufferBase::setBuff(const U8* src, Serializable::SizeType length) {
if (this->getBuffCapacity() < length) {
return FW_SERIALIZE_NO_ROOM_LEFT;
} else {
FW_ASSERT(src);
FW_ASSERT(this->getBuffAddr());
memcpy(this->getBuffAddr(), src, length);
this->m_serLoc = length;
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
}
SerializeStatus SerializeBufferBase::setBuffLen(Serializable::SizeType length) {
if (this->getBuffCapacity() < length) {
return FW_SERIALIZE_NO_ROOM_LEFT;
} else {
this->m_serLoc = length;
this->m_deserLoc = 0;
return FW_SERIALIZE_OK;
}
}
Serializable::SizeType SerializeBufferBase::getBuffLeft() const {
return this->m_serLoc - this->m_deserLoc;
}
SerializeStatus SerializeBufferBase::copyRaw(SerializeBufferBase& dest, Serializable::SizeType size) {
// make sure there is sufficient size in destination
if (dest.getBuffCapacity() < size) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
// otherwise, set destination buffer to data from deserialization pointer plus size
SerializeStatus stat = dest.setBuff(&this->getBuffAddr()[this->m_deserLoc],size);
if (stat == FW_SERIALIZE_OK) {
this->m_deserLoc += size;
}
return stat;
}
SerializeStatus SerializeBufferBase::copyRawOffset(SerializeBufferBase& dest, Serializable::SizeType size) {
// make sure there is sufficient size in destination
if (dest.getBuffCapacity() < size + dest.getBuffLength()) {
return FW_SERIALIZE_NO_ROOM_LEFT;
}
// make sure there is sufficient buffer in source
if (this->getBuffLeft() < size) {
return FW_DESERIALIZE_SIZE_MISMATCH;
}
// otherwise, serialize bytes to destination without writing length
SerializeStatus stat = dest.serialize(&this->getBuffAddr()[this->m_deserLoc], size, true);
if (stat == FW_SERIALIZE_OK) {
this->m_deserLoc += size;
}
return stat;
}
// return address of buffer not yet deserialized. This is used
// to copy the remainder of a buffer.
const U8* SerializeBufferBase::getBuffAddrLeft() const {
return &this->getBuffAddr()[this->m_deserLoc];
}
//!< gets address of end of serialization. Used to manually place data at the end
U8* SerializeBufferBase::getBuffAddrSer() {
return &this->getBuffAddr()[this->m_serLoc];
}
#ifdef BUILD_UT
bool SerializeBufferBase::operator==(const SerializeBufferBase& other) const {
if (this->getBuffLength() != other.getBuffLength()) {
return false;
}
const U8* us = this->getBuffAddr();
const U8* them = other.getBuffAddr();
FW_ASSERT(us);
FW_ASSERT(them);
for (Serializable::SizeType byte = 0; byte < this->getBuffLength(); byte++) {
if (us[byte] != them[byte]) {
return false;
}
}
return true;
}
std::ostream& operator<<(std::ostream& os, const SerializeBufferBase& buff) {
const U8* us = buff.getBuffAddr();
FW_ASSERT(us);
for (Serializable::SizeType byte = 0; byte < buff.getBuffLength(); byte++) {
os << "[" << std::setw(2) << std::hex << std::setfill('0') << us[byte] << "]" << std::dec;
}
return os;
}
#endif
ExternalSerializeBuffer::ExternalSerializeBuffer(U8* buffPtr, Serializable::SizeType size) {
this->setExtBuffer(buffPtr,size);
}
ExternalSerializeBuffer::ExternalSerializeBuffer() {
this->clear();
}
void ExternalSerializeBuffer::setExtBuffer(U8* buffPtr, Serializable::SizeType size) {
FW_ASSERT(buffPtr != nullptr);
this->m_buff = buffPtr;
this->m_buffSize = size;
}
void ExternalSerializeBuffer::clear() {
this->m_buff = nullptr;
this->m_buffSize = 0;
}
Serializable::SizeType ExternalSerializeBuffer::getBuffCapacity() const {
return this->m_buffSize;
}
U8* ExternalSerializeBuffer::getBuffAddr() {
return this->m_buff;
}
const U8* ExternalSerializeBuffer::getBuffAddr() const {
return this->m_buff;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/PolyType.hpp | #ifndef FW_POLY_TYPE_HPP
#define FW_POLY_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class PolyType : public Serializable {
public:
PolyType(U8 val); //!< U8 constructor
operator U8(); //!< U8 cast operator
void get(U8& val); //!< U8 accessor
bool isU8(); //!< U8 checker
PolyType& operator=(U8 val); //!< U8 operator=
PolyType(I8 val); //!< I8 constructor
operator I8(); //!< I8 cast operator
void get(I8& val); //!< I8 accessor
bool isI8(); //!< I8 checker
PolyType& operator=(I8 val); //!< I8 operator=
#if FW_HAS_16_BIT
PolyType(U16 val); //!< U16 constructor
operator U16(); //!< U16 cast operator
void get(U16& val); //!< U16 accessor
bool isU16(); //!< U16 checker
PolyType& operator=(U16 val); //!< I8 operator=
PolyType(I16 val); //!< I16 constructor
operator I16(); //!< I16 cast operator
void get(I16& val); //!< I16 accessor
bool isI16(); //!< I16 checker
PolyType& operator=(I16 val); //!< I16 operator=
#endif
#if FW_HAS_32_BIT
PolyType(U32 val); //!< U32 constructor
operator U32(); //!< U32 cast operator
void get(U32& val); //!< U32 accessor
bool isU32(); //!< U32 checker
PolyType& operator=(U32 val); //!< U32 operator=
PolyType(I32 val); //!< I32 constructor
operator I32(); //!< I32 cast operator
void get(I32& val); //!< I32 accessor
bool isI32(); //!< I32 checker
PolyType& operator=(I32 val); //!< I32 operator=
#endif
#if FW_HAS_64_BIT
PolyType(U64 val); //!< U64 constructor
operator U64(); //!< U64 cast operator
void get(U64& val); //!< U64 accessor
bool isU64(); //!< U64 checker
PolyType& operator=(U64 val); //!< U64 operator=
PolyType(I64 val); //!< I64 constructor
operator I64(); //!< I64 cast operator
void get(I64& val); //!< I64 accessor
bool isI64(); //!< I64 checker
PolyType& operator=(I64 val); //!< I64 operator=
#endif
#if FW_HAS_F64
PolyType(F64 val); //!< F64 constructor
operator F64(); //!< F64 cast operator
void get(F64& val); //!< F64 accessor
bool isF64(); //!< F64 checker
PolyType& operator=(F64 val); //!< F64 operator=
#endif
PolyType(F32 val); //!< F32 constructor
operator F32(); //!< F32 cast operator
void get(F32& val); //!< F32 accessor
bool isF32(); //!< F32 checker
PolyType& operator=(F32 val); //!< F32 operator=
PolyType(bool val); //!< bool constructor
operator bool(); //!< bool cast operator
void get(bool& val); //!< bool accessor
bool isBool(); //!< bool checker
PolyType& operator=(bool val); //!< bool operator=
PolyType(void* val); //!< void* constructor.
operator void*(); //!< void* cast operator
void get(void*& val); //!< void* accessor
bool isPtr(); //!< void* checker
PolyType& operator=(void* val); //!< void* operator=
PolyType(); //!< default constructor
PolyType(const PolyType &original); //!< copy constructor
virtual ~PolyType(); //!< destructor
#if FW_SERIALIZABLE_TO_STRING || BUILD_UT
void toString(StringBase& dest, bool append) const; //!< get string representation
void toString(StringBase& dest) const; //!< get string representation
#endif
PolyType& operator=(const PolyType &src); //!< PolyType operator=
bool operator<(const PolyType &other) const; //!< PolyType operator<
bool operator>(const PolyType &other) const; //!< PolyType operator>
bool operator>=(const PolyType &other) const; //!< PolyType operator>=
bool operator<=(const PolyType &other) const; //!< PolyType operator<=
bool operator==(const PolyType &other) const; //!< PolyType operator==
bool operator!=(const PolyType &other) const; //!< PolyType operator!=
SerializeStatus serialize(SerializeBufferBase& buffer) const; //!< Serialize function
SerializeStatus deserialize(SerializeBufferBase& buffer); //!< Deserialize function
PRIVATE:
typedef enum {
TYPE_NOTYPE, // !< No type stored yet
TYPE_U8, // !< U8 type stored
TYPE_I8, // !< I8 type stored
#if FW_HAS_16_BIT
TYPE_U16, // !< U16 type stored
TYPE_I16, // !< I16 type stored
#endif
#if FW_HAS_32_BIT
TYPE_U32, // !< U32 type stored
TYPE_I32, // !< I32 type stored
#endif
#if FW_HAS_64_BIT
TYPE_U64, // !< U64 type stored
TYPE_I64, // !< I64 type stored
#endif
TYPE_F32, // !< F32 type stored
#if FW_HAS_F64
TYPE_F64, // !< F64 type stored
#endif
TYPE_BOOL, // !< bool type stored
TYPE_PTR // !< pointer type stored
} Type;
Type m_dataType; //!< member that indicates type being stored
union PolyVal {
U8 u8Val; //!< U8 data storage
I8 i8Val; //!< I8 data storage
#if FW_HAS_16_BIT
U16 u16Val; //!< U16 data storage
I16 i16Val; //!< I16 data storage
#endif
#if FW_HAS_32_BIT
U32 u32Val; //!< U32 data storage
I32 i32Val; //!< I32 data storage
#endif
#if FW_HAS_64_BIT
U64 u64Val; //!< U64 data storage
I64 i64Val; //!< I64 data storage
#endif
#if FW_HAS_F64
F64 f64Val; //!< F64 data storage
#endif
F32 f32Val; // !< F32 data storage
void* ptrVal; // !< pointer data storage
bool boolVal; // !< bool data storage
} m_val; // !< stores data value
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_POLY, //!< typeid for PolyType
SERIALIZED_SIZE = sizeof(FwEnumStoreType) + sizeof(PolyVal) //!< stored serialized size
};
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/StringUtils.cpp | #include "StringUtils.hpp"
#include <Fw/Types/Assert.hpp>
#include <cstring>
char* Fw::StringUtils::string_copy(char* destination, const char* source, U32 num) {
// Handle self-copy and 0 bytes copy
if(destination == source || num == 0) {
return destination;
}
FW_ASSERT(source != nullptr);
FW_ASSERT(destination != nullptr);
// Copying an overlapping range is undefined
U32 source_len = string_length(source, num) + 1;
FW_ASSERT(source + source_len <= destination || destination + num <= source);
char* returned = strncpy(destination, source, num);
destination[num - 1] = '\0';
return returned;
}
U32 Fw::StringUtils::string_length(const CHAR* source, U32 max_len) {
U32 length = 0;
FW_ASSERT(source != nullptr);
for (length = 0; length < max_len; length++) {
if (source[length] == '\0') {
break;
}
}
return length;
}
| cpp |
fprime | data/projects/fprime/Fw/Types/MemAllocator.hpp | /**
* \file
* \author T. Canham
* \brief Defines a base class for a memory allocator for classes.
*
* A memory allocator is a class that provides memory for a component.
* This allows a user of the class to allocate memory as they choose.
* The user writes derived classes for each of the allocator types.
*
* \copyright
* Copyright 2009-2020, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef TYPES_MEMALLOCATOR_HPP_
#define TYPES_MEMALLOCATOR_HPP_
#include <FpConfig.hpp>
/*!
*
* This class is a pure virtual base class for memory allocators in Fprime.
* The intent is to provide derived classes the get memory from different sources.
* The base class can be passed to classes so the allocator can be selected at the
* system level, and different allocators can be used by different components as
* appropriate.
*
* The identifier can be used to look up a pre-allocated buffer by ID in an
* embedded system. Identifiers may be used only in a single call to an invocation.
* Some implementations of MemAllocator discard the identifier but components using
* the MemAllocator interface should not depend on the identifier to be discarded.
*
* The size is the requested size of the memory. If the allocator cannot return the
* requested amount, it should return the actual amount and users should check.
*
* The recoverable flag is intended to be used in embedded environments where
* memory can survive a processor reset and data can be recovered. The component
* using the allocator can then use the data. Any integrity checks are up to the
* user of the memory.
*
*/
namespace Fw {
class MemAllocator {
public:
//! Allocate memory
/*!
* \param identifier the memory segment identifier, each identifier is to be used in once single allocation
* \param size the requested size - changed to actual if different
* \param recoverable - flag to indicate the memory could be recoverable
* \return the pointer to memory. Zero if unable to allocate
*/
virtual void *allocate(
const NATIVE_UINT_TYPE identifier,
NATIVE_UINT_TYPE &size,
bool& recoverable)=0;
//! Deallocate memory
/*!
* \param identifier the memory segment identifier, each identifier is to be used in once single allocation
* \param ptr the pointer to memory returned by allocate()
*/
virtual void deallocate(
const NATIVE_UINT_TYPE identifier,
void* ptr)=0;
protected:
MemAllocator();
virtual ~MemAllocator();
private:
MemAllocator(MemAllocator&); //!< disable
MemAllocator(MemAllocator*); //!< disable
};
} /* namespace Fw */
#endif /* TYPES_MEMALLOCATOR_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Types/ByteArray.hpp | // ======================================================================
// \title ByteArray.hpp
// \author bocchino
// \brief hpp file for ByteArray type
//
// \copyright
// Copyright (C) 2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_ByteArray_HPP
#define Fw_ByteArray_HPP
#include <FpConfig.hpp>
namespace Fw {
//! \class ByteArray
//! \brief A variable-length byte array
//!
struct ByteArray {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Construct a ByteArray
//!
ByteArray(
U8 *const bytes, //!< Pointer to the bytes
const U32 size //!< The array size
) :
bytes(bytes),
size(size)
{
}
// ----------------------------------------------------------------------
// Data
// ----------------------------------------------------------------------
//! The bytes
U8 *const bytes;
//! The size
const U32 size;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/default/DefaultTypes.hpp | /**
* \brief DefaultTypes.hpp provides fallback defaults for the platform types
*
* This fill contains default implementations for types typically defined in
* PlatformTypes.hpp. These default implementations are based on x86_64 Linux
* but are often appropriate for most systems.
*/
#include <limits>
/**
* Default implementation for deprecated (see note)
*/
#ifndef PLATFORM_INT_TYPE_DEFINED
typedef int PlatformIntType;
extern const PlatformIntType PlatformIntType_MIN;
extern const PlatformIntType PlatformIntType_MAX;
#define PLATFORM_INT_TYPE_DEFINED
#define PRI_PlatformIntType "d"
#endif
/**
* Default implementation for deprecated (see note)
*/
#ifndef PLATFORM_UINT_TYPE_DEFINED
typedef unsigned int PlatformUIntType;
extern const PlatformUIntType PlatformUIntType_MIN;
extern const PlatformUIntType PlatformUIntType_MAX;
#define PLATFORM_UINT_TYPE_DEFINED
#define PRI_PlatformUIntType "ud"
#endif
/**
* Default implementation for ports indices
*/
#ifndef PLATFORM_INDEX_TYPE_DEFINED
typedef PlatformIntType PlatformIndexType;
extern const PlatformIndexType PlatformIndexType_MIN;
extern const PlatformIndexType PlatformIndexType_MAX;
#define PLATFORM_INDEX_TYPE_DEFINED
#define PRI_PlatformIndexType PRI_PlatformIntType
#endif
/**
* Default implementation for sizes
*/
#ifndef PLATFORM_SIZE_TYPE_DEFINED
typedef PlatformUIntType PlatformSizeType;
extern const PlatformSizeType PlatformSizeType_MIN;
extern const PlatformSizeType PlatformSizeType_MAX;
#define PLATFORM_SIZE_TYPE_DEFINED
#define PRI_PlatformSizeType PRI_PlatformUIntType
#endif
/**
* Default implementation for argument to fw_assert
*/
#ifndef PLATFORM_ASSERT_ARG_TYPE_DEFINED
typedef PlatformIntType PlatformAssertArgType;
extern const PlatformAssertArgType PlatformAssertArgType_MIN;
extern const PlatformAssertArgType PlatformAssertArgType_MAX;
#define PLATFORM_ASSERT_ARG_TYPE_DEFINED
#define PRI_PlatformAssertArgType PRI_PlatformIntType
#endif
/**
* Default implementation for pointers stored as integers
*/
#ifndef PLATFORM_POINTER_CAST_TYPE_DEFINED
// Check for __SIZEOF_POINTER__ or cause error
#ifndef __SIZEOF_POINTER__
#error "Compiler does not support __SIZEOF_POINTER__, cannot use default for PlatformPointerCastType"
#endif
// Pointer sizes are determined by size of compiler
#if __SIZEOF_POINTER__ == 8
typedef uint64_t PlatformPointerCastType;
extern const PlatformPointerCastType PlatformPointerCastType_MIN;
extern const PlatformPointerCastType PlatformPointerCastType_MAX;
#define PRI_PlatformPointerCastType PRIx64
#elif __SIZEOF_POINTER__ == 4
typedef uint32_t PlatformPointerCastType;
extern const PlatformPointerCastType PlatformPointerCastType_MIN;
extern const PlatformPointerCastType PlatformPointerCastType_MAX;
#define PRI_PlatformPointerCastType PRIx32
#elif __SIZEOF_POINTER__ == 2
typedef uint16_t PlatformPointerCastType;
extern const PlatformPointerCastType PlatformPointerCastType_MIN;
extern const PlatformPointerCastType PlatformPointerCastType_MAX;
#define PRI_PlatformPointerCastType PRIx16
#else
typedef uint8_t PlatformPointerCastType;
extern const PlatformPointerCastType PlatformPointerCastType_MIN;
extern const PlatformPointerCastType PlatformPointerCastType_MAX;
#define PRI_PlatformPointerCastType PRIx8
#endif
#define PLATFORM_POINTER_CAST_TYPE_DEFINED
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/GTest/Bytes.hpp | // ======================================================================
// \title Fw/Types/GTest/Bytes.hpp
// \author bocchino
// \brief hpp file for Bytes
//
// \copyright
// Copyright (C) 2016 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef Fw_GTest_Bytes_HPP
#define Fw_GTest_Bytes_HPP
#include <gtest/gtest.h>
#include <FpConfig.hpp>
namespace Fw {
namespace GTest {
//! \class Bytes
//! \brief A byte string for testing
//!
class Bytes {
public:
//! Construct a Bytes object
Bytes(
const U8 *const bytes, //!< The byte array
const size_t size //!< The size
) :
bytes(bytes),
size(size)
{
}
public:
//! Compare two Bytes objects
static void compare(
const Bytes& expected, //! Expected value
const Bytes& actual //! Actual value
);
private:
//! The bytes
const U8 *const bytes;
//! The size
const size_t size;
};
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Types/GTest/Bytes.cpp | // ======================================================================
// \title ASTERIA/Types/GTest/Bytes.cpp
// \author bocchino
// \brief cpp file for Bytes
//
// \copyright
// Copyright (C) 2016, California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/Types/GTest/Bytes.hpp>
namespace Fw {
namespace GTest {
void Bytes ::
compare(
const Bytes& expected,
const Bytes& actual
)
{
ASSERT_EQ(expected.size, actual.size);
for (size_t i = 0; i < expected.size; ++i)
ASSERT_EQ(expected.bytes[i], actual.bytes[i])
<< "At i=" << i << "\n";
}
}
}
| cpp |
fprime | data/projects/fprime/Fw/Types/test/ut/TypesTest.cpp | #include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Os/IntervalTimer.hpp>
#include <Os/InterruptLock.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/String.hpp>
#include <Fw/Types/InternalInterfaceString.hpp>
#include <Fw/Types/ObjectName.hpp>
#include <Fw/Types/PolyType.hpp>
#include <Fw/Types/MallocAllocator.hpp>
//
// Created by mstarch on 12/7/20.
//
#include <cstring>
#include <Fw/Types/StringUtils.hpp>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <iostream>
#include <iostream>
#define DEBUG_VERBOSE 0
#include <gtest/gtest.h>
class SerializeTestBuffer: public Fw::SerializeBufferBase {
public:
NATIVE_UINT_TYPE getBuffCapacity() const { // !< returns capacity, not current size, of buffer
return sizeof(m_testBuff);
}
U8* getBuffAddr() { // !< gets buffer address for data filling
return m_testBuff;
}
const U8* getBuffAddr() const { // !< gets buffer address for data reading
return m_testBuff;
}
private:
U8 m_testBuff[255];
};
TEST(SerializationTest,Serialization1) {
printf("Testing Serialization code\n");
SerializeTestBuffer buff;
#if DEBUG_VERBOSE
printf("U8 Test\n");
#endif
U8 u8t1 = 0xAB;
U8 u8t2 = 0;
U8* ptr = buff.getBuffAddr();
Fw::SerializeStatus stat1;
Fw::SerializeStatus stat2;
// Test chars
buff.resetSer();
stat1 = buff.serialize(u8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(0xAB,ptr[0]);
ASSERT_EQ(1,buff.m_serLoc);
stat2 = buff.deserialize(u8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(1,buff.m_deserLoc);
ASSERT_EQ(u8t2,u8t1);
#if DEBUG_VERBOSE
printf("Val: in: %d out: %d stat1: %d stat2: %d\n", u8t1, u8t2, stat1,
stat2);
printf("I8 Test\n");
#endif
buff.resetSer();
ASSERT_EQ(0,buff.m_serLoc);
ASSERT_EQ(0,buff.m_deserLoc);
I8 i8t1 = 0xFF;
I8 i8t2 = 0;
stat1 = buff.serialize(i8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(1,buff.m_serLoc);
ASSERT_EQ(0xFF,ptr[0]);
stat2 = buff.deserialize(i8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i8t1,i8t2);
ASSERT_EQ(1,buff.m_deserLoc);
buff.resetSer();
ASSERT_EQ(0,buff.m_serLoc);
ASSERT_EQ(0,buff.m_deserLoc);
// double check negative numbers
i8t1 = -100;
i8t2 = 0;
stat1 = buff.serialize(i8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(1,buff.m_serLoc);
stat2 = buff.deserialize(i8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i8t1,i8t2);
ASSERT_EQ(1,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %d out: %d stat1: %d stat2: %d\n", i8t1, i8t2, stat1,
stat2);
printf("U16 Test\n");
#endif
U16 u16t1 = 0xABCD;
U16 u16t2 = 0;
// Test shorts
buff.resetSer();
stat1 = buff.serialize(u16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(2,buff.m_serLoc);
ASSERT_EQ(0xAB,ptr[0]);
ASSERT_EQ(0xCD,ptr[1]);
stat2 = buff.deserialize(u16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u16t1,u16t2);
ASSERT_EQ(2,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %d out: %d stat1: %d stat2: %d\n", u16t1, u16t2, stat1,
stat2);
printf("I16 test\n");
#endif
I16 i16t1 = 0xABCD;
I16 i16t2 = 0;
buff.resetSer();
stat1 = buff.serialize(i16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(2,buff.m_serLoc);
// 2s complement
ASSERT_EQ(0xAB,ptr[0]);
ASSERT_EQ(0xCD,ptr[1]);
stat2 = buff.deserialize(i16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i16t1,i16t2);
ASSERT_EQ(2,buff.m_deserLoc);
// double check negative number
i16t1 = -1000;
i16t2 = 0;
buff.resetSer();
stat1 = buff.serialize(i16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(2,buff.m_serLoc);
stat2 = buff.deserialize(i16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i16t1,i16t2);
ASSERT_EQ(2,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %d out: %d stat1: %d stat2: %d\n", i16t1, i16t2, stat1,
stat2);
printf("U32 Test\n");
#endif
U32 u32t1 = 0xABCDEF12;
U32 u32t2 = 0;
// Test ints
buff.resetSer();
stat1 = buff.serialize(u32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(4,buff.m_serLoc);
ASSERT_EQ(0xAB,ptr[0]);
ASSERT_EQ(0xCD,ptr[1]);
ASSERT_EQ(0xEF,ptr[2]);
ASSERT_EQ(0x12,ptr[3]);
stat2 = buff.deserialize(u32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u32t1,u32t2);
ASSERT_EQ(4,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %d out: %d stat1: %d stat2: %d\n", u32t1, u32t2, stat1,
stat2);
printf("I32 Test\n");
#endif
I32 i32t1 = 0xABCDEF12;
I32 i32t2 = 0;
buff.resetSer();
stat1 = buff.serialize(i32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(4,buff.m_serLoc);
ASSERT_EQ(0xAB,ptr[0]);
ASSERT_EQ(0xCD,ptr[1]);
ASSERT_EQ(0xEF,ptr[2]);
ASSERT_EQ(0x12,ptr[3]);
stat2 = buff.deserialize(i32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(4,buff.m_deserLoc);
ASSERT_EQ(i32t1,i32t2);
// double check negative number
i32t1 = -1000000;
i32t2 = 0;
buff.resetSer();
stat1 = buff.serialize(i32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(4,buff.m_serLoc);
stat2 = buff.deserialize(i32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(4,buff.m_deserLoc);
ASSERT_EQ(i32t1,i32t2);
#if DEBUG_VERBOSE
printf("Val: in: %d out: %d stat1: %d stat2: %d\n", i32t1, i32t2, stat1,
stat2);
printf("U64 Test\n");
#endif
U64 u64t1 = 0x0123456789ABCDEF;
U64 u64t2 = 0;
// Test ints
buff.resetSer();
stat1 = buff.serialize(u64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(8,buff.m_serLoc);
ASSERT_EQ(0x01,ptr[0]);
ASSERT_EQ(0x23,ptr[1]);
ASSERT_EQ(0x45,ptr[2]);
ASSERT_EQ(0x67,ptr[3]);
ASSERT_EQ(0x89,ptr[4]);
ASSERT_EQ(0xAB,ptr[5]);
ASSERT_EQ(0xCD,ptr[6]);
ASSERT_EQ(0xEF,ptr[7]);
stat2 = buff.deserialize(u64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u64t1,u64t2);
ASSERT_EQ(8,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %lld out: %lld stat1: %d stat2: %d\n", u64t1, u64t2, stat1,
stat2);
printf("I64 Test\n");
#endif
I64 i64t1 = 0x0123456789ABCDEF;
I64 i64t2 = 0;
buff.resetSer();
stat1 = buff.serialize(i64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(8,buff.m_serLoc);
ASSERT_EQ(0x01,ptr[0]);
ASSERT_EQ(0x23,ptr[1]);
ASSERT_EQ(0x45,ptr[2]);
ASSERT_EQ(0x67,ptr[3]);
ASSERT_EQ(0x89,ptr[4]);
ASSERT_EQ(0xAB,ptr[5]);
ASSERT_EQ(0xCD,ptr[6]);
ASSERT_EQ(0xEF,ptr[7]);
stat2 = buff.deserialize(i64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i64t1,i64t2);
ASSERT_EQ(8,buff.m_deserLoc);
// double check negative number
i64t1 = -1000000000000;
i64t2 = 0;
buff.resetSer();
stat1 = buff.serialize(i64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(8,buff.m_serLoc);
stat2 = buff.deserialize(i64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i64t1,i64t2);
ASSERT_EQ(8,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %lld out: %lld stat1: %d stat2: %d\n", i64t1, i64t2, stat1,
stat2);
printf("F32 Test\n");
#endif
F32 f32t1 = -1.23;
F32 f32t2 = 0;
// Test ints
buff.resetSer();
stat1 = buff.serialize(f32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(4,buff.m_serLoc);
ASSERT_EQ(0xBF,ptr[0]);
ASSERT_EQ(0x9D,ptr[1]);
ASSERT_EQ(0x70,ptr[2]);
ASSERT_EQ(0xA4,ptr[3]);
stat2 = buff.deserialize(f32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_FLOAT_EQ(f32t1,f32t2);
ASSERT_EQ(4,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %f out: %f stat1: %d stat2: %d\n", f32t1, f32t2, stat1,
stat2);
printf("F64 Test\n");
#endif
F64 f64t1 = 100.232145345346534;
F64 f64t2 = 0;
buff.resetSer();
stat1 = buff.serialize(f64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(8,buff.m_serLoc);
ASSERT_EQ(0x40,ptr[0]);
ASSERT_EQ(0x59,ptr[1]);
ASSERT_EQ(0x0E,ptr[2]);
ASSERT_EQ(0xDB,ptr[3]);
ASSERT_EQ(0x78,ptr[4]);
ASSERT_EQ(0x26,ptr[5]);
ASSERT_EQ(0x8B,ptr[6]);
ASSERT_EQ(0xA6,ptr[7]);
stat2 = buff.deserialize(f64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_DOUBLE_EQ(f32t1,f32t2);
ASSERT_EQ(8,buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %lf out: %lf stat1: %d stat2: %d\n", f64t1, f64t2, stat1,
stat2);
printf("bool Test\n");
#endif
bool boolt1 = true;
bool boolt2 = false;
buff.resetSer();
stat1 = buff.serialize(boolt1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat2 = buff.deserialize(boolt2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(boolt1,boolt2);
#if DEBUG_VERBOSE
printf("Val: in: %s out: %s stat1: %d stat2: %d\n",
boolt1 ? "TRUE" : "FALSE", boolt2 ? "TRUE" : "FALSE", stat1, stat2);
printf("Pointer Test\n");
#endif
U32 u32Var = 0;
void* ptrt1 = &u32Var;
void* ptrt2 = nullptr;
buff.resetSer();
stat1 = buff.serialize(ptrt1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat2 = buff.deserialize(ptrt2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(ptrt1,ptrt2);
#if DEBUG_VERBOSE
printf("Val: in: %p out: %p stat1: %d stat2: %d\n",
ptrt1, ptrt2, stat1, stat2);
printf("Skip deserialization Tests\n");
#endif
// Test sizes
FwSizeType size1 = std::numeric_limits<FwSizeStoreType>::max();
FwSizeType size2 = 0;
buff.resetSer();
stat1 = buff.serializeSize(size1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat2 = buff.deserializeSize(size2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u64t1,u64t2);
ASSERT_EQ(sizeof(FwSizeStoreType),buff.m_deserLoc);
#if DEBUG_VERBOSE
printf("Val: in: %" PRI_FwSizeType " out: %" PRI_FwSizeType " stat1: %d stat2: %d\n",
size1, size2, stat1, stat2);
printf("Size Test\n");
#endif
// Test skipping:
buff.resetSer();
stat1 = buff.serialize(u32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat2 = buff.serialize(u32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
// should fail:
stat1 = buff.deserializeSkip(10);
ASSERT_EQ(Fw::FW_DESERIALIZE_SIZE_MISMATCH,stat1);
// skip everything:
stat1 = buff.deserializeSkip(4);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat2 = buff.deserializeSkip(4);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
// should fail:
stat1 = buff.deserializeSkip(4);
ASSERT_EQ(Fw::FW_DESERIALIZE_BUFFER_EMPTY,stat1);
// skip half/read half:
buff.resetDeser();
stat1 = buff.deserializeSkip(4);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
U32 u32val;
stat2 = buff.deserialize(u32val);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u32t2,u32val);
#if DEBUG_VERBOSE
printf("\nDeserialization Tests\n");
#endif
SerializeTestBuffer buff2;
// Do a series of serializations
u8t2 = 0;
i8t2 = 0;
u16t2 = 0;
i16t2 = 0;
u32t2 = 0;
i32t2 = 0;
u64t2 = 0;
i64t2 = 0;
f32t2 = 0.0;
f64t2 = 0.0;
boolt2 = false;
ptrt2 = nullptr;
buff.resetSer();
stat1 = buff.serialize(u8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(i8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(u16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(i16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(u32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(i32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(u64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(i64t1);
printf("i64t1 in stat: %d\n", stat1);
stat1 = buff.serialize(f32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(f64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(boolt1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff.serialize(ptrt1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
// TKC - commented out due to fprime-util choking on output
// std::cout << "Buffer contents: " << buff << std::endl;
// Serialize second buffer and test for equality
buff2.resetSer();
stat1 = buff2.serialize(u8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(i8t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(u16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(i16t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(u32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(i32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(u64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(i64t1);
printf("i64t1 in stat: %d\n", stat1);
stat1 = buff2.serialize(f32t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(f64t1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(boolt1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
stat1 = buff2.serialize(ptrt1);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat1);
ASSERT_EQ(buff,buff2);
// deserialize
stat2 = buff.deserialize(u8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u8t1,u8t2);
stat2 = buff.deserialize(i8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i8t1,i8t2);
stat2 = buff.deserialize(u16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u16t1,u16t2);
stat2 = buff.deserialize(i16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i16t1,i16t2);
stat2 = buff.deserialize(u32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u32t1,u32t2);
stat2 = buff.deserialize(i32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i32t1,i32t2);
stat2 = buff.deserialize(u64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u64t1,u64t2);
stat2 = buff.deserialize(i64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i64t1,i64t2);
stat2 = buff.deserialize(f32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_FLOAT_EQ(f32t1,f32t2);
stat2 = buff.deserialize(f64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_DOUBLE_EQ(f64t1,f64t2);
stat2 = buff.deserialize(boolt2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(boolt1,boolt2);
stat2 = buff.deserialize(ptrt2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(ptrt1,ptrt2);
// reset and deserialize again
#if DEBUG_VERBOSE
printf("\nReset and deserialize again.\n");
#endif
buff.resetDeser();
u8t2 = 0;
i8t2 = 0;
u16t2 = 0;
i16t2 = 0;
u32t2 = 0;
i32t2 = 0;
u64t2 = 0;
i64t2 = 0;
f32t2 = 0.0;
f64t2 = 0.0;
boolt2 = false;
ptrt2 = nullptr;
stat2 = buff.deserialize(u8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u8t1,u8t2);
stat2 = buff.deserialize(i8t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i8t1,i8t2);
stat2 = buff.deserialize(u16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u16t1,u16t2);
stat2 = buff.deserialize(i16t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i16t1,i16t2);
stat2 = buff.deserialize(u32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u32t1,u32t2);
stat2 = buff.deserialize(i32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i32t1,i32t2);
stat2 = buff.deserialize(u64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(u64t1,u64t2);
stat2 = buff.deserialize(i64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(i64t1,i64t2);
stat2 = buff.deserialize(f32t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_FLOAT_EQ(f32t1,f32t2);
stat2 = buff.deserialize(f64t2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_DOUBLE_EQ(f64t1,f64t2);
stat2 = buff.deserialize(boolt2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(boolt1,boolt2);
stat2 = buff.deserialize(ptrt2);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,stat2);
ASSERT_EQ(ptrt1,ptrt2);
// serialize string
Fw::String str1;
Fw::String str2;
str1 = "Foo";
str2 = "BarBlat";
buff.resetSer();
str1.serialize(buff);
str2.deserialize(buff);
ASSERT_EQ(str1,str2);
}
struct TestStruct {
U32 m_u32;
U16 m_u16;
U8 m_u8;
F32 m_f32;
U8 m_buff[25];
};
class MySerializable: public Fw::Serializable {
public:
Fw::SerializeStatus serialize(Fw::SerializeBufferBase& buffer) const {
buffer.serialize(m_testStruct.m_u32);
buffer.serialize(m_testStruct.m_u16);
buffer.serialize(m_testStruct.m_u8);
buffer.serialize(m_testStruct.m_f32);
buffer.serialize(m_testStruct.m_buff, sizeof(m_testStruct.m_buff));
return Fw::FW_SERIALIZE_OK;
}
Fw::SerializeStatus deserialize(Fw::SerializeBufferBase& buffer) {
buffer.serialize(m_testStruct.m_buff, sizeof(m_testStruct.m_buff));
buffer.serialize(m_testStruct.m_f32);
buffer.serialize(m_testStruct.m_u8);
buffer.serialize(m_testStruct.m_u16);
buffer.serialize(m_testStruct.m_u32);
return Fw::FW_SERIALIZE_OK;
}
private:
TestStruct m_testStruct;
};
TEST(PerformanceTest, SerPerfTest) {
Os::IntervalTimer timer;
MySerializable in;
MySerializable out;
SerializeTestBuffer buff;
Os::InterruptLock intLock;
intLock.lock();
timer.start();
I32 iterations = 1000000;
for (I32 iter = 0; iter < iterations; iter++) {
in.serialize(buff);
out.deserialize(buff);
}
timer.stop();
intLock.unLock();
printf("%d iterations took %d us (%f each).\n", iterations,
timer.getDiffUsec(),
static_cast<F32>(timer.getDiffUsec()) / static_cast<F32>(iterations));
}
TEST(PerformanceTest, StructCopyTest) {
char buff[sizeof(TestStruct)];
TestStruct ts;
Os::InterruptLock intLock;
Os::IntervalTimer timer;
intLock.lock();
timer.start();
I32 iterations = 1000000;
for (I32 iter = 0; iter < iterations; iter++) {
// simulate the incoming MSL-style call by doing member assignments
ts.m_u32 = 0;
ts.m_u16 = 0;
ts.m_u8 = 0;
ts.m_f32 = 0.0;
memcpy(ts.m_buff, "1234567890123456789012345", sizeof(ts.m_buff));
memcpy(buff, &ts, sizeof(ts));
memcpy(&ts, buff, sizeof(buff));
}
timer.stop();
intLock.unLock();
printf("%d iterations took %d us (%f each).\n", iterations,
timer.getDiffUsec(),
static_cast<F32>(timer.getDiffUsec()) / static_cast<F32>(iterations));
}
TEST(PerformanceTest, ClassCopyTest) {
char buff[sizeof(MySerializable)];
MySerializable ms;
Os::InterruptLock intLock;
Os::IntervalTimer timer;
intLock.lock();
timer.start();
I32 iterations = 1000000;
for (I32 iter = 0; iter < iterations; iter++) {
memcpy(buff, reinterpret_cast<void*>(&ms), sizeof(ms));
memcpy(reinterpret_cast<void*>(&ms), buff, sizeof(buff));
}
timer.stop();
intLock.unLock();
printf("%d iterations took %d us (%f each).\n", iterations,
timer.getDiffUsec(),
static_cast<F32>(timer.getDiffUsec()) / static_cast<F32>(iterations));
}
void printSizes() {
printf("Sizeof TestStruct: %lu\n", sizeof(TestStruct));
printf("Sizeof MySerializable: %lu\n", sizeof(MySerializable));
}
void AssertTest() {
printf("Assert Tests\n");
// Since native FW_ASSERT actually asserts,
// manually test by setting arguments to
// unequal values below one by one
// FW_ASSERT(0 == 1);
// FW_ASSERT(0 == 1, 1);
// FW_ASSERT(0 == 1, 1, 2);
// FW_ASSERT(0 == 1, 1, 2, 3);
// FW_ASSERT(0 == 1, 1, 2, 3, 4);
// FW_ASSERT(0 == 1, 1, 2, 3, 4, 5);
// FW_ASSERT(0 == 1, 1, 2, 3, 4, 5, 6);
// Define an Assert handler
class TestAssertHook : public Fw::AssertHook {
public:
TestAssertHook() {}
virtual ~TestAssertHook() {}
void reportAssert(
FILE_NAME_ARG file,
NATIVE_UINT_TYPE lineNo,
NATIVE_UINT_TYPE numArgs,
FwAssertArgType arg1,
FwAssertArgType arg2,
FwAssertArgType arg3,
FwAssertArgType arg4,
FwAssertArgType arg5,
FwAssertArgType arg6
) {
this->m_file = file;
this->m_lineNo = lineNo;
this->m_numArgs = numArgs;
this->m_arg1 = arg1;
this->m_arg2 = arg2;
this->m_arg3 = arg3;
this->m_arg4 = arg4;
this->m_arg5 = arg5;
this->m_arg6 = arg6;
};
void doAssert() {
this->m_asserted = true;
}
FILE_NAME_ARG getFile() {
return this->m_file;
}
NATIVE_UINT_TYPE getLineNo() {
return this->m_lineNo;
}
NATIVE_UINT_TYPE getNumArgs() {
return this->m_numArgs;
}
FwAssertArgType getArg1() {
return this->m_arg1;
}
FwAssertArgType getArg2() {
return this->m_arg2;
}
FwAssertArgType getArg3() {
return this->m_arg3;
}
FwAssertArgType getArg4() {
return this->m_arg4;
}
FwAssertArgType getArg5() {
return this->m_arg5;
}
FwAssertArgType getArg6() {
return this->m_arg6;
}
bool asserted() {
bool didAssert = this->m_asserted;
this->m_asserted = false;
return didAssert;
}
private:
#if FW_ASSERT_LEVEL == FW_FILEID_ASSERT
FILE_NAME_ARG m_file = 0;
#else
FILE_NAME_ARG m_file = nullptr;
#endif
NATIVE_UINT_TYPE m_lineNo = 0;
NATIVE_UINT_TYPE m_numArgs = 0;
FwAssertArgType m_arg1 = 0;
FwAssertArgType m_arg2 = 0;
FwAssertArgType m_arg3 = 0;
FwAssertArgType m_arg4 = 0;
FwAssertArgType m_arg5 = 0;
FwAssertArgType m_arg6 = 0;
bool m_asserted = false;
};
// register the class
TestAssertHook hook;
hook.registerHook();
// issue an assert
FW_ASSERT(0);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(0u,hook.getNumArgs());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
// issue an assert
FW_ASSERT(0,1);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(1u,hook.getNumArgs());
ASSERT_EQ(1u,hook.getArg1());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
// issue an assert
FW_ASSERT(0,1,2);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(2u,hook.getNumArgs());
ASSERT_EQ(1u,hook.getArg1());
ASSERT_EQ(2u,hook.getArg2());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
// issue an assert
FW_ASSERT(0,1,2,3);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(3u,hook.getNumArgs());
ASSERT_EQ(1u,hook.getArg1());
ASSERT_EQ(2u,hook.getArg2());
ASSERT_EQ(3u,hook.getArg3());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
// issue an assert
FW_ASSERT(0,1,2,3,4);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(4u,hook.getNumArgs());
ASSERT_EQ(1u,hook.getArg1());
ASSERT_EQ(2u,hook.getArg2());
ASSERT_EQ(3u,hook.getArg3());
ASSERT_EQ(4u,hook.getArg4());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
// issue an assert
FW_ASSERT(0,1,2,3,4,5);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(5u,hook.getNumArgs());
ASSERT_EQ(1u,hook.getArg1());
ASSERT_EQ(2u,hook.getArg2());
ASSERT_EQ(3u,hook.getArg3());
ASSERT_EQ(4u,hook.getArg4());
ASSERT_EQ(5u,hook.getArg5());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
// issue an assert
FW_ASSERT(0,1,2,3,4,5,6);
#if FW_ASSERT_LEVEL != FW_NO_ASSERT
// hook should have intercepted it
ASSERT_TRUE(hook.asserted());
ASSERT_EQ(6u,hook.getNumArgs());
ASSERT_EQ(1u,hook.getArg1());
ASSERT_EQ(2u,hook.getArg2());
ASSERT_EQ(3u,hook.getArg3());
ASSERT_EQ(4u,hook.getArg4());
ASSERT_EQ(5u,hook.getArg5());
ASSERT_EQ(6u,hook.getArg6());
#else
// assert does not fire when asserts are off
ASSERT_FALSE(hook.asserted());
#endif
}
TEST(TypesTest, CheckAssertTest) {
AssertTest();
}
TEST(TypesTest,PolyTest) {
Fw::String str;
// U8 Type ===============================================================
U8 in8 = 13;
U8 out8;
Fw::PolyType pt(in8);
out8 = static_cast<U8>(pt);
ASSERT_EQ(in8, out8);
// Test assigning to polytype and return type of assignment
in8 = 218;
// Can assign Polytype to U8 via overridden cast operator
out8 = (pt = in8);
ASSERT_EQ(static_cast<U8>(pt), 218u);
ASSERT_EQ(static_cast<U8>(pt), in8);
ASSERT_EQ(out8, in8);
#if FW_SERIALIZABLE_TO_STRING
pt.toString(str);
ASSERT_STREQ(str.toChar(), "218 ");
#endif
// U16 Type ==============================================================
U16 inU16 = 34;
U16 outU16;
Fw::PolyType ptU16(inU16);
outU16 = static_cast<U16>(ptU16);
ASSERT_EQ(inU16, outU16);
inU16 = 45000;
outU16 = (ptU16 = inU16);
ASSERT_EQ(static_cast<U16>(ptU16), inU16);
ASSERT_EQ(outU16, inU16);
#if FW_SERIALIZABLE_TO_STRING
ptU16.toString(str);
ASSERT_STREQ(str.toChar(), "45000 ");
#endif
// U32 Type ==============================================================
U32 inU32 = 89;
U32 outU32;
Fw::PolyType ptU32(inU32);
outU32 = static_cast<U32>(ptU32);
ASSERT_EQ(inU32, outU32);
inU32 = 3222111000;
outU32 = (ptU32 = inU32);
ASSERT_EQ(static_cast<U32>(ptU32), inU32);
ASSERT_EQ(outU32, inU32);
#if FW_SERIALIZABLE_TO_STRING
ptU32.toString(str);
ASSERT_STREQ(str.toChar(), "3222111000 ");
#endif
// U64 Type ==============================================================
U64 inU64 = 233;
U64 outU64;
Fw::PolyType ptU64(inU64);
outU64 = static_cast<U64>(ptU64);
ASSERT_EQ(inU64, outU64);
inU64 = 555444333222111;
outU64 = (ptU64 = inU64);
ASSERT_EQ(static_cast<U64>(ptU64), inU64);
ASSERT_EQ(outU64, inU64);
#if FW_SERIALIZABLE_TO_STRING
ptU64.toString(str);
ASSERT_STREQ(str.toChar(), "555444333222111 ");
#endif
// I8 Type ===============================================================
I8 inI8 = 2;
I8 outI8;
Fw::PolyType ptI8(inI8);
outI8 = static_cast<I8>(ptI8);
ASSERT_EQ(inI8, outI8);
inI8 = -3;
outI8 = (ptI8 = inI8);
ASSERT_EQ(static_cast<I8>(ptI8), inI8);
ASSERT_EQ(outI8, inI8);
#if FW_SERIALIZABLE_TO_STRING
ptI8.toString(str);
ASSERT_STREQ(str.toChar(), "-3 ");
#endif
// I16 Type ==============================================================
I16 inI16 = 5;
I16 outI16;
Fw::PolyType ptI16(inI16);
outI16 = static_cast<I16>(ptI16);
ASSERT_EQ(inI16, outI16);
inI16 = -7;
outI16 = (ptI16 = inI16);
ASSERT_EQ(static_cast<I16>(ptI16), inI16);
ASSERT_EQ(outI16, inI16);
#if FW_SERIALIZABLE_TO_STRING
ptI16.toString(str);
ASSERT_STREQ(str.toChar(), "-7 ");
#endif
// I32 Type ==============================================================
I32 inI32 = 11;
I32 outI32;
Fw::PolyType ptI32(inI32);
outI32 = static_cast<I32>(ptI32);
ASSERT_EQ(inI32, outI32);
inI32 = -13;
outI32 = (ptI32 = inI32);
ASSERT_EQ(static_cast<I32>(ptI32), inI32);
ASSERT_EQ(outI32, inI32);
#if FW_SERIALIZABLE_TO_STRING
ptI32.toString(str);
ASSERT_STREQ(str.toChar(), "-13 ");
#endif
// I64 Type ==============================================================
I64 inI64 = 17;
I64 outI64;
Fw::PolyType ptI64(inI64);
outI64 = static_cast<I64>(ptI64);
ASSERT_EQ(inI64, outI64);
inI64 = -19;
outI64 = (ptI64 = inI64);
ASSERT_EQ(static_cast<I64>(ptI64), inI64);
ASSERT_EQ(outI64, inI64);
#if FW_SERIALIZABLE_TO_STRING
ptI64.toString(str);
ASSERT_STREQ(str.toChar(), "-19 ");
#endif
// F32 Type ==============================================================
F32 inF32 = 23.32;
F32 outF32;
Fw::PolyType ptF32(inF32);
outF32 = static_cast<F32>(ptF32);
ASSERT_EQ(inF32, outF32);
inF32 = 29.92;
outF32 = (ptF32 = inF32);
ASSERT_EQ(static_cast<F32>(ptF32), inF32);
ASSERT_EQ(outF32, inF32);
// F64 Type ==============================================================
F64 inF64 = 31.13;
F64 outF64;
Fw::PolyType ptF64(inF64);
outF64 = static_cast<F64>(ptF64);
ASSERT_EQ(inF64, outF64);
inF64 = 37.73;
outF64 = (ptF64 = inF64);
ASSERT_EQ(static_cast<F64>(ptF64), inF64);
ASSERT_EQ(outF64, inF64);
// bool Type =============================================================
bool inbool = true;
bool outbool;
Fw::PolyType ptbool(inbool);
outbool = static_cast<bool>(ptbool);
ASSERT_EQ(inbool, outbool);
inbool = false;
outbool = (ptbool = inbool);
ASSERT_EQ(static_cast<bool>(ptbool), inbool);
ASSERT_EQ(outbool, inbool);
// ptr Type ==============================================================
void* inPtr = &ptbool;
void* outPtr;
Fw::PolyType ptPtr(inPtr);
outPtr = static_cast<void*>(ptPtr);
ASSERT_EQ(inPtr, outPtr);
inPtr = &ptF64;
outPtr = (ptPtr = inPtr);
ASSERT_EQ(static_cast<void*>(ptPtr), inPtr);
ASSERT_EQ(outPtr, inPtr);
}
TEST(TypesTest,EightyCharTest) {
Fw::String str;
str = "foo";
Fw::String str2;
str2 = "foo";
ASSERT_EQ(str,str2);
ASSERT_EQ(str,"foo");
str2 = "doodie";
ASSERT_NE(str,str2);
Fw::String str3 = str;
str3 += str2;
ASSERT_EQ(str3,"foodoodie");
str3 += "hoo";
ASSERT_EQ(str3,"foodoodiehoo");
Fw::String copyStr("ASTRING");
ASSERT_EQ(copyStr,"ASTRING");
Fw::String copyStr2 = "ASTRING";
ASSERT_EQ(copyStr2,"ASTRING");
Fw::String copyStr3(copyStr2);
ASSERT_EQ(copyStr3,"ASTRING");
Fw::InternalInterfaceString ifstr("IfString");
Fw::String if2(ifstr);
ASSERT_EQ(ifstr,if2);
ASSERT_EQ(if2,"IfString");
std::cout << "Stream: " << str2 << std::endl;
// Make our own short string
}
TEST(TypesTest,ObjectNameTest) {
Fw::ObjectName str;
str = "foo";
Fw::ObjectName str2;
str2 = "foo";
ASSERT_EQ(str,str2);
ASSERT_EQ(str,"foo");
str2 = "_bar";
ASSERT_NE(str,str2);
Fw::ObjectName str3 = str;
str3 += str2;
ASSERT_EQ(str3,"foo_bar");
str3 += "_foo";
ASSERT_EQ(str3,"foo_bar_foo");
Fw::ObjectName copyStr("ASTRING");
ASSERT_EQ(copyStr,"ASTRING");
Fw::ObjectName copyStr2(copyStr);
ASSERT_EQ(copyStr2,"ASTRING");
Fw::InternalInterfaceString ifstr("IfString");
Fw::ObjectName if2(ifstr);
ASSERT_EQ(ifstr,if2);
ASSERT_EQ(if2,"IfString");
}
TEST(TypesTest,StringFormatTest) {
Fw::String str;
str.format("Int %d String %s",10,"foo");
ASSERT_STREQ(str.toChar(), "Int 10 String foo");
}
TEST(PerformanceTest, F64SerPerfTest) {
SerializeTestBuffer buff;
#if DEBUG_VERBOSE
printf("U8 Test\n");
#endif
F64 in = 10000.0;
F64 out = 0;
NATIVE_INT_TYPE iters = 1000000;
Os::IntervalTimer timer;
timer.start();
for (NATIVE_INT_TYPE iter = 0; iter < iters; iter++) {
buff.resetSer();
buff.serialize(in);
buff.deserialize(out);
}
timer.stop();
printf("%d iterations took %d us (%f us each).\n", iters,
timer.getDiffUsec(),
static_cast<F32>(timer.getDiffUsec()) / static_cast<F32>(iters));
}
TEST(AllocatorTest,MallocAllocatorTest) {
// Since it is a wrapper around malloc, the test consists of requesting
// memory and verifying a non-zero pointer, unchanged size, and not recoverable.
Fw::MallocAllocator allocator;
NATIVE_UINT_TYPE size = 100; // one hundred bytes
bool recoverable;
void *ptr = allocator.allocate(10,size,recoverable);
ASSERT_EQ(100,size);
ASSERT_NE(ptr,nullptr);
ASSERT_FALSE(recoverable);
// deallocate memory
allocator.deallocate(100,ptr);
}
TEST(Nominal, string_copy) {
const char* copy_string = "abc123\n"; // Length of 7
char buffer_out_test[10];
char buffer_out_truth[10];
char* out_truth = ::strncpy(buffer_out_truth, copy_string, sizeof(buffer_out_truth));
char* out_test = Fw::StringUtils::string_copy(buffer_out_test, copy_string, sizeof(buffer_out_test));
ASSERT_EQ(sizeof(buffer_out_truth), sizeof(buffer_out_test)) << "Buffer size mismatch";
// Check the outputs, both should return the input buffer
ASSERT_EQ(out_truth, buffer_out_truth) << "strncpy didn't return expected value";
ASSERT_EQ(out_test, buffer_out_test) << "string_copy didn't return expected value";
// Check string correct
ASSERT_STREQ(out_test, copy_string) << "Strings not equal from strncpy";
ASSERT_STREQ(out_test, out_truth) << "Copied strings differ from strncpy";
// Should output 0s for the remaining buffer
for (U32 i = ::strnlen(buffer_out_truth, sizeof(buffer_out_truth)); i < static_cast<U32>(sizeof(buffer_out_truth));
i++) {
ASSERT_EQ(buffer_out_truth[i], 0) << "strncpy didn't output 0 fill";
ASSERT_EQ(buffer_out_test[i], 0) << "string_copy didn't output 0 fill";
}
}
TEST(OffNominal, string_copy) {
const char* copy_string = "abc123\n"; // Length of 7
char buffer_out_test[sizeof(copy_string) - 1];
char buffer_out_truth[sizeof(copy_string) - 1];
char* out_truth = ::strncpy(buffer_out_truth, copy_string, sizeof(buffer_out_truth));
char* out_test = Fw::StringUtils::string_copy(buffer_out_test, copy_string, sizeof(buffer_out_test));
ASSERT_EQ(sizeof(buffer_out_truth), sizeof(buffer_out_test)) << "Buffer size mismatch";
// Check the outputs, both should return the input buffer
ASSERT_EQ(out_truth, buffer_out_truth) << "strncpy didn't return expected value";
ASSERT_EQ(out_test, buffer_out_test) << "string_copy didn't return expected value";
// Check string correct up to last digit
U32 i = 0;
ASSERT_STRNE(out_test, out_truth) << "Strings not equal";
for (i = 0; i < static_cast<U32>(sizeof(copy_string)) - 2; i++) {
ASSERT_EQ(out_test[i], out_truth[i]);
}
ASSERT_EQ(out_truth[i], '\n') << "strncpy did not error as expected";
ASSERT_EQ(out_test[i], 0) << "string_copy didn't properly null terminate";
}
TEST(Nominal, string_len) {
const char* test_string = "abc123";
ASSERT_EQ(Fw::StringUtils::string_length(test_string, 50), 6);
ASSERT_EQ(Fw::StringUtils::string_length(test_string, 3), 3);
}
TEST(OffNominal, string_len_zero) {
const char* test_string = "abc123";
ASSERT_EQ(Fw::StringUtils::string_length(test_string, 0), 0);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Time/Time.cpp | #include <Fw/Time/Time.hpp>
#include <FpConfig.hpp>
namespace Fw {
const Time ZERO_TIME = Time();
Time::Time() : m_seconds(0), m_useconds(0), m_timeBase(TB_NONE), m_timeContext(0) {
}
Time::~Time() {
}
Time::Time(const Time& other) : Serializable() {
this->set(other.m_timeBase,other.m_timeContext,other.m_seconds,other.m_useconds);
}
Time::Time(U32 seconds, U32 useconds) {
this->set(TB_NONE,0,seconds,useconds);
}
Time::Time(TimeBase timeBase, U32 seconds, U32 useconds) {
this->set(timeBase,0,seconds,useconds);
}
void Time::set(U32 seconds, U32 useconds) {
this->set(this->m_timeBase,this->m_timeContext,seconds,useconds);
}
void Time::set(TimeBase timeBase, U32 seconds, U32 useconds) {
this->set(timeBase,this->m_timeContext,seconds,useconds);
}
Time::Time(TimeBase timeBase, FwTimeContextStoreType context, U32 seconds, U32 useconds) {
this->set(timeBase,context,seconds,useconds);
}
void Time::set(TimeBase timeBase, FwTimeContextStoreType context, U32 seconds, U32 useconds) {
this->m_timeBase = timeBase;
this->m_timeContext = context;
this->m_useconds = useconds;
this->m_seconds = seconds;
}
Time& Time::operator=(const Time& other) {
this->m_timeBase = other.m_timeBase;
this->m_timeContext = other.m_timeContext;
this->m_useconds = other.m_useconds;
this->m_seconds = other.m_seconds;
return *this;
}
bool Time::operator==(const Time& other) const {
return (Time::compare(*this,other) == EQ);
}
bool Time::operator!=(const Time& other) const {
return (Time::compare(*this,other) != EQ);
}
bool Time::operator>(const Time& other) const {
return (Time::compare(*this,other) == GT);
}
bool Time::operator<(const Time& other) const {
return (Time::compare(*this,other) == LT);
}
bool Time::operator>=(const Time& other) const {
Time::Comparison c = Time::compare(*this,other);
return ((GT == c) or (EQ == c));
}
bool Time::operator<=(const Time& other) const {
Time::Comparison c = Time::compare(*this,other);
return ((LT == c) or (EQ == c));
}
SerializeStatus Time::serialize(SerializeBufferBase& buffer) const {
// serialize members
SerializeStatus stat = Fw::FW_SERIALIZE_OK;
#if FW_USE_TIME_BASE
stat = buffer.serialize(static_cast<FwTimeBaseStoreType>(this->m_timeBase));
if (stat != FW_SERIALIZE_OK) {
return stat;
}
#endif
#if FW_USE_TIME_CONTEXT
stat = buffer.serialize(this->m_timeContext);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
#endif
stat = buffer.serialize(this->m_seconds);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
return buffer.serialize(this->m_useconds);
}
SerializeStatus Time::deserialize(SerializeBufferBase& buffer) {
SerializeStatus stat = Fw::FW_SERIALIZE_OK;
#if FW_USE_TIME_BASE
FwTimeBaseStoreType deSer;
stat = buffer.deserialize(deSer);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
this->m_timeBase = static_cast<TimeBase>(deSer);
#else
this->m_timeBase = TB_NONE;
#endif
#if FW_USE_TIME_CONTEXT
stat = buffer.deserialize(this->m_timeContext);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
#else
this->m_timeContext = 0;
#endif
stat = buffer.deserialize(this->m_seconds);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
return buffer.deserialize(this->m_useconds);
}
U32 Time::getSeconds() const {
return this->m_seconds;
}
U32 Time::getUSeconds() const {
return this->m_useconds;
}
TimeBase Time::getTimeBase() const {
return this->m_timeBase;
}
FwTimeContextStoreType Time::getContext() const {
return this->m_timeContext;
}
Time Time ::
zero(TimeBase timeBase)
{
Time time(timeBase,0, 0, 0);
return time;
}
Time::Comparison Time ::
compare(
const Time &time1,
const Time &time2
)
{
#if FW_USE_TIME_BASE
if (time1.getTimeBase() != time2.getTimeBase()) {
return INCOMPARABLE;
}
#endif
#if FW_USE_TIME_CONTEXT
if (time1.getContext() != time2.getContext()) {
return INCOMPARABLE;
}
#endif
const U32 s1 = time1.getSeconds();
const U32 s2 = time2.getSeconds();
const U32 us1 = time1.getUSeconds();
const U32 us2 = time2.getUSeconds();
if (s1 < s2) {
return LT;
} else if (s1 > s2) {
return GT;
} else if (us1 < us2) {
return LT;
} else if (us1 > us2) {
return GT;
} else {
return EQ;
}
}
Time Time ::
add(
const Time& a,
const Time& b
)
{
#if FW_USE_TIME_BASE
FW_ASSERT(a.getTimeBase() == b.getTimeBase(), a.getTimeBase(), b.getTimeBase() );
#endif
#if FW_USE_TIME_CONTEXT
FW_ASSERT(a.getContext() == b.getContext(), a.getContext(), b.getContext() );
#endif
U32 seconds = a.getSeconds() + b.getSeconds();
U32 uSeconds = a.getUSeconds() + b.getUSeconds();
FW_ASSERT(uSeconds < 1999999);
if (uSeconds >= 1000000) {
++seconds;
uSeconds -= 1000000;
}
Time c(a.getTimeBase(),a.getContext(),seconds,uSeconds);
return c;
}
Time Time ::
sub(
const Time& minuend, //!< Time minuend
const Time& subtrahend //!< Time subtrahend
)
{
#if FW_USE_TIME_BASE
FW_ASSERT(minuend.getTimeBase() == subtrahend.getTimeBase(), minuend.getTimeBase(), subtrahend.getTimeBase());
#endif
#if FW_USE_TIME_CONTEXT
FW_ASSERT(minuend.getContext() == subtrahend.getContext(), minuend.getContext(), subtrahend.getContext());
#endif
// Assert minuend is greater than subtrahend
FW_ASSERT(minuend >= subtrahend);
U32 seconds = minuend.getSeconds() - subtrahend.getSeconds();
U32 uSeconds;
if (subtrahend.getUSeconds() > minuend.getUSeconds()) {
seconds--;
uSeconds = minuend.getUSeconds() + 1000000 - subtrahend.getUSeconds();
} else {
uSeconds = minuend.getUSeconds() - subtrahend.getUSeconds();
}
return Time(minuend.getTimeBase(), minuend.getContext(), seconds, static_cast<U32>(uSeconds));
}
void Time::add(U32 seconds, U32 useconds) {
this->m_seconds += seconds;
this->m_useconds += useconds;
FW_ASSERT(this->m_useconds < 1999999,this->m_useconds);
if (this->m_useconds >= 1000000) {
++this->m_seconds;
this->m_useconds -= 1000000;
}
}
void Time::setTimeBase(TimeBase timeBase) {
this->m_timeBase = timeBase;
}
void Time::setTimeContext(FwTimeContextStoreType context) {
this->m_timeContext = context;
}
#ifdef BUILD_UT
std::ostream& operator<<(std::ostream& os, const Time& val) {
os << "(" << val.getTimeBase() << "," << val.getUSeconds() << "," << val.getSeconds() << ")";
return os;
}
#endif
}
| cpp |
fprime | data/projects/fprime/Fw/Time/Time.hpp | #ifndef FW_TIME_HPP
#define FW_TIME_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/Serializable.hpp>
namespace Fw {
class Time: public Serializable {
public:
enum {
SERIALIZED_SIZE = sizeof(FwTimeBaseStoreType)
+ sizeof(FwTimeContextStoreType)
+ sizeof(U32) + sizeof(U32)
};
Time(); // !< Default constructor
Time(const Time& other); // !< Copy constructor
Time(U32 seconds, U32 useconds); // !< Constructor with member values as arguments
Time(TimeBase timeBase, U32 seconds, U32 useconds); // !< Constructor with member values as arguments
Time(TimeBase timeBase, FwTimeContextStoreType context, U32 seconds, U32 useconds); // !< Constructor with member values as arguments
virtual ~Time(); // !< Destructor
void set(U32 seconds, U32 useconds); // !< Sets value of time stored
void set(TimeBase timeBase, U32 seconds, U32 useconds); // !< Sets value of time stored
void set(TimeBase timeBase, FwTimeContextStoreType context, U32 seconds, U32 useconds); // !< Sets value of time stored
void setTimeBase(TimeBase timeBase);
void setTimeContext(FwTimeContextStoreType context);
U32 getSeconds() const; // !< Gets seconds part of time
U32 getUSeconds() const; // !< Gets microseconds part of time
TimeBase getTimeBase() const; // !< Time base of time. This is project specific and is meant for indicating different sources of time
FwTimeContextStoreType getContext() const; // !< get the context value
SerializeStatus serialize(SerializeBufferBase& buffer) const; // !< Serialize method
SerializeStatus deserialize(SerializeBufferBase& buffer); // !< Deserialize method
bool operator==(const Time& other) const;
bool operator!=(const Time& other) const;
bool operator>(const Time& other) const;
bool operator<(const Time& other) const;
bool operator>=(const Time& other) const;
bool operator<=(const Time& other) const;
Time& operator=(const Time& other);
// Static methods:
//! The type of a comparison result
typedef enum {
LT = -1,
EQ = 0,
GT = 1,
INCOMPARABLE = 2
} Comparison;
//! \return time zero
static Time zero(TimeBase timeBase=TB_NONE);
//! Compare two times
//! \return The result
static Comparison compare(
const Time &time1, //!< Time 1
const Time &time2 //!< Time 2
);
//! Add two times
//! \return The result
static Time add(
const Time& a, //!< Time a
const Time& b //!< Time b
);
//! Subtract subtrahend from minuend
//! \return The result
static Time sub(
const Time& minuend, //!< Value being subtracted from
const Time& subtrahend //!< Value being subtracted
);
// add seconds and microseconds to existing time
void add(U32 seconds, U32 mseconds);
#ifdef BUILD_UT // Stream operators to support Googletest
friend std::ostream& operator<<(std::ostream& os, const Time& val);
#endif
PRIVATE:
U32 m_seconds; // !< seconds portion
U32 m_useconds; // !< microseconds portion
TimeBase m_timeBase; // !< basis of time (defined by system)
FwTimeContextStoreType m_timeContext; // !< user settable value. Could be reboot count, node, etc
};
extern const Time ZERO_TIME;
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Time/test/ut/TimeTest.cpp | /*
* TimeTest.cpp
*
* Created on: Apr 22, 2016
* Author: tcanham
*/
#include <Fw/Time/Time.hpp>
#include <iostream>
#include <gtest/gtest.h>
TEST(TimeTestNominal,InstantiateTest) {
Fw::Time time(TB_NONE,1,2);
ASSERT_EQ(time.m_timeBase,TB_NONE);
ASSERT_EQ(time.m_timeContext,0);
ASSERT_EQ(time.m_seconds,1);
ASSERT_EQ(time.m_useconds,2);
std::cout << time << std::endl;
}
TEST(TimeTestNominal,MathTest) {
Fw::Time time1;
Fw::Time time2;
// Comparison
time1.set(1000,1000);
time2.set(1000,1000);
ASSERT_TRUE(time1 == time2);
ASSERT_TRUE(time1 >= time2);
ASSERT_TRUE(time1 <= time2);
time1.set(1000,1000);
time2.set(2000,1000);
ASSERT_TRUE(time1 != time2);
ASSERT_TRUE(time1 < time2);
ASSERT_TRUE(time1 <= time2);
time1.set(2000,1000);
time2.set(1000,1000);
ASSERT_TRUE(time1 > time2);
ASSERT_TRUE(time1 >= time2);
// Addition
time1.set(1000,1000);
time2.set(4000,2000);
Fw::Time time_sum = Fw::Time::add(time1,time2);
ASSERT_EQ(time_sum.m_seconds,5000);
ASSERT_EQ(time_sum.m_useconds,3000);
// Normal subtraction
time1.set(1000,1000);
time2.set(4000,2000);
Fw::Time time3 = Fw::Time::sub(time2,time1);
ASSERT_EQ(time3.m_timeBase,TB_NONE);
ASSERT_EQ(time3.m_timeContext,0);
ASSERT_EQ(time3.m_seconds,3000);
ASSERT_EQ(time3.m_useconds,1000);
// Rollover subtraction
time1.set(1,999999);
time2.set(2,000001);
time3 = Fw::Time::sub(time2,time1);
ASSERT_EQ(time3.m_timeBase,TB_NONE);
ASSERT_EQ(time3.m_timeContext,0);
EXPECT_EQ(time3.m_seconds,0);
EXPECT_EQ(time3.m_useconds,2);
}
TEST(TimeTestNominal,CopyTest) {
Fw::Time time0;
// make time that's guaranteed to be different from default
Fw::Time time1(
(time0.getTimeBase() != TB_NONE ? TB_NONE : TB_PROC_TIME),
time0.getContext()+1,
time0.getSeconds()+1,
time0.getUSeconds()+1
);
// copy construction
Fw::Time time2 = time1;
ASSERT_EQ(time1.getSeconds(), time2.getSeconds());
ASSERT_EQ(time1.getUSeconds(), time2.getUSeconds());
ASSERT_EQ(time1.getTimeBase(), time2.getTimeBase());
ASSERT_EQ(time1.getContext(), time2.getContext());
// assignment operator
Fw::Time time3;
time3 = time1;
ASSERT_EQ(time1.getSeconds(), time3.getSeconds());
ASSERT_EQ(time1.getUSeconds(), time3.getUSeconds());
ASSERT_EQ(time1.getTimeBase(), time3.getTimeBase());
ASSERT_EQ(time1.getContext(), time3.getContext());
// set method
Fw::Time time4;
time4.set(time1.getTimeBase(), time1.getContext(), time1.getSeconds(), time1.getUSeconds());
ASSERT_EQ(time1.getSeconds(), time3.getSeconds());
ASSERT_EQ(time1.getUSeconds(), time3.getUSeconds());
ASSERT_EQ(time1.getTimeBase(), time3.getTimeBase());
ASSERT_EQ(time1.getContext(), time3.getContext());
}
TEST(TimeTestNominal,ZeroTimeEquality) {
Fw::Time time(TB_PROC_TIME,1,2);
ASSERT_NE(time, Fw::ZERO_TIME);
Fw::Time time2;
ASSERT_EQ(time2, Fw::ZERO_TIME);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Port/InputPortBase.cpp | #include <FpConfig.hpp>
#include <Fw/Port/InputPortBase.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
namespace Fw {
InputPortBase::InputPortBase() :
PortBase(),
m_comp(nullptr),
m_portNum(-1) {
}
InputPortBase::~InputPortBase() {
}
void InputPortBase::init() {
PortBase::init();
}
void InputPortBase::setPortNum(NATIVE_INT_TYPE portNum) {
FW_ASSERT(portNum >= 0,portNum);
this->m_portNum = portNum;
}
#if FW_OBJECT_TO_STRING == 1
void InputPortBase::toString(char* buffer, NATIVE_INT_TYPE size) {
#if FW_OBJECT_NAMES == 1
FW_ASSERT(size > 0);
FW_ASSERT(buffer != nullptr);
PlatformIntType status = snprintf(buffer, size, "InputPort: %s->%s", this->m_objName.toChar(),
this->isConnected() ? this->m_connObj->getObjName() : "None");
if (status < 0) {
buffer[0] = 0;
}
#else
(void)snprintf(buffer,size,"%s","Unnamed Input port");
#endif
}
#endif
}
| cpp |
fprime | data/projects/fprime/Fw/Port/PortBase.hpp | #ifndef FW_PORT_BASE_HPP
#define FW_PORT_BASE_HPP
#include <Fw/Obj/ObjBase.hpp>
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#if FW_PORT_TRACING == 1
extern "C" {
void setConnTrace(bool trace);
}
#endif
namespace Fw {
class PortBase : public Fw::ObjBase {
public:
#if FW_PORT_TRACING == 1
static void setTrace(bool trace); // !< turn tracing on or off
void ovrTrace(bool ovr, bool trace); // !< override tracing for a particular port
#endif
bool isConnected();
protected:
// Should only be accessed by derived classes
PortBase(); // Constructor
virtual ~PortBase(); // Destructor
virtual void init(); // !< initialization function
#if FW_PORT_TRACING == 1
void trace(); // !< trace port calls if active
#endif
Fw::ObjBase* m_connObj; // !< object port is connected to
#if FW_OBJECT_TO_STRING
virtual void toString(char* str, NATIVE_INT_TYPE size);
#endif
private:
#if FW_PORT_TRACING == 1
static bool s_trace; // !< global tracing is active
bool m_trace; // !< local trace flag
bool m_ovr_trace; // !< flag to override global trace
#endif
// Disable constructors
PortBase(PortBase*);
PortBase(PortBase&);
PortBase& operator=(PortBase&);
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Port/InputSerializePort.cpp | #include <Fw/Port/InputSerializePort.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#if FW_PORT_SERIALIZATION == 1
namespace Fw {
// SerializePort has no call interface. It is to pass through serialized data
InputSerializePort::InputSerializePort() : InputPortBase(), m_func(nullptr) {
}
InputSerializePort::~InputSerializePort() {
}
void InputSerializePort::init() {
InputPortBase::init();
}
SerializeStatus InputSerializePort::invokeSerial(SerializeBufferBase &buffer) {
FW_ASSERT(this->m_comp);
FW_ASSERT(this->m_func);
this->m_func(this->m_comp,this->m_portNum,buffer);
// The normal input ports perform deserialize() on the passed buffer,
// which is what this status is based on. This is not the case for the
// InputSerializePort, so just return an okay status
return FW_SERIALIZE_OK;
}
void InputSerializePort::addCallComp(Fw::PassiveComponentBase* callComp, CompFuncPtr funcPtr) {
FW_ASSERT(callComp);
FW_ASSERT(funcPtr);
this->m_comp = callComp;
this->m_func = funcPtr;
}
#if FW_OBJECT_TO_STRING == 1
void InputSerializePort::toString(char* buffer, NATIVE_INT_TYPE size) {
#if FW_OBJECT_NAMES == 1
FW_ASSERT(size > 0);
if (snprintf(buffer, size, "Input Serial Port: %s %s->(%s)", this->m_objName.toChar(), this->isConnected() ? "C" : "NC",
this->isConnected() ? this->m_connObj->getObjName() : "None") < 0) {
buffer[0] = 0;
}
#else
(void)snprintf(buffer,size,"%s","InputSerializePort");
#endif
}
#endif
}
#endif
| cpp |
fprime | data/projects/fprime/Fw/Port/PortBase.cpp | #include <Fw/Port/PortBase.hpp>
#include <FpConfig.hpp>
#include <Fw/Logger/Logger.hpp>
#include <cstdio>
#include "Fw/Types/Assert.hpp"
#if FW_PORT_TRACING
void setConnTrace(bool trace) {
Fw::PortBase::setTrace(trace);
}
namespace Fw {
bool PortBase::s_trace = false;
}
#endif // FW_PORT_TRACING
namespace Fw {
PortBase::PortBase()
:
Fw::ObjBase(nullptr),
m_connObj(nullptr)
#if FW_PORT_TRACING == 1
,m_trace(false),
m_ovr_trace(false)
#endif
{
}
PortBase::~PortBase() {
}
void PortBase::init() {
ObjBase::init();
}
bool PortBase::isConnected() {
return m_connObj == nullptr?false:true;
}
#if FW_PORT_TRACING == 1
void PortBase::trace() {
bool do_trace = false;
if (this->m_ovr_trace) {
if (this->m_trace) {
do_trace = true;
}
} else if (PortBase::s_trace) {
do_trace = true;
}
if (do_trace) {
#if FW_OBJECT_NAMES == 1
Fw::Logger::logMsg("Trace: %s\n", reinterpret_cast<POINTER_CAST>(this->m_objName.toChar()), 0, 0, 0, 0, 0);
#else
Fw::Logger::logMsg("Trace: %p\n", reinterpret_cast<POINTER_CAST>(this), 0, 0, 0, 0, 0);
#endif
}
}
void PortBase::setTrace(bool trace) {
PortBase::s_trace = trace;
}
void PortBase::ovrTrace(bool ovr, bool trace) {
this->m_ovr_trace = ovr;
this->m_trace = trace;
}
#endif // FW_PORT_TRACING
#if FW_OBJECT_NAMES == 1
#if FW_OBJECT_TO_STRING == 1
void PortBase::toString(char* buffer, NATIVE_INT_TYPE size) {
FW_ASSERT(size > 0);
if (snprintf(buffer, size, "Port: %s %s->(%s)", this->m_objName.toChar(), this->m_connObj ? "C" : "NC",
this->m_connObj ? this->m_connObj->getObjName() : "None") < 0) {
buffer[0] = 0;
}
}
#endif // FW_OBJECT_TO_STRING
#endif // FW_OBJECT_NAMES
}
| cpp |
fprime | data/projects/fprime/Fw/Port/OutputPortBase.cpp | #include <FpConfig.hpp>
#include <Fw/Port/OutputPortBase.hpp>
#include <Os/Log.hpp>
#include <cstdio>
#include <Fw/Types/Assert.hpp>
namespace Fw {
OutputPortBase::OutputPortBase() : PortBase()
#if FW_PORT_SERIALIZATION == 1
,m_serPort(nullptr)
#endif
{
}
OutputPortBase::~OutputPortBase() {
}
void OutputPortBase::init() {
PortBase::init();
}
#if FW_PORT_SERIALIZATION == 1
void OutputPortBase::registerSerialPort(InputPortBase* port) {
FW_ASSERT(port);
this->m_connObj = port;
this->m_serPort = port;
}
SerializeStatus OutputPortBase::invokeSerial(SerializeBufferBase &buffer) {
FW_ASSERT(this->m_serPort);
return this->m_serPort->invokeSerial(buffer);
}
#endif
#if FW_OBJECT_TO_STRING == 1
void OutputPortBase::toString(char* buffer, NATIVE_INT_TYPE size) {
#if FW_OBJECT_NAMES == 1
FW_ASSERT(size > 0);
if (snprintf(buffer, size, "OutputPort: %s %s->(%s)", this->m_objName.toChar(), this->isConnected() ? "C" : "NC",
this->isConnected() ? this->m_connObj->getObjName() : "None") < 0) {
buffer[0] = 0;
}
#else
(void)snprintf(buffer,size,"%s","OutputPort");
#endif
}
#endif
}
| cpp |
fprime | data/projects/fprime/Fw/Port/OutputPortBase.hpp | #ifndef FW_OUTPUT_PORT_BASE_HPP
#define FW_OUTPUT_PORT_BASE_HPP
#include <FpConfig.hpp>
#include <Fw/Obj/ObjBase.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Port/InputPortBase.hpp>
namespace Fw {
class OutputPortBase : public PortBase {
public:
#if FW_PORT_SERIALIZATION == 1
void registerSerialPort(InputPortBase* port); // !< register a port for serialized calls
SerializeStatus invokeSerial(SerializeBufferBase &buffer); // !< invoke the port with a serialized version of the call
#endif
protected:
OutputPortBase(); // constructor
virtual ~OutputPortBase(); // destructor
virtual void init();
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size);
#endif
#if FW_PORT_SERIALIZATION == 1
Fw::InputPortBase* m_serPort; // !< pointer to port for serialized calls
#endif
private:
// Disable constructors
OutputPortBase(OutputPortBase*);
OutputPortBase(OutputPortBase&);
OutputPortBase& operator=(OutputPortBase&);
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Port/OutputSerializePort.cpp | #include <Fw/Port/OutputSerializePort.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#if FW_PORT_SERIALIZATION
namespace Fw {
// SerializePort has no call interface. It is to pass through serialized data
OutputSerializePort::OutputSerializePort() : OutputPortBase() {
}
OutputSerializePort::~OutputSerializePort() {
}
void OutputSerializePort::init() {
OutputPortBase::init();
}
#if FW_OBJECT_TO_STRING == 1
void OutputSerializePort::toString(char* buffer, NATIVE_INT_TYPE size) {
#if FW_OBJECT_NAMES == 1
FW_ASSERT(size > 0);
if (snprintf(buffer, size, "Output Serial Port: %s %s->(%s)", this->m_objName.toChar(), this->isConnected() ? "C" : "NC",
this->isConnected() ? this->m_connObj->getObjName() : "None") < 0) {
buffer[0] = 0;
}
#else
(void)snprintf(buffer,size,"%s","OutputSerializePort");
#endif
}
#endif
}
#endif // FW_PORT_SERIALIZATION
| cpp |
fprime | data/projects/fprime/Fw/Port/InputPortBase.hpp | #ifndef FW_INPUT_PORT_BASE_HPP
#define FW_INPUT_PORT_BASE_HPP
#include <FpConfig.hpp>
#include <Fw/Obj/ObjBase.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Comp/PassiveComponentBase.hpp>
#include <Fw/Port/PortBase.hpp>
namespace Fw {
class InputPortBase : public PortBase {
public:
void setPortNum(NATIVE_INT_TYPE portNum); // !< set the port number
#if FW_PORT_SERIALIZATION
virtual SerializeStatus invokeSerial(SerializeBufferBase &buffer) = 0; // !< invoke the port with a serialized version of the call
#endif
protected:
InputPortBase(); // Constructor
virtual ~InputPortBase(); // Destructor
virtual void init();
PassiveComponentBase* m_comp; // !< pointer to containing component
NATIVE_INT_TYPE m_portNum; // !< port number in containing object
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size);
#endif
private:
// Disable constructors since we don't want to instantiate directly
InputPortBase(InputPortBase*);
InputPortBase(InputPortBase&);
InputPortBase& operator=(InputPortBase&);
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Port/InputSerializePort.hpp | #ifndef FW_INPUT_SERIALIZE_PORT_HPP
#define FW_INPUT_SERIALIZE_PORT_HPP
#include <FpConfig.hpp>
#if FW_PORT_SERIALIZATION == 1
#include <Fw/Port/InputPortBase.hpp>
namespace Fw {
class InputSerializePort : public InputPortBase {
public:
InputSerializePort();
virtual ~InputSerializePort();
void init();
SerializeStatus invokeSerial(SerializeBufferBase &buffer); // !< invoke the port with a serialized version of the call
typedef void (*CompFuncPtr)(Fw::PassiveComponentBase* callComp, NATIVE_INT_TYPE portNum, SerializeBufferBase &arg); //!< port callback definition
void addCallComp(Fw::PassiveComponentBase* callComp, CompFuncPtr funcPtr); //!< call to register a component
protected:
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size);
#endif
private:
CompFuncPtr m_func; //!< pointer to port callback function
InputSerializePort(InputSerializePort*);
InputSerializePort(InputSerializePort&);
InputSerializePort& operator=(InputSerializePort&);
};
}
#endif // FW_INPUT_SERIALIZE_PORT_HPP
#endif
| hpp |
fprime | data/projects/fprime/Fw/Port/OutputSerializePort.hpp | #ifndef FW_OUTPUT_SERIALIZE_PORT_HPP
#define FW_OUTPUT_SERIALIZE_PORT_HPP
#include <FpConfig.hpp>
#if FW_PORT_SERIALIZATION == 1
#include <Fw/Port/OutputPortBase.hpp>
namespace Fw {
class OutputSerializePort : public OutputPortBase {
public:
OutputSerializePort();
virtual ~OutputSerializePort();
virtual void init();
protected:
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size);
#endif
private:
OutputSerializePort(OutputSerializePort*);
OutputSerializePort(OutputSerializePort&);
OutputSerializePort& operator=(OutputSerializePort&);
};
}
#endif // FW_OUTPUT_SERIALIZE_PORT_HPP
#endif
| hpp |
fprime | data/projects/fprime/Fw/Log/TextLogString.hpp | #ifndef FW_TEXT_LOG_STRING_TYPE_HPP
#define FW_TEXT_LOG_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class TextLogString : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_LOG_STR,
SERIALIZED_SIZE = FW_LOG_TEXT_BUFFER_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of two size words
};
TextLogString(const char* src);
TextLogString(const StringBase& src);
TextLogString(const TextLogString& src);
TextLogString();
TextLogString& operator=(const TextLogString& other);
TextLogString& operator=(const StringBase& other);
TextLogString& operator=(const char* other);
~TextLogString();
const char* toChar() const;
NATIVE_UINT_TYPE getCapacity() const ;
private:
char m_buf[FW_LOG_TEXT_BUFFER_SIZE];
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Log/LogPacket.hpp | /*
* LogPacket.hpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#ifndef LOGPACKET_HPP_
#define LOGPACKET_HPP_
#include <Fw/Com/ComPacket.hpp>
#include <Fw/Log/LogBuffer.hpp>
#include <Fw/Time/Time.hpp>
namespace Fw {
class LogPacket : public ComPacket {
public:
LogPacket();
virtual ~LogPacket();
SerializeStatus serialize(SerializeBufferBase& buffer) const; //!< serialize contents
SerializeStatus deserialize(SerializeBufferBase& buffer);
void setId(FwEventIdType id);
void setLogBuffer(const LogBuffer& buffer);
void setTimeTag(const Fw::Time& timeTag);
FwEventIdType getId();
Fw::Time& getTimeTag();
LogBuffer& getLogBuffer();
protected:
FwEventIdType m_id; // !< Channel id
Fw::Time m_timeTag; // !< time tag
LogBuffer m_logBuffer; // !< serialized argument data
};
} /* namespace Fw */
#endif /* LOGPACKET_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Log/TextLogString.cpp | #include <Fw/Log/TextLogString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
TextLogString::TextLogString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
TextLogString::TextLogString(const StringBase& src): StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
TextLogString::TextLogString(const TextLogString& src): StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
TextLogString::TextLogString(): StringBase() {
this->m_buf[0] = 0;
}
TextLogString& TextLogString::operator=(const TextLogString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
TextLogString& TextLogString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
TextLogString& TextLogString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
TextLogString::~TextLogString() {
}
const char* TextLogString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE TextLogString::getCapacity() const {
return FW_LOG_TEXT_BUFFER_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Log/LogString.hpp | #ifndef FW_LOG_STRING_TYPE_HPP
#define FW_LOG_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class LogStringArg : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_LOG_STR,
SERIALIZED_SIZE = FW_LOG_STRING_MAX_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of two size words
};
LogStringArg();
LogStringArg(const LogStringArg& src); //!< LogStringArg string constructor
LogStringArg(const StringBase& src); //!< other string constructor
LogStringArg(const char* src); //!< char* source constructor
LogStringArg& operator=(const LogStringArg& other); //!< assignment operator
LogStringArg& operator=(const StringBase& other); //!< other string assignment operator
LogStringArg& operator=(const char* other); //!< char* assignment operator
~LogStringArg();
const char* toChar() const override;
NATIVE_UINT_TYPE getCapacity() const override;
SerializeStatus serialize(SerializeBufferBase& buffer) const override; //!< serialization function
SerializeStatus serialize(SerializeBufferBase& buffer, NATIVE_UINT_TYPE maxLen) const override; //!< serialization function
SerializeStatus deserialize(SerializeBufferBase& buffer) override; //!< deserialization function
private:
char m_buf[FW_LOG_STRING_MAX_SIZE];
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Log/AmpcsEvrLogPacket.cpp | /*
* AmpcsEvrLogPacket.cpp
*
* Created on: October 07, 2016
* Author: Kevin F. Ortega
* Aadil Rizvi
*/
#include <Fw/Log/AmpcsEvrLogPacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
AmpcsEvrLogPacket::AmpcsEvrLogPacket() :
m_eventID(0),
m_overSeqNum(0),
m_catSeqNum(0) {
this->m_type = FW_PACKET_LOG;
}
AmpcsEvrLogPacket::~AmpcsEvrLogPacket() {
}
SerializeStatus AmpcsEvrLogPacket::serialize(SerializeBufferBase& buffer) const {
SerializeStatus stat;
stat = buffer.serialize(this->m_taskName, AMPCS_EVR_TASK_NAME_LEN, true);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_eventID);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_overSeqNum);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_catSeqNum);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
return buffer.serialize(this->m_logBuffer.getBuffAddr(),m_logBuffer.getBuffLength(),true);
}
SerializeStatus AmpcsEvrLogPacket::deserialize(SerializeBufferBase& buffer) {
NATIVE_UINT_TYPE len;
SerializeStatus stat;
len = AMPCS_EVR_TASK_NAME_LEN;
stat = buffer.deserialize(this->m_taskName, len, true);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.deserialize(this->m_eventID);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.deserialize(this->m_overSeqNum);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.deserialize(this->m_catSeqNum);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
NATIVE_UINT_TYPE size = buffer.getBuffLeft();
stat = buffer.deserialize(this->m_logBuffer.getBuffAddr(),size,true);
if (stat == FW_SERIALIZE_OK) {
// Shouldn't fail
stat = this->m_logBuffer.setBuffLen(size);
FW_ASSERT(stat == FW_SERIALIZE_OK,static_cast<NATIVE_INT_TYPE>(stat));
}
return stat;
}
void AmpcsEvrLogPacket::setTaskName(U8 *taskName, U8 len) {
FW_ASSERT(taskName != nullptr);
FW_ASSERT(len == AMPCS_EVR_TASK_NAME_LEN);
memcpy(this->m_taskName, (const void*)taskName, len);
}
void AmpcsEvrLogPacket::setId(U32 eventID) {
this->m_eventID = eventID;
}
void AmpcsEvrLogPacket::setOverSeqNum(U32 overSeqNum) {
this->m_overSeqNum = overSeqNum;
}
void AmpcsEvrLogPacket::setCatSeqNum(U32 catSeqNum) {
this->m_catSeqNum = catSeqNum;
}
void AmpcsEvrLogPacket::setLogBuffer(LogBuffer& buffer) {
this->m_logBuffer = buffer;
}
const U8* AmpcsEvrLogPacket::getTaskName() const {
return this->m_taskName;
}
U32 AmpcsEvrLogPacket::getId() const {
return this->m_eventID;
}
U32 AmpcsEvrLogPacket::getOverSeqNum() const {
return this->m_overSeqNum;
}
U32 AmpcsEvrLogPacket::getCatSeqNum() const {
return this->m_catSeqNum;
}
LogBuffer& AmpcsEvrLogPacket::getLogBuffer() {
return this->m_logBuffer;
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Log/LogBuffer.hpp | /*
* LogBuffer.hpp
*
* Created on: Sep 10, 2012
* Author: ppandian
*/
/*
* Description:
* This object contains the LogBuffer type, used for storing log entries
*/
#ifndef FW_LOG_BUFFER_HPP
#define FW_LOG_BUFFER_HPP
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class LogBuffer : public SerializeBufferBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_LOG_BUFF,
SERIALIZED_SIZE = FW_LOG_BUFFER_MAX_SIZE + sizeof(FwBuffSizeType)
};
LogBuffer(const U8 *args, NATIVE_UINT_TYPE size);
LogBuffer();
LogBuffer(const LogBuffer& other);
virtual ~LogBuffer();
LogBuffer& operator=(const LogBuffer& other);
NATIVE_UINT_TYPE getBuffCapacity() const; // !< returns capacity, not current size, of buffer
U8* getBuffAddr();
const U8* getBuffAddr() const;
private:
U8 m_bufferData[FW_LOG_BUFFER_MAX_SIZE]; // command argument buffer
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Log/LogString.cpp | #include <Fw/Log/LogString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Fw {
LogStringArg::LogStringArg(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
LogStringArg::LogStringArg(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
LogStringArg::LogStringArg(const LogStringArg& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
LogStringArg::LogStringArg()
: StringBase() {
this->m_buf[0] = 0;
}
LogStringArg& LogStringArg::operator=(const LogStringArg& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
LogStringArg& LogStringArg::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
LogStringArg& LogStringArg::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
LogStringArg::~LogStringArg() {
}
const char* LogStringArg::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE LogStringArg::getCapacity() const {
return FW_LOG_STRING_MAX_SIZE;
}
SerializeStatus LogStringArg::serialize(SerializeBufferBase& buffer) const {
return this->serialize(buffer, this->length());
}
SerializeStatus LogStringArg::serialize(SerializeBufferBase& buffer, NATIVE_UINT_TYPE maxLength) const {
NATIVE_INT_TYPE len = FW_MIN(maxLength,this->length());
#if FW_AMPCS_COMPATIBLE
// serialize 8-bit size with null terminator removed
U8 strSize = len - 1;
SerializeStatus stat = buffer.serialize(strSize);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
return buffer.serialize(reinterpret_cast<const U8*>(this->toChar()),strSize, true);
#else
return buffer.serialize(reinterpret_cast<const U8*>(this->toChar()),len);
#endif
}
SerializeStatus LogStringArg::deserialize(SerializeBufferBase& buffer) {
NATIVE_UINT_TYPE maxSize = this->getCapacity() - 1;
CHAR* raw = const_cast<CHAR*>(this->toChar());
#if FW_AMPCS_COMPATIBLE
// AMPCS encodes 8-bit string size
U8 strSize;
SerializeStatus stat = buffer.deserialize(strSize);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
strSize = FW_MIN(maxSize,strSize);
stat = buffer.deserialize(reinterpret_cast<U8*>(raw),strSize,true);
// AMPCS Strings not null terminated
if(strSize < maxSize) {
raw[strSize] = 0;
}
#else
SerializeStatus stat = buffer.deserialize(reinterpret_cast<U8*>(raw),maxSize);
#endif
// Null terminate deserialized string
raw[maxSize] = 0;
return stat;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Log/LogPacket.cpp | /*
* LogPacket.cpp
*
* Created on: May 24, 2014
* Author: Timothy Canham
*/
#include <Fw/Log/LogPacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
LogPacket::LogPacket() : m_id(0) {
this->m_type = FW_PACKET_LOG;
}
LogPacket::~LogPacket() {
}
SerializeStatus LogPacket::serialize(SerializeBufferBase& buffer) const {
SerializeStatus stat = ComPacket::serializeBase(buffer);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_id);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_timeTag);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// We want to add data but not size for the ground software
return buffer.serialize(this->m_logBuffer.getBuffAddr(),m_logBuffer.getBuffLength(),true);
}
SerializeStatus LogPacket::deserialize(SerializeBufferBase& buffer) {
SerializeStatus stat = deserializeBase(buffer);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.deserialize(this->m_id);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.deserialize(this->m_timeTag);
if (stat != FW_SERIALIZE_OK) {
return stat;
}
// remainder of buffer must be telemetry value
NATIVE_UINT_TYPE size = buffer.getBuffLeft();
stat = buffer.deserialize(this->m_logBuffer.getBuffAddr(),size,true);
if (stat == FW_SERIALIZE_OK) {
// Shouldn't fail
stat = this->m_logBuffer.setBuffLen(size);
FW_ASSERT(stat == FW_SERIALIZE_OK,static_cast<NATIVE_INT_TYPE>(stat));
}
return stat;
}
void LogPacket::setId(FwEventIdType id) {
this->m_id = id;
}
void LogPacket::setLogBuffer(const LogBuffer& buffer) {
this->m_logBuffer = buffer;
}
void LogPacket::setTimeTag(const Fw::Time& timeTag) {
this->m_timeTag = timeTag;
}
FwEventIdType LogPacket::getId() {
return this->m_id;
}
Fw::Time& LogPacket::getTimeTag() {
return this->m_timeTag;
}
LogBuffer& LogPacket::getLogBuffer() {
return this->m_logBuffer;
}
} /* namespace Fw */
| cpp |
fprime | data/projects/fprime/Fw/Log/LogBuffer.cpp | #include <Fw/Log/LogBuffer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
LogBuffer::LogBuffer(const U8 *args, NATIVE_UINT_TYPE size) {
SerializeStatus stat = SerializeBufferBase::setBuff(args,size);
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_UINT_TYPE>(stat));
}
LogBuffer::LogBuffer() {
}
LogBuffer::~LogBuffer() {
}
LogBuffer::LogBuffer(const LogBuffer& other) : Fw::SerializeBufferBase() {
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
LogBuffer& LogBuffer::operator=(const LogBuffer& other) {
if(this == &other) {
return *this;
}
SerializeStatus stat = SerializeBufferBase::setBuff(other.m_bufferData,other.getBuffLength());
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
return *this;
}
NATIVE_UINT_TYPE LogBuffer::getBuffCapacity() const {
return sizeof(this->m_bufferData);
}
const U8* LogBuffer::getBuffAddr() const {
return this->m_bufferData;
}
U8* LogBuffer::getBuffAddr() {
return this->m_bufferData;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Log/AmpcsEvrLogPacket.hpp | /*
* AmpcsEvrLogPacket.hpp
*
* Created on: October 07, 2016
* Author: Kevin F. Ortega
* Aadil Rizvi
*/
#ifndef AMPCS_EVR_LOGPACKET_HPP_
#define AMPCS_EVR_LOGPACKET_HPP_
#include <Fw/Com/ComPacket.hpp>
#include <Fw/Log/LogBuffer.hpp>
#include <Fw/Time/Time.hpp>
#include <cstring>
#define AMPCS_EVR_TASK_NAME_LEN 6
namespace Fw {
class AmpcsEvrLogPacket : public ComPacket {
public:
AmpcsEvrLogPacket();
virtual ~AmpcsEvrLogPacket();
SerializeStatus serialize(SerializeBufferBase& buffer) const; //!< serialize contents
SerializeStatus deserialize(SerializeBufferBase& buffer);
void setTaskName(U8 *taskName, U8 len);
void setId(U32 eventID);
void setOverSeqNum(U32 overSeqNum);
void setCatSeqNum(U32 catSeqNum);
void setLogBuffer(LogBuffer& buffer);
const U8* getTaskName() const;
U32 getId() const;
U32 getOverSeqNum() const;
U32 getCatSeqNum() const;
LogBuffer& getLogBuffer();
protected:
U8 m_taskName[AMPCS_EVR_TASK_NAME_LEN];
U32 m_eventID;
U32 m_overSeqNum;
U32 m_catSeqNum;
LogBuffer m_logBuffer; // !< serialized argument data
};
} /* namespace Fw */
#endif /* AMPCS_EVR_LOGPACKET_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Log/test/ut/LogTest.cpp | #include <gtest/gtest.h>
#include <Fw/Log/LogPacket.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Fw/Log/LogString.hpp>
TEST(FwLogTest,LogPacketSerialize) {
// Serialize data
Fw::LogPacket pktIn;
Fw::LogBuffer buffIn;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffIn.serialize(static_cast<U32>(12)));
Fw::Time timeIn(TB_WORKSTATION_TIME,10,11);
pktIn.setId(10);
pktIn.setTimeTag(timeIn);
pktIn.setLogBuffer(buffIn);
Fw::ComBuffer comBuff;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,comBuff.serialize(pktIn));
// Deserialize data
Fw::LogPacket pktOut;
Fw::LogBuffer buffOut;
Fw::Time timeOut(TB_WORKSTATION_TIME,10,11);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,comBuff.deserialize(pktOut));
ASSERT_EQ(pktOut.getId(),10u);
ASSERT_EQ(pktOut.getTimeTag(),timeOut);
U32 valOut = 0;
buffOut = pktOut.getLogBuffer();
buffOut.resetDeser();
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffOut.deserialize(valOut));
ASSERT_EQ(valOut,12u);
// serialize string
Fw::LogStringArg str1;
Fw::LogStringArg str2;
str1 = "Foo";
buffOut.resetSer();
str1.serialize(buffOut);
str2.deserialize(buffOut);
ASSERT_EQ(str1,str2);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Fw/Comp/ActiveComponentBase.hpp | /*
* ActiveComponentBase.hpp
*
* Created on: Aug 14, 2012
* Author: tcanham
*/
/*
* Description:
*/
#ifndef FW_ACTIVE_COMPONENT_BASE_HPP
#define FW_ACTIVE_COMPONENT_BASE_HPP
#include <FpConfig.hpp>
#include <Fw/Comp/QueuedComponentBase.hpp>
#include <Fw/Deprecate.hpp>
#include <Os/Task.hpp>
namespace Fw {
class ActiveComponentBase : public QueuedComponentBase {
public:
void start(Os::Task::ParamType priority = Os::Task::TASK_DEFAULT,
Os::Task::ParamType stackSize = Os::Task::TASK_DEFAULT,
Os::Task::ParamType cpuAffinity = Os::Task::TASK_DEFAULT,
Os::Task::ParamType identifier =
Os::Task::TASK_DEFAULT); //!< called by instantiator when task is to be started
void exit(); //!< exit task in active component
Os::Task::TaskStatus join(void** value_ptr); //!< provide return value of thread if value_ptr is not NULL
enum {
ACTIVE_COMPONENT_EXIT //!< message to exit active component task
};
PROTECTED:
explicit ActiveComponentBase(const char* name); //!< Constructor
virtual ~ActiveComponentBase(); //!< Destructor
void init(NATIVE_INT_TYPE instance); //!< initialization code
virtual void preamble(); //!< A function that will be called before the event loop is entered
virtual void loop(); //!< The function that will loop dispatching messages
virtual void finalizer(); //!< A function that will be called after exiting the loop
Os::Task m_task; //!< task object for active component
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size); //!< create string description of component
#endif
PRIVATE:
static void s_baseTask(void*); //!< function provided to task class for new thread.
static void s_baseBareTask(void*); //!< function provided to task class for new thread.
};
} // namespace Fw
#endif
| hpp |
fprime | data/projects/fprime/Fw/Comp/QueuedComponentBase.hpp | /*
* ActiveComponentBase.hpp
*
* Created on: Aug 14, 2012
* Author: tcanham
*/
/*
* Description:
*/
#ifndef FW_QUEUED_COMPONENT_BASE_HPP
#define FW_QUEUED_COMPONENT_BASE_HPP
#include <Fw/Comp/PassiveComponentBase.hpp>
#include <Os/Queue.hpp>
#include <Os/Task.hpp>
#include <FpConfig.hpp>
namespace Fw {
class QueuedComponentBase : public PassiveComponentBase {
public:
// Note: Had to make MsgDispatchStatus public for LLVM.
typedef enum {
MSG_DISPATCH_OK, //!< Dispatch was normal
MSG_DISPATCH_EMPTY, //!< No more messages in the queue
MSG_DISPATCH_ERROR, //!< Errors dispatching messages
MSG_DISPATCH_EXIT //!< A message was sent requesting an exit of the loop
} MsgDispatchStatus;
PROTECTED:
QueuedComponentBase(const char* name); //!< Constructor
virtual ~QueuedComponentBase(); //!< Destructor
void init(NATIVE_INT_TYPE instance); //!< initialization function
Os::Queue m_queue; //!< queue object for active component
Os::Queue::QueueStatus createQueue(NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize);
virtual MsgDispatchStatus doDispatch()=0; //!< method to dispatch a single message in the queue.
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size); //!< dump string representation of component
#endif
NATIVE_INT_TYPE getNumMsgsDropped(); //!< return number of messages dropped
void incNumMsgDropped(); //!< increment the number of messages dropped
PRIVATE:
NATIVE_INT_TYPE m_msgsDropped; //!< number of messages dropped from full queue
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Comp/PassiveComponentBase.cpp | #include <Fw/Comp/PassiveComponentBase.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <cstdio>
namespace Fw {
PassiveComponentBase::PassiveComponentBase(const char* name) : Fw::ObjBase(name), m_idBase(0), m_instance(0) {
}
#if FW_OBJECT_TO_STRING == 1 && FW_OBJECT_NAMES == 1
void PassiveComponentBase::toString(char* buffer, NATIVE_INT_TYPE size) {
FW_ASSERT(size > 0);
FW_ASSERT(buffer != nullptr);
PlatformIntType status = snprintf(buffer, size, "Comp: %s", this->m_objName.toChar());
if (status < 0) {
buffer[0] = 0;
}
}
#endif
PassiveComponentBase::~PassiveComponentBase() {
}
void PassiveComponentBase::init(NATIVE_INT_TYPE instance) {
ObjBase::init();
this->m_instance = instance;
}
NATIVE_INT_TYPE PassiveComponentBase::getInstance() const {
return this->m_instance;
}
void PassiveComponentBase ::
setIdBase(const U32 idBase)
{
this->m_idBase = idBase;
}
U32 PassiveComponentBase ::
getIdBase() const
{
return this->m_idBase;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Comp/PassiveComponentBase.hpp | #ifndef FW_COMP_BASE_HPP
#define FW_COMP_BASE_HPP
#include <Fw/Obj/ObjBase.hpp>
#include <Fw/Types/Serializable.hpp>
#include <FpConfig.hpp>
namespace Fw {
class PassiveComponentBase : public Fw::ObjBase {
public:
//! Set the ID base
void setIdBase(
const U32 //< The new ID base
);
//! Get the ID base
//! \return The ID base
U32 getIdBase() const;
PROTECTED:
PassiveComponentBase(const char* name); //!< Named constructor
virtual ~PassiveComponentBase(); //!< Destructor
void init(NATIVE_INT_TYPE instance); //!< Initialization function
NATIVE_INT_TYPE getInstance() const;
#if FW_OBJECT_TO_STRING == 1
virtual void toString(char* str, NATIVE_INT_TYPE size); //!< returns string description of component
#endif
PRIVATE:
U32 m_idBase; //!< ID base for opcodes etc.
NATIVE_INT_TYPE m_instance; //!< instance of component object
};
}
#endif
| hpp |
fprime | data/projects/fprime/Fw/Comp/ActiveComponentBase.cpp | #include <FpConfig.hpp>
#include <Fw/Comp/ActiveComponentBase.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/TaskString.hpp>
#include <cstdio>
//#define DEBUG_PRINT(...) printf(##__VA_ARGS__); fflush(stdout)
#define DEBUG_PRINT(...)
namespace Fw {
class ActiveComponentExitSerializableBuffer : public Fw::SerializeBufferBase {
public:
NATIVE_UINT_TYPE getBuffCapacity() const {
return sizeof(m_buff);
}
U8* getBuffAddr() {
return m_buff;
}
const U8* getBuffAddr() const {
return m_buff;
}
private:
U8 m_buff[sizeof(ActiveComponentBase::ACTIVE_COMPONENT_EXIT)];
};
ActiveComponentBase::ActiveComponentBase(const char* name) : QueuedComponentBase(name) {
}
ActiveComponentBase::~ActiveComponentBase() {
DEBUG_PRINT("ActiveComponent %s destructor.\n",this->getObjName());
}
void ActiveComponentBase::init(NATIVE_INT_TYPE instance) {
QueuedComponentBase::init(instance);
}
#if FW_OBJECT_TO_STRING == 1 && FW_OBJECT_NAMES == 1
void ActiveComponentBase::toString(char* buffer, NATIVE_INT_TYPE size) {
FW_ASSERT(size > 0);
FW_ASSERT(buffer != nullptr);
PlatformIntType status = snprintf(buffer, size, "ActComp: %s", this->m_objName.toChar());
if (status < 0) {
buffer[0] = 0;
}
}
#endif
void ActiveComponentBase::start(Os::Task::ParamType priority, Os::Task::ParamType stackSize, Os::Task::ParamType cpuAffinity, Os::Task::ParamType identifier) {
Os::TaskString taskName;
#if FW_OBJECT_NAMES == 1
taskName = this->getObjName();
#else
char taskNameChar[FW_TASK_NAME_MAX_SIZE];
(void)snprintf(taskNameChar,sizeof(taskNameChar),"ActComp_%d",Os::Task::getNumTasks());
taskName = taskNameChar;
#endif
// If running with the baremetal scheduler, use a variant of the task-loop that
// does not loop internal, but waits for an external iteration call.
#if FW_BAREMETAL_SCHEDULER == 1
Os::Task::taskRoutine routine = this->s_baseBareTask;
#else
Os::Task::taskRoutine routine = this->s_baseTask;
#endif
Os::Task::TaskStatus status = this->m_task.start(taskName, routine, this, priority, stackSize, cpuAffinity, identifier);
FW_ASSERT(status == Os::Task::TASK_OK,static_cast<NATIVE_INT_TYPE>(status));
}
void ActiveComponentBase::exit() {
ActiveComponentExitSerializableBuffer exitBuff;
SerializeStatus stat = exitBuff.serialize(static_cast<I32>(ACTIVE_COMPONENT_EXIT));
FW_ASSERT(FW_SERIALIZE_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
(void)this->m_queue.send(exitBuff,0,Os::Queue::QUEUE_NONBLOCKING);
DEBUG_PRINT("exit %s\n", this->getObjName());
}
Os::Task::TaskStatus ActiveComponentBase::join(void **value_ptr) {
DEBUG_PRINT("join %s\n", this->getObjName());
return this->m_task.join(value_ptr);
}
void ActiveComponentBase::s_baseBareTask(void* ptr) {
FW_ASSERT(ptr != nullptr);
ActiveComponentBase* comp = reinterpret_cast<ActiveComponentBase*>(ptr);
//Start if not started
if (!comp->m_task.isStarted()) {
comp->m_task.setStarted(true);
comp->preamble();
}
//Bare components cannot block, so return to the scheduler
if (comp->m_queue.getNumMsgs() == 0) {
return;
}
ActiveComponentBase::MsgDispatchStatus loopStatus = comp->doDispatch();
switch (loopStatus) {
case ActiveComponentBase::MSG_DISPATCH_OK: // if normal message processing, continue
break;
case ActiveComponentBase::MSG_DISPATCH_EXIT:
comp->finalizer();
comp->m_task.setStarted(false);
break;
default:
FW_ASSERT(0,static_cast<NATIVE_INT_TYPE>(loopStatus));
}
}
void ActiveComponentBase::s_baseTask(void* ptr) {
// cast void* back to active component
ActiveComponentBase* comp = static_cast<ActiveComponentBase*> (ptr);
// indicated that task is started
comp->m_task.setStarted(true);
// print out message when task is started
// printf("Active Component %s task started.\n",comp->getObjName());
// call preamble
comp->preamble();
// call main task loop until exit or error
comp->loop();
// if main loop exits, call finalizer
comp->finalizer();
}
void ActiveComponentBase::loop() {
bool quitLoop = false;
while (!quitLoop) {
MsgDispatchStatus loopStatus = this->doDispatch();
switch (loopStatus) {
case MSG_DISPATCH_OK: // if normal message processing, continue
break;
case MSG_DISPATCH_EXIT:
quitLoop = true;
break;
default:
FW_ASSERT(0,static_cast<NATIVE_INT_TYPE>(loopStatus));
}
}
}
void ActiveComponentBase::preamble() {
}
void ActiveComponentBase::finalizer() {
}
}
| cpp |
fprime | data/projects/fprime/Fw/Comp/QueuedComponentBase.cpp | #include <Fw/Comp/QueuedComponentBase.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <Os/QueueString.hpp>
#include <cstdio>
namespace Fw {
QueuedComponentBase::QueuedComponentBase(const char* name) : PassiveComponentBase(name),m_msgsDropped(0) {
}
QueuedComponentBase::~QueuedComponentBase() {
}
void QueuedComponentBase::init(NATIVE_INT_TYPE instance) {
PassiveComponentBase::init(instance);
}
#if FW_OBJECT_TO_STRING == 1 && FW_OBJECT_NAMES == 1
void QueuedComponentBase::toString(char* buffer, NATIVE_INT_TYPE size) {
FW_ASSERT(size > 0);
FW_ASSERT(buffer != nullptr);
PlatformIntType status = snprintf(buffer, size, "QueueComp: %s", this->m_objName.toChar());
if (status < 0) {
buffer[0] = 0;
}
}
#endif
Os::Queue::QueueStatus QueuedComponentBase::createQueue(NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
Os::QueueString queueName;
#if FW_OBJECT_NAMES == 1
queueName = this->m_objName;
#else
char queueNameChar[FW_QUEUE_NAME_MAX_SIZE];
(void)snprintf(queueNameChar,sizeof(queueNameChar),"CompQ_%d",Os::Queue::getNumQueues());
queueName = queueNameChar;
#endif
return this->m_queue.create(queueName, depth, msgSize);
}
NATIVE_INT_TYPE QueuedComponentBase::getNumMsgsDropped() {
return this->m_msgsDropped;
}
void QueuedComponentBase::incNumMsgDropped() {
this->m_msgsDropped++;
}
}
| cpp |
fprime | data/projects/fprime/Fw/Buffer/Buffer.cpp | // ======================================================================
// \title Buffer.cpp
// \author mstarch
// \brief cpp file for Fw::Buffer implementation
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/Buffer/Buffer.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#if FW_SERIALIZABLE_TO_STRING
#include <Fw/Types/String.hpp>
#endif
#include <cstring>
namespace Fw {
Buffer::Buffer(): Serializable(),
m_serialize_repr(),
m_bufferData(nullptr),
m_size(0),
m_context(0xFFFFFFFF)
{}
Buffer::Buffer(const Buffer& src) : Serializable(),
m_serialize_repr(),
m_bufferData(src.m_bufferData),
m_size(src.m_size),
m_context(src.m_context)
{
if(src.m_bufferData != nullptr){
this->m_serialize_repr.setExtBuffer(src.m_bufferData, src.m_size);
}
}
Buffer::Buffer(U8* data, U32 size, U32 context) : Serializable(),
m_serialize_repr(),
m_bufferData(data),
m_size(size),
m_context(context)
{
if(m_bufferData != nullptr){
this->m_serialize_repr.setExtBuffer(this->m_bufferData, this->m_size);
}
}
Buffer& Buffer::operator=(const Buffer& src) {
// Ward against self-assignment
if (this != &src) {
this->set(src.m_bufferData, src.m_size, src.m_context);
}
return *this;
}
bool Buffer::operator==(const Buffer& src) const {
return (this->m_bufferData == src.m_bufferData) && (this->m_size == src.m_size) && (this->m_context == src.m_context);
}
bool Buffer::isValid() const {
return (this->m_bufferData != nullptr) && (this->m_size > 0);
}
U8* Buffer::getData() const {
return this->m_bufferData;
}
U32 Buffer::getSize() const {
return this->m_size;
}
U32 Buffer::getContext() const {
return this->m_context;
}
void Buffer::setData(U8* const data) {
this->m_bufferData = data;
if (m_bufferData != nullptr) {
this->m_serialize_repr.setExtBuffer(this->m_bufferData, this->m_size);
}
}
void Buffer::setSize(const U32 size) {
this->m_size = size;
if (m_bufferData != nullptr) {
this->m_serialize_repr.setExtBuffer(this->m_bufferData, this->m_size);
}
}
void Buffer::setContext(const U32 context) {
this->m_context = context;
}
void Buffer::set(U8* const data, const U32 size, const U32 context) {
this->m_bufferData = data;
this->m_size = size;
if (m_bufferData != nullptr) {
this->m_serialize_repr.setExtBuffer(this->m_bufferData, this->m_size);
}
this->m_context = context;
}
Fw::SerializeBufferBase& Buffer::getSerializeRepr() {
return m_serialize_repr;
}
Fw::SerializeStatus Buffer::serialize(Fw::SerializeBufferBase& buffer) const {
Fw::SerializeStatus stat;
#if FW_SERIALIZATION_TYPE_ID
stat = buffer.serialize(static_cast<U32>(Buffer::TYPE_ID));
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
#endif
stat = buffer.serialize(reinterpret_cast<POINTER_CAST>(this->m_bufferData));
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_size);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.serialize(this->m_context);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
return stat;
}
Fw::SerializeStatus Buffer::deserialize(Fw::SerializeBufferBase& buffer) {
Fw::SerializeStatus stat;
#if FW_SERIALIZATION_TYPE_ID
U32 typeId;
stat = buffer.deserialize(typeId);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
if (typeId != Buffer::TYPE_ID) {
return Fw::FW_DESERIALIZE_TYPE_MISMATCH;
}
#endif
POINTER_CAST pointer;
stat = buffer.deserialize(pointer);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
this->m_bufferData = reinterpret_cast<U8*>(pointer);
stat = buffer.deserialize(this->m_size);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
stat = buffer.deserialize(this->m_context);
if (stat != Fw::FW_SERIALIZE_OK) {
return stat;
}
if (this->m_bufferData != nullptr) {
this->m_serialize_repr.setExtBuffer(this->m_bufferData, this->m_size);
}
return stat;
}
#if FW_SERIALIZABLE_TO_STRING || BUILD_UT
void Buffer::toString(Fw::StringBase& text) const {
static const char * formatString = "(data = %p, size = %u,context = %u)";
char outputString[FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE];
(void)snprintf(outputString, FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE, formatString, this->m_bufferData, this->m_size,
this->m_context);
// Force NULL termination
outputString[FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE-1] = 0;
text = outputString;
}
#endif
#ifdef BUILD_UT
std::ostream& operator<<(std::ostream& os, const Buffer& obj) {
Fw::String str;
obj.toString(str);
os << str.toChar();
return os;
}
#endif
} // end namespace Fw
| cpp |
fprime | data/projects/fprime/Fw/Buffer/Buffer.hpp | // ======================================================================
// \title Buffer.hpp
// \author mstarch
// \brief hpp file for Fw::Buffer definition
//
// \copyright
// Copyright 2009-2020, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef BUFFER_HPP_
#define BUFFER_HPP_
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#if FW_SERIALIZABLE_TO_STRING
#include <Fw/Types/StringType.hpp>
#include <cstdio> // snprintf
#ifdef BUILD_UT
#include <iostream>
#include <Fw/Types/String.hpp>
#endif
#endif
namespace Fw {
//! Buffer used for wrapping pointer to data for efficient transmission
//!
//! Fw::Buffer is a wrapper for a pointer to data. It allows for data to be passed around the system without a copy of
//! the data itself. However, it comes with the expectation that the user maintain and protect this memory as it moves
//! about the system until such a time as it is returned.
//!
//! Fw::Buffer is composed of several elements: a U8* pointer to the data, a U32 size of that data, and a U32 context
//! describing the origin of that data, such that it may be freed at some later point. The default context of 0xFFFFFFFF
//! should not be used for tracking purposes, as it represents a context-free buffer.
//!
//! Fw::Buffer also comes with functions to return a representation of the data as a SerializeBufferBase. These two
//! functions allow easy access to the data as if it were a serialize or deserialize buffer. This can aid in writing and
//! reading the wrapped data whereas the standard serialize and deserialize methods treat the data as a pointer to
//! prevent excessive copying.
//!
class Buffer : public Fw::Serializable {
public:
enum {
SERIALIZED_SIZE = sizeof(U32) + sizeof(U32) + sizeof(U8*), //!< Size of Fw::Buffer when serialized
NO_CONTEXT = 0xFFFFFFFF //!< Value representing no context
};
//! Construct a buffer with no context nor data
//!
//! Constructs a buffer setting the context to the default no-context value of 0xffffffff. In addition, the size
//! and data pointers are zeroed-out.
Buffer();
//! Construct a buffer by copying members from a reference to another buffer. Does not copy wrapped data.
//!
Buffer(const Buffer& src);
//! Construct a buffer to wrap the given data pointer of given size
//!
//! Wraps the given data pointer with given size in a buffer. The context by default is set to NO_CONTEXT but can
//! be set to specify a specific context.
//! \param data: data pointer to wrap
//! \param size: size of data located at data pointer
//! \param context: user-specified context to track creation. Default: no context
Buffer(U8* data, U32 size, U32 context=NO_CONTEXT);
//! Assignment operator to set given buffer's members from another without copying wrapped data
//!
Buffer& operator=(const Buffer& src);
//! Equality operator returning true when buffers are equivalent
//!
//! Buffers are deemed equivalent if they contain a pointer to the same data, with the same size, and the same
//! context. The representation of that buffer for use with serialization and deserialization need not be
//! equivalent.
//! \param src: buffer to test against
//! \return: true if equivalent, false otherwise
bool operator==(const Buffer& src) const;
// ----------------------------------------------------------------------
// Serialization functions
// ----------------------------------------------------------------------
//! Returns a SerializeBufferBase representation of the wrapped data for serializing
//!
//! Returns a SerializeBufferBase representation of the wrapped data allowing for serializing other types of data
//! to the wrapped buffer. Once obtained the user should call one of two functions: `sbb.resetSer();` to setup for
//! serialization, or `sbb.setBuffLen(buffer.getSize());` to setup for deserializing.
//! \return representation of the wrapped data to aid in serializing to it
SerializeBufferBase& getSerializeRepr();
//! Serializes this buffer to a SerializeBufferBase
//!
//! This serializes the buffer to a SerializeBufferBase, however, it DOES NOT serialize the wrapped data. It only
//! serializes the pointer to said data, the size, and context. This is done for efficiency in moving around data,
//! and is the primary usage of Fw::Buffer. To serialize the wrapped data, use either the data pointer accessor
//! or the serialize buffer base representation and serialize from that.
//! \param serialBuffer: serialize buffer to write data into
//! \return: status of serialization
Fw::SerializeStatus serialize(Fw::SerializeBufferBase& serialBuffer) const;
//! Deserializes this buffer from a SerializeBufferBase
//!
//! This deserializes the buffer from a SerializeBufferBase, however, it DOES NOT handle serialized data. It only
//! deserializes the pointer to said data, the size, and context. This is done for efficiency in moving around data,
//! and is the primary usage of Fw::Buffer. To deserialize the wrapped data, use either the data pointer accessor
//! or the serialize buffer base representation and deserialize from that.
//! \param buffer: serialize buffer to read data into
//! \return: status of serialization
Fw::SerializeStatus deserialize(Fw::SerializeBufferBase& buffer);
// ----------------------------------------------------------------------
// Accessor functions
// ----------------------------------------------------------------------
//! Returns true if the buffer is valid (data pointer != nullptr and size > 0)
//!
bool isValid() const;
//! Returns wrapped data pointer
//!
U8* getData() const;
//! Returns size of wrapped data
//!
U32 getSize() const;
//! Returns creation context
//!
U32 getContext() const;
//! Sets pointer to wrapped data and the size of the given data
//!
void setData(U8* data);
//! Sets pointer to wrapped data and the size of the given data
//!
void setSize(U32 size);
//! Sets creation context
//!
void setContext(U32 context);
//! Sets all values
//! \param data: data pointer to wrap
//! \param size: size of data located at data pointer
//! \param context: user-specified context to track creation. Default: no context
void set(U8* data, U32 size, U32 context=NO_CONTEXT);
#if FW_SERIALIZABLE_TO_STRING || BUILD_UT
//! Supports writing this buffer to a string representation
void toString(Fw::StringBase& text) const;
#endif
#ifdef BUILD_UT
//! Supports GTest framework for outputting this type to a stream
//!
friend std::ostream& operator<<(std::ostream& os, const Buffer& obj);
#endif
PRIVATE:
Fw::ExternalSerializeBuffer m_serialize_repr; //<! Representation for serialization and deserialization functions
U8* m_bufferData; //<! data - A pointer to the data
U32 m_size; //<! size - The data size in bytes
U32 m_context; //!< Creation context for disposal
};
} // end namespace Fw
#endif /* BUFFER_HPP_ */
| hpp |
fprime | data/projects/fprime/Fw/Buffer/test/ut/TestBuffer.cpp | //
// Created by mstarch on 11/13/20.
//
#include "Fw/Buffer/Buffer.hpp"
#include <FpConfig.hpp>
#include <gtest/gtest.h>
void test_basic() {
U8 data[100];
U8 faux[100];
Fw::Buffer buffer;
// Check basic guarantees
ASSERT_EQ(buffer.m_context, Fw::Buffer::NO_CONTEXT);
buffer.setData(data);
buffer.setSize(sizeof(data));
buffer.setContext(1234);
ASSERT_EQ(buffer.getData(), data);
ASSERT_EQ(buffer.getSize(), sizeof(data));
ASSERT_EQ(buffer.getContext(), 1234);
// Test set method is equivalent
Fw::Buffer buffer_set;
buffer_set.set(data, sizeof(data), 1234);
ASSERT_EQ(buffer_set, buffer);
// Check constructors and assignments
Fw::Buffer buffer_new(buffer);
ASSERT_EQ(buffer_new.getData(), data);
ASSERT_EQ(buffer_new.getSize(), sizeof(data));
ASSERT_EQ(buffer_new.getContext(), 1234);
ASSERT_EQ(buffer, buffer_new);
// Creating empty buffer
Fw::Buffer testBuffer(nullptr,0);
ASSERT_EQ(testBuffer.getData(), nullptr);
ASSERT_EQ(testBuffer.getSize(), 0);
// Assignment operator with transitivity
Fw::Buffer buffer_assignment1, buffer_assignment2;
ASSERT_NE(buffer_assignment1.getData(), data);
ASSERT_NE(buffer_assignment1.getSize(), sizeof(data));
ASSERT_NE(buffer_assignment1.getContext(), 1234);
ASSERT_NE(buffer_assignment2.getData(), data);
ASSERT_NE(buffer_assignment2.getSize(), sizeof(data));
ASSERT_NE(buffer_assignment2.getContext(), 1234);
buffer_assignment1 = buffer_assignment2 = buffer;
ASSERT_EQ(buffer_assignment1.getData(), data);
ASSERT_EQ(buffer_assignment1.getSize(), sizeof(data));
ASSERT_EQ(buffer_assignment1.getContext(), 1234);
ASSERT_EQ(buffer_assignment2.getData(), data);
ASSERT_EQ(buffer_assignment2.getSize(), sizeof(data));
ASSERT_EQ(buffer_assignment2.getContext(), 1234);
// Check modifying the copies does not destroy
buffer_new.setSize(0);
buffer_new.setData(faux);
buffer_new.setContext(22222);
buffer_assignment1.setSize(0);
buffer_assignment1.setData(faux);
buffer_assignment1.setContext(22222);
buffer_assignment2.setSize(0);
buffer_assignment2.setData(faux);
buffer_assignment2.setContext(22222);
ASSERT_EQ(buffer.getData(), data);
ASSERT_EQ(buffer.getSize(), sizeof(data));
ASSERT_EQ(buffer.getContext(), 1234);
}
void test_representations() {
U8 data[100];
Fw::Buffer buffer;
buffer.setData(data);
buffer.setSize(sizeof(data));
buffer.setContext(1234);
// Test serialization and that it stops before overflowing
Fw::SerializeBufferBase& sbb = buffer.getSerializeRepr();
sbb.resetSer();
for (U32 i = 0; i < sizeof(data)/4; i++) {
ASSERT_EQ(sbb.serialize(i), Fw::FW_SERIALIZE_OK);
}
Fw::SerializeStatus stat = sbb.serialize(100);
ASSERT_NE(stat, Fw::FW_SERIALIZE_OK);
// And that another call to repr resets it
sbb = buffer.getSerializeRepr();
sbb.resetSer();
ASSERT_EQ(sbb.serialize(0), Fw::FW_SERIALIZE_OK);
// Now deserialize all the things
U32 out;
sbb = buffer.getSerializeRepr();
sbb.setBuffLen(buffer.getSize());
for (U32 i = 0; i < sizeof(data)/4; i++) {
ASSERT_EQ(sbb.deserialize(out), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(i, out);
}
ASSERT_NE(sbb.deserialize(out), Fw::FW_SERIALIZE_OK);
sbb = buffer.getSerializeRepr();
sbb.setBuffLen(buffer.getSize());
ASSERT_EQ(sbb.deserialize(out), Fw::FW_SERIALIZE_OK);
ASSERT_EQ(0, out);
}
void test_serialization() {
U8 data[100];
U8 wire[100];
Fw::Buffer buffer;
buffer.setData(data);
buffer.setSize(sizeof(data));
buffer.setContext(1234);
Fw::ExternalSerializeBuffer externalSerializeBuffer(wire, sizeof(wire));
externalSerializeBuffer.serialize(buffer);
ASSERT_LT(externalSerializeBuffer.m_serLoc, sizeof(data));
Fw::Buffer buffer_new;
externalSerializeBuffer.deserialize(buffer_new);
ASSERT_EQ(buffer_new, buffer);
// Make sure internal ExternalSerializeBuffer is reinitialized
ASSERT_EQ(buffer_new.m_serialize_repr.m_buff,data);
ASSERT_EQ(buffer_new.m_serialize_repr.m_buffSize,sizeof(data));
}
TEST(Nominal, BasicBuffer) {
test_basic();
}
TEST(Nominal, Representations) {
test_representations();
}
TEST(Nominal, Serialization) {
test_serialization();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Os/Mem.hpp | #ifndef _Mem_hpp_
#define _Mem_hpp_
#include <FpConfig.hpp>
#include <Fw/Obj/ObjBase.hpp>
#include <Fw/Types/Serializable.hpp>
namespace Os {
class Mem {
public:
static U32 virtToPhys(U32 virtAddr); //!< Translate virtual to physical memory
static U32 physToVirt(U32 physAddr); //!< Translate physical to virtual memory
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/SimpleQueueRegistry.cpp | /*
* SimpleQueueRegistry.cpp
*
* Created on: Apr 7, 2016
* Author: tcanham
*/
#if FW_QUEUE_REGISTRATION
#include <Os/SimpleQueueRegistry.hpp>
namespace Os {
SimpleQueueRegistry::SimpleQueueRegistry() {
}
SimpleQueueRegistry::~SimpleQueueRegistry() {
}
void SimpleQueueRegistry::regQueue(Queue* obj) {
}
void SimpleQueueRegistry::dump() {
}
} /* namespace Os */
#endif
| cpp |
fprime | data/projects/fprime/Os/InterruptLock.hpp | #ifndef _InterruptLock_hpp_
#define _InterruptLock_hpp_
#include <FpConfig.hpp>
namespace Os {
class InterruptLock {
public:
InterruptLock(); //!< Constructor
virtual ~InterruptLock(); //!< destructor
void lock(); //!< lock interrupts
void unLock(); //!< unlock interrupts
POINTER_CAST getKey(); //!< get the key, if used
private:
POINTER_CAST m_key; //!< storage of interrupt lock key if used
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/File.cpp | // ======================================================================
// \title Os/File.cpp
// \brief common function implementation for Os::File
// ======================================================================
#include <Os/File.hpp>
#include <Fw/Types/Assert.hpp>
extern "C" {
#include <Utils/Hash/libcrc/lib_crc.h> // borrow CRC
}
namespace Os {
File::File() : m_crc_buffer(), m_handle_storage(), m_delegate(*FileInterface::getDelegate(&m_handle_storage[0])) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
}
File::~File() {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
if (this->m_mode != OPEN_NO_MODE) {
this->close();
}
m_delegate.~FileInterface();
}
File::File(const File& other) :
m_mode(other.m_mode),
m_path(other.m_path),
m_crc(other.m_crc),
m_crc_buffer(),
m_handle_storage(),
m_delegate(*FileInterface::getDelegate(&m_handle_storage[0], &other.m_delegate)) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
}
File& File::operator=(const File& other) {
if (this != &other) {
this->m_mode = other.m_mode;
this->m_path = other.m_path;
this->m_crc = other.m_crc;
this->m_delegate = *FileInterface::getDelegate(&m_handle_storage[0], &other.m_delegate);
}
return *this;
}
File::Status File::open(const CHAR* filepath, File::Mode requested_mode) {
return this->open(filepath, requested_mode, OverwriteType::NO_OVERWRITE);
}
File::Status File::open(const CHAR* filepath, File::Mode requested_mode, File::OverwriteType overwrite) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT(nullptr != filepath);
FW_ASSERT(File::Mode::OPEN_NO_MODE < requested_mode && File::Mode::MAX_OPEN_MODE > requested_mode);
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
FW_ASSERT((0 <= overwrite) && (overwrite < OverwriteType::MAX_OVERWRITE_TYPE));
// Check for already opened file
if (this->isOpen()) {
return File::Status::INVALID_MODE;
}
File::Status status = this->m_delegate.open(filepath, requested_mode, overwrite);
if (status == File::Status::OP_OK) {
this->m_mode = requested_mode;
this->m_path = filepath;
}
// Reset any open CRC calculations
this->m_crc = File::INITIAL_CRC;
return status;
}
void File::close() {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT(this->m_mode < Mode::MAX_OPEN_MODE);
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
this->m_delegate.close();
this->m_mode = Mode::OPEN_NO_MODE;
this->m_path = nullptr;
}
bool File::isOpen() const {
FW_ASSERT(&this->m_delegate == reinterpret_cast<const FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
return this->m_mode != Mode::OPEN_NO_MODE;
}
File::Status File::size(FwSignedSizeType& size_result) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
if (OPEN_NO_MODE == this->m_mode) {
return File::Status::NOT_OPENED;
}
return this->m_delegate.size(size_result);
}
File::Status File::position(FwSignedSizeType &position_result) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
// Check that the file is open before attempting operation
if (OPEN_NO_MODE == this->m_mode) {
return File::Status::NOT_OPENED;
}
return this->m_delegate.position(position_result);
}
File::Status File::preallocate(FwSignedSizeType offset, FwSignedSizeType length) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT(offset >= 0);
FW_ASSERT(length >= 0);
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
// Check that the file is open before attempting operation
if (OPEN_NO_MODE == this->m_mode) {
return File::Status::NOT_OPENED;
} else if (OPEN_READ == this->m_mode) {
return File::Status::INVALID_MODE;
}
return this->m_delegate.preallocate(offset, length);
}
File::Status File::seek(FwSignedSizeType offset, File::SeekType seekType) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT((0 <= seekType) && (seekType < SeekType::MAX_SEEK_TYPE));
// Cannot do a seek with a negative offset in absolute mode
FW_ASSERT((seekType == File::SeekType::RELATIVE) || (offset >= 0));
FW_ASSERT((0 <= this->m_mode) && (this->m_mode < Mode::MAX_OPEN_MODE));
// Check that the file is open before attempting operation
if (OPEN_NO_MODE == this->m_mode) {
return File::Status::NOT_OPENED;
}
return this->m_delegate.seek(offset, seekType);
}
File::Status File::flush() {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT(this->m_mode < Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (OPEN_NO_MODE == this->m_mode) {
return File::Status::NOT_OPENED;
} else if (OPEN_READ == this->m_mode) {
return File::Status::INVALID_MODE;
}
return this->m_delegate.flush();
}
File::Status File::read(U8* buffer, FwSignedSizeType &size) {
return this->read(buffer, size, WaitType::WAIT);
}
File::Status File::read(U8* buffer, FwSignedSizeType &size, File::WaitType wait) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT(buffer != nullptr);
FW_ASSERT(size >= 0);
FW_ASSERT(this->m_mode < Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (OPEN_NO_MODE == this->m_mode) {
size = 0;
return File::Status::NOT_OPENED;
} else if (OPEN_READ != this->m_mode) {
size = 0;
return File::Status::INVALID_MODE;
}
return this->m_delegate.read(buffer, size, wait);
}
File::Status File::write(const U8* buffer, FwSignedSizeType &size) {
return this->write(buffer, size, WaitType::WAIT);
}
File::Status File::write(const U8* buffer, FwSignedSizeType &size, File::WaitType wait) {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
FW_ASSERT(buffer != nullptr);
FW_ASSERT(size >= 0);
FW_ASSERT(this->m_mode < Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (OPEN_NO_MODE == this->m_mode) {
size = 0;
return File::Status::NOT_OPENED;
} else if (OPEN_READ == this->m_mode) {
size = 0;
return File::Status::INVALID_MODE;
}
return this->m_delegate.write(buffer, size, wait);
}
FileHandle* File::getHandle() {
FW_ASSERT(&this->m_delegate == reinterpret_cast<FileInterface*>(&this->m_handle_storage[0]));
return this->m_delegate.getHandle();
}
File::Status File::calculateCrc(U32 &crc) {
File::Status status = File::Status::OP_OK;
FwSignedSizeType size = FW_FILE_CHUNK_SIZE;
crc = 0;
for (FwSizeType i = 0; i < std::numeric_limits<FwSizeType>::max(); i++) {
status = this->incrementalCrc(size);
// Break on eof or error
if ((size != FW_FILE_CHUNK_SIZE) || (status != File::OP_OK)) {
break;
}
}
// When successful, finalize the CRC
if (status == File::OP_OK) {
status = this->finalizeCrc(crc);
}
return status;
}
File::Status File::incrementalCrc(FwSignedSizeType &size) {
File::Status status = File::Status::OP_OK;
FW_ASSERT(size >= 0);
FW_ASSERT(size <= FW_FILE_CHUNK_SIZE);
if (OPEN_NO_MODE == this->m_mode) {
status = File::Status::NOT_OPENED;
} else if (OPEN_READ != this->m_mode) {
status = File::Status::INVALID_MODE;
} else {
// Read data without waiting for additional data to be available
status = this->read(this->m_crc_buffer, size, File::WaitType::NO_WAIT);
if (OP_OK == status) {
for (FwSignedSizeType i = 0; i < size && i < FW_FILE_CHUNK_SIZE; i++) {
this->m_crc = update_crc_32(this->m_crc, static_cast<CHAR>(this->m_crc_buffer[i]));
}
}
}
return status;
}
File::Status File::finalizeCrc(U32 &crc) {
File::Status status = File::Status::OP_OK;
crc = this->m_crc;
this->m_crc = File::INITIAL_CRC;
return status;
}
} // Os
| cpp |
fprime | data/projects/fprime/Os/SimpleQueueRegistry.hpp | /**
* \file
* \author T. Canham
* \brief Class declaration for a simple queue registry
*
* The simple object registry is meant to give a default implementation
* and an example of a queue registry. When the registry is instantiated,
* it registers itself with the setQueueRegistry() static method. When
* queues in the system are instantiated, they will register themselves.
* The registry can then query the instances about their names, sizes,
* and high watermarks.
*
* \copyright
* Copyright 2013-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef SIMPLEQUEUEREGISTRY_HPP_
#define SIMPLEQUEUEREGISTRY_HPP_
#if FW_QUEUE_REGISTRATION
#include <Os/Queue.hpp>
namespace Os {
class SimpleQueueRegistry: public QueueRegistry {
public:
SimpleQueueRegistry(); //!< constructor
virtual ~SimpleQueueRegistry(); //!< destructor
void regQueue(Queue* obj); //!< method called by queue init() methods to register a new queue
void dump(); //!< dump list of queues and stats
};
} /* namespace Os */
#endif // FW_QUEUE_REGISTRATION
#endif /* SIMPLEQUEUEREGISTRY_HPP_ */
| hpp |
fprime | data/projects/fprime/Os/ValidatedFile.hpp | // ======================================================================
// \title ValidatedFile.hpp
// \author bocchino
// \brief An fprime validated file
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef OS_ValidatedFile_HPP
#define OS_ValidatedFile_HPP
#include "Fw/Types/String.hpp"
#include <FpConfig.hpp>
#include "Os/ValidateFile.hpp"
namespace Os {
//! A validated file
class ValidatedFile {
public:
//! Construct a validated file
ValidatedFile(
const char* const fileName //!< The file name
);
public:
//! Validate the file
//! \return Status
Os::ValidateFile::Status validate();
//! Create the hash file
//! \return Status
Os::ValidateFile::Status createHashFile();
public:
//! Get the file name
//! \return The file name
const Fw::StringBase& getFileName() const;
//! Get the hash file name
//! \return The hash file name
const Fw::StringBase& getHashFileName() const;
//! Get the hash file buffer
//! \return The hash file buffer
const Utils::HashBuffer& getHashBuffer() const;
PRIVATE:
//! The file name
Fw::String m_fileName;
//! The hash file name
Fw::String m_hashFileName;
//! The hash value after creating or loading a validation file
Utils::HashBuffer m_hashBuffer;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/IPCQueueCommon.cpp | #include <Os/IPCQueue.hpp>
#include <cstring>
namespace Os {
Queue::QueueStatus IPCQueue::send(const Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE priority, QueueBlocking block) {
const U8* msgBuff = buffer.getBuffAddr();
NATIVE_INT_TYPE buffLength = buffer.getBuffLength();
return this->send(msgBuff,buffLength,priority, block);
}
Queue::QueueStatus IPCQueue::receive(Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE &priority, QueueBlocking block) {
U8* msgBuff = buffer.getBuffAddr();
NATIVE_INT_TYPE buffCapacity = buffer.getBuffCapacity();
NATIVE_INT_TYPE recvSize = 0;
Queue::QueueStatus recvStat = this->receive(msgBuff, buffCapacity, recvSize, priority, block);
if (QUEUE_OK == recvStat) {
if (buffer.setBuffLen(recvSize) == Fw::FW_SERIALIZE_OK) {
return QUEUE_OK;
} else {
return QUEUE_SIZE_MISMATCH;
}
} else {
return recvStat;
}
}
}
| cpp |
fprime | data/projects/fprime/Os/ValidatedFile.cpp | // ======================================================================
// \title ValidatedFile.cpp
// \author bocchino
// \brief Os::ValidatedFile implementation
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Os/ValidatedFile.hpp"
#include "Utils/Hash/Hash.hpp"
namespace Os {
ValidatedFile ::
ValidatedFile(const char *const fileName) :
m_fileName(fileName),
m_hashFileName(""),
m_hashBuffer()
{
Utils::Hash::addFileExtension(this->m_fileName, this->m_hashFileName);
}
Os::ValidateFile::Status ValidatedFile ::
validate()
{
const Os::ValidateFile::Status status =
Os::ValidateFile::validate(
this->m_fileName.toChar(),
this->m_hashFileName.toChar(),
this->m_hashBuffer
);
return status;
}
Os::ValidateFile::Status ValidatedFile ::
createHashFile()
{
const Os::ValidateFile::Status status =
Os::ValidateFile::createValidation(
this->m_fileName.toChar(),
this->m_hashFileName.toChar(),
this->m_hashBuffer
);
return status;
}
const Fw::StringBase& ValidatedFile ::
getFileName() const
{
return this->m_fileName;
}
const Fw::StringBase& ValidatedFile ::
getHashFileName() const
{
return this->m_hashFileName;
}
const Utils::HashBuffer& ValidatedFile ::
getHashBuffer() const
{
return this->m_hashBuffer;
}
}
| cpp |
fprime | data/projects/fprime/Os/Directory.hpp | #ifndef _Directory_hpp_
#define _Directory_hpp_
#include <FpConfig.hpp>
namespace Os {
// This class encapsulates a very simple directory interface that has the most often-used features
class Directory {
public:
typedef enum {
OP_OK, //!< Operation was successful
DOESNT_EXIST, //!< Directory doesn't exist
NO_PERMISSION, //!< No permission to read directory
NOT_OPENED, //!< Directory hasn't been opened yet
NOT_DIR, //!< Path is not a directory
NO_MORE_FILES, //!< Directory stream has no more files
OTHER_ERROR, //!< A catch-all for other errors. Have to look in implementation-specific code
} Status;
Directory(); //!< Constructor
virtual ~Directory(); //!< Destructor. Will close directory if still open
Status open(const char* dirName); //!< open directory. Directory must already exist
bool isOpen(); //!< check if file descriptor is open or not.
Status rewind(); //!< rewind directory stream to the beginning
Status read(char * fileNameBuffer, U32 bufSize); //!< get next filename from directory
Status read(char * fileNameBuffer, U32 bufSize, I64& inode); //!< get next filename and inode from directory
void close(); //!< close directory
NATIVE_INT_TYPE getLastError(); //!< read back last error code (typically errno)
const char* getLastErrorString(); //!< get a string of the last error (typically from strerror)
private:
POINTER_CAST m_dir; //!< Stored directory pointer (type varies across implementations)
NATIVE_INT_TYPE m_lastError; //!< stores last error
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/TaskCommon.cpp | #include <Os/Task.hpp>
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
namespace Os {
const Task::ParamType Task::TASK_DEFAULT = std::numeric_limits<Task::ParamType>::max();
TaskRegistry* Task::s_taskRegistry = nullptr;
NATIVE_INT_TYPE Task::s_numTasks = 0;
NATIVE_INT_TYPE Task::getNumTasks() {
return Task::s_numTasks;
}
I32 Task::getIdentifier() {
return m_identifier;
}
bool Task::isStarted() {
return this->m_started;
}
void Task::setStarted(bool started) {
this->m_started = started;
}
bool Task::wasSuspended() {
return this->m_suspendedOnPurpose;
}
POINTER_CAST Task::getRawHandle() {
return this->m_handle;
}
void Task::registerTaskRegistry(TaskRegistry* registry) {
FW_ASSERT(registry);
Task::s_taskRegistry = registry;
}
TaskRegistry::TaskRegistry() {
}
TaskRegistry::~TaskRegistry() {
}
}
| cpp |
fprime | data/projects/fprime/Os/Task.hpp | #ifndef _Task_hpp_
#define _Task_hpp_
#include <FpConfig.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Os/TaskString.hpp>
#include <Fw/Deprecate.hpp>
#include <Os/TaskId.hpp>
#include <limits>
namespace Os {
class TaskRegistry; //!< forward declaration
class Task {
public:
using ParamType = NATIVE_UINT_TYPE;
static const ParamType TASK_DEFAULT;
typedef enum {
TASK_OK, //!< message sent/received okay
TASK_INVALID_PARAMS, //!< started task with invalid parameters
TASK_INVALID_STACK, //!< started with invalid stack size
TASK_UNKNOWN_ERROR, //!< unexpected error return value
TASK_INVALID_AFFINITY, //!< unable to set the task affinity
TASK_DELAY_ERROR, //!< error trying to delay the task
TASK_JOIN_ERROR, //!< error trying to join the task
TASK_ERROR_RESOURCES, //!< unable to allocate more tasks
TASK_ERROR_PERMISSION, //!< permissions error setting-up tasks
} TaskStatus;
typedef void (*taskRoutine)(void* ptr); //!< prototype for task routine started in task context
struct TaskRoutineWrapper {
taskRoutine routine; //!< contains the task entrypoint
void* arg; //!< contains the task entrypoint pointer
};
Task(); //!< constructor
virtual ~Task(); //!< destructor
TaskStatus start(const Fw::StringBase& name,
taskRoutine routine,
void* arg,
ParamType priority = TASK_DEFAULT,
ParamType stackSize = TASK_DEFAULT,
ParamType cpuAffinity = TASK_DEFAULT,
ParamType identifier = TASK_DEFAULT); //!< start the task
I32 getIdentifier(); //!< get the identifier for the task
static TaskId getOsIdentifier(); // Gets the Os Task ID. Useful for passive components.
static TaskStatus delay(ParamType msecs); //!< delay the task
static NATIVE_INT_TYPE getNumTasks();
TaskStatus join(void** value_ptr); //!< Wait for task to finish
void suspend(bool onPurpose = false); //!< suspend task
void resume(); //!< resume execution of task
bool wasSuspended(); //!< returns whether or not task was suspended on purpose
bool isSuspended(); //!< check with OS to see if it is suspended already
bool isStarted(); //!< check to see if task is started
void setStarted(bool started); //!< set task to started when thread is fully up. Avoids a VxWorks race condition.
/**
* Returns the task-handle owned by this task
*/
POINTER_CAST getRawHandle();
static void registerTaskRegistry(TaskRegistry* registry);
private:
POINTER_CAST m_handle; //!< handle for implementation specific task
NATIVE_INT_TYPE m_identifier; //!< thread independent identifier
TaskString m_name; //!< object name
NATIVE_INT_TYPE m_affinity; //!< CPU affinity for SMP targets
void toString(char* buf, NATIVE_INT_TYPE buffSize); //!< print a string of the state of the task
bool m_started; //!< set when task has reached entry point
bool m_suspendedOnPurpose; //!< set when task was suspended in purpose (i.e. simulation)
TaskRoutineWrapper m_routineWrapper; //! Contains task entrypoint and argument for task wrapper
static TaskRegistry* s_taskRegistry; //!< pointer to registered task
static NATIVE_INT_TYPE s_numTasks; //!< stores the number of tasks created.
};
class TaskRegistry {
public:
TaskRegistry(); //!< constructor for task registry
virtual ~TaskRegistry(); //!< destructor for task registry
virtual void addTask(Task* task) = 0; //!< Add a task to the registry
virtual void removeTask(Task* task) = 0; //!< remove a task from the registry
};
} // namespace Os
#endif
| hpp |
fprime | data/projects/fprime/Os/TaskLock.hpp | // File: TaskLock.hpp
// Author: Nathan Serafin (nathan.serafin@jpl.nasa.gov)
// Date: 25 June, 2018
//
// OS-independent wrapper to lock out task switching.
#ifndef _TaskLock_hpp_
#define _TaskLock_hpp_
#include <FpConfig.hpp>
namespace Os {
class TaskLock {
public:
static I32 lock(); //!< Lock task switching
static I32 unLock(); //!< Unlock task switching
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/Queue.hpp | /**
* Queue.hpp:
*
* Queues are used internally to F prime in order to support the messaging between components. The
* Queue class is used to abstract away from the standard OS-based queue, allowing F prime support
* multiple OSes in a consistent way.
*
* Like most items in the OS package, the implementation is done in two parts. One part is the file
* `QueueCommon.cpp`. It contains the shared code for queues regardless of the OS. The other is a
* .cpp file containing the OS specific backends for defined functions. (i.e. Posix/Queue.cpp).
*/
#ifndef _Queue_hpp_
#define _Queue_hpp_
#include <FpConfig.hpp>
#include <Fw/Obj/ObjBase.hpp>
#include <Fw/Types/Serializable.hpp>
#include <Os/QueueString.hpp>
namespace Os {
// forward declaration for registry
class QueueRegistry;
class Queue {
public:
enum QueueStatus {
QUEUE_OK, //!< message sent/received okay
QUEUE_NO_MORE_MSGS, //!< If non-blocking, all the messages have been drained.
QUEUE_UNINITIALIZED, //!< Queue wasn't initialized successfully
QUEUE_SIZE_MISMATCH, //!< attempted to send or receive with buffer too large, too small
QUEUE_SEND_ERROR, //!< message send error
QUEUE_RECEIVE_ERROR, //!< message receive error
QUEUE_INVALID_PRIORITY, //!< invalid priority requested
QUEUE_EMPTY_BUFFER, //!< supplied buffer is empty
QUEUE_FULL, //!< queue was full when attempting to send a message
QUEUE_UNKNOWN_ERROR //!< Unexpected error; can't match with returns
};
enum QueueBlocking {
QUEUE_BLOCKING, //!< Queue receive blocks until a message arrives
QUEUE_NONBLOCKING //!< Queue receive always returns even if there is no message
};
Queue();
virtual ~Queue();
QueueStatus create(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize); //!< create a message queue
// Send serialized buffers
QueueStatus send(const Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE priority, QueueBlocking block); //!< send a message
QueueStatus receive(Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE &priority, QueueBlocking block); //!< receive a message
// Send raw buffers
QueueStatus send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block); //!< send a message
QueueStatus receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block); //!< receive a message
NATIVE_INT_TYPE getNumMsgs() const; //!< get the number of messages in the queue
NATIVE_INT_TYPE getMaxMsgs() const; //!< get the maximum number of messages (high watermark)
NATIVE_INT_TYPE getQueueSize() const; //!< get the queue depth (maximum number of messages queue can hold)
NATIVE_INT_TYPE getMsgSize() const; //!< get the message size (maximum message size queue can hold)
const QueueString& getName(); //!< get the queue name
static NATIVE_INT_TYPE getNumQueues(); //!< get the number of queues in the system
#if FW_QUEUE_REGISTRATION
static void setQueueRegistry(QueueRegistry* reg); // !< set the queue registry
#endif
protected:
//! Internal method used for creating allowing alternate implementations to implement different creation
//! behavior without needing to duplicate the majority of the creation functionality.
//! \param name: name of queue
//! \param depth: depth of queue
//! \param msgSize: size of a message stored on queue
//! \return queue creation status
QueueStatus createInternal(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize); //!< create a message queue
POINTER_CAST m_handle; //!< handle for implementation specific queue
QueueString m_name; //!< queue name
#if FW_QUEUE_REGISTRATION
static QueueRegistry* s_queueRegistry; //!< pointer to registry
#endif
static NATIVE_INT_TYPE s_numQueues; //!< tracks number of queues in the system
private:
Queue(Queue&); //!< Disabled copy constructor
Queue(Queue*); //!< Disabled copy constructor
};
class QueueRegistry {
public:
virtual void regQueue(Queue* obj)=0; //!< method called by queue init() methods to register a new queue
virtual ~QueueRegistry() {}; //!< virtual destructor for registry object
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/QueueString.cpp | #include <Os/QueueString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Os {
QueueString::QueueString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
QueueString::QueueString(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
QueueString::QueueString(const QueueString& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
QueueString::QueueString() : StringBase() {
this->m_buf[0] = 0;
}
QueueString& QueueString::operator=(const QueueString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
QueueString& QueueString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
QueueString& QueueString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
QueueString::~QueueString() {
}
const char* QueueString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE QueueString::getCapacity() const {
return FW_QUEUE_NAME_MAX_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Os/IPCQueue.hpp | #ifndef _IPCQueue_hpp_
#define _IPCQueue_hpp_
#include <Os/Queue.hpp>
namespace Os {
class IPCQueue : public Os::Queue {
public:
IPCQueue();
~IPCQueue();
QueueStatus create(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize); //!< create a message queue
// Base class has overloads - NOTE(mereweth) - this didn't work
//using Queue::send;
//using Queue::receive;
// Send serialized buffers
QueueStatus send(const Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE priority, QueueBlocking block); //!< send a message
QueueStatus receive(Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE &priority, QueueBlocking block); //!< receive a message
// Send raw buffers
QueueStatus send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block); //!< send a message
QueueStatus receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block); //!< receive a message
NATIVE_INT_TYPE getNumMsgs() const; //!< get the number of messages in the queue
NATIVE_INT_TYPE getMaxMsgs() const; //!< get the maximum number of messages (high watermark)
NATIVE_INT_TYPE getQueueSize() const; //!< get the queue depth (maximum number of messages queue can hold)
NATIVE_INT_TYPE getMsgSize() const; //!< get the message size (maximum message size queue can hold)
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/LogDefault.cpp | /**
* LogDefault.cpp:
*
* This file ensures that the Os::Log has a default instance. This means it will be created in static space here, and
* registered as the default implementation. If the user does not intend to use the default implementation of Os::Log,
* then this file can safely be ignored.
*/
#include <Os/Log.hpp>
Os::Log __default_logger__; // Create a default instance which will register itself in the constructor
| cpp |
fprime | data/projects/fprime/Os/File.hpp | // ======================================================================
// \title Os/File.hpp
// \brief common function definitions for Os::File
// ======================================================================
#ifndef Os_File_hpp_
#define Os_File_hpp_
#include <FpConfig.hpp>
namespace Os {
//! \brief base implementation of FileHandle
//!
struct FileHandle {};
// This class encapsulates a very simple file interface that has the most often-used features
class FileInterface {
public:
enum Mode {
OPEN_NO_MODE, //!< File mode not yet selected
OPEN_READ, //!< Open file for reading
OPEN_CREATE, //!< Open file for writing and truncates file if it exists, ie same flags as creat()
OPEN_WRITE, //!< Open file for writing
OPEN_SYNC_WRITE, //!< Open file for writing; writes don't return until data is on disk
OPEN_APPEND, //!< Open file for appending
MAX_OPEN_MODE //!< Maximum value of mode
};
enum Status {
OP_OK, //!< Operation was successful
DOESNT_EXIST, //!< File doesn't exist (for read)
NO_SPACE, //!< No space left
NO_PERMISSION, //!< No permission to read/write file
BAD_SIZE, //!< Invalid size parameter
NOT_OPENED, //!< file hasn't been opened yet
FILE_EXISTS, //!< file already exist (for CREATE with O_EXCL enabled)
NOT_SUPPORTED, //!< Kernel or file system does not support operation
INVALID_MODE, //!< Mode for file access is invalid for current operation
INVALID_ARGUMENT, //!< Invalid argument passed in
OTHER_ERROR, //!< A catch-all for other errors. Have to look in implementation-specific code
MAX_STATUS //!< Maximum value of status
};
enum OverwriteType {
NO_OVERWRITE, //!< Do NOT overwrite existing files
OVERWRITE, //!< Overwrite file when it exists and creation was requested
MAX_OVERWRITE_TYPE
};
enum SeekType {
RELATIVE, //!< Relative seek from current file offset
ABSOLUTE, //!< Absolute seek from beginning of file
MAX_SEEK_TYPE
};
enum WaitType {
NO_WAIT, //!< Do not wait for read/write operation to finish
WAIT, //!< Do wait for read/write operation to finish
MAX_WAIT_TYPE
};
virtual ~FileInterface() = default;
//! \brief open file with supplied path and mode
//!
//! Open the file passed in with the given mode. If overwrite is set to OVERWRITE, then opening files in
//! OPEN_CREATE mode will clobber existing files. Set overwrite to NO_OVERWRITE to preserve existing files.
//! The status of the open request is returned from the function call. Delegates to the chosen
//! implementation's `open` function.
//!
//! It is invalid to send `nullptr` as the path.
//! It is invalid to supply `mode` as a non-enumerated value.
//! It is invalid to supply `overwrite` as a non-enumerated value.
//!
//! \param path: c-string of path to open
//! \param mode: file operation mode
//! \param overwrite: overwrite existing file on create
//! \return: status of the open
//!
virtual Status open(const char* path, Mode mode, OverwriteType overwrite) = 0;
//! \brief close the file, if not opened then do nothing
//!
//! Closes the file, if open. Otherwise this function does nothing. Delegates to the chosen implementation's
//! `closeInternal` function. `mode` is set to `OPEN_NO_MODE`.
//!
virtual void close() = 0;
//! \brief get size of currently open file
//!
//! Get the size of the currently open file and fill the size parameter. Return status of the operation.
//! \param size: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
virtual Status size(FwSignedSizeType& size_result) = 0;
//! \brief get file pointer position of the currently open file
//!
//! Get the current position of the read/write pointer of the open file.
//! \param position: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
virtual Status position(FwSignedSizeType& position_result) = 0;
//! \brief pre-allocate file storage
//!
//! Pre-allocates file storage with at least `length` storage starting at `offset`. No-op on implementations
//! that cannot pre-allocate.
//!
//! It is invalid to pass a negative `offset`.
//! It is invalid to pass a negative `length`.
//!
//! \param offset: offset into file
//! \param length: length after offset to preallocate
//! \return OP_OK on success otherwise error status
//!
virtual Status preallocate(FwSignedSizeType offset, FwSignedSizeType length) = 0;
//! \brief seek the file pointer to the given offset
//!
//! Seek the file pointer to the given `offset`. If `seekType` is set to `ABSOLUTE` then the offset is calculated
//! from the start of the file, and if it is set to `CURRENT` it is calculated from the current position.
//!
//! \param offset: offset to seek to
//! \param seekType: `ABSOLUTE` for seeking from beginning of file, `CURRENT` to use current position.
//! \return OP_OK on success otherwise error status
//!
virtual Status seek(FwSignedSizeType offset, SeekType seekType) = 0;
//! \brief flush file contents to storage
//!
//! Flushes the file contents to storage (i.e. out of the OS cache to disk). Does nothing in implementations
//! that do not support flushing.
//!
//! \return OP_OK on success otherwise error status
//!
virtual Status flush() = 0;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Read data from this file up to the `size` and store it in `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been read successfully read or the end of the file has been
//! reached. When `wait` is set to `NO_WAIT` it will return whatever data is currently available.
//!
//! `size` will be updated to the count of bytes actually read. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
virtual Status read(U8* buffer, FwSignedSizeType &size, WaitType wait) = 0;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Write data to this file up to the `size` from the `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been written successfully to disk. When `wait` is set to
//! `NO_WAIT` it will return once the data is sent to the OS.
//!
//! `size` will be updated to the count of bytes actually written. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data to write to disk, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
virtual Status write(const U8* buffer, FwSignedSizeType &size, WaitType wait) = 0;
//! \brief returns the raw file handle
//!
//! Gets the raw file handle from the implementation. Note: users must include the implementation specific
//! header to make any real use of this handle. Otherwise it//!must* be passed as an opaque type.
//!
//! \return raw file handle
//!
virtual FileHandle* getHandle() = 0;
//! \brief provide a pointer to a file delegate object
//!
//! This function must return a pointer to a `FileInterface` object that contains the real implementation of the file
//! functions as defined by the implementor. This function must do several things to be considered correctly
//! implemented:
//!
//! 1. Assert that the supplied memory is non-null. e.g `FW_ASSERT(aligned_placement_new_memory != NULL);`
//! 2. Assert that their implementation fits within FW_HANDLE_MAX_SIZE.
//! e.g. `static_assert(sizeof(PosixFileImplementation) <= sizeof Os::File::m_handle_storage,
//! "FW_HANDLE_MAX_SIZE too small");`
//! 3. Assert that their implementation aligns within FW_HANDLE_ALIGNMENT.
//! e.g. `static_assert((FW_HANDLE_ALIGNMENT % alignof(PosixFileImplementation)) == 0, "Bad handle alignment");`
//! 4. If to_copy is null, placement new their implementation into `aligned_placement_new_memory`
//! e.g. `FileInterface* interface = new (aligned_placement_new_memory) PosixFileImplementation;`
//! 5. If to_copy is non-null, placement new using copy constructor their implementation into
//! `aligned_placement_new_memory`
//! e.g. `FileInterface* interface = new (aligned_placement_new_memory) PosixFileImplementation(*to_copy);`
//! 6. Return the result of the placement new
//! e.g. `return interface;`
//!
//! \return result of placement new, must be equivalent to `aligned_placement_new_memory`
//!
static FileInterface* getDelegate(U8* aligned_placement_new_memory, const FileInterface* to_copy=nullptr);
};
class File final : public FileInterface {
public:
// Required for access to m_handle_storage for static assertions against actual storage
friend FileInterface* FileInterface::getDelegate(U8*, const FileInterface*);
//! \brief constructor
//!
File();
//! \brief destructor
//!
~File() final;
//! \brief copy constructor that copies the internal representation
File(const File& other);
//! \brief assignment operator that copies the internal representation
File& operator=(const File& other);
//! \brief determine if the file is open
//! \return true if file is open, false otherwise
//!
bool isOpen() const;
// ------------------------------------
// Functions supplying default values
// ------------------------------------
//! \brief open file with supplied path and mode
//!
//! Open the file passed in with the given mode. Opening files with `OPEN_CREATE` mode will not clobber existing
//! files. Use other `open` method to set overwrite flag and clobber existing files. The status of the open
//! request is returned from the function call. Delegates to the chosen implementation's `open` function.
//!
//! It is invalid to send `nullptr` as the path.
//! It is invalid to supply `mode` as a non-enumerated value.
//!
//! \param path: c-string of path to open
//! \param mode: file operation mode
//! \return: status of the open
//!
Os::FileInterface::Status open(const char* path, Mode mode);
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Read data from this file up to the `size` and store it in `buffer`. This version will
//! will block until the requested size has been read successfully read or the end of the file has been
//! reached.
//!
//! `size` will be updated to the count of bytes actually read. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \return OP_OK on success otherwise error status
//!
Status read(U8* buffer, FwSignedSizeType &size);
//! \brief write data to this file from the supplied buffer bounded by size
//!
//! Write data from `buffer` up to the `size` and store it in this file. This call
//! will block until the requested size has been written. Otherwise, this call will write without blocking.
//!
//! `size` will be updated to the count of bytes actually written. Status will reflect the success/failure of
//! the write operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//!
//! \param buffer: memory location of data to write to file
//! \param size: size of data to write
//! \return OP_OK on success otherwise error status
//!
Status write(const U8* buffer, FwSignedSizeType &size);
// ------------------------------------
// Functions overrides
// ------------------------------------
//! \brief open file with supplied path and mode
//!
//! Open the file passed in with the given mode. If overwrite is set to OVERWRITE, then opening files in
//! OPEN_CREATE mode will clobber existing files. Set overwrite to NO_OVERWRITE to preserve existing files.
//! The status of the open request is returned from the function call. Delegates to the chosen
//! implementation's `open` function.
//!
//! It is invalid to send `nullptr` as the path.
//! It is invalid to supply `mode` as a non-enumerated value.
//! It is invalid to supply `overwrite` as a non-enumerated value.
//!
//! \param path: c-string of path to open
//! \param mode: file operation mode
//! \param overwrite: overwrite existing file on create
//! \return: status of the open
//!
Os::FileInterface::Status open(const char* path, Mode mode, OverwriteType overwrite) override;
//! \brief close the file, if not opened then do nothing
//!
//! Closes the file, if open. Otherwise this function does nothing. Delegates to the chosen implementation's
//! `closeInternal` function. `mode` is set to `OPEN_NO_MODE`.
//!
void close() override;
//! \brief get size of currently open file
//!
//! Get the size of the currently open file and fill the size parameter. Return status of the operation.
//! \param size: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
Status size(FwSignedSizeType& size_result) override;
//! \brief get file pointer position of the currently open file
//!
//! Get the current position of the read/write pointer of the open file.
//! \param position: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
Status position(FwSignedSizeType& position_result) override;
//! \brief pre-allocate file storage
//!
//! Pre-allocates file storage with at least `length` storage starting at `offset`. No-op on implementations
//! that cannot pre-allocate.
//!
//! It is invalid to pass a negative `offset`.
//! It is invalid to pass a negative `length`.
//!
//! \param offset: offset into file
//! \param length: length after offset to preallocate
//! \return OP_OK on success otherwise error status
//!
Status preallocate(FwSignedSizeType offset, FwSignedSizeType length) override;
//! \brief seek the file pointer to the given offset
//!
//! Seek the file pointer to the given `offset`. If `seekType` is set to `ABSOLUTE` then the offset is calculated
//! from the start of the file, and if it is set to `CURRENT` it is calculated from the current position.
//!
//! \param offset: offset to seek to
//! \param seekType: `ABSOLUTE` for seeking from beginning of file, `CURRENT` to use current position.
//! \return OP_OK on success otherwise error status
//!
Status seek(FwSignedSizeType offset, SeekType seekType) override;
//! \brief flush file contents to storage
//!
//! Flushes the file contents to storage (i.e. out of the OS cache to disk). Does nothing in implementations
//! that do not support flushing.
//!
//! \return OP_OK on success otherwise error status
//!
Status flush() override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Read data from this file up to the `size` and store it in `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been read successfully read or the end of the file has been
//! reached. When `wait` is set to `NO_WAIT` it will return whatever data is currently available.
//!
//! `size` will be updated to the count of bytes actually read. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
Status read(U8* buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Write data to this file up to the `size` from the `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been written successfully to disk. When `wait` is set to
//! `NO_WAIT` it will return once the data is sent to the OS.
//!
//! `size` will be updated to the count of bytes actually written. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data to write to disk, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
Status write(const U8* buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief returns the raw file handle
//!
//! Gets the raw file handle from the implementation. Note: users must include the implementation specific
//! header to make any real use of this handle. Otherwise it//!must* be passed as an opaque type.
//!
//! \return raw file handle
//!
FileHandle* getHandle() override;
//! \brief calculate the CRC32 of the entire file
//!
//! Calculates the CRC32 of the file's contents. The `crc` parameter will be updated to contain the CRC or 0 on
//! failure. Status will represent failure conditions. This call will be decomposed into calculations on
//! sections of the file `FW_FILE_CHUNK_SIZE` bytes long.
//!
//! This function requires that the file already be opened for "READ" mode.
//!
//! On error crc will be set to 0.
//!
//! This function is equivalent to the following pseudo-code:
//!
//! ```
//! U32 crc;
//! do {
//! size = FW_FILE_CHUNK_SIZE;
//! m_file.incrementalCrc(size);
//! while (size == FW_FILE_CHUNK_SIZE);
//! m_file.finalize(crc);
//! ```
//! \param crc: U32 bit value to fill with CRC
//! \return OP_OK on success otherwise error status
//!
Status calculateCrc(U32& crc);
//! \brief calculate the CRC32 of the next section of data
//!
//! Starting at the current file pointer, this will add `size` bytes of data to the currently calculated CRC.
//! Call `finalizeCrc` to retrieve the CRC or `calculateCrc` to perform a CRC on the entire file. This call will
//! not block waiting for data on the underlying read, nor will it reset the file position pointer. On error,
//! the current CRC results should be discarded by reopening the file or calling `finalizeCrc` and
//! discarding its result. `size` will be updated with the `size` actually read and used in the CRC calculation.
//!
//! This function requires that the file already be opened for "READ" mode.
//!
//! It is illegal for size to be less than or equal to 0 or greater than FW_FILE_CHUNK_SIZE.
//!
//! \param size: size of data to read for CRC
//! \return: status of the CRC calculation
//!
Status incrementalCrc(FwSignedSizeType& size);
//! \brief finalize and retrieve the CRC value
//!
//! Finalizes the CRC computation and returns the CRC value. The `crc` value will be modified to contain the
//! crc or 0 on error. Note: this will reset any active CRC calculation and effectively re-initializes any
//! `incrementalCrc` calculation.
//!
//! On error crc will be set to 0.
//!
//! \param crc: value to fill
//! \return status of the CRC calculation
//!
Status finalizeCrc(U32& crc);
private:
PRIVATE:
static const U32 INITIAL_CRC = 0xFFFFFFFF; //!< Initial value for CRC calculation
Mode m_mode = Mode::OPEN_NO_MODE; //!< Stores mode for error checking
const CHAR* m_path = nullptr; //!< Path last opened
U32 m_crc = File::INITIAL_CRC; //!< Current CRC calculation
U8 m_crc_buffer[FW_FILE_CHUNK_SIZE];
// This section is used to store the implementation-defined file handle. To Os::File and fprime, this type is
// opaque and thus normal allocation cannot be done. Instead, we allow the implementor to store then handle in
// the byte-array here and set `handle` to that address for storage.
//
alignas(FW_HANDLE_ALIGNMENT) U8 m_handle_storage[FW_HANDLE_MAX_SIZE]; //!< Storage for aligned FileHandle data
FileInterface& m_delegate; //!< Delegate for the real implementation
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/SystemResources.hpp | // ======================================================================
// \title SystemResources.hpp
// \author mstarch
// \brief hpp file for SystemResources component implementation class
//
// \copyright
// Copyright 2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef _SystemResources_hpp_
#define _SystemResources_hpp_
#include <FpConfig.hpp>
namespace Os {
namespace SystemResources {
enum SystemResourcesStatus {
SYSTEM_RESOURCES_OK, //!< Call was successful
SYSTEM_RESOURCES_ERROR, //!< Call failed
};
struct CpuTicks {
FwSizeType used; //!< Filled with non-idle (system, user) CPU ticks
FwSizeType total; //!< Filled with total CPU ticks
};
struct MemUtil {
FwSizeType used; //!< Filled with used bytes of volatile memory (permanent, paged-in)
FwSizeType total; //!< Filled with total non-volatile memory
};
/**
* \brief Request the count of the CPUs detected by the system
*
* \param cpu_count: (output) filled with CPU count on system
* \return: SYSTEM_RESOURCES_OK with valid CPU count, SYSTEM_RESOURCES_ERROR when error occurs
*/
SystemResourcesStatus getCpuCount(U32& cpu_count);
/**
* \brief Get the CPU tick information for a given CPU
*
* CPU ticks represent a small time slice of processor time. This will retrieve the used CPU ticks and total
* ticks for a given CPU. This information in a running accumulation and thus a sample-to-sample
* differencing is needed to see the 'realtime' changing load. This shall be done by the caller.
*
* \param ticks: (output) filled with the tick information for the given CPU
* \param cpu_index: index for CPU to read
* \return: SYSTEM_RESOURCES_ERROR when error occurs, SYSTEM_RESOURCES_OK otherwise.
*/
SystemResourcesStatus getCpuTicks(CpuTicks& ticks, U32 cpu_index = 0);
/**
* \brief Get system memory usage
*
* \param memory_util: (output) data structure used to store memory usage
* \return: SYSTEM_RESOURCES_ERROR when error occurs, SYSTEM_RESOURCES_OK otherwise.
*/
SystemResourcesStatus getMemUtil(MemUtil& memory_util);
} // namespace SystemResources
} // namespace Os
#endif
| hpp |
fprime | data/projects/fprime/Os/ValidateFileCommon.cpp | #include <Os/ValidateFile.hpp>
#include <Os/File.hpp>
#include <Utils/Hash/Hash.hpp>
#include <Os/FileSystem.hpp>
namespace Os {
File::Status computeHash(const char* fileName, Utils::HashBuffer &hashBuffer) {
File::Status status;
// Open file:
File file;
status = file.open(fileName, File::OPEN_READ);
if( File::OP_OK != status ) {
return status;
}
// Get the file size:
FileSystem::Status fs_status;
FwSignedSizeType fileSize = 0;
fs_status = FileSystem::getFileSize(fileName, fileSize); //!< gets the size of the file (in bytes) at location path
// fileSize will be used as a NATIVE_INT_TYPE below and thus must cast cleanly to that type
if( FileSystem::OP_OK != fs_status) {
return File::BAD_SIZE;
}
const NATIVE_INT_TYPE max_itr = static_cast<NATIVE_INT_TYPE>(fileSize/VFILE_HASH_CHUNK_SIZE + 1);
// Read all data from file and update hash:
Utils::Hash hash;
hash.init();
U8 buffer[VFILE_HASH_CHUNK_SIZE];
FwSignedSizeType size = 0;
FwSignedSizeType cnt = 0;
while( cnt <= max_itr ) {
// Read out chunk from file:
size = sizeof(buffer);
status = file.read(buffer, size, Os::File::WaitType::NO_WAIT);
if( File::OP_OK != status ) {
return status;
}
// If end of file, break:
if( size == 0 ) {
break;
}
// Add chunk to hash calculation:
hash.update(&buffer, size);
cnt++;
}
file.close();
// We should not have left the loop because of cnt > max_itr:
FW_ASSERT(size == 0);
FW_ASSERT(cnt <= max_itr);
// Calculate hash:
Utils::HashBuffer computedHashBuffer;
hash.final(computedHashBuffer);
hashBuffer = computedHashBuffer;
return status;
}
File::Status readHash(const char* hashFileName, Utils::HashBuffer &hashBuffer) {
File::Status status;
// Open hash file:
File hashFile;
status = hashFile.open(hashFileName, File::OPEN_READ);
if( File::OP_OK != status ) {
return status;
}
// Read hash from checksum file:
unsigned char savedHash[HASH_DIGEST_LENGTH];
FwSignedSizeType size = hashBuffer.getBuffCapacity();
status = hashFile.read(savedHash, size);
if( File::OP_OK != status ) {
return status;
}
if( size != static_cast<NATIVE_INT_TYPE>(hashBuffer.getBuffCapacity()) ) {
return File::BAD_SIZE;
}
hashFile.close();
// Return the hash buffer:
Utils::HashBuffer savedHashBuffer(savedHash, size);
hashBuffer = savedHashBuffer;
return status;
}
File::Status writeHash(const char* hashFileName, Utils::HashBuffer hashBuffer) {
// Open hash file:
File hashFile;
File::Status status;
status = hashFile.open(hashFileName, File::OPEN_WRITE);
if( File::OP_OK != status ) {
return status;
}
// Write out the hash
FwSignedSizeType size = hashBuffer.getBuffLength();
status = hashFile.write(hashBuffer.getBuffAddr(), size, Os::File::WaitType::NO_WAIT);
if( File::OP_OK != status ) {
return status;
}
if( size != static_cast<NATIVE_INT_TYPE>(hashBuffer.getBuffLength()) ) {
return File::BAD_SIZE;
}
hashFile.close();
return status;
}
// Enum and function for translating from a status to a validation status:
typedef enum {
FileType,
HashFileType
} StatusFileType;
ValidateFile::Status translateStatus(File::Status status, StatusFileType type) {
switch (type) {
case FileType:
switch (status) {
case File::OP_OK:
return ValidateFile::VALIDATION_OK;
case File::DOESNT_EXIST:
return ValidateFile::FILE_DOESNT_EXIST;
case File::NO_SPACE:
return ValidateFile::NO_SPACE;
case File::NO_PERMISSION:
return ValidateFile::FILE_NO_PERMISSION;
case File::BAD_SIZE:
return ValidateFile::FILE_BAD_SIZE;
case File::NOT_OPENED:
return ValidateFile::OTHER_ERROR;
case File::OTHER_ERROR:
return ValidateFile::OTHER_ERROR;
default:
FW_ASSERT(0, status);
}
break;
case HashFileType:
switch (status) {
case File::OP_OK:
return ValidateFile::VALIDATION_OK;
case File::DOESNT_EXIST:
return ValidateFile::VALIDATION_FILE_DOESNT_EXIST;
case File::NO_SPACE:
return ValidateFile::NO_SPACE;
case File::NO_PERMISSION:
return ValidateFile::VALIDATION_FILE_NO_PERMISSION;
case File::BAD_SIZE:
return ValidateFile::VALIDATION_FILE_BAD_SIZE;
case File::NOT_OPENED:
return ValidateFile::OTHER_ERROR;
case File::OTHER_ERROR:
return ValidateFile::OTHER_ERROR;
default:
FW_ASSERT(0, status);
}
break;
default:
FW_ASSERT(0, type);
}
return ValidateFile::OTHER_ERROR;
}
ValidateFile::Status ValidateFile::validate(const char* fileName, const char* hashFileName) {
Utils::HashBuffer hashBuffer; // pass by reference - final value is unused
return validate(fileName, hashFileName, hashBuffer);
}
ValidateFile::Status ValidateFile::validate(const char* fileName, const char* hashFileName, Utils::HashBuffer &hashBuffer) {
File::Status status;
// Read the hash file:
Utils::HashBuffer savedHash;
status = readHash(hashFileName, savedHash);
if( File::OP_OK != status ) {
return translateStatus(status, HashFileType);
}
// Compute the file's hash:
Utils::HashBuffer computedHash;
status = computeHash(fileName, computedHash);
if( File::OP_OK != status ) {
return translateStatus(status, FileType);
}
// Compare hashes and return:
if( savedHash != computedHash ){
return ValidateFile::VALIDATION_FAIL;
}
hashBuffer = savedHash;
return ValidateFile::VALIDATION_OK;
}
ValidateFile::Status ValidateFile::createValidation(const char* fileName, const char* hashFileName, Utils::HashBuffer &hashBuffer) {
File::Status status;
// Compute the file's hash:
status = computeHash(fileName, hashBuffer);
if( File::OP_OK != status ) {
return translateStatus(status, FileType);
}
status = writeHash(hashFileName, hashBuffer);
if( File::OP_OK != status ) {
return translateStatus(status, HashFileType);
}
return ValidateFile::VALIDATION_OK;
}
ValidateFile::Status ValidateFile::createValidation(const char* fileName, const char* hashFileName) {
Utils::HashBuffer hashBuffer; // pass by reference - final value is unused
return createValidation(fileName, hashFileName, hashBuffer);
}
}
| cpp |
fprime | data/projects/fprime/Os/IntervalTimerCommon.cpp | /**
* IntervalTimerCommon.cpp:
*
* Contains the common functions for interval timer. This set of functions makes no assumption on
* the format of the RawTime objects and thus it operates through functions that abstract that
* implementation away, or it is working on the raw values, as raw values.
*
* *Note:* If the RawTime object is using U32 upper to store seconds and U32 lower to store nano
* seconds, then X86/IntervalTimer.cpp can be used, and the implementer need only fill in the
* getRawTime function for the specific OS.
*/
#include <Os/IntervalTimer.hpp>
#include <cstring>
namespace Os {
IntervalTimer::IntervalTimer() {
memset(&this->m_startTime,0,sizeof(this->m_startTime));
memset(&this->m_stopTime,0,sizeof(this->m_stopTime));
}
IntervalTimer::~IntervalTimer() {}
void IntervalTimer::start() {
getRawTime(this->m_startTime);
}
void IntervalTimer::stop() {
getRawTime(this->m_stopTime);
}
U32 IntervalTimer::getDiffUsec() {
return getDiffUsec(this->m_stopTime, this->m_startTime);
}
}
| cpp |
fprime | data/projects/fprime/Os/TaskId.hpp | // File: TaskId.hpp
// Author: Ben Soudry (benjamin.s.soudry@jpl.nasa.gov)
// Nathan Serafin (nathan.serafin@jpl.nasa.gov)
// Date: 29 June, 2018
//
// Define a type for task IDs. This is useful as POSIX only
// provides an opaque TID with a special pthread_equal() comparison
// function. For higher-level code to not need to be aware of
// POSIX versus VxWorks versus whatever else, we can overload the
// == operator to perform the correct equality check.
#ifndef _TaskId_hpp_
#define _TaskId_hpp_
#include <Os/TaskIdRepr.hpp>
namespace Os {
class TaskId {
public:
TaskId();
~TaskId();
bool operator==(const TaskId& T) const;
bool operator!=(const TaskId& T) const;
TaskIdRepr getRepr() const;
private:
TaskIdRepr id;
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/LogPrintf.cpp | /**
* File: Os/LogPrintf.cpp
* Description: an implementation on the Os::Log abstraction that routes log messages into standard
* printf calls.
*/
#include <Os/Log.hpp>
#include <cstdio>
namespace Os {
Log::Log() {
// Register myself as a logger at construction time. If used in unison with LogDefault.cpp, this will
// automatically create this as a default logger.
this->registerLogger(this);
}
// Instance implementation
void Log::log(
const char* fmt,
POINTER_CAST a0,
POINTER_CAST a1,
POINTER_CAST a2,
POINTER_CAST a3,
POINTER_CAST a4,
POINTER_CAST a5,
POINTER_CAST a6,
POINTER_CAST a7,
POINTER_CAST a8,
POINTER_CAST a9
) {
(void) printf(fmt, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
(void) fflush(stdout);
}
}
| cpp |
fprime | data/projects/fprime/Os/Mutex.hpp | #ifndef _Mutex_hpp_
#define _Mutex_hpp_
#include <FpConfig.hpp>
namespace Os {
class Mutex {
public:
Mutex(); //!< Constructor. Mutex is unlocked when created
virtual ~Mutex(); //!< Destructor
void lock(); //!< lock the mutex
void unLock(); //!< unlock the mutex
void unlock() { this->unLock(); } //!< alias for unLock to meet BasicLockable requirements
private:
POINTER_CAST m_handle; //!< Stored handle to mutex
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/QueueString.hpp | #ifndef OS_QUEUE_STRING_TYPE_HPP
#define OS_QUEUE_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
namespace Os {
class QueueString : public Fw::StringBase {
public:
QueueString(const char* src); //!< char buffer constructor
QueueString(const StringBase& src); //!< copy constructor
QueueString(const QueueString& src); //!< copy constructor
QueueString(); //!< default constructor
QueueString& operator=(const QueueString& other); //!< assignment operator
QueueString& operator=(const StringBase& other); //!< other string assignment operator
QueueString& operator=(const char* other); //!< char* assignment operator
~QueueString(); //!< destructor
const char* toChar() const; //!< get pointer to char buffer
NATIVE_UINT_TYPE getCapacity() const ;
private:
char m_buf[FW_QUEUE_NAME_MAX_SIZE]; //!< buffer for string
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/TaskString.cpp | #include <Os/TaskString.hpp>
#include <Fw/Types/StringUtils.hpp>
namespace Os {
TaskString::TaskString(const char* src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src, sizeof(this->m_buf));
}
TaskString::TaskString(const StringBase& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
TaskString::TaskString(const TaskString& src) : StringBase() {
(void) Fw::StringUtils::string_copy(this->m_buf, src.toChar(), sizeof(this->m_buf));
}
TaskString::TaskString() {
this->m_buf[0] = 0;
}
TaskString& TaskString::operator=(const TaskString& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
TaskString& TaskString::operator=(const StringBase& other) {
if(this == &other) {
return *this;
}
(void) Fw::StringUtils::string_copy(this->m_buf, other.toChar(), sizeof(this->m_buf));
return *this;
}
TaskString& TaskString::operator=(const char* other) {
(void) Fw::StringUtils::string_copy(this->m_buf, other, sizeof(this->m_buf));
return *this;
}
TaskString::~TaskString() {
}
const char* TaskString::toChar() const {
return this->m_buf;
}
NATIVE_UINT_TYPE TaskString::getCapacity() const {
return FW_TASK_NAME_MAX_SIZE;
}
}
| cpp |
fprime | data/projects/fprime/Os/LocklessQueue.hpp | #ifndef _LOCKLESS_QUEUE_H_
#define _LOCKLESS_QUEUE_H_
#include <FpConfig.hpp>
#include <Os/Queue.hpp>
#ifndef BUILD_DARWIN // Allow compiling
#include <mqueue.h>
#endif
namespace Os {
class LocklessQueue {
typedef struct QueueNode_s {
U8 * data;
NATIVE_INT_TYPE size;
struct QueueNode_s * next;
} QueueNode;
public:
LocklessQueue (NATIVE_INT_TYPE maxmsg, NATIVE_INT_TYPE msgsize);
~LocklessQueue();
#ifndef BUILD_DARWIN // Allow compiling
void GetAttr (mq_attr & attr);
#endif
Os::Queue::QueueStatus Send (const U8 * buffer, NATIVE_INT_TYPE size);
Os::Queue::QueueStatus Receive (U8 * buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE & size);
private:
bool PopFree (QueueNode ** free_node);
void PushFree (QueueNode * my_node);
QueueNode * m_first;
QueueNode * m_last;
QueueNode * m_free_head;
QueueNode * m_index;
U8 * m_data;
#ifndef BUILD_DARWIN
mq_attr m_attr;
#endif
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/WatchdogTimer.hpp | #ifndef _WatchdogTimer_hpp_
#define _WatchdogTimer_hpp_
#include <FpConfig.hpp>
namespace Os {
class WatchdogTimer {
public:
typedef enum {
WATCHDOG_OK, //!< Call was successful
WATCHDOG_INIT_ERROR, //!< Timer initialization failed
WATCHDOG_START_ERROR, //!< Timer startup failed
WATCHDOG_CANCEL_ERROR //!< Timer cancellation failed
} WatchdogStatus;
typedef void (*WatchdogCb)(void *);
WatchdogTimer();
virtual ~WatchdogTimer();
WatchdogStatus startTicks( I32 delayInTicks, //!< number of ticks to delay. OS/timing dependent
WatchdogCb p_callback, //!< routine to call on time-out
void* parameter //!< parameter with which to call routine
);
WatchdogStatus startMs( I32 delayInMs, //!< number of ms to delay.
WatchdogCb p_callback, //!< routine to call on time-out
void* parameter //!< parameter with which to call routine
);
WatchdogStatus restart(); //!< restart timer with previous value
WatchdogStatus cancel(); //!< cancel timer
void expire(); //!< Invoke the callback function with m_parameter
private:
I32 m_handle; //!< handle for implementation specific watchdog
WatchdogCb m_cb; //!< function callback pointer
void* m_parameter; //!< parameter for timer call
I32 m_timerTicks; //!< number of ticks for timer.
I32 m_timerMs; //!< number of milliseconds for timer.
WatchdogTimer(WatchdogTimer&); //!< disable copy constructor
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/TaskString.hpp | #ifndef OS_TASK_STRING_TYPE_HPP
#define OS_TASK_STRING_TYPE_HPP
#include <FpConfig.hpp>
#include <Fw/Types/StringType.hpp>
namespace Os {
class TaskString : public Fw::StringBase {
public:
TaskString(const char* src); //!< char buffer constructor
TaskString(const StringBase& src); //!< Copy constructor
TaskString(const TaskString& src); //!< Copy constructor
TaskString(); //!< default constructor
TaskString& operator=(const TaskString& other); //!< assignment operator
TaskString& operator=(const StringBase& other); //!< other string assignment operator
TaskString& operator=(const char* other); //!< char* assignment operator
~TaskString(); //!< destructor
const char* toChar() const; //!< get pointer to internal char buffer
NATIVE_UINT_TYPE getCapacity() const; //!< return buffer size
private:
char m_buf[FW_TASK_NAME_MAX_SIZE]; //!< buffer for string
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/Event.hpp | // File: Event.hpp
// Author: Nathan Serafin (nathan.serafin@jpl.nasa.gov)
// Date: 27 July, 2018
//
// OS-independent wrapper for events.
#ifndef EVENT_HPP
#define EVENT_HPP
#include <FpConfig.hpp>
#include <Os/TaskId.hpp>
namespace Os {
class Event {
public:
enum Timeout {
EV_NO_WAIT = 0,
EV_WAIT_FOREVER = -1,
};
enum Options {
EV_EVENTS_WAIT_ALL = 0x0U,
EV_EVENTS_WAIT_ANY = 0x1U,
EV_EVENTS_RETURN_ALL = 0x2U,
EV_EVENTS_KEEP_UNWANTED = 0x4U,
EV_EVENTS_FETCH = 0x80U,
};
static I32 send(const TaskId& tid, const U32 events);
static I32 receive(const U32 events, const U8 options,
const I32 timeout, U32* eventsReceived);
static I32 clear();
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/ValidateFile.hpp | /**
* \file
* \author R. Bocchino, K. Dinkel
* \brief Defines a file class to validate files or generate a file validator file
*
* \copyright
* Copyright 2009-2016, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship
* acknowledged.
*
*/
#ifndef _ValidateFile_hpp_
#define _ValidateFile_hpp_
#define VFILE_HASH_CHUNK_SIZE (256)
#include <Utils/Hash/HashBuffer.hpp>
namespace Os {
namespace ValidateFile {
// This class encapsulates a very simple file interface for validating files against their hash files
// and creating validation files
typedef enum {
// Did the validation hash match the file hash or not?
VALIDATION_OK, //!< The validation of the file passed
VALIDATION_FAIL, //!< The validation of the file did not pass
// Did we have issues reading in the file?
FILE_DOESNT_EXIST, //!< File doesn't exist (for read)
FILE_NO_PERMISSION, //!< No permission to read/write file
FILE_BAD_SIZE, //!< Invalid size parameter
// Did we have issues reading in the hash file?
VALIDATION_FILE_DOESNT_EXIST, //!< Validation file doesn't exist (for read)
VALIDATION_FILE_NO_PERMISSION, //!< No permission to read/write file
VALIDATION_FILE_BAD_SIZE, //!< Invalid size parameter
// Did something else go wrong?
NO_SPACE, //!< No space left on the device for writing
OTHER_ERROR, //!< A catch-all for other errors. Have to look in implementation-specific code
} Status;
// also return hash
Status validate(const char* fileName, const char* hashFileName,
Utils::HashBuffer &hashBuffer);
//!< Validate the contents of a file 'fileName' against its hash
// for backwards compatibility
Status validate(const char* fileName, const char* hashFileName); //!< Validate the contents of a file 'fileName' against its hash
//!< stored in 'hashFileName'
// also return hash
Status createValidation(const char* fileName, const char* hash,
Utils::HashBuffer &hashBuffer);
// for backwards compatibility
Status createValidation(const char* fileName, const char* hashFileName); //!< Create a validation of the file 'fileName' and store it in
//!< in a file 'hashFileName'
}
}
#endif
| hpp |
fprime | data/projects/fprime/Os/MemCommon.cpp | #include <Os/Mem.hpp>
#include <cstring>
namespace Os {
U32 Mem::virtToPhys(U32 virtAddr) {
return virtAddr;
}
U32 Mem::physToVirt(U32 physAddr) {
return physAddr;
}
}
| cpp |
fprime | data/projects/fprime/Os/QueueCommon.cpp | #include <Os/Queue.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstring>
namespace Os {
#if FW_QUEUE_REGISTRATION
QueueRegistry* Queue::s_queueRegistry = nullptr;
#endif
NATIVE_INT_TYPE Queue::s_numQueues = 0;
Queue::QueueStatus Queue::send(const Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE priority, QueueBlocking block) {
const U8* msgBuff = buffer.getBuffAddr();
NATIVE_INT_TYPE buffLength = buffer.getBuffLength();
return this->send(msgBuff,buffLength,priority, block);
}
Queue::QueueStatus Queue::receive(Fw::SerializeBufferBase &buffer, NATIVE_INT_TYPE &priority, QueueBlocking block) {
U8* msgBuff = buffer.getBuffAddr();
NATIVE_INT_TYPE buffCapacity = buffer.getBuffCapacity();
NATIVE_INT_TYPE recvSize = 0;
Queue::QueueStatus recvStat = this->receive(msgBuff, buffCapacity, recvSize, priority, block);
if (QUEUE_OK == recvStat) {
if (buffer.setBuffLen(recvSize) == Fw::FW_SERIALIZE_OK) {
return QUEUE_OK;
} else {
return QUEUE_SIZE_MISMATCH;
}
} else {
return recvStat;
}
}
Queue::QueueStatus Queue::create(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
FW_ASSERT(depth > 0, depth);
FW_ASSERT(msgSize > 0, depth);
return createInternal(name, depth, msgSize);
}
#if FW_QUEUE_REGISTRATION
void Queue::setQueueRegistry(QueueRegistry* reg) {
// NULL is okay if a deregistration is desired
Queue::s_queueRegistry = reg;
}
#endif
NATIVE_INT_TYPE Queue::getNumQueues() {
return Queue::s_numQueues;
}
const QueueString& Queue::getName() {
return this->m_name;
}
}
| cpp |
fprime | data/projects/fprime/Os/Log.hpp | /**
* File: Os/Log.hpp
* Description: this file provides an implementation of the Fw::Logger class that is backed by the
* Os abstraction layer.
*/
#ifndef _Log_hpp_
#define _Log_hpp_
#include <FpConfig.hpp>
#include <Fw/Logger/Logger.hpp>
namespace Os {
class Log : public Fw::Logger {
public:
/**
* Constructor for the Os::Log object.
*/
Log();
/**
* Function called on the logger to log a message. This is abstract virtual method and
* must be supplied by the subclass. This logger object should be registered with the
* Fw::Log::registerLogger function.
* \param fmt: format string in which to place arguments
* \param a0: zeroth argument. (Default: 0)
* \param a1: first argument. (Default: 0)
* \param a2: second argument. (Default: 0)
* \param a3: third argument. (Default: 0)
* \param a4: fourth argument. (Default: 0)
* \param a5: fifth argument. (Default: 0)
* \param a6: sixth argument. (Default: 0)
* \param a7: seventh argument. (Default: 0)
* \param a8: eighth argument. (Default: 0)
* \param a9: ninth argument. (Default: 0)
*/
void log(
const char* fmt,
POINTER_CAST a0 = 0,
POINTER_CAST a1 = 0,
POINTER_CAST a2 = 0,
POINTER_CAST a3 = 0,
POINTER_CAST a4 = 0,
POINTER_CAST a5 = 0,
POINTER_CAST a6 = 0,
POINTER_CAST a7 = 0,
POINTER_CAST a8 = 0,
POINTER_CAST a9 = 0
);
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/FileSystem.hpp | #ifndef _FileSystem_hpp_
#define _FileSystem_hpp_
#include <FpConfig.hpp>
#include <Fw/Types/String.hpp>
#define FILE_SYSTEM_CHUNK_SIZE (256u)
namespace Os {
// This namespace encapsulates a very simple file system interface that has the most often-used features.
namespace FileSystem {
typedef enum {
OP_OK, //!< Operation was successful
ALREADY_EXISTS, //!< File already exists
NO_SPACE, //!< No space left
NO_PERMISSION, //!< No permission to write
NOT_DIR, //!< Path is not a directory
IS_DIR, //!< Path is a directory
NOT_EMPTY, //!< directory is not empty
INVALID_PATH, //!< Path is too long, too many sym links, doesn't exist, ect
FILE_LIMIT, //!< Too many files or links
BUSY, //!< Operand is in use by the system or by a process
OTHER_ERROR, //!< other OS-specific error
} Status;
Status createDirectory(const char* path); //!< create a new directory at location path
Status removeDirectory(const char* path); //!< remove a directory at location path
Status readDirectory(const char* path, const U32 maxNum, Fw::String fileArray[], U32& numFiles); //!< read the contents of a directory. Size of fileArray should be maxNum. Cleaner implementation found in Directory.hpp
Status removeFile(const char* path); //!< removes a file at location path
Status moveFile(const char* originPath, const char* destPath); //! moves a file from origin to destination
Status copyFile(const char* originPath, const char* destPath); //! copies a file from origin to destination
Status appendFile(const char* originPath, const char* destPath, bool createMissingDest=false); //! append file origin to destination file. If boolean true, creates a brand new file if the destination doesn't exist.
Status getFileSize(const char* path, FwSignedSizeType& size); //!< gets the size of the file (in bytes) at location path
Status getFileCount(const char* directory, U32& fileCount); //!< counts the number of files in the given directory
Status changeWorkingDirectory(const char* path); //!< move current directory to path
Status getFreeSpace(const char* path, FwSizeType& totalBytes, FwSizeType& freeBytes); //!< get FS free and total space in bytes on filesystem containing path
}
}
#endif
| hpp |
fprime | data/projects/fprime/Os/TaskIdRepr.hpp | // File: TaskIdRepr.hpp
// Author: Nathan Serafin (nathan.serafin@jpl.nasa.gov)
// Date: 29 June, 2018
//
// Depending on the target operating system, define a type
// for the storage of task IDs.
#ifndef TASKIDREPR_HPP
#define TASKIDREPR_HPP
#if defined(TGT_OS_TYPE_LINUX) || defined(TGT_OS_TYPE_DARWIN)
extern "C" {
#include <pthread.h>
}
#endif
namespace Os {
#if defined(TGT_OS_TYPE_VXWORKS) || (FW_BAREMETAL_SCHEDULER == 1)
typedef int TaskIdRepr;
#elif defined(TGT_OS_TYPE_LINUX) || defined(TGT_OS_TYPE_DARWIN)
typedef pthread_t TaskIdRepr;
#endif
}
#endif
| hpp |
fprime | data/projects/fprime/Os/IntervalTimer.hpp | /**
* IntervalTimer.hpp:
*
* Interval timer provides timing over a set interval to the caller. It is one of the core Os
* package supplied items.
*/
#ifndef _IntervalTimer_hpp_
#define _IntervalTimer_hpp_
#include <FpConfig.hpp>
namespace Os {
class IntervalTimer {
public:
/**
* RawTime:
*
* Most time is stored as an upper and lower part of this raw time object. The
* semantic meaning of this "RawTime" is platform-dependent.
*/
typedef struct {
U32 upper; //!< Upper 32-bits part of time value. Platform dependent.
U32 lower; //!< Lower 32-bits part of time value. Platform dependent.
} RawTime;
IntervalTimer(); //!< Constructor
virtual ~IntervalTimer(); //!< Destructor
//------------ Common Functions ------------
// Common functions, typically do not need to be implemented by an OS support package.
// Common implementations in IntervalTimerCommon.cpp.
//------------------------------------------
/**
* Capture a start time of the interval timed by the interval timer. This fills the
* start RawTime of the interval.
*/
void start();
/**
* Capture a stop time of the interval timed by the interval timer. This fills the
* stop RawTime of the interval.
*/
void stop();
/**
* Returns the difference in usecond difference between start and stop times. The caller
* must have called start and stop previously.
* \return U32: microseconds difference in the interval
*/
U32 getDiffUsec();
//------------ Platform Functions ------------
// Platform functions, typically do need to be implemented by an OS support package, as
// they are dependent on the platform definition of "RawTime".
//------------------------------------------
/**
* Returns the difference in microseconds between the supplied times t1, and t2. This
* calculation is done with respect to the semantic meaning of the times, and thus is
* dependent on the platform's representation of the RawTime object.
* \return U32 microsecond difference between two supplied values, t1-t2.
*/
static U32 getDiffUsec(const RawTime& t1, const RawTime& t2);
/**
* Fills the RawTime object supplied with the current raw time in a platform dependent
* way.
*/
static void getRawTime(RawTime& time);
PRIVATE:
//------------ Internal Member Variables ------------
RawTime m_startTime; //!< Stored start time
RawTime m_stopTime; //!< Stored end time
//------------ Disabled (private) Copy Constructor ------------
IntervalTimer(IntervalTimer&); //!< Disabled copy constructor
};
}
#endif
| hpp |
fprime | data/projects/fprime/Os/Linux/File.cpp | #include <FpConfig.hpp>
#include <Os/File.hpp>
#include <Fw/Types/Assert.hpp>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#include <Utils/Hash/libcrc/lib_crc.h> // borrow CRC
#ifdef __cplusplus
}
#endif // __cplusplus
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits>
#include <cstring>
#include <cstdio>
//#define DEBUG_PRINT(...) printf(##__VA_ARGS__); fflush(stdout)
#define DEBUG_PRINT(...)
namespace Os {
File::File() :m_fd(-1),m_mode(OPEN_NO_MODE),m_lastError(0) {
}
File::~File() {
if (this->m_mode != OPEN_NO_MODE) {
this->close();
}
}
File::Status File::open(const char* fileName, File::Mode mode) {
return this->open(fileName, mode, true);
}
File::Status File::open(const char* fileName, File::Mode mode, bool include_excl) {
NATIVE_INT_TYPE flags = 0;
Status stat = OP_OK;
switch (mode) {
case OPEN_READ:
flags = O_RDONLY;
break;
case OPEN_WRITE:
flags = O_WRONLY | O_CREAT;
break;
case OPEN_SYNC_WRITE:
flags = O_WRONLY | O_CREAT | O_SYNC;
break;
#ifndef TGT_OS_TYPE_RTEMS
case OPEN_SYNC_DIRECT_WRITE:
flags = O_WRONLY | O_CREAT | O_DSYNC
#ifdef __linux__
| O_DIRECT;
#else
;
#endif
break;
#endif
case OPEN_CREATE:
flags = O_WRONLY | O_CREAT | O_TRUNC;
if(include_excl) {
flags |= O_EXCL;
}
break;
case OPEN_APPEND:
flags = O_WRONLY | O_CREAT | O_APPEND;
break;
default:
FW_ASSERT(0, mode);
break;
}
NATIVE_INT_TYPE userFlags =
#ifdef __VXWORKS__
0;
#else
S_IRUSR|S_IWRITE;
#endif
NATIVE_INT_TYPE fd = ::open(fileName,flags,userFlags);
if (-1 == fd) {
this->m_lastError = errno;
switch (errno) {
case ENOSPC:
stat = NO_SPACE;
break;
case ENOENT:
stat = DOESNT_EXIST;
break;
case EACCES:
stat = NO_PERMISSION;
break;
case EEXIST:
stat = FILE_EXISTS;
break;
default:
stat = OTHER_ERROR;
break;
}
}
this->m_mode = mode;
this->m_fd = fd;
return stat;
}
bool File::isOpen() {
return this->m_fd > 0;
}
File::Status File::prealloc(NATIVE_INT_TYPE offset, NATIVE_INT_TYPE len) {
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
return NOT_OPENED;
}
File::Status fileStatus = OP_OK;
#ifdef __linux__
NATIVE_INT_TYPE stat = posix_fallocate(this->m_fd, offset, len);
if (stat) {
switch (stat) {
case ENOSPC:
case EFBIG:
fileStatus = NO_SPACE;
break;
case EBADF:
fileStatus = DOESNT_EXIST;
break;
default:
fileStatus = OTHER_ERROR;
break;
}
}
#endif
return fileStatus;
}
File::Status File::seek(NATIVE_INT_TYPE offset, bool absolute) {
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
return NOT_OPENED;
}
Status stat = OP_OK;
NATIVE_INT_TYPE whence = absolute?SEEK_SET:SEEK_CUR;
off_t act_off = ::lseek(this->m_fd,offset,whence);
// No error would be a normal one for this simple
// class, so return other error
if (act_off != offset) {
if (-1 == act_off) {
this->m_lastError = errno;
stat = OTHER_ERROR;
} else {
stat = BAD_SIZE;
}
}
return stat;
}
File::Status File::read(void * buffer, NATIVE_INT_TYPE &size, bool waitForFull) {
FW_ASSERT(buffer);
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
size = 0;
return NOT_OPENED;
}
// Validate read size before entering reading loop. Linux's read call expects size_t, which
// is defined as an unsigned value. Thus 0 and negative values rejected.
if (size <= 0) {
size = 0;
return BAD_SIZE;
}
NATIVE_INT_TYPE accSize = 0; // accumulated size
Status stat = OP_OK;
NATIVE_INT_TYPE maxIters = size*2; // loop limit; couldn't block more times than number of bytes
while (maxIters > 0) {
ssize_t readSize = ::read(this->m_fd,
#ifdef __VXWORKS__
static_cast<char*>(buffer)
#else
buffer
#endif
,size-accSize);
if (readSize != size-accSize) {
// could be an error
if (-1 == readSize) {
switch (errno) {
case EINTR: // read was interrupted
maxIters--; // decrement loop count
continue;
default:
stat = OTHER_ERROR;
break;
}
this->m_lastError = errno;
accSize = 0;
break; // break out of while loop
} else if (0 == readSize) { // end of file
break;
} else { // partial read so adjust read point and size
accSize += readSize;
if (not waitForFull) {
break; // break out of while loop
} else {
// in order to move the pointer ahead, we need to cast it
U8* charPtr = static_cast<U8*>(buffer);
charPtr = &charPtr[readSize];
buffer = static_cast<void*>(charPtr);
}
maxIters--; // decrement loop count
}
} else { // got number we wanted
accSize += readSize;
break; // break out of while loop
}
maxIters--; // decrement loop count
} // end read while loop
// make sure we didn't exceed loop count
FW_ASSERT(maxIters > 0);
size = accSize;
return stat;
}
File::Status File::write(const void * buffer, NATIVE_INT_TYPE &size, bool waitForDone) {
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
size = 0;
return NOT_OPENED;
}
// Validate read size before entering reading loop. Linux's read call expects size_t, which
// is defined as an unsigned value. Thus 0 and negative values rejected.
if (size <= 0) {
size = 0;
return BAD_SIZE;
}
Status stat = OP_OK;
// just check for EINTR
NATIVE_INT_TYPE maxIters = size*2; // loop limit; couldn't block more times than number of bytes
while (maxIters > 0) {
NATIVE_INT_TYPE writeSize = ::write(this->m_fd,
#ifdef __VXWORKS__
static_cast<char*>(const_cast<void*>(buffer)) // Ugly, but that's how VxWorks likes to roll...
#else
buffer
#endif
,size);
if (-1 == writeSize) {
switch (errno) {
case EINTR: // write was interrupted
maxIters--; // decrement loop count
continue;
case ENOSPC:
stat = NO_SPACE;
break;
default:
DEBUG_PRINT("Error %d during write of 0x%p, addrMod %d, size %d, sizeMod %d\n",
errno, buffer, static_cast<POINTER_CAST>(buffer) % 512, size, size % 512);
stat = OTHER_ERROR;
break;
}
this->m_lastError = errno;
break; // break out of while loop
} else {
size = writeSize;
#ifdef __linux__
if ((OPEN_SYNC_DIRECT_WRITE != this->m_mode) && (waitForDone)) {
NATIVE_UINT_TYPE position = lseek(this->m_fd, 0, SEEK_CUR);
sync_file_range(this->m_fd, position - writeSize, writeSize,
SYNC_FILE_RANGE_WAIT_BEFORE
| SYNC_FILE_RANGE_WRITE
| SYNC_FILE_RANGE_WAIT_AFTER);
}
#endif
break; // break out of while loop
}
}
return stat;
}
// NOTE(mereweth) - see http://lkml.iu.edu/hypermail/linux/kernel/1005.2/01845.html
// recommendation from Linus Torvalds, but doesn't seem to be that fast
File::Status File::bulkWrite(const void * buffer, NATIVE_UINT_TYPE &totalSize,
NATIVE_INT_TYPE chunkSize) {
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
totalSize = 0;
return NOT_OPENED;
}
// Validate read size before entering reading loop. Linux's read call expects size_t, which
// is defined as an unsigned value. Thus 0 and negative values rejected.
if (totalSize == 0) {
totalSize = 0;
return BAD_SIZE;
}
else if (chunkSize <= 0) {
totalSize = 0;
return BAD_SIZE;
}
#ifdef __linux__
const NATIVE_UINT_TYPE startPosition = lseek(this->m_fd, 0, SEEK_CUR);
#endif
NATIVE_UINT_TYPE newBytesWritten = 0;
for (NATIVE_UINT_TYPE idx = 0; idx < totalSize; idx += chunkSize) {
NATIVE_INT_TYPE size = chunkSize;
// if we're on the last iteration and length isn't a multiple of chunkSize
if (idx + chunkSize > totalSize) {
size = totalSize - idx;
}
const NATIVE_INT_TYPE toWrite = size;
FW_ASSERT(idx + size <= totalSize, idx + size);
const Os::File::Status fileStatus = this->write(static_cast<const U8*>(buffer) + idx, size, false);
if (!(fileStatus == Os::File::OP_OK
&& size == static_cast<NATIVE_INT_TYPE>(toWrite))) {
totalSize = newBytesWritten;
return fileStatus;
}
#ifdef __linux__
sync_file_range(this->m_fd,
startPosition + newBytesWritten,
chunkSize,
SYNC_FILE_RANGE_WRITE);
if (newBytesWritten) {
sync_file_range(this->m_fd,
startPosition + newBytesWritten - chunkSize,
chunkSize,
SYNC_FILE_RANGE_WAIT_BEFORE
| SYNC_FILE_RANGE_WRITE
| SYNC_FILE_RANGE_WAIT_AFTER);
posix_fadvise(this->m_fd,
startPosition + newBytesWritten - chunkSize,
chunkSize, POSIX_FADV_DONTNEED);
}
#endif
newBytesWritten += toWrite;
}
totalSize = newBytesWritten;
return OP_OK;
}
File::Status File::flush() {
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
return NOT_OPENED;
}
File::Status stat = OP_OK;
if (-1 == fsync(this->m_fd)) {
switch (errno) {
case ENOSPC:
stat = NO_SPACE;
break;
default:
stat = OTHER_ERROR;
break;
}
}
return stat;
}
void File::close() {
if ((this->m_fd != -1) and (this->m_mode != OPEN_NO_MODE)) {
(void)::close(this->m_fd);
this->m_fd = -1;
}
this->m_mode = OPEN_NO_MODE;
}
NATIVE_INT_TYPE File::getLastError() {
return this->m_lastError;
}
const char* File::getLastErrorString() {
return strerror(this->m_lastError);
}
File::Status File::calculateCRC32(U32 &crc)
{
// make sure it has been opened
if (OPEN_NO_MODE == this->m_mode) {
crc = 0;
return NOT_OPENED;
}
const U32 maxChunkSize = 32;
const U32 initialSeed = 0xFFFFFFFF;
// Seek to beginning of file
Status status = seek(0, true);
if (status != OP_OK) {
crc = 0;
return status;
}
U8 file_buffer[maxChunkSize];
bool endOfFile = false;
U32 seed = initialSeed;
const U32 maxIters = std::numeric_limits<U32>::max(); // loop limit
U32 numIters = 0;
while (!endOfFile && numIters < maxIters) {
++numIters;
int chunkSize = maxChunkSize;
status = read(file_buffer, chunkSize, false);
if (status == OP_OK) {
// chunkSize modified by file.read
if (chunkSize == 0) {
endOfFile = true;
continue;
}
int chunkIdx = 0;
while (chunkIdx < chunkSize) {
seed = update_crc_32(seed, file_buffer[chunkIdx]);
chunkIdx++;
}
} else {
crc = 0;
return status;
}
}
if (!endOfFile) {
crc = 0;
return OTHER_ERROR;
}
else {
crc = seed;
return OP_OK;
}
}
}
| cpp |
fprime | data/projects/fprime/Os/Linux/SystemResources.cpp | // ======================================================================
// \title Linux/SystemResources.cpp
// \author sfregoso
// \brief hpp file for SystemResources component implementation class
//
// \copyright
// Copyright 2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <cstdio>
#include <cstring>
#include <sys/sysinfo.h>
#include <Os/SystemResources.hpp>
#include <Fw/Types/Assert.hpp>
constexpr char PROC_STAT_PATH[] = "/proc/stat";
constexpr char READ_ONLY[] = "r";
constexpr int LINE_SIZE = 256;
char proc_stat_line[LINE_SIZE];
namespace Os {
SystemResources::SystemResourcesStatus SystemResources::getCpuCount(U32& cpuCount) {
cpuCount = get_nprocs();
return SYSTEM_RESOURCES_OK;
}
U64 getCpuUsed(U32 cpu_data[4]) {
return cpu_data[0] + cpu_data[1] + cpu_data[2];
}
U64 getCpuTotal(U32 cpu_data[4]) {
return cpu_data[0] + cpu_data[1] + cpu_data[2] + cpu_data[3];
}
SystemResources::SystemResourcesStatus openProcStatFile(FILE*& fp) {
if ((fp = fopen(PROC_STAT_PATH, READ_ONLY)) == nullptr) {
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
return SystemResources::SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus readProcStatLine(FILE* fp, char proc_stat_line[LINE_SIZE]) {
if (fgets(proc_stat_line, LINE_SIZE, fp) == nullptr) {
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
return SystemResources::SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus getCpuDataLine(FILE* fp,
U32 cpu_index,
char proc_stat_line[LINE_SIZE]) {
for (U32 i = 0; i < cpu_index + 1; i++) {
if (readProcStatLine(fp, proc_stat_line) != SystemResources::SYSTEM_RESOURCES_OK) {
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
if (i != cpu_index) {
continue;
}
if (strncmp(proc_stat_line, "cpu", 3) != 0) {
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
break;
}
return SystemResources::SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus parseCpuData(char proc_stat_line[LINE_SIZE],
U32 cpu_data[4]) {
if (sscanf(proc_stat_line, "%*s %u %u %u %u", &cpu_data[0], &cpu_data[1], &cpu_data[2], &cpu_data[3]) !=
4) {
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
return SystemResources::SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus getCpuData(U32 cpu_index, U32 cpu_data[4]) {
FILE* fp = nullptr;
if (openProcStatFile(fp) != SystemResources::SYSTEM_RESOURCES_OK) {
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
if (readProcStatLine(fp, proc_stat_line) != SystemResources::SYSTEM_RESOURCES_OK ||
getCpuDataLine(fp, cpu_index, proc_stat_line) != SystemResources::SYSTEM_RESOURCES_OK ||
parseCpuData(proc_stat_line, cpu_data) != SystemResources::SYSTEM_RESOURCES_OK) {
fclose(fp);
return SystemResources::SYSTEM_RESOURCES_ERROR;
}
fclose(fp);
return SystemResources::SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus SystemResources::getCpuTicks(CpuTicks& cpu_ticks, U32 cpu_index) {
SystemResources::SystemResourcesStatus status = SYSTEM_RESOURCES_ERROR;
U32 cpu_data[4] = {0};
U32 cpuCount = 0;
if ((status = getCpuCount(cpuCount)) != SYSTEM_RESOURCES_OK) {
return status;
}
if (cpu_index >= cpuCount) {
return SYSTEM_RESOURCES_ERROR;
}
if ((status = getCpuData(cpu_index, cpu_data)) != SYSTEM_RESOURCES_OK) {
return status;
}
cpu_ticks.used = getCpuUsed(cpu_data);
cpu_ticks.total = getCpuTotal(cpu_data);
return SYSTEM_RESOURCES_OK;
}
U64 getMemoryTotal(FwSizeType total_ram, FwSizeType memory_unit) {
return static_cast<U64>(total_ram)*static_cast<U64>(memory_unit);
}
U64 getMemoryUsed(FwSizeType total_ram, FwSizeType free_ram, FwSizeType memory_unit) {
return static_cast<U64>((total_ram - free_ram)) * static_cast<U64>(memory_unit);
}
bool checkCastingAndTypeErrors(FwSizeType total_ram,
FwSizeType free_ram,
FwSizeType memory_unit,
const struct sysinfo& memory_info) {
return ((total_ram <= 0) || (memory_unit <= 0) ||
(static_cast<unsigned long>(total_ram) != memory_info.totalram) ||
(static_cast<unsigned long>(free_ram) != memory_info.freeram) ||
(static_cast<unsigned int>(memory_unit) != memory_info.mem_unit));
}
bool checkInvalidMemoryCalculation(FwSizeType total_ram, FwSizeType free_ram) {
return (total_ram < free_ram);
}
bool checkMultiplicationOverflow(FwSizeType total_ram, FwSizeType memory_unit) {
return (total_ram > (std::numeric_limits<FwSizeType>::max() / memory_unit));
}
SystemResources::SystemResourcesStatus SystemResources::getMemUtil(MemUtil& memory_util) {
struct sysinfo memory_info;
if (sysinfo(&memory_info) != 0) {
return SYSTEM_RESOURCES_ERROR;
}
const FwSizeType total_ram = static_cast<FwSizeType>(memory_info.totalram);
const FwSizeType free_ram = static_cast<FwSizeType>(memory_info.freeram);
const FwSizeType memory_unit = static_cast<FwSizeType>(memory_info.mem_unit);
if (checkCastingAndTypeErrors(total_ram, free_ram, memory_unit, memory_info)) {
return SYSTEM_RESOURCES_ERROR;
}
if (checkInvalidMemoryCalculation(total_ram, free_ram)) {
return SYSTEM_RESOURCES_ERROR;
}
if (checkMultiplicationOverflow(total_ram, memory_unit)) {
return SYSTEM_RESOURCES_ERROR;
}
memory_util.used = getMemoryUsed(total_ram, free_ram, memory_unit);
memory_util.total = getMemoryTotal(total_ram, memory_unit);
return SYSTEM_RESOURCES_OK;
}
}
| cpp |
fprime | data/projects/fprime/Os/Linux/FileSystem.cpp | #include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/File.hpp>
#include <Os/FileSystem.hpp>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <unistd.h>
#include <cerrno>
#include <cstdio> // Needed for rename
#include <cstring>
#include <limits>
namespace Os {
namespace FileSystem {
Status createDirectory(const char* path) {
Status stat = OP_OK;
#ifdef __VXWORKS__
int mkStat = ::mkdir(path);
#else
int mkStat = ::mkdir(path, S_IRWXU);
#endif
if (-1 == mkStat) {
switch (errno) {
case EACCES:
case EPERM:
case EROFS:
case EFAULT:
stat = NO_PERMISSION;
break;
case EEXIST:
stat = ALREADY_EXISTS;
break;
case ELOOP:
case ENOENT:
case ENAMETOOLONG:
stat = INVALID_PATH;
break;
case ENOTDIR:
stat = NOT_DIR;
break;
case ENOSPC:
case EDQUOT:
stat = NO_SPACE;
break;
case EMLINK:
stat = FILE_LIMIT;
break;
default:
stat = OTHER_ERROR;
break;
}
}
return stat;
} // end createDirectory
Status removeDirectory(const char* path) {
Status stat = OP_OK;
if (::rmdir(path) == -1) {
switch (errno) {
case EACCES:
case EPERM:
case EROFS:
case EFAULT:
stat = NO_PERMISSION;
break;
case ENOTEMPTY:
case EEXIST:
stat = NOT_EMPTY;
break;
case EINVAL:
case ELOOP:
case ENOENT:
case ENAMETOOLONG:
stat = INVALID_PATH;
break;
case ENOTDIR:
stat = NOT_DIR;
break;
case EBUSY:
stat = BUSY;
break;
default:
stat = OTHER_ERROR;
break;
}
}
return stat;
} // end removeDirectory
Status readDirectory(const char* path, const U32 maxNum, Fw::String fileArray[], U32& numFiles) {
Status dirStat = OP_OK;
DIR* dirPtr = nullptr;
struct dirent* direntData = nullptr;
FW_ASSERT(fileArray != nullptr);
FW_ASSERT(path != nullptr);
// Open directory failed:
if ((dirPtr = ::opendir(path)) == nullptr) {
switch (errno) {
case EACCES:
dirStat = NO_PERMISSION;
break;
case ENOENT:
dirStat = INVALID_PATH;
break;
case ENOTDIR:
dirStat = NOT_DIR;
break;
default:
dirStat = OTHER_ERROR;
break;
}
return dirStat;
}
// Set errno to 0 so we know why we exited readdir
errno = 0;
U32 arrayIdx = 0;
U32 limitCount = 0;
const U32 loopLimit = std::numeric_limits<U32>::max();
// Read the directory contents and store in passed in array:
while (arrayIdx < maxNum && limitCount < loopLimit) {
++limitCount;
if ((direntData = ::readdir(dirPtr)) != nullptr) {
// We are only care about regular files
if (direntData->d_type == DT_REG) {
FW_ASSERT(arrayIdx < maxNum, static_cast<NATIVE_INT_TYPE>(arrayIdx),
static_cast<NATIVE_INT_TYPE>(maxNum));
Fw::String str(direntData->d_name);
fileArray[arrayIdx++] = str;
}
} else {
// readdir failed, did it error or did we run out of files?
if (errno != 0) {
// Only error from readdir is EBADF
dirStat = OTHER_ERROR;
}
break;
}
}
if (limitCount == loopLimit) {
dirStat = FILE_LIMIT;
}
if (::closedir(dirPtr) == -1) {
// Only error from closedir is EBADF
dirStat = OTHER_ERROR;
}
numFiles = arrayIdx;
return dirStat;
}
Status removeFile(const char* path) {
Status stat = OP_OK;
if (::unlink(path) == -1) {
switch (errno) {
case EACCES:
case EPERM:
case EROFS:
stat = NO_PERMISSION;
break;
case EISDIR:
stat = IS_DIR;
break;
case ELOOP:
case ENOENT:
case ENAMETOOLONG:
stat = INVALID_PATH;
break;
case ENOTDIR:
stat = NOT_DIR;
break;
case EBUSY:
stat = BUSY;
break;
default:
stat = OTHER_ERROR;
break;
}
}
return stat;
} // end removeFile
Status moveFile(const char* originPath, const char* destPath) {
Status stat = OP_OK;
if (::rename(originPath, destPath) == -1) {
switch (errno) {
case EACCES:
case EPERM:
case EROFS:
case EFAULT:
stat = NO_PERMISSION;
break;
case EDQUOT:
case ENOSPC:
stat = NO_SPACE;
break;
case ELOOP:
case ENAMETOOLONG:
case ENOENT:
case EINVAL:
stat = INVALID_PATH;
break;
case ENOTDIR:
case EISDIR: // Old path is not a dir
stat = NOT_DIR;
break;
case ENOTEMPTY:
case EEXIST:
stat = NOT_EMPTY;
break;
case EMLINK:
stat = FILE_LIMIT;
break;
case EBUSY:
stat = BUSY;
break;
default:
stat = OTHER_ERROR;
break;
}
}
return stat;
} // end moveFile
Status handleFileError(File::Status fileStatus) {
Status fileSystemStatus = OTHER_ERROR;
switch (fileStatus) {
case File::NO_SPACE:
fileSystemStatus = NO_SPACE;
break;
case File::NO_PERMISSION:
fileSystemStatus = NO_PERMISSION;
break;
case File::DOESNT_EXIST:
fileSystemStatus = INVALID_PATH;
break;
default:
fileSystemStatus = OTHER_ERROR;
}
return fileSystemStatus;
} // end handleFileError
/**
* A helper function that returns an "OP_OK" status if the given file
* exists and can be read from, otherwise returns an error status.
*
* If provided, will also initialize the given stat struct with file
* information.
*/
Status initAndCheckFileStats(const char* filePath, struct stat* fileInfo = nullptr) {
FileSystem::Status fs_status;
struct stat local_info;
if (!fileInfo) {
// No external struct given, so use the local one
fileInfo = &local_info;
}
if (::stat(filePath, fileInfo) == -1) {
switch (errno) {
case EACCES:
fs_status = NO_PERMISSION;
break;
case ELOOP:
case ENOENT:
case ENAMETOOLONG:
fs_status = INVALID_PATH;
break;
case ENOTDIR:
fs_status = NOT_DIR;
break;
default:
fs_status = OTHER_ERROR;
break;
}
return fs_status;
}
// Make sure the origin is a regular file
if (!S_ISREG(fileInfo->st_mode)) {
return INVALID_PATH;
}
return OP_OK;
}
/**
* A helper function that writes all the file information in the source
* file to the destination file (replaces/appends to end/etc. depending
* on destination file mode).
*
* Files must already be open and will remain open after this function
* completes.
*
* @param source File to copy data from
* @param destination File to copy data to
* @param size The number of bytes to copy
*/
Status copyFileData(File& source, File& destination, FwSignedSizeType size) {
static_assert(FILE_SYSTEM_CHUNK_SIZE != 0, "FILE_SYSTEM_CHUNK_SIZE must be >0");
U8 fileBuffer[FILE_SYSTEM_CHUNK_SIZE];
File::Status file_status;
// Set loop limit
const FwSignedSizeType copyLoopLimit = (size / FILE_SYSTEM_CHUNK_SIZE) + 2;
FwSignedSizeType loopCounter = 0;
FwSignedSizeType chunkSize;
while (loopCounter < copyLoopLimit) {
chunkSize = FILE_SYSTEM_CHUNK_SIZE;
file_status = source.read(fileBuffer, chunkSize, Os::File::WaitType::NO_WAIT);
if (file_status != File::OP_OK) {
return handleFileError(file_status);
}
if (chunkSize == 0) {
// file has been successfully copied
break;
}
file_status = destination.write(fileBuffer, chunkSize, Os::File::WaitType::WAIT);
if (file_status != File::OP_OK) {
return handleFileError(file_status);
}
loopCounter++;
}
FW_ASSERT(loopCounter < copyLoopLimit);
return FileSystem::OP_OK;
} // end copyFileData
Status copyFile(const char* originPath, const char* destPath) {
FileSystem::Status fs_status;
File::Status file_status;
FwSignedSizeType fileSize = 0;
File source;
File destination;
fs_status = initAndCheckFileStats(originPath);
if (FileSystem::OP_OK != fs_status) {
return fs_status;
}
// Get the file size:
fs_status =
FileSystem::getFileSize(originPath, fileSize); //!< gets the size of the file (in bytes) at location path
if (FileSystem::OP_OK != fs_status) {
return fs_status;
}
file_status = source.open(originPath, File::OPEN_READ);
if (file_status != File::OP_OK) {
return handleFileError(file_status);
}
file_status = destination.open(destPath, File::OPEN_WRITE);
if (file_status != File::OP_OK) {
return handleFileError(file_status);
}
fs_status = copyFileData(source, destination, fileSize);
(void)source.close();
(void)destination.close();
return fs_status;
} // end copyFile
Status appendFile(const char* originPath, const char* destPath, bool createMissingDest) {
FileSystem::Status fs_status;
File::Status file_status;
FwSignedSizeType fileSize = 0;
File source;
File destination;
fs_status = initAndCheckFileStats(originPath);
if (FileSystem::OP_OK != fs_status) {
return fs_status;
}
// Get the file size:
fs_status =
FileSystem::getFileSize(originPath, fileSize); //!< gets the size of the file (in bytes) at location path
if (FileSystem::OP_OK != fs_status) {
return fs_status;
}
file_status = source.open(originPath, File::OPEN_READ);
if (file_status != File::OP_OK) {
return handleFileError(file_status);
}
// If needed, check if destination file exists (and exit if not)
if (!createMissingDest) {
fs_status = initAndCheckFileStats(destPath);
if (FileSystem::OP_OK != fs_status) {
return fs_status;
}
}
file_status = destination.open(destPath, File::OPEN_APPEND);
if (file_status != File::OP_OK) {
return handleFileError(file_status);
}
fs_status = copyFileData(source, destination, fileSize);
(void)source.close();
(void)destination.close();
return fs_status;
} // end appendFile
Status getFileSize(const char* path, FwSignedSizeType& size) {
Status fileStat = OP_OK;
struct stat fileStatStruct;
fileStat = initAndCheckFileStats(path, &fileStatStruct);
if (FileSystem::OP_OK == fileStat) {
// Only check size if struct was initialized successfully
size = fileStatStruct.st_size;
if (static_cast<off_t>(size) != fileStatStruct.st_size) {
return FileSystem::OTHER_ERROR;
}
}
return fileStat;
} // end getFileSize
Status changeWorkingDirectory(const char* path) {
Status stat = OP_OK;
if (::chdir(path) == -1) {
switch (errno) {
case EACCES:
case EFAULT:
stat = NO_PERMISSION;
break;
case ENOTEMPTY:
stat = NOT_EMPTY;
break;
case ENOENT:
case ELOOP:
case ENAMETOOLONG:
stat = INVALID_PATH;
break;
case ENOTDIR:
stat = NOT_DIR;
break;
default:
stat = OTHER_ERROR;
break;
}
}
return stat;
} // end changeWorkingDirectory
Status getFreeSpace(const char* path, FwSizeType& totalBytes, FwSizeType& freeBytes) {
Status stat = OP_OK;
struct statvfs fsStat;
int ret = statvfs(path, &fsStat);
if (ret) {
switch (errno) {
case EACCES:
stat = NO_PERMISSION;
break;
case ELOOP:
case ENOENT:
case ENAMETOOLONG:
stat = INVALID_PATH;
break;
case ENOTDIR:
stat = NOT_DIR;
break;
default:
stat = OTHER_ERROR;
break;
}
return stat;
}
const FwSizeType block_size = static_cast<FwSizeType>(fsStat.f_frsize);
const FwSizeType free_blocks = static_cast<FwSizeType>(fsStat.f_bfree);
const FwSizeType total_blocks = static_cast<FwSizeType>(fsStat.f_blocks);
// Check for casting and type error
if (((block_size <= 0) || (static_cast<unsigned long>(block_size) != fsStat.f_frsize)) ||
((free_blocks <= 0) || (static_cast<fsblkcnt_t>(free_blocks) != fsStat.f_bfree)) ||
((total_blocks <= 0) || (static_cast<fsblkcnt_t>(block_size) != fsStat.f_blocks))) {
return OTHER_ERROR;
}
// Check for overflow in multiplication
if (free_blocks > (std::numeric_limits<FwSizeType>::max() / block_size) ||
total_blocks > (std::numeric_limits<FwSizeType>::max() / block_size)) {
return OTHER_ERROR;
}
freeBytes = free_blocks * block_size;
totalBytes = total_blocks * block_size;
return stat;
}
// Public function to get the file count for a given directory.
Status getFileCount(const char* directory, U32& fileCount) {
Status dirStat = OP_OK;
DIR* dirPtr = nullptr;
struct dirent* direntData = nullptr;
U32 limitCount;
const U32 loopLimit = std::numeric_limits<U32>::max();
fileCount = 0;
if ((dirPtr = ::opendir(directory)) == nullptr) {
switch (errno) {
case EACCES:
dirStat = NO_PERMISSION;
break;
case ENOENT:
dirStat = INVALID_PATH;
break;
case ENOTDIR:
dirStat = NOT_DIR;
break;
default:
dirStat = OTHER_ERROR;
break;
}
return dirStat;
}
// Set errno to 0 so we know why we exited readdir
errno = 0;
for (limitCount = 0; limitCount < loopLimit; limitCount++) {
if ((direntData = ::readdir(dirPtr)) != nullptr) {
// We are only counting regular files
if (direntData->d_type == DT_REG) {
fileCount++;
}
} else {
// readdir failed, did it error or did we run out of files?
if (errno != 0) {
// Only error from readdir is EBADF
dirStat = OTHER_ERROR;
}
break;
}
}
if (limitCount == loopLimit) {
dirStat = FILE_LIMIT;
}
if (::closedir(dirPtr) == -1) {
// Only error from closedir is EBADF
dirStat = OTHER_ERROR;
}
return dirStat;
} // end getFileCount
} // namespace FileSystem
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/Linux/Directory.cpp | #include <FpConfig.hpp>
#include <Os/Directory.hpp>
#include <Fw/Types/Assert.hpp>
#include <dirent.h>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
namespace Os {
Directory::Directory() :m_dir(0),m_lastError(0) {
}
Directory::~Directory() {
this->close();
}
Directory::Status Directory::open(const char* dirName) {
Status stat = OP_OK;
DIR* dir = ::opendir(dirName);
if (dir == nullptr) {
this->m_lastError = errno;
switch (errno) {
case ENOENT:
stat = DOESNT_EXIST;
break;
case EACCES:
stat = NO_PERMISSION;
break;
case ENOTDIR:
stat = NOT_DIR;
break;
default:
stat = OTHER_ERROR;
break;
}
return stat;
}
this->m_dir = reinterpret_cast<POINTER_CAST>(dir);
return stat;
}
Directory::Status Directory::rewind() {
// make sure it has been opened
if (!this->isOpen()) {
return NOT_OPENED;
}
Status stat = OP_OK;
DIR* dir = reinterpret_cast<DIR*>(this->m_dir);
// no errors defined
::rewinddir(dir);
return stat;
}
Directory::Status Directory::read(char * fileNameBuffer, U32 bufSize) {
I64 dummy;
return this->read(fileNameBuffer, bufSize, dummy);
}
Directory::Status Directory::read(char * fileNameBuffer, U32 bufSize, I64& inode) {
FW_ASSERT(fileNameBuffer);
// make sure it has been opened
if (!this->isOpen()) {
return NOT_OPENED;
}
Status stat = OP_OK;
DIR* dir = reinterpret_cast<DIR*>(this->m_dir);
// Set errno to 0 so we know why we exited readdir
errno = 0;
struct dirent *direntData = nullptr;
while ((direntData = ::readdir(dir)) != nullptr) {
// Skip hidden files
if (direntData->d_name[0] != '.') {
strncpy(fileNameBuffer, direntData->d_name, bufSize);
inode = direntData->d_ino;
break;
}
}
if (direntData == nullptr) {
// loop ended because readdir failed, did it error or did we run out of files?
if(errno != 0) {
// Only error from readdir is EBADF
stat = OTHER_ERROR;
this->m_lastError = errno;
}
else {
stat = NO_MORE_FILES;
}
}
return stat;
}
bool Directory::isOpen() {
return this->m_dir > 0;
}
void Directory::close() {
if (this->isOpen()) {
DIR* dir = reinterpret_cast<DIR*>(this->m_dir);
(void)::closedir(dir);
}
this->m_dir = 0;
}
NATIVE_INT_TYPE Directory::getLastError() {
return this->m_lastError;
}
const char* Directory::getLastErrorString() {
return strerror(this->m_lastError);
}
}
| cpp |
fprime | data/projects/fprime/Os/Linux/InterruptLock.cpp | #include <Os/InterruptLock.hpp>
#include <Os/Mutex.hpp>
STATIC Os::Mutex intLockEmulator;
namespace Os {
InterruptLock::InterruptLock() : m_key(0) {}
InterruptLock::~InterruptLock() {}
void InterruptLock::lock() {
intLockEmulator.lock();
}
void InterruptLock::unLock() {
intLockEmulator.unLock();
}
}
| cpp |
fprime | data/projects/fprime/Os/Linux/WatchdogTimer.cpp | #include <Os/WatchdogTimer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Os {
WatchdogTimer::WatchdogTimer()
: m_handle(0),m_cb(nullptr),m_parameter(nullptr),m_timerTicks(0),m_timerMs(0)
{
}
WatchdogTimer::~WatchdogTimer() {
}
WatchdogTimer::WatchdogStatus WatchdogTimer::startTicks( I32 delayInTicks, WatchdogCb p_callback, void* parameter) {
return WATCHDOG_START_ERROR;
}
WatchdogTimer::WatchdogStatus WatchdogTimer::startMs( I32 delayInMs, WatchdogCb p_callback, void* parameter) {
return WATCHDOG_START_ERROR;
}
WatchdogTimer::WatchdogStatus WatchdogTimer::restart() {
return WATCHDOG_START_ERROR;
}
WatchdogTimer::WatchdogStatus WatchdogTimer::cancel() {
return WATCHDOG_CANCEL_ERROR;
}
void WatchdogTimer::expire() {
FW_ASSERT(m_cb != nullptr);
m_cb(m_parameter);
}
}
| cpp |
fprime | data/projects/fprime/Os/MacOs/IPCQueueStub.cpp | // ======================================================================
// \title Queue.cpp
// \author dinkel
// \brief Queue implementation using the pthread library. This is NOT
// an IPC queue. It is meant to be used between threads within
// the same address space.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Os/Pthreads/BufferQueue.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/IPCQueue.hpp>
#include <cerrno>
#include <pthread.h>
#include <cstdio>
#include <new>
namespace Os {
// A helper class which stores variables for the queue handle.
// The queue itself, a pthread condition variable, and pthread
// mutex are contained within this container class.
class QueueHandle {
public:
QueueHandle() {
int ret;
ret = pthread_cond_init(&this->queueNotEmpty, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_cond_init(&this->queueNotFull, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_mutex_init(&this->queueLock, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
}
~QueueHandle() {
(void) pthread_cond_destroy(&this->queueNotEmpty);
(void) pthread_cond_destroy(&this->queueNotFull);
(void) pthread_mutex_destroy(&this->queueLock);
}
bool create(NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
return queue.create(depth, msgSize);
}
BufferQueue queue;
pthread_cond_t queueNotEmpty;
pthread_cond_t queueNotFull;
pthread_mutex_t queueLock;
};
IPCQueue::IPCQueue() : Queue() {
}
Queue::QueueStatus IPCQueue::create(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
// Queue has already been created... remove it and try again:
if (nullptr != queueHandle) {
delete queueHandle;
queueHandle = nullptr;
}
// Create queue handle:
queueHandle = new(std::nothrow) QueueHandle;
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
if( !queueHandle->create(depth, msgSize) ) {
return QUEUE_UNINITIALIZED;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(queueHandle);
#if FW_QUEUE_REGISTRATION
if (this->s_queueRegistry) {
this->s_queueRegistry->regQueue(this);
}
#endif
return QUEUE_OK;
}
IPCQueue::~IPCQueue() {
// Clean up the queue handle:
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr != queueHandle) {
delete queueHandle;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(nullptr);
}
Queue::QueueStatus sendNonBlockIPCStub(QueueHandle* queueHandle, const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
NATIVE_INT_TYPE ret;
Queue::QueueStatus status = Queue::QUEUE_OK;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// Push item onto queue:
bool pushSucceeded = queue->push(buffer, size, priority);
if(pushSucceeded) {
// Push worked - wake up a thread that might be waiting on
// the other end of the queue:
ret = pthread_cond_signal(queueNotEmpty);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
}
else {
// Push failed - the queue is full:
status = Queue::QUEUE_FULL;
}
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return status;
}
Queue::QueueStatus sendBlockIPCStub(QueueHandle* queueHandle, const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
NATIVE_INT_TYPE ret;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// If the queue is full, wait until a message is taken off the queue:
while( queue->isFull() ) {
ret = pthread_cond_wait(queueNotFull, queueLock);
FW_ASSERT(ret == 0, errno);
}
// Push item onto queue:
bool pushSucceeded = queue->push(buffer, size, priority);
// The only reason push would not succeed is if the queue
// was full. Since we waited for the queue to NOT be full
// before sending on the queue, the push must have succeeded
// unless there was a programming error or a bit flip.
FW_ASSERT(pushSucceeded, pushSucceeded);
// Push worked - wake up a thread that might be waiting on
// the other end of the queue:
ret = pthread_cond_signal(queueNotEmpty);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return Queue::QUEUE_OK;
}
Queue::QueueStatus IPCQueue::send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block) {
(void) block; // Always non-blocking for now
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
BufferQueue* queue = &queueHandle->queue;
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
if (nullptr == buffer) {
return QUEUE_EMPTY_BUFFER;
}
if (size < 0 || static_cast<NATIVE_UINT_TYPE>(size) > queue->getMsgSize()) {
return QUEUE_SIZE_MISMATCH;
}
if( QUEUE_NONBLOCKING == block ) {
return sendNonBlockIPCStub(queueHandle, buffer, size, priority);
}
return sendBlockIPCStub(queueHandle, buffer, size, priority);
}
Queue::QueueStatus receiveNonBlockIPCStub(QueueHandle* queueHandle, U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
NATIVE_INT_TYPE ret;
NATIVE_UINT_TYPE size = static_cast<NATIVE_UINT_TYPE>(capacity);
NATIVE_INT_TYPE pri = 0;
Queue::QueueStatus status = Queue::QUEUE_OK;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// Get an item off of the queue:
bool popSucceeded = queue->pop(buffer, size, pri);
if(popSucceeded) {
// Pop worked - set the return size and priority:
actualSize = static_cast<NATIVE_INT_TYPE>(size);
priority = pri;
// Pop worked - wake up a thread that might be waiting on
// the send end of the queue:
ret = pthread_cond_signal(queueNotFull);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
}
else {
actualSize = 0;
if( size > static_cast<NATIVE_UINT_TYPE>(capacity) ) {
// The buffer capacity was too small!
status = Queue::QUEUE_SIZE_MISMATCH;
}
else if( size == 0 ) {
// The queue is empty:
status = Queue::QUEUE_NO_MORE_MSGS;
}
else {
// If this happens, a programming error or bit flip occurred:
FW_ASSERT(0);
}
}
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return status;
}
Queue::QueueStatus receiveBlockIPCStub(QueueHandle* queueHandle, U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
NATIVE_INT_TYPE ret;
NATIVE_UINT_TYPE size = capacity;
NATIVE_INT_TYPE pri = 0;
Queue::QueueStatus status = Queue::QUEUE_OK;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// If the queue is empty, wait until a message is put on the queue:
while( queue->isEmpty() ) {
ret = pthread_cond_wait(queueNotEmpty, queueLock);
FW_ASSERT(ret == 0, errno);
}
// Get an item off of the queue:
bool popSucceeded = queue->pop(buffer, size, pri);
if(popSucceeded) {
// Pop worked - set the return size and priority:
actualSize = static_cast<NATIVE_INT_TYPE>(size);
priority = pri;
// Pop worked - wake up a thread that might be waiting on
// the send end of the queue:
ret = pthread_cond_signal(queueNotFull);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
}
else {
actualSize = 0;
if( size > static_cast<NATIVE_UINT_TYPE>(capacity) ) {
// The buffer capacity was too small!
status = Queue::QUEUE_SIZE_MISMATCH;
}
else {
// If this happens, a programming error or bit flip occurred:
// The only reason a pop should fail is if the user's buffer
// was too small.
FW_ASSERT(0);
}
}
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return status;
}
Queue::QueueStatus IPCQueue::receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block) {
if( reinterpret_cast<POINTER_CAST>(nullptr) == this->m_handle ) {
return QUEUE_UNINITIALIZED;
}
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
// Do not need to check the upper bound of capacity, We don't care
// how big the user's buffer is.. as long as it's big enough.
if (capacity < 0) {
return QUEUE_SIZE_MISMATCH;
}
if( QUEUE_NONBLOCKING == block ) {
return receiveNonBlockIPCStub(queueHandle, buffer, capacity, actualSize, priority);
}
return receiveBlockIPCStub(queueHandle, buffer, capacity, actualSize, priority);
}
NATIVE_INT_TYPE IPCQueue::getNumMsgs() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getCount();
}
NATIVE_INT_TYPE IPCQueue::getMaxMsgs() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getMaxCount();
}
NATIVE_INT_TYPE IPCQueue::getQueueSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getDepth();
}
NATIVE_INT_TYPE IPCQueue::getMsgSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getMsgSize();
}
}
| cpp |
fprime | data/projects/fprime/Os/MacOs/SystemResources.cpp | // ======================================================================
// \title MacOs/SystemResources.cpp
// \author mstarch
// \brief hpp file for SystemResources component implementation class
//
// \copyright
// Copyright 2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/mach_init.h>
#include <mach/mach_types.h>
#include <mach/message.h>
#include <Fw/Types/Assert.hpp>
#include <Os/SystemResources.hpp>
namespace Os {
/**
* \brief reads macOS virtual memory statistics for memory calculation
*
* Queries the macOS kernel for virtual memory information. These items are returned in units of page-size and are
* then converted back into bytes.
*
* Thanks to: https://stackoverflow.com/questions/8782228/retrieve-ram-info-on-a-mac
*
* \param used: used memory in bytes
* \param total: total memory in bytes
* \return: kern_return_t with success/failure straight from the kernel
*/
kern_return_t vm_stat_helper(FwSizeType& used, FwSizeType& total) {
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
vm_statistics_data_t vmstat;
vm_size_t vmsize;
kern_return_t stat1 = host_statistics(mach_host_self(), HOST_VM_INFO, reinterpret_cast<host_info_t>(&vmstat), &count);
kern_return_t stat2 = host_page_size(mach_host_self(), &vmsize);
if (KERN_SUCCESS == stat1 and KERN_SUCCESS == stat2) {
// Wired (permanently in RAM), active (recently used), and inactive (not recently used) pages
used = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count;
total = used + vmstat.free_count;
// Pages to totals
used *= vmsize;
total *= vmsize;
}
return (stat1 == KERN_SUCCESS) ? stat2 : stat1;
}
/**
* \brief helper around raw CPU capture API
*
* Calls for the CPU information from the machine, improving readability in cpu_by_index
*
* \param cpu_load_info: filled with CPU data
* \param cpu_count: filled with CPU count
*
* \return success/failure using kern_return_t
*/
kern_return_t cpu_data_helper(processor_cpu_load_info_t& cpu_load_info, U32& cpu_count) {
mach_msg_type_number_t processor_msg_count;
kern_return_t stat = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count,
reinterpret_cast<processor_info_array_t*>(&cpu_load_info), &processor_msg_count);
return stat;
}
/**
* \brief Query for a single CPU's ticks information
*
* Queries all CPU information but only deals with a single CPU's output. This is done because the load average is
* tracked sample to sample and the call pattern is cpu0, cpu1, ..., cpu last, wait for sample window, cpu0, ... and
* thus each call should update one CPU's sample or only the last cpu will have the benefit of the sampling window.
*
* \param cpu_index: index of current CPU being queried
* \param used: filled with CPU's used ticks count
* \param total: filled with CPU's total ticks
*
* \return success/failure using kern_return_t
*/
kern_return_t cpu_by_index(U32 cpu_index, FwSizeType& used, FwSizeType& total) {
processor_cpu_load_info_t cpu_load_info;
U32 cpu_count = 0;
kern_return_t stat = cpu_data_helper(cpu_load_info, cpu_count);
// Failure for CPU index
if (cpu_count <= cpu_index) {
stat = KERN_FAILURE;
} else if (KERN_SUCCESS == stat) {
FW_ASSERT(cpu_count > cpu_index, cpu_count, cpu_index); // Will fail if the CPU count changes while running
processor_cpu_load_info per_cpu_info = cpu_load_info[(cpu_count > cpu_index) ? cpu_index : 0];
// Total the ticks across the different states: idle, system, user, etc...
total = 0;
for (U32 i = 0; i < CPU_STATE_MAX; i++) {
total += per_cpu_info.cpu_ticks[i];
}
used = total - per_cpu_info.cpu_ticks[CPU_STATE_IDLE];
}
return stat;
}
SystemResources::SystemResourcesStatus SystemResources::getCpuCount(U32& cpuCount) {
processor_cpu_load_info_t cpu_load_info;
if (KERN_SUCCESS == cpu_data_helper(cpu_load_info, cpuCount)) {
return SYSTEM_RESOURCES_OK;
}
cpuCount = 0;
return SYSTEM_RESOURCES_ERROR;
}
SystemResources::SystemResourcesStatus SystemResources::getCpuTicks(CpuTicks& cpu_ticks, U32 cpu_index) {
// Fallbacks in case of error
cpu_ticks.used = 1;
cpu_ticks.total = 1;
kern_return_t stat = cpu_by_index(cpu_index, cpu_ticks.used, cpu_ticks.total);
return (stat == KERN_SUCCESS) ? SYSTEM_RESOURCES_OK : SYSTEM_RESOURCES_ERROR;
}
SystemResources::SystemResourcesStatus SystemResources::getMemUtil(MemUtil& memory_util) {
// Call out VM helper
if (KERN_SUCCESS == vm_stat_helper(memory_util.used, memory_util.total)) {
return SYSTEM_RESOURCES_OK;
}
// Force something sensible, while preventing divide by zero
memory_util.total = 1;
memory_util.used = 1;
return SYSTEM_RESOURCES_ERROR;
}
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/X86/IntervalTimer.cpp | /**
* X86/IntervalTimer.cpp:
*
* This file supports the core functions of the IntervalTimer for X86 implementations that support
* the following specification for the "RawTime" object:
*
* RawTime.lower = nanoseconds of time
* RawTime.upper = seconds of time.
*
* Any implementation that fills "RawTime" via this specification can use these basic implementations.
*
* Note: this file is cloned from the original Linux implementation.
*/
#include <Os/IntervalTimer.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstring>
namespace Os {
// Adapted from: http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
// should be t1In - t2In
U32 IntervalTimer::getDiffUsec(const RawTime& t1In, const RawTime& t2In) {
RawTime result = {t1In.upper - t2In.upper, 0};
if (t1In.lower < t2In.lower) {
result.upper -= 1; // subtract nsec carry to seconds
result.lower = t1In.lower + (1000000000 - t2In.lower);
} else {
result.lower = t1In.lower - t2In.lower;
}
return (result.upper * 1000000) + (result.lower / 1000);
}
}
| cpp |
fprime | data/projects/fprime/Os/Models/Models.hpp | // ======================================================================
// \title Os/Models/Models.hpp
// \brief header used to validate Os/Models before use
// ======================================================================
#include "Os/Models/FileStatusEnumAc.hpp"
#include "Os/Models/FileModeEnumAc.hpp"
#ifndef OS_MODELS_MODELS_HPP
#define OS_MODELS_MODELS_HPP
// Check consistency of every constant in the Os::File::Status enum
static_assert(static_cast<FwIndexType>(Os::File::Status::MAX_STATUS) ==
static_cast<FwIndexType>(Os::FileStatus::NUM_CONSTANTS),
"File status and FPP shadow enum have inconsistent number of values");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::OP_OK) == Os::FileStatus::T::OP_OK,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::DOESNT_EXIST) == Os::FileStatus::T::DOESNT_EXIST,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::NO_SPACE) == Os::FileStatus::T::NO_SPACE,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::NO_PERMISSION) == Os::FileStatus::T::NO_PERMISSION,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::BAD_SIZE) == Os::FileStatus::T::BAD_SIZE,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::NOT_OPENED) == Os::FileStatus::T::NOT_OPENED,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::FILE_EXISTS) == Os::FileStatus::T::FILE_EXISTS,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::NOT_SUPPORTED) == Os::FileStatus::T::NOT_SUPPORTED,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::INVALID_MODE) == Os::FileStatus::T::INVALID_MODE,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::INVALID_ARGUMENT) == Os::FileStatus::T::INVALID_ARGUMENT,
"File status and FPP shadow enum do not match");
static_assert(static_cast<Os::FileStatus::T>(Os::File::Status::OTHER_ERROR) == Os::FileStatus::T::OTHER_ERROR,
"File status and FPP shadow enum do not match");
// Check consistency of every constant in the Os::File::Mode enum
static_assert(static_cast<FwIndexType>(Os::File::Mode::MAX_OPEN_MODE) ==
static_cast<FwIndexType>(Os::FileMode::NUM_CONSTANTS),
"File mode and FPP shadow enum have inconsistent number of values");
static_assert(static_cast<Os::FileMode::T>(Os::File::Mode::OPEN_NO_MODE) == Os::FileMode::T::OPEN_NO_MODE,
"File mode and FPP shadow enum do not match");
static_assert(static_cast<Os::FileMode::T>(Os::File::Mode::OPEN_READ) == Os::FileMode::T::OPEN_READ,
"File mode and FPP shadow enum do not match");
static_assert(static_cast<Os::FileMode::T>(Os::File::Mode::OPEN_CREATE) == Os::FileMode::T::OPEN_CREATE,
"File mode and FPP shadow enum do not match");
static_assert(static_cast<Os::FileMode::T>(Os::File::Mode::OPEN_WRITE) == Os::FileMode::T::OPEN_WRITE,
"File mode and FPP shadow enum do not match");
static_assert(static_cast<Os::FileMode::T>(Os::File::Mode::OPEN_SYNC_WRITE) == Os::FileMode::T::OPEN_SYNC_WRITE,
"File mode and FPP shadow enum do not match");
static_assert(static_cast<Os::FileMode::T>(Os::File::Mode::OPEN_APPEND) == Os::FileMode::T::OPEN_APPEND,
"File mode and FPP shadow enum do not Mode");
#endif // OS_MODELS_MODELS_HPP
| hpp |
fprime | data/projects/fprime/Os/Pthreads/BufferQueueCommon.cpp | // ======================================================================
// \title BufferQueueCommon.hpp
// \author dinkel
// \brief This file implements some of the methods for the generic
// buffer queue data structure declared in BufferQueue.hpp that
// are common amongst different queue implementations.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Os/Pthreads/BufferQueue.hpp"
#include <Fw/Types/Assert.hpp>
#include <cstring>
namespace Os {
/////////////////////////////////////////////////////
// Class functions:
/////////////////////////////////////////////////////
BufferQueue::BufferQueue() {
// Set member variables:
this->m_queue = nullptr;
this->m_msgSize = 0;
this->m_depth = 0;
this->m_count = 0;
this->m_maxCount = 0;
}
BufferQueue::~BufferQueue() {
this->finalize();
}
bool BufferQueue::create(NATIVE_UINT_TYPE depth, NATIVE_UINT_TYPE msgSize) {
// Queue is already set up. destroy it and try again:
if (nullptr != this->m_queue) {
this->finalize();
}
FW_ASSERT(nullptr == this->m_queue, reinterpret_cast<POINTER_CAST>(this->m_queue));
// Set member variables:
this->m_msgSize = msgSize;
this->m_depth = depth;
return this->initialize(depth, msgSize);
}
bool BufferQueue::push(const U8* buffer, NATIVE_UINT_TYPE size, NATIVE_INT_TYPE priority) {
FW_ASSERT(size <= this->m_msgSize);
if( this->isFull() ) {
return false;
}
// Enqueue the data:
bool ret = enqueue(buffer, size, priority);
if( !ret ) {
return false;
}
// Increment count:
++this->m_count;
if( this->m_count > this->m_maxCount ) {
this->m_maxCount = this->m_count;
}
return true;
}
bool BufferQueue::pop(U8* buffer, NATIVE_UINT_TYPE& size, NATIVE_INT_TYPE &priority) {
if( this->isEmpty() ) {
size = 0;
return false;
}
// Dequeue the data:
bool ret = dequeue(buffer, size, priority);
if( !ret ) {
return false;
}
// Decrement count:
--this->m_count;
return true;
}
bool BufferQueue::isFull() {
return (this->m_count == this->m_depth);
}
bool BufferQueue::isEmpty() {
return (this->m_count == 0);
}
NATIVE_UINT_TYPE BufferQueue::getCount() {
return this->m_count;
}
NATIVE_UINT_TYPE BufferQueue::getMaxCount() {
return this->m_maxCount;
}
NATIVE_UINT_TYPE BufferQueue::getMsgSize() {
return this->m_msgSize;
}
NATIVE_UINT_TYPE BufferQueue::getDepth() {
return this->m_depth;
}
NATIVE_UINT_TYPE BufferQueue::getBufferIndex(NATIVE_INT_TYPE index) {
return (index % this->m_depth) * (sizeof(NATIVE_INT_TYPE) + this->m_msgSize);
}
void BufferQueue::enqueueBuffer(const U8* buffer, NATIVE_UINT_TYPE size, U8* data, NATIVE_UINT_TYPE index) {
// Copy size of buffer onto queue:
void* dest = &data[index];
void* ptr = memcpy(dest, &size, sizeof(size));
FW_ASSERT(ptr == dest);
// Copy buffer onto queue:
index += sizeof(size);
dest = &data[index];
ptr = memcpy(dest, buffer, size);
FW_ASSERT(ptr == dest);
}
bool BufferQueue::dequeueBuffer(U8* buffer, NATIVE_UINT_TYPE& size, U8* data, NATIVE_UINT_TYPE index) {
// Copy size of buffer from queue:
NATIVE_UINT_TYPE storedSize;
void* source = &data[index];
void* ptr = memcpy(&storedSize, source, sizeof(size));
FW_ASSERT(ptr == &storedSize);
// If the buffer passed in is not big
// enough, return false, and pass out
// the size of the message:
if(storedSize > size){
size = storedSize;
return false;
}
size = storedSize;
// Copy buffer from queue:
index += sizeof(size);
source = &data[index];
ptr = memcpy(buffer, source, storedSize);
FW_ASSERT(ptr == buffer);
return true;
}
}
| cpp |
fprime | data/projects/fprime/Os/Pthreads/Queue.cpp | // ======================================================================
// \title Queue.cpp
// \author dinkel
// \brief Queue implementation using the pthread library. This is NOT
// an IPC queue. It is meant to be used between threads within
// the same address space.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Os/Pthreads/BufferQueue.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/Queue.hpp>
#include <cerrno>
#include <pthread.h>
#include <cstdio>
#include <new>
namespace Os {
// A helper class which stores variables for the queue handle.
// The queue itself, a pthread condition variable, and pthread
// mutex are contained within this container class.
class QueueHandle {
public:
QueueHandle() {
int ret;
ret = pthread_cond_init(&this->queueNotEmpty, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_cond_init(&this->queueNotFull, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_mutex_init(&this->queueLock, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
}
~QueueHandle() {
(void) pthread_cond_destroy(&this->queueNotEmpty);
(void) pthread_cond_destroy(&this->queueNotFull);
(void) pthread_mutex_destroy(&this->queueLock);
}
bool create(NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
return queue.create(depth, msgSize);
}
BufferQueue queue;
pthread_cond_t queueNotEmpty;
pthread_cond_t queueNotFull;
pthread_mutex_t queueLock;
};
Queue::Queue() :
m_handle(reinterpret_cast<POINTER_CAST>(nullptr)) {
}
Queue::QueueStatus Queue::createInternal(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
// Queue has already been created... remove it and try again:
if (nullptr != queueHandle) {
delete queueHandle;
queueHandle = nullptr;
}
// Create queue handle:
queueHandle = new(std::nothrow) QueueHandle;
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
if( !queueHandle->create(depth, msgSize) ) {
return QUEUE_UNINITIALIZED;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(queueHandle);
#if FW_QUEUE_REGISTRATION
if (this->s_queueRegistry) {
this->s_queueRegistry->regQueue(this);
}
#endif
return QUEUE_OK;
}
Queue::~Queue() {
// Clean up the queue handle:
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr != queueHandle) {
delete queueHandle;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(nullptr);
}
Queue::QueueStatus sendNonBlock(QueueHandle* queueHandle, const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
NATIVE_INT_TYPE ret;
Queue::QueueStatus status = Queue::QUEUE_OK;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// Push item onto queue:
bool pushSucceeded = queue->push(buffer, size, priority);
if(pushSucceeded) {
// Push worked - wake up a thread that might be waiting on
// the other end of the queue:
ret = pthread_cond_signal(queueNotEmpty);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
}
else {
// Push failed - the queue is full:
status = Queue::QUEUE_FULL;
}
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return status;
}
Queue::QueueStatus sendBlock(QueueHandle* queueHandle, const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
NATIVE_INT_TYPE ret;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// If the queue is full, wait until a message is taken off the queue:
while( queue->isFull() ) {
ret = pthread_cond_wait(queueNotFull, queueLock);
FW_ASSERT(ret == 0, errno);
}
// Push item onto queue:
bool pushSucceeded = queue->push(buffer, size, priority);
// The only reason push would not succeed is if the queue
// was full. Since we waited for the queue to NOT be full
// before sending on the queue, the push must have succeeded
// unless there was a programming error or a bit flip.
FW_ASSERT(pushSucceeded, pushSucceeded);
// Push worked - wake up a thread that might be waiting on
// the other end of the queue:
ret = pthread_cond_signal(queueNotEmpty);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return Queue::QUEUE_OK;
}
Queue::QueueStatus Queue::send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block) {
(void) block; // Always non-blocking for now
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
BufferQueue* queue = &queueHandle->queue;
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
if (nullptr == buffer) {
return QUEUE_EMPTY_BUFFER;
}
if (size < 0 || static_cast<NATIVE_UINT_TYPE>(size) > queue->getMsgSize()) {
return QUEUE_SIZE_MISMATCH;
}
if( QUEUE_NONBLOCKING == block ) {
return sendNonBlock(queueHandle, buffer, size, priority);
}
return sendBlock(queueHandle, buffer, size, priority);
}
Queue::QueueStatus receiveNonBlock(QueueHandle* queueHandle, U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
NATIVE_INT_TYPE ret;
NATIVE_UINT_TYPE size = static_cast<NATIVE_UINT_TYPE>(capacity);
NATIVE_INT_TYPE pri = 0;
Queue::QueueStatus status = Queue::QUEUE_OK;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// Get an item off of the queue:
bool popSucceeded = queue->pop(buffer, size, pri);
if(popSucceeded) {
// Pop worked - set the return size and priority:
actualSize = static_cast<NATIVE_INT_TYPE>(size);
priority = pri;
// Pop worked - wake up a thread that might be waiting on
// the send end of the queue:
ret = pthread_cond_signal(queueNotFull);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
}
else {
actualSize = 0;
if( size > static_cast<NATIVE_UINT_TYPE>(capacity) ) {
// The buffer capacity was too small!
status = Queue::QUEUE_SIZE_MISMATCH;
}
else if( size == 0 ) {
// The queue is empty:
status = Queue::QUEUE_NO_MORE_MSGS;
}
else {
// If this happens, a programming error or bit flip occurred:
FW_ASSERT(0);
}
}
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return status;
}
Queue::QueueStatus receiveBlock(QueueHandle* queueHandle, U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority) {
BufferQueue* queue = &queueHandle->queue;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
pthread_mutex_t* queueLock = &queueHandle->queueLock;
NATIVE_INT_TYPE ret;
NATIVE_UINT_TYPE size = static_cast<NATIVE_UINT_TYPE>(capacity);
NATIVE_INT_TYPE pri = 0;
Queue::QueueStatus status = Queue::QUEUE_OK;
////////////////////////////////
// Locked Section
///////////////////////////////
ret = pthread_mutex_lock(queueLock);
FW_ASSERT(ret == 0, errno);
///////////////////////////////
// If the queue is empty, wait until a message is put on the queue:
while( queue->isEmpty() ) {
ret = pthread_cond_wait(queueNotEmpty, queueLock);
FW_ASSERT(ret == 0, errno);
}
// Get an item off of the queue:
bool popSucceeded = queue->pop(buffer, size, pri);
if(popSucceeded) {
// Pop worked - set the return size and priority:
actualSize = static_cast<NATIVE_INT_TYPE>(size);
priority = pri;
// Pop worked - wake up a thread that might be waiting on
// the send end of the queue:
ret = pthread_cond_signal(queueNotFull);
FW_ASSERT(ret == 0, errno); // If this fails, something horrible happened.
}
else {
actualSize = 0;
if( size > static_cast<NATIVE_UINT_TYPE>(capacity) ) {
// The buffer capacity was too small!
status = Queue::QUEUE_SIZE_MISMATCH;
}
else {
// If this happens, a programming error or bit flip occurred:
// The only reason a pop should fail is if the user's buffer
// was too small.
FW_ASSERT(0);
}
}
///////////////////////////////
ret = pthread_mutex_unlock(queueLock);
FW_ASSERT(ret == 0, errno);
////////////////////////////////
///////////////////////////////
return status;
}
Queue::QueueStatus Queue::receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block) {
if( reinterpret_cast<POINTER_CAST>(nullptr) == this->m_handle ) {
return QUEUE_UNINITIALIZED;
}
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
// Do not need to check the upper bound of capacity, We don't care
// how big the user's buffer is.. as long as it's big enough.
if (capacity < 0) {
return QUEUE_SIZE_MISMATCH;
}
if( QUEUE_NONBLOCKING == block ) {
return receiveNonBlock(queueHandle, buffer, capacity, actualSize, priority);
}
return receiveBlock(queueHandle, buffer, capacity, actualSize, priority);
}
NATIVE_INT_TYPE Queue::getNumMsgs() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getCount();
}
NATIVE_INT_TYPE Queue::getMaxMsgs() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getMaxCount();
}
NATIVE_INT_TYPE Queue::getQueueSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getDepth();
}
NATIVE_INT_TYPE Queue::getMsgSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr == queueHandle) {
return 0;
}
BufferQueue* queue = &queueHandle->queue;
return queue->getMsgSize();
}
}
| cpp |
fprime | data/projects/fprime/Os/Pthreads/BufferQueue.hpp | // ======================================================================
// \title BufferQueue.hpp
// \author dinkel
// \brief A generic buffer queue data structure.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef OS_PTHREADS_BUFFER_QUEUE_HPP
#define OS_PTHREADS_BUFFER_QUEUE_HPP
#include <FpConfig.hpp>
// This is a generic buffer queue interface.
namespace Os {
//! \class BufferQueue
//! \brief A generic buffer queue data structure
//!
//! This is a generic queue interface that can be implemented using a variety
//! of different data structures
class BufferQueue {
// Public interface:
public:
//! \brief BufferQueue constructor
//!
//! Create a BufferQueue object.
//!
BufferQueue();
//! \brief BufferQueue deconstructor
//!
//! Deallocate the queue.
//!
~BufferQueue();
//! \brief BufferQueue creation
//!
//! Create a queue with buffer allocated at initialization. Messages
//! will have a maximum size "msgSize" and the buffer with be "depth"
//! elements deep.
//!
//! \param depth the maximum number of buffers to store on queue
//! \param msgSize the maximum size of a buffer that can be stored on
//! the queue
//!
bool create(NATIVE_UINT_TYPE depth, NATIVE_UINT_TYPE msgSize);
//! \brief push an item onto the queue
//!
//! Push an item onto the queue with the specified size and priority
//!
//! \param buffer the buffer to push onto the queue
//! \param size the size of buffer
//! \param priority the priority of the buffer on the queue (higher
//! priority means that the buffer will be popped off sooner.
//!
bool push(const U8* buffer, NATIVE_UINT_TYPE size, NATIVE_INT_TYPE priority);
//! \brief pop an item off the queue
//!
//! Pull an item off of the queue and put it in "buffer" which is of size
//! "size". Returns the size of the pulled item in "size" and the priority
//! of the pulled item in "priority" on a success.
//!
//! \param buffer the buffer to fill from the queue
//! \param size the size of buffer. The size of the popped buffer
//! will also be returned in this variable. It is used as both input
//! and output
//! \param priority the priority of the buffer popped off the queue
//!
bool pop(U8* buffer, NATIVE_UINT_TYPE& size, NATIVE_INT_TYPE &priority);
//! \brief check if the queue is full
//!
//! Is the queue full?
//!
bool isFull();
//! \brief check if the queue is empty
//!
//! Is the queue empty?
//!
bool isEmpty();
//! \brief Get the current number of items on the queue
//!
//! Get the number of items on the queue.
//!
NATIVE_UINT_TYPE getCount();
//! \brief Get the maximum number of items seen on the queue
//!
//! Get the maximum number of items that have been on the queue since the
//! instantiation of the queue. This is a "high water mark" count.
//!
NATIVE_UINT_TYPE getMaxCount();
//! \brief Get the maximum message size
//!
//! Get the maximum message size allowed on the queue
//!
NATIVE_UINT_TYPE getMsgSize();
//! \brief Get the queue depths
//!
//! Get the maximum number of messages allowed on the queue
//!
NATIVE_UINT_TYPE getDepth();
// Internal member functions:
private:
// Initialize data structures necessary for the queue:
bool initialize(NATIVE_UINT_TYPE depth, NATIVE_UINT_TYPE msgSize);
// Destroy queue data structures:
void finalize();
// Enqueue a message into the data structure:
bool enqueue(const U8* buffer, NATIVE_UINT_TYPE size, NATIVE_INT_TYPE priority);
// Dequeue a message from the data structure:
bool dequeue(U8* buffer, NATIVE_UINT_TYPE& size, NATIVE_INT_TYPE &priority);
// Low level enqueue which does the copying onto the queue:
void enqueueBuffer(const U8* buffer, NATIVE_UINT_TYPE size, U8* data, NATIVE_UINT_TYPE index);
// Low level dequeue which does the copying from the queue:
bool dequeueBuffer(U8* buffer, NATIVE_UINT_TYPE& size, U8* data, NATIVE_UINT_TYPE index);
// Helper function to get the buffer index into the queue for particular
// queue index.
NATIVE_UINT_TYPE getBufferIndex(NATIVE_INT_TYPE index);
// Member variables:
void* m_queue; // The queue can be implemented in various ways
NATIVE_UINT_TYPE m_msgSize; // Max size of message on the queue
NATIVE_UINT_TYPE m_depth; // Max number of messages on the queue
NATIVE_UINT_TYPE m_count; // Current number of messages on the queue
NATIVE_UINT_TYPE m_maxCount; // Maximum number of messages ever seen on the queue
};
}
#endif // OS_PTHREADS_BUFFER_QUEUE_HPP
| hpp |
fprime | data/projects/fprime/Os/Pthreads/PriorityBufferQueue.cpp | // ======================================================================
// \title PriorityBufferQueue.hpp
// \author dinkel
// \brief An implementation of BufferQueue which uses a stable max heap
// data structure for the queue. Items of highest priority will
// be popped off of the queue first. Items of equal priority will
// be popped off the queue in FIFO order.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Os/Pthreads/BufferQueue.hpp"
#include "Os/Pthreads/MaxHeap/MaxHeap.hpp"
#include <Fw/Types/Assert.hpp>
#include <cstring>
#include <cstdio>
#include <new>
// This is a priority queue implementation implemented using a stable max heap.
// Elements pushed onto the queue will be popped off in priority order.
// Elements of the same priority will be popped off in FIFO order.
namespace Os {
/////////////////////////////////////////////////////
// Queue handler:
/////////////////////////////////////////////////////
struct PriorityQueue {
MaxHeap* heap;
U8* data;
NATIVE_UINT_TYPE* indexes;
NATIVE_UINT_TYPE startIndex;
NATIVE_UINT_TYPE stopIndex;
};
/////////////////////////////////////////////////////
// Helper functions:
/////////////////////////////////////////////////////
NATIVE_UINT_TYPE checkoutIndex(PriorityQueue* pQueue, NATIVE_UINT_TYPE depth) {
NATIVE_UINT_TYPE* indexes = pQueue->indexes;
// Get an available index from the index pool:
NATIVE_UINT_TYPE index = indexes[pQueue->startIndex % depth];
++pQueue->startIndex;
NATIVE_UINT_TYPE diff = pQueue->stopIndex - pQueue->startIndex;
FW_ASSERT(diff <= depth, diff, depth, pQueue->stopIndex, pQueue->startIndex);
return index;
}
void returnIndex(PriorityQueue* pQueue, NATIVE_UINT_TYPE depth, NATIVE_UINT_TYPE index) {
NATIVE_UINT_TYPE* indexes = pQueue->indexes;
// Return the index back to the index pool:
indexes[pQueue->stopIndex % depth] = index;
++pQueue->stopIndex;
NATIVE_UINT_TYPE diff = pQueue->stopIndex - pQueue->startIndex;
FW_ASSERT(diff <= depth, diff, depth, pQueue->stopIndex, pQueue->startIndex);
}
/////////////////////////////////////////////////////
// Class functions:
/////////////////////////////////////////////////////
bool BufferQueue::initialize(NATIVE_UINT_TYPE depth, NATIVE_UINT_TYPE msgSize) {
// Create the priority queue data structure on the heap:
MaxHeap* heap = new(std::nothrow) MaxHeap;
if (nullptr == heap) {
return false;
}
if( !heap->create(depth) ) {
delete heap;
return false;
}
U8* data = new(std::nothrow) U8[depth*(sizeof(msgSize) + msgSize)];
if (nullptr == data) {
delete heap;
return false;
}
NATIVE_UINT_TYPE* indexes = new(std::nothrow) NATIVE_UINT_TYPE[depth];
if (nullptr == indexes) {
delete heap;
delete[] data;
return false;
}
for(NATIVE_UINT_TYPE ii = 0; ii < depth; ++ii) {
indexes[ii] = getBufferIndex(ii);
}
PriorityQueue* priorityQueue = new(std::nothrow) PriorityQueue;
if (nullptr == priorityQueue) {
delete heap;
delete[] data;
delete[] indexes;
return false;
}
priorityQueue->heap = heap;
priorityQueue->data = data;
priorityQueue->indexes = indexes;
priorityQueue->startIndex = 0;
priorityQueue->stopIndex = depth;
this->m_queue = priorityQueue;
return true;
}
void BufferQueue::finalize() {
PriorityQueue* pQueue = static_cast<PriorityQueue*>(this->m_queue);
if (nullptr != pQueue)
{
MaxHeap* heap = pQueue->heap;
if (nullptr != heap) {
delete heap;
}
U8* data = pQueue->data;
if (nullptr != data) {
delete [] data;
}
NATIVE_UINT_TYPE* indexes = pQueue->indexes;
if (nullptr != indexes)
{
delete [] indexes;
}
delete pQueue;
}
this->m_queue = nullptr;
}
bool BufferQueue::enqueue(const U8* buffer, NATIVE_UINT_TYPE size, NATIVE_INT_TYPE priority) {
// Extract queue handle variables:
PriorityQueue* pQueue = static_cast<PriorityQueue*>(this->m_queue);
MaxHeap* heap = pQueue->heap;
U8* data = pQueue->data;
// Get an available data index:
NATIVE_UINT_TYPE index = checkoutIndex(pQueue, this->m_depth);
// Insert the data into the heap:
bool ret = heap->push(priority, index);
FW_ASSERT(ret, ret);
// Store the buffer to the queue:
this->enqueueBuffer(buffer, size, data, index);
return true;
}
bool BufferQueue::dequeue(U8* buffer, NATIVE_UINT_TYPE& size, NATIVE_INT_TYPE &priority) {
// Extract queue handle variables:
PriorityQueue* pQueue = static_cast<PriorityQueue*>(this->m_queue);
MaxHeap* heap = pQueue->heap;
U8* data = pQueue->data;
// Get the highest priority data from the heap:
NATIVE_UINT_TYPE index = 0;
bool ret = heap->pop(priority, index);
FW_ASSERT(ret, ret);
ret = this->dequeueBuffer(buffer, size, data, index);
if(!ret) {
// The dequeue failed, so push the popped
// value back on the heap.
ret = heap->push(priority, index);
FW_ASSERT(ret, ret);
return false;
}
// Return the index to the available indexes:
returnIndex(pQueue, this->m_depth, index);
return true;
}
}
| cpp |
fprime | data/projects/fprime/Os/Pthreads/FIFOBufferQueue.cpp | // ======================================================================
// \title FIFOBufferQueue.hpp
// \author dinkel
// \brief An implementation of BufferQueue which uses a FIFO data
// structure for the queue. Priority is ignored.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Os/Pthreads/BufferQueue.hpp"
#include <Fw/Types/Assert.hpp>
#include <cstring>
#include <new>
// This is a simple FIFO queue implementation which ignores priority
namespace Os {
/////////////////////////////////////////////////////
// Queue handler:
/////////////////////////////////////////////////////
struct FIFOQueue {
U8* data;
NATIVE_UINT_TYPE head;
NATIVE_UINT_TYPE tail;
};
/////////////////////////////////////////////////////
// Class functions:
/////////////////////////////////////////////////////
bool BufferQueue::initialize(NATIVE_UINT_TYPE depth, NATIVE_UINT_TYPE msgSize) {
U8* data = new(std::nothrow) U8[depth*(sizeof(msgSize) + msgSize)];
if (nullptr == data) {
return false;
}
FIFOQueue* fifoQueue = new(std::nothrow) FIFOQueue;
if (nullptr == fifoQueue) {
return false;
}
fifoQueue->data = data;
fifoQueue->head = 0;
fifoQueue->tail = 0;
this->m_queue = fifoQueue;
return true;
}
void BufferQueue::finalize() {
FIFOQueue* fQueue = static_cast<FIFOQueue*>(this->m_queue);
if (nullptr != fQueue)
{
U8* data = fQueue->data;
if (nullptr != data) {
delete [] data;
}
delete fQueue;
}
this->m_queue = nullptr;
}
bool BufferQueue::enqueue(const U8* buffer, NATIVE_UINT_TYPE size, NATIVE_INT_TYPE priority) {
(void) priority;
FIFOQueue* fQueue = static_cast<FIFOQueue*>(this->m_queue);
U8* data = fQueue->data;
// Store the buffer to the queue:
NATIVE_UINT_TYPE index = getBufferIndex(fQueue->tail);
this->enqueueBuffer(buffer, size, data, index);
// Increment tail of fifo:
++fQueue->tail;
return true;
}
bool BufferQueue::dequeue(U8* buffer, NATIVE_UINT_TYPE& size, NATIVE_INT_TYPE &priority) {
(void) priority;
FIFOQueue* fQueue = static_cast<FIFOQueue*>(this->m_queue);
U8* data = fQueue->data;
// Get the buffer from the queue:
NATIVE_UINT_TYPE index = getBufferIndex(fQueue->head);
bool ret = this->dequeueBuffer(buffer, size, data, index);
if(!ret) {
return false;
}
// Increment head of fifo:
++fQueue->head;
return true;
}
}
| cpp |
fprime | data/projects/fprime/Os/Pthreads/MaxHeap/MaxHeap.cpp | // ======================================================================
// \title MaxHeap.cpp
// \author dinkel
// \brief An implementation of a stable max heap data structure. Items
// popped off the heap are guaranteed to be in order of decreasing
// "value" (max removed first). Items of equal "value" will be
// popped off in FIFO order. The performance of both push and pop
// is O(log(n)).
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Os/Pthreads/MaxHeap/MaxHeap.hpp"
#include <FpConfig.hpp>
#include "Fw/Types/Assert.hpp"
#include <Fw/Logger/Logger.hpp>
#include <new>
#include <cstdio>
// Macros for traversing the heap:
#define LCHILD(x) (2 * x + 1)
#define RCHILD(x) (2 * x + 2)
#define PARENT(x) ((x - 1) / 2)
namespace Os {
MaxHeap::MaxHeap() {
// Initialize the heap:
this->m_capacity = 0;
this->m_heap = nullptr;
this->m_size = 0;
this->m_order = 0;
}
MaxHeap::~MaxHeap() {
delete [] this->m_heap;
this->m_heap = nullptr;
}
bool MaxHeap::create(NATIVE_UINT_TYPE capacity)
{
// The heap has already been created.. so delete
// it and try again.
if( nullptr != this->m_heap ) {
delete [] this->m_heap;
this->m_heap = nullptr;
}
this->m_heap = new(std::nothrow) Node[capacity];
if( nullptr == this->m_heap ) {
return false;
}
this->m_capacity = capacity;
return true;
}
bool MaxHeap::push(NATIVE_INT_TYPE value, NATIVE_UINT_TYPE id) {
// If the queue is full, return false:
if(this->isFull()) {
return false;
}
// Heap indexes:
NATIVE_UINT_TYPE parent;
NATIVE_UINT_TYPE index = this->m_size;
// Max loop bounds for bit flip protection:
NATIVE_UINT_TYPE maxIter = this->m_size+1;
NATIVE_UINT_TYPE maxCount = 0;
// Start at the bottom of the heap and work our ways
// upwards until we find a parent that has a value
// greater than ours.
while(index && maxCount < maxIter) {
// Get the parent index:
parent = PARENT(index);
// The parent index should ALWAYS be less than the
// current index. Let's verify that.
FW_ASSERT(parent < index, parent, index);
// If the current value is less than the parent,
// then the current index is in the correct place,
// so break out of the loop:
if(value <= this->m_heap[parent].value) {
break;
}
// Swap the parent and child:
this->m_heap[index] = this->m_heap[parent];
index = parent;
++maxCount;
}
// Check for programming errors or bit flips:
FW_ASSERT(maxCount < maxIter, maxCount, maxIter);
FW_ASSERT(index <= this->m_size, index);
// Set the values of the new element:
this->m_heap[index].value = value;
this->m_heap[index].order = m_order;
this->m_heap[index].id = id;
++this->m_size;
++this->m_order;
return true;
}
bool MaxHeap::pop(NATIVE_INT_TYPE& value, NATIVE_UINT_TYPE& id) {
// If there is nothing in the heap then
// return false:
if(this->isEmpty()) {
return false;
}
// Set the return values to the top (max) of
// the heap:
value = this->m_heap[0].value;
id = this->m_heap[0].id;
// Now place the last element on the heap in
// the root position, and resize the heap.
// This will put the smallest value in the
// heap on the top, violating the heap property.
NATIVE_UINT_TYPE index = this->m_size-1;
// Fw::Logger::logMsg("Putting on top: i: %u v: %d\n", index, this->m_heap[index].value);
this->m_heap[0]= this->m_heap[index];
--this->m_size;
// Now that the heap property is violated, we
// need to reorganize the heap to restore it's
// heapy-ness.
this->heapify();
return true;
}
// Is the heap full:
bool MaxHeap::isFull() {
return (this->m_size == this->m_capacity);
}
// Is the heap empty:
bool MaxHeap::isEmpty() {
return (this->m_size == 0);
}
// Get the current size of the heap:
NATIVE_UINT_TYPE MaxHeap::getSize() {
return this->m_size;
}
// A non-recursive heapify method.
// Note: This method had an additional property, such that
// items pushed of the same priority will be popped in FIFO
// order.
void MaxHeap::heapify() {
NATIVE_UINT_TYPE index = 0;
NATIVE_UINT_TYPE left;
NATIVE_UINT_TYPE right;
NATIVE_UINT_TYPE largest;
// Max loop bounds for bit flip protection:
NATIVE_UINT_TYPE maxIter = this->m_size+1;
NATIVE_UINT_TYPE maxCount = 0;
while(index <= this->m_size && maxCount < maxIter) {
// Get the children indexes for this node:
left = LCHILD(index);
right = RCHILD(index);
FW_ASSERT(left > index, left, index);
FW_ASSERT(right > left, right, left);
// If the left node is bigger than the heap
// size, we have reached the end of the heap
// so we can stop:
if (left >= this->m_size) {
break;
}
// Initialize the largest node to the current
// node:
largest = index;
// Which one is larger, the current node or
// the left node?:
largest = this->max(left, largest);
// Make sure the right node exists before checking it:
if (right < this->m_size) {
// Which one is larger, the current largest
// node or the right node?
largest = this->max(right, largest);
}
// If the largest node is the current node
// then we are done heapifying:
if (largest == index)
{
break;
}
// Swap the largest node with the current node:
// Fw::Logger::logMsg("Swapping: i: %u v: %d with i: %u v: %d\n",
// index, this->m_heap[index].value,
// largest, this->m_heap[largest].value);
this->swap(index, largest);
// Set the new index to whichever child was larger:
index = largest;
}
// Check for programming errors or bit flips:
FW_ASSERT(maxCount < maxIter, maxCount, maxIter);
FW_ASSERT(index <= this->m_size, index);
}
// Return the maximum priority index between two nodes. If their
// priorities are equal, return the oldest to keep the heap stable
NATIVE_UINT_TYPE MaxHeap::max(NATIVE_UINT_TYPE a, NATIVE_UINT_TYPE b) {
FW_ASSERT(a < this->m_size, a, this->m_size);
FW_ASSERT(b < this->m_size, b, this->m_size);
// Extract the priorities:
NATIVE_INT_TYPE aValue = this->m_heap[a].value;
NATIVE_INT_TYPE bValue = this->m_heap[b].value;
// If the priorities are equal, the "larger" one will be
// the "older" one as determined by order pushed on to the
// heap. Using this secondary ordering technique makes the
// heap stable (ie. FIFO for equal priority elements).
// Note: We check this first, because it is the most common
// case. Let's save as many ticks as we can...
if(aValue == bValue) {
NATIVE_UINT_TYPE aAge = this->m_order - this->m_heap[a].order;
NATIVE_UINT_TYPE bAge = this->m_order - this->m_heap[b].order;
if(aAge > bAge) {
return a;
}
return b;
}
// Which priority is larger?:
if( aValue > bValue ) {
return a;
}
// B is larger:
return b;
}
// Swap two nodes in the heap:
void MaxHeap::swap(NATIVE_UINT_TYPE a, NATIVE_UINT_TYPE b) {
FW_ASSERT(a < this->m_size, a, this->m_size);
FW_ASSERT(b < this->m_size, b, this->m_size);
Node temp = this->m_heap[a];
this->m_heap[a] = this->m_heap[b];
this->m_heap[b] = temp;
}
// Print heap, for debugging purposes only:
void MaxHeap::print() {
NATIVE_UINT_TYPE index = 0;
NATIVE_UINT_TYPE left;
NATIVE_UINT_TYPE right;
Fw::Logger::logMsg("Printing Heap of Size: %d\n", this->m_size);
while(index < this->m_size) {
left = LCHILD(index);
right = RCHILD(index);
if( left >= m_size && index == 0) {
Fw::Logger::logMsg("i: %u v: %d d: %u -> (NULL, NULL)\n",
index, this->m_heap[index].value, this->m_heap[index].id);
}
else if( right >= m_size && left < m_size ) {
Fw::Logger::logMsg("i: %u v: %d d: %u -> (i: %u v: %d d: %u, NULL)\n",
index, this->m_heap[index].value, this->m_heap[index].id,
left, this->m_heap[left].value, this->m_heap[left].id);
}
else if( right < m_size && left < m_size ) {
Fw::Logger::logMsg("i: %u v: %d d: %u -> (i: %u v: %d d: %u, i: %u v: %d d: %u)\n",
index, this->m_heap[index].value, this->m_heap[index].id,
left, this->m_heap[left].value,this->m_heap[left].id,
right, this->m_heap[right].value, this->m_heap[right].id);
}
++index;
}
}
}
| cpp |
fprime | data/projects/fprime/Os/Pthreads/MaxHeap/MaxHeap.hpp | // ======================================================================
// \title MaxHeap.hpp
// \author dinkel
// \brief An implementation of a stable max heap data structure
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef OS_PTHREADS_MAX_HEAP_HPP
#define OS_PTHREADS_MAX_HEAP_HPP
#include <FpConfig.hpp>
namespace Os {
//! \class MaxHeap
//! \brief A stable max heap data structure
//!
//! This is a max heap data structure. Items of the highest value will
//! be popped off the heap first. Items of equal value will be popped
//! off in FIFO order. Insertion and deletion from the heap are both
//! O(log(n)) time.
class MaxHeap {
public:
//! \brief MaxHeap constructor
//!
//! Create a max heap object
//!
MaxHeap();
//! \brief MaxHeap deconstructor
//!
//! Free memory for the heap that was allocated in the constructor
//!
~MaxHeap();
//! \brief MaxHeap creation
//!
//! Create the max heap with a given maximum size
//!
//! \param capacity the maximum number of elements to store in the heap
//!
bool create(NATIVE_UINT_TYPE capacity);
//! \brief Push an item onto the heap.
//!
//! The item will be put into the heap according to its value. The
//! id field is a data field set by the user which can be used to
//! identify the element when it is popped off the heap.
//!
//! \param value the value of the element to push onto the heap
//! \param id the identifier of the element to push onto the heap
//!
bool push(NATIVE_INT_TYPE value, NATIVE_UINT_TYPE id);
//! \brief Pop an item from the heap.
//!
//! The item with the maximum value in the heap will be returned.
//! If there are items with equal values, the oldest item will be
//! returned.
//!
//! \param value the value of the element to popped from the heap
//! \param id the identifier of the element popped from the heap
//!
bool pop(NATIVE_INT_TYPE& value, NATIVE_UINT_TYPE& id);
//! \brief Is the heap full?
//!
//! Has the heap reached max size. No new items can be put on the
//! heap if this function returns true.
//!
bool isFull();
//! \brief Is the heap empty?
//!
//! Is the heap empty? No item can be popped from the heap if
//! this function returns true.
//!
bool isEmpty();
//! \brief Get the current number of elements on the heap.
//!
//! This function returns the current number of items on the
//! heap.
//!
NATIVE_UINT_TYPE getSize();
//! \brief Print the contents of the heap to stdout.
//!
//! This function here is for debugging purposes.
//!
void print();
private:
// Private functions:
// Ensure the heap meets the heap property:
void heapify();
// Swap two elements on the heap:
void swap(NATIVE_UINT_TYPE a, NATIVE_UINT_TYPE b);
// Return the max between two elements on the heap:
NATIVE_UINT_TYPE max(NATIVE_UINT_TYPE a, NATIVE_UINT_TYPE b);
// The data structure for a node on the heap:
struct Node {
NATIVE_INT_TYPE value; // the priority of the node
NATIVE_UINT_TYPE order; // order in which node was pushed
NATIVE_UINT_TYPE id; // unique id for this node
};
// Private members:
Node* m_heap; // the heap itself
NATIVE_UINT_TYPE m_size; // the current size of the heap
NATIVE_UINT_TYPE m_order; // the current count of heap pushes
NATIVE_UINT_TYPE m_capacity; // the maximum capacity of the heap
};
}
#endif // OS_PTHREADS_MAX_HEAP_HPP
| hpp |
fprime | data/projects/fprime/Os/Pthreads/MaxHeap/test/ut/MaxHeapTest.cpp | #include "Os/Pthreads/MaxHeap/MaxHeap.hpp"
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#include <cstring>
using namespace Os;
#define DEPTH 5
#define DATA_SIZE 3
int main() {
printf("Creating heap.\n");
bool ret;
MaxHeap heap;
ret = heap.create(0);
FW_ASSERT(ret, ret);
ret = heap.create(1000000);
FW_ASSERT(ret, ret);
ret = heap.create(1);
FW_ASSERT(ret, ret);
ret = heap.create(DEPTH);
FW_ASSERT(ret, ret);
ret = heap.create(DEPTH);
FW_ASSERT(ret, ret);
NATIVE_INT_TYPE value;
NATIVE_UINT_TYPE size;
NATIVE_UINT_TYPE id=0;
printf("Testing empty...\n");
ret = heap.pop(value, id);
FW_ASSERT(id == 0, id);
FW_ASSERT(!ret, ret);
ret = heap.pop(value, id);
FW_ASSERT(id == 0, id);
FW_ASSERT(!ret, ret);
ret = heap.pop(value, id);
FW_ASSERT(id == 0, id);
FW_ASSERT(!ret, ret);
printf("Passed.\n");
printf("Testing push...\n");
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
//printf("Inserting value %d\n", ii);
ret = heap.push(ii, ii);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == ii+1, size, ii+1);
}
ret = heap.push(50, id);
FW_ASSERT(!ret, ret);
ret = heap.push(50, id);
FW_ASSERT(!ret, ret);
ret = heap.push(50, id);
FW_ASSERT(!ret, ret);
printf("Passed.\n");
printf("Testing pop...\n");
//heap.print();
for(NATIVE_INT_TYPE ii = DEPTH-1; ii >= 0; --ii) {
ret = heap.pop(value, id);
FW_ASSERT(ret, ret);
FW_ASSERT(id == static_cast<NATIVE_UINT_TYPE>(ii), id, ii);
size = heap.getSize();
FW_ASSERT(size == static_cast<NATIVE_UINT_TYPE>(ii), size, ii);
//printf("Heap state after pop:\n");
//heap.print();
//printf("Got value %d\n", value);
FW_ASSERT(value == ii, value, ii);
}
ret = heap.pop(value, id);
FW_ASSERT(!ret, ret);
printf("Passed.\n");
printf("Testing random...\n");
NATIVE_INT_TYPE values[DEPTH] = {56, 0, 500, 57, 5};
NATIVE_INT_TYPE sorted[DEPTH] = {500, 57, 56, 5, 0};
//heap.print();
// Push values on in random order:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
// Push next value in the list:
ret = heap.push(values[ii], id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == ii+1, size, ii+1);
// Pop the top value:
ret = heap.pop(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == ii, size, ii);
FW_ASSERT(value >= values[ii], value, values[ii]);
// Push the popped value:
ret = heap.push(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == ii+1, size, ii+1);
}
ret = heap.push(values[0], id);
FW_ASSERT(!ret, ret);
// Get values out from largest to smallest:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
// Pop the top value:
ret = heap.pop(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == (DEPTH-ii-1), size, (DEPTH-ii-1));
FW_ASSERT(value == sorted[ii], value, sorted[ii]);
// Push the top value:
ret = heap.push(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == (DEPTH-ii), size, (DEPTH-ii));
// Pop again:
ret = heap.pop(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == (DEPTH-ii-1), size, (DEPTH-ii-1));
FW_ASSERT(value == sorted[ii], value, sorted[ii]);
}
ret = heap.pop(value, id);
FW_ASSERT(!ret, ret);
printf("Passed.\n");
printf("Testing no priority...\n");
// For this test we expect things to come in fifo order
// since all the priorities are the same:
NATIVE_INT_TYPE priorities[DEPTH] = {7, 7, 7, 7, 7};
NATIVE_UINT_TYPE data[DEPTH] = {43, 56, 47, 33, 11};
// Push values on in random order:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
// Push next value in the list:
ret = heap.push(priorities[ii], data[ii]);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == ii+1, size, ii+1);
}
// Get values out in FIFO order:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
// Pop the top value:
ret = heap.pop(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == (DEPTH-ii-1), size, (DEPTH-ii-1));
FW_ASSERT(value == priorities[ii], value, priorities[ii]);
FW_ASSERT(id == data[ii], id, data[ii]);
}
printf("Passed.\n");
printf("Testing mixed priority...\n");
// For this test we expect things to come in fifo order
// for things of the same priority and in priority
// order for things of different priorities.
NATIVE_INT_TYPE pries[DEPTH] = {1, 7, 100, 1, 7};
NATIVE_INT_TYPE data2[DEPTH] = {4, 22, 99, 12344, 33};
NATIVE_INT_TYPE orderedPries[DEPTH] = {100, 7, 7, 1, 1};
NATIVE_UINT_TYPE ordered[DEPTH] = {99, 22, 33, 4, 12344};
// Push values on in random order:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
// Push next value in the list:
ret = heap.push(pries[ii], data2[ii]);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == ii+1, size, ii+1);
}
// Get values out in FIFO order:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
// Pop the top value:
ret = heap.pop(value, id);
FW_ASSERT(ret, ret);
size = heap.getSize();
FW_ASSERT(size == (DEPTH-ii-1), size, (DEPTH-ii-1));
FW_ASSERT(value == orderedPries[ii], value, orderedPries[ii]);
FW_ASSERT(id == ordered[ii], id, ordered[ii]);
}
printf("Passed.\n");
printf("Test done.\n");
}
| cpp |
fprime | data/projects/fprime/Os/Pthreads/test/ut/BufferQueueTest.cpp | #include "Os/Pthreads/BufferQueue.hpp"
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#include <cstring>
using namespace Os;
// Set this to 1 if testing a priority queue
// Set this to 0 if testing a fifo queue
#define PRIORITY_QUEUE 1
#define DEPTH 5
#define MSG_SIZE 3
int main() {
printf("Creating queue.\n");
bool ret;
NATIVE_UINT_TYPE size;
NATIVE_UINT_TYPE count;
NATIVE_UINT_TYPE maxCount;
NATIVE_INT_TYPE priority = 0;
BufferQueue queue;
ret = queue.create(15, 34);
FW_ASSERT(ret, ret);
ret = queue.create(DEPTH, MSG_SIZE);
FW_ASSERT(ret, ret);
U8 recv[MSG_SIZE];
U8 send[MSG_SIZE];
for(U32 ii = 0; ii < sizeof(send); ++ii) {
send[ii] = ii;
}
printf("Test empty queue...\n");
size = sizeof(recv);
ret = queue.pop(&recv[0], size, priority);
FW_ASSERT(size == 0);
FW_ASSERT(!ret, ret);
FW_ASSERT(priority == 0, priority);
printf("Passed.\n");
printf("Test full queue...\n");
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
printf("Pushing %d.\n", ii);
ret = queue.push(&send[0], sizeof(send), priority);
FW_ASSERT(ret, ret);
count = queue.getCount();
maxCount = queue.getMaxCount();
FW_ASSERT(count == ii+1, count);
FW_ASSERT(maxCount == ii+1, maxCount);
}
ret = queue.push(&send[0], sizeof(send), priority);
FW_ASSERT(!ret, ret);
printf("Passed.\n");
printf("Test weird size...\n");
size = 1;
ret = queue.pop(&recv[0], size, priority);
FW_ASSERT(!ret, ret);
FW_ASSERT(size == sizeof(send), size);
FW_ASSERT(priority == 0, priority);
printf("Passed.\n");
printf("Test pop...\n");
for(NATIVE_UINT_TYPE ii = DEPTH; ii > 0; --ii) {
printf("Popping %d.\n", ii);
size = sizeof(recv);
ret = queue.pop(&recv[0], size, priority);
FW_ASSERT(size == sizeof(recv), size);
FW_ASSERT(ret, ret);
FW_ASSERT(memcmp(recv, send, size) == 0);
FW_ASSERT(priority == 0, priority);
count = queue.getCount();
maxCount = queue.getMaxCount();
FW_ASSERT(count == ii-1, count);
FW_ASSERT(maxCount == DEPTH, maxCount);
}
size = sizeof(recv);
ret = queue.pop(&recv[0], size, priority);
FW_ASSERT(size == 0);
FW_ASSERT(!ret, ret);
FW_ASSERT(priority == 0, priority);
printf("Passed.\n");
printf("Test priorities...\n");
// Send messages with mixed priorities,
// and make sure we get back the buffers in
// the correct order.
BufferQueue queue2;
ret = queue2.create(1, 1);
FW_ASSERT(ret, ret);
ret = queue2.create(1, 1);
FW_ASSERT(ret, ret);
ret = queue2.create(DEPTH, 100);
FW_ASSERT(ret, ret);
ret = queue2.create(DEPTH, 100);
FW_ASSERT(ret, ret);
NATIVE_INT_TYPE priorities[DEPTH] = {9, 4, 100, 4, 9};
const char* messages[DEPTH] = {"hello", "how are you", "pretty good", "cosmic bro", "kthxbye"};
// Fill queue:
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
printf("Pushing '%s' at priority %d with size %zu\n", messages[ii], priorities[ii], strlen(messages[ii]));
ret = queue2.push(reinterpret_cast<const U8*>(messages[ii]), strlen(messages[ii]), priorities[ii]);
FW_ASSERT(ret, ret);
count = queue2.getCount();
maxCount = queue2.getMaxCount();
FW_ASSERT(count == ii+1, count);
FW_ASSERT(maxCount == ii+1, maxCount);
}
#if PRIORITY_QUEUE
// Pop things off the queue in the expected order:
NATIVE_INT_TYPE orderedPriorities[DEPTH] = {100, 9, 9, 4, 4};
const char* orderedMessages[DEPTH] = {"pretty good", "hello", "kthxbye", "how are you", "cosmic bro"};
#else
NATIVE_INT_TYPE orderedPriorities[DEPTH] = {0, 0, 0, 0, 0};
const char* orderedMessages[DEPTH] = {"hello", "how are you", "pretty good", "cosmic bro", "kthxbye"};
#endif
char temp[101];
size = sizeof(temp) - 1; // Leave room for extra \0 because of the message print
for(NATIVE_UINT_TYPE ii = 0; ii < DEPTH; ++ii) {
ret = queue2.pop(reinterpret_cast<U8*>(temp), size, priority);
temp[size] = '\0';
FW_ASSERT(ret, ret);
FW_ASSERT(priority == orderedPriorities[ii], priority);
FW_ASSERT(size == strlen(orderedMessages[ii]), strlen(orderedMessages[ii]));
printf("Popped '%s' at priority %d. Expected '%s' at priority %d.\n",
temp, priority, orderedMessages[ii], orderedPriorities[ii]);
FW_ASSERT(memcmp(temp, orderedMessages[ii], size) == 0, ii);
size = sizeof(temp) - 1; //Reset size
}
printf("Passed.\n");
printf("Test done.\n");
}
| cpp |
fprime | data/projects/fprime/Os/Stub/File.cpp | // ======================================================================
// \title Os/Stub/File.cpp
// \brief stub implementation for Os::File
// ======================================================================
#include "Os/Stub/File.hpp"
namespace Os {
namespace Stub {
namespace File {
StubFile::Status StubFile::open(const char *filepath, StubFile::Mode open_mode, OverwriteType overwrite) {
Status status = Status::NOT_SUPPORTED;
return status;
}
void StubFile::close() {}
StubFile::Status StubFile::size(FwSignedSizeType &size_result) {
Status status = Status::NOT_SUPPORTED;
return status;
}
StubFile::Status StubFile::position(FwSignedSizeType &position_result) {
Status status = Status::NOT_SUPPORTED;
return status;
}
StubFile::Status StubFile::preallocate(FwSignedSizeType offset, FwSignedSizeType length) {
Status status = Status::NOT_SUPPORTED;
return status;
}
StubFile::Status StubFile::seek(FwSignedSizeType offset, SeekType seekType) {
Status status = Status::NOT_SUPPORTED;
return status;
}
StubFile::Status StubFile::flush() {
Status status = Status::NOT_SUPPORTED;
return status;
}
StubFile::Status StubFile::read(U8 *buffer, FwSignedSizeType &size, StubFile::WaitType wait) {
Status status = Status::NOT_SUPPORTED;
return status;
}
StubFile::Status StubFile::write(const U8 *buffer, FwSignedSizeType &size, StubFile::WaitType wait) {
Status status = Status::NOT_SUPPORTED;
return status;
}
FileHandle* StubFile::getHandle() {
return &this->m_handle;
}
} // namespace File
} // namespace Stub
} // namespace Os
| cpp |