Search in sources :

Example 1 with StreamConnection

use of javax.microedition.io.StreamConnection in project JMRI by JMRI.

the class LocoNetBluetoothAdapter method openPort.

@Override
public String openPort(String portName, String appName) {
    int[] responseCode = new int[] { -1 };
    Exception[] exception = new Exception[] { null };
    try {
        // Find the RemoteDevice with this name.
        RemoteDevice[] devices = LocalDevice.getLocalDevice().getDiscoveryAgent().retrieveDevices(DiscoveryAgent.PREKNOWN);
        if (devices != null) {
            for (RemoteDevice device : devices) {
                if (device.getFriendlyName(false).equals(portName)) {
                    Object[] waitObj = new Object[0];
                    // Start a search for a serialport service (UUID 0x1101)
                    LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(new int[] { 0x0100 }, new UUID[] { new UUID(0x1101) }, device, new DiscoveryListener() {

                        @Override
                        public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                            synchronized (waitObj) {
                                for (ServiceRecord service : servRecord) {
                                    // Service found, get url for connection.
                                    String url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                                    if (url == null) {
                                        continue;
                                    }
                                    try {
                                        // Open connection.
                                        Connection conn = Connector.open(url, Connector.READ_WRITE);
                                        if (conn instanceof StreamConnection) {
                                            // The connection should be a StreamConnection, otherwise it's a one way communication.
                                            StreamConnection stream = (StreamConnection) conn;
                                            in = stream.openInputStream();
                                            out = stream.openOutputStream();
                                            opened = true;
                                        // Port is open, let openPort continue.
                                        //waitObj.notify();
                                        } else {
                                            throw new IOException("Could not establish a two-way communication");
                                        }
                                    } catch (IOException IOe) {
                                        exception[0] = IOe;
                                    }
                                }
                                if (!opened) {
                                    exception[0] = new IOException("No service found to connect to");
                                }
                            }
                        }

                        @Override
                        public void serviceSearchCompleted(int transID, int respCode) {
                            synchronized (waitObj) {
                                // Search for services complete, if the port was not opened, save the response code for error analysis.
                                responseCode[0] = respCode;
                                // Search completer, let openPort continue.
                                waitObj.notify();
                            }
                        }

                        @Override
                        public void inquiryCompleted(int discType) {
                        }

                        @Override
                        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                        }
                    });
                    synchronized (waitObj) {
                        // Wait until either the port is open on the search has returned a response code.
                        while (!opened && responseCode[0] == -1) {
                            try {
                                // Wait for search to complete.
                                waitObj.wait();
                            } catch (InterruptedException Ie) {
                                Ie.printStackTrace();
                            }
                        }
                    }
                    break;
                }
            }
        }
    } catch (BluetoothStateException BSe) {
        log.error("Exception when using bluetooth");
        return BSe.getLocalizedMessage();
    } catch (IOException IOe) {
        log.error("Unknown IOException when establishing connection to " + portName);
        return IOe.getLocalizedMessage();
    }
    if (!opened) {
        ConnectionStatus.instance().setConnectionState(portName, ConnectionStatus.CONNECTION_DOWN);
        if (exception[0] != null) {
            log.error("Exception when connecting to " + portName);
            return exception[0].getLocalizedMessage();
        }
        switch(responseCode[0]) {
            case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                log.error("Bluetooth connection " + portName + " not opened, unknown error");
                return "Unknown error: failed to connect to " + portName;
            case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                log.error("Bluetooth device " + portName + " could not be reached");
                return "Could not find " + portName;
            case DiscoveryListener.SERVICE_SEARCH_ERROR:
                log.error("Error when searching for " + portName);
                return "Error when searching for " + portName;
            case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                log.error("No serial service found on " + portName);
                return "Invalid bluetooth device: " + portName;
            case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                log.error("Service search on " + portName + " ended prematurely");
                return "Search for " + portName + " ended unexpectedly";
            default:
                log.warn("Unhandled response code: {}", responseCode[0]);
                break;
        }
        log.error("Unknown error when connecting to " + portName);
        return "Unknown error when connecting to " + portName;
    }
    // normal operation
    return null;
}
Also used : DeviceClass(javax.bluetooth.DeviceClass) Connection(javax.microedition.io.Connection) StreamConnection(javax.microedition.io.StreamConnection) IOException(java.io.IOException) StreamConnection(javax.microedition.io.StreamConnection) BluetoothStateException(javax.bluetooth.BluetoothStateException) IOException(java.io.IOException) BluetoothStateException(javax.bluetooth.BluetoothStateException) ServiceRecord(javax.bluetooth.ServiceRecord) RemoteDevice(javax.bluetooth.RemoteDevice) UUID(javax.bluetooth.UUID) DiscoveryListener(javax.bluetooth.DiscoveryListener)

Aggregations

IOException (java.io.IOException)1 BluetoothStateException (javax.bluetooth.BluetoothStateException)1 DeviceClass (javax.bluetooth.DeviceClass)1 DiscoveryListener (javax.bluetooth.DiscoveryListener)1 RemoteDevice (javax.bluetooth.RemoteDevice)1 ServiceRecord (javax.bluetooth.ServiceRecord)1 UUID (javax.bluetooth.UUID)1 Connection (javax.microedition.io.Connection)1 StreamConnection (javax.microedition.io.StreamConnection)1