安卓串口实现通讯奇偶校验问题(手写cpp文件调用)

发布时间 2023-11-07 14:46:15作者: 鸿运当头汪

第一步配置SDK

在local.properties文件中添加ndk对应的版本

cmake.dir=D\:\\SDK\\cmake\\3.10.2.4988404
ndk.dir=D\:\\SDK\\ndk\\21.0.6113669
sdk.dir=D\:\\SDK

第二步手写CMakeLists.txt,来调用cpp的文件

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.1.0)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
native-lib

# Sets the library as a shared library.
SHARED

# Provides a relative path to your source file(s).
src/cpp/native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
log-lib

# Specifies the name of the NDK library that
# you want CMake to locate.
log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
native-lib

# Links the target library to the log library
# included in the NDK.
${log-lib} )

第三步在build.gradle中添加cmakeList的调用

 

externalNativeBuild {
cmake {
cppFlags ""
version "3.18.1"
abiFilters "armeabi-v7a", 'arm64-v8a'

path "CMakeLists.txt"

}

第四步手写serialport.h方法,来调用cpp文件,注意这里文件路径要与CMakeLists.txt中的对应src/cpp/native-lib.cpp

 

 Java_com_hc_admc_SerialPort_open为开启奇偶校验的方法,这里注意路径要对

第五步添加native-lib.cpp文件,作用为实际奇偶校验的处理,这里可通过传递参数来控制开启奇偶校验。

 实际代码如下:

/*
* Copyright 2009-2011 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

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

#include "SerialPort.h"

#include "android/log.h"
static const char *TAG="serial_port";
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)

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;
}
}

static void throwException(JNIEnv *env, const char *name, const char *msg)
{
jclass cls = (*env).FindClass( name);
/* if cls is NULL, an exception has already been thrown */
if (cls != NULL) {
(*env).ThrowNew( cls, msg);
}

/* free the local ref */
(*env).DeleteLocalRef( cls);
}


extern "C"
JNIEXPORT jobject JNICALL
Java_com_hc_admc_SerialPort_open(JNIEnv *env, jclass clazz, jstring path, jint baudrate,
jint parity, jint data_bits, jint stop_bit,
jint flags) {
// TODO: implement open()
int fd;
speed_t speed;
jobject mFileDescriptor;

/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
throwException(env, "java/lang/IllegalArgumentException", "Invalid baudrate");
return NULL;
}
if (parity <0 || parity>2) {
throwException(env, "java/lang/IllegalArgumentException", "Invalid parity");
return NULL;
}
if (data_bits <5 || data_bits>8) {
throwException(env, "java/lang/IllegalArgumentException", "Invalid dataBits");
return NULL;
}
if (stop_bit <1 || stop_bit>2) {
throwException(env, "java/lang/IllegalArgumentException", "Invalid stopBit");
return NULL;
}
}

/* Opening device */
{
jboolean iscopy;
const char *path_utf = (*env).GetStringUTFChars( 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( path, path_utf);
if (fd == -1)
{
/* Throw an exception */
LOGE("Cannot open port");
throwException(env, "java/io/IOException", "Cannot open port");
return NULL;
}
}


/* Configure device */
{
struct termios cfg;
if (tcgetattr(fd, &cfg))
{
close(fd);
throwException(env, "java/io/IOException", "tcgetattr() failed");
return NULL;
}
LOGD("tcgetattr() cfg = %d", cfg.c_cflag);
cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);
LOGD("switch() parity = %d data_bits = %d stop_bit = %d ", parity, data_bits, stop_bit);
/* More attribute set */
switch (parity) {
case 0: break;
case 1:
cfg.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
cfg.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 2:
cfg.c_cflag |= PARENB; /* Enable parity */
cfg.c_cflag &= ~PARODD; /* 转换为偶效验*/
cfg.c_iflag |= INPCK; /* Disnable parity checking */
break;
}
switch (data_bits) {
case 5: cfg.c_cflag |= CS5; break;
case 6: cfg.c_cflag |= CS6; break;
case 7: cfg.c_cflag |= CS7; break;
case 8: cfg.c_cflag |= CS8; break;
}
switch (stop_bit) {
case 1: cfg.c_cflag &= ~CSTOPB; break;
case 2: cfg.c_cflag |= CSTOPB; break;
}

int rc = tcsetattr(fd, TCSANOW, &cfg);
LOGD("tcgetattr() cfg = %d", cfg.c_cflag);

if (rc)
{
close(fd);
throwException(env, "java/io/IOException", strcat("tcsetattr() failed: ", "rc"));
return NULL;
}

}

