纯蓝牙通信,个人中心相关。
This commit is contained in:
231
app/src/main/java/com/ckkj/griddle/device/BleDebugActivity.java
Normal file
231
app/src/main/java/com/ckkj/griddle/device/BleDebugActivity.java
Normal file
@@ -0,0 +1,231 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseActivity;
|
||||
import com.ckkj.griddle.databinding.BleDebugLayoutBinding;
|
||||
import com.ckkj.griddle.device.entity.BleDeviceSnapshot;
|
||||
import com.ckkj.griddle.device.mvp.DeviceContract;
|
||||
import com.ckkj.griddle.device.mvp.DeviceImpl;
|
||||
import com.ckkj.griddle.device.mvp.DevicePresenter;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
import com.gyf.immersionbar.ImmersionBar;
|
||||
|
||||
import butterknife.OnClick;
|
||||
|
||||
/** 纯 BLE 临时联调页:按协议展示设备字段,保留简短的操作结果。 */
|
||||
public class BleDebugActivity extends BaseActivity<BleDebugLayoutBinding, DevicePresenter>
|
||||
implements DeviceContract.DeviceView {
|
||||
private GriddleProvisioningSession session;
|
||||
private String token;
|
||||
private boolean renderPending;
|
||||
private String displayedLog;
|
||||
private final Runnable renderTask = () -> {
|
||||
renderPending = false;
|
||||
renderSession();
|
||||
};
|
||||
private final GriddleProvisioningSession.Listener listener = () -> {
|
||||
// 多个业务回调合并刷新,避免反复重绘整个页面。
|
||||
if (!renderPending) {
|
||||
renderPending = true;
|
||||
viewBinding.tvBleLog.postDelayed(renderTask, 100L);
|
||||
}
|
||||
};
|
||||
|
||||
@Override public DevicePresenter createPresenter() { return new DevicePresenter(new DeviceImpl()); }
|
||||
@Override public int getLayoutResId(Bundle savedInstanceState) { return 0; }
|
||||
|
||||
@Override
|
||||
public void initData(Bundle savedInstanceState) {
|
||||
super.initData(savedInstanceState);
|
||||
ImmersionBar.with(this).statusBarColor(android.R.color.white).statusBarDarkFont(true).init();
|
||||
session = GriddleProvisioningSession.get(this);
|
||||
token = getIntent().getStringExtra(WifiListActivity.EXTRA_SESSION_TOKEN);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
session.attach(listener);
|
||||
renderSession();
|
||||
if (session.matches(token)) session.startBusinessDebug(token);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
session.detach(listener);
|
||||
viewBinding.tvBleLog.removeCallbacks(renderTask);
|
||||
renderPending = false;
|
||||
// 不发起轮询;后台不更新 UI,会话只保留有界日志,恢复后继续查看。
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
private void renderSession() {
|
||||
if (isFinishing() || isDestroyed()) return;
|
||||
if (!session.matches(token)) {
|
||||
showMessage(getString(R.string.wifi_setup_reconnect_required));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
viewBinding.tvBleDevice.setText(getString(R.string.ble_debug_device,
|
||||
session.getDeviceName(), session.getSku(), session.getFirmwareVersion()));
|
||||
viewBinding.tvBleStatus.setText(session.isConnected() ? session.getBusinessStatus()
|
||||
: getString(session.getErrorRes() != 0 ? session.getErrorRes() : R.string.wifi_setup_disconnected));
|
||||
boolean ready = session.isBusinessReady();
|
||||
viewBinding.btnBleDeviceGet.setEnabled(ready);
|
||||
viewBinding.btnBleStateGet.setEnabled(ready);
|
||||
viewBinding.btnBlePowerOn.setEnabled(ready);
|
||||
viewBinding.btnBlePowerOff.setEnabled(ready);
|
||||
renderSnapshot(session.getBusinessSnapshot());
|
||||
String log = session.getBusinessLog();
|
||||
if (!TextUtils.equals(displayedLog, log)) {
|
||||
displayedLog = log;
|
||||
viewBinding.tvBleLog.setText(log);
|
||||
}
|
||||
}
|
||||
|
||||
private void renderSnapshot(BleDeviceSnapshot data) {
|
||||
StringBuilder device = new StringBuilder();
|
||||
row(device, R.string.ble_field_mac_address, data.deviceText("macAddress"));
|
||||
row(device, R.string.ble_field_base_mac, data.deviceText("baseMac"));
|
||||
row(device, R.string.ble_field_device_type, data.deviceText("deviceType"));
|
||||
row(device, R.string.ble_field_serial_number, data.deviceText("serialNumber"));
|
||||
row(device, R.string.ble_field_firmware, data.deviceText("firmwareVersion"));
|
||||
row(device, R.string.ble_field_hardware, data.deviceText("hardwareVersion"));
|
||||
row(device, R.string.ble_field_sku, data.deviceText("sku"));
|
||||
viewBinding.tvBleDeviceFields.setText(device);
|
||||
|
||||
StringBuilder measurements = new StringBuilder();
|
||||
row(measurements, R.string.ble_field_voltage, data.number("voltageV", "V"));
|
||||
row(measurements, R.string.ble_field_current1, data.number("currentChannel1A", "A"));
|
||||
row(measurements, R.string.ble_field_current2, data.number("currentChannel2A", "A"));
|
||||
row(measurements, R.string.ble_field_power, data.number("powerW", "W"));
|
||||
String temperature = data.number("temperatureC", "℃");
|
||||
row(measurements, R.string.ble_field_temperature, "--".equals(temperature)
|
||||
? getString(R.string.ble_debug_temperature_unavailable) : temperature);
|
||||
row(measurements, R.string.ble_field_leakage, data.number("leakageCurrentMa", "mA"));
|
||||
row(measurements, R.string.ble_field_total_energy, data.number("totalEnergyKWh", "kWh"));
|
||||
row(measurements, R.string.ble_field_today_energy, data.number("todayEnergyKWh", "kWh"));
|
||||
viewBinding.tvBleMeasurements.setText(measurements);
|
||||
|
||||
StringBuilder running = new StringBuilder();
|
||||
row(running, R.string.ble_field_power_on, boolText(data.bool("powerOn"), R.string.ble_debug_on, R.string.ble_debug_off));
|
||||
row(running, R.string.ble_field_heating, boolText(data.bool("heating"), R.string.ble_debug_heating, R.string.ble_debug_not_heating));
|
||||
row(running, R.string.ble_field_running_state, runningStateText(data.stateText("runningState")));
|
||||
row(running, R.string.ble_field_remaining, data.number("remainingSec", getString(R.string.ble_debug_seconds)));
|
||||
viewBinding.tvBleRunning.setText(running);
|
||||
|
||||
Long faultBits = data.faultBits();
|
||||
viewBinding.tvBleFaults.setText(faultText(faultBits));
|
||||
viewBinding.tvBleFaults.setTextColor(faultBits != null && faultBits != 0
|
||||
? getColor(android.R.color.holo_red_dark) : getColor(android.R.color.darker_gray));
|
||||
if (data.getReceivedAt() == 0) {
|
||||
viewBinding.tvBleDataTime.setText(R.string.ble_debug_waiting_state);
|
||||
} else {
|
||||
Long deviceTs = data.getDeviceTimestamp();
|
||||
String deviceTime = deviceTs == null ? "--" : deviceTs == 0
|
||||
? getString(R.string.ble_debug_time_not_set)
|
||||
: deviceTs > 0 && deviceTs <= 253402300799L ? dateTime(deviceTs * 1000) : "--";
|
||||
viewBinding.tvBleDataTime.setText(getString(R.string.ble_debug_updated,
|
||||
dateTime(data.getReceivedAt()), data.getSource(), deviceTime));
|
||||
}
|
||||
}
|
||||
|
||||
private void row(StringBuilder text, int label, String value) {
|
||||
if (text.length() > 0) text.append('\n');
|
||||
text.append(getString(R.string.ble_debug_field, getString(label), value));
|
||||
}
|
||||
|
||||
private String boolText(Boolean value, int whenTrue, int whenFalse) {
|
||||
return value == null ? "--" : getString(value ? whenTrue : whenFalse);
|
||||
}
|
||||
|
||||
private String runningStateText(String state) {
|
||||
switch (state) {
|
||||
case "idle": return getString(R.string.ble_debug_idle);
|
||||
case "holding": return getString(R.string.ble_debug_holding);
|
||||
case "heating": return getString(R.string.ble_debug_heating);
|
||||
case "tripped": return getString(R.string.ble_debug_tripped);
|
||||
default: return state;
|
||||
}
|
||||
}
|
||||
|
||||
private String faultText(Long bits) {
|
||||
if (bits == null) return "--";
|
||||
if (bits == 0) return getString(R.string.ble_debug_no_fault);
|
||||
int[] descriptions = {R.string.ble_debug_fault_e01, R.string.ble_debug_fault_e02,
|
||||
R.string.ble_debug_fault_e03, R.string.ble_debug_fault_e04, R.string.ble_debug_fault_e05,
|
||||
R.string.ble_debug_fault_e06, R.string.ble_debug_fault_e07, R.string.ble_debug_fault_e08};
|
||||
StringBuilder text = new StringBuilder(getString(R.string.ble_debug_fault_bits, bits));
|
||||
// 多种故障可同时发生,按位展示;不从温度自行推导故障。
|
||||
for (int bit = 0; bit < descriptions.length; bit++) {
|
||||
if ((bits & (1L << bit)) != 0) text.append('\n').append(getString(descriptions[bit]));
|
||||
}
|
||||
if ((bits & ~255L) != 0) text.append('\n').append(getString(R.string.ble_debug_unknown_fault, bits & ~255L));
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private String dateTime(long millis) {
|
||||
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
|
||||
.format(new java.util.Date(millis));
|
||||
}
|
||||
|
||||
@OnClick({R.id.btn_ble_device_get, R.id.btn_ble_state_get, R.id.btn_ble_power_on,
|
||||
R.id.btn_ble_power_off, R.id.btn_ble_clear, R.id.btn_ble_back})
|
||||
public void onClick(View v) {
|
||||
switch (v.getId()) {
|
||||
case R.id.btn_ble_device_get:
|
||||
sendCommand("device.get");
|
||||
break;
|
||||
case R.id.btn_ble_state_get:
|
||||
sendCommand("state.get");
|
||||
break;
|
||||
case R.id.btn_ble_power_on:
|
||||
// 明确告知该开关会开启设备运行/加热,不把它当成普通指示灯操作。
|
||||
new AlertDialog.Builder(this).setMessage(R.string.ble_debug_start_confirm)
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
.setPositiveButton(android.R.string.ok, (dialog, which) -> sendCommand("debug.power.on"))
|
||||
.show();
|
||||
break;
|
||||
case R.id.btn_ble_power_off:
|
||||
sendCommand("debug.power.off");
|
||||
break;
|
||||
case R.id.btn_ble_clear:
|
||||
session.clearBusinessLog(token);
|
||||
break;
|
||||
case R.id.btn_ble_back:
|
||||
finish();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void sendCommand(String type) {
|
||||
if (!session.sendBusinessCommand(token, type)) {
|
||||
ToastUtil.showShort(this, getString(R.string.ble_debug_not_ready));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
viewBinding.tvBleLog.removeCallbacks(renderTask);
|
||||
if (session != null) {
|
||||
session.detach(listener);
|
||||
// 重建页面不重复订阅、不重复校时;真正退出才释放原业务 GATT。
|
||||
if (!isChangingConfigurations()) session.close(token);
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override public void showError(String message) {
|
||||
if (!TextUtils.isEmpty(message)) ToastUtil.showShort(this, message);
|
||||
}
|
||||
@Override public void logOut(BaseBean bean) { }
|
||||
}
|
||||
@@ -74,7 +74,7 @@ public class BltDeviceListActivity
|
||||
}
|
||||
});
|
||||
|
||||
// Wi-Fi 页面退出后释放旧会话并重新搜索,返回时可直接选择其他设备。
|
||||
// Wi-Fi 或纯 BLE 调试页退出后释放旧会话并重新搜索,可直接选择其他设备。
|
||||
private final ActivityResultLauncher<Intent> wifiLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(), result -> {
|
||||
provisioning.close(connectionToken);
|
||||
@@ -317,8 +317,13 @@ public class BltDeviceListActivity
|
||||
openingWifi = true;
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putString(WifiListActivity.EXTRA_SESSION_TOKEN, connectionToken);
|
||||
// 会话所有权交给 Wi-Fi 页面;当前页留在返回栈,离开前台时只停止扫描。
|
||||
goTo(mContext, WifiListActivity.class, bundle, wifiLauncher);
|
||||
// 两个版本广播名相同,必须等 Info 读取完成后按 sku 分流,不能按 MAC 或名称猜测。
|
||||
// 页面继续复用同一会话,避免先断开再重连导致错过上报。
|
||||
if (provisioning.isBleOnly()) {
|
||||
goTo(mContext, BleDebugActivity.class, bundle, wifiLauncher);
|
||||
} else {
|
||||
goTo(mContext, WifiListActivity.class, bundle, wifiLauncher);
|
||||
}
|
||||
} else if (provisioning.getState() == GriddleProvisioningSession.State.FAILED) {
|
||||
hideDialogLoading();
|
||||
int error = provisioning.getErrorRes();
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
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<byte[]> acknowledgements = new ArrayDeque<>();
|
||||
private final ArrayDeque<byte[]> fragments = new ArrayDeque<>();
|
||||
private final ArrayDeque<JSONObject> 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;
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import android.util.Log;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
import com.ckkj.griddle.device.entity.BleDeviceSnapshot;
|
||||
import com.ckkj.griddle.device.entity.WifiNetwork;
|
||||
import com.ckkj.griddle.device.entity.WifiProvisioningInput;
|
||||
import com.ckkj.griddle.device.entity.WifiProvisioningProgress;
|
||||
@@ -83,6 +84,11 @@ public final class GriddleProvisioningSession {
|
||||
private Runnable disconnectGrace;
|
||||
private final WifiProvisioningProgress progress = new WifiProvisioningProgress();
|
||||
private int provisioningNotice;
|
||||
private GriddleBleDebugChannel businessChannel;
|
||||
private final ArrayDeque<String> businessLog = new ArrayDeque<>();
|
||||
private int businessLogCharacters;
|
||||
private String businessStatus = "尚未订阅业务通知";
|
||||
private BleDeviceSnapshot businessSnapshot = new BleDeviceSnapshot();
|
||||
|
||||
private GriddleProvisioningSession(Context context) { this.context = context.getApplicationContext(); }
|
||||
|
||||
@@ -108,6 +114,104 @@ public final class GriddleProvisioningSession {
|
||||
public ConnectionMode getConnectionMode() { return connectionMode; }
|
||||
public String getDeviceId() { return deviceId; }
|
||||
public String getSku() { return sku; }
|
||||
public boolean isBleOnly() { return "ble_only".equals(sku); }
|
||||
public boolean isBusinessReady() { return businessChannel != null && businessChannel.isReady() && isConnected(); }
|
||||
public String getBusinessStatus() { return businessStatus; }
|
||||
public BleDeviceSnapshot getBusinessSnapshot() { return businessSnapshot; }
|
||||
public String getBusinessLog() {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (String entry : businessLog) text.append(entry).append('\n');
|
||||
return text.toString();
|
||||
}
|
||||
public void clearBusinessLog(String token) {
|
||||
if (!matches(token)) return;
|
||||
businessLog.clear();
|
||||
businessLogCharacters = 0;
|
||||
publish();
|
||||
}
|
||||
|
||||
/** 仅对已读取 Info 确认为纯 BLE 的连接启用临时通道,复用原 GATT。 */
|
||||
public void startBusinessDebug(String token) {
|
||||
if (!matches(token) || !isConnected() || !isBleOnly() || probe == null || businessChannel != null) return;
|
||||
businessStatus = "正在订阅业务通知";
|
||||
Map<String, Object> info = new HashMap<>();
|
||||
info.put("macAddress", deviceId);
|
||||
info.put("firmwareVersion", firmwareVersion);
|
||||
info.put("sku", sku);
|
||||
businessSnapshot.updateDevice(info);
|
||||
appendBusinessLog("Info deviceId=" + deviceId + ", sku=" + sku + ", firmware=" + firmwareVersion);
|
||||
businessChannel = new GriddleBleDebugChannel(probe, handler, new GriddleBleDebugChannel.Listener() {
|
||||
@Override public void onLog(String message) { appendBusinessLog(message); }
|
||||
@Override public void onMessage(JSONObject message) { updateBusinessSnapshot(message); }
|
||||
@Override public void onReady() {
|
||||
businessStatus = "正在监听 Up Notify(无自动轮询)";
|
||||
publish();
|
||||
}
|
||||
@Override public void onFatal(String message) {
|
||||
businessStatus = message;
|
||||
fail(R.string.ble_debug_channel_failed);
|
||||
}
|
||||
});
|
||||
businessChannel.start();
|
||||
}
|
||||
|
||||
private void updateBusinessSnapshot(JSONObject message) {
|
||||
JSONObject body = message.optJSONObject("body");
|
||||
if (body == null) return;
|
||||
boolean reply = "reply".equals(message.optString("type"));
|
||||
JSONObject fields = reply ? body.optJSONObject("data") : body;
|
||||
if (fields == null) return;
|
||||
Map<String, Object> values = new HashMap<>();
|
||||
java.util.Iterator<String> keys = fields.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
Object value = fields.opt(key);
|
||||
values.put(key, value == JSONObject.NULL ? null : value);
|
||||
}
|
||||
String source = reply ? body.optString("requestType") : message.optString("type");
|
||||
if (reply && "device.get".equals(source)) businessSnapshot.updateDevice(values);
|
||||
else {
|
||||
// 查询回复取 body.data,主动上报取 body;仅合并协议定义的状态字段。
|
||||
Long deviceTs = message.opt("ts") instanceof Number ? message.optLong("ts") : null;
|
||||
businessSnapshot.updateState(values, System.currentTimeMillis(), source, deviceTs);
|
||||
}
|
||||
publish();
|
||||
}
|
||||
|
||||
/** 调试页只允许白名单操作;启动必须显式点击,不提供任意寄存器或继电器写入。 */
|
||||
public boolean sendBusinessCommand(String token, String type) {
|
||||
if (!matches(token) || !isBusinessReady()) return false;
|
||||
try {
|
||||
JSONObject body = new JSONObject();
|
||||
switch (type) {
|
||||
case "device.get":
|
||||
case "state.get":
|
||||
break;
|
||||
case "debug.power.on":
|
||||
type = "control.set";
|
||||
body.put("power", "on").put("durationSec", 600);
|
||||
break;
|
||||
case "debug.power.off":
|
||||
type = "control.set";
|
||||
body.put("power", "off");
|
||||
break;
|
||||
default: return false;
|
||||
}
|
||||
return businessChannel.send(type, body);
|
||||
} catch (org.json.JSONException e) { return false; }
|
||||
}
|
||||
|
||||
private void appendBusinessLog(String message) {
|
||||
String entry = new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault())
|
||||
.format(new java.util.Date()) + " " + message;
|
||||
businessLog.add(entry);
|
||||
businessLogCharacters += entry.length();
|
||||
// 调试日志只保存在内存,保留最近 200 条/约 64K 字符,避免长时间监听导致页面卡顿。
|
||||
while (businessLog.size() > 200 || businessLogCharacters > 65_536) {
|
||||
businessLogCharacters -= businessLog.remove().length();
|
||||
}
|
||||
publish();
|
||||
}
|
||||
public String getFirmwareVersion() { return firmwareVersion; }
|
||||
public int getInfoWarningRes() { return infoWarningRes; }
|
||||
public boolean supportsWifiScan() {
|
||||
@@ -123,6 +227,10 @@ public final class GriddleProvisioningSession {
|
||||
/** 第一步只建立 BLE 连接;业务服务和配网服务都可以连接,缺少配网服务不是连接失败。 */
|
||||
public String connect(BleScanDevice device) {
|
||||
releaseTransport();
|
||||
businessLog.clear();
|
||||
businessLogCharacters = 0;
|
||||
businessStatus = "尚未订阅业务通知";
|
||||
businessSnapshot = new BleDeviceSnapshot();
|
||||
token = UUID.randomUUID().toString();
|
||||
deviceName = device.getName();
|
||||
address = device.getAddress();
|
||||
@@ -245,6 +353,39 @@ public final class GriddleProvisioningSession {
|
||||
handleBusinessInfo(attempt, gatt, characteristic, status, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
@Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
handler.post(() -> {
|
||||
if (isCurrentGatt(attempt, gatt) && businessChannel != null) businessChannel.onDescriptorWrite(descriptor, status);
|
||||
});
|
||||
}
|
||||
|
||||
@Override public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
|
||||
handler.post(() -> {
|
||||
if (isCurrentGatt(attempt, gatt) && businessChannel != null) businessChannel.onMtuChanged(mtu, status);
|
||||
});
|
||||
}
|
||||
|
||||
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
handler.post(() -> {
|
||||
if (isCurrentGatt(attempt, gatt) && businessChannel != null) businessChannel.onCharacteristicWrite(characteristic, status);
|
||||
});
|
||||
}
|
||||
|
||||
@Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
|
||||
byte[] value = characteristic.getValue();
|
||||
forwardNotification(gatt, characteristic, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
@Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) {
|
||||
forwardNotification(gatt, characteristic, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
private void forwardNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) {
|
||||
handler.post(() -> {
|
||||
if (isCurrentGatt(attempt, gatt) && businessChannel != null) businessChannel.onNotification(characteristic, value);
|
||||
});
|
||||
}
|
||||
|
||||
private void handleDescription(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status, byte[] value) {
|
||||
handler.post(() -> {
|
||||
if (!isCurrentGatt(attempt, gatt) || state != State.CONNECTING) return;
|
||||
@@ -556,6 +697,10 @@ public final class GriddleProvisioningSession {
|
||||
progress.fail();
|
||||
provisioningNotice = errorRes;
|
||||
}
|
||||
if (businessChannel != null) {
|
||||
businessStatus = context.getString(errorRes);
|
||||
appendBusinessLog("连接结束:" + businessStatus);
|
||||
}
|
||||
Log.w(TAG, "BLE session stopped: " + context.getString(errorRes));
|
||||
releaseTransport();
|
||||
this.errorRes = errorRes;
|
||||
@@ -586,6 +731,8 @@ public final class GriddleProvisioningSession {
|
||||
private void releaseTransport() {
|
||||
// 让旧连接的异步回调失效;超时和退出都需要关闭 GATT,不能仅隐藏 loading。
|
||||
generation++;
|
||||
if (businessChannel != null) businessChannel.close();
|
||||
businessChannel = null;
|
||||
if (disconnectGrace != null) handler.removeCallbacks(disconnectGrace);
|
||||
disconnectGrace = null;
|
||||
clearTimeout();
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** 业务 BLE 的 DB 分片协议;先按字节重组,避免中文被跨片 UTF-8 截断。 */
|
||||
public final class BleBusinessFrames {
|
||||
public static final int MAX_JSON_BYTES = 4096;
|
||||
private int id = -1;
|
||||
private byte[] message;
|
||||
private int received;
|
||||
private boolean delivered;
|
||||
|
||||
public static int unsigned16(byte[] bytes, int offset) {
|
||||
return ((bytes[offset] & 255) << 8) | (bytes[offset + 1] & 255);
|
||||
}
|
||||
|
||||
public static byte[] frame(int flags, int id, int total, int offset, byte[] payload) {
|
||||
ByteBuffer bytes = ByteBuffer.allocate(8 + payload.length);
|
||||
bytes.put((byte) 0xDB).put((byte) flags).putShort((short) id)
|
||||
.putShort((short) total).putShort((short) offset).put(payload);
|
||||
return bytes.array();
|
||||
}
|
||||
|
||||
public static final class Result {
|
||||
public final byte[] acknowledgement;
|
||||
public final String json;
|
||||
public final boolean duplicate;
|
||||
private Result(byte[] ack, String json, boolean duplicate) {
|
||||
this.acknowledgement = ack;
|
||||
this.json = json;
|
||||
this.duplicate = duplicate;
|
||||
}
|
||||
}
|
||||
|
||||
public Result receive(byte[] packet) {
|
||||
if (packet == null || packet.length < 8 || (packet[0] & 255) != 0xDB) {
|
||||
throw new IllegalArgumentException("无效 DB 分片头");
|
||||
}
|
||||
int flags = packet[1] & 255;
|
||||
int transfer = unsigned16(packet, 2);
|
||||
int total = unsigned16(packet, 4);
|
||||
int offset = unsigned16(packet, 6);
|
||||
int length = packet.length - 8;
|
||||
if ((flags & ~3) != 0 || total < 1 || total > MAX_JSON_BYTES || length < 1
|
||||
|| offset + length > total || ((flags & 1) != 0 && offset != 0)
|
||||
|| ((flags & 2) != 0 && offset + length != total)) {
|
||||
throw new IllegalArgumentException("分片长度或标志不合法");
|
||||
}
|
||||
if ((flags & 1) != 0 && transfer != id) {
|
||||
id = transfer;
|
||||
message = new byte[total];
|
||||
received = 0;
|
||||
delivered = false;
|
||||
}
|
||||
if (transfer != id || message == null || total != message.length || offset > received) {
|
||||
throw new IllegalArgumentException("分片编号、总长或偏移不连续");
|
||||
}
|
||||
boolean duplicate = offset < received;
|
||||
if (duplicate) {
|
||||
if (offset + length > received || !Arrays.equals(Arrays.copyOfRange(message, offset, offset + length),
|
||||
Arrays.copyOfRange(packet, 8, packet.length))) {
|
||||
throw new IllegalArgumentException("重复分片内容不一致");
|
||||
}
|
||||
} else {
|
||||
System.arraycopy(packet, 8, message, received, length);
|
||||
received += length;
|
||||
}
|
||||
String json = null;
|
||||
if (received == total && (flags & 2) != 0 && !delivered) {
|
||||
try {
|
||||
json = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(message)).toString();
|
||||
} catch (CharacterCodingException e) {
|
||||
throw new IllegalArgumentException("JSON 包含无效 UTF-8", e);
|
||||
}
|
||||
delivered = true;
|
||||
}
|
||||
return new Result(frame(4, id, total, received, new byte[0]), json, duplicate);
|
||||
}
|
||||
|
||||
/** 错帧按已累计长度回复 ERROR,通知设备从期望位置恢复。 */
|
||||
public byte[] errorAcknowledgement(byte[] packet) {
|
||||
if (packet == null || packet.length < 8 || (packet[0] & 255) != 0xDB) return null;
|
||||
int transfer = unsigned16(packet, 2);
|
||||
return frame(12, transfer, unsigned16(packet, 4), transfer == id ? received : 0, new byte[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 协议字段的最新快照。缺失字段保留旧值,显式 null 清空;电量始终覆盖,绝不累加。 */
|
||||
public final class BleDeviceSnapshot {
|
||||
private static final List<String> DEVICE_KEYS = Arrays.asList("macAddress", "baseMac", "deviceType",
|
||||
"serialNumber", "firmwareVersion", "hardwareVersion", "sku");
|
||||
private static final List<String> STATE_KEYS = Arrays.asList("voltageV", "currentChannel1A", "currentChannel2A",
|
||||
"powerW", "temperatureC", "leakageCurrentMa", "totalEnergyKWh", "todayEnergyKWh",
|
||||
"powerOn", "heating", "runningState", "faultBits", "remainingSec");
|
||||
private final Map<String, Object> device = new HashMap<>();
|
||||
private final Map<String, Object> state = new HashMap<>();
|
||||
private long receivedAt;
|
||||
private String source;
|
||||
private Long deviceTimestamp;
|
||||
|
||||
public void updateDevice(Map<String, Object> fields) { merge(device, fields, DEVICE_KEYS); }
|
||||
|
||||
public void updateState(Map<String, Object> fields, long receivedAt, String source, Long deviceTimestamp) {
|
||||
if (merge(state, fields, STATE_KEYS)) {
|
||||
this.receivedAt = receivedAt;
|
||||
this.source = source;
|
||||
this.deviceTimestamp = deviceTimestamp;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean merge(Map<String, Object> target, Map<String, Object> fields, List<String> keys) {
|
||||
boolean changed = false;
|
||||
for (String key : keys) {
|
||||
if (fields.containsKey(key)) {
|
||||
target.put(key, fields.get(key));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
public String deviceText(String key) { return text(device.get(key)); }
|
||||
public String stateText(String key) { return text(state.get(key)); }
|
||||
private static String text(Object value) {
|
||||
return value instanceof String && !((String) value).isEmpty() ? (String) value : "--";
|
||||
}
|
||||
public String number(String key, String unit) {
|
||||
Object value = state.get(key);
|
||||
if (!(value instanceof Number)) return "--";
|
||||
try {
|
||||
String number = new BigDecimal(value.toString()).stripTrailingZeros().toPlainString();
|
||||
return unit.isEmpty() ? number : number + " " + unit;
|
||||
} catch (NumberFormatException e) { return "--"; }
|
||||
}
|
||||
public Boolean bool(String key) {
|
||||
Object value = state.get(key);
|
||||
return value instanceof Boolean ? (Boolean) value : null;
|
||||
}
|
||||
public Long faultBits() {
|
||||
Object value = state.get("faultBits");
|
||||
if (!(value instanceof Number)) return null;
|
||||
Number number = (Number) value;
|
||||
long bits = number.longValue();
|
||||
return bits >= 0 && bits <= 0xFFFFFFFFL && number.doubleValue() == bits ? bits : null;
|
||||
}
|
||||
public long getReceivedAt() { return receivedAt; }
|
||||
public String getSource() { return source; }
|
||||
public Long getDeviceTimestamp() { return deviceTimestamp; }
|
||||
}
|
||||
Reference in New Issue
Block a user