Android通过jni读写串口

Android读写串口的时候需要jni调用c代码来实现,在开始之前需要下载ndk并配置好环境变量,也就是path里面加上ndk的bin路径。下面是具体的步骤
1、建一个包含jni方法的串口操作类:

package com.luoye.frigo.device;

public class SerialPortReaderWriter {
    
    

    protected native int open(String path, int baudrate, int parity,int stopBites,int dataBites);
    protected native void close(int fd);
    protected native int read(int fd,byte[] bytes,int len);
    protected native int write(int fd,byte[] bytes,int len);

}

2、在java目录下编译SerialPortReaderWriter这个类:

D:\myprojects\android\LibTestApp\device\src\main\java>javac -d ../jni com/luoye/frigo/device/SerialPortReaderWriter.java

3、在jni目录下生成c头文件SerialPortReaderWriter.h:

D:\myprojects\android\LibTestApp\device\src\main\jni>javah -o SerialPortReaderWriter.h -jni com.luoye.frigo.device.SerialPortReaderWriter

4、在jni目录下添加c文件SerialPortReaderWriter.c,在这个文件中实现串口操作的逻辑:

//
// Created by dave on 2020/4/28.
//
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>

#include "SerialPortReaderWriter.h"

#include "android/log.h"
static const char *TAG="serial_port_reader_writer";
#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;
	}
}

/*
 * Class:     com_tricent_frigo_device_SerialPortReaderWriter
 * Method:    open
 * Signature: (Ljava/lang/String;IIII)I
 */
