com.serotonin.modbus4j.exception.ModbusInitException Java Examples

The following examples show how to use com.serotonin.modbus4j.exception.ModbusInitException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModbusUtil.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public static ModbusMaster createMaster(String ip, int port) {
    ModbusMaster master = null;
    try {
        IpParameters ipParam = new IpParameters();
        ipParam.setHost(ip);
        ipParam.setPort(port);
        ipParam.setEncapsulated(false);
        master = ModbusFactoryInstance.getInstance()
                .createTcpMaster(ipParam, true);
        master.setTimeout(2000);
        master.setRetries(0);
        log.info("Starting Modbus master...");
        master.init();
        log.info("Modbus master started!");
        return master;
    } catch (ModbusInitException e) {
        log.info("Stopping Modbus master...");
        master.destroy();
        log.info("Modbus master stopped!");
    }
    return master;
}
 
Example #2
Source File: CustomDriverServiceImpl.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 Value
 *
 * @param modbusMaster
 * @param pointInfo
 * @return
 * @throws ModbusTransportException
 * @throws ErrorResponseException
 * @throws ModbusInitException
 */
public String readValue(ModbusMaster modbusMaster, Map<String, AttributeInfo> pointInfo, String type) throws ModbusTransportException, ErrorResponseException, ModbusInitException {
    int slaveId = attribute(pointInfo, "slaveId");
    int functionCode = attribute(pointInfo, "functionCode");
    int offset = attribute(pointInfo, "offset");
    switch (functionCode) {
        case 1:
            BaseLocator<Boolean> coilLocator = BaseLocator.coilStatus(slaveId, offset);
            Boolean coilValue = modbusMaster.getValue(coilLocator);
            return String.valueOf(coilValue);
        case 2:
            BaseLocator<Boolean> inputLocator = BaseLocator.inputStatus(slaveId, offset);
            Boolean inputStatusValue = modbusMaster.getValue(inputLocator);
            return String.valueOf(inputStatusValue);
        case 3:
            BaseLocator<Number> holdingLocator = BaseLocator.holdingRegister(slaveId, offset, getValueType(type));
            Number holdingValue = modbusMaster.getValue(holdingLocator);
            return String.valueOf(holdingValue);
        case 4:
            BaseLocator<Number> inputRegister = BaseLocator.inputRegister(slaveId, offset, getValueType(type));
            Number inputRegisterValue = modbusMaster.getValue(inputRegister);
            return String.valueOf(inputRegisterValue);
        default:
            return "0";
    }
}
 
Example #3
Source File: AsciiSlave.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void start() throws ModbusInitException {
    super.start();

    AsciiMessageParser asciiMessageParser = new AsciiMessageParser(false);
    AsciiRequestHandler asciiRequestHandler = new AsciiRequestHandler(this);

    conn = new MessageControl();
    conn.setExceptionHandler(getExceptionHandler());

    try {
        conn.start(transport, asciiMessageParser, asciiRequestHandler, null);
        transport.start("Modbus ASCII slave");
    }
    catch (IOException e) {
        throw new ModbusInitException(e);
    }
}
 
Example #4
Source File: UdpMaster.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void init() throws ModbusInitException {
    if (ipParameters.isEncapsulated())
        messageParser = new EncapMessageParser(true);
    else
        messageParser = new XaMessageParser(true);

    try {
        socket = new DatagramSocket();
        socket.setSoTimeout(getTimeout());
    }
    catch (SocketException e) {
        throw new ModbusInitException(e);
    }
    initialized = true;
}
 
Example #5
Source File: TcpListener.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    LOG.debug(" ListenerConnectionHandler::run() ");

    if (ipParameters.isEncapsulated()) {
        ipMessageParser = new EncapMessageParser(true);
        waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory();
    }
    else {
        ipMessageParser = new XaMessageParser(true);
        waitingRoomKeyFactory = new XaWaitingRoomKeyFactory();
    }

    try {
        acceptConnection();
    }
    catch (IOException e) {
        LOG.debug("Error in TCP Listener! - " + e.getLocalizedMessage(), e);
        conn.close();
        closeConnection();
        getExceptionHandler().receivedException(new ModbusInitException(e));
    }
}
 
Example #6
Source File: TcpListener.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
void closeConnection() {
    if (conn != null) {
        LOG.debug("Closing Message Control on port: " + ipParameters.getPort());
        closeMessageControl(conn);
    }

    try {
        if (socket != null) {
            socket.close();
        }
    }
    catch (IOException e) {
        LOG.debug("Error closing socket on port " + ipParameters.getPort() + ". " + e.getLocalizedMessage());
        getExceptionHandler().receivedException(new ModbusInitException(e));
    }
    connected = false;
    conn = null;
    socket = null;
}
 
