com.hoho.android.usbserial.driver.UsbSerialPort Java Examples

The following examples show how to use com.hoho.android.usbserial.driver.UsbSerialPort. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void ftdiMethods() throws Exception {
    if(!(usbSerialDriver instanceof FtdiSerialDriver))
        return;
    byte[] b;
    usbOpen();
    usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);

    FtdiSerialDriver.FtdiSerialPort ftdiSerialPort = (FtdiSerialDriver.FtdiSerialPort) usbSerialPort;
    int lt = ftdiSerialPort.getLatencyTimer();
    ftdiSerialPort.setLatencyTimer(1);
    telnetWrite("x".getBytes());
    b = usbRead(1);
    long t1 = System.currentTimeMillis();
    telnetWrite("x".getBytes());
    b = usbRead(1);
    ftdiSerialPort.setLatencyTimer(100);
    long t2 = System.currentTimeMillis();
    telnetWrite("x".getBytes());
    b = usbRead(1);
    long t3 = System.currentTimeMillis();
    ftdiSerialPort.setLatencyTimer(lt);
    assertEquals("latency 1", 99, Math.max(t2-t1, 99)); // looks strange, but shows actual value
    assertEquals("latency 100", 99, Math.min(t3-t2, 99));
}
 
Example #2
Source File: TerminalFragment.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 6 votes vote down vote up
void start() {
    if (connected) {
        try {
            EnumSet<UsbSerialPort.ControlLine> controlLines = usbSerialPort.getSupportedControlLines();
            if (!controlLines.contains(UsbSerialPort.ControlLine.RTS)) rtsBtn.setVisibility(View.INVISIBLE);
            if (!controlLines.contains(UsbSerialPort.ControlLine.CTS)) ctsBtn.setVisibility(View.INVISIBLE);
            if (!controlLines.contains(UsbSerialPort.ControlLine.DTR)) dtrBtn.setVisibility(View.INVISIBLE);
            if (!controlLines.contains(UsbSerialPort.ControlLine.DSR)) dsrBtn.setVisibility(View.INVISIBLE);
            if (!controlLines.contains(UsbSerialPort.ControlLine.CD))   cdBtn.setVisibility(View.INVISIBLE);
            if (!controlLines.contains(UsbSerialPort.ControlLine.RI))   riBtn.setVisibility(View.INVISIBLE);
        } catch (IOException e) {
            Toast.makeText(getActivity(), "getSupportedControlLines() failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        if (refresh())
            mainLooper.postDelayed(runnable, refreshInterval);
    }
}
 
Example #3
Source File: UsbCommService.java    From AndrOBD with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void connect(Object device, boolean secure)
{
	setState(STATE.CONNECTING);
	setDevice((UsbSerialPort)device);
	start();
}
 
Example #4
Source File: TerminalFragment.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean refresh() {
    try {
        EnumSet<UsbSerialPort.ControlLine> controlLines = usbSerialPort.getControlLines();
        rtsBtn.setChecked(controlLines.contains(UsbSerialPort.ControlLine.RTS));
        ctsBtn.setChecked(controlLines.contains(UsbSerialPort.ControlLine.CTS));
        dtrBtn.setChecked(controlLines.contains(UsbSerialPort.ControlLine.DTR));
        dsrBtn.setChecked(controlLines.contains(UsbSerialPort.ControlLine.DSR));
        cdBtn.setChecked(controlLines.contains(UsbSerialPort.ControlLine.CD));
        riBtn.setChecked(controlLines.contains(UsbSerialPort.ControlLine.RI));
    } catch (IOException e) {
        status("getControlLines() failed: " + e.getMessage() + " -> stopped control line refresh");
        return false;
    }
    return true;
}
 
Example #5
Source File: DeviceConnection.java    From monkeyboard-radio-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Called once we have permission, this will open a connection to the radio
 */
private void openConnection() {
    Log.v(TAG, "Opening connection to device");

    usbDeviceConnection = usbManager.openDevice(usbDevice);
    UsbSerialDriver driver = new CdcAcmSerialDriver(usbDevice);

    Log.v(TAG, "Device has " + String.valueOf(driver.getPorts().size()) + " ports");
    deviceSerialInterface = driver.getPorts().get(0);

    try {
        deviceSerialInterface.open(usbDeviceConnection);
        deviceSerialInterface.setParameters(RadioDevice.BAUD_RATE, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        deviceSerialInterface.setDTR(false);
        deviceSerialInterface.setRTS(true);

        readBuffer.clear();

        readBufferFillerThread = new Thread(readBufferFillerRunnable);
        readBufferFillerThread.start();

        running = true;
        if (connectionStateListener != null) {
            connectionStateListener.onStart();
        }
    } catch (IOException e) {
        e.printStackTrace();
        closeConnection();
        if (connectionStateListener != null) {
            connectionStateListener.onFail();
        }
    }
}
 
Example #6
Source File: AbstractBaseNodeLoader.java    From tangobot with Apache License 2.0 5 votes vote down vote up
@Override
public NodeMain[] startNodes(UsbDevice baseUsbDevice, UsbManager usbManager) throws Exception {
    if(baseUsbDevice == null) {
        throw new Exception("null USB device provided");
    }
    log.info("Starting base node");

    // Wrap the UsbDevice in the HoHo Driver
    UsbSerialDriver driver = serialDriverForDevice(baseUsbDevice, usbManager);
    UsbDeviceConnection connection = serialConnectionForDevice(usbManager, driver);

    if (connection == null) {
        throw new Exception("No USB connection available to initialize device");
    }

    UsbSerialPort port = serialPortForDevice(driver);

    // Choose the appropriate BaseDevice implementation for the particular
    // robot base, using the corresponding subclass
    BaseDevice baseDevice = getBaseDevice(port, connection);

    // Create the ROS nodes
    log.info("Create base controller node");
    mBaseControllerNode = new BaseControllerNode(baseDevice, "/cmd_vel");
    NodeConfiguration baseControllerNodeConf = NodeConfiguration.newPublic(mRosHostname);
    baseControllerNodeConf.setNodeName(GraphName.of("base_controller"));
    baseControllerNodeConf.setMasterUri(mRosMasterUri);
    mNodeMainExecutor.execute(mBaseControllerNode, baseControllerNodeConf);

    mBatteryPublisherNode = new RobotBatteryPublisherNode(baseDevice);
    NodeConfiguration batteryPublisherConf = NodeConfiguration.newPublic(mRosHostname);
    batteryPublisherConf.setNodeName(mBaseControllerNode.getDefaultNodeName());
    batteryPublisherConf.setMasterUri(mRosMasterUri);
    mNodeMainExecutor.execute(mBatteryPublisherNode, batteryPublisherConf);

    return new NodeMain[]{mBaseControllerNode, mBaseOdomPublisher};
}
 
Example #7
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void writeFragments() throws Exception {
    usbOpen();
    usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);

    ((CommonUsbSerialPort) usbSerialPort).setWriteBufferSize(12);
    ((CommonUsbSerialPort) usbSerialPort).setWriteBufferSize(12); // keeps last buffer
    TestBuffer buf = new TestBuffer(256);
    usbSerialPort.write(buf.buf, 5000);
    while (!buf.testRead(telnetRead(-1)))
        ;
}
 
Example #8
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
// provoke data loss, when data is not read fast enough
public void readBufferOverflow() throws Exception {
    if(usbSerialDriver instanceof CdcAcmSerialDriver)
        telnetWriteDelay = 10; // arduino_leonardo_bridge.ino sends each byte in own USB packet, which is horribly slow
    usbOpen();
    usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);

    StringBuilder expected = new StringBuilder();
    StringBuilder data = new StringBuilder();
    final int maxWait = 2000;
    int bufferSize;
    for(bufferSize = 8; bufferSize < (2<<15); bufferSize *= 2) {
        int linenr;
        String line="-";
        expected.setLength(0);
        data.setLength(0);

        Log.i(TAG, "bufferSize " + bufferSize);
        usbReadBlock = true;
        for (linenr = 0; linenr < bufferSize/8; linenr++) {
            line = String.format("%07d,", linenr);
            telnetWrite(line.getBytes());
            expected.append(line);
        }
        usbReadBlock = false;

        // slowly write new data, until old data is completely read from buffer and new data is received
        boolean found = false;
        for (; linenr < bufferSize/8 + maxWait/10 && !found; linenr++) {
            line = String.format("%07d,", linenr);
            telnetWrite(line.getBytes());
            Thread.sleep(10);
            expected.append(line);
            data.append(new String(usbRead(0)));
            found = data.toString().endsWith(line);
        }
        while(!found) {
            // use waiting read to clear input queue, else next test would see unexpected data
            byte[] rest = usbRead(-1);
            if(rest.length == 0)
                fail("last line "+line+" not found");
            data.append(new String(rest));
            found = data.toString().endsWith(line);
        }
        if (data.length() != expected.length())
            break;
    }

    findDifference(data, expected);
    assertTrue(bufferSize > 16);
    assertTrue(data.length() != expected.length());
}
 
Example #9
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
private int readSpeedInt(int writeSeconds, int readTimeout) throws Exception {
    int baudrate = 115200;
    if(usbSerialDriver instanceof Ch34xSerialDriver)
        baudrate = 38400;
    int writeAhead = 5*baudrate/10; // write ahead for another 5 second read
    if(usbSerialDriver instanceof CdcAcmSerialDriver)
        writeAhead = 50;

    usbOpen(EnumSet.noneOf(UsbOpenFlags.class), readTimeout);
    usbParameters(baudrate, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(baudrate, 8, 1, UsbSerialPort.PARITY_NONE);

    int linenr = 0;
    String line="";
    StringBuilder data = new StringBuilder();
    StringBuilder expected = new StringBuilder();
    int dlen = 0, elen = 0;
    Log.i(TAG, "readSpeed: 'read' should be near "+baudrate/10);
    long begin = System.currentTimeMillis();
    long next = System.currentTimeMillis();
    for(int seconds=1; seconds <= writeSeconds; seconds++) {
        next += 1000;
        while (System.currentTimeMillis() < next) {
            if((writeAhead < 0) || (expected.length() < data.length() + writeAhead)) {
                line = String.format("%07d,", linenr++);
                telnetWrite(line.getBytes());
                expected.append(line);
            } else {
                Thread.sleep(0, 100000);
            }
            data.append(new String(usbRead(0)));
        }
        Log.i(TAG, "readSpeed: t="+(next-begin)+", read="+(data.length()-dlen)+", write="+(expected.length()-elen));
        dlen = data.length();
        elen = expected.length();
    }

    boolean found = false;
    while(!found) {
        // use waiting read to clear input queue, else next test would see unexpected data
        byte[] rest = usbRead(-1);
        if(rest.length == 0)
            break;
        data.append(new String(rest));
        found = data.toString().endsWith(line);
    }
    return findDifference(data, expected);
}
 
Example #10
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void writeTimeout() throws Exception {
    usbOpen();
    usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);

    // Basically all devices have a UsbEndpoint.getMaxPacketSize() 64. When the timeout
    // in usbSerialPort.write() is reached, some packets have been written and the rest
    // is discarded. bulkTransfer() does not return the number written so far, but -1.
    // With 115200 baud and 1/2 second timeout, typical values are:
    //   ch340    6080 of 6144
    //   pl2302   5952 of 6144
    //   cp2102   6400 of 7168
    //   cp2105   6272 of 7168
    //   ft232    5952 of 6144
    //   ft2232   9728 of 10240
    //   arduino   128 of 144
    int timeout = 500;
    int len = 0;
    int startLen = 1024;
    int step = 1024;
    int minLen = 4069;
    int maxLen = 12288;
    int bufferSize = 511;
    TestBuffer buf = new TestBuffer(len);
    if(usbSerialDriver instanceof CdcAcmSerialDriver) {
        startLen = 16;
        step = 16;
        minLen = 128;
        maxLen = 256;
        bufferSize = 31;
    }

    try {
        for (len = startLen; len < maxLen; len += step) {
            buf = new TestBuffer(len);
            Log.d(TAG, "write buffer size " + len);
            usbSerialPort.write(buf.buf, timeout);
            while (!buf.testRead(telnetRead(-1)))
                ;
        }
        fail("write timeout expected between " + minLen + " and " + maxLen + ", is " + len);
    } catch (IOException e) {
        Log.d(TAG, "usbWrite failed", e);
        while (true) {
            byte[] data = telnetRead(-1);
            if (data.length == 0) break;
            if (buf.testRead(data)) break;
        }
        Log.d(TAG, "received " + buf.len + " of " + len + " bytes of failing usbWrite");
        assertTrue("write timeout expected between " + minLen + " and " + maxLen + ", is " + len, len > minLen);
    }

    // With smaller writebuffer, the timeout is used per bulkTransfer and each call 'fits'
    // into this timout, but shouldn't further calls only use the remaining timeout?
    ((CommonUsbSerialPort) usbSerialPort).setWriteBufferSize(bufferSize);
    len = maxLen;
    buf = new TestBuffer(len);
    Log.d(TAG, "write buffer size " + len);
    usbSerialPort.write(buf.buf, timeout);
    while (!buf.testRead(telnetRead(-1)))
        ;
}
 
Example #11
Source File: SerialInputOutputManager.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SerialInputOutputManager(UsbSerialPort serialPort, Listener listener) {
    mSerialPort = serialPort;
    mListener = listener;
}
 
Example #12
Source File: SerialInputOutputManager.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SerialInputOutputManager(UsbSerialPort serialPort) {
    mSerialPort = serialPort;
}
 
Example #13
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void writeSpeed() throws Exception {
    // see logcat for performance results
    //
    // CDC arduino_leonardo_bridge.ini has transfer speed ~ 100 byte/sec
    // all other devices can get near physical limit:
    // longlines=true:, speed is near physical limit at 11.5k
    // longlines=false: speed is 3-4k for all devices, as more USB packets are required
    usbOpen();
    usbParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE);
    boolean longlines = !(usbSerialDriver instanceof CdcAcmSerialDriver);

    int linenr = 0;
    String line="";
    StringBuilder data = new StringBuilder();
    StringBuilder expected = new StringBuilder();
    int dlen = 0, elen = 0;
    Log.i(TAG, "writeSpeed: 'write' should be near "+115200/10);
    long begin = System.currentTimeMillis();
    long next = System.currentTimeMillis();
    for(int seconds=1; seconds<=5; seconds++) {
        next += 1000;
        while (System.currentTimeMillis() < next) {
            if(longlines)
                line = String.format("%060d,", linenr++);
            else
                line = String.format("%07d,", linenr++);
            usbWrite(line.getBytes());
            expected.append(line);
            data.append(new String(telnetRead(0)));
        }
        Log.i(TAG, "writeSpeed: t="+(next-begin)+", write="+(expected.length()-elen)+", read="+(data.length()-dlen));
        dlen = data.length();
        elen = expected.length();
    }
    boolean found = false;
    for (linenr=0; linenr < 2000 && !found; linenr++) {
        data.append(new String(telnetRead(0)));
        Thread.sleep(1);
        found = data.toString().endsWith(line);
    }
    next = System.currentTimeMillis();
    Log.i(TAG, "writeSpeed: t="+(next-begin)+", read="+(data.length()-dlen));
    assertTrue(found);
    int pos = indexOfDifference(data, expected);
    if(pos!=-1) {

        Log.i(TAG, "writeSpeed: first difference at " + pos);
        String datasub     =     data.substring(Math.max(pos - 20, 0), Math.min(pos + 20, data.length()));
        String expectedsub = expected.substring(Math.max(pos - 20, 0), Math.min(pos + 20, expected.length()));
        assertThat(datasub, equalTo(expectedsub));
    }
}
 
