Exemple #1
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);
      }
    }
  }
  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);
  }
 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 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 boolean hasConnection(String address) {
   mutex.readLock().lock();
   try {
     // check also visibility graph
     return routingTable.search(localDevice.getBluetoothAddress(), address);
   } finally {
     mutex.readLock().unlock();
   }
 }
 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();
   }
 }
Exemple #8
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();
   }
 }
  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();
    }
  }
  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 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();
   }
 }
 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);
 }
  @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);
    }
  }