关于串口连接那些事儿(16进制指令)

第一次接触这玩意儿 ,表示蒙蔽了好一段时间 ,还好有前辈指点 , 记录此文 

首先准备串口连接(有线) 的库  点击下载

Android Studio

你首先得把库"拉进来" 像这样


博主用的是AS3.1的版本 complete已经过时 所以使用implementation 

eclipse

e........ 今晚吃烧烤怎么样?


然后再设置读写权限


然后.......上代码:

首先你在Application 里面初始化

	//存储设备信息
	private void initSericalPort(){
		
		//将串口数据存进轻量级
		SPUtil.putString(DEVICE, "/dev/ttyS3");
		SPUtil.putString(FOOT, "/dev/ttyS2");
		SPUtil.putString(BAUDRATE, "9600");
		
		initDeviceSericalPort();
	}
	
	//初始化串口
	private void initDeviceSericalPort(){
		if (mDeviceSerialPort == null) {
			mDeviceSerialPort = openDeviceSerialPort();//得到已经初始化的串口
		}
		//赋值给设备输出协议中的输入输出流 以便使用
		DeviceOutputProtocol.initOutputProtocol(mDeviceOutputStream, mDeviceInputStream);
	}
	
	//设备打开串口
	private SerialPort openDeviceSerialPort(){
		try {
			mDeviceSerialPort = getDeviceSerialPort(); //获取设备串口
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (mDeviceSerialPort != null) {
			mDeviceInputStream = mDeviceSerialPort.getInputStream();//得到串口输入流
			mDeviceOutputStream = mDeviceSerialPort.getOutputStream();//得到串口输出流
		} else {
			ToastUtil.w(R.string.toast_connect_device);//未连接设备
		}
		
		
		return mDeviceSerialPort;
	}
	
	//得到设备串口数据
	private SerialPort getDeviceSerialPort() throws SecurityException,IOException ,InvalidParameterException{
		if (mDeviceSerialPort == null) {
			/* Read serial port parameters 读取串口参数的轻量级存储对象*/
			SharedPreferences sp = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
			//获得串口通信地址
			String path = sp.getString(DEVICE, "");
			//将波特率转为整数
			int baudrate = Integer.decode(sp.getString(BAUDRATE, "-1"));
			
			/* Check parameters 检查参数是否为空 */
			if ((path.length() == 0) || (baudrate == -1)) {
//				throw new InvalidParameterException();
				return null;
			}
			
			/* Open the serial port 确定串口携带参数开启 */
			if (mDeviceSerialPort == null)
				mDeviceSerialPort = new SerialPort(new File(path), baudrate, 0);
		}
		return mDeviceSerialPort;
	}
	

然后写与设备的交互 就像HTTP那样  hexNumStr 是16进制命令 listener是回调接口

 /**
     * 十六进制码的输出,完成读写之后的回调
     *
     * @param hexNumStr
     */
    public static void hexDeviceOutput(final String hexNumStr, OutputStream outputStream, InputStream inputStream, OnIOCompleteListener listener) {
        Observable.create((ObservableOnSubscribe<DataBuffer>) emitter -> {
            synchronized (APP.sDeviceLock) {
                byte[] outputBuffer = new byte[1];
                byte[] inputBuffer = new byte[64];
                int size;
                String hex = hexNumStr;
                hex = hexStringClean(hex);
                try {
                    if (sHexNumStr.equalsIgnoreCase(hex)) {
                        return;
                    }
                } catch (NullPointerException e) {
                    //设备第一次没有收到信息
//                    ToastUtils.showShort(R.string.empty_instruction);
                }
                sHexNumStr = hex;
                //两位装一个格子,多次输出
                for (int i = 0; i < hex.length(); i += 2) {
                    String hexNum2 = hex.substring(i, 2 + i);
                    int dec = Integer.parseInt(hexNum2, 16);
                    Arrays.fill(outputBuffer, (byte) dec);
                    try {
                        outputStream.write(outputBuffer);

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (NullPointerException e) {
                        //	ToastUtil.w("设备断开了");
                    }
                }
                //读
                if (inputStream.available() <= 0) {
                    Thread.sleep(50);
                    if (inputStream.available() <= 0) {
                        size = 0;
                    } else {
                        size = inputStream.read(inputBuffer);
                    }
                } else {
                    size = inputStream.read(inputBuffer);
                }
                if (size > 0) {
                    DataBuffer dataBeen = new DataBuffer(inputBuffer, size);
                    emitter.onNext(dataBeen);
                    if (listener != null) {
                        listener.complete();
                    }
                } else {
                    emitter.onError(new Throwable("设备没有接收到数据"));
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<DataBuffer>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull DataBuffer dataBeen) {
                        byte[] buffer = dataBeen.getBuffer();
                        int size = dataBeen.getSize();
                        String receiver = SysTranslateUtil.bytesToHexFun2(buffer).substring(0, 14);
                        listener.complete();

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
//                        Log.e("TAG", "failure: 1" + hexNumStr );
                        listener.failure(R.string.no_data_received);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

我在这里使用rxjava与硬件设施交互 得到他的返回值在onnext里面用接口传给activity  嗯 就这样 

onnext方法中的DataBuffer

public class DataBuffer {

    private byte[] buffer; // 返回的 数据(16进制命令)
    private int size; // 返回的 数据长度

    public byte[] getBuffer() {
        return buffer;
    }

    public int getSize() {
        return size;
    }

    public DataBuffer(byte[] readBuffer, int size) {
        this.buffer = readBuffer;
        this.size = size;
    }
}

我想我的代码备注应该写的很详细 当然我也是菜鸟一个 

如果还有什么疑问或指教 QQ或邮箱联系 1525089850@qq.com



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值