org.eclipse.californium.core.CoapClient Java Examples

The following examples show how to use org.eclipse.californium.core.CoapClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuavRoutines.java    From SoftwarePilot with MIT License 6 votes vote down vote up
public String invokeHostDriver(String command, String IP, CoapHandler ch, boolean gov){
		if(gov) {
				try {
						//System.out.println("URI = "+IP+":"+portStr);
						URI uri = new URI("coap://"+IP+":5117/cr");
						CoapClient client = new CoapClient(uri);
						client.setTimeout(TIMEOUT);

						client.put(ch,command,TEXT_PLAIN);
						return("Success");
						//return(response.getResponseText());
				}
				catch (Exception e) {
						return("Unable to reach driver host");
				}
		}
		return "InvokeDriver with Governor Executed";
}
 
Example #2
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
private CoapObserveRelation subscribeCOAP(String topic) throws TradfriException {

        try {
            URI uri = new URI("coaps://" + coapIP + "/" + topic);

            CoapClient client = new CoapClient(uri);
            client.setEndpoint(coapEndPoint);
            CoapHandler handler = new CoapHandler() {
                @Override
                public void onLoad(CoapResponse response) {
                    receivedCOAP(topic, response.getResponseText());
                }

                @Override
                public void onError() {
                    LOGGER.log(Level.WARNING, "COAP subscription error");
                }
            };
            return client.observe(handler);
        } catch (URISyntaxException ex) {
            LOGGER.log(Level.WARNING, "COAP SEND error: {0}", ex.getMessage());
            throw new TradfriException(ex);
        }
    }
 
Example #3
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
String requestGetCOAP(String topic) throws TradfriException {
    LOGGER.log(Level.FINE, "requext GET COAP: {0}", new Object[]{topic});
    try {
        URI uri = new URI("coaps://" + coapIP + "/" + topic);
        CoapClient client = new CoapClient(uri);
        client.setEndpoint(coapEndPoint);
        CoapResponse response = client.get();
        if (response == null || !response.isSuccess()) {
            LOGGER.log(Level.WARNING, "COAP GET error: Response error.");
            throw new TradfriException("Connection to gateway failed. Check host and PSK.");
        }
        String result = response.getResponseText();
        client.shutdown();
        return result;
    } catch (URISyntaxException ex) {
        LOGGER.log(Level.WARNING, "COAP GET error: {0}", ex.getMessage());
        throw new TradfriException(ex);
    }
}
 
Example #4
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
String requestPostCOAP(String topic, String payload) throws TradfriException {
    LOGGER.log(Level.FINE, "request POST COAP: {0}, {1}", new Object[]{topic, payload});
    try {
        URI uri = new URI("coaps://" + coapIP + "/" + topic);
        CoapClient client = new CoapClient(uri);
        client.setEndpoint(coapEndPoint);
        CoapResponse response = client.post(payload, MediaTypeRegistry.TEXT_PLAIN);
        if (response == null || !response.isSuccess()) {
            LOGGER.log(Level.WARNING, "COAP GET error: Response error.");
            throw new TradfriException("Connection to gateway failed. Check host and PSK.");
        }
        String result = response.getResponseText();
        client.shutdown();
        return result;
    } catch (URISyntaxException ex) {
        LOGGER.log(Level.WARNING, "COAP GET error: {0}", ex.getMessage());
        throw new TradfriException(ex);
    }
}
 
