串口相关 二

注意该代码并不能直接运行,仅仅起到展示效果

EventBus.getDefault().post(new EventBusBean(Constants.EventBus.SERIAL_PORT_CMD, new UartEvent(buf)));
此处代码可以负责发送读取到的信息发送出去
项目内部可以开启一个service 在service内部接受该信息,并执行业务逻辑处理;


import android.os.SystemClock;
import android.util.Log;

import com.hjq.toast.ToastUtils;
import com.qsinong.qlog.QLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.HexUtil;
import cn.pda.serialport.SerialPort;



public class SerialPortlUtils {
    private final String TAG = "SerialPortUtils";
    private String path = "/dev/ttyMT1";
    private int baudrate = 115200;
    private int port = 13; // COM13
    public boolean serialPortStatus = false; //是否打开串口标志
    public boolean threadStatus; //线程状态,为了安全终止线程
    private static SerialPortlUtils instance;
    public SerialPort serialPort = null;
    public InputStream inputStream = null;
    public OutputStream outputStream = null;

    public SerialPortlUtils() {
        openSerialPort();
    }

    public static SerialPortlUtils getInstance() {
        synchronized (SerialPortlUtils.class) {
            if (instance == null) {
                instance = new SerialPortlUtils();
            }
        }
        return instance;
    }

    /**
     * 打开串口
     *
     * @return serialPort串口对象
     */
    public SerialPort openSerialPort() {
        if (serialPort == null) {
            Log.d(TAG, "openSerialPort-------------");
            try {
                //serialPort = new SerialPort(new File(path), baudrate, 0);
                serialPort = new SerialPort(port, baudrate, 0);
                serialPort.power3v3on();
                this.serialPortStatus = true;
                threadStatus = false; //线程状态
                //获取打开的串口中的输入输出流,以便于串口数据的收发
                inputStream = serialPort.getInputStream();
                outputStream = serialPort.getOutputStream();
                new ReadThread((FileInputStream) inputStream).start(); //开始线程监控是否有数据要接收
            } catch (Throwable e) {
                QLog.e("openSerialPort: 打开串口异常:" + Log.getStackTraceString(e));
                return serialPort;
            }
            QLog.i("openSerialPort: 打开串口成功");
        }
        return serialPort;
    }

    /**
     * 时间
     */
    public void updateTime() {
        long timestamp = (System.currentTimeMillis() / 1000);
        //long timestamp = 1650009677;
        String strCommand = "A5000100000200080030000400000000AA5A";
        byte[] buffer = DataTools.HexString2Bytes(strCommand);
        timestamp += 3600 * 8;
        buffer[12] = (byte) (timestamp >> 24);
        buffer[13] = (byte) (timestamp >> 16);
        buffer[14] = (byte) (timestamp >> 8);
        buffer[15] = (byte) (timestamp & 0xff);
        byte bcc = DataTools.makeBCC(buffer, buffer.length);
        buffer[buffer.length - 2] = bcc;
        sendSerialPort(buffer);
        QLog.i("SerialPort_send_cmd_log", String.format(BaseApplication.i().getResources().getString(R.string.SerialPort_send_cmd), "同步时间", "cmd:"+ DataTools.Bytes2HexString(buffer, buffer.length))+";---时间戳:"+timestamp);
    }
   
    /**
     * 单开一线程,来读数据
     */
    private class ReadThread extends Thread {
        FileInputStream inputStream;

        ReadThread(FileInputStream inputStream) {
            this.inputStream = inputStream;
            this.setPriority(MAX_PRIORITY);
        }

        @Override
        public void run() {
            super.run();
            int maxLength = 1024 * 1024;
            int curLength = 0;
            int size = 0;
            byte[] buffer = new byte[maxLength];
            //判断进程是否在运行,更安全的结束进程
            while (!threadStatus) {
                try {
                    int available = inputStream.available();
                    if (available > 0) {
                        if (available > maxLength - curLength) {
                            available = maxLength - curLength;
                        }
                        int left = available;
                        while (left > 0) {
                            size = inputStream.read(buffer, curLength, left);
                            if (size > 0) {
                                curLength += size;
                                left -= size;
                            }
                            SystemClock.sleep(1);
                        }
                    }
                } catch (IOException e) {
                    QLog.d("run: 数据读取异常:" + e.toString());
                } finally {
                }
                if (curLength > 0) {
                    boolean flag = false;
                    while (!flag) {
                        int sPos = 0;
                        while (sPos < curLength && (buffer[sPos] & 0xff) != 0xa5) sPos += 1;
                        if (sPos >= curLength) {
                            curLength = 0;
                            flag = true;
                        } else {
                            int ePos = sPos + 1;
                            while (ePos < curLength && (buffer[ePos] & 0xff) != 0x5a) ePos += 1;
                            if (ePos >= curLength) {
                                if (sPos > 0) {
                                    curLength -= sPos;
                                    System.arraycopy(buffer, sPos, buffer, 0, curLength);
                                }
                                break;
                            } else {
                                int factLength = ePos - sPos + 1;
                                byte[] data = new byte[factLength];
                                System.arraycopy(buffer, sPos, data, 0, factLength);
                                byte[] buf = DataTools.transFrom(data);
                                if (DataTools.checkBCC(buf, buf.length)) {

                                    UartEvent event = new UartEvent(buf);
//                                    statisticsOnSecond(event);
                                    Log.d(TAG, "run: 收到全部发到该设备的指令"+ DataTools.Bytes2HexString(buf, buf.length) +" cmd指令为:="+event.cmd);
                                    if (event.cmd == Constants.SerialPortCmd.UPGRAD){
                                        QLog.i("SerialPort_send_cmd_log", String.format(BaseApplication.i().getResources().getString(R.string.SerialPort_send_cmd), "收到", DataTools.Bytes2HexString(DataTools.transTo(buf), DataTools.transTo(buf).length)));
                                        if (data[2] == 0x02){
                                        }
                                    }
                                    /**
                                     * 除升级指令外其他全部发送到对应页面接收处理
                                     */
                                    EventBus.getDefault().post(new EventBusBean(Constants.EventBus.SERIAL_PORT_CMD, new UartEvent(buf)));
                                }
                                curLength -= ePos + 1;
                                System.arraycopy(buffer, ePos + 1, buffer, 0, curLength);
                            }
                        }
                    }
                }
                SystemClock.sleep(1);
            }
        }


    }


}```

你可能感兴趣的:(硬件对接,Android,Android资源分享,串口,android,物联网)