Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ 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.

## Export topic samples

```sh
./install/bin/flight-log-inspector export-topic tests/log_files/sample_log_small.ulg sensor_combined \
--start-us 20488019 --end-us 20492907 > sensor_combined.csv
```

The command writes CSV to standard output in recorded sample order. The bounds are inclusive
and use raw log timestamps in microseconds. Omit either bound to leave that end open. Use
`--instance N` to select a topic instance. Instance 0 is the default. The CSV header lists
fields in schema order, with indexed columns for arrays, dotted names for nested fields, and
one text column for each character array. Padding fields are omitted. A window without samples
still writes the header.

## Contributing and license

See [CONTRIBUTING.md](CONTRIBUTING.md). The project is distributed under the BSD 3-Clause
Expand Down
200 changes: 195 additions & 5 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,45 @@
****************************************************************************/

#include <array>
#include <charconv>
#include <cinttypes>
#include <cstdio>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <numeric>
#include <string>
#include <string_view>
#include <type_traits>
#include <variant>
#include <vector>

#include <flight_log/data_container.hpp>
#include <flight_log/reader.hpp>

namespace {

int inspectLog(const char* path)
using StorageConfig = flight_log::DataContainer::StorageConfig;

std::shared_ptr<flight_log::DataContainer> readLog(const char* path, StorageConfig storage)
{
std::ifstream file(path, std::ios::binary);
if (!file) {
std::fprintf(stderr, "Cannot open log '%s'\n", path);
return 1;
return nullptr;
}
std::array<uint8_t, 4096> buffer{};
const auto storage = flight_log::DataContainer::StorageConfig::FullLog;
const auto data_container = std::make_shared<flight_log::DataContainer>(storage);
flight_log::Reader reader{data_container};
do {
file.read(reinterpret_cast<char*>(buffer.data()), buffer.size());
if (file.bad() || (file.fail() && !file.eof())) {
std::fprintf(stderr, "Cannot read log '%s'\n", path);
return 1;
return nullptr;
}
reader.readChunk(buffer.data(), static_cast<int>(file.gcount()));
} while (file && !data_container->hadFatalError());
Expand All @@ -44,6 +51,15 @@ int inspectLog(const char* path)
std::fprintf(stderr, "%s: %s\n", path, parsing_error.c_str());
}
if (data_container->hadFatalError()) {
return nullptr;
}
return data_container;
}

int inspectLog(const char* path)
{
const auto data_container = readLog(path, StorageConfig::FullLog);
if (!data_container) {
return 1;
}

Expand Down Expand Up @@ -126,15 +142,189 @@ int inspectLog(const char* path)
return 0;
}

using FieldReader = std::function<flight_log::Value(const flight_log::TypedDataView&)>;

struct CsvColumn {
std::string name;
FieldReader read;
};

void addCsvColumns(const flight_log::MessageFormat& format, const std::string& prefix,
const FieldReader& parent, std::vector<CsvColumn>& columns)
{
using FieldType = flight_log::Field::BasicType;
for (const auto& field : format.fields()) {
if (field->name().rfind("_padding", 0) == 0) {
continue;
}
const auto type = field->type().type;
const bool expand_array = field->arrayLength() >= 0 && type != FieldType::CHAR;
const int count = expand_array ? field->arrayLength() : 1;
for (int i = 0; i < count; ++i) {
auto name = prefix + field->name();
if (expand_array) {
name += '[' + std::to_string(i) + ']';
}
const auto read = [parent, field, expand_array, i](const flight_log::TypedDataView& sample) {
const auto value = parent ? parent(sample)[field] : sample[field];
return expand_array ? value[static_cast<std::size_t>(i)] : value;
};
if (type == FieldType::NESTED) {
addCsvColumns(*field->nestedFormat(), name + '.', read, columns);
} else {
columns.push_back({std::move(name), read});
}
}
}
}