Example #7
Source File: TcpSlave.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void start() throws ModbusInitException {
    try {
        serverSocket = new ServerSocket(port);

        Socket socket;
        while (true) {
            socket = serverSocket.accept();
            TcpConnectionHandler handler = new TcpConnectionHandler(socket);
            executorService.execute(handler);
            synchronized (listConnections) {
                listConnections.add(handler);
            }
        }
    }
    catch (IOException e) {
        throw new ModbusInitException(e);
    }
}
 
Example #8
Source File: RtuSlave.java    From modbus4j with GNU General Public License v3.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void start() throws ModbusInitException {
    super.start();

    RtuMessageParser rtuMessageParser = new RtuMessageParser(false);
    RtuRequestHandler rtuRequestHandler = new RtuRequestHandler(this);

    conn = new MessageControl();
    conn.setExceptionHandler(getExceptionHandler());

    try {
        conn.start(transport, rtuMessageParser, rtuRequestHandler, null);
        transport.start("Modbus RTU slave");
    }
    catch (IOException e) {
        throw new ModbusInitException(e);
    }
}
 
Example #9
Source File: CustomDriverServiceImpl.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 Modbus Master
 *
 * @param deviceId
 * @param driverInfo
 * @return
 * @throws ModbusInitException
 */
public ModbusMaster getMaster(Long deviceId, Map<String, AttributeInfo> driverInfo) throws ModbusInitException {
    log.debug("Modbus Tcp Connection Info {}", JSON.toJSONString(driverInfo));
    ModbusMaster modbusMaster = masterMap.get(deviceId);
    if (null == modbusMaster || !modbusMaster.isConnected()) {
        IpParameters params = new IpParameters();
        params.setHost(attribute(driverInfo, "host"));
        params.setPort(attribute(driverInfo, "port"));
        modbusMaster = modbusFactory.createTcpMaster(params, true);
        modbusMaster.init();
        masterMap.put(deviceId, modbusMaster);
    }
    return modbusMaster;
}
 
Example #10
Source File: AsciiMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void init() throws ModbusInitException {
    try {
        openConnection(null);
    }
    catch (Exception e) {
        throw new ModbusInitException(e);
    }
    initialized = true;
}
 
Example #11
Source File: SerialSlave.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void start() throws ModbusInitException {
    try {
    	
    	wrapper.open();

        transport = new StreamTransport(wrapper.getInputStream(), wrapper.getOutputStream());
    }
    catch (Exception e) {
        throw new ModbusInitException(e);
    }
}
 
Example #12
Source File: RtuMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void init() throws ModbusInitException {
    try {
        openConnection(null);
    }
    catch (Exception e) {
        throw new ModbusInitException(e);
    }
    initialized = true;
}
 
Example #13
Source File: SerialMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void init() throws ModbusInitException {
    try {
        this.openConnection(null);
    }
    catch (Exception e) {
        throw new ModbusInitException(e);
    }
}
 
Example #14
Source File: TcpMaster.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
synchronized public void init() throws ModbusInitException {
    try {
        if (keepAlive)
            openConnection();
    }
    catch (Exception e) {
        throw new ModbusInitException(e);
    }
    initialized = true;
}
 
Example #15
Source File: TcpSlave.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
void kill() {
    try {
        socket.close();
    }
    catch (IOException e) {
        getExceptionHandler().receivedException(new ModbusInitException(e));
    }
}
 
Example #16
Source File: TcpSlave.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
TcpConnectionHandler(Socket socket) throws ModbusInitException {
    this.socket = socket;
    try {
        transport = new TestableTransport(socket.getInputStream(), socket.getOutputStream());
    }
    catch (IOException e) {
        throw new ModbusInitException(e);
    }
}
 
Example #17
Source File: TcpListener.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
private void startListener() throws ModbusInitException {
    try {
        if (handler != null) {
            LOG.debug("handler not null!!!");
        }
        handler = new ListenerConnectionHandler(socket);
        LOG.debug("Init handler thread");
        executorService.execute(handler);
    }
    catch (Exception e) {
        LOG.warn("Error initializing TcpListener ", e);
        throw new ModbusInitException(e);
    }
}
 
Example #18
Source File: TcpListener.java    From modbus4j with GNU General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
synchronized public void init() throws ModbusInitException {
    LOG.debug("Init TcpListener Port: " + ipParameters.getPort());
    executorService = Executors.newCachedThreadPool();
    startListener();
    initialized = true;
    LOG.warn("Initialized Port: " + ipParameters.getPort());
}
 
