diff --git a/CMakeLists.txt b/CMakeLists.txt index 069449e4ee81f587493231d3ddd25c85991fa562..26659a90aa7cb5a617f8a27eafd2b1e6d9c85195 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,8 +17,10 @@ add_custom_target(check add_library(common OBJECT src/ErrorHandler.cpp src/Message.cpp - src/MessageParser.cpp + src/MessageParser.cpp + src/ServicePool.cpp src/Helpers/CRCHelper.cpp + src/Helpers/TimeAndDate.cpp src/Helpers/TimeHelper.cpp src/Services/EventReportService.cpp src/Services/MemoryManagementService.cpp @@ -26,14 +28,15 @@ add_library(common OBJECT src/Services/RequestVerificationService.cpp src/Services/TestService.cpp src/Services/TimeManagementService.cpp - src/Services/EventActionService.cpp + src/Services/EventActionService.cpp ) # Specify the .cpp files for the executables +file(GLOB x86_main_SRC "src/Platform/x86/*.cpp") add_executable(ecss_services src/main.cpp $<TARGET_OBJECTS:common> - src/Platform/x86/Service.cpp + ${x86_main_SRC} ) IF (EXISTS "${PROJECT_SOURCE_DIR}/lib/Catch2/CMakeLists.txt") diff --git a/README.md b/README.md index aab7c0ca428d51dcb3da71ce72b472023af475a1..539fa922b1fa02408797a25e22db0cee2bf197c4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # ECSS-E-ST-40-71C Services -In this repository you can find the implementation of the ECSS services, based on the ECSS-E-ST-40-71C standard. +In this repository you can find the implementation of the ECSS services, based +on the [ECSS-E-ST-40-71C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/) +standard. ## Directories - **ci**: GitLab CI configuration files diff --git a/ci/.clang-tidy b/ci/.clang-tidy index 79406a31501a0c54cd823f6aa9f9d5f56d9d0715..38beddf8e90c12aa96ede94f6d80bf27cc253aef 100644 --- a/ci/.clang-tidy +++ b/ci/.clang-tidy @@ -19,7 +19,7 @@ Checks: > performance-*, readability-*, zircon-* -WarningsAsErrors: '*,-misc-unused-parameters,-llvm-header-guard,-cppcoreguidelines-pro-type-member-init,-google-runtime-references,-clang-diagnostic-tautological-constant-out-of-range-compare,-readability-redundant-declaration,-modernize-use-equals-default,-fuchsia-statically-constructed-objects,-hicpp-signed-bitwise,-cert-err58-cpp' +WarningsAsErrors: '*,-misc-unused-parameters,-llvm-header-guard,-cppcoreguidelines-pro-type-member-init,-google-runtime-references,-clang-diagnostic-tautological-constant-out-of-range-compare,-readability-redundant-declaration,-modernize-use-equals-default,-fuchsia-statically-constructed-objects,-hicpp-signed-bitwise,-cert-err58-cpp,-clang-diagnostic-error,-misc-noexcept-move-constructor' HeaderFilterRegex: 'ecss-services\/((?!lib\/).)*$' AnalyzeTemporaryDtors: false ... diff --git a/ci/vera.profile b/ci/vera.profile index 4da7dae75b571530a062c8453ffa0f3c6a89781e..2382359f944d16804f95c08abf35c78c0d758ae8 100644 --- a/ci/vera.profile +++ b/ci/vera.profile @@ -9,7 +9,6 @@ set rules { L006 T001 T002 - T003 T004 T005 T006 diff --git a/inc/ECSS_Definitions.hpp b/inc/ECSS_Definitions.hpp index 3a2eeedba9ebd9fd6e080c054e485a7936880ae5..1f000979a32969565a7cdee0d7e91f63779da207 100644 --- a/inc/ECSS_Definitions.hpp +++ b/inc/ECSS_Definitions.hpp @@ -1,7 +1,6 @@ #ifndef ECSS_SERVICES_ECSS_DEFINITIONS_H #define ECSS_SERVICES_ECSS_DEFINITIONS_H -// Todo: Specify maximum size for regular messages #define ECSS_MAX_MESSAGE_SIZE 1024 #define ECSS_MAX_STRING_SIZE 256 diff --git a/inc/ErrorHandler.hpp b/inc/ErrorHandler.hpp index 25c65960e3e408ca35e5a818794eeaa83f873c70..9864f708b31bc297459627581f2542bb4352fb4e 100644 --- a/inc/ErrorHandler.hpp +++ b/inc/ErrorHandler.hpp @@ -1,6 +1,8 @@ #ifndef PROJECT_ERRORHANDLER_HPP #define PROJECT_ERRORHANDLER_HPP +#include <type_traits> + // Forward declaration of the class, since its header file depends on the ErrorHandler class Message; @@ -15,20 +17,13 @@ class Message; class ErrorHandler { private: /** - * Log the error to a logging facility. Currently, this just displays the error on the screen. - * - * @todo This function MUST be moved as platform-dependent code. Currently, it uses g++ specific - * functions for desktop. + * Log the error to a logging facility. Platform-dependent. */ template<typename ErrorType> static void logError(const Message &message, ErrorType errorType); /** - * Log an error without a Message to a logging facility. Currently, this just displays the error - * on the screen. - * - * @todo This function MUST be moved as platform-dependent code. Currently, it uses g++ specific - * functions for desktop. + * Log an error without a Message to a logging facility. Platform-dependent. */ template<typename ErrorType> static void logError(ErrorType errorType); @@ -57,11 +52,24 @@ public: * An error in the header of a packet makes it unable to be parsed */ UnacceptablePacket = 5, + /** + * A date that isn't valid according to the Gregorian calendar or cannot be parsed by the + * TimeHelper + */ + InvalidDate = 6, + /** + * Asked a Message type that doesn't exist + */ + UnknownMessageType = 7, /** - * Asked a Message type that it doesn't exist + * Asked to append unnecessary spare bits + */ + InvalidSpareBits = 8, + /** + * A function received a Message that was not of the correct type */ - UnknownMessageType = 6, + OtherMessageType = 9, }; /** @@ -165,7 +173,7 @@ public: /** * Report a failure about the progress of the execution of a request * - * Note:This function is different from reportError, because we need one more /p(stepID) + * @note This function is different from reportError, because we need one more \p stepID * to call the proper function for reporting the progress of the execution of a request * * @param message The incoming message that prompted the failure @@ -212,6 +220,33 @@ public: reportError(message, errorCode); } } + + /** + * Convert a parameter given in C++ to an ErrorSource that can be easily used in comparisons. + * @tparam ErrorType One of the enums specified in ErrorHandler. + * @param error An error code of a specific type + * @return The corresponding ErrorSource + */ + template<typename ErrorType> + inline static ErrorSource findErrorSource(ErrorType error) { + // Static type checking + if (std::is_same<ErrorType, AcceptanceErrorType>()) { + return Acceptance; + } + if (std::is_same<ErrorType, ExecutionStartErrorType>()) { + return ExecutionStart; + } + if (std::is_same<ErrorType, ExecutionProgressErrorType>()) { + return ExecutionProgress; + } + if (std::is_same<ErrorType, ExecutionCompletionErrorType>()) { + return ExecutionCompletion; + } + if (std::is_same<ErrorType, RoutingErrorType>()) { + return Routing; + } + return Internal; + } }; #endif //PROJECT_ERRORHANDLER_HPP diff --git a/inc/Helpers/CRCHelper.hpp b/inc/Helpers/CRCHelper.hpp index d70ca5782b7a33add0110990bd23c0c2253dd1e7..12da516b2d6718d6743b17779c2fcf01dec178cd 100644 --- a/inc/Helpers/CRCHelper.hpp +++ b/inc/Helpers/CRCHelper.hpp @@ -20,7 +20,6 @@ class CRCHelper { */ // TODO: Change this to hardware implementation or a trusted software one -// TODO: Use CRC with received TC and transmitted TM packets public: /** * Actual CRC calculation function. diff --git a/inc/Helpers/TimeAndDate.hpp b/inc/Helpers/TimeAndDate.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8ddc566973bddfbf78c6fa695d141935d12c06d7 --- /dev/null +++ b/inc/Helpers/TimeAndDate.hpp @@ -0,0 +1,79 @@ +#ifndef ECSS_SERVICES_TIMEANDDATE_HPP +#define ECSS_SERVICES_TIMEANDDATE_HPP + +#include <cstdint> +#include "macros.hpp" + +/** + * A class that represents the time and date. + * + * @note + * This class represents UTC (Coordinated Universal Time) date + */ +class TimeAndDate { +public: + uint16_t year; + uint8_t month; + uint8_t day; + uint8_t hour; + uint8_t minute; + uint8_t second; + + /** + * Assign the instances with the Unix epoch 1/1/1970 00:00:00 + */ + TimeAndDate(); + + /** + * @param year the year as it used in Gregorian calendar + * @param month the month as it used in Gregorian calendar + * @param day the day as it used in Gregorian calendar + * @param hour UTC hour in 24 format + * @param minute UTC minutes + * @param second UTC seconds + */ + TimeAndDate(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t + second); + + /** + * Compare two timestamps. + * + * @param Date the date that will be compared with the pointer `this` + * @return true if the pointer `this` is smaller than \p Date + */ + bool operator<(const TimeAndDate &Date); + + /** + * Compare two timestamps. + * + * @param Date the date that will be compared with the pointer `this` + * @return true if the pointer `this` is greater than \p Date + */ + bool operator>(const TimeAndDate &Date); + + /** + * Compare two timestamps. + * + * @param Date the date that will be compared with the pointer `this` + * @return true if the pointer `this` is equal to \p Date + */ + bool operator==(const TimeAndDate &Date); + + /** + * Compare two timestamps. + * + * @param Date the date that will be compared with the pointer `this` + * @return true if the pointer `this` is smaller than or equal to \p Date + */ + bool operator<=(const TimeAndDate &Date); + + /** + * Compare two timestamps. + * + * @param Date the date that will be compared with the pointer `this` + * @return true if the pointer `this` is greater than or equal to \p Date + */ + bool operator>=(const TimeAndDate &Date); +}; + +#endif //ECSS_SERVICES_TIMEANDDATE_HPP diff --git a/inc/Helpers/TimeHelper.hpp b/inc/Helpers/TimeHelper.hpp index 8661fff4c05df60a8c43b583bec6a62695f060a7..b9039cf346c410ae15563810f67e39685903716b 100644 --- a/inc/Helpers/TimeHelper.hpp +++ b/inc/Helpers/TimeHelper.hpp @@ -3,39 +3,93 @@ #include <cstdint> #include <Message.hpp> +#include "TimeAndDate.hpp" + +#define SECONDS_PER_MINUTE 60 +#define SECONDS_PER_HOUR 3600 +#define SECONDS_PER_DAY 86400 /** * This class formats the spacecraft time and cooperates closely with the ST[09] time management. - * The ECSS standard supports two time formats: the CUC and CSD that are described in - * CCSDS 301.0-B-4 standard - * The chosen time format is CUC. The reasons for this selection are the followings: - * 1)It is more flexible from the CSD. The designer is free to decide how much memory will use - * for the time unit and what that time unit will be(seconds, minutes, hours etc.). - * 2)It can use TAI(international atomic time) as reference time scale. So there is no need - * to worry about leap seconds(code UTC-based) * - * Note: The implementation of the time formats are in general RTC-dependent. First, we need to - * get the time data from the RTC, so we know what time is it and then format it! + * The ECSS standard supports two time formats: the CUC and CSD that are described in CCSDS + * 301.0-B-4 standard. The chosen time format is CDS and it is UTC-based (UTC: Coordinated + * Universal Time). It consists of two main fields: the time code preamble field (P-field) and + * the time specification field (T-field). The P-Field is the metadata for the T-Field. The + * T-Field is consisted of two segments: 1) the `DAY` and the 2) `ms of day` segments. + * The P-field won't be included in the code, because as the ECSS standards claims, it can be + * just implicitly declared. + * + * @note + * Since this code is UTC-based, the leap second correction must be made. The leap seconds that + * have been occurred between timestamps should be considered if a critical time-difference is + * needed + * */ class TimeHelper { public: + static constexpr uint8_t DaysOfMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + TimeHelper() = default; + + /** + * @param year The year that will be examined if it is a leap year (366 days) + * @return if the \p year is a leap year returns true and if it isn't returns false + */ + static bool IsLeapYear(uint16_t year); + + /** + * Convert UTC date to elapsed seconds since Unix epoch (1/1/1970 00:00:00). + * + * This is a reimplemented mktime() of <ctime> library in an embedded systems way + * + * @note + * This function can convert UTC dates after 1 January 2019 to elapsed seconds since Unix epoch + * + * @param TimeInfo the time information/data from the RTC (UTC format) + * @return the elapsed seconds between a given UTC date (after the Unix epoch) and Unix epoch + * @todo check if we need to change the epoch to the recommended one from the standard, 1 + * January 1958 + */ + static uint32_t utcToSeconds(TimeAndDate &TimeInfo); + + /** + * Convert elapsed seconds since Unix epoch to UTC date. + * + * This is a reimplemented gmtime() of <ctime> library in an embedded systems way + * + * @note + * This function can convert elapsed seconds since Unix epoch to UTC dates after 1 January 2019 + * + * @param seconds elapsed seconds since Unix epoch + * @return the UTC date based on the \p seconds + * @todo check if we need to change the epoch to the recommended one from the standard, 1 + * January 1958 + */ + static TimeAndDate secondsToUTC(uint32_t seconds); + /** - * Generate the CUC time format + * Generate the CDS time format (3.3 in CCSDS 301.0-B-4 standard). * - * @details The CUC time format consists of two main fields: the time code preamble field - * (P-field) and the time specification field(T-field). The P-Field is the metadata for the - * T-Field. The T-Field contains the value of the time unit and the designer decides what the - * time unit will be, so this is a subject for discussion. The recommended time unit from the - * standard is the second and it is probably the best solution for accuracy. - * @param seconds the seconds provided from the RTC. This function in general should have - * parameters corresponding with the RTC. For the time being we assume that the RTC has a - * 32-bit counter that counts seconds(the RTC in Nucleo F103RB!) - * @todo check if we need milliseconds(fractions of the time unit) - * @todo the time unit should be declared in the metadata. But how? - * @todo check if we need to define other epoch than the 1 January 1958 + * Converts a UTC date to CDS time format. + * + * @param TimeInfo is the data provided from RTC (UTC) + * @return TimeFormat the CDS time format. More specific, 48 bits are used for the T-field + * (16 for the `DAY` and 32 for the `ms of day`) * @todo time security for critical time operations + * @todo declare the implicit P-field */ - static uint64_t implementCUCTimeFormat(uint32_t seconds); + static uint64_t generateCDStimeFormat(struct TimeAndDate &TimeInfo); + + /** + * Parse the CDS time format (3.3 in CCSDS 301.0-B-4 standard) + * + * @param data time information provided from the ground segment. The length of the data is a + * fixed size of 48 bits + * @return the UTC date + */ + static TimeAndDate parseCDStimeFormat(const uint8_t *data); }; + #endif //ECSS_SERVICES_TIMEHELPER_HPP diff --git a/inc/Message.hpp b/inc/Message.hpp index 1b1cca380acb2186f35c7d8525a116e1c9c77dc4..3240626189f8848a4147f9e97e9d46399dfaa5fe 100644 --- a/inc/Message.hpp +++ b/inc/Message.hpp @@ -7,7 +7,6 @@ class Message; #include "ECSS_Definitions.hpp" #include <cstdint> -#include <cassert> #include <etl/String.hpp> #include <etl/wstring.h> #include "ErrorHandler.hpp" @@ -21,7 +20,7 @@ class Message; */ class Message { public: - Message () = default; + Message() = default; enum PacketType { TM = 0, // Telemetry @@ -67,10 +66,22 @@ public: * Appends the least significant \p numBits from \p data to the message * * Note: data MUST NOT contain any information beyond the most significant \p numBits bits - * @todo Error handling for failed asserts */ void appendBits(uint8_t numBits, uint16_t data); + /** + * Appends the remaining bits to complete a byte, in case the appendBits() is the last call + * and the packet data field isn't integer multiple of bytes + * + * @note Actually we should append the bits so the total length of the packets is an integer + * multiple of the padding word size declared for the application process + * @todo Confirm that the overall packet size is an integer multiple of the padding word size + * declared for every application process + * @todo check if wee need to define the spare field for the telemetry and telecommand + * secondary headers + */ + void finalize(); + /** * Appends 1 byte to the message */ @@ -96,7 +107,7 @@ public: * @param string The string to insert */ template<const size_t SIZE> - void appendString(const String<SIZE> & string); + void appendString(const String<SIZE> &string); /** * Reads the next \p numBits bits from the the message in a big-endian format @@ -272,9 +283,9 @@ public: * PTC = 7, PFC = 0 */ template<const size_t SIZE> - void appendOctetString(const String<SIZE> & string) { + void appendOctetString(const String<SIZE> &string) { // Make sure that the string is large enough to count - assertI(string.size() <= (std::numeric_limits<uint16_t>::max)(), + ASSERT_INTERNAL(string.size() <= (std::numeric_limits<uint16_t>::max)(), ErrorHandler::StringTooLarge); appendUint16(string.size()); @@ -431,18 +442,50 @@ public: * Reset the message reading status, and start reading data from it again */ void resetRead(); + + /** + * Compare the message type to an expected one. An unexpected message type will throw an + * OtherMessageType error. + * + * @return True if the message is of correct type, false if not + */ + bool assertType(Message::PacketType expectedPacketType, uint8_t expectedServiceType, + uint8_t expectedMessageType) { + if (packetType != expectedPacketType || serviceType != expectedServiceType || + messageType != expectedMessageType) { + ErrorHandler::reportInternalError(ErrorHandler::OtherMessageType); + return false; + } + + return true; + } + + /** + * Alias for Message::assertType(Message::TC, \p expectedServiceType, \p + * expectedMessageType) + */ + bool assertTC(uint8_t expectedServiceType, uint8_t expectedMessageType) { + return assertType(TC, expectedServiceType, expectedMessageType); + } + + /** + * Alias for Message::assertType(Message::TM, \p expectedServiceType, \p + * expectedMessageType) + */ + bool assertTM(uint8_t expectedServiceType, uint8_t expectedMessageType) { + return assertType(TM, expectedServiceType, expectedMessageType); + } }; template<const size_t SIZE> -inline void Message::appendString(const String<SIZE> & string) { - assertI(dataSize + string.size() < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); +inline void Message::appendString(const String<SIZE> &string) { + ASSERT_INTERNAL(dataSize + string.size() < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); // TODO: Do we need to keep this check? How does etl::string handle it? - assertI(string.size() < string.capacity(), ErrorHandler::StringTooLarge); + ASSERT_INTERNAL(string.size() < string.capacity(), ErrorHandler::StringTooLarge); memcpy(data + dataSize, string.data(), string.size()); dataSize += string.size(); } - #endif //ECSS_SERVICES_PACKET_H diff --git a/inc/MessageParser.hpp b/inc/MessageParser.hpp index c8c162f0720d1a1e1036eabbd9c038704dce0c58..4d1985b274f049dd325287de6e623b9a85b0ea4b 100644 --- a/inc/MessageParser.hpp +++ b/inc/MessageParser.hpp @@ -7,12 +7,6 @@ /** * A generic class responsible for the execution of the incoming telemetry and telecommand * packets. - * - * @todo Make the connection between the ST[01]-request verification service and the services - * that initiate it - * @todo Implement the execute function in the upcoming services or generally in the upcoming - * activities - * */ class MessageParser { @@ -21,11 +15,6 @@ public: /** * It is responsible to call the suitable function that executes the proper service. The way that * the services are selected is based on the serviceType of the \p message - * - * @todo The implementation of the execute function should correspond to the numbers of the - * services/activities that have been created - * @todo execute() needs to be redefined. The /p message isn't enough to call some - * subservices. More arguments are needed. */ void execute(Message &message); @@ -56,9 +45,6 @@ private: * * As specified in section 7.4.4.1 of the standard * - * @todo Implement the acknowledgement flags - * @todo Store and parse the source ID, if needed - * * @param data The data of the header (not null-terminated) * @param length The size of the header * @param message The Message to modify based on the header diff --git a/inc/Service.hpp b/inc/Service.hpp index 0aab624de64f9196d2ddae82ce97d3cb0c738156..fbd1aff83534859397e0cf935601f149e7922872 100644 --- a/inc/Service.hpp +++ b/inc/Service.hpp @@ -5,6 +5,8 @@ #include "Message.hpp" #include <iostream> // This file should be removed +class ServicePool; + /** * A spacecraft service, as defined in ECSS-E-ST-70-41C * @@ -17,6 +19,10 @@ class Service { private: uint16_t messageTypeCounter = 0; protected: + /** + * The service type of this Service. For example, ST[12]'s serviceType is `12`. + * Specify this value in the constructor of your service. + */ uint8_t serviceType{}; /** @@ -38,13 +44,48 @@ protected: * Note: For now, since we don't have any mechanisms to queue messages and send them later, * we just print the message to the screen */ - void storeMessage(const Message &message); + void storeMessage(Message &message); /** * This function declared only to remind us that every service must have a function like * this, but this particular function does actually nothing. */ void execute(Message &message); + + /** + * Default protected constructor for this Service + */ + Service() = default; + +public: + /** + * @brief Unimplemented copy constructor + * + * Does not allow Services should be copied. There should be only one instance for each Service. + */ + Service(Service const &) = delete; + + /** + * Unimplemented assignment operation + * + * Does not allow changing the instances of Services, as Services are singletons. + */ + void operator=(Service const &) = delete; + + /** + * Default destructor + */ + ~Service() = default; + + /** + * Default move constructor + */ + Service(Service &&service) noexcept = default; + + /** + * Default move assignment operator + */ + Service &operator=(Service &&service) noexcept = default; }; diff --git a/inc/ServicePool.hpp b/inc/ServicePool.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8a1e6035855eea8b35003ff37047ac4bb1b01f06 --- /dev/null +++ b/inc/ServicePool.hpp @@ -0,0 +1,49 @@ +#ifndef ECSS_SERVICES_SERVICEPOOL_HPP +#define ECSS_SERVICES_SERVICEPOOL_HPP + +#include "Services/RequestVerificationService.hpp" +#include "Services/TimeManagementService.hpp" +#include "Services/EventReportService.hpp" +#include "Services/EventActionService.hpp" +#include "Services/ParameterService.hpp" +#include "Services/TestService.hpp" +#include "Services/MemoryManagementService.hpp" + +/** + * Defines a class that contains instances of all Services. + * + * All Services should be stored here and should not be instantiated in a different way. + * + * @todo Find a way to disable services which are not used + */ +class ServicePool { +public: + RequestVerificationService requestVerification; + EventReportService eventReport; + MemoryManagementService memoryManagement; + TimeManagementService timeManagement; + EventActionService eventAction; + TestService testService; + ParameterService parameterManagement; + + /** + * The default ServicePool constructor + */ + ServicePool() = default; + + /** + * Reset all the services and their contents/properties to the original values + * + * @note This performs the reset in-place, i.e. no new memory is allocated. As such, all + * Services already stored as values will point to the "new" Services after a reset. + */ + void reset(); +}; + +/** + * A global variable that defines the basic pool where services can be fetched from + */ +extern ServicePool Services; + + +#endif //ECSS_SERVICES_SERVICEPOOL_HPP diff --git a/inc/Services/ParameterService.hpp b/inc/Services/ParameterService.hpp index c331ae2743d7ffbd4e137d043889515f491d0372..5672b3c6bbbc9cca8983937c075f43dae6b733d2 100644 --- a/inc/Services/ParameterService.hpp +++ b/inc/Services/ParameterService.hpp @@ -2,9 +2,11 @@ #define ECSS_SERVICES_PARAMETERSERVICE_HPP #include "Service.hpp" -// #include "Services/RequestVerificationService.hpp" +#include "ErrorHandler.hpp" +#include "etl/map.h" -#define CONFIGLENGTH 5 +// Number of stored parameters. MAX_PARAMS is just a dummy number for now. +#define MAX_PARAMS 5 /** * Implementation of the ST[20] parameter management service, @@ -18,10 +20,11 @@ * PTC and PFC for each parameter shall be specified as in * ECSS-E-ST-70-41C, chapter 7.3 */ + +typedef uint16_t ParamId; // parameter IDs are given sequentially struct Parameter { uint8_t ptc; // Packet field type code (PTC) uint8_t pfc; // Packet field format code (PFC) - uint16_t paramId; // Unique ID of the parameter uint32_t settingData; // Actual data defining the operation of a peripheral or subsystem. @@ -34,14 +37,15 @@ struct Parameter { * Holds the list with the parameters and provides functions * for parameter reporting and modification. * - * @todo Ensure that the parameter list is sorted by ID + * The parameter list is stored in a map with the parameter IDs as keys and values + * corresponding Parameter structs containing the PTC, PFC and the parameter's value. */ + class ParameterService : public Service { private: - Parameter paramsList[CONFIGLENGTH]; - // CONFIGLENGTH is just a dummy number for now, this should be statically set - static uint16_t numOfValidIds(Message idMsg); //count the valid ids in a given TC[20, 1] + etl::map<ParamId, Parameter, MAX_PARAMS> paramsList; + uint16_t numOfValidIds(Message idMsg); //count the valid ids in a given TC[20, 1] public: /** @@ -54,14 +58,14 @@ public: * containing the current configuration * **for the parameters specified in the carried valid IDs**. * - * No sophisticated error checking for now, just whether the package is of the correct type - * and whether the requested IDs are valid, ignoring the invalid ones. If no IDs are correct, - * the returned message shall be empty. + * No sophisticated error checking for now, just whether the packet is of the correct type + * and whether the requested IDs are valid, ignoring the invalid ones. + * If the packet has an incorrect header, an InternalError::UnacceptablePacket is raised. + * If no IDs are correct, the returned message shall be empty. * * @param paramId: a valid TC[20, 1] packet carrying the requested parameter IDs * @return None (messages are stored using storeMessage()) * - * @todo Generate failure notifs where needed when ST[01] is ready * * NOTES: * Method for valid ID counting is a hack (clones the message and figures out the number @@ -69,7 +73,7 @@ public: * * Everything apart from the setting data is uint16 (setting data are uint32 for now) */ - void reportParameterIds(Message paramIds); + void reportParameterIds(Message& paramIds); /** * This function receives a TC[20, 3] message and after checking whether its type is correct, @@ -79,10 +83,9 @@ public: * @param newParamValues: a valid TC[20, 3] message carrying parameter ID and replacement value * @return None * - * @todo Generate failure notifications where needed (eg. when an invalid ID is encountered) * @todo Use pointers for changing and storing addresses to comply with the standard */ - void setParameterIds(Message newParamValues); + void setParameterIds(Message& newParamValues); }; diff --git a/inc/Services/RequestVerificationService.hpp b/inc/Services/RequestVerificationService.hpp index 3f78f83b369b33b73269488b6f70451044f6c729..846695c33cca54c3052bebedf913a34def618104 100644 --- a/inc/Services/RequestVerificationService.hpp +++ b/inc/Services/RequestVerificationService.hpp @@ -126,18 +126,9 @@ public: * way that the subservices are selected is for the time being based on the messageType(class * member of class Message) of the param message * - * Note:The functions of this service takes dummy values as arguments for the time being - * - * @todo execute() needs to be redefined. The /p message isn't enough to call some - * subservices. More arguments are needed. + * Note: The functions of this service takes dummy values as arguments for the time being */ void execute(const Message &message); - - /** - * The purpose of this instance is to access the execute function of this service when a - * MessageParser object is created - */ - static RequestVerificationService instance; }; diff --git a/inc/Services/TestService.hpp b/inc/Services/TestService.hpp index f06be9693ff82a88faa69ae2b4c1f86a5760a2cf..937c1b97888e3ce1eb84f643b0dc34bd110329bc 100644 --- a/inc/Services/TestService.hpp +++ b/inc/Services/TestService.hpp @@ -32,12 +32,6 @@ public: * @todo Error handling for the switch() in the implementation of this execute function */ void execute(Message &message); - - /** - * The purpose of this instance is to access the execute function of this service when a - * MessageParser object is created - */ - static TestService instance; }; diff --git a/inc/Services/TimeManagementService.hpp b/inc/Services/TimeManagementService.hpp index d006a5d712b27ffc0218ef31dee469d5bb7d411a..d50b0f74bd9d188183c6704a80c969f64159453c 100644 --- a/inc/Services/TimeManagementService.hpp +++ b/inc/Services/TimeManagementService.hpp @@ -1,20 +1,33 @@ #ifndef ECSS_SERVICES_TIMEMANAGEMENTSERVICE_HPP #define ECSS_SERVICES_TIMEMANAGEMENTSERVICE_HPP + #include <Service.hpp> -#include <ctime> #include "Helpers/TimeHelper.hpp" /** - * Implementation of the ST[09] time management. The current implementation sends - * a report with the spacecraft time that is formatted according to the CUC time code format - * (check TimeHelper for the format) + * Implementation of the ST[09] time management. + * + * @notes + * There is a noticeable difference between setting the time using GPS and setting the time + * using space packets from the ground segment. The GPS module sends the actual time of UTC (123519 + * is 12:35:19 UTC), while space packets, for time configuration, sends the elapsed time units + * (seconds, days depends on the time format) from a specific epoch (1 January 1958 00:00:00). Time + * updates using GPS have nothing to do with this service, but for consistency and simplicity we + * are trying to set the time with a common way independently of the time source. This is also + * the reason that we chose CDS time format (because it is UTC based, check class `TimeHelper`) + * + * About the GPS receiver, we assume that it outputs NMEA (message format) data * + * @todo check if we need to follow the standard for time-management or we should send the time-data + * like GPS + * @todo check if the final GPS receiver support NMEA protocol * @todo When the time comes for the application processes we should consider this: All reports * generated by the application process that is identified by APID 0 are time reports * @todo Declare the time accuracy that the standard claims in the spacecraft - * time reference section(6.9.3.d,e) + * time reference section (6.9.3.d,e) */ + class TimeManagementService : public Service { public: TimeManagementService() { @@ -22,15 +35,33 @@ public: } /** - * TM[9,2] CUC time report + * TM[9,3] CDS time report. + * + * This function sends reports with the spacecraft time that is formatted according to the CDS + * time code format (check class `TimeHelper` for the format) * + * @param TimeInfo the time information/data from the RTC (UTC format) * @todo check if we need spacecraft time reference status * @todo ECSS standard claims: <<The time reports generated by the time reporting subservice * are spacecraft time packets. A spacecraft time packet does not carry the message type, * consisting of the service type and message subtype.>> Check if we need to implement that * or should ignore the standard? */ - void cucTimeReport(); + + void cdsTimeReport(TimeAndDate &TimeInfo); + + /** + * TC[9,128] CDS time request. + * + * This function is a custom subservice (mission specific) with message type 128 (as defined + * from the standard for custom message types, 5.3.3.1.f) and it parses the data of the + * time-management telecommand packet. This data is formatted according to the CDS time code + * format (check class `TimeHelper` for the format) + * + * @param message the message that will be parsed for its time-data. The data of the \p message + * should be a fixed size of 48 bits + */ + TimeAndDate cdsTimeRequest(Message &message); }; diff --git a/inc/macros.hpp b/inc/macros.hpp index 25a0833b069d95c291b668d7bb2d7eb93d4f79b9..f5205be237b3768b4791b0e7f47ff256b968970d 100644 --- a/inc/macros.hpp +++ b/inc/macros.hpp @@ -1,7 +1,18 @@ #ifndef ECSS_SERVICES_MACROS_HPP #define ECSS_SERVICES_MACROS_HPP -#define assertI(cond, error) (ErrorHandler::assertInternal((cond), (error))) -#define assertR(cond, error) (ErrorHandler::assertRequest((cond), *this, (error))) +/** + * Perform an assertion that, if failed, throws an ErrorHandler::Internal error + * + * @todo Actually hold program execution or throw an exception here + */ +#define ASSERT_INTERNAL(cond, error) (ErrorHandler::assertInternal((cond), (error))) + +/** + * A wrapper for ErrorHandler::assertRequest() that uses `this` as the Message object. + * + * Only to be used within the Message class. + */ +#define ASSERT_REQUEST(cond, error) (ErrorHandler::assertRequest((cond), *this, (error))) #endif //ECSS_SERVICES_MACROS_HPP diff --git a/src/ErrorHandler.cpp b/src/ErrorHandler.cpp index 45ce0c01808a8a6bb93a98062ca63fd9bbca0b0a..a2f20e7703087577a6b9c1818d75e7618cced2cf 100644 --- a/src/ErrorHandler.cpp +++ b/src/ErrorHandler.cpp @@ -1,43 +1,41 @@ #include <iostream> #include <cxxabi.h> #include <ErrorHandler.hpp> +#include <ServicePool.hpp> #include "Services/RequestVerificationService.hpp" -// TODO: Use service singleton, as soon as singletons are ready -static RequestVerificationService requestVerificationService; - template<> void ErrorHandler::reportError(const Message &message, AcceptanceErrorType errorCode) { - requestVerificationService.failAcceptanceVerification(message, errorCode); + Services.requestVerification.failAcceptanceVerification(message, errorCode); logError(message, errorCode); } template<> void ErrorHandler::reportError(const Message &message, ExecutionStartErrorType errorCode) { - requestVerificationService.failStartExecutionVerification(message, errorCode); + Services.requestVerification.failStartExecutionVerification(message, errorCode); logError(message, errorCode); } void ErrorHandler::reportProgressError(const Message &message, ExecutionProgressErrorType errorCode, uint8_t stepID) { - requestVerificationService.failProgressExecutionVerification(message, errorCode, stepID); + Services.requestVerification.failProgressExecutionVerification(message, errorCode, stepID); logError(message, errorCode); } template<> void ErrorHandler::reportError(const Message &message, ExecutionCompletionErrorType errorCode) { - requestVerificationService.failCompletionExecutionVerification(message, errorCode); + Services.requestVerification.failCompletionExecutionVerification(message, errorCode); logError(message, errorCode); } template<> void ErrorHandler::reportError(const Message &message, RoutingErrorType errorCode) { - requestVerificationService.failRoutingVerification(message, errorCode); + Services.requestVerification.failRoutingVerification(message, errorCode); logError(message, errorCode); } @@ -45,26 +43,3 @@ void ErrorHandler::reportError(const Message &message, RoutingErrorType errorCod void ErrorHandler::reportInternalError(ErrorHandler::InternalErrorType errorCode) { logError(errorCode); } - -template<typename ErrorType> -void ErrorHandler::logError(const Message &message, ErrorType errorType) { - std::cerr - /* - * Gets the error class name from the template - * Note: This is g++-dependent code and should only be used for debugging. - */ - << abi::__cxa_demangle(typeid(ErrorType).name(), nullptr, nullptr, nullptr) - << " Error " << "[" << static_cast<uint16_t>(message.serviceType) << "," << - static_cast<uint16_t>(message.messageType) << "]: " << errorType << std::endl; -} - -template<typename ErrorType> -void ErrorHandler::logError(ErrorType errorType) { - std::cerr - /* - * Gets the error class name from the template - * Note: This is g++-dependent code and should only be used for debugging. - */ - << abi::__cxa_demangle(typeid(ErrorType).name(), nullptr, nullptr, nullptr) - << " Error: " << errorType << std::endl; -} diff --git a/src/Helpers/CRCHelper.cpp b/src/Helpers/CRCHelper.cpp index e0cd4ebf914ff885c7f50a52aeec4cd3e42c8da8..8361455071673204dcaa88ab4c3f136615127fdf 100644 --- a/src/Helpers/CRCHelper.cpp +++ b/src/Helpers/CRCHelper.cpp @@ -9,7 +9,7 @@ uint16_t CRCHelper::calculateCRC(const uint8_t* message, uint32_t length) { // CRC16-CCITT generator polynomial (as specified in standard) uint16_t polynomial = 0x1021u; - for (int i = 0; i < length; i++) { + for (uint32_t i = 0; i < length; i++) { // "copy" (XOR w/ existing contents) the current msg bits into the MSB of the shift register shiftReg ^= (message[i] << 8u); diff --git a/src/Helpers/TimeAndDate.cpp b/src/Helpers/TimeAndDate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38280ecb745925f3ce989ad3547b9379bb888f67 --- /dev/null +++ b/src/Helpers/TimeAndDate.cpp @@ -0,0 +1,171 @@ +#include "Helpers/TimeHelper.hpp" + + +TimeAndDate::TimeAndDate() { + // Unix epoch 1/1/1970 + year = 1970; + month = 1; + day = 1; + hour = 0; + minute = 0; + second = 0; +} + +TimeAndDate::TimeAndDate(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, + uint8_t second) { + // check if the parameters make sense + ASSERT_INTERNAL(2019 <= year, ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(1 <= month && month <= 12, ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(1 <= day && day <= 31, ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(0 <= hour && hour <= 24, ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(0 <= minute && minute <= 60, ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(0 <= second && second <= 60, ErrorHandler::InternalErrorType::InvalidDate); + + this->year = year; + this->month = month; + this->hour = hour; + this->day = day; + this->minute = minute; + this->second = second; +} + +bool TimeAndDate::operator<(const TimeAndDate &Date) { + // compare years + if (this->year < Date.year) { + return true; + } + if (this->year > Date.year) { + return false; + } + + // compare months + if (this->month < Date.month) { + return true; + } + if (this->month > Date.month) { + return false; + } + + // compare days + if (this->day < Date.day) { + return true; + } + if (this->day > Date.day) { + return false; + } + + // compare hours + if (this->hour < Date.hour) { + return true; + } + if (this->hour > Date.hour) { + return false; + } + + // compare minutes + if (this->minute < Date.minute) { + return true; + } + if (this->minute > Date.minute) { + return false; + } + + // compare seconds + if (this->second < Date.second) { + return true; + } + + return false; +} + +bool TimeAndDate::operator>(const TimeAndDate &Date) { + // compare years + if (this->year > Date.year) { + return true; + } + if (this->year < Date.year) { + return false; + } + + // compare months + if (this->month > Date.month) { + return true; + } + if (this->month < Date.month) { + return false; + } + + // compare days + if (this->day > Date.day) { + return true; + } + if (this->day < Date.day) { + return false; + } + + // compare hours + if (this->hour > Date.hour) { + return true; + } + if (this->hour < Date.hour) { + return false; + } + + // compare minutes + if (this->minute > Date.minute) { + return true; + } + if (this->minute < Date.minute) { + return false; + } + + // compare seconds + if (this->second > Date.second) { + return true; + } + + return false; +} + +bool TimeAndDate::operator==(const TimeAndDate &Date) { + // compare years + if (this->year != Date.year) { + return false; + } + + // compare months + if (this->month != Date.month) { + return false; + } + + // compare days + if (this->day != Date.day) { + return false; + } + + // compare hours + if (this->hour != Date.hour) { + return false; + } + + // compare minutes + if (this->minute != Date.minute) { + return false; + } + + // compare seconds + if (this->second != Date.second) { + return false; + } + + return true; +} + + +bool TimeAndDate::operator<=(const TimeAndDate &Date) { + return (*this < Date || *this == Date); +} + +bool TimeAndDate::operator>=(const TimeAndDate &Date) { + return (*this > Date || *this == Date); +} diff --git a/src/Helpers/TimeHelper.cpp b/src/Helpers/TimeHelper.cpp index 462c7e8b35ea06bfe440f84b7e3e568e2a7891d2..4b6885dc9b842ade6bb33fd0c5a09270b4df11e4 100644 --- a/src/Helpers/TimeHelper.cpp +++ b/src/Helpers/TimeHelper.cpp @@ -1,43 +1,135 @@ #include "Helpers/TimeHelper.hpp" -uint64_t TimeHelper::implementCUCTimeFormat(uint32_t seconds) { - // the total number of octets including the P-field (1 octet) and T-field(4 octets) is 5 - - // define the P-field - const uint8_t bit0 = 0; // P-field extension(‘zero’: no extension, ‘one’: field is extended) - const uint8_t bits1_3 = 1; // Time code identification ( 001 -> 1958 January 1 epoch ) - const uint8_t bits4_5 = 4 - 1; // Number of octets of the basic time unit minus one - const uint8_t bits6_7 = 0; // Number of octets of the fractional time unit - const uint8_t pField = (bits6_7 << 6 | bits4_5 << 4 | bits1_3 << 1 | bit0); - - // just a reminder to be careful with the assigned values - static_assert(bit0 < 2); - static_assert(bits1_3 < 16); - static_assert(bits4_5 < 4); - static_assert(bits6_7 < 4); +bool TimeHelper::IsLeapYear(uint16_t year) { + if (year % 4 != 0) { + return false; + } + if (year % 100 != 0) { + return true; + } + return (year % 400) == 0; +} + +uint32_t TimeHelper::utcToSeconds(TimeAndDate &TimeInfo) { + // the date, that \p TimeInfo represents, should be greater than or equal to 1/1/2019 and the + // date should be valid according to Gregorian calendar + ASSERT_INTERNAL(TimeInfo.year >= 2019, ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(1 <= TimeInfo.month && TimeInfo.month <= 12, + ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(1 <= TimeInfo.day && TimeInfo.day <= 31, + ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(0 <= TimeInfo.hour && TimeInfo.hour <= 24, + ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(0 <= TimeInfo.minute && TimeInfo.minute <= 60, + ErrorHandler::InternalErrorType::InvalidDate); + ASSERT_INTERNAL(0 <= TimeInfo.second && TimeInfo.second <= 60, + ErrorHandler::InternalErrorType::InvalidDate); + + uint32_t secs = 1546300800; // elapsed seconds from Unix epoch until 1/1/2019 00:00:00 (UTC) + for (uint16_t y = 2019; y < TimeInfo.year; ++y) { + secs += (IsLeapYear(y) ? 366 : 365) * SECONDS_PER_DAY; + } + for (uint16_t m = 1; m < TimeInfo.month; ++m) { + secs += DaysOfMonth[m - 1] * SECONDS_PER_DAY; + if (m == 2 && IsLeapYear(TimeInfo.year)) { + secs += SECONDS_PER_DAY; + } + } + secs += (TimeInfo.day - 1) * SECONDS_PER_DAY; + secs += TimeInfo.hour * SECONDS_PER_HOUR; + secs += TimeInfo.minute * SECONDS_PER_MINUTE; + secs += TimeInfo.second; + return secs; +} + +struct TimeAndDate TimeHelper::secondsToUTC(uint32_t seconds) { + // elapsed seconds should be between dates, that are after 1/1/2019 and Unix epoch + ASSERT_INTERNAL(seconds >= 1546300800, ErrorHandler::InternalErrorType::InvalidDate); + + seconds -= 1546300800; // elapsed seconds from Unix epoch until 1/1/2019 00:00:00 (UTC) + TimeAndDate TimeInfo; + TimeInfo.year = 2019; + TimeInfo.month = 1; + TimeInfo.day = 0; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + // calculate years + while (seconds >= (IsLeapYear(TimeInfo.year) ? 366 : 365) * SECONDS_PER_DAY) { + seconds -= (IsLeapYear(TimeInfo.year) ? 366 : 365) * SECONDS_PER_DAY; + TimeInfo.year++; + } + + // calculate months + uint8_t i = 0; + while (seconds >= (DaysOfMonth[i] * SECONDS_PER_DAY)) { + TimeInfo.month++; + seconds -= (DaysOfMonth[i] * SECONDS_PER_DAY); + i++; + if (i == 1 && IsLeapYear(TimeInfo.year)) { + if (seconds <= (28 * SECONDS_PER_DAY)) { + break; + } + TimeInfo.month++; + seconds -= 29 * SECONDS_PER_DAY; + i++; + } + } + + // calculate days + TimeInfo.day = seconds / SECONDS_PER_DAY; + seconds -= TimeInfo.day * SECONDS_PER_DAY; + TimeInfo.day++; // add 1 day because we start count from 1 January (and not 0 January!) + + // calculate hours + TimeInfo.hour = seconds / SECONDS_PER_HOUR; + seconds -= TimeInfo.hour * SECONDS_PER_HOUR; + + // calculate minutes + TimeInfo.minute = seconds / SECONDS_PER_MINUTE; + seconds -= TimeInfo.minute * SECONDS_PER_MINUTE; + + // calculate seconds + TimeInfo.second = seconds; + return TimeInfo; +} + +uint64_t TimeHelper::generateCDStimeFormat(TimeAndDate &TimeInfo) { /** - * Define the T-field, the seconds passed from the defined epoch 1 January 1958 - * We use 4 octets(32 bits) for the time unit(seconds) because 32 bits for the seconds are - * enough to count 136 years! But if we use 24 bits for the seconds then it will count 0,5 - * years and this isn't enough. Remember we can use only integers numbers of octets for the - * time unit(second) - * - * @todo the implementation of the total seconds depends on the structure of the RTC + * Define the T-field. The total number of octets for the implementation of T-field is 6(2 for + * the `DAY` and 4 for the `ms of day` */ - uint32_t totalSeconds = seconds; + + uint32_t seconds = utcToSeconds(TimeInfo); /** - * Define time format including P-field and T-Field - * - * Notes: - * Only the 40 bits of the 64 will be used for the timeFormat(0-7 : P-field, 8-39: T-field) - * - * Shift operators have high priority. That's why we should do a type-casting first so we - * don't lose valuable bits - */ - uint64_t timeFormat = (static_cast<uint64_t>(totalSeconds) << 8 | pField); + * The `DAY` segment, 16 bits as defined from standard. Actually the days passed since Unix + * epoch + */ + auto elapsedDays = static_cast<uint16_t>(seconds / SECONDS_PER_DAY); + /** + * The `ms of day` segment, 32 bits as defined in standard. The `ms of the day` and DAY` + * should give the time passed since Unix epoch + */ + auto msOfDay = static_cast<uint32_t >((seconds % SECONDS_PER_DAY) * 1000); + + uint64_t timeFormat = (static_cast<uint64_t>(elapsedDays) << 32 | msOfDay); return timeFormat; } + +TimeAndDate TimeHelper::parseCDStimeFormat(const uint8_t *data) { + uint16_t elapsedDays = (static_cast<uint16_t >(data[0])) << 8 | static_cast<uint16_t > + (data[1]); + uint32_t msOfDay = (static_cast<uint32_t >(data[2])) << 24 | + (static_cast<uint32_t >(data[3])) << 16 | + (static_cast<uint32_t >(data[4])) << 8 | + static_cast<uint32_t >(data[5]); + + uint32_t seconds = elapsedDays * SECONDS_PER_DAY + msOfDay / 1000; + + return secondsToUTC(seconds); +} diff --git a/src/Message.cpp b/src/Message.cpp index 2d32f654ccd26b746380be4e1da50474a961e4c6..409e65e4e18ae303c8cbcac02422172615943184 100644 --- a/src/Message.cpp +++ b/src/Message.cpp @@ -10,10 +10,10 @@ Message::Message(uint8_t serviceType, uint8_t messageType, Message::PacketType p void Message::appendBits(uint8_t numBits, uint16_t data) { // TODO: Add assertion that data does not contain 1s outside of numBits bits - assertI(numBits <= 16, ErrorHandler::TooManyBitsAppend); + ASSERT_INTERNAL(numBits <= 16, ErrorHandler::TooManyBitsAppend); while (numBits > 0) { // For every sequence of 8 bits... - assertI(dataSize < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); + ASSERT_INTERNAL(dataSize < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); if (currentBit + numBits >= 8) { // Will have to shift the bits and insert the next ones later @@ -36,17 +36,26 @@ void Message::appendBits(uint8_t numBits, uint16_t data) { } } +void Message::finalize() { + // Define the spare field in telemetry and telecommand user data field (7.4.3.2.c and 7.4.4.2.c) + + if (currentBit != 0) { + currentBit = 0; + dataSize++; + } +} + void Message::appendByte(uint8_t value) { - assertI(dataSize < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); - assertI(currentBit == 0, ErrorHandler::ByteBetweenBits); + ASSERT_INTERNAL(dataSize < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); + ASSERT_INTERNAL(currentBit == 0, ErrorHandler::ByteBetweenBits); data[dataSize] = value; dataSize++; } void Message::appendHalfword(uint16_t value) { - assertI(dataSize + 2 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); - assertI(currentBit == 0, ErrorHandler::ByteBetweenBits); + ASSERT_INTERNAL(dataSize + 2 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); + ASSERT_INTERNAL(currentBit == 0, ErrorHandler::ByteBetweenBits); data[dataSize] = static_cast<uint8_t>((value >> 8) & 0xFF); data[dataSize + 1] = static_cast<uint8_t>(value & 0xFF); @@ -55,8 +64,8 @@ void Message::appendHalfword(uint16_t value) { } void Message::appendWord(uint32_t value) { - assertI(dataSize + 4 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); - assertI(currentBit == 0, ErrorHandler::ByteBetweenBits); + ASSERT_INTERNAL(dataSize + 4 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooLarge); + ASSERT_INTERNAL(currentBit == 0, ErrorHandler::ByteBetweenBits); data[dataSize] = static_cast<uint8_t>((value >> 24) & 0xFF); data[dataSize + 1] = static_cast<uint8_t>((value >> 16) & 0xFF); @@ -67,13 +76,12 @@ void Message::appendWord(uint32_t value) { } uint16_t Message::readBits(uint8_t numBits) { - assertR(numBits <= 16, ErrorHandler::TooManyBitsRead); - // TODO: Add assert + ASSERT_REQUEST(numBits <= 16, ErrorHandler::TooManyBitsRead); uint16_t value = 0x0; while (numBits > 0) { - assertR(readPosition < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); + ASSERT_REQUEST(readPosition < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); if (currentBit + numBits >= 8) { auto bitsToAddNow = static_cast<uint8_t>(8 - currentBit); @@ -95,7 +103,7 @@ uint16_t Message::readBits(uint8_t numBits) { } uint8_t Message::readByte() { - assertR(readPosition < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); + ASSERT_REQUEST(readPosition < ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); uint8_t value = data[readPosition]; readPosition++; @@ -104,7 +112,7 @@ uint8_t Message::readByte() { } uint16_t Message::readHalfword() { - assertR(readPosition + 2 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); + ASSERT_REQUEST(readPosition + 2 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); uint16_t value = (data[readPosition] << 8) | data[readPosition + 1]; readPosition += 2; @@ -113,7 +121,7 @@ uint16_t Message::readHalfword() { } uint32_t Message::readWord() { - assertR(readPosition + 4 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); + ASSERT_REQUEST(readPosition + 4 <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); uint32_t value = (data[readPosition] << 24) | (data[readPosition + 1] << 16) | (data[readPosition + 2] << 8) | data[readPosition + 3]; @@ -123,8 +131,8 @@ uint32_t Message::readWord() { } void Message::readString(char *string, uint8_t size) { - assertR(readPosition + size <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); - assertR(size < ECSS_MAX_STRING_SIZE, ErrorHandler::StringTooShort); + ASSERT_REQUEST(readPosition + size <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); + ASSERT_REQUEST(size < ECSS_MAX_STRING_SIZE, ErrorHandler::StringTooShort); memcpy(string, data + readPosition, size); string[size] = '\0'; // todo: Use that for now to avoid problems. Later to be removed @@ -133,8 +141,8 @@ void Message::readString(char *string, uint8_t size) { } void Message::readString(uint8_t *string, uint16_t size) { - assertR(readPosition + size <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); - assertR(size < ECSS_MAX_STRING_SIZE, ErrorHandler::StringTooShort); + ASSERT_REQUEST(readPosition + size <= ECSS_MAX_MESSAGE_SIZE, ErrorHandler::MessageTooShort); + ASSERT_REQUEST(size < ECSS_MAX_STRING_SIZE, ErrorHandler::StringTooShort); memcpy(string, data + readPosition, size); diff --git a/src/MessageParser.cpp b/src/MessageParser.cpp index 51451cf7e0a102213df999b4f7acc4b542904ce9..af4988a1a302b2da35eed9d2cbe45e6b1508b706 100644 --- a/src/MessageParser.cpp +++ b/src/MessageParser.cpp @@ -1,21 +1,20 @@ #include <cstring> #include <Services/EventActionService.hpp> +#include <ServicePool.hpp> #include "ErrorHandler.hpp" #include "MessageParser.hpp" #include "macros.hpp" #include "Services/TestService.hpp" #include "Services/RequestVerificationService.hpp" -TestService TestService::instance; -RequestVerificationService RequestVerificationService::instance; void MessageParser::execute(Message &message) { switch (message.serviceType) { case 1: - RequestVerificationService::instance.execute(message); + Services.requestVerification.execute(message); break; case 17: - TestService::instance.execute(message); + Services.testService.execute(message); break; default: ErrorHandler::reportInternalError(ErrorHandler::UnknownMessageType); @@ -24,7 +23,7 @@ void MessageParser::execute(Message &message) { } Message MessageParser::parse(uint8_t *data, uint32_t length) { - assertI(length >= 6, ErrorHandler::UnacceptablePacket); + ASSERT_INTERNAL(length >= 6, ErrorHandler::UnacceptablePacket); uint16_t packetHeaderIdentification = (data[0] << 8) | data[1]; uint16_t packetSequenceControl = (data[2] << 8) | data[3]; @@ -38,10 +37,10 @@ Message MessageParser::parse(uint8_t *data, uint32_t length) { auto sequenceFlags = static_cast<uint8_t>(packetSequenceControl >> 14); // Returning an internal error, since the Message is not available yet - assertI(versionNumber == 0, ErrorHandler::UnacceptablePacket); - assertI(secondaryHeaderFlag == 1, ErrorHandler::UnacceptablePacket); - assertI(sequenceFlags == 0x3, ErrorHandler::UnacceptablePacket); - assertI(packetDataLength == length - 6, ErrorHandler::UnacceptablePacket); + ASSERT_INTERNAL(versionNumber == 0, ErrorHandler::UnacceptablePacket); + ASSERT_INTERNAL(secondaryHeaderFlag == 1, ErrorHandler::UnacceptablePacket); + ASSERT_INTERNAL(sequenceFlags == 0x3, ErrorHandler::UnacceptablePacket); + ASSERT_INTERNAL(packetDataLength == length - 6, ErrorHandler::UnacceptablePacket); Message message(0, 0, packetType, APID); diff --git a/src/Platform/x86/ErrorHandler.cpp b/src/Platform/x86/ErrorHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6119440cc09527624c64a4adc517e7d6c551e7ee --- /dev/null +++ b/src/Platform/x86/ErrorHandler.cpp @@ -0,0 +1,40 @@ +/** + * This file specifies the logging utilities for x86 desktop platforms. These logging functions + * just print the error to screen (via stderr). + */ + +#include <iostream> +#include <cxxabi.h> +#include <ErrorHandler.hpp> +#include <Message.hpp> + +// TODO: Find a way to reduce the number of copies of this chunk +template void ErrorHandler::logError(const Message &, ErrorHandler::AcceptanceErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::ExecutionStartErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::ExecutionProgressErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::ExecutionCompletionErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::RoutingErrorType); +template void ErrorHandler::logError(ErrorHandler::InternalErrorType); + +template<typename ErrorType> +void ErrorHandler::logError(const Message &message, ErrorType errorType) { + std::cerr + /* + * Gets the error class name from the template + * Note: This is g++-dependent code and should only be used for debugging. + */ + << abi::__cxa_demangle(typeid(ErrorType).name(), nullptr, nullptr, nullptr) + << " Error " << "[" << static_cast<uint16_t>(message.serviceType) << "," << + static_cast<uint16_t>(message.messageType) << "]: " << errorType << std::endl; +} + +template<typename ErrorType> +void ErrorHandler::logError(ErrorType errorType) { + std::cerr + /* + * Gets the error class name from the template + * Note: This is g++-dependent code and should only be used for debugging. + */ + << abi::__cxa_demangle(typeid(ErrorType).name(), nullptr, nullptr, nullptr) + << " Error: " << errorType << std::endl; +} diff --git a/src/Platform/x86/Service.cpp b/src/Platform/x86/Service.cpp index ff9d9d95de57f749996cb8a2fcd7853cebda7813..6a251f27d1d3a70713833baa949bdcc5a787ec0d 100644 --- a/src/Platform/x86/Service.cpp +++ b/src/Platform/x86/Service.cpp @@ -2,7 +2,10 @@ #include <iomanip> #include "Service.hpp" -void Service::storeMessage(const Message &message) { +void Service::storeMessage(Message &message) { + // appends the remaining bits to complete a byte + message.finalize(); + // Just print it to the screen std::cout << "New " << ((message.packetType == Message::TM) ? "TM" : "TC") << "[" << std::hex diff --git a/src/ServicePool.cpp b/src/ServicePool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f76e2ee77d066b475c0678baec2159ad3dc1a246 --- /dev/null +++ b/src/ServicePool.cpp @@ -0,0 +1,14 @@ +#include "ServicePool.hpp" + +ServicePool Services = ServicePool(); + +void ServicePool::reset() { + // Call the destructor + this->~ServicePool(); + + // Call the constructor + // Note the usage of "placement new" that replaces the contents of the Services variable. + // This is not dangerous usage, since all the memory that will be used for this has been + // statically allocated from before. + new (this) ServicePool(); +} diff --git a/src/Services/EventActionService.cpp b/src/Services/EventActionService.cpp index b61b16dcff7a92cbbeabfe226e983ee6fdc0eee7..2ace42dd9796cfff95120b189ed95e35e44c9722 100644 --- a/src/Services/EventActionService.cpp +++ b/src/Services/EventActionService.cpp @@ -4,149 +4,140 @@ /** * @todo: Check if a uint16_t is needed (in case of changing the size of - * eventActionDefinitionArray + * eventActionDefinitionArray) */ void EventActionService::addEventActionDefinitions(Message message) { // TC[19,1] + message.assertTC(19, 1); - if (message.messageType == 1 && message.packetType == Message::TC && message.serviceType == - 19) { - uint16_t index; - uint16_t applicationID = message.readEnum16(); - uint16_t eventDefinitionID = message.readEnum16(); - bool accepted = true; + uint16_t index; + uint16_t applicationID = message.readEnum16(); + uint16_t eventDefinitionID = message.readEnum16(); + bool accepted = true; + for (index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { + if (eventActionDefinitionArray[index].applicationId == applicationID && + eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID && + eventActionDefinitionArray[index].enabled) { + // @todo: throw a failed start of execution error + accepted = false; + } + } + if (accepted){ for (index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (eventActionDefinitionArray[index].applicationId == applicationID && - eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID && - eventActionDefinitionArray[index].enabled) { - // @todo: throw a failed start of execution error - accepted = false; + // @todo: throw an error if it's full + if (eventActionDefinitionArray[index].empty) { + break; } } - if (accepted){ - for (index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - // @todo: throw an error if it's full - if (eventActionDefinitionArray[index].empty) { - break; - } - } - if (index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE) { - eventActionDefinitionArray[index].empty = false; - eventActionDefinitionArray[index].enabled = true; - eventActionDefinitionArray[index].applicationId = applicationID; - eventActionDefinitionArray[index].eventDefinitionID = eventDefinitionID; - if (message.dataSize - 4 > ECSS_EVENT_SERVICE_STRING_SIZE) { - ErrorHandler::reportInternalError(ErrorHandler::InternalErrorType::MessageTooLarge); - } else { - char data[ECSS_EVENT_SERVICE_STRING_SIZE]; - message.readString(data, message.dataSize - 4); - eventActionDefinitionArray[index].request = String<ECSS_EVENT_SERVICE_STRING_SIZE>( - data); - } + if (index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE) { + eventActionDefinitionArray[index].empty = false; + eventActionDefinitionArray[index].enabled = true; + eventActionDefinitionArray[index].applicationId = applicationID; + eventActionDefinitionArray[index].eventDefinitionID = eventDefinitionID; + if (message.dataSize - 4 > ECSS_EVENT_SERVICE_STRING_SIZE) { + ErrorHandler::reportInternalError(ErrorHandler::InternalErrorType::MessageTooLarge); + } else { + char data[ECSS_EVENT_SERVICE_STRING_SIZE]; + message.readString(data, message.dataSize - 4); + eventActionDefinitionArray[index].request = String<ECSS_EVENT_SERVICE_STRING_SIZE>( + data); } } } } void EventActionService::deleteEventActionDefinitions(Message message) { - // TC[19,2] - if (message.messageType == 2 && message.packetType == Message::TC && message.serviceType - == 19) { - uint16_t numberOfEventActionDefinitions = message.readUint16(); - for (uint16_t i = 0; i < numberOfEventActionDefinitions; i++) { - uint16_t applicationID = message.readEnum16(); - uint16_t eventDefinitionID = message.readEnum16(); - for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (eventActionDefinitionArray[index].applicationId == applicationID && - eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID && - eventActionDefinitionArray[index].enabled) { - eventActionDefinitionArray[index].empty = true; - eventActionDefinitionArray[index].eventDefinitionID = 65535; - eventActionDefinitionArray[index].request = ""; - eventActionDefinitionArray[index].applicationId = 0; - eventActionDefinitionArray[index].enabled = false; - } - } - } + message.assertTC(19, 2); - } -} - -void EventActionService::deleteAllEventActionDefinitions(Message message) { - // TC[19,3] - if (message.messageType == 3 && message.packetType == Message::TC && message.serviceType - == 19) { - setEventActionFunctionStatus(false); + uint16_t numberOfEventActionDefinitions = message.readUint16(); + for (uint16_t i = 0; i < numberOfEventActionDefinitions; i++) { + uint16_t applicationID = message.readEnum16(); + uint16_t eventDefinitionID = message.readEnum16(); for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (not eventActionDefinitionArray[index].empty) { + if (eventActionDefinitionArray[index].applicationId == applicationID && + eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID && + eventActionDefinitionArray[index].enabled) { eventActionDefinitionArray[index].empty = true; - eventActionDefinitionArray[index].enabled = false; eventActionDefinitionArray[index].eventDefinitionID = 65535; eventActionDefinitionArray[index].request = ""; eventActionDefinitionArray[index].applicationId = 0; + eventActionDefinitionArray[index].enabled = false; } } } } +void EventActionService::deleteAllEventActionDefinitions(Message message) { + // TC[19,3] + message.assertTC(19, 3); + + setEventActionFunctionStatus(false); + for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { + if (not eventActionDefinitionArray[index].empty) { + eventActionDefinitionArray[index].empty = true; + eventActionDefinitionArray[index].enabled = false; + eventActionDefinitionArray[index].eventDefinitionID = 65535; + eventActionDefinitionArray[index].request = ""; + eventActionDefinitionArray[index].applicationId = 0; + } + } +} + void EventActionService::enableEventActionDefinitions(Message message) { // TC[19,4] - if (message.messageType == 4 && message.packetType == Message::TC && message.serviceType - == 19) { - uint16_t numberOfEventActionDefinitions = message.readUint16(); - if (numberOfEventActionDefinitions != 0){ - for (uint16_t i = 0; i < numberOfEventActionDefinitions; i++) { - uint16_t applicationID = message.readEnum16(); - uint16_t eventDefinitionID = message.readEnum16(); - for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (eventActionDefinitionArray[index].applicationId == applicationID && - eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID) { - eventActionDefinitionArray[index].enabled = true; - } - } - } - } else { + message.assertTC(19, 4); + + uint16_t numberOfEventActionDefinitions = message.readUint16(); + if (numberOfEventActionDefinitions != 0){ + for (uint16_t i = 0; i < numberOfEventActionDefinitions; i++) { + uint16_t applicationID = message.readEnum16(); + uint16_t eventDefinitionID = message.readEnum16(); for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (not eventActionDefinitionArray[index].empty){ + if (eventActionDefinitionArray[index].applicationId == applicationID && + eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID) { eventActionDefinitionArray[index].enabled = true; } } } + } else { + for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { + if (not eventActionDefinitionArray[index].empty){ + eventActionDefinitionArray[index].enabled = true; + } + } } } void EventActionService::disableEventActionDefinitions(Message message) { // TC[19,5] - if (message.messageType == 5 && message.packetType == Message::TC && message.serviceType - == 19) { - uint16_t numberOfEventActionDefinitions = message.readUint16(); - if (numberOfEventActionDefinitions != 0){ - for (uint16_t i = 0; i < numberOfEventActionDefinitions; i++) { - uint16_t applicationID = message.readEnum16(); - uint16_t eventDefinitionID = message.readEnum16(); - for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (eventActionDefinitionArray[index].applicationId == applicationID && - eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID) { - eventActionDefinitionArray[index].enabled = false; - } - } - } - } else { + message.assertTC(19, 5); + + uint16_t numberOfEventActionDefinitions = message.readUint16(); + if (numberOfEventActionDefinitions != 0){ + for (uint16_t i = 0; i < numberOfEventActionDefinitions; i++) { + uint16_t applicationID = message.readEnum16(); + uint16_t eventDefinitionID = message.readEnum16(); for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { - if (not eventActionDefinitionArray[index].empty){ + if (eventActionDefinitionArray[index].applicationId == applicationID && + eventActionDefinitionArray[index].eventDefinitionID == eventDefinitionID) { eventActionDefinitionArray[index].enabled = false; } } } + } else { + for (uint16_t index = 0; index < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; index++) { + if (not eventActionDefinitionArray[index].empty){ + eventActionDefinitionArray[index].enabled = false; + } + } } } void EventActionService::requestEventActionDefinitionStatus(Message message) { // TC[19,6] - if (message.messageType == 6 && message.packetType == Message::TC && message.serviceType - == 19) { - eventActionStatusReport(); - } + message.assertTC(19, 6); + + eventActionStatusReport(); } void EventActionService::eventActionStatusReport() { @@ -171,29 +162,25 @@ void EventActionService::eventActionStatusReport() { void EventActionService::enableEventActionFunction(Message message) { // TC[19,8] - if (message.messageType == 8 && message.packetType == Message::TC && message.serviceType - == 19) { - setEventActionFunctionStatus(true); - } + message.assertTC(19, 8); + + setEventActionFunctionStatus(true); } void EventActionService::disableEventActionFunction(Message message) { // TC[19,9] - if (message.messageType == 9 && message.packetType == Message::TC && message.serviceType - == 19) { - setEventActionFunctionStatus(false); - } + message.assertTC(19, 9); + + setEventActionFunctionStatus(false); } -// Should I use the name execute here instead of executeAction? -// Should I use applicationID too? +// TODO: Should I use applicationID too? void EventActionService::executeAction(uint16_t eventID) { // Custom function if (eventActionFunctionStatus) { for (uint16_t i = 0; i < ECSS_EVENT_ACTION_STRUCT_ARRAY_SIZE; i++) { if (not eventActionDefinitionArray[i].empty && - eventActionDefinitionArray[i].enabled == - true) { + eventActionDefinitionArray[i].enabled) { if (eventActionDefinitionArray[i].eventDefinitionID == eventID) { MessageParser messageParser; Message message = messageParser.parseRequestTC( diff --git a/src/Services/EventReportService.cpp b/src/Services/EventReportService.cpp index 162b4b2349e6f5a14f264d1cf5a027580282c960..f537f32988fe319ffb79f46f5985656f09868241 100644 --- a/src/Services/EventReportService.cpp +++ b/src/Services/EventReportService.cpp @@ -71,51 +71,49 @@ EventReportService::highSeverityAnomalyReport(Event eventID, const String<64> & void EventReportService::enableReportGeneration(Message message) { // TC[5,5] - if (message.serviceType == 5 && message.packetType == Message::TC && message.messageType == 5) { - /** - * @todo: Report an error if length > numberOfEvents - */ - uint16_t length = message.readUint16(); - Event eventID[length]; + message.assertTC(5, 5); + + /** + * @todo: Report an error if length > numberOfEvents + */ + uint16_t length = message.readUint16(); + Event eventID[length]; + for (uint16_t i = 0; i < length; i++) { + eventID[i] = static_cast<Event >(message.readEnum16()); + } + if (length <= numberOfEvents) { for (uint16_t i = 0; i < length; i++) { - eventID[i] = static_cast<Event >(message.readEnum16()); + stateOfEvents[static_cast<uint16_t> (eventID[i])] = true; } - if (length <= numberOfEvents) { - for (uint16_t i = 0; i < length; i++) { - stateOfEvents[static_cast<uint16_t> (eventID[i])] = true; - } - } - disabledEventsCount = stateOfEvents.size() - stateOfEvents.count(); } + disabledEventsCount = stateOfEvents.size() - stateOfEvents.count(); } void EventReportService::disableReportGeneration(Message message) { // TC[5,6] - if (message.serviceType == 5 && message.packetType == Message::TC && message.messageType - == 6) { - /** - * @todo: Report an error if length > numberOfEvents - */ - uint16_t length = message.readUint16(); - Event eventID[length]; + message.assertTC(5, 6); + + /** + * @todo: Report an error if length > numberOfEvents + */ + uint16_t length = message.readUint16(); + Event eventID[length]; + for (uint16_t i = 0; i < length; i++) { + eventID[i] = static_cast<Event >(message.readEnum16()); + } + if (length <= numberOfEvents) { for (uint16_t i = 0; i < length; i++) { - eventID[i] = static_cast<Event >(message.readEnum16()); - } - if (length <= numberOfEvents) { - for (uint16_t i = 0; i < length; i++) { - stateOfEvents[static_cast<uint16_t> (eventID[i])] = false; - } + stateOfEvents[static_cast<uint16_t> (eventID[i])] = false; } - disabledEventsCount = stateOfEvents.size() - stateOfEvents.count(); } + disabledEventsCount = stateOfEvents.size() - stateOfEvents.count(); } void EventReportService::requestListOfDisabledEvents(Message message) { // TC[5,7] - // I think this is all that is needed here. - if (message.serviceType == 5 && message.packetType == Message::TC && message.messageType == 7) { - listOfDisabledEventsReport(); - } + message.assertTC(5, 7); + + listOfDisabledEventsReport(); } void EventReportService::listOfDisabledEventsReport() { @@ -125,7 +123,7 @@ void EventReportService::listOfDisabledEventsReport() { uint16_t numberOfDisabledEvents = stateOfEvents.size() - stateOfEvents.count(); report.appendHalfword(numberOfDisabledEvents); for (uint16_t i = 0; i < stateOfEvents.size(); i++) { - if (stateOfEvents[i] == 0) { + if (not stateOfEvents[i]) { report.appendEnum16(i); } } diff --git a/src/Services/MemoryManagementService.cpp b/src/Services/MemoryManagementService.cpp index f904291c44b171161064a131300c79847b785346..c29c8fc1fc6a60efda6386a10d20c733d7ad78b2 100644 --- a/src/Services/MemoryManagementService.cpp +++ b/src/Services/MemoryManagementService.cpp @@ -15,7 +15,7 @@ MemoryManagementService::RawDataMemoryManagement::RawDataMemoryManagement( // Function declarations for the raw data memory management subservice void MemoryManagementService::RawDataMemoryManagement::loadRawData(Message &request) { /** - * Bare in mind that there is currently no error checking for invalid parameters. + * Bear in mind that there is currently no error checking for invalid parameters. * A future version will include error checking and the corresponding error report/notification, * as the manual implies. * @@ -23,8 +23,7 @@ void MemoryManagementService::RawDataMemoryManagement::loadRawData(Message &requ * @todo Add failure reporting */ // Check if we have the correct packet - assert(request.serviceType == 6); - assert(request.messageType == 2); + request.assertTC(6, 2); // Read the memory ID from the request auto memoryID = MemoryManagementService::MemoryID(request.readEnum8()); @@ -74,8 +73,7 @@ void MemoryManagementService::RawDataMemoryManagement::loadRawData(Message &requ void MemoryManagementService::RawDataMemoryManagement::dumpRawData(Message &request) { // Check if we have the correct packet - assert(request.serviceType == 6); - assert(request.messageType == 5); + request.assertTC(6, 5); // Create the report message object of telemetry message subtype 6 Message report = mainService.createTM(6); @@ -124,8 +122,7 @@ void MemoryManagementService::RawDataMemoryManagement::dumpRawData(Message &requ void MemoryManagementService::RawDataMemoryManagement::checkRawData(Message &request) { // Check if we have the correct packet - assert(request.serviceType == 6); - assert(request.messageType == 9); + request.assertTC(6, 9); // Create the report message object of telemetry message subtype 10 Message report = mainService.createTM(10); diff --git a/src/Services/ParameterService.cpp b/src/Services/ParameterService.cpp index bf19881992e6265b8254ae0c09bc118a665a780f..b32fa5b589adf76d9910c7fd3ca1c3aa33803f38 100644 --- a/src/Services/ParameterService.cpp +++ b/src/Services/ParameterService.cpp @@ -2,13 +2,9 @@ #define DEMOMODE -#ifdef DEMOMODE - #include <ctime> #include <cstdlib> -#endif - ParameterService::ParameterService() { #ifdef DEMOMODE // Test code, setting up some of the parameter fields @@ -16,56 +12,87 @@ ParameterService::ParameterService() { time_t currTime = time(nullptr); struct tm *today = localtime(&currTime); - paramsList[0].paramId = 0; // random parameter ID - paramsList[0].settingData = today->tm_hour; // the current hour - paramsList[0].ptc = 3; // unsigned int - paramsList[0].pfc = 14; // 32 bits + Parameter test1, test2; + + test1.settingData = today->tm_hour; // the current hour + test1.ptc = 3; // unsigned int + test1.pfc = 14; // 32 bits + + test2.settingData = today->tm_min; // the current minute + test2.ptc = 3; // unsigned int + test2.pfc = 14; // 32 bits + + // MAKE SURE THE IDS ARE UNIQUE WHEN INSERTING! + /** + * @todo: Make a separate insert() function for parameter insertion to protect from blunders + * if needed to + */ + + paramsList.insert(std::make_pair(0, test1)); + paramsList.insert(std::make_pair(1, test2)); - paramsList[1].paramId = 1; // random parameter ID - paramsList[1].settingData = today->tm_min; // the current minute - paramsList[1].ptc = 3; // unsigned int - paramsList[1].pfc = 14; // 32 bits #endif } -void ParameterService::reportParameterIds(Message paramIds) { +void ParameterService::reportParameterIds(Message& paramIds) { + paramIds.assertTC(20, 1); Message reqParam(20, 2, Message::TM, 1); // empty TM[20, 2] parameter report message - if (paramIds.packetType == Message::TC && paramIds.serviceType == 20 && - paramIds.messageType == 1) { - uint16_t ids = paramIds.readUint16(); - reqParam.appendUint16(numOfValidIds(paramIds)); // include the number of valid IDs - - for (int i = 0; i < ids; i++) { - uint16_t currId = paramIds.readUint16(); // current ID to be appended - - if (currId < CONFIGLENGTH) { // check to prevent out-of-bounds access due to invalid id - reqParam.appendUint16(currId); - reqParam.appendUint32(paramsList[currId].settingData); - } else { - // generate failure of execution notification for ST[06] - continue; //ignore the invalid ID - } + paramIds.resetRead(); // since we're passing a reference, the reading position shall be reset + // to its default before any read operations (to ensure the correct data is being read) + + // assertion: correct message, packet and service type (at failure throws an + // InternalError::UnacceptablePacket) + ErrorHandler::assertRequest(paramIds.packetType == Message::TC, paramIds, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + ErrorHandler::assertRequest(paramIds.messageType == 1, paramIds, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + ErrorHandler::assertRequest(paramIds.serviceType == 20, paramIds, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + + uint16_t ids = paramIds.readUint16(); + reqParam.appendUint16(numOfValidIds(paramIds)); // include the number of valid IDs + + for (int i = 0; i < ids; i++) { + uint16_t currId = paramIds.readUint16(); // current ID to be appended + + if (paramsList.find(currId) != paramsList.end()) { + reqParam.appendUint16(currId); + reqParam.appendUint32(paramsList[currId].settingData); + } else { + ErrorHandler::reportError(paramIds, + ErrorHandler::ExecutionStartErrorType::UnknownExecutionStartError); + continue; // generate failed start of execution notification & ignore } } storeMessage(reqParam); } -void ParameterService::setParameterIds(Message newParamValues) { - if (newParamValues.packetType == Message::TC && newParamValues.serviceType == 20 && - newParamValues.messageType == 3) { - uint16_t ids = newParamValues.readUint16(); //get number of ID's +void ParameterService::setParameterIds(Message& newParamValues) { + newParamValues.assertTC(20, 3); - for (int i = 0; i < ids; i++) { - uint16_t currId = newParamValues.readUint16(); + // assertion: correct message, packet and service type (at failure throws an + // InternalError::UnacceptablePacket which gets logged) - if (currId < CONFIGLENGTH) { - paramsList[currId].settingData = newParamValues.readUint32(); - } else { - // generate failure of execution notification for ST[06] - continue; // ignore the invalid ID - } + ErrorHandler::assertRequest(newParamValues.packetType == Message::TC, newParamValues, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + ErrorHandler::assertRequest(newParamValues.messageType == 3, newParamValues, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + ErrorHandler::assertRequest(newParamValues.serviceType == 20, newParamValues, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + + uint16_t ids = newParamValues.readUint16(); //get number of ID's + + for (int i = 0; i < ids; i++) { + uint16_t currId = newParamValues.readUint16(); + + if (paramsList.find(currId) != paramsList.end()) { + paramsList[currId].settingData = newParamValues.readUint32(); + } else { + ErrorHandler::reportError(newParamValues, + ErrorHandler::ExecutionStartErrorType::UnknownExecutionStartError); + continue; // generate failed start of execution notification & ignore } } } @@ -85,7 +112,7 @@ uint16_t ParameterService::numOfValidIds(Message idMsg) { idMsg.readUint32(); //skip the 32bit settings blocks, we need only the IDs } - if (currId < CONFIGLENGTH) { + if (paramsList.find(currId) != paramsList.end()) { validIds++; } } diff --git a/src/Services/RequestVerificationService.cpp b/src/Services/RequestVerificationService.cpp index 768971daf89b7388075adad9f3e6a471b0795e0c..465b1c5635ed2ac2164433cf282defa377e7b838 100644 --- a/src/Services/RequestVerificationService.cpp +++ b/src/Services/RequestVerificationService.cpp @@ -152,7 +152,8 @@ RequestVerificationService::failRoutingVerification(const Message &request, storeMessage(report); } - +// TODO: This function should not be here. These are TM messages, but `execute` should accept a +// TC message. void RequestVerificationService::execute(const Message &message) { switch (message.messageType) { case 1: diff --git a/src/Services/TestService.cpp b/src/Services/TestService.cpp index 2584c75cb529826e3653a56cda8eb33d114933be..224c2614d6a29742bb57162e1d96669bdb3ffa21 100644 --- a/src/Services/TestService.cpp +++ b/src/Services/TestService.cpp @@ -1,6 +1,7 @@ #include "Services/TestService.hpp" void TestService::areYouAlive(Message &request) { + request.assertTC(17, 1); // TM[17,2] are-you-alive connection test report Message report = createTM(2); @@ -8,6 +9,7 @@ void TestService::areYouAlive(Message &request) { } void TestService::onBoardConnection(Message &request) { + request.assertTC(17, 3); // TM[17,4] on-board connection test report Message report = createTM(4); diff --git a/src/Services/TimeManagementService.cpp b/src/Services/TimeManagementService.cpp index 2b3feb68aa059b7131863d84cd2d6e79d8328fa1..c6f922953ba4b434dd8a2b6461f5eab05d435aea 100644 --- a/src/Services/TimeManagementService.cpp +++ b/src/Services/TimeManagementService.cpp @@ -1,20 +1,27 @@ #include "Services/TimeManagementService.hpp" -void TimeManagementService::cucTimeReport() { - // TM[9,2] CUC time report +void TimeManagementService::cdsTimeReport(TimeAndDate &TimeInfo) { + // TM[9,3] CDS time report - Message timeReport = createTM(2); + Message timeReport = createTM(3); - /** - * For the time being we will use C++ functions to get a time value, but this will change - * when the RTC will be implemented - */ - uint32_t seconds; - seconds = time(nullptr); // seconds have passed since 00:00:00 GMT, Jan 1, 1970 - uint64_t timeFormat = TimeHelper::implementCUCTimeFormat(seconds); // store the return value + uint64_t timeFormat = TimeHelper::generateCDStimeFormat(TimeInfo); - timeReport.appendByte(timeFormat); // append the P-field - timeReport.appendWord(timeFormat >> 8); // append the T-field + timeReport.appendHalfword(static_cast<uint16_t >(timeFormat >> 32)); + timeReport.appendWord(static_cast<uint32_t >(timeFormat)); storeMessage(timeReport); } + +TimeAndDate TimeManagementService::cdsTimeRequest(Message &message) { + // TC[9,128] CDS time request + message.assertTC(9, 128); + + // check if we have the correct size of the data. The size should be 6 (48 bits) + ErrorHandler::assertRequest(message.dataSize == 6, message, + ErrorHandler::AcceptanceErrorType::UnacceptableMessage); + + TimeAndDate timeInfo = TimeHelper::parseCDStimeFormat(message.data); + + return timeInfo; +} diff --git a/src/main.cpp b/src/main.cpp index ea2a99af0ce752e6fdf312071f2970f1ce3505fb..5615e2641d4329f20a94335f149b62b05f9279df 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,5 @@ #include <iostream> +#include <ServicePool.hpp> #include "Helpers/CRCHelper.hpp" #include "Helpers/TimeHelper.hpp" #include "Services/TestService.hpp" @@ -35,7 +36,7 @@ int main() { std::cout << packet.readFloat() << " " << std::dec << packet.readSint32() << std::endl; // ST[17] test - TestService testService; + TestService & testService = Services.testService; Message receivedPacket = Message(17, 1, Message::TC, 1); testService.areYouAlive(receivedPacket); receivedPacket = Message(17, 3, Message::TC, 1); @@ -44,7 +45,7 @@ int main() { // ST[20] test - ParameterService paramService; + ParameterService & paramService = Services.parameterManagement; // Test code for reportParameter Message sentPacket = Message(20, 1, Message::TC, 1); //application id is a dummy number (1) @@ -72,7 +73,7 @@ int main() { *(pStr + 1) = 'G'; *(pStr + 2) = '\0'; - MemoryManagementService memMangService; + MemoryManagementService & memMangService = Services.memoryManagement; Message rcvPack = Message(6, 5, Message::TC, 1); rcvPack.appendEnum8(MemoryManagementService::MemoryID::EXTERNAL); // Memory ID rcvPack.appendUint16(3); // Iteration count @@ -112,7 +113,7 @@ int main() { // ST[01] test - RequestVerificationService reqVerifService; + RequestVerificationService & reqVerifService = Services.requestVerification; Message receivedMessage = Message(1, 1, Message::TC, 3); reqVerifService.successAcceptanceVerification(receivedMessage); @@ -196,14 +197,17 @@ int main() { errorMessage.appendBits(2, 7); errorMessage.appendByte(15); - - // TimeHelper test - uint64_t test = TimeHelper::implementCUCTimeFormat(1200); - std::cout << "\n" << test << "\n"; - // ST[09] test - TimeManagementService timeReport; - timeReport.cucTimeReport(); + TimeManagementService & timeReport = Services.timeManagement; + TimeAndDate timeInfo; + // 10/04/1998 10:15:00 + timeInfo.year = 1998; + timeInfo.month = 4; + timeInfo.day = 10; + timeInfo.hour = 10; + timeInfo.minute = 15; + timeInfo.second = 0; + timeReport.cdsTimeReport(timeInfo); // ST[05] (5,5 to 5,8) test [works] EventReportService::Event eventIDs[] = {EventReportService::HighSeverityUnknownEvent, @@ -226,7 +230,7 @@ int main() { // ST[19] test - EventActionService eventActionService; + EventActionService & eventActionService = Services.eventAction; Message eventActionDefinition(19, 1, Message::TC, 1); eventActionDefinition.appendEnum16(0); eventActionDefinition.appendEnum16(2); diff --git a/test/Helpers/TimeAndDate.cpp b/test/Helpers/TimeAndDate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44d1c43938ee20b9e2de6f3d040b3dba2b7a07a2 --- /dev/null +++ b/test/Helpers/TimeAndDate.cpp @@ -0,0 +1,234 @@ +#include "catch2/catch.hpp" +#include "Helpers/TimeAndDate.hpp" + + +TEST_CASE("Date comparison", "[operands]") { + + SECTION("Invalid date") { + TimeAndDate InvalidDate0(1900, 2, 2, 4, 5, 6); // error in year + TimeAndDate InvalidDate1(2030, 70, 2, 4, 5, 6); // error in month + TimeAndDate InvalidDate2(2030, 2, 73, 4, 5, 6); // error in day + TimeAndDate InvalidDate3(2030, 2, 2, 74, 5, 6); // error in hour + TimeAndDate InvalidDate4(2030, 2, 2, 4, 75, 6); // error in minute + TimeAndDate InvalidDate5(2030, 2, 2, 4, 5, 76); // error in seconds + } + + SECTION("Different year") { + TimeAndDate Now; + // 10/04/2021 10:15:00 + Now.year = 2021; + Now.month = 4; + Now.day = 10; + Now.hour = 10; + Now.minute = 15; + Now.second = 0; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now < Date) == false); + CHECK((Now > Date) == true); + CHECK((Now > Date) == true); + CHECK((Now < Date) == false); + + CHECK((Now <= Date) == false); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == false); + + CHECK((Now == Date) == false); + } + + SECTION("Different month") { + + TimeAndDate Now; + // 10/05/2020 10:15:00 + Now.year = 2020; + Now.month = 5; + Now.day = 10; + Now.hour = 10; + Now.minute = 15; + Now.second = 0; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now < Date) == false); + CHECK((Now > Date) == true); + CHECK((Now > Date) == true); + CHECK((Now < Date) == false); + + CHECK((Now <= Date) == false); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == false); + + CHECK((Now == Date) == false); + } + + SECTION("Different day") { + TimeAndDate Now; + // 11/04/2020 10:15:00 + Now.year = 2020; + Now.month = 5; + Now.day = 11; + Now.hour = 10; + Now.minute = 15; + Now.second = 0; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now < Date) == false); + CHECK((Now > Date) == true); + CHECK((Now > Date) == true); + CHECK((Now < Date) == false); + + CHECK((Now <= Date) == false); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == false); + + CHECK((Now == Date) == false); + } + + SECTION("Different hour") { + TimeAndDate Now; + // 10/04/2020 11:15:00 + Now.year = 2020; + Now.month = 4; + Now.day = 10; + Now.hour = 11; + Now.minute = 15; + Now.second = 0; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now < Date) == false); + CHECK((Now > Date) == true); + CHECK((Now > Date) == true); + CHECK((Now < Date) == false); + + CHECK((Now <= Date) == false); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == false); + + CHECK((Now == Date) == false); + } + + SECTION("Different minute") { + TimeAndDate Now; + // 10/04/2020 10:16:00 + Now.year = 2020; + Now.month = 4; + Now.day = 10; + Now.hour = 10; + Now.minute = 16; + Now.second = 0; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now < Date) == false); + CHECK((Now > Date) == true); + CHECK((Now > Date) == true); + CHECK((Now < Date) == false); + + CHECK((Now <= Date) == false); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == false); + + CHECK((Now == Date) == false); + } + + SECTION("Different second") { + TimeAndDate Now; + // 10/04/2020 10:15:01 + Now.year = 2020; + Now.month = 4; + Now.day = 10; + Now.hour = 10; + Now.minute = 15; + Now.second = 1; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now < Date) == false); + CHECK((Now > Date) == true); + CHECK((Now > Date) == true); + CHECK((Now < Date) == false); + + CHECK((Now <= Date) == false); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == false); + + CHECK((Now == Date) == false); + } + + SECTION("Same date") { + TimeAndDate Now; + // 10/04/2020 10:15:01 + Now.year = 2020; + Now.month = 4; + Now.day = 10; + Now.hour = 10; + Now.minute = 15; + Now.second = 0; + + TimeAndDate Date; + // 10/04/2020 10:15:00 + Date.year = 2020; + Date.month = 4; + Date.day = 10; + Date.hour = 10; + Date.minute = 15; + Date.second = 0; + + CHECK((Now == Date) == true); + CHECK((Now <= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now >= Date) == true); + CHECK((Now <= Date) == true); + } +} diff --git a/test/Helpers/TimeHelper.cpp b/test/Helpers/TimeHelper.cpp index 0b23a2a05d7bb06a032bbfee1c51f2baa6d2f23d..31fb012da5fff869c06e1305fa6e194b7cf9be0b 100644 --- a/test/Helpers/TimeHelper.cpp +++ b/test/Helpers/TimeHelper.cpp @@ -2,9 +2,230 @@ #include "Helpers/TimeHelper.hpp" TEST_CASE("Time format implementation", "[CUC]") { - // very simple tests for the TimeHelper - CHECK(TimeHelper::implementCUCTimeFormat(60) == 0b11110000110010); - CHECK(TimeHelper::implementCUCTimeFormat(1000) == 0x3E832); - CHECK(TimeHelper::implementCUCTimeFormat(1200) == 0x4B032); + SECTION("Invalid date") { + TimeAndDate TimeInfo; + + // invalid year + TimeInfo.year = 2018; + TimeInfo.month = 4; + TimeInfo.day = 10; + TimeInfo.hour = 10; + TimeInfo.minute = 15; + TimeInfo.second = 0; + + TimeHelper time; + TimeHelper::utcToSeconds(TimeInfo); + + // invalid month + TimeInfo.year = 2018; + TimeInfo.month = 60; + TimeInfo.day = 10; + TimeInfo.hour = 10; + TimeInfo.minute = 15; + TimeInfo.second = 0; + + TimeHelper::utcToSeconds(TimeInfo); + + // invalid day + TimeInfo.year = 2018; + TimeInfo.month = 4; + TimeInfo.day = 35; + TimeInfo.hour = 10; + TimeInfo.minute = 15; + TimeInfo.second = 0; + + TimeHelper::utcToSeconds(TimeInfo); + + // invalid hour + TimeInfo.year = 2018; + TimeInfo.month = 4; + TimeInfo.day = 10; + TimeInfo.hour = 100; + TimeInfo.minute = 15; + TimeInfo.second = 0; + + TimeHelper::utcToSeconds(TimeInfo); + + // invalid minute + TimeInfo.year = 2018; + TimeInfo.month = 4; + TimeInfo.day = 10; + TimeInfo.hour = 10; + TimeInfo.minute = 200; + TimeInfo.second = 0; + + TimeHelper::utcToSeconds(TimeInfo); + + // invalid second + TimeInfo.year = 2018; + TimeInfo.month = 4; + TimeInfo.day = 10; + TimeInfo.hour = 10; + TimeInfo.minute = 15; + TimeInfo.second = 122; + + TimeHelper::utcToSeconds(TimeInfo); + } + + SECTION("Convert UTC date to elapsed seconds since Unix epoch") { + TimeAndDate TimeInfo; + // 10/04/2020 10:15:00 + TimeInfo.year = 2020; + TimeInfo.month = 4; + TimeInfo.day = 10; + TimeInfo.hour = 10; + TimeInfo.minute = 15; + TimeInfo.second = 0; + + TimeHelper time; + uint32_t currTime = TimeHelper::utcToSeconds(TimeInfo); + + uint16_t elapsedDays = currTime / 86400; + uint32_t msOfDay = currTime % 86400 * 1000; + uint64_t timeFormat = (static_cast<uint64_t>(elapsedDays) << 32 | msOfDay); + CHECK(TimeHelper::generateCDStimeFormat(TimeInfo) == timeFormat); + + // 1/1/2019 00:00:00 + TimeInfo.year = 2019; + TimeInfo.month = 1; + TimeInfo.day = 1; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + currTime = TimeHelper::utcToSeconds(TimeInfo); + + elapsedDays = currTime / 86400; + msOfDay = currTime % 86400 * 1000; + timeFormat = (static_cast<uint64_t>(elapsedDays) << 32 | msOfDay); + CHECK(TimeHelper::generateCDStimeFormat(TimeInfo) == timeFormat); + + // 5/12/2020 00:00:00 + TimeInfo.year = 2020; + TimeInfo.month = 12; + TimeInfo.day = 5; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + currTime = TimeHelper::utcToSeconds(TimeInfo); + CHECK(currTime == 1607126400); + + // 10/12/2020 00:00:00 + TimeInfo.year = 2020; + TimeInfo.month = 12; + TimeInfo.day = 10; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + currTime = TimeHelper::utcToSeconds(TimeInfo); + CHECK(currTime == 1607558400); + + // 15/12/2020 00:00:00 + TimeInfo.year = 2020; + TimeInfo.month = 12; + TimeInfo.day = 15; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + currTime = TimeHelper::utcToSeconds(TimeInfo); + CHECK(currTime == 1607990400); + + // 20/12/2020 00:00:00 + TimeInfo.year = 2020; + TimeInfo.month = 12; + TimeInfo.day = 20; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + currTime = TimeHelper::utcToSeconds(TimeInfo); + CHECK(currTime == 1608422400); + } + + SECTION("Convert elapsed seconds since Unix epoch to UTC date") { + uint32_t seconds = 1586513700; // elapsed seconds between 10/04/2020 10:15:00 and Unix epoch + + TimeHelper time; + TimeAndDate TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2020); + CHECK(TimeInfo.month == 4); + CHECK(TimeInfo.day == 10); + CHECK(TimeInfo.hour == 10); + CHECK(TimeInfo.minute == 15); + CHECK(TimeInfo.second == 0); + + seconds = 1546300800; // elapsed seconds between 1/1/2019 00:00:00 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2019); + CHECK(TimeInfo.month == 1); + CHECK(TimeInfo.day == 1); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); + + seconds = 1550966400; // elapsed seconds between 24/2/2019 00:00:00 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2019); + CHECK(TimeInfo.month == 2); + CHECK(TimeInfo.day == 24); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); + + seconds = 1551571200; // elapsed seconds between 3/3/2019 00:00:00 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2019); + CHECK(TimeInfo.month == 3); + CHECK(TimeInfo.day == 3); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); + + seconds = 1742907370; // elapsed seconds between 25/3/2025 12:56:10 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2025); + CHECK(TimeInfo.month == 3); + CHECK(TimeInfo.day == 25); + CHECK(TimeInfo.hour == 12); + CHECK(TimeInfo.minute == 56); + CHECK(TimeInfo.second == 10); + + seconds = 1583020800; // elapsed seconds between 1/3/2020 00:00:00 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2020); + CHECK(TimeInfo.month == 3); + CHECK(TimeInfo.day == 1); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); + + seconds = 1582934400; // elapsed seconds between 2/29/2020 00:00:00 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2020); + CHECK(TimeInfo.month == 2); + CHECK(TimeInfo.day == 29); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); + + seconds = 1577923200; // elapsed seconds between 2/1/2020 00:00:00 and Unix epoch + + TimeInfo = TimeHelper::secondsToUTC(seconds); + CHECK(TimeInfo.year == 2020); + CHECK(TimeInfo.month == 1); + CHECK(TimeInfo.day == 2); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); + } } diff --git a/test/Message.cpp b/test/Message.cpp index f0b78e3c5af4a8e330282c3c6cbd4ef571c0fb37..01df6ce0f149d21a9d2c9c381e372fb7ab904e0b 100644 --- a/test/Message.cpp +++ b/test/Message.cpp @@ -173,3 +173,85 @@ TEST_CASE("Requirement 7.3.13 (Packet)", "[message][ecss]") { CHECK(static_cast<int>(telemetry.packetType) == 0); CHECK(static_cast<int>(telecommand.packetType) == 1); } + +TEST_CASE("Spare field", "[message]") { + Message message1(0, 0, Message::TM, 0); + + message1.appendByte(1); + message1.appendHalfword(2); + message1.appendBits(1, 5); + message1.finalize(); + + CHECK(message1.dataSize == 4); + + Message message2(0, 0, Message::TM, 0); + message2.appendByte(1); + message2.appendHalfword(2); + message2.appendBits(2, 5); + message2.finalize(); + + CHECK(message2.dataSize == 4); + + Message message3(0, 0, Message::TM, 0); + + message3.appendByte(1); + message3.appendHalfword(2); + message3.appendBits(3, 5); + message3.finalize(); + + CHECK(message3.dataSize == 4); + + Message message4(0, 0, Message::TM, 0); + + message4.appendByte(1); + message4.appendHalfword(2); + message4.appendBits(4, 5); + message4.finalize(); + + CHECK(message4.dataSize == 4); + + Message message5(0, 0, Message::TM, 0); + + message5.appendByte(1); + message5.appendHalfword(2); + message5.appendBits(5, 5); + message5.finalize(); + + CHECK(message5.dataSize == 4); + + Message message6(0, 0, Message::TM, 0); + + message6.appendByte(1); + message6.appendHalfword(2); + message6.appendBits(6, 5); + message6.finalize(); + + CHECK(message6.dataSize == 4); + + Message message7(0, 0, Message::TM, 0); + + message7.appendByte(1); + message7.appendHalfword(2); + message7.appendBits(7, 5); + message7.finalize(); + + CHECK(message7.dataSize == 4); + + Message message8(0, 0, Message::TM, 0); + + message8.appendByte(1); + message8.appendHalfword(2); + message8.appendBits(8, 5); + message8.finalize(); + + CHECK(message8.dataSize == 4); + + Message message9(0, 0, Message::TM, 0); + + message9.appendByte(1); + message9.appendHalfword(2); + message9.appendBits(0, 5); + message9.finalize(); + + CHECK(message9.dataSize == 3); +} diff --git a/test/Services/EventActionService.cpp b/test/Services/EventActionService.cpp index f40de3fda9cc5aeab243d61ce786b5c991fb4651..964e8826e64404a08c7c6c544f85c0e69408fa56 100644 --- a/test/Services/EventActionService.cpp +++ b/test/Services/EventActionService.cpp @@ -5,9 +5,11 @@ #include <etl/String.hpp> #include <cstring> #include <iostream> +#include <ServicePool.hpp> + +EventActionService & eventActionService = Services.eventAction; TEST_CASE("Add event-action definitions TC[19,1]", "[service][st09]") { - EventActionService eventActionService; char checkstring[256]; Message message(19, 1, Message::TC, 0); message.appendEnum16(0); @@ -43,7 +45,6 @@ TEST_CASE("Add event-action definitions TC[19,1]", "[service][st09]") { } TEST_CASE("Delete event-action definitions TC[19,2]", "[service][st09]") { - EventActionService eventActionService; Message message0(19, 1, Message::TC, 0); message0.appendEnum16(1); message0.appendEnum16(0); @@ -116,7 +117,6 @@ TEST_CASE("Delete event-action definitions TC[19,2]", "[service][st09]") { } TEST_CASE("Delete all event-action definitions TC[19,3]", "[service][st09]") { - EventActionService eventActionService; Message message0(19, 1, Message::TC, 0); message0.appendEnum16(1); message0.appendEnum16(0); @@ -160,7 +160,6 @@ TEST_CASE("Delete all event-action definitions TC[19,3]", "[service][st09]") { } TEST_CASE("Enable event-action definitions TC[19,4]", "[service][st09]") { - EventActionService eventActionService; Message message0(19, 1, Message::TC, 0); message0.appendEnum16(1); message0.appendEnum16(0); @@ -186,7 +185,6 @@ TEST_CASE("Enable event-action definitions TC[19,4]", "[service][st09]") { } TEST_CASE("Disable event-action definitions TC[19,5]", "[service][st09]") { - EventActionService eventActionService; Message message0(19, 1, Message::TC, 0); message0.appendEnum16(1); message0.appendEnum16(0); @@ -209,7 +207,6 @@ TEST_CASE("Disable event-action definitions TC[19,5]", "[service][st09]") { } TEST_CASE("Request event-action definition status TC[19,6]", "[service][st09]") { - EventActionService eventActionService; Message message(19, 6, Message::TC, 0); eventActionService.requestEventActionDefinitionStatus(message); REQUIRE(ServiceTests::hasOneMessage()); @@ -219,7 +216,6 @@ TEST_CASE("Request event-action definition status TC[19,6]", "[service][st09]") } TEST_CASE("Event-action status report TM[19,7]", "[service][st09]") { - EventActionService eventActionService; Message message0(19, 1, Message::TC, 0); message0.appendEnum16(1); message0.appendEnum16(0); @@ -251,14 +247,12 @@ TEST_CASE("Event-action status report TM[19,7]", "[service][st09]") { } TEST_CASE("Enable event-action function TC[19,8]", "[service][st09]") { - EventActionService eventActionService; Message message(19, 8, Message::TC, 0); eventActionService.enableEventActionFunction(message); CHECK(eventActionService.getEventActionFunctionStatus() == true); } TEST_CASE("Disable event-action function TC[19,9]", "[service][st09]") { - EventActionService eventActionService; Message message(19, 9, Message::TC, 0); eventActionService.disableEventActionFunction(message); CHECK(eventActionService.getEventActionFunctionStatus() == false); diff --git a/test/Services/EventReportService.cpp b/test/Services/EventReportService.cpp index ca90bee5d782856869384041d48f13d13054c694..e34dbca9de8352bb4c7afd09ff4f874f9f922161 100644 --- a/test/Services/EventReportService.cpp +++ b/test/Services/EventReportService.cpp @@ -4,11 +4,9 @@ #include "ServiceTests.hpp" #include <cstring> -/* - * @todo: Change the reinterpret_cast - */ +EventReportService & eventReportService = Services.eventReport; + TEST_CASE("Informative Event Report TM[5,1]", "[service][st05]") { - EventReportService eventReportService; const char eventReportData[] = "HelloWorld"; char checkString[255]; eventReportService.informativeEventReport(EventReportService::InformativeUnknownEvent, @@ -28,7 +26,6 @@ TEST_CASE("Informative Event Report TM[5,1]", "[service][st05]") { } TEST_CASE("Low Severity Anomaly Report TM[5,2]", "[service][st05]") { - EventReportService eventReportService; const char eventReportData[] = "HelloWorld"; char checkString[255]; eventReportService.lowSeverityAnomalyReport(EventReportService::LowSeverityUnknownEvent, @@ -48,7 +45,6 @@ TEST_CASE("Low Severity Anomaly Report TM[5,2]", "[service][st05]") { } TEST_CASE("Medium Severity Anomaly Report TM[5,3]", "[service][st05]") { - EventReportService eventReportService; const char eventReportData[] = "HelloWorld"; char checkString[255]; eventReportService.mediumSeverityAnomalyReport @@ -68,7 +64,6 @@ TEST_CASE("Medium Severity Anomaly Report TM[5,3]", "[service][st05]") { } TEST_CASE("High Severity Anomaly Report TM[5,4]", "[service][st05]") { - EventReportService eventReportService; const char eventReportData[] = "HelloWorld"; char checkString[255]; eventReportService.highSeverityAnomalyReport(EventReportService::HighSeverityUnknownEvent, @@ -88,7 +83,6 @@ TEST_CASE("High Severity Anomaly Report TM[5,4]", "[service][st05]") { } TEST_CASE("Enable Report Generation TC[5,5]", "[service][st05]") { - EventReportService eventReportService; eventReportService.getStateOfEvents().reset(); EventReportService::Event eventID[] = {EventReportService::AssertionFail, EventReportService::LowSeverityUnknownEvent}; @@ -102,7 +96,6 @@ TEST_CASE("Enable Report Generation TC[5,5]", "[service][st05]") { } TEST_CASE("Disable Report Generation TC[5,6]", "[service][st05]") { - EventReportService eventReportService; EventReportService::Event eventID[] = {EventReportService::InformativeUnknownEvent, EventReportService::MediumSeverityUnknownEvent}; Message message(5, 6, Message::TC, 1); @@ -120,7 +113,6 @@ TEST_CASE("Disable Report Generation TC[5,6]", "[service][st05]") { } TEST_CASE("Request list of disabled events TC[5,7]", "[service][st05]") { - EventReportService eventReportService; Message message(5, 7, Message::TC, 1); eventReportService.requestListOfDisabledEvents(message); REQUIRE(ServiceTests::hasOneMessage()); @@ -131,7 +123,6 @@ TEST_CASE("Request list of disabled events TC[5,7]", "[service][st05]") { } TEST_CASE("List of Disabled Events Report TM[5,8]", "[service][st05]") { - EventReportService eventReportService; EventReportService::Event eventID[] = {EventReportService::MCUStart, EventReportService::HighSeverityUnknownEvent}; Message message(5, 6, Message::TC, 1); @@ -156,7 +147,6 @@ TEST_CASE("List of Disabled Events Report TM[5,8]", "[service][st05]") { } TEST_CASE("List of observables 6.5.6", "[service][st05]") { - EventReportService eventReportService; EventReportService::Event eventID[] = {EventReportService::HighSeverityUnknownEvent}; Message message(5, 6, Message::TC, 1); message.appendUint16(1); diff --git a/test/Services/MemoryManagementService.cpp b/test/Services/MemoryManagementService.cpp index 64b0181f904a8d53845d43019c6dc9f579b41b9b..ec1ef2d5c0e4094d1905ad3ebfcc342d5adef396 100644 --- a/test/Services/MemoryManagementService.cpp +++ b/test/Services/MemoryManagementService.cpp @@ -4,6 +4,8 @@ #include "ServiceTests.hpp" #include "Helpers/CRCHelper.hpp" +MemoryManagementService & memMangService = Services.memoryManagement; + TEST_CASE("TM[6,2]", "[service][st06]") { // Required test variables char *pStr = static_cast<char *>(malloc(4)); @@ -12,8 +14,6 @@ TEST_CASE("TM[6,2]", "[service][st06]") { *(pStr + 2) = '\0'; uint8_t data[2] = {'h', 'R'}; - MemoryManagementService memMangService; - Message receivedPacket = Message(6, 2, Message::TC, 1); receivedPacket.appendEnum8(MemoryManagementService::MemoryID::EXTERNAL); // Memory ID receivedPacket.appendUint16(2); // Iteration count diff --git a/test/Services/ParameterService.cpp b/test/Services/ParameterService.cpp index dbf1820b51e3d1d13f13f70e5f3eb7e139289894..61b96d6c1cc1c93cdc0c013717f401cb01c4abec 100644 --- a/test/Services/ParameterService.cpp +++ b/test/Services/ParameterService.cpp @@ -3,18 +3,16 @@ #include "Message.hpp" #include "ServiceTests.hpp" -#define CATCH_CONFIG_MAIN +ParameterService & pserv = Services.parameterManagement; TEST_CASE("Parameter Report Subservice") { - ParameterService pserv; - SECTION("Faulty Instruction Handling Test") { Message request(20, 1, Message::TC, 1); Message report(20, 2, Message::TM, 1); request.appendUint16(2); // number of requested IDs request.appendUint16(34672); // faulty ID in this context - request.appendUint16(3); // valid + request.appendUint16(1); // valid pserv.reportParameterIds(request); report = ServiceTests::get(0); @@ -29,11 +27,19 @@ TEST_CASE("Parameter Report Subservice") { } } + // **WARNING** + // TODO: Update this test (and all tests in general) to use the error handler's output when + // checking for assertions. SECTION("Wrong Message Type Handling Test") { Message falseRequest(15, 3, Message::TM, 1); // a totally wrong message pserv.reportParameterIds(falseRequest); - Message response = ServiceTests::get(0); + Message errorNotif = ServiceTests::get(0); + CHECK(errorNotif.messageType == 4); // check for proper failed start of + // execution notification + CHECK(errorNotif.serviceType == 1); + + Message response = ServiceTests::get(1); CHECK(response.messageType == 2); CHECK(response.serviceType == 20); CHECK(response.packetType == Message::TM); @@ -42,29 +48,44 @@ TEST_CASE("Parameter Report Subservice") { } TEST_CASE("Parameter Setting Subservice") { - ParameterService pserv; - SECTION("Faulty Instruction Handling Test") { Message setRequest(20, 3, Message::TC, 1); Message reportRequest(20, 1, Message::TC, 1); - setRequest.appendUint16(2); // correct number of IDs - setRequest.appendUint16(3); // correct ID + setRequest.appendUint16(2); // total number of IDs + setRequest.appendUint16(1); // correct ID in this context setRequest.appendUint32(3735928559); // 0xDEADBEEF in hex (new setting) setRequest.appendUint16(16742); // faulty ID in this context setRequest.appendUint32(3131746989); // 0xBAAAAAAD (this shouldn't be found in the report) reportRequest.appendUint16(2); reportRequest.appendUint16(16742); - reportRequest.appendUint16(3); + reportRequest.appendUint16(1); // used to be 3, which pointed the bug with + // numOfValidIds out, now is 1 in order to be a valid ID (a separate test for + // numOfValidIds shall be introduced) + + // Since every reporting and setting is called with the same (sometimes faulty) parameters, + // and there are errors generated (as should be) it is important to catch and check for + // them in order to preserve the integrity of the test. pserv.reportParameterIds(reportRequest); - Message before = ServiceTests::get(0); + Message errorNotif1 = ServiceTests::get(0); + CHECK(errorNotif1.messageType == 4); + CHECK(errorNotif1.serviceType == 1); + + Message before = ServiceTests::get(1); pserv.setParameterIds(setRequest); + Message errorNotif2 = ServiceTests::get(2); + CHECK(errorNotif2.messageType == 4); + CHECK(errorNotif2.serviceType == 1); pserv.reportParameterIds(reportRequest); - Message after = ServiceTests::get(1); + Message errorNotif3 = ServiceTests::get(3); + CHECK(errorNotif3.messageType == 4); + CHECK(errorNotif3.serviceType == 1); + + Message after = ServiceTests::get(4); before.readUint16(); after.readUint16(); // skip the number of IDs diff --git a/test/Services/RequestVerificationService.cpp b/test/Services/RequestVerificationService.cpp index 3e80440466cb13eb0a89d49dbc3d23b7eafd43ab..8464dc5b8eb48cb1dfc1de38c0f4bcd3dfc59a20 100644 --- a/test/Services/RequestVerificationService.cpp +++ b/test/Services/RequestVerificationService.cpp @@ -3,9 +3,9 @@ #include <Message.hpp> #include "ServiceTests.hpp" -TEST_CASE("TM[1,1]", "[service][st01]") { - RequestVerificationService reqVerifService; +RequestVerificationService & reqVerifService = Services.requestVerification; +TEST_CASE("TM[1,1]", "[service][st01]") { Message receivedMessage = Message(1, 1, Message::TC, 3); reqVerifService.successAcceptanceVerification(receivedMessage); REQUIRE(ServiceTests::hasOneMessage()); @@ -27,8 +27,6 @@ TEST_CASE("TM[1,1]", "[service][st01]") { } TEST_CASE("TM[1,2]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 2, Message::TC, 3); reqVerifService.failAcceptanceVerification(receivedMessage, ErrorHandler::UnknownAcceptanceError); @@ -52,8 +50,6 @@ TEST_CASE("TM[1,2]", "[service][st01]") { } TEST_CASE("TM[1,3]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 3, Message::TC, 3); reqVerifService.successStartExecutionVerification(receivedMessage); REQUIRE(ServiceTests::hasOneMessage()); @@ -75,8 +71,6 @@ TEST_CASE("TM[1,3]", "[service][st01]") { } TEST_CASE("TM[1,4]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 2, Message::TC, 3); reqVerifService.failStartExecutionVerification(receivedMessage, ErrorHandler::UnknownExecutionStartError); @@ -100,8 +94,6 @@ TEST_CASE("TM[1,4]", "[service][st01]") { } TEST_CASE("TM[1,5]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 5, Message::TC, 3); reqVerifService.successProgressExecutionVerification(receivedMessage, 0); REQUIRE(ServiceTests::hasOneMessage()); @@ -124,8 +116,6 @@ TEST_CASE("TM[1,5]", "[service][st01]") { } TEST_CASE("TM[1,6]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 5, Message::TC, 3); reqVerifService.failProgressExecutionVerification(receivedMessage, ErrorHandler::UnknownExecutionProgressError, @@ -151,8 +141,6 @@ TEST_CASE("TM[1,6]", "[service][st01]") { } TEST_CASE("TM[1,7]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 7, Message::TC, 3); reqVerifService.successCompletionExecutionVerification(receivedMessage); REQUIRE(ServiceTests::hasOneMessage()); @@ -174,8 +162,6 @@ TEST_CASE("TM[1,7]", "[service][st01]") { } TEST_CASE("TM[1,8]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 8, Message::TC, 3); reqVerifService.failCompletionExecutionVerification(receivedMessage, ErrorHandler::UnknownExecutionCompletionError); @@ -198,8 +184,6 @@ TEST_CASE("TM[1,8]", "[service][st01]") { } TEST_CASE("TM[1,10]", "[service][st01]") { - RequestVerificationService reqVerifService; - Message receivedMessage = Message(1, 10, Message::TC, 3); reqVerifService.failRoutingVerification(receivedMessage, ErrorHandler::UnknownRoutingError); REQUIRE(ServiceTests::hasOneMessage()); diff --git a/test/Services/ServiceTests.hpp b/test/Services/ServiceTests.hpp index a160558a0aac56d215ae6af329ce7b690c0b2f4d..09957305df164f3c7042ddd058aa19a4081b7054 100644 --- a/test/Services/ServiceTests.hpp +++ b/test/Services/ServiceTests.hpp @@ -2,7 +2,9 @@ #define ECSS_SERVICES_TESTS_SERVICES_SERVICETESTS_HPP #include <vector> +#include <map> #include <Message.hpp> +#include <ServicePool.hpp> /** * Supporting class for tests against ECSS services @@ -10,8 +12,34 @@ * @todo See if members of this class can be made non-static */ class ServiceTests { +protected: + /** + * The list of Messages that have been sent as a result of all the processing. + * + * Whenever a Message is sent from anywhere in the code, it is stored in this array. The + * testing code can fetch these Messages using the ServiceTests::get() method. + */ static std::vector<Message> queuedMessages; + /** + * The list of Errors that the ErrorHandler caught. + * + * Whenever an Error is thrown anywhere in the code, it is collected in the thrownErrors + * array. Then, the user can tests whether or which types of errors were thrown, using + * the ServiceTests::hasNoErrors() and ServiceTests::thrownError() functions. + * + * A multimap with keys (ErrorHandler::ErrorSource, ErrorHandler::ErrorType) and values of `1`. + * + * @todo If errors get more complex, this should hold the complete error information + */ + static std::multimap<std::pair<ErrorHandler::ErrorSource, uint16_t>, bool> thrownErrors; + + /** + * Whether an error assertion function was called, indicating that we are expecting to see + * Errors thrown after this Message + */ + static bool expectingErrors; + public: /** * Get a message from the list of queued messages to send @@ -22,12 +50,26 @@ public: } /** - * Add a message to the queue of messages to be sent + * Add a message to the queue of messages having been sent */ static void queue(const Message &message) { queuedMessages.push_back(message); } + /** + * Add one error to the list of occurred errors. + * + * @note This function will be called automatically by the ErrorHandler, and should not be + * used in tests. + * + * @param errorSource The source of the error. + * @param errorCode The integer code of the error, coming directly from one of the ErrorCode + * enumerations in ErrorHandler. + */ + static void addError(ErrorHandler::ErrorSource errorSource, uint16_t errorCode) { + thrownErrors.emplace(std::make_pair(errorSource, errorCode), 1); + } + /** * Counts the number of messages in the queue */ @@ -43,10 +85,56 @@ public: } /** - * Remove all the queued messages from the list, starting over from 0 items again + * Reset the testing environment, starting from zero for all parameters */ static void reset() { queuedMessages.clear(); + thrownErrors.clear(); + expectingErrors = false; + + Services.reset(); + } + +/** + * Return whether an error assertion function was called, which means that we are expecting this + * request to contain errors + * @return + */ + static bool isExpectingErrors() { + return expectingErrors; + } + + /** + * Find if there are *no* thrown errors + * @return True if 0 errors were thrown after the message + * @todo Implement a way to run this assertion at the end of every test + */ + static bool hasNoErrors() { + return thrownErrors.empty(); + } + + /** + * Find the number of thrown errors after the processing of this Message. + */ + static uint64_t countErrors() { + expectingErrors = true; + + return thrownErrors.size(); + } + + /** + * Find if an error + * @tparam ErrorType An enumeration of ErrorHandler + * @param errorType The error code of the Error, corresponding to the correct type as + * specified in ErrorHandler + */ + template<typename ErrorType> + static bool thrownError(ErrorType errorType) { + ErrorHandler::ErrorSource errorSource = ErrorHandler::findErrorSource(errorType); + + expectingErrors = true; + + return thrownErrors.find(std::make_pair(errorSource, errorType)) != thrownErrors.end(); } }; diff --git a/test/Services/TestService.cpp b/test/Services/TestService.cpp index a94934ad20836620ec2ab1779d4ce0107798d08c..700c0b9df512d6a5e8aa2ae803762f1e07240294 100644 --- a/test/Services/TestService.cpp +++ b/test/Services/TestService.cpp @@ -3,9 +3,9 @@ #include <Message.hpp> #include "ServiceTests.hpp" -TEST_CASE("TM[17,1]", "[service][st17]") { - TestService testService; +TestService & testService = Services.testService; +TEST_CASE("TM[17,1]", "[service][st17]") { Message receivedPacket = Message(17, 1, Message::TC, 1); testService.areYouAlive(receivedPacket); REQUIRE(ServiceTests::hasOneMessage()); @@ -17,8 +17,6 @@ TEST_CASE("TM[17,1]", "[service][st17]") { } TEST_CASE("TM[17,3]", "[service][st17]") { - TestService testService; - Message receivedPacket = Message(17, 3, Message::TC, 1); receivedPacket.appendEnum16(40); testService.onBoardConnection(receivedPacket); diff --git a/test/Services/TimeManagementService.cpp b/test/Services/TimeManagementService.cpp index 714c99e144480c5037a286a5dcdada334f06d145..f8d0ba754d561656bcb008716d97741f7cf6bb7c 100644 --- a/test/Services/TimeManagementService.cpp +++ b/test/Services/TimeManagementService.cpp @@ -2,15 +2,77 @@ #include <Services/TimeManagementService.hpp> #include "ServiceTests.hpp" -TEST_CASE("TM[9,2]", "[service][st09]") { - TimeManagementService timeFormat; +TimeManagementService & timeService = Services.timeManagement; - uint32_t seconds; - seconds = time(nullptr); +TEST_CASE("TM[9,3]", "[service][st09]") { + TimeAndDate TimeInfo; - timeFormat.cucTimeReport(); + // 10/04/2020 10:15:00 + TimeInfo.year = 2020; + TimeInfo.month = 4; + TimeInfo.day = 10; + TimeInfo.hour = 10; + TimeInfo.minute = 15; + TimeInfo.second = 0; + + uint32_t currTime = TimeHelper::utcToSeconds(TimeInfo); + + uint16_t elapsedDays = currTime/86400; + uint32_t msOfDay = currTime % 86400 * 1000; + uint64_t timeFormat = (static_cast<uint64_t>(elapsedDays) << 32 | msOfDay); + + timeService.cdsTimeReport(TimeInfo); Message response = ServiceTests::get(0); - CHECK(response.readByte() == 50); - CHECK(response.readWord() == seconds); + CHECK(response.serviceType == 9); + CHECK(response.messageType == 3); + CHECK(response.packetType == Message::TM); + CHECK(response.readHalfword() == static_cast<uint16_t>(timeFormat >> 32)); + CHECK(response.readWord() == static_cast<uint32_t >(timeFormat)); + + Message message = Message(9, 128, Message::TC, 3); + message.appendHalfword(static_cast<uint16_t >(timeFormat >> 32)); + message.appendWord(static_cast<uint32_t >(timeFormat)); + + TimeInfo = timeService.cdsTimeRequest(message); + CHECK(TimeInfo.year == 2020); + CHECK(TimeInfo.month == 4); + CHECK(TimeInfo.day == 10); + CHECK(TimeInfo.hour == 10); + CHECK(TimeInfo.minute == 15); + CHECK(TimeInfo.second == 0); + + + // 1/1/2019 00:00:00 + TimeInfo.year = 2019; + TimeInfo.month = 1; + TimeInfo.day = 1; + TimeInfo.hour = 0; + TimeInfo.minute = 0; + TimeInfo.second = 0; + + currTime = TimeHelper::utcToSeconds(TimeInfo); + + elapsedDays = currTime/86400; + msOfDay = currTime % 86400 * 1000; + timeFormat = (static_cast<uint64_t>(elapsedDays) << 32 | msOfDay); + + timeService.cdsTimeReport(TimeInfo); + response = ServiceTests::get(1); + CHECK(response.serviceType == 9); + CHECK(response.messageType == 3); + CHECK(response.packetType == Message::TM); + CHECK(response.readHalfword() == static_cast<uint16_t>(timeFormat >> 32)); + CHECK(response.readWord() == static_cast<uint32_t >(timeFormat)); + + message = Message(9, 128, Message::TC, 3); + message.appendHalfword(static_cast<uint16_t >(timeFormat >> 32)); + message.appendWord(static_cast<uint32_t >(timeFormat)); + TimeInfo = timeService.cdsTimeRequest(message); + CHECK(TimeInfo.year == 2019); + CHECK(TimeInfo.month == 1); + CHECK(TimeInfo.day == 1); + CHECK(TimeInfo.hour == 0); + CHECK(TimeInfo.minute == 0); + CHECK(TimeInfo.second == 0); } diff --git a/test/TestPlatform.cpp b/test/TestPlatform.cpp index 10f9cdf366fd4950138248a6564b33c7d8dd0a10..f6297918c4bd8f09fe7e93a7902bf8ac9833963e 100644 --- a/test/TestPlatform.cpp +++ b/test/TestPlatform.cpp @@ -5,15 +5,49 @@ #include <Service.hpp> #include "Services/ServiceTests.hpp" +// Explicit template specializations for the logError() function +template void ErrorHandler::logError(const Message &, ErrorHandler::AcceptanceErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::ExecutionStartErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::ExecutionProgressErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::ExecutionCompletionErrorType); +template void ErrorHandler::logError(const Message &, ErrorHandler::RoutingErrorType); +template void ErrorHandler::logError(ErrorHandler::InternalErrorType); + +// Initialisation of ServiceTests properties std::vector<Message> ServiceTests::queuedMessages = std::vector<Message>(); +std::multimap<std::pair<ErrorHandler::ErrorSource, uint16_t>, bool> ServiceTests::thrownErrors = + std::multimap<std::pair<ErrorHandler::ErrorSource, uint16_t>, bool>(); +bool ServiceTests::expectingErrors = false; -void Service::storeMessage(const Message &message) { +void Service::storeMessage(Message &message) { + // Just add the message to the queue ServiceTests::queue(message); } +template<typename ErrorType> +void ErrorHandler::logError(const Message &message, ErrorType errorType) { + logError(errorType); +} + +template<typename ErrorType> +void ErrorHandler::logError(ErrorType errorType) { + ServiceTests::addError(ErrorHandler::findErrorSource(errorType), errorType); +} + struct ServiceTestsListener : Catch::TestEventListenerBase { using TestEventListenerBase::TestEventListenerBase; // inherit constructor + void sectionEnded(Catch::SectionStats const §ionStats) override { + // Make sure we don't have any errors + if (not ServiceTests::isExpectingErrors()) { + // An Error was thrown with this Message. If you expected this to happen, please call a + // corresponding assertion function from ServiceTests to silence this message. + + //TODO: Uncomment the following line as soon as Issue #19 is closed + // CHECK(ServiceTests::hasNoErrors()); + } + } + void testCaseEnded(Catch::TestCaseStats const &testCaseStats) override { // Tear-down after a test case is run ServiceTests::reset();