package chuankou; import java.nio.charset.StandardCharsets; /** * 串口发送入口,统一封装发送流程便于跨模块调用。 */ public final class sendmessage { private static final SerialPortService DEFAULT_SERVICE = new SerialPortService(); private static volatile SerialPortService activeService = DEFAULT_SERVICE; private sendmessage() { // utility class } /** * 发送原始字节数据。 * * @param data 待发送字节 * @return true 表示发送成功 */ public static boolean send(byte[] data) { if (data == null || data.length == 0) { return false; } SerialPortService service = getActiveService(); if (service == null || !service.isOpen()) { return false; } return service.send(data); } /** * 发送十六进制字符串(允许包含空格)。 */ public static boolean sendHex(String hexString) { byte[] data = hexToBytes(hexString); return data != null && send(data); } /** * 发送 UTF-8 文本。 */ public static boolean sendText(String text) { if (text == null || text.isEmpty()) { return false; } return send(text.getBytes(StandardCharsets.UTF_8)); } /** * 将外部打开的串口实例注入发送器,避免重复打开。 */ public static void attachService(SerialPortService serialPortService) { if (serialPortService == null) { return; } synchronized (sendmessage.class) { // 这里假设调用方提供的 service 已经成功打开串口 if (serialPortService.isOpen()) { activeService = serialPortService; } } } /** * 获取当前使用的串口服务。 */ public static SerialPortService getActiveService() { SerialPortService service = activeService; return service != null ? service : DEFAULT_SERVICE; } /** * 通过活动串口服务发送数据(保证引用同步)。 */ public static boolean sendViaActive(byte[] data) { SerialPortService service = getActiveService(); if (service == null || !service.isOpen()) { return false; } return service.send(data); } private static byte[] hexToBytes(String hexString) { if (hexString == null) { return null; } String normalized = hexString.replaceAll("\\s+", "").toUpperCase(); if (normalized.length() == 0 || normalized.length() % 2 != 0) { return null; } byte[] result = new byte[normalized.length() / 2]; for (int i = 0; i < normalized.length(); i += 2) { int high = Character.digit(normalized.charAt(i), 16); int low = Character.digit(normalized.charAt(i + 1), 16); if (high < 0 || low < 0) { return null; } result[i / 2] = (byte) ((high << 4) + low); } return result; } }