QGCActivity.java 25.9 KB
Newer Older
1
package org.mavlink.qgroundcontrol;
dogmaphobic's avatar
dogmaphobic committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

/* Copyright 2013 Google Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * Project home page: http://code.google.com/p/usb-serial-for-android/
 */
///////////////////////////////////////////////////////////////////////////////////////////
//  Written by: Mike Goza April 2014
//
//  These routines interface with the Android USB Host devices for serial port communication.
26
//  The code uses the usb-serial-for-android software library.  The QGCActivity class is the
dogmaphobic's avatar
dogmaphobic committed
27 28 29 30 31
//  interface to the C++ routines through jni calls.  Do not change the functions without also
//  changing the corresponding calls in the C++ routines or you will break the interface.
//
////////////////////////////////////////////////////////////////////////////////////////////

32
import java.util.ArrayList;
dogmaphobic's avatar
dogmaphobic committed
33 34 35 36
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
37 38
import java.util.Timer;
import java.util.TimerTask;
dogmaphobic's avatar
dogmaphobic committed
39 40 41 42 43 44 45
import java.io.IOException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
46 47 48 49
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
dogmaphobic's avatar
dogmaphobic committed
50 51
import android.widget.Toast;
import android.util.Log;
52
import android.os.PowerManager;
dogmaphobic's avatar
dogmaphobic committed
53
import android.os.Bundle;
54 55
import android.app.PendingIntent;
import android.view.WindowManager;
dogmaphobic's avatar
dogmaphobic committed
56 57 58 59 60

import com.hoho.android.usbserial.driver.*;
import org.qtproject.qt5.android.bindings.QtActivity;
import org.qtproject.qt5.android.bindings.QtApplication;

61
public class QGCActivity extends QtActivity
dogmaphobic's avatar
dogmaphobic committed
62
{
63
    public  static int BAD_PORT = 0;
64
    private static QGCActivity m_instance;
dogmaphobic's avatar
dogmaphobic committed
65 66 67 68 69 70 71 72
    private static UsbManager m_manager;    //  ANDROID USB HOST CLASS
    private static List<UsbSerialDriver> m_devices; //  LIST OF CURRENT DEVICES
    private static HashMap<Integer, UsbSerialDriver> m_openedDevices;   //  LIST OF OPENED DEVICES
    private static HashMap<Integer, UsbIoManager> m_ioManager;	//  THREADS FOR LISTENING FOR INCOMING DATA
    private static HashMap<Integer, Integer> m_userData;    //  CORRESPONDING USER DATA FOR OPENED DEVICES.  USED IN DISCONNECT CALLBACK
    //  USED TO DETECT WHEN A DEVICE HAS BEEN UNPLUGGED
    private BroadcastReceiver m_UsbReceiver = null;
    private final static ExecutorService m_Executor = Executors.newSingleThreadExecutor();
73
    private static final String TAG = "QGC_QGCActivity";
74
    private static PowerManager.WakeLock m_wl;
75 76
    private static String USB_ACTION = "org.mavlink.qgroundcontrol.action.USB_PERMISSION";
    private TaiSync taiSync = null;
dogmaphobic's avatar
dogmaphobic committed
77

78 79
    public static Context m_context;

dogmaphobic's avatar
dogmaphobic committed
80 81 82 83 84 85
    private final static UsbIoManager.Listener m_Listener =
            new UsbIoManager.Listener()
            {
                @Override
                public void onRunError(Exception eA, int userDataA)
                {
dogmaphobic's avatar
dogmaphobic committed
86
                    Log.e(TAG, "onRunError Exception");
dogmaphobic's avatar
dogmaphobic committed
87 88 89 90 91 92 93 94 95 96
                    nativeDeviceException(userDataA, eA.getMessage());
                }

                @Override
                public void onNewData(final byte[] dataA, int userDataA)
                {
                    nativeDeviceNewData(userDataA, dataA);
                }
            };

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    private final BroadcastReceiver mOpenAccessoryReceiver =
        new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (USB_ACTION.equals(action)) {
                    UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        openAccessory(accessory);
                    }
                } else if( UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
                    UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                    if (accessory != null) {
                        closeAccessory(accessory);
                    }
                }
            }
        };

dogmaphobic's avatar
dogmaphobic committed
117 118 119 120 121
    //  NATIVE C++ FUNCTION THAT WILL BE CALLED IF THE DEVICE IS UNPLUGGED
    private static native void nativeDeviceHasDisconnected(int userDataA);
    private static native void nativeDeviceException(int userDataA, String messageA);
    private static native void nativeDeviceNewData(int userDataA, byte[] dataA);

