100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
UI updates: Improved event subscription
Rich Turner63fdf8c0c66e
diff --git a/ui/app/or-app/src/or-header.ts b/ui/app/or-app/src/or-header.tsindex 6d0d8752d..ca2ed9d7d 100644--- a/ui/app/or-app/src/or-header.ts+++ b/ui/app/or-app/src/or-header.ts@@ -340,6 +340,8 @@ class OrHeader extends LitElement {public connectedCallback(): void {super.connectedCallback();window.addEventListener("hashchange", this._hashCallback, false);+ const realm = window.sessionStorage.getItem('realm');+ if (realm) manager.displayRealm = realm;}public disconnectedCallback(): void {@@ -433,8 +435,6 @@ class OrHeader extends LitElement {return html``;}- const realm = window.sessionStorage.getItem('realm');- if(realm) manager.displayRealm = realm;const picker = this._getTenants().then((tenants) => {const menuItems = tenants.map((r) => {diff --git a/ui/app/or-app/src/pages/page-map.ts b/ui/app/or-app/src/pages/page-map.tsindex 093ba9d77..cddfb611d 100644--- a/ui/app/or-app/src/pages/page-map.ts+++ b/ui/app/or-app/src/pages/page-map.ts@@ -11,7 +11,7 @@ import {} from "@openremote/or-map";import manager, {OREvent, Util} from "@openremote/core";import {createSelector} from "reselect";-import {Asset, AssetEvent, AssetEventCause, AttributeEvent, GeoJSONPoint, Attribute, WellknownMetaItems, WellknownAttributes, AssetQueryOperator, LogicGroupOperator} from "@openremote/model";+import {Asset, AssetEvent, AssetEventCause, AttributeEvent, GeoJSONPoint, Attribute, WellknownMetaItems, WellknownAttributes, LogicGroupOperator} from "@openremote/model";import {getAssetsRoute} from "./page-assets";import {Page, router} from "../types";import {AppStateKeyed} from "../app";@@ -19,8 +19,6 @@ import {AppStateKeyed} from "../app";export interface MapState {assets: Asset[];currentAssetId: string;- assetSubscriptionId: string;- attributeSubscriptionId: string;}export interface MapStateKeyed extends AppStateKeyed {@@ -29,9 +27,7 @@ export interface MapStateKeyed extends AppStateKeyed {const INITIAL_STATE: MapState = {assets: [],- currentAssetId: undefined,- assetSubscriptionId: undefined,- attributeSubscriptionId: undefined+ currentAssetId: undefined};const pageMapSlice = createSlice({@@ -74,23 +70,11 @@ const pageMapSlice = createSlice({...state,assets: action.payload};- },- setAssetSubscriptionId(state, action: PayloadAction<string>) {- return {- ...state,- assetSubscriptionId: action.payload- };- },- setAttributeSubscriptionId(state, action: PayloadAction<string>) {- return {- ...state,- attributeSubscriptionId: action.payload- };}}});-const {assetEventReceived, attributeEventReceived, setAssets, setAssetSubscriptionId, setAttributeSubscriptionId} = pageMapSlice.actions;+const {assetEventReceived, attributeEventReceived, setAssets} = pageMapSlice.actions;export const pageMapReducer = pageMapSlice.reducer;export function pageMapProvider<S extends MapStateKeyed>(store: EnhancedStore<S>, config?:MapAssetCardConfig) {@@ -167,13 +151,19 @@ export class PageMap<S extends MapStateKeyed> extends Page<S> {protected _assetSelector = (state: S) => state.map.assets;protected _paramsSelector = (state: S) => state.app.params;+ protected subscribedRealm?: string;+ protected assetSubscriptionId: string;+ protected attributeSubscriptionId: string;protected subscribeAssets = (): ThunkAction<void, MapStateKeyed, unknown, Action<string>> => async (dispatch) => {+ const realm = manager.displayRealm;+ this.subscribedRealm = realm;+try {const result = await manager.rest.api.AssetResource.queryAssets({tenant: {- realm: manager.displayRealm+ realm: realm},select: {attributes: [WellknownAttributes.LOCATION],@@ -220,51 +210,60 @@ export class PageMap<S extends MapStateKeyed> extends Page<S> {}});+ if (realm !== this.subscribedRealm) {+ // Realm has changed+ return;+ }++ if (!this.isConnected) {+ return;+ }+if (result.data) {const assets = result.data;- dispatch(setAssets(assets))+ dispatch(setAssets(assets));const ids = result.data.map(asset => asset.id);- const assetSubscriptionId = await manager.events.subscribeAssetEvents(ids, false, {filterType: "asset", attributeNames: [WellknownAttributes.LOCATION]}, (event) => {+ const assetSubscriptionId = await manager.events.subscribeAssetEvents(ids, false, undefined, (event) => {dispatch(assetEventReceived(event));});- if (!this.isConnected) {+ if (!this.isConnected || realm !== this.subscribedRealm) {manager.events.unsubscribe(assetSubscriptionId);return;}- dispatch(setAssetSubscriptionId(assetSubscriptionId));+ this.assetSubscriptionId = assetSubscriptionId;const attributeSubscriptionId = await manager.events.subscribeAttributeEvents(ids, false, (event) => {dispatch(attributeEventReceived(event));});- if (!this.isConnected) {+ if (!this.isConnected || realm !== this.subscribedRealm) {+ manager.events.unsubscribe(assetSubscriptionId);manager.events.unsubscribe(attributeSubscriptionId);return;}- dispatch(setAttributeSubscriptionId(attributeSubscriptionId));+ this.attributeSubscriptionId = attributeSubscriptionId;}-} catch (e) {console.error("Failed to subscribe to assets", e)}};protected unsubscribeAssets = (): ThunkAction<void, MapStateKeyed, unknown, Action<string>> => (dispatch, getState) => {- if (getState().map.assetSubscriptionId) {- manager.events.unsubscribe(getState().map.assetSubscriptionId);- dispatch(setAssetSubscriptionId(null));+ if (this.assetSubscriptionId) {+ manager.events.unsubscribe(this.assetSubscriptionId);+ this.assetSubscriptionId = undefined;}- if (getState().map.attributeSubscriptionId) {- manager.events.unsubscribe(getState().map.attributeSubscriptionId);- dispatch(setAttributeSubscriptionId(null));+ if (this.attributeSubscriptionId) {+ manager.events.unsubscribe(this.attributeSubscriptionId);+ this.attributeSubscriptionId = undefined;}};@@ -320,7 +319,7 @@ export class PageMap<S extends MapStateKeyed> extends Page<S> {<or-map-marker-asset ?active="${this._currentAsset && this._currentAsset.id === asset.id}" .asset="${asset}"></or-map-marker-asset>`;})- }+ }</or-map>`;}diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.tsindex e880305c8..1b46c0e49 100644--- a/ui/component/core/src/event.ts+++ b/ui/component/core/src/event.ts@@ -12,6 +12,7 @@ import {EventRequestResponseWrapper,EventSubscription,ReadAssetsEvent,+ ReadAttributeEvent,SharedEvent,TriggeredEventSubscription} from "@openremote/model";@@ -37,8 +38,15 @@ export interface EventProvider {unsubscribe<T extends SharedEvent>(subscriptionId: string): void;+ /**+ * Subscribe to {@link AssetEvent}s for the specified {@link Asset}s for all {@link Asset}s+ */subscribeAssetEvents(ids: string[] | AttributeRef[] | null, requestCurrentValues: boolean, filter: AssetFilter | undefined, callback: (event: AssetEvent) => void): Promise<string>;+ /**+ * Subscribe to {@link AttributeEvent}s for the specified {@link Asset}s and if {@link AttributeRef}s are provided+ * then the attribute names from the refs will be used for each asset ID.+ */subscribeAttributeEvents(ids: string[] | AttributeRef[], requestCurrentValues: boolean, callback: (event: AttributeEvent) => void): Promise<string>;sendEvent<T extends SharedEvent>(event: T): void;@@ -83,8 +91,11 @@ abstract class EventProviderImpl implements EventProvider {protected _statusCallbacks: Array<(status: EventProviderStatus) => void> = [];protected _pendingSubscription: EventSubscriptionInfo<SharedEvent> | null = null;protected _queuedSubscriptions: EventSubscriptionInfo<SharedEvent>[] = [];- protected _subscriptionMap: { [id: string]: EventSubscriptionInfo<SharedEvent> } = {};- protected _assetSubscriptionMap: Map<string, AssetSubscriptionInfo> = new Map<string, AssetSubscriptionInfo>();+ protected _subscriptionMap: Map<string, EventSubscriptionInfo<SharedEvent>> = new Map();+ protected _assetEventPromise?: Promise<string>;+ protected _assetEventCallbackMap: Map<string, (e: AssetEvent) => void> = new Map();+ protected _attributeEventPromise?: Promise<string>;+ protected _attributeEventCallbackMap: Map<string, (e: AttributeEvent) => void> = new Map();protected static _subscriptionCounter: number = 0;abstract get endpointUrl(): string;@@ -186,7 +197,7 @@ abstract class EventProviderImpl implements EventProvider {this._pendingSubscription = null;// Store subscriptionId and callback- this._subscriptionMap[subscriptionId] = subscription;+ this._subscriptionMap.set(subscriptionId, subscription);this._processNextSubscription();const deferred = subscription.deferred;@@ -214,27 +225,31 @@ abstract class EventProviderImpl implements EventProvider {return this._pendingSubscription.deferred!.promise;}- public unsubscribe<T extends SharedEvent>(subscriptionId: string) {-- const callback = this._subscriptionMap[subscriptionId];+ public async unsubscribe<T extends SharedEvent>(subscriptionId: string): Promise<void> {- if (callback) {- delete this._subscriptionMap[subscriptionId];+ if (this._subscriptionMap.delete(subscriptionId)) {this._doUnsubscribe(subscriptionId);- } else {- const removeSubscriptions: string[] = [];- this._assetSubscriptionMap.forEach((info, key) => {- const callbackMap = info.callbacks;- callbackMap.delete(subscriptionId);- if (callbackMap.size === 0) {- removeSubscriptions.push(key);- }- });+ return;+ }- removeSubscriptions.forEach((subscriptionIdToRemove) => {- this._assetSubscriptionMap.delete(subscriptionIdToRemove);- this.unsubscribe(subscriptionIdToRemove);- });+ if (this._assetEventCallbackMap.delete(subscriptionId)) {+ if (this._assetEventPromise && this._assetEventCallbackMap.size === 0) {+ // Remove the asset subscription+ const assetEventSubscriptionId = await this._assetEventPromise;+ this._assetEventPromise = undefined;+ this.unsubscribe(assetEventSubscriptionId);+ }+ return;+ }++ if (this._attributeEventCallbackMap.delete(subscriptionId)) {+ if (this._attributeEventPromise && this._attributeEventCallbackMap.size === 0) {+ // Remove the attribute subscription+ const attributeEventSubscriptionId = await this._attributeEventPromise;+ this._attributeEventPromise = undefined;+ this.unsubscribe(attributeEventSubscriptionId);+ }+ return;}}@@ -254,71 +269,81 @@ abstract class EventProviderImpl implements EventProvider {public async subscribeAssetEvents(ids: string[] | AttributeRef[] | null, requestCurrentValues: boolean, filter: AssetFilter | undefined, callback: (event: AssetEvent) => void): Promise<string> {- const subscription: EventSubscription<AssetEvent> = {- eventType: "asset"- };-const isAttributeRef = ids && typeof ids[0] !== "string";const assetIds = isAttributeRef ? (ids as AttributeRef[]).map((ref) => ref.id!) : ids as string[] | null;+ const subscriptionId = "AssetEvent" + EventProviderImpl._subscriptionCounter++;- if (filter || assetIds && assetIds.length > 0) {+ // If not already done then create a single global subscription for asset events and filter for each callback+ if (!this._assetEventPromise) {- if (!filter) {- filter = {- filterType: "asset"- };- }+ const subscription: EventSubscription<AssetEvent> = {+ eventType: "asset"+ };+ this._assetEventPromise = this.subscribe(subscription, (event) => {+ this._assetEventCallbackMap.forEach((callback) => callback(event));+ });+ }- if (assetIds && assetIds.length > 0) {- filter.assetIds = assetIds;+ // Build a filter to only respond to the callback for the requested assets+ const eventFilter = (e: AssetEvent) => {+ if (!assetIds) {+ callback(e);+ return;}+ if (!e.asset) {+ return;+ }+ if (assetIds.find((id) => id === e.asset!.id)) {+ callback(e);+ }+ };- subscription.filter = filter;- }-- let subscriptionId: string | null = null;+ this._assetEventCallbackMap.set(subscriptionId, eventFilter);- try {- subscriptionId = await this.subscribe(subscription, callback);+ return this._assetEventPromise.then(() => {- // Get the current state of the assets- if (assetIds && requestCurrentValues) {- const readRequest: EventRequestResponseWrapper<ReadAssetsEvent> = {- messageId: "read-assets:" + assetIds.join(",") + ":" + subscriptionId,- event: {- eventType: "read-assets",- assetQuery: {- ids: assetIds+ try {+ // Get the current state of the assets if requested+ if (assetIds && requestCurrentValues) {+ const readRequest: EventRequestResponseWrapper<ReadAssetsEvent> = {+ messageId: "read-assets:" + assetIds.join(",") + ":" + subscriptionId,+ event: {+ eventType: "read-assets",+ assetQuery: {+ ids: assetIds+ }}}+ this.sendEventWithReply(readRequest)+ .then((e: SharedEvent) => {+ const assetsEvent = e as AssetsEvent;+ // Check subscription still exists+ if (!assetsEvent.assets || !this._assetEventCallbackMap.has(subscriptionId)) {+ return;+ }++ assetsEvent.assets.forEach((asset) => {+ const assetEvent: AssetEvent = {+ eventType: "asset",+ asset: asset,+ cause: AssetEventCause.READ+ };+ eventFilter(assetEvent);+ });+ });}- const response: AssetsEvent = await this.sendEventWithReply(readRequest);- if (response.assets) {- response.assets.forEach((asset) => {- const assetEvent: AssetEvent = {- eventType: "asset",- asset: asset,- cause: AssetEventCause.READ- };- callback(assetEvent);- });+ } catch (e) {+ console.error("Failed to subscribe to asset events for assets: " + ids);+ if (subscriptionId) {+ this.unsubscribe(subscriptionId);}+ throw e;}- } catch (e) {- console.error("Failed to subscribe to asset events for assets: " + ids);- if (subscriptionId) {- this.unsubscribe(subscriptionId);- }- throw e;- }- return subscriptionId!;+ return subscriptionId;+ });}- /**- * Subscribe for updates to a particular attribute; internally this creates subscriptions for all attributes of an- * asset and manages delivery of the update attributes to the subscribers- */public async subscribeAttributeEvents(ids: string[] | AttributeRef[], requestCurrentValues: boolean, callback: (event: AttributeEvent) => void): Promise<string> {if (!ids || ids.length === 0) {@@ -330,115 +355,89 @@ abstract class EventProviderImpl implements EventProvider {const attributes = isAttributeRef ? ids as AttributeRef[] : undefined;const subscriptionId = "AttributeEvent" + EventProviderImpl._subscriptionCounter++;- // Check if we have an existing subscription for each asset, otherwise create one- const assetSubscriptions = assetIds.map(- (assetId) => {- const assetAttributes = attributes ? attributes.filter((ref) => ref.id === assetId) : undefined;- let info = this._assetSubscriptionMap.get(assetId);- let promise: Promise<any> = Promise.resolve(assetId);-- if (!info) {- info = {- callbacks: new Map<string, (attributeEvent: AttributeEvent) => void>()- };-- this._assetSubscriptionMap.set(assetId, info);- const subscription: EventSubscription<AttributeEvent> = {- subscriptionId: assetId,- eventType: "attribute",- filter: {- filterType: "asset",- assetIds: [assetId]- }- };- promise = this.subscribe(subscription, (evt) => {- const assetSubscription = this._assetSubscriptionMap.get(assetId);-- if (!assetSubscription) {- return;- }+ // If not already done then create a single global subscription for asset events and filter for each callback+ if (!this._attributeEventPromise) {- // Keep cached asset in sync- if (assetSubscription.asset) {- if (evt.attributeState!.deleted) {- delete assetSubscription.asset.attributes![evt.attributeState!.ref!.name!];- } else {- const attr = assetSubscription.asset.attributes![evt.attributeState!.ref!.name!];- attr.value = evt.attributeState!.value;- attr.timestamp = evt.timestamp;- }- }+ const subscription: EventSubscription<AttributeEvent> = {+ eventType: "attribute"+ };+ this._attributeEventPromise = this.subscribe(subscription, (event) => {+ this._attributeEventCallbackMap.forEach((callback) => callback(event));+ });+ }- assetSubscription.callbacks.forEach((cb, key) => {- cb(evt);- });- }).then((sId) => {- // Get and store the asset so we can quickly provide the current value of attributes- const readEvent: EventRequestResponseWrapper<ReadAssetsEvent> = {- event: {- eventType: "read-assets",- assetQuery: {- ids: [assetId],- select: {- excludeParentInfo: true,- excludePath: true- }- }- }- };- return this.sendEventWithReply(readEvent);- }).then((response) => {- const assetsEvent = response as AssetsEvent;- if (assetsEvent.assets && assetsEvent.assets.length === 1) {- info!.asset = assetsEvent.assets[0];- }- info!.promise = undefined;- })- info.promise = promise;- } else if (info.promise) {- promise = info.promise;+ // Build a filter to only respond to the callback for the requested attributes+ const eventFilter = (e: AttributeEvent) => {+ ids.forEach((idOrRef: string | AttributeRef) => {+ if (typeof (idOrRef) === "string") {+ if (e.attributeState!.ref!.id === idOrRef) {+ callback(e);+ }+ } else {+ const eventRef = e.attributeState!.ref!;+ if (eventRef.id === idOrRef.id && eventRef.name === idOrRef.name) {+ callback(e);+ }}+ });+ };++ this._attributeEventCallbackMap.set(subscriptionId, eventFilter);- info.callbacks.set(subscriptionId, (evt) => {- if (assetAttributes) {- if (assetAttributes.find((attributeRef) => evt.attributeState!.ref!.name === attributeRef.name)) {- callback(evt);+ return this._attributeEventPromise.then(() => {++ try {+ // Get the current state of the attributes if requested+ if (requestCurrentValues) {+ // Just request the whole asset(s) and let the event filter do the work+ const readRequest: EventRequestResponseWrapper<ReadAssetsEvent> = {+ messageId: "read-assets:" + assetIds.join(",") + ":" + subscriptionId,+ event: {+ eventType: "read-assets",+ assetQuery: {+ ids: assetIds+ }}- } else {- callback(evt);}- });+ this.sendEventWithReply(readRequest)+ .then((e: SharedEvent) => {+ const assetsEvent = e as AssetsEvent;+ // Check subscription still exists+ if (!assetsEvent.assets || !this._attributeEventCallbackMap.has(subscriptionId)) {+ return;+ }- return promise;- }- )-- await Promise.all(assetSubscriptions);-- if (requestCurrentValues) {- assetIds.forEach((assetId) => {- const info = this._assetSubscriptionMap.get(assetId);- if (info && info.asset) {- Object.entries(info.asset.attributes!).forEach(([attributeName, attr]) => {- if (!attributes || attributes.find((ref) => ref.id === info.asset!.id && ref.name === attributeName)) {- callback({- eventType: "attribute",- timestamp: attr.timestamp,- attributeState: {- value: attr.value,- ref: {- id: assetId,- name: attributeName- }+ assetsEvent.assets.forEach((asset) => {+ if (asset.attributes) {+ Object.entries(asset.attributes!).forEach(([attributeName, attr]) => {+ if (!attributes || attributes.find((ref) => ref.id === asset!.id && ref.name === attributeName)) {+ eventFilter({+ eventType: "attribute",+ timestamp: attr.timestamp,+ attributeState: {+ value: attr.value,+ ref: {+ id: asset.id,+ name: attributeName+ }+ }+ });+ }+ });}});- }- });+ });}- });- }+ } catch (e) {+ console.error("Failed to subscribe to asset events for assets: " + ids);+ if (subscriptionId) {+ this.unsubscribe(subscriptionId);+ }+ throw e;+ }- return subscriptionId;+ return subscriptionId;+ });}protected _processNextSubscription() {@@ -484,7 +483,7 @@ abstract class EventProviderImpl implements EventProvider {}protected _onMessageReceived(subscriptionId: string, event: SharedEvent) {- const subscriptionInfo = this._subscriptionMap[subscriptionId];+ const subscriptionInfo = this._subscriptionMap.get(subscriptionId);if (subscriptionInfo) {subscriptionInfo.callback(event);@@ -496,11 +495,11 @@ abstract class EventProviderImpl implements EventProvider {if (Object.keys(this._subscriptionMap).length > 0) {for (const subscriptionId in this._subscriptionMap) {- if (this._subscriptionMap.hasOwnProperty(subscriptionId)) {- this._queuedSubscriptions.unshift(this._subscriptionMap[subscriptionId]);+ if (this._subscriptionMap.has(subscriptionId)) {+ this._queuedSubscriptions.unshift(this._subscriptionMap.get(subscriptionId)!);}}- this._subscriptionMap = {};+ this._subscriptionMap.clear();}this._processNextSubscription();diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.tsindex 4ee176759..6262add0a 100644--- a/ui/component/core/src/index.ts+++ b/ui/component/core/src/index.ts@@ -507,7 +507,7 @@ export class Manager implements EventProviderFactory {}set displayRealm(realm: string) {- if (!this.isSuperUser()) {+ if (!this.isSuperUser() || this._displayRealm === realm) {return;}this._displayRealm = realm;diff --git a/ui/component/or-map/src/markers/or-map-marker-asset.ts b/ui/component/or-map/src/markers/or-map-marker-asset.tsindex f024c0d3c..d91a48d1a 100644--- a/ui/component/or-map/src/markers/or-map-marker-asset.ts+++ b/ui/component/or-map/src/markers/or-map-marker-asset.ts@@ -3,7 +3,6 @@ import {OrMapMarker} from "./or-map-marker";import {AttributeEvent, GeoJSONPoint, AssetEvent, AssetEventCause, Asset, SharedEvent, AssetDescriptor, WellknownAttributes} from "@openremote/model";import {subscribe} from "@openremote/core";import manager, {AssetModelUtil} from "@openremote/core";-import {Util} from "@openremote/core";export function getMarkerIconAndColorFromAssetType(type: AssetDescriptor | string | undefined): {icon: string, color: string | undefined} | undefined {if (!type) {