最近在android项目中要使用到串口编程,开始的时候为了省事,直接把以前在linux下用纯C写得串口程序封装成so库,再在JNI中调用so库,一点也没有问题。
虽说没有什么问题,总觉得在JAVA中使用纯C实现串口所有的操作很像是在“挂羊头卖狗肉”,而且也有点繁琐,想说JAVA应该把这些东西直接封装成API,于是在网上查资料,想找到类似于windows下的CreateFile的API接口,未果。
还好JAVA之中有个FileDescriptor类,可以把串口当作一个FileDescriptor,打开之后操作FileDescriptor就相当于操作串口。
不管是windows、linux、或是android操作系统,串口编程无非是以下几步:
这是典型的流驱动设备,操作很简单,在C语言里无非就是open、write、read、close几个操作就能轻松搞定的东西。这跟文件的输入输出流其实是一个概念,所以在windows中可以用CreateFile操作串口,同样的道理,在java中可以使用FileDescriptor操作串口。
下面是android 串口编程的具体步骤,先创建一个串口类SerialPort:
private static final String TAG = "SerialPort"; /* * Do not remove or rename the field mFd: it is used by native method close(); */ private FileDescriptor mFd; private FileInputStream mFileInputStream; private FileOutputStream mFileOutputStream; public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException { /* Check access permission */ if (!device.canRead() || !device.canWrite()) { try { /* Missing read/write permission, trying to chmod the file */ Process su; su = Runtime.getRuntime().exec("/system/bin/su"); String cmd = "chmod 666 " + 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, flags); if (mFd == null) { Log.e(TAG, "native open returns null"); throw new IOException(); } mFileInputStream = new FileInputStream(mFd); mFileOutputStream = new FileOutputStream(mFd); } // Getters and setters public InputStream getInputStream() { return mFileInputStream; } public OutputStream getOutputStream() { return mFileOutputStream; } // JNI private native static FileDescriptor open(String path, int baudrate, int flags); public native void close(); static { System.loadLibrary("serial_port"); }
这个类中主要干了两件事情:
创建了打开串口和关闭串口的本地方法
private native static FileDescriptor open(String path, int baudrate, int flags); public native void close();
关联串口的文件描述符(FileDescriptor),并把文件的输入输出流与之关联,在代码之中
private FileDescriptor mFd; private FileInputStream mFileInputStream; private FileOutputStream mFileOutputStream; mFd = open(device.getAbsolutePath(), baudrate, flags); mFileInputStream = new FileInputStream(mFd); mFileOutputStream = new FileOutputStream(mFd);
这段代码的意思就是把串口打开,并取得串口的输入输出操作(读写操作)。
到了这里,有个问题,如何打开串口?
代码上可知,打开串口的操作用的是一个本地方法open,那只能在JNI中实现这个接口,下面是jni中的实现:
static speed_t getBaudrate(jint baudrate) { switch(baudrate) { case 0: return B0; case 50: return B50; case 75: return B75; case 110: return B110; case 134: return B134; case 150: return B150; case 200: return B200; case 300: return B300; case 600: return B600; case 1200: return B1200; case 1800: return B1800; case 2400: return B2400; case 4800: return B4800; case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; case 230400: return B230400; case 460800: return B460800; case 500000: return B500000; case 576000: return B576000; case 921600: return B921600; case 1000000: return B1000000; case 1152000: return B1152000; case 1500000: return B1500000; case 2000000: return B2000000; case 2500000: return B2500000; case 3000000: return B3000000; case 3500000: return B3500000; case 4000000: return B4000000; default: return -1; } } /* * Class: android_serialport_SerialPort * Method: open * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor; */ JNIEXPORT jobject JNICALL Java_android_1serialport_1api_SerialPort_open (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags) { int fd; speed_t speed; jobject mFileDescriptor; /* Check arguments */ { speed = getBaudrate(baudrate); if (speed == -1) { /* TODO: throw an exception */ LOGE("Invalid baudrate"); return NULL; } } /* Opening device */ { jboolean iscopy; const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy); LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags); fd = open(path_utf, O_RDWR | flags); LOGD("open() fd = %d", fd); (*env)->ReleaseStringUTFChars(env, path, path_utf); if (fd == -1) { /* Throw an exception */ LOGE("Cannot open port"); /* TODO: throw an exception */ return NULL; } } /* Configure device */ { struct termios cfg; LOGD("Configuring serial port"); if (tcgetattr(fd, &cfg)) { LOGE("tcgetattr() failed"); close(fd); /* TODO: throw an exception */ return NULL; } cfmakeraw(&cfg); cfsetispeed(&cfg, speed); cfsetospeed(&cfg, speed); if (tcsetattr(fd, TCSANOW, &cfg)) { LOGE("tcsetattr() failed"); close(fd); /* TODO: throw an exception */ return NULL; } } /* Create a corresponding file descriptor */ { 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: cedric_serial_SerialPort * Method: close * Signature: ()V */ JNIEXPORT void JNICALL Java_android_1serialport_1api_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); LOGD("close(fd = %d)", descriptor); close(descriptor); }
在Java_android_1serialport_1api_SerialPort_open接口中,能发现一些熟悉的东西:
fd = open(path_utf, O_RDWR | flags); tcgetattr(fd, &cfg) cfmakeraw(&cfg); cfsetispeed(&cfg, speed); cfsetospeed(&cfg, speed);
...
这些都是在linux下的串口编程,分别是打开串口设备节点,配置数据流控、波特率等,这些东西其实不是重点,重点是如何把打开的串口设备与FileDescriptor关联,即把fd封装到FileDescriptor中去:
/* Create a corresponding file descriptor */ { 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;
上面的代码简单解释来说就是mFileDescriptor与fd关联并返回给JAVA层。
至此,其实串口的JAVA封装已经完成,这个类其实已经可以完成串口的所有操作(打开,配置,读写,关闭),接下来的事情只是逻辑层面的事情了。