package net.northking.cctp.upperComputer.deviceManager.thread;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import net.northking.cctp.upperComputer.deviceManager.AndroidDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import net.northking.cctp.upperComputer.driver.adb.Adb;
import net.northking.cctp.upperComputer.driver.adb.AdbDevice;
import net.northking.cctp.upperComputer.driver.adb.AdbTransport;
import net.northking.cctp.upperComputer.driver.agent.AndroidAgentSession;
import net.northking.cctp.upperComputer.driver.agent.command.WatchDisplayInfoCommand;
import net.northking.cctp.upperComputer.driver.agent.command.WatchWifiStateCommand;
import net.northking.cctp.upperComputer.driver.agent.command.data.DisplayData;
import net.northking.cctp.upperComputer.service.DeviceConnectionService;
import net.northking.cctp.upperComputer.utils.SpringUtils;
import net.northking.cctp.upperComputer.webSocket.thread.AndroidMessageHandlerThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 此类功能在于注册设备，启动手机上面的agent程序
 */
public class AndroidDeviceInitThread extends Thread {

    private final Logger logger = LoggerFactory.getLogger(AndroidDeviceInitThread.class);

    private final AdbDevice adbDevice;

    private final Adb adb;

    private AdbTransport transport;

    private AndroidAgentSession androidAgentSession;

    private LinkedHashMap<String, Object> deviceInfo;

    private boolean agentStatus = false;

    private final Object lock = new Object();

    private final String AGENT_START_SHELL = "export CLASSPATH=/data/local/tmp/agent.apk;app_process /system/bin net.northking.product.cctpplus.Agent";

    private final String AGENT_KIll_SHELL = "killall -9 cctp.agent";

    private boolean wifiStatus = false;

    private ArrayList<DisplayData> displayDataList;

    private AgentThread agentThread;

    private Integer forwardPort;

    private int time = 1;

    public AndroidDeviceInitThread(Adb adb, AdbDevice adbDevice, Integer forwardPort) {
        this.adb = adb;
        this.adbDevice = adbDevice;
        this.forwardPort = forwardPort;
        setName(adbDevice.getSerial());
    }

