我正在使用jamod库连接到modbus,我已经连接到modbus模拟器并成功读取值,但我想实时读取值。
java - 从modbus模拟器读取实时保持寄存器-LMLPHP
我的问题是如果在模拟器中更改了值,我想更改textfield中的值。

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

这段代码既没有编译也没有运行,但它提供了有关如何连续轮询数据的提示…

10-06 16:02