/* Create a corresponding file descriptor */
{
jclass cFileDescriptor = env->FindClass( "java/io/FileDescriptor");
jmethodID iFileDescriptor = env->GetMethodID( cFileDescriptor, "<init>", "()V");
jfieldID descriptorID = (env)->GetFieldID( cFileDescriptor, "descriptor", "I");
mFileDescriptor = (env)->NewObject( cFileDescriptor, iFileDescriptor);
(env)->SetIntField( mFileDescriptor, descriptorID, (jint)fd);
}

return mFileDescriptor;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_hc_admc_SerialPort_close(JNIEnv *env, jobject thiz) {
// TODO: implement close()

// TODO
jclass SerialPortClass = env->GetObjectClass( thiz);
jclass FileDescriptorClass = env->FindClass( "java/io/FileDescriptor");

jfieldID mFdID = env->GetFieldID( SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = env->GetFieldID( FileDescriptorClass, "descriptor", "I");

jobject mFd = env->GetObjectField( thiz, mFdID);
jint descriptor = env->GetIntField( mFd, descriptorID);

close(descriptor);
}

第六步在项目进行实际调用
创建SerialPort文件调用cpp方法,路径参考上面配置com.hc.admc,这里根据自己实际情况进行调整
/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.hc.admc;

import android.util.Log;

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;

public class 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 parity, int dataBits, int stopBit , 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();
}
}

this.mFd = open(device.getAbsolutePath(), baudrate,parity, dataBits, stopBit, flags);
if (this.mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}else{
this.mFileInputStream = new FileInputStream(this.mFd);
this.mFileOutputStream = new FileOutputStream(this.mFd);
}
}

// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}

public OutputStream getOutputStream() {
return mFileOutputStream;
}

// JNI
public native static FileDescriptor open(String path, int baudrate, int parity, int dataBits, int stopBit,int flags);
public native void close();

static {
System.loadLibrary("native-lib");
}
}
第七步创建SerialHelper文件读取串口中获得的数据
package com.hc.admc.SerialHelperPort;


import com.hc.admc.SerialPort;
import com.hc.serialport.HexUtils;
import com.hc.serialport.SerialPortLib;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
* Created by BC020 on 2018/5/17.
*/

