Example #1
0
 public BluetoothClient() throws BluetoothStateException {
   LocalDevice localDev = LocalDevice.getLocalDevice();
   System.out.println("Local Bluetooth Name is " + localDev.getFriendlyName());
   localDev.setDiscoverable(DiscoveryAgent.GIAC);
   DiscoveryAgent discovery = localDev.getDiscoveryAgent();
   discovery.startInquiry(DiscoveryAgent.GIAC, this);
 }
Example #2
0
  public static void main(String[] args) throws IOException {
    System.out.println("Main.main");

    LocalDevice localDevice = LocalDevice.getLocalDevice();

    localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service

    String address = "742F6896BDD2"; // A500
    UUID device_UUID = new UUID(address, false);
    String url = "btspp://localhost:" + device_UUID + ";name=A500";
    StreamConnectionNotifier server = (StreamConnectionNotifier) Connector.open(url);

    System.out.println("wait until client connects");
    StreamConnection connection = server.acceptAndOpen(); // Wait until client connects
    // === At this point, two devices should be connected ===//
    System.out.println("connected");
    DataInputStream dis = connection.openDataInputStream();

    char c;
    while (true) {
      c = dis.readChar();
      if (c == 'x') break;
    }

    connection.close();

    System.out.println("Main.end");
  }