Example #5
Source File: TelemetryCoapIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the upload of a telemetry message containing a payload that
 * exceeds the CoAP adapter's configured max payload size fails with a 4.13
 * response code.
 *
 * @param ctx The test context.
 * @throws IOException if the CoAP request cannot be sent to the adapter.
 * @throws ConnectorException  if the CoAP request cannot be sent to the adapter.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadFailsForLargePayload(final VertxTestContext ctx) throws ConnectorException, IOException {

    final Tenant tenant = new Tenant();

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .compose(ok -> {
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Request request = createCoapsRequest(Code.POST, Type.CON, getPostResource(), IntegrationTestSupport.getPayload(4096));
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.REQUEST_ENTITY_TOO_LARGE), request);
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #6
Source File: TelemetryCoapIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a number of telemetry messages uploaded to Hono's CoAP adapter
 * using QoS 1 can be successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadUsingQoS1(final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);

    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapsRequest(Code.POST, Type.CON, getPostResource(), 0)),
            count -> {
        final Promise<OptionSet> result = Promise.promise();
        final Request request = createCoapsRequest(Code.POST, Type.CON, getPostResource(), count);
        client.advanced(getHandler(result), request);
        return result.future();
    });
}
 
Example #7
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a gateway for a device that it is not authorized for with a
 * 403.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForUnauthorizedGateway(final VertxTestContext ctx) {

    // GIVEN a device that is connected via gateway "not-the-created-gateway"
    final Tenant tenant = new Tenant();
    final String gatewayId = helper.getRandomDeviceId(tenantId);
    final Device deviceData = new Device();
    deviceData.setVia(Collections.singletonList("not-the-created-gateway"));

    helper.registry.addPskDeviceForTenant(tenantId, tenant, gatewayId, SECRET)
    .compose(ok -> helper.registry.registerDevice(tenantId, deviceId, deviceData))
    .compose(ok -> {

        // WHEN another gateway tries to upload a message for the device
        final Promise<OptionSet> result = Promise.promise();
        final CoapClient client = getCoapsClient(gatewayId, tenantId, SECRET);
        client.advanced(getHandler(result, ResponseCode.FORBIDDEN),
                createCoapsRequest(Code.PUT, getPutResource(tenantId, deviceId), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #8
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a disabled gateway
 * for an enabled device with a 403.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledGateway(final VertxTestContext ctx) {

    // GIVEN a device that is connected via a disabled gateway
    final Tenant tenant = new Tenant();
    final String gatewayId = helper.getRandomDeviceId(tenantId);
    final Device gatewayData = new Device();
    gatewayData.setEnabled(false);
    final Device deviceData = new Device();
    deviceData.setVia(Collections.singletonList(gatewayId));

    helper.registry.addPskDeviceForTenant(tenantId, tenant, gatewayId, gatewayData, SECRET)
    .compose(ok -> helper.registry.registerDevice(tenantId, deviceId, deviceData))
    .compose(ok -> {

        // WHEN the gateway tries to upload a message for the device
        final Promise<OptionSet> result = Promise.promise();
        final CoapClient client = getCoapsClient(gatewayId, tenantId, SECRET);
        client.advanced(getHandler(result, ResponseCode.FORBIDDEN), createCoapsRequest(Code.PUT, getPutResource(tenantId, deviceId), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #9
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a disabled device.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledDevice(final VertxTestContext ctx) {

    // GIVEN a disabled device
    final Tenant tenant = new Tenant();
    final Device deviceData = new Device();
    deviceData.setEnabled(false);

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, deviceData, SECRET)
    .compose(ok -> {

        // WHEN the device tries to upload a message
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.NOT_FOUND), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #10
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the CoAP adapter rejects messages from a device that belongs to a tenant for which the CoAP adapter
 * has been disabled.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledTenant(final VertxTestContext ctx) {

    // GIVEN a tenant for which the CoAP adapter is disabled
    final Tenant tenant = new Tenant();
    tenant.addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_COAP).setEnabled(false));

    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .compose(ok -> {

        // WHEN a device that belongs to the tenant uploads a message
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.FORBIDDEN), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.completing());
}
 
Example #11
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter fails to authenticate a device if the shared key registered
 * for the device does not match the key used by the device in the DTLS handshake.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadFailsForNonMatchingSharedKey(final VertxTestContext ctx) {

    final Tenant tenant = new Tenant();

    // GIVEN a device for which PSK credentials have been registered
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, "NOT" + SECRET)
    .compose(ok -> {
        // WHEN a device tries to upload data and authenticate using the PSK
        // identity for which the server has a different shared secret on record
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result), createCoapsRequest(Code.POST, getPostResource(), 0));
        return result.future();
    })
    .onComplete(ctx.failing(t -> {
        // THEN the request fails because the DTLS handshake cannot be completed
        assertStatus(ctx, HttpURLConnection.HTTP_UNAVAILABLE, t);
        ctx.completeNow();
    }));
}
 
Example #12
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a number of messages uploaded to Hono's CoAP adapter
 * can be successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesAnonymously(final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapClient();
    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapRequest(Code.PUT, getPutResource(tenantId, deviceId), 0)),
            count -> {
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapRequest(Code.PUT, getPutResource(tenantId, deviceId), count);
                client.advanced(getHandler(result), request);
                return result.future();
            });
}
 
Example #13
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #14
Source File: Main.java    From TRADFRI2MQTT with Apache License 2.0 6 votes vote down vote up
private void set(String uriString, String payload) {
	//System.out.println("payload\n" + payload);
	try {
		URI uri = new URI(uriString);
		CoapClient client = new CoapClient(uri);
		client.setEndpoint(endPoint);
		CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN);
		if (response != null && response.isSuccess()) {
			//System.out.println("Yay");
		} else {
			System.out.println("Sending payload to " + uriString + " failed!");
		}
		client.shutdown();
	} catch (URISyntaxException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #15
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a number of messages uploaded to Hono's CoAP adapter using TLS_PSK based authentication can be
 * successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesUsingPsk(final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET)
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);

    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapsRequest(Code.POST, getPostResource(), 0)),
            count -> {
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapsRequest(Code.POST, getPostResource(), count);
                client.advanced(getHandler(result), request);
                return result.future();
            });
}
 
Example #16
Source File: TradfriGateway.java    From ThingML-Tradfri with Apache License 2.0 5 votes vote down vote up
protected void set(String path, String payload) {
           Logger.getLogger(TradfriGateway.class.getName()).log(Level.INFO, "SET: " + "coaps://" + gateway_ip + "/" + path + " = " + payload);
           CoapClient client = new CoapClient("coaps://" + gateway_ip + "/" + path);
           client.setEndpoint(coap);
           CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN);
           if (response != null && response.isSuccess()) {
                   //System.out.println("Yay");
           } else {
                   logger.log(Level.SEVERE, "Sending payload to " + "coaps://" + gateway_ip + "/" + path + " failed!");
           }
           client.shutdown();
}
 
