package com.ckkj.griddle.device; import android.annotation.SuppressLint; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.os.Handler; import com.ckkj.griddle.device.entity.BleBusinessFrames; import org.json.JSONException; import org.json.JSONObject; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.Arrays; import java.util.TimeZone; import java.util.UUID; /** 临时业务通道:所有入口均在会话主线程,GATT 写操作串行,设备上行 ACK 优先发送。 */ @SuppressLint("MissingPermission") final class GriddleBleDebugChannel { interface Listener { void onLog(String message); void onMessage(JSONObject message); void onReady(); void onFatal(String message); } private static final UUID SERVICE = UUID.fromString("44424301-0001-4dbc-8000-00805f9b34fb"); private static final UUID DOWN = UUID.fromString("44424304-0001-4dbc-8000-00805f9b34fb"); private static final UUID UP = UUID.fromString("44424305-0001-4dbc-8000-00805f9b34fb"); private static final UUID CCC = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private final BluetoothGatt gatt; private final Handler handler; private final Listener listener; private final BleBusinessFrames receiver = new BleBusinessFrames(); private final ArrayDeque acknowledgements = new ArrayDeque<>(); private final ArrayDeque fragments = new ArrayDeque<>(); private final ArrayDeque commands = new ArrayDeque<>(); private BluetoothGattCharacteristic down; private BluetoothGattCharacteristic up; private BluetoothGattDescriptor ccc; private boolean closed; private boolean ready; private boolean subscribing; private boolean negotiatingMtu; private boolean writing; private int payloadBytes = 12; // 默认 MTU 23:ATT 头 3 字节,协议头 8 字节。 private int transferId; private int outgoingId; private int outgoingTotal; private int acknowledged; private JSONObject active; private Runnable setupTimeout; private Runnable writeTimeout; private Runnable replyTimeout; GriddleBleDebugChannel(BluetoothGatt gatt, Handler handler, Listener listener) { this.gatt = gatt; this.handler = handler; this.listener = listener; } void start() { try { BluetoothGattService service = gatt.getService(SERVICE); down = service == null ? null : service.getCharacteristic(DOWN); up = service == null ? null : service.getCharacteristic(UP); ccc = up == null ? null : up.getDescriptor(CCC); if (down == null || up == null || ccc == null || (down.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0 || (up.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0) { fatal("设备缺少协议要求的 Down Write / Up Notify / CCC 特征"); return; } setupTimeout = () -> fatal("订阅通知或协商 MTU 超时,请重新连接"); handler.postDelayed(setupTimeout, 12_000L); if (!gatt.setCharacteristicNotification(up, true)) { fatal("开启本地 Notify 失败"); return; } subscribing = true; ccc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); if (!gatt.writeDescriptor(ccc)) fatal("提交 CCC 订阅失败"); else listener.onLog("正在订阅 Up Notify…"); } catch (RuntimeException e) { fatal("订阅通知失败,请检查蓝牙权限及连接"); } } void onDescriptorWrite(BluetoothGattDescriptor descriptor, int status) { if (closed || !subscribing || descriptor != ccc) return; subscribing = false; if (status != BluetoothGatt.GATT_SUCCESS) { fatal("CCC 订阅失败,GATT=" + status); return; } listener.onLog("Up Notify 订阅成功;开始协商 MTU"); try { negotiatingMtu = true; if (!gatt.requestMtu(517)) { negotiatingMtu = false; finishSetup(23); } } catch (RuntimeException e) { fatal("MTU 请求失败,请重新连接"); } } void onMtuChanged(int mtu, int status) { if (closed || !negotiatingMtu) return; negotiatingMtu = false; finishSetup(status == BluetoothGatt.GATT_SUCCESS ? mtu : 23); } private void finishSetup(int mtu) { if (closed) return; handler.removeCallbacks(setupTimeout); payloadBytes = Math.min(512, Math.max(23, mtu) - 3) - 8; ready = true; listener.onLog("通道就绪:MTU=" + mtu + ",单片 JSON 最大 " + payloadBytes + " 字节。不会自动轮询。"); listener.onReady(); // 协议要求连接后读取基本信息和状态;纯 BLE 版分别设置 UTC 和时区,不自动开启运行。 send("device.get", new JSONObject()); send("state.get", new JSONObject()); try { long now = System.currentTimeMillis(); send("time.set", new JSONObject().put("utcSec", now / 1000)); send("timezone.set", new JSONObject().put("utcOffsetMinutes", TimeZone.getDefault().getOffset(now) / 60_000)); } catch (JSONException e) { fatal("初始化业务 JSON 失败"); } writeNext(); } boolean isReady() { return ready && !closed; } boolean send(String type, JSONObject body) { if (!isReady() || commands.size() >= 8) return false; try { JSONObject command = new JSONObject().put("ver", 1).put("id", "app-" + UUID.randomUUID()) .put("type", type).put("body", body); commands.add(command); writeNext(); return true; } catch (JSONException e) { return false; } } private void beginCommand() { if (active != null || commands.isEmpty()) return; active = commands.remove(); byte[] bytes = active.toString().getBytes(StandardCharsets.UTF_8); outgoingId = transferId = (transferId + 1) & 0xFFFF; outgoingTotal = bytes.length; acknowledged = 0; for (int offset = 0; offset < bytes.length; offset += payloadBytes) { int end = Math.min(bytes.length, offset + payloadBytes); int flags = (offset == 0 ? 1 : 0) | (end == bytes.length ? 2 : 0); fragments.add(BleBusinessFrames.frame(flags, outgoingId, bytes.length, offset, Arrays.copyOfRange(bytes, offset, end))); } listener.onLog("发送请求:" + active.optString("type")); final JSONObject request = active; replyTimeout = () -> { if (closed || active != request) return; listener.onLog("请求超时,结果未确认(不自动重发) id=" + request.optString("id") + ",累计 ACK=" + acknowledged + "/" + outgoingTotal); active = null; fragments.clear(); writeNext(); }; handler.postDelayed(replyTimeout, 12_000L); } private void writeNext() { if (!isReady() || writing) return; if (acknowledgements.isEmpty() && fragments.isEmpty()) beginCommand(); byte[] packet = !acknowledgements.isEmpty() ? acknowledgements.poll() : fragments.poll(); if (packet == null) return; try { down.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); down.setValue(packet); writing = true; writeTimeout = () -> fatal("GATT 写操作超时,请重新连接"); handler.postDelayed(writeTimeout, 5_000L); if (!gatt.writeCharacteristic(down)) fatal("提交 Down 写操作失败"); } catch (RuntimeException e) { fatal("Down 写操作失败,请检查蓝牙权限及连接"); } } void onCharacteristicWrite(BluetoothGattCharacteristic characteristic, int status) { if (closed || characteristic != down || !writing) return; handler.removeCallbacks(writeTimeout); writing = false; if (status != BluetoothGatt.GATT_SUCCESS) { fatal("Down 写入失败,GATT=" + status); return; } writeNext(); } void onNotification(BluetoothGattCharacteristic characteristic, byte[] packet) { if (closed || characteristic != up) return; if (packet == null || packet.length < 8 || (packet[0] & 255) != 0xDB) { listener.onLog("忽略非 DB 格式通知(可检查固件协议版本)"); return; } int flags = packet[1] & 255; if (flags == 4 || flags == 12) { if (packet.length != 8 || active == null || BleBusinessFrames.unsigned16(packet, 2) != outgoingId || BleBusinessFrames.unsigned16(packet, 4) != outgoingTotal) return; int offset = BleBusinessFrames.unsigned16(packet, 6); if (offset > outgoingTotal || offset < acknowledged) return; acknowledged = offset; // ACK 继续参与传输确认,不再把底层通知和正常 ACK 显示在页面。 if (flags == 12) fatal("设备拒绝业务分片,请重新连接后重试"); return; } try { BleBusinessFrames.Result result = receiver.receive(packet); queueAcknowledgement(result.acknowledgement); if (result.json != null) receiveJson(result.json); } catch (IllegalArgumentException e) { listener.onLog("RX 分片错误:" + e.getMessage()); queueAcknowledgement(receiver.errorAcknowledgement(packet)); } } private void queueAcknowledgement(byte[] packet) { if (packet == null) return; // 设备窗口为 4;限制异常固件造成的积压,不能无限占用内存。 if (acknowledgements.size() >= 32) { fatal("上行通知超过 ACK 处理能力,请重新连接"); return; } acknowledgements.add(packet); writeNext(); } private void receiveJson(String raw) { try { JSONObject json = new JSONObject(raw); String type = json.optString("type"); boolean reply = "reply".equals(type); if (json.optInt("ver", -1) != 1) { listener.onLog("业务协议版本不匹配,忽略请求匹配"); return; } JSONObject body = json.optJSONObject("body"); if (body == null || type.isEmpty()) { listener.onLog("收到缺少 type/body 的业务消息,已忽略"); return; } if (!reply) { listener.onMessage(json); listener.onLog("收到设备主动上报:" + type); } if (reply && active != null && body != null && active.optString("id").equals(json.optString("id")) && active.optString("type").equals(body.optString("requestType"))) { // 只有匹配请求的业务 reply.code=OK 才代表执行成功,ACK 不修改开关状态。 listener.onLog("业务结果 " + body.optString("requestType") + ":" + body.optString("code") + ("OK".equals(body.optString("code")) ? "(执行成功)" : "(执行未成功)")); if ("OK".equals(body.optString("code"))) listener.onMessage(json); handler.removeCallbacks(replyTimeout); active = null; fragments.clear(); writeNext(); } } catch (JSONException e) { listener.onLog("收到无法解析的业务 JSON,已忽略"); } } private void fatal(String message) { if (closed) return; listener.onLog("通道错误:" + message); close(); listener.onFatal(message); } void close() { closed = true; ready = false; if (setupTimeout != null) handler.removeCallbacks(setupTimeout); if (writeTimeout != null) handler.removeCallbacks(writeTimeout); if (replyTimeout != null) handler.removeCallbacks(replyTimeout); acknowledgements.clear(); fragments.clear(); commands.clear(); active = null; } }