Skip to content

Instantly share code, notes, and snippets.

@boxofrox
Created January 11, 2025 03:15
Show Gist options
  • Save boxofrox/062fb74cbaba1bd95d77b0f4fc8d9791 to your computer and use it in GitHub Desktop.
Save boxofrox/062fb74cbaba1bd95d77b0f4fc8d9791 to your computer and use it in GitHub Desktop.
// file: lib/config/ConfigLoader.java
public interface ConfigLoader {
void openConfig();
/**
* Allow user to access a specified table.
* @param String name - name of table in config file.
* @return Optional in case config is missing a table with the specified name.
*/
Optional<ConfigTable> getTable(String name);
}
// file: lib/config/ConfigTable.java
public interface ConfigTable {
/**
* Get double value from specified field.
* @param String name - name of field in table (ex: "speed.min")
* @return Optional in case config is missing a field with the specified name, or unable to convert string in config into a double. Might need a Result type to indicate missing vs bad value.
*/
Optional<double> getDouble(String name);
Optional<boolean> getBoolean(String name);
}
// file: subsystems/drivetrain/Drivetrain.java
import lib.config.ConfigTable;
public class Drivetrain {
public Drivetrain(ConfigTable table) {
double turnP;
{
Optional<double> kP = table.getDouble("swerve.turn.kP");
if (!kP.isPresent()) {
System.err.println("Error: drivetrain cannot find toml property swerve.turn.kP");
throw new Exception("Error: drivetrain cannot find toml property swerve.turn.kP");
}
}
}
}
public class Robot : TimedRobot {
public void RobotInit() {
ConfigLoader config = null; // Will eventually replace with TomlConfigLoader one we find a library.
mDrivetrain = new Drivetrain(config.getTable("drivetrain").orElseThrow(() -> throw new Exception("Config file missing table \"drivetrain\"")));
}
}
// file: lib/config/TomlConfigLoader.java
public class TomlConfigLoader implements ConfigLoader {
public TomlConfigLoader(String config_filename) {
// Do nothing until we find a library.
}
public void openConfig() {
// Do nothing until we find a library.
}
public Optional<ConfigTable> getTable(String name) {
// Do minimum until we find a library, then rewrite to create ConfigTable for the specified name.
return Optional.of(new TomlConfigTable());
}
}
// file: lib/config/TomlConfigTable.java
public class TomlConfigTable implements ConfigTable {
public Optional<double> getDouble(String name) {
return Optional.empty();
}
public Optional<boolean> getBoolean(String name) {
// Do the same as getDouble() until we find a java toml library.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment