-
Notifications
You must be signed in to change notification settings - Fork 2
Fluid Constants
FluidConstants are 'constant' values initially declared at compile-time which can be updated over network tables at run-time. This is useful for values which you may want to change quickly without needing to re-deploy or SSH into your robot.
The FluidConstant class implements the Supplier<T>
interface to allow abstraction to a supplier in cases where you only retrieve the current value. If your use case matches that, cast the variable to a Supplier so if anything about this class changes, your code will not break!
Creates a new FluidConstant of type String
with the name network-table-name
and initial value initialValue
FluidConstant<String> myFluidConstant = new FluidConstant<>("network-table-name", "initialValue");
NetworkTable constantsTable = NetworkTableInstance.getDefault().getTable("constants");
myFluidConstant.registerToTable(constantsTable);
String value = myFluidConstant.getValue(); // Gets the current value
String initialValue = myFluidConstant.getInitialValue(); // Gets the value as defined at compile-time
myFluidConstant.setValue("New value"); // Set the current value
- OR -
If you only plan on retreiving the values use this instead:
// Cast the fluid constant to a Supplier. This make your code unbreakable because Supplier will never change, but FluidConstant might!
Supplier<String> myFluidConstantSupplier = myFluidConstant;
myFluidConstantSupplier.get();
You can use any method of listing and modifying NetworkTables for this. If you have no idea what those are, you can use the FRC Outline Viewer that comes bundled with WPILib.
The parameter to this method accepts a BiConsumer
. It is an anonymous 'lambda' function that can either be declared in-line with the rest of the code or as a method which accepts 2 arguments (Both the same as your constant type).
myFluidConstant.registerListener((oldVal, newVal) -> {
// Your code here
});
- OR -
private void onUpdate(String oldVal, String newVal) {
// Your code here
}
// ...
myFluidConstant.registerListener(this::onUpdate);
Both the registerToTable
and registerListener
methods return the instance of FluidConstant<T>
to allow chaining them after the initial declaration.
So instead of:
NetworkTable constantsTable = NetworkTableInstance.getDefault().getTable("constants");
FluidConstant<Double> fcDouble = new FluidConstant<>("fc-double", 0d);
fcDouble.registerToTable(constantsTable);
fcDouble.registerListener(this::fcDoubleUpdated);
You can instead do:
NetworkTable constantsTable = NetworkTableInstance.getDefault().getTable("constants");
FluidConstant<Double> fcDouble = new FluidConstant<>("fc-double", 0d)
.registerToTable(constantsTable)
.registerListener(this::fcDoubleUpdated);
This makes your code more readable and more organized.