diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..f56d799 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,28 @@ +name: Build and test + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + linux: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y doctest-dev + - name: Configure + run: >- + cmake -S . -B build -DCMAKE_BUILD_TYPE=Release + -DFLIGHT_LOG_BUILD_EXAMPLES=ON + -DFLIGHT_LOG_ENABLE_UNIT_TESTS=ON + - name: Build + run: cmake --build build --parallel 2 + - name: Test + run: ctest --test-dir build --output-on-failure diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b964321 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/build*/ +/install/ +/CMakeUserPresets.json +/.cache/ +.DS_Store diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..31f6096 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,62 @@ +cmake_minimum_required(VERSION 3.16) + +project(FlightLogInspector VERSION 0.1.0 LANGUAGES CXX) + +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) +include(CTest) + +option(FLIGHT_LOG_BUILD_EXAMPLES "Build the reader and writer examples" OFF) +option(FLIGHT_LOG_ENABLE_UNIT_TESTS "Build unit tests using an installed doctest package" OFF) +set(CMAKE_CXX_EXTENSIONS OFF) + +add_library(flight_log + src/data_container.cpp + src/messages.cpp + src/reader.cpp + src/simple_writer.cpp + src/writer.cpp +) +add_library(flight_log::flight_log ALIAS flight_log) +target_compile_features(flight_log PUBLIC cxx_std_17) +target_include_directories(flight_log PUBLIC + $ + $ +) +set_target_properties(flight_log PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR}) + +add_executable(flight-log-inspector src/main.cpp) +target_link_libraries(flight-log-inspector PRIVATE flight_log::flight_log) + +if(FLIGHT_LOG_BUILD_EXAMPLES) + add_subdirectory(examples) +endif() + +if(BUILD_TESTING) + add_subdirectory(tests) +endif() + +set(flight_log_cmake_dir "${CMAKE_INSTALL_LIBDIR}/cmake/flight_log") +configure_package_config_file(cmake/flight_logConfig.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/flight_logConfig.cmake + INSTALL_DESTINATION ${flight_log_cmake_dir} +) +write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/flight_logConfigVersion.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion +) + +install(TARGETS flight-log-inspector RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +install(TARGETS flight_log EXPORT flight_logTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) +install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) +install(EXPORT flight_logTargets NAMESPACE flight_log:: DESTINATION ${flight_log_cmake_dir}) +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/flight_logConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/flight_logConfigVersion.cmake + DESTINATION ${flight_log_cmake_dir} +) +install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DATADIR}/doc/flight-log-inspector) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..55c1085 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing + +## Before you start + +Open an issue for changes that affect the log format, public API, or CLI behavior. Include a +small reproducible example when reporting a parsing issue. + +## Workflow + +1. Create a topic branch from the default branch. +2. Keep each pull request focused on one logical change. +3. Build the project, run CTest with `FLIGHT_LOG_ENABLE_UNIT_TESTS=ON`, and document the inputs + you used to verify the change. +4. Match the surrounding C++ style. Add tests for new behavior in `tests/`. + +Prefer generated or minimized test logs when adding fixtures. Include the source and license +information for any third-party material in [NOTICE](NOTICE). + +Contributions are distributed under the terms in [LICENSE](LICENSE). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4273d4e --- /dev/null +++ b/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2023, PX4 Development Team +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..6fc6f39 --- /dev/null +++ b/NOTICE @@ -0,0 +1,43 @@ +NOTICE + +Flight Log Inspector incorporates BSD 3-Clause-licensed code and test +fixtures from ulog_cpp, published by the PX4 Development Team. + +Source repository: https://github.com/PX4/ulog_cpp +Source snapshot: ff74c6f2fb2e0c48b727f03865eea56ec7f56969 + +The original LICENSE is reproduced verbatim. The derived C++ files +retain their SPDX identifiers and refer here for file copyright notices. +The three ULog fixtures in tests/log_files/ are unchanged copies of the +snapshot's test/log_files/ files. Identifying strings inside these logs +are recorded device metadata, topic names, and log messages. + +Copyright (c) 2026 cpp-hardtech for project-specific modifications. + +Copyright declarations by file + +Copyright (c) 2023 PX4 Development Team. + src/data_container.cpp + src/main.cpp + src/messages.cpp + src/reader.cpp + src/simple_writer.cpp + src/writer.cpp + include/flight_log/data_container.hpp + include/flight_log/data_handler_interface.hpp + include/flight_log/exception.hpp + include/flight_log/messages.hpp + include/flight_log/raw_messages.hpp + include/flight_log/reader.hpp + include/flight_log/simple_writer.hpp + include/flight_log/subscription.hpp + include/flight_log/utils.hpp + include/flight_log/writer.hpp + examples/ulog_data.cpp + examples/ulog_writer.cpp + tests/main.cpp + tests/read_api_test.cpp + tests/ulog_parsing_test.cpp + +Copyright (c) 2025 PX4 Development Team. + examples/ulog_streamed_parsing.cpp diff --git a/README.md b/README.md index 86ec899..6802e1a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,54 @@ -# flight-log-inspector -Inspect ULog flight recordings and verify log quality from the command line. +# Flight Log Inspector + +Flight Log Inspector reads recorded ULog (`.ulg`) flight telemetry. Use the command-line tool +to inspect topic instances and their sample counts, message layouts, metadata, initial and +default parameters, text messages, and logging dropouts. A C++ library exposes typed samples, +incremental parsing, and log writing. + +## Requirements + +- A C++17 compiler, CMake 3.16 or newer, and a little-endian system. +- Optional: an installed doctest CMake package for the C++ unit tests. + +## Build + +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PWD/install" +cmake --build build --parallel +ctest --test-dir build --output-on-failure +cmake --install build +``` + +The CLI, library, and default CLI tests build without external dependencies. Set +`-DFLIGHT_LOG_ENABLE_UNIT_TESTS=ON` to include the C++ test suite and +`-DFLIGHT_LOG_BUILD_EXAMPLES=ON` to build the reader and writer examples. Set +`-DBUILD_TESTING=OFF` to skip test registration. + +## Quick start + +```sh +./install/bin/flight-log-inspector tests/log_files/sample_log_small.ulg +``` + +In the topic listing, `sensor_combined (0) - 1298` means instance 0 has 1,298 samples. +Parsing warnings go to standard error. A fatal parse error or an unreadable file produces a +nonzero exit status. The CLI keeps samples in memory while it builds the report. The C++ +reader can process chunks incrementally for large logs. Logs with appended data segments +may yield partial results. + +## C++ library + +Point `CMAKE_PREFIX_PATH` to the installation directory, then link the library in your project. + +```cmake +find_package(flight_log CONFIG REQUIRED) +target_link_libraries(my_tool PRIVATE flight_log::flight_log) +``` + +Public headers are under `flight_log/`. The [examples](examples/) show typed sample access, +streaming reads, and file writing. + +## Contributing and license + +See [CONTRIBUTING.md](CONTRIBUTING.md). The project is distributed under the BSD 3-Clause +License in [LICENSE](LICENSE). Source and fixture attribution are recorded in [NOTICE](NOTICE). diff --git a/cmake/flight_logConfig.cmake.in b/cmake/flight_logConfig.cmake.in new file mode 100644 index 0000000..106a585 --- /dev/null +++ b/cmake/flight_logConfig.cmake.in @@ -0,0 +1,3 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/flight_logTargets.cmake") diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000..5f1440c --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,4 @@ +foreach(example IN ITEMS ulog_data ulog_streamed_parsing ulog_writer) + add_executable(${example} ${example}.cpp) + target_link_libraries(${example} PRIVATE flight_log::flight_log) +endforeach() diff --git a/examples/ulog_data.cpp b/examples/ulog_data.cpp new file mode 100644 index 0000000..ac08207 --- /dev/null +++ b/examples/ulog_data.cpp @@ -0,0 +1,124 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include +#include +#include +#include +#include + +// Example of how to use the typed data API for accessing topic data + +int main(int argc, char** argv) +{ + if (argc < 2) { + printf("Usage: %s \n", argv[0]); + return -1; + } + FILE* file = fopen(argv[1], "rb"); + if (!file) { + printf("opening file failed\n"); + return -1; + } + uint8_t buffer[4096]; + int bytes_read; + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) { + reader.readChunk(buffer, bytes_read); + } + fclose(file); + + // Check for errors + if (!data_container->parsingErrors().empty()) { + printf("###### File Parsing Errors ######\n"); + for (const auto& parsing_error : data_container->parsingErrors()) { + printf(" %s\n", parsing_error.c_str()); + } + } + if (data_container->hadFatalError()) { + printf("Fatal parsing error, exiting\n"); + return -1; + } + + // Read out some data + + // List all subscription names + auto subscription_names = data_container->subscriptionNames(); + for (const auto& sub : subscription_names) { + std::cout << sub << "\n"; + } + std::cout << "\n"; + + // Get a particular subscription + if (subscription_names.find("vehicle_status") != subscription_names.end()) { + const auto& subscription = data_container->subscription("vehicle_status"); + + // Get message format of subscription + auto message_format = subscription->format(); + std::cout << "Message format: " << message_format->name() << "\n"; + + // List all field names + std::cout << "Field names: " + << "\n"; + for (const std::string& field : subscription->fieldNames()) { + std::cout << " " << field << "\n"; + } + + // Get particular field + try { + auto nav_state_field = subscription->field("nav_state"); + + // Iterate over all samples + std::cout << "nav_state values: \n "; + for (const auto& sample : *subscription) { + // always correctly extracts the type as defined in the message definition, + // gets cast to the value you put in int. + // This also works for arrays and strings. + auto nav_state = sample[nav_state_field].as(); + std::cout << nav_state << ", "; + } + std::cout << "\n"; + + // get a specific sample + auto sample_12 = subscription->at(12); + + // access values by name + auto timestamp = sample_12["timestamp"].as(); + + std::cout << "timestamp at sample 12: " << timestamp << "\n"; + } catch (const flight_log::AccessException& exception) { + std::cout << "AccessException: " << exception.what() << "\n"; + } + } else { + std::cout << "No vehicle_status subscription found\n"; + } + + if (data_container->messageFormats().find("esc_status") != + data_container->messageFormats().end()) { + const auto& message_format = data_container->messageFormats().at("esc_status"); + std::cout << "Message format: " << message_format->name() << "\n"; + for (const auto& field_name : message_format->fieldNames()) { + std::cout << " " << field_name << "\n"; + } + } else { + std::cout << "No esc_status message format found\n"; + } + + if (subscription_names.find("esc_status") != subscription_names.end()) { + try { + auto esc_status = data_container->subscription("esc_status"); + for (const auto& sample : *esc_status) { + std::cout << "esc_power: " << sample["esc"][7]["esc_power"].as() << "\n"; + } + } catch (const flight_log::AccessException& exception) { + std::cout << "AccessException: " << exception.what() << "\n"; + } + } else { + std::cout << "No esc_status subscription found\n"; + } + return 0; +} diff --git a/examples/ulog_streamed_parsing.cpp b/examples/ulog_streamed_parsing.cpp new file mode 100644 index 0000000..f836861 --- /dev/null +++ b/examples/ulog_streamed_parsing.cpp @@ -0,0 +1,186 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +// Example for parsing and processing an ULog file in real-time, without keeping the whole file +// in memory + +class TopicSubscription { + public: + virtual ~TopicSubscription() = default; + + virtual void handleData(const flight_log::TypedDataView& data) = 0; +}; + +// A topic we are interested in +class VehicleStatus : public TopicSubscription { + public: + explicit VehicleStatus(const std::shared_ptr& subscription) + { + _timestamp_field = subscription->field("timestamp"); + _nav_state_field = subscription->field("nav_state"); + // Optional field (e.g. when a message changes) + if (subscription->fieldMap().find("armed_state") != subscription->fieldMap().end()) { + _armed_state_field = subscription->field("armed_state"); + } + } + + void handleData(const flight_log::TypedDataView& data) override + { + const auto timestamp = data[*_timestamp_field].as(); + const auto nav_state = data[*_nav_state_field].as(); + uint8_t armed_state = 0; + if (_armed_state_field) { + armed_state = data[*_nav_state_field].as(); + } + printf("vehicle_status: t: %" PRId64 ": nav_state: %" PRIu32 ", armed_state: %" PRId8 "\n", + timestamp, nav_state, armed_state); + } + + private: + std::shared_ptr _timestamp_field; + std::shared_ptr _nav_state_field; + std::shared_ptr _armed_state_field; +}; + +class ULogDataHandler : public flight_log::DataContainer { + public: + ULogDataHandler() : flight_log::DataContainer(flight_log::DataContainer::StorageConfig::Header) {} + + void error(const std::string& msg, bool is_recoverable) override + { + printf("Parsing error: %s\n", msg.c_str()); + } + + void headerComplete() override { flight_log::DataContainer::headerComplete(); } + + void messageInfo(const flight_log::MessageInfo& message_info) override + { + DataContainer::messageInfo(message_info); + if (message_info.isMulti()) { + // Multi messages might be continued, but we only know with the next message, so we keep it + // stored and append if needed. We assume that continued multi messages are not interleaved + // with other messages. + if (message_info.isContinued()) { + if (_current_multi_message.field().name() == message_info.field().name()) { + // Append to previous + _current_multi_message.valueRaw().insert(_current_multi_message.valueRaw().end(), + message_info.valueRaw().begin(), + message_info.valueRaw().end()); + } + } else { + finishCurrentMultiMessage(); + _current_multi_message = message_info; + } + } else { + finishCurrentMultiMessage(); + messageInfoComplete(message_info); + } + } + void parameter(const flight_log::Parameter& parameter) override + { + finishCurrentMultiMessage(); + DataContainer::parameter(parameter); + } + void addLoggedMessage(const flight_log::AddLoggedMessage& add_logged_message) override + { + finishCurrentMultiMessage(); + DataContainer::addLoggedMessage(add_logged_message); + if (_subscriptions_by_message_id.find(add_logged_message.msgId()) != + _subscriptions_by_message_id.end()) { + throw flight_log::ParsingException("Duplicate AddLoggedMessage message ID"); + } + + auto format_iter = messageFormats().find(add_logged_message.messageName()); + if (format_iter == messageFormats().end()) { + throw flight_log::ParsingException("AddLoggedMessage message format not found"); + } + + auto ulog_subscription = std::make_shared( + add_logged_message, std::vector{}, format_iter->second); + + if (add_logged_message.messageName() == "vehicle_status" && add_logged_message.multiId() == 0) { + auto subscription = std::make_shared(ulog_subscription); + _subscriptions_by_message_id.insert( + {add_logged_message.msgId(), SubscriptionData{ulog_subscription, subscription}}); + } + } + void logging(const flight_log::Logging& logging) override + { + finishCurrentMultiMessage(); + DataContainer::logging(logging); + } + void data(const flight_log::Data& data) override + { + finishCurrentMultiMessage(); + const auto iter = _subscriptions_by_message_id.find(data.msgId()); + if (iter != _subscriptions_by_message_id.end()) { + const flight_log::TypedDataView data_view(data, *iter->second.ulog_subscription->format()); + iter->second.subscription->handleData(data_view); + } + } + + private: + struct SubscriptionData { + std::shared_ptr ulog_subscription; + std::shared_ptr subscription; + }; + + void finishCurrentMultiMessage() + { + if (!_current_multi_message.field().name().empty()) { + messageInfoComplete(_current_multi_message); + _current_multi_message.field() = {}; + } + } + void messageInfoComplete(const flight_log::MessageInfo& message_info) + { + if (message_info.field().definitionResolved()) { + printf("Info message: %s\n", message_info.field().name().c_str()); + } + } + + std::map _subscriptions_by_message_id; + flight_log::MessageInfo _current_multi_message{"", + ""}; ///< Keep this stored for continued messages +}; + +int main(int argc, char** argv) +{ + if (argc < 2) { + printf("Usage: %s \n", argv[0]); + return -1; + } + FILE* file = fopen(argv[1], "rb"); + if (!file) { + printf("opening file failed\n"); + return -1; + } + uint8_t buffer[4096]; + int bytes_read; + const auto data_container = std::make_shared(); + flight_log::Reader reader{data_container}; + while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) { + try { + reader.readChunk(buffer, bytes_read); + } catch (const flight_log::ExceptionBase& exception) { + printf("Failed to parse ulog file: %s\n", exception.what()); + return -1; + } + if (data_container->hadFatalError()) { + printf("Failed to parse ulog file\n"); + return -1; + } + } + fclose(file); + + return 0; +} diff --git a/examples/ulog_writer.cpp b/examples/ulog_writer.cpp new file mode 100644 index 0000000..2d9c9d2 --- /dev/null +++ b/examples/ulog_writer.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include +#include +#include +#include + +// Example of how to create an ULog file with timeseries, printf messages and parameters + +using namespace std::chrono_literals; + +namespace { +uint64_t currentTimeUs() +{ + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} +} // namespace + +struct MyData { + uint64_t timestamp; + float debug_array[4]; + float cpuload; + float temperature; + int8_t counter; + + static std::string messageName() { return "my_data"; } + + static std::vector fields() + { + // clang-format off + return { + {"uint64_t", "timestamp"}, // Monotonic timestamp in microseconds (since boot), must always be the first field + {"float", "debug_array", 4}, + {"float", "cpuload"}, + {"float", "temperature"}, + {"int8_t", "counter"}, + }; // clang-format on + } +}; + +int main(int argc, char** argv) +{ + if (argc < 2) { + printf("Usage: %s \n", argv[0]); + return -1; + } + + try { + flight_log::SimpleWriter writer(argv[1], currentTimeUs()); + writer.writeInfo("sys_name", "ULogExampleWriter"); + + writer.writeParameter("PARAM_A", 382.23F); + writer.writeParameter("PARAM_B", 8272); + + writer.writeMessageFormat(MyData::messageName(), MyData::fields()); + writer.headerComplete(); + + const uint16_t my_data_msg_id = writer.writeAddLoggedMessage(MyData::messageName()); + + writer.writeTextMessage(flight_log::Logging::Level::Info, "Hello world", currentTimeUs()); + + float cpuload = 25.423F; + for (int i = 0; i < 100; ++i) { + MyData data{}; + data.timestamp = currentTimeUs(); + data.cpuload = cpuload; + data.counter = i; + writer.writeData(my_data_msg_id, data); + cpuload -= 0.424F; + + std::this_thread::sleep_for(10ms); + } + } catch (const flight_log::ExceptionBase& e) { + printf("ULog exception: %s\n", e.what()); + } + + return 0; +} diff --git a/include/flight_log/data_container.hpp b/include/flight_log/data_container.hpp new file mode 100644 index 0000000..c4258a5 --- /dev/null +++ b/include/flight_log/data_container.hpp @@ -0,0 +1,150 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include +#include +#include +#include +#include + +#include "data_handler_interface.hpp" +#include "subscription.hpp" + +namespace flight_log { + +class DataContainer : public DataHandlerInterface { + public: + enum class StorageConfig { + Header, ///< keep header in memory (subscriptions are still kept without samples) + FullLog, ///< keep full log in memory + }; + + struct NameAndMultiIdKey { + std::string name; + int multi_id{0}; + + NameAndMultiIdKey() = default; + + NameAndMultiIdKey(std::string name, int multi_id) : name(std::move(name)), multi_id(multi_id) {} + + bool operator==(const NameAndMultiIdKey& other) const + { + return name == other.name && multi_id == other.multi_id; + } + + bool operator<(const NameAndMultiIdKey& other) const + { + return name < other.name || (name == other.name && multi_id < other.multi_id); + } + + bool operator>(const NameAndMultiIdKey& other) const + { + return name > other.name || (name == other.name && multi_id > other.multi_id); + } + }; + + explicit DataContainer(StorageConfig storage_config); + virtual ~DataContainer() = default; + + void error(const std::string& msg, bool is_recoverable) override; + + void headerComplete() override; + + void fileHeader(const FileHeader& header) override; + void messageInfo(const MessageInfo& message_info) override; + void messageFormat(const MessageFormat& message_format) override; + void parameter(const Parameter& parameter) override; + void parameterDefault(const ParameterDefault& parameter_default) override; + void addLoggedMessage(const AddLoggedMessage& add_logged_message) override; + void logging(const Logging& logging) override; + void data(const Data& data) override; + void dropout(const Dropout& dropout) override; + bool isValidDataMessage(uint16_t msg_id, uint16_t payload_size) const override; + + // Stored data + bool isHeaderComplete() const { return _header_complete; } + bool hadFatalError() const { return _had_fatal_error; } + const std::vector& parsingErrors() const { return _parsing_errors; } + const FileHeader& fileHeader() const { return _file_header; } + const std::map& messageInfo() const { return _message_info; } + const std::map>>& messageInfoMulti() const + { + return _message_info_multi; + } + const std::map>& messageFormats() const + { + return _message_formats; + } + const std::map& initialParameters() const { return _initial_parameters; } + const std::map& defaultParameters() const + { + return _default_parameters; + } + const std::vector& changedParameters() const { return _changed_parameters; } + const std::vector& logging() const { return _logging; } + const std::vector& dropouts() const { return _dropouts; } + + const std::map>& subscriptionsByNameAndMultiId() + { + return _subscriptions_by_name_and_multi_id; + } + + const std::map>& subscriptionsByMessageId() + { + return _subscriptions_by_message_id; + } + + std::set subscriptionNames() const + { + std::set names; + for (const auto& kv : _subscriptions_by_name_and_multi_id) { + names.insert(kv.first.name); + } + return names; + } + + std::shared_ptr subscription(const std::string& name, int multi_id = 0) const + { + const auto it = _subscriptions_by_name_and_multi_id.find({name, multi_id}); + if (it == _subscriptions_by_name_and_multi_id.end()) { + throw AccessException("Subscription not found: " + name); + } + return it->second; + } + + protected: + std::map& messageInfoRef() { return _message_info; } + std::map>>& messageInfoMultiRef() + { + return _message_info_multi; + } + std::map& initialParametersRef() { return _initial_parameters; } + std::map& defaultParametersRef() { return _default_parameters; } + std::vector& changedParametersRef() { return _changed_parameters; } + std::vector& loggingRef() { return _logging; } + std::vector& dropoutsRef() { return _dropouts; } + + private: + const StorageConfig _storage_config; + + bool _header_complete{false}; + bool _had_fatal_error{false}; + std::vector _parsing_errors; + + FileHeader _file_header; + std::map _message_info; + std::map>> _message_info_multi; + std::map> _message_formats; + std::map _initial_parameters; + std::map _default_parameters; + std::vector _changed_parameters; + std::map> _subscriptions_by_message_id; + std::map> _subscriptions_by_name_and_multi_id; + std::vector _logging; + std::vector _dropouts; +}; + +} // namespace flight_log diff --git a/include/flight_log/data_handler_interface.hpp b/include/flight_log/data_handler_interface.hpp new file mode 100644 index 0000000..76c28e0 --- /dev/null +++ b/include/flight_log/data_handler_interface.hpp @@ -0,0 +1,46 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include + +#include "messages.hpp" + +namespace flight_log { + +class DataHandlerInterface { + public: + virtual void headerComplete() {} + + virtual void error(const std::string& msg, bool is_recoverable) {} + + // Data methods + virtual void fileHeader(const FileHeader& header) {} + virtual void messageInfo(const MessageInfo& message_info) {} + virtual void messageFormat(const MessageFormat& message_format) {} + virtual void parameter(const Parameter& parameter) {} + virtual void parameterDefault(const ParameterDefault& parameter_default) {} + virtual void addLoggedMessage(const AddLoggedMessage& add_logged_message) {} + virtual void logging(const Logging& logging) {} + virtual void data(const Data& data) {} + virtual void dropout(const Dropout& dropout) {} + virtual void sync(const Sync& sync) {} + + /** + * Used by Reader's corruption-recovery search to check a candidate byte offset that + * looks like it could be the start of a DATA message before accepting it as a resync + * point. Reader has no knowledge of subscriptions/formats itself, so it delegates the + * check here. Default is permissive (accepts everything). + * @param msg_id the candidate message's embedded msg_id + * @param payload_size the candidate message's payload size (msg_size minus the 2-byte + * msg_id) + * @return true if msg_id is a known subscription and payload_size is plausible for it + */ + virtual bool isValidDataMessage(uint16_t msg_id, uint16_t payload_size) const { return true; } + + private: +}; + +} // namespace flight_log diff --git a/include/flight_log/exception.hpp b/include/flight_log/exception.hpp new file mode 100644 index 0000000..dc281cd --- /dev/null +++ b/include/flight_log/exception.hpp @@ -0,0 +1,45 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include +#include + +namespace flight_log { + +class ExceptionBase : public std::exception { + public: + explicit ExceptionBase(std::string reason) : _reason(std::move(reason)) {} + const char* what() const noexcept override { return _reason.c_str(); } + + protected: + const std::string _reason; +}; + +/** + * Data stream exception, either during serialization (writing) or deserialization (reading) + */ +class ParsingException : public ExceptionBase { + public: + explicit ParsingException(std::string reason) : ExceptionBase(std::move(reason)) {} +}; + +/** + * API is used in the wrong way, or some arguments do not satisfy some requirements + */ +class UsageException : public ExceptionBase { + public: + explicit UsageException(std::string reason) : ExceptionBase(std::move(reason)) {} +}; + +/** + * Some field/subscription does not exist or index is out of range + */ +class AccessException : public ExceptionBase { + public: + explicit AccessException(std::string reason) : ExceptionBase(std::move(reason)) {} +}; + +} // namespace flight_log diff --git a/include/flight_log/messages.hpp b/include/flight_log/messages.hpp new file mode 100644 index 0000000..f81cdaf --- /dev/null +++ b/include/flight_log/messages.hpp @@ -0,0 +1,781 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "exception.hpp" +#include "raw_messages.hpp" +#include "utils.hpp" + +namespace flight_log { + + +/** + * @brief Definition for a function that writes data to a file + * Each message has a serialize() method that takes a DataWriteCB as argument. + * The serialize() method calls the DataWriteCB with the data to be written. + */ +using DataWriteCB = std::function; + +/** + * @brief ULog file header "message". The file header is always the first element in a ULG file. + */ +class FileHeader { + public: + FileHeader(const ulog_file_header_s& header, const ulog_message_flag_bits_s& flag_bits); + explicit FileHeader(const ulog_file_header_s& header); + + explicit FileHeader(uint64_t timestamp = 0, bool has_default_parameters = false); + + const ulog_file_header_s& header() const { return _header; } + const ulog_message_flag_bits_s& flagBits() const { return _flag_bits; } + + void serialize(const DataWriteCB& writer) const; + + bool operator==(const FileHeader& h) const + { + return memcmp(&_header, &h._header, sizeof(_header)) == 0 && + (!_has_flag_bits || memcmp(&_flag_bits, &h._flag_bits, sizeof(_flag_bits)) == 0); + } + + private: + ulog_file_header_s _header{}; + ulog_message_flag_bits_s _flag_bits{}; + bool _has_flag_bits{true}; +}; + +class MessageFormat; // forward declaration + +/** + * @brief Type definition for a Field. A field is a named data element in a message. + * Fields occur in + * - Message Formats + * - Parameter message types (they have exactly one field) + * - Info Messages (MessageInfo) (they have exactly one field) + * + * A field can be of a basic type (int, float, char, ...), an array of a basic type, + * or reference a MessageFormat (nested message). + * + * In case a field is of nested type, the nested Message Format has to be resolved during parsing. + * Since all Message Formats are in the header, at the end of the header, all nested fields should + * be resolved. + * + * A field can be in "resolved" and "unresolved" state. In resolved state, the following things + * are defined: + * - Offset of the field in the Message Format + * - Size of the field + * + * In a correct file, all fields can be resolved after the header is parsed. + */ +class Field { + public: + /** + * Enum for the basic types of a field. Note that they can also appear as arrays, NESTED + * references a child MessageFormat. + */ + enum class BasicType { + INT8, + UINT8, + INT16, + UINT16, + INT32, + UINT32, + INT64, + UINT64, + FLOAT, + DOUBLE, + CHAR, + BOOL, + NESTED, + }; + + /** + * TypeAttribute type stores basic information about a type. In case of basic types, + * the attribute field is just copied from the kBaiscTypes map. In case of nested types, + * the attributes are dynamically computed in nested type resolution. + */ + struct TypeAttributes { + std::string name; ///< name of the type + BasicType type{BasicType::NESTED}; ///< type as an enum + int size{0}; ///< size in bytes. Recursively computed for nested types + std::shared_ptr nested_message{nullptr}; /// < nested message format + + TypeAttributes() = default; + + TypeAttributes(std::string name, BasicType type, int size) + : name(std::move(name)), type(type), size(size), nested_message(nullptr) + { + } + }; + + /** + * @brief Map of all basic types. Used to resolve basic types from strings. + */ + static const std::map kBasicTypes; + + Field() = default; + + /** + * @brief Construct a field from input bytes. The string is expected to be in the format + * '[len] ' or ' '. + * This function is used when parsing data. + * @param str The input string pointer + * @param len The length of the input string + */ + Field(const char* str, int len); + + /** + * @brief Construct a field from a string. The string is expected to be in the format + * @param type_str The type string + * @param name_str The name string + * @param array_length_int The array length. -1 if not an array + */ + Field(const std::string& type_str, std::string name_str, int array_length_int = -1) + : _array_length(array_length_int), _name(std::move(name_str)) + { + auto it = kBasicTypes.find(type_str); + if (it != kBasicTypes.end()) { + _type = it->second; + } else { + // if not a basic type, set it to recursive + _type = TypeAttributes(type_str, BasicType::NESTED, 0); + } + } + + std::string encode() const; + + /** + * @brief Equality operator for fields. Two fields are equal if their type, array length and name + * are equal. + * @param field The field to compare to + * @return True if the fields are equal + */ + bool operator==(const Field& field) const + { + return _type.name == field._type.name && _array_length == field._array_length && + _name == field._name; + } + + /** + * @brief Get the type attributes of the field + * @return The type attributes + */ + const TypeAttributes& type() const { return _type; } + + /** + * @brief Get the array length of the field + * @return The array length, -1 if not an array + */ + int arrayLength() const { return _array_length; } + + /** + * @brief Get the offset of the field in the message. This is only valid if the field is resolved. + * @return The offset in bytes, -1 if not resolved + */ + int offsetInMessage() const { return _offset_in_message_bytes; } + + /** + * @brief Get the name of the field + * @return The name + */ + const std::string& name() const { return _name; } + + /** + * @brief Get the size of the field in bytes. This is only valid if the field is resolved. + * @return The size in bytes, 0 if nested type is not resolved + */ + inline int sizeBytes() const; + + /** + * @brief Returns true if the field is resolved. A field is resolved if the offset in message + * is defined and the type is not nested or the nested message is resolved. + * @return True if the field is resolved + */ + bool definitionResolved() const + { + return _offset_in_message_bytes >= 0 && + (_type.type != BasicType::NESTED || _type.nested_message != nullptr); + } + + /** + * @brief Attempt to resolve the definition of the field. + * This would be called to resolve the definition of a field in a message format. + * Fields would have to be resolved in-order, after each field being resolved, the offset + * of the next field can be computed by reading the size of the last field. + * @param existing_formats The map of existing message formats. Used to resolve nested types. + * @param offset The offset of the field in the message + */ + void resolveDefinition( + const std::map>& existing_formats, int offset); + + /** + * Resolve this field's definition, knowing that it will for sure not be of nested type. + * Resolution will fail if the type is nested. + * @param offset the offset of the field in the message + */ + void resolveDefinition(int offset); + + /** + * For nested fields, this returns the format of the nested field. + * For not nested fields, this throws. + * @return The format of the nested field + */ + std::shared_ptr nestedFormat() const; + + /** + * For nested fields, this will return a field from the nested message format. + * For not nested fields, this throws + * @param name The name of the field of the nested message format + * @return The field from the nested message format + */ + std::shared_ptr nestedField(const std::string& name) const; + + private: + TypeAttributes _type; ///< type attributes + int _array_length{-1}; ///< -1 means not-an-array + int _offset_in_message_bytes{ + -1}; ///< default to begin of message. Gets filled on MessageFormat resolution + std::string _name; /// < name of the field +}; + +/** + * @brief A value is a wrapper around a variant of all possible value types. + * This class can extract values from the underlying data representation and cast the values + * to the user defined types, or return them as a variant. + * + * The basic concept of this class is to always(!) extract the value in the format that it is + * defined in the MessageFormat. For example, if the value is defined as a float, in the + * MessageFormat, it will be interpreted as float. + * + * Since these types are only available at runtime, one can get the value as an std::variant, + * and then do appropriate handling for each type. In case the user knows what type to expect, + * it can also be explicitly casted to the desired type. In this case, any type conversion that is + * allowed by `static_cast` will be performed. + * + * Array types can be directly extracted as std::vector, string types as std::string. + */ +class Value { + public: + /** + * NativeTypeVariant is a variant of all possible types that a value can be. + * Note that it includes all array types as std::vectors, but not nested type. + * Nested is handled differently. + */ + using NativeTypeVariant = + std::variant, std::vector, + std::vector, std::vector, std::vector, + std::vector, std::vector, std::vector, + std::vector, std::vector, std::vector, std::string>; + + /** + * Construct a "Value" representation from underlying memory and Field reference + * @param field_ref The field reference to use + * @param backing_ref_begin Begin iterator of underlying memory + * @param backing_ref_end End iterator of underlying memory + * @param array_index Array within an array field to access directly + */ + Value(const Field& field_ref, const std::vector::const_iterator& backing_ref_begin, + const std::vector::const_iterator& backing_ref_end, int array_index = -1) + : _field_ref(field_ref), + _array_index(array_index), + _backing_ref_begin(backing_ref_begin), + _backing_ref_end(backing_ref_end) + { + } + + Value(const Field& field_ref, const std::vector& backing_ref, int array_index = -1) + : Value(field_ref, backing_ref.begin(), backing_ref.end(), array_index) + { + } + + /** + * @brief Get the value as a variant of all possible types. + * In case the underlying type is an array, it will be extracted as a std::vector. + * In case the underlying type is a char array, it will be extracted as a std::string. + * In case the underlying type is an array, but we access a specific element, it will be + * extracted as the basic type T. + * @return std::variant of the value, in type defined in the Message Format + */ + NativeTypeVariant asNativeTypeVariant() const; + + /** + * @brief Cast the value to a desired, compile time known type. This will perform a static_cast + * to the desired type, if the type conversion is allowed by static_cast. + * For example one can extract a value defined as a uint8_t as an int. + * + * There are the following rules: + * - If requested type is vector and native type is also vector, vector is returned + * - If requested type is vector, but native type is vector, each element gets casted from K + * to T + * - If requested type is not a vector, but native type is a vector, the first element is returned + * - If requested type is a vector, but native type is not a vector, a vector with 1 element is + * returned + * - If requested type is T and native type is K, a static_cast is performed on the element + * - If requested type is T and native type is T as well, the element is returned + * + * Specifically, when casting (signed) char, char is first casted to unsigned char, as this + * is generally the more expected behaviour (e.g. when casting a char to an int, one would + * expect the ASCII value of the char, not the signed value). + * @tparam T + * @return + */ + template + T as() const + { + T res; + std::visit( + [&res](auto&& arg) { + using NativeType = std::decay_t; + using ReturnType = T; + if constexpr (is_string::value || is_string::value) { + // there is a string involved. Only allowed when both are string + if constexpr (is_string::value && is_string::value) { + // both are string + res = arg; + } else { + // one is string, the other is not + throw AccessException("Assign strings and non-string types"); + } + } else if constexpr (is_vector::value) { + // this is natively a vector + if constexpr (is_vector::value) { + // return type is also vector + if constexpr (std::is_same_v) { + // return type is same as native type + res = arg; + } else { + // return type is different from native type, but a vector + res.resize(arg.size()); + for (std::size_t i = 0; i < arg.size(); i++) { + res[i] = staticCastEnsureUnsignedChar(arg[i]); + } + } + } else { + // return type is not a vector, just return first element + if (arg.size() > 0) { + res = staticCastEnsureUnsignedChar(arg[0]); + } else { + throw AccessException("Cannot convert empty vector to non-vector type"); + } + } + } else { + // this is natively not a vector + if constexpr (is_vector::value) { + // return type is a vector + res.resize(1); + res[0] = staticCastEnsureUnsignedChar(arg); + } else { + // return type is not a vector + res = staticCastEnsureUnsignedChar(arg); + } + } + }, + asNativeTypeVariant()); + return res; + } + + /** + * Access a field in a nested message. This creates a new Value class, + * with the field definition from the nested Message Format. + * @param field The field in the nested format to access + * @return The value of the field in the nested format + */ + Value operator[](const Field& field) const; + + /** + * Access a field in a nested message. This creates a new Value class, + * with the field definition from the nested Message Format. + * @param field The field in the nested format to access + * @return The value of the field in the nested format + */ + Value operator[](const std::shared_ptr& field) const; + + /** + * Access a field in a nested message. This creates a new Value class, + * with the field definition from the nested Message Format. + * @param field_name the name of the field in the nested format to access + * @return the value of the field in the nested format + */ + Value operator[](const std::string& field_name) const; + + /** + * Access a certain position in the array of this field. This creates a new Value class, + * with the array index property set. This allows access of individual message elements + * without converting the entire field into a vector first. + * @param index the index of the element to access + * @return a new Value object with the array index property set + */ + Value operator[](size_t index) const; + + private: + template + static T deserialize(const std::vector::const_iterator& backing_start, + const std::vector::const_iterator& backing_end, int offset, + int array_offset) + { + T v; + const int total_offset = offset + (array_offset * sizeof(T)); + if (backing_start > backing_end || + backing_end - backing_start < static_cast(sizeof(v)) + total_offset) { + throw AccessException("Unexpected data type size"); + } + // GCC 14.2 raises an error here when building with -fsanitize=address +#if defined(__GNUC__) && (__GNUC__ >= 14) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Warray-bounds" +#pragma GCC diagnostic ignored "-Wstringop-overflow" +#endif + std::copy(backing_start + total_offset, backing_start + total_offset + sizeof(v), + reinterpret_cast(&v)); +#if defined(__GNUC__) && (__GNUC__ >= 14) +#pragma GCC diagnostic pop +#endif + return v; + } + + template + static std::vector deserializeVector(const std::vector::const_iterator& backing_start, + const std::vector::const_iterator& backing_end, + int offset, int size) + { + std::vector res; + res.resize(size); + for (int i = 0; i < size; i++) { + res[i] = deserialize(backing_start, backing_end, offset, i); + } + return res; + } + + const Field& _field_ref; /// < reference to the field definition + const int _array_index = -1; /// < index in the array, -1 if accessing head, or not an array + const std::vector::const_iterator + _backing_ref_begin; /// < begin iterator of the backing vector + const std::vector::const_iterator + _backing_ref_end; /// < end iterator of the backing vector +}; + +/** + * Class that contains an Info Message. An info message can either be standalone, or be comprised + * of multiple subsequent info messages. + * An info message has a single field, which can theoretically be of any type. However, in practice + * it is mostly a basic type. + */ +class MessageInfo { + public: + explicit MessageInfo(const uint8_t* msg, bool is_multi = false); + + MessageInfo(Field field, std::vector value, bool is_multi = false, + bool continued = false); + + MessageInfo(const std::string& key, const std::string& value); + MessageInfo(const std::string& key, int32_t value); + MessageInfo(const std::string& key, float value); + + const Field& field() const { return _field; } + Field& field() { return _field; } + std::vector& valueRaw() { return _value; } + const std::vector& valueRaw() const { return _value; } + Value value() const { return Value(_field, _value); } + bool isContinued() const { return _continued; } + bool isMulti() const { return _is_multi; } + + void serialize(const DataWriteCB& writer, ULogMessageType type = ULogMessageType::INFO) const; + + bool operator==(const MessageInfo& info) const + { + return _field == info._field && _value == info._value && _continued == info._continued && + _is_multi == info._is_multi; + } + + private: + void initValues(const char* values, int len); + Field _field; + std::vector _value; + bool _continued{false}; + bool _is_multi{false}; +}; + +/** + * Class that contains a Message Format. A message format contains all the fields contained in + * Message Formats have to appear in the header of the log file, and are also parsed there. + * a message. Message formats are referenced in + * - Subscriptions: Each subscription is of a specific message format. + * - Fields: Each field can be of type nested, and have a reference to a message format then. + * + * Message Formats can be recursive. A MessageFormat can contain a Field that is of nested type, + * which refers to another MessgeFormat and so on. Therefore, when MessageFormats are parsed, + * they are generally not "resolved" as for then nested Fields, MessageDefinitions may not be + * available yet. + * MessageFormats are resolved once the header is parsed. + */ +class MessageFormat { + public: + /** + * Construct a messsage format from a raw message. This is used when parsing the header. + * @param msg the raw message + */ + explicit MessageFormat(const uint8_t* msg); + + /** + * Manually construct a message format. + * @param name name of the message format + * @param fields list of fields, in-order. + */ + explicit MessageFormat(std::string name, const std::vector& fields); + + /** + * @return the name of the message format + */ + const std::string& name() const { return _name; } + + /** + * @return the map of fields, keyed by name + */ + const std::map>& fieldMap() const { return _fields; } + + /** + * Serialize the message format into a raw message. + * @param writer + */ + void serialize(const DataWriteCB& writer) const; + + /** + * Compare two message formats for equality. + * Two message formats are equal if they have the same name, and the same fields in the same + * order. + * @param format the message format to compare to + * @return true if the message formats are equal, false otherwise + */ + bool operator==(const MessageFormat& format) const + { + if (_name != format._name) { + return false; + } + if (_fields.size() != format._fields.size()) { + return false; + } + for (size_t i = 0; i < _fields_ordered.size(); i++) { + if (!(*_fields_ordered[i] == *format._fields_ordered[i])) { + return false; + } + } + return true; + } + + /** + * Recursively tries to resolve the MessageFormat with the help of a map of all known, existing + * message formats. This is used to resolve nested fields, at the end of parsing the header. + * @param existing_formats + */ + void resolveDefinition( + const std::map>& existing_formats) const; + + /** + * Returns the total size of this MessageFormat in bytes. This is only valid once the + * MessageFormat has been resolved. All fields have to be resolved, and the size of the + * MessageFormat is the sum of the sizes of all fields. + * @return the size of the MessageFormat in bytes + */ + int sizeBytes() const; + + /** + * Returns the minimum size of this MessageFormat in bytes as it can appear on the wire in a + * Data message. This is only valid once the MessageFormat has been resolved (see sizeBytes()). + * + * ULog allows to omits trailing alignment padding fields (_padding0, etc.) from the + * on-wire Data payload, since they carry no information - the FORMAT definition still lists + * them because it describes the full in-memory struct layout (needed e.g. to correctly compute + * offsets when this format is used as a nested type in an array). sizeBytes() sums every field + * including such trailing padding, so it's an upper bound; this is the corresponding lower + * bound. A real Data message's payload size should fall within [minWireSizeBytes(), + * sizeBytes()]. + * @return the minimum size of this MessageFormat on the wire, in bytes + */ + int minWireSizeBytes() const; + + /** + * @return the list of fields, in-order + */ + const std::vector>& fields() const { return _fields_ordered; } + + /** + * @return the list of field names, in-order + */ + std::vector fieldNames() const + { + std::vector names; + names.reserve(_fields_ordered.size()); + for (const auto& field_it : _fields_ordered) { + names.push_back(field_it->name()); + } + return names; + } + + /** + * Get a field by name. + * @param name the name of the field + * @return the requested field + */ + std::shared_ptr field(const std::string& name) const + { + const auto it = _fields.find(name); + if (it == _fields.end()) { + throw AccessException("Field not found: " + name); + } + return it->second; + } + + private: + std::string _name; + std::map> + _fields; /// < map of fields, keyed by name, same fields as in the list + std::vector> + _fields_ordered; /// < list of fields, in-order, same fields as in the map +}; + +using Parameter = MessageInfo; + +class ParameterDefault { + public: + explicit ParameterDefault(const uint8_t* msg); + + ParameterDefault(Field field, std::vector value, + ulog_parameter_default_type_t default_types); + + const Field& field() const { return _field; } + Field& field() { return _field; } + const std::vector& valueRaw() const { return _value; } + Value value() const { return Value(_field, _value); } + + void serialize(const DataWriteCB& writer) const; + + ulog_parameter_default_type_t defaultType() const { return _default_types; } + + private: + void initValues(const char* values, int len); + Field _field; + std::vector _value; + ulog_parameter_default_type_t _default_types{}; +}; + +class AddLoggedMessage { + public: + explicit AddLoggedMessage(const uint8_t* msg); + + AddLoggedMessage(uint8_t multi_id, uint16_t msg_id, std::string message_name); + + const std::string& messageName() const { return _message_name; } + uint8_t multiId() const { return _multi_id; } + uint16_t msgId() const { return _msg_id; } + + void serialize(const DataWriteCB& writer) const; + + private: + uint8_t _multi_id{}; + uint16_t _msg_id{}; + std::string _message_name; +}; + +class Logging { + public: + enum class Level : uint8_t { + Emergency = '0', + Alert = '1', + Critical = '2', + Error = '3', + Warning = '4', + Notice = '5', + Info = '6', + Debug = '7' + }; + explicit Logging(const uint8_t* msg, bool is_tagged = false); + + Logging(Level level, std::string message, uint64_t timestamp); + + Level logLevel() const { return _log_level; } + std::string logLevelStr() const; + uint16_t tag() const { return _tag; } + bool hasTag() const { return _has_tag; } + uint64_t timestamp() const { return _timestamp; } + const std::string& message() const { return _message; } + + void serialize(const DataWriteCB& writer) const; + + bool operator==(const Logging& logging) const + { + return _log_level == logging._log_level && _tag == logging._tag && + _has_tag == logging._has_tag && _timestamp == logging._timestamp && + _message == logging._message; + } + + private: + Level _log_level{}; + uint16_t _tag{}; + bool _has_tag{false}; + uint64_t _timestamp{}; + std::string _message; +}; + +/** + * Data is an element that contains a single element from a subscription. In order + * to decode it, it will need to get referenced to a MessageFormat. This is done using + * the TypedDataView class in Subscription. + */ +class Data { + public: + explicit Data(const uint8_t* msg); + + Data(uint16_t msg_id, std::vector data); + + uint16_t msgId() const { return _msg_id; } + const std::vector& data() const { return _data; } + + void serialize(const DataWriteCB& writer) const; + + bool operator==(const Data& data) const { return _msg_id == data._msg_id && _data == data._data; } + + private: + uint16_t _msg_id{}; + std::vector _data; +}; + +class Dropout { + public: + explicit Dropout(const uint8_t* msg); + + explicit Dropout(uint16_t duration_ms); + + uint16_t durationMs() const { return _duration_ms; } + + void serialize(const DataWriteCB& writer) const; + + private: + uint16_t _duration_ms{}; +}; + +class Sync { + public: + explicit Sync(const uint8_t* msg); + + explicit Sync() = default; + + void serialize(const DataWriteCB& writer) const; + + private: + static constexpr uint8_t kSyncMagicBytes[] = {0x2F, 0x73, 0x13, 0x20, 0x25, 0x0C, 0xBB, 0x12}; +}; + +} // namespace flight_log diff --git a/include/flight_log/raw_messages.hpp b/include/flight_log/raw_messages.hpp new file mode 100644 index 0000000..9561208 --- /dev/null +++ b/include/flight_log/raw_messages.hpp @@ -0,0 +1,286 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include + +namespace flight_log { + +// NOLINTBEGIN(*) Keep the original naming + +enum class ULogMessageType : uint8_t { + FORMAT = 'F', + DATA = 'D', + INFO = 'I', + INFO_MULTIPLE = 'M', + PARAMETER = 'P', + PARAMETER_DEFAULT = 'Q', + ADD_LOGGED_MSG = 'A', + REMOVE_LOGGED_MSG = 'R', + SYNC = 'S', + DROPOUT = 'O', + LOGGING = 'L', + LOGGING_TAGGED = 'C', + FLAG_BITS = 'B', +}; + +/* declare message data structs with byte alignment (no padding) */ +#pragma pack(push, 1) + +/** first bytes of the file */ +struct ulog_file_header_s { + uint8_t magic[8]; + uint64_t timestamp; +}; + +static constexpr uint8_t ulog_file_magic_bytes[] = {'U', 'L', 'o', 'g', 0x01, 0x12, 0x35}; + +/** first bytes of the crypto key file */ +struct ulog_key_header_s { + /* magic identifying the file content */ + uint8_t magic[7]; + + /* version of this header file */ + uint8_t hdr_ver; + + /* file creation timestamp */ + uint64_t timestamp; + + /* crypto algorithm used for key exchange */ + uint8_t exchange_algorithm; + + /* encryption key index used for key exchange */ + uint8_t exchange_key; + + /* size of the key */ + uint16_t key_size; + + /* size of logfile crypto algoritm initialization data, e.g. nonce */ + uint16_t initdata_size; + + /* actual data (initdata+key) */ + uint8_t data[0]; +}; + +/** + * @brief Message Header for the ULog + * + * This header components that is in the beginning of every ULog messages that gets written into + * Definitions section as well as the Data section of the ULog file. + */ +struct ulog_message_header_s { + uint16_t msg_size; ///< Size of the message excluding the header size + uint8_t + msg_type; ///< Message type, which is one of the ASCII alphabet, defined in ULogMessageType +}; + +#define ULOG_MSG_HEADER_LEN \ + 3 // Length of the header in bytes: accounts for msg_size (2 bytes) and msg_type (1 byte) + +/** + * @brief Format Message + * + * This message describes a single ULog topic's name and it's inner fields. The inner fields can + * have the type as defined in the uORB message file (e.g. msg/action_request.msg). Including other + * uORB topics, which is the nested type case. + * + * @param format Format of the uORB topic in the format: "message_name:field0;field1;" + * Example: "action_request:uint64_t timestamp;uint8_t action;uint8_t source;uint8_t mode;uint8_t[5] + * _padding0;" + */ +struct ulog_message_format_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::FORMAT); + + char format[1500]; +}; + +/** + * @brief Subscription Message + * + * This message describes which uORB topic the logger has subscribed to. + * + * Used for indicating which msg_id corresponds to which uORB topic name (message_name) + */ +struct ulog_message_add_logged_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::ADD_LOGGED_MSG); + + uint8_t multi_id; ///< Multi instance id, if the topic is one of a multi instance uORB topic + uint16_t msg_id; ///< Message ID, an internally tracked id in the logger, which matches with the + ///< msg_id in ulog_message_data_s message + char message_name[255]; ///< Name of the uORB topic +}; + +/** + * @brief Unsubscription Message + * + * This message describes which uORB topic the logger has unsubscribed from. + */ +struct ulog_message_remove_logged_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::REMOVE_LOGGED_MSG); + + uint16_t msg_id; +}; + +/** + * @brief Sync Message + */ +struct ulog_message_sync_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::SYNC); + + uint8_t sync_magic[8]; +}; + +struct ulog_message_dropout_s { + uint16_t msg_size = sizeof(uint16_t); ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::DROPOUT); + + uint16_t duration; ///< in ms +}; + +/** + * @brief Logged Data Message + * + * Includes the binary data of the uORB topic with the corresponding logger's internal msg_id. + * + * The uint8_t data[] section follows after the msg_id part, but the message struct only defines up + * until the msg_id, since the data length varies per each uORB topic (the struct size of the uORB + * message). + */ +struct ulog_message_data_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::DATA); + + uint16_t msg_id; +}; + +/** + * @brief Information Message + * + * Writes the dictionary type key:value relationship of any kind of information. + * + * Example: key_value_str[] = "char[5] sys_toolchain_ver9.4.0" + */ +struct ulog_message_info_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::INFO); + + uint8_t key_len; ///< Length of the 'key' + char key_value_str[255]; ///< String with the key and value information +}; + +/** + * @brief Multiple Information Message + * + * Writes the dictionary type key:value relationship of any kind of information, but + * for the ones which has a long value that can't be contained in a single Information Message. + */ +struct ulog_message_info_multiple_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::INFO_MULTIPLE); + + uint8_t is_continued; ///< Can be used for arrays: set to 1, if this message is part of the + ///< previous with the same key + uint8_t key_len; ///< Length of the 'key' + char key_value_str[1200]; ///< String with the key and value information +}; + +/** + * @brief Logged String Message + * + * Logged string from a flight controller or telemetry source. + * Useful for Debugging. + */ +struct ulog_message_logging_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::LOGGING); + + uint8_t log_level; ///< same levels as in the linux kernel + uint64_t timestamp; + char message[128]; ///< defines the maximum length of a logged message string +}; + +struct ulog_message_logging_tagged_s { + uint16_t msg_size; ///< size of message - ULOG_MSG_HEADER_LEN + uint8_t msg_type = static_cast(ULogMessageType::LOGGING_TAGGED); + + uint8_t log_level; ///< same levels as in the linux kernel + uint16_t tag; + uint64_t timestamp; + char message[128]; ///< defines the maximum length of a logged message string +}; + +/** + * @brief Parameter Message + * + * Includes a parameter value information in the format " " + */ +struct ulog_message_parameter_s { + uint16_t msg_size; + uint8_t msg_type = static_cast(ULogMessageType::PARAMETER); + + uint8_t key_len; + char key_value_str[255]; ///< String with the key and value information +}; + +/** + * @brief ULog default parameter type flags + * + * These flags indicate whether the default parameter defined in the + * ulog_message_parameter_default_s message is System's default or the User setup's default value. + * As user can set a custom default parameter for each vehicle setup that overrides the system's + * default value. + */ +enum class ulog_parameter_default_type_t : uint8_t { + system = (1 << 0), ///< System wide default parameter + current_setup = (1 << 1) ///< Custom setup default parameter +}; + +inline ulog_parameter_default_type_t operator|(ulog_parameter_default_type_t a, + ulog_parameter_default_type_t b) +{ + return static_cast(static_cast(a) | + static_cast(b)); +} + +/** + * @brief Default Parameter Message + * + * This message defines a parameter name and it's default value. Which is useful for figuring out in + * ULog analyzer which Parameters are non-default (User modified), which can give a quick insight + * into how the vehicle is configured, since the default parameter values are well known & + * understood (e.g. PID Tuning values) + */ +struct ulog_message_parameter_default_s { + uint16_t msg_size; + uint8_t msg_type = static_cast(ULogMessageType::PARAMETER_DEFAULT); + + ulog_parameter_default_type_t default_types; + uint8_t key_len; + char key_value_str[255]; ///< String with the key and value information +}; + +#define ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK (1 << 0) + +#define ULOG_COMPAT_FLAG0_DEFAULT_PARAMETERS_MASK (1 << 0) + +struct ulog_message_flag_bits_s { + uint16_t msg_size; + uint8_t msg_type = static_cast(ULogMessageType::FLAG_BITS); + + uint8_t compat_flags[8]; + uint8_t incompat_flags[8]; ///< @see ULOG_INCOMPAT_FLAG_* + uint64_t appended_offsets[3]; ///< file offset(s) for appended data if + ///< ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK is set +}; + +#pragma pack(pop) + +// NOLINTEND(*) + +} // namespace flight_log diff --git a/include/flight_log/reader.hpp b/include/flight_log/reader.hpp new file mode 100644 index 0000000..ce4b2bc --- /dev/null +++ b/include/flight_log/reader.hpp @@ -0,0 +1,68 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include +#include + +#include "data_handler_interface.hpp" + +namespace flight_log { + +/** + * Class to deserialize an ULog file. Parsed messages are passed back to a DataHandlerInterface + * class. + */ +class Reader { + public: + explicit Reader(std::shared_ptr data_handler_interface); + ~Reader(); + + /** + * Parse next chunk of serialized ULog data. Call this iteratively, e.g. over a complete file. + * data_handler_interface will be called immediately for each parsed ULog message. + */ + void readChunk(const uint8_t* data, int length); + + private: + static constexpr int kBufferSizeInit = 2048; + + static const std::set kKnownMessageTypes; + + int readMagic(const uint8_t* data, int length); + int readFlagBits(const uint8_t* data, int length); + void corruptionDetected(); + int appendToPartialBuffer(const uint8_t* data, int length); + void tryToRecover(const uint8_t* data, int length); + + void readHeaderMessage(const uint8_t* message); + void readDataMessage(const uint8_t* message); + + enum class State { + ReadMagic, + ReadFlagBits, + ReadHeader, + ReadData, + InvalidData, + }; + + State _state{State::ReadMagic}; + const std::shared_ptr _data_handler_interface; + + uint8_t* _partial_message_buffer{nullptr}; ///< contains at most one ULog message (unless + ///< _need_recovery==true) + int _partial_message_buffer_length_capacity{0}; + int _partial_message_buffer_length{0}; + + bool _need_recovery{false}; + bool _corruption_reported{false}; + + int _total_num_read{}; ///< statistics, total number of bytes read (includes current partial + ///< buffer data) + + ulog_file_header_s _file_header{}; +}; + +} // namespace flight_log diff --git a/include/flight_log/simple_writer.hpp b/include/flight_log/simple_writer.hpp new file mode 100644 index 0000000..39fa38b --- /dev/null +++ b/include/flight_log/simple_writer.hpp @@ -0,0 +1,163 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include +#include +// GCC 14.2 raises an error in when building with -fsanitize=address +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif +#include +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif +#include +#include + +#include "writer.hpp" + +namespace flight_log { + +/** + * ULog serialization class which checks for integrity and correct calling order. + * It throws an UsageException() in case of a failed integrity check. + */ +class SimpleWriter { + public: + /** + * Constructor with a callback for writing data. + * @param data_write_cb callback for serialized ULog data + * @param timestamp_us start timestamp [us] + */ + explicit SimpleWriter(DataWriteCB data_write_cb, uint64_t timestamp_us); + /** + * Constructor to write to a file. + * @param filename ULog file to write to (will be overwritten if it exists) + * @param timestamp_us start timestamp [us] + */ + explicit SimpleWriter(const std::string& filename, uint64_t timestamp_us); + + ~SimpleWriter(); + + /** + * Write a key-value info. Typically used for versioning information and written to the header. + * @tparam T one of std::string, int32_t, float + * @param key (unique) name, e.g. sys_name + * @param value + */ + template + void writeInfo(const std::string& key, const T& value) + { + _writer->messageInfo(flight_log::MessageInfo(key, value)); + } + + /** + * Write a parameter name-value pair to the header + * @tparam T one of int32_t, float + * @param key (unique) name, e.g. PARAM_A + * @param value + */ + template + void writeParameter(const std::string& key, const T& value) + { + if (_header_complete) { + throw UsageException("Header already complete"); + } + _writer->parameter(flight_log::Parameter(key, value)); + } + + /** + * Write a message format definition to the header. + * + * Supported field types: + * "int8_t", "uint8_t", "int16_t", "uint16_t", "int32_t", "uint32_t", "int64_t", "uint64_t", + * "float", "double", "bool", "char" + * + * The first field must be: {"uint64_t", "timestamp"}. + * + * Note that ULog also supports nested format definitions, which is not supported here. + * + * When aligning the fields according to a multiple of their size, there must be no padding + * between fields. The simplest way to achieve this is to order fields by decreasing size of + * their type. If incorrect, a UsageException() is thrown. + * + * @param name format name, must match the regex: "[a-zA-Z0-9_\\-/]+" + * @param fields message fields, names must match the regex: "[a-z0-9_]+" + */ + void writeMessageFormat(const std::string& name, const std::vector& fields); + + /** + * Call this to complete the header (after calling the above methods). + */ + void headerComplete(); + + /** + * Write a parameter change (@see writeParameter()) + */ + template + void writeParameterChange(const std::string& key, const T& value) + { + if (!_header_complete) { + throw UsageException("Header not yet complete"); + } + _writer->parameter(flight_log::Parameter(key, value)); + } + + /** + * Create a time-series instance based on a message format definition. + * @param message_format_name Format name from writeMessageFormat() + * @param multi_id Instance id, if there's multiple + * @return message id, used for writeData() later on + */ + uint16_t writeAddLoggedMessage(const std::string& message_format_name, uint8_t multi_id = 0); + + /** + * Write a text message + */ + void writeTextMessage(Logging::Level level, const std::string& message, uint64_t timestamp); + + /** + * Write some data. The timestamp must be monotonically increasing for a given time-series (i.e. + * same id). + * @param id ID from writeAddLoggedMessage() + * @param data data according to the message format definition + */ + template + void writeData(uint16_t id, const T& data) + { + writeDataImpl(id, reinterpret_cast(&data), sizeof(data)); + } + + /** + * Flush the buffer and call fsync() on the file (only if the file-based constructor is used). + */ + void fsync(); + + private: + static const std::string kFormatNameRegexStr; + static const std::regex kFormatNameRegex; + static const std::string kFieldNameRegexStr; + static const std::regex kFieldNameRegex; + + struct Format { + unsigned message_size; + }; + struct Subscription { + unsigned message_size; + }; + + void writeDataImpl(uint16_t id, const uint8_t* data, unsigned length); + + std::unique_ptr _writer; + std::FILE* _file{nullptr}; + + bool _header_complete{false}; + std::unordered_map _formats; + std::vector _subscriptions; +}; + +} // namespace flight_log diff --git a/include/flight_log/subscription.hpp b/include/flight_log/subscription.hpp new file mode 100644 index 0000000..b904950 --- /dev/null +++ b/include/flight_log/subscription.hpp @@ -0,0 +1,281 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#pragma once +#include + +#include "messages.hpp" + +namespace flight_log { + +/** + * TypedDataView is a view on a Data object, which allows to access the data using the + * MessageFormat meta definition. The subscription object only contains the Data object, + * without repeated reference to the underlying MessageFormat, for storage efficiency reasons. + * + * Note that TypedDataView should be a short-lived object solely to access data. As + * it stores references to the underlying Data and MessageFormat objects, it is only valid + * as long as the the MessageFormat and Data objects are untouched and valid. + */ +class TypedDataView { + public: + /** + * Value is a view on a single field of a TypedDataView. + * @param data_ref Reference to the underlying Data Object + * @param message_format_ref Reference to the underlying MessageFormat + */ + TypedDataView(const Data& data_ref, const MessageFormat& message_format_ref) + : _data_ref(data_ref), _message_format_ref(message_format_ref) + { + } + + /** + * @return The name of the message format that this data object is based on + */ + std::string name() const { return _message_format_ref.name(); } + + /** + * Accesses the value at a specific field. + * @param field The field to be accessed + * @return The value object for the field + */ + Value at(const Field& field) const + { + if (!field.definitionResolved()) { + throw ParsingException("Field definition not resolved"); + } + return Value(field, _data_ref.data()); + } + + /** + * Accesses the value at a specific field. + * @param field The field to be accessed + * @return The value object for the field + */ + Value at(const std::shared_ptr& field) const { return at(*field); } + + /** + * Accesses the value at a specific field. + * @param field_name + * @return The value object for the field + */ + Value at(const std::string& field_name) const + { + auto field = _message_format_ref.field(field_name); + return at(field); + } + + /** + * Accesses the value at a specific field. + * @param field_name + * @return The value object for the field + */ + Value operator[](const Field& field) const { return at(field); } + + /** + * Accesses the value at a specific field. + * @param field_name + * @return The value object for the field + */ + Value operator[](const std::shared_ptr& field) const { return at(field); } + + /** + * Accesses the value at a specific field. + * @param field_name + * @return The value object for the field + */ + Value operator[](const std::string& field_name) const { return at(field_name); } + + /** + * @return The underlying MessageFormat object + */ + const MessageFormat& format() const { return _message_format_ref; } + + /** + * Checks if a field is present in the underlying MessageFormat + */ + bool hasField(const std::string& field_name) const + { + const auto iter = _message_format_ref.fieldMap().find(field_name); + return iter != _message_format_ref.fieldMap().end() && iter->second->definitionResolved(); + } + + /** + * @return The underlying raw data vector + */ + const std::vector& rawData() const { return _data_ref.data(); } + + private: + const Data& _data_ref; + const MessageFormat& _message_format_ref; +}; + +/** + * Iterator to iterate over a subscription. Subscriptions contain a vector of Data objects, + * the Data objects themselves are not typed to a specific MessageFormat, but the Subscription is. + * This iterator implicitly converts each Data object to a TypedDataView, which allows access to + * all Fields. + * @tparam base_iterator_type const iterator or modifiable iterator + */ +template +class SubscriptionIterator { + public: + SubscriptionIterator(const base_iterator_type& it, std::shared_ptr message_format) + : _it(it), _message_format(std::move(message_format)) + { + } + + using iterator_category = std::random_access_iterator_tag; // NOLINT(*-identifier-naming) + using value_type = TypedDataView; // NOLINT(*-identifier-naming) + using difference_type = std::ptrdiff_t; // NOLINT(*-identifier-naming) + using pointer = TypedDataView*; // NOLINT(*-identifier-naming) + using reference = TypedDataView&; // NOLINT(*-identifier-naming) + + TypedDataView operator*() { return TypedDataView(*_it, *_message_format); } + + TypedDataView operator*() const { return TypedDataView(*_it, *_message_format); } + + SubscriptionIterator& operator++() + { + ++_it; + return *this; + } + + SubscriptionIterator operator++(int) + { + SubscriptionIterator tmp(*this); + operator++(); + return tmp; + } + + SubscriptionIterator& operator--() + { + --_it; + return *this; + } + + SubscriptionIterator operator--(int) + { + SubscriptionIterator tmp(*this); + operator--(); + return tmp; + } + + SubscriptionIterator& operator+=(difference_type n) + { + _it += n; + return *this; + } + + SubscriptionIterator operator+(difference_type n) const + { + SubscriptionIterator tmp(*this); + tmp += n; + return tmp; + } + + SubscriptionIterator& operator-=(difference_type n) + { + _it -= n; + return *this; + } + + SubscriptionIterator operator-(difference_type n) const + { + SubscriptionIterator tmp(*this); + tmp -= n; + return tmp; + } + + difference_type operator-(const SubscriptionIterator& other) const { return _it - other._it; } + + TypedDataView operator[](difference_type n) { return *((*this) + n); } + + bool operator==(const SubscriptionIterator& other) const { return _it == other._it; } + + bool operator!=(const SubscriptionIterator& other) const { return _it != other._it; } + + bool operator<(const SubscriptionIterator& other) const { return _it < other._it; } + + bool operator>(const SubscriptionIterator& other) const { return _it > other._it; } + + bool operator<=(const SubscriptionIterator& other) const { return _it <= other._it; } + + bool operator>=(const SubscriptionIterator& other) const { return _it >= other._it; } + + private: + base_iterator_type _it; + std::shared_ptr _message_format; +}; + +class Subscription { + public: + Subscription(AddLoggedMessage add_logged_message, std::vector samples, + std::shared_ptr message_format) + : _add_logged_message(std::move(add_logged_message)), + _message_format(std::move(message_format)), + _samples(std::move(samples)) + { + } + + void emplaceSample(const Data& sample) { _samples.emplace_back(sample); } + + const AddLoggedMessage& getAddLoggedMessage() const { return _add_logged_message; } + + const std::vector& rawSamples() const { return _samples; } + + const std::shared_ptr& format() const { return _message_format; } + + const std::map>& fieldMap() const + { + return _message_format->fieldMap(); + } + + std::vector fieldNames() const { return _message_format->fieldNames(); } + + std::shared_ptr field(const std::string& name) const + { + return _message_format->field(name); + } + + auto begin() + { + return SubscriptionIterator::iterator>(_samples.begin(), _message_format); + } + auto end() + { + return SubscriptionIterator::iterator>(_samples.end(), _message_format); + } + + auto begin() const + { + return SubscriptionIterator::const_iterator>(_samples.begin(), + _message_format); + } + auto end() const + { + return SubscriptionIterator::const_iterator>(_samples.cend(), + _message_format); + } + + TypedDataView at(std::size_t n) const + { + if (n >= size()) { + throw AccessException("Index out of range: " + std::to_string(n)); + } + return begin()[n]; + } + + TypedDataView operator[](std::size_t n) { return at(n); } + + std::size_t size() const { return _samples.size(); } + + private: + AddLoggedMessage _add_logged_message; + std::shared_ptr _message_format; + std::vector _samples; +}; + +} // namespace flight_log \ No newline at end of file diff --git a/include/flight_log/utils.hpp b/include/flight_log/utils.hpp new file mode 100644 index 0000000..1673dab --- /dev/null +++ b/include/flight_log/utils.hpp @@ -0,0 +1,61 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +namespace flight_log { +/** + * Just does a static cast, except for signed char, it interprets it as unsigned char + * @tparam ReturnType The type to cast to + * @tparam OriginType The type to cast from + * @param v The value to cast + * @return The casted value + */ +template +static inline ReturnType staticCastEnsureUnsignedChar(const OriginType& v) +{ + if constexpr (std::is_same_v, char>) { + return static_cast(static_cast(v)); + } + return static_cast(v); +} + +/** + * Manual implementation of strnlen, since it does not exist in std. + * Counts the number of characters in the string, excluding the terminal zero. + * Returns at most `max_len` + * @param ptr The pointer to the string in memory + * @param max_len The maximum number of characters to report + * @return The number of characters in the string until terminating zero, not including the zero + * or max_len if no terminating zero found until max_len reached + */ +inline int strnlen(const uint8_t* ptr, int max_len) +{ + int len = 0; + while ((len < max_len) && (*ptr != 0)) { + ptr++; + len++; + } + return len; +} + +/** + * SFINAE helper to check if a type is a vector + * @tparam T The type to check + */ +template +struct is_vector : std::false_type { // NOLINT(*-identifier-naming) +}; +template +struct is_vector> : std::true_type {}; + +/** + * SFINAE helper to check if a type is a string + * @tparam T The type to check + */ +template +struct is_string : std::is_same, std::string> { // NOLINT(*-identifier-naming) +}; + +} // namespace flight_log diff --git a/include/flight_log/writer.hpp b/include/flight_log/writer.hpp new file mode 100644 index 0000000..5e9882a --- /dev/null +++ b/include/flight_log/writer.hpp @@ -0,0 +1,41 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#pragma once + +#include +#include + +#include "data_handler_interface.hpp" + +/** + * Low-level class for serializing ULog data. This exposes the full ULog functionality, but does + * not do integrity checks. Use SimpleWriter for a simpler API with checks. + */ +namespace flight_log { + +class Writer : public DataHandlerInterface { + public: + explicit Writer(DataWriteCB data_write_cb); + virtual ~Writer() = default; + + void headerComplete() override; + + void fileHeader(const FileHeader& header) override; + void messageInfo(const MessageInfo& message_info) override; + void messageFormat(const MessageFormat& message_format) override; + void parameter(const Parameter& parameter) override; + void parameterDefault(const ParameterDefault& parameter_default) override; + void addLoggedMessage(const AddLoggedMessage& add_logged_message) override; + void logging(const Logging& logging) override; + void data(const Data& data) override; + void dropout(const Dropout& dropout) override; + void sync(const Sync& sync) override; + + private: + const DataWriteCB _data_write_cb; + bool _header_complete{false}; +}; + +} // namespace flight_log diff --git a/src/data_container.cpp b/src/data_container.cpp new file mode 100644 index 0000000..355aa92 --- /dev/null +++ b/src/data_container.cpp @@ -0,0 +1,197 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include + +namespace flight_log { + +DataContainer::DataContainer(DataContainer::StorageConfig storage_config) + : _storage_config(storage_config) +{ +} +void DataContainer::error(const std::string& msg, bool is_recoverable) +{ + if (!is_recoverable) { + _had_fatal_error = true; + } + _parsing_errors.push_back(msg); +} +void DataContainer::headerComplete() +{ + // try to resolve all fields in message formats + for (auto& it : _message_formats) { + auto& message_format = it.second; + message_format->resolveDefinition(_message_formats); + } + + // try to resolve all fields for all message infos + for (auto& it : _message_info) { + auto& message_info = it.second; + message_info.field().resolveDefinition(_message_formats, 0); + } + + // try to resolve all fields for all multi message infos + for (auto& it : _message_info_multi) { + for (auto& message_infos_for_field : it.second) { + for (auto& message_info : message_infos_for_field) { + message_info.field().resolveDefinition(_message_formats, 0); + } + } + } + + // try to resolve all fields for params + for (auto& it : _default_parameters) { + auto& parameter_value = it.second; + parameter_value.field().resolveDefinition(_message_formats, 0); + } + + for (auto& it : _initial_parameters) { + auto& parameter_value = it.second; + parameter_value.field().resolveDefinition(_message_formats, 0); + } + + for (auto& parameter_value : _changed_parameters) { + parameter_value.field().resolveDefinition(_message_formats, 0); + } + + _header_complete = true; +} +void DataContainer::fileHeader(const FileHeader& header) +{ + _file_header = header; +} +void DataContainer::messageInfo(const MessageInfo& message_info_arg) +{ + // create mutable copy + MessageInfo message_info = message_info_arg; + if (_header_complete) { + // if header is complete, we can resolve definition here + message_info.field().resolveDefinition(_message_formats, 0); + } + if (_header_complete && _storage_config == StorageConfig::Header) { + return; + } + if (message_info.isMulti()) { + if (message_info.isContinued()) { + auto& messages = _message_info_multi[message_info.field().name()]; + if (messages.empty()) { + throw ParsingException("info_multi msg is continued, but no previous"); + } + messages[messages.size() - 1].push_back(message_info); + } else { + _message_info_multi[message_info.field().name()].push_back({message_info}); + } + } else { + _message_info.insert({message_info.field().name(), message_info}); + } +} +void DataContainer::messageFormat(const MessageFormat& message_format) +{ + if (_message_formats.find(message_format.name()) != _message_formats.end()) { + throw ParsingException("Duplicate message format"); + } + _message_formats.insert({message_format.name(), std::make_shared(message_format)}); +} +void DataContainer::parameter(const Parameter& parameter_arg) +{ + if (_header_complete && _storage_config == StorageConfig::Header) { + return; + } + if (_header_complete) { + auto parameter_value = parameter_arg; + // if header is complete, we can resolve definition here + parameter_value.field().resolveDefinition(_message_formats, 0); + _changed_parameters.push_back(parameter_value); + } else { + _initial_parameters.insert({parameter_arg.field().name(), parameter_arg}); + } +} +void DataContainer::parameterDefault(const ParameterDefault& parameter_default_arg) +{ + ParameterDefault parameter_default = parameter_default_arg; + if (_header_complete) { + // if header is already complete, we can resolve definition here + parameter_default.field().resolveDefinition(_message_formats, 0); + } + _default_parameters.insert({parameter_default.field().name(), parameter_default}); +} +void DataContainer::addLoggedMessage(const AddLoggedMessage& add_logged_message) +{ + // Subscriptions are always created, also in Header mode (without samples), so that + // data messages can be validated against their format. + if (_subscriptions_by_message_id.find(add_logged_message.msgId()) != + _subscriptions_by_message_id.end()) { + throw ParsingException("Duplicate AddLoggedMessage message ID"); + } + + auto format_iter = _message_formats.find(add_logged_message.messageName()); + if (format_iter == _message_formats.end()) { + throw ParsingException("AddLoggedMessage message format not found"); + } + + auto new_subscription = + std::make_shared(add_logged_message, std::vector{}, format_iter->second); + _subscriptions_by_message_id.insert({add_logged_message.msgId(), new_subscription}); + + const NameAndMultiIdKey key{add_logged_message.messageName(), + static_cast(add_logged_message.multiId())}; + _subscriptions_by_name_and_multi_id.insert({key, new_subscription}); +} +void DataContainer::logging(const Logging& logging) +{ + if (_header_complete && _storage_config == StorageConfig::Header) { + return; + } + _logging.emplace_back(std::move(logging)); +} +void DataContainer::data(const Data& data) +{ + const auto& iter = _subscriptions_by_message_id.find(data.msgId()); + if (iter == _subscriptions_by_message_id.end()) { + throw ParsingException("Invalid subscription"); + } + + // Guard against a Data message whose payload doesn't belong to this subscription's + // format at all. This can happen when the byte stream desyncs around a + // corrupted/dropped region: the framing (msg_size/msg_type/msg_id) can still look + // superficially valid while the payload actually belongs to a different message + // entirely. Without this check such a message would be silently decoded using the + // wrong field layout (reading garbage as e.g. a timestamp/float), rather than being + // discarded. Reader::tryToRecover() also calls isValidDataMessage() with this same + // logic before ever accepting such a candidate as a resync point in the first place - + // this check here is a defense-in-depth backstop for the (normally unreachable) case + // of a bad message slipping through outside of recovery. + if (!isValidDataMessage(data.msgId(), static_cast(data.data().size()))) { + const auto& format = *iter->second->format(); + throw ParsingException("Invalid data size for msg_id=" + std::to_string(data.msgId()) + " (" + + iter->second->getAddLoggedMessage().messageName() + ") has size " + + std::to_string(data.data().size()) + ", expected between " + + std::to_string(format.minWireSizeBytes()) + " and " + + std::to_string(format.sizeBytes())); + } + + if (_storage_config == StorageConfig::Header) { + return; // validated, but not stored + } + iter->second->emplaceSample(std::move(data)); +} +bool DataContainer::isValidDataMessage(uint16_t msg_id, uint16_t payload_size) const +{ + const auto iter = _subscriptions_by_message_id.find(msg_id); + if (iter == _subscriptions_by_message_id.end()) { + return false; + } + const auto& format = *iter->second->format(); + const auto actual_size = static_cast(payload_size); + return actual_size >= format.minWireSizeBytes() && actual_size <= format.sizeBytes(); +} +void DataContainer::dropout(const Dropout& dropout) +{ + if (_header_complete && _storage_config == StorageConfig::Header) { + return; + } + _dropouts.emplace_back(std::move(dropout)); +} +} // namespace flight_log diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..d573e4e --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,148 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +int inspectLog(const char* path) +{ + std::ifstream file(path, std::ios::binary); + if (!file) { + std::fprintf(stderr, "Cannot open log '%s'\n", path); + return 1; + } + std::array buffer{}; + const auto storage = flight_log::DataContainer::StorageConfig::FullLog; + const auto data_container = std::make_shared(storage); + flight_log::Reader reader{data_container}; + do { + file.read(reinterpret_cast(buffer.data()), buffer.size()); + if (file.bad() || (file.fail() && !file.eof())) { + std::fprintf(stderr, "Cannot read log '%s'\n", path); + return 1; + } + reader.readChunk(buffer.data(), static_cast(file.gcount())); + } while (file && !data_container->hadFatalError()); + + for (const auto& parsing_error : data_container->parsingErrors()) { + std::fprintf(stderr, "%s: %s\n", path, parsing_error.c_str()); + } + if (data_container->hadFatalError()) { + return 1; + } + + // Dropouts + const auto& dropouts = data_container->dropouts(); + const auto total_dropouts_ms = std::accumulate( + dropouts.begin(), dropouts.end(), uint64_t{0}, + [](uint64_t sum, const flight_log::Dropout& curr) { return sum + curr.durationMs(); }); + printf("Dropouts: %zu, total duration: %" PRIu64 " ms\n", dropouts.size(), total_dropouts_ms); + + auto print_value = [](const std::string& name, const flight_log::Value& value) { + std::visit( + [&name](auto&& arg) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + printf(" %s: %s\n", name.c_str(), arg.c_str()); + } else if constexpr (std::is_same_v) { + printf(" %s: %i\n", name.c_str(), arg); + } else if constexpr (std::is_same_v) { + printf(" %s: %u\n", name.c_str(), arg); + } else if constexpr (std::is_same_v) { + printf(" %s: %.3f\n", name.c_str(), static_cast(arg)); + } else { + printf(" %s: \n", name.c_str()); + } + }, + value.asNativeTypeVariant()); + }; + + // Info messages + printf("Info Messages:\n"); + for (const auto& info_msg : data_container->messageInfo()) { + print_value(info_msg.second.field().name(), info_msg.second.value()); + } + // Info multi messages + printf("Info Multiple Messages:"); + for (const auto& info_msg : data_container->messageInfoMulti()) { + printf(" [%s: %zu],", info_msg.first.c_str(), info_msg.second.size()); + } + printf("\n"); + + // Messages + printf("\n"); + printf("Name (multi id) - number of data points\n"); + for (const auto& item : data_container->subscriptionsByNameAndMultiId()) { + printf(" %s (%i) - %zu\n", item.first.name.c_str(), item.first.multi_id, + item.second->size()); + } + + printf("Formats:\n"); + for (const auto& msg_format : data_container->messageFormats()) { + std::string format_fields; + for (const auto& field : msg_format.second->fields()) { + format_fields += field->encode() + ", "; + } + printf(" %s: %s\n", msg_format.second->name().c_str(), format_fields.c_str()); + } + + // logging + printf("Logging:\n"); + for (const auto& logging : data_container->logging()) { + std::string tag_str; + if (logging.hasTag()) { + tag_str = std::to_string(logging.tag()) + " "; + } + printf(" %s<%s> %" PRIu64 " %s\n", tag_str.c_str(), logging.logLevelStr().c_str(), + logging.timestamp(), logging.message().c_str()); + } + + // Parameters + printf("Default Params:\n"); + for (const auto& default_param : data_container->defaultParameters()) { + print_value(default_param.second.field().name(), default_param.second.value()); + } + printf("Initial Params:\n"); + for (const auto& initial_param : data_container->initialParameters()) { + print_value(initial_param.second.field().name(), initial_param.second.value()); + } + + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + constexpr auto usage = "Usage: flight-log-inspector \n"; + if (argc == 2 && std::string_view(argv[1]) == "--help") { + std::fputs(usage, stdout); + return 0; + } + if (argc != 2) { + std::fputs(usage, stderr); + return 2; + } + try { + return inspectLog(argv[1]); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s: %s\n", argv[1], error.what()); + return 1; + } +} diff --git a/src/messages.cpp b/src/messages.cpp new file mode 100644 index 0000000..b4b1fe3 --- /dev/null +++ b/src/messages.cpp @@ -0,0 +1,692 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include + +#include +#include +#include +#include + +#define CHECK_MSG_SIZE(size, min_required) \ + if ((size) < (min_required)) throw ParsingException("message too short") + +namespace flight_log { + +FileHeader::FileHeader(const ulog_file_header_s& header, const ulog_message_flag_bits_s& flag_bits) + : _header(header), _flag_bits(flag_bits) +{ +} +FileHeader::FileHeader(const ulog_file_header_s& header) : _header(header), _has_flag_bits(false) +{ +} + +FileHeader::FileHeader(uint64_t timestamp, bool has_default_parameters) +{ + // Set flags + if (has_default_parameters) { + _flag_bits.compat_flags[0] |= ULOG_COMPAT_FLAG0_DEFAULT_PARAMETERS_MASK; + } + _flag_bits.msg_size = sizeof(_flag_bits) - ULOG_MSG_HEADER_LEN; + + memcpy(_header.magic, ulog_file_magic_bytes, sizeof(ulog_file_magic_bytes)); + _header.magic[7] = 1; // file version 1 + _header.timestamp = timestamp; +} + +void FileHeader::serialize(const DataWriteCB& writer) const +{ + writer(reinterpret_cast(&_header), sizeof(_header)); + if (_has_flag_bits) { + ulog_message_flag_bits_s flag_bits = _flag_bits; + flag_bits.msg_size = sizeof(flag_bits) - ULOG_MSG_HEADER_LEN; + writer(reinterpret_cast(&flag_bits), sizeof(flag_bits)); + } +} + +MessageInfo::MessageInfo(const uint8_t* msg, bool is_multi) : _is_multi(is_multi) +{ + if (is_multi) { + const ulog_message_info_multiple_s* info_multi = + reinterpret_cast(msg); + CHECK_MSG_SIZE(info_multi->msg_size, 3); + _continued = info_multi->is_continued; + if (info_multi->key_len > info_multi->msg_size - 2) { + throw ParsingException("Key too long"); // invalid + } + _field = Field(info_multi->key_value_str, info_multi->key_len); + initValues(info_multi->key_value_str + info_multi->key_len, + info_multi->msg_size - info_multi->key_len - 2); + } else { + const ulog_message_info_s* info = reinterpret_cast(msg); + CHECK_MSG_SIZE(info->msg_size, 2); + if (info->key_len > info->msg_size - 1) { + throw ParsingException("Key too long"); // invalid + } + _field = Field(info->key_value_str, info->key_len); + initValues(info->key_value_str + info->key_len, info->msg_size - info->key_len - 1); + } + if (_field.type().type != Field::BasicType::NESTED) { + // For basic types we can resolve the definition immediately + _field.resolveDefinition(0); + } +} +void MessageInfo::initValues(const char* values, int len) +{ + _value.resize(len); + memcpy(_value.data(), values, len); +} +Field::Field(const char* str, int len) +{ + // Format: '[len] ' or ' ' + // Find first space + const std::string_view key_value{str, static_cast(len)}; + const std::string::size_type first_space = key_value.find(' '); + if (first_space == std::string::npos) { + throw ParsingException("Invalid key format"); + } + const std::string_view key_array = key_value.substr(0, first_space); + _name = key_value.substr(first_space + 1); + // Check for arrays + const std::string::size_type bracket = key_array.find('['); + std::string type_name; + if (bracket == std::string::npos) { + type_name = key_array; + } else { + type_name = key_array.substr(0, bracket); + if (key_array[key_array.length() - 1] != ']') { + throw ParsingException("Invalid key format (missing ])"); + } + _array_length = std::stoi(std::string(key_array.substr(bracket + 1))); + } + auto it_basic = kBasicTypes.find(type_name); + if (it_basic != kBasicTypes.end()) { + _type = it_basic->second; + } else { + // Assume this is a recursive type (unresolved at this point) + _type = {type_name, Field::BasicType::NESTED, 0}; + } +} + +void Field::resolveDefinition( + const std::map>& existing_formats, int offset) +{ + // if this is already resolved, do nothing + if (definitionResolved()) { + return; + } + + _offset_in_message_bytes = offset; + // if this is a basic type, we are done + if (_type.type != Field::BasicType::NESTED) { + return; + } + + auto it = existing_formats.find(_type.name); + if (it == existing_formats.end()) { + throw ParsingException("Message format not found: " + _type.name); + } + _type.nested_message = it->second; + // recursively resolve nested type + _type.nested_message->resolveDefinition(existing_formats); + _type.size = _type.nested_message->sizeBytes(); +} + +void Field::resolveDefinition(int offset) +{ + if (definitionResolved()) { + return; + } + + if (_type.type == Field::BasicType::NESTED) { + throw ParsingException("Nested type not resolved"); + } + _offset_in_message_bytes = offset; +} + +std::shared_ptr Field::nestedFormat() const +{ + if (_type.type != Field::BasicType::NESTED) { + throw AccessException("Not a nested type"); + } + return _type.nested_message; +} + +std::shared_ptr Field::nestedField(const std::string& name) const +{ + if (_type.type != Field::BasicType::NESTED) { + throw AccessException("Not a nested type"); + } + return _type.nested_message->field(name); +} + +const std::map Field::kBasicTypes{ + {"int8_t", {"int8_t", Field::BasicType::INT8, 1}}, + {"uint8_t", {"uint8_t", Field::BasicType::UINT8, 1}}, + {"int16_t", {"int16_t", Field::BasicType::INT16, 2}}, + {"uint16_t", {"uint16_t", Field::BasicType::UINT16, 2}}, + {"int32_t", {"int32_t", Field::BasicType::INT32, 4}}, + {"uint32_t", {"uint32_t", Field::BasicType::UINT32, 4}}, + {"int64_t", {"int64_t", Field::BasicType::INT64, 8}}, + {"uint64_t", {"uint64_t", Field::BasicType::UINT64, 8}}, + {"float", {"float", Field::BasicType::FLOAT, 4}}, + {"double", {"double", Field::BasicType::DOUBLE, 8}}, + {"bool", {"bool", Field::BasicType::BOOL, 1}}, + {"char", {"char", Field::BasicType::CHAR, 1}}}; + +int Field::sizeBytes() const +{ + if (!definitionResolved()) { + throw ParsingException("Unresolved type " + _type.name); + } + return _type.size * ((_array_length == -1) ? 1 : _array_length); +} + +std::string Field::encode() const +{ + if (_array_length >= 0) { + return _type.name + '[' + std::to_string(_array_length) + ']' + ' ' + _name; + } + return _type.name + ' ' + _name; +} +Value::NativeTypeVariant Value::asNativeTypeVariant() const +{ + if (_array_index >= 0 && _field_ref.arrayLength() < 0) { + throw AccessException("Can not access array element of non-array field"); + } + + if (_field_ref.arrayLength() == -1 || _array_index >= 0) { + // decode as a single value. Either it is a single value, + // or the user has explicitly selected an array element + const int array_offset = _array_index >= 0 ? _array_index : 0; + switch (_field_ref.type().type) { + case Field::BasicType::INT8: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::UINT8: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::INT16: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::UINT16: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::INT32: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::UINT32: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::INT64: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::UINT64: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::FLOAT: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::DOUBLE: + return deserialize(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), array_offset); + case Field::BasicType::BOOL: + return deserialize(_backing_ref_begin, _backing_ref_end, _field_ref.offsetInMessage(), + array_offset); + case Field::BasicType::CHAR: + return deserialize(_backing_ref_begin, _backing_ref_end, _field_ref.offsetInMessage(), + array_offset); + case Field::BasicType::NESTED: + throw AccessException("Can't get nested field as basic type. Field " + _field_ref.name()); + } + } else { + // decode as an array + switch (_field_ref.type().type) { + case Field::BasicType::INT8: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::UINT8: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::INT16: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::UINT16: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::INT32: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::UINT32: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::INT64: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::UINT64: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::FLOAT: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::DOUBLE: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::BOOL: + return deserializeVector(_backing_ref_begin, _backing_ref_end, + _field_ref.offsetInMessage(), _field_ref.arrayLength()); + case Field::BasicType::CHAR: { + auto string_start_iterator = _backing_ref_begin + _field_ref.offsetInMessage(); + if (_backing_ref_end - string_start_iterator < _field_ref.arrayLength()) { + throw AccessException("Decoding fault, memory too short"); + } + const int string_length = strnlen(&(*string_start_iterator), _field_ref.arrayLength()); + return std::string(string_start_iterator, string_start_iterator + string_length); + } + + case Field::BasicType::NESTED: + throw AccessException("Can't get nested field as basic type. Field " + _field_ref.name()); + } + } + return deserialize(_backing_ref_begin, _backing_ref_end, _field_ref.offsetInMessage(), + 0); +} + +Value Value::operator[](const Field& field) const +{ + if (_field_ref.type().type != Field::BasicType::NESTED) { + throw AccessException("Cannot access field of non-nested type"); + } + if (!_field_ref.definitionResolved()) { + throw AccessException("Cannot access field of unresolved type"); + } + const int submessage_offset = _field_ref.offsetInMessage() + + ((_array_index >= 0) ? _field_ref.type().size * _array_index : 0); + + return Value(field, _backing_ref_begin + submessage_offset, _backing_ref_end); +} + +Value Value::operator[](const std::shared_ptr& field) const +{ + return operator[](*field); +} + +Value Value::operator[](const std::string& field_name) const +{ + if (_field_ref.type().type != Field::BasicType::NESTED) { + throw AccessException("Cannot access field of non-nested type"); + } + if (!_field_ref.definitionResolved()) { + throw AccessException("Cannot access field of unresolved type"); + } + const auto& field = _field_ref.type().nested_message->field(field_name); + return operator[](*field); +} + +Value Value::operator[](size_t index) const +{ + if (_field_ref.arrayLength() < 0) { + throw AccessException("Cannot access field of non-array type"); + } + if (index >= static_cast(_field_ref.arrayLength())) { + throw AccessException("Index out of bounds"); + } + return Value(_field_ref, _backing_ref_begin, _backing_ref_end, index); +} + +MessageInfo::MessageInfo(Field field, std::vector value, bool is_multi, bool continued) + : _field(std::move(field)), _value(std::move(value)), _continued(continued), _is_multi(is_multi) +{ +} +MessageInfo::MessageInfo(const std::string& key, int32_t value) : _field({"int32_t", key}) +{ + _value.resize(sizeof(value)); + memcpy(_value.data(), &value, sizeof(value)); +} +MessageInfo::MessageInfo(const std::string& key, float value) : _field({"float", key}) +{ + _value.resize(sizeof(value)); + memcpy(_value.data(), &value, sizeof(value)); +} +MessageInfo::MessageInfo(const std::string& key, const std::string& value) + : _field({"char", key, static_cast(value.length())}) +{ + _value.resize(value.length()); + memcpy(_value.data(), value.data(), value.length()); +} +void MessageInfo::serialize(const DataWriteCB& writer, ULogMessageType type) const +{ + const std::string field_encoded = _field.encode(); + if (_is_multi) { + ulog_message_info_multiple_s info_multi{}; + info_multi.is_continued = _continued; + const int msg_size = field_encoded.length() + _value.size() + 2; + if (msg_size > std::numeric_limits::max() || + field_encoded.length() > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + info_multi.key_len = field_encoded.length(); + info_multi.msg_size = msg_size; + + writer(reinterpret_cast(&info_multi), ULOG_MSG_HEADER_LEN + 2); + writer(reinterpret_cast(field_encoded.data()), field_encoded.size()); + writer(reinterpret_cast(_value.data()), _value.size()); + } else { + ulog_message_info_s info{}; + const int msg_size = field_encoded.length() + _value.size() + 1; + if (msg_size > std::numeric_limits::max() || + field_encoded.length() > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + info.key_len = field_encoded.length(); + info.msg_size = msg_size; + info.msg_type = static_cast(type); + + writer(reinterpret_cast(&info), ULOG_MSG_HEADER_LEN + 1); + writer(reinterpret_cast(field_encoded.data()), field_encoded.size()); + writer(reinterpret_cast(_value.data()), _value.size()); + } +} +MessageFormat::MessageFormat(const uint8_t* msg) +{ + const ulog_message_format_s* format = reinterpret_cast(msg); + // Format: :;; ... + auto format_str = std::string_view(format->format, format->msg_size); + const std::string::size_type colon = format_str.find(':'); + if (colon == std::string::npos) { + throw ParsingException("Invalid message format (no :)"); // invalid + } + _name = format_str.substr(0, colon); + format_str = format_str.substr(colon + 1); + while (!format_str.empty()) { + const std::string::size_type semicolon = format_str.find(';'); + if (semicolon == std::string::npos) { + throw ParsingException("Invalid message format (no ;)"); // invalid + } + auto f = std::make_shared(format_str.data(), static_cast(semicolon)); + _fields.insert({f->name(), f}); + _fields_ordered.push_back(f); + format_str = format_str.substr(semicolon + 1); + } +} +MessageFormat::MessageFormat(std::string name, const std::vector& fields) + : _name(std::move(name)) +{ + for (const auto& current_field : fields) { + auto f = std::make_shared(current_field); + _fields.insert({f->name(), f}); + _fields_ordered.push_back(f); + } +} + +int MessageFormat::sizeBytes() const +{ + int size = 0; + for (const auto& it : _fields) { + size += it.second->sizeBytes(); + } + return size; +} + +int MessageFormat::minWireSizeBytes() const +{ + int end = static_cast(_fields_ordered.size()); + while (end > 0 && _fields_ordered[end - 1]->name().rfind("_padding", 0) == 0) { + --end; + } + int size = 0; + for (int i = 0; i < end; ++i) { + size += _fields_ordered[i]->sizeBytes(); + } + return size; +} + +void MessageFormat::resolveDefinition( + const std::map>& existing_formats) const +{ + int offset = 0; + for (const auto& current_field : _fields_ordered) { + if (!current_field->definitionResolved()) { + current_field->resolveDefinition(existing_formats, offset); + } + offset += current_field->sizeBytes(); + } +} + +void MessageFormat::serialize(const DataWriteCB& writer) const +{ + std::string format_str = _name + ':'; + + for (const auto& current_field : _fields_ordered) { + format_str += current_field->encode() + ';'; + } + + ulog_message_format_s format; + const int msg_size = format_str.length(); + if (msg_size > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + format.msg_size = msg_size; + writer(reinterpret_cast(&format), ULOG_MSG_HEADER_LEN); + writer(reinterpret_cast(format_str.data()), format_str.size()); +} + +ParameterDefault::ParameterDefault(const uint8_t* msg) +{ + const ulog_message_parameter_default_s* param_default = + reinterpret_cast(msg); + CHECK_MSG_SIZE(param_default->msg_size, 3); + _default_types = param_default->default_types; + if (param_default->key_len > param_default->msg_size - 2) { + throw ParsingException("Key too long"); // invalid + } + _field = Field(param_default->key_value_str, param_default->key_len); + initValues(param_default->key_value_str + param_default->key_len, + param_default->msg_size - param_default->key_len - 2); + if (_field.type().type != Field::BasicType::NESTED) { + // For basic types we can resolve the definition immediately + _field.resolveDefinition(0); + } +} +void ParameterDefault::initValues(const char* values, int len) +{ + _value.resize(len); + memcpy(_value.data(), values, len); +} +ParameterDefault::ParameterDefault(Field field, std::vector value, + ulog_parameter_default_type_t default_types) + : _field(std::move(field)), _value(std::move(value)), _default_types(default_types) +{ +} +void ParameterDefault::serialize(const DataWriteCB& writer) const +{ + const std::string field_encoded = _field.encode(); + ulog_message_parameter_default_s parameter_default{}; + const int msg_size = field_encoded.length() + _value.size() + 2; + if (msg_size > std::numeric_limits::max() || + field_encoded.length() > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + parameter_default.key_len = field_encoded.length(); + parameter_default.msg_size = msg_size; + parameter_default.default_types = _default_types; + + writer(reinterpret_cast(¶meter_default), ULOG_MSG_HEADER_LEN + 2); + writer(reinterpret_cast(field_encoded.data()), field_encoded.size()); + writer(reinterpret_cast(_value.data()), _value.size()); +} + +AddLoggedMessage::AddLoggedMessage(const uint8_t* msg) +{ + const ulog_message_add_logged_s* add_logged = + reinterpret_cast(msg); + CHECK_MSG_SIZE(add_logged->msg_size, 4); + _multi_id = add_logged->multi_id; + _msg_id = add_logged->msg_id; + _message_name = std::string(add_logged->message_name, add_logged->msg_size - 3); +} +AddLoggedMessage::AddLoggedMessage(uint8_t multi_id, uint16_t msg_id, std::string message_name) + : _multi_id(multi_id), _msg_id(msg_id), _message_name(std::move(message_name)) +{ +} +void AddLoggedMessage::serialize(const DataWriteCB& writer) const +{ + ulog_message_add_logged_s add_logged; + const int msg_size = _message_name.size() + 3; + if (msg_size > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + add_logged.multi_id = _multi_id; + add_logged.msg_id = _msg_id; + add_logged.msg_size = msg_size; + + writer(reinterpret_cast(&add_logged), ULOG_MSG_HEADER_LEN + 3); + writer(reinterpret_cast(_message_name.data()), _message_name.size()); +} + +Logging::Logging(const uint8_t* msg, bool is_tagged) : _has_tag(is_tagged) +{ + uint8_t log_level{}; + if (is_tagged) { + const ulog_message_logging_tagged_s* logging = + reinterpret_cast(msg); + CHECK_MSG_SIZE(logging->msg_size, 12); + log_level = logging->log_level; + _tag = logging->tag; + _timestamp = logging->timestamp; + _message = std::string(logging->message, logging->msg_size - 11); + } else { + const ulog_message_logging_s* logging = reinterpret_cast(msg); + CHECK_MSG_SIZE(logging->msg_size, 10); + log_level = logging->log_level; + _timestamp = logging->timestamp; + _message = std::string(logging->message, logging->msg_size - 9); + } + if (log_level < static_cast(Level::Emergency) || + log_level > static_cast(Level::Debug)) { + _log_level = Level::Debug; + } else { + _log_level = static_cast(log_level); + } +} +Logging::Logging(Level level, std::string message, uint64_t timestamp) + : _log_level(level), _timestamp(timestamp), _message(std::move(message)) +{ +} +std::string Logging::logLevelStr() const +{ + switch (_log_level) { + case Level::Emergency: + return "Emergency"; + case Level::Alert: + return "Alert"; + case Level::Critical: + return "Critical"; + case Level::Error: + return "Error"; + case Level::Warning: + return "Warning"; + case Level::Notice: + return "Notice"; + case Level::Info: + return "Info"; + case Level::Debug: + return "Debug"; + } + return "unknown"; +} +void Logging::serialize(const DataWriteCB& writer) const +{ + if (_has_tag) { + ulog_message_logging_tagged_s logging; + const int msg_size = _message.size() + 11; + if (msg_size > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + logging.log_level = static_cast(_log_level); + logging.tag = _tag; + logging.timestamp = _timestamp; + logging.msg_size = msg_size; + + writer(reinterpret_cast(&logging), ULOG_MSG_HEADER_LEN + 11); + writer(reinterpret_cast(_message.data()), _message.size()); + } else { + ulog_message_logging_s logging; + const int msg_size = _message.size() + 9; + if (msg_size > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + logging.log_level = static_cast(_log_level); + logging.timestamp = _timestamp; + logging.msg_size = msg_size; + + writer(reinterpret_cast(&logging), ULOG_MSG_HEADER_LEN + 9); + writer(reinterpret_cast(_message.data()), _message.size()); + } +} + +Data::Data(const uint8_t* msg) +{ + const ulog_message_data_s* msg_data = reinterpret_cast(msg); + CHECK_MSG_SIZE(msg_data->msg_size, 3); + _msg_id = msg_data->msg_id; + const int data_len = msg_data->msg_size - 2; + _data.resize(data_len); + memcpy(_data.data(), &msg_data->msg_id + 1, data_len); +} +Data::Data(uint16_t msg_id, std::vector data) : _msg_id(msg_id), _data(std::move(data)) +{ +} +void Data::serialize(const DataWriteCB& writer) const +{ + ulog_message_data_s data_msg; + const int msg_size = _data.size() + 2; + if (msg_size > std::numeric_limits::max()) { + throw ParsingException("message too long"); + } + data_msg.msg_id = _msg_id; + data_msg.msg_size = msg_size; + + writer(reinterpret_cast(&data_msg), ULOG_MSG_HEADER_LEN + 2); + writer(reinterpret_cast(_data.data()), _data.size()); +} + +Dropout::Dropout(const uint8_t* msg) +{ + const ulog_message_dropout_s* dropout = reinterpret_cast(msg); + CHECK_MSG_SIZE(dropout->msg_size, 2); + _duration_ms = dropout->duration; +} +Dropout::Dropout(uint16_t duration_ms) : _duration_ms(duration_ms) +{ +} +void Dropout::serialize(const DataWriteCB& writer) const +{ + ulog_message_dropout_s dropout; + const int msg_size = sizeof(dropout) - ULOG_MSG_HEADER_LEN; + dropout.duration = _duration_ms; + dropout.msg_size = msg_size; + + writer(reinterpret_cast(&dropout), sizeof(dropout)); +} +Sync::Sync(const uint8_t* msg) +{ + const ulog_message_sync_s* sync = reinterpret_cast(msg); + CHECK_MSG_SIZE(sync->msg_size, sizeof(kSyncMagicBytes)); + if (memcmp(sync->sync_magic, kSyncMagicBytes, sizeof(kSyncMagicBytes)) != 0) { + throw ParsingException("Invalid sync magic bytes"); + } +} +void Sync::serialize(const DataWriteCB& writer) const +{ + ulog_message_sync_s sync; + const int msg_size = sizeof(sync) - ULOG_MSG_HEADER_LEN; + static_assert(sizeof(sync.sync_magic) == sizeof(kSyncMagicBytes)); + memcpy(sync.sync_magic, kSyncMagicBytes, sizeof(kSyncMagicBytes)); + sync.msg_size = msg_size; + + writer(reinterpret_cast(&sync), sizeof(sync)); +} +} // namespace flight_log diff --git a/src/reader.cpp b/src/reader.cpp new file mode 100644 index 0000000..9e0597b --- /dev/null +++ b/src/reader.cpp @@ -0,0 +1,427 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include + +#include + +#include + +#if 0 // NOLINT (readability-avoid-unconditional-preprocessor-if) +#define DBG_PRINTF(...) printf(__VA_ARGS__) +#else +#define DBG_PRINTF(...) +#endif + +namespace flight_log { + +const std::set Reader::kKnownMessageTypes{{ + ULogMessageType::FORMAT, + ULogMessageType::DATA, + ULogMessageType::INFO, + ULogMessageType::INFO_MULTIPLE, + ULogMessageType::PARAMETER, + ULogMessageType::PARAMETER_DEFAULT, + ULogMessageType::ADD_LOGGED_MSG, + ULogMessageType::REMOVE_LOGGED_MSG, + ULogMessageType::SYNC, + ULogMessageType::DROPOUT, + ULogMessageType::LOGGING, + ULogMessageType::LOGGING_TAGGED, + ULogMessageType::FLAG_BITS, +}}; + +// cppcheck-suppress [uninitMemberVar,unmatchedSuppression] +Reader::Reader(std::shared_ptr data_handler_interface) + : _data_handler_interface(std::move(data_handler_interface)) +{ + // Reader assumes to run on little endian + // TODO: use std::endian from C++20 + int num = 1; + // cppcheck-suppress [knownConditionTrueFalse,unmatchedSuppression] + if (*reinterpret_cast(&num) != 1) { + _data_handler_interface->error("Reader requires little endian", false); + _state = State::InvalidData; + } + _partial_message_buffer = static_cast(malloc(kBufferSizeInit)); + _partial_message_buffer_length_capacity = kBufferSizeInit; +} + +Reader::~Reader() +{ + if (_partial_message_buffer) { + free(_partial_message_buffer); + } +} + +void Reader::readChunk(const uint8_t* data, int length) +{ + if (_state == State::InvalidData) { + return; + } + + if (_state == State::ReadMagic) { + const int num_read = readMagic(data, length); + data += num_read; + length -= num_read; + _total_num_read += num_read; + } + + if (_state == State::ReadFlagBits && length > 0) { + const int num_read = readFlagBits(data, length); + data += num_read; + length -= num_read; + _total_num_read += num_read; + } + + static constexpr int kULogHeaderLength = static_cast(sizeof(ulog_message_header_s)); + + while (length > 0 && !_need_recovery) { + // Try to get a full ulog message. There's 2 options: + // - we have some partial data in the buffer. We need to append and use that buffer + // - no partial data left. Use 'data' if it contains a full message + const uint8_t* ulog_message = nullptr; + bool clear_from_partial_message_buffer = false; + if (_partial_message_buffer_length > 0) { + auto ensure_enough_data_in_partial_buffer = [&](int required_data) -> bool { + if (_partial_message_buffer_length < required_data) { + // Try to append + const int num_append = std::min(required_data - _partial_message_buffer_length, length); + if (_partial_message_buffer_length + num_append > + _partial_message_buffer_length_capacity) { + // Overflow, resize buffer + _partial_message_buffer_length_capacity = _partial_message_buffer_length + num_append; + _partial_message_buffer = static_cast( + realloc(_partial_message_buffer, _partial_message_buffer_length_capacity)); + DBG_PRINTF("%i: resized partial buffer to %i\n", _total_num_read, + _partial_message_buffer_length_capacity); + } + memcpy(_partial_message_buffer + _partial_message_buffer_length, data, num_append); + _partial_message_buffer_length += num_append; + data += num_append; + length -= num_append; + _total_num_read += num_append; + } + return _partial_message_buffer_length >= required_data; + }; + if (ensure_enough_data_in_partial_buffer(kULogHeaderLength)) { + const ulog_message_header_s* header = + reinterpret_cast(_partial_message_buffer); + if (ensure_enough_data_in_partial_buffer(header->msg_size + kULogHeaderLength)) { + ulog_message = reinterpret_cast(_partial_message_buffer); + clear_from_partial_message_buffer = true; + } else { + // Not enough data yet (length == 0) or overflow + DBG_PRINTF("%i: not enough data (length=%i)\n", _total_num_read, length); + } + } + + } else { + int full_message_length = 0; + if (length > kULogHeaderLength) { + const ulog_message_header_s* header = reinterpret_cast(data); + if (length >= header->msg_size + kULogHeaderLength) { + full_message_length = header->msg_size + kULogHeaderLength; + } + } + if (full_message_length > 0) { + ulog_message = data; + data += full_message_length; + length -= full_message_length; + _total_num_read += full_message_length; + } else { + // Not a full message in buffer -> add to partial buffer + const int num_append = appendToPartialBuffer(data, length); + data += num_append; + length -= num_append; + _total_num_read += num_append; + } + } + + if (ulog_message) { + const ulog_message_header_s* header = + reinterpret_cast(ulog_message); + + // Check for corruption + if (header->msg_size == 0 || header->msg_type == 0) { + DBG_PRINTF("%i: Invalid msg detected\n", _total_num_read); + corruptionDetected(); + // We'll exit the loop afterwards + } else { + // Parse the message + try { + if (_state == State::ReadHeader) { + readHeaderMessage(ulog_message); + } + if (_state == State::ReadData) { + readDataMessage(ulog_message); + } + } catch (const ParsingException& exception) { + DBG_PRINTF("%i: parser exception: %s\n", _total_num_read, exception.what()); + corruptionDetected(); + } + } + + if (clear_from_partial_message_buffer) { + // In most cases this will clear the whole buffer, but in case of corruptions we might have + // more data + const int num_remove = header->msg_size + kULogHeaderLength; + memmove(_partial_message_buffer, _partial_message_buffer + num_remove, + _partial_message_buffer_length - num_remove); + _partial_message_buffer_length -= num_remove; + } + } + } + + if (_need_recovery) { + tryToRecover(data, length); + } +} + +void Reader::tryToRecover(const uint8_t* data, int length) +{ + // Try to find a valid message in 'data' by moving data into the partial buffer and search for a + // message + while (length > 0) { + const int num_append = appendToPartialBuffer(data, length); + data += num_append; + length -= num_append; + _total_num_read += num_append; + + if (_partial_message_buffer_length >= static_cast(sizeof(ulog_message_header_s))) { + bool found = false; + int index = 0; + // If the partial buffer was already full, skip the first index, otherwise we risk infinite + // recursion + if (num_append == 0) { + index = 1; + } + for (; + index < _partial_message_buffer_length - static_cast(sizeof(ulog_message_header_s)); + ++index) { + const ulog_message_header_s* header = + reinterpret_cast(_partial_message_buffer + index); + // Try to use it if it looks sane (we could also check for a SYNC message) + if (header->msg_size != 0 && header->msg_type != 0 && header->msg_size < 10000 && + kKnownMessageTypes.find(static_cast(header->msg_type)) != + kKnownMessageTypes.end()) { + // A DATA candidate additionally has to reference a real subscription with a + // plausible payload size for it - the checks above alone (known type + size + // cap) are satisfied by a lot of unrelated byte patterns, and DATA messages + // are by far the most common type, so without this a resync can easily lock + // onto the wrong offset: bytes that happen to look like a Data header for some + // other message entirely, rather than the true next message. See + // DataHandlerInterface::isValidDataMessage(). + bool candidate_valid = true; + if (static_cast(header->msg_type) == ULogMessageType::DATA) { + if (header->msg_size < 2 || _partial_message_buffer_length - index < + static_cast(sizeof(ulog_message_header_s)) + 2) { + // Too small to even hold the 2-byte msg_id, or not enough buffered data + // yet to see it - can't validate this candidate, so don't accept it + // (more data may still arrive for a later pass). + candidate_valid = false; + } else { + uint16_t candidate_msg_id = 0; + memcpy(&candidate_msg_id, + _partial_message_buffer + index + sizeof(ulog_message_header_s), + sizeof(candidate_msg_id)); + const auto candidate_payload_size = static_cast(header->msg_size - 2); + candidate_valid = _data_handler_interface->isValidDataMessage(candidate_msg_id, + candidate_payload_size); + } + } + if (candidate_valid) { + found = true; + break; + } + } + } + + // Discard unused data + if (index > 0) { + memmove(_partial_message_buffer, _partial_message_buffer + index, + _partial_message_buffer_length - index); + _partial_message_buffer_length -= index; + } + + if (found) { + DBG_PRINTF( + "%i: recovered, recursive call (index = %i, length = %i, partial buf len = %i)\n", + _total_num_read, index, length, _partial_message_buffer_length); + _need_recovery = false; + readChunk(data, length); + + return; + } + DBG_PRINTF("%i: no valid msg found (length = %i, partial buf len = %i)\n", _total_num_read, + length, _partial_message_buffer_length); + } + } +} + +void Reader::corruptionDetected() +{ + if (!_corruption_reported) { + _data_handler_interface->error("Message corruption detected", true); + _corruption_reported = true; + } + _need_recovery = true; +} + +int Reader::appendToPartialBuffer(const uint8_t* data, int length) +{ + const int num_append = + std::min(length, _partial_message_buffer_length_capacity - _partial_message_buffer_length); + memcpy(_partial_message_buffer + _partial_message_buffer_length, data, num_append); + _partial_message_buffer_length += num_append; + return num_append; +} + +int Reader::readMagic(const uint8_t* data, int length) +{ + // Assume we read the whole magic in one piece. If needed, we could handle reading it in multiple + // bits. Note that this could also happen for truncated files. + if (length < static_cast(sizeof(ulog_file_header_s))) { + _data_handler_interface->error("Not enough data to read file magic", false); + _state = State::InvalidData; + return 0; + } + + const ulog_file_header_s* header = reinterpret_cast(data); + + // Check magic bytes + if (memcmp(header->magic, ulog_file_magic_bytes, sizeof(ulog_file_magic_bytes)) != 0) { + _data_handler_interface->error("Invalid file format (incorrect header bytes)", false); + _state = State::InvalidData; + return 0; + } + + _state = State::ReadFlagBits; + _file_header = *header; + + return sizeof(ulog_file_header_s); +} + +int Reader::readFlagBits(const uint8_t* data, int length) +{ + // Assume we read the whole flags in one piece (for simplicity of the parser) + int ret = 0; + if (length < static_cast(sizeof(ulog_message_flag_bits_s))) { + _data_handler_interface->error("Not enough data to read file flags", false); + _state = State::InvalidData; + return 0; + } + // This message is optional and follows directly the file magic + const ulog_message_flag_bits_s* flag_bits = + reinterpret_cast(data); + if (static_cast(flag_bits->msg_type) == ULogMessageType::FLAG_BITS) { + // This is expected to be the first message after the file magic + if (flag_bits->appended_offsets[0] != 0) { + // TODO: handle appended data + _data_handler_interface->error("File contains appended offsets - this is not supported", + true); + } + // Check incompat flags + bool has_incompat_flags = false; + if (flag_bits->incompat_flags[0] & ~(ULOG_INCOMPAT_FLAG0_DATA_APPENDED_MASK)) { + has_incompat_flags = true; + } + for (unsigned i = 1; + i < sizeof(flag_bits->incompat_flags) / sizeof(flag_bits->incompat_flags[0]); ++i) { + if (flag_bits->incompat_flags[i]) { + has_incompat_flags = true; + } + } + if (has_incompat_flags) { + _data_handler_interface->error("Unknown incompatible flag set: cannot parse the log", false); + _state = State::InvalidData; + } else { + _data_handler_interface->fileHeader({_file_header, *flag_bits}); + ret = flag_bits->msg_size + ULOG_MSG_HEADER_LEN; + _state = State::ReadHeader; + } + } else { + // Create header w/o flag bits + _data_handler_interface->fileHeader(FileHeader{_file_header}); + _state = State::ReadHeader; + } + return ret; +} + +void Reader::readHeaderMessage(const uint8_t* message) +{ + const ulog_message_header_s* header = reinterpret_cast(message); + switch (static_cast(header->msg_type)) { + case ULogMessageType::INFO: + _data_handler_interface->messageInfo(MessageInfo{message, false}); + break; + case ULogMessageType::INFO_MULTIPLE: + _data_handler_interface->messageInfo(MessageInfo{message, true}); + break; + case ULogMessageType::FORMAT: + _data_handler_interface->messageFormat(MessageFormat{message}); + break; + case ULogMessageType::PARAMETER: + _data_handler_interface->parameter(Parameter{message}); + break; + case ULogMessageType::PARAMETER_DEFAULT: + _data_handler_interface->parameterDefault(ParameterDefault{message}); + break; + case ULogMessageType::ADD_LOGGED_MSG: + case ULogMessageType::LOGGING: + case ULogMessageType::LOGGING_TAGGED: + DBG_PRINTF("%i: Header completed\n", _total_num_read); + _state = State::ReadData; + _data_handler_interface->headerComplete(); + break; + default: + DBG_PRINTF("%i: Unknown/unexpected message type in header: %i\n", _total_num_read, + header->msg_size); + break; + } +} + +void Reader::readDataMessage(const uint8_t* message) +{ + const ulog_message_header_s* header = reinterpret_cast(message); + switch (static_cast(header->msg_type)) { + case ULogMessageType::INFO: + _data_handler_interface->messageInfo(MessageInfo{message, false}); + break; + case ULogMessageType::INFO_MULTIPLE: + _data_handler_interface->messageInfo(MessageInfo{message, true}); + break; + case ULogMessageType::PARAMETER: + _data_handler_interface->parameter(Parameter{message}); + break; + case ULogMessageType::PARAMETER_DEFAULT: + _data_handler_interface->parameterDefault(ParameterDefault{message}); + break; + case ULogMessageType::ADD_LOGGED_MSG: + _data_handler_interface->addLoggedMessage(AddLoggedMessage{message}); + break; + case ULogMessageType::LOGGING: + _data_handler_interface->logging(Logging{message}); + break; + case ULogMessageType::LOGGING_TAGGED: + _data_handler_interface->logging(Logging{message, true}); + break; + case ULogMessageType::DATA: + _data_handler_interface->data(Data{message}); + break; + case ULogMessageType::DROPOUT: + _data_handler_interface->dropout(Dropout{message}); + break; + case ULogMessageType::SYNC: + _data_handler_interface->sync(Sync{message}); + break; + default: + DBG_PRINTF("%i: Unknown/unexpected message type in data: %i\n", _total_num_read, + header->msg_size); + break; + } +} + +} // namespace flight_log diff --git a/src/simple_writer.cpp b/src/simple_writer.cpp new file mode 100644 index 0000000..590b29d --- /dev/null +++ b/src/simple_writer.cpp @@ -0,0 +1,160 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include + +#ifdef _WIN32 +// clang-format off +#include +#include +// clang-format on +#else +#include +#endif + +namespace flight_log { + +const std::string SimpleWriter::kFormatNameRegexStr = "[a-zA-Z0-9_\\-/]+"; +const std::regex SimpleWriter::kFormatNameRegex = std::regex(std::string(kFormatNameRegexStr)); +const std::string SimpleWriter::kFieldNameRegexStr = "[a-z0-9_]+"; +const std::regex SimpleWriter::kFieldNameRegex = std::regex(std::string(kFieldNameRegexStr)); + +SimpleWriter::SimpleWriter(DataWriteCB data_write_cb, uint64_t timestamp_us) + : _writer(std::make_unique(std::move(data_write_cb))) +{ + _writer->fileHeader(FileHeader(timestamp_us)); +} + +SimpleWriter::SimpleWriter(const std::string& filename, uint64_t timestamp_us) +{ + _file = std::fopen(filename.c_str(), "wb"); + if (!_file) { + throw ParsingException("Failed to open file"); + } + + _writer = std::make_unique( + [this](const uint8_t* data, int length) { std::fwrite(data, 1, length, _file); }); + _writer->fileHeader(FileHeader(timestamp_us)); +} + +SimpleWriter::~SimpleWriter() +{ + _writer.reset(); + if (_file) { + std::fclose(_file); + } +} + +void SimpleWriter::writeMessageFormat(const std::string& name, const std::vector& fields) +{ + if (_header_complete) { + throw UsageException("Header already complete"); + } + // Ensure the first field is the 64 bit timestamp. This is a bit stricter than what ULog requires + if (fields.empty() || fields[0].name() != "timestamp" || + fields[0].type().type != Field::BasicType::UINT64 || fields[0].arrayLength() != -1) { + throw UsageException("First message field must be 'uint64_t timestamp'"); + } + if (_formats.find(name) != _formats.end()) { + throw UsageException("Duplicate format: " + name); + } + + // Validate naming pattern + if (!std::regex_match(name, kFormatNameRegex)) { + throw UsageException("Invalid name: " + name + ", valid regex: " + kFormatNameRegexStr); + } + for (const auto& field : fields) { + if (!std::regex_match(field.name(), kFieldNameRegex)) { + throw UsageException("Invalid field name: " + field.name() + + ", valid regex: " + kFieldNameRegexStr); + } + } + + // Check field types and verify padding + unsigned message_size = 0; + for (const auto& field : fields) { + const auto& basic_type_iter = Field::kBasicTypes.find(field.type().name); + if (basic_type_iter == Field::kBasicTypes.end()) { + throw UsageException("Invalid field type (nested formats are not supported): " + + field.type().name); + } + const int array_size = field.arrayLength() <= 0 ? 1 : field.arrayLength(); + if (message_size % basic_type_iter->second.size != 0) { + throw UsageException( + "struct requires padding, reorder fields by decreasing type size. Padding before " + "field: " + + field.name()); + } + message_size += array_size * basic_type_iter->second.size; + } + _formats[name] = Format{message_size}; + _writer->messageFormat(MessageFormat(name, fields)); +} + +void SimpleWriter::headerComplete() +{ + if (_header_complete) { + throw UsageException("Header already complete"); + } + _writer->headerComplete(); + _header_complete = true; +} + +void SimpleWriter::writeTextMessage(Logging::Level level, const std::string& message, + uint64_t timestamp) +{ + if (!_header_complete) { + throw UsageException("Header not yet complete"); + } + _writer->logging({level, message, timestamp}); +} + +void SimpleWriter::fsync() +{ + if (_file) { + fflush(_file); +#ifdef _WIN32 + FlushFileBuffers(reinterpret_cast(static_cast(_fileno(_file)))); +#else + ::fsync(fileno(_file)); +#endif + } +} +uint16_t SimpleWriter::writeAddLoggedMessage(const std::string& message_format_name, + uint8_t multi_id) +{ + if (!_header_complete) { + throw UsageException("Header not yet complete"); + } + const uint16_t msg_id = _subscriptions.size(); + auto format_iter = _formats.find(message_format_name); + if (format_iter == _formats.end()) { + throw UsageException("Format not found: " + message_format_name); + } + _subscriptions.push_back({format_iter->second.message_size}); + _writer->addLoggedMessage(AddLoggedMessage(multi_id, msg_id, message_format_name)); + return msg_id; +} + +void SimpleWriter::writeDataImpl(uint16_t id, const uint8_t* data, unsigned length) +{ + if (!_header_complete) { + throw UsageException("Header not yet complete"); + } + if (id >= _subscriptions.size()) { + throw UsageException("Invalid ID"); + } + const unsigned expected_size = _subscriptions[id].message_size; + // Sanity check data size. sizeof(data) can be bigger because of struct padding at the end + if (length < expected_size) { + throw UsageException("sizeof(data) is too small"); + } + std::vector data_vec; + data_vec.resize(expected_size); + memcpy(data_vec.data(), data, expected_size); + _writer->data(Data(id, std::move(data_vec))); +} + +} // namespace flight_log diff --git a/src/writer.cpp b/src/writer.cpp new file mode 100644 index 0000000..87226ed --- /dev/null +++ b/src/writer.cpp @@ -0,0 +1,71 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#include + +namespace flight_log { + +Writer::Writer(DataWriteCB data_write_cb) : _data_write_cb(std::move(data_write_cb)) +{ + // Writer assumes to run on little endian + // TODO: use std::endian from C++20 + int num = 1; + // cppcheck-suppress [knownConditionTrueFalse,unmatchedSuppression] + if (*reinterpret_cast(&num) != 1) { + throw UsageException("Writer requires little endian"); + } +} + +void Writer::headerComplete() +{ + _header_complete = true; +} +void Writer::fileHeader(const FileHeader& header) +{ + header.serialize(_data_write_cb); +} +void Writer::messageInfo(const MessageInfo& message_info) +{ + message_info.serialize(_data_write_cb); +} +void Writer::messageFormat(const MessageFormat& message_format) +{ + if (_header_complete) { + throw UsageException("Header completed, cannot write formats"); + } + message_format.serialize(_data_write_cb); +} +void Writer::parameter(const Parameter& parameter) +{ + parameter.serialize(_data_write_cb, ULogMessageType::PARAMETER); +} +void Writer::parameterDefault(const ParameterDefault& parameter_default) +{ + parameter_default.serialize(_data_write_cb); +} +void Writer::addLoggedMessage(const AddLoggedMessage& add_logged_message) +{ + if (!_header_complete) { + throw UsageException("Header not yet completed, cannot write AddLoggedMessage"); + } + add_logged_message.serialize(_data_write_cb); +} +void Writer::logging(const Logging& logging) +{ + logging.serialize(_data_write_cb); +} +void Writer::data(const Data& data) +{ + data.serialize(_data_write_cb); +} +void Writer::dropout(const Dropout& dropout) +{ + dropout.serialize(_data_write_cb); +} +void Writer::sync(const Sync& sync) +{ + sync.serialize(_data_write_cb); +} +} // namespace flight_log diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..1d021d0 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,27 @@ +set(cli_tests ${CMAKE_CURRENT_SOURCE_DIR}/check_cli.cmake) +set(empty_log ${CMAKE_CURRENT_BINARY_DIR}/empty.ulg) +file(WRITE ${empty_log} "") + +add_test(NAME cli-help COMMAND ${CMAKE_COMMAND} + -DCLI=$ -DARGUMENT=--help + -DEXPECTED_STATUS=0 "-DEXPECTED_OUTPUT=Usage: flight-log-inspector" + -P ${cli_tests} +) +add_test(NAME cli-summary COMMAND ${CMAKE_COMMAND} + -DCLI=$ + -DARGUMENT=${CMAKE_CURRENT_SOURCE_DIR}/log_files/sample_log_small.ulg + -DEXPECTED_STATUS=0 "-DEXPECTED_OUTPUT=sensor_combined (0) - 1298" + -P ${cli_tests} +) +add_test(NAME cli-empty-input COMMAND ${CMAKE_COMMAND} + -DCLI=$ -DARGUMENT=${empty_log} + -DEXPECTED_STATUS=1 "-DEXPECTED_ERROR=Not enough data to read file magic" + -P ${cli_tests} +) + +if(FLIGHT_LOG_ENABLE_UNIT_TESTS) + find_package(doctest CONFIG REQUIRED) + add_executable(flight_log_unit_tests main.cpp read_api_test.cpp ulog_parsing_test.cpp) + target_link_libraries(flight_log_unit_tests PRIVATE doctest::doctest flight_log::flight_log) + add_test(NAME unit-tests COMMAND flight_log_unit_tests) +endif() diff --git a/tests/check_cli.cmake b/tests/check_cli.cmake new file mode 100644 index 0000000..d862a6b --- /dev/null +++ b/tests/check_cli.cmake @@ -0,0 +1,21 @@ +execute_process(COMMAND "${CLI}" "${ARGUMENT}" + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error +) + +if(NOT status STREQUAL EXPECTED_STATUS) + message(FATAL_ERROR "Expected exit ${EXPECTED_STATUS}, got ${status}\n${error}") +endif() + +if(DEFINED EXPECTED_OUTPUT) + string(FIND "${output}" "${EXPECTED_OUTPUT}" output_index) + if(output_index EQUAL -1) + message(FATAL_ERROR "Output did not contain '${EXPECTED_OUTPUT}'") + endif() +endif() + +if(DEFINED EXPECTED_ERROR) + string(FIND "${error}" "${EXPECTED_ERROR}" error_index) + if(error_index EQUAL -1) + message(FATAL_ERROR "Error output did not contain '${EXPECTED_ERROR}'\n${error}") + endif() +endif() diff --git a/tests/log_files/sample.ulg b/tests/log_files/sample.ulg new file mode 100644 index 0000000..d9c71bb Binary files /dev/null and b/tests/log_files/sample.ulg differ diff --git a/tests/log_files/sample_log_small.ulg b/tests/log_files/sample_log_small.ulg new file mode 100644 index 0000000..d08ba65 Binary files /dev/null and b/tests/log_files/sample_log_small.ulg differ diff --git a/tests/log_files/sample_logging_tagged_and_default_params.ulg b/tests/log_files/sample_logging_tagged_and_default_params.ulg new file mode 100644 index 0000000..4d8f82d Binary files /dev/null and b/tests/log_files/sample_logging_tagged_and_default_params.ulg differ diff --git a/tests/main.cpp b/tests/main.cpp new file mode 100644 index 0000000..9647d2a --- /dev/null +++ b/tests/main.cpp @@ -0,0 +1,14 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ + +#define DOCTEST_CONFIG_IMPLEMENT +#include + +int main(int argc, char** argv) +{ + doctest::Context context; + context.applyCommandLine(argc, argv); + return context.run(); +} diff --git a/tests/read_api_test.cpp b/tests/read_api_test.cpp new file mode 100644 index 0000000..6613851 --- /dev/null +++ b/tests/read_api_test.cpp @@ -0,0 +1,300 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#include + +#include +#include +#include +#include +#include + +class TestWriter : public flight_log::Writer { + public: + explicit TestWriter(const flight_log::DataWriteCB& cb) : flight_log::Writer(cb) {} + + ~TestWriter() override = default; + + void error(const std::string& msg, bool is_recoverable) override { ++num_errors; } + + int num_errors{0}; + + private: +}; + +TEST_SUITE_BEGIN("[ULog Access]"); + +TEST_CASE("Write complicated, nested data format, then read it") +{ + std::vector written_data; + TestWriter writer([&](const uint8_t* data, int length) { + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + // Input data + const flight_log::FileHeader file_header{}; + const flight_log::MessageFormat root_type{"root_type", + {{"uint64_t", "timestamp"}, + {"int32_t", "integer"}, + {"char", "string", 17}, + {"double", "double"}, + {"child_1_type", "child_1"}}}; + + const flight_log::MessageFormat child_1_type{"child_1_type", + {{"uint32_t", "unsigned_int"}, + {"child_1_1_type", "child_1_1"}, + {"child_1_2_type", "child_1_2", 3}, + {"uint64_t", "unsigned_long", 4}}}; + + const flight_log::MessageFormat child_1_1_type{ + "child_1_1_type", + {{"char", "byte"}, {"char", "string", 19}, {"child_1_1_1_type", "child_1_1_1"}}}; + + const flight_log::MessageFormat child_1_1_1_type{"child_1_1_1_type", + { + {"int32_t", "integer"}, + }}; + + const flight_log::MessageFormat child_1_2_type{"child_1_2_type", + {{"uint8_t", "byte_a"}, {"uint8_t", "byte_b"}}}; + + /* + * t00 [0-8] timestamp + * t01 [8-12] integer + * t02 [12-29] string + * t03 [29-37] double + * t04 [37-41] child_1 / unsigned_int + * t05 [41-42] child_1 / child_1_1 / byte + * t06 [42-61] child_1 / child_1_1 / string + * t07 [61-65] child_1 / child_1_1 / child_1_1_1 / integer + * t08 [65-66] child_1 / child_1_2 / [0] / byte_a + * t09 [66-67] child_1 / child_1_2 / [0] / byte_b + * t10 [67-68] child_1 / child_1_2 / [1] / byte_a + * t11 [68-69] child_1 / child_1_2 / [1] / byte_b + * t12 [69-70] child_1 / child_1_2 / [2] / byte_a + * t13 [70-71] child_1 / child_1_2 / [2] / byte_b + * t14 [71-103] child_1 / unsigned_long[4] + */ + + std::vector data_vector; + data_vector.resize(103); + + const uint64_t t00 = 0xdeadbeefdeadbeef; + const int32_t t01 = -123456; + const char t02[] = "Hello World!----"; + const double t03 = 3.14159265358979323846; + const uint32_t t04 = 0xdeadbeef; + const char t05 = 'a'; + const char t06[] = "Hello World! 2----"; + const int32_t t07 = 123456; + const uint8_t t08 = 0x12; + const uint8_t t09 = 0x34; + const uint8_t t10 = 0x56; + const uint8_t t11 = 0x78; + const uint8_t t12 = 0x9a; + const uint8_t t13 = 0xbc; + const std::vector t14 = {0xfeedc0defeedc0d0, 0xfeedc0defeedc0d1, 0xfeedc0defeedc0d2, + 0xfeedc0defeedc0d3}; + + memcpy(data_vector.data() + 0, &t00, 8); + memcpy(data_vector.data() + 8, &t01, 4); + memcpy(data_vector.data() + 12, &t02, 17); + memcpy(data_vector.data() + 29, &t03, 8); + memcpy(data_vector.data() + 37, &t04, 4); + memcpy(data_vector.data() + 41, &t05, 1); + memcpy(data_vector.data() + 42, &t06, 19); + memcpy(data_vector.data() + 61, &t07, 4); + memcpy(data_vector.data() + 65, &t08, 1); + memcpy(data_vector.data() + 66, &t09, 1); + memcpy(data_vector.data() + 67, &t10, 1); + memcpy(data_vector.data() + 68, &t11, 1); + memcpy(data_vector.data() + 69, &t12, 1); + memcpy(data_vector.data() + 70, &t13, 1); + memcpy(data_vector.data() + 71, t14.data(), 8 * 4); + + const flight_log::MessageInfo info{{"root_type", "info"}, data_vector}; + + const flight_log::AddLoggedMessage add_logged_message_1{0, 1, "root_type"}; + const flight_log::AddLoggedMessage add_logged_message_2{1, 2, "root_type"}; + const flight_log::Data data_1{1, data_vector}; + const flight_log::Data data_2{2, data_vector}; + + // Write data + writer.fileHeader(file_header); + writer.messageInfo(info); + writer.messageFormat(child_1_1_1_type); + writer.messageFormat(root_type); + writer.messageFormat(child_1_type); + writer.messageFormat(child_1_1_type); + writer.messageFormat(child_1_2_type); + + writer.headerComplete(); + writer.messageInfo(info); + writer.addLoggedMessage(add_logged_message_1); + writer.addLoggedMessage(add_logged_message_2); + writer.data(data_1); + writer.data(data_1); + writer.data(data_2); + writer.data(data_2); + writer.data(data_2); + + REQUIRE_GT(written_data.size(), 0); + REQUIRE_EQ(writer.num_errors, 0); + + // Read it + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + reader.readChunk(written_data.data(), written_data.size()); + + // Check for errors + REQUIRE(data_container->parsingErrors().empty()); + REQUIRE_FALSE(data_container->hadFatalError()); + + auto subscription_names = data_container->subscriptionNames(); + CHECK_EQ(subscription_names.size(), 1); + CHECK_EQ(*(subscription_names.begin()), "root_type"); + + auto subscription_1 = data_container->subscription("root_type"); + auto subscription_2 = data_container->subscription("root_type", 1); + + CHECK_EQ(subscription_1->size(), 2); + CHECK_EQ(subscription_2->size(), 3); + + // check access with string selectors + for (const auto& sample : *subscription_1) { + CHECK_EQ(sample["timestamp"].as(), t00); + CHECK_EQ(sample["integer"].as(), t01); + CHECK_EQ(sample["string"].as(), t02); + CHECK_EQ(sample["double"].as(), t03); + CHECK_EQ(sample["child_1"]["unsigned_int"].as(), t04); + CHECK_EQ(sample["child_1"]["child_1_1"]["byte"].as(), t05); + CHECK_EQ(sample["child_1"]["child_1_1"]["string"].as(), t06); + CHECK_EQ(sample["child_1"]["child_1_1"]["child_1_1_1"]["integer"].as(), t07); + CHECK_EQ(sample["child_1"]["child_1_2"][0]["byte_a"].as(), t08); + CHECK_EQ(sample["child_1"]["child_1_2"][0]["byte_b"].as(), t09); + CHECK_EQ(sample["child_1"]["child_1_2"][1]["byte_a"].as(), t10); + CHECK_EQ(sample["child_1"]["child_1_2"][1]["byte_b"].as(), t11); + CHECK_EQ(sample["child_1"]["child_1_2"][2]["byte_a"].as(), t12); + CHECK_EQ(sample["child_1"]["child_1_2"][2]["byte_b"].as(), t13); + CHECK_EQ(sample["child_1"]["unsigned_long"].as>(), t14); + } + + // check access with field selectors + auto f_timestamp = subscription_1->field("timestamp"); + auto f_integer = subscription_1->field("integer"); + auto f_string = subscription_1->field("string"); + auto f_double = subscription_1->field("double"); + auto f_child_1 = subscription_1->field("child_1"); + auto f_c1_unsinged_int = f_child_1->nestedField("unsigned_int"); + auto f_c1_c1_1 = f_child_1->nestedField("child_1_1"); + auto f_c1_c1_1_byte = f_c1_c1_1->nestedField("byte"); + auto f_c1_c1_1_string = f_c1_c1_1->nestedField("string"); + auto f_c1_c1_1_c1_1_1 = f_c1_c1_1->nestedField("child_1_1_1"); + auto f_c1_c1_1_c1_1_1_integer = f_c1_c1_1_c1_1_1->nestedField("integer"); + auto f_c1_c1_2 = f_child_1->nestedField("child_1_2"); + auto f_c1_c1_2_byte_a = f_c1_c1_2->nestedField("byte_a"); + auto f_c1_c1_2_byte_b = f_c1_c1_2->nestedField("byte_b"); + auto f_c1_unsigned_long = f_child_1->nestedField("unsigned_long"); + + for (const auto& sample : *subscription_2) { + CHECK_EQ(sample[f_timestamp].as(), t00); + CHECK_EQ(sample[f_integer].as(), t01); + CHECK_EQ(sample[f_string].as(), t02); + CHECK_EQ(sample[f_double].as(), t03); + CHECK_EQ(sample[f_child_1][f_c1_unsinged_int].as(), t04); + CHECK_EQ(sample[f_child_1][f_c1_c1_1][f_c1_c1_1_byte].as(), t05); + CHECK_EQ(sample[f_child_1][f_c1_c1_1][f_c1_c1_1_string].as(), t06); + CHECK_EQ(sample[f_child_1][f_c1_c1_1][f_c1_c1_1_c1_1_1][f_c1_c1_1_c1_1_1_integer].as(), + t07); + CHECK_EQ(sample[f_child_1][f_c1_c1_2][0][f_c1_c1_2_byte_a].as(), t08); + CHECK_EQ(sample[f_child_1][f_c1_c1_2][0][f_c1_c1_2_byte_b].as(), t09); + CHECK_EQ(sample[f_child_1][f_c1_c1_2][1][f_c1_c1_2_byte_a].as(), t10); + CHECK_EQ(sample[f_child_1][f_c1_c1_2][1][f_c1_c1_2_byte_b].as(), t11); + CHECK_EQ(sample[f_child_1][f_c1_c1_2][2][f_c1_c1_2_byte_a].as(), t12); + CHECK_EQ(sample[f_child_1][f_c1_c1_2][2][f_c1_c1_2_byte_b].as(), t13); + CHECK_EQ(sample[f_child_1][f_c1_unsigned_long].as>(), t14); + } + + // check type conversions + auto sample = *subscription_2->begin(); + CHECK_EQ(sample[f_timestamp].as(), static_cast(t00)); + CHECK_EQ(sample[f_timestamp].as(), static_cast(t00)); + CHECK_EQ(sample[f_timestamp].as(), static_cast(t00)); + CHECK_EQ(sample[f_timestamp].as>(), std::vector{t00}); + CHECK_EQ(sample[f_timestamp].as>(), std::vector{static_cast(t00)}); + + CHECK_EQ(sample[f_child_1][f_c1_unsigned_long].as(), t14[0]); + CHECK_EQ(sample[f_child_1][f_c1_unsigned_long][1].as(), static_cast(t14[1])); + CHECK_EQ(sample[f_child_1][f_c1_unsigned_long][1].as>(), + std::vector{static_cast(t14[1])}); + + CHECK(std::holds_alternative(sample[f_timestamp].asNativeTypeVariant())); + CHECK(std::holds_alternative(sample[f_integer].asNativeTypeVariant())); + CHECK(std::holds_alternative(sample[f_string].asNativeTypeVariant())); + CHECK(std::holds_alternative(sample[f_double].asNativeTypeVariant())); + CHECK( + std::holds_alternative(sample[f_child_1][f_c1_unsinged_int].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_1][f_c1_c1_1_byte].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_1][f_c1_c1_1_string].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_1][f_c1_c1_1_c1_1_1][f_c1_c1_1_c1_1_1_integer] + .asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_2][0][f_c1_c1_2_byte_a].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_2][0][f_c1_c1_2_byte_b].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_2][1][f_c1_c1_2_byte_a].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_2][1][f_c1_c1_2_byte_b].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_2][2][f_c1_c1_2_byte_a].asNativeTypeVariant())); + CHECK(std::holds_alternative( + sample[f_child_1][f_c1_c1_2][2][f_c1_c1_2_byte_b].asNativeTypeVariant())); + CHECK(std::holds_alternative>( + sample[f_child_1][f_c1_unsigned_long].asNativeTypeVariant())); + + // Check exceptions + CHECK_THROWS_AS(sample["non_existent"], flight_log::AccessException); + CHECK_THROWS_AS(sample[f_child_1][f_c1_unsigned_long][100], flight_log::AccessException); + CHECK_THROWS_AS(data_container->subscription("non_existent_subscription"), + flight_log::AccessException); +} + +TEST_CASE("Read string values that fill the whole field or are empty") +{ + std::vector written_data; + TestWriter writer([&](const uint8_t* data, int length) { + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + // ULog strings carry no terminating zero and may be empty (char[0]). + writer.fileHeader(flight_log::FileHeader{}); + writer.messageInfo(flight_log::MessageInfo{"empty", ""}); + writer.messageInfo(flight_log::MessageInfo{"full", "hello"}); + writer.headerComplete(); + CHECK_EQ(writer.num_errors, 0); + + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + reader.readChunk(written_data.data(), written_data.size()); + CHECK(data_container->parsingErrors().empty()); + CHECK_FALSE(data_container->hadFatalError()); + + const auto& info = data_container->messageInfo(); + CHECK_EQ(info.at("empty").field().arrayLength(), 0); + CHECK_EQ(info.at("empty").value().as(), ""); + CHECK_EQ(info.at("full").field().arrayLength(), 5); + CHECK_EQ(info.at("full").value().as(), "hello"); +} + +TEST_SUITE_END(); diff --git a/tests/ulog_parsing_test.cpp b/tests/ulog_parsing_test.cpp new file mode 100644 index 0000000..f841aa5 --- /dev/null +++ b/tests/ulog_parsing_test.cpp @@ -0,0 +1,598 @@ +/**************************************************************************** + * See NOTICE for the copyright declaration for this file. + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#include + +#include +#include +#include +#include +#include +#include + +class TestWriter : public flight_log::Writer { + public: + explicit TestWriter(const flight_log::DataWriteCB& cb) : flight_log::Writer(cb) {} + + ~TestWriter() override = default; + + void error(const std::string& msg, bool is_recoverable) override { ++num_errors; } + + int num_errors{0}; + + private: +}; + +TEST_SUITE_BEGIN("[ULog Parsing]"); + +TEST_CASE("ULog parsing - basic test: write then read") +{ + std::vector written_data; + TestWriter writer([&](const uint8_t* data, int length) { + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + // Input data + const flight_log::FileHeader file_header{}; + const flight_log::MessageFormat format1{"message_name", + {{"uint64_t", "timestamp"}, {"float", "float_value"}}}; + const flight_log::MessageFormat format2{ + "other_message", {{"uint64_t", "timestamp"}, {"uint32_t", "array", 3}, {"uint16_t", "x"}}}; + std::vector data_vector; + data_vector.resize(22); + data_vector[0] = 32; + data_vector[20] = 49; + const flight_log::MessageInfo info{"info", "test_value"}; + const flight_log::Logging logging{flight_log::Logging::Level::Warning, "logging message", 3'834'732}; + const uint16_t msg_id = 1; + const flight_log::AddLoggedMessage add_logged_message{0, msg_id, "other_message"}; + const flight_log::Data data{msg_id, data_vector}; + + // Write data + writer.fileHeader(file_header); + writer.messageInfo(info); + writer.messageFormat(format1); + writer.messageFormat(format2); + writer.headerComplete(); + writer.logging(logging); + writer.addLoggedMessage(add_logged_message); + writer.data(data); + writer.data(data); + + REQUIRE_GT(written_data.size(), 0); + REQUIRE_EQ(writer.num_errors, 0); + + // // Test: write to disk + // FILE* file = fopen("test.ulg", "wb"); + // fwrite(written_data.data(), 1, written_data.size(), file); + // fclose(file); + + // Read it + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + reader.readChunk(written_data.data(), written_data.size()); + + // Check for errors + REQUIRE(data_container->parsingErrors().empty()); + REQUIRE_FALSE(data_container->hadFatalError()); + + // Check RAW API + CHECK_EQ(file_header, data_container->fileHeader()); + CHECK_EQ(format1, *(data_container->messageFormats().at("message_name"))); + CHECK_EQ(format2, *(data_container->messageFormats().at("other_message"))); + CHECK_EQ(info, data_container->messageInfo().at("info")); + REQUIRE_EQ(data_container->logging().size(), 1); + CHECK_EQ(logging, data_container->logging()[0]); + CHECK_EQ(data_container->subscriptionsByMessageId().at(msg_id)->rawSamples().size(), 2); + CHECK_EQ(data, data_container->subscriptionsByMessageId().at(msg_id)->rawSamples()[0]); + CHECK_EQ(data, data_container->subscriptionsByMessageId().at(msg_id)->rawSamples()[1]); + + // Check convenience API + CHECK_EQ(format2, *(data_container->subscription("other_message")->format())); + CHECK_EQ(data_container->subscription("other_message")->size(), 2); + + auto timestamp_field = data_container->subscription("other_message")->field("timestamp"); + auto x_field = data_container->subscription("other_message")->field("x"); + + for (const auto& sample : *(data_container->subscription("other_message"))) { + // field access + CHECK_EQ(sample[timestamp_field].as(), 32); + CHECK_EQ(sample[x_field].as(), 49); + // direct string access + CHECK_EQ(sample["timestamp"].as(), 32); + CHECK_EQ(sample["x"].as(), 49); + } +} + +namespace { +void readFileWriteTest(const std::filesystem::path& path, + const std::function& next_chunk_size) +{ + FILE* file = fopen(path.c_str(), "rb"); + CHECK(file); + + std::vector written_data; + auto writer = std::make_shared([&](const uint8_t* data, int length) { + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + std::vector input_data; + uint8_t buffer[4096]; + int bytes_read; + flight_log::Reader reader{writer}; + while ((bytes_read = + fread(buffer, 1, std::min(next_chunk_size(), sizeof(buffer)), file)) > 0) { + input_data.resize(input_data.size() + bytes_read); + memcpy(input_data.data() + input_data.size() - bytes_read, buffer, bytes_read); + reader.readChunk(buffer, bytes_read); + } + fclose(file); + + // // Test: write to disk + // FILE* file_test = fopen(path.filename().c_str(), "wb"); + // fwrite(written_data.data(), 1, written_data.size(), file_test); + // fclose(file_test); + + REQUIRE_GT(written_data.size(), 0); + REQUIRE_GT(input_data.size(), 0); + REQUIRE_EQ(writer->num_errors, 0); + CHECK_EQ(input_data.size(), written_data.size()); + CHECK_EQ(input_data, written_data); +} +} // namespace + +TEST_CASE("ULog parsing - read sample files then write") +{ + // Iterate over test log files + const std::string src_file_path = __FILE__; + const std::string test_file_dir = + src_file_path.substr(0, src_file_path.rfind('/')) + "/log_files"; + printf("Log files dir: %s\n", test_file_dir.c_str()); + + bool found_logs = false; + bool test_min_chunk_size = true; + for (const auto& dir_entry : std::filesystem::directory_iterator(test_file_dir)) { + if (dir_entry.is_directory() || dir_entry.path().extension() != ".ulg") { + continue; + } + found_logs = true; + printf("Testing file %s\n", dir_entry.path().filename().string().c_str()); + + // Iterate over chunk sizes + const int first_chunk_size = 100; // always include magic+flags messages in the first chunk + const int chunk_sizes[] = {1, 5, 1024, 4048}; + for (const auto& chunk_size : chunk_sizes) { + if (!test_min_chunk_size && chunk_size <= 3) { + continue; + } + printf("Read chunk size: %i\n", chunk_size); + bool first = true; + readFileWriteTest(dir_entry, [&]() { + if (first) { + first = false; + return first_chunk_size; + } + return chunk_size; + }); + } + test_min_chunk_size = false; // only test small chunk size for first log, as it's slow + } + + REQUIRE(found_logs); +} + +TEST_CASE("ULog parsing - test corruption") +{ + // Corrupt the stream by inserting zero bytes + int insert_zero_bytes = 0; + std::vector written_data; + TestWriter writer([&](const uint8_t* data, int length) { + if (insert_zero_bytes > 0) { + printf("inserting zero bytes, num written: %zu\n", written_data.size()); + written_data.resize(written_data.size() + insert_zero_bytes); + insert_zero_bytes = 0; + } + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + // Input data + const flight_log::FileHeader file_header{}; + const flight_log::MessageFormat format2{ + "other_message", {{"uint64_t", "timestamp"}, {"uint32_t", "array", 3}, {"uint16_t", "x"}}}; + std::vector data_vector; + data_vector.resize(22); + data_vector[0] = 32; + data_vector[20] = 49; + const flight_log::Logging logging{flight_log::Logging::Level::Warning, "logging message", 3'834'732}; + const uint16_t msg_id = 1; + const flight_log::AddLoggedMessage add_logged_message{0, msg_id, "other_message"}; + const flight_log::Data data{msg_id, data_vector}; + + // Write data + writer.fileHeader(file_header); + writer.messageFormat(format2); + writer.headerComplete(); + insert_zero_bytes = 423; + writer.logging(logging); + writer.addLoggedMessage(add_logged_message); + writer.data(data); + writer.data(data); + + REQUIRE_GT(written_data.size(), 0); + REQUIRE_EQ(writer.num_errors, 0); + + // Read it + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + // Read in multiple chunks, as the parser needs more readChunk calls to recover. + // We could change the parser to handle it, but in practice this should not be an issue. + const int last_chunk_size = 30; + reader.readChunk(written_data.data(), written_data.size() - last_chunk_size); + reader.readChunk(written_data.data() + written_data.size() - last_chunk_size, last_chunk_size); + + // Expected to have errors + CHECK_GT(data_container->parsingErrors().size(), 0); + REQUIRE_FALSE(data_container->hadFatalError()); + + // Compare + CHECK_EQ(file_header, data_container->fileHeader()); + CHECK_EQ(format2, *(data_container->messageFormats().at("other_message"))); + // Here we inserted zero bytes, but the next messages should not be dropped + REQUIRE_EQ(data_container->logging().size(), 1); + CHECK_EQ(logging, data_container->logging()[0]); + CHECK_EQ(data_container->subscriptionsByMessageId().at(msg_id)->rawSamples().size(), 2); + CHECK_EQ(data, data_container->subscriptionsByMessageId().at(msg_id)->rawSamples()[0]); + CHECK_EQ(data, data_container->subscriptionsByMessageId().at(msg_id)->rawSamples()[1]); + + auto timestamp_field = data_container->subscription("other_message")->field("timestamp"); + auto x_field = data_container->subscription("other_message")->field("x"); + + for (const auto& sample : *(data_container->subscription("other_message"))) { + // field access + CHECK_EQ(sample[timestamp_field].as(), 32); + CHECK_EQ(sample[x_field].as(), 49); + // direct string access + CHECK_EQ(sample["timestamp"].as(), 32); + CHECK_EQ(sample["x"].as(), 49); + } +} + +TEST_CASE("ULog parsing - corruption recovery rejects wrong-size data for a known msg_id") +{ + // Same technique as the "test corruption" case above, but instead of only inserting zero + // bytes, follow them with a fabricated Data message header: known msg_type, plausible + // msg_size, and even the SAME msg_id as a real subscription - but with a payload size that + // doesn't match that subscription's format. Before the isValidDataMessage() fix, + // tryToRecover() would accept this as a valid resync point purely because it looks + // superficially plausible, and it would end up stored as a corrupted sample. The fix must + // reject it and instead recover at the next genuine message. + std::vector injected_bytes; + std::vector written_data; + TestWriter writer([&](const uint8_t* data, int length) { + if (!injected_bytes.empty()) { + written_data.insert(written_data.end(), injected_bytes.begin(), injected_bytes.end()); + injected_bytes.clear(); + } + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + // A tiny, unpadded format (8 + 4 = 12 bytes), so its on-wire size is unambiguous. + const flight_log::MessageFormat format{"target_message", + {{"uint64_t", "timestamp"}, {"float", "value"}}}; + const uint16_t msg_id = 1; + const flight_log::AddLoggedMessage add_logged_message{0, msg_id, "target_message"}; + + auto make_data = [&](uint64_t timestamp, float value) { + std::vector bytes(12); + memcpy(bytes.data(), ×tamp, sizeof(timestamp)); + memcpy(bytes.data() + sizeof(timestamp), &value, sizeof(value)); + return flight_log::Data{msg_id, bytes}; + }; + const auto data1 = make_data(100, 1.5F); + const auto data2 = make_data(200, 2.5F); + + writer.fileHeader(flight_log::FileHeader{}); + writer.messageFormat(format); + writer.headerComplete(); + writer.addLoggedMessage(add_logged_message); + writer.data(data1); + + // Zero run to trigger corruptionDetected(), followed by the fabricated candidate. + injected_bytes.resize(50, 0); + const uint16_t fake_payload_size = 20; // target_message's real payload size is 12 + const uint16_t fake_msg_size = fake_payload_size + 2; // + 2-byte msg_id + auto append_u16 = [&](uint16_t v) { + injected_bytes.push_back(static_cast(v & 0xFF)); + injected_bytes.push_back(static_cast((v >> 8) & 0xFF)); + }; + append_u16(fake_msg_size); + injected_bytes.push_back('D'); // ULogMessageType::DATA + append_u16(msg_id); // the SAME msg_id as the real subscription above + // Fill the (wrong-size) payload with a byte value that can't be mistaken for any known + // msg_type character at any scan offset, so the search deterministically skips through it. + injected_bytes.resize(injected_bytes.size() + fake_payload_size, 0xAA); + + writer.data(data2); // flushes injected_bytes first, then the genuine next message + + REQUIRE_GT(written_data.size(), 0); + REQUIRE_EQ(writer.num_errors, 0); + + // Read it + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + // As in the "test corruption" case above: if recovery completes with no remaining + // external bytes to process (length == 0 at the point tryToRecover's recursive + // readChunk() call runs), the just-recovered message stays buffered but unprocessed + // until a later readChunk() call with length > 0 flushes it - readChunk()'s main loop + // only runs while length > 0. So a second, small trailing call is needed here too. + const int last_chunk_size = 5; + reader.readChunk(written_data.data(), written_data.size() - last_chunk_size); + reader.readChunk(written_data.data() + written_data.size() - last_chunk_size, last_chunk_size); + + // Expected to have errors, but not be fatal + CHECK_GT(data_container->parsingErrors().size(), 0); + REQUIRE_FALSE(data_container->hadFatalError()); + + // The fabricated wrong-size candidate must NOT have been accepted as a third sample. + const auto& samples = data_container->subscriptionsByMessageId().at(msg_id)->rawSamples(); + REQUIRE_EQ(samples.size(), 2); + CHECK_EQ(data1, samples[0]); + CHECK_EQ(data2, samples[1]); +} + +namespace { +// Streaming consumer in Header storage mode (like a converter that writes each sample out +// immediately). Records only the samples the base class accepted: if DataContainer::data() +// throws, the exception propagates to the Reader, as it would in a real consumer. +class HeaderModeCollector : public flight_log::DataContainer { + public: + HeaderModeCollector() : flight_log::DataContainer(flight_log::DataContainer::StorageConfig::Header) {} + void data(const flight_log::Data& data) override + { + flight_log::DataContainer::data(data); + accepted.push_back(data); + } + std::vector accepted; +}; + +// Writes a file with one 12-byte "target_message" subscription: data1, then whatever +// 'injected' holds (raw bytes), then data2. +std::vector writeFileWithInjectedBytes(const std::vector& injected, + flight_log::Data& data1, flight_log::Data& data2) +{ + std::vector injected_bytes; + std::vector written_data; + TestWriter writer([&](const uint8_t* data, int length) { + if (!injected_bytes.empty()) { + written_data.insert(written_data.end(), injected_bytes.begin(), injected_bytes.end()); + injected_bytes.clear(); + } + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }); + + const flight_log::MessageFormat format{"target_message", + {{"uint64_t", "timestamp"}, {"float", "value"}}}; + const uint16_t msg_id = 1; + auto make_data = [&](uint64_t timestamp, float value) { + std::vector bytes(12); + memcpy(bytes.data(), ×tamp, sizeof(timestamp)); + memcpy(bytes.data() + sizeof(timestamp), &value, sizeof(value)); + return flight_log::Data{msg_id, bytes}; + }; + data1 = make_data(100, 1.5F); + data2 = make_data(200, 2.5F); + + writer.fileHeader(flight_log::FileHeader{}); + writer.messageFormat(format); + writer.headerComplete(); + writer.addLoggedMessage(flight_log::AddLoggedMessage{0, msg_id, "target_message"}); + writer.data(data1); + injected_bytes = injected; + writer.data(data2); // flushes injected_bytes first + REQUIRE_EQ(writer.num_errors, 0); + return written_data; +} + +// A Data message header for msg_id 1 with a payload of 'payload_size' bytes of 0xAA. +std::vector fabricatedDataMessage(uint16_t payload_size) +{ + std::vector bytes; + const uint16_t msg_size = payload_size + 2; // + 2-byte msg_id + bytes.push_back(static_cast(msg_size & 0xFF)); + bytes.push_back(static_cast(msg_size >> 8)); + bytes.push_back('D'); + bytes.push_back(1); + bytes.push_back(0); + bytes.resize(bytes.size() + payload_size, 0xAA); + return bytes; +} + +void readInTwoChunks(flight_log::Reader& reader, std::vector& written_data) +{ + // See the corruption tests above for why a small trailing chunk is needed after recovery. + const int last_chunk_size = 5; + reader.readChunk(written_data.data(), written_data.size() - last_chunk_size); + reader.readChunk(written_data.data() + written_data.size() - last_chunk_size, last_chunk_size); +} +} // namespace + +TEST_CASE("ULog parsing - Header storage mode recovers on the next genuine data message") +{ + // Zero run between two valid samples. Header mode doesn't create subscriptions, so before + // the fix isValidDataMessage() rejected every DATA candidate and recovery skipped past all + // following data messages (data2 was lost). + flight_log::Data data1{0, {}}; + flight_log::Data data2{0, {}}; + auto written_data = writeFileWithInjectedBytes(std::vector(50, 0), data1, data2); + + const auto collector = std::make_shared(); + flight_log::Reader reader{collector}; + readInTwoChunks(reader, written_data); + + CHECK_GT(collector->parsingErrors().size(), 0); + REQUIRE_FALSE(collector->hadFatalError()); + REQUIRE_EQ(collector->accepted.size(), 2); + CHECK_EQ(data1, collector->accepted[0]); + CHECK_EQ(data2, collector->accepted[1]); +} + +TEST_CASE("ULog parsing - Header storage mode rejects wrong-size data for a known msg_id") +{ + // A well-framed Data message for the known msg_id, but with a 20-byte payload where the + // format needs 12. No zero run, so this is parsed in the normal path (not recovery). Before + // the fix, Header mode skipped the size check and the consumer received it. + flight_log::Data data1{0, {}}; + flight_log::Data data2{0, {}}; + auto written_data = writeFileWithInjectedBytes(fabricatedDataMessage(20), data1, data2); + + const auto collector = std::make_shared(); + flight_log::Reader reader{collector}; + readInTwoChunks(reader, written_data); + + CHECK_GT(collector->parsingErrors().size(), 0); + REQUIRE_FALSE(collector->hadFatalError()); + REQUIRE_EQ(collector->accepted.size(), 2); + CHECK_EQ(data1, collector->accepted[0]); + CHECK_EQ(data2, collector->accepted[1]); +} + +struct MyData { + uint64_t timestamp; + float debug_array[4]; + float cpuload; + float temperature; + int8_t counter; + + bool operator==(const MyData& other) const + { + for (unsigned i = 0; i < sizeof(debug_array) / sizeof(debug_array[0]); ++i) { + if (debug_array[i] != other.debug_array[i]) { + return false; + } + } + return timestamp == other.timestamp && cpuload == other.cpuload && + temperature == other.temperature && counter == other.counter; + } + + static std::string messageName() { return "my_data"; } + + static std::vector fields() + { + // clang-format off + return { + {"uint64_t", "timestamp"}, + {"float", "debug_array", 4}, + {"float", "cpuload"}, + {"float", "temperature"}, + {"int8_t", "counter"}, + }; // clang-format on + } +}; + +TEST_CASE("ULog parsing - simple writer") +{ + std::vector written_data; + flight_log::SimpleWriter writer( + [&](const uint8_t* data, int length) { + const int prev_size = written_data.size(); + written_data.resize(written_data.size() + length); + memcpy(written_data.data() + prev_size, data, length); + }, + 0); + + const std::string sys_name = "ULogExampleWriter"; + writer.writeInfo("sys_name", sys_name); + + const float param_a = 382.23F; + const int32_t param_b = 8272; + writer.writeParameter("PARAM_A", param_a); + writer.writeParameter("PARAM_B", param_b); + + CHECK_THROWS(writer.writeMessageFormat("invalid_require_padding", { + {"uint64_t", "timestamp"}, + {"int8_t", "a"}, + {"float", "b"}, + })); + + CHECK_THROWS( + writer.writeMessageFormat("invalid_type", {{"uint64_t", "timestamp"}, {"my_type", "a"}})); + + CHECK_THROWS(writer.writeMessageFormat("invalid_no_timestamp", {{"int8_t", "a"}})); + + CHECK_THROWS(writer.writeMessageFormat("invalid_field_name", + {{"uint64_t", "timestamp"}, {"int8_t", "a/b"}})); + + writer.writeMessageFormat(MyData::messageName(), MyData::fields()); + writer.headerComplete(); + + const uint16_t my_data_msg_id = writer.writeAddLoggedMessage(MyData::messageName()); + + const std::string text_message = "Hello world"; + writer.writeTextMessage(flight_log::Logging::Level::Info, text_message, 0); + + // Write some messages + float cpuload = 25.423F; + std::vector written_data_messages; + for (int i = 0; i < 100; ++i) { + MyData data{}; + data.timestamp = static_cast(i) * 1000; + data.cpuload = cpuload; + data.counter = i; + writer.writeData(my_data_msg_id, data); + written_data_messages.push_back(data); + cpuload -= 0.424F; + } + + // Parse data + const auto data_container = + std::make_shared(flight_log::DataContainer::StorageConfig::FullLog); + flight_log::Reader reader{data_container}; + reader.readChunk(written_data.data(), written_data.size()); + + // Check for errors + REQUIRE(data_container->parsingErrors().empty()); + REQUIRE_FALSE(data_container->hadFatalError()); + + // Compare + CHECK_EQ(sys_name, data_container->messageInfo().at("sys_name").value().as()); + REQUIRE_EQ(data_container->logging().size(), 1); + CHECK_EQ(text_message, data_container->logging()[0].message()); + CHECK_EQ(param_a, data_container->initialParameters().at("PARAM_A").value().as()); + CHECK_EQ(param_b, (data_container->initialParameters().at("PARAM_B").value().as())); + + CHECK_EQ(MyData::messageName(), + data_container->messageFormats().at(MyData::messageName())->name()); + REQUIRE_EQ(data_container->subscriptionNames().size(), 1); + + const auto subscription = data_container->subscription(MyData::messageName()); + REQUIRE_EQ(subscription->size(), written_data_messages.size()); + for (size_t i = 0; i < subscription->size(); ++i) { + const auto& sample = (*subscription)[i]; + const auto& gt = written_data_messages[i]; + MyData memcopied_sample{}; + REQUIRE_GE(sizeof(MyData), sample.rawData().size()); + // check raw byte equality + memcpy(&memcopied_sample, sample.rawData().data(), sample.rawData().size()); + CHECK_EQ(gt, memcopied_sample); + // check API access field equality + CHECK_EQ(gt.timestamp, sample["timestamp"].as()); + CHECK_EQ(gt.cpuload, sample["cpuload"].as()); + CHECK_EQ(gt.counter, sample["counter"].as()); + } +} + +TEST_SUITE_END();