串口开发
编译so文件和项目配置
google串口api下载https://github.com/cepr/android-serialport-api
修改android-serialport-api-master\android-serialport-api-master\android-serialport-api\project\jni目录下的Android.mk、Application.mk和SerialPort.c文件
Android.mk修改解决libserial_port.so: has text relocations异常
LOCAL_PATH := $(call my-dir )
include $(CLEAR_VARS)
TARGET_PLATFORM := android-29
LOCAL_MODULE := serial_port
LOCAL_SRC_FILES := SerialPort.c
LOCAL_LDLIBS := -llog
LOCAL_LDFLAGS += -fPIC
include $(BUILD_SHARED_LIBRARY)
原因在于加载的so库需要重定位, Android 6.0及更高版本已明文禁止此种情形发生。在Android 6.0之前,text reloactions的问题,会在编译的过程中,作为warning报出来;在Android 6.0以上版本,升级为error了。
SerialPort.c修改解决java.lang.UnsatisfiedLinkError: No implementation found for java.io.FileDescriptor com.example.serialport.SerialPort.open(java.lang.String, int, int) (tried Java_com_example_serialport_SerialPort_open and Java_com_example_serialport_SerialPort_open__Ljava_lang_String_2II)异常
#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 ;
}
}
JNIEXPORT jobject JNICALL Java_com_example_serialport_SerialPort_open
(JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)
{
int fd;
speed_t speed;
jobject mFileDescriptor;
{
speed = getBaudrate(baudrate);
if (speed == -1 ) {
LOGE("Invalid baudrate" );
return NULL ;
}
}
{
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 )
{
LOGE("Cannot open port" );
return NULL ;
}
}
{
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 ;
}
}
{
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;
}
JNIEXPORT void JNICALL Java_com_example_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);
LOGD("close(fd = %d)" , descriptor);
close(descriptor);
}
在jni目录下执行ndk-build命令生成新的so文件
sourceSets {
main {
jniLibs.srcDirs = ['libs' ]
}
}
ndk {
abiFilters 'armeabi-v7a'
}
代码
package com.example.serialport;
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" ;
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort (File device, int baudrate, int flags)
throws SecurityException, IOException {
if (!device.canRead() || !device.canWrite()) {
try {
Process su;
su = Runtime.getRuntime().exec("/system/xbin/su" );
String cmd = "root 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 ();
}
}
System.out.println(device.getAbsolutePath() + "==============================" );
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);
}
public InputStream getInputStream () {
return mFileInputStream;
}
public OutputStream getOutputStream () {
return mFileOutputStream;
}
private native static FileDescriptor open (String path, int baudrate, int flags) ;
public native void close () ;
static {
System.loadLibrary("serial_port" );
}
}
package com.example.serialport;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SerialController {
private ExecutorService mThreadPoolExecutor = Executors.newCachedThreadPool();
private InputStream inputStream;
private OutputStream outputStream;
private boolean isOpened = false ;
private OnSerialListener mOnSerialListener;
public List<String> getAllSerialPortPath () {
SerialPortFinder mSerialPortFinder = new SerialPortFinder ();
String[] deviceArr = mSerialPortFinder.getAllDevicesPath();
return new ArrayList <>(Arrays.asList(deviceArr));
}
public void openSerialPort (String serialPath, int baudRate, int flags) {
try {
SerialPort serialPort = new SerialPort (new File (serialPath), baudRate, flags);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
isOpened = true ;
if (mOnSerialListener != null ) {
mOnSerialListener.onSerialOpenSuccess();
}
mThreadPoolExecutor.execute(new ReceiveDataThread ());
} catch (Exception e) {
if (mOnSerialListener != null ) {
mOnSerialListener.onSerialOpenException(e);
}
}
}
public void closeSerialPort () {
try {
if (inputStream != null ) {
inputStream.close();
}
if (outputStream != null ) {
outputStream.close();
}
isOpened = false ;
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendSerialPort (byte [] bytes) {
if (!isOpened) {
return ;
}
try {
if (outputStream != null ) {
outputStream.write(bytes);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isOpened () {
return isOpened;
}
private class ReceiveDataThread extends Thread {
@Override
public void run () {
super .run();
while (isOpened) {
if (inputStream != null ) {
byte [] readData = new byte [1024 ];
try {
int size = inputStream.read(readData);
if (size > 0 ) {
if (mOnSerialListener != null ) {
mOnSerialListener.onReceivedData(readData, size);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public void setOnSerialListener (OnSerialListener onSerialListener) {
this .mOnSerialListener = onSerialListener;
}
public interface OnSerialListener {
void onReceivedData (byte [] data, int size) ;
void onSerialOpenSuccess () ;
void onSerialOpenException (Exception e) ;
}
}
package com.example.serialport;
import android.util.Log;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class SerialPortUtil {
private static final String TAG = "wmj" ;
private SerialController serialController;
public void fun () {
serialController = new SerialController ();
List<String> serialPortPaths = serialController.getAllSerialPortPath();
if (!serialPortPaths.contains("/dev/ttyHS1" )) return ;
serialController.openSerialPort("/dev/ttyHS1" , 9600 , 2 );
Log.d(TAG, "端口开关状态" + serialController.isOpened());
serialController.setOnSerialListener(new SerialController .OnSerialListener() {
@Override
public void onReceivedData (byte [] data, int size) {
String s = new String (data, 0 , size, StandardCharsets.UTF_8);
Log.d(TAG, "onReceivedData: " + s);
}
@Override
public void onSerialOpenSuccess () {
Log.d(TAG, "onSerialOpenSuccess: " );
}
@Override
public void onSerialOpenException (Exception e) {
Log.d(TAG, "onSerialOpenException: " + e);
}
});
serialController.sendSerialPort("def哈哈" .getBytes(StandardCharsets.UTF_8));
}
}
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/15420487.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议 进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步