コード例 #1
1
  public void DownloadBinaryViaSerial(){
		// TODO Auto-generated method stub
		//System.out.println("Download running...");
		byte[] buff = new byte[2048];
		
		int size;
		
		
		try {
			binaryInput = new DataInputStream(new FileInputStream(binaryPathFromSketch));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			System.out.println("File not found : "+binaryPathFromSketch);
			e1.printStackTrace();
		}
		
		//System.out.println("Start uploading");
		try {
			while((size = binaryInput.read(buff)) > -1){
				output.write(buff, 0, size);
				
				//fileSize += size;
				/*for(int i=0 ; i < size ; i++){
					checkSumByte += buff[i];
				}*/
			
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			binaryInput.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	   /* File file = new File(binaryPathFromSketch);
	    System.out.println("[ROBOTIS]binary size : "+file.length()+"Bytes");*/
		checkSumByte = ArmCompiler.getChecksumOfBinary(); //[ROBOTIS]2012-12-19 change method to calculate checksum for mac OS x
		String outTemp = String.format("0x%x", checkSumByte);
		//System.out.println("Checksum : "+outTemp);
		//SerialWrite(checkSumByte);
		port.setDTR(true);
		write(checkSumByte);
		
		try {
			binaryInput.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  }
コード例 #2
0
 public void wakeupRobot() {
   synchronized (this) {
     serialPort.setRTS(false);
     serialPort.setDTR(false);
   }
   try {
     Thread.sleep(500);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   synchronized (this) {
     serialPort.setRTS(true);
     serialPort.setDTR(true);
   }
 }
コード例 #3
0
ファイル: LocoBufferUsbAdapter.java プロジェクト: KenC57/JMRI
  /** Always use flow control, not considered a user-setable option */
  protected void setSerialPort(SerialPort activeSerialPort)
      throws gnu.io.UnsupportedCommOperationException {
    // find the baud rate value, configure comm options
    int baud = 19200; // default, but also defaulted in the initial value of selectedSpeed
    for (int i = 0; i < validBaudNumber().length; i++) {
      if (validBaudRates()[i].equals(mBaudRate)) {
        baud = validBaudNumber()[i];
      }
    }
    activeSerialPort.setSerialPortParams(
        baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

    // set RTS high, DTR high - done early, so flow control can be configured after
    activeSerialPort.setRTS(true); // not connected in some serial ports and adapters
    activeSerialPort.setDTR(true); // pin 1 in Mac DIN8; on main connector, this is DTR

    // configure flow control to always on
    int flow = SerialPort.FLOWCONTROL_RTSCTS_OUT;
    activeSerialPort.setFlowControlMode(flow);
    log.debug(
        "Found flow control "
            + activeSerialPort.getFlowControlMode()
            + " RTSCTS_OUT="
            + SerialPort.FLOWCONTROL_RTSCTS_OUT
            + " RTSCTS_IN= "
            + SerialPort.FLOWCONTROL_RTSCTS_IN);
  }
コード例 #4
0
ファイル: SerialDriverAdapter.java プロジェクト: KenC57/JMRI
  public String openPort(String portName, String appName) {
    // open the port, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        return handlePortBusy(p, portName, log);
      }

      // try to set it for communication via SerialDriver
      try {
        activeSerialPort.setSerialPortParams(
            9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set RTS high, DTR high
      activeSerialPort.setRTS(true); // not connected in some serial ports and adapters
      activeSerialPort.setDTR(true); // pin 1 in DIN8; on main connector, this is DTR

      // disable flow control; hardware lines used for signaling, XON/XOFF might appear in data
      activeSerialPort.setFlowControlMode(0);
      activeSerialPort.enableReceiveTimeout(50); // 50 mSec timeout before sending chars

      // set timeout
      // activeSerialPort.enableReceiveTimeout(1000);
      log.debug(
          "Serial timeout was observed as: "
              + activeSerialPort.getReceiveTimeout()
              + " "
              + activeSerialPort.isReceiveTimeoutEnabled());

      // get and save stream
      serialStream = activeSerialPort.getInputStream();

      // purge contents, if any
      purgeStream(serialStream);

      // report status
      if (log.isInfoEnabled()) {
        log.info(
            "Wangrow " + portName + " port opened at " + activeSerialPort.getBaudRate() + " baud");
      }
      opened = true;

    } catch (gnu.io.NoSuchPortException p) {
      return handlePortNotFound(p, portName, log);
    } catch (Exception ex) {
      log.error("Unexpected exception while opening port " + portName + " trace follows: " + ex);
      ex.printStackTrace();
      return "Unexpected error while opening port " + portName + ": " + ex;
    }

    return null; // indicates OK return
  }
コード例 #5
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);
  }
コード例 #6
0
  /**
   * 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);
  }
コード例 #7
0
  @SuppressWarnings("unchecked")
  public SerialTransmitController(String port, String rts_or_dtr) throws Exception {
    CommPortIdentifier pi = null;
    try {
      pi = CommPortIdentifier.getPortIdentifier(port);
    } catch (NoSuchPortException nspe) {
      String port_names = "";
      boolean comma = false;
      Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
      while (ports.hasMoreElements()) {
        CommPortIdentifier portIdentifier = ports.nextElement();
        if (comma) port_names += ",";
        port_names += portIdentifier.getName();
        comma = true;
      }
      throw new IOException(
          String.format("Port %s is not valid (valid ports are %s)", port, port_names));
    }
    CommPort ptt_comm_port = null;
    try {
      ptt_comm_port = pi.open(this.getClass().getName(), 1000);
    } catch (PortInUseException piue) {
      throw new IOException(String.format("Port %s is in use", port));
    }
    if (ptt_comm_port instanceof SerialPort) {
      ptt_serial_port = (SerialPort) ptt_comm_port;
      // serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,
      //		                           SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
    } else {
      System.err.println("5");
      throw new IOException(String.format("Port %s is not a serial port", port));
    }

    ptt_serial_port.setRTS(false);
    ptt_serial_port.setDTR(false);

    System.err.println("Opened a PTT port: " + port);

    if (rts_or_dtr.equalsIgnoreCase("RTS")) {
      rts = true;
      return;
    }
    if (rts_or_dtr.equalsIgnoreCase("DTR")) {
      dtr = true;
      return;
    }

    throw new IOException(String.format("Signal %s is not valid (must be RTS or DTR)", rts_or_dtr));
  }
コード例 #8
0
 public void setDTR(boolean state) {
   port.setDTR(state);
 }
コード例 #9
0
  public synchronized String openPort(String portName, String appName) {
    // open the port, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        handlePortBusy(p, portName);
        return "Port " + p + " in use already";
      }

      // try to set it for communication via SerialDriver
      try {
        // Doc says 7 bits, but 8 seems needed
        activeSerialPort.setSerialPortParams(
            38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set RTS high, DTR high
      activeSerialPort.setRTS(true); // not connected in some serial ports and adapters
      activeSerialPort.setDTR(true); // pin 1 in DIN8; on main connector, this is DTR

      // disable flow control; hardware lines used for signaling, XON/XOFF might appear in data
      activeSerialPort.setFlowControlMode(0);

      // set timeout
      log.debug(
          "Serial timeout was observed as: "
              + activeSerialPort.getReceiveTimeout()
              + " "
              + activeSerialPort.isReceiveTimeoutEnabled());

      // get and save stream
      serialStream = new DataInputStream(activeSerialPort.getInputStream());
      ostream = activeSerialPort.getOutputStream();

      // make less verbose
      sendBytes(new byte[] {(byte) 'L', (byte) '-', 10, 13});
      // purge contents, if any
      int count = serialStream.available();
      log.debug("input stream shows " + count + " bytes available");
      while (count > 0) {
        serialStream.skip(count);
        count = serialStream.available();
      }

      // report status?
      if (log.isInfoEnabled()) {
        log.info(
            portName
                + " port opened at "
                + activeSerialPort.getBaudRate()
                + " baud, sees "
                + " DTR: "
                + activeSerialPort.isDTR()
                + " RTS: "
                + activeSerialPort.isRTS()
                + " DSR: "
                + activeSerialPort.isDSR()
                + " CTS: "
                + activeSerialPort.isCTS()
                + "  CD: "
                + activeSerialPort.isCD());
      }

    } catch (java.io.IOException ex) {
      log.error("IO error while opening port " + portName, ex);
      return "IO error while opening port " + portName + ": " + ex;
    } catch (gnu.io.UnsupportedCommOperationException ex) {
      log.error("Unsupported communications operation while opening port " + portName, ex);
      return "Unsupported communications operation while opening port " + portName + ": " + ex;
    } catch (gnu.io.NoSuchPortException ex) {
      log.error("No such port: " + portName, ex);
      return "No such port: " + portName + ": " + ex;
    }
    return null; // indicates OK return
  }
コード例 #10
0
 @Override
 public void stopTransmitter() {
   if (rts) ptt_serial_port.setRTS(false);
   if (dtr) ptt_serial_port.setDTR(false);
 }
コード例 #11
0
 @Override
 public void startTransmitter() {
   if (rts) ptt_serial_port.setRTS(true);
   if (dtr) ptt_serial_port.setDTR(true);
 }
コード例 #12
0
ファイル: DSMRPort.java プロジェクト: RWESmart/openhab
  /**
   * Opens the Operation System Serial Port
   *
   * <p>This method opens the port and set Serial Port parameters according to the DSMR
   * specification. Since the specification is clear about these parameters there are not
   * configurable.
   *
   * <p>If there are problem while opening the port, it is the responsibility of the calling method
   * to handle this situation (and for example close the port again).
   *
   * <p>Opening an already open port is harmless. The method will return immediately
   *
   * @return true if opening was successful (or port was already open), false otherwise
   */
  private boolean open() {
    synchronized (portLock) {
      // Sanity check
      if (portState != PortState.CLOSED) {
        return true;
      }

      try {
        // Opening Operating System Serial Port
        logger.debug("Creating CommPortIdentifier");
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        logger.debug("Opening CommPortIdentifier");
        CommPort commPort = portIdentifier.open("org.openhab.binding.dsmr", readTimeoutMSec);
        logger.debug("Configure serial port");
        serialPort = (SerialPort) commPort;
        serialPort.enableReceiveThreshold(1);
        serialPort.enableReceiveTimeout(readTimeoutMSec);

        // Configure Serial Port based on specified port speed
        logger.debug("Configure serial port speed " + portSpeed);
        switch (portSpeed) {
          case LOW_SPEED:
            serialPort.setSerialPortParams(
                9600, SerialPort.DATABITS_7, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
            serialPort.setDTR(false);
            serialPort.setRTS(true);

            break;
          case HIGH_SPEED:
            serialPort.setSerialPortParams(
                115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            break;
          default:
            logger.error("Invalid speed, closing port");

            return false;
        }
      } catch (NoSuchPortException nspe) {
        logger.error("Could not open port: " + portName, nspe);

        return false;
      } catch (PortInUseException piue) {
        logger.error("Port already in use: " + portName, piue);

        return false;
      } catch (UnsupportedCommOperationException ucoe) {
        logger.error("Port is not suitable: " + portName, ucoe);

        return false;
      }

      // SerialPort is ready, open the reader
      logger.info("SerialPort opened successful");
      try {
        bis = new BufferedInputStream(serialPort.getInputStream());
      } catch (IOException ioe) {
        logger.error("Failed to get inputstream for serialPort. Closing port", ioe);

        return false;
      }
      logger.info("DSMR Port opened successful");

      return true;
    }
  }