Example #17
Source File: CoAPWrapper.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
public void run(){
       
 	client = new CoapClient(serverURI);
     
     while(isActive()){
     	if (System.currentTimeMillis() / 1000 > nextExpectedMessage){
     	    client.observe(this);
     	}
   try{
     Thread.sleep(60000);
   }catch(Exception ex){}
}           
 }
 
Example #18
Source File: TestCoapServerPushSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testSource() throws Exception {
  CoapServerConfigs coapServerConfigs = new CoapServerConfigs();
  coapServerConfigs.resourceName = () -> "sdc";
  coapServerConfigs.port = NetworkUtils.getRandomPort();
  coapServerConfigs.maxConcurrentRequests = 1;
  CoapServerPushSource source =
      new CoapServerPushSource(coapServerConfigs, DataFormat.TEXT, new DataParserFormatConfig());
  final PushSourceRunner runner =
      new PushSourceRunner.Builder(CoapServerDPushSource.class, source).addOutputLane("a").build();
  runner.runInit();
  try {
    final List<Record> records = new ArrayList<>();
    runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
      @Override
      public void processBatch(StageRunner.Output output) {
        records.clear();
        records.addAll(output.getRecords().get("a"));
        runner.setStop();
      }
    });

    URI coapURI = new URI("coap://localhost:" + coapServerConfigs.port + "/" + coapServerConfigs.resourceName.get());
    CoapClient client = new CoapClient(coapURI);
    CoapResponse response = client.post("Hello", MediaTypeRegistry.TEXT_PLAIN);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getCode(), CoAP.ResponseCode.VALID);

    runner.waitOnProduce();
    Assert.assertEquals(1, records.size());
    Assert.assertEquals("Hello", records.get(0).get("/text").getValue());

  } finally {
    runner.runDestroy();
  }
}
 
