Exemple #1
0
 private synchronized void closeSerialPort() {
   if (serialPort != null) {
     serialPort.removeEventListener();
     serialPort.close();
     serialPort = null;
   }
 }
Exemple #2
0
  /**
   * End call.
   *
   * @throws Exception the exception
   */
  private void endCall() throws Exception {
    this.incomingCall = false;
    if (serialVoiceReader != null) {
      serialVoiceReader.terminate();
      serialVoiceReader = null;
    }
    if (serialVoiceWriter != null) {
      serialVoiceWriter.terminate();
      serialVoiceWriter = null;
    }
    if (voiceInputStream != null) {
      voiceInputStream.close();
    }
    if (voiceOutputStream != null) {
      voiceOutputStream.close();
    }
    if (voiceStreamCommPort != null) {
      voiceStreamCommPort.notifyOnDataAvailable(false);
      voiceStreamCommPort.removeEventListener();
      voiceStreamCommPort.close();
      voiceStreamCommPort = null;
    }
    // Thread jsed = Utils.getThread("Java Sound Event Dispatcher");

  }
Exemple #3
0
  /** Establish the connection with the device connected to the serial port. */
  public void setupSerialPort() {

    try {

      // If port already open, close it.
      if (serialPort != null) {
        serialPort.close();
        serialPort = null;
      }

      // Initialize serial port attributes.
      log.info("Fetching communication port {}", getTanitaCommPort());
      CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort());

      log.info("Opening communication port {}", getTanitaCommPort());
      serialPort = (SerialPort) wPortId.open(portOwnerName, 2000);

      // Make sure the port is "Clear To Send"
      serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity);
      bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

      portIsAvailable = checkIfPortIsAvailable();

    } catch (Exception wCouldNotAccessSerialPort) {
      portIsAvailable = false;
      log.warn("Could not access the specified serial port.");
    }
  }
  public static boolean checkPort(){
	  SerialPort testPort = null;
	  String iname = Preferences.get("serial.port");
	  if(iname == null)
		  return false;
	  Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId =
          (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
         // System.out.println("found " + portId.getName());
          if (portId.getName().equals(iname)) {
        	  try {
				 testPort = (SerialPort)portId.open("serial madness", 2000);
			} catch (PortInUseException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.println("[Serial]Port is already in use, press reset button!");
				//testPort.close();
				return false;
				
			}
        	 // System.out.println("[SERIAL]port is ok!");
        	  testPort.close();
        	  return true;
          }
        }
      }
      //System.out.println("[SERIAL]port is not ok!");
    //testPort.close();
	return false;
	  
  }
  public static boolean touchPort(String iname, int irate) throws SerialException {
    SerialPort port;
    boolean result = false;
    try {
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if ((CommPortIdentifier.PORT_SERIAL == portId.getPortType()) && (portId.getName().equals(iname))) {
          port = (SerialPort) portId.open("tap", 2000);
          port.setSerialPortParams(irate, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          port.close();				
          result = true;
        }
      }
    } catch (PortInUseException e) {
      throw new SerialException(
        I18n.format(_("Serial port ''{0}'' already in use. Try quitting any programs that may be using it."), iname)
      );
    } catch (Exception e) {
      throw new SerialException(
        I18n.format(_("Error touching serial port ''{0}''."), iname), e
      );
    }
	return result;
  }
  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();
    }
  }
 public void disconnect() throws Exception {
   if (is != null) is.close();
   if (os != null) os.close();
   if (serialPort != null) {
     serialPort.removeEventListener();
     serialPort.close();
   }
 }
 public void schliesseSerialPort() {
   if (serialPortGeoeffnet == true) {
     System.out.println("Schließe Serialport");
     serialPort.close();
     serialPortGeoeffnet = false;
   } else {
     System.out.println("Serialport bereits geschlossen");
   }
 }
Exemple #9
0
 public void shutdown() {
   shutdown = true;
   if (serialPort != null) {
     try {
       log.info("Closing serial port");
       serialPort.close();
     } catch (Exception e) {
       // ignore
       log.info("Error Closing serial port");
     }
   }
 }
 public synchronized void close() {
   try {
     in.close();
     output.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   if (serialPort != null) {
     serialPort.removeEventListener();
     serialPort.close();
   }
 }
 private void init(
     SerialPort serialPort, SerialParameters serialParams, SerialTestResultsDisplay results)
     throws SerialConnectionException {
   _parameters = serialParams;
   _sPort = serialPort;
   _results = results;
   _sendThread = new Thread(this);
   _chunkSize = 4096;
   _savedStream = new ByteArrayOutputStream();
   try {
     _os = _sPort.getOutputStream();
   } catch (IOException e) {
     _sPort.close();
     throw new SerialConnectionException("Error opening i/o streams");
   }
 }
Exemple #12
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");
   }
 }
  @Override
  public void close() {
    try {

      serialPort.close();
      input.close();
      output.close();

      deviceTx.add(POISON_PILL);

    } catch (IOException e) {
      e.printStackTrace();
    }

    status = CLOSED;
  }
  public synchronized void dispose() {
    // stop operations here. This is a deprecated method, but OK for us.
    if (readerThread != null) {
      stopThread(readerThread);
    }

    // release port
    if (activeSerialPort != null) {
      activeSerialPort.close();
    }
    serialStream = null;
    ostream = null;
    activeSerialPort = null;
    portNameVector = null;

    // and clean up parent
    super.dispose();
  }
