Skip to content

Commit

Permalink
Update photon-server, format and lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Juniormunk committed Nov 4, 2024
1 parent c94275c commit 869b60d
Show file tree
Hide file tree
Showing 17 changed files with 221 additions and 250 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,22 @@ public class NetworkConfig {
public boolean shouldPublishProto = false;

/**
* If we should ONLY match cameras by path, and NEVER only by base-name. For now
* default to false
* If we should ONLY match cameras by path, and NEVER only by base-name. For now default to false
* to preserve old matching logic.
*
* <p>
* This also disables creating new CameraConfigurations for detected "new"
* cameras.
* <p>This also disables creating new CameraConfigurations for detected "new" cameras.
*/
public boolean matchCamerasOnlyByPath = false;

@JsonIgnore
public static final String NM_IFACE_STRING = "${interface}";
@JsonIgnore
public static final String NM_IP_STRING = "${ipaddr}";
@JsonIgnore public static final String NM_IFACE_STRING = "${interface}";
@JsonIgnore public static final String NM_IP_STRING = "${ipaddr}";

public String networkManagerIface = "";
// TODO: remove these strings if no longer needed
public String setStaticCommand = "nmcli con mod ${interface} ipv4.addresses ${ipaddr}/8 ipv4.method \"manual\" ipv6.method \"disabled\"";
public String setDHCPcommand = "nmcli con mod ${interface} ipv4.method \"auto\" ipv6.method \"disabled\"";
public String setStaticCommand =
"nmcli con mod ${interface} ipv4.addresses ${ipaddr}/8 ipv4.method \"manual\" ipv6.method \"disabled\"";
public String setDHCPcommand =
"nmcli con mod ${interface} ipv4.method \"auto\" ipv6.method \"disabled\"";

public NetworkConfig() {
// We can (usually) manage networking on Linux devices, and if we can, we should
Expand All @@ -68,7 +65,8 @@ public NetworkConfig() {

@JsonCreator
public NetworkConfig(
@JsonProperty("ntServerAddress") @JsonAlias({ "ntServerAddress", "teamNumber" }) String ntServerAddress,
@JsonProperty("ntServerAddress") @JsonAlias({"ntServerAddress", "teamNumber"})
String ntServerAddress,
@JsonProperty("connectionType") NetworkMode connectionType,
@JsonProperty("staticIp") String staticIp,
@JsonProperty("hostname") String hostname,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,13 @@
/**
* Manages the loading of neural network models.
*
* <p>
* Models are loaded from the filesystem at the <code>modelsFolder</code>
* location. PhotonVision
* also supports shipping pre-trained models as resources in the JAR. If the
* model has already been
* <p>Models are loaded from the filesystem at the <code>modelsFolder</code> location. PhotonVision
* also supports shipping pre-trained models as resources in the JAR. If the model has already been
* extracted to the filesystem, it will not be extracted again.
*
* <p>
* Each model must have a corresponding <code>labels</code> file. The labels
* file format is
* simply a list of string names per label, one label per line. The labels file
* must have the same
* name as the model file, but with the suffix <code>-labels.txt</code> instead
* of <code>.rknn
* <p>Each model must have a corresponding <code>labels</code> file. The labels file format is
* simply a list of string names per label, one label per line. The labels file must have the same
* name as the model file, but with the suffix <code>-labels.txt</code> instead of <code>.rknn
* </code>.
*/
public class NeuralNetworkModelManager {
Expand Down Expand Up @@ -116,19 +109,16 @@ public List<String> getSupportedBackends() {
/**
* Stores model information, such as the model file, labels, and version.
*
* <p>
* The first model in the list is the default model.
* <p>The first model in the list is the default model.
*/
private Map<NeuralNetworkBackend, ArrayList<Model>> models;

/**
* Retrieves the deep neural network models available, in a format that can be
* used by the
* Retrieves the deep neural network models available, in a format that can be used by the
* frontend.
*
* @return A map containing the available models, where the key is the backend
* and the value is a
* list of model names.
* @return A map containing the available models, where the key is the backend and the value is a
* list of model names.
*/
public HashMap<String, ArrayList<String>> getModels() {
HashMap<String, ArrayList<String>> modelMap = new HashMap<>();
Expand All @@ -147,17 +137,13 @@ public HashMap<String, ArrayList<String>> getModels() {
}

/**
* Retrieves the model with the specified name, assuming it is available under a
* supported
* Retrieves the model with the specified name, assuming it is available under a supported
* backend.
*
* <p>
* If this method returns `Optional.of(..)` then the model should be safe to
* load.
* <p>If this method returns `Optional.of(..)` then the model should be safe to load.
*
* @param modelName the name of the model to retrieve
* @return an Optional containing the model if found, or an empty Optional if
* not found
* @return an Optional containing the model if found, or an empty Optional if not found
*/
public Optional<Model> getModel(String modelName) {
if (models == null) {
Expand All @@ -167,8 +153,8 @@ public Optional<Model> getModel(String modelName) {
// Check if the model exists in any supported backend
for (NeuralNetworkBackend backend : supportedBackends) {
if (models.containsKey(backend)) {
Optional<Model> model = models.get(backend).stream().filter(m -> m.getName().equals(modelName))
.findFirst();
Optional<Model> model =
models.get(backend).stream().filter(m -> m.getName().equals(modelName)).findFirst();
if (model.isPresent()) {
return model;
}
Expand Down Expand Up @@ -202,9 +188,10 @@ private void loadModel(File model) {
return;
}

Optional<NeuralNetworkBackend> backend = Arrays.stream(NeuralNetworkBackend.values())
.filter(b -> b.format.equals(modelExtension))
.findFirst();
Optional<NeuralNetworkBackend> backend =
Arrays.stream(NeuralNetworkBackend.values())
.filter(b -> b.format.equals(modelExtension))
.findFirst();

if (!backend.isPresent()) {
logger.warn("Model " + model.getName() + " has an unknown extension.");
Expand Down Expand Up @@ -261,7 +248,8 @@ public void discoverModels(File modelsFolder) {
// After loading all of the models, sort them by name to ensure a consistent
// ordering
models.forEach(
(backend, backendModels) -> backendModels.sort((a, b) -> a.getName().compareTo(b.getName())));
(backend, backendModels) ->
backendModels.sort((a, b) -> a.getName().compareTo(b.getName())));

// Log
StringBuilder sb = new StringBuilder();
Expand All @@ -287,16 +275,17 @@ public void extractModels(File modelsDirectory) {
String resource = "models";

try {
String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
try (JarFile jarFile = new JarFile(jarPath)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.getName().startsWith(resource + "/") || entry.isDirectory()) {
continue;
}
Path outputPath = modelsDirectory.toPath()
.resolve(entry.getName().substring(resource.length() + 1));
Path outputPath =
modelsDirectory.toPath().resolve(entry.getName().substring(resource.length() + 1));

if (Files.exists(outputPath)) {
logger.info("Skipping extraction of DNN resource: " + entry.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ public void setBrightnessImpl(int brightness) {
}

public static void setConfig(HardwareConfig config) {
if (Platform.getCurrentPlatform().isRaspberryPi())
return;
if (Platform.getCurrentPlatform().isRaspberryPi()) return;
commands.replace("setState", config.ledSetCommand);
commands.replace("dim", config.ledDimCommand);
commands.replace("blink", config.ledBlinkCommand);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ public class HardwareManager {

private final MetricsManager metricsManager;

@SuppressWarnings({ "FieldCanBeLocal", "unused" })
@SuppressWarnings({"FieldCanBeLocal", "unused"})
private final StatusLED statusLED;

@SuppressWarnings("FieldCanBeLocal")
private final IntegerSubscriber ledModeRequest;

private final IntegerPublisher ledModeState;

@SuppressWarnings({ "FieldCanBeLocal", "unused" })
@SuppressWarnings({"FieldCanBeLocal", "unused"})
private final NTDataChangeListener ledModeListener;

public final VisionLED visionLED; // May be null if no LED is specified
Expand All @@ -76,10 +76,13 @@ private HardwareManager(HardwareConfig hardwareConfig, HardwareSettings hardware
this.metricsManager = new MetricsManager();
this.metricsManager.setConfig(hardwareConfig);

ledModeRequest = NetworkTablesManager.getInstance().kRootTable
.getIntegerTopic("ledModeRequest")
.subscribe(-1);
ledModeState = NetworkTablesManager.getInstance().kRootTable.getIntegerTopic("ledModeState").publish();
ledModeRequest =
NetworkTablesManager.getInstance()
.kRootTable
.getIntegerTopic("ledModeRequest")
.subscribe(-1);
ledModeState =
NetworkTablesManager.getInstance().kRootTable.getIntegerTopic("ledModeState").publish();
ledModeState.set(VisionLEDMode.kDefault.value);

CustomGPIO.setConfig(hardwareConfig);
Expand All @@ -90,30 +93,33 @@ private HardwareManager(HardwareConfig hardwareConfig, HardwareSettings hardware
pigpioSocket = null;
}

statusLED = hardwareConfig.statusRGBPins.size() == 3
? new StatusLED(hardwareConfig.statusRGBPins)
: null;
statusLED =
hardwareConfig.statusRGBPins.size() == 3
? new StatusLED(hardwareConfig.statusRGBPins)
: null;

if (statusLED != null) {
TimedTaskManager.getInstance().addTask("StatusLEDUpdate", this::statusLEDUpdate, 150);
}

var hasBrightnessRange = hardwareConfig.ledBrightnessRange.size() == 2;
visionLED = hardwareConfig.ledPins.isEmpty()
? null
: new VisionLED(
hardwareConfig.ledPins,
hasBrightnessRange ? hardwareConfig.ledBrightnessRange.get(0) : 0,
hasBrightnessRange ? hardwareConfig.ledBrightnessRange.get(1) : 100,
pigpioSocket,
ledModeState::set);

ledModeListener = visionLED == null
? null
: new NTDataChangeListener(
NetworkTablesManager.getInstance().kRootTable.getInstance(),
ledModeRequest,
visionLED::onLedModeChange);
visionLED =
hardwareConfig.ledPins.isEmpty()
? null
: new VisionLED(
hardwareConfig.ledPins,
hasBrightnessRange ? hardwareConfig.ledBrightnessRange.get(0) : 0,
hasBrightnessRange ? hardwareConfig.ledBrightnessRange.get(1) : 100,
pigpioSocket,
ledModeState::set);

ledModeListener =
visionLED == null
? null
: new NTDataChangeListener(
NetworkTablesManager.getInstance().kRootTable.getInstance(),
ledModeRequest,
visionLED::onLedModeChange);

Runtime.getRuntime().addShutdownHook(new Thread(this::onJvmExit));

Expand All @@ -129,17 +135,15 @@ private HardwareManager(HardwareConfig hardwareConfig, HardwareSettings hardware
public void setBrightnessPercent(int percent) {
if (percent != hardwareSettings.ledBrightnessPercentage) {
hardwareSettings.ledBrightnessPercentage = percent;
if (visionLED != null)
visionLED.setBrightness(percent);
if (visionLED != null) visionLED.setBrightness(percent);
ConfigManager.getInstance().requestSave();
logger.info("Setting led brightness to " + percent + "%");
}
}

private void onJvmExit() {
logger.info("Shutting down LEDs...");
if (visionLED != null)
visionLED.setState(false);
if (visionLED != null) visionLED.setState(false);

ConfigManager.getInstance().onJvmExit();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,10 @@ public static PiVersion getPiVersion() {
}

private static PiVersion calcPiVersion() {
if (!Platform.getCurrentPlatform().isRaspberryPi())
return PiVersion.UNKNOWN;
if (!Platform.getCurrentPlatform().isRaspberryPi()) return PiVersion.UNKNOWN;
String piString = getPiVersionString();
for (PiVersion p : PiVersion.values()) {
if (piString.toLowerCase().contains(p.identifier))
return p;
if (piString.toLowerCase().contains(p.identifier)) return p;
}
return UNKNOWN;
}
Expand All @@ -58,8 +56,7 @@ private static PiVersion calcPiVersion() {
// Versions here:
// https://github.com/raspberrypi/linux/blob/rpi-5.10.y/arch/arm/boot/dts/bcm2710-rpi-cm3.dts
private static String getPiVersionString() {
if (!Platform.getCurrentPlatform().isRaspberryPi())
return "";
if (!Platform.getCurrentPlatform().isRaspberryPi()) return "";
try {
shell.executeBashCommand("cat /proc/device-tree/model");
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ void onLedModeChange(NetworkTableEvent entryNotification) {
}
setInternal(newLedMode, true);

if (modeConsumer != null)
modeConsumer.accept(newLedMode.value);
if (modeConsumer != null) modeConsumer.accept(newLedMode.value);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ public void setConfig(HardwareConfig config) {
}

public String safeExecute(String str) {
if (str.isEmpty())
return "";
if (str.isEmpty()) return "";
try {
return execute(str);
} catch (Exception e) {
Expand All @@ -69,8 +68,7 @@ public String safeExecute(String str) {
private String cpuMemSave = null;

public String getMemory() {
if (cmds.cpuMemoryCommand.isEmpty())
return "";
if (cmds.cpuMemoryCommand.isEmpty()) return "";
if (cpuMemSave == null) {
// save the value and only run it once
cpuMemSave = execute(cmds.cpuMemoryCommand);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,8 @@ public String toString() {

public static List<NMDeviceInfo> getAllInterfaces() {
long now = System.currentTimeMillis();
if (now - lastReadTimestamp < 5000)
return allInterfaces;
else
lastReadTimestamp = now;
if (now - lastReadTimestamp < 5000) return allInterfaces;
else lastReadTimestamp = now;

var ret = new ArrayList<NMDeviceInfo>();

Expand All @@ -100,7 +98,8 @@ public static List<NMDeviceInfo> getAllInterfaces() {
if (out == null) {
return new ArrayList<>();
}
Pattern pattern = Pattern.compile("GENERAL.CONNECTION:(.*)\nGENERAL.DEVICE:(.*)\nGENERAL.TYPE:(.*)");
Pattern pattern =
Pattern.compile("GENERAL.CONNECTION:(.*)\nGENERAL.DEVICE:(.*)\nGENERAL.TYPE:(.*)");
Matcher matcher = pattern.matcher(out);
while (matcher.find()) {
if (!matcher.group(2).equals("lo")) {
Expand Down
Loading

0 comments on commit 869b60d

Please sign in to comment.