Example #19
Source File: CoapClientTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private CoapClient getCoapClient() throws URISyntaxException {
  URI coapURI = new URI(conf.resourceUrl);
  CoapClient coapClient = new CoapClient(coapURI);
  coapClient.setTimeout(conf.connectTimeoutMillis);
  if (conf.requestType == RequestType.NONCONFIRMABLE) {
    coapClient.useNONs();
  } else if (conf.requestType == RequestType.CONFIRMABLE) {
    coapClient.useCONs();
  }
  // TODO: coaps (DTLS Support) - https://issues.streamsets.com/browse/SDC-5893
  return coapClient;
}
 
Example #20
Source File: LinuxKernel.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public static void main(String args[]) throws Exception {
		String base = "";
		String myIP = "127.0.0.1";
		for (String arg : args) {
				String[] prm = arg.split("=");
				if (prm[0].equals("base") ){
						base = prm[1];
				}
				else if (prm[0].equals("myip") ){
						myIP = prm[1];
				}
		}
		LinuxKernel k = new LinuxKernel();

		if (base.equals("") == false) {
				String mapAsString = "Active Drivers\n";
				Set keys = k.n2p.keySet();
				for (Iterator i = keys.iterator(); i.hasNext(); ) {
						String name = (String) i.next();
						String value = (String) k.n2p.get(name);
						name = myIP + ":" + name;
						value = myIP + ":" + value;
						mapAsString = mapAsString + name + " --> " + value + "\n";
				}

				CoapClient client = new CoapClient("coap://"+base+":5117/cr");
				CoapResponse response = client.put("dn=add-"+mapAsString,0);//create response
				System.out.println(response);
		}

}
 
Example #21
Source File: CaptureImageV2Driver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public String invokeDriver(String dn, String params, CoapHandler ch) {
	params = params + "-dp=" + "AUAVsim";
	if(this.d2p == null) {
		try {
			URI portStr = new URI("coap://127.0.0.1:5117/cr");
			CoapClient e = new CoapClient(portStr);
			CoapResponse client = e.put("dn=list", 0);
			String ls = client.getResponseText();
			this.d2p = new HashMap();
			String[] lines = ls.split("\n");

			for(int x = 0; x < lines.length; ++x) {
				String[] data = lines[x].split("-->");
				if(data.length == 2) {
					this.d2p.put(data[0].trim(), data[1].trim());
				}
			}
		} catch (Exception var12) {
			this.d2p = null;
			System.out.println("AUAVRoutine invokeDriver error");
			var12.printStackTrace();
			return "Invoke Error";
		}
	}

	if(this.d2p != null) {
		String var13 = (String)this.d2p.get(dn);
		if(var13 != null) {
			try {
				URI var14 = new URI("coap://127.0.0.1:" + var13 + "/cr");
				CoapClient var15 = new CoapClient(var14);
				var15.put(ch, params, 0);
				return "Success";
			} catch (Exception var11) {
				return "Unable to reach driver " + dn + "  at port: " + var13;
			}
		} else {
			return "Unable to find driver: " + dn;
		}
	} else {
		return "InvokeDriver: Unreachable code touched";
	}
}
 
