package com.siwei.recyclebox.ui.main;

import android.Manifest;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.databinding.ObservableField;
import android.hardware.usb.UsbManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.dm.api.IOta;
import com.aliyun.alink.linkkit.api.LinkKit;
import com.aliyun.alink.linksdk.cmp.connect.channel.MqttPublishRequest;
import com.aliyun.alink.linksdk.cmp.connect.channel.MqttSubscribeRequest;
import com.aliyun.alink.linksdk.cmp.core.base.AMessage;
import com.aliyun.alink.linksdk.cmp.core.base.ARequest;
import com.aliyun.alink.linksdk.cmp.core.base.AResponse;
import com.aliyun.alink.linksdk.cmp.core.base.ConnectState;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectNotifyListener;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectSendListener;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectSubscribeListener;
import com.aliyun.alink.linksdk.tmp.api.OutputParams;
import com.aliyun.alink.linksdk.tmp.device.payload.ValueWrapper;
import com.aliyun.alink.linksdk.tmp.listener.IPublishResourceListener;
import com.aliyun.alink.linksdk.tools.AError;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.siwei.recyclebox.BuildConfig;
import com.siwei.recyclebox.deviceUtils.SerialPortUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import top.maybesix.xhlibrary.serialport.ComPortData;
import top.maybesix.xhlibrary.serialport.SerialPortHelper;
import top.maybesix.xhlibrary.util.HexStringUtils;

import com.siwei.recyclebox.utils.DemoOne;
import com.siwei.recyclebox.utils.SilentInstall;
import com.siwei.recyclebox.utils.unZipFileDemo;

import static android.content.Context.BATTERY_SERVICE;
import static java.lang.Thread.sleep;

public class MainViewModel extends BaseViewModel implements SerialPortHelper.OnSerialPortReceivedListener {

    Integer lockSwitch = 0;//锁的状态
    private static Context context;//上下文
    private final Timer timer = new Timer();
    private TimerTask task1;
    private TimerTask task2;
    private TimerTask task3;

    //    private LocationUtils mLocationUtils;//定位,现在不需要定位
//    private MapLocationInfo mMapLocationInfo;
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onCreate() {
        super.onCreate();
 /*       mLocationUtils = LocationUtils.getInstance();
        Log.i(TAG,"定位--------------------");
        mLocationUtils.startLocationInfo();
        mLocationUtils.onCreate(new LocationUtils.LocationListener() {
            @Override
            public void locationSuccess(MapLocationInfo mapLocationInfo, String message) {
                mMapLocationInfo = mapLocationInfo;
                Log.i("定位： ","" + message);
                Log.i(TAG,"定位ok");
                Log.i(TAG,mMapLocationInfo.toString());
                Log.i(TAG,"纬度"+mMapLocationInfo.getLatitude()+"经度"+mMapLocationInfo.getLongitude());
            }
            @Override
            public void locationFail(String message) {
                Log.i("定位： ","" + message);
            }
        });
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mLocationUtils.stopLocationClient();
            }
        },5000);*/
        MainViewModel.context = getApplication();
        SPUtils.getInstance().put("RunningState", 0);//设备运行状态
        SPUtils.getInstance().put("magDoorSwitch", 0);//门磁状态
        Integer networkNum = netWorkInfoStatic();
        SPUtils.getInstance().put("netWork", networkNum);//网络状态
        /*BatteryManager batteryManager = (BatteryManager)getSystemService(BATTERY_SERVICE);//电量管理
        int battery = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);//查询电量值
        Log.i(TAG,"电量值="+battery);//现在的直接接电源，不需要判断电量值，开发太阳能板可以用到
        */

        if (SPUtils.getInstance().getInt("TaskSwitch") == 1) {//判断是否已经开始了任务循环，避免多次开启；在application设的1
            repeatTask();
        }
        SPUtils.getInstance().put("TaskSwitch", 0);

    }

    private MediaPlayer mMediaPlay = null;
    public ObservableField<String> textReadWeightData = new ObservableField<>();//称重数据显示
    public ObservableField<String> textReportData = new ObservableField<>();//上报数据显示
    public ObservableField<String> textIMEI = new ObservableField<>();//imei显示
    public ObservableField<String> textqueryCurrentData = new ObservableField<>();//电流过大查询显示


    /*
     * 按钮模拟指令
     * */
    //查询电流过大值
    public View.OnClickListener btnClickqueryCurrent = view -> {
//        System.out.println("btnClickqueryCurrent");
        Integer queryCurrentData = SerialPortUtil.getInstance().getOtherDevice().queryCurrent();
        textqueryCurrentData.set(String.valueOf(queryCurrentData));
    };
    //清除电流过大查询值
    public View.OnClickListener btnClickclearCurrent = view -> {
//        System.out.println("btnClickclearCurrent");
        SerialPortUtil.getInstance().getOtherDevice().clearCurrent();
    };
    //查询电流值
    public View.OnClickListener btnClickQueryPower = view -> {
//        System.out.println("read response");
        SerialPortUtil.getInstance().getOtherDevice().queryPower();
    };

    public View.OnClickListener btnClickSpeech = new View.OnClickListener() {
        //播放音频
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        AssetFileDescriptor fd = getApplication().getAssets().openFd("onPushRod.mp3");
                        mMediaPlay = new MediaPlayer();
                        mMediaPlay.reset();
                        mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                        mMediaPlay.prepare();
                        Log.i(TAG, "播放音频");
                        mMediaPlay.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    };