Example #14
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void purgeHwBuffers() throws Exception {
    // purge write buffer
    // 2400 is slowest baud rate for isCp21xxRestrictedPort
    usbOpen();
    usbParameters(2400, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(2400, 8, 1, UsbSerialPort.PARITY_NONE);
    byte[] buf = new byte[64];
    for(int i=0; i<buf.length; i++) buf[i]='a';
    StringBuilder data = new StringBuilder();

    usbWrite(buf);
    Thread.sleep(50); // ~ 12 bytes
    boolean purged = usbSerialPort.purgeHwBuffers(true, false);
    usbWrite("bcd".getBytes());
    Thread.sleep(50);
    while(data.length()==0 || data.charAt(data.length()-1)!='d')
        data.append(new String(telnetRead()));
    Log.i(TAG, "purgeHwBuffers " + purged + ": " + buf.length+1 + " -> " + data.length());

    assertTrue(data.length() > 5);
    if(purged)
        assertTrue(data.length() < buf.length+1);
    else
        assertEquals(data.length(), buf.length + 3);

    // purge read buffer
    usbClose();
    usbOpen(EnumSet.of(UsbOpenFlags.NO_IOMANAGER_THREAD));
    usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetWrite("x".getBytes());
    Thread.sleep(10); // ~ 20 bytes
    purged = usbSerialPort.purgeHwBuffers(false, true);
    Log.d(TAG, "purged = " + purged);
    telnetWrite("y".getBytes());
    Thread.sleep(10); // ~ 20 bytes
    if(purged) {
        if(usbSerialDriver instanceof Cp21xxSerialDriver) { // only working on some devices/ports
            if(isCp21xxRestrictedPort) {
                assertThat(usbRead(2), equalTo("xy".getBytes())); // cp2105/1
            } else if(usbSerialDriver.getPorts().size() > 1) {
                assertThat(usbRead(1), equalTo("y".getBytes()));  // cp2105/0
            } else {
                assertThat(usbRead(2), equalTo("xy".getBytes())); // cp2102
            }
        } else {
            assertThat(usbRead(1), equalTo("y".getBytes()));
        }
    } else {
        assertThat(usbRead(2), equalTo("xy".getBytes()));
    }
}
 
Example #15
Source File: DeviceTest.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void readTimeout() throws Exception {
    if (usbSerialDriver instanceof FtdiSerialDriver)
        return; // periodically sends status messages, so does not block here
    final Boolean[] closed = {Boolean.FALSE};

    Runnable closeThread = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            usbClose();
            closed[0] = true;
        }
    };

    usbOpen(EnumSet.of(UsbOpenFlags.NO_IOMANAGER_THREAD));
    usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);

    byte[] buf = new byte[]{1};
    int len,i,j;
    long time;

    // w/o timeout
    telnetWrite(buf);
    len = usbSerialPort.read(buf, 0); // not blocking because data is available
    assertEquals(1, len);

    time = System.currentTimeMillis();
    closed[0] = false;
    Executors.newSingleThreadExecutor().submit(closeThread);
    len = usbSerialPort.read(buf, 0); // blocking until close()
    assertEquals(0, len);
    assertTrue(System.currentTimeMillis()-time >= 100);
    // wait for usbClose
    for(i=0; i<100; i++) {
        if(closed[0]) break;
        Thread.sleep(1);
    }
    assertTrue("not closed in time", closed[0]);

    // with timeout
    usbOpen(EnumSet.of(UsbOpenFlags.NO_IOMANAGER_THREAD));
    usbParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);
    telnetParameters(19200, 8, 1, UsbSerialPort.PARITY_NONE);

    int longTimeout = 1000;
    int shortTimeout = 10;
    time = System.currentTimeMillis();
    len = usbSerialPort.read(buf, shortTimeout);
    assertEquals(0, len);
    assertTrue(System.currentTimeMillis()-time < 100);

    // no issue with slow transfer rate and short read timeout
    time = System.currentTimeMillis();
    for(i=0; i<50; i++) {
        Thread.sleep(10);
        telnetWrite(buf);
        for(j=0; j<20; j++) {
            len = usbSerialPort.read(buf, shortTimeout);
            if (len > 0)
                break;
        }
        assertEquals("failed after " + i, 1, len);
    }
    Log.i(TAG, "average time per read " + (System.currentTimeMillis()-time)/i + " msec");

    if(!(usbSerialDriver instanceof CdcAcmSerialDriver)) {
        int diffLen;
        usbClose();
        // no issue with high transfer rate and long read timeout
        diffLen = readSpeedInt(5, longTimeout);
        if(usbSerialDriver instanceof Ch34xSerialDriver && diffLen == -1)
            diffLen = 0; // todo: investigate last packet loss
        assertEquals(0, diffLen);
        usbClose();
        // date loss with high transfer rate and short read timeout !!!
        diffLen = readSpeedInt(5, shortTimeout);
        assertNotEquals(0, diffLen);

        // data loss observed with read timeout up to 200 msec, e.g.
        //  difference at 181 len 64
        //        got 000020,0000021,0000030,0000031,0000032,0
        //   expected 000020,0000021,0000022,0000023,0000024,0
        // difference at 341 len 128
        //        got 000048,0000049,0000066,0000067,0000068,0
        //   expected 000048,0000049,0000050,0000051,0000052,0
        // difference at 724 len 704
        //        got 0000112,0000113,0000202,0000203,0000204,
        //   expected 0000112,0000113,0000114,0000115,0000116,
        // difference at 974 len 8
        //        got 00231,0000232,0000234,0000235,0000236,00
        //   expected 00231,0000232,0000233,0000234,0000235,00
    }
}
 
