Valor 6800 1.0
Loading...
Searching...
No Matches
BaseSensor.h
1
2#pragma once
3
4#include <functional>
5#include <string>
6
7#include <frc/TimedRobot.h>
8#include <frc/Timer.h>
9
10#include "valkyrie/Loggable.h"
11#include "valkyrie/util/Profiler.h"
12
13namespace valor {
14
26template <class T>
28 public:
36 virtual void reset() { prevState = currState = T{}; }
37
46 void setGetter(std::function<T()> _lambda) { sensorLambda = _lambda; }
47
56 void applyPostProcessing(std::function<T(T)> func) { postProcessor = func; }
57
66 inline T get() { return currState; }
67
68 protected:
74 explicit BaseSensor(frc::TimedRobot& robot) {
75 profiler.Start();
76 robot.AddPeriodic(
77 [this] {
78 profiler.Reset();
79 refresh();
80 units::millisecond_t refreshTime = profiler.Get();
81 calculate();
82 units::millisecond_t calculateTime = profiler.Get() - refreshTime;
83 if (util::Profiler::IsEnabled()) {
84 WriteLog("Profiler/Cycle Time", units::millisecond_t{profiler.Get()});
85 WriteLog("Profiler/Refresh Time", refreshTime);
86 WriteLog("Profiler/Calculate Time", calculateTime);
87 }
88 },
89 frc::TimedRobot::kDefaultPeriod / 2, 5_ms);
90 }
91
92 BaseSensor() = default;
93
100 virtual void calculate() = 0;
101
108 virtual void refresh() {
109 prevState = currState;
110 if (sensorLambda) {
111 currState = sensorLambda();
112 if (postProcessor)
113 currState = postProcessor(currState);
114 }
115 }
116
122 std::function<T()> sensorLambda;
123
129 std::function<T(T)> postProcessor;
130
137 T prevState, currState;
138
139 frc::Timer profiler;
140};
141} // namespace valor
Abstract class that all Valor sensors should implement.
Definition BaseSensor.h:27
T get()
Get the current sensor state.
Definition BaseSensor.h:66
BaseSensor(frc::TimedRobot &robot)
Construct a new BaseSensor object.
Definition BaseSensor.h:74
void setGetter(std::function< T()> _lambda)
Set the lambda function to fetch sensor data.
Definition BaseSensor.h:46
virtual void reset()
Reset the sensor state.
Definition BaseSensor.h:36
T prevState
Previous and current sensor states.
Definition BaseSensor.h:137
void applyPostProcessing(std::function< T(T)> func)
Set a post-processing function for sensor data.
Definition BaseSensor.h:56
std::function< T()> sensorLambda
Lambda function to fetch sensor data.
Definition BaseSensor.h:122
std::function< T(T)> postProcessor
Lambda function to post-process sensor data.
Definition BaseSensor.h:129
virtual void refresh()
Refresh the sensor state.
Definition BaseSensor.h:108
virtual void calculate()=0
Perform sensor-specific calculations.
Base helper for publishing and subscribing values to NetworkTables.
Definition Loggable.h:204
T ReadLog(std::string_view field, const T &defaultValue={})
Read a value from NetworkTables for the given field.
Definition Loggable.h:343
T WriteLog(std::string_view field, const T &data)
Publish a value to NetworkTables under the given field.
Definition Loggable.h:313