    int a = 2;//判断点击奇偶数
    public View.OnClickListener btnClickOpenLight1234 = new View.OnClickListener() {
        //打开关闭灯4按钮 开灯1
        @Override
        public void onClick(View view) {
            if (a % 2 == 0) {
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLight1();
                    SerialPortUtil.getInstance().getOtherDevice().openLight2();
                    SerialPortUtil.getInstance().getOtherDevice().openLight3();
                    SerialPortUtil.getInstance().getOtherDevice().openLight4();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    SerialPortUtil.getInstance().getOtherDevice().closeLight1();
                    SerialPortUtil.getInstance().getOtherDevice().closeLight2();
                    SerialPortUtil.getInstance().getOtherDevice().closeLight3();
                    SerialPortUtil.getInstance().getOtherDevice().closeLight4();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            a++;
        }
    };
    //打开关闭灯4按钮
    public View.OnClickListener btnClickOpenLight4 = view -> {
        if (a % 2 == 0) {
            SerialPortUtil.getInstance().getOtherDevice().openLight4();
        } else {
            SerialPortUtil.getInstance().getOtherDevice().closeLight4();
        }
        a++;
    };
    //打开关闭灯3按钮
    public View.OnClickListener btnClickOpenLight3 = view -> {
        if (a % 2 == 0) {
            SerialPortUtil.getInstance().getOtherDevice().openLight3();
        } else {
            SerialPortUtil.getInstance().getOtherDevice().closeLight3();
        }
        a++;
    };
    //打开关闭灯2按钮
    public View.OnClickListener btnClickOpenLight2 = view -> {
        if (a % 2 == 0) {
            SerialPortUtil.getInstance().getOtherDevice().openLight2();
        } else {
            SerialPortUtil.getInstance().getOtherDevice().closeLight2();
        }
        a++;
    };
    //打开关闭灯1按钮
    public View.OnClickListener btnClickOpenLight1 = view -> {
        if (a % 2 == 0) {
            SerialPortUtil.getInstance().getOtherDevice().openLight1();
        } else {
            SerialPortUtil.getInstance().getOtherDevice().closeLight1();
        }
        a++;
    };
    //设置更大的电流值
    public View.OnClickListener btnClickSetPowerBigger = view -> SerialPortUtil.getInstance().getOtherDevice().setPowerBigger();

    //上报事件测试
    public View.OnClickListener btnClickSendMsg = view -> {
        SendSmsResponse("温度超声波失灵");//下面写了，超股20次发送超声波失灵才上报，因为超声波问题不重要，每次都上报就浪费资源
        SendSmsResponse("温度超声波失灵");
        SendSmsResponse("温度超声波失灵");
        SendSmsResponse("温度超声波失灵");
        reportDeviceEvent("commoneEvent", "open", 3);
    };
    //获取属性
    public View.OnClickListener btnClickGetDeviceValue = view -> {
//            getDeviceProperty("1");//目前没用用到此方法。此方法是获取阿里云上的属性值，具体参数自行修改
    };
    //称重查询
    public View.OnClickListener btnClickreadWeight = view -> {
//        System.out.println("btnClickreadWeight");
//            Integer weightData=SerialPortUtil.getInstance().getOtherDevice().readWeight();
        Integer weightData = SerialPortUtil.getInstance().getWeightDevice().readWeight();
        textReadWeightData.set(weightData + "g");
    };
    public View.OnClickListener btnClicksetScale = new View.OnClickListener() {
        //设置称重刻度值
        @Override
        public void onClick(View view) {
//            System.out.println("btnClicksetScale");
//            SerialPortUtil.getInstance().getOtherDevice().weightSet();
            SerialPortUtil.getInstance().getWeightDevice().weightSet();
//            SerialPortUtil.getInstance().getOtherDevice().setScale();
            mHandler.postDelayed(() -> SerialPortUtil.getInstance().getWeightDevice().setScale(), 1000);
        }
    };
    //称重去皮清零
    public View.OnClickListener btnClickclearWeight = view -> {
//        System.out.println("btnClickclearWeight");
//            SerialPortUtil.getInstance().getOtherDevice().weightClear();
        SerialPortUtil.getInstance().getWeightDevice().weightClear();
    };
    //称重砝码校准
    public View.OnClickListener btnClickweightCalibration = view -> {
//        System.out.println("btnClickweightCalibration");
//            SerialPortUtil.getInstance().getOtherDevice().weightCalibration();
        SerialPortUtil.getInstance().getWeightDevice().weightCalibration();
    };
    //称重空载
    public View.OnClickListener btnClickzeroCalibration = view -> {
//            System.out.println("btnClickzeroCalibration");
//           SerialPortUtil.getInstance().getOtherDevice().zeroCalibration();
        SerialPortUtil.getInstance().getWeightDevice().zeroCalibration();
    };
    //重启app
    public View.OnClickListener btnClickrestartApp = view -> {
//            System.out.println("btnClickrestartApp");
        restartApp();//重启方法
    };
    //重启
    public View.OnClickListener btnClickrestartAndroid = view -> {
        restartAndroid();//重启系统
    };
    //关闭app
    public View.OnClickListener btnClickfinishApp = view -> {
//        System.out.println("btnClickfinishApp");
        System.exit(0);
    };
    //数据上报
    public View.OnClickListener btnClickReport = view -> {
//        System.out.println("btnClickReport");
        reportProperty();
    };
    public View.OnClickListener btnQeryIMEI = new View.OnClickListener() {
        //查询IMEI，IMEI是唯一值，阿里云添加设备就是用IMEI命名的
        @Override
        public void onClick(View view) {
            textIMEI.set("IMEI==" + IMEI);
            Log.i("imei", IMEI);
        }
    };
    public View.OnClickListener btnClickPushRod = new View.OnClickListener() {
        //关门推杆
        @Override
        public void onClick(View view) {
//            System.out.println("btnClickPushRod");
            pushRodMethodNonet();
        }
    };
    public View.OnClickListener btnClickPullRod = new View.OnClickListener() {
        //开门拉杆
        @Override
        public void onClick(View view) {
//            System.out.println("btnClickPullRod");
            pullRodMethod();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    int numInt = 0;
                    long curr = System.currentTimeMillis();
                    while (System.currentTimeMillis() - curr < 89000) {//规定时间内没关门就自动关门
                        try {
                            sleep(1000);
                            numInt++;
//                            Log.i(TAG,numInt+"秒");
                            if (SPUtils.getInstance().getString("RodSwitch").equals("0")) {//判断是否已经关门
                                break;
                            }
                            if (numInt == 82) {//82秒后关门
                                pushRodMethodNonet();
                                break;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            });
            thread.start();
        }
    };

    int stopValue = 0;

    public void repeatRod() {
        Thread thread = new Thread(() -> {
            //循环开门推拉杆
            stopValue = 1;
            SerialPortUtil.getInstance().getOtherDevice().pullRod();
            mHandler.postDelayed(() -> SerialPortUtil.getInstance().getOtherDevice().pushRod(), 60000);
            mHandler.postDelayed(() -> repeatRod(), 120000);
        });
        thread.start();
    }

    ;
    int stopValue2 = 0;

    public void repeatLock() {
        Thread thread = new Thread(() -> {
            //循环开关锁
            stopValue2 = 1;
            SerialPortUtil.getInstance().getOtherDevice().openLock();
            mHandler.postDelayed(() -> SerialPortUtil.getInstance().getOtherDevice().closeLock(), 7000);
            mHandler.postDelayed(() -> repeatLock(), 40000);
        });
        thread.start();
    }

    ;
    public View.OnClickListener btnClickRodRepeat = new View.OnClickListener() {
        //循环开门按钮
        @Override
        public void onClick(View view) {
//            System.out.println("btnClickRodRepeat");
            if (stopValue == 0) {
                repeatRod();
            }
        }
    };
    //循环开锁按钮
    public View.OnClickListener btnClickLockRepeat = view -> {
//        System.out.println("btnClickRodRepeat");
        if (stopValue2 == 0) {
            repeatLock();
        }
    };
    public View.OnClickListener btnClickOpenLock = new View.OnClickListener() {
        //开锁按钮
        @Override
        public void onClick(View view) {
//            System.out.println("btnClickOpenLock");
            try {
                SerialPortUtil.getInstance().getOtherDevice().openLock();
                mHandler.postDelayed(() -> {
                    try {
                        AssetFileDescriptor fd = getApplication().getAssets().openFd("openLock.mp3");
                        mMediaPlay = new MediaPlayer();
                        mMediaPlay.reset();
                        mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                        mMediaPlay.prepare();
                        Log.i(TAG, "播放音频");
                        mMediaPlay.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }, 200);
                lockSwitch = 1;//解锁
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SerialPortUtil.getInstance().getOtherDevice().closeLock();
                        lockSwitch = 0;//关锁
                    }
                }, 7000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void pullRodMethod() {
        SerialPortUtil.getInstance().getOtherDevice().pullRod();
        mHandler.postDelayed(() -> {
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("nonetPullRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 100);
    }

    private void pullonNetRodMethod() {
        //有网开门
        SerialPortUtil.getInstance().getOtherDevice().pullRod();
        mHandler.postDelayed(() -> {
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("netPullRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 100);
    }

    private void pushRodMethod() {
        //有网下关门
        SerialPortUtil.getInstance().getOtherDevice().pushRod();//关门
        reportProperty();
        reportDeviceEvent("commoneEvent", "close", 3);
        mHandler.postDelayed(() -> {
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("onPushRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 200);
        mHandler.postDelayed(() -> {
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("onPushRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 4000);
        mHandler.postDelayed(() -> {
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("afterPushRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 13000);
        //关门过程中称重会有波动，暂时不上报
        mHandler.postDelayed(() -> {
            reportProperty();
        }, 4000);
    }

    public void onSerialPortDataReceived(ComPortData comPortData) {
        //处理接收的串口消息
        String s = HexStringUtils.byteArray2HexString(comPortData.getRecData());
//        Log.i(TAG, "onReceived: " + s);
    }
   /* private void avgWeight(){//循环读取称重，已经在weightDevice中写了，这里不用再去写了。而且在这里写，很容易造成阻塞，需要加锁
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i("avgWeight（）","---运行次数");
                int weight = 0;
                int[] arr=new int[5];
                int n;
                for(n=0;n<5;n++){
                        arr[n]=SerialPortUtil.getInstance().getWeightDevice().readWeight();
//                    try {
//                        sleep(200);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    arr[n]=n;
//                    Log.i("n=", String.valueOf(n));
//                arr[n]=SerialPortUtil.getInstance().getOtherDevice().readWeight();
//                    Log.i("weight=", String.valueOf(arr[n]));
                    weight=arr[n]+weight;
                    if(n==3){
                        Log.i("weight=", Arrays.toString(arr));
                        int dvalue1 = Math.abs(arr[3]-arr[2]);
                        int dvalue2 = Math.abs(arr[3]-arr[1]);
                        if(dvalue1<30&&dvalue2<30){
                            Log.i("weight n-1=", String.valueOf(arr[3]));
                            SPUtils.getInstance().put("avgWeight最后读数",arr[3]);
                        }else {
                            double v = weight / 5;
                            int avg = new Double(v).intValue();
                            Log.i("weight avg=", String.valueOf(avg));
                            SPUtils.getInstance().put("avgWeight平均数",avg);
                        }
                    }
                }
            }
        });
        thread.start();
    }*/


    private void pushRodMethodNonet() {
        //无网下关门，不会上报数据
        SerialPortUtil.getInstance().getOtherDevice().pushRod();//关门
        mHandler.postDelayed(() -> {
            Log.i(TAG, "关门中，谨防夹手");
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("onPushRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 200);
        mHandler.postDelayed(() -> {
            Log.i(TAG, "关门中，谨防夹手");
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("onPushRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 4000);
        mHandler.postDelayed(() -> {
            Log.i(TAG, "垃圾分类，人人有责");
            try {
                AssetFileDescriptor fd = getApplication().getAssets().openFd("afterPushRod.mp3");
                mMediaPlay = new MediaPlayer();
                mMediaPlay.reset();
                mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mMediaPlay.prepare();
                Log.i(TAG, "播放音频");
                mMediaPlay.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 13000);
    }

    public Handler mHandler = new Handler(msg -> {
        return true;
    });
    public String IMEI = getDeviceId(getApplication());

    private String TAG = "MainViewModel";
    /*
     * 接收物联网平台指令并执行
     * */
    private IConnectNotifyListener notifyListener = new IConnectNotifyListener() {
        //物联网平台发送指令，接收并且响应
        int closeTimeOver = 1;

        @Override
        public void onNotify(String connectId, String topic, AMessage aMessage) {
            System.out.println("收到云端下行的数据：connectId:" + connectId + "  topic :" + topic + "  aMessage data:" + aMessage.getData().getClass().getSimpleName());
            byte[] dataBytes = (byte[]) aMessage.getData();
            System.out.println(new String(dataBytes));
//            if (topic.endsWith("thing/event/property/post_reply")){ //推送设备属性的回包。
//            }
            if (topic.endsWith("thing/service/restartApp")) {
                restartApp();//重启app
            }
            if (topic.endsWith("thing/service/finishApp")) {
                System.exit(0);//关闭app
            }
            if (topic.endsWith("thing/service/restartAndroidSystem")) {
                restartAndroid();//重启系统
            }
            if (topic.endsWith("thing/service/RemoteOpen")) {//   云端开门的请求。
                if (SPUtils.getInstance().getInt("clearWight", 2) == 1) {
                    SerialPortUtil.getInstance().getWeightDevice().weightClear();//去皮清零
//                SerialPortUtil.getInstance().getOtherDevice().clearWeight();//去皮清零
                    SPUtils.getInstance().put("clearWight", 2);
                }
                pullonNetRodMethod();//开门
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reportProperty();//上报数据
                        reportDeviceEvent("commoneEvent", "open", 3);//开门回调
                    }
                }, 500);
                Log.i(TAG, "收到云端开门=============");
                Thread thread = new Thread(() -> {
                    int numInt = 0;
                    long curr = System.currentTimeMillis();
                    while (System.currentTimeMillis() - curr < 89000) {
                        try {
                            sleep(1000);
                            numInt++;
//                            Log.i("开门","开门"+numInt);
                            if (SPUtils.getInstance().getString("RodSwitch").equals("0")) {
                                break;//关门了就退出
                            }
                            if (numInt == 41) {
                                reportProperty();
                            }
                            if (numInt == 82) {
                                if (closeTimeOver == 1) {
                                    pushRodMethod();//82秒后关门
                                    closeTimeOver = 2;
                                }
                                break;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();
            }
            if (topic.endsWith("thing/service/RemoteClose")) {
                Log.i(TAG, "收到云端关门========================");
                if (closeTimeOver == 1) {
                    pushRodMethod();
                    closeTimeOver = 2;
                }
            }
            if (topic.endsWith("thing/service/RemoteAgentOpen")) {//开收运门
                Log.i(TAG, "收到云端开运收门");
                SPUtils.getInstance().put("magDoorSwitch", 1);
                SPUtils.getInstance().put("clearWight", 1);
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLock();
                    mHandler.postDelayed(() -> {
                        try {
                            AssetFileDescriptor fd = getApplication().getAssets().openFd("openLock.mp3");
                            mMediaPlay = new MediaPlayer();
                            mMediaPlay.reset();
                            mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                            mMediaPlay.prepare();
                            Log.i(TAG, "播放音频");
                            mMediaPlay.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }, 200);
                    lockSwitch = 1;
                    mHandler.postDelayed(() -> {
                        SerialPortUtil.getInstance().getOtherDevice().closeLock();
                        SerialPortUtil.getInstance().getWeightDevice().weightClear();//若关闭，称重清零
                        lockSwitch = 0;//关锁
                        Thread thread = new Thread(() -> {
                            try {
                                long curr = System.currentTimeMillis();
                                while (System.currentTimeMillis() - curr < 300000) {
                                    Thread.sleep(10000);
                                    Integer magDoorSwitch = SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//通过门磁感应判断收运门是否关闭
                                    if (magDoorSwitch == 0) {
                                        SerialPortUtil.getInstance().getWeightDevice().weightClear();//若关闭，称重清零
//                                                SerialPortUtil.getInstance().getOtherDevice().clearWeight();
                                        mHandler.postDelayed(() -> reportProperty(), 3000);
                                        SPUtils.getInstance().put("magDoorSwitch", 0);
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                        thread.start();
                    }, 7000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/RemoteAgentClose")) {//关收运门
                SPUtils.getInstance().put("magDoorSwitch", 0);
                SerialPortUtil.getInstance().getWeightDevice().weightClear();
//                                                SerialPortUtil.getInstance().getOtherDevice().clearWeight();
                reportProperty();
                mHandler.postDelayed(() -> reportProperty(), 3000);
            }
            if (topic.endsWith("thing/service/RemoteOpenPort2")) {//开继电器2号端口
                short i = 2;
                try {
                    SerialPortUtil.getInstance().getRelayControllerDevive().openOne(i);
                    SerialPortUtil.getInstance().getRelayControllerDevive().closeOne(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/RemoteOpenPort2")) {//开继电器3号端口
                short i = 3;
                try {
                    SerialPortUtil.getInstance().getRelayControllerDevive().openOne(i);
                    SerialPortUtil.getInstance().getRelayControllerDevive().closeOne(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/RemoteOpenPort2")) {//开继电器4号端口
                short i = 4;
                try {
                    SerialPortUtil.getInstance().getRelayControllerDevive().openOne(i);
                    SerialPortUtil.getInstance().getRelayControllerDevive().closeOne(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/OpenLight1")) {//开灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLight1();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/CloseLight1")) {//关灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().closeLight1();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/OpenLight2")) {//开灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLight2();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/CloseLight2")) {//关灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().closeLight2();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/OpenLight3")) {//开灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLight3();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/CloseLight3")) {//关灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().closeLight3();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/OpenLight4")) {//开灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLight4();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/CloseLight4")) {//关灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().closeLight4();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/OpenLight1234")) {//开灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().openLight1();
                    SerialPortUtil.getInstance().getOtherDevice().openLight2();
                    SerialPortUtil.getInstance().getOtherDevice().openLight3();
                    SerialPortUtil.getInstance().getOtherDevice().openLight4();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/CloseLight1234")) {//关灯
                try {
                    SerialPortUtil.getInstance().getOtherDevice().closeLight1();
                    SerialPortUtil.getInstance().getOtherDevice().closeLight2();
                    SerialPortUtil.getInstance().getOtherDevice().closeLight3();
                    SerialPortUtil.getInstance().getOtherDevice().closeLight4();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/RepeatRod")) {//循环推杆
                try {
                    repeatRod();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/RepeatLock")) {//循环开锁
                try {
                    repeatLock();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (topic.endsWith("thing/service/currentWeight")) {
                reportProperty();
                int weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();
//                int weight = SerialPortUtil.getInstance().getOtherDevice().readWeight();
                String pushDSata = weight + "";
                MqttPublishRequest publishRequest = new MqttPublishRequest();
                publishRequest.isRPC = false;
                publishRequest.topic = topic.replace("request", "response");
                String[] array = topic.split("/");
                String resId = array[3];
                publishRequest.msgId = resId;
                // TODO 用户根据实际情况填写 仅做参考
                publishRequest.payloadObj = "{\"id\":\"" + resId + "\", \"code\":\"200\"" + ",\"data\":{,\"weightNum\":" + weight + "} }";
//                publishRequest.payloadObj = "{\"weightNum\":"+weight+"}";
                LinkKit.getInstance().publish(publishRequest, new IConnectSendListener() {//Linkkit将设备接入阿里云平台 并管理控制
                    @Override
                    public void onResponse(ARequest aRequest, AResponse aResponse) {
                        System.out.println("onresponse.");
                    }

                    @Override
                    public void onFailure(ARequest aRequest, AError aError) {

                    }
                });
            }
            // 云端下行数据回调
            // connectId 连接类型 topic 下行 topic; aMessage 下行数据
            //String pushData = new String((byte[]) aMessage.data);
            // pushData 示例  {"method":"thing.service.test_service","id":"123374967","params":{"vv":60},"version":"1.0.0"}
            // method 服务类型； params 下推数据内容
        }

        @Override
        public boolean shouldHandle(String connectId, String topic) {
            Log.e("MainViewModel", "shouldHandler  connectId:" + connectId + "  topic:" + topic);
            if (topic.contains("property/set"))
                return false;
            // 选择是否不处理某个 topic 的下行数据
            // 如果不处理某个topic，则onNotify不会收到对应topic的下行数据
            return true; //TODO 根基实际情况设置
        }

        @Override
        public void onConnectStateChange(String connectId, ConnectState connectState) {
            System.out.println("onConnectStateChange  connectId:" + connectId + "  connectState:" + connectState);
            if (connectState == ConnectState.CONNECTED) {
//                reportProperty(1);
                int writePermission = ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (writePermission != PackageManager.PERMISSION_GRANTED) {
                    //未授权写权限。
                    requestFilePermissions.call();
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reportProperty();//重新连接后上报数据
                    }
                }, 3000);
                reportVersion();
                otaListener();
            }
            // 对应连接类型的连接状态变化回调，具体连接状态参考 SDK ConnectState
        }
    };
    public SingleLiveEvent<Boolean> requestFilePermissions = new SingleLiveEvent<>();

    public MainViewModel(@NonNull Application application) {
        super(application);
    }

    public MainViewModel(@NonNull Application application, BaseModel model) {
        super(application, model);
    }

    /**
     * 数据上行
     * 上报状态
     */
    public void reportProperty() {
        Thread thread = new Thread(() -> {
            //        publishRepeat();
            Log.i(TAG, "上报数据");
            try {
                double longitude = 104.05;
                double latitude = 30.69;
//                        if (mMapLocationInfo != null) {
//                            longitude = mMapLocationInfo.getLongitude();
//                            latitude = mMapLocationInfo.getLatitude();
//                            Log.i(TAG, mMapLocationInfo.toString() + "--地址：" + mMapLocationInfo.getAddress());
//                        }
                Integer weight = 0;
                Log.i("num=1", "读一次称重");
                weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
                if (weight == 1) {
                    weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();//读称重
                }
//            weight=SerialPortUtil.getInstance().getOtherDevice().readWeight();//称重
                Integer capacity = 0;
                try {
                    capacity = SerialPortUtil.getInstance().getUltrasonicDevice().ultRead();//超声波距离
                    if (capacity == 0) {//不准就再读一次
                        capacity = SerialPortUtil.getInstance().getUltrasonicDevice().ultRead();//超声波距离
                    }
                } catch (Exception e) {
                    Log.e(TAG, "reportProperty: ",e );
                    e.printStackTrace();
                }
                Integer magDoorSwitch = 0;
//                        magDoorSwitch = SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//门磁   //因为门磁安装问题，不需要去判断是否开关门了
                Integer currentTemperature = 0;
//                    currentTemperature = SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
//                        if (currentTemperature == 0) {
//                            currentTemperature = SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
//                        }
                Map<String, ValueWrapper> locationMap = new HashMap<>();
                Map<String, ValueWrapper> reportData = new HashMap<>();
                String rodNumberStr = SPUtils.getInstance().getString("RodNumber");
                if (rodNumberStr.equals("")) {
                    rodNumberStr = "0";
                }
                int rodNumberInt = Integer.parseInt(rodNumberStr);
                String rodSwitchStr = SPUtils.getInstance().getString("RodSwitch");
                if (rodSwitchStr.equals("")) {
                    rodSwitchStr = "0";
                }
                int rodSwitchInt = Integer.parseInt(rodSwitchStr);
                String lockNumberStr = SPUtils.getInstance().getString("LockNumber");
                if (lockNumberStr.equals("")) {
                    lockNumberStr = "0";
                }
                int lockNumberInt = Integer.parseInt(lockNumberStr);
                int clampHandNum = SPUtils.getInstance().getInt("ClampHandNum", 0);
                int runningStateInt = SPUtils.getInstance().getInt("RunningState");
                reportData.put("RodOpenNum", new ValueWrapper.IntValueWrapper(rodNumberInt));
                reportData.put("LockOpenNum", new ValueWrapper.IntValueWrapper(lockNumberInt));
                reportData.put("ClampHandNum", new ValueWrapper.IntValueWrapper(clampHandNum));
                reportData.put("Weight", new ValueWrapper.IntValueWrapper(weight));    //重量  单位 --- 克
                reportData.put("CurrentTemperature", new ValueWrapper.IntValueWrapper(currentTemperature));//温度，范围正负 ，精确到小数点后2位
                reportData.put("RestCapacity", new ValueWrapper.IntValueWrapper(capacity));  //距离值，单位mm
                reportData.put("MagDoorSwitch", new ValueWrapper.BooleanValueWrapper(magDoorSwitch));//门磁 0-关闭状态  1-开门状态
                reportData.put("LockSwitch", new ValueWrapper.BooleanValueWrapper(lockSwitch));   //锁开关状态：0-关锁  1-解锁  解锁后3s就关锁
                reportData.put("RodSwitch", new ValueWrapper.BooleanValueWrapper(rodSwitchInt));   //推杆状态：0-关闭状态  1-打开  开门
                reportData.put("RunningState", new ValueWrapper.BooleanValueWrapper(runningStateInt)); // 0正常
//            1设备故障 未识别到称重设备 报警  未识别到杆、门磁、锁、温度、红外、超声波设备 报警
//            2温度过高 报警
//            3收运门意外打开报警
//            4称重失灵报警 错误一次就再读一次  超过两次读取错误就报警
//            5温度和超声波失灵警告 失灵显示的000000000

                System.out.println(IMEI + "DeviceId");
                reportData.put("IMEI", new ValueWrapper.StringValueWrapper(IMEI));
                locationMap.put("longitude", new ValueWrapper.DoubleValueWrapper(longitude));
                locationMap.put("latitude", new ValueWrapper.DoubleValueWrapper(latitude));
                locationMap.put("altitude", new ValueWrapper.DoubleValueWrapper(523.1));
                reportData.put("GeoLocation", new ValueWrapper.StructValueWrapper(locationMap)); //

                textReportData.set("称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " +
                        currentTemperature + "度;门磁 " + magDoorSwitch + ";杆状态 " + rodSwitchInt + ";锁状态 " + lockSwitch + ";杆开门次数 " + rodNumberInt + ";开锁次数 " + lockNumberInt + ";被夹次数" + clampHandNum + ";运行状态" + runningStateInt
                );

                String text = "称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " + currentTemperature + "度;门磁 " + magDoorSwitch + ";杆状态 " +
                        rodSwitchInt + ";锁状态 " + lockSwitch + ";杆开门次数 " + rodNumberInt + ";开锁次数 " + lockNumberInt + ";被夹次数" + clampHandNum + "------------------------------";
                Log.i(TAG, text + "=textReportData---------------------");
                mHandler.postDelayed(() -> {
                    int networkNum = SPUtils.getInstance().getInt("netWork", 1);
                    if (networkNum != 0) {
                        LinkKit.getInstance().getDeviceThing().thingPropertyPost(reportData, new IPublishResourceListener() {
                            @Override
                            public void onSuccess(String s, Object o) {
                                Log.d("", "onSuccess() called with: s = [" + s + "], o = [" + o + "]");
                                SPUtils.getInstance().put("RunningState", 0);
                                textReportData.set(textReportData.get() + "-上报成功");
                            }

                            @Override
                            public void onError(String s, AError aError) {
                                Log.e("Main", s);
                            }
                        });
                    }
                }, 200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.start();

    }

    /*
     * 上报给蓝牙的数据格式
     * */
    public JSONObject reportDataMethod() {
        //称重必须要传，其他的可以删掉，不过要和后台协商，统一数据格式
        Integer capacity = 1000;
//        capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离/
//        if(capacity==0){
//            capacity=SerialPortUtil.getInstance().getOtherDevice().getDistance();//超声波距离/
//        }
        Integer magDoorSwitch = 0;
//        magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//门磁
        Integer currentTemperature = 25;
//        currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
//        if(currentTemperature==0){
//            currentTemperature=SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
//        }
        Integer weight = 0;
        weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();
        if (weight == 1) {
            weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();
        }
        //        weight=SerialPortUtil.getInstance().getOtherDevice().readWeight();//称重

        String text = "称重 " + weight.toString() + ";距离 " + capacity.toString() + "mm;温度 " + currentTemperature + "度;门磁 " + magDoorSwitch + ";杆状态 " + ";锁状态 " + lockSwitch;
        Log.i(TAG, text + "=textReportData---------------------");

//        JSONObject locationMap =new JSONObject();
        String rodNumberStr = SPUtils.getInstance().getString("RodNumber");
        if (rodNumberStr.equals("")) {
            rodNumberStr = "0";
        }
        int rodNumberInt = Integer.parseInt(rodNumberStr);
        String rodSwitchStr = SPUtils.getInstance().getString("RodSwitch");
        if (rodSwitchStr.equals("")) {
            rodSwitchStr = "0";
        }
        int rodSwitchInt = Integer.parseInt(rodSwitchStr);

        String lockNumberStr = SPUtils.getInstance().getString("LockNumber");
        if (lockNumberStr.equals("")) {
            lockNumberStr = "0";
        }
        int lockNumberInt = Integer.parseInt(lockNumberStr);
        int runningStateInt = SPUtils.getInstance().getInt("RunningState");
        JSONObject tem1 = new JSONObject();
        tem1.put("V", IMEI);
        tem1.put("I", "IMEI");

        JSONObject tem2 = new JSONObject();
        tem2.put("V", rodNumberInt);
        tem2.put("I", "RodOpenNum");

        JSONObject tem3 = new JSONObject();
        tem3.put("V", lockNumberInt);
        tem3.put("I", "LockOpenNum");

        JSONObject tem4 = new JSONObject();
        tem4.put("V", weight);
        tem4.put("I", "Weight");

        JSONObject tem5 = new JSONObject();
        tem5.put("V", currentTemperature);
        tem5.put("I", "CurrentTemperature");

        JSONObject tem6 = new JSONObject();
        tem6.put("V", capacity);
        tem6.put("I", "RestCapacity");

        JSONObject tem7 = new JSONObject();
        tem7.put("V", magDoorSwitch);
        tem7.put("I", "MagDoorSwitch");

        JSONObject tem8 = new JSONObject();
        tem8.put("V", lockSwitch);
        tem8.put("I", "LockSwitch");

        JSONObject tem9 = new JSONObject();
        tem9.put("V", rodSwitchInt);
        tem9.put("I", "RodSwitch");

        JSONObject tem10 = new JSONObject();
        tem10.put("V", runningStateInt);
        tem10.put("I", "RunningState");

//        locationMap.put("longitude", 107.31);
//        locationMap.put("latitude", 23.16);
//        locationMap.put("altitude", 523.1);
//        JSONObject tem11 =new JSONObject();
//        tem11.put("V",locationMap);
//        tem11.put("I","GeoLocation");

        JSONArray array = new JSONArray();
        array.add(tem1);
        array.add(tem2);
        array.add(tem3);
        array.add(tem4);
        array.add(tem5);
        array.add(tem6);
        array.add(tem7);
        array.add(tem8);
        array.add(tem9);
        array.add(tem10);
//        array.add(tem11);
        JSONObject reportData = new JSONObject();
        reportData.put("P", array);
        Log.i(TAG, "reportData=+++++" + reportData.toString());
        SPUtils.getInstance().put("RunningState", 0);
        return reportData;
//        return (String) reportData;
    }

    /*
     * 加密传给蓝牙的数据格式
     * */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public String reportDataMethodEncrypt() {
        JSONObject reportData = new JSONObject();
        reportData.put("T", SPUtils.getInstance().getString("type"));
        //加密数据
        String base64Str = "";
        try {
            base64Str = DemoOne.encrypt(reportDataMethod().toString() + "@", "1234567890123456", "0987654321098765");//加密数据
        } catch (Exception e) {
            e.printStackTrace();
        }
        reportData.put("D", base64Str);

        return reportData.toString();
    }

    //设备事件上报
    public static void reportDeviceEvent(String identifier, String event, int num) {
        HashMap<String, ValueWrapper> hashMap = new HashMap<>();
        HashMap<String, ValueWrapper> hashMapWeight = new HashMap<>();
        // TODO 用户根据实际情况设置
        // hashMap.put("ErrorCode", new ValueWrapper.IntValueWrapper(0));
        if (num == 1) {
            hashMap.put("warnEvent", new ValueWrapper.StringValueWrapper(event));
        } else if (num == 2) {
            hashMap.put("errorEvent", new ValueWrapper.StringValueWrapper(event));
        } else if (num == 3) {
            int weight = SerialPortUtil.getInstance().getWeightDevice().readWeight();
            String weightS = weight + "";
            hashMap.put("action", new ValueWrapper.StringValueWrapper(event));
            hashMap.put("weight", new ValueWrapper.StringValueWrapper(weightS));
        }
        OutputParams params = new OutputParams(hashMap);
        Log.i("事件上报", identifier + "=====" + event);
        int networkNum = SPUtils.getInstance().getInt("netWork", 1);
        if (networkNum != 0) {
            LinkKit.getInstance().getDeviceThing().thingEventPost(identifier, params, new IPublishResourceListener() {
                @Override
                public void onSuccess(String resId, Object o) { // 事件上报成功
                    Log.i("事件上报", "上报成功");
                }

                @Override
                public void onError(String resId, AError aError) { // 事件上报失败
                    Log.i("事件上报", "上报失败");
                }
            });
        } else {
            Log.i("上报", "失败，没有网络");
        }

    }

    private void getDeviceProperty(String identifier) {
        // 根据 identifier 获取当前物模型中该属性的值
        Log.i("获取属性", "-----------------------");
        Log.i("获取属性", "" + LinkKit.getInstance().getDeviceThing().getPropertyValue("Weight"));
        Log.i("获取属性", "" + LinkKit.getInstance().getDeviceThing());
        Log.i("获取属性", "" + LinkKit.getInstance().getDeviceThing().toString());
        Log.i("获取属性", "" + LinkKit.getInstance().getDeviceThing().getPropertyValue("Weight").getValue());
        ValueWrapper.IntValueWrapper weight = (ValueWrapper.IntValueWrapper) LinkKit.getInstance().getDeviceThing().getPropertyValue("Weight");
        Log.i("获取属性", "" + weight.getValue());
        // 获取所有属性
//        LinkKit.getInstance().getDeviceThing().getProperties();
        for (int i = 0; i < LinkKit.getInstance().getDeviceThing().getProperties().size(); i++) {
            Log.i("全部属性---------", "" + LinkKit.getInstance().getDeviceThing().getProperties().get(i).getName());
            Log.i("全部属性---------", "" + LinkKit.getInstance().getDeviceThing().getProperties().get(i).getAccessMode());
            Log.i("全部属性---------", "" + LinkKit.getInstance().getDeviceThing().getProperties().get(i).getDesc());
            Log.i("全部属性---------", "" + LinkKit.getInstance().getDeviceThing().getProperties().get(i).getIdentifier());
            Log.i("全部属性---------", "" + LinkKit.getInstance().getDeviceThing().getProperties().get(i).getDataType());
        }
        Log.i("全部属性---------", "" + LinkKit.getInstance().getDeviceThing().getProperties());
    }

    public void registerAliIoTListener() {
        // 注册下行监听，包括长连接的状态和云端下行的数据
        LinkKit.getInstance().registerOnPushListener(notifyListener);
        MqttSubscribeRequest subscribeRequest = new MqttSubscribeRequest();
        subscribeRequest.topic = "/a1EtqHmfpNk/" + IMEI + "/user/checkOnlineStatus";//正式服
//       subscribeRequest.topic = "/a13H8L6bDyf/"+IMEI+"/user/checkOnlineStatus";//测试服
        subscribeRequest.isSubscribe = true;
        subscribeRequest.qos = 0;
        LinkKit.getInstance().subscribe(subscribeRequest, new IConnectSubscribeListener() {
            @Override
            public void onSuccess() {
                System.out.println("checkOnlineStatus subscribe success");
            }

            @Override
            public void onFailure(AError aError) {
                System.out.println("checkOnlineStatus subscribe Fail");
            }
        });

        publish();
    }

    private void reportVersion() {
        //上报版本
        IOta mOta = LinkKit.getInstance().getOta();
        mOta.reportVersion(BuildConfig.VERSION_CODE + "", (i, s) -> Log.i(TAG, "上报版本  i:" + i + "  s:" + s));
    }

    /*
     * 安装下载的app
     * */
    protected void installAPK() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                File apkFile = new File("/sdcard/Android/data/otaFile/app/app.apk");
                if (apkFile.isDirectory()) {
                    unZipFileDemo.deleteDir(apkFile);
                }
                File apkFile2 = new File("/sdcard/Android/data/otaFile/file.zip");
                unZipFileDemo.unZipFile(apkFile2, "/sdcard/Android/data/otaFile/app.apk");
                File apkFile3 = new File("/sdcard/Android/data/otaFile/app.apk");

                Log.i("安装", "start");
                if (SilentInstall.install(apkFile3.toString())) {
                    Log.i("安装", "yes");
                } else {
                    Log.i("安装", "no");
                }
            }
        }, 1000);
    }

    /*
     *监听是否有新版本app，有就下载
     * */
    public void otaListener() {
        IOta mOta = LinkKit.getInstance().getOta();
        IOta.OtaConfig mConfig = new IOta.OtaConfig();
        mConfig.deviceVersion = "1";
//        mConfig.otaFile = new File(getApplication().getCacheDir()+"/otaFile/file.apk");
        System.out.println("dataDirPath:" + getApplication().getFilesDir().getAbsolutePath());
        mConfig.otaFile = new File("/sdcard/Android/data/otaFile/file.zip");
        if (!mConfig.otaFile.exists()) {
            boolean isCreate = mConfig.otaFile.mkdirs();
            System.out.println("创建文件：" + isCreate);
        }
        Log.i(TAG, "路径为=" + mConfig.otaFile.toString());
        Log.i(TAG, "路径为-" + mConfig.otaFile.getAbsolutePath());
        mOta.tryStartOta(mConfig, (step, otaResult) -> {
            int code = otaResult.getErrorCode();
            Object data = otaResult.getData();
            System.out.println("stryStartOta:  code:" + code + "  data:" + data.toString());
            if (data.toString().equals("100")) {
                installAPK();
            }
            switch (step) {
                case IOta.STEP_REPORT_VERSION:
                    // 上报版本
                    reportVersion();
                    break;
                case IOta.STEP_SUBSCRIBE:
                    // 订阅回调
                    System.out.println("订阅回调。");
                    break;
                case IOta.STEP_RCVD_OTA:
                    // 有新的OTA固件，返回true 表示继续升级
                    System.out.println("有新的OTA固件！！！");
                    File file = new File("/sdcard/Android/data/otaFile/file.zip");
                    if (file.isDirectory()) {
                        unZipFileDemo.deleteDir(file);
                    }
                    break;
                case IOta.STEP_DOWNLOAD:
                    // 下载固件中
                    System.out.println("下载固件中！！！！");
                    break;
            }
            return true;
        });
    }

    private int disconnectTimes = 0;

    private void publish() {
        //一个循环方法，用来更新数据
        System.out.println("checkOnlineStatus");
        MqttPublishRequest publishRequest = new MqttPublishRequest();
        publishRequest.isRPC = false;

        publishRequest.topic = "/a1EtqHmfpNk/" + IMEI + "/user/checkOnlineStatus";//正式服
//        publishRequest.topic = "/a13H8L6bDyf/"+IMEI+"/user/checkOnlineStatus";//测试服
        publishRequest.qos = 0;
        publishRequest.payloadObj = "{\"id\":" + publishRequest.msgId + ", \"version\":\"8.0\",\"time\":" + System.currentTimeMillis() + "}";
        publishRequest.payloadObj = "{\"id\":\"1}";

        int networkNum = SPUtils.getInstance().getInt("netWork", 1);
        if (networkNum != 0) {
            LinkKit.getInstance().publish(publishRequest, new IConnectSendListener() {
                @Override
                public void onResponse(ARequest aRequest, AResponse aResponse) {
//                    Log.i(TAG,"发布成功");
                    disconnectTimes = 0;
                    System.out.println("publish on Response :" + aResponse.getData());
                }

                @Override
                public void onFailure(ARequest aRequest, AError aError) {
//                    Log.i(TAG,"发布失败");
                    System.out.println("publish onFailure  error:" + aError.getMsg());
                    disconnectTimes++;
                    if (disconnectTimes > 5) {
                        registerAliIoTListener(); //重新连接。
                        disconnectTimes = 0;
                        return;
                    }
                }
            });
        }

    }


    public void unRegisterIoTListener() {
        // 取消注册 notifyListener，notifyListener对象需和注册的时候是同一个对象
        LinkKit.getInstance().unRegisterOnPushListener(notifyListener);
        LinkKit.getInstance().deinit();
    }

    public static final UUID UUID_SERVICE = UUID.fromString("7377647A-0000-1000-8000-00805F9B34FB");    //全部自定义.
    public static final UUID UUID_DESC_NOTITY = UUID.fromString("7377647A-0000-1000-adc5-89df72c789ec");
    public static final UUID UUID_CHAR_WRITE = UUID.fromString("7377647A-0000-1000-7264-00805F9B34FB");
    public static final UUID UUID_CHAR_READ_NOTIFY = UUID.fromString("7377647A-0000-1000-6e66-00805F9B34FB");
    private BluetoothLeAdvertiser mBluetoothLeAdvertiser; // BLE广播
    private BluetoothGattServer mBluetoothGattServer; // BLE服务端
    private BluetoothGatt bluetoothGatt;
    // BLE广播Callback
    private AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            Log.d(TAG, "BLE广播开启成功");
        }

        @Override
        public void onStartFailure(int errorCode) {
            Log.e(TAG, "BLE广播开启失败,错误码:" + errorCode);
        }
    };
    //    private final BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() {
//        @Override
//        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
//            super.onMtuChanged(gatt, mtu, status);
//            Log.d("onMtuChanged"," onMtuChanged");
//            if (BluetoothGatt.GATT_SUCCESS == status) {
//                Log.d("BleService", "onMtuChanged success MTU = " + mtu);
//            }else {
//                Log.d("BleService", "onMtuChanged fail ");
//            }
//        }
//    };
//    private boolean requestMtu2(){
//        if (bluetoothGatt != null) {
//            // 25 *6 +3 =153
//            return bluetoothGatt.requestMtu(517);
//        }
//        return false;
//    }
    /*
     * 蓝牙连接，通信
     * */
    // BLE服务端Callback
    private BluetoothGattServerCallback mBluetoothGattServerCallback = new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {

//            bluetoothGatt = device.connectGatt(getApplication(), true, mBluetoothGattCallback);
//            Log.i("requestMTUU=",bluetoothGatt.requestMtu(25)+"");
//            Log.i("requestMtu2=",requestMtu2()+"");
//            onMtuChanged(device,517);
            Log.i(TAG, String.format("onConnectionStateChange:%s,%s,%s,%s", device.getName(), device.getAddress(), status, newState));
            Log.d(TAG, String.format(status == 0 ? (newState == 2 ? "与[%s]连接成功" : "与[%s]连接断开") : ("与[%s]连接出错,错误码:" + status), device));
        }

        @Override
        public void onServiceAdded(int status, BluetoothGattService service) {
            Log.i(TAG, String.format("onServiceAdded:%s,%s", status, service.getUuid()));
            Log.d(TAG, String.format(status == 0 ? "添加服务[%s]成功" : "添加服务[%s]失败,错误码:" + status, service.getUuid()));
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
            Log.i(TAG, String.format("onCharacteristicReadRequest:%s,%s,%s,%s,%s", device.getName(), device.getAddress(), requestId, offset, characteristic.getUuid()));
            new Thread(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void run() {
                    String response = SPUtils.getInstance().getString("response");
//                    +"asasasa15s1a5s1a651sa51s6a51s6a51s5a1s65a1sa51sa651sa561sa51s5a1s6a51s65a1s"
//                    response="{\"encryptData\":\"81ypl9FQ9YyoyLyjPpd6BpvC0kT+QDGvKt9eQU8YjFhMuMpVsAMwSw/+kOFDhKKp8JEbFWKM3vTDZp5HhxIl0GloODH5RAutIFDNcLP1c13OrIfeFMmaOivV63omw5CbAMBQp0nuMXPbzHICiZ2HFJhcA0Ahm0g+R+4ze74ku4Ojbor+3s3Q4G3pF+6tnJelR/P4ovA81Ls0dvc1aBSC15hPjkD94j4mAsariqcj328zDQE9oXFb7I5k7z5jkAAVB4cm0qxnk/Np+KoEA1DU0TtQEjvN18Ak/kEND7hk5fU2xGcCmS6OMzltUk4Z3acaydWDaAfvZnChP/wUwXBcVmRdK50tgq8/70xhUWZT5WycOYmov7cO/F7gK1aP/u8hCNztYkG+sXyReXfHfFWk/0AtbT19+wUoyVgaihUfKI/knNSjqunBnVjksNKqRIKqWAUdQIarlxo+V7zdwsBcMnHQBCVeSGdG3OPfaEVMEOFopjOB7q7YLPd93AhYr/x9eQc6tRaZOR1dVgiq3hpxOD3uDCcumDjK88XcyvaD/EYV7rEukd8bTOF6lVEy3iCx+AT9GTqm123";
                    byte[] responseBytes = response.getBytes();
                    Log.i(TAG, "responseBytes.length==" + responseBytes.length);
                    Log.i(TAG, "offset=" + offset);
                    if (SPUtils.getInstance().getInt("phoneType") == 2) {
                        mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, responseBytes.length, responseBytes);// 响应客户端
                        Log.d(TAG, "客户端读取Characteristic[" + characteristic.getUuid() + "]:\n" + response);
                    } else {
                        if (responseBytes.length > offset) {
                            int restLen = responseBytes.length - offset;
                            byte[] bytesCopy = new byte[restLen > 22 ? 22 : restLen];
                            System.arraycopy(responseBytes, offset, bytesCopy, 0, restLen > 22 ? 22 : restLen);
                            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, bytesCopy);// 响应客户端
                            Log.d(TAG, "客户端读取Characteristic[" + characteristic.getUuid() + "]:\n" + bytesCopy.toString());
                            Log.d(TAG, "客户端读取Characteristic[" + characteristic.getUuid() + "]:\n" + response);
                        } else {
                            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, responseBytes);// 响应客户端
                        }
                    }

//                    Log.d(TAG,"客户端读取Characteristic[" + characteristic.getUuid() + "]:\n" + bytesCopy.toString());
//                        Log.d(TAG,"客户端读取Characteristic[" + characteristic.getUuid() + "]:\n" + response);
//                    mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS,responseBytes.length,responseBytes );// 响应客户端
                }
            }).start();
        }

        @Override
        public void onCharacteristicWriteRequest(final BluetoothDevice device, int requestId,
                                                 final BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] requestBytes) {
            // 获取客户端发过来的数据
            new Thread(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void run() {
                    Log.i(TAG, "device=" + device.toString());
                    Log.i(TAG, "requestId=" + requestId);
                    Log.i(TAG, "characteristic=" + characteristic.toString());
                    Log.i(TAG, "preparedWrite=" + preparedWrite);
                    Log.i(TAG, "responseNeeded=" + responseNeeded);
                    Log.i(TAG, "offset=" + offset);
                    Log.i(TAG, "requestBytes=" + requestBytes.toString());
                    String requestStr = new String(requestBytes);
                    System.out.println(requestStr);
                    Log.i(TAG, "changdu==" + requestStr.length());
                    String[] data = requestStr.split("[|]");

                    if (data[0].endsWith("fir3")) {
                        mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, requestBytes);// 响应客户端
                        if (data[1].equals("11")) {
                            if (SPUtils.getInstance().getInt("clearWight", 2) == 1) {
                                SerialPortUtil.getInstance().getWeightDevice().weightClear();//去皮清零
//                SerialPortUtil.getInstance().getOtherDevice().clearWeight();//去皮清零
                                SPUtils.getInstance().put("clearWight", 2);
                            }
                            pullRodMethod();
                            Log.i(TAG, "----------------------*************--" + data[1] + "+++" + data[2]);
                            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, requestBytes);// 响应客户端
                            String timeStr = data[2];
                            int timeInt = Integer.parseInt(timeStr);
                            if (timeInt == 0) {
                                timeInt = 82;
                            }
                            int finalTimeInt = timeInt * 1000 + 5000;
                            Log.i("计时", "" + finalTimeInt);
                            Thread thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    int numInt = 0;
                                    long curr = System.currentTimeMillis();
                                    while (System.currentTimeMillis() - curr < finalTimeInt + 5000) {
                                        try {
                                            sleep(1000);
                                            numInt++;
//                                                Log.i("倒计时时间",numInt+"---"+SPUtils.getInstance().getString("RodSwitch")+"---"+finalTimeInt);
                                            if (SPUtils.getInstance().getString("RodSwitch").equals("0")) {
                                                break;
                                            }
                                            if (numInt * 1000 == finalTimeInt) {
                                                pushRodMethodNonet();
                                                SPUtils.getInstance().put("type", "close");
                                                String response = reportDataMethodEncrypt();
                                                SPUtils.getInstance().put("response", response);
                                                onCharacteristicReadRequest(device, requestId, offset, characteristic);
                                                break;
                                            }
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                            thread.start();
                        }
                        if (data[1].equals("22")) {
                            mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, requestBytes);// 响应客户端
                            try {
                                SPUtils.getInstance().put("magDoorSwitch", 1);
                                SPUtils.getInstance().put("clearWight", 1);
                                SerialPortUtil.getInstance().getWeightDevice().weightClear();//若关闭，称重清零
                                SerialPortUtil.getInstance().getOtherDevice().openLock();
                                mHandler.postDelayed(() -> {
                                    try {
                                        AssetFileDescriptor fd = getApplication().getAssets().openFd("openLock.mp3");
                                        mMediaPlay = new MediaPlayer();
                                        mMediaPlay.reset();
                                        mMediaPlay.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                                        mMediaPlay.prepare();
                                        Log.i(TAG, "播放音频");
                                        mMediaPlay.start();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }, 200);
                                lockSwitch = 1;//解锁
                                mHandler.postDelayed(() -> {
                                    SerialPortUtil.getInstance().getOtherDevice().closeLock();
                                    lockSwitch = 0;//关锁
                                    Thread thread = new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                long curr = System.currentTimeMillis();
                                                while (System.currentTimeMillis() - curr < 600000) {
                                                    Thread.sleep(10000);
                                                    Integer magDoorSwitch = SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//通过门磁感应判断收运门是否关闭
                                                    if (magDoorSwitch == 0) {
                                                        SerialPortUtil.getInstance().getWeightDevice().weightClear();//若关闭，称重清零
                                                        SPUtils.getInstance().put("magDoorSwitch", 0);
//                                                            SerialPortUtil.getInstance().getOtherDevice().clearWeight();
                                                        String response = reportDataMethodEncrypt();
                                                        SPUtils.getInstance().put("response", response);
                                                        onCharacteristicReadRequest(device, requestId, offset, characteristic);
                                                        break;
                                                    }
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                    thread.start();
                                }, 7000);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if (requestStr.equals("close")) {
                        pushRodMethodNonet();
                        Log.i(TAG, "++++++收到321");
                        Log.i(TAG, "+++++关门");
                        SPUtils.getInstance().put("type", "close");
                        String response = reportDataMethodEncrypt();
                        SPUtils.getInstance().put("response", response);
                        onCharacteristicReadRequest(device, requestId, offset, characteristic);
                    }
                    if (requestStr.equals("close2")) {
                        Log.i(TAG, "+++++收运门关");
                        SerialPortUtil.getInstance().getWeightDevice().weightClear();//若关闭，称重清零
                        SPUtils.getInstance().put("magDoorSwitch", 0);
//                          SerialPortUtil.getInstance().getOtherDevice().clearWeight();
                        SPUtils.getInstance().put("type", "close");
                        String response = reportDataMethodEncrypt();
                        SPUtils.getInstance().put("response", response);
                        onCharacteristicReadRequest(device, requestId, offset, characteristic);
                    }
                    if (requestStr.equals("link|1")) {
                        SPUtils.getInstance().put("phoneType", 1);
                        Log.i(TAG, "++++++收到123");
                        Log.i(TAG, "+++++开门请求");
                        Log.i(TAG, "+++++requestStrlength" + requestStr.length());
                        SPUtils.getInstance().put("type", "open");
                        String response = reportDataMethodEncrypt();
                        SPUtils.getInstance().put("response", response);
                        onCharacteristicReadRequest(device, requestId, offset, characteristic);
                    }
                    if (requestStr.equals("link|2")) {
                        SPUtils.getInstance().put("phoneType", 2);
                        Log.i(TAG, "++++++收到123");
                        Log.i(TAG, "+++++开门请求");
                        Log.i(TAG, "+++++requestStrlength" + requestStr.length());
                        SPUtils.getInstance().put("type", "open");
                        String response = reportDataMethodEncrypt();
                        SPUtils.getInstance().put("response", response);
                        onCharacteristicReadRequest(device, requestId, offset, characteristic);
                    }
                    Log.i(TAG, String.format("onCharacteristicWriteRequest:%s,%s,%s,%s,%s,%s,%s,%s", device.getName(), device.getAddress(), requestId, characteristic.getUuid(),
                            preparedWrite, responseNeeded, offset, requestStr));
                    Log.d(TAG, "客户端写入Characteristic[" + characteristic.getUuid() + "]write:\n" + requestStr);
                    mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, requestBytes);// 响应客户端
                }
            }).start();
        }

        @Override
        public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
            Log.i(TAG, String.format("onExecuteWrite:%s,%s,%s,%s", device.getName(), device.getAddress(), requestId, execute));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onNotificationSent(BluetoothDevice device, int status) {
            Log.i(TAG, String.format("onNotificationSent:%s,%s,%s", device.getName(), device.getAddress(), status));
        }


        @Override
        public void onMtuChanged(BluetoothDevice device, int mtu) {
            super.onMtuChanged(device, 512);
            Log.i(TAG, String.format("onMtuChanged:%s,%s,%s", device.getName(), device.getAddress(), mtu));
        }


    };
    BluetoothGattCharacteristic characteristicRead;

    public void startBLEServer() {
        BluetoothManager bluetoothManager = (BluetoothManager) getApplication().getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.setName("62F");
        // ============启动BLE蓝牙广播(广告) =================================================================================
        Log.i(TAG, "启动BLE蓝牙广播(广告)");
        //广播设置(必须)
        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER) //广播模式: 低功耗,平衡,低延迟
                .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH) //发射功率级别: 极低,低,中,高
                .setConnectable(true) //能否连接,广播分为可连接广播和不可连接广播
                .setTimeout(0)
                .build();
        //广播数据(必须，广播启动就会发送)
        AdvertiseData advertiseData = new AdvertiseData.Builder()
                .setIncludeDeviceName(true) //包含蓝牙名称
                .setIncludeTxPowerLevel(true) //包含发射功率级别
                .addManufacturerData(0x09, "sw".getBytes()) //设备厂商数据，自定义
                .build();
        //扫描响应数据(可选，当客户端扫描时才发送)
        AdvertiseData scanResponse = new AdvertiseData.Builder()
                .addManufacturerData(2, new byte[]{66, 66, 31, 45, (byte) 0xac}) //设备厂商数据，自定义
                .addServiceUuid(new ParcelUuid(UUID_SERVICE)) //服务UUID
//                .addServiceData(new ParcelUuid(UUID_SERVICE), new byte[]{2}) //服务数据，自定义
                .build();
        mBluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
        mBluetoothLeAdvertiser.startAdvertising(settings, advertiseData, scanResponse, mAdvertiseCallback);

        // 注意：必须要开启可连接的BLE广播，其它设备才能发现并连接BLE服务端!
        // =============启动BLE蓝牙服务端=====================================================================================
        BluetoothGattService service = new BluetoothGattService(UUID_SERVICE, BluetoothGattService.SERVICE_TYPE_PRIMARY);
        //添加可读+通知characteristic
        characteristicRead = new BluetoothGattCharacteristic(UUID_CHAR_READ_NOTIFY,
                BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE,
                BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE);
        characteristicRead.addDescriptor(new BluetoothGattDescriptor(UUID_DESC_NOTITY, BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ));
        service.addCharacteristic(characteristicRead);
        //添加可写characteristic
        BluetoothGattCharacteristic characteristicWrite = new BluetoothGattCharacteristic(UUID_CHAR_WRITE,
                BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE
                , BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ);
        service.addCharacteristic(characteristicWrite);
        if (bluetoothManager != null)
            mBluetoothGattServer = bluetoothManager.openGattServer(getApplication(), mBluetoothGattServerCallback);
        mBluetoothGattServer.addService(service);
    }

    public void stopBleServer() {
        if (mBluetoothLeAdvertiser != null)
            mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
        if (mBluetoothGattServer != null)
            mBluetoothGattServer.close();
    }


    public static final String INTENT_ACTION_GRANT_USB = "com.siwei.recyclebox.GRANT_USB";
    private List<UsbSerialPort> mEntries = new ArrayList<UsbSerialPort>();
    private BroadcastReceiver mUsbReceiver;
    private UsbManager mUsbManager;
    UsbSerialPort port = null;

    public void closePort() {
        try {
            port.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        try {
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO : 没有权限，读不到deviceid，要向用户申请读取手机信息的权限
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return "";
            }
            String imei = tm.getDeviceId();
            if (!StringUtils.isEmpty(imei)) {
//                deviceId.append("imei");
                deviceId.append(imei);
//                PALog.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //wifi mac地址
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String wifiMac = info.getMacAddress();
            if (!StringUtils.isEmpty(wifiMac)) {
//                deviceId.append("wifi");
                deviceId.append(wifiMac);
//                PALog.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!StringUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
//                PALog.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
//            String uuid = getUUID(context);
//            if(!isEmpty(uuid)){
//                deviceId.append("id");
//                deviceId.append(uuid);
//                PALog.e("getDeviceId : ", deviceId.toString());
//                return deviceId.toString();
//            }
        } catch (Exception e) {
            e.printStackTrace();
//            deviceId.append("id").append(getUUID(context));
        }
//        PALog.e("getDeviceId : ", deviceId.toString());
        return deviceId.toString();
    }

    /*@RequiresApi(api = Build.VERSION_CODES.N)
    private JSONObject getAllDeviceProperty(){
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        AtomicInteger weightResult = new AtomicInteger();
        JSONObject jsonObject = new JSONObject();
        CompletableFuture<Integer> weightFuture = CompletableFuture.supplyAsync(()->{
            WeightDevice weightDevice = (WeightDevice) SerialPortUtil.getInstance().getWeightDevice();
            int weight = weightDevice.readWeight();
            return weight;
        },executorService);
        CompletableFuture<Double> temperatureFuture = CompletableFuture.supplyAsync(()->{
            return 41.1;
        },executorService);

        weightFuture.thenAccept((result)->{
            jsonObject.put("weight",result);
        });
        temperatureFuture.thenAccept((result)->{
            jsonObject.put("currentTemperature",result);
        });
        jsonObject.put("IMEI",IMEI);
        jsonObject.put("RunningState",0);
        jsonObject.put("LockSwitch",1);

        return jsonObject;
    }*/
    /*
     * 判断是否有网
     * */
    public Integer netWorkInfo() {
        ConnectivityManager connectivity = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                Log.i(TAG, "WiFi网络...");//WiFi网络
                return 2;
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
//移动网络
                Log.i(TAG, "移动网络....");
                return 1;
            } else {
//网络错误
                Log.i(TAG, "网络错误....");
                return 0;
            }
        } else {
//网络错误
            Log.i(TAG, "设备网络错误....");
            return 0;
        }
    }

    /*
     * 判断是否有网
     * */
    public static Integer netWorkInfoStatic() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                Log.i("network", "WiFi网络...");//WiFi网络
                return 2;
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
//移动网络
                Log.i("network", "移动网络....");
                return 1;
            } else {
//网络错误
                Log.i("network", "网络错误....");
                return 0;
            }
        } else {
//网络错误
            Log.i("network", "设备网络错误....");
            return 0;
        }
    }

    /*
     * 重启app方法
     * */
    public void restartApp() {
        Intent mStartActivity = new Intent(getApplication(), MainActivity.class);
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplication(), mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    }

    public void restartAndroid() {
        //获取root权限，前提是设备已经root过
        try {
            Process process = Runtime.getRuntime().exec("su");
            //执行重启命令
            Runtime.getRuntime().exec("su -c reboot");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Object getSystemService(String name) {
        return getApplication().getSystemService(name);
    }

    public void repeatTask() {
        task3 = new TimerTask() {
            public void run() {
                publishRepeat();
                reportProperty();
//                Log.i("Task","300秒循环");
            }
        };
        timer.schedule(task3, 20000, 600000);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 11);
        calendar.set(Calendar.MINUTE, 26);
        task2 = new TimerTask() {
            @Override
            public void run() {
                openLight();
                if (readTime() == 3) {
                    restartAndroid();
                }
                Integer networkInt = netWorkInfo();
                if (networkInt == 0) {
                    restartApp();
                }
                SPUtils.getInstance().put("netWork", networkInt);
            }
        };
        timer.schedule(task2, 3300000, 3300000);

        task1 = new TimerTask() {
            @Override
            public void run() {
                publish();
            }
        };
        timer.schedule(task1, 1000, 200000);

    }

    private void publishRepeat() {
//        Integer currentTemperature= SerialPortUtil.getInstance().getOtherDevice().geTemperature();//温度
////        Integer magDoorSwitch=SerialPortUtil.getInstance().getOtherDevice().queryMagDoor();//门磁安装问题，不需要判断意外开门了
//        Integer queryCurrent=SerialPortUtil.getInstance().getOtherDevice().queryCurrent();
//        if(queryCurrent==1){
//            int num=SPUtils.getInstance().getInt("ClampHandNum",0);
//            SPUtils.getInstance().put("ClampHandNum",num+1);//记录被夹次数
//            SerialPortUtil.getInstance().getOtherDevice().clearCurrent();
//        }
//        if(currentTemperature>70){
//            SPUtils.getInstance().put("RunningState",2);//温度过高
//            Log.i(TAG,"温度过高");
//            SendSmsResponse("温度过高");
//        }
//        if(currentTemperature>25){
////            SerialPortUtil.getInstance().getOtherDevice().openLight1();/打开风扇
//        }else{
        //            SerialPortUtil.getInstance().getOtherDevice().closeFan();//关闭风扇
//            SerialPortUtil.getInstance().getOtherDevice().closeLight1();
    }
        /*if(magDoorSwitch==1){
            if(SPUtils.getInstance().getInt("magDoorSwitch")==0){
                SPUtils.getInstance().put("RunningState",3);
                Log.i(TAG,"收运门意外打开");
                SendSmsResponse("收运门意外打开");
            }
        }*/

    //    }
    public int readTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        Log.i("Time hour=","现在是"+hour+"点");
        return hour;
    }

    public void openLight() {
//        Log.i("d定时","ok");
        if (readTime() > 18 || readTime() < 2) {
//            Log.i("night","开灯");
            SerialPortUtil.getInstance().getOtherDevice().openLight1();
            SerialPortUtil.getInstance().getOtherDevice().openLight2();
            SerialPortUtil.getInstance().getOtherDevice().openLight3();
            SerialPortUtil.getInstance().getOtherDevice().openLight4();
        } else {
//            Log.i("day","关灯");
            SerialPortUtil.getInstance().getOtherDevice().closeLight1();
            SerialPortUtil.getInstance().getOtherDevice().closeLight2();
            SerialPortUtil.getInstance().getOtherDevice().closeLight3();
            SerialPortUtil.getInstance().getOtherDevice().closeLight4();
        }
    }


    public static void SendSmsResponse(String event) {//
//        if(event.equals("温度超声波失灵")){
//            int errorNum=SPUtils.getInstance().getInt("errorEvent",1)+1;
//            SPUtils.getInstance().put("errorEvent",errorNum);
//            if(errorNum==20){//过滤，每20次再上报一次，因为超声和温度是同一个设备，读取了2次，实际上是10次上报一次
//                reportDeviceEvent("errorEvent","温度超声波失灵",2);
//                Log.i("警告","发送"+event);
//                SPUtils.getInstance().put("errorEvent",0);
//            }
//
//        }else {
//            int warnEvent=SPUtils.getInstance().getInt("warnEvent",1)+1;
//            SPUtils.getInstance().put("errorEvent",warnEvent);
//            if(warnEvent==3){//过滤
//                reportDeviceEvent("warnEvent",event,1);
//                Log.i("报警","发送"+event);
//                SPUtils.getInstance().put("errorEvent",0);
//            }
//            Log.i("报警","次数"+warnEvent);
//        }

    }
//    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//    public void startJobScheduler() {//servise保活
//        int jobId = 1;
//        @SuppressLint("JobSchedulerService") JobInfo.Builder jobInfo = new JobInfo.Builder(jobId, new ComponentName(getApplication(), MyService.class));
//        jobInfo.setPeriodic(10000);
//        jobInfo.setPersisted(true);
//        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
//        jobScheduler.schedule(jobInfo.build());
//    }

}
