Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
0
  /** @see com.svhelloworld.knotlog.engine.sources.StreamedSource#open() */
  @Override
  public InputStream open() {
    try {
      // make sure the specified port is available
      CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(config.getName());
      if (identifier.isCurrentlyOwned()) {
        throw new SerialPortOccupiedException(
            config.getName() + " port is currently opened by another application");
      }
      // open up the port
      CommPort port = identifier.open(getOwnerName(), PORT_TIMEOUT);
      if (port instanceof SerialPort) {

        // configure serial port
        serialPort = (SerialPort) port;
        serialPort.setSerialPortParams(
            config.getBaudRate(),
            config.getDataBits().getRXTXConstant(),
            config.getStopBit().getRXTXConstant(),
            config.getParity().getRXTXConstant());
        /*
         * the following 2 lines fix the exception:
         *       "IOException: Underlying input stream returned zero bytes"
         *       that is thrown when we read from the InputStream.
         */
        serialPort.enableReceiveTimeout(PORT_TIMEOUT);
        serialPort.enableReceiveThreshold(0);

        InputStream is = serialPort.getInputStream();
        return is;
      }
      // not a serial port
      throw new SerialPortException("must operate against a serial port");
    } catch (PortInUseException e) {
      throw new SerialPortOccupiedException(e.getMessage(), e);
    } catch (Exception e) {
      throw new SerialPortException(e.getMessage(), e);
    }
  }
Ejemplo n.º 6
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.");
    }
  }
  /** 通过串口向单片机写入数据 */
  public boolean portWrite() {
    boolean notFinished = true;
    try {
      // get port ID
      CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(this.portName);

      // open port(port holder, timeout),打开端口(串口所有者,超时等待时间:ms)
      try {
        this.sPort = (SerialPort) portId.open("可爱的皮卡丘", this.timeout);

        // set port(BaudRate,Databits,Stopbits,Parity),设置串口(波特率,数据位,停止位,校验位)
        try {
          this.sPort.setSerialPortParams(
              9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
          e.printStackTrace();
        }

        // 写入数据
        OutputStream OS = null;
        try {
          OS = new BufferedOutputStream(sPort.getOutputStream());
        } catch (IOException e) {
          e.printStackTrace();
        }
        // 选择操作
        System.out.println("选择一下操作: 静止按1; 前进按2; 后退按3; 结束操作按4.");
        int command = s.nextInt();

        switch (command) {
          case 1:
            try {
              OS.write(this.stop);
            } catch (IOException e) {
              e.printStackTrace();
            }
            break;
          case 2:
            try {
              OS.write(this.forward);
            } catch (IOException e) {
              e.printStackTrace();
            }
            break;
          case 3:
            try {
              OS.write(this.backward);
            } catch (IOException e) {
              e.printStackTrace();
            }
            break;
          case 4:
            notFinished = false;
            break;
        }

        try {
          OS.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        this.sPort.close();

      } catch (PortInUseException e) {
        e.printStackTrace();
      }
    } catch (NoSuchPortException e) {
      e.printStackTrace();
    }
    return notFinished;
  }
Ejemplo n.º 8
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