简体   繁体   English

从Californium CoAP客户端检索观察值

[英]Retrieve the observed value from Californium CoAP client

I am trying to implement a CoAP client based on Californium. 我正在尝试实现基于Californium的CoAP客户端。 I make this client observing to a resource: 我让这个客户观察资源:

public static class CoapCl{

    double val = 0;
    CoapClient client = new CoapClient("coap://localhost/Ultrasonic");
    CoapObserveRelation relation = client.observe(new CoapHandler() {
    @Override public void onLoad(CoapResponse response)
    {
        val = Double.parseDouble(response.getResponseText());
    }

    @Override
    public void onError() {
        System.out.println("Failed");

    }
});
}

I want to access the value "val" from another class. 我想从另一个类访问值“ val”。 How can I do it ? 我该怎么做 ? I tried to call a reference from the CoapCl class like this and print the value out: 我试图像这样从CoapCl类中调用一个引用,并打印出值:

CoapCl client = new CoapCl();
    while(true)
    {
    System.out.println("Testing: " + client.val);
    }   

This will print all the value I get from the CoAP client, both changed and unchanged value. 这将打印我从CoAP客户端获得的所有值,包括已更改和未更改的值。 What should I do if I only want to get the changed value ? 如果我只想获得更改的值该怎么办?

Well, the issue itself isn't related to Californium and CoAP. 嗯,问题本身与Californium和CoAP无关。 Except that CoapHandler is async but this is rather a strench. 除了CoapHandler是异步的,但这是一个痛苦。 Nevertheless, I'd recommend to end up with some kind of callback: 不过,我建议以某种回调结束:

public class CoapCl {
    private final Consumer<Double> valueChangedAction;
    private final CoapClient client = new CoapClient("coap://localhost/Ultrasonic");

    public CoapCl(Consumer<Double> valueChangedAction) {
        this.valueChangedAction = valueChangedAction;
    }

    public void run() {
        client.observe(new CoapHandler() {
            @Override
            public void onLoad(CoapResponse response) {
                valueChangedAction.accept(
                    Double.parseDouble(
                        response.getResponseText()
                    )
                );
            }

            @Override
            public void onError() {
                System.out.println("Failed");
            }
        });
    }
}

new CoapCl(val -> System.out.println("Testing: " + val)).run();

Please keep in mind you have to block the main thread someway to keep the program from immediate exit. 请记住,您必须以某种方式阻塞主线程,以防止程序立即退出。 Before, you had blocked it with your infinite loop. 以前,您已经使用无限循环将其阻止。 Now you'll have to use System.in.read() or Thread.sleep or something else if you have no such stuff yet in your program. 现在,如果程序中还没有此类内容,则必须使用System.in.read()或Thread.sleep或其他方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM