ProlificSerialDriver.java 17.7 KB
Newer Older
dogmaphobic's avatar
dogmaphobic committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 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 219
/* 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/
 */

/*
 * Ported to usb-serial-for-android
 * by Felix Hädicke <felixhaedicke@web.de>
 *
 * Based on the pyprolific driver written
 * by Emmanuel Blot <emmanuel.blot@free.fr>
 * See https://github.com/eblot/pyftdi
 */

package com.hoho.android.usbserial.driver;

import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.util.Log;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

public class ProlificSerialDriver extends CommonUsbSerialDriver {
    private static final int USB_READ_TIMEOUT_MILLIS = 1000;
    private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;

    private static final int USB_RECIP_INTERFACE = 0x01;

    private static final int PROLIFIC_VENDOR_READ_REQUEST = 0x01;
    private static final int PROLIFIC_VENDOR_WRITE_REQUEST = 0x01;

    private static final int PROLIFIC_VENDOR_OUT_REQTYPE = UsbConstants.USB_DIR_OUT
            | UsbConstants.USB_TYPE_VENDOR;

    private static final int PROLIFIC_VENDOR_IN_REQTYPE = UsbConstants.USB_DIR_IN
            | UsbConstants.USB_TYPE_VENDOR;

    private static final int PROLIFIC_CTRL_OUT_REQTYPE = UsbConstants.USB_DIR_OUT
            | UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE;

    private static final int WRITE_ENDPOINT = 0x02;
    private static final int READ_ENDPOINT = 0x83;
    private static final int INTERRUPT_ENDPOINT = 0x81;

    private static final int FLUSH_RX_REQUEST = 0x08;
    private static final int FLUSH_TX_REQUEST = 0x09;

    private static final int SET_LINE_REQUEST = 0x20;
    private static final int SET_CONTROL_REQUEST = 0x22;

    private static final int CONTROL_DTR = 0x01;
    private static final int CONTROL_RTS = 0x02;

    private static final int STATUS_FLAG_CD = 0x01;
    private static final int STATUS_FLAG_DSR = 0x02;
    private static final int STATUS_FLAG_RI = 0x08;
    private static final int STATUS_FLAG_CTS = 0x80;

    private static final int STATUS_BUFFER_SIZE = 10;
    private static final int STATUS_BYTE_IDX = 8;

    private static final int DEVICE_TYPE_HX = 0;
    private static final int DEVICE_TYPE_0 = 1;
    private static final int DEVICE_TYPE_1 = 2;

    private int mDeviceType = DEVICE_TYPE_HX;

    private UsbEndpoint mReadEndpoint;
    private UsbEndpoint mWriteEndpoint;
    private UsbEndpoint mInterruptEndpoint;

    private int mControlLinesValue = 0;

    private int mBaudRate = -1, mDataBits = -1, mStopBits = -1, mParity = -1;

    private int mStatus = 0;
    private volatile Thread mReadStatusThread = null;
    private final Object mReadStatusThreadLock = new Object();
    boolean mStopReadStatusThread = false;
    private IOException mReadStatusException = null;

    private final String TAG = ProlificSerialDriver.class.getSimpleName();

    private final byte[] inControlTransfer(int requestType, int request,
            int value, int index, int length) throws IOException {
        byte[] buffer = new byte[length];
        int result = mConnection.controlTransfer(requestType, request, value,
                index, buffer, length, USB_READ_TIMEOUT_MILLIS);
        if (result != length) {
            throw new IOException(
                    String.format("ControlTransfer with value 0x%x failed: %d",
                            value, result));
        }
        return buffer;
    }

    private final void outControlTransfer(int requestType, int request,
            int value, int index, byte[] data) throws IOException {
        int length = (data == null) ? 0 : data.length;
        int result = mConnection.controlTransfer(requestType, request, value,
                index, data, length, USB_WRITE_TIMEOUT_MILLIS);
        if (result != length) {
            throw new IOException(
                    String.format("ControlTransfer with value 0x%x failed: %d",
                            value, result));
        }
    }

