コード例 #1
0
ファイル: RemoteControl.java プロジェクト: COMP7401/project
  /** Main entry to the program. */
  public static void main(String[] args) {
    RemoteControl remote = new RemoteControl();

    RemoteDevice racecar = Bluetooth.getKnownDevice("Batmobile");

    if (racecar == null) {
      System.out.println("No Such device existed");
      System.exit(1);
    }
    BTConnection racecarConnection = Bluetooth.connect(racecar);

    if (racecarConnection == null) {
      System.out.println("Connection Failed");
      System.exit(1);
    } else {
      System.out.println("Connected to Racecar");
    }

    DataOutputStream dos = racecarConnection.openDataOutputStream();
    try {
      System.out.println("Sending controller signal");
      dos.writeInt(CONTROLLER_DEVICE);
      dos.flush();
      System.out.println("Sent Controller signal");
    } catch (Exception ex) {
      // Do nothing
    }
    remote.setRacecarConnection(racecarConnection);
    remote.setRacecarOutputStream(dos);

    // Waiting for flag to set us off here
    System.out.println("Waiting for Flag connection");
    NXTConnection flagConnection = Bluetooth.waitForConnection();
    System.out.println("Connected to flag");
    DataInputStream dis = flagConnection.openDataInputStream();
    try {
      int check = dis.readInt();
      if (check == FLAG_SIGNAL) {
        System.out.println("Recived flag signal");
        dos.writeInt(FLAG_SIGNAL);
        dos.flush();
        System.out.println("sent flag signal to racecar");
        dis.close();
        remote.run();
      } else {
        System.out.println("Did not recieve flag connection");
      }

    } catch (Exception e) {

    }
  }
コード例 #2
0
ファイル: t5-s-slavecomplete.java プロジェクト: jd7h/des
  // a method for every state
  public static void Btinit() {
    // execute all actions of this state
    LCD.drawString("Btinit", 0, 3);
    LCD.drawString("Waiting...", 0, 0);
    LCD.refresh();

    BTConnection btc = Bluetooth.waitForConnection();

    LCD.clear();
    LCD.drawString("Connected", 0, 0);
    LCD.refresh();

    DataInputStream dis = btc.openDataInputStream();
    DataOutputStream dos = btc.openDataOutputStream();

    // BTfunctionality btThread = new BTfunctionality("SlaveReader",dis,dos);
    btThread = new BTfunctionality("SlaveReader", dis, dos);
    btThread.start();

    // leg de huidige tijd vast voor alle transitions met een timeoutcondition
    long starttime = System.currentTimeMillis();

    // when done, wait for a trigger for a transition
    boolean transitionTaken = false;
    while (!transitionTaken) {
      if ((true)) {
        current = State.WATCH;
        transitionTaken = true;
      }
    }
  }
コード例 #3
0
ファイル: DiscoveryAgent.java プロジェクト: 71104/simulejos
 /**
  * Removes the device from inquiry mode.
  *
  * <p>An <code>inquiryCompleted()</code> event will occur with a type of <code>INQUIRY_TERMINATED
  * </code> as a result of calling this method. After receiving this event, no further <code>
  * deviceDiscovered()</code> events will occur as a result of this inquiry.
  *
  * <p>This method will only cancel the inquiry if the <code>listener</code> provided is the
  * listener that started the inquiry.
  *
  * @param listener the listener that is receiving inquiry events
  * @return <code>true</code> if the inquiry was canceled; otherwise <code>false</code> if the
  *     inquiry was not canceled or if the inquiry was not started using <code>listener</code>
  * @exception NullPointerException if <code>listener</code> is <code>null</code>
  */
 public boolean cancelInquiry(DiscoveryListener listener) {
   if (listener == null) {
     throw new NullPointerException();
   }
   // Return true/false value from Bluetooth class
   return Bluetooth.cancelInquiry();
 }
