From 2b756769ea4adad21332d8a294871712cd42cc3f Mon Sep 17 00:00:00 2001
From: 张世豪 <979909237@qq.com>
Date: 星期三, 26 十一月 2025 13:57:24 +0800
Subject: [PATCH] 优化了轮询逻辑注意有打印输出

---
 src/chushihua/lunxun.java |  482 ++++++++++++++++++++++++++++++++++-------------------
 1 files changed, 311 insertions(+), 171 deletions(-)

diff --git a/src/chushihua/lunxun.java b/src/chushihua/lunxun.java
index 217dab3..c3ffeb7 100644
--- a/src/chushihua/lunxun.java
+++ b/src/chushihua/lunxun.java
@@ -5,8 +5,10 @@
 import home.Fkj;
 import home.MachineConfig;
 import publicway.QueryData;
+import publicway.TimestampUtil;
 import xitongshezhi.SystemDebugDialog;
 
+import java.util.Iterator;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -16,22 +18,17 @@
  * 鐢ㄤ簬瀹氭椂鍚戞墍鏈夊崱妲藉彂閫佹煡璇㈡寚浠�
  * 鏀寔鏆傚仠鍜屾仮澶嶅姛鑳斤紝妫�鏌ヤ覆鍙h繛鎺ョ姸鎬�
  * 鏂板锛氫笉鍚屽崱妲界姸鎬佷娇鐢ㄤ笉鍚屾煡璇㈤鐜�
