赞
踩
import cn.yumakeji.lib_serialportapi.SerialPort;
import cn.yumakeji.lib_serialportapi.callback.SerialCallBack;
import cn.yumakeji.lib_serialportapi.utils.ByteUtil;
import cn.yumakeji.lib_serialportapi.utils.LogUtil;
/**
* 数据操作封装
*/
public class SerialPortUtil {
public static String TAG = "serial_port";
/**
* 标记当前串口状态(true:打开,false:关闭)
**/
public boolean isFlagSerial = false;
public SerialPort serialPort = null;
public InputStream inputStream = null;
public OutputStream outputStream = null;
public Thread receiveThread = null;
private SerialPortUtil() {
}
public static SerialPortUtil getInstance() {
return SingletonHolder.sInstance;
}
//静态内部类
private static class SingletonHolder {
private static final SerialPortUtil sInstance = new SerialPortUtil();
}
/**
* 打开串口
* <p>
* 串口有五个重要的参数:串口设备名,波特率,检验位,数据位,停止位
* 其中检验位一般默认位NONE,数据位一般默认为8,停止位默认为1
*
* @param device 串口设备的绝对路径
* @param baudrate 波特率
* @param flags 校验位
* @return
*/
public boolean open(File device, int baudrate, int flags) {
boolean isopen = false;
if (isFlagSerial) {
LogUtil.e(TAG, "串口已经打开,打开失败");
return false;
}
try {
serialPort = new SerialPort(device, baudrate, flags);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
receive();
isopen = true;
isFlagSerial = true;
} catch (Exception e) {
e.printStackTrace();
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);
return;
}
try {
outputStream.write(data.getBytes("gbk"));
outputStream.flush();
LogUtil.e(TAG, "sendSerialData:" + data);
} catch (IOException e) {
e.printStackTrace();
LogUtil.e(TAG, "发送指令出现异常");
}
}
/**
* 接收串口数据的方法
*/
public void receive() {
if (receiveThread != null && !isFlagSerial) {
return;
}
receiveThread = new Thread() {
@Override
public void run() {
while (isFlagSerial) {
try {
byte[] readData = new byte[256];
if (inputStream == null) {
return;
}
int size = inputStream.read(readData);
if (size > 0 && isFlagSerial) {
// strData = ByteUtil.byteToStr(readData, size);
if (onDataReceiveListener != null) {
onDataReceiveListener.onSerialPortData(readData, size);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
receiveThread.start();
}
private SerialCallBack onDataReceiveListener;
public void setOnDataReceiveListener(SerialCallBack onDataReceiveListener) {
this.onDataReceiveListener = onDataReceiveListener;
}
}
public class MainActivity extends AppCompatActivity implements SerialCallBack {
private static final int REQUESE_CODE = 0xFFA;
private CheckBox mCbHex;
private CheckBox mCbAscii;
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
SerialPortUtil.getInstance().close();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
HxgPermissionHelper.requestPermissionsResult(this, requestCode, permissions);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCbHex = findViewById(R.id.cb_hex);
mCbAscii = findViewById(R.id.cb_ascii);
mCbHex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mCbAscii.setChecked(false);
} else {
mCbAscii.setChecked(true);
}
}
});
mCbAscii.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mCbHex.setChecked(false);
} else {
mCbHex.setChecked(true);
}
}
});
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
HxgPermissionHelper.with(this)
.requestCode(REQUESE_CODE)
.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.request();
SerialPortUtil.getInstance().setOnDataReceiveListener(this);
}
@HxgPermissionSuccess(requestCode = REQUESE_CODE)
private void success() {
Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
LogUtil.d(AppUtils.isRooted() + "");
}
@HxgPermissionFail(requestCode = REQUESE_CODE)
private void fail() {
Toast.makeText(this, "权限获取失败", Toast.LENGTH_SHORT).show();
}
/**
* 打开串口
*
* @param view
*/
public void onOpenClick(View view) {
boolean open = SerialPortUtil.getInstance().open(new File("/dev/ttyS0"), 38400, 0);
if (open) {
LogUtil.d("串口已经打开");
} else {
LogUtil.d("串口打开失败");
}
}
/**
* 发送数据
*
* @param view
*/
public void onSendClick(View view) {
String trim = ((EditText) findViewById(R.id.et_input)).getText().toString().trim();
if (TextUtils.isEmpty(trim)) {
Toast.makeText(AppGlobals.getApplication().getApplicationContext(), "请输入发送内容", Toast.LENGTH_LONG).show();
return;
}
if (!mCbHex.isChecked() && !mCbAscii.isChecked()) {
Toast.makeText(AppGlobals.getApplication().getApplicationContext(), "请选择数据类型", Toast.LENGTH_LONG).show();
return;
}
if (mCbHex.isChecked()) {
SerialPortUtil.getInstance().sendHexString(trim);
}
if (mCbAscii.isChecked()) {
SerialPortUtil.getInstance().sendAsciiString(trim);
}
}
/**
* 关闭串口
*
* @param view
*/
public void onCloseClick(View view) {
boolean close = SerialPortUtil.getInstance().close();
if (close) {
LogUtil.d("串口已经关闭");
}
}
/**
* 获取串口数据
*
* @param view
*/
public void onInfoClick(View view) {
SerialPortFinder spf = new SerialPortFinder();
if (spf.getAllDevices() != null && spf.getAllDevices().length > 0) {
LogUtil.e(String.valueOf(Arrays.asList(spf.getAllDevicesPath())));
}
if (spf.getAllDevicesPath() != null && spf.getAllDevicesPath().length > 0) {
LogUtil.e(String.valueOf(Arrays.asList(spf.getAllDevicesPath())));
}
}
/**
* 接收数据
*
* @param buffer
* @param size
*/
@Override
public void onSerialPortData(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mCbHex.isChecked()) {
LogUtil.d(ByteUtil.byteToStr(buffer, size));
((TextView) findViewById(R.id.tv_read_message)).setText(ByteUtil.byteToStr(buffer, size));
}
if (mCbAscii.isChecked()) {
try {
LogUtil.d(new String(buffer, 0, size,"gbk"));
// ((TextView) findViewById(R.id.tv_read_message)).setText(new String(buffer, 0, size));
((TextView) findViewById(R.id.tv_read_message)).setText(new String(buffer, 0, size,"gbk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
});
}
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER"/>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。