陈力
2023-05-27 3cbf0a380d302bf1cf8d7e4aa4ff36d5dbb90adb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package android_serialport_api;
 
import android.util.Log;
 
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.lotaai.canguiayw.common.SettingConfig;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class SerialPortUtils {
    private static final String TAG = "SerialPortUtils";
    public boolean serialPortStatus = false; //是否打开串口标志
    public String data_;
    public boolean threadStatus; //线程状态,为了安全终止线程
 
    public SerialPort serialPort = null;
    public InputStream inputStream = null;
    public OutputStream outputStream = null;
 
    public static String[] getAllDevices() {
        SerialPortFinder serialPortFinder = new SerialPortFinder();
        String[] allDevices = serialPortFinder.getAllDevices();
        for (int i=0; i<allDevices.length; i++) {
            allDevices[i] = "/dev/" + allDevices[i];
            Log.d(TAG, "No." + (i+1) + " = " + allDevices[i]);
        }
        return allDevices;
    }
 
    /**
     * 打开串口
     * @return serialPort串口对象
     */
    public SerialPort openSerialPort(String path, int baudrate){
        try {
            serialPort = new SerialPort(new File(path), baudrate, 0);
            this.serialPortStatus = true;
            threadStatus = false; //线程状态
            //获取打开的串口中的输入输出流,以便于串口数据的收发
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
 
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    //判断进程是否在运行,更安全的结束进程
                    while (!threadStatus){
                        byte[] buffer = new byte[64];
                        int size; //读取数据的大小
                        try {
                            size = inputStream.read(buffer);
                            if (size > 0){
                                if (onDataReceiveListener!=null) {
                                    onDataReceiveListener.onDataReceive(buffer, size);
                                }
//                                LogUtils.i(TAG, "锁串口返回:" + ConvertUtils.bytes2HexString(buffer));
                            }
                        } catch (IOException e) {
                            LogUtils.e(TAG, "锁串口返回run: 数据读取异常:" +e.toString());
                        }
                    }
                }
            };
            SettingConfig.getInstance().getExecutor().execute(syncRunnable);
        } catch (IOException e) {
            LogUtils.e(TAG, "openSerialPort: 打开串口异常:" + e.toString());
            return serialPort;
        }
        LogUtils.i(TAG, "openSerialPort: 打开串口:" + path + ", 波特率:" + baudrate);
        return serialPort;
    }
 
    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        try {
            inputStream.close();
            outputStream.close();
 
            this.serialPortStatus = false;
            this.threadStatus = true; //线程状态
            serialPort.close();
        } catch (IOException e) {
            Log.e(TAG, "closeSerialPort: 关闭串口异常:"+e.toString());
            return;
        }
        Log.d(TAG, "closeSerialPort: 关闭串口成功");
    }
 
    /**
     * 发送串口指令(字符串)
     * @param data String数据指令
     */
    public void sendSerialPort(String data){
        byte[] sendData = data.getBytes(); //string转byte[]
        sendSerialPort(sendData);
    }
 
    public void sendSerialPort(byte[] sendData) {
        try {
            if (sendData==null){
                return;
            }
            this.data_ = new String(sendData);
            if (sendData.length > 0) {
                StringBuffer stringBuffer = new StringBuffer();
                for (int i=0; i<sendData.length; i++) {
                    stringBuffer.append(String.format("0x%02x", sendData[i]) + " ");
                }
//                LogUtils.i(TAG, "发送串口数据:" + stringBuffer.toString());
                outputStream.write(sendData);
                outputStream.flush();
            }
        } catch (IOException e) {
            LogUtils.e(TAG, "sendSerialPort: 串口数据发送失败:"+e.toString());
        }
    }
 
    //这是写了一监听器来监听接收数据
    public OnDataReceiveListener onDataReceiveListener = null;
    public interface OnDataReceiveListener {
        void onDataReceive(byte[] buffer, int size);
    }
    public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
        onDataReceiveListener = dataReceiveListener;
    }
}