JNIEXPORT jint JNICALL Java_com_luoye_frigo_device_SerialPortReaderWriter_open
  (JNIEnv *env, jobject thiz, jstring path, jint baudrate, jint parity, jint stop_bites, jint data_bites){
    
    
        int fd=0;
    	speed_t speed;
    	jobject mFileDescriptor;

    	/* Check arguments */
    	{
    
    
    		speed = getBaudrate(baudrate);
    		if (speed == -1) {
    
    
    			/* TODO: throw an exception */
    			LOGE("Invalid baudrate");
    			return -1;
    		}
    		if(parity>5||parity<1){
    
    
    		    LOGE("Invalid parity");
                return -2;
    		}
    		if(stop_bites>3||stop_bites<1){
    
    
                LOGE("Invalid stop_bites");
                return -3;
            }
            if(data_bites>8||data_bites<5){
    
    
                LOGE("Invalid data_bites");
                return -4;
            }
    	}

    	/* 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 | O_NOCTTY | O_NDELAY);
    		fd = open(path_utf, O_RDWR | O_NOCTTY | O_NDELAY);
    		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 -5;
    		}
    	}

    	/* Configure device */
    	{
    
    
    		struct termios cfg;
    		LOGD("Configuring serial port");
    		if (tcgetattr(fd, &cfg))
    		{
    
    
    			LOGE("tcgetattr() failed");
    			close(fd);
    			/* TODO: throw an exception */
    			return -6;
    		}

    		//cfmakeraw(&cfg);

            /*设置波特率*/
            //tcflush(fd,TCIOFLUSH);
            cfsetispeed(&cfg,speed);

            /*设置数据位*/
            cfg.c_cflag &= ~CSIZE;
            switch (data_bites) /*设置数据位数*/
            {
    
    
                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 (parity)
            {
    
    
                case 1:
                    cfg.c_cflag &= ~PARENB;   /* Clear parity enable */
                    cfg.c_iflag &= ~INPCK;     /* Enable parity checking */
                    break;
                case 2:
                    cfg.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
                    cfg.c_iflag |= INPCK;             /* Disnable parity checking */
                    break;
                case 3:
                    cfg.c_cflag |= PARENB;     /* Enable parity */
                    cfg.c_cflag &= ~PARODD;   /* 转换为偶效验*/
                    cfg.c_iflag |= INPCK;       /* Disnable parity checking */
                    break;
                case 4:  /*as no parity*/
                    cfg.c_cflag &= ~PARENB;
                    cfg.c_cflag &= ~CSTOPB;
                    break;
                case 5:
                    cfg.c_cflag &= ~PARENB;
                    cfg.c_cflag &= CSTOPB;
                    break;
            }
            /* 设置停止位*/
            switch (stop_bites)
            {
    
    
                case 1:
                    cfg.c_cflag &= ~CSTOPB;
                    break;
                case 2:
                    cfg.c_cflag |= CSTOPB;
                    break;
            }
            cfg.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
            //屏蔽软件流控,让X-ON X-OFF可以发送出去
            cfg.c_iflag &= ~ (IXON | IXOFF | IXANY | ICRNL);
            cfg.c_oflag &= ~OPOST;
            cfg.c_cc[VTIME] = 150; /* 设置超时15 seconds*/
            cfg.c_cc[VMIN] = 0;
            tcflush(fd,TCIFLUSH);/* Update the cfg and do it NOW */
            //立即将新属性赋予串口
            if (tcsetattr(fd, TCSANOW, &cfg))
            {
    
    
                LOGE("tcsetattr() failed");
                close(fd);
                /* TODO: throw an exception */
                return -7;
            }
    	}
        return fd;
  }

/*
 * Class:     com_tricent_frigo_device_SerialPortReaderWriter
 * Method:    close
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_luoye_frigo_device_SerialPortReaderWriter_close
  (JNIEnv *env, jobject thiz, jint fd){
    
    
    LOGD("close(fd = %d)", fd);
    close(fd);
  }

/*
 * Class:     com_tricent_frigo_device_SerialPortReaderWriter
 * Method:    read
 * Signature: (I[BI)I
 */
JNIEXPORT jint JNICALL Java_com_luoye_frigo_device_SerialPortReaderWriter_read
  (JNIEnv *env, jobject thiz, jint fd, jbyteArray byteArray, jint len){
    
    
        //方式1
        jbyte* byte = (*env)->GetByteArrayElements(env,byteArray, 0);
        //jbyte* byte = env->GetByteArrayElements(byteArray, 0);//c++写法
        int nRet = read(fd,byte,len);
        LOGD("read(nRet = %d)", nRet);
        //方式2
        //char chTmp[len];
        //memset(chTmp, 0, len);
        //int nRet = read(fd,chTmp,len);
        //LOGD("read(nRet = %d)", nRet);
        //(*env)->SetByteArrayRegion(env,byteArray, 0, len, chTmp);
        return nRet;
  }

/*
 * Class:     com_tricent_frigo_device_SerialPortReaderWriter
 * Method:    write
 * Signature: (I[BI)I
 */
JNIEXPORT jint JNICALL Java_com_luoye_frigo_device_SerialPortReaderWriter_write
  (JNIEnv *env, jobject thiz, jint fd, jbyteArray byteArray, jint len){
    
    
        jbyte* byte = (*env)->GetByteArrayElements(env,byteArray, 0);
        int nRet = write(fd,byte,len);
        LOGD("write(nRet = %d)", nRet);
        (*env)->ReleaseByteArrayElements(env, byteArray, byte, 0);
        return nRet;
  }

5、在jni目录下添加makefile文件Android.mk:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := dev-jni
LOCAL_SRC_FILES := SerialPortReaderWriter.c
LOCAL_LDLIBS    := -llog
include $(BUILD_SHARED_LIBRARY)

6、在jni目录下执行ndk-build命令:

D:\myprojects\android\LibTestApp\device\src\main\jni>ndk-build

7、将生成的libs目录拷贝到项目根目录
8、在Java类SerialPortReaderWriter中添加:

static {
    
    
        System.loadLibrary("dev-jni");
    }

完善后的完整代码:

package com.luoye.frigo.device;

public class SerialPortReaderWriter {
    
    
	static {
    
    
	        System.loadLibrary("dev-jni");
	}
    protected native int open(String path, int baudrate, int parity,int stopBites,int dataBites);
    protected native void close(int fd);
    protected native int read(int fd,byte[] bytes,int len);
    protected native int write(int fd,byte[] bytes,int len);

    private int fd=-1;
    public void openSerialPort(String path, int baudrate, int parity,int stopBites,int dataBites){
    
    
        fd=open(path,baudrate,parity,stopBites,dataBites);
    }
    public void openSerialPort(String path, int baudrate){
    
    
        openSerialPort(path,baudrate,1,1,8);
    }
    public void closeSerialPort(){
    
    
        close(fd);
        fd=-1;
    }
    public int read(byte[] bytes){
    
    
        if(bytes==null||fd==-1){
    
    
            return 0;
        }
        int len=bytes.length;
        return read(fd,bytes,len);
    }
    public int write(byte[] bytes){
    
    
        if(bytes==null||fd==-1){
    
    
            return 0;
        }
        int len=bytes.length;
        return write(fd,bytes,len);
    }
}

9、使用示例:

SerialPortReaderWriter serialPortReaderWriter=new SerialPortReaderWriter();
serialPortReaderWriter.openSerialPort("/dev/ttymxc3",9600);
serialPortReaderWriter.write("hello world".getBytes());
byte bs[]=new byte[32];
int r=serialPortReaderWriter.read(bs);
etr.setText(r+":"+new String(bs));
serialPortReaderWriter.closeSerialPort();

补充(另一种方式:通过在Java类中保留文件描述符,然后基于此获取java的输入输出流来对串口进行读写):

package com.luoye.frigo.device;

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

	public interface SerialPath{
    
    
		String TTYMXC1="/dev/ttymxc1";
		String TTYMXC2="/dev/ttymxc2";
		String TTYMXC3="/dev/ttymxc3";
		String TTYMXC4="/dev/ttymxc4";
	}
	public interface SerialPortParity {
    
    
		int None=1; //没有校验位 无校验(8bit)
		int Odd=2;  //每个字节穿送整个过程中bit为1的个数是奇数个(校验位调整个数)奇校验(7bit)
		int ComEvent=3; //每个字节传送整个过程中bit为1的个数是偶数个(校验位调整个数)偶校验(7bit)
		int Mark=4; //校验位总为1(8bit)
		int Space=5; //校验位总为0 Space校验(7bit)
	}
	//定义停止位
	public interface  SerialPortStopBits{
    
    
		int STOP_1 = 1;
		int STOP_2=2;
	}
	//数据位
	public interface SerialPortDataBits{
    
    
		int BITS_5 = 5;
		int BITS_6 = 6;
		int BITS_7 = 7;
		int BITS_8 = 8;
	}
//
//
//	/*
//	 * Do not remove or rename the field mFd: it is used by native method close();
//	 */
	private FileDescriptor mFd;
	private FileInputStream mFileInputStream;
	private FileOutputStream mFileOutputStream;

	protected SerialPort(File device, int baudrate, int parity, int stopBites, int dataBites) 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, parity,stopBites,dataBites);
		if (mFd == null) {
    
    
			Log.e(TAG, "native open returns null");
			throw new IOException();
		}
		mFileInputStream = new FileInputStream(mFd);
		mFileOutputStream = new FileOutputStream(mFd);
	}


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

	protected OutputStream getOutputStream() {
    
    
		return mFileOutputStream;
	}

	// JNI:设备文件路径,波特率,奇偶校验位,停止位,数据位
	private native static FileDescriptor open(String path, int baudrate, int parity,int stopBites,int dataBites);
	protected native void close();
	static {
    
    
		System.loadLibrary("serial_port");
	}
}

