mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-06-21 01:01:43 +00:00
[wpiunits] Add subproject for a Java typesafe unit system (#5371)
# Background
Unit safety has always been a problem in WPILib. Any value corresponding to a physical measurement, such as current draw or distance traveled, is represented by a bare number with no unit tied to it; it's up to the programmer to know what units they're working and take care to remember that while working on their robot program. This leads to bugs when programmers accidentally mix units without knowing, or measure something (such as a wheel diameter) in one unit and program using another. `wpiunits` is intended to eliminate that class of bugs.
Another source of friction is the controllers and models in `wpimath` that expect all inputs to be in terms of SI units (meter, kilogram, and so on), while most FRC teams are US-based and most commonly use imperial units. wpimath does a good job of noting unit types in method names and argument names; however, it still relies on users properly converting values (and knowing they even have to do so).
# API
There are really only two core classes in this library: `Unit` and `Measure`. A `Unit` represents some dimension like distance or time. `Unit` is subclassed to define specific dimensions (eg `Distance` and `Time`) and those subclasses are instantiated to defined particular units in those dimensions, such as `Meters` and `Feet` being instances of the `Distance` class.
A `Measure` is a value tied to a particular dimension like distance and knows what unit that value is tied to. `Measure` has two implementations - one immutable and one mutable. The `Measure` interface only defines *read-only* operations; any API working with measurements should use the interface. The default implementation is `ImmutableMeasure`, which only implements those read-only operations and is useful for tracking constants. `MutableMeasure` also adds some methods that will allow for mutation of its internal state; this class is intended for use for things like sensors and controllers that track internal state and don't want to allocate new `Measure` objects every time something like `myEncoder.getDistance()` is called. However, the APIs for those methods should still only expose the read-only `Measure` interface so users can't (without casting or reflection) change the internal values.
A `Units` class provides convenient definitions for most of the commonly used unit types, such as `Meters`, `Feet`, and `Milliseconds`. I recommend static importing these units eg `import static edu.wpi.first.units.Units.Meters`) so they can be used like `Meters.of(1.234)` instead of `Units.Meters.of(1.234)`
# Examples
These examples are admittedly contrived. Users shouldn't be interacting much with measure objects themselves, since wpimath and wpilibj classes will be updated to support working with them; users will often just have to take a `Measure` output from one place (such as an encoder) and feed it as input to something else (such as a PID controller or kinematics model)
```java
// Using raw units
Encoder encoder = ...
int kPulsesPerRev = 2048;
double kWheelDiameterMeters = Units.inchesToMeters(6);
double kGearRatio = 10.86;
// always have to remember this encoder will output in meters!
encoder.setDistancePerPulse(kWheelDiameterMeters * Math.PI / (kGearRatio * kPulsesPerRev));
Command driveDistance(double distance) {
// have to know the distance argument needs to be in meters!
return run(this::driveStraight).until(() -> encoder.getDistance() >= distance);
}
// Oops! This will go 16 feet, not 5!
Command driveFiveFeet = driveDistance(5);
Command driveOneMeter = driveDistance(1);
```
```java
// Using wpiunits
Encoder encoder = ...
int kPulsesPerRev = 2048;
Measure<Distance> kWheelDiameter = Inches.of(6);
double kGearRatio = 10.86;
encoder.setDistancePerPulse(kWheelDiameter.times(Math.PI).divide(kGearRatio * kPulsesPerRev));
Command driveDistance(Measure<Distance> distance) {
// Measure#gte automatically handles unit conversions
return run(this::driveStraight).until(() -> encoder.getDistance().gte(distance));
}
// Users HAVE to be explicit about their units
Command driveFiveFeet = driveDistance(Feet.of(5));
Command driveOneMeter = driveDistance(Meters.of(1));
```
```java
SmartDashboard.putNumber("Temperature (C)", pdp.getTemperature().in(Celsius));
SmartDashboard.putNumber("Temperature (F)", pdp.getTemperature().in(Fahrenheit));
```
```java
var InchSecond = Inch.mult(Second); // new combined unit types can be user-defined
var InchPerSecond = Inch.per(Second);
PIDController<Distance, ElectricPotential> heightController = new PIDController<>(
/* kP */ Volts.of(0.2).per(Inch),
/* kI */ Volts.of(0.002).per(InchSecond),
/* kD */ Volts.of(0.008).per(InchPerSecond)
);
var elevatorTop = Feet.of(4).plus(Inches.of(6.125));
elevatorMotor.setVoltage(heightController.calculate(encoder.getDistance(), elevatorTop));
```
This commit is contained in:
207
wpiunits/src/main/java/edu/wpi/first/units/Units.java
Normal file
207
wpiunits/src/main/java/edu/wpi/first/units/Units.java
Normal file
@@ -0,0 +1,207 @@
|
||||
// Copyright (c) FIRST and other WPILib contributors.
|
||||
// Open Source Software; you can modify and/or share it under the terms of
|
||||
// the WPILib BSD license file in the root directory of this project.
|
||||
|
||||
package edu.wpi.first.units;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public final class Units {
|
||||
private Units() {
|
||||
// Prevent instantiation
|
||||
}
|
||||
|
||||
// Pseudo-classes describing the more common units of measure.
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static final Unit AnonymousBaseUnit = new Dimensionless(1, "<?>", "<?>");
|
||||
|
||||
// Distance
|
||||
public static final Distance Meters = BaseUnits.Distance;
|
||||
public static final Distance Millimeters = Milli(Meters, "Millimeter", "mm");
|
||||
public static final Distance Centimeters =
|
||||
derive(Meters).splitInto(100).named("Centimeter").symbol("cm").make();
|
||||
public static final Distance Inches =
|
||||
derive(Millimeters).aggregate(25.4).named("Inch").symbol("in").make();
|
||||
public static final Distance Feet =
|
||||
derive(Inches).aggregate(12).named("Foot").symbol("ft").make();
|
||||
|
||||
// Time
|
||||
public static final Time Seconds = BaseUnits.Time;
|
||||
public static final Time Second = Seconds; // singularized alias
|
||||
public static final Time Milliseconds = Milli(Seconds);
|
||||
public static final Time Millisecond = Milliseconds; // singularized alias
|
||||
public static final Time Microseconds = Micro(Seconds);
|
||||
public static final Time Microsecond = Microseconds; // singularized alias
|
||||
public static final Time Minutes =
|
||||
derive(Seconds).aggregate(60).named("Minute").symbol("min").make();
|
||||
public static final Time Minute = Minutes; // singularized alias
|
||||
|
||||
// Angle
|
||||
public static final Angle Revolutions = BaseUnits.Angle;
|
||||
public static final Angle Rotations = new Angle(1, "Rotation", "R"); // alias
|
||||
public static final Angle Radians =
|
||||
derive(Revolutions).splitInto(2 * Math.PI).named("Radian").symbol("rad").make();
|
||||
public static final Angle Degrees =
|
||||
derive(Revolutions).splitInto(360).named("Degree").symbol("°").make();
|
||||
|
||||
// Velocity
|
||||
public static final Velocity<Distance> MetersPerSecond = Meters.per(Second);
|
||||
public static final Velocity<Distance> FeetPerSecond = Feet.per(Second);
|
||||
public static final Velocity<Distance> InchesPerSecond = Inches.per(Second);
|
||||
|
||||
public static final Velocity<Angle> RevolutionsPerSecond = Revolutions.per(Second);
|
||||
public static final Velocity<Angle> RotationsPerSecond = Rotations.per(Second);
|
||||
public static final Velocity<Angle> RPM = Rotations.per(Minute);
|
||||
public static final Velocity<Angle> RadiansPerSecond = Radians.per(Second);
|
||||
public static final Velocity<Angle> DegreesPerSecond = Degrees.per(Second);
|
||||
|
||||
// Acceleration
|
||||
public static final Velocity<Velocity<Distance>> MetersPerSecondPerSecond =
|
||||
MetersPerSecond.per(Second);
|
||||
public static final Velocity<Velocity<Distance>> Gs =
|
||||
derive(MetersPerSecondPerSecond).aggregate(9.80665).named("G").symbol("G").make();
|
||||
|
||||
// Mass
|
||||
public static final Mass Kilograms = BaseUnits.Mass;
|
||||
public static final Mass Grams = Milli(Kilograms, "Gram", "g");
|
||||
public static final Mass Pounds =
|
||||
derive(Grams).aggregate(453.592).named("Pound").symbol("lb.").make();
|
||||
public static final Mass Ounces =
|
||||
derive(Pounds).splitInto(16).named("Ounce").symbol("oz.").make();
|
||||
|
||||
// Unitless
|
||||
public static final Dimensionless Value = BaseUnits.Value;
|
||||
public static final Dimensionless Percent =
|
||||
derive(Value).splitInto(100).named("Percent").symbol("%").make();
|
||||
|
||||
// Voltage
|
||||
public static final Voltage Volts = BaseUnits.Voltage;
|
||||
public static final Voltage Millivolts = Milli(Volts);
|
||||
|
||||
// Current
|
||||
public static final Current Amps = BaseUnits.Current;
|
||||
public static final Current Milliamps = Milli(Amps);
|
||||
|
||||
// Energy
|
||||
public static final Energy Joules = BaseUnits.Energy;
|
||||
public static final Energy Millijoules = Milli(Joules);
|
||||
public static final Energy Kilojoules = Kilo(Joules);
|
||||
|
||||
// Power
|
||||
public static final Power Watts = BaseUnits.Power;
|
||||
public static final Power Milliwatts = Milli(Watts);
|
||||
public static final Power Horsepower =
|
||||
derive(Watts).aggregate(745.7).named("Horsepower").symbol("HP").make();
|
||||
|
||||
// Temperature
|
||||
public static final Temperature Kelvin = BaseUnits.Temperature;
|
||||
public static final Temperature Celsius =
|
||||
derive(Kelvin).offset(+273.15).named("Celsius").symbol("°C").make();
|
||||
|
||||
public static final Temperature Fahrenheit =
|
||||
derive(Celsius)
|
||||
.mappingInputRange(0, 100)
|
||||
.toOutputRange(32, 212)
|
||||
.named("Fahrenheit")
|
||||
.symbol("°F")
|
||||
.make();
|
||||
|
||||
// Standard feedforward units for kV and kA.
|
||||
// kS and kG are just volts, which is already defined earlier
|
||||
public static final Per<Voltage, Velocity<Distance>> VoltsPerMeterPerSecond =
|
||||
Volts.per(MetersPerSecond);
|
||||
public static final Per<Voltage, Velocity<Velocity<Distance>>> VoltsPerMeterPerSecondSquared =
|
||||
Volts.per(MetersPerSecondPerSecond);
|
||||
|
||||
public static final Per<Voltage, Velocity<Angle>> VoltsPerRadianPerSecond =
|
||||
Volts.per(RadiansPerSecond);
|
||||
public static final Per<Voltage, Velocity<Velocity<Angle>>> VoltsPerRadianPerSecondSquared =
|
||||
Volts.per(RadiansPerSecond.per(Second));
|
||||
|
||||
/**
|
||||
* Creates a unit equal to a thousandth of the base unit, eg Milliseconds = Milli(Units.Seconds).
|
||||
*
|
||||
* @param <U> the type of the unit
|
||||
* @param baseUnit the unit being derived from. This does not have to be the base unit of measure
|
||||
* @param name the name of the new derived unit
|
||||
* @param symbol the symbol of the new derived unit
|
||||
*/
|
||||
@SuppressWarnings({"PMD.MethodName", "checkstyle:methodname"})
|
||||
public static <U extends Unit<U>> U Milli(Unit<U> baseUnit, String name, String symbol) {
|
||||
return derive(baseUnit).splitInto(1000).named(name).symbol(symbol).make();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a unit equal to a thousandth of the base unit, eg Milliseconds = Milli(Units.Seconds).
|
||||
*
|
||||
* @param <U> the type of the unit
|
||||
* @param baseUnit the unit being derived from. This does not have to be the base unit of measure
|
||||
*/
|
||||
@SuppressWarnings({"PMD.MethodName", "checkstyle:methodname"})
|
||||
public static <U extends Unit<U>> U Milli(Unit<U> baseUnit) {
|
||||
return Milli(
|
||||
baseUnit, "Milli" + baseUnit.name().toLowerCase(Locale.ROOT), "m" + baseUnit.symbol());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a unit equal to a millionth of the base unit, eg {@code Microseconds =
|
||||
* Micro(Units.Seconds, "Microseconds", 'us")}.
|
||||
*
|
||||
* @param <U> the type of the unit
|
||||
* @param baseUnit the unit being derived from. This does not have to be the base unit of measure
|
||||
* @param name the name of the new derived unit
|
||||
* @param symbol the symbol of the new derived unit
|
||||
*/
|
||||
@SuppressWarnings({"PMD.MethodName", "checkstyle:methodname"})
|
||||
public static <U extends Unit<U>> U Micro(Unit<U> baseUnit, String name, String symbol) {
|
||||
return derive(baseUnit).splitInto(1_000_000).named(name).symbol(symbol).make();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a unit equal to a millionth of the base unit, eg Microseconds = Micro(Units.Seconds).
|
||||
*
|
||||
* @param <U> the type of the unit
|
||||
* @param baseUnit the unit being derived from. This does not have to be the base unit of measure
|
||||
*/
|
||||
@SuppressWarnings({"PMD.MethodName", "checkstyle:methodname"})
|
||||
public static <U extends Unit<U>> U Micro(Unit<U> baseUnit) {
|
||||
return Micro(
|
||||
baseUnit, "Micro" + baseUnit.name().toLowerCase(Locale.ROOT), "u" + baseUnit.symbol());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a unit equal to a thousand of the base unit, eg Kilograms = Kilo(Units.Grams).
|
||||
*
|
||||
* @param <U> the type of the unit
|
||||
* @param baseUnit the unit being derived from. This does not have to be the base unit of measure
|
||||
* @param name the name of the new derived unit
|
||||
* @param symbol the symbol of the new derived unit
|
||||
*/
|
||||
@SuppressWarnings({"PMD.MethodName", "checkstyle:methodname"})
|
||||
public static <U extends Unit<U>> U Kilo(Unit<U> baseUnit, String name, String symbol) {
|
||||
return derive(baseUnit).aggregate(1000).named(name).symbol(symbol).make();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a unit equal to a thousand of the base unit, eg Kilograms = Kilo(Units.Grams).
|
||||
*
|
||||
* @param <U> the type of the unit
|
||||
* @param baseUnit the unit being derived from. This does not have to be the base unit of measure
|
||||
*/
|
||||
@SuppressWarnings({"PMD.MethodName", "checkstyle:methodname"})
|
||||
public static <U extends Unit<U>> U Kilo(Unit<U> baseUnit) {
|
||||
return Kilo(
|
||||
baseUnit, "Kilo" + baseUnit.name().toLowerCase(Locale.ROOT), "K" + baseUnit.symbol());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <U extends Unit<U>> UnitBuilder<U> derive(Unit<U> unit) {
|
||||
return new UnitBuilder<>((U) unit);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <U extends Unit<U>> U anonymous() {
|
||||
return (U) AnonymousBaseUnit;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user