+ * 浼樺寲锛氬唴瀛樼鐞嗗拰闀挎椂闂磋繍琛岀ǔ瀹氭��
  */
 public class lunxun {
 	private static volatile boolean isRunning = false;
 	private static volatile boolean isPaused = false;
 	private static final AtomicBoolean shouldStop = new AtomicBoolean(false);
 	private static Thread pollingThread;
-	private static int pollingInterval = 100; // 榛樿杞闂撮殧
+	private static int pollingInterval =50; // 榛樿杞闂撮殧
 	public static boolean sendChaxunzhiling=true;//鏄惁鍚戜覆鍙e彂閫佹煡璇㈡寚浠�
-
-	public static boolean isSendChaxunzhiling() {
-		return sendChaxunzhiling;
-	}
-
-	public static void setSendChaxunzhiling(boolean sendChaxunzhiling) {
-		lunxun.sendChaxunzhiling = sendChaxunzhiling;
-	}
+	// 娣诲姞闈欐�佸彉閲忔帶鍒朵汉鑴告娴�
+	public static boolean ishaveface = false; // 鏄惁妫�娴嬪埌浜鸿劯锛岄粯璁ゆ病鏈変汉鑴�
 
 	// 鍗℃Ы鐩稿叧甯搁噺
 	private static final int MIN_SLOT = 1;
@@ -44,6 +41,15 @@
 
 	// 鎬ц兘浼樺寲锛氭煡璇㈡寚浠ょ紦瀛�
 	private static final Map<Integer, String> queryCommandCache = new ConcurrentHashMap<>();
+	
+	// 鍐呭瓨浼樺寲锛氱紦瀛樺ぇ灏忛檺鍒跺拰娓呯悊鏈哄埗
+	private static final int MAX_CACHE_SIZE = 100;
+	private static final long CACHE_CLEANUP_INTERVAL = 60000; // 1鍒嗛挓娓呯悊涓�娆�
+	private static long lastCleanupTime = 0;
+	
+	// 閿欒鏃ュ織闄愭祦鏈哄埗
+	private static final Map<String, Long> lastErrorLogTime = new ConcurrentHashMap<>();
+	private static final long ERROR_LOG_INTERVAL = 5000; // 鐩稿悓閿欒5绉掑唴鍙褰曚竴娆�
 
 	// 璋冭瘯妯″紡鎺у埗
 	public static  boolean DEBUG_ENABLED = false;
@@ -53,6 +59,14 @@
 	private static final int HAS_CARD_QUERY_INTERVAL = 10000; // 鏈夊崱鍗℃Ы鏌ヨ闂撮殧锛�10绉�
 	private static final Map<Integer, Long> lastQueryTimeMap = new ConcurrentHashMap<>(); // 璁板綍姣忎釜鍗℃Ы鐨勬渶鍚庢煡璇㈡椂闂�
 
+	public static boolean isSendChaxunzhiling() {
+		return sendChaxunzhiling;
+	}
+
+	public static void setSendChaxunzhiling(boolean sendChaxunzhiling) {
+		lunxun.sendChaxunzhiling = sendChaxunzhiling;
+	}
+
 	/**
 	 * 妫�鏌ヤ覆鍙h繛鎺ョ姸鎬� - 浼樺寲鐗堟湰锛屾坊鍔犻噸璇曟満鍒�
 	 * @return true-涓插彛宸茶繛鎺�, false-涓插彛鏈繛鎺�
@@ -76,11 +90,11 @@
 				}
 				serialConnected = true;
 			} else {
-				Errlog.logOperation("涓插彛杩炴帴澶辫触 - 涓插彛鏈墦寮�");
+				logErrorWithRateLimit("serial_connection_failed", "涓插彛杩炴帴澶辫触 - 涓插彛鏈墦寮�");
 				serialConnected = false;
 			}
 		} catch (Exception e) {
-			Errlog.logOperation("涓插彛杩炴帴妫�鏌ュ紓甯�: " + e.getMessage());
+			logErrorWithRateLimit("serial_connection_exception", "涓插彛杩炴帴妫�鏌ュ紓甯�: " + e.getMessage());
 			serialConnected = false;
 		}
 
@@ -117,10 +131,13 @@
 
 		// 鍚姩鍓嶄弗鏍兼鏌ヤ覆鍙h繛鎺�
 		if (!checkSerialConnectionWithRetry()) {
-			Errlog.logOperation("涓插彛鏈繛鎺ワ紝鏃犳硶鍚姩杞鏌ヨ");
+			logErrorWithRateLimit("start_polling_serial_failed", "涓插彛鏈繛鎺ワ紝鏃犳硶鍚姩杞鏌ヨ");
 			return false;
 		}
 
+		// 鍚姩鍓嶅厛娓呯悊涓�娆″唴瀛�
+		performCleanup();
+
 		// 浠庨厤缃腑鑾峰彇杞闂撮殧
 		loadPollingIntervalFromConfig();
 
@@ -137,7 +154,7 @@
 			pollingThread.start(); 
 			return true;
 		} catch (Exception e) {
-			Errlog.logOperation("鍚姩杞鏌ヨ绾跨▼鏃跺彂鐢熷紓甯�: " + e.getMessage());
+			logErrorWithRateLimit("start_polling_thread_exception", "鍚姩杞鏌ヨ绾跨▼鏃跺彂鐢熷紓甯�: " + e.getMessage());
 			isRunning = false;
 			shouldStop.set(true);
 			return false;
@@ -174,15 +191,15 @@
 				pollingThread.join(3000); // 绛夊緟3绉�
 				// 妫�鏌ョ嚎绋嬫槸鍚﹁繕鍦ㄨ繍琛�
 				if (pollingThread.isAlive()) {
-					Errlog.logOperation("杞绾跨▼鏈湪3绉掑唴鍋滄锛屾爣璁颁负瀹堟姢绾跨▼骞跺拷鐣�");
+					logErrorWithRateLimit("polling_thread_stop_timeout", "杞绾跨▼鏈湪3绉掑唴鍋滄锛屾爣璁颁负瀹堟姢绾跨▼骞跺拷鐣�");
 					// 涓嶅己鍒跺仠姝紝鑰屾槸纭繚瀹冩槸瀹堟姢绾跨▼
 					pollingThread.setDaemon(true);
 				}
 			} catch (InterruptedException e) {
-				Errlog.logOperation("鍋滄杞鏌ヨ鏃惰涓柇: " + e.getMessage());
+				logErrorWithRateLimit("stop_polling_interrupted", "鍋滄杞鏌ヨ鏃惰涓柇: " + e.getMessage());
 				Thread.currentThread().interrupt();
 			} catch (Exception e) {
-				Errlog.logOperation("鍋滄杞绾跨▼鏃跺彂鐢熷紓甯�: " + e.getMessage());
+				logErrorWithRateLimit("stop_polling_exception", "鍋滄杞绾跨▼鏃跺彂鐢熷紓甯�: " + e.getMessage());
 			} finally {
 				pollingThread = null;
 			}
@@ -234,7 +251,7 @@
 
 		// 鎭㈠鍓嶆鏌ヤ覆鍙h繛鎺�
 		if (!checkSerialConnectionWithRetry()) {
-			Errlog.logOperation("涓插彛鏈繛鎺ワ紝鏃犳硶鎭㈠杞鏌ヨ");
+			logErrorWithRateLimit("resume_polling_serial_failed", "涓插彛鏈繛鎺ワ紝鏃犳硶鎭㈠杞鏌ヨ");
 			return false;
 		}
 
@@ -276,7 +293,7 @@
 	 */
 	public static void setPollingInterval(int interval) {
 		if (interval < 10) {
-			Errlog.logOperation("杞闂撮殧涓嶈兘灏忎簬10ms");
+			logErrorWithRateLimit("polling_interval_too_small", "杞闂撮殧涓嶈兘灏忎簬10ms");
 			return;
 		}
 
@@ -328,7 +345,7 @@
 				//System.out.println("閰嶇疆绯荤粺鏈垵濮嬪寲锛屼娇鐢ㄩ粯璁よ疆璇㈤棿闅�: " + pollingInterval + "ms");
 			}
 		} catch (Exception e) {
-			Errlog.logOperation("鍔犺浇杞闂撮殧閰嶇疆澶辫触: " + e.getMessage());
+			logErrorWithRateLimit("load_polling_interval_failed", "鍔犺浇杞闂撮殧閰嶇疆澶辫触: " + e.getMessage());
 			//System.out.println("浣跨敤榛樿杞闂撮殧: " + pollingInterval + "ms");
 		}
 	}
