Android serial port (android serial port api) and androidserial

Source: Internet
Author: User

Android serial port (android serial port api) and androidserial

A few days ago, the company needed to use the logging machine statistics using the Development Board equipped with the Android system. For siege lions, they needed to read and write the serial port of the logging machine on the Android platform, after searching for something on the internet, I found that the android serial port api on google code can be used. After the wall is reached, I got the source code and found a demo, which is good, in this post, the source code of the serial port api is easy to implement a read/write serial port, which is of course written in native, if there are still some children's shoes that are unclear about using jni and native on android, you can jump to my previous post and click me.


Create a tool class in the Android project. This class is used to open the path serial port in the parameter by calling the Native method openSerialPort declared in Jni. The specific parameter of this serial port is: baudrate bit rate, databits data bit, stopbits stop bit, and parity. if it is enabled successfully, this method will return the file description instance of the path serial port, so that you can obtain the IO stream that can read and write the serial port, the serial port can be used as a file for US (it is indeed a device file on linux ). if it succeeds, press the different command or data protocol R/W serial port.

/** * @Title: SerialPortUtil.java * @Description: the util of serial port * @author Jesse   * @date Nov 21, 2014 10:10:49 AM * @version V1.0   */public class SerialPortUtil {private final String TAG = SerialPortUtil.class.getSimpleName();private static SerialPortUtil mInstance = null;private StudioJni studioJni = StudioJni.getInstance();private FileDescriptor mFd;private FileInputStream mFileInputStream = null; private FileOutputStream mFileOutputStream = null; private boolean isRunning = false;public static SerialPortUtil getInstance(){if(mInstance == null){mInstance = new SerialPortUtil();}return mInstance;}public boolean openSerialPort(String path,int baudrate,int databits, int stopbits, char parity){Log.i(TAG, "openSerialPort,path:" + path + " ,baudrate:" + baudrate + " ,databits:" +databits+ " ,stopbits:" + stopbits + " ,parity:" + parity);if(isRunning){Log.i(TAG, "openSerialPort,the serial port is running");return false;}mFd = studioJni.serialPortOpen(path, baudrate,databits,stopbits,parity);if(mFd != null){isRunning = true;mFileInputStream = new FileInputStream(mFd);      mFileOutputStream = new FileOutputStream(mFd); }else{Log.i(TAG, "openSerialPort," + "the deivce is null");}return isRunning;}public void closeSerialPort(){Log.i(TAG, "closeSerialPort");studioJni.serialPortClose();isRunning = false;}public InputStream getInputStream() {      return mFileInputStream;  }    public OutputStream getOutputStream() {      return mFileOutputStream;  }  }
In the Native implementation, the configured parameters are used to open the serial port and the serial port is configured. If the configuration succeeds, a java file description is returned. If the configuration fails, null is returned.

JNIEXPORT jobject JNICALL serial_port_open(JNIEnv *env,jclass thiz,jstring path, jint baudrate,                                           jint databits,jint stopbits,jchar parity){    LOGI(CAMERA_TAG,"serial_port_open");    int fd;    speed_t speed;    jobject mFileDescriptor;    /* Check arguments */    {        speed = getBaudrate(baudrate);        if (speed == -1) {            /* TODO: throw an exception */            LOGI(CAMERA_TAG,"serial_port_open,Invalid baudrate");            LOGE(CAMERA_TAG,"serial_port_open,Invalid baudrate");            return NULL;        }    }    /* Opening device */    {        jboolean iscopy;        const char *path_utf = env -> GetStringUTFChars(path, &iscopy);        LOGI(CAMERA_TAG,"serial_port_open,Opening serial port %s with flags 0x%x", path_utf, O_RDWR);        fd = open(path_utf, O_RDWR);        LOGI(CAMERA_TAG,"serial_port_open,open() fd = %d", fd);        env->ReleaseStringUTFChars(path, path_utf);        if (fd == -1)        {            /* Throw an exception */            LOGI(CAMERA_TAG,"serial_port_open,Cannot open port");            LOGE(CAMERA_TAG,"serial_port_open","Cannot open port");            /* TODO: throw an exception */            return NULL;        }    }    /* Configure device */    {        struct termios cfg;        LOGI(CAMERA_TAG,"serial_port_open,Configuring serial port");        if (tcgetattr(fd, &cfg))        {            LOGI(CAMERA_TAG,"serial_port_open,tcgetattr() failed");            LOGE(CAMERA_TAG,"serial_port_open","tcgetattr() failed");            close(fd);            /* TODO: throw an exception */            return NULL;        }        cfmakeraw(&cfg);        cfsetispeed(&cfg, speed);        cfsetospeed(&cfg, speed);        if (tcsetattr(fd, TCSANOW, &cfg))        {            LOGI(CAMERA_TAG,"serial_port_open","tcsetattr() failed");            LOGE(CAMERA_TAG,"serial_port_open","tcsetattr() failed");            close(fd);            /* TODO: throw an exception */            return NULL;        }        set_Parity(fd, databits, stopbits, parity);        FD = fd;    }    /* 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;}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.