blob: 6c849c3c89648547da8848ef6998f74ecdbe89e5 [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:
17 ConstantSender<ConstantsData, ConstantsList>(
18 aos::EventLoop *event_loop, std::string constants_path,
19 std::string_view channel_name = "/constants")
20 : ConstantSender<ConstantsData, ConstantsList>(
21 event_loop, constants_path, aos::network::GetTeamNumber(),
22 channel_name) {}
23
24 ConstantSender<ConstantsData, ConstantsList>(aos::EventLoop *event_loop,
25 std::string constants_path,
26 const uint16_t team_number,
27 std::string_view channel_name)
28 : team_number_(team_number),
29 channel_name_(channel_name),
30 constants_path_(constants_path),
31 event_loop_(event_loop),
32 sender_(event_loop_->MakeSender<ConstantsData>(channel_name_)) {
33 event_loop->OnRun([this]() {
34 typename aos::Sender<ConstantsData>::Builder builder =
35 sender_.MakeBuilder();
36 builder.CheckOk(builder.Send(GetConstantsForTeamNumber(builder.fbb())));
37 });
38 }
39
40 private:
41 const uint16_t team_number_ = 0;
42 std::string_view channel_name_;
43 flatbuffers::Offset<ConstantsData> GetConstantsForTeamNumber(
44 flatbuffers::FlatBufferBuilder *fbb) {
45 aos::FlatbufferDetachedBuffer<ConstantsList> fb =
46 aos::JsonFileToFlatbuffer<ConstantsList>(constants_path_);
47 const ConstantsList &message = fb.message();
48 const auto *constants = message.constants();
49 // Search through the constants for the one matching our team number.
50 for (const auto &constant_data : *constants) {
51 if (team_number_ == constant_data->team()) {
52 // Values is equal to the constants meant for the specific robot.
53 const ConstantsData *values = constant_data->data();
54 flatbuffers::Offset<ConstantsData> flatbuffer_constants =
55 aos::RecursiveCopyFlatBuffer(values, fbb);
56 return flatbuffer_constants;
57 }
58 }
59 LOG(FATAL) << "There was no match for " << team_number_
60 << ". Check the constants.json file for the team number that is "
61 "missing.";
62 }
63
64 std::string constants_path_;
65 aos::EventLoop *event_loop_;
66 aos::Sender<ConstantsData> sender_;
67};
68
69} // namespace frc971::constants
70
71#endif // FRC971_CONSTANTS_CONSTANTS_SENDER_H_