SerialPort.h

扫描二维码关注公众号,回复: 12272471 查看本文章
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_luoye_frigo_device_SerialPort */

#ifndef _Included_com_tricent_frigo_device_SerialPort
#define _Included_com_tricent_frigo_device_SerialPort
#ifdef __cplusplus
extern "C" {
    
    
#endif
/*
 * Class:     com_luoye_frigo_device_SerialPort
 * Method:    open
 * Signature: (Ljava/lang/String;IIII)Ljava/io/FileDescriptor;
 */
JNIEXPORT jobject JNICALL Java_com_luoye_frigo_device_SerialPort_open
  (JNIEnv *, jclass, jstring, jint, jint, jint, jint);

/*
 * Class:     com_tricent_frigo_device_SerialPort
 * Method:    close
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_luoye_frigo_device_SerialPort_close
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

SerialPort.c

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

/*
 * Class:     android_serialport_SerialPort
 * Method:    open
 * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
 */
JNIEXPORT jobject JNICALL Java_com_luoye_frigo_device_SerialPort_open
  (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint parity, jint stop_bites, jint data_bites)
{
    
    
	int fd;
	speed_t speed;
	jobject mFileDescriptor;

	/* Check arguments */
	{
    
    
		speed = getBaudrate(baudrate);
		if (speed == -1) {
    
    
			/* TODO: throw an exception */
			LOGE("Invalid baudrate");
			return NULL;
		}
		if(parity>5||parity<1){
    
    
		    LOGE("Invalid parity");
            return NULL;
		}
		if(stop_bites>3||stop_bites<1){
    
    
            LOGE("Invalid stop_bites");
            return NULL;
        }
        if(data_bites>8||data_bites<5){
    
    
            LOGE("Invalid data_bites");
            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 | O_NOCTTY | O_NDELAY);
		fd = open(path_utf, O_RDWR | O_NOCTTY | O_NDELAY);
		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);

        /*设置波特率*/
        //tcflush(fd,TCIOFLUSH);
        cfsetispeed(&cfg,speed);

        /*设置数据位*/
        cfg.c_cflag &= ~CSIZE;
        switch (data_bites) /*设置数据位数*/
        {
    
    
            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 (parity)
        {
    
    
            case 1:
                cfg.c_cflag &= ~PARENB;   /* Clear parity enable */
                cfg.c_iflag &= ~INPCK;     /* Enable parity checking */
                break;
            case 2:
                cfg.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
                cfg.c_iflag |= INPCK;             /* Disnable parity checking */
                break;
            case 3:
                cfg.c_cflag |= PARENB;     /* Enable parity */
                cfg.c_cflag &= ~PARODD;   /* 转换为偶效验*/
                cfg.c_iflag |= INPCK;       /* Disnable parity checking */
                break;
            case 4:  /*as no parity*/
                cfg.c_cflag &= ~PARENB;
                cfg.c_cflag &= ~CSTOPB;
                break;
            case 5:
                cfg.c_cflag &= ~PARENB;
                cfg.c_cflag &= CSTOPB;
                break;
        }
        /* 设置停止位*/
        switch (stop_bites)
        {
    
    
            case 1:
                cfg.c_cflag &= ~CSTOPB;
                break;
            case 2:
                cfg.c_cflag |= CSTOPB;
                break;
        }
        cfg.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
        //屏蔽软件流控,让X-ON X-OFF可以发送出去
        cfg.c_iflag &= ~ (IXON | IXOFF | IXANY | ICRNL);
        cfg.c_oflag &= ~OPOST;
        cfg.c_cc[VTIME] = 150; /* 设置超时15 seconds*/
        cfg.c_cc[VMIN] = 0;
        tcflush(fd,TCIFLUSH);/* Update the cfg and do it NOW */
        //立即将新属性赋予串口
        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_com_luoye_frigo_device_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);
}

猜你喜欢

转载自blog.csdn.net/m0_46455711/article/details/105814956
今日推荐