CTRE Phoenix 6 C++ 24.2.0
ParentDevice.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) Cross The Road Electronics.  All rights reserved.
3 * License information can be found in CTRE_LICENSE.txt
4 * For support and suggestions contact support@ctr-electronics.com or file
5 * an issue tracker at https://github.com/CrossTheRoadElec/Phoenix-Releases
6 */
7#pragma once
8
16#include <map>
17#include <memory>
18#include <mutex>
19#include <units/dimensionless.h>
20
21namespace ctre {
22namespace phoenix6 {
23namespace hardware {
24
25 /**
26 * Parent class for all devices
27 */
29 {
30 protected:
32
34
35 /**
36 * \brief Type trait to verify that all types passed in are subclasses of ParentDevice.
37 */
38 template <typename... Devices>
40 std::conjunction<std::is_base_of<ParentDevice, std::remove_reference_t<Devices>>...>
41 {};
42
43 /**
44 * \brief Whether all types passed in are subclasses of ParentDevice.
45 */
46 template <typename... Devices>
47 static constexpr bool is_all_device_v = is_all_device<Devices...>::value;
48
49 private:
50 std::map<uint32_t, std::unique_ptr<BaseStatusSignal>> _signalValues;
51 std::recursive_mutex _signalValuesLck;
52 /**
53 * Use a shared pointer so users that access the control request via #GetAppliedControl has a copy
54 * of the pointer without risk of it becoming a dangling pointer due to parallel operations
55 */
56 std::shared_ptr<controls::ControlRequest> _controlReq = std::make_shared<controls::EmptyControl>();
57 std::mutex _controlReqLck;
58
59 double _creationTime = GetCurrentTimeSeconds();
60
61 bool _isInitialized = false;
62 ctre::phoenix::StatusCode _versionStatus{ctre::phoenix::StatusCode::CouldNotRetrieveV6Firmware};
63 double _timeToRefreshVersion = GetCurrentTimeSeconds();
64
65 StatusSignal<int> &_compliancy{LookupStatusSignal<int>(ctre::phoenix6::spns::SpnValue::Compliancy_Version, "Compliancy", false)};
66 StatusSignal<int> &_resetSignal{LookupStatusSignal<int>(ctre::phoenix6::spns::SpnValue::Startup_ResetFlags, "ResetFlags", false)};
67
68 void ReportIfTooOld();
69
70 template <typename T>
71 StatusSignal<T> &LookupCommon(uint16_t spn, uint16_t mapper_iter, std::function<std::map<int, StatusSignal<T>>()> map_filler, std::string signalName, bool reportOnConstruction)
72 {
73 BaseStatusSignal *toFind;
74 {
75 /* lock access to the map */
76 std::lock_guard<std::recursive_mutex> lock{_signalValuesLck};
77
78 const uint32_t totalHash = spn | ((uint32_t)mapper_iter << 16);
79 /* lookup and return if found */
80 auto iter = _signalValues.find(totalHash);
81 if (iter != _signalValues.end())
82 {
83 /* Found it, toFind is now the found StatusSignal */
84 toFind = iter->second.get();
85 /* since we didn't construct, report errors */
86 reportOnConstruction = true;
87 }
88 else
89 {
90 /* insert into map */
91 /* Mapper_iter is 0 when using straight SPNs, otherwise it's nonzero for switchable SPNs */
92 if (mapper_iter != 0)
93 {
94 /* Switchable spn, so generate the map to switch with */
95 _signalValues.emplace(totalHash, std::unique_ptr<StatusSignal<T>>{new StatusSignal<T>{
96 deviceIdentifier, spn, [this]()
97 { ReportIfTooOld(); },
98 map_filler, std::move(signalName)}});
99 }
100 else
101 {
102 /* Non-switchable spn, so just add the SPN plain */
103 _signalValues.emplace(totalHash, std::unique_ptr<StatusSignal<T>>{new StatusSignal<T>{
104 deviceIdentifier, spn, [this]()
105 { ReportIfTooOld(); },
106 std::move(signalName)}});
107 }
108
109 /* look up and return */
110 iter = _signalValues.find(totalHash);
111 toFind = iter->second.get();
112 }
113 }
114
115 /* Now cast it up to the StatusSignal */
116 StatusSignal<T> *ret = dynamic_cast<StatusSignal<T> *>(toFind);
117 /* If ret is null, that means the cast failed. Otherwise we can return it */
118 if (ret == nullptr)
119 {
120 /* Cast failed, let user know this doesn't exist */
121 static StatusSignal<T> failure{ctre::phoenix::StatusCode::InvalidParamValue};
122 return failure;
123 }
124 else
125 {
126 /* Good cast, refresh it and return this now */
127 ret->Refresh(reportOnConstruction);
128 return *ret;
129 }
130 }
131
132 public:
133 ParentDevice(int deviceID, std::string model, std::string canbus) :
134 deviceIdentifier{DeviceIdentifier{deviceID, std::move(model), std::move(canbus)}}
135 {
136 /* This needs to be set to true after everything else has already been initialized */
137 _isInitialized = true;
138 }
139
140 virtual ~ParentDevice() = default;
141
142 /**
143 * \returns The device ID of this device [0,62].
144 */
145 int GetDeviceID() const
146 {
148 }
149
150 /**
151 * \returns Name of the network this device is on.
152 */
153 const std::string &GetNetwork() const
154 {
156 }
157
158 /**
159 * \brief Gets a number unique for this device's hardware type and ID.
160 * This number is not unique across networks.
161 *
162 * \details This can be used to easily reference hardware devices on
163 * the same network in collections such as maps.
164 *
165 * \returns Hash of this device.
166 */
167 uint64_t GetDeviceHash() const
168 {
170 }
171
172 /**
173 * \brief Get the latest applied control.
174 * Caller can cast this to the derived class if they know its type. Otherwise,
175 * use controls#ControlRequest#GetControlInfo to get info out of it.
176 *
177 * \details This returns a shared pointer to avoid becoming a dangling pointer
178 * due to parallel operations changing the underlying data. Make sure
179 * to save the shared_ptr to a variable before chaining function calls,
180 * otherwise the data may be freed early.
181 *
182 * \returns Latest applied control
183 */
184 std::shared_ptr<const controls::ControlRequest> GetAppliedControl() const
185 {
186 return _controlReq;
187 }
188
189 /**
190 * \brief Get the latest applied control.
191 * Caller can cast this to the derived class if they know its type. Otherwise,
192 * use controls#ControlRequest#GetControlInfo to get info out of it.
193 *
194 * \details This returns a shared pointer to avoid becoming a dangling pointer
195 * due to parallel operations changing the underlying data. Make sure
196 * to save the shared_ptr to a variable before chaining function calls,
197 * otherwise the data may be freed early.
198 *
199 * \returns Latest applied control
200 */
201 std::shared_ptr<controls::ControlRequest> GetAppliedControl()
202 {
203 return _controlReq;
204 }
205
206 /**
207 * \returns true if device has reset since the previous call of this routine.
208 */
210 {
211 return _resetSignal.Refresh(false).HasUpdated();
212 }
213
214 /**
215 * \returns a function that checks for device resets.
216 */
217 std::function<bool()> GetResetOccurredChecker() const
218 {
219 return [resetSignal=_resetSignal]() mutable {
220 return resetSignal.Refresh(false).HasUpdated();
221 };
222 }
223
224 /**
225 * \brief This is a reserved routine for internal testing. Use the other get routines to retrieve signal values.
226 *
227 * \param signal Signal to get.
228 * \return StatusSignalValue holding value
229 */
231 {
232 return LookupStatusSignal<double>((uint16_t)signal, "Generic", true);
233 }
234
235 /**
236 * \brief Optimizes the device's bus utilization by reducing the update frequencies of its status signals.
237 *
238 * All status signals that have not been explicitly given an update frequency using
239 * BaseStatusSignal#SetUpdateFrequency will be disabled. Note that if other status
240 * signals in the same status frame have been given an update frequency, the update
241 * frequency will be honored for the entire frame.
242 *
243 * This function only needs to be called once on this device in the robot program. Additionally, this
244 * method does not necessarily need to be called after setting the update frequencies of other signals.
245 *
246 * To restore the default status update frequencies, remove this method call, redeploy the robot
247 * application, and power-cycle the devices on the bus. Alternatively, the user can override
248 * individual status update frequencies using BaseStatusSignal#SetUpdateFrequency.
249 *
250 * \param timeoutSeconds Maximum amount of time to wait for each status frame when performing the action
251 * \return Status code of the first failed update frequency set call, or OK if all succeeded
252 */
253 ctre::phoenix::StatusCode OptimizeBusUtilization(units::time::second_t timeoutSeconds = 50_ms);
254
255 /**
256 * \brief Optimizes the bus utilization of the provided devices by reducing the update
257 * frequencies of their status signals.
258 *
259 * All status signals that have not been explicitly given an update frequency using
260 * BaseStatusSignal#SetUpdateFrequency will be disabled. Note that if other status
261 * signals in the same status frame have been given an update frequency, the update
262 * frequency will be honored for the entire frame.
263 *
264 * This function only needs to be called once in the robot program for the provided devices.
265 * Additionally, this method does not necessarily need to be called after setting the update
266 * frequencies of other signals.
267 *
268 * To restore the default status update frequencies, remove this method call, redeploy the robot
269 * application, and power-cycle the devices on the bus. Alternatively, the user can override
270 * individual status update frequencies using BaseStatusSignal#SetUpdateFrequency.
271 *
272 * This will wait up to 0.050 seconds (50ms) for each status frame.
273 *
274 * \param devices Devices for which to optimize bus utilization, passed as a comma-separated list of device references.
275 * \return Status code of the first failed optimize call, or OK if all succeeded
276 */
277 template <typename... Devices, typename = std::enable_if_t<is_all_device_v<Devices...>>>
278 static ctre::phoenix::StatusCode OptimizeBusUtilizationForAll(Devices &... devices)
279 {
280 return OptimizeBusUtilizationForAll(std::array<ParentDevice *, sizeof...(Devices)>{(&devices)...});
281 }
282
283 /**
284 * \brief Optimizes the bus utilization of the provided devices by reducing the update
285 * frequencies of their status signals.
286 *
287 * All status signals that have not been explicitly given an update frequency using
288 * BaseStatusSignal#SetUpdateFrequency will be disabled. Note that if other status
289 * signals in the same status frame have been given an update frequency, the update
290 * frequency will be honored for the entire frame.
291 *
292 * This function only needs to be called once in the robot program for the provided devices.
293 * Additionally, this method does not necessarily need to be called after setting the update
294 * frequencies of other signals.
295 *
296 * To restore the default status update frequencies, remove this method call, redeploy the robot
297 * application, and power-cycle the devices on the bus. Alternatively, the user can override
298 * individual status update frequencies using BaseStatusSignal#SetUpdateFrequency.
299 *
300 * This will wait up to 0.050 seconds (50ms) for each status frame.
301 *
302 * \param devices Devices for which to optimize bus utilization, passed as a vector or initializer list of device addresses.
303 * \return Status code of the first failed optimize call, or OK if all succeeded
304 */
305 static ctre::phoenix::StatusCode OptimizeBusUtilizationForAll(const std::vector<ParentDevice *> &devices)
306 {
307 ctre::phoenix::StatusCode retval = ctre::phoenix::StatusCode::OK;
308 for (auto device : devices) {
309 const auto err = device->OptimizeBusUtilization();
310 if (retval.IsOK()) {
311 retval = err;
312 }
313 }
314 return retval;
315 }
316
317 /**
318 * \brief Optimizes the bus utilization of the provided devices by reducing the update
319 * frequencies of their status signals.
320 *
321 * All status signals that have not been explicitly given an update frequency using
322 * BaseStatusSignal#SetUpdateFrequency will be disabled. Note that if other status
323 * signals in the same status frame have been given an update frequency, the update
324 * frequency will be honored for the entire frame.
325 *
326 * This function only needs to be called once in the robot program for the provided devices.
327 * Additionally, this method does not necessarily need to be called after setting the update
328 * frequencies of other signals.
329 *
330 * To restore the default status update frequencies, remove this method call, redeploy the robot
331 * application, and power-cycle the devices on the bus. Alternatively, the user can override
332 * individual status update frequencies using BaseStatusSignal#SetUpdateFrequency.
333 *
334 * This will wait up to 0.050 seconds (50ms) for each status frame.
335 *
336 * \param devices Devices for which to optimize bus utilization, passed as an array of device addresses.
337 * \return Status code of the first failed optimize call, or OK if all succeeded
338 */
339 template <size_t N>
340 static ctre::phoenix::StatusCode OptimizeBusUtilizationForAll(const std::array<ParentDevice *, N> &devices)
341 {
342 ctre::phoenix::StatusCode retval = ctre::phoenix::StatusCode::OK;
343 for (auto device : devices) {
344 const auto err = device->OptimizeBusUtilization();
345 if (retval.IsOK()) {
346 retval = err;
347 }
348 }
349 return retval;
350 }
351
352 protected:
353 virtual ctre::phoenix::StatusCode SetControlPrivate(controls::ControlRequest &request);
354
355 template <typename T>
356 StatusSignal<T> &LookupStatusSignal(uint16_t spn, std::string signalName, bool reportOnConstruction)
357 {
358 std::function<std::map<int, StatusSignal<T>>()> emptyMapFiller = []
359 {
360 return std::map<int, StatusSignal<T>>{};
361 };
362 return LookupCommon<T>(spn, 0, emptyMapFiller, std::move(signalName), reportOnConstruction);
363 }
364
365 template <typename T>
366 StatusSignal<T> &LookupStatusSignal(uint16_t spn, uint16_t mapper_iter, std::function<std::map<int, StatusSignal<T>>()> map_filler, std::string signalName, bool reportOnConstruction)
367 {
368 return LookupCommon<T>(spn, mapper_iter, map_filler, std::move(signalName), reportOnConstruction);
369 }
370
371 /** Returns a unitless version of the StatusSignal by value. Do not store the result in a reference. */
372 template <typename T, typename U>
373 StatusSignal<T> LookupDimensionlessStatusSignal(uint16_t spn, std::string signalName)
374 {
375 return StatusSignal<T>{LookupStatusSignal<U>(spn, std::move(signalName), true)};
376 }
377 };
378
379}
380}
381}
@ OK
No Error.
Definition: StatusCodes.h:1192
@ CouldNotRetrieveV6Firmware
Device firmware could not be retrieved.
Definition: StatusCodes.h:1874
@ InvalidParamValue
An invalid argument was passed into the function/VI, such as a null pointer.
Definition: StatusCodes.h:1525
bool HasUpdated()
Check whether the signal has been updated since the last check.
Definition: StatusSignal.hpp:580
StatusSignal< T > & Refresh(bool ReportOnError=true)
Refreshes the value of this status signal.
Definition: StatusSignal.hpp:817
Abstract Control Request class that other control requests extend for use.
Definition: ControlRequest.hpp:28
Generic Empty Control class used to do nothing.
Definition: ControlRequest.hpp:71
Definition: DeviceIdentifier.hpp:19
int deviceID
Definition: DeviceIdentifier.hpp:23
uint32_t deviceHash
Definition: DeviceIdentifier.hpp:24
std::string network
Definition: DeviceIdentifier.hpp:21
Parent class for all devices.
Definition: ParentDevice.hpp:29
static controls::EmptyControl _emptyControl
Definition: ParentDevice.hpp:31
const std::string & GetNetwork() const
Definition: ParentDevice.hpp:153
static constexpr bool is_all_device_v
Whether all types passed in are subclasses of ParentDevice.
Definition: ParentDevice.hpp:47
std::shared_ptr< controls::ControlRequest > GetAppliedControl()
Get the latest applied control.
Definition: ParentDevice.hpp:201
virtual ctre::phoenix::StatusCode SetControlPrivate(controls::ControlRequest &request)
DeviceIdentifier deviceIdentifier
Definition: ParentDevice.hpp:33
StatusSignal< T > & LookupStatusSignal(uint16_t spn, std::string signalName, bool reportOnConstruction)
Definition: ParentDevice.hpp:356
std::function< bool()> GetResetOccurredChecker() const
Definition: ParentDevice.hpp:217
std::shared_ptr< const controls::ControlRequest > GetAppliedControl() const
Get the latest applied control.
Definition: ParentDevice.hpp:184
ctre::phoenix::StatusCode OptimizeBusUtilization(units::time::second_t timeoutSeconds=50_ms)
Optimizes the device's bus utilization by reducing the update frequencies of its status signals.
static ctre::phoenix::StatusCode OptimizeBusUtilizationForAll(const std::array< ParentDevice *, N > &devices)
Optimizes the bus utilization of the provided devices by reducing the update frequencies of their sta...
Definition: ParentDevice.hpp:340
static ctre::phoenix::StatusCode OptimizeBusUtilizationForAll(Devices &... devices)
Optimizes the bus utilization of the provided devices by reducing the update frequencies of their sta...
Definition: ParentDevice.hpp:278
StatusSignal< double > & GetGenericSignal(uint32_t signal)
This is a reserved routine for internal testing.
Definition: ParentDevice.hpp:230
StatusSignal< T > LookupDimensionlessStatusSignal(uint16_t spn, std::string signalName)
Returns a unitless version of the StatusSignal by value.
Definition: ParentDevice.hpp:373
int GetDeviceID() const
Definition: ParentDevice.hpp:145
ParentDevice(int deviceID, std::string model, std::string canbus)
Definition: ParentDevice.hpp:133
uint64_t GetDeviceHash() const
Gets a number unique for this device's hardware type and ID.
Definition: ParentDevice.hpp:167
bool HasResetOccurred()
Definition: ParentDevice.hpp:209
StatusSignal< T > & LookupStatusSignal(uint16_t spn, uint16_t mapper_iter, std::function< std::map< int, StatusSignal< T > >()> map_filler, std::string signalName, bool reportOnConstruction)
Definition: ParentDevice.hpp:366
static ctre::phoenix::StatusCode OptimizeBusUtilizationForAll(const std::vector< ParentDevice * > &devices)
Optimizes the bus utilization of the provided devices by reducing the update frequencies of their sta...
Definition: ParentDevice.hpp:305
CTREXPORT double GetCurrentTimeSeconds()
Get the current timestamp in seconds.
Definition: RcManualEvent.hpp:12
Type trait to verify that all types passed in are subclasses of ParentDevice.
Definition: ParentDevice.hpp:41