2 * Copyright 2009 Cedric Priscal
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.example.sycapp;
20 import java.io.FileDescriptor;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
27 import android.util.Log;
29 public class SerialPort {
31 private static final String TAG = "SerialPort";
34 * Do not remove or rename the field mFd: it is used by native method close();
36 private FileDescriptor mFd;
37 private FileInputStream mFileInputStream;
38 private FileOutputStream mFileOutputStream;
40 public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
42 /* Check access permission */
43 if (!device.canRead() || !device.canWrite()) {
45 /* Missing read/write permission, trying to chmod the file */
47 su = Runtime.getRuntime().exec("/system/bin/su");
48 String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
50 su.getOutputStream().write(cmd.getBytes());
51 if ((su.waitFor() != 0) || !device.canRead()
52 || !device.canWrite()) {
53 throw new SecurityException();
55 } catch (Exception e) {
57 throw new SecurityException();
61 mFd = open(device.getAbsolutePath(), baudrate, flags);
63 Log.e(TAG, "native open returns null");
64 throw new IOException();
66 mFileInputStream = new FileInputStream(mFd);
67 mFileOutputStream = new FileOutputStream(mFd);
70 // Getters and setters
71 public InputStream getInputStream() {
72 return mFileInputStream;
75 public OutputStream getOutputStream() {
76 return mFileOutputStream;
80 private native static FileDescriptor open(String path, int baudrate, int flags);
81 public native void close();
83 System.loadLibrary("serial_port");