package com.mes.util; import com.mes.ui.MesClient; import javax.bluetooth.*; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnection; import java.io.*; public class BluetoothUtils { // 目标设备地址 二线:001135390238 k3:00113538028A 一线:001135390246 private static final String TARGET_DEVICE_ADDRESS = "001135390238"; // 标志位 private static volatile boolean isRunning = true; // 【关键修改】将连接对象和流对象提升为静态变量,保持持久化 private static StreamConnection connection; private static InputStream is; private static BufferedReader reader; public static void init() { try { LocalDevice localDevice = LocalDevice.getLocalDevice(); System.out.println("本地蓝牙名称: " + localDevice.getFriendlyName()); System.out.println("将尝试连接到设备地址: " + TARGET_DEVICE_ADDRESS); String btsppUrl = "btspp://" + TARGET_DEVICE_ADDRESS + ":1;authenticate=false;encrypt=false;master=false"; // 在新线程中连接,避免阻塞 new Thread(() -> { try { // 如果已经连接,先跳过 if (connection != null && MesClient.com_connect_flag) { return; } System.out.println("尝试建立蓝牙连接..."); // 建立连接 connection = (StreamConnection) Connector.open(btsppUrl); // 【关键修改】连接成功后立即初始化流,并保持打开状态 if (connection != null) { is = connection.openInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); MesClient.com_connect_flag = true; System.out.println("蓝牙连接成功,输入流已就绪"); } } catch (IOException e) { System.err.println("蓝牙连接失败: " + e.getMessage()); closeConnection(); // 连接失败清理资源 } }).start(); } catch (BluetoothStateException e) { e.printStackTrace(); } } /** * 接收数据并解析重量 (复用已有的连接和流) */ public static String connectAndReceiveData() { // 1. 检查连接状态 if (connection == null || reader == null || !MesClient.com_connect_flag) { System.err.println("错误: 蓝牙未连接"); return "未连接"; } try { long startTime = System.currentTimeMillis(); long timeout = 2000; // 3秒超时 // 清空缓冲区旧数据(可选,视称重仪表特性而定) while (reader.ready()) { reader.readLine(); } System.out.println("开始读取重量数据..."); // 2. 循环读取直到超时或获取到数据 while ((System.currentTimeMillis() - startTime < timeout)) { // 使用 ready() 避免 readLine() 在没有数据时无限阻塞 if (reader.ready()) { String data = reader.readLine(); if (data != null) { System.out.println("收到数据: " + data); String wet = extractWeight(data); if (wet != null && !wet.equals("")) { return wet; } } } else { // 没有数据时短暂休眠 Thread.sleep(100); } } System.out.println("读取超时"); return "超时"; } catch (IOException | InterruptedException e) { System.err.println("读取数据异常: " + e.getMessage()); // 【关键修改】只有在发生真实IO异常时才关闭连接,触发重连 closeConnection(); return "异常"; } // 【关键修改】这里去掉了 finally { close() },确保连接不被切断 } /** * 关闭蓝牙连接并重置资源 */ public static void closeConnection() { isRunning = false; MesClient.com_connect_flag = false; try { if (reader != null) { reader.close(); reader = null; } if (is != null) { is.close(); is = null; } if (connection != null) { connection.close(); connection = null; } System.out.println("蓝牙资源已释放"); } catch (IOException e) { e.printStackTrace(); } } // 解析重量 public static String extractWeight(String input) { if (input == null) return null; java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\d+(?:\\.\\d+)?\\s*kg", java.util.regex.Pattern.CASE_INSENSITIVE); java.util.regex.Matcher matcher = pattern.matcher(input); if (matcher.find()) { return matcher.group().trim(); } // 如果没有kg单位,尝试直接提取数字(视仪表格式调整) try { // 简单的数字提取备用方案 String num = input.replaceAll("[^0-9.]", ""); if(!num.isEmpty()) return num + "kg"; } catch(Exception e){} return ""; } }