Example #16
Source File: TerminalFragment.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void connect() {
    UsbDevice device = null;
    UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
    for(UsbDevice v : usbManager.getDeviceList().values())
        if(v.getDeviceId() == deviceId)
            device = v;
    if(device == null) {
        status("connection failed: device not found");
        return;
    }
    UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
    if(driver == null) {
        driver = CustomProber.getCustomProber().probeDevice(device);
    }
    if(driver == null) {
        status("connection failed: no driver for device");
        return;
    }
    if(driver.getPorts().size() < portNum) {
        status("connection failed: not enough ports at device");
        return;
    }
    usbSerialPort = driver.getPorts().get(portNum);
    UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
    if(usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(driver.getDevice())) {
        usbPermission = UsbPermission.Requested;
        PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
        usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
        return;
    }
    if(usbConnection == null) {
        if (!usbManager.hasPermission(driver.getDevice()))
            status("connection failed: permission denied");
        else
            status("connection failed: open failed");
        return;
    }

    try {
        usbSerialPort.open(usbConnection);
        usbSerialPort.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        if(withIoManager) {
            usbIoManager = new SerialInputOutputManager(usbSerialPort, this);
            Executors.newSingleThreadExecutor().submit(usbIoManager);
        }
        status("connected");
        connected = true;
        controlLines.start();
    } catch (Exception e) {
        status("connection failed: " + e.getMessage());
        disconnect();
    }
}
 
