Search in sources :

Example 11 with ObserveRequest

use of org.eclipse.leshan.core.request.ObserveRequest in project leshan by eclipse.

the class ObserveTest method can_observe_timestamped_object.

@Test
public void can_observe_timestamped_object() throws InterruptedException {
    TestObservationListener listener = new TestObservationListener();
    helper.server.getObservationService().addListener(listener);
    // observe device timezone
    ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(), new ObserveRequest(3));
    assertEquals(ResponseCode.CONTENT, observeResponse.getCode());
    assertNotNull(observeResponse.getCoapResponse());
    assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class)));
    // an observation response should have been sent
    Observation observation = observeResponse.getObservation();
    assertEquals("/3", observation.getPath().toString());
    assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId());
    Set<Observation> observations = helper.server.getObservationService().getObservations(helper.getCurrentRegistration());
    assertTrue("We should have only on observation", observations.size() == 1);
    assertTrue("New observation is not there", observations.contains(observation));
    // *** HACK send time-stamped notification as Leshan client does not support it *** //
    // create time-stamped nodes
    TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(), new LwM2mObject(3, new LwM2mObjectInstance(0, LwM2mSingleResource.newStringResource(15, "Paris"))));
    List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
    timestampedNodes.add(mostRecentNode);
    timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2, new LwM2mObject(3, new LwM2mObjectInstance(0, LwM2mSingleResource.newStringResource(15, "Londres")))));
    byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3"), new LwM2mModel(helper.createObjectModels()), new DefaultLwM2mValueConverter());
    Response firstCoapResponse = (Response) observeResponse.getCoapResponse();
    sendNotification(getConnector(helper.client), payload, firstCoapResponse, ContentFormat.JSON_CODE);
    // *** Hack End *** //
    // verify result
    listener.waitForNotification(2000);
    assertTrue(listener.receivedNotify().get());
    assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent());
    assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode());
    assertNotNull(listener.getResponse().getCoapResponse());
    assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class)));
}
Also used : ArrayList(java.util.ArrayList) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) LwM2mModel(org.eclipse.leshan.core.model.LwM2mModel) DefaultLwM2mValueConverter(org.eclipse.leshan.core.node.codec.DefaultLwM2mValueConverter) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse) Response(org.eclipse.californium.core.coap.Response) LwM2mResponse(org.eclipse.leshan.core.response.LwM2mResponse) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse) ReadResponse(org.eclipse.leshan.core.response.ReadResponse) TimestampedLwM2mNode(org.eclipse.leshan.core.node.TimestampedLwM2mNode) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) LwM2mPath(org.eclipse.leshan.core.node.LwM2mPath) Observation(org.eclipse.leshan.core.observation.Observation) LwM2mObject(org.eclipse.leshan.core.node.LwM2mObject) Test(org.junit.Test)

Example 12 with ObserveRequest

use of org.eclipse.leshan.core.request.ObserveRequest in project leshan by eclipse.

the class ObservationServiceTest method givenAnObservation.

private Observation givenAnObservation(String registrationId, LwM2mPath target) {
    Registration registration = store.getRegistration(registrationId);
    if (registration == null) {
        registration = givenASimpleClient(registrationId);
        store.addRegistration(registration);
    }
    coapRequest = Request.newGet();
    coapRequest.setToken(CaliforniumTestSupport.createToken());
    coapRequest.getOptions().addUriPath(String.valueOf(target.getObjectId()));
    coapRequest.getOptions().addUriPath(String.valueOf(target.getObjectInstanceId()));
    coapRequest.getOptions().addUriPath(String.valueOf(target.getResourceId()));
    coapRequest.setObserve();
    coapRequest.setDestinationContext(EndpointContextUtil.extractContext(support.registration.getIdentity()));
    Map<String, String> context = ObserveUtil.createCoapObserveRequestContext(registration.getEndpoint(), registrationId, new ObserveRequest(target.toString()));
    coapRequest.setUserContext(context);
    store.put(coapRequest.getToken(), new org.eclipse.californium.core.observe.Observation(coapRequest, null));
    Observation observation = new Observation(coapRequest.getToken().getBytes(), registrationId, target, null);
    observationService.addObservation(registration, observation);
    return observation;
}
Also used : Registration(org.eclipse.leshan.server.registration.Registration) Observation(org.eclipse.leshan.core.observation.Observation) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest)