@@ -351,170 +368,195 @@
 	/**
 	 * 杞浠诲姟鍐呴儴绫� - 浼樺寲鐗堟湰
 	 * 鏀寔涓嶅悓鐘舵�佸崱妲界殑涓嶅悓鏌ヨ棰戠巼
+	 * 浼樺寲锛氬唴瀛樼鐞嗗拰閲嶇敤瀵硅薄
 	 */
-
 	private static class PollingTask implements Runnable {
-		private int currentIndex = 0; // 褰撳墠绱㈠紩锛岀敤浜庨亶鍘唖lotArray
-		private int consecutiveFailures = 0; // 杩炵画澶辫触娆℃暟
-		private static final int MAX_CONSECUTIVE_FAILURES = 5; // 鏈�澶ц繛缁け璐ユ鏁�
+	    private int currentIndex = 0; // 褰撳墠绱㈠紩锛岀敤浜庨亶鍘唖lotArray
+	    private int consecutiveFailures = 0; // 杩炵画澶辫触娆℃暟
+	    private static final int MAX_CONSECUTIVE_FAILURES = 5; // 鏈�澶ц繛缁け璐ユ鏁�
+	    private final StringBuilder debugBuilder = new StringBuilder(100); // 閲嶇敤 StringBuilder
 
-		@Override
-		public void run() {
-			//System.out.println("杞鏌ヨ绾跨▼寮�濮嬭繍琛�");
+	    @Override
+	    public void run() {
+	        //System.out.println("杞鏌ヨ绾跨▼寮�濮嬭繍琛�");
 
-			while (isRunning && !Thread.currentThread().isInterrupted() && !shouldStop.get()) {
-				try {
+	        while (isRunning && !Thread.currentThread().isInterrupted() && !shouldStop.get()) {
+	            try {
+	                // 妫�鏌ユ槸鍚︽殏鍋�
+	                if (isPaused) {
+	                    synchronized (lunxun.class) {
+	                        while (isPaused && isRunning && !shouldStop.get()) {
+	                            lunxun.class.wait(1000); // 绛夊緟1绉掓垨鐩村埌琚敜閱�
+	                        }
+	                    }
+	                    continue;
+	                }
 
-					//                	System.out.println("鏌ヨ涓�.....绾跨▼");
-					// 妫�鏌ユ槸鍚︽殏鍋�
-					if (isPaused) {
-						synchronized (lunxun.class) {
-							while (isPaused && isRunning && !shouldStop.get()) {
-								lunxun.class.wait(1000); // 绛夊緟1绉掓垨鐩村埌琚敜閱�
-							}
-						}
-						continue;
-					}
+	                // 瀹氭湡妫�鏌ヤ覆鍙h繛鎺ョ姸鎬侊紙姣�10娆″惊鐜鏌ヤ竴娆★級
+	                if (currentIndex % 10 == 0 && !checkSerialConnectionWithRetry()) {
+	                    logErrorWithRateLimit("serial_disconnected", "涓插彛杩炴帴鏂紑锛屾殏鍋滆疆璇�");
+	                    pausePolling();
+	                    continue;
+	                }
 
-					// 瀹氭湡妫�鏌ヤ覆鍙h繛鎺ョ姸鎬侊紙姣�10娆″惊鐜鏌ヤ竴娆★級
-					if (currentIndex % 10 == 0 && !checkSerialConnectionWithRetry()) {
-						Errlog.logOperation("涓插彛杩炴帴鏂紑锛屾殏鍋滆疆璇�");
-						pausePolling();
-						continue;
-					}
+	                // 瀹氭湡娓呯悊缂撳瓨锛堟瘡100娆″惊鐜竻鐞嗕竴娆★級
+	                if (currentIndex % 100 == 0) {
+	                    cleanupOldCache();
+	                }
 
-					// 鑾峰彇鍗℃Ы鏁扮粍
-					Fkj[] slotArray = SlotManager.getSlotArray();
-					if (slotArray == null || slotArray.length == 0) {
-						Errlog.logOperation("鍗℃Ы鏁扮粍鏈垵濮嬪寲");
-						Thread.sleep(pollingInterval);
-						continue;
-					}
+	                // 鑾峰彇鍗℃Ы鏁扮粍
+	                Fkj[] slotArray = SlotManager.getSlotArray();
+	                if (slotArray == null || slotArray.length == 0) {
+	                    logErrorWithRateLimit("slot_array_not_initialized", "鍗℃Ы鏁扮粍鏈垵濮嬪寲");
+	                    Thread.sleep(pollingInterval);
+	                    continue;
+	                }
 
-					// 鏂板锛氭牴鎹崱妲界姸鎬佸拰鏌ヨ棰戠巼鍐冲畾鏄惁鍙戦�佹煡璇�
-					boolean sentQuery = false;
-					long currentTime = System.currentTimeMillis();
+	                // 閬嶅巻鎵�鏈夊崱妲�
+	                for (int i = 0; i < slotArray.length; i++) {
+	                    if (!isRunning || shouldStop.get()) {
+	                        break;
+	                    }
+	                    
+	                    int slotIndex = (currentIndex + i) % slotArray.length;
+	                    Fkj slot = slotArray[slotIndex];
+	                    if (slot != null) {
+	                        String hasCard = slot.getHasCard();
+	                        int slotNumber = slotIndex + 1;
 
-					// 閬嶅巻鍗℃Ы锛屽鎵鹃渶瑕佹煡璇㈢殑鍗℃Ы
-					for (int i = 0; i < slotArray.length && !sentQuery; i++) {
-						int slotIndex = (currentIndex + i) % slotArray.length;
-						Fkj slot = slotArray[slotIndex];
-						if (slot != null) {
-							String hasCard = slot.getHasCard();
-							int slotNumber = slotIndex + 1;
-							Long lastQueryTime = lastQueryTimeMap.get(slotNumber);
+	                        // 妫�鏌ユ槸鍚﹀洜涓轰汉鑴告娴嬮渶瑕佽烦杩囨湁鍗″崱妲�
+	                        if (ishaveface && "1".equals(hasCard)) {
+	                            // 璺宠繃鏈夊崱鍗℃Ы锛岀珛鍗崇户缁笅涓�涓紝涓嶇瓑寰�
+	                            if (DEBUG_ENABLED) {
+	                                debugBuilder.setLength(0);
+	                                debugBuilder.append("妫�娴嬪埌浜鸿劯锛岃烦杩囨湁鍗″崱妲� ").append(slotNumber).append(" 鐨勬煡璇n");
+	                                SystemDebugDialog.appendAsciiData(debugBuilder.toString());
+	                            }
+	                            continue; // 绔嬪嵆缁х画涓嬩竴涓崱妲斤紝涓嶇瓑寰�
+	                        }
 
-							// 纭畾鏌ヨ闂撮殧锛氬彧鏈塰asCard="1"鐨勫崱妲戒娇鐢�10绉掗棿闅旓紝鍏朵粬鎯呭喌锛堝寘鎷�"-1"锛夐兘浣跨敤100ms闂撮殧
-							int queryInterval = "1".equals(hasCard) ? HAS_CARD_QUERY_INTERVAL : NO_CARD_QUERY_INTERVAL;
+	                        // 鍙戦�佹煡璇㈡寚浠ゅ埌褰撳墠鍗℃Ы
+	                        boolean sendSuccess = sendQueryToSlot(slotNumber);
+	                        
+	                        if (sendSuccess) {
+	                            // 鏇存柊鏈�鍚庢煡璇㈡椂闂�
+	                            lastQueryTimeMap.put(slotNumber, System.currentTimeMillis());
+	                            consecutiveFailures = 0;
 
-							// 妫�鏌ユ槸鍚﹁揪鍒版煡璇㈡椂闂�
-							if (lastQueryTime == null || currentTime - lastQueryTime >= queryInterval) {
-								if (sendQueryToSlot(slotNumber)) {
-									// 鏇存柊鏈�鍚庢煡璇㈡椂闂�
-									lastQueryTimeMap.put(slotNumber, currentTime);
-									sentQuery = true;
-									consecutiveFailures = 0;
+	                            if (DEBUG_ENABLED) {
+	                                String status;
+	                                if ("1".equals(hasCard)) {
+	                                    status = "鏈夊崱";
+	                                } else if ("-1".equals(hasCard)) {
+	                                    status = "鏈煡";
+	                                } else {
+	                                    status = "鏃犲崱";
+	                                }
+	                                
+	                                debugBuilder.setLength(0);
+	                                debugBuilder.append("Slot ").append(slotNumber)
+	                                           .append(" (").append(status).append(") 鏌ヨ鎴愬姛\n");
+	                                SystemDebugDialog.appendAsciiData(debugBuilder.toString());
+	                            }
+	                        } else {
+	                            consecutiveFailures++;
+	                            if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
+	                                logErrorWithRateLimit("consecutive_failures", "lunxun杩炵画澶辫触娆℃暟杩囧锛屾殏鍋滆疆璇�");
+	                                pausePolling();
+	                                break;
+	                            }
+	                        }
 
-									// 鎴愬姛鍙戦�佹煡璇㈠悗锛岀瓑寰�100ms鍐嶇户缁笅涓�涓煡璇�
-									Thread.sleep(100);
+	                        // 鍙戦�佹煡璇㈡寚浠ゅ悗绛夊緟50ms锛岀劧鍚庣户缁笅涓�涓崱妲�
+	                        Thread.sleep(50);
+	                    }
+	                }
 
-									if (DEBUG_ENABLED) {
-										String status;
-										if ("1".equals(hasCard)) {
-											status = "鏈夊崱";
-										} else if ("-1".equals(hasCard)) {
-											status = "鏈煡";
-										} else {
-											status = "鏃犲崱";
-										}
-										SystemDebugDialog.appendAsciiData(
-												String.format("Slot %d (%s) 鏌ヨ鎴愬姛锛岄棿闅�: %dms\n", 
-														slotNumber, status, queryInterval));
-									}
-								} else {
-									consecutiveFailures++;
-									if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
-										Errlog.logOperation("lunxun杩炵画澶辫触娆℃暟杩囧锛屾殏鍋滆疆璇�");
-										pausePolling();
-										break;
-									}
-								}
-							}
-						}
-					}
+	                // 鏇存柊褰撳墠绱㈠紩
+	                currentIndex = (currentIndex + 1) % slotArray.length;
 
-					// 鏇存柊褰撳墠绱㈠紩
-					currentIndex = (currentIndex + 1) % slotArray.length;
+	            } catch (InterruptedException e) {
+	                //System.out.println("杞鏌ヨ绾跨▼琚腑鏂�");
+	                Thread.currentThread().interrupt();
+	                break;
+	            } catch (Exception e) {
+	                logErrorWithRateLimit("polling_exception", "杞鏌ヨ杩囩▼涓彂鐢熷紓甯�: " + e.getMessage());
+	                consecutiveFailures++;
 
-					// 濡傛灉娌℃湁鍙戦�佹煡璇紝绛夊緟涓�娈垫椂闂村啀缁х画
-					if (!sentQuery) {
-						Thread.sleep(pollingInterval);
-					}
+	                // 鍙戠敓寮傚父鏃剁瓑寰呬竴娈垫椂闂村啀缁х画
+	                try {
+	                    Thread.sleep(1000);
+	                } catch (InterruptedException ie) {
+	                    Thread.currentThread().interrupt();
+	                    break;
+	                }
+	            }
+	        }
 
-				} catch (InterruptedException e) {
-					//System.out.println("杞鏌ヨ绾跨▼琚腑鏂�");
-					Thread.currentThread().interrupt();
-					break;
-				} catch (Exception e) {
-					Errlog.logOperation("杞鏌ヨ杩囩▼涓彂鐢熷紓甯�: " + e.getMessage());
-					consecutiveFailures++;
-
-					// 鍙戠敓寮傚父鏃剁瓑寰呬竴娈垫椂闂村啀缁х画
-					try {
-						Thread.sleep(1000);
-					} catch (InterruptedException ie) {
-						Thread.currentThread().interrupt();
-						break;
-					}
-				}
-			}
-
-			//System.out.println("杞鏌ヨ绾跨▼缁撴潫杩愯");
+	        //System.out.println("杞鏌ヨ绾跨▼缁撴潫杩愯");
+	    }
+		// 娣诲姞鑾峰彇鍜岃缃汉鑴告娴嬬姸鎬佺殑鏂规硶
+		public static boolean isIshaveface() {
+		    return ishaveface;
 		}
 