Example #17
Source File: SerialInputOutputManager.java    From Arduino-Serial-Controller with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Creates a new instance with the provided listener.
 */
public SerialInputOutputManager(UsbSerialPort driver, Listener listener) {
    mDriver = driver;
    mListener = listener;
}
 
Example #18
Source File: SerialInputOutputManager.java    From Arduino-Serial-Controller with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Creates a new instance with no listener.
 */
public SerialInputOutputManager(UsbSerialPort driver) {
    this(driver, null);
}
 
Example #19
Source File: UsbCommService.java    From AndrOBD with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void start()
{
	if (sPort != null)
	{
		final UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
		if (usbManager == null)
		{
               connectionFailed();
               return;
           }
		
		UsbDevice device = sPort.getDriver().getDevice();
		if (!usbManager.hasPermission(device))
		{
			PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
			usbManager.requestPermission(device, usbPermissionIntent);
			connectionFailed();
			return;
		}

           UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
		if (connection == null)
		{
			connectionFailed();
			return;
		}

		try
		{
			sPort.open(connection);
			sPort.setDTR(true);
			sPort.setParameters(38400, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

			log.info("Starting io manager ..");
			Thread runner = new Thread(mSerialIoManager);
			runner.setPriority(Thread.MAX_PRIORITY);
			runner.start();

			// we are connected -> signal connectionEstablished
			connectionEstablished(sPort.toString());
		}
		catch (IOException e)
		{
			log.log(Level.SEVERE, "Error setting up device: " + e.getMessage(), e);
			try
			{
				sPort.close();
			}
			catch (IOException e2)
			{
				// Ignore.
			}
			connectionFailed();
			sPort = null;
		}
	}
}
 
Example #20
Source File: UsbCommService.java    From AndrOBD with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Set USB serial port device
 * @param port serial port to be set
 */
private void setDevice(UsbSerialPort port)
{
	sPort = port;
	mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
}
 
Example #21
Source File: TerminalFragment.java    From SimpleUsbTerminal with MIT License 4 votes vote down vote up
private void connect(Boolean permissionGranted) {
    UsbDevice device = null;
    UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
    for(UsbDevice v : usbManager.getDeviceList().values())
        if(v.getDeviceId() == deviceId)
            device = v;
    if(device == null) {
        status("connection failed: device not found");
        return;
    }
    UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
    if(driver == null) {
        driver = CustomProber.getCustomProber().probeDevice(device);
    }
    if(driver == null) {
        status("connection failed: no driver for device");
        return;
    }
    if(driver.getPorts().size() < portNum) {
        status("connection failed: not enough ports at device");
        return;
    }
    usbSerialPort = driver.getPorts().get(portNum);
    UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
    if(usbConnection == null && permissionGranted == null && !usbManager.hasPermission(driver.getDevice())) {
        PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(Constants.INTENT_ACTION_GRANT_USB), 0);
        usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
        return;
    }
    if(usbConnection == null) {
        if (!usbManager.hasPermission(driver.getDevice()))
            status("connection failed: permission denied");
        else
            status("connection failed: open failed");
        return;
    }

    connected = Connected.Pending;
    try {
        usbSerialPort.open(usbConnection);
        usbSerialPort.setParameters(baudRate, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), usbConnection, usbSerialPort);
        service.connect(socket);
        // usb connect is not asynchronous. connect-success and connect-error are returned immediately from socket.connect
        // for consistency to bluetooth/bluetooth-LE app use same SerialListener and SerialService classes
        onSerialConnect();
    } catch (Exception e) {
        onSerialConnectError(e);
    }
}
 
