blob: 92c14faad048ef09f95ac35631cbcf326c8461d1 [file] [log] [blame]
Henry Speisere5f05aa2022-05-02 21:24:26 -07001#ifndef FRC971_CONSTANTS_CONSTANTS_SENDER_H_
2#define FRC971_CONSTANTS_CONSTANTS_SENDER_H_
3
4#include "aos/events/event_loop.h"
5#include "aos/flatbuffer_merge.h"
6#include "aos/json_to_flatbuffer.h"
7#include "aos/network/team_number.h"
8#include "gflags/gflags.h"
9#include "glog/logging.h"
10
11namespace frc971::constants {
12
13// Publishes the constants specific to the current robot
14template <typename ConstantsData, typename ConstantsList>
15class ConstantSender {
16 public:
James Kuszmaul9776b392023-01-14 14:08:08 -080017 ConstantSender(aos::EventLoop *event_loop, std::string constants_path,
18 std::string_view channel_name = "/constants")
Henry Speisere5f05aa2022-05-02 21:24:26 -070019 : ConstantSender<ConstantsData, ConstantsList>(
20 event_loop, constants_path, aos::network::GetTeamNumber(),
21 channel_name) {}
22
James Kuszmaul9776b392023-01-14 14:08:08 -080023 ConstantSender(aos::EventLoop *event_loop, std::string constants_path,
24 const uint16_t team_number, std::string_view channel_name)
Henry Speisere5f05aa2022-05-02 21:24:26 -070025 : team_number_(team_number),
26 channel_name_(channel_name),
27 constants_path_(constants_path),
28 event_loop_(event_loop),
29 sender_(event_loop_->MakeSender<ConstantsData>(channel_name_)) {
30 event_loop->OnRun([this]() {
31 typename aos::Sender<ConstantsData>::Builder builder =
32 sender_.MakeBuilder();
33 builder.CheckOk(builder.Send(GetConstantsForTeamNumber(builder.fbb())));
34 });
35 }
36
37 private:
38 const uint16_t team_number_ = 0;
39 std::string_view channel_name_;
40 flatbuffers::Offset<ConstantsData> GetConstantsForTeamNumber(
41 flatbuffers::FlatBufferBuilder *fbb) {
42 aos::FlatbufferDetachedBuffer<ConstantsList> fb =
43 aos::JsonFileToFlatbuffer<ConstantsList>(constants_path_);
44 const ConstantsList &message = fb.message();
45 const auto *constants = message.constants();
46 // Search through the constants for the one matching our team number.
47 for (const auto &constant_data : *constants) {
48 if (team_number_ == constant_data->team()) {
49 // Values is equal to the constants meant for the specific robot.
50 const ConstantsData *values = constant_data->data();
51 flatbuffers::Offset<ConstantsData> flatbuffer_constants =
52 aos::RecursiveCopyFlatBuffer(values, fbb);
53 return flatbuffer_constants;
54 }
55 }
56 LOG(FATAL) << "There was no match for " << team_number_
57 << ". Check the constants.json file for the team number that is "
58 "missing.";
59 }
60
61 std::string constants_path_;
62 aos::EventLoop *event_loop_;
63 aos::Sender<ConstantsData> sender_;
64};
65
66} // namespace frc971::constants
67
68#endif // FRC971_CONSTANTS_CONSTANTS_SENDER_H_