コード例 #4
0
ファイル: DiscoveryAgent.java プロジェクト: 71104/simulejos
 /**
  * Returns an array of Bluetooth devices that have either been found by the local device during
  * previous inquiry requests or been specified as a pre-known device depending on the argument.
  * The list of previously found devices is maintained by the implementation of this API. (In other
  * words, maintenance of the list of previously found devices is an implementation detail.) A
  * device can be set as a pre-known device in the Bluetooth Control Center.
  *
  * @param option <code>CACHED</code> if previously found devices should be returned; <code>
  *     PREKNOWN</code> if pre-known devices should be returned
  * @return an array containing the Bluetooth devices that were previously found if <code>option
  *     </code> is <code>CACHED</code>; an array of devices that are pre-known devices if <code>
  *     option</code> is <code>PREKNOWN</code>; <code>null</code> if no devices meet the criteria
  * @exception IllegalArgumentException if <code>option</code> is not <code>CACHED</code> or <code>
  *     PREKNOWN</code>
  */
 public RemoteDevice[] retrieveDevices(int option) {
   // TODO: For now it doesn't discern between CACHED or PREKNOWN as our
   // leJOS Bluetooth stack doesn't support this?
   // if(option == CACHED|option == PREKNOWN)
   ArrayList<RemoteDevice> v = Bluetooth.getKnownDevicesList();
   RemoteDevice[] rdlist = new RemoteDevice[v.size()];
   for (int i = 0; i < rdlist.length; i++) rdlist[i] = v.get(i);
   return rdlist;
 }
コード例 #5
0
 public ClientSwarmThread() {
   BTConnection swarmcon = Bluetooth.waitForConnection();
   try {
     SkyIn = new ObjectInputStream(swarmcon.openInputStream());
     SkyOut = new ObjectOutputStream(swarmcon.openOutputStream());
   } catch (IOException e) {
     // y r u no work
   }
 }
コード例 #6
0
  // Main thread
  public void run() {
    String stringBuffer = "";
    byte[] byteBuffer = new byte[1024];

    connection = Bluetooth.waitForConnection();
    connected = true;
    is = connection.openDataInputStream();
    os = connection.openDataOutputStream();
    terminateFlag = false;

    while (!terminateFlag) {
      // read into byte[] buffer
      int bytesRead;
      try {
        bytesRead = is.read(byteBuffer);
      } catch (IOException e) {
        bytesRead = 0;
      }
      if (bytesRead > 0) {
        // transfer from byte[] into StringBuffer
        stringBuffer += new String(byteBuffer, 0, bytesRead);
        // check for }
        // if found, this suggests that we just finished receiving a full message
        int endChar = stringBuffer.indexOf("}");
        if (endChar != -1) {
          // check for matching {
          int startChar = stringBuffer.indexOf("{");
          if (startChar != -1 && startChar < endChar) {
            // parse the message and add it to the queue
            Message messageRead = new Message(stringBuffer.substring(startChar, endChar + 1));
            messageQueue.push(messageRead);
            Message ack = new Message(messageRead.getSeqNum());
            ack.pairs.add(new String[] {"ack", null});
            sendMessage(ack);
          }

          // clean command up to } off stringBuffer
          if (endChar == stringBuffer.length() - 1) {
            stringBuffer = "";
          } else {
            stringBuffer = stringBuffer.substring(endChar + 1);
          }
        }
      }
    }

    // disconnect
    try {
      is.close();
      os.close();
    } catch (IOException e) {
      // TODO: not fail silently
    }
    connection.close();
    connected = false;
  }
コード例 #7
0
ファイル: StateController.java プロジェクト: danopia/brixmark
  public void run() {
    System.out.println("Connecting to " + name);
    conn = Bluetooth.connect(Bluetooth.getKnownDevice(name));
    conn.setIOMode(NXTConnection.PACKET);

    dis = conn.openDataInputStream();
    dos = conn.openDataOutputStream();
    System.out.println("NXT connected");

    // Request dimensions
    try {
      dos.writeByte(3);
      dos.flush();
    } catch (IOException e1) {
    }

    try {
      while (true) {
        byte type = dis.readByte();
        switch (type) {
          case 1:
            byte slot = dis.readByte();
            byte state = dis.readByte();
            states[slot] = state;
            break;

          case 3:
            slotCount = dis.readByte();
            stateCount = dis.readByte();
            break;

          case 127:
            EStop.thread.activate = true;
            break;
        }
      }
    } catch (IOException e) {
      Sound.buzz();
      System.out.println("Comm dropped to " + name);
    }
  }
