Search in sources :

Example 1 with DeviceClass

use of javax.bluetooth.DeviceClass in project openhab1-addons by openhab.

the class BTDeviceDiscoveryService method run.

@Override
public void run() {
    try {
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        logger.debug("Initializing local bluetooth device ({}, {})", localDevice.getBluetoothAddress(), localDevice.getFriendlyName());
        DiscoveryAgent agent = localDevice.getDiscoveryAgent();
        final Object inquiryCompletedEvent = new Object();
        // this is the call back for the bluetooth driver
        DiscoveryListener listener = new DiscoveryListener() {

            @Override
            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                if (!newDevices.contains(btDevice)) {
                    newDevices.add(btDevice);
                    if (!oldDevices.contains(btDevice)) {
                        BluetoothDevice device = toBluetoothDevice(btDevice);
                        logger.debug("Device discovered: {}", device.toString());
                        for (BluetoothEventHandler handler : eventHandler) {
                            handler.handleDeviceInRange(device);
                        }
                    }
                }
            }

            @Override
            public void inquiryCompleted(int discType) {
                // check if any device has disappeared
                for (RemoteDevice btDevice : oldDevices) {
                    if (newDevices.contains(btDevice)) {
                        continue;
                    }
                    BluetoothDevice device = toBluetoothDevice(btDevice);
                    logger.debug("Device out of range: {}", device.toString());
                    for (BluetoothEventHandler handler : eventHandler) {
                        handler.handleDeviceOutOfRange(device);
                    }
                }
                oldDevices = new HashSet<RemoteDevice>(newDevices);
                // we now pass the list of all devices in range to the event handlers
                Iterable<BluetoothDevice> devices = Iterables.transform(newDevices, new Function<RemoteDevice, BluetoothDevice>() {

                    @Override
                    public BluetoothDevice apply(RemoteDevice from) {
                        return toBluetoothDevice(from);
                    }
                });
                for (BluetoothEventHandler handler : eventHandler) {
                    handler.handleAllDevicesInRange(devices);
                }
                newDevices.clear();
                synchronized (inquiryCompletedEvent) {
                    // tell the main thread that we are done
                    inquiryCompletedEvent.notifyAll();
                }
            }

            @Override
            public void serviceSearchCompleted(int transID, int respCode) {
            }

            @Override
            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
            }
        };
        // this is the main loop, which will run as long as the thread is not marked as interrupted
        while (!interrupted) {
            long starttime = new Date().getTime();
            // check if we at all need to run the bluetooth discovery
            boolean runDiscovery = false;
            for (BluetoothEventHandler handler : eventHandler) {
                if (handler.isActive()) {
                    runDiscovery = true;
                    break;
                }
            }
            if (runDiscovery) {
                synchronized (inquiryCompletedEvent) {
                    try {
                        logger.debug("Launching bluetooth device discovery...");
                        boolean started = agent.startInquiry(DiscoveryAgent.GIAC, listener);
                        if (started) {
                            inquiryCompletedEvent.wait();
                        }
                    } catch (BluetoothStateException e) {
                        logger.error("Error while starting the bluetooth agent", e);
                    } catch (InterruptedException e) {
                        interrupted = true;
                    }
                }
            }
            if (!interrupted) {
                // let this thread sleep until the next discovery should be done
                long sleeptime = refreshRate * 1000L - (new Date().getTime() - starttime);
                if (sleeptime > 0) {
                    logger.debug("Sleeping for {} s...", sleeptime / 1000.0);
                    try {
                        Thread.sleep(sleeptime);
                    } catch (InterruptedException e) {
                        interrupted = true;
                    }
                }
            }
        }
    } catch (BluetoothStateException e) {
        logger.error("Error while initializing local bluetooth device.", e);
    }
}
Also used : DeviceClass(javax.bluetooth.DeviceClass) BluetoothStateException(javax.bluetooth.BluetoothStateException) Date(java.util.Date) BluetoothEventHandler(org.openhab.binding.bluetooth.BluetoothEventHandler) DiscoveryAgent(javax.bluetooth.DiscoveryAgent) LocalDevice(javax.bluetooth.LocalDevice) RemoteDevice(javax.bluetooth.RemoteDevice) DiscoveryListener(javax.bluetooth.DiscoveryListener)

Example 2 with DeviceClass

use of javax.bluetooth.DeviceClass 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

BluetoothStateException (javax.bluetooth.BluetoothStateException)2 DeviceClass (javax.bluetooth.DeviceClass)2 DiscoveryListener (javax.bluetooth.DiscoveryListener)2 RemoteDevice (javax.bluetooth.RemoteDevice)2 IOException (java.io.IOException)1 Date (java.util.Date)1 DiscoveryAgent (javax.bluetooth.DiscoveryAgent)1 LocalDevice (javax.bluetooth.LocalDevice)1 ServiceRecord (javax.bluetooth.ServiceRecord)1 UUID (javax.bluetooth.UUID)1 Connection (javax.microedition.io.Connection)1 StreamConnection (javax.microedition.io.StreamConnection)1 BluetoothEventHandler (org.openhab.binding.bluetooth.BluetoothEventHandler)1