package com.wdkl.ncs.s433.transbox;

import android.app.smdt.SmdtManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdkl.ncs.s433.transbox.common.Constants;
import com.wdkl.ncs.s433.transbox.receiver.NetworkConnectChangedReceiver;
import com.wdkl.ncs.s433.transbox.tcp.EventBusModel;
import com.wdkl.ncs.s433.transbox.tcp.TcpAction;
import com.wdkl.ncs.s433.transbox.tcp.TcpClient;
import com.wdkl.ncs.s433.transbox.tcp.TcpModel;
import com.wdkl.ncs.s433.transbox.tcp.TcpType;
import com.wdkl.ncs.s433.transbox.utils.AutoRebootUtil;
import com.wdkl.ncs.s433.transbox.utils.NetUtil;
import com.wdkl.ncs.s433.transbox.utils.SpeechUtil;
import com.wdkl.ncs.s433.transbox.utils.StringUtils;

import org.apache.commons.lang3.ArrayUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.CRC32;

public class MainActivity extends SerialPortActivity  {
    String TAG = "MainActivity";
    EditText mReception;
    ConnectivityManager connectivityManager;
    private SmdtManager smdtManager;

    //private final ExecutorService send433ThreadPool = Executors.newSingleThreadExecutor();
    //private Send433Thread send433Thread;
    private Map<String,String> s433Data = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册EventBus
        EventBus.getDefault().register(this);
        mReception = (EditText) findViewById(R.id.EditTextReception);
        final Button buttonSetup = (Button) findViewById(R.id.ButtonSetup);
        buttonSetup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
//                openNetworkDebug();
                startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            }
        });
        final Button rebootAppButton = (Button) findViewById(R.id.RebootApp);
        rebootAppButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AutoRebootUtil.restartApp();
            }
        });

        smdtManager = SmdtManager.create(this);

        this.init();
//        this.initReceive();
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        NetworkRequest request = builder.build();
        connectivityManager =(ConnectivityManager) getApplication().getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(request,callback);
    }

    private void init() {
        TextView settingInfo = (TextView) findViewById(R.id.setttingInfo);
        StringBuilder sb = new StringBuilder();
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Log.i("Application", "getSerialPort: " + sp.getString("serialDeivce", "/dev/ttyS2"));
        String path = sp.getString("serialDeivce", "/dev/ttyS2"); //sp.getString("DEVICE", "");
        int baudrate = Integer.decode(sp.getString("baudRate", "115200")); //Integer.decode(sp.getString("BAUDRATE", "-1"));
        int parity = Integer.decode(sp.getString("parity", "0"));
        int dataBits = Integer.decode(sp.getString("dataBits", "8"));
        int stopBits = Integer.decode(sp.getString("stopBits", "1"));
        String tcpServer = sp.getString("tcpServer", "120.77.212.146");
        Integer tcpServerPort = Integer.decode(sp.getString("tcpServerPort", "5080"));
        Constants.MAC_ADDR = NetUtil.getInstance().getMacAddress();
        String localIP = NetUtil.getInstance().getLocalIP();
        sb.append("串口号：" + path + "\n");
        sb.append("波特率：" + baudrate + "\n");
        sb.append("校验位：" + parity + "\n");
        sb.append("数据位：" + dataBits + "\n");
        sb.append("停止位：" + stopBits + "\n");
        sb.append("服务器地址：" + tcpServer + "\n");
        sb.append("服务器端口：" + tcpServerPort + "\n");
        sb.append("本机MAC地址：" + Constants.MAC_ADDR + "\n");
        sb.append("本机IP地址：" + localIP + "\n");
        sb.append("APP版本： V" + BuildConfig.VERSION_NAME);
        settingInfo.setText(sb.toString());
        Log.e(TAG, "init: "+ localIP);
        TextView tcpstatus = (TextView) findViewById(R.id.serialStatus);
        if (Constants.SERIAL_PORT_STATUS) {
            tcpstatus.setText("正常");
            tcpstatus.setTextColor(getResources().getColor(R.color.green));
        } else {
            tcpstatus.setText(Constants.SERIAL_PORT_FAIL_RESON);
            tcpstatus.setTextColor(getResources().getColor(R.color.red));
        }
        //初始化tcp
        if (Constants.NET_WORK_AVAILABLE) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(!TcpClient.getInstance().isRunning()) {
                        TcpClient.getInstance().init(tcpServer, tcpServerPort, 60);
                    }else{
                        TcpClient.getInstance().doConnect();
                    }
                }
            }).start();
        }

        SpeechUtil.getInstance().init(this, null);

        //默认打开网络调试
        openNetworkDebug();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        connectivityManager.unregisterNetworkCallback(callback);
