|
|
|
@ -8,13 +8,22 @@ import java.io.File;
|
|
|
|
|
import java.io.IOException;
|
|
|
|
|
import java.io.InputStream;
|
|
|
|
|
import java.io.OutputStream;
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @author by AllenJ on 2018/4/20.
|
|
|
|
|
*
|
|
|
|
|
* <p>
|
|
|
|
|
* 通过串口用于接收或发送数据
|
|
|
|
|
*/
|
|
|
|
|
public class SerialPortUtil {
|
|
|
|
|
/**
|
|
|
|
|
* 串口名称
|
|
|
|
|
*/
|
|
|
|
|
private static final String DEVICE_PATH = "/dev/ttyMSM1";
|
|
|
|
|
/**
|
|
|
|
|
* 串口比特率
|
|
|
|
|
*/
|
|
|
|
|
private static final int DEVICE_BIT_RATE = 115200;
|
|
|
|
|
private SerialPort serialPort = null;
|
|
|
|
|
private InputStream inputStream = null;
|
|
|
|
|
private OutputStream outputStream = null;
|
|
|
|
@ -28,13 +37,12 @@ public class SerialPortUtil {
|
|
|
|
|
public void openSerialPort() {
|
|
|
|
|
try {
|
|
|
|
|
// 设置当前设备SU命令的位置
|
|
|
|
|
SerialPort.setSuPath("/system/xbin/su");
|
|
|
|
|
serialPort = new SerialPort(new File("/dev/ttyS0"), 9600, 0);
|
|
|
|
|
// SerialPort.setSuPath("/system/xbin/su");
|
|
|
|
|
serialPort = new SerialPort(new File(DEVICE_PATH), DEVICE_BIT_RATE, 0);
|
|
|
|
|
//调用对象SerialPort方法,获取串口中"读和写"的数据流
|
|
|
|
|
inputStream = serialPort.getInputStream();
|
|
|
|
|
outputStream = serialPort.getOutputStream();
|
|
|
|
|
isStart = true;
|
|
|
|
|
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
}
|
|
|
|
@ -58,7 +66,6 @@ public class SerialPortUtil {
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
@ -69,7 +76,7 @@ public class SerialPortUtil {
|
|
|
|
|
*/
|
|
|
|
|
public void sendSerialPort(String data) {
|
|
|
|
|
try {
|
|
|
|
|
byte[] sendData = DataUtils.HexToByteArr(data);
|
|
|
|
|
byte[] sendData = data.getBytes(StandardCharsets.US_ASCII);
|
|
|
|
|
outputStream.write(sendData);
|
|
|
|
|
outputStream.flush();
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
@ -100,10 +107,9 @@ public class SerialPortUtil {
|
|
|
|
|
try {
|
|
|
|
|
int size = inputStream.read(readData);
|
|
|
|
|
if (size > 0) {
|
|
|
|
|
String readString = DataUtils.ByteArrToHex(readData, 0, size);
|
|
|
|
|
// EventBus.getDefault().post(readString);
|
|
|
|
|
String readString = new String(readData, 0, size, StandardCharsets.US_ASCII);
|
|
|
|
|
Log.d("wangym", "got msg = "+ readString);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
}
|
|
|
|
|