Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android串口通信實戰:把android-serialport-api精簡成一個清晰Demo

編輯:關於 Android 程式設計

最近在做Android串口開發,找到了開源的android-serialport-api類庫(主頁:https://code.google.com/p/android-serialport-api/,可下載APK與源碼)。但把源碼下載下來後發現,它既不能直接使用,結構也偏複雜。其實串口的操作無非就四步:

  1. 打開串口(並配置串口);
  2. 讀串口;
  3. 寫串口;
  4. 關閉串口。

android-serialport-api用了繼承等較複雜的設計,初學者很難快速抓住上面這四步。所以我自己寫了一個精簡demo,只有一個Activity,把打開、寫、讀串口的操作都放在裡面;至於關閉串口,理解了前面幾步後你自然會寫。本文參考自CSDN上兩篇相關博文。

第一步:認識JNI與serial_port.so

談Android串口,繞不開JNI技術——它讓Java能調用C寫成的庫。為了能在Android中使用串口,該庫作者自己寫了一個C動態鏈接庫(自動命名為libserial_port.so),放在libs/armeabi裡,C源碼則在JNI目錄中。下載源碼後,把這兩個文件夾複製到自己新建的工程即可。

第二步:放置Java類,包名不能改

接著把調用這個動態鏈接庫的Java類放到src下的android.serialport包裡。包名一定要保持這個名字,因為熟悉JNI的人都知道,C庫中函數的命名與調用它的類所在包名相關,一旦包名與鏈接庫裡函數的命名對不上,就調用不到庫函數。打開jni中的.c文件就能看到這種命名規則:

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>
#include "android/log.h"

static const char* TAG = "serial_port";

static speed_t getBaudrate(jint baudrate) {
    switch (baudrate) {
    case 0: return B0;
    case 50: return B50;
    // ... 省略大量波特率映射
    case 115200: return B115200;
    case 4000000: return B4000000;
    default: return -1;
    }
}

/*
 * Class:     android_serialport_SerialPort
 * Method:    open
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
  (JNIEnv *env, jobject thiz, jstring path, jint baudrate) {
    int fd;
    speed_t speed;
    jobject mFileDescriptor;
    // 校驗波特率
    speed = getBaudrate(baudrate);
    if (speed == -1) { LOGE("Invalid baudrate"); return NULL; }
    // 打開設備
    const char* path_utf = (*env)->GetStringUTFChars(env, path, NULL);
    fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);
    (*env)->ReleaseStringUTFChars(env, path, path_utf);
    if (fd == -1) { LOGE("Cannot open port"); return NULL; }
    // 配置設備
    struct termios cfg;
    if (tcgetattr(fd, &cfg)) { close(fd); return NULL; }
    cfmakeraw(&cfg);
    cfsetispeed(&cfg, speed);
    cfsetospeed(&cfg, speed);
    if (tcsetattr(fd, TCSANOW, &cfg)) { close(fd); return NULL; }
    // 創建對應的FileDescriptor
    jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
    jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
    jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
    mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
    (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint) fd);
    return mFileDescriptor;
}

/*
 * Class:     android_serialport_SerialPort
 * Method:    close
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close
  (JNIEnv *env, jobject thiz) {
    jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
    jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");
    jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
    jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");
    jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
    jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);
    close(descriptor);
}

可以清楚看到,函數命名規則直接與包名掛鉤。

第三步:SerialPort與SerialPortFinder

android.serialport包下有兩個類。SerialPort.java主要負責加載so文件,並通過JNI打開、關閉串口:

package android.serialport;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.util.Log;

public class SerialPort {
    private static final String TAG = "SerialPort";
    // 不要刪除或重命名mFd字段:它被native方法close()使用
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    public SerialPort(File device, int baudrate) throws SecurityException, IOException {
        // 校驗讀寫權限
        if (!device.canRead() || !device.canWrite()) {
            try {
                // 缺少讀寫權限時,嘗試chmod
                Process su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 777 " + device.getAbsolutePath() + "\n" + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException();
            }
        }
        mFd = open(device.getAbsolutePath(), baudrate);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    public InputStream getInputStream() { return mFileInputStream; }
    public OutputStream getOutputStream() { return mFileOutputStream; }

    // JNI
    private native static FileDescriptor open(String path, int baudrate);
    public native void close();
    static {
        System.loadLibrary("serial_port");
    }
}

其中System.loadLibrary("serial_port")就是加載動態鏈接庫的關鍵一句,我們的串口操作正是通過這個類來實現的。至於SerialPortFinder.java,它用來查找系統中可用的串口;如果你已經明確知道設備有哪些串口,就可以跳過它,進一步簡化demo。

第四步:編寫自己的Activity

我在android.serialport包下新建了MyserialActivity.java,代碼如下:

package android.serialport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.serialport.R;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyserialActivity extends Activity {
    EditText mReception;
    FileOutputStream mOutputStream;
    FileInputStream mInputStream;
    SerialPort sp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 打開串口
        final Button buttonSetup = (Button) findViewById(R.id.ButtonSetup);
        buttonSetup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mReception = (EditText) findViewById(R.id.EditTextRec);
                try {
                    sp = new SerialPort(new File("/dev/ttyS2"), 9600);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mOutputStream = (FileOutputStream) sp.getOutputStream();
                mInputStream = (FileInputStream) sp.getInputStream();
                Toast.makeText(getApplicationContext(), "open", Toast.LENGTH_SHORT).show();
            }
        });

        // 寫串口
        final Button buttonsend = (Button) findViewById(R.id.ButtonSent1);
        buttonsend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    mOutputStream.write(new String("send").getBytes());
                    mOutputStream.write('\n');
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext(), "send", Toast.LENGTH_SHORT).show();
            }
        });

        // 讀串口
        final Button buttonrec = (Button) findViewById(R.id.ButtonRec);
        buttonrec.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int size;
                try {
                    byte[] buffer = new byte[64];
                    if (mInputStream == null) return;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        onDataReceived(buffer, size);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        });
    }

    void onDataReceived(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (mReception != null) {
                    mReception.append(new String(buffer, 0, size));
                }
            }
        });
    }
}

可以看到功能很簡單:三個按鈕分別負責打開串口(buttonSetup)、寫串口(buttonsend)、讀串口(buttonrec),外加一個文本框顯示接收到的信息。功能已經精簡到極致。

在模擬器中調試串口

先要用-serial選項啟動模擬器(記得改成你的模擬器名字):

然後進入adb shell:

cd /dev
chmod 777 ttyS2

執行結果:

我們的串口就是ttyS2,用chmod命令授予操作權限,否則後續應用可能沒有串口操作權限。接著運行程序:

其中Console就是打開串口(偷懶沒改名)。你可以把電腦的COM1連到另一台電腦的串口上,在那台電腦打開串口助手之類的軟件,配置好參數(從源碼裡不難看出),按下模擬器裡的send鍵,就能在對方串口助手中看到:

反過來,從那台電腦發送數據,這邊也能正常顯示:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved