Ejemplo n.º 1
0
  public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (portId.getName().equals("COM17")) {
          // if (portId.getName().equals("/dev/term/a")) {
          try {
            serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
          } catch (PortInUseException e) {
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
          }
          try {
            serialPort.setSerialPortParams(
                9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
          }

          try {
            outputStream.write(messageString.getBytes());
          } catch (IOException e) {
          }
        }
      }
    }
  }
  /** Opens the Serial port with the baud and port_name given */
  public boolean OpenSerial(int baud, String port) {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      if (currPortId.getName().equals(port)) {
        portId = currPortId;
        break;
      }
    }

    if (portId == null) {
      System.err.println("Can not open serial port");
      return false;
    }

    try {
      serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);

      serialPort.setSerialPortParams(
          baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      input = serialPort.getInputStream();
      output = serialPort.getOutputStream();

      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
      Thread.sleep(1500);
    } catch (Exception e) {
      return false;
    }

    return true;
  }
Ejemplo n.º 3
0
  public TestSer(String port) {

    try {
      portId = CommPortIdentifier.getPortIdentifier(port);
      serialPort = (SerialPort) portId.open("TestSer", 2000);
      is = serialPort.getInputStream();
      os = serialPort.getOutputStream();
      /*
      			serialPort.addEventListener(this);
      			serialPort.notifyOnDataAvailable(true);
      */

      serialPort.setSerialPortParams(
          115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      serialPort.setFlowControlMode(
          SerialPort.FLOWCONTROL_RTSCTS_OUT | SerialPort.FLOWCONTROL_RTSCTS_IN);

      serialPort.enableReceiveTimeout(TIMEOUT);
      //			serialPort.enableReceiveThreshold(4);

    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.exit(-1);
    }
  }
Ejemplo n.º 4
0
  /**
   * This creates an mbed object for an mbed connected over Serial. <br>
   * Using this class requires the Sun Communications API to be installed
   *
   * @param PortName The Serial Port mbed is connected to eg "COM5" on Windows.
   * @param Baud The baud rate
   */
  public SerialRPC(String PortName, int Baud) {
    // open serial port
    try {
      mbedPortID = CommPortIdentifier.getPortIdentifier(PortName);

      mbedPort = mbedPortID.open("mbed", 100000);
      mbedSerialPort = (SerialPort) mbedPort;
      mbedSerialPort.setSerialPortParams(
          Baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      inputStream = new DataInputStream(mbedPort.getInputStream());
      outputStream = new PrintStream(mbedPort.getOutputStream(), true);

      reader = new BufferedReader(new InputStreamReader(inputStream));
      to_mbed = new PrintWriter(outputStream, true);

      mbedSerialPort.addEventListener(this);
      // Important to set this regardless of whether interrupts are in use to keep the buffer clear
      mbedSerialPort.notifyOnDataAvailable(true);

    } catch (TooManyListenersException e) {
      // Error adding event listener
      System.out.println("Too many Event Listeners");
    } catch (NoSuchPortException e) {
      System.out.println("No Such Port");
    } catch (PortInUseException e) {
      System.out.println("Port Already In Use");
    } catch (UnsupportedCommOperationException e) {
      System.out.println("Unsupported Comm Operation");
    } catch (IOException e) {
      System.out.println("Serial Port IOException");
    }
  }
Ejemplo n.º 5
0
 public static void initSerial() {
   Enumeration portList = CommPortIdentifier.getPortIdentifiers();
   CommPortIdentifier portId = null;
   boolean portFound = false;
   while (portList.hasMoreElements()) {
     portId = (CommPortIdentifier) portList.nextElement();
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       if (portId.getName().equals("COM3")) {
         portFound = true;
       }
     }
   }
   if (!portFound) {
     System.out.println("port COM3 not found.");
     return;
   }
   SerialPort port;
   try {
     port = (SerialPort) portId.open("COM3", 2000);
     port.setSerialPortParams(
         115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
     comOS = new DataOutputStream(port.getOutputStream());
   } catch (PortInUseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (UnsupportedCommOperationException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 6
0
  private void write(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortScale); // Tomamos el puerto
        m_CommPortPrinter =
            (SerialPort) m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura
        m_in = m_CommPortPrinter.getInputStream();

        m_CommPortPrinter.addEventListener(this);
        m_CommPortPrinter.notifyOnDataAvailable(true);

        m_CommPortPrinter.setSerialPortParams(
            4800,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_ODD); // Configuramos el puerto
      }
      m_out.write(data);
    } catch (NoSuchPortException e) {
      e.printStackTrace();
    } catch (PortInUseException e) {
      e.printStackTrace();
    } catch (UnsupportedCommOperationException e) {
      e.printStackTrace();
    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 7
0
 public static void listPorts() {
   Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
   while (portEnum.hasMoreElements()) {
     CommPortIdentifier portIdentifier = portEnum.nextElement();
     System.out.println(
         portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
   }
 }
Ejemplo n.º 8
0
  public static Serial open(String defaultPort) {
    boolean portFound = false;
    final int mComPortIdentifier = CommPortIdentifier.PORT_SERIAL;
    final Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    final int BAUD = 115200;

    while (portList.hasMoreElements()) {
      final CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
      System.out.println("Found port id: " + portId);

      if (portId.getPortType() == mComPortIdentifier) {
        System.out.println("Found CommPortIdentifier.");

        if (portId.getName().equals(defaultPort)) {
          System.out.println("Found port " + defaultPort);

          SerialPort serialPort;
          OutputStream outputStream = null;

          try {
            serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
          } catch (PortInUseException e) {
            System.out.println("Port in use.");
            continue;
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            e.printStackTrace();
          }

          try {
            serialPort.setSerialPortParams(
                BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
          }

          try {
            serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
          }

          return new Serial(serialPort, outputStream);
        }
      }
    }

    if (!portFound) {
      System.out.println("port " + defaultPort + " not found.");
    }
    return null;
  }
Ejemplo n.º 9
0
 public static List<String> getAvailablePorts() {
   List<String> portNames = new ArrayList<>();
   Enumeration identifiers = CommPortIdentifier.getPortIdentifiers();
   while (identifiers.hasMoreElements()) {
     CommPortIdentifier identifier = (CommPortIdentifier) identifiers.nextElement();
     if (identifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       portNames.add(identifier.getName());
     }
   }
   return portNames;
 }
Ejemplo n.º 10
0
 /*! This method initializes the input and output stream member
 	variables. It throws an exception if the COM port identifier
 	is not found.
 */
 private void initSerial() throws Exception {
   CommPortIdentifier portId =
       CommPortIdentifier.getPortIdentifier(
           comPort); // get the port ID for the port name received through command line
   if (portId == null) {
     throw new NullPointerException("no com port identifier");
   }
   serPort = (SerialPort) portId.open("Shake", 5000); // open the serial Port
   outStream = serPort.getOutputStream(); // get output stream to the serial port
   inStream = serPort.getInputStream(); // get input stram to the serial port
   inBufReader = new BufferedReader(new InputStreamReader(inStream));
 }
Ejemplo n.º 11
0
  // search for all the serial ports
  // pre: none
  // post: adds all the found ports to a combo box on the GUI
  public void searchForPorts() {
    ports = CommPortIdentifier.getPortIdentifiers();

    while (ports.hasMoreElements()) {
      CommPortIdentifier curPort = (CommPortIdentifier) ports.nextElement();

      // get only serial ports
      if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        portMap.put(curPort.getName(), curPort);
      }
    }
  }
Ejemplo n.º 12
0
  /*
   * Open the port, wait for chip init
   */
  public static int initialize(String portName) {
    System.out.println("Enumerating serial ports:");
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        // DDT
        System.out.println(portId.getName());

        if (portId.getName().equals(portName)) {
          System.out.println("Name match on port " + portName);
          // Init the port, matches name we were given
          try {
            serialPort = (SerialPort) portId.open("tx-skeleton", 64);
          } catch (PortInUseException e) {
            e.printStackTrace();
            System.out.println("Port in use!");
            return (4);
          }
          try {
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            System.out.println("Unable to connect to I/O streams");
            return (3);
          }

          try {
            System.out.println("Initializing ADXL202 board...");
            // 38400N81
            serialPort.setSerialPortParams(
                38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            // ADXL202 is powered via DTR line, so set it on
            serialPort.setDTR(true);

            try {
              // Wait a couple of seconds for chip to initialize (blinking LED)
              Thread.sleep(2000);
            } catch (InterruptedException ie) {
            }

          } catch (UnsupportedCommOperationException e) {
            System.out.println("Unable to configure serial port!");
            return (1);
          }
          return (0);
        }
      }
    }

    return (1);
  }
Ejemplo n.º 13
0
 // find all available serial ports for the settings->ports menu.
 public String[] ListSerialPorts() {
   @SuppressWarnings("unchecked")
   Enumeration<CommPortIdentifier> ports =
       (Enumeration<CommPortIdentifier>) CommPortIdentifier.getPortIdentifiers();
   ArrayList<String> portList = new ArrayList<String>();
   while (ports.hasMoreElements()) {
     CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
     if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       portList.add(port.getName());
     }
   }
   portsDetected = (String[]) portList.toArray(new String[0]);
   return portsDetected;
 }
Ejemplo n.º 14
0
 public static SerialPort openPortByName(String name, int baudRate) {
   SerialPort port = null;
   try {
     CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(name);
     port = (SerialPort) identifier.open("SerialPort", 2000);
     port.setSerialPortParams(
         baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   } catch (PortInUseException | NoSuchPortException | UnsupportedCommOperationException ex) {
     ErrorDialog dialog = new ErrorDialog(null, true, ex.getMessage());
     ComponentPosition.centerFrame(dialog);
     dialog.setVisible(true);
   }
   return port;
 }
Ejemplo n.º 15
0
  public boolean oeffneSerialPort() {
    Boolean foundPort = false;
    if (serialPortGeoeffnet != false) {
      System.out.println("Serialport bereits geöffnet");
      return false;
    }
    System.out.println("Öffne Serialport");
    enumComm = CommPortIdentifier.getPortIdentifiers();
    while (enumComm.hasMoreElements()) {
      serialPortId = (CommPortIdentifier) enumComm.nextElement();
      if (portName.contentEquals(serialPortId.getName())) {
        foundPort = true;
        break;
      }
    }
    if (foundPort != true) {
      System.out.println("Serialport nicht gefunden: " + portName);
      return false;
    }
    try {
      serialPort = (SerialPort) serialPortId.open("Öffnen und Senden", 500);
    } catch (PortInUseException e) {
      System.out.println("Port belegt");
    }

    try {
      outputStream = serialPort.getOutputStream();
    } catch (IOException e) {
      System.out.println("Keinen Zugriff auf OutputStream");
    }

    try {
      inputStream = serialPort.getInputStream();
    } catch (IOException e) {
      System.out.println("Keinen Zugriff auf InputStream");
    }

    serialPort.notifyOnDataAvailable(true);
    try {
      serialPort.setSerialPortParams(baudrate, dataBits, stopBits, parity);
    } catch (UnsupportedCommOperationException e) {
      System.out.println("Konnte Schnittstellen-Paramter nicht setzen");
    }

    reader = new BufferedReader(new InputStreamReader(inputStream));
    writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    serialPortGeoeffnet = true;
    return true;
  }
Ejemplo n.º 16
0
  public void open()
      throws NoSuchPortException, PortInUseException, IOException,
          UnsupportedCommOperationException {
    portId = CommPortIdentifier.getPortIdentifier(portName);
    port = (SerialPort) portId.open(CLASS_NAME, 0);
    in = port.getInputStream();
    out = port.getOutputStream();

    port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
    port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT);

    printPortStatus();
    port.setSerialPortParams(
        19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    printPortStatus();
  }
Ejemplo n.º 17
0
  // connect to the selected port in the combo box
  // pre: ports are already found by using the searchForPorts method
  // post: the connected comm port is stored in commPort, otherwise,
  // an exception is generated
  public void connect() {
    //        String selectedPort = (String)window.cboxPorts.getSelectedItem();
    /** Setting 에서 Comport 불러오는 걸로 수정 * */
    // String selectedPort = "COM4";
    selectedPortIdentifier = (CommPortIdentifier) portMap.get(selectedPort);

    CommPort commPort = null;

    try {
      // the method below returns an object of type CommPort
      commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT);
      // the CommPort object can be casted to a SerialPort object
      serialPort = (SerialPort) commPort;

      // for controlling GUI elements
      setConnected(true);

      // logging
      logText = selectedPort + " opened successfully.";
      System.out.println(logText + "\n");

      // CODE ON SETTING BAUD RATE ETC OMITTED
      // XBEE PAIR ASSUMED TO HAVE SAME SETTINGS ALREADY
    } catch (PortInUseException e) {
      logText = selectedPort + " is in use. (" + e.toString() + ")";
      System.out.println(logText + "\n");
    } catch (Exception e) {
      logText = "Failed to open " + selectedPort + "(" + e.toString() + ")";
      System.out.println(logText + "\n");
    }
  }
Ejemplo n.º 18
0
  public int setUpBam() {
    Enumeration<?> portIdentifiers = CommPortIdentifier.getPortIdentifiers();
    CommPortIdentifier portId = null;

    while (portIdentifiers.hasMoreElements()) {
      CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();

      if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
          && pid.getName().equals(wantedPortName)) {
        portId = pid;
        System.out.println("Found port: " + pid.getName());
        break;
      }
    }

    try {
      port = (SerialPort) portId.open("Driver", 10000);
    } catch (PortInUseException e) {
      System.err.println("Port already in use: " + e);
      System.exit(1);
    }

    try {
      port.setSerialPortParams(
          57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {
      System.err.println("Failed to set up port: " + e);
    }
    System.out.println("Port should be open now");
    return 0;
  }
Ejemplo n.º 19
0
  /** returns an array of all the serial ports available */
  public static CommPortIdentifier[] getSerialPorts() {
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
    int i = 0;
    while (portEnum.hasMoreElements()) {
      i++;
      portEnum.nextElement();
    }

    CommPortIdentifier[] portId = new CommPortIdentifier[i];
    Enumeration portEnum2 = CommPortIdentifier.getPortIdentifiers();

    i = 0;
    while (portEnum2.hasMoreElements()) {
      portId[i] = (CommPortIdentifier) portEnum2.nextElement();
      i++;
    }
    return portId;
  }
  /** @param data */
  @Override
  protected void internalWrite(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortPrinter); // Tomamos el puerto
        m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura

        if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          ((SerialPort) m_CommPortPrinter)
              .setSerialPortParams(
                  9600,
                  SerialPort.DATABITS_8,
                  SerialPort.STOPBITS_1,
                  SerialPort.PARITY_NONE); // Configuramos el puerto
          ((SerialPort) m_CommPortPrinter)
              .setFlowControlMode(
                  SerialPort
                      .FLOWCONTROL_RTSCTS_IN); // this line prevents the printer tmu220 to stop
                                               // printing after +-18 lines printed
          // this line prevents the printer tmu220 to stop printing after +-18 lines printed. Bug
          // 8324
          // But if added a regression error appears. Bug 9417, Better to keep it commented.
          // ((SerialPort)m_CommPortPrinter).setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
          // Not needed to set parallel properties
          //                } else if (m_PortIdPrinter.getPortType() ==
          // CommPortIdentifier.PORT_PARALLEL) {
          //                    ((ParallelPort)m_CommPortPrinter).setMode(1);

        }
      }
      m_out.write(data);
      // JG 16 May 12 use multicatch
    } catch (NoSuchPortException
        | PortInUseException
        | UnsupportedCommOperationException
        | IOException e) {
      System.err.println(e);
    }
  }
