美文网首页Android Community
Android基础知识之串口通信

Android基础知识之串口通信

作者: HongGang | 来源:发表于2018-08-16 23:40 被阅读35次

    Android串口通信

    使用Google的开源库android-serialport-api

    一、搭建项目环境

    1. 在Main文件夹下创建 libs 与 jniLibs 文件夹,然后将库中对应的文件拷入

    2. 在 java 文件夹下创建 android_serialport_api (注意:因为用的谷歌原生so库,所以SerialPort类的包名一定要是android_serialport_api,如果想修改这个包名,就需要重新生成对应的so库)

    3. 然后在 build.gradle 中添加

      sourceSets {
          main { 
              jni.srcDirs = []
          }
      }
      

    二、数据通信

    • 创建串口工具类:

      public class SerialPortUtil {
      
          private static volatile SerialPortUtil serialPortUtil;
      
          private SerialPortUtil() {
      
          }
      
          public static SerialPortUtil getInstance() {
              if (serialPortUtil == null) {
                  synchronized (SerialPortUtil.class) {
                      if (serialPortUtil == null) {
                          serialPortUtil = new SerialPortUtil();
                      }
                  }
              }
              return serialPortUtil;
          }
      
          private SerialPort serialPort;
          private OutputStream outputStream;
          private InputStream inputStream;
      
          /**
           * 打开串口
           */
          public void openSerialPort() {
              try {
                  /*设置打开的串口*/
                  final String portPath = "/dev/ttyS0";
                  /*设置波特率*/
                  final int baudRate = 115200;
                  serialPort = new SerialPort(new File(portPath), baudRate, 0);
                  outputStream = serialPort.getOutputStream();
                  inputStream = serialPort.getInputStream();
                  /*开启线程读取数据*/
                  new ReadThread().start();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          /**
           * 读取数据的线程
           */
          private class ReadThread extends Thread {
              @Override
              public void run() {
                  super.run();
                  while (!isInterrupted()) {
                      int size;
                      try {
                          byte[] buffer = new byte[64];
                          if (inputStream == null)
                              return;
                          size = inputStream.read(buffer);
                          if (size > 0) {
                              if (dataReceiveListener != null) {
                                  dataReceiveListener.receiveData(buffer, size);
                              }
                          }
                      } catch (IOException e) {
                          e.printStackTrace();
                          return;
                      }
                  }
              }
          }
      
          /**
           * 关闭串口
           */
          public void closeSerialPort() {
              try {
                  inputStream.close();
                  outputStream.close();
                  serialPort.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          /**
           * 发送数据到串口
           *
           * @param data 需要发送的数据
           */
          public void sendDataToSerialPort(byte[] data) {
              try {
                  int dataLength = data.length;
                  if (dataLength > 0) {
                      outputStream.write(data);
                      outputStream.write('\n');
                      outputStream.flush();
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          public interface DataReceiveListener {
              void receiveData(byte[] data, int size);
          }
      
          private DataReceiveListener dataReceiveListener;
      
          public void setOnDataReceiveListener(DataReceiveListener dataReceiveListener) {
              this.dataReceiveListener = dataReceiveListener;
          }
      }
      
      
    • 创建串口信息获取类:

      public class SerialPortFinder {
      
          public class Driver {
              public Driver(String name, String root) {
                  mDriverName = name;
                  mDeviceRoot = root;
              }
              private String mDriverName;
              private String mDeviceRoot;
              Vector<File> mDevices = null;
              public Vector<File> getDevices() {
                  if (mDevices == null) {
                      mDevices = new Vector<File>();
                      File dev = new File("/dev");
                      File[] files = dev.listFiles();
                      int i;
                      for (i=0; i<files.length; i++) {
                          if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
                              Log.d(TAG, "Found new device: " + files[i]);
                              mDevices.add(files[i]);
                          }
                      }
                  }
                  return mDevices;
              }
              public String getName() {
                  return mDriverName;
              }
          }
      
          private static final String TAG = "SerialPort";
      
          private Vector<Driver> mDrivers = null;
      
          Vector<Driver> getDrivers() throws IOException {
              if (mDrivers == null) {
                  mDrivers = new Vector<Driver>();
                  LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
                  String l;
                  while((l = r.readLine()) != null) {
                      // Issue 3:
                      // Since driver name may contain spaces, we do not extract driver name with split()
                      String drivername = l.substring(0, 0x15).trim();
                      String[] w = l.split(" +");
                      if ((w.length >= 5) && (w[w.length-1].equals("serial"))) {
                          Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length-4]);
                          mDrivers.add(new Driver(drivername, w[w.length-4]));
                      }
                  }
                  r.close();
              }
              return mDrivers;
          }
      
          public String[] getAllDevices() {
              Vector<String> devices = new Vector<String>();
              // Parse each driver
              Iterator<Driver> itdriv;
              try {
                  itdriv = getDrivers().iterator();
                  while(itdriv.hasNext()) {
                      Driver driver = itdriv.next();
                      Iterator<File> itdev = driver.getDevices().iterator();
                      while(itdev.hasNext()) {
                          String device = itdev.next().getName();
                          String value = String.format("%s (%s)", device, driver.getName());
                          devices.add(value);
                      }
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return devices.toArray(new String[devices.size()]);
          }
      
          public String[] getAllDevicesPath() {
              Vector<String> devices = new Vector<String>();
              // Parse each driver
              Iterator<Driver> itdriv;
              try {
                  itdriv = getDrivers().iterator();
                  while(itdriv.hasNext()) {
                      Driver driver = itdriv.next();
                      Iterator<File> itdev = driver.getDevices().iterator();
                      while(itdev.hasNext()) {
                          String device = itdev.next().getAbsolutePath();
                          devices.add(device);
                      }
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return devices.toArray(new String[devices.size()]);
          }
      }
      
      
    • 使用方法

      SerialPortUtil.getInstance().openSerialPort();
          SerialPortFinder finder = new SerialPortFinder();
          String[] allDevices = finder.getAllDevices();
          Log.e("LHG", Arrays.toString(allDevices));
          SerialPortUtil.getInstance().setOnDataReceiveListener(new SerialPortUtil.DataReceiveListener() {
              @Override
              public void receiveData(byte[] data, int size) {
                  
              }
          });
      

    相关文章

      网友评论

        本文标题:Android基础知识之串口通信

        本文链接:https://www.haomeiwen.com/subject/uvuabftx.html