浏览代码

Update 优化读卡器相关代码

Yue 7 小时之前
父节点
当前提交
30f9c7bd4b

+ 6 - 7
UI/CF.APP/chicken_farm/android/app/src/main/java/com/vber/chicken_farm/rfid/RfidConstants.java

@@ -6,18 +6,18 @@ package com.vber.chicken_farm.rfid;
 public final class RfidConstants {
     // 日志TAG
     public static final String TAG = "RfidService";
-    
+
     // 默认设备端口
     public static final String DEVPORT = "/dev/ttyS3";
     public static final String DEVPORT2 = "/dev/ttyS2";
-    
+
     // 默认波特率列表
     // public static final int[] BAUD_LIST = {115200, 460800, 57600};
-    public static final int[] BAUD_LIST = {115200};
-    
+    public static final int[] BAUD_LIST = { 115200 };
+
     // 默认功率
     public static final int DEFAULT_POWER = 7;
-    public static final int POWER_HIGH = 10;
+    public static final int POWER_HIGH = 15;
     public static final int POWER_LOW = 7;
 
     // 默认Q值
@@ -31,7 +31,7 @@ public final class RfidConstants {
 
     // 默认唤醒锁超时时间(10分钟)
     public static final long WAKE_LOCK_TIMEOUT_MS = 10 * 60 * 1000L;
-    
+
     // 唤醒锁标识
     public static final String WAKE_LOCK_TAG = "RfidService:WakeLock";
 
@@ -44,7 +44,6 @@ public final class RfidConstants {
     // 扫描空闲超时时间(120分钟)
     public static final long SCAN_IDLE_TIMEOUT_MS = 120 * 60 * 1000L;
 
-
     private RfidConstants() {
         // 禁止实例化
     }

+ 66 - 65
UI/CF.APP/chicken_farm/android/app/src/main/java/com/vber/chicken_farm/rfid/RfidService.java

@@ -47,7 +47,7 @@ public class RfidService extends Service {
     private static final String TAG = RfidConstants.TAG;
     private static final int MSG_UPDATE_LISTVIEW = 0;
     private static final int MSG_STOP_SCAN = 1;
-    
+
     private SoundService soundService;
 
     // 核心状态变量
@@ -65,15 +65,14 @@ public class RfidService extends Service {
     // 可配置参数(默认值从常量类读取)
     private int connectRetryTimes = RfidConstants.DEFAULT_CONNECT_RETRY_TIMES;
     private long wakeLockTimeoutMs = RfidConstants.WAKE_LOCK_TIMEOUT_MS;
-    private String[] devPorts = {RfidConstants.DEVPORT};
+    private String[] devPorts = { RfidConstants.DEVPORT };
     private int[] baudRates = RfidConstants.BAUD_LIST;
     private long scanReconnectDelayMs = RfidConstants.DEFAULT_SCAN_RECONNECT_DELAY_MS;
     private long scanIdleTimeoutMs = RfidConstants.SCAN_IDLE_TIMEOUT_MS;
     private int asciiNum;
     public static int ErrorCount;
     public static int ErrorCRC;
-    public boolean isMultipleTag = false; 
-
+    public boolean isMultipleTag = false;
 
     // 扫描空闲超时处理器
     private Handler idleHandler;
@@ -144,7 +143,8 @@ public class RfidService extends Service {
             // 移除之前的任务,重新计时
             idleHandler.removeCallbacks(idleDisconnectRunnable);
             idleHandler.postDelayed(idleDisconnectRunnable, scanIdleTimeoutMs);
-            // Log.d(RfidConstants.TAG, "扫描空闲计时器已重置,超时时间:" + scanIdleTimeoutMs / 1000 + "秒");
+            // Log.d(RfidConstants.TAG, "扫描空闲计时器已重置,超时时间:" + scanIdleTimeoutMs / 1000 +
+            // "秒");
         }
     }
 
@@ -166,8 +166,7 @@ public class RfidService extends Service {
         if (pm != null) {
             wakeLock = pm.newWakeLock(
                     PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
-                    RfidConstants.WAKE_LOCK_TAG
-            );
+                    RfidConstants.WAKE_LOCK_TAG);
             wakeLock.setReferenceCounted(false);
         } else {
             Log.e(RfidConstants.TAG, "获取PowerManager失败,无法初始化唤醒锁");
@@ -180,7 +179,7 @@ public class RfidService extends Service {
     private void initReader() {
         try {
             PowerUtil.power("1"); // 开启电源
-            rrlib = new LcModule(this).createProduct(0x20);//0x20:国芯  0x10:荣睿
+            rrlib = new LcModule(this).createProduct(0x20);// 0x20:国芯 0x10:荣睿
             if (rrlib == null) {
                 throw new Exception("创建RFID阅读器实例失败");
             }
@@ -209,7 +208,7 @@ public class RfidService extends Service {
                             break;
                         case MSG_STOP_SCAN:
                             stopScan();
-                         default:
+                        default:
                             break;
                     }
                 } catch (Exception ex) {
@@ -225,13 +224,13 @@ public class RfidService extends Service {
         Log.d(RfidConstants.TAG, "初始化音效服务成功");
 
         // if(rrlib != null){
-        //     SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
-        //     soundPool.load(this, R.raw.barcodebeep, 1);
-        //     rrlib.setsoundid(0, soundPool);
-        //     Log.d(RfidConstants.TAG, "初始化音效成功");
-        //     // rrlib.beginSound(true);
+        // SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
+        // soundPool.load(this, R.raw.barcodebeep, 1);
+        // rrlib.setsoundid(0, soundPool);
+        // Log.d(RfidConstants.TAG, "初始化音效成功");
+        // // rrlib.beginSound(true);
 
-        //     rrlib.playSound();
+        // rrlib.playSound();
         // }
     }
 
@@ -278,13 +277,13 @@ public class RfidService extends Service {
                     // rrlib.StartRead();
                     // isScanning = true;
                     acquireWakeLock();
-                    if(!isConnected){
+                    if (!isConnected) {
                         connect();
                     }
                     // stopIdleTimeout(); // 恢复扫描后停止空闲计时
                     // Log.d(RfidConstants.TAG, "亮屏恢复RFID扫描成功");
                     // if (listener != null) {
-                    //     listener.onTagScanned(rrlib.getInventoryTagMapList()); // 触发一次扫描回调
+                    // listener.onTagScanned(rrlib.getInventoryTagMapList()); // 触发一次扫描回调
                     // }
                 } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
@@ -457,6 +456,9 @@ public class RfidService extends Service {
         try {
             for (int i = 1; i <= retryTimes && !connected; i++) {
                 Log.d(RfidConstants.TAG, "====> 第 " + i + " 次连接 <====");
+                if (i > 1) {
+                    disconnect(true);
+                }
                 for (String port : devPorts) {
                     for (int baud : baudRates) {
                         // 尝试连接端口
@@ -496,11 +498,11 @@ public class RfidService extends Service {
                             Log.d(RfidConstants.TAG, "Reader TidLen: " + readerParameter.TidLen);
                             Log.d(RfidConstants.TAG, "Reader TidPtr: " + readerParameter.TidPtr);
                             break; // 跳出所有循环
-                        }else {
-                            Log.e(RfidConstants.TAG, "连接["+ i +"]: " + result);
+                        } else {
+                            Log.e(RfidConstants.TAG, "连接[" + i + "]: " + result);
                         }
                     }
-                } 
+                }
             }
 
             // 所有重试失败
@@ -525,35 +527,36 @@ public class RfidService extends Service {
      * 断开RFID设备连接
      */
     public void disconnect() {
-        if (!isConnected) {
+        disconnect(false);
+    }
+
+    public void disconnect(boolean isForce) {
+        if (!isForce && !isConnected) {
             Log.w(RfidConstants.TAG, "RFID设备未连接,无需断开");
             return;
         }
-
-        executorService.execute(() -> {
-            try {
-                rrlib.DisConnect();
-                // PowerUtil.power("0"); // 关闭电源
-                isConnected = false;
-                isScanning = false;
-                releaseWakeLock();
-                stopIdleTimeout(); // 断开连接,停止空闲计时
-                Log.d(RfidConstants.TAG, "RFID设备断开连接成功");
-                if (listener != null) {
-                    listener.onDisconnected();
-                }
-            } catch (Exception e) {
-                Log.e(RfidConstants.TAG, "Disconnect error", e);
-                if (listener != null) {
-                    listener.onScanError("断开连接失败:" + e.getMessage());
-                }
+        try {
+            rrlib.DisConnect();
+            // PowerUtil.power("0"); // 关闭电源
+            isConnected = false;
+            isScanning = false;
+            releaseWakeLock();
+            stopIdleTimeout(); // 断开连接,停止空闲计时
+            Log.d(RfidConstants.TAG, "RFID设备断开连接成功");
+            if (listener != null) {
+                listener.onDisconnected();
+            }
+        } catch (Exception e) {
+            Log.e(RfidConstants.TAG, "Disconnect error", e);
+            if (listener != null) {
+                listener.onScanError("断开连接失败:" + e.getMessage());
             }
-        });
+        }
     }
-    
+
     public boolean startScan(boolean multipleTag) {
         Log.d(RfidConstants.TAG, "=====>RFID设备开始扫描");
-        if(!isConnected){
+        if (!isConnected) {
             connect();
         }
         if (!isConnected) {
@@ -568,7 +571,7 @@ public class RfidService extends Service {
             stopIdleTimeout(); // 重复启动也重置计时
             return true;
         }
-        if(this.isMultipleTag != multipleTag){
+        if (this.isMultipleTag != multipleTag) {
             this.isMultipleTag = multipleTag;
             setReaderParameter(null);
             setPower();
@@ -576,6 +579,7 @@ public class RfidService extends Service {
         Log.d(RfidConstants.TAG, "RFID设备扫描,功率:" + getPower() + "W");
         return _startScan();
     }
+
     /**
      * 开始扫描标签
      */
@@ -608,7 +612,8 @@ public class RfidService extends Service {
                 Log.d(RfidConstants.TAG, "1秒RFID扫描自动停止");
                 if (isScanning) {
                     stopScan();
-                    if(listener != null && (!isMultipleTag || isMultipleTag && rrlib.getInventoryTagMapList().size()==0 )){
+                    if (listener != null
+                            && (!isMultipleTag || isMultipleTag && rrlib.getInventoryTagMapList().size() == 0)) {
                         listener.onScanError("未扫描到电子编号");
                     }
                 }
@@ -659,7 +664,7 @@ public class RfidService extends Service {
             }
             return;
         }
-        
+
         // 创建一个新的参数对象,避免修改传入的对象
         final ReaderParameter paramToUse;
         if (param == null) {
@@ -731,17 +736,15 @@ public class RfidService extends Service {
     }
 
     // -------------------------- 状态查询API --------------------------
-    
 
     public ReaderParameter getReaderParameter() {
         return readerParameter;
     }
+
     public int getPower() {
         return power;
     }
 
-
-
     public boolean isConnected() {
         return isConnected;
     }
@@ -772,16 +775,16 @@ public class RfidService extends Service {
 
     // -------------------------- 内部工具方法 --------------------------
 
-
-    private void setPower() { 
-        if(isMultipleTag){
+    private void setPower() {
+        if (isMultipleTag) {
             setPower(RfidConstants.POWER_HIGH);
             Log.d(RfidConstants.TAG, "RFID设备启动多标签扫描,功率:" + getPower() + "W");
-        }else{
+        } else {
             setPower(RfidConstants.POWER_LOW);
             Log.d(RfidConstants.TAG, "RFID设备启动单标签扫描,功率:" + getPower() + "W");
         }
     }
+
     /**
      * 获取唤醒锁(处理息屏场景)
      */
@@ -822,7 +825,7 @@ public class RfidService extends Service {
         }
     }
 
-      // 实现TagCallback的MsgCallback内部类
+    // 实现TagCallback的MsgCallback内部类
     private class MsgCallback implements TagCallback {
         @Override
         public void tagCallback(ReadTag arg) {
@@ -839,15 +842,15 @@ public class RfidService extends Service {
                 if (asciiNum == 1) {
                     epc = hexToAscii(epc);
                 }
-                final String processedEpc = epc;  // 创建一个局部final变量供lambda使用
+                final String processedEpc = epc; // 创建一个局部final变量供lambda使用
                 InventoryTagMap m = rrlib.getInventoryTagMapList().stream()
-                .filter(item -> processedEpc.equals(item.strEPC))
-                .findFirst()
-                .orElse(null);
+                        .filter(item -> processedEpc.equals(item.strEPC))
+                        .findFirst()
+                        .orElse(null);
 
                 if (m == null) {
                     // 新标签:播放提示音并添加到列表
-                    Log.d(RfidConstants.TAG, "tagCallback: new InventoryTagMap :" +m);
+                    Log.d(RfidConstants.TAG, "tagCallback: new InventoryTagMap :" + m);
                     m = new InventoryTagMap();
                     m.strEPC = processedEpc;
                     m.antenna = arg.antId;
@@ -857,22 +860,22 @@ public class RfidService extends Service {
                     // 使用SoundService播放音效
                     soundService.playBeep();
                 } else {
-                    if(!isMultipleTag){
+                    if (!isMultipleTag) {
                         msgHandler.removeMessages(MSG_STOP_SCAN);
                         msgHandler.sendEmptyMessage(MSG_STOP_SCAN);
-                        if(isScanning){
+                        if (isScanning) {
                             msgHandler.removeMessages(MSG_UPDATE_LISTVIEW);
                             msgHandler.sendEmptyMessageDelayed(MSG_UPDATE_LISTVIEW, 50);
                         }
                     }
                     m.nReadCount++;
                 }
-                if(isMultipleTag){
+                if (isMultipleTag) {
                     Log.d(RfidConstants.TAG, "tagCallback: TAG_COUNT:" + rrlib.getInventoryTagMapList().size());
                     msgHandler.removeMessages(MSG_UPDATE_LISTVIEW);
                     msgHandler.sendEmptyMessageDelayed(MSG_UPDATE_LISTVIEW, 100);
                 }
-            } 
+            }
         }
 
         @Override
@@ -882,8 +885,7 @@ public class RfidService extends Service {
                 ErrorCRC += 1;
             }
             ErrorCount += 1;
-            
-            
+
             // 触发扫描错误回调
             if (listener != null) {
                 listener.onScanError("CRC错误: reason=" + reason + ", 错误数=" + ErrorCount);
@@ -911,7 +913,6 @@ public class RfidService extends Service {
             return 0;
         }
     }
-    
 
     private static String hexToAscii(String hexStr) {
         StringBuilder output = new StringBuilder("");

+ 11 - 1
UI/CF.APP/chicken_farm/lib/core/services/pda/rfid_manager.dart

@@ -1,4 +1,5 @@
 import 'package:chicken_farm/core/utils/logger.dart';
+import 'package:chicken_farm/core/utils/toast.dart';
 import 'package:chicken_farm/modes/rfid/rfid_model.dart';
 import 'rfid_channel.dart';
 
@@ -10,6 +11,7 @@ typedef ScannOnKeyPress = void Function(String error);
 
 /// RFID 工具类(纯逻辑调用)
 class RfidManager {
+  static bool isConnect = false;
   // 存储标签扫描回调函数
   final TagScannedCallback? _onTagScanned;
   final RFIDScannedCallback? _onRFIDScanned;
@@ -38,14 +40,21 @@ class RfidManager {
     // 2. 设置配置项
     // await RfidChannel.setConnectRetryTimes(5); // 连接重试5次
     // await RfidChannel.setScanIdleTimeout(5 * 60 * 1000); // 5分钟空闲超时
+    if (!isConnect) {
+      ToastUtil.show("读卡器正在连接中...", duration: 10);
+    }
 
     // 3. 监听RFID事件
     RfidChannel.rfidEvents.listen((RfidEvent event) {
       switch (event.type) {
         case RfidEventType.connectSuccess:
+          ToastUtil.success("电子编号读卡器连接成功");
+          isConnect = true;
           logger.i("✅ 设备连接成功: ${event.data}");
           break;
         case RfidEventType.connectFailed:
+          isConnect = false;
+          ToastUtil.errorAlert("电子编号读卡器连接失败");
           logger.e("❌ 设备连接失败: ${event.error}");
           break;
         case RfidEventType.tagScanned:
@@ -64,6 +73,7 @@ class RfidManager {
           // }
           break;
         case RfidEventType.disconnected:
+          isConnect = false;
           logger.i("🔌 设备已断开连接");
           break;
         case RfidEventType.onKeyPress: // 处理按键事件
@@ -80,7 +90,7 @@ class RfidManager {
     });
 
     // 4. 连接设备
-    await RfidChannel.connect(retryTimes: 5);
+    await RfidChannel.connect(retryTimes: 3);
   }
 
   /// 开始扫描