Ejemplo n.º 21
0
  void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
      System.out.println("Error: Port is currently in use");
    } else {
      CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

      if (commPort instanceof SerialPort) {
        SerialPort mSerialPort = (SerialPort) commPort;
        mSerialPort.setSerialPortParams(
            57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        InputStream mIn = mSerialPort.getInputStream();
        OutputStream mOut = mSerialPort.getOutputStream();

        (new Thread(new SerialReader(mIn))).start();
        (new Thread(new SerialWriter(mOut))).start();

      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
  }
  public void connection() {
    try {
      portId = CommPortIdentifier.getPortIdentifier("COM10");

      sPort = (SerialPort) portId.open("COM10", 1000);
      sPort.setSerialPortParams(9600, 8, 1, sPort.PARITY_NONE);

      is = sPort.getInputStream();
      os = sPort.getOutputStream();

      dis = new DataInputStream(is);
      dos = new DataOutputStream(os);
    } catch (NoSuchPortException e) {
      System.out.println("No Port\n" + e);
    } catch (PortInUseException e) {
      System.out.println("Port\n" + e);
    } catch (UnsupportedCommOperationException e) {
      System.out.println("Unsupported Problem\n" + e);
    } catch (IOException e) {
      System.out.println("IO Problem" + e);
    } catch (Exception e) {
      System.out.println("Unknown Problem" + e);
    }
  }
Ejemplo n.º 23
0
  public void printAllPorts() {
    Enumeration ports = CommPortIdentifier.getPortIdentifiers();

    if (ports == null) {
      System.out.println("No comm ports found!");
      return;
    }

    // print out all ports
    System.out.println("printing all ports...");
    while (ports.hasMoreElements()) {
      System.out.println("  " + ((CommPortIdentifier) ports.nextElement()).getName());
    }
    System.out.println("done.");
  }
Ejemplo n.º 24
0
  /** Connect to Serial Port (e.g FTDI module) */
  public boolean connect(CommPortIdentifier port, int speed) throws PortInUseException {
    this.speed = speed;
    serialPort = (SerialPort) port.open("FTDI", 2000);
    try {
      outputStream = serialPort.getOutputStream();
      inputStream = serialPort.getInputStream();

      serialPort.setSerialPortParams(
          this.speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      serialPort.notifyOnOutputEmpty(true);
      return true;
    } catch (IOException e) {
      e.printStackTrace();
    } catch (UnsupportedCommOperationException e) {
      e.printStackTrace();
    }
    return false;
  }
Ejemplo n.º 25
0
 /**
  * @return A HashSet containing the CommPortIdentifier for all serial ports that are not currently
  *     being used.
  */
 @SuppressWarnings({"rawtypes"})
 private static HashSet<CommPortIdentifier> getAvailableSerialPorts() {
   HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
   Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
   while (thePorts.hasMoreElements()) {
     CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
     switch (com.getPortType()) {
       case CommPortIdentifier.PORT_SERIAL:
         try {
           CommPort thePort = com.open("CommUtil", 50);
           thePort.close();
           h.add(com);
         } catch (PortInUseException e) {
           System.out.println("Port, " + com.getName() + ", is in use.");
         } catch (Exception e) {
           System.err.println("Failed to open port " + com.getName());
           e.printStackTrace();
         }
     }
   }
   return h;
 }
Ejemplo n.º 26
0
  public static void main(String args[]) {

    // Command to turn of GPS
    int[] turn_off = new int[8];
    turn_off[0] = DLE;
    turn_off[1] = Pid_Command_Packet;
    turn_off[2] = 2; // Length of data
    turn_off[3] = Cmnd_Turn_Off_Pwr;
    turn_off[4] = 0;
    turn_off[6] = DLE;
    turn_off[7] = ETX;

    calcChecksum(turn_off);
    System.out.println("Turn off checksum: " + turn_off[5]);

    // Command to ask GPS for time data.
    int[] transfer_time = new int[8];
    transfer_time[0] = DLE;
    transfer_time[1] = Pid_Command_Packet;
    transfer_time[2] = 2;
    transfer_time[3] = Cmnd_Transfer_Time;
    transfer_time[4] = 0;
    transfer_time[6] = DLE;
    transfer_time[7] = ETX;

    calcChecksum(transfer_time);
    System.out.println("Transfer time" + transfer_time[5]);

    // Command to make a product request to the GPS.
    int[] product_request = new int[6];
    product_request[0] = DLE;
    product_request[1] = Pid_Product_Rqst;
    product_request[2] = 0;
    product_request[4] = DLE;
    product_request[5] = ETX;

    calcChecksum(product_request);
    System.out.println("Product request:" + product_request[5]);

    // Command to ask GPS for position data
    int[] transfer_position = new int[8];
    transfer_position[0] = DLE;
    transfer_position[1] = Pid_Command_Packet;
    transfer_position[2] = 2;
    transfer_position[3] = Cmnd_Transfer_Posn;
    transfer_position[4] = 0;
    transfer_position[6] = DLE;
    transfer_position[7] = ETX;

    calcChecksum(transfer_position);

    // Command to ask the GPS to start transmitting PVT data
    int[] start_PVT = new int[8];
    start_PVT[0] = DLE;
    start_PVT[1] = Pid_Command_Packet;
    start_PVT[2] = 2;
    start_PVT[3] = Cmnd_Start_Pvt_Data;
    start_PVT[4] = 0;
    start_PVT[6] = DLE;
    start_PVT[7] = ETX;

    calcChecksum(start_PVT);

    // Acknowledge-packet.
    int[] ack = new int[8];
    ack[0] = DLE;
    ack[1] = Pid_Ack_Byte;
    ack[2] = 2;
    ack[4] = 0;
    ack[6] = DLE;
    ack[7] = ETX;

    SerialPort port;
    BufferedInputStream input;
    BufferedOutputStream output;

    System.out.println("Using COM1.");
    // Open port.
    try {
      port =
          (SerialPort) CommPortIdentifier.getPortIdentifier("COM1").open("dk.itu.haas.GPS", 3000);
    } catch (NoSuchPortException e) {
      System.out.println("No such port!\n" + e.getMessage());
      return;
    } catch (PortInUseException e) {
      System.out.println("Port already in use! (??!)\n" + e.getMessage());
      return;
    }

    try {
      input = new BufferedInputStream(port.getInputStream());
      output = new BufferedOutputStream(port.getOutputStream());
    } catch (IOException e) {
      System.out.println("IOException... ");
      return;
    }

    System.out.println("Sending:");

    printPacket(turn_off);
    sendPacket(output, turn_off);

    /*
    printPacket(transfer_position);
    sendPacket(output, transfer_position);
    */
    /*
    printPacket(start_PVT);
    sendPacket(output, start_PVT);
    */
    /*
    printPacket(product_request);
    sendPacket(output, product_request);
    */
    System.out.println("--");

    int[] packet;
    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
    }

    try {
      while (input.available() > 0) {
        packet = readPacket(input);
        if (packet != null) {
          System.out.println("Received:");
          printPacket(packet);

          // Send acknowledge.
          ack[3] = packet[1];
          calcChecksum(ack);
          sendPacket(output, ack);

          System.out.println("--");
        } else {
          System.out.println("No packet received.");
        }
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
      }
    } catch (IOException e) {
      System.out.println("IOError!");
      return;
    }
  }
Ejemplo n.º 27
0
  /**
   * Opens the communication port.
   *
   * @throws Exception if an error occurs.
   */
  public void open() throws Exception {

    // If this is Linux then first of all we need to check that
    // device file exists. Otherwise call to m_PortIdentifyer.open()
    // method will crash JVM.
    // It is ugly patch but it is too late...
    if (SystemUtils.IS_OS_LINUX) {
      File portDevFile = new File(m_Parameters.getPortName());

      if (!portDevFile.exists()) {
        throw new Exception(
            "Modbus serial device " + m_Parameters.getPortName() + " doesn't exist!");
      }
    }

    // 1. obtain a CommPortIdentifier instance
    try {
      m_PortIdentifyer = CommPortIdentifier.getPortIdentifier(m_Parameters.getPortName());
    } catch (NoSuchPortException e) {
      final String errMsg =
          "Could not get port identifier, maybe insufficient permissions. " + e.getMessage();
      logger.debug(errMsg);
      throw new Exception(errMsg);
    }
    logger.trace("Got Port Identifier");

    // 2. open the port, wait for given timeout
    try {
      m_SerialPort = (SerialPort) m_PortIdentifyer.open("Modbus Serial Master", 30000);
    } catch (PortInUseException e) {
      logger.debug("open port failed: " + e.getMessage());

      throw new Exception(e.getMessage());
    }
    logger.trace("Got Serial Port");

    // 3. set the parameters
    try {
      setConnectionParameters();
    } catch (Exception e) {
      // ensure it is closed
      m_SerialPort.close();
      logger.debug("parameter setup failed: " + e.getMessage());
      throw e;
    }

    if (Modbus.SERIAL_ENCODING_ASCII.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusASCIITransport();
    } else if (Modbus.SERIAL_ENCODING_RTU.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusRTUTransport();
      setReceiveTimeout(m_Parameters.getReceiveTimeout()); // just here for the moment.
    } else if (Modbus.SERIAL_ENCODING_BIN.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusBINTransport();
    }
    m_Transport.setEcho(m_Parameters.isEcho());

    // Open the input and output streams for the connection. If they won't
    // open, close the port before throwing an exception.
    try {
      m_SerialIn = m_SerialPort.getInputStream();
      m_Transport.setCommPort(m_SerialPort);
      //       m_Transport.prepareStreams(m_SerialIn,
      //                                  m_SerialPort.getOutputStream());
    } catch (IOException e) {
      m_SerialPort.close();
      logger.debug(e.getMessage());

      throw new Exception("Error opening i/o streams");
    }
    logger.trace("i/o Streams prepared");

    // Add this object as an event listener for the serial port.
    try {
      m_SerialPort.addEventListener(this);
    } catch (TooManyListenersException e) {
      m_SerialPort.close();
      final String errMsg = "too many listeners added";
      logger.debug("{}: {}", errMsg, e.getMessage());
      throw new Exception(errMsg);
    }

    // Set notifyOnBreakInterrup to allow event driven break handling.
    m_SerialPort.notifyOnBreakInterrupt(true);

    m_Open = true;
  } // open
Ejemplo n.º 28
0
  // open a serial connection to a device.  We won't know it's the robot until
  public int OpenPort(String portName) {
    if (portOpened && portName.equals(recentPort)) return 0;

    ClosePort();

    Log("<font color='green'>Connecting to " + portName + "...</font>\n");

    // find the port
    try {
      portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    } catch (Exception e) {
      Log("<span style='color:red'>Ports could not be identified:" + e.getMessage() + "</span>\n");
      e.printStackTrace();
      return 1;
    }

    if (portIdentifier.isCurrentlyOwned()) {
      Log(
          "<span style='color:red'>Error: Another program is currently using this port."
              + "</span>\n");
      return 2;
    }

    // open the port
    try {
      commPort = portIdentifier.open("DrawbotGUI", 2000);
    } catch (Exception e) {
      Log("Port could not be opened:" + e.getMessage() + NL);
      e.printStackTrace();
      return 3;
    }

    if ((commPort instanceof SerialPort) == false) {
      Log("<span style='color:red'>Only serial ports are handled by this example." + "</span>\n");
      return 4;
    }

    // set the port parameters (like baud rate)
    serialPort = (SerialPort) commPort;
    try {
      serialPort.setSerialPortParams(
          BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    } catch (Exception e) {
      Log("<span style='color:red'>Port could not be configured:" + e.getMessage() + "</span>\n");
      return 5;
    }

    try {
      in = serialPort.getInputStream();
      out = serialPort.getOutputStream();
    } catch (Exception e) {
      Log("<span style='color:red'>Streams could not be opened:" + e.getMessage() + "</span>\n");
      return 6;
    }

    try {
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (TooManyListenersException e) {
      Log("<span style='color:red'>Streams could not be opened:" + e.getMessage() + "</span>\n");
      return 7;
    }

    Log("<span style='green'>Opened.</span>\n");
    SetRecentPort(portName);
    portOpened = true;
    UpdateMenuBar();

    return 0;
  }