Android Using Serial Communication and Protocol Resolution

Keywords: Android Google svn less

Special Statement: Respect for Originality, Link to the Origin: http://blog.csdn.net/junfeng120125/article/details/9328947

1. android Serial Communication
Serial communication adopts a third-party open source project to realize serial data transmission and reception.
1. Use http://code.google.com/p/android-serialport-api/ serialport api and jni of the project;
2. Supports simultaneous sending and receiving of 4 serial ports. It has the function of automatic sending at regular intervals. The mode of sending and receiving can be Txt or Hex.
3. n, 8, 1, no choice;
4. In order to alleviate the situation of interface carton, a separate thread is used to refresh the receiving area regularly.
5. Data in the sending area and some settings will be saved automatically when the program closes and loaded automatically when it opens.
6. jni recompiled it with the latest NDKr8b

Simple writing steps:
1. Create a new project and name it yourself.
2. Copy the serialport api and jni folder directly to the new project. If you don't want to compile jni yourself, even the libs folder will be copied together.
3. Download NDK from the official android website, decompress it, go to jni directory in CMD, and execute absolute path ndk-build.
4. Encapsulate a tool class by yourself or use SerialPort class directly, for example:
Direct plagiarism of SerialPortActivity.java from the original project, with a slight change, focusing on here
mSerialPort = mApplication.getSerialPort();
Here it can be changed to
New Serial Port (new File ("/dev/s3c2410_serial0"), 9600, 0);//COM0, baud rate 9600
5. There's nothing to say about the use of Serial PortFinder. After instantiation, you can get all the devices with. getAllDevicesPath().
For others, such as data conversion, please refer to the source code.

Source code can refer to Google android-serialport-api example
http://code.google.com/p/android-serialport-api/source/checkout
svn checkout http://android-serialport-api.googlecode.com/svn/trunk

2. Analysis of Serial Communication Protocol
1. Basic communication format
Field description length (bytes)
Starter 0F, hexadecimal code 1
The information type is one byte, hexadecimal code (0F,F0,FF and other reserved codes are not used)1
Information length is the length of information content, and ASCII code represents (0-9, A-F, maximum length 256) (e.g. 11, hexadecimal is 0B, then two bytes are written 0x300 x42).
Note: Because the maximum length of 256 can not meet the requirements of some instructions, the length is extended. The following is an extension description:
If the highest bit of the first byte is 1, the extension length is indicated. In the extended length state, the other 15 bytes are saved in the hexadecimal large-end mode. For example: 0x800x12 means the length is 0x001 2, 0x81 0x12 means the length is 0x0112. Two
Information content A set of hexadecimal codes N
Checking a byte, hexadecimal code, is the exclusive or of all codes from the type of self-information to the object number. One
End character F0, one byte, hexadecimal code (for reliability, the end character of locomotive issuance is F0 FF)1
2. Protocol Resolution

/** 
     * Read Terminal Device Data 
     * @author Administrator 
     */  
    private class ReadThread extends Thread {  

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

            // Define the maximum length of a package  
            int maxLength = 2048;  
            byte[] buffer = new byte[maxLength];  
            // Real length per receipt  
            int available = 0;  
            // The total length of packets that have been received at present  
            int currentLength = 0;  
            // Protocol header length 4 bytes (start 1, type 1, length 2)  
            int headerLength = 4;  

            while (!isInterrupted()) {  
                try {  
                    available = mInputStream.available();  
                    if (available > 0) {  
                        // Prevent overflow caused by exceeding the maximum length of the array  
                        if (available > maxLength - currentLength) {  
                            available = maxLength - currentLength;  
                        }  
                        mInputStream.read(buffer, currentLength, available);  
                        currentLength += available;  
                    }  

                }  
                catch (Exception e) {  
                    e.printStackTrace();  
                }  

                int cursor = 0;  
                // If the current received packet is larger than the length of the header, the current packet is parsed  
                while (currentLength >= headerLength) {  
                    // Get the first byte of the head  
                    if (buffer[cursor] != 0x0F) {  
                        --currentLength;  
                        ++cursor;  
                        continue;  
                    }  

                    int contentLenght = parseLen(buffer, cursor, headerLength);  
                    // If the length of the content package is greater than the maximum content length or less than or equal to 0, then the package has a problem and is discarded.  
                    if (contentLenght <= 0 || contentLenght > maxLength - 5) {  
                        currentLength = 0;  
                        break;  
                    }  
                    // If the length of the current acquisition is less than the length of the entire packet, jump out of the loop and wait to continue receiving data.  
                    int factPackLen = contentLenght + 5;  
                    if (currentLength < contentLenght + 5) {  
                        break;  
                    }  

                    // A complete package is generated  
                    // proceOnePacket(buffer,i,factPackLen);  
                    onDataReceived(buffer, cursor, factPackLen);  
                    currentLength -= factPackLen;  
                    cursor += factPackLen;   
                }  
                // Remaining bytes moved to the head of the buffer  
                if (currentLength > 0 && cursor > 0) {  
                    System.arraycopy(buffer, cursor, buffer, 0, currentLength);  
                }  
            }  
        }  
    }  

    /** 
     * Get the length of protocol content 
     * @param header 
     * @return 
     */  
    public int parseLen(byte buffer[], int index, int headerLength) {  

//      if (buffer.length - index < headerLength) { return 0; }  
        byte a = buffer[index + 2];  
        byte b = buffer[index + 3];  
        int rlt = 0;  
        if (((a >> 7) & 0x1) == 0x1) {  
            rlt = (((a & 0x7f) << 8) | b);  
        }  
        else {  
            char[] tmp = new char[2];  
            tmp[0] = (char) a;  
            tmp[1] = (char) b;  
            String s = new String(tmp, 0, 2);  
            rlt = Integer.parseInt(s, 16);  
        }  

        return rlt;  
    }  

protected void onDataReceived(final byte[] buffer, final int index, final int packlen) {  
        System.out.println("Receive the message");  
        byte[] buf = new byte[packlen];  
        System.arraycopy(buffer, index, buf, 0, packlen);  
        ProtocolAnalyze.getInstance(myHandler).analyze(buf);   
    } 

Posted by Travist6983 on Tue, 25 Jun 2019 11:11:11 -0700