Search in sources :

Example 1 with CoapHandler

use of org.eclipse.californium.core.CoapHandler in project thingsboard by thingsboard.

the class DeviceEmulator method start.

public void start() {
    executor.submit(new Runnable() {

        @Override
        public void run() {
            try {
                sendObserveRequest(rpcClient);
                while (!Thread.interrupted()) {
                    sendRequest(attributesClient, createAttributesRequest());
                    sendRequest(telemetryClient, createTelemetryRequest());
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error("Error occurred while sending COAP requests", e);
            }
        }

        private void sendRequest(CoapClient client, JsonNode request) throws JsonProcessingException {
            CoapResponse telemetryResponse = client.setTimeout(60000).post(mapper.writeValueAsString(request), MediaTypeRegistry.APPLICATION_JSON);
            log.info("Response: {}, {}", telemetryResponse.getCode(), telemetryResponse.getResponseText());
        }

        private void sendObserveRequest(CoapClient client) throws JsonProcessingException {
            client.observe(new CoapHandler() {

                @Override
                public void onLoad(CoapResponse coapResponse) {
                    log.info("Command: {}, {}", coapResponse.getCode(), coapResponse.getResponseText());
                    try {
                        JsonNode node = mapper.readTree(coapResponse.getResponseText());
                        int requestId = node.get("id").asInt();
                        String method = node.get("method").asText();
                        ObjectNode params = (ObjectNode) node.get("params");
                        ObjectNode response = mapper.createObjectNode();
                        response.put("id", requestId);
                        response.set("response", params);
                        log.info("Command Response: {}, {}", requestId, mapper.writeValueAsString(response));
                        CoapClient commandResponseClient = new CoapClient(getFeatureTokenUrl(host, port, token, FeatureType.RPC));
                        commandResponseClient.post(new CoapHandler() {

                            @Override
                            public void onLoad(CoapResponse response) {
                                log.info("Command Response Ack: {}, {}", response.getCode(), response.getResponseText());
                            }

                            @Override
                            public void onError() {
                            // Do nothing
                            }
                        }, mapper.writeValueAsString(response), MediaTypeRegistry.APPLICATION_JSON);
                    } catch (IOException e) {
                        log.error("Error occurred while processing COAP response", e);
                    }
                }

                @Override
                public void onError() {
                // Do nothing
                }
            });
        }
    });
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CoapHandler(org.eclipse.californium.core.CoapHandler) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) CoapClient(org.eclipse.californium.core.CoapClient)

Example 2 with CoapHandler

use of org.eclipse.californium.core.CoapHandler in project thingsboard by thingsboard.

the class NoSecObserveClient method start.

public void start() {
    executor.submit(() -> {
        try {
            Request request = Request.newGet();
            request.setObserve();
            observeRelation = coapClient.observe(request, new CoapHandler() {

                @Override
                public void onLoad(CoapResponse response) {
                    String responseText = response.getResponseText();
                    CoAP.ResponseCode code = response.getCode();
                    Integer observe = response.getOptions().getObserve();
                    log.info("CoAP Response received! " + "responseText: {}, " + "code: {}, " + "observe seq number: {}", responseText, code, observe);
                    latch.countDown();
                }

                @Override
                public void onError() {
                    log.error("Ack error!");
                    latch.countDown();
                }
            });
        } catch (Exception e) {
            log.error("Error occurred while sending COAP requests: ");
        }
    });
    try {
        latch.await();
        observeRelation.proactiveCancel();
    } catch (InterruptedException e) {
        log.error("Error occurred: ", e);
    }
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) CoapHandler(org.eclipse.californium.core.CoapHandler) Request(org.eclipse.californium.core.coap.Request) CoAP(org.eclipse.californium.core.coap.CoAP) URISyntaxException(java.net.URISyntaxException)

Example 3 with CoapHandler

use of org.eclipse.californium.core.CoapHandler in project thingsboard by thingsboard.

the class AbstractCoapServerSideRpcIntegrationTest method processOnLoadResponse.

protected void processOnLoadResponse(CoapResponse response, CoapClient client, Integer observe, CountDownLatch latch) {
    JsonNode responseJson = JacksonUtil.fromBytes(response.getPayload());
    client.setURI(getRpcResponseFeatureTokenUrl(accessToken, responseJson.get("id").asInt()));
    client.post(new CoapHandler() {

        @Override
        public void onLoad(CoapResponse response) {
            log.warn("Command Response Ack: {}, {}", response.getCode(), response.getResponseText());
            latch.countDown();
        }

        @Override
        public void onError() {
            log.warn("Command Response Ack Error, No connect");
        }
    }, DEVICE_RESPONSE, MediaTypeRegistry.APPLICATION_JSON);
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) CoapHandler(org.eclipse.californium.core.CoapHandler) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 4 with CoapHandler

use of org.eclipse.californium.core.CoapHandler in project hono by eclipse.

the class CoapTestBase method warmUp.

/**
 * Triggers the establishment of a downstream sender
 * for a tenant so that subsequent messages will be
 * more likely to be forwarded.
 *
 * @param client The CoAP client to use for sending the request.
 * @param request The request to send.
 * @return A succeeded future.
 */
protected final Future<Void> warmUp(final CoapClient client, final Request request) {
    logger.debug("sending request to trigger CoAP adapter's downstream message sender");
    final Promise<Void> result = Promise.promise();
    client.advanced(new CoapHandler() {

        @Override
        public void onLoad(final CoapResponse response) {
            waitForWarmUp();
        }

        @Override
        public void onError() {
            waitForWarmUp();
        }

        private void waitForWarmUp() {
            vertx.setTimer(1000, tid -> result.complete());
        }
    }, request);
    return result.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) KeyPair(java.security.KeyPair) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) AdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) CertificateType(org.eclipse.californium.scandium.dtls.CertificateType) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) CoapResponse(org.eclipse.californium.core.CoapResponse) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) GeneralSecurityException(java.security.GeneralSecurityException) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Utils(org.eclipse.californium.core.Utils) JsonObject(io.vertx.core.json.JsonObject) URI(java.net.URI) Tenants(org.eclipse.hono.tests.Tenants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Device(org.eclipse.hono.service.management.device.Device) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) MessageContext(org.eclipse.hono.application.client.MessageContext) SubscriberRole(org.eclipse.hono.tests.CommandEndpointConfiguration.SubscriberRole) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) InetSocketAddress(java.net.InetSocketAddress) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) Request(org.eclipse.californium.core.coap.Request) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) QoS(org.eclipse.hono.util.QoS) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapClient(org.eclipse.californium.core.CoapClient) X500Principal(javax.security.auth.x500.X500Principal) KeyLoader(org.eclipse.hono.config.KeyLoader) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Constants(org.eclipse.hono.util.Constants) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) MediaTypeRegistry(org.eclipse.californium.core.coap.MediaTypeRegistry) StaticNewAdvancedCertificateVerifier(org.eclipse.californium.scandium.dtls.x509.StaticNewAdvancedCertificateVerifier) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Type(org.eclipse.californium.core.coap.CoAP.Type) Logger(org.slf4j.Logger) AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Truth.assertThat(com.google.common.truth.Truth.assertThat) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Code(org.eclipse.californium.core.coap.CoAP.Code) Adapter(org.eclipse.hono.util.Adapter) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) CoapHandler(org.eclipse.californium.core.CoapHandler) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) Collections(java.util.Collections) CoapResponse(org.eclipse.californium.core.CoapResponse) CoapHandler(org.eclipse.californium.core.CoapHandler)

