@Override protected ReadResponse doRead(ReadRequest request) { LwM2mPath path = request.getPath(); // Manage Object case if (path.isObject()) { List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>(); for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) { lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue())); } return ReadResponse.success( new LwM2mObject(getId(), lwM2mObjectInstances.toArray(new LwM2mObjectInstance[0]))); } // Manage Instance case LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); if (instance == null) return ReadResponse.notFound(); if (path.getResourceId() == null) { return ReadResponse.success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance)); } // Manage Resource case return instance.read(path.getResourceId()); }
@Override public ReadResponse read(int resourceid) { if (resources.containsKey(resourceid)) { return ReadResponse.success(resources.get(resourceid)); } return ReadResponse.notFound(); }
LwM2mObjectInstance getLwM2mObjectInstance(int instanceid, LwM2mInstanceEnabler instance) { List<LwM2mResource> resources = new ArrayList<>(); for (ResourceModel resourceModel : getObjectModel().resources.values()) { if (resourceModel.operations.isReadable()) { ReadResponse response = instance.read(resourceModel.id); if (response.getCode() == ResponseCode.CONTENT && response.getContent() instanceof LwM2mResource) resources.add((LwM2mResource) response.getContent()); } } return new LwM2mObjectInstance(instanceid, resources.toArray(new LwM2mResource[0])); }
@Test public void can_write_replace_resource_in_json() { // write device timezone final String timeZone = "Europe/Paris"; WriteResponse response = helper.server.send(helper.getClient(), new WriteRequest(Mode.REPLACE, 3, 0, 15, timeZone)); // verify result assertEquals(ResponseCode.CHANGED, response.getCode()); // read the timezone to check the value changed ReadResponse readResponse = helper.server.send(helper.getClient(), new ReadRequest(3, 0, 15)); LwM2mResource resource = (LwM2mResource) readResponse.getContent(); assertEquals(timeZone, resource.getValue()); }
@Test public void can_write_object_instance() { // write device timezone and offset LwM2mResource utcOffset = LwM2mSingleResource.newStringResource(14, "+02"); LwM2mResource timeZone = LwM2mSingleResource.newStringResource(15, "Europe/Paris"); WriteResponse response = helper.server.send( helper.getClient(), new WriteRequest(Mode.REPLACE, 3, 0, utcOffset, timeZone)); // verify result assertEquals(ResponseCode.CHANGED, response.getCode()); // read the timezone to check the value changed ReadResponse readResponse = helper.server.send(helper.getClient(), new ReadRequest(3, 0)); LwM2mObjectInstance instance = (LwM2mObjectInstance) readResponse.getContent(); assertEquals(utcOffset, instance.getResource(14)); assertEquals(timeZone, instance.getResource(15)); }