org.eclipse.californium.core.CoapResponse Java Examples
The following examples show how to use
org.eclipse.californium.core.CoapResponse.
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: TradfriCoapHandler.java From smarthome with Eclipse Public License 2.0 | 6 votes |
@Override public void onLoad(CoapResponse response) { logger.debug("CoAP response\noptions: {}\npayload: {}", response.getOptions(), response.getResponseText()); if (response.isSuccess()) { if (callback != null) { try { callback.onUpdate(parser.parse(response.getResponseText())); callback.setStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE); } catch (JsonParseException e) { logger.warn("Observed value is no valid json: {}, {}", response.getResponseText(), e.getMessage()); } } if (future != null) { String data = response.getResponseText(); future.complete(data); } } else { logger.debug("CoAP error {}", response.getCode()); if (callback != null) { callback.setStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR); } if (future != null) { future.completeExceptionally(new RuntimeException("Response " + response.getCode().toString())); } } }
Example #2
Source File: HCoapClient.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
public OneM2mResponse process(OneM2mRequest reqMessage) throws Exception { OneM2mResponse resMessage = null; // try { Request request = CoapRequestCodec.encode(reqMessage); log.debug("SEND CoAP MESSAGE: "); log.debug(reqMessage.toString()); log.debug(request.getPayloadString()); CoapResponse response = client.advanced(request); if(response == null) { log.error("response is null"); return null; } resMessage = CoapResponseCodec.decode(response); // } catch (Exception e) { // e.printStackTrace(); // } return resMessage; }
Example #3
Source File: HCoapClient.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
public OneM2mResponse process(OneM2mRequest reqMessage) throws Exception { OneM2mResponse resMessage = null; // try { Request request = CoapRequestCodec.encode(reqMessage); log.debug("SEND CoAP MESSAGE: "); log.debug(reqMessage.toString()); log.debug(request.getPayloadString()); CoapResponse response = client.advanced(request); if(response == null) { log.error("response is null"); return null; } resMessage = CoapResponseCodec.decode(response); // } catch (Exception e) { // e.printStackTrace(); // } return resMessage; }
Example #4
Source File: ManagerTradfri.java From helloiot with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: ManagerTradfri.java From helloiot with GNU General Public License v3.0 | 6 votes |
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 #6
Source File: ManagerTradfri.java From helloiot with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: Main.java From TRADFRI2MQTT with Apache License 2.0 | 6 votes |
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 #8
Source File: CoapTestBase.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * 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 #9
Source File: CoapTestBase.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Gets a handler for CoAP responses. * * @param responseHandler The handler to invoke with the outcome of the request. the handler will be invoked with a * succeeded result if the response contains the expected code. Otherwise it will be invoked with a * result that is failed with a {@link CoapResultException}. * @param expectedStatusCode The status code that is expected in the response. * @return The handler. */ protected final CoapHandler getHandler(final Handler<AsyncResult<OptionSet>> responseHandler, final ResponseCode expectedStatusCode) { return new CoapHandler() { @Override public void onLoad(final CoapResponse response) { if (response.getCode() == expectedStatusCode) { logger.debug("=> received {}", Utils.prettyPrint(response)); responseHandler.handle(Future.succeededFuture(response.getOptions())); } else { logger.warn("expected {} => received {}", expectedStatusCode, Utils.prettyPrint(response)); responseHandler.handle(Future.failedFuture( new CoapResultException(toHttpStatusCode(response.getCode()), response.getResponseText()))); } } @Override public void onError() { responseHandler .handle(Future.failedFuture(new CoapResultException(HttpURLConnection.HTTP_UNAVAILABLE))); } }; }
Example #10
Source File: AuavRoutines.java From SoftwarePilot with MIT License | 5 votes |
AUAVHandler () { ch = new CoapHandler() { @Override public void onLoad(CoapResponse response) { resp = response.getResponseText(); auavLock("continue"); } @Override public void onError() { resp = "CoapHandler Error"; System.out.println("RoutineLock: " +auavLock+"-FAILED"); auavLock("continue"); }}; }
Example #11
Source File: HCoapClient.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void onLoad(CoapResponse response) { if (listener != null) { OneM2mResponse resMessage; try { resMessage = CoapResponseCodec.decode(response); listener.receiveResponse(resMessage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Example #12
Source File: TestCoapServerPushSource.java From datacollector with Apache License 2.0 | 5 votes |
@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 #13
Source File: HCoapClient.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void onLoad(CoapResponse response) { if (listener != null) { OneM2mResponse resMessage; try { resMessage = CoapResponseCodec.decode(response); listener.receiveResponse(resMessage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Example #14
Source File: ManagerTradfri.java From helloiot with GNU General Public License v3.0 | 5 votes |
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 #15
Source File: TradfriGateway.java From ThingML-Tradfri with Apache License 2.0 | 5 votes |
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 #16
Source File: TradfriGateway.java From ThingML-Tradfri with Apache License 2.0 | 5 votes |
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: LinuxKernel.java From SoftwarePilot with MIT License | 5 votes |
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 #18
Source File: CaptureImageV2Driver.java From SoftwarePilot with MIT License | 5 votes |
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 #19
Source File: CoAPWrapper.java From gsn with GNU General Public License v3.0 | 4 votes |
@Override public void onLoad(CoapResponse response) { OptionSet os = response.getOptions(); nextExpectedMessage = os.getMaxAge() * 2 + (System.currentTimeMillis() / 1000); postStreamElement(new Serializable[]{response.getPayload()}); }
Example #20
Source File: HelloWorldClient.java From hands-on-coap with Eclipse Public License 1.0 | 4 votes |
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 #21
Source File: CoapResponseCodec.java From SI with BSD 2-Clause "Simplified" License | 4 votes |
public static OneM2mResponse decode(CoapResponse resCoap) throws Exception { OneM2mResponse resMessage = new OneM2mResponse(); if (resCoap.advanced().getSource().getHostName() != null) { resMessage.setRemoteHost(resCoap.advanced().getSource().getHostName()); } for (Option option : resCoap.getOptions().asSortedList()) { int number = option.getNumber(); String value = option.getStringValue().trim(); switch(number) { case OptionNumberRegistry.CONTENT_FORMAT: CONTENT_TYPE type = COAP_CONTENT_TYPE.getContentType(option.getIntegerValue()); if(type != null && type != CONTENT_TYPE.NONE) { resMessage.setContentType(type); } break; case ONEM2M_RSC: resMessage.setResponseStatusCode(option.getIntegerValue()); break; case ONEM2M_RQI: resMessage.setRequestIdentifier(value); break; case ONEM2M_FR: resMessage.setFrom(value); break; case ONEM2M_OT: resMessage.setOriginatingTimestamp(value); break; case ONEM2M_RSET: resMessage.setResultExpirationTimestamp(value); break; case ONEM2M_EC: resMessage.setEventCategory(option.getIntegerValue()); break; } } if (resCoap.getPayload() != null && resCoap.getPayload().length > 0) { resMessage.setContent(resCoap.getPayload()); } return resMessage; }
Example #22
Source File: CaptureImageV2Driver.java From SoftwarePilot with MIT License | 4 votes |
@Override public void onLoad(CoapResponse response) { resp = response.getResponseText(); drvUnsetLock(); }
Example #23
Source File: CameraRoutine.java From SoftwarePilot with MIT License | 4 votes |
@Override public void onLoad(CoapResponse response) { resp = response.getResponseText(); rtnLock("barrier-1"); }
Example #24
Source File: CoapClientTarget.java From datacollector with Apache License 2.0 | 4 votes |
@Override public void write(Batch batch) throws StageException { Iterator<Record> records = batch.getRecords(); while (records.hasNext()) { Record record = records.next(); CoapResponse response = null; HttpMethod method = conf.coapMethod; int contentType = getContentType(); try { if (method == HttpMethod.POST || method == HttpMethod.PUT) { ByteArrayOutputStream byteBufferOutputStream = new ByteArrayOutputStream(); try (DataGenerator dataGenerator = generatorFactory.getGenerator(byteBufferOutputStream)) { dataGenerator.write(record); dataGenerator.flush(); if (conf.dataFormat == DataFormat.TEXT) { response = coapClient.post(byteBufferOutputStream.toString(), contentType); } else { response = coapClient.post(byteBufferOutputStream.toByteArray(), contentType); } } } else if (method == HttpMethod.GET ) { response = coapClient.get(); } else if (method == HttpMethod.DELETE ) { response = coapClient.delete(); } if (response == null) { errorRecordHandler.onError( new OnRecordErrorException( record, Errors.COAP_02 ) ); } else if (!response.isSuccess()) { errorRecordHandler.onError( new OnRecordErrorException( record, Errors.COAP_00, response.getCode(), response.getResponseText() ) ); } } catch (Exception ex) { LOG.error(Errors.COAP_01.getMessage(), ex.toString(), ex); throw new OnRecordErrorException(record, Errors.COAP_01, ex.toString()); } } }
Example #25
Source File: CoapResponseCodec.java From SI with BSD 2-Clause "Simplified" License | 4 votes |
public static OneM2mResponse decode(CoapResponse resCoap) throws Exception { OneM2mResponse resMessage = new OneM2mResponse(); if (resCoap.advanced().getSource().getHostName() != null) { resMessage.setRemoteHost(resCoap.advanced().getSource().getHostName()); } for (Option option : resCoap.getOptions().asSortedList()) { int number = option.getNumber(); String value = option.getStringValue().trim(); switch(number) { case OptionNumberRegistry.CONTENT_FORMAT: CONTENT_TYPE type = COAP_CONTENT_TYPE.getContentType(option.getIntegerValue()); if(type != null && type != CONTENT_TYPE.NONE) { resMessage.setContentType(type); } break; case ONEM2M_RSC: resMessage.setResponseStatusCode(option.getIntegerValue()); break; case ONEM2M_RQI: resMessage.setRequestIdentifier(value); break; case ONEM2M_FR: resMessage.setFrom(value); break; case ONEM2M_OT: resMessage.setOriginatingTimestamp(value); break; case ONEM2M_RSET: resMessage.setResultExpirationTimestamp(value); break; case ONEM2M_EC: resMessage.setEventCategory(option.getIntegerValue()); break; } } if (resCoap.getPayload() != null && resCoap.getPayload().length > 0) { resMessage.setContent(resCoap.getPayload()); } return resMessage; }
Example #26
Source File: MakeTrace.java From SoftwarePilot with MIT License | 4 votes |
@Override public void onLoad(CoapResponse response) { }
Example #27
Source File: LightBulb.java From ThingML-Tradfri with Apache License 2.0 | 4 votes |
public LightBulb(int id, TradfriGateway gateway, CoapResponse response) { this.id = id; this.gateway = gateway; if (response != null) parseResponse(response); }
Example #28
Source File: LightBulb.java From ThingML-Tradfri with Apache License 2.0 | 4 votes |
protected void updateBulb() { CoapResponse response = gateway.get(TradfriConstants.DEVICES + "/" + id); if (response != null) parseResponse(response); }
Example #29
Source File: LightBulb.java From ThingML-Tradfri with Apache License 2.0 | 4 votes |
protected void parseResponse(CoapResponse response) { boolean updateListeners = false; gateway.getLogger().log(Level.INFO, response.getResponseText()); try { JSONObject json = new JSONObject(response.getResponseText()); jsonObject = json; String new_name = json.getString(TradfriConstants.NAME); if (name == null || !name.equals(new_name)) updateListeners = true; name = new_name; dateInstalled = new Date(json.getLong(TradfriConstants.DATE_INSTALLED)*1000); dateLastSeen = new Date(json.getLong(TradfriConstants.DATE_LAST_SEEN)*1000); boolean new_online = json.getInt(TradfriConstants.DEVICE_REACHABLE) != 0; if (new_online != online) updateListeners = true; online = new_online; manufacturer = json.getJSONObject("3").getString("0"); type = json.getJSONObject("3").getString("1"); firmware = json.getJSONObject("3").getString("3"); JSONObject light = json.getJSONArray(TradfriConstants.LIGHT).getJSONObject(0); if (light.has(TradfriConstants.ONOFF) && light.has(TradfriConstants.DIMMER)) { boolean new_on = (light.getInt(TradfriConstants.ONOFF) != 0); int new_intensity = light.getInt(TradfriConstants.DIMMER); if (on != new_on) updateListeners = true; if (intensity != new_intensity) updateListeners = true; on = new_on; intensity = new_intensity; } else { if (online) updateListeners = true; online = false; } if (light.has(TradfriConstants.COLOR)) { String new_color = light.getString(TradfriConstants.COLOR); if (color == null || !color.equals(new_color)) updateListeners = true; color = new_color; } } catch (JSONException e) { System.err.println("Cannot update bulb info: error parsing the response from the gateway."); e.printStackTrace(); } if (updateListeners) { for (TradfriBulbListener l : listners) l.bulb_state_changed(this); } }
Example #30
Source File: CoapHandler.java From SI with BSD 2-Clause "Simplified" License | 2 votes |
/** * Invoked when a CoAP response or notification has arrived. * * @param response the response */ public void onLoad(CoapResponse response);