]> sigrok.org Git - sigrok-androidutils.git/blob - src/org/sigrok/androidutils/UsbSupplicant.java
0f219a87c932c2dbc7466762b1865c0dea00b3da
[sigrok-androidutils.git] / src / org / sigrok / androidutils / UsbSupplicant.java
1 /*
2  * This file is part of the sigrok-androidutils project.
3  *
4  * Copyright (C) 2014 Marcus Comstedt <marcus@mc.pp.se>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 /*
20  * Copyright (C) 2011 The Android Open Source Project
21  *
22  * Licensed under the Apache License, Version 2.0 (the "License");
23  * you may not use this file except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  * http://www.apache.org/licenses/LICENSE-2.0
27  *
28  * Unless required by applicable law or agreed to in writing, software
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  */
34
35 package org.sigrok.androidutils;
36
37 import android.app.PendingIntent;
38 import android.content.BroadcastReceiver;
39 import android.content.Context;
40 import android.content.Intent;
41 import android.content.IntentFilter;
42 import android.content.res.Resources;
43 import android.content.res.XmlResourceParser;
44 import android.hardware.usb.UsbDevice;
45 import android.hardware.usb.UsbInterface;
46 import android.hardware.usb.UsbManager;
47 import android.util.Log;
48 import java.io.IOException;
49 import java.util.HashMap;
50 import java.util.Vector;
51 import org.xmlpull.v1.XmlPullParser;
52 import org.xmlpull.v1.XmlPullParserException;
53
54 public class UsbSupplicant
55 {
56         static final String ACTION_USB_PERMISSION =
57         "org.sigrok.androidutils.USB_PERMISSION";
58
59         protected final Context context;
60         protected final UsbManager manager;
61         private final BroadcastReceiver permReceiver;
62         private final BroadcastReceiver hotplugReceiver;
63         private final IntentFilter permFilter;
64         private final IntentFilter hotplugFilter;
65         private final Vector<DeviceFilter> deviceFilters;
66
67         // The code in the following inner class is taken from AOSP,
68         // which is licensed under the Apache License, Version 2.0.
69         private static class DeviceFilter {
70                 // USB Vendor ID (or -1 for unspecified)
71                 public final int mVendorId;
72                 // USB Product ID (or -1 for unspecified)
73                 public final int mProductId;
74                 // USB device or interface class (or -1 for unspecified)
75                 public final int mClass;
76                 // USB device subclass (or -1 for unspecified)
77                 public final int mSubclass;
78                 // USB device protocol (or -1 for unspecified)
79                 public final int mProtocol;
80
81                 public DeviceFilter(int vid, int pid, int clasz, int subclass, int protocol) {
82                         mVendorId = vid;
83                         mProductId = pid;
84                         mClass = clasz;
85                         mSubclass = subclass;
86                         mProtocol = protocol;
87                 }
88
89                 public DeviceFilter(UsbDevice device) {
90                         mVendorId = device.getVendorId();
91                         mProductId = device.getProductId();
92                         mClass = device.getDeviceClass();
93                         mSubclass = device.getDeviceSubclass();
94                         mProtocol = device.getDeviceProtocol();
95                 }
96
97                 public static DeviceFilter read(XmlPullParser parser)
98                                 throws XmlPullParserException, IOException {
99                         int vendorId = -1;
100                         int productId = -1;
101                         int deviceClass = -1;
102                         int deviceSubclass = -1;
103                         int deviceProtocol = -1;
104
105                         int count = parser.getAttributeCount();
106                         for (int i = 0; i < count; i++) {
107                                 String name = parser.getAttributeName(i);
108                                 // All attribute values are ints
109                                 int value = Integer.parseInt(parser.getAttributeValue(i));
110
111                                 if ("vendor-id".equals(name)) {
112                                         vendorId = value;
113                                 } else if ("product-id".equals(name)) {
114                                         productId = value;
115                                 } else if ("class".equals(name)) {
116                                         deviceClass = value;
117                                 } else if ("subclass".equals(name)) {
118                                         deviceSubclass = value;
119                                 } else if ("protocol".equals(name)) {
120                                         deviceProtocol = value;
121                                 }
122                         }
123                         return new DeviceFilter(vendorId, productId,
124                                         deviceClass, deviceSubclass, deviceProtocol);
125                 }
126
127                 private boolean matches(int clasz, int subclass, int protocol) {
128                         return ((mClass == -1 || clasz == mClass) &&
129                                         (mSubclass == -1 || subclass == mSubclass) &&
130                                         (mProtocol == -1 || protocol == mProtocol));
131                 }
132
133                 public boolean matches(UsbDevice device) {
134                         if (mVendorId != -1 && device.getVendorId() != mVendorId)
135                                 return false;
136                         if (mProductId != -1 && device.getProductId() != mProductId)
137                                 return false;
138
139                         // Check device class/subclass/protocol.
140                         if (matches(device.getDeviceClass(), device.getDeviceSubclass(),
141                                         device.getDeviceProtocol()))
142                                 return true;
143
144                         // If device doesn't match, check the interfaces.
145                         int count = device.getInterfaceCount();
146                         for (int i = 0; i < count; i++) {
147                                 UsbInterface intf = device.getInterface(i);
148                                 if (matches(intf.getInterfaceClass(), intf.getInterfaceSubclass(),
149                                                 intf.getInterfaceProtocol()))
150                                         return true;
151                         }
152
153                         return false;
154                 }
155
156                 @Override
157                 public String toString() {
158                         return "DeviceFilter[mVendorId=" + mVendorId + ",mProductId=" + mProductId +
159                                         ",mClass=" + mClass + ",mSubclass=" + mSubclass +
160                                         ",mProtocol=" + mProtocol + "]";
161                 }
162         }
163
164         public UsbSupplicant(Context ctx, int device_filter_resource)
165         {
166                 context = ctx;
167                 manager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE);
168                 permReceiver = new BroadcastReceiver() {
169                         @Override
170                         public void onReceive(Context context, Intent intent) {
171                                 String action = intent.getAction();
172                                 if (ACTION_USB_PERMISSION.equals(action)) {
173                                         permissionCallback((UsbDevice)intent.getParcelableExtra(
174                                                 UsbManager.EXTRA_DEVICE), intent.getBooleanExtra(
175                                                 UsbManager.EXTRA_PERMISSION_GRANTED, false));
176                                 }
177                         }
178                 };
179                 hotplugReceiver = new BroadcastReceiver() {
180                         @Override
181                         public void onReceive(Context context, Intent intent) {
182                                 if (intent != null && UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
183                                         attachCallback((UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
184                                 } else if (intent != null && UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) {
185                                         detachCallback((UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
186                                 }
187                         }
188                 };
189                 permFilter = new IntentFilter(ACTION_USB_PERMISSION);
190                 hotplugFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
191                 hotplugFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
192                 deviceFilters = new Vector<DeviceFilter>();
193                 addDeviceFilters(ctx.getResources(), device_filter_resource);
194         }
195
196         private void addDeviceFilters(Resources res, int res_id)
197         {
198                 XmlResourceParser parser = res.getXml(res_id);
199                 if (parser == null) {
200                         Log.w("UsbSupplicant", "Unable to get device filter resource");
201                         return;
202                 }
203                 deviceFilters.clear();
204                 try {
205                         while (parser.next() != XmlPullParser.END_DOCUMENT) {
206                                 if (parser.getEventType() == XmlPullParser.START_TAG) {
207                                         if ("usb-device".equals(parser.getName()))
208                                                 deviceFilters.add(DeviceFilter.read(parser));
209                                 }
210                         }
211                 } catch (IOException e) {
212                         Log.wtf("UsbSupplicant",
213                                 "Failed to parse device filter resource", e);
214                 } catch (XmlPullParserException e) {
215                         Log.wtf("UsbSupplicant",
216                                 "Failed to parse device filter resource", e);
217                 }
218         }
219
220         protected boolean interesting(UsbDevice dev)
221         {
222                 if (dev == null)
223                         return false;
224
225                 for (DeviceFilter f : deviceFilters)
226                         if (f.matches(dev))
227                                 return true;
228
229                 return false;
230         }
231
232         protected void askFor(UsbDevice dev)
233         {
234                 manager.requestPermission(dev, PendingIntent.getBroadcast(context, 0,
235                         new Intent(ACTION_USB_PERMISSION), 0));
236         }
237
238         public void start()
239         {
240                 context.registerReceiver(permReceiver, permFilter);
241                 context.registerReceiver(hotplugReceiver, hotplugFilter);
242                 HashMap<String,UsbDevice> devlist = manager.getDeviceList();
243                 for (UsbDevice dev : devlist.values()) {
244                         if (interesting(dev) && !manager.hasPermission(dev)) {
245                                 Log.d("UsbSupplicant", "found interesting device " + dev);
246                                 askFor(dev);
247                         }
248                 }
249         }
250
251         public void stop()
252         {
253                 context.unregisterReceiver(hotplugReceiver);
254                 context.unregisterReceiver(permReceiver);
255         }
256
257         protected void permissionCallback(UsbDevice dev, boolean granted)
258         {
259                 Log.d("UsbSupplicant", "permission " +
260                                 (granted ? "granted" : "denied") + " for device " + dev);
261         }
262
263         protected void attachCallback(UsbDevice dev)
264         {
265                 if (interesting(dev) && !manager.hasPermission(dev))
266                         askFor(dev);
267         }
268
269         protected void detachCallback(UsbDevice dev)
270         {
271         }
272 }