James Kuszmaul | cf32412 | 2023-01-14 14:07:17 -0800 | [diff] [blame^] | 1 | // Copyright (c) FIRST and other WPILib contributors. |
| 2 | // Open Source Software; you can modify and/or share it under the terms of |
| 3 | // the WPILib BSD license file in the root directory of this project. |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <atomic> |
| 8 | #include <functional> |
| 9 | #include <map> |
| 10 | #include <string> |
| 11 | #include <string_view> |
| 12 | #include <thread> |
| 13 | #include <utility> |
| 14 | |
| 15 | #include <wpi/DataLogReader.h> |
| 16 | #include <wpi/DenseMap.h> |
| 17 | #include <wpi/Signal.h> |
| 18 | #include <wpi/mutex.h> |
| 19 | |
| 20 | class DataLogThread { |
| 21 | public: |
| 22 | explicit DataLogThread(wpi::log::DataLogReader reader) |
| 23 | : m_reader{std::move(reader)}, m_thread{[=, this] { ReadMain(); }} {} |
| 24 | ~DataLogThread(); |
| 25 | |
| 26 | bool IsDone() const { return m_done; } |
| 27 | std::string_view GetBufferIdentifier() const { |
| 28 | return m_reader.GetBufferIdentifier(); |
| 29 | } |
| 30 | unsigned int GetNumRecords() const { return m_numRecords; } |
| 31 | unsigned int GetNumEntries() const { |
| 32 | std::scoped_lock lock{m_mutex}; |
| 33 | return m_entryNames.size(); |
| 34 | } |
| 35 | |
| 36 | // Passes wpi::log::StartRecordData to func |
| 37 | template <typename T> |
| 38 | void ForEachEntryName(T&& func) { |
| 39 | std::scoped_lock lock{m_mutex}; |
| 40 | for (auto&& kv : m_entryNames) { |
| 41 | func(kv.second); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | wpi::log::StartRecordData GetEntry(std::string_view name) const { |
| 46 | std::scoped_lock lock{m_mutex}; |
| 47 | auto it = m_entryNames.find(name); |
| 48 | if (it == m_entryNames.end()) { |
| 49 | return {}; |
| 50 | } |
| 51 | return it->second; |
| 52 | } |
| 53 | |
| 54 | const wpi::log::DataLogReader& GetReader() const { return m_reader; } |
| 55 | |
| 56 | // note: these are called on separate thread |
| 57 | wpi::sig::Signal_mt<const wpi::log::StartRecordData&> sigEntryAdded; |
| 58 | wpi::sig::Signal_mt<> sigDone; |
| 59 | |
| 60 | private: |
| 61 | void ReadMain(); |
| 62 | |
| 63 | wpi::log::DataLogReader m_reader; |
| 64 | mutable wpi::mutex m_mutex; |
| 65 | std::atomic_bool m_active{true}; |
| 66 | std::atomic_bool m_done{false}; |
| 67 | std::atomic<unsigned int> m_numRecords{0}; |
| 68 | std::map<std::string, wpi::log::StartRecordData, std::less<>> m_entryNames; |
| 69 | wpi::DenseMap<int, wpi::log::StartRecordData> m_entries; |
| 70 | std::thread m_thread; |
| 71 | }; |