001/*
002 * Copyright (C) Cross The Road Electronics.  All rights reserved.
003 * License information can be found in CTRE_LICENSE.txt
004 * For support and suggestions contact support@ctr-electronics.com or file
005 * an issue tracker at https://github.com/CrossTheRoadElec/Phoenix-Releases
006 */
007package com.ctre.phoenix6;
008
009import static edu.wpi.first.units.Units.*;
010
011import java.util.Arrays;
012import java.util.List;
013import java.util.Map;
014
015import com.ctre.phoenix6.Timestamp.TimestampSource;
016import com.ctre.phoenix6.hardware.DeviceIdentifier;
017import com.ctre.phoenix6.hardware.ParentDevice.MapGenerator;
018import com.ctre.phoenix6.jni.ErrorReportingJNI;
019import com.ctre.phoenix6.jni.StatusSignalJNI;
020
021import edu.wpi.first.units.Measure;
022import edu.wpi.first.units.PerUnit;
023import edu.wpi.first.units.TimeUnit;
024import edu.wpi.first.units.Unit;
025import edu.wpi.first.units.measure.*;
026
027/**
028 * Class that provides operations to retrieve
029 * information about a status signal.
030 */
031public abstract class BaseStatusSignal {
032    protected StatusSignalJNI jni;
033
034    private final DeviceIdentifier deviceIdentifier;
035    private int spn;
036    private final String name;
037    private final Runnable _reportIfOldFunc;
038
039    private final Map<Integer, String> _unitStrings;
040    private int _unitsKey;
041
042    protected String units;
043    protected double baseValue = 0;
044    protected AllTimestamps timestamps = new AllTimestamps();
045    protected StatusCode error = StatusCode.StatusCodeNotInitialized;
046
047    private double _lastTimestamp = 0.0;
048
049    BaseStatusSignal(DeviceIdentifier deviceIdentifier, int spn, String signalName, Runnable reportIfOldFunc) {
050        this.jni = new StatusSignalJNI(deviceIdentifier.getNetwork().getNameUTF8Bytes(), deviceIdentifier.getDeviceHash());
051        this.jni.spn = spn;
052
053        this.deviceIdentifier = deviceIdentifier;
054        this.spn = spn;
055        this.name = signalName;
056        this._reportIfOldFunc = reportIfOldFunc;
057
058        this.units = jni.JNI_GetUnits();
059        this._unitStrings = null;
060        this._unitsKey = spn;
061    }
062
063    BaseStatusSignal(DeviceIdentifier deviceIdentifier, int spn, String signalName, Runnable reportIfOldFunc, MapGenerator unitsGenerator) {
064        this.jni = new StatusSignalJNI(deviceIdentifier.getNetwork().getNameUTF8Bytes(), deviceIdentifier.getDeviceHash());
065        this.jni.spn = spn;
066
067        this.deviceIdentifier = deviceIdentifier;
068        this.spn = spn;
069        this.name = signalName;
070        this._reportIfOldFunc = reportIfOldFunc;
071
072        this.units = jni.JNI_GetUnits();
073        this._unitStrings = unitsGenerator.run();
074        this._unitsKey = spn;
075
076        var tmpJni = jni.clone();
077        for (var unitString : _unitStrings.entrySet()) {
078            tmpJni.spn = unitString.getKey();
079            unitString.setValue(tmpJni.JNI_GetUnits());
080        }
081    }
082
083    /* Constructor for an invalid BaseStatusSignal */
084    BaseStatusSignal(StatusCode error) {
085        this(new DeviceIdentifier(), 0, "Invalid", () -> {});
086        this.error = error;
087    }
088
089    /**
090     * Gets the name of this signal.
091     *
092     * @return Name of this signal
093     */
094    public final String getName() {
095        return name;
096    }
097
098    /**
099     * Gets the units for this signal.
100     *
101     * @return String representation of units for this signal
102     */
103    public final String getUnits() {
104        return units;
105    }
106
107    /**
108     * Gets the value of this signal as a double.
109     *
110     * @return Value of this signal as a double instead of the generic type
111     */
112    public final double getValueAsDouble() {
113        return baseValue;
114    }
115
116    /**
117     * Gets all timestamps relevant for this signal.
118     *
119     * @return All timestamps available for this signal
120     */
121    public final AllTimestamps getAllTimestamps() {
122        return timestamps;
123    }
124
125    /**
126     * Gets the most accurate timestamp available for this signal.
127     * <p>
128     * The timestamp sources from most to least accurate are:
129     * <ul>
130     *   <li> {@link Timestamp.TimestampSource#Device}
131     *   <li> {@link Timestamp.TimestampSource#CANivore}
132     *   <li> {@link Timestamp.TimestampSource#System}
133     * </ul>
134     * Note that some of these sources may not be available.
135     *
136     * @return The most accurate timestamp available
137     */
138    public final Timestamp getTimestamp() {
139        return timestamps.getBestTimestamp();
140    }
141
142    /**
143     * Gets the status code of the last time this signal was refreshed.
144     *
145     * @return Status code of the last time this signal was refreshed
146     */
147    public final StatusCode getStatus() {
148        return error;
149    }
150
151    /**
152     * Checks whether the signal has been updated since the last check.
153     * <p>
154     * Note that the signal must be refreshed before calling this routine.
155     *
156     * @return true if the signal has updated since the previous call of this routine
157     */
158    public final boolean hasUpdated()
159    {
160        boolean retval = false;
161        /* did we receive an update */
162        final var timestamp = getAllTimestamps().getSystemTimestamp();
163        if (timestamp.isValid()) {
164            /* if the update timestamp is new, then a new frame was sent */
165            if (_lastTimestamp != timestamp.getTime()) {
166                _lastTimestamp = timestamp.getTime();
167                retval = true;
168            }
169        }
170        return retval;
171    }
172
173    /**
174     * Sets the rate at which the device will publish this signal.
175     * <p>
176     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
177     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
178     * supported and will be promoted up to the next highest supported frequency.
179     * <p>
180     * If other StatusSignals in the same status frame have been set to an update frequency,
181     * the fastest requested update frequency will be applied to the frame.
182     * <p>
183     * This will wait up to 0.100 seconds (100ms) by default.
184     *
185     * @param frequencyHz Rate to publish the signal in Hz
186     * @return Status code of setting the update frequency
187     */
188    public final StatusCode setUpdateFrequency(double frequencyHz) {
189        return setUpdateFrequency(frequencyHz, 0.100);
190    }
191
192    /**
193     * Sets the rate at which the device will publish this signal.
194     * <p>
195     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
196     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
197     * supported and will be promoted up to the next highest supported frequency.
198     * <p>
199     * If other StatusSignals in the same status frame have been set to an update frequency,
200     * the fastest requested update frequency will be applied to the frame.
201     * <p>
202     * This will wait up to 0.100 seconds (100ms) by default.
203     *
204     * @param frequency Rate to publish the signal
205     * @return Status code of setting the update frequency
206     */
207    public final StatusCode setUpdateFrequency(Frequency frequency) {
208        return setUpdateFrequency(frequency.in(Hertz));
209    }
210
211    /**
212     * Sets the rate at which the device will publish this signal.
213     * <p>
214     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
215     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
216     * supported and will be promoted up to the next highest supported frequency.
217     * <p>
218     * If other StatusSignals in the same status frame have been set to an update frequency,
219     * the fastest requested update frequency will be applied to the frame.
220     *
221     * @param frequencyHz Rate to publish the signal in Hz
222     * @param timeoutSeconds Maximum amount of time to wait when performing the action
223     * @return Status code of setting the update frequency
224     */
225    public final StatusCode setUpdateFrequency(double frequencyHz, double timeoutSeconds) {
226        StatusCode retval = StatusCode.valueOf(jni.JNI_SetUpdateFrequency(frequencyHz, timeoutSeconds));
227        if (!retval.isOK()) {
228            String device = this.deviceIdentifier.toString() + " setUpdateFrequency " + this.name;
229            ErrorReportingJNI.reportStatusCode(retval.value, device);
230        }
231        return retval;
232    }
233
234    /**
235     * Sets the rate at which the device will publish this signal.
236     * <p>
237     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
238     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
239     * supported and will be promoted up to the next highest supported frequency.
240     * <p>
241     * If other StatusSignals in the same status frame have been set to an update frequency,
242     * the fastest requested update frequency will be applied to the frame.
243     *
244     * @param frequency Rate to publish the signal
245     * @param timeoutSeconds Maximum amount of time to wait when performing the action
246     * @return Status code of setting the update frequency
247     */
248    public final StatusCode setUpdateFrequency(Frequency frequency, double timeoutSeconds) {
249        return setUpdateFrequency(frequency.in(Hertz), timeoutSeconds);
250    }
251
252    /**
253     * Gets the rate at which the device will publish this signal.
254     * <p>
255     * This is typically the last value passed into {@link #setUpdateFrequency}. The returned value
256     * may be higher if another StatusSignal in the same status frame has been set to a higher
257     * update frequency.
258     *
259     * @return Applied update frequency of the signal in Hz
260     */
261    public final double getAppliedUpdateFrequency() {
262        return jni.JNI_GetAppliedUpdateFrequency();
263    }
264
265    /**
266     * Gets the rate at which the device will publish this signal as a unit type.
267     * <p>
268     * This is typically the last value passed into {@link #setUpdateFrequency}. The returned value
269     * may be higher if another StatusSignal in the same status frame has been set to a higher
270     * update frequency.
271     *
272     * @return Applied update frequency of the signal
273     */
274    public final Frequency getAppliedUpdateFrequencyMeasure() {
275        return Hertz.of(getAppliedUpdateFrequency());
276    }
277
278    /**
279     * Performs latency compensation on signal using the signalSlope and signal's latency to determine
280     * the magnitude of compensation. The caller must refresh these StatusSignals beforehand;
281     * this function only does the math required for latency compensation.
282     * <p>
283     * This compensates for up to 300ms of latency by default.
284     * <p>
285     * <b>Example</b>:
286     * var compensatedTurns = BaseStatusSignal.getLatencyCompensatedValue(fx.getPosition(), fx.getVelocity());
287     *
288     * @param signal Signal to be latency compensated. Caller must make sure this signal is up to date
289     *               either by calling {@link StatusSignal#refresh()} or {@link StatusSignal#waitForUpdate(double)}.
290     * @param signalSlope Derivative of signal that informs compensation magnitude. Caller must make sure this
291     *                    signal is up to date either by calling {@link StatusSignal#refresh()} or
292     *                    {@link StatusSignal#waitForUpdate(double)}.
293     * @return Latency compensated value from the signal StatusSignal.
294     */
295    public static
296    <U extends Unit, U_PER_SEC extends PerUnit<U, TimeUnit>, MEAS extends Measure<U>, MEAS_PER_SEC extends Measure<U_PER_SEC>>
297    MEAS getLatencyCompensatedValue(StatusSignal<MEAS> signal, StatusSignal<MEAS_PER_SEC> signalSlope) {
298        return getLatencyCompensatedValue(signal, signalSlope, 0.300);
299    }
300
301    /**
302     * Performs latency compensation on signal using the signalSlope and signal's latency to determine
303     * the magnitude of compensation. The caller must refresh these StatusSignals beforehand;
304     * this function only does the math required for latency compensation.
305     * <p>
306     * <b>Example</b>:
307     * var compensatedTurns = BaseStatusSignal.getLatencyCompensatedValue(fx.getPosition(), fx.getVelocity());
308     *
309     * @param signal Signal to be latency compensated. Caller must make sure this signal is up to date
310     *               either by calling {@link StatusSignal#refresh()} or {@link StatusSignal#waitForUpdate(double)}.
311     * @param signalSlope Derivative of signal that informs compensation magnitude. Caller must make sure this
312     *                    signal is up to date either by calling {@link StatusSignal#refresh()} or
313     *                    {@link StatusSignal#waitForUpdate(double)}.
314     * @param maxLatencySeconds The maximum amount of latency to compensate for in seconds. A negative or zero
315     *                          value disables the max latency cap. This is used to cap the contribution of
316     *                          latency compensation for stale signals, such as after the device has been
317     *                          disconnected from the CAN bus.
318     * @return Latency compensated value from the signal StatusSignal.
319     */
320    public static
321    <U extends Unit, U_PER_SEC extends PerUnit<U, TimeUnit>, MEAS extends Measure<U>, MEAS_PER_SEC extends Measure<U_PER_SEC>>
322    MEAS getLatencyCompensatedValue(StatusSignal<MEAS> signal, StatusSignal<MEAS_PER_SEC> signalSlope, double maxLatencySeconds) {
323        final var nonCompensatedSignal = signal.getValue();
324        final var changeInSignal = signalSlope.getValue();
325        double latency = signal.getTimestamp().getLatency();
326        if (maxLatencySeconds > 0.0 && latency > maxLatencySeconds) {
327            latency = maxLatencySeconds;
328        }
329        @SuppressWarnings("unchecked")
330        var retval = (MEAS)nonCompensatedSignal.plus((MEAS)changeInSignal.times(Seconds.of(latency)));
331        return retval;
332    }
333
334    /**
335     * Performs latency compensation on signal using the signalSlope and signal's latency to determine
336     * the magnitude of compensation. The caller must refresh these StatusSignals beforehand;
337     * this function only does the math required for latency compensation.
338     * <p>
339     * <b>Important</b>: The signalSlope must be the rate of change of the signal. If it is not the latency
340     * compensation may not perform as expected.
341     * <p>
342     * This compensates for up to 300ms of latency by default.
343     * <p>
344     * <b>Example</b>:
345     * double compensatedTurns = BaseStatusSignal.getLatencyCompensatedValueAsDouble(fx.getPosition(), fx.getVelocity());
346     *
347     * @param signal Signal to be latency compensated. Caller must make sure this signal is up to date
348     *               either by calling {@link StatusSignal#refresh()} or {@link StatusSignal#waitForUpdate(double)}.
349     * @param signalSlope Derivative of signal that informs compensation magnitude. Caller must make sure this
350     *                    signal is up to date either by calling {@link StatusSignal#refresh()} or
351     *                    {@link StatusSignal#waitForUpdate(double)}.
352     * @return Latency compensated value from the signal StatusSignal.
353     */
354    public static double getLatencyCompensatedValueAsDouble(BaseStatusSignal signal, BaseStatusSignal signalSlope) {
355        return getLatencyCompensatedValueAsDouble(signal, signalSlope, 0.300);
356    }
357
358    /**
359     * Performs latency compensation on signal using the signalSlope and signal's latency to determine
360     * the magnitude of compensation. The caller must refresh these StatusSignals beforehand;
361     * this function only does the math required for latency compensation.
362     * <p>
363     * <b>Important</b>: The signalSlope must be the rate of change of the signal. If it is not the latency
364     * compensation may not perform as expected.
365     * <p>
366     * <b>Example</b>:
367     * double compensatedTurns = BaseStatusSignal.getLatencyCompensatedValueAsDouble(fx.getPosition(), fx.getVelocity());
368     *
369     * @param signal Signal to be latency compensated. Caller must make sure this signal is up to date
370     *               either by calling {@link StatusSignal#refresh()} or {@link StatusSignal#waitForUpdate(double)}.
371     * @param signalSlope Derivative of signal that informs compensation magnitude. Caller must make sure this
372     *                    signal is up to date either by calling {@link StatusSignal#refresh()} or
373     *                    {@link StatusSignal#waitForUpdate(double)}.
374     * @param maxLatencySeconds The maximum amount of latency to compensate for in seconds. A negative or zero
375     *                          value disables the max latency cap. This is used to cap the contribution of
376     *                          latency compensation for stale signals, such as after the device has been
377     *                          disconnected from the CAN bus.
378     * @return Latency compensated value from the signal StatusSignal.
379     */
380    public static double getLatencyCompensatedValueAsDouble(BaseStatusSignal signal, BaseStatusSignal signalSlope, double maxLatencySeconds) {
381        final double nonCompensatedSignal = signal.getValueAsDouble();
382        final double changeInSignal = signalSlope.getValueAsDouble();
383        double latency = signal.getTimestamp().getLatency();
384        if (maxLatencySeconds > 0.0 && latency > maxLatencySeconds) {
385            latency = maxLatencySeconds;
386        }
387        return nonCompensatedSignal + (changeInSignal * latency);
388    }
389
390    /**
391     * Waits for new data on all provided signals up to timeout.
392     * This API is typically used with CANivore Bus signals as they will be synced using the
393     * CANivore Timesync feature and arrive simultaneously. Signals on a roboRIO bus cannot
394     * be synced and may require a significantly longer blocking call to receive all signals.
395     * <p>
396     * Note that CANivore Timesync requires Phoenix Pro.
397     * <p>
398     * This can also be used with a timeout of zero to refresh many signals at once, which
399     * is faster than calling refresh() on every signal. This is equivalent to calling {@link #refreshAll}.
400     * <p>
401     * If a signal arrives multiple times while waiting, such as when *not* using CANivore
402     * Timesync, the newest signal data is fetched. Additionally, if this function times out,
403     * the newest signal data is fetched for all signals (when possible). We recommend checking
404     * the individual status codes using {@link #getStatus()} when this happens.
405     *
406     * @param timeoutSeconds Maximum time to wait for new data in seconds.
407     *                       Pass zero to refresh all signals without blocking.
408     * @param signals Signals to wait for new data against
409     * @return InvalidNetwork if signals are on different CAN bus networks,
410     *         RxTimeout if it took longer than timeoutSeconds to receive all the signals,
411     *         MultiSignalNotSupported if using the roboRIO bus with more than one signal and a non-zero timeout.
412     *         An OK status code means that all signals arrived within timeoutSeconds and they are all OK.
413     *
414     *         Any other value represents the StatusCode of the first failed signal.
415     *         Call getStatus() on each signal to determine which ones failed.
416     */
417    public static StatusCode waitForAll(double timeoutSeconds, BaseStatusSignal... signals) {
418        return waitForAll(timeoutSeconds, true, signals);
419    }
420    /**
421     * Waits for new data on all provided signals up to timeout.
422     * This API is typically used with CANivore Bus signals as they will be synced using the
423     * CANivore Timesync feature and arrive simultaneously. Signals on a roboRIO bus cannot
424     * be synced and may require a significantly longer blocking call to receive all signals.
425     * <p>
426     * Note that CANivore Timesync requires Phoenix Pro.
427     * <p>
428     * This can also be used with a timeout of zero to refresh many signals at once, which
429     * is faster than calling refresh() on every signal. This is equivalent to calling {@link #refreshAll}.
430     * <p>
431     * If a signal arrives multiple times while waiting, such as when *not* using CANivore
432     * Timesync, the newest signal data is fetched. Additionally, if this function times out,
433     * the newest signal data is fetched for all signals (when possible). We recommend checking
434     * the individual status codes using {@link #getStatus()} when this happens.
435     *
436     * @param timeoutSeconds Maximum time to wait for new data in seconds.
437     *                       Pass zero to refresh all signals without blocking.
438     * @param signals List of signals to wait for new data against
439     * @return InvalidNetwork if signals are on different CAN bus networks,
440     *         RxTimeout if it took longer than timeoutSeconds to receive all the signals,
441     *         MultiSignalNotSupported if using the roboRIO bus with more than one signal and a non-zero timeout.
442     *         An OK status code means that all signals arrived within timeoutSeconds and they are all OK.
443     *
444     *         Any other value represents the StatusCode of the first failed signal.
445     *         Call getStatus() on each signal to determine which ones failed.
446     */
447    public static StatusCode waitForAll(double timeoutSeconds, List<BaseStatusSignal> signals) {
448        return waitForAll(timeoutSeconds, true, signals);
449    }
450
451    /**
452     * Waits for new data on all provided signals up to timeout.
453     * This API is typically used with CANivore Bus signals as they will be synced using the
454     * CANivore Timesync feature and arrive simultaneously. Signals on a roboRIO bus cannot
455     * be synced and may require a significantly longer blocking call to receive all signals.
456     * <p>
457     * Note that CANivore Timesync requires Phoenix Pro.
458     * <p>
459     * This can also be used with a timeout of zero to refresh many signals at once, which
460     * is faster than calling refresh() on every signal. This is equivalent to calling {@link #refreshAll}.
461     * <p>
462     * If a signal arrives multiple times while waiting, such as when *not* using CANivore
463     * Timesync, the newest signal data is fetched. Additionally, if this function times out,
464     * the newest signal data is fetched for all signals (when possible). We recommend checking
465     * the individual status codes using {@link #getStatus()} when this happens.
466     *
467     * @param timeoutSeconds Maximum time to wait for new data in seconds.
468     *                       Pass zero to refresh all signals without blocking.
469     * @param reportError Whether to report any errors to the Driver Station/stderr, defaults to true
470     * @param signals Signals to wait for new data against
471     * @return InvalidNetwork if signals are on different CAN bus networks,
472     *         RxTimeout if it took longer than timeoutSeconds to receive all the signals,
473     *         MultiSignalNotSupported if using the roboRIO bus with more than one signal and a non-zero timeout.
474     *         An OK status code means that all signals arrived within timeoutSeconds and they are all OK.
475     *
476     *         Any other value represents the StatusCode of the first failed signal.
477     *         Call getStatus() on each signal to determine which ones failed.
478     */
479    public static StatusCode waitForAll(double timeoutSeconds, boolean reportError, BaseStatusSignal... signals) {
480        return waitForAll(timeoutSeconds, reportError, Arrays.asList(signals));
481    }
482    /**
483     * Waits for new data on all provided signals up to timeout.
484     * This API is typically used with CANivore Bus signals as they will be synced using the
485     * CANivore Timesync feature and arrive simultaneously. Signals on a roboRIO bus cannot
486     * be synced and may require a significantly longer blocking call to receive all signals.
487     * <p>
488     * Note that CANivore Timesync requires Phoenix Pro.
489     * <p>
490     * This can also be used with a timeout of zero to refresh many signals at once, which
491     * is faster than calling refresh() on every signal. This is equivalent to calling {@link #refreshAll}.
492     * <p>
493     * If a signal arrives multiple times while waiting, such as when *not* using CANivore
494     * Timesync, the newest signal data is fetched. Additionally, if this function times out,
495     * the newest signal data is fetched for all signals (when possible). We recommend checking
496     * the individual status codes using {@link #getStatus()} when this happens.
497     *
498     * @param timeoutSeconds Maximum time to wait for new data in seconds.
499     *                       Pass zero to refresh all signals without blocking.
500     * @param reportError Whether to report any errors to the Driver Station/stderr, defaults to true
501     * @param signals List of signals to wait for new data against
502     * @return InvalidNetwork if signals are on different CAN bus networks,
503     *         RxTimeout if it took longer than timeoutSeconds to receive all the signals,
504     *         MultiSignalNotSupported if using the roboRIO bus with more than one signal and a non-zero timeout.
505     *         An OK status code means that all signals arrived within timeoutSeconds and they are all OK.
506     *
507     *         Any other value represents the StatusCode of the first failed signal.
508     *         Call getStatus() on each signal to determine which ones failed.
509     */
510    public static StatusCode waitForAll(double timeoutSeconds, boolean reportError, List<BaseStatusSignal> signals) {
511        return waitForAllImpl("ctre.phoenix6.BaseStatusSignal.waitForAll", timeoutSeconds, reportError, signals);
512    }
513
514    /**
515     * Performs a non-blocking refresh on all provided signals.
516     * <p>
517     * This provides a performance improvement over separately calling refresh() on each signal.
518     *
519     * @param signals Signals to refresh
520     * @return InvalidNetwork if signals are on different CAN bus networks.
521     *         An OK status code means that all signals are OK.
522     *
523     *         Any other value represents the StatusCode of the first failed signal.
524     *         Call getStatus() on each signal to determine which ones failed.
525     */
526    public static StatusCode refreshAll(BaseStatusSignal... signals) {
527        return refreshAll(true, signals);
528    }
529    /**
530     * Performs a non-blocking refresh on all provided signals.
531     * <p>
532     * This provides a performance improvement over separately calling refresh() on each signal.
533     *
534     * @param signals List of signals to refresh
535     * @return InvalidNetwork if signals are on different CAN bus networks.
536     *         An OK status code means that all signals are OK.
537     *
538     *         Any other value represents the StatusCode of the first failed signal.
539     *         Call getStatus() on each signal to determine which ones failed.
540     */
541    public static StatusCode refreshAll(List<BaseStatusSignal> signals) {
542        return refreshAll(true, signals);
543    }
544
545    /**
546     * Performs a non-blocking refresh on all provided signals.
547     * <p>
548     * This provides a performance improvement over separately calling refresh() on each signal.
549     *
550     * @param reportError Whether to report any errors to the Driver Station/stderr, defaults to true
551     * @param signals Signals to refresh
552     * @return InvalidNetwork if signals are on different CAN bus networks.
553     *         An OK status code means that all signals are OK.
554     *
555     *         Any other value represents the StatusCode of the first failed signal.
556     *         Call getStatus() on each signal to determine which ones failed.
557     */
558    public static StatusCode refreshAll(boolean reportError, BaseStatusSignal... signals) {
559        return refreshAll(reportError, Arrays.asList(signals));
560    }
561    /**
562     * Performs a non-blocking refresh on all provided signals.
563     * <p>
564     * This provides a performance improvement over separately calling refresh() on each signal.
565     *
566     * @param reportError Whether to report any errors to the Driver Station/stderr, defaults to true
567     * @param signals List of signals to refresh
568     * @return InvalidNetwork if signals are on different CAN bus networks.
569     *         An OK status code means that all signals are OK.
570     *
571     *         Any other value represents the StatusCode of the first failed signal.
572     *         Call getStatus() on each signal to determine which ones failed.
573     */
574    public static StatusCode refreshAll(boolean reportError, List<BaseStatusSignal> signals) {
575        return waitForAllImpl("ctre.phoenix6.BaseStatusSignal.refreshAll", 0, reportError, signals);
576    }
577
578    /**
579     * Checks if all signals have an OK error code.
580     *
581     * @param signals Signals to check error code of
582     * @return True if all are good, false otherwise
583     */
584    public static boolean isAllGood(BaseStatusSignal... signals) {
585        for (BaseStatusSignal sig : signals) {
586            if (!sig.getStatus().isOK()) {
587                return false;
588            }
589        }
590        return true;
591    }
592
593    /**
594     * Checks if all signals have an OK error code.
595     *
596     * @param signals List of signals to check error code of
597     * @return True if all are good, false otherwise
598     */
599    public static boolean isAllGood(List<BaseStatusSignal> signals) {
600        for (BaseStatusSignal sig : signals) {
601            if (!sig.getStatus().isOK()) {
602                return false;
603            }
604        }
605        return true;
606    }
607
608    /**
609     * Sets the update frequency of all specified status signals to the provided common frequency.
610     * <p>
611     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
612     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
613     * supported and will be promoted up to the next highest supported frequency.
614     * <p>
615     * If other StatusSignals in the same status frame have been set to an update frequency,
616     * the fastest requested update frequency will be applied to the frame.
617     * <p>
618     * This will wait up to 0.100 seconds (100ms) for each signal.
619     *
620     * @param frequencyHz Rate to publish the signal in Hz
621     * @param signals Signals to apply the update frequency to
622     * @return Status code of the first failed update frequency set call, or OK if all succeeded
623     */
624    public static StatusCode setUpdateFrequencyForAll(double frequencyHz, BaseStatusSignal... signals) {
625        return setUpdateFrequencyForAll(frequencyHz, Arrays.asList(signals));
626    }
627
628    /**
629     * Sets the update frequency of all specified status signals to the provided common frequency.
630     * <p>
631     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
632     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
633     * supported and will be promoted up to the next highest supported frequency.
634     * <p>
635     * If other StatusSignals in the same status frame have been set to an update frequency,
636     * the fastest requested update frequency will be applied to the frame.
637     * <p>
638     * This will wait up to 0.100 seconds (100ms) for each signal.
639     *
640     * @param frequencyHz Rate to publish the signal in Hz
641     * @param signals List of signals to apply the update frequency to
642     * @return Status code of the first failed update frequency set call, or OK if all succeeded
643     */
644    public static StatusCode setUpdateFrequencyForAll(double frequencyHz, List<BaseStatusSignal> signals) {
645        if (signals.isEmpty()) {
646            return StatusCode.OK;
647        }
648
649        StatusSignalJNI[] toSet = new StatusSignalJNI[signals.size()];
650        for (int i = 0; i < signals.size(); ++i) {
651            toSet[i] = signals.get(i).jni;
652        }
653
654        StatusCode retval = StatusCode.valueOf(
655            StatusSignalJNI.JNI_SetUpdateFrequencyForAll(frequencyHz, toSet, 0.100)
656        );
657        if (!retval.isOK()) {
658            ErrorReportingJNI.reportStatusCode(
659                retval.value,
660                "ctre.phoenix6.BaseStatusSignal.setUpdateFrequencyForAll"
661            );
662        }
663        return retval;
664    }
665
666    /**
667     * Sets the update frequency of all specified status signals to the provided common frequency.
668     * <p>
669     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
670     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
671     * supported and will be promoted up to the next highest supported frequency.
672     * <p>
673     * If other StatusSignals in the same status frame have been set to an update frequency,
674     * the fastest requested update frequency will be applied to the frame.
675     * <p>
676     * This will wait up to 0.100 seconds (100ms) for each signal.
677     *
678     * @param frequency Rate to publish the signal
679     * @param signals Signals to apply the update frequency to
680     * @return Status code of the first failed update frequency set call, or OK if all succeeded
681     */
682    public static StatusCode setUpdateFrequencyForAll(Frequency frequency, BaseStatusSignal... signals) {
683        return setUpdateFrequencyForAll(frequency.in(Hertz), signals);
684    }
685
686    /**
687     * Sets the update frequency of all specified status signals to the provided common frequency.
688     * <p>
689     * A frequency of 0 Hz will turn off the signal. Otherwise, the minimum supported signal
690     * frequency is 4 Hz, and the maximum is 1000 Hz. Additionally, some update frequencies are not
691     * supported and will be promoted up to the next highest supported frequency.
692     * <p>
693     * If other StatusSignals in the same status frame have been set to an update frequency,
694     * the fastest requested update frequency will be applied to the frame.
695     * <p>
696     * This will wait up to 0.100 seconds (100ms) for each signal.
697     *
698     * @param frequency Rate to publish the signal
699     * @param signals List of signals to apply the update frequency to
700     * @return Status code of the first failed update frequency set call, or OK if all succeeded
701     */
702    public static StatusCode setUpdateFrequencyForAll(Frequency frequency, List<BaseStatusSignal> signals) {
703        return setUpdateFrequencyForAll(frequency.in(Hertz), signals);
704    }
705
706    protected final void updateUnits(int unitsKey) {
707        if (_unitsKey != unitsKey && _unitStrings != null && _unitStrings.containsKey(unitsKey)) {
708            units = _unitStrings.get(unitsKey);
709            _unitsKey = unitsKey;
710        }
711    }
712
713    protected final void refreshValue(boolean waitForSignal, double timeout, boolean reportError) {
714        _reportIfOldFunc.run();
715
716        if (waitForSignal) {
717            error = StatusCode.valueOf(jni.JNI_WaitForSignal(timeout));
718        } else {
719            error = StatusCode.valueOf(jni.JNI_RefreshSignal(timeout));
720        }
721        baseValue = jni.value;
722        timestamps.update(
723            jni.swtimeStampSeconds, TimestampSource.System, true,
724            jni.hwtimeStampSeconds, TimestampSource.CANivore, true,
725            jni.ecutimeStampSeconds, TimestampSource.Device, jni.ecutimeStampSeconds != 0.0
726        );
727        updateUnits(jni.unitsKey);
728
729        if (reportError && !this.error.isOK()) {
730            String device = this.deviceIdentifier.toString() + " Status Signal " + this.name;
731            ErrorReportingJNI.reportStatusCode(this.error.value, device);
732        }
733    }
734
735    private static StatusCode waitForAllImpl(String location, double timeoutSeconds, boolean reportError, List<BaseStatusSignal> signals) {
736        if (signals.isEmpty()) {
737            /* We don't have any signals to wait for, so return early */
738            return StatusCode.OK;
739        }
740
741        CANBus network = signals.get(0).deviceIdentifier.getNetwork();
742        StatusSignalJNI[] toGet = new StatusSignalJNI[signals.size()];
743        for (int i = 0; i < signals.size(); ++i) {
744            var sig = signals.get(i);
745            if (i != 0 && !sig.deviceIdentifier.getNetwork().equals(network)) {
746                /* Networks don't match, return early */
747                for (var s : signals) {
748                    s.error = StatusCode.InvalidNetwork;
749                }
750                ErrorReportingJNI.reportStatusCode(StatusCode.InvalidNetwork.value, location);
751                return StatusCode.InvalidNetwork;
752            }
753            toGet[i] = sig.jni;
754        }
755
756        /* Report if any device firmware versions are too old */
757        for (var signal : signals) {
758            signal._reportIfOldFunc.run();
759        }
760
761        /* Now wait for all the signals */
762        int err = StatusSignalJNI.JNI_WaitForAll(network.getNameUTF8Bytes(), timeoutSeconds, toGet);
763        for (int i = 0; i < signals.size(); ++i) {
764            var sig = signals.get(i);
765            sig.error = StatusCode.valueOf(toGet[i].statusCode);
766            sig.baseValue = toGet[i].value;
767            sig.timestamps.update(
768                toGet[i].swtimeStampSeconds, TimestampSource.System, true,
769                toGet[i].hwtimeStampSeconds, TimestampSource.CANivore, true,
770                toGet[i].ecutimeStampSeconds, TimestampSource.Device, toGet[i].ecutimeStampSeconds != 0.0
771            );
772            sig.updateUnits(toGet[i].unitsKey);
773        }
774
775        /* error reporting */
776        StatusCode retval = StatusCode.valueOf(err);
777        if (reportError && !retval.isOK()) {
778            for (var signal : signals) {
779                if (!signal.error.isOK()) {
780                    String sigLocation = signal.deviceIdentifier.toString() + " Status Signal " + signal.name;
781                    ErrorReportingJNI.reportStatusCode(signal.error.value, sigLocation);
782                }
783            }
784            ErrorReportingJNI.reportStatusCode(retval.value, location);
785        }
786        return StatusCode.valueOf(err);
787    }
788};