All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ghgande.j2mod.modbus.net.TCPSlaveConnection Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
/*
 * Copyright 2002-2016 jamod & j2mod development teams
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ghgande.j2mod.modbus.net;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.io.AbstractModbusTransport;
import com.ghgande.j2mod.modbus.io.ModbusRTUTCPTransport;
import com.ghgande.j2mod.modbus.io.ModbusTCPTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Class that implements a TCPSlaveConnection.
 *
 * @author Dieter Wimberger
 * @author Steve O'Hara (4NG)
 * @version 2.0 (March 2016)
 */
public class TCPSlaveConnection {

    private static final Logger logger = LoggerFactory.getLogger(TCPSlaveConnection.class);

    // instance attributes
    private Socket socket;
    private int timeout = Modbus.DEFAULT_TIMEOUT;
    private boolean connected;
    private ModbusTCPTransport transport;

    /**
     * Constructs a TCPSlaveConnection instance using a given socket
     * instance.
     *
     * @param socket the socket instance to be used for communication.
     */
    public TCPSlaveConnection(Socket socket) {
        this(socket, false);
    }

    /**
     * Constructs a TCPSlaveConnection instance using a given socket
     * instance.
     *
     * @param socket        the socket instance to be used for communication.
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     */
    public TCPSlaveConnection(Socket socket, boolean useRtuOverTcp) {
        try {
            setSocket(socket, useRtuOverTcp);
        }
        catch (IOException ex) {
            logger.debug("TCPSlaveConnection::Socket invalid");

            throw new IllegalStateException("Socket invalid", ex);
        }
    }

    /**
     * Closes this TCPSlaveConnection.
     */
    public void close() {
        if (connected) {
            try {
                transport.close();
                socket.close();
            }
            catch (IOException ex) {
                logger.warn("Could not close socket", ex);
            }
            connected = false;
        }
    }

    /**
     * Returns the ModbusTransport associated with this
     * TCPMasterConnection.
     *
     * @return the connection's ModbusTransport.
     */
    public AbstractModbusTransport getModbusTransport() {
        return transport;
    }

    /** 
     * @return last activity timestamp of a connection
     * @see ModbusTCPTransport#getLastActivityTimestamp()
     * @see System#nanoTime() 
     */
    public long getLastActivityTimestamp() {
        return transport.getLastActivityTimestamp();
    }
    
    /**
     * Prepares the associated ModbusTransport of this
     * TCPMasterConnection for use.
     *
     * @param socket        the socket to be used for communication.
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     * @throws IOException if an I/O related error occurs.
     */
    private void setSocket(Socket socket, boolean useRtuOverTcp) throws IOException {
        this.socket = socket;

        if (transport == null) {
            if (useRtuOverTcp) {
                logger.trace("setSocket() -> using RTU over TCP transport.");
                transport = new ModbusRTUTCPTransport(socket);
            }
            else {
                logger.trace("setSocket() -> using standard TCP transport.");
                transport = new ModbusTCPTransport(socket);
            }
        }
        else {
            transport.setSocket(socket);
        }

        connected = true;
    }

    /**
     * Returns the timeout for this TCPSlaveConnection.
     *
     * @return the timeout as int.
     */
    public int getTimeout() {
        return timeout;
    }

    /**
     * Sets the timeout for this TCPSlaveConnection.
     *
     * @param timeout the timeout in milliseconds as int.
     */
    public void setTimeout(int timeout) {
        this.timeout = timeout;

        try {
            socket.setSoTimeout(timeout);
        }
        catch (IOException ex) {
            logger.warn("Could not set timeout to {}", timeout, ex);
        }
    }

    /**
     * Returns the destination port of this TCPSlaveConnection.
     *
     * @return the port number as int.
     */
    public int getPort() {
        return socket.getLocalPort();
    }

    /**
     * Returns the destination InetAddress of this
     * TCPSlaveConnection.
     *
     * @return the destination address as InetAddress.
     */
    public InetAddress getAddress() {
        return socket.getLocalAddress();
    }

    /**
     * Tests if this TCPSlaveConnection is connected.
     *
     * @return true if connected, false otherwise.
     */
    public boolean isConnected() {
        return connected;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy