从 modbus 模拟器读取实时保持寄存器

Reading real time holding registers from the modbus simulator

我正在使用 jamod 库连接到 modbus,我已经连接到 modbus 模拟器并成功读取值,但我想实时读取值。

我的问题是,如果 simulator.This 中的值已更改,我想更改文本字段中的值,下面是我的代码

VBox vb = new VBox();
        vb.setAlignment(Pos.CENTER);
        TextField tf1 = new TextField();
        TextField tf2 = new TextField();
        TextField tf3 = new TextField();
        vb.getChildren().addAll(tf1,tf2,tf3);
        StackPane root = new StackPane();
        root.getChildren().add(vb);
        InetAddress inet = InetAddress.getLocalHost();
        TCPMasterConnection con = new TCPMasterConnection(inet);
        con.setPort(502);
        con.connect();
        ReadMultipleRegistersRequest req=new 
        ReadMultipleRegistersRequest(0,5);

        ModbusTCPTransaction trans = new ModbusTCPTransaction(con);
        trans.setRequest(req);


            trans.execute();
            ReadMultipleRegistersResponse res = 
(ReadMultipleRegistersResponse) trans.getResponse();
            tf1.setText(String.valueOf(res.getRegisterValue(0)));
            tf2.setText(String.valueOf(res.getRegisterValue(1)));
            tf3.setText(String.valueOf(res.getRegisterValue(2)));

投票值

定义将轮询数据的Runnable

Runnable r = new Runnable(){

    @Override
    public void run(){
        //TODO: define abort criteria for boolean:isRunning
        while(isRunning){
            //TODO define int:pollDelay
            Thread.sleep(pollDelay);

            //here you poll for new results
            trans.setRequest(req);
            ReadMultipleRegistersResponse res = 
                (ReadMultipleRegistersResponse) trans.getResponse();
            tf1.setText(String.valueOf(res.getRegisterValue(0)));
            ...
        }
    }
}

然后启动runnable而不是只获取一次数据

VBox vb = new VBox();
vb.setAlignment(Pos.CENTER);
TextField tf1 = new TextField();
...

ModbusTCPTransaction trans = new ModbusTCPTransaction(con);

Runnable r = new ... //see code above
new Thread(r).start(); //starts the polling

此代码既未编译也未编译 运行,但它为您提供了有关如何连续轮询数据的提示...