Example #22
Source File: SerialInputOutputManager.java    From PodEmu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new instance with the provided listener.
 */
public SerialInputOutputManager(UsbSerialPort driver, Listener listener) {
    mDriver = driver;
    mListener = listener;
}
 
Example #23
Source File: SerialInputOutputManager.java    From PodEmu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new instance with no listener.
 */
public SerialInputOutputManager(UsbSerialPort driver) {
    this(driver, null);
}
 
Example #24
Source File: SerialInterface_USBSerial.java    From PodEmu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Initilize the device
 * @param context - application context
 * @return - true on success, false on failure
 */
public boolean init(Context context)
{
    PodEmuLog.debug("USBSerial: initialization started.");
    UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

    // Find all available drivers from attached devices.
    List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
    if (availableDrivers.isEmpty())
    {
        PodEmuLog.debug("USBSerial: no devices found. Exiting...");
        return false;
    }

    // Open a connection to the first available driver.
    UsbSerialDriver driver = availableDrivers.get(0);
    connection = usbManager.openDevice(driver.getDevice());
    if (connection == null)
    {
        // You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
        PodEmuLog.log("USBSerial: Cannot establish serial connection! Exiting...");
        return false;
    }

    // Read some data! Most have just one port (port 0).
    List<UsbSerialPort> ports = driver.getPorts();
    port = ports.get(0);
    try {
        PodEmuLog.debug("USBSerial: openning connection with baud rate="+baudRate);
        port.open(connection);
        port.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        PodEmuService.communicateSerialStatusChange();
        PodEmuLog.debug("USBSerial: connection succesfully open");
    }
    catch (IOException e)
    {
        // TODO Deal with error
        PodEmuLog.debug("USBSerial: unknown exception occured! See trace log below:");
        PodEmuLog.error(e.getMessage());
        return false;
    }

    return true;
}
 