    private final byte[] vendorIn(int value, int index, int length)
            throws IOException {
        return inControlTransfer(PROLIFIC_VENDOR_IN_REQTYPE,
                PROLIFIC_VENDOR_READ_REQUEST, value, index, length);
    }

    private final void vendorOut(int value, int index, byte[] data)
            throws IOException {
        outControlTransfer(PROLIFIC_VENDOR_OUT_REQTYPE,
                PROLIFIC_VENDOR_WRITE_REQUEST, value, index, data);
    }

    private final void ctrlOut(int request, int value, int index, byte[] data)
            throws IOException {
        outControlTransfer(PROLIFIC_CTRL_OUT_REQTYPE, request, value, index,
                data);
    }

    private void doBlackMagic() throws IOException {
        vendorIn(0x8484, 0, 1);
        vendorOut(0x0404, 0, null);
        vendorIn(0x8484, 0, 1);
        vendorIn(0x8383, 0, 1);
        vendorIn(0x8484, 0, 1);
        vendorOut(0x0404, 1, null);
        vendorIn(0x8484, 0, 1);
        vendorIn(0x8383, 0, 1);
        vendorOut(0, 1, null);
        vendorOut(1, 0, null);
        vendorOut(2, (mDeviceType == DEVICE_TYPE_HX) ? 0x44 : 0x24, null);
    }

    private void resetDevice() throws IOException {
        purgeHwBuffers(true, true);
    }

    private void setControlLines(int newControlLinesValue) throws IOException {
        ctrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null);
        mControlLinesValue = newControlLinesValue;
    }

    private final void readStatusThreadFunction() {
        try {
            while (!mStopReadStatusThread) {
                byte[] buffer = new byte[STATUS_BUFFER_SIZE];
                int readBytesCount = mConnection.bulkTransfer(mInterruptEndpoint,
                        buffer,
                        STATUS_BUFFER_SIZE,
                        500);
                if (readBytesCount > 0) {
                    if (readBytesCount == STATUS_BUFFER_SIZE) {
                        mStatus = buffer[STATUS_BYTE_IDX] & 0xff;
                    } else {
                        throw new IOException(
                                String.format("Invalid CTS / DSR / CD / RI status buffer received, expected %d bytes, but received %d",
                                        STATUS_BUFFER_SIZE,
                                        readBytesCount));
                    }
                }
            }
        } catch (IOException e) {
            mReadStatusException = e;
        }
    }

    private final int getStatus() throws IOException {
        if ((mReadStatusThread == null) && (mReadStatusException == null)) {
            synchronized (mReadStatusThreadLock) {
                if (mReadStatusThread == null) {
                    byte[] buffer = new byte[STATUS_BUFFER_SIZE];
                    int readBytes = mConnection.bulkTransfer(mInterruptEndpoint,
                            buffer,
                            STATUS_BUFFER_SIZE,
                            100);
                    if (readBytes != STATUS_BUFFER_SIZE) {
                        Log.w(TAG, "Could not read initial CTS / DSR / CD / RI status");
                    } else {
                        mStatus = buffer[STATUS_BYTE_IDX] & 0xff;
                    }

                    mReadStatusThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            readStatusThreadFunction();
                        }
                    });
                    mReadStatusThread.setDaemon(true);
                    mReadStatusThread.start();
                }
            }
        }

Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
220
        /* throw and clear an exception which occurred in the status read thread */
dogmaphobic's avatar
dogmaphobic committed
221 222 223 224 225 226 227 228 229 230 231 232 233
        IOException readStatusException = mReadStatusException;
        if (mReadStatusException != null) {
            mReadStatusException = null;
            throw readStatusException;
        }
        
        return mStatus;
    }

    private final boolean testStatusFlag(int flag) throws IOException {
        return ((getStatus() & flag) == flag);
    }

