Android serial communication programming and serial protocol analysis _android

Source: Internet
Author: User
Tags svn hex code

Android Serial Communication programming: Embedded programming and wearable devices and smart devices will be used in the serial port, here to take you analysis,

One, Android serial communication

Serial communication using a Third-party open source project to achieve the serial port data transceiver.

1. Use of the SerialPort API and JNI for http://code.google.com/p/android-serialport-api/projects;
2. Support 4 serial port at the same time send and receive, has the automatic sending function, the transceiver mode can choose TXT or hex mode;
3. n,8,1, no choice;
4. In order to reduce the interface of cotton situation, the receiving area of the refresh using a separate thread for timing refresh;
5. The data of the sending area and some setting items are automatically saved when the program is closed and automatically loaded when it is opened.
6. JNI recompiled with the latest ndkr8b

Simple Writing steps:

1. Create a new project and name yourself
2. Copy SerialPort APIs and JNI folders directly to the new project, and if you don't want to compile jni yourself, even Libs folders are copied together
3. Go to the official Android website to download NDK, unzip, transfer to JNI directory in cmd, and execute absolute path \ndk-build
4. Encapsulate a tool class yourself or use the SerialPort class directly, and give a direct use example:
Direct plagiarism of the original project Serialportactivity.java, and a little change, focus on the change here
Mserialport = Mapplication.getserialport ();
This can be changed into
New SerialPort (New File ("/dev/s3c2410_serial0"), 9600, 0);//com0, baud rate 9600
5. The use of Serialportfinder is no good to talk about, after the instantiation of the. Getalldevicespath () will be able to get all the equipment.
Other such as data conversion, please refer to the source code

Source 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

Second, the Serial Communication Protocol analysis

1. Basic Communication Format

Field description Length (bytes)
Starting character 0F, hex code 1
Information type one byte, hexadecimal code (0F,F0,FF etc Reservation code not) 1
The length of information is the length of the information content, the ASCII notation (0~9,a~f, the maximum length is 256) (for example, 11 is long, hexadecimal is 0B, then two bytes is written 0x30 0x42).
Note: Because the maximum length of 256 does not meet the requirements of some instructions, the length is extended, the following is the extension description:
If the first byte has a maximum bit of 1, the extension length is indicated. In the extended-length state, the other 15 bytes are saved by the 16-in-big-endian mode to save the length. For example: 0x80 0x12 represents a length of 0x001 2,0x81 0x12 represents a length of 0x0112. 2
Information content a set of hexadecimal code N
Verifies a byte, which is a hexadecimal code, from the type of the message to the object number of all the code of the different or. 1
Terminator F0, one byte, hexadecimal code (in order to ensure reliability, car machine issued terminator for F0 FF) 1

2. Protocol resolution


/** * Read terminal data * @author Administrator/Private class Readthread extends Thread {@Override 
 
      public void Run () {super.run (); 
      Defines the maximum length of a package int maxLength = 2048; 
      byte[] buffer = new Byte[maxlength]; 
      Each receive the actual length int available = 0; 
      The total length of the package that is currently received is int currentlength = 0; 
 
      Protocol Header length 4 bytes (Start character 1, type 1, length 2) int headerlength = 4; 
          while (!isinterrupted ()) {try {available = minputstream.available (); 
              if (available > 0) {//prevent overflow from 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; 
       Resolves the current package if the packet is currently larger than the length of the header while (Currentlength >= headerlength) {//Fetch the first byte of the header 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, the package is problematic, discard if (contentlenght <= 0 | | | contentlenght > MAXLENGTH-5) { 
            currentlength = 0; 
          Break 
          ///If you are currently getting a length smaller than the entire package, jump out of the loop and wait to continue receiving the data int factpacklen = Contentlenght + 5; 
          if (Currentlength < Contentlenght + 5) {break; 
          A full package is produced//Proceonepacket (Buffer,i,factpacklen); 
          ondatareceived (buffer, cursor, factpacklen); 
          Currentlength-= Factpacklen;  
        cursor + = Factpacklen;  The//residue bytes are moved to the buffer first if (currentlength > 0 && cursor > 0) {system.arraycopy (buffer, CursOr, buffer, 0, currentlength); /** * Get Protocol Content Length * @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 ("received letter 
    Interest "); 
    byte[] buf = new Byte[packlen]; 
    System.arraycopy (buffer, index, buf, 0, Packlen);  
  Protocolanalyze.getinstance (MyHandler). Analyze (BUF); 

 }

Thank you for reading, I hope to help you, thank you for your support for this site!

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.