From fab8c02a0aa8f941a507bdcb3e4d72deb6eb2242 Mon Sep 17 00:00:00 2001
From: weimingfei <fei_gaming@sina.com>
Date: 星期五, 24 十月 2025 14:53:18 +0800
Subject: [PATCH] 钥匙柜

---
 keyCabinet-android/app/src/main/java/com/doumee/keyCabinet/ui/main/MainActivity.java |  909 +++++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 857 insertions(+), 52 deletions(-)

diff --git a/keyCabinet-android/app/src/main/java/com/doumee/keyCabinet/ui/main/MainActivity.java b/keyCabinet-android/app/src/main/java/com/doumee/keyCabinet/ui/main/MainActivity.java
index 54fcdac..1b06374 100644
--- a/keyCabinet-android/app/src/main/java/com/doumee/keyCabinet/ui/main/MainActivity.java
+++ b/keyCabinet-android/app/src/main/java/com/doumee/keyCabinet/ui/main/MainActivity.java
@@ -15,7 +15,6 @@
 import android.text.Spanned;
 import android.text.TextUtils;
 import android.text.style.TextAppearanceSpan;
-import android.util.DisplayMetrics;
 import android.view.Gravity;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -40,21 +39,28 @@
 import com.bumptech.glide.request.target.Target;
 import com.bumptech.glide.request.transition.Transition;
 import com.doumee.keyCabinet.BuildConfig;
-import com.doumee.keyCabinet.base.BannerPicResponsePara;
+import com.doumee.keyCabinet.bean.CabinetConfigDataBean;
+import com.doumee.keyCabinet.bean.DevConfigBean;
 import com.doumee.keyCabinet.bean.FaceUserBean;
-import com.doumee.keyCabinet.bean.LoginBean;
+import com.doumee.keyCabinet.dao.CabinetGridDo;
+import com.doumee.keyCabinet.dao.DaoManager;
 import com.doumee.keyCabinet.databinding.MainActivityBinding;
+import com.doumee.keyCabinet.event.CLGridEvent;
+import com.doumee.keyCabinet.event.CLKeyEvent;
+import com.doumee.keyCabinet.event.CloseGridOneResultEvent;
 import com.doumee.keyCabinet.event.GetFacesEvent;
+import com.doumee.keyCabinet.event.GetKeyStatusEvent;
 import com.doumee.keyCabinet.event.HeartEvent;
-import com.doumee.keyCabinet.event.KeyDoorEvent;
+import com.doumee.keyCabinet.event.HttpEvent;
 import com.doumee.keyCabinet.event.KeyResultEvent;
-import com.doumee.keyCabinet.event.KeyStatusListener;
+import com.doumee.keyCabinet.event.ManageOpenGridResultEvent;
+import com.doumee.keyCabinet.event.OpenAllGridEvent;
 import com.doumee.keyCabinet.event.OpenGridEvent;
-import com.doumee.keyCabinet.event.ReLoginEvent;
+import com.doumee.keyCabinet.event.OpenGridListEvent;
+import com.doumee.keyCabinet.event.OpenGridOneResultEvent;
 import com.doumee.keyCabinet.event.TimeClockEvent;
 import com.doumee.keyCabinet.ui.face.ActivationActivity;
 import com.doumee.keyCabinet.ui.face.FaceActivity;
-import com.doumee.keyCabinet.ui.guide.GuideActivity;
 import com.doumee.keyCabinet.ui.keyCabinet.ChangeUrlActivity;
 import com.doumee.keyCabinet.ui.keyCabinet.KeyCabinetActivity;
 import com.doumee.keyCabinet.ui.keyCabinet.ManageLoginActivity;
@@ -75,6 +81,9 @@
 import com.doumee.keyCabinet.utils.face.ImportFileManager;
 import com.doumee.keyCabinet.utils.face.RegisterConfigUtils;
 import com.doumee.keyCabinet.utils.face.model.SingleBaseConfig;
+import com.doumee.keyCabinet.utils.i485.SerialPortModel;
+import com.doumee.keyCabinet.utils.i485.SerialPortReadObserver;
+import com.doumee.keyCabinet.utils.i485.SportUtils;
 import com.doumee.keyCabinet.utils.update.PermissionUtils;
 import com.doumee.keyCabinet.utils.update.PermissiondDialog;
 import com.doumee.keyCabinet.utils.update.UpdateUtil;
@@ -82,7 +91,6 @@
 import com.doumee.keyCabinet.MApplication;
 import com.doumee.keyCabinet.R;
 import com.doumee.keyCabinet.base.MyBaseActivity;
-import com.doumee.keyCabinet.bean.MemberBean;
 import com.doumee.keyCabinet.utils.AdListResponseParam;
 import com.doumee.lib_coremodel.http.utils.GsonTools;
 import com.doumee.lib_coremodel.util.SpUtil;
@@ -94,15 +102,15 @@
 import com.example.datalibrary.model.User;
 import com.example.datalibrary.view.PreviewTexture;
 import com.yanzhenjie.permission.runtime.Permission;
+
 import org.greenrobot.eventbus.EventBus;
-import org.greenrobot.eventbus.Logger;
 import org.greenrobot.eventbus.Subscribe;
+import org.greenrobot.eventbus.ThreadMode;
 
 import java.util.ArrayList;
-import java.util.Calendar;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
-import java.util.Random;
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.concurrent.Executors;
@@ -153,7 +161,7 @@
                     }
                     getVM().upBraceletLog();*/
                     case 2:
-                        getVM().resetReq();
+
                         break;
                 }
             }
@@ -182,6 +190,7 @@
         startService(intent2);
         getPermission();
         Timber.tag("====>").d(LMobileInfo.getDeviceUniqueId());
