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.controls;
008
009import com.ctre.phoenix6.CANBus;
010import com.ctre.phoenix6.StatusCode;
011import com.ctre.phoenix6.controls.jni.ControlJNI;
012import com.ctre.phoenix6.hardware.traits.*;
013
014import edu.wpi.first.units.*;
015import edu.wpi.first.units.measure.*;
016import static edu.wpi.first.units.Units.*;
017
018import java.util.HashMap;
019import java.util.Map;
020
021/**
022 * Requests Motion Magic® to target a final velocity using a motion profile. 
023 * This allows smooth transitions between velocity set points.  Users can
024 * optionally provide a duty cycle feedforward.
025 * <p>
026 * Motion Magic® Velocity produces a motion profile in real-time while attempting to honor the specified
027 * Acceleration and (optional) Jerk.  This control mode does not use the CruiseVelocity, Expo_kV, or Expo_kA
028 * configs.
029 * <p>
030 * If the specified acceleration is zero, the Acceleration under Motion Magic® configuration parameter is used
031 * instead.  This allows for runtime adjustment of acceleration for advanced users.  Jerk is also specified in
032 * the Motion Magic® persistent configuration values.  If Jerk is set to zero, Motion Magic® will produce a
033 * trapezoidal acceleration profile.
034 * <p>
035 * Target velocity can also be changed on-the-fly and Motion Magic® will do its best to adjust the profile. 
036 * This control mode is duty cycle based, so relevant closed-loop gains will use fractional duty cycle for the
037 * numerator:  +1.0 represents full forward output.
038 */
039public final class MotionMagicVelocityDutyCycle implements ControlRequest, Cloneable {
040    /**
041     * Target velocity to drive toward in rotations per second.  This can be changed
042     * on-the fly.
043     * 
044     * <ul>
045     *   <li> Units: rotations per second
046     * </ul>
047     * 
048     */
049    public double Velocity;
050    /**
051     * This is the absolute Acceleration to use generating the profile.  If this
052     * parameter is zero, the Acceleration persistent configuration parameter is
053     * used instead. Acceleration is in rotations per second squared.  If nonzero,
054     * the signage does not matter as the absolute value is used.
055     * 
056     * <ul>
057     *   <li> Units: rotations per second²
058     * </ul>
059     * 
060     */
061    public double Acceleration = 0.0;
062    /**
063     * Set to true to use FOC commutation (requires Phoenix Pro), which increases
064     * peak power by ~15% on supported devices (see {@link SupportsFOC}). Set to
065     * false to use trapezoidal commutation.
066     * <p>
067     * FOC improves motor performance by leveraging torque (current) control. 
068     * However, this may be inconvenient for applications that require specifying
069     * duty cycle or voltage.  CTR-Electronics has developed a hybrid method that
070     * combines the performances gains of FOC while still allowing applications to
071     * provide duty cycle or voltage demand.  This not to be confused with simple
072     * sinusoidal control or phase voltage control which lacks the performance
073     * gains.
074     */
075    public boolean EnableFOC = true;
076    /**
077     * Feedforward to apply in fractional units between -1 and +1. This is added to
078     * the output of the onboard feedforward terms.
079     * 
080     * <ul>
081     *   <li> Units: fractional
082     * </ul>
083     * 
084     */
085    public double FeedForward = 0.0;
086    /**
087     * Select which gains are applied by selecting the slot.  Use the configuration
088     * api to set the gain values for the selected slot before enabling this
089     * feature. Slot must be within [0,2].
090     */
091    public int Slot = 0;
092    /**
093     * Set to true to static-brake the rotor when output is zero (or within
094     * deadband).  Set to false to use the NeutralMode configuration setting
095     * (default). This flag exists to provide the fundamental behavior of this
096     * control when output is zero, which is to provide 0V to the motor.
097     */
098    public boolean OverrideBrakeDurNeutral = false;
099    /**
100     * Set to true to force forward limiting.  This allows users to use other limit
101     * switch sensors connected to robot controller.  This also allows use of active
102     * sensors that require external power.
103     */
104    public boolean LimitForwardMotion = false;
105    /**
106     * Set to true to force reverse limiting.  This allows users to use other limit
107     * switch sensors connected to robot controller.  This also allows use of active
108     * sensors that require external power.
109     */
110    public boolean LimitReverseMotion = false;
111    /**
112     * Set to true to ignore hardware limit switches and the LimitForwardMotion and
113     * LimitReverseMotion parameters, instead allowing motion.
114     * <p>
115     * This can be useful on mechanisms such as an intake/feeder, where a limit
116     * switch stops motion while intaking but should be ignored when feeding to a
117     * shooter.
118     * <p>
119     * The hardware limit faults and Forward/ReverseLimit signals will still report
120     * the values of the limit switches regardless of this parameter.
121     */
122    public boolean IgnoreHardwareLimits = false;
123    /**
124     * Set to true to ignore software limits, instead allowing motion.
125     * <p>
126     * This can be useful when calibrating the zero point of a mechanism such as an
127     * elevator.
128     * <p>
129     * The software limit faults will still report the values of the software limits
130     * regardless of this parameter.
131     */
132    public boolean IgnoreSoftwareLimits = false;
133    /**
134     * Set to true to delay applying this control request until a timesync boundary
135     * (requires Phoenix Pro and CANivore). This eliminates the impact of
136     * nondeterministic network delays in exchange for a larger but deterministic
137     * control latency.
138     * <p>
139     * This requires setting the ControlTimesyncFreqHz config in MotorOutputConfigs.
140     * Additionally, when this is enabled, the UpdateFreqHz of this request should
141     * be set to 0 Hz.
142     */
143    public boolean UseTimesync = false;
144
145    /**
146     * The frequency at which this control will update.
147     * This is designated in Hertz, with a minimum of 20 Hz
148     * (every 50 ms) and a maximum of 1000 Hz (every 1 ms).
149     * Some update frequencies are not supported and will be
150     * promoted up to the next highest supported frequency.
151     * <p>
152     * If this field is set to 0 Hz, the control request will
153     * be sent immediately as a one-shot frame. This may be useful
154     * for advanced applications that require outputs to be
155     * synchronized with data acquisition. In this case, we
156     * recommend not exceeding 50 ms between control calls.
157     */
158    public double UpdateFreqHz = 100;
159
160    /**
161     * Requests Motion Magic® to target a final velocity using a motion profile. 
162     * This allows smooth transitions between velocity set points.  Users can
163     * optionally provide a duty cycle feedforward.
164     * <p>
165     * Motion Magic® Velocity produces a motion profile in real-time while
166     * attempting to honor the specified Acceleration and (optional) Jerk.  This
167     * control mode does not use the CruiseVelocity, Expo_kV, or Expo_kA configs.
168     * <p>
169     * If the specified acceleration is zero, the Acceleration under Motion Magic®
170     * configuration parameter is used instead.  This allows for runtime adjustment
171     * of acceleration for advanced users.  Jerk is also specified in the Motion
172     * Magic® persistent configuration values.  If Jerk is set to zero, Motion
173     * Magic® will produce a trapezoidal acceleration profile.
174     * <p>
175     * Target velocity can also be changed on-the-fly and Motion Magic® will do its
176     * best to adjust the profile.  This control mode is duty cycle based, so
177     * relevant closed-loop gains will use fractional duty cycle for the numerator: 
178     * +1.0 represents full forward output.
179     * 
180     * @param Velocity Target velocity to drive toward in rotations per second. 
181     *                 This can be changed on-the fly.
182     */
183    public MotionMagicVelocityDutyCycle(double Velocity) {
184        this.Velocity = Velocity;
185    }
186
187    /**
188     * Requests Motion Magic® to target a final velocity using a motion profile. 
189     * This allows smooth transitions between velocity set points.  Users can
190     * optionally provide a duty cycle feedforward.
191     * <p>
192     * Motion Magic® Velocity produces a motion profile in real-time while
193     * attempting to honor the specified Acceleration and (optional) Jerk.  This
194     * control mode does not use the CruiseVelocity, Expo_kV, or Expo_kA configs.
195     * <p>
196     * If the specified acceleration is zero, the Acceleration under Motion Magic®
197     * configuration parameter is used instead.  This allows for runtime adjustment
198     * of acceleration for advanced users.  Jerk is also specified in the Motion
199     * Magic® persistent configuration values.  If Jerk is set to zero, Motion
200     * Magic® will produce a trapezoidal acceleration profile.
201     * <p>
202     * Target velocity can also be changed on-the-fly and Motion Magic® will do its
203     * best to adjust the profile.  This control mode is duty cycle based, so
204     * relevant closed-loop gains will use fractional duty cycle for the numerator: 
205     * +1.0 represents full forward output.
206     * 
207     * @param Velocity Target velocity to drive toward in rotations per second. 
208     *                 This can be changed on-the fly.
209     */
210    public MotionMagicVelocityDutyCycle(AngularVelocity Velocity) {
211        this(Velocity.in(RotationsPerSecond));
212    }
213
214    @Override
215    public String getName() {
216        return "MotionMagicVelocityDutyCycle";
217    }
218
219    @Override
220    public String toString() {
221        String ss = "Control: MotionMagicVelocityDutyCycle\n";
222        ss += "    Velocity: " + Velocity + " rotations per second" + "\n";
223        ss += "    Acceleration: " + Acceleration + " rotations per second²" + "\n";
224        ss += "    EnableFOC: " + EnableFOC + "\n";
225        ss += "    FeedForward: " + FeedForward + " fractional" + "\n";
226        ss += "    Slot: " + Slot + "\n";
227        ss += "    OverrideBrakeDurNeutral: " + OverrideBrakeDurNeutral + "\n";
228        ss += "    LimitForwardMotion: " + LimitForwardMotion + "\n";
229        ss += "    LimitReverseMotion: " + LimitReverseMotion + "\n";
230        ss += "    IgnoreHardwareLimits: " + IgnoreHardwareLimits + "\n";
231        ss += "    IgnoreSoftwareLimits: " + IgnoreSoftwareLimits + "\n";
232        ss += "    UseTimesync: " + UseTimesync + "\n";
233        return ss;
234    }
235
236    @Override
237    public StatusCode sendRequest(CANBus network, int deviceHash) {
238        return StatusCode.valueOf(ControlJNI.JNI_RequestControlMotionMagicVelocityDutyCycle(
239                network.getNameUTF8Bytes(), deviceHash, UpdateFreqHz, Velocity, Acceleration, EnableFOC, FeedForward, Slot, OverrideBrakeDurNeutral, LimitForwardMotion, LimitReverseMotion, IgnoreHardwareLimits, IgnoreSoftwareLimits, UseTimesync));
240    }
241
242    /**
243     * Gets information about this control request.
244     *
245     * @return Map of control parameter names and corresponding applied values
246     */
247    @Override
248    public Map<String, String> getControlInfo() {
249        var controlInfo = new HashMap<String, String>();
250        controlInfo.put("Name", getName());
251        controlInfo.put("Velocity", String.valueOf(this.Velocity));
252        controlInfo.put("Acceleration", String.valueOf(this.Acceleration));
253        controlInfo.put("EnableFOC", String.valueOf(this.EnableFOC));
254        controlInfo.put("FeedForward", String.valueOf(this.FeedForward));
255        controlInfo.put("Slot", String.valueOf(this.Slot));
256        controlInfo.put("OverrideBrakeDurNeutral", String.valueOf(this.OverrideBrakeDurNeutral));
257        controlInfo.put("LimitForwardMotion", String.valueOf(this.LimitForwardMotion));
258        controlInfo.put("LimitReverseMotion", String.valueOf(this.LimitReverseMotion));
259        controlInfo.put("IgnoreHardwareLimits", String.valueOf(this.IgnoreHardwareLimits));
260        controlInfo.put("IgnoreSoftwareLimits", String.valueOf(this.IgnoreSoftwareLimits));
261        controlInfo.put("UseTimesync", String.valueOf(this.UseTimesync));
262        return controlInfo;
263    }
264    
265    /**
266     * Modifies this Control Request's Velocity parameter and returns itself for
267     * method-chaining and easier to use request API.
268     * <p>
269     * Target velocity to drive toward in rotations per second.  This can be changed
270     * on-the fly.
271     * 
272     * <ul>
273     *   <li> Units: rotations per second
274     * </ul>
275     * 
276     *
277     * @param newVelocity Parameter to modify
278     * @return Itself
279     */
280    public MotionMagicVelocityDutyCycle withVelocity(double newVelocity) {
281        Velocity = newVelocity;
282        return this;
283    }
284    
285    /**
286     * Modifies this Control Request's Velocity parameter and returns itself for
287     * method-chaining and easier to use request API.
288     * <p>
289     * Target velocity to drive toward in rotations per second.  This can be changed
290     * on-the fly.
291     * 
292     * <ul>
293     *   <li> Units: rotations per second
294     * </ul>
295     * 
296     *
297     * @param newVelocity Parameter to modify
298     * @return Itself
299     */
300    public MotionMagicVelocityDutyCycle withVelocity(AngularVelocity newVelocity) {
301        Velocity = newVelocity.in(RotationsPerSecond);
302        return this;
303    }
304    
305    /**
306     * Helper method to get this Control Request's Velocity parameter converted
307     * to a unit type. If not using the Java units library, {@link #Velocity}
308     * can be accessed directly instead.
309     * <p>
310     * Target velocity to drive toward in rotations per second.  This can be changed
311     * on-the fly.
312     * 
313     * <ul>
314     *   <li> Units: rotations per second
315     * </ul>
316     * 
317     *
318     * @return Velocity
319     */
320    public AngularVelocity getVelocityMeasure() {
321        return RotationsPerSecond.of(Velocity);
322    }
323    
324    /**
325     * Modifies this Control Request's Acceleration parameter and returns itself for
326     * method-chaining and easier to use request API.
327     * <p>
328     * This is the absolute Acceleration to use generating the profile.  If this
329     * parameter is zero, the Acceleration persistent configuration parameter is
330     * used instead. Acceleration is in rotations per second squared.  If nonzero,
331     * the signage does not matter as the absolute value is used.
332     * 
333     * <ul>
334     *   <li> Units: rotations per second²
335     * </ul>
336     * 
337     *
338     * @param newAcceleration Parameter to modify
339     * @return Itself
340     */
341    public MotionMagicVelocityDutyCycle withAcceleration(double newAcceleration) {
342        Acceleration = newAcceleration;
343        return this;
344    }
345    
346    /**
347     * Modifies this Control Request's Acceleration parameter and returns itself for
348     * method-chaining and easier to use request API.
349     * <p>
350     * This is the absolute Acceleration to use generating the profile.  If this
351     * parameter is zero, the Acceleration persistent configuration parameter is
352     * used instead. Acceleration is in rotations per second squared.  If nonzero,
353     * the signage does not matter as the absolute value is used.
354     * 
355     * <ul>
356     *   <li> Units: rotations per second²
357     * </ul>
358     * 
359     *
360     * @param newAcceleration Parameter to modify
361     * @return Itself
362     */
363    public MotionMagicVelocityDutyCycle withAcceleration(AngularAcceleration newAcceleration) {
364        Acceleration = newAcceleration.in(RotationsPerSecondPerSecond);
365        return this;
366    }
367    
368    /**
369     * Helper method to get this Control Request's Acceleration parameter converted
370     * to a unit type. If not using the Java units library, {@link #Acceleration}
371     * can be accessed directly instead.
372     * <p>
373     * This is the absolute Acceleration to use generating the profile.  If this
374     * parameter is zero, the Acceleration persistent configuration parameter is
375     * used instead. Acceleration is in rotations per second squared.  If nonzero,
376     * the signage does not matter as the absolute value is used.
377     * 
378     * <ul>
379     *   <li> Units: rotations per second²
380     * </ul>
381     * 
382     *
383     * @return Acceleration
384     */
385    public AngularAcceleration getAccelerationMeasure() {
386        return RotationsPerSecondPerSecond.of(Acceleration);
387    }
388    
389    /**
390     * Modifies this Control Request's EnableFOC parameter and returns itself for
391     * method-chaining and easier to use request API.
392     * <p>
393     * Set to true to use FOC commutation (requires Phoenix Pro), which increases
394     * peak power by ~15% on supported devices (see {@link SupportsFOC}). Set to
395     * false to use trapezoidal commutation.
396     * <p>
397     * FOC improves motor performance by leveraging torque (current) control. 
398     * However, this may be inconvenient for applications that require specifying
399     * duty cycle or voltage.  CTR-Electronics has developed a hybrid method that
400     * combines the performances gains of FOC while still allowing applications to
401     * provide duty cycle or voltage demand.  This not to be confused with simple
402     * sinusoidal control or phase voltage control which lacks the performance
403     * gains.
404     *
405     * @param newEnableFOC Parameter to modify
406     * @return Itself
407     */
408    public MotionMagicVelocityDutyCycle withEnableFOC(boolean newEnableFOC) {
409        EnableFOC = newEnableFOC;
410        return this;
411    }
412    
413    /**
414     * Modifies this Control Request's FeedForward parameter and returns itself for
415     * method-chaining and easier to use request API.
416     * <p>
417     * Feedforward to apply in fractional units between -1 and +1. This is added to
418     * the output of the onboard feedforward terms.
419     * 
420     * <ul>
421     *   <li> Units: fractional
422     * </ul>
423     * 
424     *
425     * @param newFeedForward Parameter to modify
426     * @return Itself
427     */
428    public MotionMagicVelocityDutyCycle withFeedForward(double newFeedForward) {
429        FeedForward = newFeedForward;
430        return this;
431    }
432    
433    /**
434     * Modifies this Control Request's Slot parameter and returns itself for
435     * method-chaining and easier to use request API.
436     * <p>
437     * Select which gains are applied by selecting the slot.  Use the configuration
438     * api to set the gain values for the selected slot before enabling this
439     * feature. Slot must be within [0,2].
440     *
441     * @param newSlot Parameter to modify
442     * @return Itself
443     */
444    public MotionMagicVelocityDutyCycle withSlot(int newSlot) {
445        Slot = newSlot;
446        return this;
447    }
448    
449    /**
450     * Modifies this Control Request's OverrideBrakeDurNeutral parameter and returns itself for
451     * method-chaining and easier to use request API.
452     * <p>
453     * Set to true to static-brake the rotor when output is zero (or within
454     * deadband).  Set to false to use the NeutralMode configuration setting
455     * (default). This flag exists to provide the fundamental behavior of this
456     * control when output is zero, which is to provide 0V to the motor.
457     *
458     * @param newOverrideBrakeDurNeutral Parameter to modify
459     * @return Itself
460     */
461    public MotionMagicVelocityDutyCycle withOverrideBrakeDurNeutral(boolean newOverrideBrakeDurNeutral) {
462        OverrideBrakeDurNeutral = newOverrideBrakeDurNeutral;
463        return this;
464    }
465    
466    /**
467     * Modifies this Control Request's LimitForwardMotion parameter and returns itself for
468     * method-chaining and easier to use request API.
469     * <p>
470     * Set to true to force forward limiting.  This allows users to use other limit
471     * switch sensors connected to robot controller.  This also allows use of active
472     * sensors that require external power.
473     *
474     * @param newLimitForwardMotion Parameter to modify
475     * @return Itself
476     */
477    public MotionMagicVelocityDutyCycle withLimitForwardMotion(boolean newLimitForwardMotion) {
478        LimitForwardMotion = newLimitForwardMotion;
479        return this;
480    }
481    
482    /**
483     * Modifies this Control Request's LimitReverseMotion parameter and returns itself for
484     * method-chaining and easier to use request API.
485     * <p>
486     * Set to true to force reverse limiting.  This allows users to use other limit
487     * switch sensors connected to robot controller.  This also allows use of active
488     * sensors that require external power.
489     *
490     * @param newLimitReverseMotion Parameter to modify
491     * @return Itself
492     */
493    public MotionMagicVelocityDutyCycle withLimitReverseMotion(boolean newLimitReverseMotion) {
494        LimitReverseMotion = newLimitReverseMotion;
495        return this;
496    }
497    
498    /**
499     * Modifies this Control Request's IgnoreHardwareLimits parameter and returns itself for
500     * method-chaining and easier to use request API.
501     * <p>
502     * Set to true to ignore hardware limit switches and the LimitForwardMotion and
503     * LimitReverseMotion parameters, instead allowing motion.
504     * <p>
505     * This can be useful on mechanisms such as an intake/feeder, where a limit
506     * switch stops motion while intaking but should be ignored when feeding to a
507     * shooter.
508     * <p>
509     * The hardware limit faults and Forward/ReverseLimit signals will still report
510     * the values of the limit switches regardless of this parameter.
511     *
512     * @param newIgnoreHardwareLimits Parameter to modify
513     * @return Itself
514     */
515    public MotionMagicVelocityDutyCycle withIgnoreHardwareLimits(boolean newIgnoreHardwareLimits) {
516        IgnoreHardwareLimits = newIgnoreHardwareLimits;
517        return this;
518    }
519    
520    /**
521     * Modifies this Control Request's IgnoreSoftwareLimits parameter and returns itself for
522     * method-chaining and easier to use request API.
523     * <p>
524     * Set to true to ignore software limits, instead allowing motion.
525     * <p>
526     * This can be useful when calibrating the zero point of a mechanism such as an
527     * elevator.
528     * <p>
529     * The software limit faults will still report the values of the software limits
530     * regardless of this parameter.
531     *
532     * @param newIgnoreSoftwareLimits Parameter to modify
533     * @return Itself
534     */
535    public MotionMagicVelocityDutyCycle withIgnoreSoftwareLimits(boolean newIgnoreSoftwareLimits) {
536        IgnoreSoftwareLimits = newIgnoreSoftwareLimits;
537        return this;
538    }
539    
540    /**
541     * Modifies this Control Request's UseTimesync parameter and returns itself for
542     * method-chaining and easier to use request API.
543     * <p>
544     * Set to true to delay applying this control request until a timesync boundary
545     * (requires Phoenix Pro and CANivore). This eliminates the impact of
546     * nondeterministic network delays in exchange for a larger but deterministic
547     * control latency.
548     * <p>
549     * This requires setting the ControlTimesyncFreqHz config in MotorOutputConfigs.
550     * Additionally, when this is enabled, the UpdateFreqHz of this request should
551     * be set to 0 Hz.
552     *
553     * @param newUseTimesync Parameter to modify
554     * @return Itself
555     */
556    public MotionMagicVelocityDutyCycle withUseTimesync(boolean newUseTimesync) {
557        UseTimesync = newUseTimesync;
558        return this;
559    }
560
561    /**
562     * Sets the frequency at which this control will update.
563     * This is designated in Hertz, with a minimum of 20 Hz
564     * (every 50 ms) and a maximum of 1000 Hz (every 1 ms).
565     * Some update frequencies are not supported and will be
566     * promoted up to the next highest supported frequency.
567     * <p>
568     * If this field is set to 0 Hz, the control request will
569     * be sent immediately as a one-shot frame. This may be useful
570     * for advanced applications that require outputs to be
571     * synchronized with data acquisition. In this case, we
572     * recommend not exceeding 50 ms between control calls.
573     *
574     * @param newUpdateFreqHz Parameter to modify
575     * @return Itself
576     */
577    @Override
578    public MotionMagicVelocityDutyCycle withUpdateFreqHz(double newUpdateFreqHz) {
579        UpdateFreqHz = newUpdateFreqHz;
580        return this;
581    }
582
583    /**
584     * Sets the frequency at which this control will update.
585     * This is designated in Hertz, with a minimum of 20 Hz
586     * (every 50 ms) and a maximum of 1000 Hz (every 1 ms).
587     * Some update frequencies are not supported and will be
588     * promoted up to the next highest supported frequency.
589     * <p>
590     * If this field is set to 0 Hz, the control request will
591     * be sent immediately as a one-shot frame. This may be useful
592     * for advanced applications that require outputs to be
593     * synchronized with data acquisition. In this case, we
594     * recommend not exceeding 50 ms between control calls.
595     *
596     * @param newUpdateFreqHz Parameter to modify
597     * @return Itself
598     */
599    @Override
600    public MotionMagicVelocityDutyCycle withUpdateFreqHz(Frequency newUpdateFreqHz) {
601        UpdateFreqHz = newUpdateFreqHz.in(Hertz);
602        return this;
603    }
604
605    @Override
606    public MotionMagicVelocityDutyCycle clone() {
607        try {
608            return (MotionMagicVelocityDutyCycle)super.clone();
609        } catch (CloneNotSupportedException ex) {
610            /* this should never happen */
611            throw new RuntimeException(ex);
612        }
613    }
614}
615