Android system access to serial devices

Source: Internet
Author: User

In common embedded peripherals, serial communication is a commonly used communication mechanism. This article introduces how to access serial devices in Android systems.

In Android, how to access the underlying Linux Device Driver must use HAL, that is, the hardware abstraction layer. For more information about HAL concepts and framework analysis, see the author's following blog posts.

> In-depth introduction-migration of Android system and platform development (7)-First knowledge of HAL

Http://blog.csdn.net/mr_raptor/article/details/8069588

> In-depth introduction-Android system migration and platform development (8)-HAL Stub Framework Analysis

Http://blog.csdn.net/mr_raptor/article/details/8074549

> In-depth introduction-Android system transplantation and platform development (10)-led HAL simple design case analysis

Http://blog.csdn.net/mr_raptor/article/details/8082360


1. First, we define the serial port API class, namely: SerialService, which prompts two API interfaces: read () and write () for the serial port access application.

@ Serial_app \ src \ cn \ com \ farsight \ SerialService. java

Package cn.com. farsight. serialService; import java. io. bufferedReader; import java. io. unsupportedEncodingException; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import android. util. log; public class SerialService {private static final String TAG = "SerialService"; // The underlying initialization status is private boolean isInitOk = false; // load the local database, read () and write () through JNI local code to achieve static {Log. d (TAG, "System. loadLibrary () "); System. loadLibrary ("serial_runtime");} // constructor, used to initialize the local HAL and runtimepublic SerialService () {Log. d (TAG, "SerialService ()"); // initialize the local HALisInitOk = _ init (); Log. d (TAG, "_ init ()");} // read the serial port data public String read () {Log. d (TAG, "read ()"); if (! IsInitOk) return "Serial Port initialization failed. Make sure you have connected the serial port device. "; // Because Java String is a dubyte character and serial data is a raw byte stream, bytes [] data = new byte [128] Must be converted. // read byte stream from the driver _ read (data, 128); String ret; try {// convert to Java String character ret = new String (data, "GBK ");} catch (UnsupportedEncodingException e1) {return null;} return ret;} // write String data public int write (String s) {Log. d (TAG, "write ()"); int len; try {// After the Java String is transcoded to the word throttling, write to the serial port len = _ write (s. getBytes ("GBK");} catch (UnsupportedEncodingException e1) {return-1;} return len;} private static native boolean _ init (); private static native int _ read (byte [] data, int len); private static native int _ write (byte [] data );}

2. Compile the runtime code of SerialService, that is, cn_com_farsight_SerialService_SerialService.cpp, to call the JNI function: _ init (), _ read (), _ write ().

Serial Port Hardware Abstraction Layer header file:

@ Serial_hal \ include \ serial. h

# Include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
# Include
     
      
# Define serial_HARDWARE_MODULE_ID "serial"/* Each hardware module must have a Data Structure Variable named HAL_MODULE_INFO_SYM, the type of its first member must be hw_module_t */struct serial_module_t {struct hw_module_t common; // module type};/* See hardware. description of the definition of hw_module_t in h. The first member of xxx_module_t must be of the hw_module_t type, and the second is the related information of the module. Of course, it can be left unspecified, no module information is defined here * // * The first member function of each device data structure must be of the hw_device_t type, the second is the public methods and attributes */struct serial_control_device_t {struct hw_device_t common; // device type/* supporting control APIs go here */int (* serial_read_hal) (struct serial_control_device_t * dev, char * buf, int count ); /*************************************** /int (* serial_write_hal) (struct serial_control_device_t * dev, char * buf, int count ); /*************************************** /}; /* See hardware. the hw_device_t description in h requires that the first member of the custom xxx_device_t must be of the hw_device_t type, followed by some other interface information */
     
    
   
  
 

@ Serial_runtime \ cn_com_farsight_SerialService_SerialService.cpp

The following code uses some knowledge points of JNI. For details, see:

> In-depth introduction-Android system transplantation and platform development (9)-JNI Introduction

Http://blog.csdn.net/mr_raptor/article/details/8080606

# Include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
# Include
     
      
# Include
      
        # Include
       
         # Include
        
          # Include
         
           # Include
          
            # Include ".. /include/serial. h "int fd; static int serial_device_close (struct hw_device_t * device) {LOGD (" % s E ", _ func _); struct serial_control_device_t * ctx = (struct serial_control_device_t *) device; if (ctx) {free (ctx);} close (fd); LOGD ("% s X", _ func _); return 0 ;} static int serial_read_drv (struct serial_control_device_t * dev, char * buf, int count) {LOGD ("% s E", _ func _); int len = 0; len = read (fd, buf, Count); if (len <0) {perror ("read");} LOGD ("% s X", _ func _); return len ;} static int serial_write_drv (struct serial_control_device_t * dev, char * buf, int size) {LOGD ("% s E", _ func _); int len = write (fd, buf, size); if (len <0) {perror ("write");} LOGD ("% s X", _ func _); return len ;} static int serial_device_open (const struct hw_module_t * module, const char * name, struct hw_device_t ** device) {LOGD ("% s E ",_ _ Func _); struct serial_control_device_t * dev; struct termios opt; dev = (struct serial_control_device_t *) malloc (sizeof (* dev); memset (dev, 0, sizeof (* dev); // HAL must init propertydev-> common. tag = HARDWARE_DEVICE_TAG; // you must write this dev-> common. version = 0; dev-> common. module = module; dev-> serial_read_hal = serial_read_drv; dev-> serial_write_hal = serial_write_drv; * device = & dev-> common; // MichaelTang add Open ttyUSBx char devname [PATH_MAX]; DIR * dir; struct dirent * de; dir = opendir ("/dev"); if (dir = NULL) return-1; strcpy (devname, "/dev"); char * filename = devname + strlen (devname); * filename ++ = '/'; while (de = readdir (dir) {if (de-> d_name [0] = '. '| strncmp (de-> d_name, "ttyUSB", 6) // start. will ignorcontinue; strcpy (filename, de-> d_name); if (fd = open (devname, O_RDWR | O_NOCTTY | O_NDELA Y) <0) {LOGE ("open error"); return-1 ;}else {LOGD ("open OK \ n"); break ;}} // initialize the serial port tcgetattr (fd, & opt); // tcflush (fd, TCIOFLUSH); cfsetispeed (& opt, B9600); cfsetospeed (& opt, B9600 ); // tcflush (fd, TCIOFLUSH); opt. c_cflag | = (CLOCAL | CREAD); opt. c_cflag & = ~ CSIZE; opt. c_cflag & = ~ CRTSCTS; opt. c_cflag | = CS8;/* opt. c_cflag | = PARENB; // enable; allow the input of the parity opt. c_cflag | = PARODD; // J check the input using the odd check opt. c_iflag | = (INPCK | ISTRIP); // */opt. c_iflag | = IGNPAR; opt. c_cflag & = ~ CSTOPB; opt. c_oflag = 0; opt. c_lflag = 0; tcsetattr (fd, TCSANOW, & opt); LOGD ("% s X", _ func _); return 0 ;}// define an hw_module_methods_t struct, the associated entry function static struct hw_module_methods_t serial_module_methods = {open: serial_device_open}; // defines the entry of Stub. // note that: // 1 is required. Hw_module_t inherits class // 2. The value const struct serial_module_t HAL_MODULE_INFO_SYM = {common: {tag: HARDWARE_MODULE_TAG, version_major: 1, version_minor: 0, id: Role, // module ID, the upper-layer Service uses this ID to apply the current Stub name: "serial HAL module", author: "farsight", methods: & serial_module_methods, // entry function management struct }, /* supporting APIs go here */};
          
         
        
       
      
     
    
   
  
 


4. download the relevant code:

Http://download.csdn.net/detail/mr_raptor/7033385

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.