]> sigrok.org Git - sigrok-androidutils.git/blob - src/org/sigrok/androidutils/UsbHelper.java
e16b33d7242fcc6ef40f4d52351cfdface668ccd
[sigrok-androidutils.git] / src / org / sigrok / androidutils / UsbHelper.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 package org.sigrok.androidutils;
21
22 import android.content.Context;
23 import android.hardware.usb.UsbDevice;
24 import android.hardware.usb.UsbDeviceConnection;
25 import android.hardware.usb.UsbManager;
26 import android.util.Log;
27 import java.util.HashMap;
28
29 public final class UsbHelper
30 {
31         private static UsbManager manager;
32
33         public static void setContext(Context ctx)
34         {
35                 if (ctx == null)
36                         manager = null;
37                 else
38                         manager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE);
39         }
40
41         private static int open(UsbManager manager, String name, int mode)
42         {
43                 if (manager == null) {
44                         Log.w("UsbHelper", "no manager");
45                         return -1;
46                 }
47                 HashMap<String,UsbDevice> devlist = manager.getDeviceList();
48                 UsbDevice dev = (devlist == null ? null : devlist.get(name));
49                 if (dev == null)
50                         return -1;
51                 if (!manager.hasPermission(dev))
52                         return -1;
53                 UsbDeviceConnection conn = manager.openDevice(dev);
54                 return (conn == null ? -1 : conn.getFileDescriptor());
55         }
56
57         public static int open(String name, int mode)
58         {
59                 try {
60                         return open(manager, name, mode);
61                 } catch (Exception e) {
62                         Log.w("UsbHelper", "caught exception " + e);
63                         return -1;
64                 }
65         }
66 }
67