コード例 #8
0
ファイル: MainCtrl2.java プロジェクト: sdp-2011/sdp-9
 // Aims to establish a conection over Bluetooth
 private static void connect() {
   Thread tryingDisplay = new ScreenWriter("Trying to connect", 7);
   tryingDisplay.start();
   // Wait until connected
   connection = Bluetooth.waitForConnection();
   Thread connectedDisplay = new ScreenWriter("Connected", 7);
   connectedDisplay.start();
   inputStream = connection.openDataInputStream();
   outputStream = connection.openDataOutputStream();
   Thread openConnDisplay = new ScreenWriter("Connection Opened", 7);
   openConnDisplay.start();
 }
コード例 #9
0
ファイル: BTReceive.java プロジェクト: aramovski/lego_segway
  public void run() {

    try {

      // TODO: clean closing of connection

      for (; ; ) {

        BTConnection btc = Bluetooth.waitForConnection();
        DataInputStream dis = btc.openDataInputStream();

        // Read Input-Number from BTSend
        int n = dis.readInt();

        switch (n) {
          case 0:
            // up
            swp.forward();
            break;
          case 1:
            // down
            swp.backward();
            break;
          case 2:
            // left
            swp.arc(-1, 60, true);
            break;
          case 3:
            // right
            swp.arc(1, 60, true);
            break;
          case 4:
            // Stop
            swp.stop();
            break;
          default:
            // do nothing
            break;
        }

        LCD.clear();
        dis.close();
        btc.close();
      }

    } catch (Exception ioe) {
      // LCD.drawString(ioe.getMessage(), 2, 0);
    }
  }
コード例 #10
0
  private void connectToDevice() {
    try {
      btc = Bluetooth.waitForConnection();
      if (btc == null) {
        RConsole.println("[BT] Connection error!");
        throw new BluetoothStateException("Connection error!");
      }

      dos = btc.openDataOutputStream();

    } catch (BluetoothStateException e) {
      e.printStackTrace();
      Delay.msDelay(waitBetweenSends);
      connectToDevice();
    }
  }
コード例 #11
0
ファイル: NXTLCPRespond.java プロジェクト: sdp-2011/sdp-9
  public static void main(String[] args) throws Exception {
    String[] connectionStrings = new String[] {"Bluetooth", "USB", "RS485"};
    TextMenu connectionMenu = new TextMenu(connectionStrings, 0, "Connection");
    NXTCommConnector[] connectors = {
      Bluetooth.getConnector(), USB.getConnector(), RS485.getConnector()
    };

    int connectionType = connectionMenu.select();
    LCD.clear();
    LCD.clear();
    LCD.drawString("Type: " + connectionStrings[connectionType], 0, 0);
    LCD.drawString("Running...", 0, 1);
    Responder resp = new Responder(connectors[connectionType]);
    resp.start();
    resp.join();
    LCD.drawString("Closing...  ", 0, 1);
  }
コード例 #12
0
  // Opens BT Connection
  public boolean openBTConnection() {

    try {
      // Connection is open and is set to lisent until connected
      btc = Bluetooth.waitForConnection();
      btc.setIOMode(NXTConnection.RAW);

      // Opens the input and output streams
      dis = btc.openDataInputStream();
      dos = btc.openDataOutputStream();

      connectionMade = true;
    } catch (Exception e) {
      // Error handler
      System.out.println(e.getMessage());
      connectionMade = false;
      return false;
    }

    return true;
  }
コード例 #13
0
ファイル: BTReceive2.java プロジェクト: lego-line/lejos
  public static void main(String[] args) throws Exception {
    String connected = "Connected";
    String waiting = "Waiting...";
    String closing = "Closing...";

    while (true) {
      LCD.drawString(waiting, 0, 0);
      LCD.refresh();

      // BTConnection btc = Bluetooth.waitForConnection();
      BTConnection btc = Bluetooth.waitForConnection(0, NXTConnection.RAW);

      LCD.clear();
      LCD.drawString(connected, 0, 0);
      LCD.refresh();

      DataInputStream dis = btc.openDataInputStream();
      DataOutputStream dos = btc.openDataOutputStream();

      for (int i = 0; i < 100; i++) {
        int n = dis.readInt();
        LCD.drawInt(n, 7, 0, 1);
        LCD.refresh();
        dos.writeInt(-n);
        dos.flush();
      }

      dis.close();
      dos.close();
      Thread.sleep(100); // wait for data to drain
      LCD.clear();
      LCD.drawString(closing, 0, 0);
      LCD.refresh();
      btc.close();
      LCD.clear();
    }
  }
