package com.jwk.spring.boot.test;

import com.jwk.spring.boot.constant.Constant;
import com.jwk.spring.boot.modbus4j.ModbusRtuMaster;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;

/**
 * 模拟主站设备
 *
 * @author wusq
 * @date 2021/1/3
 */
@Slf4j
public class RtuMasterTest {

    public static void main(String[] args) throws Exception {
        createRtuMaster();
    }

    private static void createRtuMaster() throws Exception {
        // 从站设备ID是1
        int slaveId = 1;
        ModbusRtuMaster rtuMaster = new ModbusRtuMaster("COM1", 9600
                , SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE
                , 0, 0);
        rtuMaster.connect();
        for (; ; ) {
            try {
                short[] shorts = rtuMaster
                        .getModbusMasterUtil().readCoils( 0, 3, slaveId).getShortData();
                System.out.println(Arrays.toString(shorts));
                boolean b = rtuMaster.getModbusMasterUtil().writeCoil( 1, new Random().nextInt(100), slaveId);
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error("", e);
                rtuMaster.reConnect();
            }
        }
    }
}
