isopen = false;
}
return isopen;
}
/**
-
打开串口
-
@param device 串口设备文件
-
@param baudRate 波特率
-
@param parity 奇偶校验,0 None(默认); 1 Odd; 2 Even
-
@param dataBits 数据位,5 ~ 8 (默认8)
-
@param stopBit 停止位,1 或 2 (默认 1)
-
@param flags 标记 0(默认)
-
@return
*/
public boolean open(File device, int baudRate, int parity, int dataBits,
int stopBit, int flags) {
boolean isopen = false;
if (isFlagSerial) {
LogUtil.e(TAG, “串口已经打开,打开失败”);
return false;
}
try {
serialPort = new SerialPort(device, baudRate, parity, dataBits, stopBit, flags);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
receive();
isopen = true;
isFlagSerial = true;
} catch (Exception e) {
e.printStackTrace();
isopen = false;
}
return isopen;
}
/**
- 关闭串口
*/
public boolean close() {
if (!isFlagSerial) {
LogUtil.e(TAG, “串口关闭失败”);
return false;
}
boolean isClose = false;
LogUtil.e(TAG, “关闭串口”);
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (serialPort != null) {
serialPort.close();
}
isClose = true;
isFlagSerial = false;//关闭串口时,连接状态标记为false
} catch (IOException e) {
e.printStackTrace();
isClose = false;
}
return isClose;
}
/**
- 发送16进制,串口指令
*/
public void sendHexString(String data) {
if (!isFlagSerial) {
LogUtil.e(TAG, “串口未打开,发送失败” + data);
return;
}
try {
outputStream.write(ByteUtil.hex2byte(data));
outputStream.flush();
LogUtil.e(TAG, “sendSerialData:” + data);
} catch (IOException e) {
e.printStackTrace();
LogUtil.e(TAG, “发送指令出现异常”);
}
}
/**
- 发送ASCII,串口指令
*/
public void sendAsciiString(String data) {
if (!isFlagSerial) {
LogUtil.e(TAG, “串口未打开,发送失败” + data);