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
Work on asset-mixin.ts (subscribe mixin) and improvements for or-asset-tree relates to #184, fixes #160
Rich Turnerff124cc67298
diff --git a/ui/component/core/package.json b/ui/component/core/package.jsonindex a031044ff..b8fa070cc 100644--- a/ui/component/core/package.json+++ b/ui/component/core/package.json@@ -19,21 +19,21 @@"@openremote/or-icon": "^1.1.0","@openremote/rest": "^1.1.0","i18next": "^15.0.9",- "i18next-xhr-backend": "^2.0.1","i18next-sprintf-postprocessor": "0.2.2",+ "i18next-xhr-backend": "^2.0.1","moment": "^2.24.0","platform": "^1.3.5",- "url-search-params-polyfill": "^5.0.0",- "qs": "^6.8.0"+ "qs": "^6.8.0",+ "url-search-params-polyfill": "^5.0.0"},"devDependencies": {"@mdi/svg": ">=4.5.95",+ "@types/qs": "^6.5.3","tslint": ">=5.11.0","typescript": ">=3.4.5","webpack": "^4.41.2","webpack-cli": "^3.3.9","xmldom": "^0.1.27",- "xpath": "^0.0.27",- "@types/qs": "^6.5.3"+ "xpath": "^0.0.27"}}diff --git a/ui/component/core/src/asset-mixin.ts b/ui/component/core/src/asset-mixin.tsindex 4d9ac9f2a..7e4b17cae 100644--- a/ui/component/core/src/asset-mixin.ts+++ b/ui/component/core/src/asset-mixin.ts@@ -1,7 +1,7 @@/* tslint:disable:no-empty */import {EventProviderFactory, EventProviderStatus} from "./event";import {arraysEqual} from "./util";-import {AssetEvent, AttributeEvent, AttributeRef} from "@openremote/model";+import {AttributeRef, SharedEvent, EventIdentifier} from "@openremote/model";declare type Constructor<T = {}> = new (...args: any[]) => T;@@ -16,10 +16,10 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exteclass extends base {public _connectRequested = false;- public _assetSubscriptionId?: string;- public _attributeSubscriptionId?: string;+ public _subscriptionIds?: string[];public _assetIds?: string[];public _attributeRefs?: AttributeRef[];+ public _status: EventProviderStatus = EventProviderStatus.DISCONNECTED;public _statusCallback = (status: EventProviderStatus) => this._onEventProviderStatusChanged(status);connectedCallback() {@@ -27,18 +27,18 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T extesuper.connectedCallback();}- this.connect();+ this.connectEvents();}disconnectedCallback() {- this.disconnect();+ this.disconnectEvents();if (super.disconnectedCallback) {super.disconnectedCallback();}}- public connect() {+ public connectEvents() {if (!eventProviderFactory.getEventProvider()) {console.log("No event provider available so cannot subscribe");return;@@ -52,46 +52,83 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T extethis._doConnect();}- public async _doConnect() {- if (!this._connectRequested || this._attributeSubscriptionId) {+ public disconnectEvents() {+ if (!this._connectRequested) {return;}+ this._connectRequested = false;+ eventProviderFactory.getEventProvider()!.unsubscribeStatusChange(this._statusCallback);+ this._onEventsDisconnect();+ }- if (eventProviderFactory.getEventProvider()!.status !== EventProviderStatus.CONNECTED) {+ public async _doConnect() {+ if (!this.eventsConnected) {return;}+ this._onEventsConnect();+ }++ public get eventsConnected() {+ return this._connectRequested && eventProviderFactory.getEventProvider()!.status === EventProviderStatus.CONNECTED;+ }++ public _onEventProviderStatusChanged(status: EventProviderStatus) {+ switch (status) {+ case EventProviderStatus.DISCONNECTED:+ this._onEventsDisconnect();+ break;+ case EventProviderStatus.CONNECTED:+ this._doConnect();+ break;+ }+ }++ public _onEventsConnect() {+ this._addEventSubscriptions();+ this.onEventsConnect();+ }++ public _onEventsDisconnect() {+ this._removeEventSubscriptions();+ this.onEventsDisconnect();+ }++ /**+ * Defaults to subscribe to attribute events and optionally asset events, override in subclasses to do+ * custom subscriptions.+ * Returns the subscription IDs of any created subscriptions+ */+ public async _addEventSubscriptions(): Promise<string[]> {const isAttributes = !!this._attributeRefs;const ids: string[] | AttributeRef[] | undefined = this._attributeRefs ? this._attributeRefs : this._assetIds;+ const subscriptions = [];if (ids && ids.length > 0) {if (!isAttributes) {- this._assetSubscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAssetEvents(ids, true, (event) => this._onAssetEvent(event));+ subscriptions.push(await eventProviderFactory.getEventProvider()!.subscribeAssetEvents(ids, true, (event) => this._onEvent(event)));}- this._attributeSubscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAttributeEvents(ids, isAttributes, (event) => this._onAttributeEvent(event));+ subscriptions.push(await eventProviderFactory.getEventProvider()!.subscribeAttributeEvents(ids, isAttributes, (event) => this._onEvent(event)));}- this.onStatusChange(EventProviderStatus.CONNECTED);- }- public disconnect() {- if (!this._connectRequested) {- return;- }- this._connectRequested = false;- eventProviderFactory.getEventProvider()!.unsubscribeStatusChange(this._statusCallback);- this._doDisconnect();+ return subscriptions;}- public _doDisconnect() {- if (!this._assetSubscriptionId) {+ public _removeEventSubscriptions() {+ if (!this._subscriptionIds) {return;}- eventProviderFactory.getEventProvider()!.unsubscribe(this._assetSubscriptionId);- eventProviderFactory.getEventProvider()!.unsubscribe(this._attributeSubscriptionId!);- this._assetSubscriptionId = undefined;- this._attributeSubscriptionId = undefined;- this.onStatusChange(EventProviderStatus.DISCONNECTED);+ this._subscriptionIds.forEach((subscriptionId) => {+ eventProviderFactory.getEventProvider()!.unsubscribe(subscriptionId);+ });++ this._subscriptionIds = undefined;+ }++ public _refreshEventSubscriptions() {+ this._removeEventSubscriptions();+ this._addEventSubscriptions();}public set assetIds(assetIds: string[] | undefined) {@@ -100,8 +137,11 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte}this._assetIds = assetIds;- this._doDisconnect();- this._doConnect();+ this._refreshEventSubscriptions();+ }++ public get assetIds() {+ return this._assetIds;}public set attributeRefs(attributes: AttributeRef[] | undefined) {@@ -110,49 +150,23 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte}this._attributeRefs = attributes;- this._doDisconnect();- this._doConnect();- }-- public _onEventProviderStatusChanged(status: EventProviderStatus) {- switch (status) {- case EventProviderStatus.DISCONNECTED:- this._doDisconnect();- break;- case EventProviderStatus.CONNECTED:- this._doConnect();- break;- }- }-- public _onAttributeEvent(event: AttributeEvent) {- if (!this._connectRequested || !this._attributeSubscriptionId) {- return;- }-- this.onAttributeEvent(event);+ this._refreshEventSubscriptions();}- public _onAssetEvent(event: AssetEvent) {- if (!this._connectRequested || !this._assetSubscriptionId) {- return;- }-- this.onAssetEvent(event);+ public _sendEvent(event: SharedEvent) {+ eventProviderFactory.getEventProvider()!.sendEvent(event);}- public _sendEvent(event: AttributeEvent) {- if (eventProviderFactory.getEventProvider()!.status === EventProviderStatus.CONNECTED) {- eventProviderFactory.getEventProvider()!.sendEvent(event);- }+ public _sendEventWithReply(event: SharedEvent & EventIdentifier): Promise<SharedEvent & EventIdentifier> {+ return eventProviderFactory.getEventProvider()!.sendEventWithReply(event);}// noinspection JSUnusedLocalSymbols- public onStatusChange(status: EventProviderStatus) {}+ public onEventsConnect() {}// noinspection JSUnusedLocalSymbols- public onAttributeEvent(event: AttributeEvent) {}+ public onEventsDisconnect() {}// noinspection JSUnusedLocalSymbols- public onAssetEvent(event: AssetEvent) {}+ public _onEvent(event: SharedEvent) {}};diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.tsindex 9a87b65f9..240ed3f09 100644--- a/ui/component/core/src/event.ts+++ b/ui/component/core/src/event.ts@@ -10,7 +10,8 @@ import {AssetEvent,ReadAssetEvent,TriggeredEventSubscription,- AttributeRef+ AttributeRef,+ EventIdentifier} from "@openremote/model";export enum EventProviderStatus {@@ -39,6 +40,8 @@ export interface EventProvider {subscribeAttributeEvents(ids: string[] | AttributeRef[], requestCurrentValues: boolean, callback: (event: AttributeEvent) => void): Promise<string>;sendEvent<T extends SharedEvent>(event: T): void;++ sendEventWithReply<T extends SharedEvent & EventIdentifier, U extends SharedEvent & EventIdentifier>(event: T): Promise<U>;}// Interface to provide a singleton implementation of EventProvider@@ -57,6 +60,7 @@ const SUBSCRIBED_MESSAGE_PREFIX = "SUBSCRIBED:";const UNSUBSCRIBE_MESSAGE_PREFIX = "UNSUBSCRIBE:";const RENEW_MESSAGE_PREFIX = "RENEW:";const UNAUTHORIZED_MESSAGE_PREFIX = "UNAUTHORIZED:";+const TRIGGERED_MESSAGE_PREFIX = "TRIGGERED:";const EVENT_MESSAGE_PREFIX = "EVENT:";abstract class EventProviderImpl implements EventProvider {@@ -183,12 +187,12 @@ abstract class EventProviderImpl implements EventProvider {}}},- reason => {+ (reason) => {if (this._pendingSubscription) {- let subscriptionInfo = this._pendingSubscription;+ const subscriptionInfo = this._pendingSubscription;this._pendingSubscription = null;this._processNextSubscription();- let deferred = subscriptionInfo.deferred;+ const deferred = subscriptionInfo.deferred;subscriptionInfo.deferred = null;if (deferred) {@@ -202,7 +206,7 @@ abstract class EventProviderImpl implements EventProvider {public unsubscribe<T extends SharedEvent>(subscriptionId: string) {- let callback = this._subscriptionMap[subscriptionId];+ const callback = this._subscriptionMap[subscriptionId];if (callback) {delete this._subscriptionMap[subscriptionId];this._doUnsubscribe(subscriptionId);@@ -210,7 +214,17 @@ abstract class EventProviderImpl implements EventProvider {}public sendEvent<T extends SharedEvent>(event: T): void {- this._doSend(event);++ if (this._status === EventProviderStatus.CONNECTED) {+ this._doSend(event);+ }+ }++ public sendEventWithReply<T extends SharedEvent & EventIdentifier, U extends SharedEvent & EventIdentifier>(event: T): Promise<U> {+ if (this._status !== EventProviderStatus.CONNECTED) {+ return Promise.reject("Not connected");+ }+ return this._doSendWithReply(event);}public async subscribeAssetEvents(ids: string[] | AttributeRef[] | null, requestCurrentValues: boolean, callback: (event: AssetEvent) => void): Promise<string> {@@ -421,6 +435,8 @@ abstract class EventProviderImpl implements EventProvider {protected abstract _doSend<T extends SharedEvent>(event: T): void;+ protected abstract _doSendWithReply<T extends SharedEvent & EventIdentifier, U extends SharedEvent & EventIdentifier>(event: T): Promise<U>;+protected abstract _doConnect(): Promise<boolean>;protected abstract _doDisconnect(): void;@@ -439,6 +455,7 @@ export class WebSocketEventProvider extends EventProviderImpl {protected _webSocket: WebSocket | undefined = undefined;protected _connectDeferred: Deferred<boolean> | null = null;protected _subscribeDeferred: Deferred<string> | null = null;+ protected _repliesDeferred: Map<string, Deferred<any>> = new Map<string, Deferred<any>>();protected _renewalTimer: number | null = null;get endpointUrl(): string {@@ -499,10 +516,11 @@ export class WebSocketEventProvider extends EventProviderImpl {};this._webSocket!.onmessage = (e) => {- let msg = e.data as string;+ const msg = e.data as string;+if (msg && msg.startsWith(SUBSCRIBED_MESSAGE_PREFIX)) {- let jsonStr = msg.substring(SUBSCRIBED_MESSAGE_PREFIX.length);- let subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;+ const jsonStr = msg.substring(SUBSCRIBED_MESSAGE_PREFIX.length);+ const subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;// Create a renewal timer if not done soif (!this._renewalTimer) {@@ -511,28 +529,38 @@ export class WebSocketEventProvider extends EventProviderImpl {}, WebSocketEventProvider._subscriptionRenewalMillis);}- let deferred = this._subscribeDeferred;+ const 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;+ const jsonStr = msg.substring(UNAUTHORIZED_MESSAGE_PREFIX.length);+ const subscription = JSON.parse(jsonStr) as EventSubscription<SharedEvent>;+ const 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 triggered = JSON.parse(str) as TriggeredEventSubscription<SharedEvent>;+ } else if (msg.startsWith(TRIGGERED_MESSAGE_PREFIX)) {+ const str = msg.substring(TRIGGERED_MESSAGE_PREFIX.length);+ const triggered = JSON.parse(str) as TriggeredEventSubscription<SharedEvent>;if (triggered.events) {triggered.events.forEach((event) => {this._onMessageReceived(triggered.subscriptionId!, event);});}+ } else if (msg.startsWith(EVENT_MESSAGE_PREFIX)) {+ const str = msg.substring(EVENT_MESSAGE_PREFIX.length);+ const event = JSON.parse(str) as SharedEvent;+ if ((event as EventIdentifier).messageId) {+ const deferred = this._repliesDeferred.get((event as EventIdentifier).messageId!);+ this._repliesDeferred.delete((event as EventIdentifier).messageId!);+ if (deferred) {+ deferred.resolve(event as (SharedEvent & EventIdentifier));+ }+ }}};@@ -549,6 +577,8 @@ export class WebSocketEventProvider extends EventProviderImpl {protected _doDisconnect(): void {this._webSocket!.close();+ this._subscribeDeferred = null;+ this._repliesDeferred.clear();}protected _doSubscribe<T extends SharedEvent>(subscription: EventSubscription<T>): Promise<string> {@@ -570,11 +600,11 @@ export class WebSocketEventProvider extends EventProviderImpl {if (!this._webSocket) {return;}- let cancelSubscription: CancelEventSubscription<SharedEvent> = {+ const cancelSubscription: CancelEventSubscription<SharedEvent> = {subscriptionId: subscriptionId};this._webSocket.send(UNSUBSCRIBE_MESSAGE_PREFIX + JSON.stringify(cancelSubscription));- if (Object.keys(this._subscriptionMap).length == 0 && this._renewalTimer) {+ if (Object.keys(this._subscriptionMap).length === 0 && this._renewalTimer) {clearInterval(this._renewalTimer);}}@@ -584,18 +614,30 @@ export class WebSocketEventProvider extends EventProviderImpl {return;}- let renewSubscriptions: RenewEventSubscriptions = {+ const 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;+ const message = EVENT_MESSAGE_PREFIX + JSON.stringify(event);+ this._webSocket!.send(message);+ }++ protected _doSendWithReply<T extends SharedEvent & EventIdentifier, U extends SharedEvent & EventIdentifier>(event: T): Promise<U> {++ if (!event.messageId) {+ event.messageId = new Date().getTime().toString(10);}- let message = EVENT_MESSAGE_PREFIX + JSON.stringify(event);- this._webSocket.send(message);+ if (this._repliesDeferred.has(event.messageId)) {+ return Promise.reject("There's already a pending send and reply with this ID");+ }++ const deferred = new Deferred<U>();+ this._repliesDeferred.set(event.messageId, deferred);+ this._webSocket!.send(EVENT_MESSAGE_PREFIX + JSON.stringify(event));+ return deferred.promise;}-}\ No newline at end of file+}diff --git a/ui/component/or-asset-tree/src/components/or-modal.ts b/ui/component/or-asset-tree/src/components/or-modal.tsdeleted file mode 100644index 788c43007..000000000--- a/ui/component/or-asset-tree/src/components/or-modal.ts+++ /dev/null@@ -1,54 +0,0 @@-import {customElement, html, LitElement, property, PropertyValues, TemplateResult, css} from "lit-element";-import "@openremote/or-select";-import "@openremote/or-icon";-import "@openremote/or-translate";--@customElement("or-modal")-export class OrModal extends LitElement {-- @property({type: Boolean, reflect: true})- public show: boolean = false;-- @property({type: Boolean})- public dismissible: boolean = true;-- public static get styles() {- return css`- :host {- position: relative;- }-- div[hidden] {- height: 0px;- }-- div {- transition: all 0.8s ease-in;- position: absolute;- height: auto;- }- `;- }-- protected updated(_changedProperties: PropertyValues): void {- super.updated(_changedProperties);-- if (_changedProperties.has("show") && this.dismissible) {- if (this.show) {- document.body.addEventListener("click", this._onMouseClick);- } else {- document.body.removeEventListener("click", this._onMouseClick)- }- }- }-- protected _onMouseClick(evt: MouseEvent) {- if (!this.contains(evt.target as Node)) {- this.show = false;- }- }-- protected render(): TemplateResult | void {- return html`<div ?hidden="${!this.show}">TEST</div>`;- }-}\ No newline at end of filediff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.tsindex d9bd89268..1329599eb 100644--- a/ui/component/or-asset-tree/src/index.ts+++ b/ui/component/or-asset-tree/src/index.ts@@ -1,11 +1,11 @@import {customElement, html, LitElement, property, PropertyValues, query, TemplateResult} from "lit-element";import "@openremote/or-input";import "@openremote/or-icon";-import {Asset, AssetQuery, AssetTreeNode, Constants, Tenant, ClientRole} from "@openremote/model";+import {Asset, AssetQuery, AssetTreeNode, ClientRole, SharedEvent, EventIdentifier, AssetsEvent, AssetEvent, ReadAssetsEvent, AssetEventCause} from "@openremote/model";import "@openremote/or-translate";import {style} from "./style";-import manager, {AssetModelUtil, OREvent, EventCallback} from "@openremote/core";-import {OrInputChangedEvent, InputType} from "@openremote/or-input";+import manager, {AssetModelUtil, OREvent, EventCallback, subscribe} from "@openremote/core";+import {InputType} from "@openremote/or-input";import Qs from "qs";import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";import {getContentWithMenuTemplate, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";@@ -121,7 +121,7 @@ declare global {// TODO: Add websocket support// TODO: Make modal a standalone component@customElement("or-asset-tree")-export class OrAssetTree extends LitElement {+export class OrAssetTree extends subscribe(manager)(LitElement) {static get styles() {return [@@ -136,7 +136,7 @@ export class OrAssetTree extends LitElement {public assets?: Asset[];@property({type: Array})- public assetIds?: string[];+ public _assetIdsOverride?: string[];@property({type: Array})public rootAssets?: Asset[];@@ -163,47 +163,39 @@ export class OrAssetTree extends LitElement {public selectedIds?: string[];@property({type: String})- public sortBy?: string;+ public sortBy?: string = "name";@property({attribute: false})protected _nodes?: UiAssetTreeNode[];- @property()- protected _showLoading: boolean = true;-+ protected _connected: boolean = false;protected _selectedNodes: UiAssetTreeNode[] = [];protected _initCallback?: EventCallback;- protected _ready = false;public get selectedNodes(): UiAssetTreeNode[] {return this._selectedNodes ? [...this._selectedNodes] : [];}- public disconnectedCallback() {- super.disconnectedCallback();- manager.removeListener(this.onManagerEvent);+ /**+ * Override subscribe mixin behaviour to get re-render+ */+ public set assetIds(assetIds: string[]) {+ this._assetIdsOverride = assetIds;+ super.assetIds = assetIds;}- protected _onReady() {- this._ready = true;- this._loadAssets();+ public connectedCallback() {+ super.connectedCallback();+ manager.addListener(this.onManagerEvent);}- protected firstUpdated(_changedProperties: PropertyValues): void {- super.firstUpdated(_changedProperties);- manager.addListener(this.onManagerEvent);- if (manager.ready) {- this._onReady();- }+ public disconnectedCallback() {+ super.disconnectedCallback();+ manager.removeListener(this.onManagerEvent);}protected onManagerEvent = (event: OREvent) => {switch (event) {- case OREvent.READY:- if (!manager.ready) {- this._onReady();- }- break;case OREvent.DISPLAY_REALM_CHANGED:this._nodes = undefined;break;@@ -232,7 +224,7 @@ export class OrAssetTree extends LitElement {</div></div>- ${!this._nodes || this._showLoading+ ${!this._nodes? html`<span id="loading"><or-translate value="loading"></or-translate></span>`: html`@@ -254,30 +246,11 @@ export class OrAssetTree extends LitElement {return this.readonly || !manager.hasRole(ClientRole.WRITE_RULES);}- protected _treeNodeTemplate(treeNode: UiAssetTreeNode, level: number): TemplateResult | string {-- const descriptor = AssetModelUtil.getAssetDescriptor(treeNode.asset!.type!);-- return html`- <li ?data-selected="${treeNode.selected}" ?data-expanded="${treeNode.expanded}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, treeNode)}">- <div class="node-container" style="padding-left: ${level*22}px">- <div class="node-name">- <div class="expander" ?data-expandable="${treeNode.expandable}"></div>- ${getAssetDescriptorIconTemplate(descriptor)}- <span>${treeNode.asset!.name}</span>- </div>- </div>- <ol>- ${!treeNode.children ? `` : treeNode.children.map((childNode) => this._treeNodeTemplate(childNode, level + 1))}- </ol>- </li>- `;- }-protected shouldUpdate(_changedProperties: PropertyValues): boolean {const result = super.shouldUpdate(_changedProperties);- if (_changedProperties.has("assetIds")+ if (_changedProperties.has("_assetIdsOverride")+ || _changedProperties.has("assets")|| _changedProperties.has("rootAssets")|| _changedProperties.has("rootAssetIds")) {this._nodes = undefined;@@ -471,38 +444,27 @@ export class OrAssetTree extends LitElement {}protected _getSortFunction(): (a: UiAssetTreeNode, b: UiAssetTreeNode) => number {- return (a, b) => { return (a.asset as any)![this.sortBy!] < (b.asset as any)![this.sortBy!] ? -1 : (a.asset as any)![this.sortBy!] > (b.asset as any)![this.sortBy!] ? 1 : 0 };- }-- protected _getRealm(): string | undefined {- return manager.isSuperUser() ? manager.displayRealm : manager.getRealm();- }-- protected _doRequest<T>(event: CustomEvent<RequestEventDetail<T>>, handler: (detail: T) => void) {- this.dispatchEvent(event);- window.setTimeout(() => {- if (event.detail.allow) {- handler(event.detail.detail);- }- })+ return (a, b) => (a.asset as any)![this.sortBy!] < (b.asset as any)![this.sortBy!] ? -1 : (a.asset as any)![this.sortBy!] > (b.asset as any)![this.sortBy!] ? 1 : 0;}protected _loadAssets() {- if (!this._ready) {- return;- }-const sortFunction = this._getSortFunction();if (!this.assets) {- let query: AssetQuery = {++ if (!this._connected) {+ return;+ }++ const query: AssetQuery = {tenant: {- realm: this._getRealm()+ realm: manager.isSuperUser() ? manager.displayRealm : manager.getRealm()},- select: {+ select: { // Just need the basic asset info+ excludeAttributes: true,excludePath: true,- excludeParentInfo: false+ excludeParentInfo: true}};@@ -517,14 +479,70 @@ export class OrAssetTree extends LitElement {query.recursive = true;}- manager.rest.api.AssetResource.queryAssets(query).then((response) => {- this._buildTreeNodes(response.data, sortFunction);- });+ this._sendEventWithReply({+ eventType: "read-assets",+ assetQuery: query+ } as ReadAssetsEvent)+ .then((ev: SharedEvent & EventIdentifier) =>+ this._buildTreeNodes((ev as AssetsEvent).assets!, sortFunction));} else {this._buildTreeNodes(this.assets, sortFunction);}}+ /* Subscribe mixin overrides */++ public async _addEventSubscriptions(): Promise<string[]> {+ // Subscribe to asset events for all assets in the realm+ const subscriptions = [];+ subscriptions.push(await manager.getEventProvider()!.subscribeAssetEvents(null, false, (event) => this._onEvent(event)));+ return subscriptions;+ }++ public onEventsConnect() {+ this._connected = true;+ this._loadAssets();+ }++ public onEventsDisconnect() {+ this._connected = false;+ this._nodes = undefined;+ }++ public _onEvent(event: SharedEvent) {++ if (event.eventType === "assets") {+ const assetsEvent = event as AssetsEvent;+ this._buildTreeNodes(assetsEvent.assets!, this._getSortFunction());+ return;+ }++ if (event.eventType === "asset" && this._nodes && this._nodes.length > 0) {++ const assetEvent = event as AssetEvent;+ if (assetEvent.cause === AssetEventCause.READ) {+ return;+ }+ if (assetEvent.cause === AssetEventCause.UPDATE+ && !(assetEvent.updatedProperties!.includes("name")+ || assetEvent.updatedProperties!.includes("parentId"))) {+ return;+ }++ // Extract all assets, update and rebuild tree+ const assets: Asset[] = [];+ if (assetEvent.cause !== AssetEventCause.DELETE) {+ assets.push(assetEvent.asset!);+ }+ OrAssetTree._forEachNodeRecursive(this._nodes, (node) => {+ if (node.asset!.id !== assetEvent.asset!.id) {+ assets.push(node.asset!);+ }+ });+ this._buildTreeNodes(assets, this._getSortFunction());+ }+ }+protected _buildTreeNodes(assets: Asset[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number) {if (!assets || assets.length === 0) {this._nodes = [];@@ -558,10 +576,10 @@ export class OrAssetTree extends LitElement {this._nodes = rootAssets;}+if (this.selectedIds && this.selectedIds.length > 0) {this._updateSelectedNodes();}- this._showLoading = false;}protected _buildChildTreeNodes(treeNode: UiAssetTreeNode, assets: Asset[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number) {@@ -581,6 +599,26 @@ export class OrAssetTree extends LitElement {});}+ protected _treeNodeTemplate(treeNode: UiAssetTreeNode, level: number): TemplateResult | string {++ const descriptor = AssetModelUtil.getAssetDescriptor(treeNode.asset!.type!);++ return html`+ <li ?data-selected="${treeNode.selected}" ?data-expanded="${treeNode.expanded}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, treeNode)}">+ <div class="node-container" style="padding-left: ${level * 22}px">+ <div class="node-name">+ <div class="expander" ?data-expandable="${treeNode.expandable}"></div>+ ${getAssetDescriptorIconTemplate(descriptor)}+ <span>${treeNode.asset!.name}</span>+ </div>+ </div>+ <ol>+ ${!treeNode.children ? `` : treeNode.children.map((childNode) => this._treeNodeTemplate(childNode, level + 1))}+ </ol>+ </li>+ `;+ }+protected static _forEachNodeRecursive(nodes: UiAssetTreeNode[], fn: (node: UiAssetTreeNode) => void) {if (!nodes) {return;@@ -591,4 +629,13 @@ export class OrAssetTree extends LitElement {this._forEachNodeRecursive(node.children, fn);});}++ protected _doRequest<T>(event: CustomEvent<RequestEventDetail<T>>, handler: (detail: T) => void) {+ this.dispatchEvent(event);+ window.setTimeout(() => {+ if (event.detail.allow) {+ handler(event.detail.detail);+ }+ });+ }}diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.tsindex c6634cb87..099fe122d 100644--- a/ui/component/or-asset-viewer/src/index.ts+++ b/ui/component/or-asset-viewer/src/index.ts@@ -24,7 +24,8 @@ import {AttributeEvent,AttributeType,MetaItem,- MetaItemType+ MetaItemType,+ SharedEvent} from "@openremote/model";import {style} from "./style";import i18next from "i18next";@@ -778,24 +779,27 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem// return html`<or-input id="property-${property}" type="${type}" .minLength="${minLength}" .maxLength="${maxLength}" dense .value="${value}" readonly label="${i18next.t(property)}"></or-input>`;// }-// TODO: Add debounce in here to minimise render calls- onAttributeEvent(event: AttributeEvent) {- const attrName = event.attributeState!.attributeRef!.attributeName!;+ _onEvent(event: SharedEvent) {+ if (event.eventType === "asset") {+ this.asset = (event as AssetEvent).asset;+ this._loading = false;+ return;+ }++ if (event.eventType === "attribute") {+ const attributeEvent = event as AttributeEvent;+ const attrName = attributeEvent.attributeState!.attributeRef!.attributeName!;- if (this.asset && this.asset.attributes && this.asset.attributes.hasOwnProperty(attrName)) {- if (event.attributeState!.deleted) {- delete this.asset.attributes[attrName];- this.asset = {...this.asset}+ if (this.asset && this.asset.attributes && this.asset.attributes.hasOwnProperty(attrName)) {+ if (attributeEvent.attributeState!.deleted) {+ delete this.asset.attributes[attrName];+ this.asset = {...this.asset};+ }}}}- onAssetEvent(event: AssetEvent) {- this.asset = event.asset;- this._loading = false;- }-protected _getPanelConfig(asset: Asset): AssetViewerConfig {const config = {...OrAssetViewer.DEFAULT_VIEWER_CONFIG};diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.tsindex 0bba593e5..614aaaa2e 100644--- a/ui/component/or-attribute-input/src/index.ts+++ b/ui/component/or-attribute-input/src/index.ts@@ -9,7 +9,8 @@ import {AttributeValueDescriptor,AttributeValueType,MetaItemType,- ValueType+ ValueType,+ SharedEvent} from "@openremote/model";import manager, {AssetModelUtil, subscribe, Util} from "@openremote/core";import "@openremote/or-input";@@ -253,7 +254,6 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE}public render() {-if (this._invalid) {return html`<div>INVALID</div>@@ -271,15 +271,20 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE}}- public onAttributeEvent(event: AttributeEvent) {+ public _onEvent(event: SharedEvent) {+ if (event.eventType !== "attribute") {+ return;+ }+ const attributeEvent = event as AttributeEvent;+const oldValue = this.attribute ? this.attribute.value : undefined;if (this.attribute) {- this.attribute.value = event.attributeState!.value;+ this.attribute.value = attributeEvent.attributeState!.value;this.attribute.valueTimestamp = event.timestamp;this._loading = false;super.requestUpdate();}- this.dispatchEvent(new OrInputChangedEvent(event.attributeState!.value, oldValue));+ this.dispatchEvent(new OrInputChangedEvent(attributeEvent.attributeState!.value, oldValue));}protected onValueChange(newValue: any) {diff --git a/ui/component/or-data-viewer/src/index.ts b/ui/component/or-data-viewer/src/index.tsindex 38d13f365..804ce9aa6 100644--- a/ui/component/or-data-viewer/src/index.ts+++ b/ui/component/or-data-viewer/src/index.ts@@ -2,20 +2,9 @@ import {customElement, html, LitElement, property, PropertyValues, TemplateResulimport "@openremote/or-chart";import "@openremote/or-translate";import {translate} from "@openremote/or-translate";-import manager, {AssetModelUtil, subscribe, Util} from "@openremote/core";import "@openremote/or-panel";import {OrChartConfig, OrChartEvent} from "@openremote/or-chart";-import {- Asset,- AssetAttribute,- AssetEvent,- AssetType,- Attribute,- AttributeEvent,- AttributeType,- MetaItemType,- MetaItem-} from "@openremote/model";+import {Asset, AssetAttribute, Attribute} from "@openremote/model";import {style} from "./style";import i18next from "i18next";import {styleMap} from "lit-html/directives/style-map";@@ -50,32 +39,37 @@ export interface DataViewerConfig {chartConfig?: OrChartConfig;}-class EventHandler {- _callbacks: Function[];+ public _callbacks: Function[];constructor() {this._callbacks = [];}- startCallbacks() {+ public startCallbacks() {return new Promise((resolve, reject) => {if (this._callbacks && this._callbacks.length > 0) {- this._callbacks.forEach(cb => cb());+ this._callbacks.forEach((cb) => cb());}resolve();- })+ });}- addCallback(callback: Function) {+ public addCallback(callback: Function) {this._callbacks.push(callback);}}const onRenderComplete = new EventHandler();@customElement("or-data-viewer")-export class OrDataViewer extends subscribe(manager)(translate(i18next)(LitElement)) {+export class OrDataViewer extends translate(i18next)(LitElement) {++ static get styles() {+ return [+ style+ ];+ }public static DEFAULT_PANEL_TYPE: PanelType = "chart";@@ -84,7 +78,7 @@ export class OrDataViewer extends subscribe(manager)(translate(i18next)(LitEleme},panels: {- "chart": {+ chart: {type: "chart",hideOnMobile: true,panelStyles: {@@ -95,74 +89,16 @@ export class OrDataViewer extends subscribe(manager)(translate(i18next)(LitEleme}};- static get styles() {- return [- style- ];- }-- @property({type: Array, attribute: false})- protected _assets?: Asset[];-- @property()- protected _loading: boolean = false;-- config?: DataViewerConfig;--- constructor() {- super();- window.addEventListener('resize', () => OrDataViewer.generateGrid(this.shadowRoot));-- this.addEventListener(OrChartEvent.NAME,() => OrDataViewer.generateGrid(this.shadowRoot));- }-- protected render() {-- if (this._loading) {- return html`- <div class="msg"><or-translate value="loading"></or-translate></div>- `;- }-- if (!this.config) {- return html``;- }-- return html`- <div id="wrapper">- <div id="container" style="${this.config.viewerStyles ? styleMap(this.config.viewerStyles) : ""}">- ${Object.entries(this.config.panels).map(([name, panelConfig]) => this.getPanel(name, panelConfig))}- </div>- </div>- `;- }-- protected updated(_changedProperties: PropertyValues) {- super.updated(_changedProperties);-- this.onCompleted().then(() => {- onRenderComplete.startCallbacks().then(() => {- OrDataViewer.generateGrid(this.shadowRoot);- });- });-- }-- async onCompleted() {- await this.updateComplete;- }-public static generateGrid(shadowRoot: ShadowRoot | null) {if (shadowRoot) {- const grid = shadowRoot.querySelector('#container');+ 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 items = shadowRoot.querySelectorAll('.panel');+ 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) => {- const content = item.querySelector('.panel-content-wrapper');+ const content = item.querySelector(".panel-content-wrapper");if (content) {const rowSpan = Math.ceil((content.getBoundingClientRect().height + rowGap) / (rowHeight + rowGap));(item as HTMLElement).style.gridRowEnd = "span " + rowSpan;@@ -173,6 +109,24 @@ export class OrDataViewer extends subscribe(manager)(translate(i18next)(LitEleme}}+ public config?: DataViewerConfig;++ @property({type: Array, attribute: false})+ protected _assets?: Asset[];++ @property()+ protected _loading: boolean = false;++ constructor() {+ super();+ window.addEventListener("resize", () => OrDataViewer.generateGrid(this.shadowRoot));+ this.addEventListener(OrChartEvent.NAME, () => OrDataViewer.generateGrid(this.shadowRoot));+ }++ public async onCompleted() {+ await this.updateComplete;+ }+public getPanel(name: string, panelConfig: PanelConfig) {const content = this.getPanelContent(name, panelConfig);@@ -180,9 +134,8 @@ export class OrDataViewer extends subscribe(manager)(translate(i18next)(LitElemereturn;}-return html`- <div class=${classMap({"panel": true, mobileHidden: panelConfig.hideOnMobile === true})} id="${name}-panel" style="${panelConfig && panelConfig.panelStyles ? styleMap(panelConfig.panelStyles) : ""}">+ <div class=${classMap({panel: true, mobileHidden: panelConfig.hideOnMobile === true})} id="${name}-panel" style="${panelConfig && panelConfig.panelStyles ? styleMap(panelConfig.panelStyles) : ""}"><div class="panel-content-wrapper">${(panelConfig && panelConfig.type === "chart") ? html`<div class="panel-title">@@ -216,4 +169,35 @@ export class OrDataViewer extends subscribe(manager)(translate(i18next)(LitEleme}return content;}++ protected render() {++ if (this._loading) {+ return html`+ <div class="msg"><or-translate value="loading"></or-translate></div>+ `;+ }++ if (!this.config) {+ return html``;+ }++ return html`+ <div id="wrapper">+ <div id="container" style="${this.config.viewerStyles ? styleMap(this.config.viewerStyles) : ""}">+ ${Object.entries(this.config.panels).map(([name, panelConfig]) => this.getPanel(name, panelConfig))}+ </div>+ </div>+ `;+ }++ protected updated(_changedProperties: PropertyValues) {+ super.updated(_changedProperties);++ this.onCompleted().then(() => {+ onRenderComplete.startCallbacks().then(() => {+ OrDataViewer.generateGrid(this.shadowRoot);+ });+ });+ }}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 072349202..e2ce691e4 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@@ -1,6 +1,6 @@import {customElement, property, PropertyValues} from "lit-element";import {OrMapMarker} from "./or-map-marker";-import {AttributeEvent, AttributeType, GeoJSONPoint, AssetType, AssetEvent, AssetEventCause, Asset, MetaItemType} from "@openremote/model";+import {AttributeEvent, AttributeType, GeoJSONPoint, AssetType, AssetEvent, AssetEventCause, Asset, MetaItemType, SharedEvent} from "@openremote/model";import {subscribe} from "@openremote/core";import manager, {AssetModelUtil} from "@openremote/core";import {Util} from "@openremote/core";@@ -63,22 +63,31 @@ export class OrMapMarkerAsset extends subscribe(manager)(OrMapMarker) {return super.shouldUpdate(_changedProperties);}- public onAttributeEvent(event: AttributeEvent) {- if (event.attributeState!.attributeRef!.attributeName === AttributeType.LOCATION.attributeName) {- this._updateLocation(event.attributeState!.value as GeoJSONPoint);+ public _onEvent(event: SharedEvent) {+ if (event.eventType === "attribute") {+ const attributeEvent = event as AttributeEvent;++ if (attributeEvent.attributeState!.attributeRef!.attributeName === AttributeType.LOCATION.attributeName) {+ this._updateLocation(attributeEvent.attributeState!.value as GeoJSONPoint);+ return;+ }++ return;}- }- public onAssetEvent(event: AssetEvent) {- switch (event.cause) {- case AssetEventCause.READ:- case AssetEventCause.CREATE:- case AssetEventCause.UPDATE:- this.onAssetChanged(event.asset);- break;- case AssetEventCause.DELETE:- this.onAssetChanged(undefined);- break;+ if (event.eventType === "asset") {+ const assetEvent = event as AssetEvent;++ switch (assetEvent.cause) {+ case AssetEventCause.READ:+ case AssetEventCause.CREATE:+ case AssetEventCause.UPDATE:+ this.onAssetChanged(assetEvent.asset);+ break;+ case AssetEventCause.DELETE:+ this.onAssetChanged(undefined);+ break;+ }}}diff --git a/ui/component/or-map/src/or-map-asset-card.ts b/ui/component/or-map/src/or-map-asset-card.tsindex f3e557571..24d687e8a 100644--- a/ui/component/or-map/src/or-map-asset-card.ts+++ b/ui/component/or-map/src/or-map-asset-card.ts@@ -10,7 +10,7 @@ import {TemplateResult,unsafeCSS} from "lit-element";-import {Asset,Attribute, AssetEvent, AssetEventCause, AttributeEvent, AttributeType, AttributeValueType, MetaItemType, AttributeDescriptor} from "@openremote/model";+import {Asset,Attribute, AssetEvent, AssetEventCause, AttributeEvent, AttributeType, AttributeValueType, MetaItemType, AttributeDescriptor, SharedEvent} from "@openremote/model";import manager, {AssetModelUtil,DefaultColor1,@@ -100,33 +100,36 @@ export class OrMapAssetCard extends subscribe(manager)(LitElement) {return super.shouldUpdate(_changedProperties);}- public onAttributeEvent(event: AttributeEvent) {-- if (this.asset) {- this.asset = Util.updateAsset(this.asset, event);- this.requestUpdate();+ public _onEvent(event: SharedEvent) {++ if (event.eventType === "asset") {+ const assetEvent = event as AssetEvent;++ switch (assetEvent.cause) {+ case AssetEventCause.READ:+ case AssetEventCause.CREATE:+ case AssetEventCause.UPDATE:+ this.asset = assetEvent.asset;+ break;+ case AssetEventCause.DELETE:+ this.asset = undefined;+ break;+ }}- }-- public onAssetEvent(event: AssetEvent) {- switch (event.cause) {- case AssetEventCause.READ:- case AssetEventCause.CREATE:- case AssetEventCause.UPDATE:- this.asset = event.asset;- break;- case AssetEventCause.DELETE:- this.asset = undefined;- break;++ if (event.eventType === "attribute") {+ if (this.asset) {+ this.asset = Util.updateAsset(this.asset, event as AttributeEvent);+ this.requestUpdate();+ }}}getCardConfig() {- if(!this.config) return;- if(!this.asset) return this.config.default;+ if (!this.config) { return; }+ if (!this.asset) { return this.config.default; }const config = this.config.assetTypes && this.config.assetTypes.hasOwnProperty(this.asset.type!) ? this.config.assetTypes[this.asset.type!] : this.config.default;-return config;}@@ -156,13 +159,14 @@ export class OrMapAssetCard extends subscribe(manager)(LitElement) {<div id="attribute-list"><ul>${attrs.map((attr) => {- let attributeDescriptor: AttributeDescriptor | undefined = AssetModelUtil.getAttributeDescriptorFromAsset(attr.name!);+ const attributeDescriptor: AttributeDescriptor | undefined = AssetModelUtil.getAttributeDescriptorFromAsset(attr.name!);let label = Util.getAttributeLabel(attr, attributeDescriptor);const unit = Util.getMetaValue(MetaItemType.UNIT_TYPE, attr, attributeDescriptor);- if(unit)- label = label + " ("+i18next.t(unit)+")";- return html`<li><span class="attribute-name">${label}</span><span class="attribute-value"><or-attribute-field .attribute="${attr}"></or-attribute-field></span></li>`;+ if (unit) {+ label = label + " (" + i18next.t(unit) + ")";+ }+ return html`<li><span class="attribute-name">${label}</span><span class="attribute-value"><or-attribute-field .attribute="${attr}"></or-attribute-field></span></li>`;})}</ul></div>diff --git a/ui/component/or-map/src/or-map-attribute-field.ts b/ui/component/or-map/src/or-map-attribute-field.tsindex 52eec8c5b..b160322be 100644--- a/ui/component/or-map/src/or-map-attribute-field.ts+++ b/ui/component/or-map/src/or-map-attribute-field.ts@@ -39,7 +39,7 @@ orAttributeTemplateProvider.setTemplate((attribute: AssetAttribute) => {});@customElement("or-attribute-field")-export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitElement)) {+export class OrAttributeInput extends translate(i18next)(LitElement) {static get styles() {return css`diff --git a/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.ts b/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.tsindex 021184904..46a77a79a 100644--- a/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.ts+++ b/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.ts@@ -48,7 +48,7 @@ export const createContextMenuButtons = (workspace: EditorWorkspace, e: MouseEve{type: "button",label: i18next.t("processors", "Processors"),- icon: "settings",+ icon: "cog",action: () => { ContextMenu.open(e.pageX, e.pageY, workspace, createNodeButtons(NodeType.PROCESSOR)); }},{diff --git a/ui/demo/demo-core/src/index.ts b/ui/demo/demo-core/src/index.tsindex c7dbc9d83..744a2b55b 100644--- a/ui/demo/demo-core/src/index.ts+++ b/ui/demo/demo-core/src/index.ts@@ -5,7 +5,7 @@ import "@openremote/or-translate";import {IconSets} from "@openremote/or-icon";import i18next from "i18next";-import {AssetEvent, AttributeEvent, MetaItemType} from "@openremote/model";+import {AssetEvent, AttributeEvent, MetaItemType, SharedEvent} from "@openremote/model";import {getApartment1Asset} from "./util";@customElement("or-demo")@@ -81,14 +81,14 @@ class OrDemo extends subscribe(manager)(LitElement) {this.requestUpdate();}- public onAssetEvent(event: AssetEvent) {+ public onEvent(event: SharedEvent) {console.log("Asset Event Received:" + JSON.stringify(event, null, 2));- }- public onAttributeEvent(event: AttributeEvent) {- console.log("Attribute Event Received:" + JSON.stringify(event, null, 2));- if (event.attributeState && event.attributeState.attributeRef!.attributeName === "alarmEnabled") {- this.alarmEnabled = event.attributeState!.value;+ if (event.eventType === "attribute") {+ const attributeEvent = event as AttributeEvent;+ if (attributeEvent.attributeState && attributeEvent.attributeState.attributeRef!.attributeName === "alarmEnabled") {+ this.alarmEnabled = attributeEvent.attributeState!.value;+ }}}}