+        initPort();
     }
 
     private void initM(){
@@ -262,6 +271,7 @@
         getDB().tvId.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
+                startActivity(ManageLoginActivity.class);
                 //鏇存敼url
                 if(lastDownTime2!=null){
                     if(System.currentTimeMillis()-lastDownTime2>1000){
@@ -277,15 +287,40 @@
                 }
             }
         });
+        getDB().tvVersion.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                //todo 涓存椂浠g爜
+                setJiuConfig();
+            }
+        });
         upErrInfo();
+        getVM().devLogin();
         getVM().devHeart();
-        BraceletLogUtils.saveLog("app鎵撳紑");
+        getVM().getConfidLD().observe(this, new Observer<DevConfigBean>() {
+            @Override
+            public void onChanged(DevConfigBean devConfigBean) {
+                if(devConfigBean!=null){
+                    if(devConfigBean.getBannerList()!=null) {
+                        setBanner(devConfigBean.getBannerList());
+                    }
+                    setJiuConfig();
+                }
+            }
+        });
     }
 
-
+    private void setJiuConfig(){
+        getVM().addInfo("閰掔簿閰嶇疆锛�"+(MApplication.getConfigBean().getCabinetConfigDataVO()!=null)+
+                ",涓插彛寮�鍚細"+(jiuPort!=null));
+        if(MApplication.getConfigBean().getCabinetConfigDataVO()!=null&&
+            jiuPort!=null){
+            setJiuConfig(0);
+        }
+    }
 
     boolean isOne;