Don Gagne's avatar
Don Gagne committed
234 235
    public ProlificSerialDriver(UsbDevice device) {
        super(device);
dogmaphobic's avatar
dogmaphobic committed
236 237 238 239 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 284 285 286 287 288 289 290
    }

    @Override
    public void open() throws IOException {
        UsbInterface usbInterface = mDevice.getInterface(0);

        if (!mConnection.claimInterface(usbInterface, true)) {
            throw new IOException("Error claiming Prolific interface 0");
        }

        boolean openSuccessful = false;
        try {
            for (int i = 0; i < usbInterface.getEndpointCount(); ++i) {
                UsbEndpoint currentEndpoint = usbInterface.getEndpoint(i);

                switch (currentEndpoint.getAddress()) {
                case READ_ENDPOINT:
                    mReadEndpoint = currentEndpoint;
                    break;

                case WRITE_ENDPOINT:
                    mWriteEndpoint = currentEndpoint;
                    break;

                case INTERRUPT_ENDPOINT:
                    mInterruptEndpoint = currentEndpoint;
                    break;
                }
            }

            if (mDevice.getDeviceClass() == 0x02) {
                mDeviceType = DEVICE_TYPE_0;
            } else {
                try {
                    Method getRawDescriptorsMethod
                        = mConnection.getClass().getMethod("getRawDescriptors");
                    byte[] rawDescriptors
                        = (byte[]) getRawDescriptorsMethod.invoke(mConnection);
                    byte maxPacketSize0 = rawDescriptors[7];
                    if (maxPacketSize0 == 64) {
                        mDeviceType = DEVICE_TYPE_HX;
                    } else if ((mDevice.getDeviceClass() == 0x00)
                            || (mDevice.getDeviceClass() == 0xff)) {
                        mDeviceType = DEVICE_TYPE_1;
                    } else {
                      Log.w(TAG, "Could not detect PL2303 subtype, "
                          + "Assuming that it is a HX device");
                      mDeviceType = DEVICE_TYPE_HX;
                    }
                } catch (NoSuchMethodException e) {
                    Log.w(TAG, "Method UsbDeviceConnection.getRawDescriptors, "
                            + "required for PL2303 subtype detection, not "
                            + "available! Assuming that it is a HX device");
                    mDeviceType = DEVICE_TYPE_HX;
                } catch (Exception e) {
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
291
                    Log.e(TAG, "An unexpected exception occurred while trying "
dogmaphobic's avatar
dogmaphobic committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                            + "to detect PL2303 subtype", e);
                }
            }

            setControlLines(mControlLinesValue);
            resetDevice();

            doBlackMagic();
            openSuccessful = true;
        } finally {
            if (!openSuccessful) {
              try {
                mConnection.releaseInterface(usbInterface);
              } catch (Exception ingored) {
                // Do not cover possible exceptions
              }
            }
        }
    }

    @Override
    public void close() throws IOException {
        try {
            mStopReadStatusThread = true;
            synchronized (mReadStatusThreadLock) {
                if (mReadStatusThread != null) {
                    try {
                        mReadStatusThread.join();
                    } catch (Exception e) {
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
321
                        Log.w(TAG, "An error occurred while waiting for status read thread", e);
dogmaphobic's avatar
dogmaphobic committed
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 347 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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 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
                    }
                }
            }

            resetDevice();
        } finally {
            mConnection.releaseInterface(mDevice.getInterface(0));
        }
    }

    @Override
    public int read(byte[] dest, int timeoutMillis) throws IOException {
        synchronized (mReadBufferLock) {
            int readAmt = Math.min(dest.length, mReadBuffer.length);
            int numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer,
                    readAmt, timeoutMillis);
            if (numBytesRead < 0) {
                return 0;
            }
            System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead);
            return numBytesRead;
        }
    }

    @Override
    public int write(byte[] src, int timeoutMillis) throws IOException {
        int offset = 0;

        while (offset < src.length) {
            final int writeLength;
            final int amtWritten;

            synchronized (mWriteBufferLock) {
                final byte[] writeBuffer;

                writeLength = Math.min(src.length - offset, mWriteBuffer.length);
                if (offset == 0) {
                    writeBuffer = src;
                } else {
                    // bulkTransfer does not support offsets, make a copy.
                    System.arraycopy(src, offset, mWriteBuffer, 0, writeLength);
                    writeBuffer = mWriteBuffer;
                }

                amtWritten = mConnection.bulkTransfer(mWriteEndpoint,
                        writeBuffer, writeLength, timeoutMillis);
            }

            if (amtWritten <= 0) {
                throw new IOException("Error writing " + writeLength
                        + " bytes at offset " + offset + " length="
                        + src.length);
            }

            offset += amtWritten;
        }
        return offset;
    }

    @Override
    public void setParameters(int baudRate, int dataBits, int stopBits,
            int parity) throws IOException {
        if ((mBaudRate == baudRate) && (mDataBits == dataBits)
                && (mStopBits == stopBits) && (mParity == parity)) {
            // Make sure no action is performed if there is nothing to change
            return;
        }

        byte[] lineRequestData = new byte[7];

        lineRequestData[0] = (byte) (baudRate & 0xff);
        lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff);
        lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff);
        lineRequestData[3] = (byte) ((baudRate >> 24) & 0xff);

        switch (stopBits) {
        case STOPBITS_1:
            lineRequestData[4] = 0;
            break;

        case STOPBITS_1_5:
            lineRequestData[4] = 1;
            break;

        case STOPBITS_2:
            lineRequestData[4] = 2;
            break;

        default:
            throw new IllegalArgumentException("Unknown stopBits value: " + stopBits);
        }

        switch (parity) {
        case PARITY_NONE:
            lineRequestData[5] = 0;
            break;

        case PARITY_ODD:
            lineRequestData[5] = 1;
            break;

        case PARITY_EVEN:
            lineRequestData[5] = 2;
            break;

        case PARITY_MARK:
            lineRequestData[5] = 3;
            break;

        case PARITY_SPACE:
            lineRequestData[5] = 4;
            break;

        default:
            throw new IllegalArgumentException("Unknown parity value: " + parity);
        }

        lineRequestData[6] = (byte) dataBits;

        ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData);

        resetDevice();

        mBaudRate = baudRate;
        mDataBits = dataBits;
        mStopBits = stopBits;
        mParity = parity;
    }

    @Override
    public boolean getCD() throws IOException {
        return testStatusFlag(STATUS_FLAG_CD);
    }

    @Override
    public boolean getCTS() throws IOException {
        return testStatusFlag(STATUS_FLAG_CTS);
    }

    @Override
    public boolean getDSR() throws IOException {
        return testStatusFlag(STATUS_FLAG_DSR);
    }

    @Override
    public boolean getDTR() throws IOException {
        return ((mControlLinesValue & CONTROL_DTR) == CONTROL_DTR);
    }

    @Override
    public void setDTR(boolean value) throws IOException {
        int newControlLinesValue;
        if (value) {
            newControlLinesValue = mControlLinesValue | CONTROL_DTR;
        } else {
            newControlLinesValue = mControlLinesValue & ~CONTROL_DTR;
        }
        setControlLines(newControlLinesValue);
    }

    @Override
    public boolean getRI() throws IOException {
        return testStatusFlag(STATUS_FLAG_RI);
    }

    @Override
    public boolean getRTS() throws IOException {
        return ((mControlLinesValue & CONTROL_RTS) == CONTROL_RTS);
    }

    @Override
    public void setRTS(boolean value) throws IOException {
        int newControlLinesValue;
        if (value) {
            newControlLinesValue = mControlLinesValue | CONTROL_RTS;
        } else {
            newControlLinesValue = mControlLinesValue & ~CONTROL_RTS;
        }
        setControlLines(newControlLinesValue);
    }

    @Override
    public boolean purgeHwBuffers(boolean purgeReadBuffers, boolean purgeWriteBuffers) throws IOException {
        if (purgeReadBuffers) {
            vendorOut(FLUSH_RX_REQUEST, 0, null);
        }

        if (purgeWriteBuffers) {
            vendorOut(FLUSH_TX_REQUEST, 0, null);
        }

        return true;
    }

    public static Map<Integer, int[]> getSupportedDevices() {
        final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
        supportedDevices.put(Integer.valueOf(UsbId.VENDOR_PROLIFIC),
                new int[] { UsbId.PROLIFIC_PL2303, });
        return supportedDevices;
    }
}