コード例 #1
0
  /** {@inheritDoc} */
  public String RPC(String Name, String Method, String[] Args) {
    // write to serial port and receive result
    String Response;
    String Arguments = "";
    if (Args != null) {
      int s = Args.length;
      for (int i = 0; i < s; i++) {
        Arguments = Arguments + " " + Args[i];
      }
    }
    try {
      to_mbed.println("/" + Name + "/" + Method + Arguments);
      mbedSerialPort.notifyOnDataAvailable(false);
    } catch (NullPointerException e) {

    }
    boolean valid = true;
    try {
      while (reader.ready() == false) {}
      ;
      do {
        Response = reader.readLine();

        if (Response.length() >= 1) {
          valid = Response.charAt(0) != '!';
        }
      } while (valid == false);
    } catch (IOException e) {
      System.err.println("IOException, error reading from port");
      Response = "error";
    }

    mbedSerialPort.notifyOnDataAvailable(true);
    return (Response);
  }
コード例 #2
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");
    }
  }
コード例 #3
0
  public SimpleRead() {
    try {
      /*
       * open方法打开通讯端口
       * ,
       * 获得一个CommPort对象
       * 。
       * 它使程序独占端口
       * 。
       * 如果端口正被其他应用程序占用
       * ,将使用
       * CommPortOwnershipListener事件机制
       * ,
       * 传递一个PORT_OWNERSHIP_REQUESTED事件
       * 。
       * 每个端口都关联一个
       * InputStream
       * 何一个OutputStream
       * 。
       * 如果端口是用open方法打开的
       * ,
       * 那么任何的getInputStream都将返回相同的数据流对象
       * ,
       * 除非有close
       * 被调用
       * 。有两个参数
       * ,
       * 第一个为应用程序名
       * ;
       * 第二个参数是在端口打开时阻塞等待的毫秒数
       * 。
       */
      serialPort = (SerialPort) portId.open("packinglinesmanage", 2000);
    } catch (PortInUseException e) {
    }
    try {
      inputStream = serialPort.getInputStream(); /* 获取端口的输入流对象 */
    } catch (IOException e) {
    }
    try {
      serialPort.addEventListener(this); /* 注册一个SerialPortEventListener事件来监听串口事件 */
    } catch (TooManyListenersException e) {
    }

    serialPort.notifyOnDataAvailable(true); /* 数据可用 */

    try {
      serialPort.setSerialPortParams(
          9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); /*
																	 * 设置串口初始化参数,
																	 * 依次是波特率
																	 * ,数据位
																	 * ,停止位和校验
																	 */
    } catch (UnsupportedCommOperationException e) {
    }

    readThread = new Thread(this);
    readThread.start();
  }
