List of usage examples for io.vertx.core.json JsonObject getJsonObject
public JsonObject getJsonObject(String key)
From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java
License:Apache License
/** * Collect all readings from a list of devices. (result is saved in deviceReadings) * * @param devices List of devices to read from. *//*from www . j av a2 s .c om*/ private void collectDevicesReadings(List<JsonObject> devices) { String hwId = null; String time; String value; JsonObject reading; JsonObject readings; Instant commandsWrittenTime; for (JsonObject device : devices) { try { hwId = device.getString("hwId"); // Do a blocking reading. value = readValue(device); time = LocalDateTime.now().toString(); logger.trace( "Read value '{}' from device with hwId '{}' on Owserver at {}:{} with adapter id \"{}\".", value, hwId, this.host, this.port, this.getId()); reading = new JsonObject().put("hwId", hwId).put("value", value).put("time", time); // Get hold of array of recorded readings for this specific device. if (!deviceReadings.containsKey(hwId)) { readings = new JsonObject().put("lastReading", new JsonObject().put("value", (Object) null) // Set property to prevent a possible nullpointer exception later. ); deviceReadings.put(hwId, readings); } else { readings = deviceReadings.get(hwId); } String lastValue = readings.getJsonObject("lastReading").getString("value"); // Only add this reading to list of readings for device if the value of the reading has changed since the last time we did a reading. We save a lot of space and memory by doing this! if (!value.equals(lastValue)) { readings.put("lastReading", reading); logger.debug( "Recorded new value '{}' at time '{}' for device with hwId '{}' on Owserver at {}:{} with adapter id \"{}\".", value, time, hwId, this.host, this.port, this.getId()); List<JsonObject> childs = getChildDevicesOnly(hwId); if (childs.isEmpty()) { // This device has no children, so we just notify that this device has a value that has changed. JsonObject broadcast = new JsonObject().put("adapterId", this.getId()) .put("port", this.port).put("host", this.host).put("reading", reading); vertx.eventBus().publish(AdapterEvents.EVENTBUS_ADAPTERS, broadcast, new DeliveryOptions().addHeader("action", AdapterEvents.EVENT_DEVICE_NEWREADING)); } else { // This is a parent device so we must check which of its children that has changed and notify each and every one of them on the bus. String[] childValues = value.split(","); String[] lastChildValues; if (lastValue == null) { lastChildValues = new String[childValues.length]; } else { lastChildValues = lastValue.split(","); } for (int i = 0; i < childValues.length; i++) { if (!childValues[i].equals(lastChildValues[i])) { JsonObject broadcast = new JsonObject().put("adapterId", this.getId()) .put("port", this.port).put("host", this.host).put("reading", new JsonObject().put("hwId", childs.get(i).getString("hwId")) .put("time", reading.getString("time")) .put("value", childValues[i])); vertx.eventBus().publish(AdapterEvents.EVENTBUS_ADAPTERS, broadcast, new DeliveryOptions().addHeader("action", AdapterEvents.EVENT_DEVICE_NEWREADING)); } } } } } catch (Exception ex) { logger.error("Failed to poll device '{}' for value on Owserver at {}:{} with adapter id \"{}\".", hwId, this.host, this.port, this.getId()); } // Execute possible queued commands between each iteration. This is necessary since a reading from several parasitic devices could take many seconds to complete. commandsWrittenTime = Instant.now(); executeQueuedCommands(); commandsWrittenDuration.plus(Duration.between(commandsWrittenTime, Instant.now())); } }
From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java
License:Apache License
/** * Read value from device with specified hwId. * * @param hwId Id on device/* w ww . ja v a 2 s .c o m*/ * @return device last recorded value. * @throws DeviceMissingException throws exception if specified device does not exist. */ private JsonObject getDeviceValue(String hwId) throws DeviceMissingException { if (hwId == null || !deviceLookup.containsKey(hwId)) { throw new DeviceMissingException("Trying to perform a action on a non existing device.", hwId); } // Check if child device. if (!hwId.contains(CHILDSEPARATOR)) { JsonObject reading = this.deviceReadings.get(hwId); JsonObject response = new JsonObject().put("reading", reading); return response; } else { JsonObject response; JsonObject reading = this.deviceReadings.get(hwId.split(CHILDSEPARATOR)[0]); // Get value from parent. if (reading == null) { response = new JsonObject().put("reading", (JsonObject) null); } else { int index = Integer.parseInt(hwId.split(CHILDSEPARATOR)[1]) - 1; // Get child idsuffix. String value = reading.getJsonObject("lastReading").getString("value").split(",")[index]; // Get child reading from parent reading. response = new JsonObject().put("reading", new JsonObject().put("hwId", hwId) .put("time", reading.getJsonObject("lastReading").getString("time")).put("value", value)); } return response; } }
From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java
License:Apache License
/** * Set value on device with specified hwId. * * @param hwId Id on device/*from w w w . j a va2s . c o m*/ * @param value value to set on device. * @throws DeviceMissingException throws exception if specified device does not exist. * @throws OwServerConnectionException throws exception if command fails for any reason. */ private void setDeviceValue(String hwId, String value) throws DeviceMissingException, OwServerConnectionException { if (hwId == null || !deviceLookup.containsKey(hwId)) { throw new DeviceMissingException("Trying to perform a action on a non existing device.", hwId); } if (hwId.contains(CHILDSEPARATOR)) { String parentId = hwId.split(CHILDSEPARATOR)[0]; String childSuffix = hwId.split(CHILDSEPARATOR)[1]; JsonObject parentDevice = deviceLookup.get(parentId); JsonObject typeInfo = parentDevice.getJsonObject("typeInfo"); if (typeInfo == null) { throw new OwServerConnectionException(String.format("typeInfo missing for device with type '%s'", parentDevice.getString("type"))); } JsonArray childDevices = typeInfo.getJsonArray("childDevices"); if (childDevices != null && childDevices.size() > 0) { String writePath = childDevices.stream().filter(t -> t instanceof JsonObject) .map(t -> (JsonObject) t).filter((d) -> d.getString("idSuffix").equals(childSuffix)) .map((cd) -> cd.getString("valueWritePath")).findFirst().get(); writePath = parentDevice.getString("path") + writePath; // Queue command. Record time so we could measure how long command has been queued before executed, if we want to. this.commandQueue.offer(new JsonObject().put("path", writePath).put("value", value).put("nanoTime", System.nanoTime())); } } else { JsonObject device = deviceLookup.get(hwId); JsonObject typeInfo = device.getJsonObject("typeInfo"); if (typeInfo == null) { throw new OwServerConnectionException( String.format("typeInfo missing for device with type '%s'", device.getString("type"))); } // Check if this type of device is writable. if (typeInfo.containsKey("valueWritePath")) { String writePath = device.getString("path") + typeInfo.getString("valueWritePath"); // Queue command. Record time so we could measure how long command has been queued before executed, if we want to. this.commandQueue.offer(new JsonObject().put("path", writePath).put("value", value).put("nanoTime", System.nanoTime())); } } }
From source file:se.liquidbytes.jel.system.device.DeviceManager.java
License:Apache License
/** * Retrieve the current value of an result using specified result id. * * @param deviceId id of existing result. * @param resultHandler//w ww .java 2 s . com */ public void retrieveDeviceValue(String deviceId, Handler<AsyncResult<JsonObject>> resultHandler) { DeliveryOptions options = new DeliveryOptions(); options.addHeader("action", "retrieveDeviceValue"); JsonObject device = allDevices.get(deviceId); if (device == null) { resultHandler.handle(Future.failedFuture(String.format("Device with id %s does not exist.", deviceId))); return; } DeployedAdapter adapter = JelService.adapterManager().getAdapter(device.getString("adapterId")); if (adapter == null) { resultHandler.handle(Future.failedFuture( String.format("Adapter with id %s does not exist.", device.getString("adapterId")))); return; } // Send message to adapter to report back its devices. JelService.vertx().eventBus() .send(String.format("%s.%s@%s:%d", AdapterEvents.EVENTBUS_ADAPTERS, adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort()), new JsonObject().put("hwId", device.getString("hwId")), options, res -> { if (res.succeeded()) { JsonObject reading = ((JsonObject) res.result().body()).getJsonObject("result") .getJsonObject("reading"); String time = null, value = null; if (reading != null) { time = reading.getJsonObject("lastReading").getString("time"); value = reading.getJsonObject("lastReading").getString("value"); } JsonObject result = new JsonObject().put("deviceId", device.getString("deviceId")) .put("time", time).put("value", value); resultHandler.handle(Future.succeededFuture(result)); } else { resultHandler.handle(Future.failedFuture(res.cause())); } }); }
From source file:se.liquidbytes.jel.system.device.DeviceManager.java
License:Apache License
/** * Method takes action on a new result reading. * * @param deviceReading/*from w ww .j a va 2 s .co m*/ */ private void handleNewDeviceReading(JsonObject deviceReading) { JsonObject reading = deviceReading.getJsonObject("reading"); String deviceId = this.generateDeviceId(deviceReading.getString("adapterId"), reading.getString("hwId")); Map<String, ? extends Device> devices = siteDevices.get("1"); //TODO: hardcoded. Device siteDevice = devices.get(deviceId); int lowLimit = 22; int highLimit = 24; if (siteDevice != null) { double temp = Double.parseDouble(reading.getString("value")); logger.info("Sensor: '{}' with id: {} and hwid: {}, temp: {}.", siteDevice.getName(), deviceId, reading.getString("hwId"), temp); switch (reading.getString("hwId")) { case "B74C8A010800": { // Vardagsrummet if (temp < lowLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "4D4D13000000_3"), "1", (r) -> { }); } if (temp > highLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "4D4D13000000_3"), "0", (r) -> { }); } break; } case "C9E69E010800": { // Hall(toalett/pannrum)" if (temp < lowLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "4D4D13000000_2"), "1", (r) -> { }); } if (temp > highLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "4D4D13000000_2"), "0", (r) -> { }); } break; } case "158DB5010800": { // kk if (temp < lowLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "4D4D13000000_4"), "1", (r) -> { }); } if (temp > highLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "4D4D13000000_4"), "0", (r) -> { }); } break; } case "52A9B5010800": { // Nya entren if (temp < lowLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "3E4D13000000_1"), "1", (r) -> { }); } if (temp > highLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "3E4D13000000_1"), "0", (r) -> { }); } break; } case "0C92B5010800": { // Arbetsrum if (temp < lowLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "3E4D13000000_3"), "1", (r) -> { }); } if (temp > highLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "3E4D13000000_3"), "0", (r) -> { }); } break; } case "969D98010800": { // Badrum if (temp < lowLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "3E4D13000000_2"), "1", (r) -> { }); } if (temp > highLimit) { this.updateDeviceValue( this.generateDeviceId(deviceReading.getString("adapterId"), "3E4D13000000_2"), "0", (r) -> { }); } break; } } // TODO: update result last readings, and current value in deviceLists. possible broadcast to clients dependings on samplerate. JsonObject newReading = new JsonObject().put("adapterId", deviceReading.getString("adapterId")) .put("deviceId", deviceId).put("time", reading.getString("time")) .put("value", reading.getString("value")); JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, newReading, new DeliveryOptions().addHeader("action", InternalEvents.EVENT_DEVICE_NEWREADING)); JelService.vertx().eventBus().publish(PublicEvents.EVENTBUS_PUBLIC, newReading, new DeliveryOptions().addHeader("action", PublicEvents.EVENT_DEVICE_NEWREADING)); } }
From source file:se.liquidbytes.jel.web.api.SystemApi.java
License:Apache License
public void systemInformation(RoutingContext context) { service.systemInformation((r) -> { if (r.succeeded()) { JsonObject source = r.result(); Representation rep = PresentationFactory.getRepresentation(API_ENDPOINT + "/system/info") .withProperty("applicationVersion", source.getString("applicationVersion")) .withProperty("applicationStarttime", source.getString("applicationStarttime")) .withProperty("serverCurrenttime", source.getString("serverCurrenttime")) .withProperty("applicationBuildnumber", source.getString("applicationBuildnumber")) .withRepresentation("java", PresentationFactory.getRepresentation() .withProperty("virtualMachine", source.getJsonObject("java").getString("virtualMachine")) .withProperty("runtime", source.getJsonObject("java").getString("runtime")) .withProperty("version", source.getJsonObject("java").getString("version")) .withProperty("vendor", source.getJsonObject("java").getString("vendor")) .withProperty("specificationName", source.getJsonObject("java").getString("specificationName")) .withProperty("javaHome", source.getJsonObject("java").getString("javaHome"))) .withRepresentation("os", PresentationFactory.getRepresentation() .withProperty("name", source.getJsonObject("os").getString("name")) .withProperty("description", source.getJsonObject("os").getString("description")) .withProperty("version", source.getJsonObject("os").getString("version")) .withProperty("architecture", source.getJsonObject("os").getString("architecture"))) .withRepresentation("hardware", PresentationFactory.getRepresentation() .withProperty("availableCPUs", source.getJsonObject("hardware").getInteger("availableCPUs")) .withProperty("ipAddress", source.getJsonObject("hardware").getString("ipAddress")) .withProperty("gatewayAddress", source.getJsonObject("hardware").getString("gatewayAddress")) .withProperty("serverEndpoint", source.getJsonObject("hardware").getString("serverEndpoint")) .withProperty("bogoMIPS", source.getJsonObject("hardware").getString("bogoMIPS")) .withProperty("details", source.getJsonObject("hardware").getJsonObject("details"))); context.response().end(rep.toString(context.get("__content-type"))); } else {//from w w w .j a v a 2 s . c o m context.fail(r.cause()); } }); }
From source file:se.liquidbytes.jel.web.api.SystemApi.java
License:Apache License
public void systemResources(RoutingContext context) { service.systemResources((r) -> {/*from w ww . j a va2 s .c o m*/ if (r.succeeded()) { JsonObject source = r.result(); Representation rep = PresentationFactory.getRepresentation(API_ENDPOINT + "/system/resources") .withRepresentation("cpu", PresentationFactory.getRepresentation() .withProperty("temperature", source.getJsonObject("cpu").getFloat("temperature")) .withProperty("loadAverage", source.getJsonObject("cpu").getFloat("loadAverage"))) .withRepresentation("disk", PresentationFactory.getRepresentation().withProperty("fullness", source.getJsonObject("disk").getFloat("fullness"))) .withRepresentation("java", PresentationFactory.getRepresentation() .withProperty("freeMemory", source.getJsonObject("java").getLong("freeMemory")) .withProperty("totalMemory", source.getJsonObject("java").getLong("totalMemory"))) .withRepresentation("memory", PresentationFactory.getRepresentation() .withProperty("free", source.getJsonObject("memory").getLong("free")) .withProperty("total", source.getJsonObject("memory").getLong("total"))); context.response().end(rep.toString(context.get("__content-type"))); } else { context.fail(r.cause()); } }); }
From source file:studio.lysid.scales.deploy.DeploymentOptionsParser.java
License:Open Source License
private static void parseConfigForVerticle(JsonObject verticlesDeploymentOptions, Verticle verticle) { JsonObject customVerticleOptions = verticlesDeploymentOptions.getJsonObject(verticle.shortName); if (customVerticleOptions != null) { verticle.deploymentOptions.fromJson(customVerticleOptions); logger.info("Deployment options parsed for verticle [{0}]. {1} instance(s) will be deployed.", verticle.shortName, verticle.deploymentOptions.getInstances()); } else {/*from w w w. j av a 2s .c om*/ verticle.deploymentOptions.setInstances(0); logger.warn( "Deployment options NOT FOUND for verticle [{0}], it will NOT be deployed. Prefer setting options for all verticles and use \"instances\":0 for those you don't want to deploy.", verticle.shortName); } }