コード例 #14
0
// Bluetooth communication class to handle bt stuff
public class BT_Comm {

  public static final byte MOVE_FOWARD = 10;
  public static final byte MOVE_FOWARD_LEFT = 11;
  public static final byte MOVE_FOWARD_RIGHT = 12;
  public static final byte ROTATE_LEFT = 13;
  public static final byte ROTATE_RIGHT = 14;
  public static final byte MOVE_BACKWARD = 15;
  public static final byte MOVE_BACKWARD_LEFT = 16;
  public static final byte MOVE_BACKWARD_RIGHT = 17;
  public static final byte STOP = 18;

  public static final byte SET_MOTOR_SPD = 19;

  public static final byte SEND_ULTRA_DATA = 20;

  public static final byte CLOSE_COMM = 21;

  public static final byte CUSTOM_MOVE = 25;

  // Stores local MAC Address
  private String localAddress = Bluetooth.getLocalAddress();

  private BTConnection btc;
  private DataInputStream dis;
  private DataOutputStream dos;

  private Boolean connectionMade = false;

  private int motorSpeed = 360;

  public String getMacAddress() {
    return localAddress;
  }

  // Opens BT Connection
  public boolean openBTConnection() {

    try {
      // Connection is open and is set to lisent until connected
      btc = Bluetooth.waitForConnection();
      btc.setIOMode(NXTConnection.RAW);

      // Opens the input and output streams
      dis = btc.openDataInputStream();
      dos = btc.openDataOutputStream();

      connectionMade = true;
    } catch (Exception e) {
      // Error handler
      System.out.println(e.getMessage());
      connectionMade = false;
      return false;
    }

    return true;
  }

