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
Fix or-attribute-input write and improve event subscriptions
Rich Turner901502ed64e5
diff --git a/ui/component/core/src/asset-mixin.ts b/ui/component/core/src/asset-mixin.tsindex 77a76c7c9..ad25df57d 100644--- a/ui/component/core/src/asset-mixin.ts+++ b/ui/component/core/src/asset-mixin.ts@@ -99,19 +99,19 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte* custom subscriptions.* Returns the subscription IDs of any created subscriptions*/- public async _addEventSubscriptions(): Promise<string[]> {+ public async _addEventSubscriptions(): Promise<void> {const isAttributes = !!this._attributeRefs;const ids: string[] | AttributeRef[] | undefined = this._attributeRefs ? this._attributeRefs : this._assetIds;- const subscriptions = [];+ this._subscriptionIds = [];if (ids && ids.length > 0) {if (!isAttributes) {- subscriptions.push(await eventProviderFactory.getEventProvider()!.subscribeAssetEvents(ids, true, (event) => this._onEvent(event)));+ const assetSubscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAssetEvents(ids, true, (event) => this._onEvent(event));+ this._subscriptionIds.push(assetSubscriptionId);}- subscriptions.push(await eventProviderFactory.getEventProvider()!.subscribeAttributeEvents(ids, isAttributes, (event) => this._onEvent(event)));+ const subscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAttributeEvents(ids, isAttributes, (event) => this._onEvent(event));+ this._subscriptionIds.push(subscriptionId);}-- return subscriptions;}public _removeEventSubscriptions() {@@ -153,6 +153,10 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T extethis._refreshEventSubscriptions();}+ public get attributeRefs(): AttributeRef[] | undefined {+ return this._attributeRefs;+ }+public _sendEvent(event: SharedEvent) {eventProviderFactory.getEventProvider()!.sendEvent(event);}diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.tsindex 15b7305ec..bd53a13f8 100644--- a/ui/component/core/src/event.ts+++ b/ui/component/core/src/event.ts@@ -1,17 +1,18 @@import manager from "./index";import {arrayRemove, Deferred} from "./util";import {+ Asset,+ AssetEvent,+ AssetEventCause,+ AssetsEvent,AttributeEvent,+ AttributeRef,CancelEventSubscription,+ EventRequestResponseWrapper,EventSubscription,+ ReadAssetsEvent,SharedEvent,- AssetEvent,TriggeredEventSubscription,- AttributeRef,- EventRequestResponseWrapper,- ReadAssetsEvent,- AssetsEvent,- AssetEventCause,Attribute} from "@openremote/model";@@ -56,6 +57,12 @@ interface EventSubscriptionInfo<T extends SharedEvent> {deferred: Deferred<string> | null;}+interface AssetSubscriptionInfo {+ callbacks: Map<string, (attributeEvent: AttributeEvent) => void>;+ asset?: Asset;+ promise?: Promise<void>;+}+const SUBSCRIBE_MESSAGE_PREFIX = "SUBSCRIBE:";const SUBSCRIBED_MESSAGE_PREFIX = "SUBSCRIBED:";const UNSUBSCRIBE_MESSAGE_PREFIX = "UNSUBSCRIBE:";@@ -77,6 +84,8 @@ abstract class EventProviderImpl implements EventProvider {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 static _subscriptionCounter: number = 0;abstract get endpointUrl(): string;@@ -208,9 +217,24 @@ abstract class EventProviderImpl implements EventProvider {public unsubscribe<T extends SharedEvent>(subscriptionId: string) {const callback = this._subscriptionMap[subscriptionId];+if (callback) {delete this._subscriptionMap[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);+ }+ });++ removeSubscriptions.forEach((subscriptionIdToRemove) => {+ this._assetSubscriptionMap.delete(subscriptionIdToRemove);+ this.unsubscribe(subscriptionIdToRemove);+ });}}@@ -287,6 +311,10 @@ abstract class EventProviderImpl implements EventProvider {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) {@@ -296,76 +324,107 @@ abstract class EventProviderImpl implements EventProvider {const isAttributeRef = typeof ids[0] !== "string";const assetIds = isAttributeRef ? [...new Set((ids as AttributeRef[]).map((id) => id.entityId!))] : [...new Set(ids as string[])];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((attributeRef) => attributeRef.entityId === 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);- const subscription: EventSubscription<AttributeEvent> = {- eventType: "attribute",- filter: {- filterType: "asset",- assetIds: assetIds- }- };-- let subscriptionId: string | null = null;+ if (!assetSubscription) {+ return;+ }- try {- subscriptionId = await this.subscribe(subscription, (evt) => {- if (attributes) {- // Filter events for these attributes- const eventRef = evt.attributeState!.attributeRef!;- if (attributes.findIndex((attrRef) => eventRef.entityId === attrRef.entityId && eventRef.attributeName === attrRef.attributeName) >= 0) {- callback(evt);- }- } else {- callback(evt);+ 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;}- });- // Get the current value of each assets attributes- if (requestCurrentValues) {- const readEvent: EventRequestResponseWrapper<ReadAssetsEvent> = {- messageId: "read-assets:" + assetIds.join("") + ":" + subscriptionId,- event: {- eventType: "read-assets",- assetQuery: {- ids: assetIds,- select: {- excludeParentInfo: true,- excludePath: true- }+ info.callbacks.set(subscriptionId, (evt) => {+ if (assetAttributes) {+ if (assetAttributes.find((attributeRef) => evt.attributeState!.attributeRef!.attributeName === attributeRef.attributeName)) {+ callback(evt);}+ } else {+ callback(evt);}- };- const response: AssetsEvent = await this.sendEventWithReply(readEvent);- if (response.assets) {- response.assets.forEach((asset) => {- Object.entries(asset.attributes!).forEach(([attributeName, v]) => {- const attr = v as Attribute;- if (!attributes || attributes.find((attributeRef) => attributeRef.entityId === asset.id && attributeRef.attributeName === attributeName)) {- callback({- eventType: "attribute",- timestamp: attr.valueTimestamp,- attributeState: {- value: attr.value,- attributeRef: {- entityId: asset.id,- attributeName: attributeName- }+ });++ 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, v]) => {+ const attr = v as Attribute;+ if (!attributes || attributes.find((attributeRef) => attributeRef.entityId === info.asset!.id && attributeRef.attributeName === attributeName)) {+ callback({+ eventType: "attribute",+ timestamp: attr.valueTimestamp,+ attributeState: {+ value: attr.value,+ attributeRef: {+ entityId: assetId,+ attributeName: attributeName}- });- }- });- })+ }+ });+ }+ });}- }- } catch (e) {- console.error("Failed to subscribe to attribute events for assets/attributes: " + assetIds.join(", "));- if (subscriptionId) {- this.unsubscribe(subscriptionId);- }- throw e;+ });}- return subscriptionId!;+ return subscriptionId;}protected _processNextSubscription() {@@ -619,7 +678,9 @@ export class WebSocketEventProvider extends EventProviderImpl {}this._subscribeDeferred = new Deferred();- subscription.subscriptionId = WebSocketEventProvider._subscriptionCounter++ + "";+ if (!subscription.subscriptionId) {+ subscription.subscriptionId = WebSocketEventProvider._subscriptionCounter++ + "";+ }this._webSocket.send(SUBSCRIBE_MESSAGE_PREFIX + JSON.stringify(subscription));return this._subscribeDeferred.promise;}diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.tsindex 19cd52633..9c80a30e5 100644--- a/ui/component/or-asset-viewer/src/index.ts+++ b/ui/component/or-asset-viewer/src/index.ts@@ -271,13 +271,13 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: Assif (!childAssetTypeAttribute || typeof childAssetTypeAttribute.value !== "string") {return;}- let childAssetType = childAssetTypeAttribute.value as string;+ const childAssetType = childAssetTypeAttribute.value as string;let childAssets: Asset[] = [];// Determine available and selected attributes for the child asset typelet availableAttributes: string[] = [];let selectedAttributes: string[] = [];- let newlySelectedAttributes: string[] = []; // Updated when the dialog is open+ const newlySelectedAttributes: string[] = []; // Updated when the dialog is openif (groupConfig.childAssetTypes && groupConfig.childAssetTypes[childAssetType]) {availableAttributes = groupConfig.childAssetTypes[childAssetType].availableAttributes ? groupConfig.childAssetTypes[childAssetType].availableAttributes! : [];@@ -288,7 +288,7 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: Assif (availableAttributes.length === 0) {const descriptor = AssetModelUtil.getAssetDescriptor(childAssetType);if (descriptor && descriptor.attributeDescriptors) {- availableAttributes = descriptor.attributeDescriptors.map((descriptor) => descriptor.attributeName!);+ availableAttributes = descriptor.attributeDescriptors.map((desc) => desc.attributeName!);}}if ((!selectedAttributes || selectedAttributes.length === 0) && availableAttributes) {@@ -327,7 +327,7 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: Ass${availableAttributes.sort().map((attribute) =>html`<div style="grid-column: 1 / -1;"><or-input .type="${InputType.CHECKBOX}" .label="${i18next.t(attribute)}" .value="${!!newlySelectedAttributes.find((selected) => selected === attribute)}"- @or-input-changed="${(evt: OrInputChangedEvent) => evt.detail.value ? newlySelectedAttributes.push(attribute) : newlySelectedAttributes.splice(newlySelectedAttributes.findIndex((s) => s == attribute), 1)}"></or-input>+ @or-input-changed="${(evt: OrInputChangedEvent) => evt.detail.value ? newlySelectedAttributes.push(attribute) : newlySelectedAttributes.splice(newlySelectedAttributes.findIndex((s) => s === attribute), 1)}"></or-input></div>`)}</div>`;@@ -336,7 +336,7 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: Ass};// Function to update the table and message when assets or config changes- let updateTable = () => {+ const updateTable = () => {const loadingMsg: OrTranslate = hostElement.shadowRoot!.getElementById(panelName + "-attribute-table-msg") as OrTranslate;const attributeTable: OrTable = hostElement.shadowRoot!.getElementById(panelName + "-attribute-table") as OrTable;@@ -361,13 +361,13 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: Assconst headers = [...selectedAttributes].sort();attributeTable.headers = headers.map((header) => i18next.t(header));attributeTable.headers.unshift(i18next.t("groupAssetName"));- attributeTable.rows = childAssets.map((asset) => {+ attributeTable.rows = childAssets.map((childAsset) => {// todo: it's only processing including selected headers here...// move this to the columnFilter option of the tableconst arr = headers.map((attributeName) => {- return asset.attributes![attributeName] ? asset.attributes![attributeName].value! as string : "";+ return childAsset.attributes![attributeName] ? childAsset.attributes![attributeName].value! as string : "";});- arr.unshift(asset.name!);+ arr.unshift(childAsset.name!);return arr;});window.setTimeout(() => OrAssetViewer.generateGrid(hostElement.shadowRoot), 0);@@ -405,10 +405,9 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: Asscontent = html`${attrs.sort((attr1, attr2) => attr1.name! < attr2.name! ? -1 : attr1.name! > attr2.name! ? 1 : 0).map((attr) => {- let style = styles ? styles[attr.name!] : undefined;- return getField(attr.name!, false, style, getAttributeTemplate(asset, attr, hostElement, viewerConfig, panelConfig));- })}- `;+ const attrStyle = styles ? styles[attr.name!] : undefined;+ return getField(attr.name!, false, attrStyle, getAttributeTemplate(asset, attr, hostElement, viewerConfig, panelConfig));+ })}`;}return content;@@ -652,8 +651,8 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElemif (shadowRoot) {const grid = shadowRoot.querySelector('#container');if (grid) {- const rowHeight = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-auto-rows'));- const rowGap = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-row-gap'));+ const rowHeight = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-auto-rows'), 10);+ const rowGap = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-row-gap'), 10);const items = shadowRoot.querySelectorAll('.panel');if (items) {items.forEach((item) => {diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.tsindex 9bc4e686f..927efd6f6 100644--- a/ui/component/or-attribute-input/src/index.ts+++ b/ui/component/or-attribute-input/src/index.ts@@ -168,10 +168,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitEpublic disconnectedCallback() {super.disconnectedCallback();- if (this._writeTimeoutHandler) {- window.clearTimeout(this._writeTimeoutHandler);- this._writeTimeoutHandler = undefined;- }+ this._clearWriteTimeout();}public shouldUpdate(_changedProperties: PropertyValues): boolean {@@ -190,7 +187,33 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitEupdateDescriptors = true;}- if (_changedProperties.has("attribute") || _changedProperties.has("attributeRef")) {+ if (_changedProperties.has("attribute")) {+ const oldAttr = _changedProperties.get("attribute") as AssetAttribute;+ const attr = this.attribute;++ if (oldAttr && attr) {+ const oldValue = oldAttr.value;+ const oldTimestamp = oldAttr.valueTimestamp;++ // Compare attributes ignoring the timestamp and value+ oldAttr.value = attr.value;+ oldAttr.valueTimestamp = attr.valueTimestamp;+ if (Util.objectsEqual(oldAttr, attr)) {+ // Compare value and timestamp+ if (!Util.objectsEqual(oldValue, attr.value) || oldTimestamp !== attr.valueTimestamp) {+ this._onAttributeValueChanged(oldValue, attr.value, attr.valueTimestamp);+ } else if (_changedProperties.size === 1) {+ // Only the attribute has 'changed' and we've handled it so don't perform update+ return false;+ }+ } else {+ updateSubscribedRefs = true;+ updateDescriptors = true;+ }+ }+ }++ if (_changedProperties.has("attributeRef") && !Util.objectsEqual(_changedProperties.get("attributeRef"), this.attributeRef)) {updateSubscribedRefs = true;updateDescriptors = true;}@@ -219,11 +242,23 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitEif (this.disableSubscribe) {this.attributeRefs = undefined;} else {- const attributeRef = this.attribute ? {entityId: this.attribute.assetId!, attributeName: this.attribute.name!} : this.attributeRef;+ const attributeRef = this._getAttributeRef();this.attributeRefs = attributeRef ? [attributeRef] : undefined;}}+ protected _getAttributeRef(): AttributeRef | undefined {+ if (this.attributeRef) {+ return this.attributeRef;+ }+ if (this.attribute) {+ return {+ entityId: this.attribute.assetId!,+ attributeName: this.attribute.name!+ }+ }+ }+protected _updateDescriptors(): void {this._attributeValueDescriptor = undefined;@@ -262,7 +297,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitEthis._valueFormatter = undefined;if (this.customProvider) {- this._template = this.customProvider(this.assetType, this.attribute, this._attributeDescriptor, this._attributeValueDescriptor, (v) => this._onValueChange(v), this.readonly, this.disabled, this.label);+ this._template = this.customProvider(this.assetType, this.attribute, this._attributeDescriptor, this._attributeValueDescriptor, (v) => this._updateValue(v), this.readonly, this.disabled, this.label);}if (this._template) {@@ -274,7 +309,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE} else if (this._attributeValueDescriptor) {switch (this._attributeValueDescriptor.name) {case AttributeValueType.GEO_JSON_POINT.name:- this._template = GeoJsonPointInputTemplateProvider(this.assetType, this.attribute, this._attributeDescriptor, this._attributeValueDescriptor, (v) => this._onValueChange(v), this.readonly, this.disabled, this.label);+ this._template = GeoJsonPointInputTemplateProvider(this.assetType, this.attribute, this._attributeDescriptor, this._attributeValueDescriptor, (v) => this._updateValue(v), this.readonly, this.disabled, this.label);return;case AttributeValueType.BOOLEAN.name:case AttributeValueType.SWITCH_TOGGLE.name:@@ -375,7 +410,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE}content = html`<or-input id="input" .type="${this._inputType}" .label="${this._label}" .value="${value}" .allowedValues="${this._options}" .min="${this._min}" .max="${this._max}" .options="${this._options}" .readonly="${this._readonly}" .disabled="${this._disabled}" @or-input-changed="${(e: OrInputChangedEvent) => {- this._onValueChange(e.detail.value);+ this._updateValue(e.detail.value);e.stopPropagation()}}"></or-input>`;}@@ -392,36 +427,46 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE}protected getValue(): any {- return this._attributeEvent ? this._attributeEvent.attributeState!.value : this.value;+ return this._attributeEvent ? this._attributeEvent.attributeState!.value : this.attribute ? this.attribute.value : this.value;}+ /**+ * This is called by asset-mixin+ */public _onEvent(event: SharedEvent) {if (event.eventType !== "attribute") {return;}+ const oldValue = this.getValue();this._attributeEvent = event as AttributeEvent;- const oldValue = this.attribute ? this.attribute.value : undefined;+ this._onAttributeValueChanged(oldValue, this._attributeEvent.attributeState!.value, event.timestamp);+ }++ protected _onAttributeValueChanged(oldValue: any, newValue: any, timestamp?: number) {if (this.attribute) {- this.attribute.value = this._attributeEvent.attributeState!.value;- this.attribute.valueTimestamp = event.timestamp;- super.requestUpdate();+ this.attribute.value = newValue;+ this.attribute.valueTimestamp = timestamp;}- this.dispatchEvent(new OrAttributeInputChangedEvent(this._attributeEvent.attributeState!.value, oldValue));++ this._clearWriteTimeout();+ this.value = newValue;+ this.dispatchEvent(new OrAttributeInputChangedEvent(newValue, oldValue));}- protected _onValueChange(newValue: any) {+ protected _updateValue(newValue: any) {const oldValue = this.getValue();if (this.readonly || this._readonly) {return;}- // Check if this control is linked to the backend via asset-mixin; if so send an update and wait for the- // updated attribute event to come back through the system or timeout and reset the value- if (this.attributeRefs) {- const attributeRef = this.attributeRefs[0];+ // If we have an attributeRef then send an update and wait for the updated attribute event to come back through+ // the system or for the attribute property to be updated by a parent control or timeout and reset the value+ const attributeRef = this._getAttributeRef();++ if (attributeRef) {super._sendEvent({eventType: "attribute",@@ -431,13 +476,20 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE}} as AttributeEvent);- // Clear the last attribute event which will cause loading state on renderthis._writeTimeoutHandler = window.setTimeout(() => this._onWriteTimeout(), this.writeTimeout);} else {+ this.value = newValue;this.dispatchEvent(new OrAttributeInputChangedEvent(newValue, oldValue));}}+ protected _clearWriteTimeout() {+ if (this._writeTimeoutHandler) {+ window.clearTimeout(this._writeTimeoutHandler);+ this._writeTimeoutHandler = undefined;+ }+ }+protected _onWriteTimeout() {this._writeTimeoutHandler = undefined;}diff --git a/ui/component/or-input/src/index.ts b/ui/component/or-input/src/index.tsindex 5d8b6229b..78d338908 100644--- a/ui/component/or-input/src/index.ts+++ b/ui/component/or-input/src/index.ts@@ -770,7 +770,7 @@ export class OrInput extends LitElement {newValue = undefined;}- if (typeof(newValue) === "string" && typeof(previousValue) !== "string") {+ if (typeof(newValue) === "string") {switch (this.type) {case InputType.CHECKBOX:case InputType.SWITCH: