use of io.openems.api.device.Device in project openems by OpenEMS.
the class Config method getBridgesJson.
public JsonArray getBridgesJson(ConfigFormat format, Role role) throws NotImplementedException {
JsonArray jBridges = new JsonArray();
for (Bridge bridge : thingRepository.getBridges()) {
JsonObject jBridge = (JsonObject) ConfigUtils.getAsJsonElement(bridge, format, role);
/*
* Device
*/
JsonArray jDevices = new JsonArray();
for (Device device : bridge.getDevices()) {
JsonObject jDevice = (JsonObject) ConfigUtils.getAsJsonElement(device, format, role);
jDevices.add(jDevice);
}
jBridge.add("devices", jDevices);
jBridges.add(jBridge);
}
return jBridges;
}
use of io.openems.api.device.Device in project openems by OpenEMS.
the class ThingRepository method removeThing.
/**
* Remove a Thing from the Repository.
*
* @param thing
*/
public synchronized void removeThing(Thing thing) {
// Remove from thingIds
thingIds.remove(thing.id());
// Remove from thingClasses
thingClasses.remove(thing.getClass(), thing);
// Remove from bridges
if (thing instanceof Bridge) {
bridges.remove(thing);
}
// Remove from schedulers
if (thing instanceof Scheduler) {
schedulers.remove(thing);
}
// Remove from persistences
if (thing instanceof Persistence) {
persistences.remove(thing);
}
// Remove from queryablePersistences
if (thing instanceof QueryablePersistence) {
queryablePersistences.remove(thing);
}
// Remove from deviceNatures
if (thing instanceof DeviceNature) {
deviceNatures.remove(thing);
}
// Remove controller
if (thing instanceof Controller) {
Controller controller = (Controller) thing;
for (Scheduler scheduler : getSchedulers()) {
scheduler.removeController(controller);
}
}
// Remove device
if (thing instanceof Device) {
for (Bridge bridge : bridges) {
bridge.removeDevice((Device) thing);
}
}
// Remove Listener
thing.removeListener(this);
for (ThingsChangedListener listener : thingListeners) {
listener.thingChanged(thing, Action.REMOVE);
}
}
use of io.openems.api.device.Device in project openems by OpenEMS.
the class ConfigUtils method getAsJsonElement.
/**
* Converts an object to a JsonElement
*
* @param value
* @return
* @throws NotImplementedException
*/
public static JsonElement getAsJsonElement(Object value, ConfigFormat format, Role role) throws NotImplementedException {
// null
if (value == null) {
return null;
}
// optional
if (value instanceof Optional<?>) {
if (!((Optional<?>) value).isPresent()) {
return null;
} else {
value = ((Optional<?>) value).get();
}
}
try {
/*
* test for simple types
*/
return JsonUtils.getAsJsonElement(value);
} catch (NotImplementedException e) {
;
}
if (value instanceof Thing) {
/*
* type Thing
*/
Thing thing = (Thing) value;
JsonObject j = new JsonObject();
if (format == ConfigFormat.OPENEMS_UI || !thing.id().startsWith("_")) {
// ignore generated id names starting with "_"
j.addProperty("id", thing.id());
j.addProperty("alias", thing.getAlias());
}
// for file-format class is not needed for DeviceNatures
j.addProperty("class", thing.getClass().getCanonicalName());
ThingRepository thingRepository = ThingRepository.getInstance();
for (ConfigChannel<?> channel : thingRepository.getConfigChannels(thing)) {
if (channel.isReadAllowed(role)) {
// check read permissions
JsonElement jChannel = null;
jChannel = ConfigUtils.getAsJsonElement(channel, format, role);
if (jChannel != null) {
j.add(channel.id(), jChannel);
}
}
}
// for Bridge: add 'devices' array of thingIds
if (value instanceof Bridge) {
Bridge bridge = (Bridge) value;
JsonArray jDevices = new JsonArray();
for (Device device : bridge.getDevices()) {
jDevices.add(device.id());
}
j.add("devices", jDevices);
}
return j;
} else if (value instanceof ConfigChannel<?>) {
/*
* type ConfigChannel
*/
ConfigChannel<?> channel = (ConfigChannel<?>) value;
if (!channel.valueOptional().isPresent()) {
// no value set
return null;
} else if (format == ConfigFormat.FILE && channel.getDefaultValue().equals(channel.valueOptional())) {
// default value not changed
return null;
} else {
// recursive call
return ConfigUtils.getAsJsonElement(channel.valueOptional().get(), format, role);
}
} else if (value instanceof ThingMap) {
/*
* ThingMap (we need only id)
*/
return new JsonPrimitive(((ThingMap) value).id());
} else if (value instanceof List<?>) {
/*
* List
*/
JsonArray jArray = new JsonArray();
for (Object v : (List<?>) value) {
jArray.add(ConfigUtils.getAsJsonElement(v, format, role));
}
return jArray;
} else if (value instanceof Set<?>) {
/*
* Set
*/
JsonArray jArray = new JsonArray();
for (Object v : (Set<?>) value) {
jArray.add(ConfigUtils.getAsJsonElement(v, format, role));
}
return jArray;
}
throw new NotImplementedException(//
"Converter for [" + value + "]" + " of type [" + value.getClass().getSimpleName() + //
"]" + " to JSON is not implemented.");
}
use of io.openems.api.device.Device in project openems by OpenEMS.
the class ChannelExport method main.
public static void main(String[] args) throws OpenemsException {
String openemsPath = "C:\\Users\\matthias.rossmann\\Dev\\git\\openems-neu\\edge\\src";
Collection<ThingDoc> deviceNatures;
HashMap<Path, FileWriter> files = new HashMap<>();
try {
deviceNatures = ClassRepository.getInstance().getAvailableDeviceNatures();
FileWriter devices = new FileWriter(Paths.get(openemsPath, "\\io\\openems\\impl\\device\\Readme.md").toFile());
devices.write("# List of implemented Devices.\r\n\r\n");
for (ThingDoc thingDoc : deviceNatures) {
try {
System.out.println(thingDoc.getClazz().getName());
if (thingDoc.getClazz().equals(AsymmetricSymmetricCombinationEssNature.class) || thingDoc.getClazz().equals(EssClusterNature.class) || thingDoc.getClazz().isInterface() || Modifier.isAbstract(thingDoc.getClazz().getModifiers())) {
continue;
}
Path p = Paths.get(openemsPath, thingDoc.getClazz().getName().replaceAll("[^\\.]*$", "").replace(".", "/"), "Readme.md");
FileWriter fw;
if (files.containsKey(p)) {
fw = files.get(p);
} else {
fw = new FileWriter(p.toFile());
files.put(p, fw);
fw.write("");
}
fw.append("# " + thingDoc.getTitle() + "\r\n" + thingDoc.getText() + "\r\n\r\nFollowing Values are implemented:\r\n\r\n" + "|ChannelName|Unit|\r\n" + "|---|---|\r\n");
devices.append("* [" + thingDoc.getTitle() + "](" + Paths.get(thingDoc.getClazz().getName().replaceAll("io.openems.impl.device.", "").replaceAll("[^\\.]*$", "").replace(".", "/"), "Readme.md").toString().replace("\\", "/") + ")\r\n");
Thing thing = thingDoc.getClazz().getConstructor(String.class, Device.class).newInstance("", null);
if (thing instanceof ModbusDeviceNature) {
((ModbusDeviceNature) thing).init();
}
List<ChannelDoc> channelDocs = new LinkedList<>(thingDoc.getChannelDocs());
Collections.sort(channelDocs, new Comparator<ChannelDoc>() {
@Override
public int compare(ChannelDoc arg0, ChannelDoc arg1) {
return arg0.getName().compareTo(arg1.getName());
}
});
for (ChannelDoc channelDoc : channelDocs) {
Member member = channelDoc.getMember();
try {
List<Channel> channels = new ArrayList<>();
if (member instanceof Method) {
if (((Method) member).getReturnType().isArray()) {
Channel[] ch = (Channel[]) ((Method) member).invoke(thing);
for (Channel c : ch) {
channels.add(c);
}
} else {
// It's a Method with ReturnType Channel
channels.add((Channel) ((Method) member).invoke(thing));
}
} else if (member instanceof Field) {
// It's a Field with Type Channel
channels.add((Channel) ((Field) member).get(thing));
} else {
continue;
}
if (channels.isEmpty()) {
System.out.println("Channel is returning null! Thing [" + thing.id() + "], Member [" + member.getName() + "]");
continue;
}
for (Channel channel : channels) {
if (channel != null) {
StringBuilder unit = new StringBuilder();
if (channel instanceof ReadChannel) {
ReadChannel rchannel = ((ReadChannel) channel);
unit.append(rchannel.unitOptional());
rchannel.getLabels().forEach((key, value) -> {
unit.append(key + ": " + value + "<br/>");
});
}
fw.append("|" + channel.id() + "|" + unit + "|\r\n");
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
System.out.println("Unable to add Channel. Member [" + member.getName() + "]");
}
}
} catch (NoSuchMethodException e) {
}
}
for (FileWriter fw : files.values()) {
fw.close();
}
devices.close();
} catch (Exception e) {
e.printStackTrace();
}
}
use of io.openems.api.device.Device in project openems by OpenEMS.
the class Config method parseJsonConfig.
public synchronized void parseJsonConfig(JsonObject jConfig) throws OpenemsException {
/*
* read Users
*/
if (jConfig.has("users")) {
JsonObject jUsers = JsonUtils.getAsJsonObject(jConfig, "users");
for (Entry<String, JsonElement> jUsersElement : jUsers.entrySet()) {
JsonObject jUser = JsonUtils.getAsJsonObject(jUsersElement.getValue());
String username = jUsersElement.getKey();
String passwordBase64 = JsonUtils.getAsString(jUser, "password");
String saltBase64 = JsonUtils.getAsString(jUser, "salt");
try {
User.getUserByName(username).initialize(passwordBase64, saltBase64);
} catch (OpenemsException e) {
log.error("Error parsing config: " + e.getMessage());
}
}
}
// important! no more setting of users allowed!
User.initializeFinished();
/*
* read each Bridge in "things" array
*/
JsonArray jThings = JsonUtils.getAsJsonArray(jConfig, "things");
for (JsonElement jBridgeElement : jThings) {
JsonObject jBridge = JsonUtils.getAsJsonObject(jBridgeElement);
String bridgeClass = JsonUtils.getAsString(jBridge, "class");
Bridge bridge = (Bridge) InjectionUtils.getThingInstance(bridgeClass);
thingRepository.addThing(bridge);
log.info("Add Bridge[" + bridge.id() + "], Implementation[" + bridge.getClass().getSimpleName() + "]");
ConfigUtils.injectConfigChannels(thingRepository.getConfigChannels(bridge), jBridge);
/*
* read each Device in "things" array
*/
List<Device> devices = new ArrayList<>();
JsonArray jDevices = JsonUtils.getAsJsonArray(jBridge, "devices");
for (JsonElement jDeviceElement : jDevices) {
JsonObject jDevice = JsonUtils.getAsJsonObject(jDeviceElement);
Device device = thingRepository.createDevice(jDevice, bridge);
devices.add(device);
bridge.addDevice(device);
}
}
/*
* Init bridge
*/
for (Bridge b : thingRepository.getBridges()) {
for (Device d : b.getDevices()) {
d.init();
}
b.init();
}
for (BridgeInitializedEventListener listener : bridgeInitEventListeners) {
listener.onBridgeInitialized();
}
/*
* read Scheduler
*/
if (jConfig.has("scheduler")) {
JsonObject jScheduler = JsonUtils.getAsJsonObject(jConfig, "scheduler");
String schedulerClass = JsonUtils.getAsString(jScheduler, "class");
Scheduler scheduler = (Scheduler) InjectionUtils.getThingInstance(schedulerClass);
thingRepository.addThing(scheduler);
log.debug("Add Scheduler[" + scheduler.id() + "], Implementation[" + scheduler.getClass().getSimpleName() + "]");
ConfigUtils.injectConfigChannels(thingRepository.getConfigChannels(scheduler), jScheduler);
/*
* read each Controller in "controllers" array
*/
JsonArray jControllers = JsonUtils.getAsJsonArray(jScheduler, "controllers");
for (JsonElement jControllerElement : jControllers) {
JsonObject jController = JsonUtils.getAsJsonObject(jControllerElement);
Controller controller = thingRepository.createController(jController);
scheduler.addController(controller);
controller.init();
}
scheduler.init();
}
for (SchedulerInitializedEventListener listener : schedulerInitEventListeners) {
listener.onSchedulerInitialized();
}
/*
* read Persistence
*/
if (jConfig.has("persistence")) {
JsonArray jPersistences = JsonUtils.getAsJsonArray(jConfig, "persistence");
for (JsonElement jPersistenceElement : jPersistences) {
JsonObject jPersistence = JsonUtils.getAsJsonObject(jPersistenceElement);
String persistenceClass = JsonUtils.getAsString(jPersistence, "class");
Persistence persistence = (Persistence) InjectionUtils.getThingInstance(persistenceClass);
thingRepository.addThing(persistence);
log.info("Add Persistence[" + persistence.id() + "], Implementation[" + persistence.getClass().getSimpleName() + "]");
ConfigUtils.injectConfigChannels(thingRepository.getConfigChannels(persistence), jPersistence);
persistence.init();
}
}
/*
* Configuration is finished -> apply again channel annotation to all of them because many channels are only
* defined during init()
*/
thingRepository.getThings().forEach(thing -> {
thingRepository.applyChannelAnnotation(thing);
});
/*
* Start all worker threads
*/
thingRepository.getThings().forEach(thing -> {
// TODO use executor
if (thing instanceof Thread) {
((Thread) thing).start();
}
});
/*
* Register myself as onChangeListener on all ConfigChannels
*/
for (ConfigChannel<?> channel : thingRepository.getConfigChannels()) {
channel.addChangeListener(this);
}
/*
* After 10 seconds: build the ClassRepository cache to speed up future calls
* (this speeds up the first opening of the UI, as the cache does not need to be built)
*/
Executors.newScheduledThreadPool(1).schedule(() -> {
try {
ClassRepository.getInstance().getAvailableThings();
} catch (ReflectionException e) {
/* ignore */
}
}, 10, TimeUnit.SECONDS);
}
Aggregations