  // Closes BT Connection
  public void closeBTConnection() {
    try {
      dis.close();
      dos.close();
      connectionMade = false;
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }

  // Read msg
  public int readMessage() {
    byte rMSG = -1;
    try {
      // Read
      rMSG = dis.readByte();
      // Decode
      decodeMSG(rMSG);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      connectionMade = false;
      return -1;
    }

    return rMSG; // returns msg read
  }

  // Write msg
  public boolean writeMessage(int msg) {

    try {
      // Write
      dos.write(msg);
      // flush to stream
      dos.flush();
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return false;
    }

    return true;
  }

  // Get connection mode
  public boolean getConnectionMade() {
    return connectionMade;
  }

  // Decode msg method
  public void decodeMSG(Byte msg) throws IOException {
    // Motor Movement Functions
    //        int currentSpeedA = Motor.A.getSpeed();
    //        int currentSpeedB = Motor.B.getSpeed();

    if (msg == MOVE_FOWARD) {
      Motor.A.backward();
      Motor.B.backward();
    } else if (msg == MOVE_FOWARD_LEFT) {
      Motor.A.backward();
      Motor.B.setSpeed(motorSpeed / 2);
      Motor.B.backward();

    } else if (msg == MOVE_FOWARD_RIGHT) {
      Motor.A.setSpeed(motorSpeed / 2);
      Motor.A.backward();
      Motor.B.backward();

    } else if (msg == ROTATE_LEFT) {
      Motor.A.backward();
      Motor.B.forward();
    } else if (msg == ROTATE_RIGHT) {
      Motor.A.forward();
      Motor.B.backward();
    } else if (msg == MOVE_BACKWARD) {
      Motor.A.forward();
      Motor.B.forward();
    } else if (msg == STOP) {
      Motor.A.setSpeed(motorSpeed);
      Motor.B.setSpeed(motorSpeed);
      Motor.A.stop();
      Motor.B.stop();
    }

    // Motor set Speed Function
    if (msg == SET_MOTOR_SPD) {

      Byte rMsg = 40;

      rMsg = dis.readByte();

      int spd = 9 * rMsg;
      motorSpeed = spd;

      Motor.A.setSpeed(spd);
      Motor.B.setSpeed(spd);
    }

    if (msg == CUSTOM_MOVE) {
      int motorB = dis.read();
      int motorA = dis.read();
      Motor.A.setSpeed(motorA * 9);
      Motor.B.setSpeed(motorB * 9);
      Motor.A.backward();
      Motor.B.backward();
    }

    // Connection close msg
    if (msg == CLOSE_COMM) {
      closeBTConnection();
    }
  }
}
コード例 #15
0
ファイル: RemoteNXTTest.java プロジェクト: lego-line/lejos
  public static void main(String[] args) throws Exception {
    RemoteNXT nxt = null;
    int power = 0;
    int mode = 1;
    int motor = 0;
    String motorString = "Motor:";
    String modeString = "Mode:";
    String powerString = "Power:";
    String batteryString = "Battery:";
    String lightString = "Light:";
    String tachoString = "Tacho:";

    // Get the type of communications to be used
    String[] connectionStrings = new String[] {"Bluetooth", "RS485"};
    TextMenu connectionMenu = new TextMenu(connectionStrings, 1, "Connection");
    NXTCommConnector[] connectors = {Bluetooth.getConnector(), RS485.getConnector()};

    int connectionType = connectionMenu.select();

    // Now connect
    try {
      LCD.clear();
      LCD.drawString("Connecting...", 0, 0);
      nxt = new RemoteNXT("NXT", connectors[connectionType]);
      LCD.clear();
      LCD.drawString("Type: " + connectionStrings[connectionType], 0, 0);
      LCD.drawString("Connected", 0, 1);
      Thread.sleep(2000);
    } catch (IOException ioe) {
      LCD.clear();
      LCD.drawString("Conn Failed", 0, 0);
      Thread.sleep(2000);
      System.exit(1);
    }

    LCD.clear();
    RemoteMotor[] motors = {nxt.A, nxt.B, nxt.C};
    LightSensor light = new LightSensor(nxt.S2);
    while (true) {
      // Get data from the remote NXT and display it
      LCD.drawString(motorString, 0, 0);
      LCD.drawInt(motor, 3, 10, 0);
      LCD.drawString(powerString, 0, 1);
      LCD.drawInt(power, 3, 10, 1);
      LCD.drawString(modeString, 0, 2);
      LCD.drawInt(mode, 3, 10, 2);
      LCD.drawString(tachoString, 0, 3);
      LCD.drawInt(motors[motor].getTachoCount(), 6, 7, 3);
      LCD.drawString(batteryString, 0, 4);
      LCD.drawInt(nxt.Battery.getVoltageMilliVolt(), 6, 7, 4);
      LCD.drawString(lightString, 0, 5);
      LCD.drawInt(light.readValue(), 6, 7, 5);
      LCD.drawString(nxt.getBrickName(), 0, 6);
      LCD.drawString(nxt.getFirmwareVersion(), 0, 7);
      LCD.drawString(nxt.getProtocolVersion(), 4, 7);
      LCD.drawInt(nxt.getFlashMemory(), 6, 8, 7);

      // Do we have a button press?
      int key = Button.readButtons();
      if (key != 0) {
        // New command, work out what to do.
        if (key == 1) { // ENTER
          power += 20;
          if (power > 100) power = 0;
        } else if (key == 2) { // LEFT
          mode++;
          if (mode > 4) mode = 1;
        } else if (key == 4) { // RIGHT
          motor++;
          if (motor > 2) motor = 0;
        } else if (key == 8) { // ESCAPE
          LCD.clear();
          LCD.drawString("Closing...", 0, 0);
          for (int i = 0; i < motors.length; i++) motors[i].flt();
          nxt.close();
          Thread.sleep(2000);
          System.exit(0);
        }

        LCD.clear();
        LCD.drawString("Setting power", 0, 0);
        motors[motor].setPower(power);
        LCD.drawString("Moving motor", 0, 1);
        if (mode == 1) motors[motor].forward();
        else if (mode == 2) motors[motor].backward();
        else if (mode == 3) motors[motor].flt();
        else if (mode == 4) motors[motor].stop();
        // Wait for the button to be released...
        while (Button.readButtons() != 0) Thread.yield();
        LCD.clear();
      }
    }
  }