1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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 an
14  * limitations under the License.
15  */
16 
17 package com.android.server;
18 
19 import android.annotation.EnforcePermission;
20 import android.content.Context;
21 import android.hardware.ISerialManager;
22 import android.os.ParcelFileDescriptor;
23 
24 import java.io.File;
25 import java.util.ArrayList;
26 
27 public class SerialService extends ISerialManager.Stub {
28 
29     private final Context mContext;
30     private final String[] mSerialPorts;
31 
SerialService(Context context)32     public SerialService(Context context) {
33         mContext = context;
34         mSerialPorts = context.getResources().getStringArray(
35                 com.android.internal.R.array.config_serialPorts);
36     }
37 
38     @EnforcePermission(android.Manifest.permission.SERIAL_PORT)
getSerialPorts()39     public String[] getSerialPorts() {
40         super.getSerialPorts_enforcePermission();
41 
42         ArrayList<String> ports = new ArrayList<String>();
43         for (int i = 0; i < mSerialPorts.length; i++) {
44             String path = mSerialPorts[i];
45             if (new File(path).exists()) {
46                 ports.add(path);
47             }
48         }
49         String[] result = new String[ports.size()];
50         ports.toArray(result);
51         return result;
52     }
53 
54     @EnforcePermission(android.Manifest.permission.SERIAL_PORT)
openSerialPort(String path)55     public ParcelFileDescriptor openSerialPort(String path) {
56         super.openSerialPort_enforcePermission();
57 
58         for (int i = 0; i < mSerialPorts.length; i++) {
59             if (mSerialPorts[i].equals(path)) {
60                 return native_open(path);
61             }
62         }
63         throw new IllegalArgumentException("Invalid serial port " + path);
64     }
65 
native_open(String path)66     private native ParcelFileDescriptor native_open(String path);
67 }
68