Example #22
Source File: TradfriGateway.java    From ThingML-Tradfri with Apache License 2.0 5 votes vote down vote up
protected CoapResponse get(String path) {
               Logger.getLogger(TradfriGateway.class.getName()).log(Level.INFO, "GET: " + "coaps://" + gateway_ip + "/" + path);
	CoapClient client = new CoapClient("coaps://" + gateway_ip + "/" + path);
	client.setEndpoint(coap);
	CoapResponse response = client.get(1);
	if (response == null) {
		logger.log(Level.SEVERE, "Connection to Gateway timed out, please check ip address or increase the ACK_TIMEOUT in the Californium.properties file");
	}
	return response;
}
 
Example #23
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
void requestPutCOAP(String topic, String payload) {
    LOGGER.log(Level.FINE, "requext PUT COAP: {0}, {1}", new Object[]{topic, payload});
    try {
        URI uri = new URI("coaps://" + coapIP + "/" + topic);
        CoapClient client = new CoapClient(uri);
        client.setEndpoint(coapEndPoint);
        CoapResponse response = client.put(payload, MediaTypeRegistry.TEXT_PLAIN);
        if (response == null || !response.isSuccess()) {
            LOGGER.log(Level.WARNING, "COAP PUT error: {0}", response.getResponseText());
        }
        client.shutdown();
    } catch (URISyntaxException ex) {
        LOGGER.log(Level.WARNING, "COAP PUT error: {0}", ex.getMessage());
    }
}
 
Example #24
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates the client to use for uploading data to the secure endpoint
 * of the CoAP adapter.
 *
 * @param pskStoreToUse The store to retrieve shared secrets from.
 * @return The client.
 */
protected CoapClient getCoapsClient(final PskStore pskStoreToUse) {

    final DtlsConnectorConfig.Builder dtlsConfig = new DtlsConnectorConfig.Builder();
    dtlsConfig.setAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
    dtlsConfig.setPskStore(pskStoreToUse);
    dtlsConfig.setMaxRetransmissions(1);
    final CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
    builder.setNetworkConfig(NetworkConfig.createStandardWithoutFile());
    builder.setConnector(new DTLSConnector(dtlsConfig.build()));
    return new CoapClient().setEndpoint(builder.build());
}
 
Example #25
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a number of messages uploaded to the CoAP adapter via a gateway
 * using TLS_PSK can be successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesViaGateway(final VertxTestContext ctx) throws InterruptedException {

    // GIVEN a device that is connected via two gateways
    final Tenant tenant = new Tenant();
    final String gatewayOneId = helper.getRandomDeviceId(tenantId);
    final String gatewayTwoId = helper.getRandomDeviceId(tenantId);
    final Device deviceData = new Device();
    deviceData.setVia(Arrays.asList(gatewayOneId, gatewayTwoId));

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addPskDeviceForTenant(tenantId, tenant, gatewayOneId, SECRET)
    .compose(ok -> helper.registry.addPskDeviceToTenant(tenantId, gatewayTwoId, SECRET))
    .compose(ok -> helper.registry.registerDevice(tenantId, deviceId, deviceData))
    .onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient gatewayOne = getCoapsClient(gatewayOneId, tenantId, SECRET);
    final CoapClient gatewayTwo = getCoapsClient(gatewayTwoId, tenantId, SECRET);

    testUploadMessages(ctx, tenantId,
            () -> warmUp(gatewayOne, createCoapsRequest(Code.PUT, getPutResource(tenantId, deviceId), 0)),
            count -> {
                final CoapClient client = (count.intValue() & 1) == 0 ? gatewayOne : gatewayTwo;
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapsRequest(Code.PUT, getPutResource(tenantId, deviceId), count);
                client.advanced(getHandler(result), request);
                return result.future();
            });
}
 
