Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI updates: event component fully implemented

Rich Turner23cbc2c9ca4f
diff --git a/client/src/main/webapp/src/or-app/or-app-events.html b/client/src/main/webapp/src/or-app/or-app-events.html
index 024ba354b..fed43affd 100644
--- a/client/src/main/webapp/src/or-app/or-app-events.html
+++ b/client/src/main/webapp/src/or-app/or-app-events.html
@@ -34,7 +34,7 @@
value: value
}
}
- openremote.INSTANCE.sendServiceMessage("EVENT" + JSON.stringify(attributeEvent));
+ openremote.INSTANCE.sendServiceMessage("EVENT:" + JSON.stringify(attributeEvent));
}
subscribeAttributeEvents(assetIds) {
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 83a965360..fc282bac0 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -37,7 +37,6 @@ import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.AuthContext;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.web.WebService;
import org.openremote.manager.asset.console.ConsoleResourceImpl;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.rules.AssetQueryPredicate;
@@ -50,6 +49,7 @@ import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.calendar.CalendarEvent;
import org.openremote.model.calendar.RecurrenceRule;
+import org.openremote.model.event.TriggeredEventSubscription;
import org.openremote.model.event.shared.TenantFilter;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.BaseAssetQuery;
@@ -67,9 +67,8 @@ import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import java.sql.*;
-import java.time.Instant;
-import java.util.*;
import java.util.Date;
+import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -188,7 +187,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (authContext.isSuperUser()) {
Asset asset = find(event.getAssetId(), true);
if (asset != null)
- replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
+ replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, event.getAttributeNames());
return;
}
@@ -203,7 +202,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? RESTRICTED_READ : PRIVATE_READ
);
if (asset != null) {
- replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
+ replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, event.getAttributeNames());
}
});
@@ -1402,15 +1401,18 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
- protected void replyWithAttributeEvents(String sessionKey, Asset asset, String[] attributeNames) {
+ protected void replyWithAttributeEvents(String sessionKey, String subscriptionId, Asset asset, String[] attributeNames) {
List<String> names = attributeNames == null ? Collections.emptyList() : Arrays.asList(attributeNames);
// Client may want to read a subset or all attributes of the asset
- clientEventService.sendToSession(sessionKey, asset.getAttributesStream()
- .filter(attribute -> names.isEmpty() || attribute.getName().filter(names::contains).isPresent())
- .map(AssetAttribute::getStateEvent)
- .filter(Optional::isPresent)
- .map(Optional::get).toArray(AttributeEvent[]::new));
+ AttributeEvent[] events = asset.getAttributesStream()
+ .filter(attribute -> names.isEmpty() || attribute.getName().filter(names::contains).isPresent())
+ .map(AssetAttribute::getStateEvent)
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .toArray(AttributeEvent[]::new);
+ TriggeredEventSubscription<AttributeEvent> triggeredEventSubscription = new TriggeredEventSubscription<>(events, subscriptionId);
+ clientEventService.sendToSession(sessionKey, triggeredEventSubscription);
}
protected static boolean calendarEventPredicateMatches(CalendarEventActivePredicate eventActivePredicate, Asset asset) {
diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
index 902013083..f4115081f 100644
--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
@@ -128,6 +128,7 @@ public class ClientEventService implements ContainerService {
new EventTypeConverters()
);
+ // TODO: Remove prefix and just use event type then use a subscription wrapper to pass subscription ID around
messageBrokerSetupService.getContext().addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
diff --git a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
index 88385f576..990310ba2 100644
--- a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
+++ b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
@@ -23,7 +23,6 @@ import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultMessage;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.util.UniqueIdentifierGenerator;
import org.openremote.container.web.socket.WebsocketConstants;
import org.openremote.manager.concurrent.ManagerExecutorService;
import org.openremote.model.event.TriggeredEventSubscription;
@@ -197,7 +196,7 @@ public class EventSubscriptions {
|| sessionSubscription.subscription.getFilter().apply(event)) {
LOG.fine("Creating message for subscribed session '" + sessionKey + "': " + event);
- TriggeredEventSubscription<SharedEvent> triggeredEventSubscription = new TriggeredEventSubscription<>(event, sessionSubscription.subscriptionId);
+ TriggeredEventSubscription<SharedEvent> triggeredEventSubscription = new TriggeredEventSubscription<>(new SharedEvent[] {event}, sessionSubscription.subscriptionId);
if (sessionSubscription.subscription.getInternalConsumer() == null) {
Message msg = new DefaultMessage();
diff --git a/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java b/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java
index 9dc98a9d5..2170ef3cf 100644
--- a/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java
+++ b/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java
@@ -68,10 +68,10 @@ public class EventTypeConverters implements TypeConverters {
@Converter
public String writeTriggeredEventSubscription(TriggeredEventSubscription triggeredEventSubscription, Exchange exchange) throws Exception {
if (!TextUtil.isNullOrEmpty(triggeredEventSubscription.getSubscriptionId())) {
- return SharedEvent.MESSAGE_PREFIX + triggeredEventSubscription.getSubscriptionId() + ":" + Container.JSON.writeValueAsString(triggeredEventSubscription.getEvent());
+ return SharedEvent.MESSAGE_PREFIX + triggeredEventSubscription.getSubscriptionId() + ":" + Container.JSON.writeValueAsString(triggeredEventSubscription.getEvents());
}
- return SharedEvent.MESSAGE_PREFIX + Container.JSON.writeValueAsString(triggeredEventSubscription.getEvent());
+ return SharedEvent.MESSAGE_PREFIX + Container.JSON.writeValueAsString(triggeredEventSubscription.getEvents());
}
@Converter
diff --git a/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java b/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java
index a84913a27..9fc06b969 100644
--- a/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java
@@ -40,6 +40,8 @@ public class ReadAssetAttributesEvent extends SharedEvent {
protected String[] attributeNames;
+ protected String subscriptionId;
+
protected ReadAssetAttributesEvent() {
}
@@ -64,6 +66,14 @@ public class ReadAssetAttributesEvent extends SharedEvent {
this.attributeNames = attributeNames;
}
+ public String getSubscriptionId() {
+ return subscriptionId;
+ }
+
+ public void setSubscriptionId(String subscriptionId) {
+ this.subscriptionId = subscriptionId;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.java b/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.java
index 29f09bb71..411a2ffad 100644
--- a/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.java
+++ b/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.java
@@ -23,19 +23,21 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.event.shared.SharedEvent;
+import java.util.Arrays;
+
public class TriggeredEventSubscription<E extends SharedEvent> {
- protected E event;
+ protected E[] events;
protected String subscriptionId;
@JsonCreator
- public TriggeredEventSubscription(@JsonProperty("event") E event, @JsonProperty("subscriptionId") String subscriptionId) {
- this.event = event;
+ public TriggeredEventSubscription(@JsonProperty("events") E[] events, @JsonProperty("subscriptionId") String subscriptionId) {
+ this.events = events;
this.subscriptionId = subscriptionId;
}
- public E getEvent() {
- return event;
+ public E[] getEvents() {
+ return events;
}
public String getSubscriptionId() {
@@ -45,7 +47,7 @@ public class TriggeredEventSubscription<E extends SharedEvent> {
@Override
public String toString() {
return "TriggeredEventSubscription{" +
- "event=" + event +
+ "events=" + Arrays.toString(events) +
", subscriptionId='" + subscriptionId + '\'' +
'}';
}
diff --git a/ui/component/core/src/console.ts b/ui/component/core/src/console.ts
index ae093ae64..de2630c5c 100644
--- a/ui/component/core/src/console.ts
+++ b/ui/component/core/src/console.ts
@@ -12,7 +12,6 @@ export interface ProviderMessage {
provider: string;
action: string;
data?: any;
-
[x: string]: any;
}
@@ -169,7 +168,7 @@ export class Console {
try {
// Get an ID for this console if it doesn't have one
if (!this._registration.id) {
- await this.sendRegistration();
+ await this.sendRegistration(0);
}
if (this._registration.providers) {
@@ -190,6 +189,7 @@ export class Console {
}
} catch (e) {
console.error(e);
+ } finally {
this._initialiseInProgress = false;
}
}
@@ -290,13 +290,18 @@ export class Console {
}
// Uses a delayed mechanism to avoid excessive calls to the server during enabling providers
- public async sendRegistration(): Promise<void> {
+ public sendRegistration(delay?: number): Promise<void> {
+
if (this._registrationTimer) {
window.clearTimeout(this._registrationTimer);
this._registrationTimer = null;
}
- await new Promise(resolve => {
+ delay = delay !== undefined ? delay : 2000;
+
+ console.debug("Sending registration in: " + delay + "ms");
+
+ return new Promise((resolve, reject) => {
this._registrationTimer = window.setTimeout(() => {
this._registrationTimer = null;
console.debug("Console: updating registration");
@@ -311,11 +316,13 @@ export class Console {
console.debug("Console: registration successful");
console.debug("Console: updating locally stored registration");
window.localStorage.setItem("OpenRemoteConsole:" + this._realm, JSON.stringify(this._registration));
+ resolve();
});
- } finally {
- resolve();
+ } catch (e) {
+ console.error("Failed to register console");
+ reject("Failed to register console");
}
- }, 2000);
+ },);
});
}
@@ -367,22 +374,25 @@ export class Console {
switch (msg.action.trim().toUpperCase()) {
case "PROVIDER_INIT":
- this._handleProviderResponse(JSON.stringify({
+ let initResponse: ProviderInitialiseResponse = {
action: "PROVIDER_INIT",
provider: "push",
version: "web",
enabled: true,
+ hasPermission: true,
requiresPermission: false,
success: true
- }));
+ };
+ this._handleProviderResponse(JSON.stringify(initResponse));
break;
case "PROVIDER_ENABLE":
- this._handleProviderResponse(JSON.stringify({
+ let enableResponse: ProviderEnableResponse = {
action: "PROVIDER_ENABLE",
provider: "push",
hasPermission: true,
success: true
- }));
+ };
+ this._handleProviderResponse(JSON.stringify(enableResponse));
break;
default:
throw new Error("Unsupported provider '" + msg.provider + "' and action '" + msg.action + "'");
@@ -394,22 +404,25 @@ export class Console {
switch (msg.action) {
case "PROVIDER_INIT":
- this._handleProviderResponse(JSON.stringify({
+ let initResponse: ProviderInitialiseResponse = {
action: "PROVIDER_INIT",
provider: "storage",
version: "1.0.0",
enabled: true,
+ hasPermission: true,
requiresPermission: false,
success: true
- }));
+ };
+ this._handleProviderResponse(JSON.stringify(initResponse));
break;
case "PROVIDER_ENABLE":
- this._handleProviderResponse(JSON.stringify({
+ let enableResponse: ProviderEnableResponse = {
action: "PROVIDER_ENABLE",
provider: "storage",
hasPermission: true,
success: true
- }));
+ };
+ this._handleProviderResponse(JSON.stringify(enableResponse));
break;
case "STORE":
let keyValue = msg.key ? msg.key.trim() : null;
diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.ts
index 54dfaaaa2..1fb1c6340 100644
--- a/ui/component/core/src/event.ts
+++ b/ui/component/core/src/event.ts
@@ -1,7 +1,13 @@
-//import rest from "@openremote/rest";
import openremote from "./index";
import {Deferred} from "./util";
-import {EventSubscription, SharedEvent} from "@openremote/model";
+import {
+ AttributeEvent,
+ CancelEventSubscription,
+ EventSubscription,
+ RenewEventSubscriptions,
+ SharedEvent,
+ ReadAssetAttributesEvent
+} from "@openremote/model";
export enum EventProviderStatus {
DISCONNECTED = "DISCONNECTED",
@@ -10,20 +16,33 @@ export enum EventProviderStatus {
}
export interface EventProvider {
+ status: EventProviderStatus;
+
connect(): Promise<boolean>;
disconnect(): void;
+
+ subscribe<T extends SharedEvent>(eventSubscription: EventSubscription<T>, callback: (event: T) => void): Promise<string>;
+
+ unsubscribe<T extends SharedEvent>(subscriptionId: string): void;
+
+ subscribeAttributeEvents(assetIds: string[], callback: (event: AttributeEvent) => void): Promise<string>;
+
+ sendEvent<T extends SharedEvent>(event: T): void;
}
interface EventSubscriptionInfo<T extends SharedEvent> {
eventSubscription: EventSubscription<T>;
callback: (event: T) => void;
- deferred: Deferred<number> | null;
+ deferred: Deferred<string> | null;
}
const SUBSCRIBE_MESSAGE_PREFIX = "SUBSCRIBE:";
const SUBSCRIBED_MESSAGE_PREFIX = "SUBSCRIBED:";
const UNSUBSCRIBE_MESSAGE_PREFIX = "UNSUBSCRIBE:";
+const RENEW_MESSAGE_PREFIX = "RENEW:";
+const UNAUTHORIZED_MESSAGE_PREFIX = "UNAUTHORIZED:";
+const EVENT_MESSAGE_PREFIX = "EVENT:";
abstract class EventProviderImpl implements EventProvider {
@@ -38,15 +57,7 @@ abstract class EventProviderImpl implements EventProvider {
protected _pendingSubscription: EventSubscriptionInfo<SharedEvent> | null = null;
protected _queuedSubscriptions: EventSubscriptionInfo<SharedEvent>[] = [];
- protected _subscriptionMap: { [id: number]: EventSubscriptionInfo<SharedEvent> } = {};
-
- protected abstract _doConnect(): Promise<boolean>;
-
- protected abstract _doDisconnect(): void;
-
- protected abstract _doSubscribe<T extends SharedEvent>(subscription: EventSubscription<T>): Promise<number>;
-
- protected abstract _doUnsubscribe(subscriptionId: number): void;
+ protected _subscriptionMap: { [id: string]: EventSubscriptionInfo<SharedEvent> } = {};
abstract get endpointUrl(): string;
@@ -81,11 +92,11 @@ abstract class EventProviderImpl implements EventProvider {
if (this._reconnectTimer) {
window.clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
- this._reconnectDelayMillis = WebSocketEventProvider.MIN_RECONNECT_DELAY;
}
if (connected) {
console.debug("Connected to event service: " + this.endpointUrl);
+ this._reconnectDelayMillis = WebSocketEventProvider.MIN_RECONNECT_DELAY;
this._onStatusChanged(EventProviderStatus.CONNECTED);
window.setTimeout(() => {
@@ -121,12 +132,12 @@ abstract class EventProviderImpl implements EventProvider {
this._doDisconnect();
}
- public subscribe<T extends SharedEvent>(eventSubscription: EventSubscription<T>, callback: (event: T) => void): Promise<number> {
+ public subscribe<T extends SharedEvent>(eventSubscription: EventSubscription<T>, callback: (event: T) => void): Promise<string> {
let subscriptionInfo = {
eventSubscription: eventSubscription,
callback: callback as ((event: SharedEvent) => void),
- deferred: new Deferred<number>()
+ deferred: new Deferred<string>()
};
if (this._pendingSubscription != null || this._status !== EventProviderStatus.CONNECTED) {
@@ -171,7 +182,7 @@ abstract class EventProviderImpl implements EventProvider {
return this._pendingSubscription.deferred!.promise;
}
- public unsubscribe<T extends SharedEvent>(subscriptionId: number) {
+ public unsubscribe<T extends SharedEvent>(subscriptionId: string) {
let callback = this._subscriptionMap[subscriptionId];
if (callback) {
@@ -180,6 +191,44 @@ abstract class EventProviderImpl implements EventProvider {
}
}
+ public sendEvent<T extends SharedEvent>(event: T): void {
+ this._doSend(event);
+ }
+
+ public async subscribeAttributeEvents(assetIds: string[], callback: (event: AttributeEvent) => void): Promise<string> {
+ let subscription: EventSubscription<AttributeEvent> = {
+ eventType: "attribute",
+ filter: {
+ filterType: "attribute-entity-id",
+ entityIds: assetIds
+ }
+ };
+
+ let subscriptionId: string | null = null;
+
+ try {
+ subscriptionId = await this.subscribe(subscription, callback);
+
+ // Get the current value of each assets attributes
+ assetIds.forEach(assetId => {
+ let readEvent: ReadAssetAttributesEvent = {
+ assetId: assetId,
+ eventType: "read-asset-attributes",
+ subscriptionId: subscriptionId!
+ };
+ this.sendEvent(readEvent);
+ });
+ } catch (e) {
+ console.log("Failed to subscribe to attribute events for assets: " + assetIds);
+ if (subscriptionId) {
+ this.unsubscribe(subscriptionId);
+ }
+ throw e;
+ }
+
+ return subscriptionId!;
+ }
+
protected _processNextSubscription() {
if (this._status != EventProviderStatus.CONNECTED || this._queuedSubscriptions.length === 0) {
return;
@@ -190,7 +239,7 @@ abstract class EventProviderImpl implements EventProvider {
if (subscriptionInfo) {
this.subscribe(subscriptionInfo.eventSubscription, subscriptionInfo.callback)
.then(
- (id: number) => {
+ (id: string) => {
let deferred = subscriptionInfo!.deferred;
subscriptionInfo!.deferred = null;
@@ -222,8 +271,12 @@ abstract class EventProviderImpl implements EventProvider {
}, 0);
}
- protected _onMessageReceived(messageId: string, message: any) {
- console.debug("Event provider message received");
+ protected _onMessageReceived(subscriptionId: string, event: SharedEvent) {
+ let subscriptionInfo = this._subscriptionMap[subscriptionId];
+
+ if (subscriptionInfo) {
+ subscriptionInfo.callback(event);
+ }
}
protected _onConnect() {
@@ -241,12 +294,6 @@ abstract class EventProviderImpl implements EventProvider {
this._processNextSubscription();
}
- protected _onError() {
- console.debug("Event provider error");
- // Could have inconsistent state so disconnect and let consumers decide what to do and when to reconnect
- this.disconnect();
- }
-
protected _onDisconnect() {
console.debug("Event provider disconnected");
this._onStatusChanged(EventProviderStatus.DISCONNECTED);
@@ -276,26 +323,40 @@ abstract class EventProviderImpl implements EventProvider {
}
this.connect().then(connected => {
- if (connected) {
- this._reconnectDelayMillis = WebSocketEventProvider.MIN_RECONNECT_DELAY;
- } else {
+ if (!connected) {
this._scheduleReconnect();
}
- })
+ }).catch(error => {
+ this._scheduleReconnect();
+ });
}, this._reconnectDelayMillis);
if (this._reconnectDelayMillis < WebSocketEventProvider.MAX_RECONNECT_DELAY) {
this._reconnectDelayMillis = Math.min(WebSocketEventProvider.MAX_RECONNECT_DELAY, this._reconnectDelayMillis + 3000);
}
}
+
+ protected abstract _doSend<T extends SharedEvent>(event: T): void;
+
+ protected abstract _doConnect(): Promise<boolean>;
+
+ protected abstract _doDisconnect(): void;
+
+ protected abstract _doSubscribe<T extends SharedEvent>(subscription: EventSubscription<T>): Promise<string>;
+
+ protected abstract _doUnsubscribe(subscriptionId: string): void;
}
export class WebSocketEventProvider extends EventProviderImpl {
- private _endpointUrl: string;
+ protected static _subscriptionCounter: number = 1;
+ protected static _subscriptionRenewalMillis = 150 * 1000;
+
+ private readonly _endpointUrl: string;
protected _webSocket: WebSocket | undefined = undefined;
protected _connectDeferred: Deferred<boolean> | null = null;
- protected _subscribeDeferred: Deferred<number> | null = null;
+ protected _subscribeDeferred: Deferred<string> | null = null;
+ protected _renewalTimer: number | null = null;
get endpointUrl(): string {
return this._endpointUrl;
@@ -336,7 +397,9 @@ export class WebSocketEventProvider extends EventProviderImpl {
this._connectDeferred = null;
deferred.resolve(false);
} else {
- this._onError();
+ console.debug("Event provider error");
+ // Could have inconsistent state so disconnect and let consumers decide what to do and when to reconnect
+ this._beforeDisconnect();
}
};
@@ -348,7 +411,7 @@ export class WebSocketEventProvider extends EventProviderImpl {
this._connectDeferred = null;
deferred.resolve(false);
} else {
- this._onDisconnect();
+ this._beforeDisconnect();
}
};
@@ -356,24 +419,65 @@ export class WebSocketEventProvider extends EventProviderImpl {
let msg = e.data as string;
if (msg && msg.startsWith(SUBSCRIBED_MESSAGE_PREFIX)) {
let jsonStr = msg.substring(SUBSCRIBED_MESSAGE_PREFIX.length);
- let id = JSON.parse(jsonStr) as number;
+ let subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;
- if (this._subscribeDeferred) {
- this._subscribeDeferred.resolve(id);
+ // Create a renewal timer if not done so
+ if (!this._renewalTimer) {
+ setInterval(() => {
+ this._doRenewal();
+ }, WebSocketEventProvider._subscriptionRenewalMillis);
+ }
+
+ let deferred = this._subscribeDeferred;
+ this._subscribeDeferred = null;
+ if (deferred) {
+ deferred.resolve(subscription.subscriptionId);
+ }
+ } else if (msg.startsWith(UNAUTHORIZED_MESSAGE_PREFIX)) {
+ let jsonStr = msg.substring(UNAUTHORIZED_MESSAGE_PREFIX.length);
+ let subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;
+ let deferred = this._subscribeDeferred;
+ this._subscribeDeferred = null;
+ if (deferred) {
+ console.warn("Unauthorized event subscription: " + subscription);
+ deferred.reject("Unauthorized");
+ }
+ } else if (msg.startsWith(EVENT_MESSAGE_PREFIX)) {
+ let str = msg.substring(EVENT_MESSAGE_PREFIX.length);
+ let seperatorPos = str.indexOf(":");
+ if (seperatorPos > 0) {
+ let strArr = [str.substring(0, seperatorPos), str.substring(seperatorPos + 1)];
+ let subscriptionId = strArr[0];
+ let jsonStr = strArr[1];
+ if (jsonStr.startsWith("[")) {
+ let events = JSON.parse(jsonStr) as SharedEvent[];
+ events.forEach(event => {
+ this._onMessageReceived(subscriptionId, event);
+ });
+ } else {
+ let event = JSON.parse(jsonStr) as SharedEvent;
+ this._onMessageReceived(subscriptionId, event);
+ }
}
- } else {
- this._onMessageReceived(e.lastEventId, e.data);
}
};
return this._connectDeferred.promise;
}
+ protected _beforeDisconnect(): void {
+ if (this._renewalTimer != null) {
+ clearInterval(this._renewalTimer);
+ this._renewalTimer = null;
+ }
+ this._onDisconnect();
+ }
+
protected _doDisconnect(): void {
this._webSocket!.close();
}
- protected _doSubscribe<T extends SharedEvent>(subscription: EventSubscription<T>): Promise<number> {
+ protected _doSubscribe<T extends SharedEvent>(subscription: EventSubscription<T>): Promise<string> {
if (!this._webSocket) {
return Promise.reject("Not connected");
}
@@ -383,14 +487,41 @@ export class WebSocketEventProvider extends EventProviderImpl {
}
this._subscribeDeferred = new Deferred();
+ subscription.subscriptionId = WebSocketEventProvider._subscriptionCounter++ + "";
this._webSocket.send(SUBSCRIBE_MESSAGE_PREFIX + JSON.stringify(subscription));
return this._subscribeDeferred.promise;
}
- protected _doUnsubscribe(subscriptionId: number): void {
+ protected _doUnsubscribe(subscriptionId: string): void {
+ if (!this._webSocket) {
+ return;
+ }
+ let cancelSubscription: CancelEventSubscription<SharedEvent> = {
+ subscriptionId: subscriptionId
+ };
+ this._webSocket.send(UNSUBSCRIBE_MESSAGE_PREFIX + JSON.stringify(cancelSubscription));
+ if (Object.keys(this._subscriptionMap).length == 0 && this._renewalTimer) {
+ clearInterval(this._renewalTimer);
+ }
+ }
+
+ protected _doRenewal() {
if (!this._webSocket) {
return;
}
- this._webSocket.send(UNSUBSCRIBE_MESSAGE_PREFIX + JSON.stringify(subscriptionId));
+
+ let renewSubscriptions: RenewEventSubscriptions = {
+ subscriptionIds: Object.keys(this._subscriptionMap)
+ };
+ this._webSocket.send(RENEW_MESSAGE_PREFIX + JSON.stringify(renewSubscriptions));
+ }
+
+ protected _doSend<T extends SharedEvent>(event: T): void {
+ if (!this._webSocket) {
+ return;
+ }
+
+ let message = EVENT_MESSAGE_PREFIX + JSON.stringify(event);
+ this._webSocket.send(message);
}
}
\ No newline at end of file
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index da5a96510..474324371 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -9,7 +9,8 @@ export enum ORError {
MANAGER_FAILED_TO_LOAD = "MANAGER_FAILED_TO_LOAD",
KEYCLOAK_FAILED_TO_LOAD = "KEYCLOAK_FAILED_TO_LOAD",
AUTH_TYPE_UNSUPPORTED = "AUTH_TYPE_UNSUPPORTED",
- CONSOLE_ERROR = "CONSOLE_INIT_ERROR"
+ CONSOLE_ERROR = "CONSOLE_INIT_ERROR",
+ EVENTS_CONNECTION_ERROR = "EVENTS_CONNECTION_ERROR"
}
export enum Auth {
@@ -99,7 +100,11 @@ export class Manager {
}
get isError() {
- return this._error != null;
+ return this._error != null && this._error !== ORError.NONE;
+ }
+
+ get connectionStatus() {
+ return this._events && this._events.status;
}
get console() {
@@ -212,9 +217,10 @@ export class Manager {
success = await this.doAuthInit();
}
- if (success) {
- success = this.doEventsSubscriptionInit();
- }
+ // TODO: Reinstate this once websocket supports anonymous connections
+ // if (success) {
+ // success = await this.doEventsSubscriptionInit();
+ // }
if (success) {
this._ready = true;
@@ -294,17 +300,23 @@ export class Manager {
return true;
}
- protected doEventsSubscriptionInit(): boolean {
+ protected async doEventsSubscriptionInit(): Promise<boolean> {
+ let connected = false;
+
switch (this._config.eventProviderType) {
case EventProviderType.WEBSOCKET:
this._events = new WebSocketEventProvider(this._config.managerUrl, (status: EventProviderStatus) => {this.onEventsProviderStatusChanged(status)});
- this._events.connect();
+ connected = await this._events.connect();
break;
case EventProviderType.POLLING:
break;
}
- return true;
+ if (!connected) {
+ this._setError(ORError.EVENTS_CONNECTION_ERROR);
+ }
+
+ return connected;
}
protected onEventsProviderStatusChanged(status: EventProviderStatus) {
@@ -572,10 +584,19 @@ export class Manager {
this._emitEvent(OREvent.ERROR);
}
+ // TODO: Remove events logic once websocket supports anonymous connections
protected _setAuthenticated(authenticated: boolean) {
this._authenticated = authenticated;
if (authenticated) {
this._emitEvent(OREvent.AUTHENTICATED);
+ if (!this._events) {
+ this.doEventsSubscriptionInit();
+ }
+ } else {
+ if (this._events != null) {
+ this._events.disconnect();
+ }
+ this._events = null;
}
}
}
diff --git a/ui/component/model/build.gradle b/ui/component/model/build.gradle
index f5b7bd21a..b73e083c9 100644
--- a/ui/component/model/build.gradle
+++ b/ui/component/model/build.gradle
@@ -33,7 +33,7 @@ generateTypeScript {
]
customTypeNamingFunction = "function(name, simpleName) { if (name.indexOf(\"\$\") > 0) return name.substr(name.lastIndexOf(\".\")+1).replace(\"\$\",\"\"); }"
customTypeMappings = [
- "org.openremote.model.value.ObjectValue:object",
+ "org.openremote.model.value.ObjectValue:{ [id: string]: any }",
"org.openremote.model.value.ArrayValue:Array<any>",
"org.openremote.model.value.NumberValue:number",
"org.openremote.model.value.StringValue:string",
diff --git a/ui/demo/demo-core/build.gradle b/ui/demo/demo-core/build.gradle
new file mode 100644
index 000000000..2aa1b243b
--- /dev/null
+++ b/ui/demo/demo-core/build.gradle
@@ -0,0 +1,11 @@
+task clean() {
+ doLast {
+ delete "dist"
+ }
+}
+
+task build() {
+ dependsOn npmBuild
+}
+
+npmBuild.dependsOn resolveTask(":ui:component:core:build")
\ No newline at end of file
diff --git a/ui/demo/demo-core/index.html b/ui/demo/demo-core/index.html
index 1308e5b8e..24f3c2629 100644
--- a/ui/demo/demo-core/index.html
+++ b/ui/demo/demo-core/index.html
@@ -7,6 +7,10 @@
<title>Demo</title>
</head>
<body>
+<div id="info"></div>
+<br />
+<br />
+<div id="asset"></div>
</body>
<script src="<%= htmlWebpackPlugin.files.js[0] %>"></script>
</html>
diff --git a/ui/demo/demo-core/src/index.ts b/ui/demo/demo-core/src/index.ts
index 2f2a32eb9..9d5dc9126 100644
--- a/ui/demo/demo-core/src/index.ts
+++ b/ui/demo/demo-core/src/index.ts
@@ -1,9 +1,25 @@
import {html, render} from "lit-html";
import {when} from "lit-html/directives/when";
-import openremote, {Auth, Manager} from "@openremote/core";
+import rest from "@openremote/rest";
+import openremote, {Auth, Manager, OREvent} from "@openremote/core";
+import {
+ AssetQuery,
+ AttributeEvent,
+ BaseAssetQueryInclude,
+ BaseAssetQueryMatch,
+ EventSubscription,
+ Asset
+} from "@openremote/model";
-let loggedInTemplate = (openremote:Manager) => html `<span>Welcome ${openremote.username}</span>(<button @click="${ ()=> {openremote.logout()}}">logout</button>)`;
-let loggedOutTemplate = (openremote:Manager) => html `<span>Please</span><button @click="${() => {openremote.login()}}">login</button>`;
+let alarmEnabled = false;
+
+let loggedInTemplate = (openremote: Manager) => html`<span>Welcome ${openremote.username} </span><button @click="${() => {
+ openremote.logout()
+}}">logout</button>`;
+
+let loggedOutTemplate = (openremote: Manager) => html`<button @click="${() => {
+ openremote.login()
+}}">login</button>`;
let mainTemplate = (openremote: Manager) => html`
<p><b>Message:</b> ${when(openremote.authenticated, () => loggedInTemplate(openremote), () => loggedOutTemplate(openremote))}</p>
@@ -15,18 +31,76 @@ let mainTemplate = (openremote: Manager) => html`
<p><b>Roles: </b> ${openremote.roles ? openremote.roles.join(", ") : ""}</p>
<p><b>Is Super User: </b> ${openremote.isSuperUser()}</p>
<p><b>Is Manager Same Origin: </b> ${openremote.isManagerSameOrigin()}</p>
+<p><b>Connection Status: </b> ${openremote.connectionStatus}</p>
<p><b>Is Error: </b> ${openremote.isError}</p>
<p><b>Error:</b> ${openremote.error}</p>
-<p><b>Config: </b> ${openremote.config ? JSON.stringify(openremote.config) : ""}</p>
-<p><b>Console Registration: </b>${openremote.console ? JSON.stringify(openremote.console.registration) : ""}</p>
+<p><b>Config: </b> ${openremote.config ? JSON.stringify(openremote.config, null, 2) : ""}</p>
+<p><b>Console Registration: </b>${openremote.console ? JSON.stringify(openremote.console.registration, null, 2) : ""}</p>
+`;
+
+let assetTemplate = (alarmEnabled: boolean) => html `
+<p><b>Alarm Enabled: </b> ${alarmEnabled}</p>
`;
-function refresh() {
- render(mainTemplate(openremote), document.body);
+async function refreshUI() {
+ render(mainTemplate(openremote), document.getElementById("info")!);
+ render(assetTemplate(alarmEnabled), document.getElementById("asset")!);
+}
+
+async function subscribeApartmentAttributeEvents(assetId: string) {
+
+ let callback: (event: AttributeEvent) => void = (event) => {
+ console.log("Event Received:" + JSON.stringify(event, null, 2));
+ if (event.attributeState && event.attributeState.attributeRef!.attributeName === "alarmEnabled") {
+ alarmEnabled = event.attributeState!.value;
+ refreshUI();
+ }
+ };
+
+ let subscriptionId = await openremote.events!.subscribeAttributeEvents([assetId], callback);
+ console.log("Subscribed: " + subscriptionId);
}
-openremote.addListener(event => {
+async function initApartment1Asset(): Promise<void> {
+ let query: AssetQuery = {
+ name: {
+ predicateType: "string",
+ match: BaseAssetQueryMatch.EXACT,
+ value: "Apartment 1"
+ },
+ type: {
+ predicateType: "string",
+ match: BaseAssetQueryMatch.EXACT,
+ value: "urn:openremote:asset:residence"
+ },
+ select: {
+ include: BaseAssetQueryInclude.ONLY_ID_AND_NAME
+ }
+ };
+
+ let response = await rest.api.AssetResource.queryAssets(query);
+ let assets = response.data;
+
+ if (assets.length !== 1) {
+ console.log("Failed to retrieve the 'Apartment 1' asset");
+ return;
+ }
+
+ let apartment1 = assets[0];
+ console.log("Apartment 1 Asset received: " + JSON.stringify(apartment1, null, 2));
+ subscribeApartmentAttributeEvents(apartment1.id!);
+}
+
+openremote.addListener((event: OREvent) => {
console.log("OR Event:" + event);
+
+ switch(event) {
+ case OREvent.AUTHENTICATED:
+ initApartment1Asset().then(refreshUI);
+ break;
+ default:
+ refreshUI();
+ }
});
openremote.init({
@@ -34,5 +108,6 @@ openremote.init({
keycloakUrl: "http://192.168.1.85:8080/auth",
auth: Auth.KEYCLOAK,
autoLogin: false,
- realm: "master"
-}).then(refresh);
\ No newline at end of file
+ realm: "tenantA"
+})
+;
diff --git a/ui/demo/demo-core/webpack.config.js b/ui/demo/demo-core/webpack.config.js
index ca8e0d62c..3334a3985 100644
--- a/ui/demo/demo-core/webpack.config.js
+++ b/ui/demo/demo-core/webpack.config.js
@@ -1,4 +1,5 @@
var HtmlWebpackPlugin = require("html-webpack-plugin");
+var path = require("path");
module.exports = {
mode: 'development',