Exemplo n.º 1
0
  /** Opens a new connection to the slave. */
  private void prepareConnection() {
    try {
      connection = new TCPMasterConnection(address);
      connection.setPort(port);

      connection.connect();

      transaction = new ModbusTCPTransaction(this.connection);
    } catch (Exception e) {
      log.warning("Opening connection not successful: " + e.getMessage());
    }
  }
Exemplo n.º 2
0
  /**
   * Read one value of the slave
   *
   * @param address Address of Memory of value in slave
   * @return the read value
   */
  public int sendReadRequest(int address) throws Exception {

    ReadInputRegistersResponse response = null;
    short tmp_value = 0;

    try {
      ReadInputRegistersRequest request = new ReadInputRegistersRequest(address, 1);
      response = (ReadInputRegistersResponse) this.sendRequest(request);
      tmp_value = response.getRegister(0).toShort();
      if (tmp_value == 0x7FFF) throw new Exception("0x7FFF received - value ignored");
    } catch (Exception ex) {
      log.warning("Error on reading value: " + ex.getMessage());
      throw ex;
    }
    return tmp_value;
  }
Exemplo n.º 3
0
  /**
   * Creates the ModBusWrapper.
   *
   * @param ip can contain the port information
   */
  public ModBusWrapper(String ip) {
    int idx = ip.indexOf(':');

    // extract port information
    if (idx > 0) {
      port = Integer.parseInt(ip.substring(idx + 1));
      ip = ip.substring(0, idx);
    }

    try {
      address = InetAddress.getByName(ip);
    } catch (Exception e) {
      log.severe("Failed to create address: " + ip + ";" + e.getMessage());
      return;
    }
  }
Exemplo n.º 4
0
  /**
   * Send a request to JAMod library. Opens and closes the connection each time. Otherwise the TCP
   * Stack of the slaves seams to have problems creating a response.
   *
   * @param request
   * @return the response
   */
  private ModbusResponse sendRequest(ModbusRequest request) {
    if (request == null) return null;
    prepareConnection();

    ModbusResponse response = null;
    transaction.setRequest(request);

    try {
      transaction.execute();
      response = transaction.getResponse();
    } catch (Exception e) {
      log.warning("Sending request not successful: " + e.getMessage());
    }
    this.connection.close();

    return response;
  }
Exemplo n.º 5
0
  /**
   * Write a configuration value to the slave
   *
   * @param address Address of the configuration value
   * @param value Value to be set
   * @return true if value received correctly
   */
  public boolean sendWriteRequest(int address, int value) {
    SimpleRegister reg = new SimpleRegister(value);

    try {
      WriteSingleRegisterRequest request = new WriteSingleRegisterRequest(address, reg);
      WriteSingleRegisterResponse response =
          (WriteSingleRegisterResponse) this.sendRequest(request);

      if (value != response.getRegisterValue()) {
        log.warning("The sent value isn't the same as the received value");
        return false;
      }
    } catch (Exception ex) {
      log.warning("Error on writing value: " + ex.getMessage());
      return false;
    }

    return true;
  }
Exemplo n.º 6
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