122 123 124 125
    // Native C++ functions called to log output
    public static native void qgcLogDebug(String message);
    public static native void qgcLogWarning(String message);

dogmaphobic's avatar
dogmaphobic committed
126 127 128 129 130
    ////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Constructor.  Only used once to create the initial instance for the static functions.
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////
131
    public QGCActivity()
dogmaphobic's avatar
dogmaphobic committed
132 133 134 135 136 137 138 139
    {
        m_instance = this;
        m_openedDevices = new HashMap<Integer, UsbSerialDriver>();
        m_userData = new HashMap<Integer, Integer>();
        m_ioManager = new HashMap<Integer, UsbIoManager>();
        Log.i(TAG, "Instance created");
    }

dogmaphobic's avatar
dogmaphobic committed
140 141 142
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
143 144
        PowerManager pm = (PowerManager)m_instance.getSystemService(Context.POWER_SERVICE);
        m_wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "QGroundControl");
145 146 147 148 149 150 151
        if(m_wl != null) {
            m_wl.acquire();
            Log.i(TAG, "SCREEN_BRIGHT_WAKE_LOCK acquired.");
        } else {
            Log.i(TAG, "SCREEN_BRIGHT_WAKE_LOCK not acquired!!!");
        }
        m_instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

        if (m_manager == null) {
            try {
                m_manager = (UsbManager)m_instance.getSystemService(Context.USB_SERVICE);
                taiSync = new TaiSync();

                IntentFilter filter = new IntentFilter(USB_ACTION);
                filter.addAction( UsbManager.ACTION_USB_ACCESSORY_DETACHED);
                registerReceiver(mOpenAccessoryReceiver, filter);

                probeAccessories();
            } catch(Exception e) {
               Log.e(TAG, "Exception getCurrentDevices(): " + e);
            }
        }
dogmaphobic's avatar
dogmaphobic committed
167 168 169
    }

    @Override
170 171 172
    protected void onDestroy()
    {
        unregisterReceiver(mOpenAccessoryReceiver);
173 174 175 176 177 178 179 180
        try {
            if(m_wl != null) {
                m_wl.release();
                Log.i(TAG, "SCREEN_BRIGHT_WAKE_LOCK released.");
            }
        } catch(Exception e) {
           Log.e(TAG, "Exception onDestroy()");
        }
dogmaphobic's avatar
dogmaphobic committed
181 182 183 184 185 186
        super.onDestroy();
    }

    public void onInit(int status) {
    }