Example 13 with ObserveRequest

use of org.eclipse.leshan.core.request.ObserveRequest in project leshan by eclipse.

the class ClientServlet method doPost.

/**
 * {@inheritDoc}
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];
    // /clients/endPoint/LWRequest/observe : do LightWeight M2M observe request on a given client.
    if (path.length >= 3 && "observe".equals(path[path.length - 1])) {
        try {
            String target = StringUtils.substringBetween(req.getPathInfo(), clientEndpoint, "/observe");
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                // get content format
                String contentFormatParam = req.getParameter(FORMAT_PARAM);
                ContentFormat contentFormat = contentFormatParam != null ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null;
                // create & process request
                ObserveRequest request = new ObserveRequest(contentFormat, target);
                ObserveResponse cResponse = server.send(registration, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }
    String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);
    // /clients/endPoint/LWRequest : do LightWeight M2M execute request on a given client.
    if (path.length == 4) {
        try {
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                ExecuteRequest request = new ExecuteRequest(target, IOUtils.toString(req.getInputStream()));
                ExecuteResponse cResponse = server.send(registration, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }
    // /clients/endPoint/LWRequest : do LightWeight M2M create request on a given client.
    if (2 <= path.length && path.length <= 3) {
        try {
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                // get content format
                String contentFormatParam = req.getParameter(FORMAT_PARAM);
                ContentFormat contentFormat = contentFormatParam != null ? ContentFormat.fromName(contentFormatParam.toUpperCase()) : null;
                // create & process request
                LwM2mNode node = extractLwM2mNode(target, req);
                if (node instanceof LwM2mObjectInstance) {
                    CreateRequest request = new CreateRequest(contentFormat, target, (LwM2mObjectInstance) node);
                    CreateResponse cResponse = server.send(registration, request, TIMEOUT);
                    processDeviceResponse(req, resp, cResponse);
                } else {
                    throw new IllegalArgumentException("payload must contain an object instance");
                }
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }
}
Also used : ContentFormat(org.eclipse.leshan.core.request.ContentFormat) CreateRequest(org.eclipse.leshan.core.request.CreateRequest) CreateResponse(org.eclipse.leshan.core.response.CreateResponse) ExecuteResponse(org.eclipse.leshan.core.response.ExecuteResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) LwM2mObjectInstance(org.eclipse.leshan.core.node.LwM2mObjectInstance) Registration(org.eclipse.leshan.server.registration.Registration)

Example 14 with ObserveRequest

use of org.eclipse.leshan.core.request.ObserveRequest in project leshan by eclipse.

the class DownlinkRequestSerDes method jSerialize.

public static JsonObject jSerialize(DownlinkRequest<?> r) {
    final JsonObject o = Json.object();
    o.add("path", r.getPath().toString());
    r.accept(new DownLinkRequestVisitorAdapter() {

        @Override
        public void visit(ObserveRequest request) {
            o.add("kind", "observe");
            if (request.getContentFormat() != null)
                o.add("contentFormat", request.getContentFormat().getCode());
        }

        @Override
        public void visit(DeleteRequest request) {
            o.add("kind", "delete");
        }

        @Override
        public void visit(DiscoverRequest request) {
            o.add("kind", "discover");
        }

        @Override
        public void visit(CreateRequest request) {
            o.add("kind", "create");
            o.add("contentFormat", request.getContentFormat().getCode());
            if (request.getInstanceId() != null)
                o.add("instanceId", request.getInstanceId());
            JsonArray resources = new JsonArray();
            for (LwM2mResource resource : request.getResources()) {
                resources.add(LwM2mNodeSerDes.jSerialize(resource));
            }
            o.add("resources", resources);
        }

        @Override
        public void visit(ExecuteRequest request) {
            o.add("kind", "execute");
            o.add("parameters", request.getParameters());
        }

        @Override
        public void visit(WriteAttributesRequest request) {
            o.add("kind", "writeAttributes");
            o.add("observeSpec", request.getObserveSpec().toString());
        }

        @Override
        public void visit(WriteRequest request) {
            o.add("kind", "write");
            o.add("contentFormat", request.getContentFormat().getCode());
            o.add("mode", request.isPartialUpdateRequest() ? "UPDATE" : "REPLACE");
            o.add("node", LwM2mNodeSerDes.jSerialize(request.getNode()));
        }

        @Override
        public void visit(ReadRequest request) {
            o.add("kind", "read");
            if (request.getContentFormat() != null)
                o.add("contentFormat", request.getContentFormat().getCode());
        }
    });
    return o;
}
Also used : CreateRequest(org.eclipse.leshan.core.request.CreateRequest) WriteRequest(org.eclipse.leshan.core.request.WriteRequest) JsonObject(com.eclipsesource.json.JsonObject) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) LwM2mResource(org.eclipse.leshan.core.node.LwM2mResource) WriteAttributesRequest(org.eclipse.leshan.core.request.WriteAttributesRequest) DownLinkRequestVisitorAdapter(org.eclipse.leshan.core.request.DownLinkRequestVisitorAdapter) JsonArray(com.eclipsesource.json.JsonArray) ExecuteRequest(org.eclipse.leshan.core.request.ExecuteRequest) DiscoverRequest(org.eclipse.leshan.core.request.DiscoverRequest) DeleteRequest(org.eclipse.leshan.core.request.DeleteRequest) ReadRequest(org.eclipse.leshan.core.request.ReadRequest)

Example 15 with ObserveRequest

use of org.eclipse.leshan.core.request.ObserveRequest in project leshan by eclipse.

the class DownlinkRequestSerDesTest method ser_and_des_read_request_then_compare_to_observe_request.

@Test
public void ser_and_des_read_request_then_compare_to_observe_request() throws Exception {
    ReadRequest readRequest = new ReadRequest(ContentFormat.TLV, 3, 0, 1);
    JsonObject ser = DownlinkRequestSerDes.jSerialize(readRequest);
    DownlinkRequest<?> r2 = DownlinkRequestSerDes.deserialize(ser);
    assertNotEquals(r2, new ObserveRequest(ContentFormat.TLV, 3, 0, 1));
}
Also used : JsonObject(com.eclipsesource.json.JsonObject) ObserveRequest(org.eclipse.leshan.core.request.ObserveRequest) ReadRequest(org.eclipse.leshan.core.request.ReadRequest) Test(org.junit.Test)

Aggregations

ObserveRequest (org.eclipse.leshan.core.request.ObserveRequest)15 ObserveResponse (org.eclipse.leshan.core.response.ObserveResponse)10 Test (org.junit.Test)10 Observation (org.eclipse.leshan.core.observation.Observation)9 ReadRequest (org.eclipse.leshan.core.request.ReadRequest)7 LwM2mResponse (org.eclipse.leshan.core.response.LwM2mResponse)7 ReadResponse (org.eclipse.leshan.core.response.ReadResponse)7 LwM2mPath (org.eclipse.leshan.core.node.LwM2mPath)6 WriteRequest (org.eclipse.leshan.core.request.WriteRequest)6 LwM2mModel (org.eclipse.leshan.core.model.LwM2mModel)5 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)5 Response (org.eclipse.californium.core.coap.Response)4 DefaultLwM2mValueConverter (org.eclipse.leshan.core.node.codec.DefaultLwM2mValueConverter)4 CreateRequest (org.eclipse.leshan.core.request.CreateRequest)4 DiscoverRequest (org.eclipse.leshan.core.request.DiscoverRequest)4 ExecuteRequest (org.eclipse.leshan.core.request.ExecuteRequest)4 Registration (org.eclipse.leshan.server.registration.Registration)4 JsonObject (com.eclipsesource.json.JsonObject)3 ArrayList (java.util.ArrayList)3 LwM2mNode (org.eclipse.leshan.core.node.LwM2mNode)3