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