package chuankou; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; /** * 负责将串口调试相关配置持久化到 set.properties 文件。 */ public final class SerialPortPreferences { private static final String PROPERTIES_FILE = "set.properties"; private static final String KEY_PORT = "serialPortName"; private static final String KEY_BAUD = "serialBaudRate"; private static final String KEY_AUTO = "serialAutoConnect"; private static final int DEFAULT_BAUD = 115200; private SerialPortPreferences() { } public static String getPortName() { return readProperty(KEY_PORT); } public static void setPortName(String portName) { writeProperty(KEY_PORT, sanitizeString(portName)); } public static int getBaudRate() { String value = readProperty(KEY_BAUD); if (value == null) { return DEFAULT_BAUD; } try { return Integer.parseInt(value.trim()); } catch (NumberFormatException ex) { return DEFAULT_BAUD; } } public static void setBaudRate(int baudRate) { writeProperty(KEY_BAUD, String.valueOf(baudRate)); } public static boolean isAutoConnectEnabled() { String value = readProperty(KEY_AUTO); if (value == null) { return true; // 默认开启 } return Boolean.parseBoolean(value.trim()); } public static void setAutoConnectEnabled(boolean enabled) { writeProperty(KEY_AUTO, Boolean.toString(enabled)); } private static String readProperty(String key) { Properties props = new Properties(); try (FileInputStream in = new FileInputStream(PROPERTIES_FILE)) { props.load(in); String value = props.getProperty(key); if (value == null || value.trim().isEmpty() || "-1".equals(value.trim())) { return null; } return value.trim(); } catch (IOException ex) { return null; } } private static void writeProperty(String key, String value) { synchronized (SerialPortPreferences.class) { Properties props = new Properties(); try (FileInputStream in = new FileInputStream(PROPERTIES_FILE)) { props.load(in); } catch (IOException ignored) { // 文件不存在时使用空配置 } if (value == null || value.trim().isEmpty()) { props.setProperty(key, "-1"); } else { props.setProperty(key, value.trim()); } try (FileOutputStream out = new FileOutputStream(PROPERTIES_FILE)) { props.store(out, "Serial Port Preferences Updated"); } catch (IOException ex) { System.err.println("保存串口配置失败: " + ex.getMessage()); } } } private static String sanitizeString(String value) { if (value == null) { return null; } String trimmed = value.trim(); return trimmed.isEmpty() ? null : trimmed; } }