Example #3
0
  public static void main(String[] args) {
    if (args.length == 0) {
      gui = true;
      GUI.startGUI();
      btServer = new BTServer();
      try {
        btServer.startServer();
      } catch (IOException ioException) {
        Log.e(TAG, "IOexception!", ioException);
      }
    } else {
      try {
        out = new OutputStreamWriter(new FileOutputStream(args[0]));

        LocalDevice localDevice = LocalDevice.getLocalDevice();
        writeMessage("Local System:\n");
        writeMessage("Address: " + localDevice.getBluetoothAddress() + "\n");
        writeMessage("Name: " + localDevice.getFriendlyName() + "\n");

        btServer = new BTServer();
        btServer.startServer();
      } catch (IOException ioException) {
        Log.e(TAG, "IOException!", ioException);
      }
    }
  }
  /** Called by iPOJO when the instance becomes valid. */
  @Validate
  private void start() {
    logger.log(LogService.LOG_DEBUG, "BD Remote control component instance is starting.");
    String btAddress = null;

    LocalDevice localDevice = null;
    try {
      localDevice = LocalDevice.getLocalDevice();
    } catch (BluetoothStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();

    RemoteDevice[] cachedDevices = discoveryAgent.retrieveDevices(DiscoveryAgent.CACHED);
    if (cachedDevices != null) {
      int s = cachedDevices.length;
      for (int i = 0; i < s; i++) {
        logger.log(
            LogService.LOG_DEBUG,
            "Cached device"
                + i
                + ":"
                + cachedDevices[i].getBluetoothAddress()
                + ", "
                + cachedDevices[i]);
        btAddress = cachedDevices[i].getBluetoothAddress();
      }
    }
    RemoteDevice[] preknownDevices = discoveryAgent.retrieveDevices(DiscoveryAgent.PREKNOWN);
    if (preknownDevices != null) {
      int s = preknownDevices.length;
      for (int i = 0; i < s; i++) {
        logger.log(
            LogService.LOG_DEBUG,
            "Preknown device"
                + i
                + ":"
                + preknownDevices[i].getBluetoothAddress()
                + ", "
                + preknownDevices[i]);
      }
    }

    try {
      incomingThread = new IncomingThread(1, btAddress);
      incomingThread.start();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #5
0
 public RfcommServer() throws IOException {
   // RFCOMMベースのサーバの開始。
   // - btspp:は PRCOMM 用なのでベースプロトコルによって変わる。
   server =
       (StreamConnectionNotifier)
           Connector.open("btspp://localhost:" + serverUUID, Connector.READ_WRITE, true);
   // ローカルデバイスにサービスを登録。必須ではない。
   ServiceRecord record = LocalDevice.getLocalDevice().getRecord(server);
   LocalDevice.getLocalDevice().updateRecord(record);
 }
Example #6
0
  public NXTLocator(Display d) {
    mDisplay = d;
    messages = new TextBox("NXT Status", "Welcome!\n", 8192, TextField.ANY);
    mDisplay.setCurrent(messages);

    // retrieve the local Bluetooth device object
    try {
      local = LocalDevice.getLocalDevice();
      agent = local.getDiscoveryAgent();
    } catch (BluetoothStateException bse) {
      messages.insert("no device found\n", messages.size());
    }
  }
Example #7
0
 public BluetoothHandler() {
   // display local device address and name
   LocalDevice localDevice;
   try {
     localDevice = LocalDevice.getLocalDevice();
     System.out.println("Address: " + localDevice.getBluetoothAddress());
     System.out.println("Name: " + localDevice.getFriendlyName());
   } catch (BluetoothStateException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #8
0
  /**
   * Creates a PrintClient object and prepares the object for device discovery and service
   * searching.
   *
   * @exception BluetoothStateException if the Bluetooth system could not be initialized
   */
  public Discoverer() throws BluetoothStateException {

    /*
     * Retrieve the local Bluetooth device object.
     */
    LocalDevice local = LocalDevice.getLocalDevice();

    /*
     * Retrieve the DiscoveryAgent object that allows us to perform device
     * and service discovery.
     */
    agent = local.getDiscoveryAgent();

    deviceList = new Vector();
    serviceList = new Vector();
  }
  public void handleUpdatePacket(Packet p, String from) {
    // dont update packets that came from this device
    if (p.getSource().equals(localDevice.getBluetoothAddress())) return;

    // get the md5 of the payload of the packet and store it
    // if the previous md5 is the same with the new one
    // then this packet is redundant
    String hash = md5(p.getPayload());
    if (history.containsKey(p.getSource())) {
      String old = history.get(p.getSource());
      if (old.equals(hash)) return;
    }

    ByteBuffer buffer = ByteBuffer.allocate(p.getPayload().length);
    buffer.put(p.getPayload());
    routingTable.remove(p.getSource());
    routingTable.add(p.getSource());
    byte[] tmp = new byte[12];
    while (buffer.hasRemaining()) {
      buffer.get(tmp, 0, 12);
      routingTable.add(p.getSource(), new String(tmp));
    }

    for (String address : connections.keySet()) {
      if (!address.equals(from)) {
        connections.get(address).offer(p);
      }
    }
    history.put(p.getSource(), hash);
  }
  private SyndicateCore() throws BluetoothStateException {
    // initialize properties
    initProperties();
    Log("SynCore", "properties initialized");
    SYNDICATE_UUID = new UUID("04A6C7B", false);
    localDevice = LocalDevice.getLocalDevice();
    Log("SynCore", "local device initialized");

    mutex = new ReentrantReadWriteLock();
    connections = new HashMap<String, ConnectionHandler>();
    routingTable = new RoutingTable();
    routingTable.add(localDevice.getBluetoothAddress());
    lock = new ReentrantLock();
    master = false;
    in = new ConcurrentLinkedQueue<Packet>();
    history = new ConcurrentHashMap<String, String>();
  }
 public Set<String> getConnections() {
   mutex.readLock().lock();
   try {
     return routingTable.devices(localDevice.getBluetoothAddress());
   } finally {
     mutex.readLock().unlock();
   }
 }
  public void handleDataPacket(Packet p) {
    // this packet is for this device
    if (p.getDestination().equals(localDevice.getBluetoothAddress())) {
      offer(p);
    } else {
      String nextHop = routingTable.nextHop(localDevice.getBluetoothAddress(), p.getDestination());

      if (nextHop != null) {
        Log("SynCore", "Packet from: " + p.getSource() + " routed to: " + nextHop);
        for (String n : connections.keySet()) {
          if (n.equals(nextHop)) {
            connections.get(n).offer(p);
          }
        }
      }
    }
  }
 public boolean hasConnection(String address) {
   mutex.readLock().lock();
   try {
     // check also visibility graph
     return routingTable.search(localDevice.getBluetoothAddress(), address);
   } finally {
     mutex.readLock().unlock();
   }
 }
 public boolean send(String destination, byte[] data) {
   mutex.writeLock().lock();
   try {
     String nextHop = routingTable.nextHop(localDevice.getBluetoothAddress(), destination);
     if (nextHop != null) {
       Packet p =
           new Packet(Packet.DATA_PACKET, localDevice.getBluetoothAddress(), destination, data);
       ConnectionHandler handler = connections.get(nextHop);
       if (handler != null) {
         handler.offer(p);
         return true;
       }
     }
   } finally {
     mutex.writeLock().unlock();
   }
   return false;
 }
  public static ArrayList<BTDevice> discoverDevices() throws IOException, InterruptedException {

    final Object inquiryCompletedEvent = new Object();
    final ArrayList<BTDevice> discoveredDevices = new ArrayList<BTDevice>();
    discoveredDevices.clear();

    DiscoveryListener listener =
        new DiscoveryListener() {

          public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
            System.out.println(
                "-> BT Address: "
                    + btDevice.getBluetoothAddress()
                    + ", Authenticated:"
                    + btDevice.isAuthenticated()
                    + " Class: "
                    + cod);
            String friendlyName = btDevice.getBluetoothAddress();
            try {
              friendlyName = btDevice.getFriendlyName(false);
              if (cod.toString().toLowerCase().contains("printer")) {
                friendlyName = friendlyName + "(Impresora)";
              }
              System.out.println("\tFriendly Name:" + friendlyName);
            } catch (IOException cantGetDeviceName) {
              System.out.println("\t:( no  name");
            }
            discoveredDevices.add(new BTDevice(btDevice.getBluetoothAddress(), friendlyName));
          }

          public void inquiryCompleted(int discType) {
            System.out.println("Device Inquiry completed!");
            synchronized (inquiryCompletedEvent) {
              inquiryCompletedEvent.notifyAll();
            }
          }

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

          public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {}
        };

    synchronized (inquiryCompletedEvent) {
      boolean started =
          LocalDevice.getLocalDevice()
              .getDiscoveryAgent()
              .startInquiry(DiscoveryAgent.GIAC, listener);
      if (started) {
        System.out.println("-->>> wait for device inquiry to complete...");
        inquiryCompletedEvent.wait();
        System.out.println(discoveredDevices.size() + " device(s) found");
      }
    }
    return discoveredDevices;
  }
Example #16
0
  public static ClientSessionRecord get(String btAddr, Vector sessions, String uuid) {

    ClientSessionRecord sRec = ClientSessionRecord.search(btAddr, sessions);
    if (sRec != null) {
      return sRec;
    }
    try {
      String addr[] = {btAddr};
      DeviceDiscoverer devD = new DeviceDiscoverer(addr, LocalDevice.getLocalDevice());
      Vector devices = devD.getDiscoveredDevices();
      if (!devices.isEmpty()) {
        System.out.println("[client:] To download from " + devices.elementAt(0));
        // search for the service in the device(s) detected
        UUID[] uuidSet = new UUID[1];
        uuidSet[0] = new UUID(uuid, false);
        System.out.println("[client:] Some devices were found ");

        ServiceDiscoverer servD =
            new ServiceDiscoverer(
                uuidSet, (RemoteDevice) devices.elementAt(0), LocalDevice.getLocalDevice());

        Vector servRec = servD.getServiceRecords();
        System.out.println(servRec);
        if (!servRec.isEmpty()) {
          ClientSession conn =
              (ClientSession)
                  Connector.open(
                      ((ServiceRecord) servRec.elementAt(0))
                          .getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
          ClientSessionRecord retVal = new ClientSessionRecord(conn, btAddr);
          sessions.addElement(retVal);
          return retVal;
        } else {
          return null;
        }
      } else {
        return null;
      }
    } catch (IOException e) {
      return null;
    }
  }
 public void run() {
   ran = true;
   LocalDevice localDevice;
   try {
     localDevice = LocalDevice.getLocalDevice();
   } catch (BluetoothStateException e) {
     synchronized (waiter) {
       waiter.notify();
     }
     return;
   }
   DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
   try {
     discoveryAgent.searchServices(null, uuidSet, device, new BluetoothHelper());
   } catch (Exception e) {
     synchronized (waiter) {
       waiter.notify();
     }
     return;
   }
 }
 public void removeConnection(String address) {
   mutex.writeLock().lock();
   try {
     if (connections.containsKey(address)) {
       ConnectionHandler handler = connections.get(address);
       connections.remove(address);
       routingTable.remove(localDevice.getBluetoothAddress(), address);
       handler.setStop(true);
     }
   } finally {
     mutex.writeLock().unlock();
   }
 }
Example #19
0
 /**
  * Create and open a Connection. This Implementation only supports the <code>btl2cap://</code>
  * protocol schema. If url begins with <code>btl2cap://localhost</code>, this method call will
  * return a <code>javax.bluetooth.L2CAPConnectionNotifier</code>.
  *
  * @param url The URL for the connection.
  * @return A new <code>javax.bluetooth.L2CAPConnection</code> or a <code>
  *     javax.bluetooth.L2CAPConnectionNotifier</code>
  * @throws IllegalArgumentException If a parameter is invalid.
  * @throws IOException If some other kind of I/O error occurs.
  * @see javax.bluetooth.L2CAPConnection
  * @see javax.bluetooth.L2CAPConnectionNotifier
  */
 public static Connection open(String url) throws IOException {
   try {
     if (url.startsWith("btl2cap://localhost:")) {
       int endIndex = url.indexOf(';');
       String psmString = url.substring(20, endIndex);
       Short psmShort = Short.decode(psmString);
       short psm = psmShort.shortValue();
       return new JSR82ConnectionNotifier(psm);
     }
     if (url.startsWith("btl2cap://")) {
       byte[] bdAddrBytes = new byte[12];
       String bdAddrString = url.substring(10, 22);
       Long bdAddrLong = Long.decode("0x" + bdAddrString);
       long remoteAddrLong = bdAddrLong.longValue();
       int endIndex = url.indexOf(';', 22);
       String psmString = url.substring(23, endIndex);
       Short psmShort = Short.decode(psmString);
       short psm = psmShort.shortValue();
       BluetoothStack bluetooth = BluetoothStack.getBluetoothStack();
       LocalDevice localDev = LocalDevice.getLocalDevice();
       DiscoveryAgent discovery = localDev.getDiscoveryAgent();
       RemoteDevice remoteDevice = discovery.getRemoteDevice(remoteAddrLong);
       if (remoteDevice != null) {
         JSR82Channel channel = new JSR82Channel();
         bluetooth.connectL2CAPChannel(channel, remoteDevice, psm);
         return channel;
       } else throw new IllegalArgumentException("Unable to locate Bluetooth Device.");
     }
   } catch (BluetoothStateException e) {
     throw new IOException("" + e);
   } catch (HCIException e) {
     throw new IOException("" + e);
   }
   throw new IllegalArgumentException(
       "This implementation of Connector only supports btl2cap:// Connections.");
 }
  public Packet requestUpdatePacket() {
    mutex.readLock().lock();
    try {
      Set<String> n = connections.keySet();
      ByteBuffer buf = ByteBuffer.allocate(n.size() * 12);
      for (String i : n) {
        buf.put(i.getBytes());
      }

      return new Packet(
          Packet.UPDATE_PACKET, localDevice.getBluetoothAddress(), "UPDATEPACKET", buf.array());
    } finally {
      mutex.readLock().unlock();
    }
  }
 public void acceptConnection(BtConnection connection, boolean server) {
   mutex.writeLock().lock();
   try {
     if (!hasConnection(connection.getRemoteDevice().getBluetoothAddress())
         && connections.size() < 2) {
       ConnectionHandler handler = new ConnectionHandler(connection);
       connections.put(handler.getBtAddress(), handler);
       handler.start();
       routingTable.add(localDevice.getBluetoothAddress(), handler.getBtAddress());
     } else {
       connection.close();
     }
   } catch (IOException e) {
     Log("SynCore.acceptConnection", e.getMessage());
   } finally {
     mutex.writeLock().unlock();
   }
 }
  protected BTGPSLocationProvider() throws LocationException {

    // TODO: Move this to searchConnect method?
    // TODO: The problem here is that it searches every time. Slow. Need to try Properties?
    // TODO: BIG ONE: Should only connect to GPS that isPaired() (from menu). Will
    // allow some degree of control over which GPS is connects to in classroom.
    try {
      da = LocalDevice.getLocalDevice().getDiscoveryAgent();
      da.startInquiry(DiscoveryAgent.GIAC, this);
    } catch (BluetoothStateException e) {
      throw new LocationException(e.getMessage());
    }

    while (!doneInq) {
      Thread.yield();
    }

    if (btDevice == null) throw new LocationException("No device found");

    String address = btDevice.getBluetoothAddress();
    String btaddy = "btspp://" + address;

    try {
      StreamConnectionNotifier scn = (StreamConnectionNotifier) Connector.open(btaddy);

      if (scn == null) throw new LocationException("Bad BT address");
      StreamConnection c = scn.acceptAndOpen();

      /* This problem below occurred one time for my Holux GPS. The solution was to
       * remove the device from the Bluetooth menu, then find and pair again.
       */
      if (c == null) throw new LocationException("Failed. Try pairing at menu again");
      InputStream in = c.openInputStream();

      if (in != null) {
        gps = new SimpleGPS(in);
        // c.close(); // TODO: Clean up when done. HOW TO HANDLE IN LOCATION?
      }
    } catch (IOException e) {
      throw new LocationException(e.getMessage());
    }
    // Add itself to SimpleGPS as listener
    SimpleGPS.addListener(this);
  }
Example #23
0
  public static List<RemoteDevice> findDevices() {

    List<RemoteDevice> bluetoothDevices = new ArrayList<>();
    final Object inquiryCompletedEvent = new Object();

    DiscoveryListener listener =
        new DiscoveryListener() {

          @Override
          public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
            bluetoothDevices.add(btDevice);
          }

          @Override
          public void inquiryCompleted(int discType) {
            synchronized (inquiryCompletedEvent) {
              inquiryCompletedEvent.notifyAll();
            }
          }

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

          @Override
          public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {}
        };

    synchronized (inquiryCompletedEvent) {
      try {
        boolean started =
            LocalDevice.getLocalDevice()
                .getDiscoveryAgent()
                .startInquiry(DiscoveryAgent.GIAC, listener);
        if (started) {
          inquiryCompletedEvent.wait();
        }
      } catch (BluetoothStateException | InterruptedException ex) {
        LogManager.getLogger(BluetoothDevices.class).debug(ex);
      }
    }
    return bluetoothDevices;
  }
 public BluetoothBrowser() throws BluetoothStateException {
   localDevice = LocalDevice.getLocalDevice();
   agent = localDevice.getDiscoveryAgent();
 }
  @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() {

            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);
                  }
                }
              }
            }

            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>() {
                        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();
              }
            }

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

            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);
    }
  }
Example #26
0
 public static void main(String[] args) throws Exception {
   LocalDevice device = LocalDevice.getLocalDevice();
   System.out.print(device.getFriendlyName() + " at ");
   System.out.print(device.getBluetoothAddress());
   System.exit(0);
 }