Example #19
Source File: Test4.java    From modbus4j with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // SerialParameters params = new SerialParameters();
    // params.setCommPortId("COM1");
    // params.setPortOwnerName("dufus");
    // params.setBaudRate(9600);

    // IpParameters params = new IpParameters();
    // params.setHost(host)


    // ModbusListener listener = modbusFactory.createRtuListener(processImage, 31, params, false);
    // ModbusListener listener = modbusFactory.createAsciiListener(processImage, 31, params);
    int port = 5000;
    final ModbusSlaveSet listener = new TcpSlave(port, false);
    // ModbusSlave listener = modbusFactory.createUdpSlave(processImage, 31);

    // Add a few slave process images to the listener.
    listener.addProcessImage(getModscanProcessImage(1));
    //        listener.addProcessImage(getModscanProcessImage(2));
    //listener.addProcessImage(getModscanProcessImage(3));
    //        listener.addProcessImage(getModscanProcessImage(5));
    //listener.addProcessImage(getModscanProcessImage(9));

    // When the "listener" is started it will use the current thread to run. So, if an exception is not thrown
    // (and we hope it won't be), the method call will not return. Therefore, we start the listener in a separate
    // thread so that we can use this thread to modify the values.
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                listener.start();
            }
            catch (ModbusInitException e) {
                e.printStackTrace();
            }
        }
    }).start();

    while (true) {
        synchronized (listener) {
            listener.wait(200);
        }

        for (ProcessImage processImage : listener.getProcessImages())
            updateProcessImage((BasicProcessImage) processImage);
    }
}
 
Example #20
Source File: ListenerTest2.java    From modbus4j with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    ModbusFactory modbusFactory = new ModbusFactory();
    final ModbusSlaveSet listener = modbusFactory.createTcpSlave(false);
    listener.addProcessImage(getModscanProcessImage(1));
    listener.addProcessImage(getModscanProcessImage(2));

    // When the "listener" is started it will use the current thread to run. So, if an exception is not thrown
    // (and we hope it won't be), the method call will not return. Therefore, we start the listener in a separate
    // thread so that we can use this thread to modify the values.
    new Thread(new Runnable() {
        public void run() {
            try {
                listener.start();
            }
            catch (ModbusInitException e) {
                e.printStackTrace();
            }
        }
    }).start();

    while (true) {
        updateProcessImage1((BasicProcessImage) listener.getProcessImage(1));
        updateProcessImage2((BasicProcessImage) listener.getProcessImage(2));

        synchronized (listener) {
            listener.wait(5000);
        }
    }
}
 
Example #21
Source File: ModbusMaster.java    From modbus4j with GNU General Public License v3.0 2 votes vote down vote up
/**
 * <p>init.</p>
 *
 * @throws com.serotonin.modbus4j.exception.ModbusInitException if any.
 */
abstract public void init() throws ModbusInitException;
 
Example #22
Source File: ModbusSlaveSet.java    From modbus4j with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Starts the slave. If an exception is not thrown, this method does not return, but uses the thread to execute the
 * listening.
 *
 * @throws com.serotonin.modbus4j.exception.ModbusInitException if necessary
 */
abstract public void start() throws ModbusInitException;
 
Example #23
Source File: ListenerTest.java    From modbus4j with GNU General Public License v3.0 2 votes vote down vote up
public static void main(String[] args) throws Exception {
    // SerialParameters params = new SerialParameters();
    // params.setCommPortId("COM1");
    // params.setPortOwnerName("dufus");
    // params.setBaudRate(9600);

    // IpParameters params = new IpParameters();
    // params.setHost(host)

    ModbusFactory modbusFactory = new ModbusFactory();
    // ModbusListener listener = modbusFactory.createRtuListener(processImage, 31, params, false);
    // ModbusListener listener = modbusFactory.createAsciiListener(processImage, 31, params);
    final ModbusSlaveSet listener = modbusFactory.createTcpSlave(false);
    // ModbusSlave listener = modbusFactory.createUdpSlave(processImage, 31);

    // Add a few slave process images to the listener.
    listener.addProcessImage(getModscanProcessImage(1));
    //        listener.addProcessImage(getModscanProcessImage(2));
    listener.addProcessImage(getModscanProcessImage(3));
    //        listener.addProcessImage(getModscanProcessImage(5));
    listener.addProcessImage(getModscanProcessImage(9));

    // When the "listener" is started it will use the current thread to run. So, if an exception is not thrown
    // (and we hope it won't be), the method call will not return. Therefore, we start the listener in a separate
    // thread so that we can use this thread to modify the values.
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                listener.start();
            }
            catch (ModbusInitException e) {
                e.printStackTrace();
            }
        }
    }).start();

    while (true) {
        synchronized (listener) {
            listener.wait(200);
        }

        for (ProcessImage processImage : listener.getProcessImages())
            updateProcessImage((BasicProcessImage) processImage);
    }
}