    @Override
    public void run() {
        while (!isInterrupted() && time <= 5) {  //5次启动不好，重启设备
            //启动agent代理
            startDeviceAgent();
            synchronized (lock) {
                try {
                    logger.info("等待设备【{}】agent程序启动.................", adbDevice.getSerial());
                    lock.wait(60000);
                } catch (InterruptedException e) {
                    break;
                }
            }
            logger.info("设备【{}】agent环境准备结果为：{}。。。。。。。。。。。。", adbDevice.getSerial(), agentStatus);
            if (agentStatus) {
                try {
                    deviceInfo = getDeviceInfo();
                        logger.info("设备【{}】agent启动成功，注册设备到服务端，并开始监听设备的屏幕和wifi。。。。。。。。。。。。", adbDevice.getSerial());
                        //注册设备
                        AndroidDeviceManager.getInstance().registerDeviceToDeviceManager(deviceInfo);
                        //清除计时器
                        time = 1;
                        //发布agent已经准备好的消息
                        AndroidDeviceManager.getInstance().publishDeviceAgentAlready(adbDevice.getSerial());
                        //开启监听设备的变化
                        startWatchDeviceChange();
                } catch (IOException e) {
                    logger.warn("读取手机信息失败，请观察手机是否接上上位机", e);
                }
            } else {
               logger.warn("设备【{}】agent启动不成功，干掉重来.....",adbDevice.getSerial());
                adb.shell(adbDevice, AGENT_KIll_SHELL);
            }
            AndroidDeviceManager.getInstance().publishDeviceAgentDead(adbDevice.getSerial());
            time++;
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                break;
            }
        }
        if (time > 5) {
            logger.warn("设备【{}】启动agent5次没成功过，可能是设备卡死了，关机重启一下设备....................",adbDevice.getSerial());
            adb.shell(adbDevice, "reboot");
        }
        logger.warn("设备【{}】的初始化线程退出，设备下线................................", adbDevice.getSerial());
    }

    private void startWatchDeviceChange() {
        androidAgentSession = new AndroidAgentSession(adbDevice, true);
        try {
            androidAgentSession.start();
        } catch (IOException e) {
            logger.error("设备[{}]的androidAgentSession开启失败", adbDevice.getSerial(), e);
            androidAgentSession = null;
            AndroidDeviceManager.getInstance().offlineDeviceFromDeviceManager(adbDevice.getSerial());
            return;
        }
        logger.debug("开始监听wifi状态。。。。。。。。");
        androidAgentSession.send(WatchWifiStateCommand.getInstance());
        logger.debug("开始监听屏幕的参数。。。。。。。。");
        androidAgentSession.send(WatchDisplayInfoCommand.getInstance());
        DataInput dataInput = androidAgentSession.getDataInput();
        while (!isInterrupted()) {
            try {
                int commandId = dataInput.readInt();
                if (commandId == WatchWifiStateCommand.getInstance().getCommandId()) {
                    Boolean isOpen = WatchWifiStateCommand.getInstance().buildReceive(dataInput);
                    if (isOpen != wifiStatus) {
                        wifiStatus = isOpen;
                        deviceInfo.put("wifiStatus", isOpen);
                        AndroidDeviceManager.getInstance().registerDeviceToDeviceManager(deviceInfo);
                        Map<String, Object> data = new HashMap<>();
                        data.put("wifiStatus", wifiStatus);
                        sendMessageToConnection(data, "wifi");
                    }
                } else if (commandId == WatchDisplayInfoCommand.getInstance().getCommandId()) {
                    ArrayList<DisplayData> screenDataList = WatchDisplayInfoCommand.getInstance().buildReceive(dataInput);
                    if (!CollectionUtils.isEmpty(screenDataList)) {
                        logger.debug("收到屏幕数据：{}", JSON.toJSONString(screenDataList));
                        boolean changed = checkScreenChanged(screenDataList);
                        if (changed) {
                            displayDataList = screenDataList;
                            deviceInfo.put("display", screenDataList);
                            //todo:先做一块屏幕的
                            DisplayData screenData = screenDataList.get(0);
                            deviceInfo.put("rotation", screenData.getRotation());
                            AndroidDeviceManager.getInstance().registerDeviceToDeviceManager(deviceInfo);
                            Map<String, Object> data = new HashMap<>();
                            data.put("rotation", screenData.getRotation());
                            data.put("realWidth", screenData.getWidth());
                            data.put("realHeight", screenData.getHeight());
                            data.put("scale", 1.0);
                            sendMessageToConnection(data, "rotation");
                        }
                    }
                }
            } catch (IOException e) {
                logger.warn("设备【{}】读取监控屏幕和wifi的agentSession输出出错", adbDevice.getSerial(), e);
                break;
            }
        }
        if (null != androidAgentSession) {
            androidAgentSession.closeSilence();
            androidAgentSession = null;
            AndroidDeviceManager.getInstance().offlineDeviceFromDeviceManager(adbDevice.getSerial());
        }
        logger.debug("设备[{}]监控屏幕和wifi的agentSession挂了。。。。。。。。。。。。。。。。。", adbDevice.getSerial());
    }

    /**
     * 对比手机得屏幕是否发生改变
     *
     * @param screenDataList
     * @return
     */
    private boolean checkScreenChanged(ArrayList<DisplayData> screenDataList) {
        if (null == displayDataList) {
            return true;
        } else {
            for (DisplayData displayData : displayDataList) {
                for (DisplayData data : screenDataList) {
                    if (displayData.getId() == data.getId()) {  //同一块屏幕
                        if (displayData.getRotation() != data.getRotation() || displayData.getHeight() != data.getHeight()
                                || displayData.getWidth() != data.getWidth() || displayData.getDensity() != data.getDensity()
                                || displayData.getDensityDpi() != data.getDensityDpi() || displayData.getFlag() != data.getFlag()
                                || displayData.getRefreshRate() != data.getRefreshRate() || displayData.getXdpi() != data.getXdpi()
                                || displayData.getYdpi() != data.getYdpi()) {
                            return true;
                        }
                        break;
                    }
                }
            }
        }
        return false;
    }

    private void sendMessageToConnection(Map<String, Object> data, String type) {
        AndroidMessageHandlerThread handleMessageThread = (AndroidMessageHandlerThread) SpringUtils.getBean(DeviceConnectionService.class).getHandleMessageThread(adbDevice.getSerial());
        if (null != handleMessageThread) {
            if ("rotation".equals(type)) {
                logger.debug("发送设备【{}】的屏幕方向到前端。。。。。。。。。。。", adbDevice.getSerial());
                handleMessageThread.sendScreenChange(data);
            } else if ("wifi".equals(type)) {
                logger.debug("发送设备【{}】的的wifi状态到前端。。。。。。。。。。。", adbDevice.getSerial());
                handleMessageThread.sendWifiChange(data);
            }
        } else {
            logger.debug("该设备处于未处于连接状态，就不发给前端了。。。。。。。。。。。");
        }
    }

    /**
     * 启动agent代理程序
     */
    private void startDeviceAgent() {
        this.agentThread = new AgentThread();
        this.agentThread.start();
    }

    /**
     * 获取设备信息
     *
     * @return
     * @throws IOException
     */
    private LinkedHashMap<String, Object> getDeviceInfo() throws IOException {
        LinkedHashMap<String, Object> deviceInfo = new LinkedHashMap<>();
        //region soc平台
        AdbTransport getPropTransport = adb.shell(adbDevice, "getprop");
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(getPropTransport.getInputStream()));
        Map<String, String> deviceProperties = new HashMap<String, String>();
        while ((line = reader.readLine()) != null) {
            String[] split = line.split(": ");
            if (split.length == 2) {
                String key = split[0].substring(1, split[0].length() - 1);
                String value = split[1].substring(1, split[1].length() - 1);
                deviceProperties.put(key, value);
            }
        }
        getPropTransport.close();

        //endregion

        //region CPU核心数
        int cpuCoreNum = 0;
        AdbTransport cpuInfoTransport = adb.shell(adbDevice, "cat /proc/cpuinfo");
        reader = new BufferedReader(new InputStreamReader(cpuInfoTransport.getInputStream()));
        while ((line = reader.readLine()) != null) {
            if (line.contains("processor")) {
                cpuCoreNum++;
            }
        }
        cpuInfoTransport.close();
        deviceInfo.put("cpuCores", cpuCoreNum);
        deviceInfo.put("cpuPlatform", deviceProperties.getOrDefault("ro.board.platform", "unknown"));
        //region 品牌
        deviceInfo.put("manufacturer", deviceProperties.getOrDefault("ro.product.manufacturer", "unknown"));
        //region 型号
        deviceInfo.put("model", deviceProperties.getOrDefault("ro.product.model", "unknown"));
        //region 平台
        deviceInfo.put("platform", "android");
        //region 产品
        deviceInfo.put("product", deviceProperties.getOrDefault("ro.product.name", "unknown"));
        //region 设备号
        deviceInfo.put("serial", adbDevice.getSerial());
        //region 平台版本
        deviceInfo.put("version", deviceProperties.getOrDefault("ro.build.version.release", "unknown"));
        //region sdk
        deviceInfo.put("sdk", deviceProperties.getOrDefault("ro.build.version.sdk", "unknown"));
        //region cpu名称 仅华为有
        deviceInfo.put("cpuName", deviceProperties.getOrDefault("ro.config.cpu_info_display", "unknown"));
        //region 屏幕尺寸
        AdbTransport screenSizeTransport = adb.shell(adbDevice, "wm size");
        reader = new BufferedReader(new InputStreamReader(screenSizeTransport.getInputStream()));
        int screenWidth = 0;
        int screenHeight = 0;
        while ((line = reader.readLine()) != null) {
            //针对鸿蒙3获取分辨率做适配
            if (line.startsWith("Override size:")) {
                String text = line.substring(15).trim();
                if (text.contains("x")) {
                    String[] data = text.split("x");
                    try {
                        screenWidth = Integer.parseInt(data[0]);
                        screenHeight = Integer.parseInt(data[1]);
                        break;
                    } catch (NumberFormatException ignored) {

                    }
                }
            }
            if (line.startsWith("Physical size:")) {
                String text = line.substring(15).trim();
                if (text.contains("x")) {
                    String[] data = text.split("x");
                    try {
                        screenWidth = Integer.parseInt(data[0]);
                        screenHeight = Integer.parseInt(data[1]);
                    } catch (NumberFormatException ignored) {

                    }
                }
            }
        }
        screenSizeTransport.close();
        deviceInfo.put("width", screenWidth);
        deviceInfo.put("height", screenHeight);
        //region 屏幕物理尺寸
        AdbTransport dpiTransport = adb.shell(adbDevice, "wm density reset"); //此值可自定义修改，重置一次
        dpiTransport.close();
        dpiTransport = adb.shell(adbDevice, "wm density");
        reader = new BufferedReader(new InputStreamReader(dpiTransport.getInputStream()));
        double dpi = 0d;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("Physical density:")) {
                String text = line.substring(18);
                try {
                    dpi = Double.parseDouble(text);
                } catch (NumberFormatException ignored) {

                }
            }
        }
        dpiTransport.close();
        double screenSize = Math.sqrt(screenWidth * screenWidth + screenHeight * screenHeight) / dpi;
        deviceInfo.put("size", screenSize);
        //region 是否鸿蒙
        boolean isHarmony = false;
        AdbTransport packageTransport = adb.shell(adbDevice, "pm list package com.huawei.harmonyos.foundation");
        reader = new BufferedReader(new InputStreamReader(packageTransport.getInputStream()));
        while ((line = reader.readLine()) != null) {
            if (line.contains("com.huawei.harmonyos.foundation")) {
                isHarmony = true;
            }
        }
        packageTransport.close();
        deviceInfo.put("isHarmony", isHarmony);
        //region 运行内存
        long memorySize = 0L; //单位：byte
        AdbTransport memoryInfoTransport = adb.shell(adbDevice, "cat /proc/meminfo");
        reader = new BufferedReader(new InputStreamReader(memoryInfoTransport.getInputStream()));
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("MemTotal:")) {
                String[] data = line.split("\\s+");
                if (data.length == 3) {
                    memorySize = Long.parseLong(data[1]) / 1024;
                }
            }
        }
        memoryInfoTransport.close();
        deviceInfo.put("ram", memorySize);
        //region 储存空间 以/data这个用户可使用空间为准
        long dataSize = 0L;//单位 byte
        AdbTransport dataSizeTransport = adb.shell(adbDevice, "df -k /data");
        reader = new BufferedReader(new InputStreamReader(dataSizeTransport.getInputStream()));
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("/dev")) {
                String[] data = line.split("\\s+");
                if (data.length >= 3) {
                    try {
                        dataSize = Long.parseLong(data[1]) / 1024;
                        break;
                    } catch (NumberFormatException ignored) {

                    }
                }
            }
        }
        dataSizeTransport.close();
        deviceInfo.put("rom", dataSize);
        //屏幕方向
        Integer rotation = 0;
        AdbTransport rotationTransport = adb.shell(adbDevice, "settings get system user_rotation");
        reader = new BufferedReader(new InputStreamReader(rotationTransport.getInputStream()));
        while ((line = reader.readLine()) != null) {
//            if ("cmd: Can't find service: settings".equals(line)) {  //系统崩掉之后setting服务无法使用
//                if (AndroidDeviceManager.getInstance().getDeviceSystemStatus(adbDevice.getSerial())) {
//                    logger.error("设备【{}】中setting服务无法访问，重启设备", adbDevice.getSerial());
//                    AdbTransport reboot = adb.shell(adbDevice, "reboot");
//                    reboot.close();
//                    AndroidDeviceManager.getInstance().setDeviceSystemStatus(adbDevice.getSerial(),false);
//                    return null;
//                } else {
//                    logger.warn("设备【{}】正在重启，请稍后..................", adbDevice.getSerial());
//                    return null;
//                }
//            }
            try {
                rotation = Integer.parseInt(line);
            } catch (NumberFormatException e) {
                logger.warn("屏幕方向数据有误，得到数据为：{}", line, e);
            }
        }
        rotationTransport.close();
        deviceInfo.put("rotation", rotation);
        AdbTransport wifiTransport = adb.shell(adbDevice, "cmd wifi status");
        reader = new BufferedReader(new InputStreamReader(wifiTransport.getInputStream()));
        while ((line = reader.readLine()) != null) {
            if (line.contains("Wifi is enabled")) {
                wifiStatus = true;
                break;
            } else if (line.contains("Wifi is disabled")) {
                wifiStatus = false;
                break;
            }
        }
        wifiTransport.close();
        deviceInfo.put("wifiStatus", wifiStatus);
        deviceInfo.put("scale", 1.0);
        deviceInfo.put("forwardPort", forwardPort);
        return deviceInfo;
    }

    public void exit() {
        if (null != agentThread) {
            agentThread.exitAgent();
        }
        this.interrupt();
    }

    public Map<String, Integer> getRealScreenSize() {
        if (null != displayDataList) {
            DisplayData displayData = displayDataList.get(0);
            Map<String, Integer> sizeMap = new HashMap<>();
            sizeMap.put("width", displayData.getWidth());
            sizeMap.put("height", displayData.getHeight());
            sizeMap.put("rotation", displayData.getRotation());
            return sizeMap;
        }
        return null;
    }

    public AdbDevice getAdbDevice() {
        return adbDevice;
    }

    public boolean isAgentStatus() {
        return agentStatus;
    }

    public Integer getForwardPort(){
        return forwardPort;
    }

    private class AgentThread extends Thread {

        @Override
        public void run() {
            try {
                File agentFile = new File(UpperComputerManager.getInstance().getApplicationPath() + "/agent.apk");
                FileInputStream agentFileInputStream = new FileInputStream(agentFile);
                boolean push = adb.push(adbDevice, agentFileInputStream, Integer.parseInt(agentFile.lastModified() / 1000 + ""), 777, "/data/local/tmp/agent.apk", null);
                if (push) {
                    logger.info("agent.apk推送成功！");
                } else {
                    logger.warn("agent.apk推送失败！");
                }
            } catch (FileNotFoundException e) {
                logger.warn("文件【{}】不存在", UpperComputerManager.getInstance().getApplicationPath() + "/agent.apk", e);
            }
            try {
                File agentFile = new File(UpperComputerManager.getInstance().getApplicationPath() + "/cctp.apk");
                FileInputStream agentFileInputStream = new FileInputStream(agentFile);
                boolean push = adb.push(adbDevice, agentFileInputStream, Integer.parseInt(agentFile.lastModified() / 1000 + ""), 777, "/data/local/tmp/cctp.apk", null);
                if (push) {
                    logger.info("cctp.apk推送成功！");
                } else {
                    logger.warn("cctp.apk推送失败！");
                }
            } catch (FileNotFoundException e) {
                logger.warn("文件【{}】不存在", UpperComputerManager.getInstance().getApplicationPath() + "/cctp.apk", e);
            }
            boolean keepScreenOn = Boolean.parseBoolean(SpringUtil.getProperty("nk.mobile-computer.keepScreenOn"));
            String agentStartShell = AGENT_START_SHELL;
            if (keepScreenOn) {
                agentStartShell = agentStartShell + " --keep-screen-on";
            }
            transport = adb.shell(adbDevice, agentStartShell);
            BufferedReader reader = null;
            File dir = new File(UpperComputerManager.getInstance().getApplicationPath() + "/agentLog/");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
            String format = simpleDateFormat.format(new Date());
            File agentFile = new File(dir.getAbsolutePath() + "/" + adbDevice.getSerial().replaceAll(":", ".") + "_" +format+ "_agent.log");
            FileWriter fileWriter = null;
            BufferedWriter writer = null;
            try {
                //agent日志由覆盖改为追加
                fileWriter = new FileWriter(agentFile, true);
                writer = new BufferedWriter(fileWriter);
                //增加当前时刻输入
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                writer.write(sdf.format(new Date()));
                writer.newLine();
                writer.flush();
            } catch (IOException e) {
                logger.warn("agent日志写入失败。。。。。。。");
            }
            try {
                reader = new BufferedReader(new InputStreamReader(transport.getInputStream()));
                String line;
                int n = 0;
                while ((line = reader.readLine()) != null) {
                    if (writer != null) {
                        writer.write(line);
                        writer.newLine();
                        writer.flush();
                    }
                    if ("SERVICE_APK_INSTALLED".equals(line)) {
                        logger.info("设备【{}】cctp程序安装成功。。。。。。", adbDevice.getSerial());
                        n++;
                    }
                    if ("预准备的CCTPService版本与已安装的相同，跳过安装".equals(line)) {
                        logger.info("设备【{}】cctp程序已经存在，无需安装。。。。。。", adbDevice.getSerial());
                        n++;
                    }
                    if ("SERVICE_APK_INSTALL_FAILED".equals(line)) {
                        logger.info("设备【{}】agent程序安装失败。。。。。。", adbDevice.getSerial());
                        agentStatus = false;
                        synchronized (lock) {  //唤醒外面线程继续执行
                            lock.notify();
                        }
                        break;
                    }
                    if ("UNIX_SOCKET_READY".equals(line)) {
                        logger.info("设备【{}】agent程序Socket服务已启动，等待Agent Session。。。。。。", adbDevice.getSerial());
                        n++;
                    }
                    if ("MAIN_OK".equals(line)) {
                        logger.info("设备【{}】agent程序启动完成............", adbDevice.getSerial());
                        n++;
                    }
                    if ("SYSTEM_DEAD".equals(line)) {
                        logger.info("设备【{}】系统崩了一次，重新启动一下agent...........", adbDevice.getSerial());
                        adb.shell(adbDevice, AGENT_KIll_SHELL);
                        agentStatus = false;
                        synchronized (lock) {  //唤醒外面线程继续执行
                            lock.notify();
                        }
                        break;
                    }
                    if ("SYSTEM_READY".equals(line)) {
                        logger.info("设备【{}】系统准备好，开始启动agent...........", adbDevice.getSerial());
                    }
                    if ("SYSTEM_UNAVAILABLE".equals(line)) {
                        logger.info("设备【{}】的系统还未准备好，等待...........", adbDevice.getSerial());
                    }
                    if (n == 3) {
                        n++;
                        agentStatus = true;
                        AndroidDeviceManager.getInstance().setDeviceSystemStatus(adbDevice.getSerial(), true);
                        synchronized (lock) {  //唤醒外面线程继续执行
                            lock.notify();
                        }
                    }
                }
                agentStatus = false;
                logger.info("设备【{}】agent程序已经退出...........", adbDevice.getSerial());
                if (n != 4) {   //非正常退出agent程序
                    synchronized (lock) {  //唤醒外面线程继续执行
                        lock.notify();
                    }
                }
            } catch (IOException e) {
                logger.warn("设备【{}】的agent被G掉了。。。。。。。。", adbDevice.getSerial(), e);
                agentStatus = false;
            } finally {
                //通常Agent退出都为意外情况
                if (writer!=null){
                    adb.refreshState(adbDevice);
                    try (AdbTransport logcatTransport = adb.shell(adbDevice, "logcat -d")) {
                        if (logcatTransport!=null){
                            writer.write("\nAgent退出，以下为转储logcat日志\n");
                            BufferedReader logcatReader = new BufferedReader(new InputStreamReader(logcatTransport.getInputStream()));
                            String logcatLine;
                            while ((logcatLine = logcatReader.readLine()) != null) {
                                writer.write(logcatLine);
                                writer.newLine();
                            }
                            writer.write("以上为转储logcat日志\n");
                            writer.flush();
                        }

                    } catch (Exception ignored) {

                    }
                }
                if (null != reader) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != writer) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != fileWriter) {
                    try {
                        fileWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != transport) {
                    try {
                        logger.debug("退出设备【{}】的agent程序,关闭资源", adbDevice.getSerial());
                        transport.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public void exitAgent() {
            adb.shell(adbDevice, AGENT_KIll_SHELL);
            agentStatus = false;
        }
    }
}