Example #26
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the CoAP adapter delivers a one-way command to a device.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The test context
 * @throws InterruptedException if the test fails.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("commandAndControlVariants")
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessagesWithTtdThatReplyWithOneWayCommand(
        final CoapCommandEndpointConfiguration endpointConfig,
        final VertxTestContext ctx) throws InterruptedException {

    final Tenant tenant = new Tenant();
    final String expectedCommand = String.format("%s=%s", Constants.HEADER_COMMAND, COMMAND_TO_SEND);

    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET).onComplete(setup.completing());
    ctx.verify(() -> assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue());

    final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
    final AtomicInteger counter = new AtomicInteger();

    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway()
            ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5)
            : deviceId;
    final String subscribingDeviceId = endpointConfig.isSubscribeAsGatewayForSingleDevice() ? commandTargetDeviceId
            : deviceId;

    testUploadMessages(ctx, tenantId,
            () -> warmUp(client, createCoapsRequest(Code.POST, getPostResource(), 0)),
            msg -> {
                final Integer ttd = MessageHelper.getTimeUntilDisconnect(msg);
                logger.debug("north-bound-cmd received {}, ttd: {}", msg, ttd);
                TimeUntilDisconnectNotification.fromMessage(msg).ifPresent(notification -> {
                    ctx.verify(() -> {
                        assertThat(notification.getTenantId()).isEqualTo(tenantId);
                        assertThat(notification.getDeviceId()).isEqualTo(subscribingDeviceId);
                    });
                    logger.debug("send one-way-command");
                    final JsonObject inputData = new JsonObject().put(COMMAND_JSON_KEY, (int) (Math.random() * 100));
                    helper.sendOneWayCommand(
                            tenantId,
                            commandTargetDeviceId,
                            COMMAND_TO_SEND,
                            "application/json",
                            inputData.toBuffer(),
                            // set "forceCommandRerouting" message property so that half the command are rerouted via the AMQP network
                            IntegrationTestSupport.newCommandMessageProperties(() -> counter.getAndIncrement() >= MESSAGES_TO_SEND / 2),
                            notification.getMillisecondsUntilExpiry() / 2);
                });
            },
            count -> {
                final Promise<OptionSet> result = Promise.promise();
                final Request request = createCoapsRequest(endpointConfig, commandTargetDeviceId, count);
                request.getOptions().addUriQuery(String.format("%s=%d", Constants.HEADER_TIME_TILL_DISCONNECT, 4));
                logger.debug("south-bound send {}", request);
                client.advanced(getHandler(result, ResponseCode.CHANGED), request);
                return result.future()
                        .map(responseOptions -> {
                            ctx.verify(() -> {
                                assertResponseContainsOneWayCommand(
                                        endpointConfig,
                                        responseOptions,
                                        expectedCommand,
                                        tenantId,
                                        commandTargetDeviceId);
                            });
                            return responseOptions;
                        });
            });
}
 
Example #27
Source File: HelloWorldClient.java    From hands-on-coap with Eclipse Public License 1.0 4 votes vote down vote up
public static void main(String[] args) {

        CoapClient client = new CoapClient("coap://localhost/Hello");
        
        CoapResponse response = client.get();
        
        if (response!=null) {
        
        	System.out.println( response.getCode() );
        	System.out.println( response.getOptions() );
        	System.out.println( response.getResponseText() );
        	
        } else {
        	
        	System.out.println("Request failed");
        	
        }
    }
 
Example #28
Source File: HelloWorldClient.java    From hands-on-coap with Eclipse Public License 1.0 4 votes vote down vote up
public static void main(String[] args) {
    CoapClient client = new CoapClient();
    // TOOD :)
}
 
Example #29
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Sends some (optional) messages before uploading the batch of
 * real test messages.
 *
 * @param client The CoAP client to use for sending the messages.
 * @return A succeeded future upon completion.
 */
protected Future<Void> sendWarmUpMessages(final CoapClient client) {
    return Future.succeededFuture();
}
 
Example #30
Source File: CoapTestBase.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates the client to use for uploading data to the insecure endpoint
 * of the CoAP adapter.
 *
 * @return The client.
 */
protected CoapClient getCoapClient() {
    return new CoapClient();
}