-    private void setBanner(List<BannerPicResponsePara> bannerList){
+    private void setBanner(List<String> bannerList){
         getDB().banner.setPages(new CBViewHolderCreator<BannerViewImageHolder>() {
             @Override
             public BannerViewImageHolder createHolder() {
@@ -326,36 +361,81 @@
     protected void doRegister(int type, ActionEventData data) {
         switch (type){
             case 2:
-            case 3:
-                /*tipDownCount = 10;
-                isShowTip = true;
-                getDB().tvDjs.setText(tipDownCount+"s");
-                getDB().tvTip21.setText(getTipText("AC101"), TextView.BufferType.SPANNABLE);
-                getDB().clTip.setVisibility(View.VISIBLE);*/
+            case 3: {
                 //鏍¢獙鏄惁鐧诲綍
                 if(MApplication.getConfigBean().getId()==null){
                     Toast.makeText(mContext, "璁惧鏈坊鍔狅紝鏃犳硶鎿嶄綔", Toast.LENGTH_SHORT).show();
                     getVM().devLogin();
                     return;
                 }
-                MApplication.getLoginBean().setFlag(type==2?0:1);
-                startActivity(FaceActivity.class);
-                //startActivity(KeyCabinetActivity.class,b);
+                checkGridStatus(0);
+                List<CabinetGridDo> gridDos = getVM().getOpenGrids();
+                if (gridDos.size() > 0) {
+                    showUnCloseTip(gridDos);
+                    return;
+                }
+                MApplication.setLoginBean(null);
+                MApplication.getLoginBean().setFlag(type == 2 ? 0 : 1);
+                startActivity(KeyCabinetActivity.class);
+                }
                 break;
             case 4:
                 isShowTip = false;
                 getDB().clTip.setVisibility(View.GONE);
+                break;
+            case 5: {
+                List<CabinetGridDo> gridDos = getVM().getOpenGrids();
+                if (gridDos.size() > 0) {
+                    showUnCloseTip(gridDos);
+                }else {
+                    isShowTip = false;
+                    getDB().clTip.setVisibility(View.GONE);
+                }
+                }
+                break;
+            case 55:
+                getVM().infoObs.set("");
                 break;
             default:
                 break;
         }
     }
 
+    private void showUnCloseTip(List<CabinetGridDo> gridDos){
+        tipDownCount = 10;
+        isShowTip = true;
+        getDB().tvDjs.setText(tipDownCount + "s");
+        StringBuilder sb = new StringBuilder();
+        for(CabinetGridDo d:gridDos){
+            if (sb.length()>0) {
+                sb.append("銆�");
+            }
+            String name = d.getCabinetName();
+            if (TextUtils.isEmpty(name)) {
+                name = gridDos.get(0).getGridKey();
+            }
+            sb.append(name);
+        }
+        getDB().tvTip22.setText(getTipText(sb.toString()), TextView.BufferType.SPANNABLE);
+        getDB().tvTip23.setText(getErrPhoneText(), TextView.BufferType.SPANNABLE);
+        getDB().clTip.setVisibility(View.VISIBLE);
+    }
+
+    private SpannableString getErrPhoneText(){
+        String phone = MApplication.getConfigBean().getLinkPhone();
+        String text = "濡傛湁闂璇疯仈绯荤鐞嗗憳"+phone;
+        SpannableString styledText = new SpannableString(text);
+        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_tip3), 0, text.length()-phone.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+        styledText.setSpan(new TextAppearanceSpan(this,R.style.style_tip1), text.length()-phone.length()+1, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+        return styledText;
+    }
+
+    private boolean isShowing = false;
     @Override
     protected void onResume() {
         super.onResume();
+        isShowing = true;
         showTime = System.currentTimeMillis();
-        MApplication.setLoginBean(new LoginBean());
         if(!isFaceOk) {
             //initLicense();
         }
@@ -363,11 +443,20 @@
             checkUpdate();
         }
         triggerGarbageCollection();
-        getVM().resetReq();
+
         if(!isOne) {
             getDB().banner.startTurning(3000);
         }else {
             getDB().banner.stopTurning();
+        }
+        unCloseGrid();
+    }
+
+    private void unCloseGrid(){
+        //鏈叧闂紝璋冪敤鎺ュ彛
+        List<CabinetGridDo> gridDos = getVM().getOpenGrids();
+        if(gridDos.size()>0){
+            getVM().timeOutUnCloseAlarm(gridDos.get(0));
         }
     }
 
@@ -388,11 +477,17 @@
         handler = null;
         faceHandler.removeCallbacksAndMessages(null);
         faceHandler = null;
+        portHandler.removeCallbacksAndMessages(null);
+        portHandler = null;
+        closePort(gridPort);
+        closePort(keyPort);
+        closePort(jiuPort);
+        closePort(chosePort);
     }
 
     private void restartApp(){
         // 鍒涘缓涓�涓柊鐨勫惎鍔ㄦ剰鍥�
-        Intent intent = new Intent(mContext, GuideActivity.class);
+        Intent intent = new Intent(mContext, MainActivity.class);
         // 璁剧疆FLAG_ACTIVITY_CLEAR_TASK鏍囧織浣�
         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
         // 浣跨敤PendingIntent鍖呰鍚姩鎰忓浘
@@ -416,14 +511,6 @@
             }else {
                 isNeedUpdateFace = true;
             }
-        }
-    }
-
-    @Subscribe
-    public void ReLoginEvent(ReLoginEvent event){
-        if(!isFinishing()){
-            handler.sendEmptyMessageDelayed(2,20000);
-            getVM().devLogin();
         }
     }
 
@@ -617,6 +704,7 @@
     protected void onPause() {
         super.onPause();
         showTime = null;
+        isShowing = false;
     }
 
     private int finishCount;
@@ -996,36 +1084,49 @@
      * 鐩戝惉寮�闂�
      * @param e
      */
-    @Subscribe
+    @Subscribe(threadMode=ThreadMode.MAIN)
     public void OpenGridEvent(OpenGridEvent e){
         if(!isFinishing()){
-            EventBus.getDefault().post(new KeyDoorEvent(MApplication.nextBoolean()?"0":"1"));
+            //寮�鍚煖闂�
+            String code = "8A"+SportUtils.intToHex(Integer.parseInt(e.getBoardCode()))
+                    +SportUtils.intToHex(Integer.parseInt(e.getChannelCode()))+"11";
+            code += SportUtils.getBCC(code);
+            send485(0,code);
         }
     }
 
-    /**
-     * 鐩戝惉閽ュ寵
-     * @param e
-     */
-    @Subscribe
-    public void KeyStatusListener(KeyStatusListener e){
+    //鏌滈棬鍏ㄥ紑
+    @Subscribe(threadMode=ThreadMode.MAIN)
+    public void OpenAllGridEvent(OpenAllGridEvent e){
         if(!isFinishing()){
-            if(e.getStatus()==0){
-                //寮�濮�
-                Random random = new Random();
-                EventBus.getDefault().post(new KeyResultEvent(random.nextBoolean()?"0":"1"));
-            }else {
-                //缁撴潫
+            //寮�鍚煖闂�
+            sendPortHandlerMsg(1,"8A01FF1165",0);
+            sendPortHandlerMsg(1,"8A02FF1166",8000);
+        }
+    }
+
+    //鏌滈棬鎵归噺寮�
+    @Subscribe(threadMode=ThreadMode.MAIN)
+    public void OpenGridListEvent(OpenGridListEvent e){
+        if(!isFinishing()){
+            //寮�鍚煖闂�
+            long time = 0;
+            for(String key:e.getKeys()){
+                String code = "8A"+key+"11";
+                code += SportUtils.getBCC(code);
+                sendPortHandlerMsg(1,code,time);
+                time+=400;
             }
         }
     }
 
     private SpannableString getTipText(String name){
-        String text = name+"鏌滈棬鏈叧闂�";
+        String text = "璇峰叧闂�"+name+"鏌滈棬";
         SpannableString styledText = new SpannableString(text);
+        styledText.setSpan(new TextAppearanceSpan(this,R.style.style_tip2), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
         styledText.setSpan(new TextAppearanceSpan(this, R.style.style_tip1),
-                0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
-        styledText.setSpan(new TextAppearanceSpan(this,R.style.style_tip2), name.length()+1, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+                3, 3+name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+        styledText.setSpan(new TextAppearanceSpan(this,R.style.style_tip2), name.length()+3, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
         return styledText;
     }
 
@@ -1035,6 +1136,7 @@
         getVM().devHeart();
     }
 
+
     @Subscribe
     public void HeartEvent(HeartEvent e){
         if(!isFinishing()){
@@ -1042,4 +1144,707 @@
         }
     }
 
+
+    @Subscribe
+    public void CloseGridOneResultEvent(CloseGridOneResultEvent e){
+        if(!isFinishing()&&isShowing){
+            //鍦ㄩ椤碉紝鏍¢獙鍏抽棬鐨勯挜鍖欐槸鍚﹀尮閰�
+            if (e.getIsOpen() == 0) {
+                //鍏抽棬鎴愬姛
+                //鏌ヨ閽ュ寵鍙�
+                CabinetGridDo gridDo = DaoManager.getCabinetGridDao().getGridByKey(e.getKey());
+                if (gridDo != null) {
+                    getVM().addInfo("姣旇緝閽ュ寵锛氬綋鍓嶏細"+gridDo.getCurKeyCode()+", 鍏宠仈閽ュ寵锛�"+gridDo.getKeyCode());
+                    if(!TextUtils.isEmpty(gridDo.getCurKeyCode())&&
+                            !TextUtils.isEmpty(gridDo.getKeyCode())&&
+                            !gridDo.getCurKeyCode().equals(gridDo.getKeyCode())){
+                        //閽ュ寵涓嶄竴鏍凤紝寮�闂�
+                        Toast.makeText(mContext, "閽ュ寵瀛樻斁浣嶇疆閿欒", Toast.LENGTH_SHORT).show();
+                        EventBus.getDefault().post(new OpenGridEvent(Integer.parseInt(e.getKey().substring(2,4), 16)+"",
+                                Integer.parseInt(e.getKey().substring(0,2), 16)+""));
+                    }else {
+                        if(isShowTip){
+                            doRegister(5,null);
+                        }
+                        if(isShowing){
+                            //鍦ㄩ椤靛叧闂ㄦ垚鍔燂紝闇�璋冪敤鍏抽棬鏂规硶
+                            getVM().closeGrid(gridDo);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private SerialPortModel gridPort;
+    private SerialPortReadObserver gridReadObserver = new SerialPortReadObserver() {
+        @Override
+        public void onResult(String result) {
+            runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if(result==null){
+
+                    }else {
+                        getVM().addInfo("鍙戦�佹寚浠ゅけ璐ワ細");
+                    }
+                }
+            });
+        }
+
+        @Override
+        public void onResultBytes(byte[] bytes) {
+            if(bytes.length==0){
+                return;
+            }
+            runOnUiThread(() -> {
+                getVM().addInfo("鑾峰彇鍒伴棬鏁版嵁:"+StringUtil.DateToStrSS(new Date())+"==>"+ SportUtils.bytesToHexSimple(bytes));
+            });
+            EventBus.getDefault().post(new CLGridEvent(SportUtils.bytesToHexSimple(bytes)));
+        }
+    };
+
+    @Subscribe(threadMode = ThreadMode.MAIN)
+    public void HttpEvent(HttpEvent e){
+        if(!isFinishing()){
+            getVM().addInfo(e.getMsg());
+        }
+    }
+
+    @Subscribe(threadMode = ThreadMode.MAIN)
+    public void CLGridEvent(CLGridEvent e){
+        if(!isFinishing()){
+            String data = e.getData();
+            data = data.toUpperCase();
+            data = data.replaceAll("\\s+", "");
+            if(data.startsWith("8A")){
+                //寮�閿佸弽棣�
+                String bh = data.substring(2,4);
+                if(data.length()==10){
+                    //鍗曚釜
+                    String tdh = data.substring(4,6);
+                    String open = data.substring(6,8);
+                    /*runOnUiThread(() -> {
+                        getVM().addInfo("鑾峰彇鍒伴棬鏁版嵁:" + "鐗堝彿锛�"+bh+",閿佸彿锛�"+tdh+",鏄惁寮�闂�--"+("00".equals(open)?"鏄�":"鍚�"));
+                    });*/
+                    String key = bh+tdh;
+                    CabinetGridDo gridDo = DaoManager.getCabinetGridDao().getGridByKey(key);
+                    if(gridDo==null){
+                        //鏂板
+                        gridDo = new CabinetGridDo();
+                        gridDo.setIsOpen("00".equals(open)?1:0);
+                        gridDo.setGridKey(key);
+                        gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                        DaoManager.getCabinetGridDao().insert(gridDo);
+                    }else {
+                        gridDo.setIsOpen("00".equals(open)?1:0);
+                        gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                        DaoManager.getCabinetGridDao().update(gridDo);
+                    }
+                    //寮�闂ㄨ繑鍥�
+                    EventBus.getDefault().post(new OpenGridOneResultEvent(key,gridDo.getIsOpen()));
+                    if(!portHandler.hasMessages(1)){
+                        EventBus.getDefault().post(new ManageOpenGridResultEvent());
+                    }
+                }else if(data.length()==16){
+                    //鎵归噺
+                    //8A 02 00 00 00 00 11 99
+                    String dm = data.substring(4,12);
+                    dm = SportUtils.hexToBinary(dm);
+                    StringBuilder sb = new StringBuilder(dm);
+                    dm = sb.reverse().toString();
+                    List<CabinetGridDo> gridDos = DaoManager.getCabinetGridDao().loadAll();
+                    HashMap<String,CabinetGridDo> oldMap = new HashMap<>();
+                    for(CabinetGridDo d:gridDos){
+                        oldMap.put(d.getGridKey(),d);
+                    }
+                    List<CabinetGridDo> addList = new ArrayList<>();
+                    List<CabinetGridDo> updateList = new ArrayList<>();
+                    String finalDm = dm;
+                    /*runOnUiThread(() -> {
+                        getVM().addInfo("鎵归噺鏌ヨ杩斿洖锛�" +bh+","+ finalDm+",鎬绘暟鎹細"+oldMap.size());
+                    });*/
+                    try {
+                        for(int i=1;i<=dm.length();i++){
+                            String key = bh+SportUtils.intToHex(i);
+                            if(oldMap.containsKey(key)){
+                                CabinetGridDo gridDo = oldMap.get(key);
+                                gridDo.setIsOpen("1".equals(dm.substring(i-1,i))?0:1);
+                                gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                                updateList.add(gridDo);
+                            }/*else {
+                                getVM().addInfo("鏂板key锛�" +key);
+                                CabinetGridDo gridDo = new CabinetGridDo();
+                                gridDo.setGridKey(key);
+                                gridDo.setIsOpen("1".equals(dm.substring(i-1,i))?0:1);
+                                gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                                addList.add(gridDo);
+                            }*/
+                        }
+                        runOnUiThread(() -> {
+                            getVM().addInfo("鎵归噺寮�闂ㄦ洿鏂板簱鏁版嵁:鐗堝彿锛�" +bh+","+ addList.size()+","+updateList.size());
+                        });
+                        getVM().insertGrids(addList);
+                        getVM().updateGrids(updateList);
+                        if(!portHandler.hasMessages(1)){
+                            EventBus.getDefault().post(new ManageOpenGridResultEvent());
+                        }
+                    }catch (Exception exception){
+                        runOnUiThread(() -> {
+                            getVM().addInfo("鎵归噺寮�闂ㄦ姤閿欙細" +exception.getMessage());
+                        });
+                    }
+                }
+            }else if(data.startsWith("81")){
+                //涓诲姩鍏抽棬 81 01 01 11 90
+                String bh = data.substring(2,4);
+                String tdh = data.substring(4,6);
+                String open = data.substring(6,8);
+                String key = bh+tdh;
+                CabinetGridDo gridDo = DaoManager.getCabinetGridDao().getGridByKey(key);
+                if(gridDo==null){
+                    //鏂板
+                    gridDo = new CabinetGridDo();
+                    gridDo.setIsOpen("00".equals(open)?1:0);
+                    gridDo.setGridKey(key);
+                    gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                    DaoManager.getCabinetGridDao().insert(gridDo);
+                }else {
+                    gridDo.setIsOpen("00".equals(open)?1:0);
+                    gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                    DaoManager.getCabinetGridDao().update(gridDo);
+                }
+                //鍏抽棬杩斿洖
+                EventBus.getDefault().post(new CloseGridOneResultEvent(key,gridDo.getIsOpen()));
+                if(isShowing&&isShowTip){
+                    //淇敼鏄剧ず鎻愰啋
+                    doRegister(5,null);
+                }
+            }else if(data.startsWith("80")){
+                //鏌ヨ鎵�鏈夐棬鐘舵��
+                //80 01 00 00 FF FF 33 B2
+                //80 02 00 00 00 F7 33 46
+                if(data.length()>=14){
+                    String bh = data.substring(2,4);
+                    String dm = data.substring(4,12);
+                    dm = dm.replaceAll("0","");
+                    dm = SportUtils.hexToBinary(dm);
+                    StringBuilder sb = new StringBuilder(dm);
+                    dm = sb.reverse().toString();
+                    List<CabinetGridDo> gridDos = DaoManager.getCabinetGridDao().loadAll();
+                    HashMap<String,CabinetGridDo> oldMap = new HashMap<>();
+                    for(CabinetGridDo d:gridDos){
+                        oldMap.put(d.getGridKey(),d);
+                    }
+                    List<CabinetGridDo> addList = new ArrayList<>();
+                    List<CabinetGridDo> updateList = new ArrayList<>();
+                    String finalDm = dm;
+                    runOnUiThread(() -> {
+                        getVM().addInfo("鎵归噺鏌ヨ杩斿洖锛�" +bh+","+ finalDm+",鎬绘暟鎹細"+oldMap.size());
+                    });
+                    try {
+                        for(int i=1;i<=dm.length();i++){
+                            String key = bh+SportUtils.intToHex(i);
+                            /*String finalDm1 = dm;
+                            int finalI = i;
+                            runOnUiThread(() -> {
+                                getVM().addInfo("key锛�" +key+","+("1".equals(finalDm1.substring(finalI -1, finalI))?"鍏�":"寮�"));
+                            });*/
+                            //System.out.println("===>"+key+","+("1".equals(dm.substring(i-1,i))?"鍏�":"寮�"));
+                            if(oldMap.containsKey(key)){
+                                CabinetGridDo gridDo = oldMap.get(key);
+                                gridDo.setIsOpen("1".equals(dm.substring(i-1,i))?0:1);
+                                gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                                updateList.add(gridDo);
+                            }else {
+                                CabinetGridDo gridDo = new CabinetGridDo();
+                                gridDo.setGridKey(key);
+                                gridDo.setIsOpen("1".equals(dm.substring(i-1,i))?0:1);
+                                gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                                addList.add(gridDo);
+                            }
+                        }
+                        runOnUiThread(() -> {
+                            getVM().addInfo("鏇存柊搴撴暟鎹�:鐗堝彿锛�" +bh+","+ addList.size()+","+updateList.size());
+                        });
+                        getVM().insertGrids(addList);
+                        getVM().updateGrids(updateList);
+                    }catch (Exception exception){
+                        runOnUiThread(() -> {
+                            getVM().addInfo("鎶ラ敊锛�" +exception.getMessage());
+                        });
+                    }
+
+                }
+            }
+        }
+    }
+
+    private SerialPortModel keyPort;
+    //涓婁竴娆℃暟鎹�
+    private String keyPreviousData;
+    private SerialPortReadObserver keyReadObserver = new SerialPortReadObserver() {
+        @Override
+        public void onResult(String result) {
+            if(result==null){
+
+            }else {
+                getVM().addInfo("鍙戦�佹寚浠ゅけ璐ワ細");
+            }
+        }
+
+        @Override
+        public void onResultBytes(byte[] bytes) {
+            if(bytes.length==0){
+                return;
+            }
+            EventBus.getDefault().post(new CLKeyEvent(SportUtils.bytesToHexSimple(bytes)));
+        }
+    };
+
+    @Subscribe(threadMode = ThreadMode.MAIN)
+    public void CLKeyEvent(CLKeyEvent e){
+        if(!isFinishing()){
+            //鏍¢獙鐜板湪鐨勬暟鎹槸鍚︽槸鍏ㄦ暟鎹�
+            String data1 = e.getData();
+            data1 = data1.toUpperCase();
+            String data = data1.replaceAll("\\s+", "");
+            if(data.startsWith("CC01")){
+                keyPreviousData = data;
+            }else if(data.startsWith("CC02")){
+                runOnUiThread(() -> {
+                    getVM().addInfo("鑾峰彇鍒伴挜鍖欐暟鎹�:" + data);
+                    jxKey(data);
+                });
+                keyPreviousData = null;
+            }else {
+                if(!TextUtils.isEmpty(keyPreviousData)){
+                    String data2 = keyPreviousData+data;
+                    runOnUiThread(() -> {
+                        getVM().addInfo("鑾峰彇鍒伴挜鍖欐暟鎹�:" + data2);
+                        jxKey(data2);
+                    });
+                    keyPreviousData = null;
+                }
+            }
+        }
+    }
+
+    @Subscribe
+    public void GetKeyStatusEvent(GetKeyStatusEvent e){
+        if(!isFinishing()){
+            checkKeyStatus(0);
+        }
+    }
+    //瑙f瀽閽ュ寵鏁版嵁
+    private void jxKey(String data){
+        List<CabinetGridDo> gridDos = DaoManager.getCabinetGridDao().loadAll();
+        HashMap<String,CabinetGridDo> oldMap = new HashMap<>();
+        for(CabinetGridDo d:gridDos){
+            oldMap.put(d.getGridKey(),d);
+        }
+        List<CabinetGridDo> addList = new ArrayList<>();
+        List<CabinetGridDo> updateList = new ArrayList<>();
+        //浜屽彿鐗�
+        int bh = 2;
+        if(data.startsWith("CC01")){
+            //涓�鍙风増
+            bh = 1;
+        }
+        String[] sp = data.split("AA");
+        for(String s:sp){
+            if(s.length()>=20){
+                String key = SportUtils.intToHex(bh)+s.substring(4,6);
+                String isHaveKey = s.substring(8,10);
+                String keyCode = s.substring(10,18);
+                if(oldMap.containsKey(key)){
+                    //淇敼
+                    CabinetGridDo gridDo = oldMap.get(key);
+                    if("01".equals(isHaveKey)) {
+                        gridDo.setCurKeyCode(keyCode);
+                    }else {
+                        gridDo.setCurKeyCode("");
+                    }
+                    gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                    updateList.add(gridDo);
+                }else {
+                    //鏂板
+                    CabinetGridDo gridDo = new CabinetGridDo();
+                    gridDo.setGridKey(key);
+                    if("01".equals(isHaveKey)) {
+                        gridDo.setCurKeyCode(keyCode);
+                    }else {
+                        gridDo.setCurKeyCode("");
+                    }
+                    gridDo.setUpdateTime(StringUtil.DateToStr(new Date()));
+                    addList.add(gridDo);
+                }
+            }
+        }
+        getVM().insertGrids(addList);
+        getVM().updateGrids(updateList);
+        EventBus.getDefault().post(new KeyResultEvent());
+    }
+
+    private SerialPortModel jiuPort;
+    private SerialPortReadObserver jiuReadObserver = new SerialPortReadObserver() {
+        @Override
+        public void onResult(String result) {
+            if(result==null){
+
+            }else {
+                getVM().addInfo("鍙戦�佹寚浠ゅけ璐ワ細");
+            }
+        }
+
+        @Override
+        public void onResultBytes(byte[] bytes) {
+            if(bytes.length==0){
+                return;
+            }
+            runOnUiThread(() -> {
+                getVM().addInfo("鑾峰彇鍒伴厭绮炬娴嬫暟鎹�:" + new String(bytes));
+            });
+        }
+    };
+    private SerialPortModel chosePort;
+    private SerialPortReadObserver choseReadObserver = new SerialPortReadObserver() {
+        @Override
+        public void onResult(String result) {
+            runOnUiThread(new Runnable() {
+                @Override
+                public void run() {
+                    if(result==null){
+
+                    }else {
+                        getVM().addInfo("鍙戦�佹寚浠ゅけ璐ワ細");
+                    }
+                }
+            });
+        }
+
+        @Override
+        public void onResultBytes(byte[] bytes) {
+            if(bytes.length==0){
+                return;
+            }
+            runOnUiThread(() -> {
+                getVM().addInfo("鑾峰彇鍒伴棬鏁版嵁:" + SportUtils.bytesToHexSimple(bytes));
+            });
+            if(startIndex==1){
+                gridPath = path;
+                getVM().addInfo("璁剧疆闂ㄤ覆鍙h矾寰�:" + path);
+                SpUtil.saveString("port_grid",path);
+            }else if(startIndex==2){
+                keyPath = path;
+                getVM().addInfo("璁剧疆閽ュ寵涓插彛璺緞:" + path);
+                SpUtil.saveString("port_key",path);
+            }else if(startIndex==3){
+                jiuPath = path;
+                getVM().addInfo("璁剧疆閰掔簿涓插彛璺緞:" + path);
+                SpUtil.saveString("port_jiu",path);
+            }
+        }
+    };
+
+    List<String> ports;
+    private int index = 0;
+    private String path;
+    private int startIndex;
+    private String gridPath;
+    private String keyPath;
+    private String jiuPath;
+    private int xhCount = 0;
+    private Handler portHandler = new Handler(){
+        @Override
+        public void handleMessage(@NonNull Message msg) {
+            switch (msg.what){
+                case 0:
+                    if(index>=1&&!checkEnd()){
+                        path = ports.get(index);
+                        index--;
+                        portHandler.sendEmptyMessage(4);
+                    }else if(checkEnd()){
+                        initPort();
+                    }else if(xhCount<3){
+                        initPort();
+                    }
+                    break;
+                case 1:
+                    //鍙戦�佹煖鏍煎懡浠�
+                    send485(0, (String) msg.obj);
+                    break;
+                case 2:
+                    //鍙戦�侀挜鍖欏懡浠�
+                    send485(1, (String) msg.obj);
+                    break;
+                case 3:
+                    //鍙戦�侀厭绮炬鏌ュ懡浠�
+                    send485(2, (String) msg.obj);
+                    break;
+                case 4:
+                    if(startIndex>2){
+                        portHandler.sendEmptyMessage(0);
+                    }else {
+                        try {
+                            chosePort();
+                        } catch (SecurityException e) {
+                            portHandler.sendEmptyMessageDelayed(5, 1000);
+                        }
+                    }
+                    break;
+                case 5:
+                    closePort(chosePort);
+                    portHandler.sendEmptyMessageDelayed(4,1000);
+                    break;
+                case 6:
+
+                    break;
+                default:
+                    break;
+            }
+        }
+    };
+
+    //妫�鏌ユ墍鏈夐棬鐘舵��
+    private void checkGridStatus(long time){
+        sendPortHandlerMsg(1,"80010033B2",time+100);
+        sendPortHandlerMsg(1,"80020033B1",time+800);
+    }
+
+    //妫�鏌ユ墍鏈夐挜鍖欑姸鎬�
+    private void checkKeyStatus(long time){
+        sendPortHandlerMsg(2,"A001010000000002",time+200);
+        sendPortHandlerMsg(2,"A002010000000003",time+400);
+    }
+
+    private void setJiuConfig(long time){
+        CabinetConfigDataBean config = MApplication.getConfigBean().getCabinetConfigDataVO();
+        //璁剧疆鍚规皵鏃堕棿
+        sendPortHandlerMsg(3,"blow:"+config.getBlowTime(),time+100);
+        //鍘嬪姏鍊�
+        sendPortHandlerMsg(3,"mic_ad:"+config.getPressure(),time+300);
+        //娴撳害闃堝��
+        sendPortHandlerMsg(3,"alarm:"+config.getConcentration(),time+600);
+        //娴撳害闃堝�煎崟浣� (1=mg/100ml;2=mg/L;3=%BAC)
+        sendPortHandlerMsg(3,"unit:"+config.getThreshold(),time+900);
+    }
+
+    private void sendPortHandlerMsg(int what,String obj,long time){
+        Message mc = Message.obtain();
+        mc.what=what;
+        mc.obj = obj;
+        portHandler.sendMessageDelayed(mc,time);
+    }
+
+    //鍒濆鍖栦覆鍙�
+    private void initPort(){
+        SpUtil.setString("port_grid","/dev/ttyS7");
+        SpUtil.setString("port_key","/dev/ttyS1");
+        SpUtil.setString("port_jiu","/dev/ttyS2");
+        gridPath = SpUtil.getString("port_grid");
+        getVM().addInfo("闂ㄤ覆鍙i摼鎺ワ細"+gridPath);
+        keyPath = SpUtil.getString("port_key");
+        getVM().addInfo("閽ュ寵涓插彛閾炬帴锛�"+keyPath);
+        jiuPath = SpUtil.getString("port_jiu");
+        getVM().addInfo("閰掔簿涓插彛閾炬帴锛�"+jiuPath);
+        if(!TextUtils.isEmpty(SpUtil.getString("port_grid"))&&
+                !TextUtils.isEmpty(SpUtil.getString("port_key"))&&
+                !TextUtils.isEmpty(SpUtil.getString("port_jiu"))){
+            xhCount=0;
+            closePort(chosePort);
+            if(!TextUtils.isEmpty(SpUtil.getString("port_grid"))){
+                String path = SpUtil.getString("port_grid");
+                closePort(gridPort);
+                getVM().addInfo("闂ㄤ覆鍙i摼鎺ワ細"+path);
+                gridPort = new SerialPortModel(path,9600 ,8
+                        ,1 , 0,gridReadObserver);
+                boolean isSucc = gridPort.open();
+                if(isSucc) {
+                    getVM().addInfo("闂ㄤ覆鍙i摼鎺ユ垚鍔燂細"+path);
+                    String msg = isSucc ? "鎴愬姛" : "澶辫触";
+                    //getVM().append("涓插彛 "+ settingBean.getDevicePath() + " -杩炴帴"+msg);
+                    gridPort.startRead();
+                    //鏌ヨ鎵�鏈夋煖鏍奸棬淇℃伅
+                   checkGridStatus(300);
+                }else {
+                    getVM().addInfo("闂ㄤ覆鍙i摼鎺ュけ璐ワ細"+path);
+                }
+            }
+            if(!TextUtils.isEmpty(SpUtil.getString("port_key"))){
+                String path = SpUtil.getString("port_key");
+                closePort(keyPort);
+                keyPort = new SerialPortModel(path,115200 ,8
+                        ,1 , 0,keyReadObserver);
+                boolean isSucc = keyPort.open();
+                if(isSucc) {
+                    getVM().addInfo("閽ュ寵涓插彛閾炬帴鎴愬姛锛�"+path);
+                    String msg = isSucc ? "鎴愬姛" : "澶辫触";
+                    //getVM().append("涓插彛 "+ settingBean.getDevicePath() + " -杩炴帴"+msg);
+                    keyPort.startRead();
+                    checkKeyStatus(1500);
+                }else {
+                    getVM().addInfo("閽ュ寵涓插彛閾炬帴澶辫触锛�"+path);
+                }
+            }
+            if(!TextUtils.isEmpty(SpUtil.getString("port_jiu"))){
+                String path = SpUtil.getString("port_jiu");
+                closePort(jiuPort);
+                jiuPort = new SerialPortModel(path,9600 ,8
+                        ,1 , 0,jiuReadObserver);
+                boolean isSucc = jiuPort.open();
+                if(isSucc) {
+                    getVM().addInfo("閰掔簿涓插彛閾炬帴鎴愬姛锛�"+path);
+                    String msg = isSucc ? "鎴愬姛" : "澶辫触";
+                    //getVM().append("涓插彛 "+ settingBean.getDevicePath() + " -杩炴帴"+msg);
+                    jiuPort.startRead();
+                }else {
+                    getVM().addInfo("閰掔簿涓插彛閾炬帴澶辫触锛�"+path);
+                }
+            }
+        }else {
+            if(xhCount>2){
+                return;
+            }
+            xhCount++;
+            ports = SportUtils.getSerialPortPaths(this);
+            if(ports==null){
+                getVM().addInfo("鏈煡璇㈠埌涓插彛鍒楄〃");
+            }else {
+                getVM().addInfo("涓插彛鍒楄〃锛�"+ports.size());
+            }
+            if(ports.size()>0){
+                index = ports.size()-1;
+                portHandler.sendEmptyMessage(0);
+            }
+        }
+    }
+
+    private void chosePort(){
+        getVM().addInfo("褰撳墠涓嬫爣锛�"+startIndex+" ,path="+path);
+        if(startIndex==0&&TextUtils.isEmpty(gridPath)){
+            startIndex++;
+            getVM().addInfo("闂ㄤ覆鍙i摼鎺ワ細"+path);
+            chosePort = new SerialPortModel(path,9600 ,8
+                    ,1 , 0,choseReadObserver);
+            boolean isSucc = chosePort.open();
+            if(isSucc) {
+                getVM().addInfo("闂ㄤ覆鍙i摼鎺ユ垚鍔燂細"+path);
+                String msg = isSucc ? "鎴愬姛" : "澶辫触";
+                //getVM().append("涓插彛 "+ settingBean.getDevicePath() + " -杩炴帴"+msg);
+                chosePort.startRead();
+                //鍙戦�佹煖鏍兼牎楠屼俊鎭�
+                send485(3,"80010033B2");
+            }else {
+                getVM().addInfo("闂ㄤ覆鍙i摼鎺ュけ璐ワ細"+path);
+            }
+            portHandler.sendEmptyMessageDelayed(5,1500);
+            return;
+        }
+        if(startIndex==1&&TextUtils.isEmpty(keyPath)){
+            startIndex++;
+            chosePort = new SerialPortModel(path,115200 ,8
+                    ,1 , 0,choseReadObserver);
+            boolean isSucc = chosePort.open();
+            if(isSucc) {
+                getVM().addInfo("閽ュ寵涓插彛閾炬帴鎴愬姛锛�"+path);
+                String msg = isSucc ? "鎴愬姛" : "澶辫触";
+                //getVM().append("涓插彛 "+ settingBean.getDevicePath() + " -杩炴帴"+msg);
+                chosePort.startRead();
+                //鍙戦�侀挜鍖欐牎楠屼俊鎭�
+                send485(3,"A001010000000002");
+            }else {
+                getVM().addInfo("閽ュ寵涓插彛閾炬帴澶辫触锛�"+path);
+            }
+            portHandler.sendEmptyMessageDelayed(5,1500);
+            return;
+        }
+        if(startIndex==2&&TextUtils.isEmpty(jiuPath)){
+            startIndex++;
+            chosePort = new SerialPortModel(path,9600 ,8
+                    ,1 , 0,choseReadObserver);
+            boolean isSucc = chosePort.open();
+            if(isSucc) {
+                getVM().addInfo("閰掔簿涓插彛閾炬帴鎴愬姛锛�"+path);
+                String msg = isSucc ? "鎴愬姛" : "澶辫触";
+                //getVM().append("涓插彛 "+ settingBean.getDevicePath() + " -杩炴帴"+msg);
+                chosePort.startRead();
+                //鍙戦�侀厭绮炬牎楠屼俊鎭�
+                send485(4,"read");
+            }else {
+                getVM().addInfo("閰掔簿涓插彛閾炬帴澶辫触锛�"+path);
+            }
+            portHandler.sendEmptyMessageDelayed(5,1500);
+            return;
+        }
+        portHandler.sendEmptyMessageDelayed(0,0);
+    }
+
+    private void send485(int type,String code){
+        runOnUiThread(new Runnable() {
+            @Override
+            public void run() {
+                getVM().addInfo("鍙戦�佹寚浠わ細"+StringUtil.DateToStrSS(new Date())+"==>"+code);
+            }
+        });
+        if(type==0){
+            if(gridPort!=null){
+                byte[] sendByte = SportUtils.hexToByteArray(code);
+                gridPort.write(sendByte);
+            }
+        }else if(type==1){
+            if(keyPort!=null){
+                byte[] sendByte = SportUtils.hexToByteArray(code);
+                keyPort.write(sendByte);
+            }
+        }else if(type==2){
+            if(jiuPort!=null){
+                byte[] sendByte =code.getBytes();
+                jiuPort.write(sendByte);
+            }
+        }else if(type==3){
+            if(chosePort!=null){
+                byte[] sendByte = SportUtils.hexToByteArray(code);
+                chosePort.write(sendByte);
+            }
+        }else if(type==4){
+            if(chosePort!=null){
+                byte[] sendByte =code.getBytes();
+                chosePort.write(sendByte);
+            }
+        }
+    }
+
+    private void closePort(SerialPortModel port){
+        try {
+            if(port==null){
+                return;
+            }
+            port.stopRead();
+            port.close();
+            port = null;
+        }catch (Exception e){
+
+        }
+    }
+
+    private boolean checkEnd(){
+        if(TextUtils.isEmpty(gridPath)){
+            getVM().addInfo("闂ㄩ敊璇�");
+            startIndex=0;
+            return false;
+        }
+        if(TextUtils.isEmpty(keyPath)){
+            getVM().addInfo("閽ュ寵閿欒");
+            startIndex=1;
+            return false;
+        }
+        if(TextUtils.isEmpty(jiuPath)){
+            getVM().addInfo("閰掔簿閿欒");
+            startIndex=2;
+            return false;
+        }
+        getVM().addInfo("涓插彛鍏ㄩ儴閾炬帴鎴愬姛锛�");
+        return true;
+    }
 }

--
Gitblit v1.9.3