use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class StuderDeviceNature method createStuderProtocol.
private void createStuderProtocol() {
try {
this.protocol = defineStuderProtocol();
if (this.parent instanceof StuderDevice) {
StuderDevice parent = (StuderDevice) this.parent;
if (parent.getBridge() instanceof StuderBridge) {
StuderBridge bridge = (StuderBridge) parent.getBridge();
// create WriteTasks
writeTasks = Collections.synchronizedList(new ArrayList<>());
for (WriteProperty<?> property : protocol.getWritableProperties()) {
writeTasks.add(new StuderBridgeWriteTask(property, bridge.getSrcAddress(), parent.getDstAddress(), bridge));
}
// create ReadTasks
readTasks = Collections.synchronizedList(new ArrayList<>());
requiredReadTasks = Collections.synchronizedList(new ArrayList<>());
for (ReadProperty<?> property : protocol.getReadProperties()) {
readTasks.add(new StuderBridgeReadTask(property, bridge.getSrcAddress(), parent.getDstAddress(), bridge));
}
} else {
log.error("Invalid Bridge Type. The bridge needs to inherit from ModbusBridge.");
}
} else {
log.error("Invalid Device Type. The Device needs to inherit from ModbusDevice");
}
for (ThingChannelsUpdatedListener listener : this.listeners) {
listener.thingChannelsUpdated(this);
}
} catch (OpenemsException e) {
log.error("Failed to define modbus protocol!", e);
}
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class EdgeWebsocketServer method _onMessage.
/**
* Message event of websocket. Handles a new message. At this point the Edge is
* already authenticated.
*/
@Override
protected void _onMessage(WebSocket websocket, JsonObject jMessage) {
// get edgeIds from websocket
int[] edgeIds = websocket.getAttachment();
// set last update timestamps in MetadataService
for (int edgeId : edgeIds) {
Optional<Edge> edgeOpt = this.parent.metadataService.getEdgeOpt(edgeId);
if (edgeOpt.isPresent()) {
Edge edge = edgeOpt.get();
edge.setLastMessage();
}
}
// get MessageId from message
JsonObject jMessageId = JsonUtils.getAsOptionalJsonObject(jMessage, "messageId").orElse(new JsonObject());
/*
* Config? -> store in Metadata
*/
Optional<JsonObject> jConfigOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "config");
if (jConfigOpt.isPresent()) {
JsonObject jConfig = jConfigOpt.get();
for (int edgeId : edgeIds) {
Edge edge;
try {
edge = this.parent.metadataService.getEdge(edgeId);
edge.setConfig(jConfig);
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.METADATA_ERROR, e.getMessage());
}
}
return;
}
/*
* Is this a reply? -> forward to UI
*/
if (jMessage.has("messageId")) {
for (int edgeId : edgeIds) {
try {
this.parent.uiWebsocketService.handleEdgeReply(edgeId, jMessage);
} catch (OpenemsException e) {
WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.EDGE_UNABLE_TO_FORWARD, "ID:" + edgeId, e.getMessage());
}
}
return;
}
/*
* New timestamped data
*/
Optional<JsonObject> jTimedataOpt = JsonUtils.getAsOptionalJsonObject(jMessage, "timedata");
if (jTimedataOpt.isPresent()) {
timedata(edgeIds, jTimedataOpt.get());
return;
}
/*
* Unknown message
*/
for (String edgeName : getEdgeNames(edgeIds)) {
WebSocketUtils.sendNotificationOrLogError(websocket, jMessageId, LogBehaviour.WRITE_TO_LOG, Notification.UNKNOWN_MESSAGE, edgeName, StringUtils.toShortString(jMessage, 100));
}
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class WriteProperty method writeValue.
public default void writeValue(int srcAddress, int dstAddress, StuderBridge studerBridge) throws OpenemsException {
try {
T value;
Optional<T> valueOptional = this.channel().writeShadowCopy();
if (valueOptional.isPresent()) {
value = valueOptional.get();
} else {
return;
}
System.out.println("Write value[" + value + "] to " + this.channel().address());
WriteRequest<T> writeRequest = writeRequest(srcAddress, dstAddress, value);
studerBridge.execute(writeRequest);
} catch (IOException e) {
throw new OpenemsException("Unable to write value", e);
}
}
use of io.openems.common.exceptions.OpenemsException 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);
}
use of io.openems.common.exceptions.OpenemsException in project openems by OpenEMS.
the class KebaDevice method send.
/**
* Send UDP message to Keba EVCS
*
* @param s
* @throws IOException
* @throws ConfigException
* @throws InterruptedException
*/
protected void send(String s) throws OpenemsException {
Optional<Inet4Address> ipOpt = this.ip.valueOptional();
if (!ipOpt.isPresent()) {
throw new ConfigException("No IP address configured for Device[" + this.id() + "]");
} else {
Inet4Address ip = ipOpt.get();
byte[] raw = s.getBytes();
DatagramPacket packet = new DatagramPacket(raw, raw.length, ip, PORT);
DatagramSocket dSocket = null;
try {
dSocket = new DatagramSocket();
log.info("Sending message to KEBA [" + s + "]");
dSocket.send(packet);
} catch (SocketException e) {
throw new OpenemsException("Unable to open UDP socket for sending [" + s + "] to [" + ip.getHostAddress() + "]: " + e.getMessage(), e);
} catch (IOException e) {
throw new OpenemsException("Unable to send [" + s + "] UDP message to [" + ip.getHostAddress() + "]: " + e.getMessage());
} finally {
if (dSocket != null) {
dSocket.close();
}
}
}
}
Aggregations