+		public static void setIshaveface(boolean ishaveface) {
+		    lunxun.ishaveface = ishaveface;
+		    if (DEBUG_ENABLED) {
+		        if (ishaveface) {
+		            SystemDebugDialog.appendAsciiData("妫�娴嬪埌浜鸿劯锛岃疆璇㈠皢鍙煡璇㈡棤鍗″崱妲絓n");
+		        } else {
+		            SystemDebugDialog.appendAsciiData("鏈娴嬪埌浜鸿劯锛岃疆璇㈡仮澶嶆甯告煡璇㈡ā寮廫n");
+		        }
+		    }
+		}
 		/**
 		 * 鍚戞寚瀹氬崱妲藉彂閫佹煡璇㈡寚浠� - 浼樺寲鐗堟湰
 		 * 浣跨敤缂撳瓨鎸囦护锛屼紭鍖栬皟璇曡緭鍑�
 		 */
-		private boolean sendQueryToSlot(int slotNumber) {
-			try {
-				// 浣跨敤缂撳瓨鐨勬煡璇㈡寚浠�            	
-				String queryCommand = getCachedQueryCommand(slotNumber);
-				// System.out.println("鎸囦护鏄細"+queryCommand);
-				if (DEBUG_ENABLED) {
-					SystemDebugDialog.appendAsciiData("send to "+slotNumber+" queryCommand");
-				}
+		/**
+	     * 鍚戞寚瀹氬崱妲藉彂閫佹煡璇㈡寚浠� - 浼樺寲鐗堟湰
+	     * 浣跨敤缂撳瓨鎸囦护锛屼紭鍖栬皟璇曡緭鍑�
+	     */
+	    private boolean sendQueryToSlot(int slotNumber) {
+	        try {
+	            // 浣跨敤缂撳瓨鐨勬煡璇㈡寚浠�            	
+	            String queryCommand = getCachedQueryCommand(slotNumber);
+	            System.out.println(slotNumber+"鍙戦�佷簡鎸囦护鏄細"+queryCommand+"鏃堕棿"+TimestampUtil.getTimestamp());
+	            
+	            if (DEBUG_ENABLED) {
+	                SystemDebugDialog.appendAsciiData("send to "+slotNumber+" queryCommand");
+	            }
 
-				if (queryCommand != null && !queryCommand.trim().isEmpty()) {
-					// 鍙戦�佸埌涓插彛
+	            if (queryCommand != null && !queryCommand.trim().isEmpty()) {
+	                // 鍙戦�佸埌涓插彛
+	                if(sendChaxunzhiling) {
+	                    boolean sendResult = Sendmsg.sendMessage(queryCommand);
+	                    if (sendResult) {
+	                        return true;
+	                    } else {
+	                        if (DEBUG_ENABLED) {
+	                            SystemDebugDialog.appendAsciiData(slotNumber+" Send query command to card slot err");
+	                        }
+	                        // 鍙戦�佸け璐ュ彲鑳芥槸涓插彛鏂紑锛屾洿鏂拌繛鎺ョ姸鎬�
+	                        serialConnected = false;
+	                        return false;
+	                    }
+	                } else {
+	                    return false;
+	                }
+	            } else {
+	                logErrorWithRateLimit("empty_query_command", "鐢熸垚鐨勬煡璇㈡寚浠や负绌猴紝鍗℃Ы: " + slotNumber);
+	                return false;
+	            }
 
-					if(sendChaxunzhiling) {
-						boolean sendResult = Sendmsg.sendMessage(queryCommand);
-						if (sendResult) {
-							return true;
-						} else {
-							if (DEBUG_ENABLED) {
-								SystemDebugDialog.appendAsciiData(slotNumber+" Send query command to card slot err");
-							}
-							// 鍙戦�佸け璐ュ彲鑳芥槸涓插彛鏂紑锛屾洿鏂拌繛鎺ョ姸鎬�
-							serialConnected = false;
-							return false;
-						}
-					}else {
-						return false;
-					}
-				} else {
-					Errlog.logOperation("鐢熸垚鐨勬煡璇㈡寚浠や负绌猴紝鍗℃Ы: " + slotNumber);
-					return false;
-				}
-
-			} catch (Exception e) {
-				Errlog.logOperation("鍙戦�佹煡璇㈡寚浠ゅ埌鍗℃Ы " + slotNumber + " 鏃跺彂鐢熷紓甯�: " + e.getMessage());
-				// 鍙戠敓寮傚父鏃舵洿鏂颁覆鍙h繛鎺ョ姸鎬�
-				serialConnected = false;
-				return false;
-			}
-		}
+	        } catch (Exception e) {
+	            logErrorWithRateLimit("send_query_exception", "鍙戦�佹煡璇㈡寚浠ゅ埌鍗℃Ы " + slotNumber + " 鏃跺彂鐢熷紓甯�: " + e.getMessage());
+	            // 鍙戠敓寮傚父鏃舵洿鏂颁覆鍙h繛鎺ョ姸鎬�
+	            serialConnected = false;
+	            return false;
+	        }
+	    }
 	}
 
 	/**
@@ -524,13 +566,13 @@
 	 */
 	public static boolean sendImmediateQuery(int slotNumber) {
 		if (slotNumber < MIN_SLOT || slotNumber > MAX_SLOT) {
-			Errlog.logOperation("鍗℃Ы缂栧彿蹇呴』鍦�" + MIN_SLOT + "-" + MAX_SLOT + "涔嬮棿");
+			logErrorWithRateLimit("invalid_slot_number", "鍗℃Ы缂栧彿蹇呴』鍦�" + MIN_SLOT + "-" + MAX_SLOT + "涔嬮棿");
 			return false;
 		}
 
 		// 妫�鏌ヤ覆鍙h繛鎺�
 		if (!checkSerialConnectionWithRetry()) {
-			Errlog.logOperation("涓插彛鏈繛鎺ワ紝鏃犳硶鍙戦�佹煡璇㈡寚浠�");
+			logErrorWithRateLimit("immediate_query_serial_failed", "涓插彛鏈繛鎺ワ紝鏃犳硶鍙戦�佹煡璇㈡寚浠�");
 			return false;
 		}
 
@@ -551,16 +593,16 @@
 					}
 					return true;
 				} else {
-					Errlog.logOperation("绔嬪嵆鏌ヨ澶辫触 - 鍙戦�佹寚浠ゅ埌鍗℃Ы " + slotNumber + " 澶辫触");
+					logErrorWithRateLimit("immediate_query_send_failed", "绔嬪嵆鏌ヨ澶辫触 - 鍙戦�佹寚浠ゅ埌鍗℃Ы " + slotNumber + " 澶辫触");
 					return false;
 				}
 			} else {
-				Errlog.logOperation("绔嬪嵆鏌ヨ澶辫触 - 鐢熸垚鐨勬煡璇㈡寚浠や负绌猴紝鍗℃Ы: " + slotNumber);
+				logErrorWithRateLimit("immediate_query_empty_command", "绔嬪嵆鏌ヨ澶辫触 - 鐢熸垚鐨勬煡璇㈡寚浠や负绌猴紝鍗℃Ы: " + slotNumber);
 				return false;
 			}
 
 		} catch (Exception e) {
-			Errlog.logOperation("绔嬪嵆鏌ヨ鍗℃Ы " + slotNumber + " 鏃跺彂鐢熷紓甯�: " + e.getMessage());
+			logErrorWithRateLimit("immediate_query_exception", "绔嬪嵆鏌ヨ鍗℃Ы " + slotNumber + " 鏃跺彂鐢熷紓甯�: " + e.getMessage());
 			return false;
 		}
 	}