Example 5 with CoapHandler

use of org.eclipse.californium.core.CoapHandler in project thingsboard by thingsboard.

the class AbstractCoapServerSideRpcProtoIntegrationTest method processOnLoadResponse.

@Override
protected void processOnLoadResponse(CoapResponse response, CoapClient client, Integer observe, CountDownLatch latch) {
    ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = getProtoTransportPayloadConfiguration();
    ProtoFileElement rpcRequestProtoSchemaFile = protoTransportPayloadConfiguration.getTransportProtoSchema(RPC_REQUEST_PROTO_SCHEMA);
    DynamicSchema rpcRequestProtoSchema = protoTransportPayloadConfiguration.getDynamicSchema(rpcRequestProtoSchemaFile, ProtoTransportPayloadConfiguration.RPC_REQUEST_PROTO_SCHEMA);
    byte[] requestPayload = response.getPayload();
    DynamicMessage.Builder rpcRequestMsg = rpcRequestProtoSchema.newMessageBuilder("RpcRequestMsg");
    Descriptors.Descriptor rpcRequestMsgDescriptor = rpcRequestMsg.getDescriptorForType();
    try {
        DynamicMessage dynamicMessage = DynamicMessage.parseFrom(rpcRequestMsgDescriptor, requestPayload);
        Descriptors.FieldDescriptor requestIdDescriptor = rpcRequestMsgDescriptor.findFieldByName("requestId");
        int requestId = (int) dynamicMessage.getField(requestIdDescriptor);
        ProtoFileElement rpcResponseProtoSchemaFile = protoTransportPayloadConfiguration.getTransportProtoSchema(DEVICE_RPC_RESPONSE_PROTO_SCHEMA);
        DynamicSchema rpcResponseProtoSchema = protoTransportPayloadConfiguration.getDynamicSchema(rpcResponseProtoSchemaFile, ProtoTransportPayloadConfiguration.RPC_RESPONSE_PROTO_SCHEMA);
        DynamicMessage.Builder rpcResponseBuilder = rpcResponseProtoSchema.newMessageBuilder("RpcResponseMsg");
        Descriptors.Descriptor rpcResponseMsgDescriptor = rpcResponseBuilder.getDescriptorForType();
        DynamicMessage rpcResponseMsg = rpcResponseBuilder.setField(rpcResponseMsgDescriptor.findFieldByName("payload"), DEVICE_RESPONSE).build();
        client.setURI(getRpcResponseFeatureTokenUrl(accessToken, requestId));
        client.post(new CoapHandler() {

            @Override
            public void onLoad(CoapResponse response) {
                log.warn("Command Response Ack: {}", response.getCode());
                latch.countDown();
            }

            @Override
            public void onError() {
                log.warn("Command Response Ack Error, No connect");
            }
        }, rpcResponseMsg.toByteArray(), MediaTypeRegistry.APPLICATION_JSON);
    } catch (InvalidProtocolBufferException e) {
        log.warn("Command Response Ack Error, Invalid response received: ", e);
    }
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) CoapHandler(org.eclipse.californium.core.CoapHandler) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) DynamicSchema(com.github.os72.protobuf.dynamic.DynamicSchema) DynamicMessage(com.google.protobuf.DynamicMessage) ProtoFileElement(com.squareup.wire.schema.internal.parser.ProtoFileElement) ProtoTransportPayloadConfiguration(org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration) Descriptors(com.google.protobuf.Descriptors)

Aggregations

CoapHandler (org.eclipse.californium.core.CoapHandler)5 CoapResponse (org.eclipse.californium.core.CoapResponse)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 URISyntaxException (java.net.URISyntaxException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 DynamicSchema (com.github.os72.protobuf.dynamic.DynamicSchema)1 Truth.assertThat (com.google.common.truth.Truth.assertThat)1 Truth.assertWithMessage (com.google.common.truth.Truth.assertWithMessage)1 Descriptors (com.google.protobuf.Descriptors)1 DynamicMessage (com.google.protobuf.DynamicMessage)1 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)1 ProtoFileElement (com.squareup.wire.schema.internal.parser.ProtoFileElement)1 AsyncResult (io.vertx.core.AsyncResult)1 Future (io.vertx.core.Future)1 Handler (io.vertx.core.Handler)1 Promise (io.vertx.core.Promise)1 Vertx (io.vertx.core.Vertx)1 Buffer (io.vertx.core.buffer.Buffer)1 JsonObject (io.vertx.core.json.JsonObject)1