Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Platform Rewrite #1520

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public class NetworkConfig {
"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 try to. Command
// We can (usually) manage networking on Linux devices, and if we can, we should
// try to. Command
// line inhibitions happen at a level above this class
setShouldManage(deviceCanManageNetwork());
}
Expand Down Expand Up @@ -122,7 +123,7 @@ public void setShouldManage(boolean shouldManage) {

@JsonIgnore
private boolean deviceCanManageNetwork() {
return Platform.isLinux();
return Platform.getCurrentPlatform().isLinux();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public class NeuralNetworkModelManager {
private NeuralNetworkModelManager() {
ArrayList<NeuralNetworkBackend> backends = new ArrayList<>();

if (Platform.isRK3588()) {
if (Platform.getCurrentPlatform().isRK3588()) {
backends.add(NeuralNetworkBackend.RKNN);
}

Expand Down Expand Up @@ -245,7 +245,8 @@ public void discoverModels(File modelsFolder) {
logger.error("Failed to discover models at " + modelsFolder.getAbsolutePath(), e);
}

// After loading all of the models, sort them by name to ensure a consistent ordering
// 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())));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void setBrightnessImpl(int brightness) {
}

public static void setConfig(HardwareConfig config) {
if (Platform.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 @@ -87,7 +87,7 @@ private HardwareManager(HardwareConfig hardwareConfig, HardwareSettings hardware

CustomGPIO.setConfig(hardwareConfig);

if (Platform.isRaspberryPi()) {
if (Platform.getCurrentPlatform().isRaspberryPi()) {
pigpioSocket = new PigpioSocket();
} else {
pigpioSocket = null;
Expand Down Expand Up @@ -149,7 +149,7 @@ private void onJvmExit() {
}

public boolean restartDevice() {
if (Platform.isLinux()) {
if (Platform.getCurrentPlatform().isLinux()) {
try {
return shellExec.executeBashCommand("reboot now") == 0;
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public static PiVersion getPiVersion() {
}

private static PiVersion calcPiVersion() {
if (!Platform.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;
Expand All @@ -56,7 +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.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 @@ -27,7 +27,7 @@ public class PlatformUtils {

@SuppressWarnings("StatementWithEmptyBody")
private static boolean checkForRoot() {
if (Platform.isLinux()) {
if (Platform.getCurrentPlatform().isLinux()) {
try {
shell.executeBashCommand("id -u");
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public StatusLED(List<Integer> statusLedPins) {
}
}

if (Platform.isRaspberryPi()) {
if (Platform.getCurrentPlatform().isRaspberryPi()) {
redLED = new PigpioPin(statusLedPins.get(0));
greenLED = new PigpioPin(statusLedPins.get(1));
blueLED = new PigpioPin(statusLedPins.get(2));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public VisionLED(
this.ledPins = ledPins.stream().mapToInt(i -> i).toArray();
ledPins.forEach(
pin -> {
if (Platform.isRaspberryPi()) {
if (Platform.getCurrentPlatform().isRaspberryPi()) {
visionLEDs.add(new PigpioPin(pin));
} else {
visionLEDs.add(new CustomGPIO(pin));
Expand All @@ -87,7 +87,7 @@ public void blink(int pulseLengthMillis, int blinkCount) {
}

private void blinkImpl(int pulseLengthMillis, int blinkCount) {
if (Platform.isRaspberryPi()) {
if (Platform.getCurrentPlatform().isRaspberryPi()) {
try {
setStateImpl(false); // hack to ensure hardware PWM has stopped before trying to blink
pigpioSocket.generateAndSendWaveform(pulseLengthMillis, blinkCount, ledPins);
Expand All @@ -104,7 +104,7 @@ private void blinkImpl(int pulseLengthMillis, int blinkCount) {
}

private void setStateImpl(boolean state) {
if (Platform.isRaspberryPi()) {
if (Platform.getCurrentPlatform().isRaspberryPi()) {
try {
// stop any active blink
pigpioSocket.waveTxStop();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ public class MetricsManager {
public void setConfig(HardwareConfig config) {
if (config.hasCommandsConfigured()) {
cmds = new FileCmds();
} else if (Platform.isRaspberryPi()) {
} else if (Platform.getCurrentPlatform().isRaspberryPi()) {
cmds = new PiCmds(); // Pi's can use a hardcoded command set
} else if (Platform.isRK3588()) {
} else if (Platform.getCurrentPlatform().isRK3588()) {
cmds = new RK3588Cmds(); // RK3588 chipset hardcoded command set
} else if (Platform.isLinux()) {
} else if (Platform.getCurrentPlatform().isLinux()) {
cmds = new LinuxCmds(); // Linux/Unix platforms assume a nominal command set
} else {
cmds = new CmdBase(); // default - base has no commands
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
public class NetworkManager {
private static final Logger logger = new Logger(NetworkManager.class, LogGroup.General);

private NetworkManager() {}
private NetworkManager() {
}

private static class SingletonHolder {
private static final NetworkManager INSTANCE = new NetworkManager();
Expand All @@ -59,7 +60,7 @@ public void initialize(boolean shouldManage) {
return;
}

if (!Platform.isLinux()) {
if (!Platform.getCurrentPlatform().isLinux()) {
logger.info("Not managing network on non-Linux platforms.");
return;
}
Expand All @@ -79,9 +80,11 @@ public void initialize(boolean shouldManage) {
var config = ConfigManager.getInstance().getConfig().getNetworkConfig();
if (physicalDevices.stream().noneMatch(it -> (it.devName.equals(config.networkManagerIface)))) {
try {
// if the configured interface isn't in the list of available ones, select one that is
// if the configured interface isn't in the list of available ones, select one
// that is
var iFace = physicalDevices.stream().findFirst().orElseThrow();
logger.warn("The configured interface doesn't match any available interface. Applying configuration to " + iFace.devName);
logger.warn("The configured interface doesn't match any available interface. Applying configuration to "
+ iFace.devName);
// update NetworkConfig with found interface
config.networkManagerIface = iFace.devName;
ConfigManager.getInstance().requestSave();
Expand All @@ -96,7 +99,8 @@ public void initialize(boolean shouldManage) {
}
}

logger.info("Setting " + config.connectionType + " with team " + config.ntServerAddress + " on " + config.networkManagerIface);
logger.info("Setting " + config.connectionType + " with team " + config.ntServerAddress + " on "
+ config.networkManagerIface);

// always set hostname (unless it's blank)
if (!config.hostname.isBlank()) {
Expand Down Expand Up @@ -129,22 +133,19 @@ private void setHostname(String hostname) {
var shell = new ShellExec(true, false);
shell.executeBashCommand("cat /etc/hostname | tr -d \" \\t\\n\\r\"");
var oldHostname = shell.getOutput().replace("\n", "");
logger.debug("Old host name: >" + oldHostname +"<");
logger.debug("New host name: >" + hostname +"<");
logger.debug("Old host name: >" + oldHostname + "<");
logger.debug("New host name: >" + hostname + "<");

if (!oldHostname.equals(hostname)) {
var setHostnameRetCode =
shell.executeBashCommand(
"echo $NEW_HOSTNAME > /etc/hostname".replace("$NEW_HOSTNAME", hostname));
setHostnameRetCode =
shell.executeBashCommand("hostnamectl set-hostname " + hostname);
var setHostnameRetCode = shell.executeBashCommand(
"echo $NEW_HOSTNAME > /etc/hostname".replace("$NEW_HOSTNAME", hostname));
setHostnameRetCode = shell.executeBashCommand("hostnamectl set-hostname " + hostname);

// Add to /etc/hosts
var addHostRetCode =
shell.executeBashCommand(
String.format(
"sed -i \"s/127.0.1.1.*%s/127.0.1.1\\t%s/g\" /etc/hosts",
oldHostname, hostname));
var addHostRetCode = shell.executeBashCommand(
String.format(
"sed -i \"s/127.0.1.1.*%s/127.0.1.1\\t%s/g\" /etc/hosts",
oldHostname, hostname));

shell.executeBashCommand("systemctl restart avahi-daemon.service");

Expand All @@ -169,29 +170,28 @@ private void setConnectionDHCP(NetworkConfig config) {
String connName = "dhcp-" + config.networkManagerIface;

String addDHCPcommand = """
nmcli connection add
con-name "${connection}"
ifname "${interface}"
type ethernet
autoconnect no
ipv4.method auto
ipv6.method disabled
""";
nmcli connection add
con-name "${connection}"
ifname "${interface}"
type ethernet
autoconnect no
ipv4.method auto
ipv6.method disabled
""";
addDHCPcommand = addDHCPcommand.replaceAll("[\\n]", " ");

var shell = new ShellExec();
try {
if (NetworkUtils.connDoesNotExist(connName)) {
// create connection
logger.info("Creating the DHCP connection " + connName );
logger.info("Creating the DHCP connection " + connName);
shell.executeBashCommand(
addDHCPcommand
.replace("${connection}", connName)
.replace("${interface}", config.networkManagerIface)
);
addDHCPcommand
.replace("${connection}", connName)
.replace("${interface}", config.networkManagerIface));
}
// activate it
logger.info("Activating the DHCP connection " + connName );
logger.info("Activating the DHCP connection " + connName);
shell.executeBashCommand("nmcli connection up \"${connection}\"".replace("${connection}", connName), false);
} catch (Exception e) {
logger.error("Exception while setting DHCP!", e);
Expand All @@ -201,16 +201,16 @@ private void setConnectionDHCP(NetworkConfig config) {
private void setConnectionStatic(NetworkConfig config) {
String connName = "static-" + config.networkManagerIface;
String addStaticCommand = """
nmcli connection add
con-name "${connection}"
ifname "${interface}"
type ethernet
autoconnect no
ipv4.addresses ${ipaddr}/8
ipv4.gateway ${gateway}
ipv4.method "manual"
ipv6.method "disabled"
""";
nmcli connection add
con-name "${connection}"
ifname "${interface}"
type ethernet
autoconnect no
ipv4.addresses ${ipaddr}/8
ipv4.gateway ${gateway}
ipv4.method "manual"
ipv6.method "disabled"
""";
addStaticCommand = addStaticCommand.replaceAll("[\\n]", " ");

String modStaticCommand = "nmcli connection mod \"${connection}\" ipv4.addresses ${ipaddr}/8 ipv4.gateway ${gateway}";
Expand All @@ -222,33 +222,31 @@ private void setConnectionStatic(NetworkConfig config) {

// guess at the gateway from the staticIp
String[] parts = config.staticIp.split("\\.");
parts[parts.length-1] = "1";
parts[parts.length - 1] = "1";
String gateway = String.join(".", parts);

var shell = new ShellExec();
try {
if (NetworkUtils.connDoesNotExist(connName)) {
// create connection
logger.info("Creating the Static connection " + connName );
logger.info("Creating the Static connection " + connName);
shell.executeBashCommand(
addStaticCommand
.replace("${connection}", connName)
.replace("${interface}", config.networkManagerIface)
.replace("${ipaddr}", config.staticIp)
.replace("${gateway}", gateway)
);
addStaticCommand
.replace("${connection}", connName)
.replace("${interface}", config.networkManagerIface)
.replace("${ipaddr}", config.staticIp)
.replace("${gateway}", gateway));
} else {
// modify it in case the static IP address is different
logger.info("Modifying the Static connection " + connName );
logger.info("Modifying the Static connection " + connName);
shell.executeBashCommand(
modStaticCommand
.replace("${connection}", connName)
.replace("${ipaddr}", config.staticIp)
.replace("${gateway}", gateway)
);
modStaticCommand
.replace("${connection}", connName)
.replace("${ipaddr}", config.staticIp)
.replace("${gateway}", gateway));
}
// activate it
logger.info("Activating the Static connection " + connName );
logger.info("Activating the Static connection " + connName);
shell.executeBashCommand("nmcli connection up \"${connection}\"".replace("${connection}", connName), false);
} catch (Exception e) {
logger.error("Error while setting static IP!", e);
Expand All @@ -268,7 +266,10 @@ private void monitorDevice(String devName, int millisInterval) {
return;
}
logger.debug("Watching network interface at path: " + path);
var last = new Object() {boolean carrier = true; boolean exceptionLogged = false;};
var last = new Object() {
boolean carrier = true;
boolean exceptionLogged = false;
};
Runnable task = () -> {
try {
boolean carrier = Files.readString(path).trim().equals("1");
Expand All @@ -283,14 +284,14 @@ private void monitorDevice(String devName, int millisInterval) {
}
last.carrier = carrier;
last.exceptionLogged = false;
} catch (Exception e) {
if (!last.exceptionLogged) {
// Log the exception only once, but keep trying
logger.error("Could not check network status for " + devName, e);
last.exceptionLogged = true;
}
} catch (Exception e) {
if (!last.exceptionLogged) {
// Log the exception only once, but keep trying
logger.error("Could not check network status for " + devName, e);
last.exceptionLogged = true;
}
};
}
};

TimedTaskManager.getInstance().addTask(taskName, task, millisInterval);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public static List<NMDeviceInfo> getAllInterfaces() {

var ret = new ArrayList<NMDeviceInfo>();

if (!Platform.isLinux()) {
if (!Platform.getCurrentPlatform().isLinux()) {
// Can only determine interface name on Linux, give up
return ret;
}
Expand Down Expand Up @@ -118,7 +118,8 @@ public static List<NMDeviceInfo> getAllInterfaces() {
}

public static List<NMDeviceInfo> getAllActiveInterfaces() {
// Seems like if an interface exists but isn't actually connected, the connection name will be
// Seems like if an interface exists but isn't actually connected, the
// connection name will be
// an empty string. Check here and only return connections with non-empty names
return getAllInterfaces().stream()
.filter(it -> !it.connName.trim().isEmpty())
Expand Down Expand Up @@ -159,7 +160,8 @@ public static NMDeviceInfo getNMinfoForDevName(String devName) {
public static boolean connDoesNotExist(String connName) {
var shell = new ShellExec(true, true);
try {
// set nmcli back to DHCP, and re-run dhclient -- this ought to grab a new IP address
// set nmcli back to DHCP, and re-run dhclient -- this ought to grab a new IP
// address
shell.executeBashCommand("nmcli -f GENERAL.STATE connection show \"" + connName + "\"");
return (shell.getExitCode() == 10);
} catch (Exception e) {
Expand Down
Loading
Loading