package com.shlb.comb.fragment;
|
|
import android.os.Bundle;
|
import android.view.LayoutInflater;
|
import android.view.View;
|
import android.view.ViewGroup;
|
import android.widget.ArrayAdapter;
|
import android.widget.EditText;
|
import android.widget.Spinner;
|
import android.widget.TextView;
|
import android.widget.Toast;
|
|
import androidx.annotation.NonNull;
|
import androidx.annotation.Nullable;
|
import androidx.fragment.app.Fragment;
|
import androidx.recyclerview.widget.GridLayoutManager;
|
import androidx.recyclerview.widget.RecyclerView;
|
|
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
|
import com.shlb.comb.manager.BleGlobalManager;
|
import com.shlb.comb.event.UpdateEvent;
|
import org.greenrobot.eventbus.EventBus;
|
import org.greenrobot.eventbus.Subscribe;
|
import org.greenrobot.eventbus.ThreadMode;
|
import android.bluetooth.BluetoothProfile;
|
import com.shlb.comb.R;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
import com.shlb.comb.util.CMD;
|
import com.shlb.comb.util.CRCutil;
|
|
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
|
import android.text.Html;
|
import android.content.DialogInterface;
|
|
public class SettingsFragment extends Fragment {
|
|
private RecyclerView rvGrid;
|
private EditText etLayer;
|
private EditText etStation;
|
private Spinner spinnerBaud;
|
private QMUIRoundButton btnWriteAll;
|
private QMUIRoundButton btnReadData;
|
private QMUIRoundButton btnReadParam;
|
private QMUIRoundButton btnClearLog;
|
private TextView tvStatus;
|
private TextView tvLog;
|
private TextView tvLayerStatus;
|
private TextView tvStationStatus;
|
private TextView tvBaudStatus;
|
private android.widget.ScrollView svLog;
|
|
private QMUITipDialog mLoadingDialog;
|
|
private GridAdapter mAdapter;
|
private List<BoxStatus> boxStatusList = new ArrayList<>();
|
private StringBuilder logBuilder = new StringBuilder();
|
|
private java.util.Queue<String> cmdQueue = new java.util.LinkedList<>();
|
private String currentExecutingCmd = ""; // 当前正在执行的指令,用于校验响应
|
|
private static class BoxStatus {
|
int id;
|
boolean isOnline;
|
boolean hasGlass;
|
|
public BoxStatus(int id) {
|
this.id = id;
|
this.isOnline = false;
|
this.hasGlass = false;
|
}
|
}
|
|
private Runnable autoReadRunnable = new Runnable() {
|
@Override
|
public void run() {
|
// 蓝牙连接成功后 自动触发监控详情的 读取数据 和 参数设定这里的 读取参数
|
if (BleGlobalManager.getInstance().isConnected()) {
|
showLoading("正在同步数据...");
|
|
if (btnReadData != null) btnReadData.performClick();
|
|
new android.os.Handler().postDelayed(() -> {
|
if (btnReadParam != null) btnReadParam.performClick();
|
|
// 假设参数读取触发后 1.5秒 关闭 loading,或者在解析完所有参数后关闭
|
// 这里简单处理,延时关闭
|
new android.os.Handler().postDelayed(() -> {
|
dismissLoading();
|
}, 1500);
|
}, 1000); // 间隔1秒,避免指令冲突
|
}
|
}
|
};
|
private android.os.Handler debounceHandler = new android.os.Handler();
|
private static final long DEBOUNCE_DELAY_MS = 1500; // 1.5 seconds debounce
|
|
@Override
|
public void onStart() {
|
super.onStart();
|
if (!EventBus.getDefault().isRegistered(this)) {
|
EventBus.getDefault().register(this);
|
}
|
updateConnectionStatus();
|
}
|
|
@Override
|
public void onStop() {
|
super.onStop();
|
if (EventBus.getDefault().isRegistered(this)) {
|
EventBus.getDefault().unregister(this);
|
}
|
}
|
|
private void updateConnectionStatus() {
|
if (BleGlobalManager.getInstance().isConnected()) {
|
tvStatus.setText("状态:已连接");
|
} else {
|
tvStatus.setText("状态:未连接");
|
}
|
}
|
|
@Subscribe(threadMode = ThreadMode.MAIN)
|
public void onEventRefresh(UpdateEvent event) {
|
if (event.getType() == UpdateEvent.Type.CONN_STATU) {
|
// Check if obj is integer
|
if (event.getObj() instanceof Integer) {
|
int status = (int) event.getObj();
|
if (status == BluetoothProfile.STATE_CONNECTED) {
|
tvStatus.setText("状态:已连接");
|
Toast.makeText(getContext(), "蓝牙已连接", Toast.LENGTH_SHORT).show();
|
|
// 蓝牙连接成功后 自动触发
|
triggerAutoRead();
|
} else {
|
tvStatus.setText("状态:已断开");
|
}
|
}
|
} else if (event.getType() == UpdateEvent.Type.DEVICE_INFO) {
|
// Received data
|
String hex = event.getMsg();
|
tvStatus.setText("收到数据: " + hex);
|
appendLog(hex, false); // false for received (Green)
|
parseAndRefresh(hex);
|
}
|
}
|
|
private void parseAndRefresh(String hex) {
|
if (hex == null) return;
|
|
// 根据CMD前8位判断指令类型
|
if (hex.length() >= 8) {
|
// 参数读取返回 (长度至少12位)
|
// 读层数: A55A0308...
|
// 读站号: A55A0304...
|
// 读波特率: A55A0305...
|
if (hex.length() >= 12 && (
|
hex.startsWith(CMD.READ_FLOORS.substring(0, 8)) ||
|
hex.startsWith(CMD.READ_STATION_NUM.substring(0, 8)) ||
|
hex.startsWith(CMD.READ_BAUD_RATE.substring(0, 8)))) {
|
parseParamResponse(hex);
|
return;
|
}
|
|
// 数据读取返回 (长度至少32位)
|
// 读数据: A55A0301...
|
if (hex.length() >= 32 && hex.startsWith(CMD.READ_DATA.substring(0, 8))) {
|
parseDataResponse(hex);
|
return;
|
}
|
}
|
|
// 写入指令的返回 (A55A06开头)
|
if (hex.startsWith("A55A06") && hex.length() >= 12) {
|
parseWriteResponse(hex);
|
return;
|
}
|
}
|
|
private void setLabelStatus(TextView view, String text, int colorResId) {
|
if (view != null && getContext() != null) {
|
view.setText(text);
|
view.setTextColor(androidx.core.content.ContextCompat.getColor(getContext(), colorResId));
|
}
|
}
|
|
/**
|
* 解析参数读取返回 (站号、波特率、层数)
|
*/
|
private void parseParamResponse(String hex) {
|
try {
|
// 命令类型: 第7-8位
|
String cmdType = hex.substring(6, 8);
|
// 数据内容: 第11-12位
|
String dataHex = hex.substring(10, 12);
|
int value = Integer.parseInt(dataHex, 16);
|
|
if ("04".equals(cmdType)) {
|
// 站号
|
if (etStation != null) etStation.setText(String.valueOf(value));
|
setLabelStatus(tvStationStatus, "(读取值)", R.color.base_color);
|
appendLog("读取站号: " + value);
|
} else if ("05".equals(cmdType)) {
|
// 波特率
|
if (spinnerBaud != null && value >= 0 && value < spinnerBaud.getAdapter().getCount()) {
|
spinnerBaud.setSelection(value);
|
}
|
setLabelStatus(tvBaudStatus, "(读取值)", R.color.base_color);
|
appendLog("读取波特率: " + value);
|
} else if ("08".equals(cmdType)) {
|
// 层数
|
if (etLayer != null) etLayer.setText(String.valueOf(value));
|
setLabelStatus(tvLayerStatus, "(读取值)", R.color.base_color);
|
appendLog("读取层数: " + value);
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
appendLog("参数解析异常: " + e.getMessage());
|
setLabelStatus(tvStationStatus, "(读取失败)", R.color.orange);
|
setLabelStatus(tvBaudStatus, "(读取失败)", R.color.orange);
|
setLabelStatus(tvLayerStatus, "(读取失败)", R.color.orange);
|
}
|
}
|
|
/**
|
* 解析写入指令返回
|
*/
|
private void parseWriteResponse(String hex) {
|
try {
|
// 结果状态: 第11-12位
|
String statusHex = hex.substring(10, 12);
|
boolean isSuccess = "01".equals(statusHex);
|
|
// 只要当前有正在执行的指令,且收到了写入回复(A55A06开头),我们就认为是当前指令的回复
|
// 因为我们采用队列机制,必须发一条等一条,所以不会有乱序问题。
|
// 这种方式规避了 ENTER 和 EXIT 前8位相同导致无法区分的问题。
|
|
if (!currentExecutingCmd.isEmpty()) {
|
if (isSuccess) {
|
// 记录日志:根据当前期待的指令来记录,而不是根据返回的 hex
|
// 使用完整指令前缀匹配,避免 ENTER (3B0101) 和 EXIT (3B0100) 前8位相同导致的误判
|
if (currentExecutingCmd.startsWith(CMD.ENTER_SETTING)) {
|
appendLog("进入设定模式成功");
|
} else if (currentExecutingCmd.startsWith(CMD.WRITE_STATION_NUM)) {
|
appendLog("写入站号成功");
|
setLabelStatus(tvStationStatus, "(写入值)", R.color.base_color_s);
|
} else if (currentExecutingCmd.startsWith(CMD.WRITE_BAUD_RATE)) {
|
appendLog("写入波特率成功");
|
setLabelStatus(tvBaudStatus, "(写入值)", R.color.base_color_s);
|
} else if (currentExecutingCmd.startsWith(CMD.EXIT_SETTING)) {
|
appendLog("退出设定模式成功");
|
}
|
|
// 只有成功才继续执行下一条
|
processNextCmd();
|
} else {
|
// 执行失败
|
cmdQueue.clear();
|
currentExecutingCmd = "";
|
tvStatus.setText("写入失败");
|
|
if (currentExecutingCmd.startsWith(CMD.WRITE_STATION_NUM)) {
|
setLabelStatus(tvStationStatus, "(写入失败)", R.color.orange);
|
} else if (currentExecutingCmd.startsWith(CMD.WRITE_BAUD_RATE)) {
|
setLabelStatus(tvBaudStatus, "(写入失败)", R.color.orange);
|
}
|
|
appendLog("写入失败: " + hex);
|
Toast.makeText(getContext(), "写入失败", Toast.LENGTH_SHORT).show();
|
}
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
cmdQueue.clear();
|
currentExecutingCmd = "";
|
appendLog("写入响应解析异常: " + e.getMessage());
|
// 异常也视为失败
|
setLabelStatus(tvStationStatus, "(写入失败)", R.color.orange);
|
setLabelStatus(tvBaudStatus, "(写入失败)", R.color.orange);
|
}
|
}
|
|
private void processNextCmd() {
|
if (cmdQueue != null && !cmdQueue.isEmpty()) {
|
String nextCmd = cmdQueue.poll();
|
currentExecutingCmd = nextCmd;
|
|
// 更新状态显示
|
if (nextCmd.startsWith(CMD.ENTER_SETTING.substring(0, 10))) {
|
tvStatus.setText("正在进入设定模式...");
|
} else if (nextCmd.startsWith(CMD.WRITE_STATION_NUM.substring(0, 10))) {
|
tvStatus.setText("正在写入站号...");
|
} else if (nextCmd.startsWith(CMD.WRITE_BAUD_RATE.substring(0, 10))) {
|
tvStatus.setText("正在写入波特率...");
|
} else if (nextCmd.startsWith(CMD.EXIT_SETTING.substring(0, 10))) {
|
tvStatus.setText("正在退出设定模式...");
|
}
|
|
sendCmdWithCrc(nextCmd);
|
} else {
|
// 队列为空,全部完成
|
currentExecutingCmd = "";
|
tvStatus.setText("参数写入完成");
|
Toast.makeText(getContext(), "参数写入成功", Toast.LENGTH_SHORT).show();
|
}
|
}
|
|
/**
|
* 解析监控数据返回 (是否有玻璃、在线状态)
|
*/
|
private void parseDataResponse(String hex) {
|
try {
|
// 解析是否有玻璃: 第11-18位 (8个字符 = 32位)
|
// 索引 10-17
|
String glassHex = hex.substring(10, 18);
|
appendLog("解析玻璃数据: " + glassHex);
|
|
// 直接解析 hex 为 long (Big Endian)
|
// "00000004" -> 4 -> ...00100 -> Bit 2 -> Box 3
|
long glassBits = Long.parseLong(glassHex, 16);
|
|
String onlineHex = hex.substring(18, 26);
|
appendLog("解析在线数据: " + onlineHex);
|
long onlineBits = Long.parseLong(onlineHex, 16);
|
|
// 更新30个格子的状态
|
for (BoxStatus box : boxStatusList) {
|
int bitIndex = box.id - 1; // 对应位索引 0-29
|
if (bitIndex >= 0 && bitIndex < 32) {
|
// 检查对应位是否为1
|
box.hasGlass = ((glassBits >> bitIndex) & 1) == 1;
|
box.isOnline = ((onlineBits >> bitIndex) & 1) == 1;
|
}
|
}
|
|
// 刷新列表显示
|
if (mAdapter != null) {
|
mAdapter.notifyDataSetChanged();
|
}
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
tvStatus.setText("数据解析错误: " + e.getMessage());
|
appendLog("数据解析错误: " + e.getMessage());
|
}
|
}
|
|
|
|
@Nullable
|
@Override
|
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
return inflater.inflate(R.layout.fragment_settings, container, false);
|
}
|
|
@Override
|
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
super.onViewCreated(view, savedInstanceState);
|
|
// Initialize box status list
|
boxStatusList.clear();
|
for (int i = 1; i <= 30; i++) {
|
boxStatusList.add(new BoxStatus(i));
|
}
|
|
initView(view);
|
|
// 如果已经连接,自动触发读取
|
if (BleGlobalManager.getInstance().isConnected()) {
|
triggerAutoRead();
|
}
|
}
|
|
private void triggerAutoRead() {
|
// 使用防抖机制,避免短时间内多次触发
|
debounceHandler.removeCallbacks(autoReadRunnable);
|
debounceHandler.postDelayed(autoReadRunnable, DEBOUNCE_DELAY_MS);
|
}
|
|
private void showLoading(String msg) {
|
if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
|
mLoadingDialog.dismiss();
|
}
|
mLoadingDialog = new QMUITipDialog.Builder(getContext())
|
.setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
|
.setTipWord(msg)
|
.create();
|
// 允许点击外部或返回键取消 loading(只是关闭 dialog)
|
mLoadingDialog.setCancelable(true);
|
mLoadingDialog.setCanceledOnTouchOutside(true);
|
mLoadingDialog.show();
|
}
|
|
private void dismissLoading() {
|
if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
|
mLoadingDialog.dismiss();
|
}
|
}
|
|
private void initView(View view) {
|
rvGrid = view.findViewById(R.id.rv_grid);
|
etLayer = view.findViewById(R.id.et_layer);
|
etStation = view.findViewById(R.id.et_station);
|
spinnerBaud = view.findViewById(R.id.spinner_baud);
|
btnWriteAll = view.findViewById(R.id.btn_write_all);
|
btnReadData = view.findViewById(R.id.btn_read_data);
|
btnReadParam = view.findViewById(R.id.btn_read_param);
|
btnClearLog = view.findViewById(R.id.btn_clear_log);
|
tvStatus = view.findViewById(R.id.tv_status);
|
tvLog = view.findViewById(R.id.tv_log);
|
svLog = view.findViewById(R.id.sv_log);
|
tvLayerStatus = view.findViewById(R.id.tv_layer_status);
|
tvStationStatus = view.findViewById(R.id.tv_station_status);
|
tvBaudStatus = view.findViewById(R.id.tv_baud_status);
|
|
// 解决日志区域滑动冲突
|
svLog.setOnTouchListener((v, event) -> {
|
v.getParent().requestDisallowInterceptTouchEvent(true);
|
if ((event.getAction() & android.view.MotionEvent.ACTION_MASK) == android.view.MotionEvent.ACTION_UP) {
|
v.getParent().requestDisallowInterceptTouchEvent(false);
|
}
|
return false;
|
});
|
|
// Restore logs if any
|
if (logBuilder.length() > 0) {
|
tvLog.setText(Html.fromHtml(logBuilder.toString()));
|
} else {
|
logBuilder.append("日志记录:<br>");
|
tvLog.setText(Html.fromHtml(logBuilder.toString()));
|
}
|
|
// Grid Setup
|
// 10 columns to match the image (10 boxes per row)
|
// Since we are in a horizontal scroll view, this will layout correctly
|
rvGrid.setLayoutManager(new GridLayoutManager(getContext(), 10));
|
mAdapter = new GridAdapter();
|
rvGrid.setAdapter(mAdapter);
|
|
// Spinner Setup
|
String[] baudRates = new String[]{"156Kbps", "625Kbps", "2.5Mbps", "5Mbps", "10Mbps"};
|
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, baudRates);
|
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
|
spinnerBaud.setAdapter(spinnerAdapter);
|
spinnerBaud.setSelection(0); // Select 156Kbps by default
|
|
// Button Listeners
|
btnWriteAll.setOnClickListener(v -> {
|
if (!BleGlobalManager.getInstance().isConnected()) {
|
Toast.makeText(getContext(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
|
appendLog("错误: 蓝牙未连接");
|
return;
|
}
|
|
String stationStr = etStation.getText().toString().trim();
|
if (stationStr.isEmpty()) {
|
Toast.makeText(getContext(), "请输入站号", Toast.LENGTH_SHORT).show();
|
return;
|
}
|
|
try {
|
int station = Integer.parseInt(stationStr);
|
if (station < 1 || station > 64) {
|
Toast.makeText(getContext(), "站号范围无效(1-64)", Toast.LENGTH_SHORT).show();
|
return;
|
}
|
} catch (NumberFormatException e) {
|
Toast.makeText(getContext(), "请输入有效的数字", Toast.LENGTH_SHORT).show();
|
return;
|
}
|
|
// 构造指令队列
|
cmdQueue.clear();
|
|
// 1. 进入设定
|
cmdQueue.offer(CMD.ENTER_SETTING);
|
|
// 2. 写入站号
|
int station = Integer.parseInt(stationStr);
|
String stationHex = String.format("%02X", station);
|
cmdQueue.offer(CMD.WRITE_STATION_NUM + stationHex);
|
|
// 3. 写入波特率
|
int baudIndex = spinnerBaud.getSelectedItemPosition();
|
String baudHex = String.format("%02X", baudIndex);
|
cmdQueue.offer(CMD.WRITE_BAUD_RATE + baudHex);
|
|
// 4. 退出设定
|
cmdQueue.offer(CMD.EXIT_SETTING);
|
|
// 开始执行
|
processNextCmd();
|
});
|
|
btnReadData.setOnClickListener(v -> {
|
if (BleGlobalManager.getInstance().isConnected()) {
|
tvStatus.setText("状态:正在读取数据...");
|
sendCmdWithCrc(CMD.READ_DATA);
|
} else {
|
Toast.makeText(getContext(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
|
appendLog("错误: 蓝牙未连接");
|
}
|
});
|
|
btnReadParam.setOnClickListener(v -> {
|
if (BleGlobalManager.getInstance().isConnected()) {
|
tvStatus.setText("状态:正在读取参数...");
|
sendCmdWithCrc(CMD.READ_FLOORS);
|
new android.os.Handler().postDelayed(() -> {
|
sendCmdWithCrc(CMD.READ_STATION_NUM);
|
}, 200);
|
new android.os.Handler().postDelayed(() -> {
|
sendCmdWithCrc(CMD.READ_BAUD_RATE);
|
}, 400);
|
} else {
|
Toast.makeText(getContext(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
|
appendLog("错误: 蓝牙未连接");
|
}
|
});
|
|
btnClearLog.setOnClickListener(v -> {
|
logBuilder.setLength(0);
|
logBuilder.append("日志记录:<br>");
|
tvLog.setText(Html.fromHtml(logBuilder.toString()));
|
});
|
}
|
|
private void appendLog(String msg) {
|
appendLog(msg, null);
|
}
|
|
private String getCmdDescription(String hex) {
|
if (hex == null) return "";
|
|
// 发送指令匹配
|
if (hex.startsWith(CMD.READ_DATA)) return "-读数据";
|
if (hex.startsWith(CMD.READ_FLOORS)) return "-读层数";
|
if (hex.startsWith(CMD.READ_STATION_NUM)) return "-读站号";
|
if (hex.startsWith(CMD.READ_BAUD_RATE)) return "-读波特率";
|
|
// 3B指令 (Enter/Exit) 特殊处理
|
if (hex.startsWith(CMD.ENTER_SETTING.substring(0, 8))) {
|
// 1. 上下文优先: 如果当前有正在执行的指令,以当前指令为准
|
if (!currentExecutingCmd.isEmpty()) {
|
if (currentExecutingCmd.startsWith(CMD.ENTER_SETTING)) return "-进入设定";
|
if (currentExecutingCmd.startsWith(CMD.EXIT_SETTING)) return "-退出设定";
|
}
|
|
// 2. 精确匹配退出指令
|
if (hex.startsWith(CMD.EXIT_SETTING)) return "-退出设定";
|
|
// 3. 默认情况: 上下文为空且非明确退出指令,优先判定为退出设定
|
// (修复: 从参数设定页返回时,收到的退出响应会被误判为进入设定)
|
return "-退出设定";
|
}
|
|
if (hex.startsWith(CMD.ENTER_SETTING)) return "-进入设定";
|
if (hex.startsWith(CMD.EXIT_SETTING)) return "-退出设定";
|
if (hex.startsWith(CMD.WRITE_STATION_NUM)) return "-写站号";
|
if (hex.startsWith(CMD.WRITE_BAUD_RATE)) return "-写波特率";
|
|
// 接收数据匹配
|
// 读数据返回: A55A0301...
|
if (hex.startsWith(CMD.READ_DATA.substring(0, 8))) return "-读数据";
|
|
// 读参数返回
|
if (hex.length() >= 8) {
|
if (hex.startsWith(CMD.READ_FLOORS.substring(0, 8))) return "-读层数";
|
if (hex.startsWith(CMD.READ_STATION_NUM.substring(0, 8))) return "-读站号";
|
if (hex.startsWith(CMD.READ_BAUD_RATE.substring(0, 8))) return "-读波特率";
|
}
|
|
// 写入返回 (A55A06开头)
|
if (hex.startsWith("A55A06") && hex.length() >= 12) {
|
return "-写入返回";
|
}
|
|
return "";
|
}
|
|
private void appendLog(String msg, Boolean isSent) {
|
String time = com.blankj.utilcode.util.TimeUtils.getNowString(new java.text.SimpleDateFormat("HH:mm:ss.SSS"));
|
|
String displayMsg = msg;
|
String cmdDesc = "";
|
|
// 如果是 hex 指令 (纯 0-9 A-F a-f),加空格格式化
|
if (msg.matches("^[0-9A-Fa-f]+$")) {
|
StringBuilder sb = new StringBuilder();
|
for (int i = 0; i < msg.length(); i += 2) {
|
if (i + 2 <= msg.length()) {
|
sb.append(msg.substring(i, i + 2)).append(" ");
|
} else {
|
sb.append(msg.substring(i));
|
}
|
}
|
displayMsg = sb.toString().trim();
|
|
// 获取指令描述
|
cmdDesc = getCmdDescription(msg);
|
}
|
|
String logLine;
|
if (isSent != null) {
|
String color = isSent ? "#1890ff" : "#05aa87"; // Blue for sent, Green for received
|
// 拼接到前缀后面: "发送-读站号: " 或 "收到-读站号: "
|
String prefix = (isSent ? "发送" : "收到") + cmdDesc + ": ";
|
logLine = time + " <font color='" + color + "'>" + prefix + displayMsg + "</font><br>";
|
} else {
|
// 普通日志
|
logLine = time + " " + displayMsg + "<br>";
|
}
|
|
logBuilder.append(logLine);
|
if (tvLog != null) {
|
tvLog.setText(Html.fromHtml(logBuilder.toString()));
|
if (svLog != null) {
|
svLog.post(() -> svLog.fullScroll(View.FOCUS_DOWN));
|
}
|
}
|
}
|
|
private void sendCmdWithCrc(String cmd) {
|
if (!BleGlobalManager.getInstance().isConnected()) {
|
Toast.makeText(getContext(), "请先连接蓝牙", Toast.LENGTH_SHORT).show();
|
appendLog("错误: 蓝牙未连接");
|
return;
|
}
|
|
byte[] cmdBytes = BleGlobalManager.hexStringToBytes(cmd);
|
if (cmdBytes != null) {
|
String crc = CRCutil.getCRC(cmdBytes);
|
// Pad CRC to 4 chars if needed
|
while (crc.length() < 4) {
|
crc = "0" + crc;
|
}
|
String fullCmd = cmd + crc.toUpperCase();
|
|
appendLog(fullCmd, true); // true for sent (Blue)
|
BleGlobalManager.getInstance().sendCmd(fullCmd);
|
} else {
|
appendLog("错误: 指令转换失败");
|
}
|
}
|
|
private class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
|
|
@NonNull
|
@Override
|
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_grid_box, parent, false);
|
return new ViewHolder(view);
|
}
|
|
@Override
|
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
|
// Calculate Box ID based on 3 rows of 10, Right to Left logic as seen in image
|
// Row 1 (pos 0-9): 10 ... 1
|
// Row 2 (pos 10-19): 20 ... 11
|
// Row 3 (pos 20-29): 30 ... 21
|
|
int row = position / 10;
|
int col = position % 10;
|
int boxId = (row + 1) * 10 - col;
|
|
holder.tvBoxNumber.setText(String.valueOf(boxId));
|
|
// Find status for this box
|
BoxStatus status = null;
|
for (BoxStatus s : boxStatusList) {
|
if (s.id == boxId) {
|
status = s;
|
break;
|
}
|
}
|
|
if (status != null) {
|
// Priority: Online > Glass
|
// User requirement: "优先显示是否在线" (Prioritize displaying online status)
|
// "19-26为也是16进制,解析成二进制32代码我这30个格子是否在线"
|
// Usually this means if offline, show offline color. If online, show state (glass/no glass).
|
|
if (!status.isOnline) {
|
holder.viewBox.setBackgroundResource(R.drawable.bg_box_offline); // Offline (Grey)
|
} else {
|
if (status.hasGlass) {
|
holder.viewBox.setBackgroundResource(R.drawable.bg_box_full); // Green
|
} else {
|
holder.viewBox.setBackgroundResource(R.drawable.bg_box_empty); // Online but empty (White)
|
}
|
}
|
}
|
}
|
|
@Override
|
public int getItemCount() {
|
return 30;
|
}
|
|
class ViewHolder extends RecyclerView.ViewHolder {
|
TextView tvBoxNumber;
|
View viewBox;
|
|
public ViewHolder(@NonNull View itemView) {
|
super(itemView);
|
tvBoxNumber = itemView.findViewById(R.id.tv_box_number);
|
viewBox = itemView.findViewById(R.id.view_box);
|
}
|
}
|
}
|
}
|