void writeCsvText(std::ostream& output, std::string_view text)
{
if (text.find_first_of(",\"\r\n") == std::string_view::npos) {
output << text;
return;
}
output << '"';
for (const char character : text) {
if (character == '"') {
output << '"';
}
output << character;
}
output << '"';
}

void writeCsvValue(std::ostream& output, const flight_log::Value& value)
{
std::visit(
[&output](const auto& native) {
using T = std::decay_t<decltype(native)>;
if constexpr (std::is_floating_point_v<T>) {
output << std::setprecision(std::numeric_limits<T>::max_digits10) << native;
} else if constexpr (std::is_integral_v<T>) {
output << flight_log::staticCastEnsureUnsignedChar<decltype(+native)>(native);
} else if constexpr (std::is_same_v<T, std::string>) {
writeCsvText(output, native);
} else {
throw flight_log::AccessException("Expected a scalar CSV column");
}
},
value.asNativeTypeVariant());
}

struct ExportOptions {
int instance = 0;
uint64_t start_us = 0;
uint64_t end_us = std::numeric_limits<uint64_t>::max();
};

bool parseExportOptions(int argc, char** argv, ExportOptions& options)
{
for (int i = 4; i < argc; i += 2) {
const std::string_view option = argv[i];
const std::string_view text = argv[i + 1];
uint64_t number = 0;
const auto end = text.data() + text.size();
const auto parsed = std::from_chars(text.data(), end, number);
if (parsed.ec != std::errc{} || parsed.ptr != end) {
std::fprintf(stderr, "Invalid number for %s: %s\n", argv[i], argv[i + 1]);
return false;
}
if (option == "--start-us") {
options.start_us = number;
} else if (option == "--end-us") {
options.end_us = number;
} else if (option == "--instance" && number <= std::numeric_limits<uint8_t>::max()) {
options.instance = static_cast<int>(number);
} else {
std::fprintf(stderr, "Invalid export option or value: %s %s\n", argv[i], argv[i + 1]);
return false;
}
}
if (options.start_us > options.end_us) {
std::fputs("--start-us must be less than or equal to --end-us\n", stderr);
return false;
}
return true;
}

int exportTopic(const char* path, const char* topic, const ExportOptions& options)
{
const auto data = readLog(path, StorageConfig::FullLog);
if (!data) {
return 1;
}
const auto& subscriptions = data->subscriptionsByNameAndMultiId();
const auto selected = subscriptions.find({topic, options.instance});
if (selected == subscriptions.end()) {
std::fprintf(stderr, "%s: Topic '%s' instance %d not found\n", path, topic, options.instance);
return 1;
}
const auto& subscription = *selected->second;
const auto& fields = subscription.fieldMap();
const auto timestamp = fields.find("timestamp");
if (timestamp == fields.end() || timestamp->second->arrayLength() >= 0 ||
timestamp->second->type().type != flight_log::Field::BasicType::UINT64) {
std::fprintf(stderr, "%s: Topic '%s' has no scalar uint64_t timestamp\n", path, topic);
return 1;
}

std::vector<CsvColumn> columns;
addCsvColumns(*subscription.format(), "", {}, columns);
for (std::size_t i = 0; i < columns.size(); ++i) {
if (i != 0) {
std::cout << ',';
}
writeCsvText(std::cout, columns[i].name);
}
std::cout << '\n';
for (const auto sample : subscription) {
const auto time_us = sample[timestamp->second].as<uint64_t>();
if (time_us < options.start_us || time_us > options.end_us) {
continue;
}
for (std::size_t i = 0; i < columns.size(); ++i) {
if (i != 0) {
std::cout << ',';
}
writeCsvValue(std::cout, columns[i].read(sample));
}
std::cout << '\n';
}
if (!std::cout.flush()) {
std::fputs("Cannot write topic CSV\n", stderr);
return 1;
}
return 0;
}

} // namespace

