Search code examples
javam2mleshan

objectID is always 0 in Observe.onResponse


I'm trying to set up a custom server based on Leshan-server code. I want to store some data received from devices into a database. Currently I'm using the provided leshan-client-demo as the only client, for testing purpose.

My plan is to listen to observation responses, with an ObservationListener.onResponse handler.

For each of these events, I also need to retrieve the name of each resource to write them accordingly into my database. For that, I use server.getModelProvider related methods.

Here is a code snippet of my handler:

private LeshanServer server;
private ObservationListener obsListener = new ObservationListener() {
    public void onResponse(Observation obs, Registration reg, ObserveResponse res) {
        LwM2mObjectInstance content = (LwM2mObjectInstance) res.getContent();
        int objectId = content.getId(); // Here I retrieve the object ID, but it's always 0
        LwM2mModel objectModel = server.getModelProvider().getObjectModel(reg);

        for (Map.Entry<Integer, LwM2mResource> r : content.getResources().entrySet()) {
            int resId = r.getValue().getId(); // This one is okay
            ResourceModel model = objectModel.getResourceModel(objectId, resId); // and here I'm trying to use it
            if (model != null) {
                System.out.println(model.name);
            }
        }
    }
    // Other handlers next...
}

The issue is to retrieve correctly the object id. Here my objectId is always 0. So except for the first object, the resource model is null (as I suppose it doesen't match anything). I don't see any other relevant data in the ObserveResponse.

When I manually set objectId to other values (1, 2, 3, ...8), it works like a charm for the corresponding object.

I think it's not normal. What could be the origin of this bug?


Solution

  • I think res().getContent().getId() will return resourceId, not the ObjectId. In my case i tried setting observe for resource with id 2 and i got 2 from getId(). There is another way of getting ObjectId which is obs.getPath(), this way you will get LwM2mPath which contains ObjectId, InstanceId and ResourceId.