コード例 #4
0
ファイル: Rs232Connector.java プロジェクト: remiguitreau/ojt
  @Override
  public void open() {
    // r�cup�ration de l'identifiant du port
    try {
      logger.info("Liste des ports : " + CommPortIdentifier.getPortIdentifiers());
      final Enumeration identifiers = CommPortIdentifier.getPortIdentifiers();
      while (identifiers.hasMoreElements()) {
        logger.info(((CommPortIdentifier) identifiers.nextElement()).getName());
      }
      portId = CommPortIdentifier.getPortIdentifier(connectionDescriptor.getPortName());
    } catch (final NoSuchPortException e) {
      throw new RuntimeException(
          "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString());
    }

    // ouverture du port
    try {
      serialPort = (SerialPort) portId.open("driver", 2000);
    } catch (final PortInUseException e) {
      throw new RuntimeException(
          "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString());
    }

    // param�trage du port
    // hmmmmmmmmmmmm cf :
    // http://forum.java.sun.com/thread.jspa?threadID=673793&start=15&tstart=0
    boolean result = false;
    while (!result) {
      try {
        serialPort.setSerialPortParams(
            connectionDescriptor.getBaudRate(),
            connectionDescriptor.getDataBits(),
            connectionDescriptor.getStopBits(),
            connectionDescriptor.getParity());
        result = true;
      } catch (final Exception ex) {
        logger.error("Unable to set serial ports parameters", ex);
        result = false;
        try {
          Thread.sleep(200);
        } catch (final InterruptedException exc) {
          logger.error("Error while sleeping", exc);
        }
      }
    }
    /** @todo : test */
    // Suppression
    try {
      serialPort.enableReceiveTimeout(5000); // timeout de 1 ms
    } catch (final UnsupportedCommOperationException ex) {
      logger.warn(
          "Warning : impossible to set timeout for port " + connectionDescriptor.getPortName(), ex);
    }

    try {
      // inputStream = new BufferedReader(new
      // InputStreamReader(serialPort.getInputStream()));
      inputStream = serialPort.getInputStream();
    } catch (final IOException e) {
      serialPort.close();
      throw new RuntimeException(
          "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString());
    }

    try {
      serialPort.addEventListener(
          new SerialPortEventListener() {

            @Override
            public void serialEvent(final SerialPortEvent evt) {
              if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                synchronized (bufferMonitor) {
                  if (writeIndex >= BUFFER_LENGTH - 1) {
                    flushBuffer();
                  }
                  try {
                    byte newData = 0;
                    while (newData != -1) {
                      newData = (byte) inputStream.read();
                      if (newData == -1) {
                        break;
                      }
                      if (writeIndex >= BUFFER_LENGTH - 1) {
                        flushBuffer();
                      }
                      buffer[writeIndex++] = newData;
                    }
                  } catch (final Exception exc) {
                    logger.error("Error reading input stream from serial port", exc);
                  }
                  bufferMonitor.notify();
                }
              }
            }
          });
      serialPort.notifyOnDataAvailable(true);
      serialPort.enableReceiveTimeout(20);

    } catch (final TooManyListenersException exc) {
      logger.error("", exc);
    } catch (final UnsupportedCommOperationException exc) {
      logger.error("", exc);
    }

    final Thread threadParse =
        new Thread("Rs232Connector_" + connectionDescriptor.getPortName() + "_dispatch_thread") {
          @Override
          public void run() {
            try {
              parseThread();
            } catch (final Exception e) {
              logger.error("Error while parsing thread", e);
            }
          }
        };
    threadParse.start();
  }
コード例 #5
0
ファイル: Khepera.java プロジェクト: pi19404/micropsi
  private void initialize() {

    // ==========================================
    /*
     * get System porperties:
     */
    String operatingSystem = null;
    Properties p = System.getProperties();
    Enumeration e = p.elements();
    while (e.hasMoreElements()) {
      operatingSystem = e.nextElement().toString();
      //				System.out.println(operatingSystem);
      if (operatingSystem.equals("Linux")) {
        logger.debug("found " + operatingSystem + " Operating System");
        comPort = "/dev/ttyS0";
        break;
      }
      if (operatingSystem.equals("Windows XP")) {
        logger.debug("found " + operatingSystem + " Operating System");
        comPort = "COM1";
        break;
      }

      //				if(operatingSystem.equals("Linux") || operatingSystem.equals("Windows")) {
      //					logger.debug("found "+operatingSystem+" Operating System");
      //					break;
      //				}
    }
    //	===============end===========================

    Enumeration pList = CommPortIdentifier.getPortIdentifiers();
    //		logger.debug("(Khepera) initializeeeee()...");

    while (pList.hasMoreElements()) {
      CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();

      if (cpi.getName().equals(comPort)) {
        try {
          com = null;
          com = (SerialPort) cpi.open("KHEPERA_" + comPort, 1000);
          try {

            //	========================================
            /* under Linux this block is crucial to setSerialPortParams()
             * - i have no idea why...
             */
            String s =
                "default settings: "
                    + com.getBaudRate()
                    + " "
                    + com.getDataBits()
                    + " "
                    + com.getParity()
                    + " "
                    + com.getStopBits();
            System.out.println(s);
            //	===============end=========================

            com.setSerialPortParams(
                57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
            System.out.println(
                "Current settings: "
                    + com.getBaudRate()
                    + " "
                    + com.getDataBits()
                    + " "
                    + com.getParity()
                    + " "
                    + com.getStopBits());
          } catch (UnsupportedCommOperationException e1) {
            logger.debug("(Khepera) UnsupportedCommOperation: " + e1);
            e1.printStackTrace();
          }
          //					try {
          //						com.setSerialPortParams(BAUDRATE,
          //								com.DATABITS_8,
          //								com.STOPBITS_2,
          //								com.PARITY_NONE);
          //						com.setFlowControlMode(com.FLOWCONTROL_NONE);
          //					} catch (UnsupportedCommOperationException e1) {
          //						logger.debug("(Khepera) UnsupportedCommOperation: "+e1);
          //						e1.printStackTrace();
          //					}
          logger.debug("[Khepera.initialize()] established " + comPort);

          out = null;
          out = com.getOutputStream();
          inStream = null;
          inStream = com.getInputStream();

          byte[] readBuffer2 = new byte[1000];
          if (inStream.available() > 0) {
            int numBytes2 = inStream.read(readBuffer2);
            String result2 = new String(readBuffer2, 0, numBytes2);
            logger.debug("result2: " + result2);
          }

          //					in = null;
          in = new BufferedReader(new InputStreamReader(inStream));

          bufferedKheperaAnswer =
              new BufferedKheperaAnswer(logger, inStream, this, writelock, debug, operatingSystem);
          try {
            com.addEventListener(bufferedKheperaAnswer);

            com.notifyOnOutputEmpty(true);
            com.notifyOnDataAvailable(true);
            com.notifyOnOverrunError(true);
            com.notifyOnBreakInterrupt(true);
            com.notifyOnCarrierDetect(true);
            com.notifyOnCTS(true);
            com.notifyOnDSR(true);
            com.notifyOnFramingError(true);
            com.notifyOnParityError(true);
            com.notifyOnRingIndicator(false);
          } catch (TooManyListenersException e1) {
            logger.debug(
                "[Khepera.initialize()] can not add further eventListeners to serialPort object"
                    + e);
            e1.printStackTrace();
          }
        } catch (PortInUseException e2) {
          logger.debug("[Khepera.initialize()] Port in use: " + e2);
          e2.printStackTrace();
        } catch (IOException e3) {
          logger.debug(
              "[Khepera.initialize()] IOException while initialising COMport: <"
                  + comPort
                  + ">"
                  + e);
          e3.printStackTrace();
        }
        break;
      }
    }
    if (com == null)
      logger.error(
          "[Khepera.initialize()] unable to find specified COMport "
              + comPort
              + ". giving up! (the robot is not connected yet.)");
    else {
      logger.debug("[Khepera.initialize()] starting bufferedKheperaAnswer.start()");
      bufferedKheperaAnswer.start();

      if (debug) logger.debug("[Khepera.initialize()] initialize() finished");

      update = new KheperaUpdateManager(this, logger, debug);
      logger.debug("[Khepera.initialize()] starting KheperaUpdateManager update.start()");
      update.start();
    }
  }