示例#1
0
  public void open() throws IOException {
    try {
      if (portName != null) {
        portId = CommPortIdentifier.getPortIdentifier(portName);
      }
      if (portId == null) {
        throw new IOException("Invalid port " + portName);
      }
      serialPort = (SerialPort) portId.open(portId.getName(), baudRate);
      if (portId == null) {
        throw new IOException("Invalid port " + portName);
      }

      serialPort.setSerialPortParams(
          baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      serialPort.notifyOnOutputEmpty(true);
      outputStream = serialPort.getOutputStream();
      inputStream = serialPort.getInputStream();
      Logger.getLogger(SerialDevice.class.getName())
          .log(Level.INFO, "Connection Stabilished with {0}", serialPort.getName());
    } catch (Exception e) {
      e.printStackTrace();
      Logger.getLogger(SerialDevice.class.getName())
          .log(Level.SEVERE, "Could not init the device on " + serialPort.getName(), e);
      serialPort.close();
    }
  }
示例#2
0
  public void write(final String pMessageString) {
    System.out.println("\n>>> \"" + pMessageString + "\" to " + serialPort.getName());

    try {
      out.write(pMessageString.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Pulses the DTR on the given serial port.
   *
   * @param serialPort The port on which to pulse the DTR.
   * @throws IOException If an IO error occurs during the pulse.
   */
  private final void pulseDTR(final SerialPort serialPort) throws IOException {
    if (logger.isLoggable(Level.INFO)) {
      logger.log(Level.INFO, "Pulsing the DTR on serial port [" + serialPort.getName() + "]");
    }

    serialPort.setDTR(true);

    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
      // Eat.
      if (logger.isLoggable(Level.WARNING)) {
        logger.log(
            Level.WARNING,
            "Was interrupted while pulsing the DTR of port [" + serialPort.getName() + "]",
            e);
      }
    }

    serialPort.setDTR(false);
  }
示例#4
0
 // disconnect the serial port
 // pre: an open serial port
 // post: clsoed serial port
 public void disconnect() {
   // close the serial port
   try {
     //            writeData(0, 0);
     serialPort.removeEventListener();
     serialPort.close();
     input.close();
     output.close();
     setConnected(false);
     logText = "Disconnected.";
     System.out.println(logText + "\n");
   } catch (Exception e) {
     logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")";
     System.out.println(logText + "\n");
   }
 }
示例#5
0
 @Override
 public void close() throws IOException {
   Logger.getLogger(SerialDevice.class.getName())
       .log(Level.INFO, "Closing device on {0}", serialPort.getName());
   // send("X");
   connected = false;
   try {
     inputStream.close();
   } catch (Exception e) {
   }
   try {
     outputStream.close();
   } catch (Exception e) {
   }
   try {
     if (serialPort != null) {
       serialPort.close();
     }
   } catch (Exception e) {
   }
 }
  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 serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(
            57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        InputStream in = serialPort.getInputStream();
        out = serialPort.getOutputStream();

        (new Thread(new SerialReader(in))).start();
        // (new Thread(new SerialWriter(out))).start();
        // new SerialWriter(out).run();
        System.out.println("CommPort : " + serialPort.getName() + " is open");
      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
  }
示例#7
0
  /**
   * python example def transmit_to_widget(label, data, data_size): ser.write(chr(SOM_VALUE))
   * ser.write(chr(label)) ser.write(chr(data_size & 0xFF)) // lsb ser.write(chr((data_size >> 8) &
   * 0xFF)) // msb for j in range(data_size): ser.write(data[j]) ser.write(chr(EOM_VALUE))
   */
  private void write() {

    char som = 0x7E;
    char eom = 0xE7;
    char label = 6; // 10 serial , 6 send

    Integer[] chan = getChannelData();

    int data_size = chan.length;

    char clsb = (char) (data_size & 0xFF);
    char cmsb = (char) ((data_size >> 8) & 0xFF);

    byte lsb = (byte) clsb;
    byte msb = (byte) cmsb;

    ArrayList<Byte> ab = new ArrayList<Byte>();
    ab.add((byte) som); // start delimter
    ab.add((byte) label); // label - whats happening
    ab.add(lsb); // start byte
    ab.add(msb); // mast
    for (int i = 0; i < data_size; i++) {
      ab.add(chan[i].byteValue());
    }
    ab.add((byte) eom);

    // Byte[] messageString = new Byte[ab.size()];
    // messageString = ab.toArray(messageString);
    byte[] messageString = new byte[ab.size()];
    for (int i = 0; i < ab.size(); i++) {
      messageString[i] = ab.get(i);
    }

    // debug in hex
    debugBytes(messageString);

    boolean portFound = false;
    String defaultPort = "/dev/ttyUSB0";

    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();

      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

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

          portFound = true;

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

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

          try {
            serialPort.setSerialPortParams(
                57600, 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());
            e.printStackTrace();
            System.exit(-1);
          }

          System.out.println("Writing \"" + messageString + "\" to " + serialPort.getName());

          try {
            outputStream.write(messageString);
          } catch (IOException e) {
            e.printStackTrace();
          }

          try {
            Thread.sleep(2000); // Be sure data is xferred before closing
          } catch (Exception e) {
            e.printStackTrace();
          }
          serialPort.close();
          System.exit(1);
        }
      }
    }

    if (!portFound) {
      System.out.println("port " + defaultPort + " not found.");
    }
  }