int main(int argc, char** argv)
{
constexpr auto usage = "Usage: flight-log-inspector <file.ulg>\n";
constexpr auto usage = "Usage: flight-log-inspector <file.ulg>\n"
" flight-log-inspector export-topic <file.ulg> <topic>\n"
" [--instance N] [--start-us N] [--end-us N]\n";
if (argc == 2 && std::string_view(argv[1]) == "--help") {
std::fputs(usage, stdout);
return 0;
}
if (argc > 2 && std::string_view(argv[1]) == "export-topic") {
if (argc < 4 || (argc - 4) % 2 != 0) {
std::fputs(usage, stderr);
return 2;
}
ExportOptions options;
if (!parseExportOptions(argc, argv, options)) {
return 2;
}
try {
return exportTopic(argv[2], argv[3], options);
} catch (const std::exception& error) {
std::fprintf(stderr, "%s: %s\n", argv[2], error.what());
return 1;
}
}
if (argc != 2) {
std::fputs(usage, stderr);
return 2;
Expand Down
5 changes: 5 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ add_test(NAME cli-help COMMAND ${CMAKE_COMMAND}
-DEXPECTED_STATUS=0 "-DEXPECTED_OUTPUT=Usage: flight-log-inspector"
-P ${cli_tests}
)
add_test(NAME cli-export-topic COMMAND ${CMAKE_COMMAND}
-DCLI=$<TARGET_FILE:flight-log-inspector>
-DLOG=${CMAKE_CURRENT_SOURCE_DIR}/log_files/sample_log_small.ulg
-P ${CMAKE_CURRENT_SOURCE_DIR}/check_export_topic.cmake
)
add_test(NAME cli-summary COMMAND ${CMAKE_COMMAND}
-DCLI=$<TARGET_FILE:flight-log-inspector>
-DARGUMENT=${CMAKE_CURRENT_SOURCE_DIR}/log_files/sample_log_small.ulg
Expand Down
38 changes: 38 additions & 0 deletions tests/check_export_topic.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
execute_process(COMMAND "${CLI}" export-topic "${LOG}" sensor_combined
--start-us 20488019 --end-us 20492907
RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error
)
if(NOT status STREQUAL "0")
message(FATAL_ERROR "export-topic exited ${status}\n${error}")
endif()
string(REGEX MATCHALL "[^\n]+" rows "${output}")
list(LENGTH rows row_count)
if(NOT row_count EQUAL 3)
message(FATAL_ERROR "Expected header and two samples, got ${row_count} lines")
endif()
list(GET rows 0 header)
list(GET rows 1 first)
list(GET rows 2 last)
if(NOT header STREQUAL "timestamp,gyro_rad[0],gyro_rad[1],gyro_rad[2],gyro_integral_dt,accelerometer_timestamp_relative,accelerometer_m_s2[0],accelerometer_m_s2[1],accelerometer_m_s2[2],accelerometer_integral_dt,accelerometer_clipping"
OR NOT first MATCHES "^20488019,0[.]0015724377,"
OR NOT last MATCHES "^20492907,0[.]00342134805,")
message(FATAL_ERROR "Unexpected CSV columns or edge samples\n${output}")
endif()

execute_process(COMMAND "${CLI}" export-topic "${LOG}" telemetry_status --instance 1
RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error
)
string(REGEX MATCHALL "[^\n]+" rows "${output}")
list(LENGTH rows row_count)
string(FIND "${output}" "heartbeats[3].system_id" field_position)
if(NOT status STREQUAL "0" OR NOT row_count EQUAL 9 OR field_position EQUAL -1)
message(FATAL_ERROR "Expected 8 instance-1 samples and nested columns (exit ${status})\n${error}")
endif()

execute_process(COMMAND "${CLI}" export-topic "${LOG}" sensor_combined
--start-us 100 --end-us 10
RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error
)
if(NOT status STREQUAL "2" OR NOT output STREQUAL "" OR NOT error MATCHES "--start-us.*--end-us")
message(FATAL_ERROR "Reversed time range was accepted (exit ${status})\n${error}")
endif()
Loading