Search in sources :

Example 11 with ObserveResponse

use of org.eclipse.leshan.core.response.ObserveResponse 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 ObserveResponse

use of org.eclipse.leshan.core.response.ObserveResponse in project leshan by eclipse.

the class RedisRequestResponseHandler method sendResponse.

private void sendResponse(String ticket, LwM2mResponse response) {
    if (response instanceof ObserveResponse) {
        Observation observation = ((ObserveResponse) response).getObservation();
        observatioIdToTicket.put(new KeyId(observation.getId()), ticket);
    }
    try (Jedis j = pool.getResource()) {
        JsonObject m = Json.object();
        m.add("ticket", ticket);
        m.add("rep", ResponseSerDes.jSerialize(response));
        j.publish(RESPONSE_CHANNEL, m.toString());
    }
}
Also used : Jedis(redis.clients.jedis.Jedis) Observation(org.eclipse.leshan.core.observation.Observation) JsonObject(com.eclipsesource.json.JsonObject) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse)

Example 13 with ObserveResponse

use of org.eclipse.leshan.core.response.ObserveResponse 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 ObserveResponse

use of org.eclipse.leshan.core.response.ObserveResponse in project leshan by eclipse.

the class ResponseSerDes method deserialize.

public static LwM2mResponse deserialize(JsonObject o) {
    String sCode = o.getString("code", null);
    if (sCode == null)
        throw new IllegalStateException("Invalid response missing code attribute");
    ResponseCode code = ResponseCode.fromName(sCode);
    String errorMessage = o.getString("errorMessage", null);
    String kind = o.getString("kind", null);
    switch(kind) {
        case "observe":
            {
                // TODO ser Observation
                LwM2mNode content = LwM2mNodeSerDes.deserialize((JsonObject) o.get("content"));
                return new ObserveResponse(code, content, null, null, errorMessage);
            }
        case "delete":
            return new DeleteResponse(code, errorMessage);
        case "discover":
            String objectLinks = o.getString("objectLinks", "");
            return new DiscoverResponse(code, Link.parse(objectLinks.getBytes()), errorMessage);
        case "create":
            {
                String location = o.getString("location", null);
                return new CreateResponse(code, location, errorMessage);
            }
        case "execute":
            return new ExecuteResponse(code, errorMessage);
        case "writeAttributes":
            {
                return new WriteAttributesResponse(code, errorMessage);
            }
        case "write":
            {
                return new WriteResponse(code, errorMessage);
            }
        case "read":
            {
                LwM2mNode content = LwM2mNodeSerDes.deserialize((JsonObject) o.get("content"));
                return new ReadResponse(code, content, errorMessage);
            }
        default:
            throw new IllegalStateException("Invalid response missing kind attribute");
    }
}
Also used : ResponseCode(org.eclipse.leshan.ResponseCode) CreateResponse(org.eclipse.leshan.core.response.CreateResponse) WriteResponse(org.eclipse.leshan.core.response.WriteResponse) JsonObject(com.eclipsesource.json.JsonObject) WriteAttributesResponse(org.eclipse.leshan.core.response.WriteAttributesResponse) DiscoverResponse(org.eclipse.leshan.core.response.DiscoverResponse) ExecuteResponse(org.eclipse.leshan.core.response.ExecuteResponse) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode) ObserveResponse(org.eclipse.leshan.core.response.ObserveResponse) DeleteResponse(org.eclipse.leshan.core.response.DeleteResponse) ReadResponse(org.eclipse.leshan.core.response.ReadResponse)

Aggregations

ObserveResponse (org.eclipse.leshan.core.response.ObserveResponse)14 Observation (org.eclipse.leshan.core.observation.Observation)10 ObserveRequest (org.eclipse.leshan.core.request.ObserveRequest)10 ReadResponse (org.eclipse.leshan.core.response.ReadResponse)9 Test (org.junit.Test)8 LwM2mResponse (org.eclipse.leshan.core.response.LwM2mResponse)7 LwM2mModel (org.eclipse.leshan.core.model.LwM2mModel)6 LwM2mPath (org.eclipse.leshan.core.node.LwM2mPath)6 Response (org.eclipse.californium.core.coap.Response)4 LwM2mObjectInstance (org.eclipse.leshan.core.node.LwM2mObjectInstance)4 DefaultLwM2mValueConverter (org.eclipse.leshan.core.node.codec.DefaultLwM2mValueConverter)4 JsonObject (com.eclipsesource.json.JsonObject)3 ArrayList (java.util.ArrayList)3 LwM2mNode (org.eclipse.leshan.core.node.LwM2mNode)3 TimestampedLwM2mNode (org.eclipse.leshan.core.node.TimestampedLwM2mNode)3 ReadRequest (org.eclipse.leshan.core.request.ReadRequest)3 WriteRequest (org.eclipse.leshan.core.request.WriteRequest)3 CreateResponse (org.eclipse.leshan.core.response.CreateResponse)3 DiscoverResponse (org.eclipse.leshan.core.response.DiscoverResponse)3 ExecuteResponse (org.eclipse.leshan.core.response.ExecuteResponse)3