dogmaphobic's avatar
dogmaphobic committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Find all current devices that match the device filter described in the androidmanifest.xml and the
    //  device_filter.xml
    //
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    private static boolean getCurrentDevices()
    {
        if (m_instance == null)
            return false;

        if (m_devices != null)
            m_devices.clear();

        m_devices = UsbSerialProber.findAllDevices(m_manager);

        return true;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  List all available devices that are not already open.  It returns the serial port info
    //  in a : separated string array.  Each string entry consists of the following:
    //
    //  DeviceName:Company:ProductId:VendorId
    //
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static String[] availableDevicesInfo()
    {
        //  GET THE LIST OF CURRENT DEVICES
        if (!getCurrentDevices())
        {
219
            Log.e(TAG, "QGCActivity instance not present");
dogmaphobic's avatar
dogmaphobic committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
            return null;
        }

        //  MAKE SURE WE HAVE ENTRIES
        if (m_devices.size() <= 0)
        {
            //Log.e(TAG, "No USB devices found");
            return null;
        }

        if (m_openedDevices == null)
        {
            Log.e(TAG, "m_openedDevices is null");
            return null;
        }

        int countL = 0;
        int iL;

239
        //  CHECK FOR ALREADY OPENED DEVICES AND DON'T INCLUDE THEM IN THE COUNT
dogmaphobic's avatar
dogmaphobic committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        for (iL=0; iL<m_devices.size(); iL++)
        {
            if (m_openedDevices.get(m_devices.get(iL).getDevice().getDeviceId()) != null)
            {
                countL++;
                break;
            }
        }

        if (m_devices.size() - countL <= 0)
        {
            //Log.e(TAG, "No open USB devices found");
            return null;
        }

        String[] listL = new String[m_devices.size() - countL];
        UsbSerialDriver driverL;
        String tempL;

        //  GET THE DATA ON THE INDIVIDUAL DEVICES SKIPPING THE ONES THAT ARE ALREADY OPEN
        countL = 0;
        for (iL=0; iL<m_devices.size(); iL++)
        {
            driverL = m_devices.get(iL);
            if (m_openedDevices.get(driverL.getDevice().getDeviceId()) == null)
            {
                UsbDevice deviceL = driverL.getDevice();
                tempL = deviceL.getDeviceName() + ":";

                if (driverL instanceof FtdiSerialDriver)
                    tempL = tempL + "FTDI:";
                else if (driverL instanceof CdcAcmSerialDriver)
                    tempL = tempL + "Cdc Acm:";
                else if (driverL instanceof Cp2102SerialDriver)
                    tempL = tempL + "Cp2102:";
                else if (driverL instanceof ProlificSerialDriver)
                    tempL = tempL + "Prolific:";
                else
                    tempL = tempL + "Unknown:";

                tempL = tempL + Integer.toString(deviceL.getProductId()) + ":";
                tempL = tempL + Integer.toString(deviceL.getVendorId()) + ":";
                listL[countL] = tempL;
                countL++;
284
                qgcLogDebug("Found " + tempL);
dogmaphobic's avatar
dogmaphobic committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
            }
        }

        return listL;
    }



    /////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Open a device based on the name.
    //
    //  Args:   nameA - name of the device to open
    //          userDataA - C++ pointer to the QSerialPort that is trying to open the device.  This is
    //                      used by the detector to inform the C++ side if it is unplugged
    //
    //  Returns:    ID number of opened port.  This number is used to reference the correct port in subsequent
    //              calls like close(), read(), and write().
    //
    /////////////////////////////////////////////////////////////////////////////////////////////////
305
    public static int open(Context parentContext, String nameA, int userDataA)
dogmaphobic's avatar
dogmaphobic committed
306 307 308
    {
        int idL = BAD_PORT;

309 310 311
        m_context = parentContext;

        //qgcLogDebug("Getting device list");
dogmaphobic's avatar
dogmaphobic committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        if (!getCurrentDevices())
            return BAD_PORT;

        //  CHECK THAT PORT IS NOT ALREADY OPENED
        if (m_openedDevices != null)
        {
            for (UsbSerialDriver driverL: m_openedDevices.values())
            {
                if (nameA.equals(driverL.getDevice().getDeviceName()))
                {
                    Log.e(TAG, "Device already opened");
                    return BAD_PORT;
                }
            }
        }
        else
            return BAD_PORT;

        if (m_devices == null)
            return BAD_PORT;

        //  OPEN THE DEVICE
        try
        {
            for (int iL=0; iL<m_devices.size(); iL++)
            {
                Log.i(TAG, "Checking device " + m_devices.get(iL).getDevice().getDeviceName() + " id: " + m_devices.get(iL).getDevice().getDeviceId());
                if (nameA.equals(m_devices.get(iL).getDevice().getDeviceName()))
                {
                    idL = m_devices.get(iL).getDevice().getDeviceId();
                    m_openedDevices.put(idL, m_devices.get(iL));
                    m_userData.put(idL, userDataA);

                    if (m_instance.m_UsbReceiver == null)
                    {
dogmaphobic's avatar
dogmaphobic committed
347
                        Log.i(TAG, "Creating new broadcast receiver");
dogmaphobic's avatar
dogmaphobic committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
                        m_instance.m_UsbReceiver= new BroadcastReceiver()
                        {
                            public void onReceive(Context contextA, Intent intentA)
                            {
                                String actionL = intentA.getAction();

                                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(actionL))
                                {
                                    UsbDevice deviceL = (UsbDevice)intentA.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                                    if (deviceL != null)
                                    {
                                        if (m_userData.containsKey(deviceL.getDeviceId()))
                                        {
                                            nativeDeviceHasDisconnected(m_userData.get(deviceL.getDeviceId()));
                                        }
                                    }
                                }
                            }
                        };
                        //  TURN ON THE INTENT FILTER SO IT WILL DETECT AN UNPLUG SIGNAL
                        IntentFilter filterL = new IntentFilter();
                        filterL.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                        m_instance.registerReceiver(m_instance.m_UsbReceiver, filterL);
                    }

                    m_openedDevices.get(idL).open();

                    //  START UP THE IO MANAGER TO READ/WRITE DATA TO THE DEVICE
                    UsbIoManager managerL = new UsbIoManager(m_openedDevices.get(idL), m_Listener, userDataA);
                    if (managerL == null)
                        Log.e(TAG, "UsbIoManager instance is null");
                    m_ioManager.put(idL, managerL);
                    m_Executor.submit(managerL);
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
381
                    Log.i(TAG, "Port open successful");
dogmaphobic's avatar
dogmaphobic committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
                    return idL;
                }
            }

            return BAD_PORT;
        }
        catch(IOException exA)
        {
            if (idL != BAD_PORT)
            {
                m_openedDevices.remove(idL);
                m_userData.remove(idL);

                if(m_ioManager.get(idL) != null)
                    m_ioManager.get(idL).stop();

                m_ioManager.remove(idL);
            }
400
            qgcLogWarning("Port open exception: " + exA.getMessage());
dogmaphobic's avatar
dogmaphobic committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
            return BAD_PORT;
        }
    }

    public static void startIoManager(int idA)
    {
        if (m_ioManager.get(idA) != null)
            return;

        UsbSerialDriver driverL = m_openedDevices.get(idA);

        if (driverL == null)
            return;

        UsbIoManager managerL = new UsbIoManager(driverL, m_Listener, m_userData.get(idA));
        m_ioManager.put(idA, managerL);
        m_Executor.submit(managerL);
    }

    public static void stopIoManager(int idA)
    {
        if(m_ioManager.get(idA) == null)
            return;

        m_ioManager.get(idA).stop();
        m_ioManager.remove(idA);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Sets the parameters on an open port.
    //
    //  Args:   idA - ID number from the open command
    //          baudRateA - Decimal value of the baud rate.  I.E. 9600, 57600, 115200, etc.
    //          dataBitsA - number of data bits.  Valid numbers are 5, 6, 7, 8
    //          stopBitsA - number of stop bits.  Valid numbers are 1, 2
    //          parityA - No Parity=0, Odd Parity=1, Even Parity=2
    //
    //  Returns:  T/F Success/Failure
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean setParameters(int idA, int baudRateA, int dataBitsA, int stopBitsA, int parityA)
    {
        UsbSerialDriver driverL = m_openedDevices.get(idA);

        if (driverL == null)
            return false;

        try
        {
            driverL.setParameters(baudRateA, dataBitsA, stopBitsA, parityA);
            return true;
        }
        catch(IOException eA)
        {
            return false;
        }
    }



    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Close the device.
    //
    //  Args:  idA - ID number from the open command
    //
    //  Returns:  T/F Success/Failure
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean close(int idA)
    {
        UsbSerialDriver driverL = m_openedDevices.get(idA);

        if (driverL == null)
            return false;

        try
        {
            stopIoManager(idA);
            m_userData.remove(idA);
            m_openedDevices.remove(idA);
            driverL.close();

            return true;
        }
        catch(IOException eA)
        {
            return false;
        }
    }



    //////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Write data to the device.
    //
    //  Args:   idA - ID number from the open command
    //          sourceA - byte array of data to write
    //          timeoutMsecA - amount of time in milliseconds to wait for the write to occur
    //
    //  Returns:  number of bytes written
    //
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    public static int write(int idA, byte[] sourceA, int timeoutMSecA)
    {
        UsbSerialDriver driverL = m_openedDevices.get(idA);

        if (driverL == null)
            return 0;

        try
        {
            return driverL.write(sourceA, timeoutMSecA);
        }
        catch(IOException eA)
        {
            return 0;
        }
        /*
        UsbIoManager managerL = m_ioManager.get(idA);

        if(managerL != null)
        {
            managerL.writeAsync(sourceA);
            return sourceA.length;
        }
        else
            return 0;
        */
    }



    /////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Determine if a device name if valid.  Note, it does not look for devices that are already open
    //
    //  Args:  nameA - name of device to look for
    //
    //  Returns: T/F
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean isDeviceNameValid(String nameA)
    {
        if (m_devices.size() <= 0)
            return false;

        for (int iL=0; iL<m_devices.size(); iL++)
        {
            if (m_devices.get(iL).getDevice().getDeviceName() == nameA)
                return true;
        }

        return false;
    }



    /////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Check if the device is open
    //
    //  Args:  nameA - name of device
    //
    //  Returns:  T/F
    //
    //////////////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean isDeviceNameOpen(String nameA)
    {
        if (m_openedDevices == null)
            return false;

        for (UsbSerialDriver driverL: m_openedDevices.values())
        {
            if (nameA.equals(driverL.getDevice().getDeviceName()))
                return true;
        }

        return false;
    }



    /////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Set the Data Terminal Ready flag on the device
    //
    //  Args:   idA - ID number from the open command
    //          onA - on=T, off=F
    //
    //  Returns:  T/F Success/Failure
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean setDataTerminalReady(int idA, boolean onA)
    {
        try
        {
            UsbSerialDriver driverL = m_openedDevices.get(idA);

            if (driverL == null)
                return false;

            driverL.setDTR(onA);
            return true;
        }
        catch(IOException eA)
        {
            return false;
        }
    }



    ////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Set the Request to Send flag
    //
    //  Args:   idA - ID number from the open command
    //          onA - on=T, off=F
    //
    //  Returns:  T/F Success/Failure
    //
    ////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean setRequestToSend(int idA, boolean onA)
    {
        try
        {
            UsbSerialDriver driverL = m_openedDevices.get(idA);

            if (driverL == null)
                return false;

            driverL.setRTS(onA);
            return true;
        }
        catch(IOException eA)
        {
            return false;
        }
    }



    ///////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Purge the hardware buffers based on the input and output flags
    //
    //  Args:   idA - ID number from the open command
    //          inputA - input buffer purge.  purge=T
    //          outputA - output buffer purge.  purge=T
    //
    //  Returns:  T/F Success/Failure
    //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static boolean purgeBuffers(int idA, boolean inputA, boolean outputA)
    {
        try
        {
            UsbSerialDriver driverL = m_openedDevices.get(idA);

            if (driverL == null)
                return false;

            return driverL.purgeHwBuffers(inputA, outputA);
        }
        catch(IOException eA)
        {
            return false;
        }
    }



    //////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Get the native device handle (file descriptor)
    //
    //  Args:   idA - ID number from the open command
    //
    //  Returns:  device handle
    //
    ///////////////////////////////////////////////////////////////////////////////////////////
    public static int getDeviceHandle(int idA)
    {
        UsbSerialDriver driverL = m_openedDevices.get(idA);

        if (driverL == null)
            return -1;

        UsbDeviceConnection connectL = driverL.getDeviceConnection();
        if (connectL == null)
            return -1;
        else
            return connectL.getFileDescriptor();
    }



    //////////////////////////////////////////////////////////////////////////////////////////////
    //
    //  Get the open usb serial driver for the given id
    //
    //  Args:  idA - ID number from the open command
    //
    //  Returns:  usb device driver
    //
    /////////////////////////////////////////////////////////////////////////////////////////////
    public static UsbSerialDriver getUsbSerialDriver(int idA)
    {
        return m_openedDevices.get(idA);
    }
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

    UsbAccessory openUsbAccessory = null;
    Object openAccessoryLock = new Object();

    private void openAccessory(UsbAccessory usbAccessory)
    {
        Log.i(TAG, "openAccessory: " + usbAccessory.getSerial());
        try {
            synchronized(openAccessoryLock) {
                if ((openUsbAccessory != null && !taiSync.isRunning()) || openUsbAccessory == null) {
                    openUsbAccessory = usbAccessory;
                    taiSync.open(m_manager.openAccessory(usbAccessory));
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "openAccessory exception: " + e);
            taiSync.close();
            closeAccessory(openUsbAccessory);
        }
    }

    private void closeAccessory(UsbAccessory usbAccessory)
    {
        Log.i(TAG, "closeAccessory");

        synchronized(openAccessoryLock) {
            if (openUsbAccessory != null && usbAccessory == openUsbAccessory && taiSync.isRunning()) {
                taiSync.close();
                openUsbAccessory = null;
            }
        }
    }

    private void probeAccessories()
    {
        final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(USB_ACTION), 0);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
           @Override
           public void run()
           {
//               Log.i(TAG, "probeAccessories");
               UsbAccessory[] accessories = m_manager.getAccessoryList();
               if (accessories != null) {
                   for (UsbAccessory usbAccessory : accessories) {
                       if (m_manager.hasPermission(usbAccessory)) {
                           openAccessory(usbAccessory);
                       } else {
                           Log.i(TAG, "requestPermission");
                           m_manager.requestPermission(usbAccessory, pendingIntent);
                       }
                   }
               }
           }
        }, 0, 3000);
    }
dogmaphobic's avatar
dogmaphobic committed
770 771
}