JNI调用串口

本文详细介绍了如何在Android应用中通过JNI技术调用本地C/C++代码,实现与串口设备的通信。首先,阐述了JNI的概念及其在Android开发中的作用,然后讲解了配置Android工程以支持JNI的方法。接着,重点讲解了C/C++代码中打开、读写及关闭串口的关键步骤,并给出了相应的示例代码。最后,讨论了在实际应用中可能遇到的问题和解决方案,帮助开发者成功地在Android平台上进行串口通信。
摘要由CSDN通过智能技术生成
SerialTool.c

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.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: cedric_serial_SerialPort
* Method: open
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT jobject JNICALL Java_com_example_serialtool_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) {
/* 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", 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");
/* 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_com_example_serialtool_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);
}

Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := SerialTool
LOCAL_SRC_FILES := SerialTool.c
LOCAL_LDLIBS := -llog

include $(BUILD_SHARED_LIBRARY)

SerialPort.java
package com.example.serialtool;

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

/*
* 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) 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 777 " + 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);
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);
public native void close();
static {
System.loadLibrary("SerialTool");
}
}

MainActivity.java
package com.example.serialtool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.text.format.Formatter;
//import com.huayu.io.SerialPort;
import android.util.Log;

public class MainActivity extends Activity {
private SerialPort mySerialPort = null;
private EditText sendText;
private EditText baudText;
private EditText portText;
private TextView textStatus;
private TextView textRecv;
private boolean openFlag = false;
private Thread mt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendText = (EditText)findViewById(R.id.editText1);
baudText = (EditText)findViewById(R.id.editText2);
portText = (EditText)findViewById(R.id.editText3);
sendText.setText("this send text");
baudText.setText("19200");
portText.setText("ttyMT0");
textStatus = (TextView)findViewById(R.id.textView1);
textRecv = (TextView)findViewById(R.id.textView2);
textStatus.setText("this is status");
textRecv.setText("this is received text");
}
protected final Handler mh = new Handler(){
public void handleMessage(Message msg){
/*
if(textRecv.getText().toString().length() > 256)
textRecv.setText("");
textRecv.append(msg.obj.toString());
*/
textRecv.setText(msg.obj.toString());
}
};
private Runnable mThread = new Runnable(){

@Override
public void run() {
openFlag = true;
InputStream instream = mySerialPort.getInputStream();
long fileLen = 0;
long startTime = System.currentTimeMillis();
List<String> allData = new ArrayList<String>();
final long ROWBYTECOUNT = 64;
while(openFlag)
{
int ia = 0;
try {
ia = instream.available();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ia = 0;
}
if(ia>0)
{
Log.i("thread", "have byte " + ia);
byte[] buf = new byte[1024];
try {
int len = instream.read(buf, 0, ia);
if(len > 0)
{
fileLen += len;
int current=0;
StringBuffer stringBuffer = new StringBuffer();
for(int i=0; i<len; i++)
{
current = current<<1+buf[i];
if((i%32!=0)||(i==len-1)){
stringBuffer.append(Integer.toHexString(current)+" ");
current=0;
}
if(i!=0&&i%ROWBYTECOUNT==0){
allData.add(0,stringBuffer.toString()+"\n");
stringBuffer = new StringBuffer();
}
}
long time = (System.currentTimeMillis()-startTime)/1000;
if(time>0){
if(stringBuffer.length()>60){
allData.remove(allData.size()-1);
}
long dataLen = fileLen/time;
Message msg = mh.obtainMessage();
String firstLine = time+"s "+Formatter.formatFileSize(getApplicationContext(), dataLen)+"\n";
StringBuffer msgStr = new StringBuffer(firstLine);
for(String lin:allData){
msgStr.append(lin);
}
msg.obj =msgStr.toString();
mh.sendMessage(msg);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
public void onOpen(View v)
{
textStatus.setText("opening");
if(mySerialPort == null)
{
String devname = "/dev/" + portText.getText().toString();
int baud = Integer.parseInt(baudText.getText().toString()); //115200;//baudText.getText();
try {
mySerialPort = new SerialPort(new File(devname), baud);
mt = new Thread(mThread);
mt.start();
textStatus.setText("open ok");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textStatus.setText("open ok");
}
else
{
textStatus.setText("serial port already opened!");
}
}
public void onClose(View v)
{
openFlag = false;
textStatus.setText("closing");
if(mySerialPort != null)
{
try {
mySerialPort.getInputStream().close();
mySerialPort.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
mySerialPort.close();
mySerialPort = null;
textStatus.setText("close ok");
}
else
{
textStatus.setText("serial port already closed");
}
}
public void onSend(View v)
{
textStatus.setText("onSend");
if(mySerialPort != null)
{
OutputStream outstream = mySerialPort.getOutputStream();
String s = sendText.getText().toString();
try {
outstream.write(s.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
textStatus.setText("please do open firstly");
}
}
}



/***************************************************实例2***************************************************/
1.   本地类 TtyNativeControl
package  com.notioni.uart.manager;
import   Java .lang.ref.WeakReference;
import   Android .os.Handler;
import   android .os.Looper;
import  android.os.Message;
import  android.util.Log;
/**
本地方法类
*/
public   class  TtyNativeControl {
private   final   static  String  TAG  =  "TtyNativeControl" ;
static {
System. loadLibrary ( "uart_ctl" );
}
private   static   final   int   TTY_MSG_RECEIVE  = 1;
private   static   final   int   TTY_CLOSE_DEVICE  =  TTY_MSG_RECEIVE +1;
private  EventHandler  mEventHandler ;
private  ReceiveCallback  mReceiveCallBack ;
TtyNativeControl(){
mReceiveCallBack  =  null ;
Looper looper;
if ((looper = Looper. myLooper ()) !=  null ){
mEventHandler  =  new  EventHandler( this , looper);
} else   if ((looper = Looper. getMainLooper ()) !=  null ){
mEventHandler  =  new  EventHandler( this , looper);
} else {
mEventHandler  =  null ;
}
native_setup( new  WeakReference<TtyNativeControl>( this ));
}
/**
打开驱动
@return   是否打开成功
*/
public   int  openTty(){
return  _openTty();
}
/**
关闭驱动,需要一定时间,所以采用 Handler 机制
*/
public   int  closeTty(){
// mEventHandler.obtainMessage(TTY_CLOSE_DEVICE).sendToTarget();
// return 1;
return  _closeTty();
}
/**
发送数据
@param  data
@return
*/
public   int  sendMsgToTty( byte [] data){
return  _sendMsgToTty(data);
}
/**
接收数据
@param  callback
*/
public   final   void  receiveMsgFromTty(ReceiveCallback callback){
mReceiveCallBack  = callback;
_receiveMsgFromTty();
}
/**
设置串口数据位,校验位 , 速率,停止位
@param  databits  数据位   取值   7 8
@param  event  校验类型   取值 N ,E, O,
@param  speed  速率   取值  2400,4800,9600,115200
@param  stopBit  停止位   取值 或者  2
*/
public   int  configTty( int  databits, char  event, int  speed, int  stopBit){
return  _configTty(databits, event, speed, stopBit);
}
/**
@param  mode  是否使用原始模式 (Raw Mode) 方式来通讯   取值 0,1,2  说明: 0=nothing,1=Raw mode,2=no raw mode
@param
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值