Example #25
Source File: UsbSerialDevice.java    From react-native-usbserial with MIT License 4 votes vote down vote up
public UsbSerialDevice(UsbSerialPort port) {
    this.port = port;
}
 
Example #26
Source File: ReactUsbSerialModule.java    From react-native-usbserial with MIT License 4 votes vote down vote up
private WritableMap createUsbSerialDevice(UsbManager manager,
                                          UsbSerialDriver driver) throws IOException {

    UsbDeviceConnection connection = manager.openDevice(driver.getDevice());

    // Most have just one port (port 0).
    UsbSerialPort port = driver.getPorts().get(0);

    port.open(connection);
    port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

    String id = generateId();
    UsbSerialDevice usd = new UsbSerialDevice(port);
    WritableMap map = Arguments.createMap();

    // Add UsbSerialDevice to the usbSerialDriverDict map
    usbSerialDriverDict.put(id, usd);

    map.putString("id", id);

    return map;
}
 
Example #27
Source File: SerialInputOutputManager.java    From OkUSB with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance with the provided listener.
 */
public SerialInputOutputManager(UsbSerialPort driver, Listener listener) {
    mDriver = driver;
    mListener = listener;
}
 
Example #28
Source File: SerialInputOutputManager.java    From OkUSB with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance with no listener.
 */
public SerialInputOutputManager(UsbSerialPort driver) {
    this(driver, null);
}
 
Example #29
Source File: UsbDeviceNodeLoader.java    From tangobot with Apache License 2.0 4 votes vote down vote up
protected UsbSerialPort serialPortForDevice(UsbSerialDriver driver) {
    return driver.getPorts().get(0);
}
 
Example #30
Source File: KobukiNodeLoader.java    From tangobot with Apache License 2.0 4 votes vote down vote up
@Override
protected BaseDevice getBaseDevice(UsbSerialPort port, UsbDeviceConnection connection) throws Exception {
    return new KobukiBaseDevice(port, connection);
}