//        unregisterReceiver(networkConnectChangedReceiver);
        SpeechUtil.getInstance().release();
    }

    @Override
    protected void onDataReceived(byte[] buffer, int size) {
        runOnUiThread(new Runnable() {
            public void run() {
                /*if (mReception != null) {
                    byte[] bytes = Arrays.copyOfRange(buffer, 0, size);
                    String receiveData = bytesToHex(bytes);
                    String receiveString = new String(bytes, 0, size);
                    Log.e("Application", "receiveData: " + receiveData);
                    if (receiveString.contains("\r") || receiveString.contains("\n")) {
                        Log.e("Application", "有回车键: ");
                    }
                    if (receiveData.startsWith("fe")) {
                        byte[] cardCode = ArrayUtils.subarray(bytes, 5, 9);
                        //小端字节顺序，需要将数组反转
                        ArrayUtils.reverse(cardCode);
                        String hex = bytesToHex(cardCode);
                        String s = String.format("%010d", Integer.valueOf(hex, 16));
                        Log.e("Application", "s: " + s);
                        Log.e("Application", "receiveString: " + receiveString);
                        Log.e("Application", "receiveData: " + receiveData);
                    }

                    if (receiveData.startsWith("fd") && receiveData.endsWith("df")) {
                        String mac = receiveData.substring(2,  receiveData.indexOf("df"));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        mReception.append(sdf.format(new Date()) + " 收到数据：" + mac + "\n");
                        //发送tcp消息
                        if (TcpClient.getInstance().isRunning()) {
                            TcpClient.getInstance().sendMsg(AlarmMessageUtil.getAlarmMessage(mac));
                        }

                    }

                }*/
            }
        });
    }

    @Override
    protected void onDataReceivedString(String data) {
        //$8C:FC:A0:F1:01:A7{"action":"ACK","type":"S433"}#
        Log.e(TAG, "receive 433 Data: " + data);

        /*if (BuildConfig.DEBUG) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mReception != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        mReception.append(sdf.format(new Date()) + " 收到数据：" + data + "\n");
                    }
                }
            });
        }*/

        try {
            if (data.startsWith("$") && data.endsWith("#")) {
                //只有收到的是ACK才转发服务器
                String tempData = data.substring(1, data.length() - 1);
                int sepIndex = tempData.indexOf("{");
                String mac = tempData.substring(0, sepIndex);
                String tcpData = tempData.substring(sepIndex);
                //Log.e("Application", "tempData: " + tempData + ", mac: " + mac + ", tcpData: " + tcpData);
                TcpModel tcpModel = TcpModel.getModelByJson(tcpData);
                if (tcpModel != null) {
                    if (TcpAction.S433Action.ACK == tcpModel.getAction()) {
                        //收到433回复后转发给服务器
                        JSONObject jsonData = new JSONObject();
                        jsonData.put("receiverMac", mac);
                        tcpModel.setData(jsonData);
                        TcpClient.getInstance().sendMsg(tcpModel.toJson());

                        //收到ack回复同时清除重发缓存
                        /*Iterator<Map.Entry<String, String>> iterator = s433Data.entrySet().iterator();
                        while (iterator.hasNext()) {
                            if (iterator.next().getKey().equals(mac)) {
                                Log.e(TAG, "收到ack回复,清除缓存mac: " + mac);
                                iterator.remove();
                            }
                        }*/
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void openNetworkDebug() {
        try {
            Process p = Runtime.getRuntime().exec("su");
            OutputStream op = p.getOutputStream();
            DataOutputStream os = new DataOutputStream(op);
//            os.writeBytes("/system/bin/sh\n");
            os.writeBytes("setprop service.adb.tcp.port 5555\n");
            os.writeBytes("stop adbd\n");
            os.writeBytes("start adbd\n");
            os.writeBytes("exit\n");
            os.flush();
            os.close();
            op.close();
            Log.i("openNetworkDebug", "打开调试:---- ");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();

    }

    /**
     * NFC 读取卡号
     *
     * @param bytes
     * @return
     */
    private String bytesToKeyCode(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%c", b));
        }
        return sb.toString();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(EventBusModel eventBusModel) {
        switch (eventBusModel.getMsgType()) {
            case Constants.EVENT_TCP_STATE: {
                updateTcpStatus();
                break;
            }
            case Constants.NET_WORK_STATUS_CHANGE: {
                if ((int) eventBusModel.getMsg() > -1) {
                    this.init();
                }
                break;
            }
            case  Constants.NET_WORK_AVAILABLE_CHANGE:{
                Log.e("TAG", "onMoonEvent: "+(boolean) eventBusModel.getMsg());
                if((boolean) eventBusModel.getMsg()){
                    this.init();
                }else{
                    if (TcpClient.getInstance().isRunning()){
                        TcpClient.getInstance().closeClient();
                    }
                }
                break;
            }

            case Constants.EVENT_TCP_MSG:
                //处理tcp消息
                TcpModel tcpModel = (TcpModel) eventBusModel.getMsg();
                handleTcpMsg(tcpModel);
                break;
            case Constants.EVENT_RESTART_APP:
                //restart app
                AutoRebootUtil.restartApp();
                break;
        }
    }

    NetworkConnectChangedReceiver networkConnectChangedReceiver;

    private void initReceive() {
        //网络状态广播
        networkConnectChangedReceiver = new NetworkConnectChangedReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(networkConnectChangedReceiver, intentFilter);
    }


    private void updateTcpStatus() {
        TextView tcpstatus = (TextView) findViewById(R.id.tcpStatus);
        if (Constants.TCP_CONNCETED) {
            tcpstatus.setText("正常");
            tcpstatus.setTextColor(getResources().getColor(R.color.green));
        } else {
            tcpstatus.setText("未连接");
            tcpstatus.setTextColor(getResources().getColor(R.color.red));
        }

    }

    private synchronized void handleTcpMsg(final TcpModel tcpModel) {
        //返回ack
        TcpModel respondModel = new TcpModel();
        respondModel.setType(TcpType.S433);
        respondModel.setAction(TcpAction.S433Action.ACK);
        respondModel.setData(Constants.MAC_ADDR);
        TcpClient.getInstance().sendMsg(respondModel.toJson());

        try {
            switch (tcpModel.getType()) {
                case TIME:
                    if (tcpModel.getAction() == TcpAction.TimeAction.SYNC) {
                        //同步时间
                        //action: SYNC_TIME, data: {"time_zone":"PRC","time":"1683626639"}
                        JSONObject jsonObject = JSON.parseObject(tcpModel.getData().toString());
                        String timezone = jsonObject.getString("time_zone");
                        long time = Long.parseLong(jsonObject.getString("time")) * 1000;

                        setSysTime(time, timezone);
                    }
                    break;
                case DEVICE:
                    if (tcpModel.getAction() == TcpAction.DeviceAction.APP_UPDATE) {
                        //
                    } else if (tcpModel.getAction() == TcpAction.DeviceAction.RESTART) {
                        SpeechUtil.getInstance().stopSpeak();
                        AutoRebootUtil.restartApp();
                    } else if (tcpModel.getAction() == TcpAction.DeviceAction.REBOOT) {
                        AutoRebootUtil.reboot();
                    }
                    break;
                case SIDE:
                    //
                    break;
                case S433:
                    //$8C:FC:A0:F1:01:A7{"action":"SOS_CALL","type":"S433","data":{"title":"12房紧急呼叫"}}#
                    //{"action":"SYNC_TIME","data":{"time_zone":"Asia/Shanghai","receiverMac":"8c:fc:a0:f1:01:de","time":1684909246},"type":"S433"}
                    //{"action":"CALL","data":{"title":"11房-21床呼叫","receiverMacs":["8c:fc:A0:F1:01:A7","8c:fc:a0:f1:01:de"]},"toId":489,"type":"S433"}
                    JSONObject s433Send = new JSONObject();
                    s433Send.put("action", tcpModel.getAction());
                    JSONObject data = new JSONObject();
                    JSONObject tcpData = null;
                    if (tcpModel.getData() != null) {
                        tcpData = JSON.parseObject(tcpModel.getData().toString());
                    }

                    if (tcpModel.getAction() == TcpAction.S433Action.SOS_CALL
                            || tcpModel.getAction() == TcpAction.S433Action.CALL
                            || tcpModel.getAction() == TcpAction.S433Action.CANCEL) {
                        //解析数据并通过433发射出去
                        if (tcpData != null) {
                            //语音播报
                            String title = tcpData.getString("title");
                            if (tcpModel.getAction() == TcpAction.S433Action.SOS_CALL || tcpModel.getAction() == TcpAction.S433Action.CALL) {
                                if (!TextUtils.isEmpty(title)) {
                                    if ("reboot".equals(title)) {
                                        //重启点阵屏
                                        SpeechUtil.getInstance().stopSpeak();
                                    } else if (title.startsWith("led")) {
                                        //修改点阵屏IP
                                    } else if (title.startsWith("host")) {
                                        //修改Android控制板IP
                                    } else {
                                        //点阵屏显示
                                        String speech = StringUtils.appendSpace(title);
                                        SpeechUtil.getInstance().addSpeech(speech, false);
                                    }
                                }
                            } else if (tcpModel.getAction() == TcpAction.S433Action.CANCEL) {
                                if (TextUtils.isEmpty(title)) {
                                    SpeechUtil.getInstance().stopSpeak();
                                } else {
                                    String speech = StringUtils.appendSpace(title);
                                    SpeechUtil.getInstance().removeSpeak(speech);
                                }
                            }

                            if (tcpData.getString("receiverMacs") != null) {
                                //给多个点阵屏发送
                                /*JSONArray macs = JSON.parseArray(tcpData.getString("receiverMacs"));
                                data.put("title", title);
                                s433Send.put("data", data);
                                for (int i = 0; i < macs.size(); i++) {
                                    send433DataByMac((String) macs.get(i), s433Send.toJSONString());
                                }*/

                                send433Data(tcpModel.toJson());
                            } else if (tcpData.getString("receiverMac") != null) {
                                //给单个点阵屏发送
                                String mac = tcpData.getString("receiverMac");
                                data.put("title", title);
                                s433Send.put("data", data);

                                //send433DataByMac(mac, s433Send.toJSONString());
                                send433Data(tcpModel.toJson());
                            }
                        }
                    } else if (tcpModel.getAction() == TcpAction.S433Action.DATA) {
                        //屏参
                        if (tcpData != null) {
                            data.put("led_style", tcpData.getString("led_style"));
                            data.put("led_size", tcpData.getIntValue("led_size"));
                            data.put("volume", tcpData.getIntValue("volume"));

                            if (tcpData.getString("receiverMac") != null) {
                                //给单个点阵屏发送
                                String mac = tcpData.getString("receiverMac");
                                s433Send.put("data", data);

                                //send433DataByMac(mac, s433Send.toJSONString());
                                send433Data(tcpModel.toJson());
                            }
                        }
                    } else if (tcpModel.getAction() == TcpAction.S433Action.SYNC_TIME) {
                        // 时间同步
                        if (tcpData != null) {
                            data.put("time", tcpData.getLong("time").toString());
                            data.put("time_zone", tcpData.getString("time_zone"));

                            if (tcpData.getString("receiverMac") != null) {
                                //给单个点阵屏发送
                                String mac = tcpData.getString("receiverMac");
                                s433Send.put("data", data);

                                //send433DataByMac(mac, s433Send.toJSONString());
                                send433Data(tcpModel.toJson());
                            }
                        }
                    } else if (tcpModel.getAction() == TcpAction.S433Action.EXIST) {
                        if (tcpData != null) {
                            if (tcpData.getString("receiverMac") != null) {
                                //给单个点阵屏发送
                                String mac = tcpData.getString("receiverMac");

                                //send433DataByMac(mac, s433Send.toJSONString());
                                send433Data(tcpModel.toJson());
                            }
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            Log.e(TAG, "handleTcpMsg exception");
            e.printStackTrace();
        }
    }

    private void send433DataByMac(final String mac, final String data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //$8C:FC:A0:F0:01:3E{"action":"CALL","data":{"title":"你好世界"}}#
                    //拼接头尾
                    String msg = "$" + mac + data + "#";
                    Log.e(TAG, "send 433 msg ==>" + msg);
                    //433发送
                    sendMsg(msg, mOutputStream, 120);
                    s433Data.put(mac, data);

                    //若没有收到ack回复则再次发送
                    for (int i = 0; i < 2; i++) {
                        Thread.sleep(2000);
                        if (s433Data.containsKey(mac)) {
                            //再次发送
                            sendMsg(msg, mOutputStream, 120);
                        } else {
                            return;
                        }
                    }

                    Log.e(TAG, "send 2 times end: " + mac);
                    //两次发送完成后清除该缓存
                    s433Data.remove(mac);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void send433Data(final String data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //$8C:FC:A0:F0:01:3E{"action":"CALL","data":{"title":"你好世界"}}#
                    //{"action":"CANCEL","data":{"receiverMac":"8C:FC:A0:F0:01:7A"},"type":"S433"}
                    //拼接头尾
                    String msg = "$" + data + "#";
                    //Log.e(TAG, "send 433 msg ==>" + msg);
                    //433发送
                    sendMsg(msg, mOutputStream, 120);
                    Thread.sleep(1500);
                    sendMsg(msg, mOutputStream, 120);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /*private void send433Data() {
        if (send433Thread == null) {
            send433Thread = new Send433Thread();
        }
        send433ThreadPool.execute(send433Thread);
    }

    public class Send433Thread implements Runnable {
        @Override
        public void run() {
            if (s433Data.size() > 0) {
                Iterator<String> iterator = s433Data.iterator();
                while (iterator.hasNext()) {
                    try {
                        //拼接头尾
                        String data = "$" + iterator.next() + "#";
                        Log.e(TAG, "send 433 data ==>" + data);
                        //433发送
                        sendMsg(data, mOutputStream, 120);
                        iterator.remove();

                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }*/

    /**
     * 消息分包发送，包格式如下：每个包可传输的数据内容是发送缓冲区的大小减去21个字节。21个字节为包控制数据
     * 保证接收端接收后可校验包的正确性。假设发送缓冲区是60个字节，那么每个包最多可发送39个字节的消息数据，
     * 因为包已经校验准确性，接收端只需合并包内容数据即可。消息id使用整个消息内容的crc校验值
     * 帧头 有效数据长度 包序 总包数 消息id 包内容        crc包校验
     * 2B      1B      1B  1B     8B    MAX-18          8B
     *
     * @param msg
     * @param outputStream 输出
     * @param packageLength 芯片发射分包长度（60，修改后为120）
     */
    private synchronized void sendMsg(String msg, OutputStream outputStream, int packageLength) throws IOException {

        char[] alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_".toCharArray();

        try {
            byte[] msgBytes = msg.getBytes();
            //msgBytesLength 要发送的消息总长度，
            int msgBytesLength = msgBytes.length;
            //packageContentLength 每个包可发送的长度
            int packageContentLength = packageLength - 21;
            //要发送包的个数
            int packages = msgBytesLength / packageContentLength + (msgBytesLength % packageContentLength != 0 ? 1 : 0);
//            String msgId = NanoIdUtils.randomNanoId(new Random(), alphabet, 5);
            CRC32 crc32Msg = new CRC32();
            crc32Msg.update(msgBytes);
            long msgId = crc32Msg.getValue();
//            byte[] packageContent = new byte[packageContentLength];
            byte[] start = String2Byte("AA55");

            Log.e(TAG, "send 433 msg ==>" + msg);
            for (int i = 0; i < packages; i++) {
                ByteBuffer buffer = ByteBuffer.allocate(packageLength - 8); //校验数据之前的数据
                buffer.put(start);
                //消息内容实际数据长度
                byte contentLength = (byte) Math.min(packageContentLength, msgBytesLength - i * packageContentLength);
                buffer.put(contentLength);
                //包序
                buffer.put((byte) (i + 1));
                //总包数
                buffer.put((byte) packages);
                //消息id字节
                byte[] msgIdBytes = ByteBuffer.allocate(8).putLong(msgId).array(); //msgId.getBytes();
                buffer.put(msgIdBytes);
                //包内容
                byte[] subarray = ArrayUtils.subarray(msgBytes, i * packageContentLength, i * packageContentLength + contentLength);
                ByteBuffer wrap = ByteBuffer.allocate(packageContentLength).put(subarray);
                if (subarray.length < packageContentLength) {
                    wrap.put(new byte[packageContentLength - subarray.length]);
                }
                buffer.put(wrap.array());
                CRC32 crc32 = new CRC32();
                //计算校验
                crc32.update(buffer.array());
                Log.i(TAG, "sendMsg: "+ArrayUtils.toString(buffer.array()));
                long value = crc32.getValue();
                Log.i(TAG, "Crc: " + value);
                byte[] crc = ByteBuffer.allocate(8).putLong(value).array();
                ByteBuffer bufferSend = ByteBuffer.allocate(packageLength);
                //把crc校验加入到包尾
                bufferSend.put(buffer.array());
                bufferSend.put(crc);
                //发送包
                Log.i(TAG, "sendMsg: 发送："+ArrayUtils.toString(bufferSend.array()));
                outputStream.write(bufferSend.array());
            }


        } catch (IOException e) {
            throw e;
        }

    }


    /**
     * 16进制字符串转换成byte数组
     */
    public byte[] String2Byte(String s) {
        s = s.replace(" ", "");
        s = s.replace("#", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return baKeyword;
    }


    private ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback(){
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);
            Log.e(TAG, "onAvailable: ");
            Constants.NET_WORK_AVAILABLE=true;
            EventBusModel eventBusModel = new EventBusModel(Constants.NET_WORK_AVAILABLE_CHANGE,Constants.NET_WORK_AVAILABLE);
            EventBus.getDefault().post(eventBusModel);
        }

        @Override
        public void onLost(@NonNull Network network) {
            Log.e(TAG, "onLost: "+NetUtil.getInstance().getNetAvailable());
            super.onLost(network);
            if(NetUtil.getInstance().getNetAvailable()){
                Constants.NET_WORK_AVAILABLE=true;
            }else{
                Constants.NET_WORK_AVAILABLE=false;
            }
            EventBusModel eventBusModel = new EventBusModel(Constants.NET_WORK_AVAILABLE_CHANGE,Constants.NET_WORK_AVAILABLE);
            EventBus.getDefault().post(eventBusModel);
        }

//        @Override
//        public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
//            super.onCapabilitiesChanged(network, networkCapabilities);
//            Log.e(TAG, "onCapabilitiesChanged: "+networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED));
////            if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)){
////                Constants.NET_WORK_AVAILABLE=true;
////                EventBusModel eventBusModel = new EventBusModel(Constants.NET_WORK_AVAILABLE_CHANGE,Constants.NET_WORK_AVAILABLE);
////                EventBus.getDefault().post(eventBusModel);
////            }
//        }
    };


    /**
     * 设置系统时间
     *
     * @param time
     */
    private void setSysTime(long time, String timeZone) {
        try {
            if (smdtManager != null) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date(time));
                smdtManager.setTime(getApplicationContext(),
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH)+1,
                        calendar.get(Calendar.DAY_OF_MONTH),
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE));

                Log.e(TAG, "set sys time: " + time);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}