現(xiàn)在網(wǎng)上關(guān)于硬件通訊的文章有很多,寫法也都一樣,我這里也只是記錄一下我在開發(fā)過程中使用的方法。
在與硬件進(jìn)行通訊之前,我們需要熟悉硬件通訊協(xié)議,我之前用到的是485單工通信協(xié)議,由報文頭+數(shù)據(jù)+校驗位組成。硬件方給我們的協(xié)議一般都是以他們需要處理的數(shù)據(jù)為準(zhǔn),大多是16進(jìn)制的數(shù)據(jù),我們在處理中有時需要轉(zhuǎn)換成十進(jìn)制或者將十進(jìn)制轉(zhuǎn)換成16進(jìn)制,這個需要根據(jù)項目實際需要去處理。
了解了硬件協(xié)議后,我們需要知道硬件的設(shè)備號和波特率,這是硬件通訊實現(xiàn)的最重要的兩個參數(shù),這兩個都是由硬件方提供的,有了這兩個參數(shù),我們就可以進(jìn)行通訊啦。
與硬件實現(xiàn)鏈接的方法都是用C++去實現(xiàn)的,因為C++實現(xiàn)硬件間的通訊是最方便的,可以直接掉用很多底層的接口,并且用C++是可以提高效率的。在Android Studio 里我們使用NDK實現(xiàn)與C++的調(diào)用,以前使用Eclipse時還需要手寫C文件,要提前學(xué)習(xí)各種格式,要注意很多地方。但是現(xiàn)在Android Studio可以很方便的幫我們創(chuàng)建這些文件和方法,只需要我們在船艦Projrct時勾選上支持C++即可。
C++實現(xiàn)連接的方法基本都是一樣,直接上代碼:
JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
(JNIEnv *env, jobject thiz, jstring path, jint baudrate) {
int fd;
speed_t speed;
jobject mFileDescriptor;
/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
LOGE("Invalid baudrate");
return NULL;
}
}
/* Opening device */
{
jboolean iscopy;
const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy);
LOGD("Opening serial port %s", path_utf);
fd = open(path_utf, O_RDWR);
LOGD("open() fd = %d", fd);
(*env)->ReleaseStringUTFChars(env, path, path_utf);
if (fd == -1) {
/* Throw an exception */
LOGE("Cannot open port");
return NULL;
}
}
/* Configure device */
{
struct termios cfg;
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg)) {
LOGE("tcgetattr() failed");
close(fd);
return NULL;
}
cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);
if (tcsetattr(fd, TCSANOW, &cfg)) {
LOGE("tcsetattr() failed");
close(fd);
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;
}
關(guān)于JNI相關(guān)的語法可以直接百度,再學(xué)習(xí)一點C語言的寫法,實現(xiàn)NDK與C的互相調(diào)用就很簡單了。
上面方法返回的就是我們需要的FileDescriptor ,我們后面的操作都是基于它。
public SerialPort(File device, int baudrate) throws SecurityException, IOException {
if (!device.canRead() || !device.canWrite()) {
try {
Process su;
su = Runtime.getRuntime().exec("su");
String cmd = "chmod 777 " + device.getAbsolutePath();
su.getOutputStream().write(cmd.getBytes());
su.getOutputStream().flush();
int waitFor = su.waitFor();
boolean canRead = device.canRead();
boolean canWrite = device.canWrite();
if (waitFor != 0 || !canRead || !canWrite) {
throw new SecurityException();
}
} catch (Exception e) {
BaseUtil.saveErrorMsgToLocal(e.getMessage(), "seriallibrary");
e.printStackTrace();
}
}
mFd = open(device.getAbsolutePath(), baudrate);
if (mFd == null) {
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
通過上面的操作,我們就已經(jīng)實現(xiàn)了和硬件的連接,剩下的就只有數(shù)據(jù)的傳輸了。
public byte[] sendData(byte[] data) {
synchronized (this) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
BaseUtil.saveErrorMsgToLocal(e.getMessage(), "hardwarelibrary");
e.printStackTrace();
}
int available;
try {
//清空之前沒有讀完的信息
if ((available = mInputStream.available()) > 0) {
byte[] bytes = new byte[available];
mInputStream.read(bytes);
}
//發(fā)送數(shù)據(jù)
mOutputStream.write(data);
mOutputStream.flush();
//啟動超時計時器
mTimerTask = new MyTimerTask();
mTimer.schedule(mTimerTask, TIMEOUT);
isTimeout = false;
byte[] head = new byte[RESPONSE_HEAD_LEN];
while (!isTimeout) {
available = mInputStream.available();
if (available >= RESPONSE_HEAD_LEN) {
mInputStream.read(head);
int lastDataLen = head[RESPONSE_DATA_LEN_INDEX] + RESPONSE_CHECKSUM_LEN;
byte[] lastData = new byte[lastDataLen];
while (!isTimeout) {
available = mInputStream.available();
if (available >= lastDataLen) {
mInputStream.read(lastData);
byte[] result = new byte[RESPONSE_HEAD_LEN + lastDataLen];
System.arraycopy(head, 0, result, 0, RESPONSE_HEAD_LEN);
System.arraycopy(lastData, 0, result, RESPONSE_HEAD_LEN, lastDataLen);
return result;
}
Thread.sleep(10);
}
}
Thread.sleep(10);
}
return null;
} catch (Exception e) {
BaseUtil.saveErrorMsgToLocal(e.getMessage(), "hardwarelibrary");
e.printStackTrace();
} finally {
if (mTimerTask != null) {
mTimerTask.cancel();
}
}
return null;
}
}
上面就是i實現(xiàn)的數(shù)據(jù)的發(fā)送與讀取,串口通信一般都是一發(fā)一收,由InputStream和OutputStream去實現(xiàn)數(shù)據(jù)的傳輸。
if ((available = mInputStream.available()) > 0) {
這里多了一步判斷,避免上一次的數(shù)據(jù)還沒有讀完就再次進(jìn)行數(shù)據(jù)傳輸。
mOutputStream.write(data);
mOutputStream.flush();
除了上面正常的數(shù)據(jù)發(fā)送接收外,還有幾種情況也很常見:
1、限時讀取指定長度的數(shù)據(jù)
2、限時讀取指定標(biāo)志位數(shù)據(jù)
以上兩種情況在我們的日常開發(fā)中也是很常見的,之前在做身份證模塊的時候,發(fā)現(xiàn)讀取時間不一樣,接收到的數(shù)據(jù)長度就會不一樣,這個時候就得考慮定長數(shù)據(jù)去解析了。
public synchronized byte[] readData(int length, int timeout) throws Exception {
byte[] data = new byte[length];
long startTime = System.currentTimeMillis();
while (mInputStream.available() < length) {
if ((System.currentTimeMillis() - startTime) > timeout) {
throw new Exception("讀取超時");
}
Thread.sleep(20);
}
mInputStream.read(data, 0, length);
return data;
}
第一種情況實現(xiàn)起來也很簡單,主要是解決數(shù)據(jù)長度時間的判斷.下面是第二種情況。
public byte[] readData(byte delimiter, int maxLen, int timeout) throws Exception {
byte[] data = new byte[maxLen];
int readedLen = 0;
long startTime = System.currentTimeMillis();
while (true) {
if(mSerialPort.getInputStream().available() <= 0) {
Thread.sleep(20);
}
if((System.currentTimeMillis() - startTime) > timeout) {
throw new Exception("讀取超時");
}
mSerialPort.getInputStream().read(data, readedLen, 1);
if(delimiter == data[readedLen]) {
break;
}
readedLen ++;
if (readedLen == maxLen) {
throw new Exception("超過限定長度");
}
}
return data;
}
第二種情況就多了對指定字符的處理,讀取到標(biāo)志位,就結(jié)束本次數(shù)據(jù)處理。