@@ -572,7 +614,7 @@
 	public static int sendImmediateQueryToAll() {
 		// 妫�鏌ヤ覆鍙h繛鎺�
 		if (!checkSerialConnectionWithRetry()) {
-			Errlog.logOperation("涓插彛鏈繛鎺ワ紝鏃犳硶鍙戦�佹壒閲忔煡璇㈡寚浠�");
+			logErrorWithRateLimit("batch_query_serial_failed", "涓插彛鏈繛鎺ワ紝鏃犳硶鍙戦�佹壒閲忔煡璇㈡寚浠�");
 			return 0;
 		}
 
@@ -625,7 +667,7 @@
 		if (connected) {
 			//            //System.out.println("涓插彛杩炴帴鐘舵�佸凡璁剧疆涓�: 宸茶繛鎺�");
 		} else {
-			Errlog.logOperation("涓插彛杩炴帴鐘舵�佸凡璁剧疆涓�: 鏈繛鎺�");
+			logErrorWithRateLimit("serial_disconnected_external", "涓插彛杩炴帴鐘舵�佸凡璁剧疆涓�: 鏈繛鎺�");
 			// 濡傛灉涓插彛鏂紑涓旇疆璇㈡鍦ㄨ繍琛岋紝鑷姩鏆傚仠杞
 			if (isRunning && !isPaused) {
 				pausePolling();
@@ -664,9 +706,9 @@
 			}
 		}
 
-		return String.format("杞鐘舵��: %s, 涓插彛: %s, 闂撮殧: %dms, 鎸囦护缂撳瓨: %d, 鍗℃Ы鑼冨洿: %d-%d, 鏃犲崱: %d(100ms), 鏈夊崱: %d(10s)", 
+		return String.format("杞鐘舵��: %s, 涓插彛: %s, 闂撮殧: %dms, 鎸囦护缂撳瓨: %d, 鍗℃Ы鑼冨洿: %d-%d, 鏃犲崱: %d(100ms), 鏈夊崱: %d(10s)\n%s", 
 				status, serialStatus, pollingInterval, cacheSize, MIN_SLOT, MAX_SLOT, 
-				noCardCount, hasCardCount);
+				noCardCount, hasCardCount, getMemoryStatus());
 	}
 
 	/**
@@ -695,7 +737,7 @@
 			if (isPaused) {
 				// 鎭㈠鍓嶆鏌ヤ覆鍙h繛鎺�
 				if (!checkSerialConnectionWithRetry()) {
-					Errlog.logOperation("涓插彛鏈繛鎺ワ紝鏃犳硶鎭㈠杞鏌ヨ");
+					logErrorWithRateLimit("external_resume_serial_failed", "涓插彛鏈繛鎺ワ紝鏃犳硶鎭㈠杞鏌ヨ");
 					return false;
 				}
 
@@ -752,7 +794,7 @@
 	 */
 	public static void setNoCardQueryInterval(int interval) {
 		if (interval < 10) {
-			Errlog.logOperation("鏃犲崱鍗℃Ы鏌ヨ闂撮殧涓嶈兘灏忎簬10ms");
+			logErrorWithRateLimit("no_card_interval_too_small", "鏃犲崱鍗℃Ы鏌ヨ闂撮殧涓嶈兘灏忎簬10ms");
 			return;
 		}
 		// 娉ㄦ剰锛氳繖閲屽彧鏄缃父閲忥紝瀹為檯杩愯鏃堕渶瑕侀噸鏂板惎鍔ㄨ疆璇㈡墠鑳界敓鏁�
@@ -765,7 +807,7 @@
 	 */
 	public static void setHasCardQueryInterval(int interval) {
 		if (interval < 1000) {
-			Errlog.logOperation("鏈夊崱鍗℃Ы鏌ヨ闂撮殧涓嶈兘灏忎簬1000ms");
+			logErrorWithRateLimit("has_card_interval_too_small", "鏈夊崱鍗℃Ы鏌ヨ闂撮殧涓嶈兘灏忎簬1000ms");
 			return;
 		}
 		// 娉ㄦ剰锛氳繖閲屽彧鏄缃父閲忥紝瀹為檯杩愯鏃堕渶瑕侀噸鏂板惎鍔ㄨ疆璇㈡墠鑳界敓鏁�
@@ -779,4 +821,102 @@
 	public static void setDEBUG_ENABLED(boolean dEBUG_ENABLED) {
 		DEBUG_ENABLED = dEBUG_ENABLED;
 	}
+
+	// ==================== 鏂板鍐呭瓨浼樺寲鏂规硶 ====================
+
+	/**
+	 * 娓呯悊鏃х紦瀛� - 闃叉鍐呭瓨鏃犻檺澧為暱
+	 */
+	private static void cleanupOldCache() {
+		long currentTime = System.currentTimeMillis();
+		if (currentTime - lastCleanupTime < CACHE_CLEANUP_INTERVAL) {
+			return;
+		}
+		
+		lastCleanupTime = currentTime;
+		
+		// 娓呯悊闀挎椂闂存湭浣跨敤鐨勬煡璇㈡椂闂磋褰�
+		long cleanupThreshold = currentTime - 300000; // 5鍒嗛挓鏈娇鐢�
+		lastQueryTimeMap.entrySet().removeIf(entry -> 
+			currentTime - entry.getValue() > cleanupThreshold
+		);
+		
+		// 闄愬埗鏌ヨ鎸囦护缂撳瓨澶у皬
+		if (queryCommandCache.size() > MAX_CACHE_SIZE) {
+			Iterator<Map.Entry<Integer, String>> iterator = queryCommandCache.entrySet().iterator();
+			int itemsToRemove = queryCommandCache.size() - MAX_CACHE_SIZE;
+			for (int i = 0; i < itemsToRemove && iterator.hasNext(); i++) {
+				iterator.next();
+				iterator.remove();
+			}
+		}
+		
+		// 娓呯悊閿欒鏃ュ織闄愭祦璁板綍
+		lastErrorLogTime.entrySet().removeIf(entry -> 
+			currentTime - entry.getValue() > 300000 // 5鍒嗛挓
+		);
+	}
+
+	/**
+	 * 闄愭祦閿欒鏃ュ織 - 闃叉澶ч噺閲嶅鏃ュ織鍗犵敤鍐呭瓨
+	 */
+	private static void logErrorWithRateLimit(String errorKey, String message) {
+		long currentTime = System.currentTimeMillis();
+		Long lastTime = lastErrorLogTime.get(errorKey);
+		
+		if (lastTime == null || currentTime - lastTime > ERROR_LOG_INTERVAL) {
+			Errlog.logOperation(message);
+			lastErrorLogTime.put(errorKey, currentTime);
+			
+			// 娓呯悊杩囨湡鐨勯敊璇褰�
+			if (lastErrorLogTime.size() > 50) {
+				lastErrorLogTime.entrySet().removeIf(entry -> 
+					currentTime - entry.getValue() > 300000 // 5鍒嗛挓
+				);
+			}
+		}
+	}
+
+	/**
+	 * 鑾峰彇鍐呭瓨鐘舵�佷俊鎭�
+	 */
+	public static String getMemoryStatus() {
+		Runtime runtime = Runtime.getRuntime();
+		long totalMemory = runtime.totalMemory();
+		long freeMemory = runtime.freeMemory();
+		long usedMemory = totalMemory - freeMemory;
+		long maxMemory = runtime.maxMemory();
+		
+		return String.format("鍐呭瓨浣跨敤: %.2fMB/%.2fMB (鏈�澶�: %.2fMB), 缂撳瓨: 鏃堕棿璁板綍=%d, 鎸囦护缂撳瓨=%d, 閿欒璁板綍=%d",
+			usedMemory / (1024.0 * 1024.0),
+			totalMemory / (1024.0 * 1024.0),
+			maxMemory / (1024.0 * 1024.0),
+			lastQueryTimeMap.size(),
+			queryCommandCache.size(),
+			lastErrorLogTime.size());
+	}
+
+	/**
+	 * 鎵嬪姩瑙﹀彂鍐呭瓨娓呯悊
+	 */
+	public static void performCleanup() {
+		// 娓呯悊鏌ヨ鏃堕棿璁板綍涓暱鏃堕棿鏈煡璇㈢殑鍗℃Ы
+		long cleanupThreshold = System.currentTimeMillis() - 3600000; // 1灏忔椂
+		lastQueryTimeMap.entrySet().removeIf(entry -> 
+			entry.getValue() < cleanupThreshold
+		);
+		
+		// 娓呯┖鏌ヨ鎸囦护缂撳瓨
+		queryCommandCache.clear();
+		
+		// 娓呯┖閿欒鏃ュ織闄愭祦璁板綍
+		lastErrorLogTime.clear();
+		
+		// 寤鸿绯荤粺杩涜鍨冨溇鍥炴敹锛堜絾涓嶅己鍒讹級
+		System.gc();
+		
+		if (DEBUG_ENABLED) {
+			SystemDebugDialog.appendAsciiData("鎵ц鍐呭瓨娓呯悊瀹屾垚\n");
+		}
+	}
 }
\ No newline at end of file

--
Gitblit v1.10.0