public abstract class SerialHelper {

private SerialPortLib mSerialPort;
private OutputStream mOutputStream;
private InputStream mInputStream;
private SerialHelper.ReadThread mReadThread;
private SerialHelper.SendThread mSendThread;
private String sPort;
private int iDelay;
private int iBaudRate;
private boolean _isOpen;
private byte[] _bLoopData;
private SerialPort serialPort;

public SerialHelper(String sPort, int iBaudRate) {
this.sPort = "/dev/s3c2410_serial0";
this.iDelay = 200;
this.iBaudRate = 2400;
this._isOpen = false;
this._bLoopData = new byte[]{(byte)48};
this.sPort = sPort;
this.iBaudRate = iBaudRate;
}
public SerialHelper() {
this("/dev/s3c2410_serial0", 9600);
}
public void open() throws Exception {
serialPort = new SerialPort(new File(this.sPort), this.iBaudRate, 2,8,1, 0);
// this.mSerialPort = new SerialPortLib(new File(this.sPort), this.iBaudRate, 0);
this.mOutputStream = this.serialPort.getOutputStream();
this.mInputStream = this.serialPort.getInputStream();
this.mReadThread = new SerialHelper.ReadThread();
this.mReadThread.start();
this.mSendThread = new SerialHelper.SendThread();
this.mSendThread.setSuspendFlag();
this.mSendThread.start();
this._isOpen = true;
}

public SerialHelper(String sPort, String sBaudRate) {
this(sPort, Integer.parseInt(sBaudRate));
}

public void close() {
if(this.mReadThread != null) {
this.mReadThread.interrupt();
}

if(this.mSendThread != null) {
this.mSendThread.interrupt();
}

if(this.serialPort != null) {
this.serialPort.close();
this.serialPort = null;
}
this._isOpen = false;
}

public void send(byte[] bOutArray) {
try {
this.mOutputStream.write(bOutArray);
this.clearLoopData();
} catch (IOException var3) {
var3.printStackTrace();
}

}

public byte[] getbLoopData() {
return this._bLoopData;
}

public void clearLoopData() {
this._bLoopData = null;
}

public void sendHex(String sHex) {
byte[] bOutArray = HexUtils.HexToByteArr(sHex);
this.send(bOutArray);
}

public void sendHex(byte[] bytes) {
this.send(bytes);
}

public void sendTxt(String sTxt) {
byte[] bOutArray = new byte[0];

try {
bOutArray = sTxt.getBytes("GB2312");
this.send(bOutArray);
} catch (UnsupportedEncodingException var4) {
var4.printStackTrace();
}

}

public int getBaudRate() {
return this.iBaudRate;
}

public boolean setBaudRate(int iBaud) {
if(this._isOpen) {
return false;
} else {
this.iBaudRate = iBaud;
return true;
}
}

public boolean setBaudRate(String sBaud) {
int iBaud = Integer.parseInt(sBaud);
return this.setBaudRate(iBaud);
}

public String getPort() {
return this.sPort;
}

public boolean setPort(String sPort) {
if(this._isOpen) {
return false;
} else {
this.sPort = sPort;
return true;
}
}

public boolean isOpen() {
return this._isOpen;
}

public void setbLoopData(byte[] bLoopData) {
this._bLoopData = bLoopData;
}

public void setTxtLoopData(String sTxt) {
this._bLoopData = sTxt.getBytes();
}

public void setHexLoopData(String sHex) {
this._bLoopData = HexUtils.HexToByteArr(sHex);
}

public int getiDelay() {
return this.iDelay;
}

public void setiDelay(int iDelay) {
this.iDelay = iDelay;
}

public void startSend() {
if(this.mSendThread != null) {
this.mSendThread.setResume();
}

}

public void stopSend() {
if(this.mSendThread != null) {
this.mSendThread.setSuspendFlag();
}

}

protected abstract void onDataReceived(ComBean var1);

private class SendThread extends Thread {
public boolean suspendFlag;

private SendThread() {
this.suspendFlag = true;
}

public void run() {
super.run();

while(!this.isInterrupted()) {
synchronized(this) {
while(this.suspendFlag) {
try {
this.wait();
} catch (Exception var5) {
var5.printStackTrace();
}
}
}

SerialHelper.this.send(SerialHelper.this.getbLoopData());

try {
Thread.sleep((long) SerialHelper.this.iDelay);
} catch (InterruptedException var4) {
var4.printStackTrace();
}
}

}

public void setSuspendFlag() {
this.suspendFlag = true;
}

public synchronized void setResume() {
this.suspendFlag = false;
this.notify();
}
}

//----------------读取线程----------------
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
while (!isInterrupted()) {
try {
if (mInputStream == null) return;

if (mInputStream.available() > 0) {
Thread.sleep(2000);
}else {
Thread.sleep(1);
continue;
}
byte[] buffer = new byte[1024];
int size = mInputStream.read(buffer);
if (size > 0) {
ComBean comBean = new ComBean(sPort, buffer, size);
onDataReceived(comBean);
}

} catch (Throwable e) {
e.printStackTrace();
return;
}
}
}
}
}

 

 这里数字为2时开启偶校验,为1时开启奇校验

最后一步,软件运行时调用,在主函数MainActivity中添加调用。