Exemple #15
0
 /** Terminate. */
 public void terminate() {
   try {
     endCall();
     if (commandOutputStream != null) {
       commandOutputStream.close();
     }
     if (commandInputStream != null) {
       commandInputStream.close();
     }
     if (modemComPort != null) {
       modemComPort.notifyOnDataAvailable(false);
       modemComPort.removeEventListener();
       modemComPort.close();
       modemComPort = null;
     }
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
   }
 }
Exemple #16
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) {
   }
 }
  public void dispose() {
    try {
      // do io streams need to be closed first?
      if (input != null) input.close();
      if (output != null) output.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    input = null;
    output = null;

    try {
      if (port != null) port.close();  // close the port

      //System.out.println("[Serial]port is closed!");
    } catch (Exception e) {
      e.printStackTrace();
    }
    port = null;
  }
 /*
  * Code cribbed from RXTX example
  */
 public static void closePort(SerialPort serialPort) {
   if (serialPort != null) {
     serialPort.notifyOnDataAvailable(false);
     serialPort.removeEventListener();
     if (inputStream != null) {
       try {
         inputStream.close();
         inputStream = null;
       } catch (IOException e) {
       }
     }
     if (outputStream != null) {
       try {
         outputStream.close();
         outputStream = null;
       } catch (IOException e) {
       }
     }
     serialPort.close();
     serialPort = null;
   }
 }
Exemple #19
0
  public void ClosePort() {
    if (portOpened) {
      if (serialPort != null) {
        try {
          // Close the I/O streams.
          out.close();
          in.close();
          // Close the port.
          serialPort.removeEventListener();
          serialPort.close();
        } catch (IOException e) {
          // Don't care
        }
      }

      ClearLog();
      portOpened = false;
      portConfirmed = false;
      previewPane.setConnected(false);
      UpdateMenuBar();
    }
  }
Exemple #20
0
  /** Closes the DSMRPort and release OS resources */
  public void close() {
    synchronized (portLock) {
      logger.info("Closing DSMR port");

      portState = PortState.CLOSED;

      // Close resources
      if (bis != null) {
        try {
          bis.close();
        } catch (IOException ioe) {
          logger.debug("Failed to close reader", ioe);
        }
      }
      if (serialPort != null) {
        serialPort.close();
      }

      // Release resources
      bis = null;
      serialPort = null;
    }
  }
  /** {@inheritDoc} */
  @Override
  public final void upgradeNode(final String portName, final String hexFileLocation)
      throws IOException {
    if (portName == null) {
      throw new IllegalArgumentException("Port cannot be null here !");
    }

    if (hexFileLocation == null) {
      throw new IllegalArgumentException("Hex file location cannot be null here !");
    }

    final File hexFile = new File(hexFileLocation);

    if (!hexFile.exists() || !hexFile.isFile()) {
      throw new IllegalArgumentException(
          "[" + hexFileLocation + "] is not a file or it is not a file !");
    }

    final SerialPort port = this.getSerialPort(portName);
    this.pulseDTR(port);
    port.close();

    this.runAVRDude(hexFileLocation, portName);
  }
  /**
   * 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.");
    }
  }
Exemple #23
0
 public void close() {
   serialPort.close(); // this seems to bail on my machine (d3)
 }
 /**
  * This should be called when you stop using the port. This will prevent port locking on platforms
  * like Linux.
  */
 public synchronized void closeSerial() {
   if (serialPort != null) {
     serialPort.removeEventListener();
     serialPort.close();
   }
 }
 /** @see com.svhelloworld.knotlog.engine.sources.StreamedSource#close() */
 @Override
 public void close() {
   serialPort.close();
 }
 @Override
 public void close() {
   ptt_serial_port.close();
 }
Exemple #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
Exemple #28
0
 /** Close this serial device */
 public void close() {
   serialPort.removeEventListener();
   IOUtils.closeQuietly(inputStream);
   IOUtils.closeQuietly(outputStream);
   serialPort.close();
 }