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
Updated asset-mixin and updated or-map-marker-asset to work with asset-mixin
Rich Turnercc48fef20b08
diff --git a/ui/build.gradle b/ui/build.gradleindex 452456aa9..ef9f02911 100644--- a/ui/build.gradle+++ b/ui/build.gradle@@ -25,5 +25,5 @@ task installDist {}task modelWatch {- dependsOn resolveTask(":ui:component:model:build"), resolveTask(":ui:component:rest:build")+ dependsOn resolveTask(":ui:component:rest:build")}\ No newline at end of filediff --git a/ui/component/core/src/asset-mixin.ts b/ui/component/core/src/asset-mixin.tsindex 48cda343b..021f4de21 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 {AttributeEvent} from "@openremote/model";+import {AttributeEvent, AssetEvent, AssetEventCause} from "@openremote/model";declare type Constructor<T = {}> = new (...args: any[]) => T;@@ -10,7 +10,8 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T extereturn class extends base {public _connectRequested = false;- public _subscriptionId?: string;+ public _assetSubscriptionId?: string;+ public _attributeSubscriptionId?: string;public _assetIds?: string[];public _statusCallback = (status: EventProviderStatus) => this._onEventProviderStatusChanged(status);@@ -35,7 +36,11 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte}public connect() {- if (this._connectRequested || !eventProviderFactory.getEventProvider()) {+ if (!eventProviderFactory.getEventProvider()) {+ console.log("No event provider available so cannot subscribe");+ return;+ }+ if (this._connectRequested) {return;}@@ -45,7 +50,7 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte}public async _doConnect() {- if (!this._connectRequested || this._subscriptionId) {+ if (!this._connectRequested || this._attributeSubscriptionId) {return;}@@ -57,7 +62,8 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T extereturn;}- this._subscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAttributeEvents(this._assetIds, (event) => this._onAttributeEvent(event));+ this._assetSubscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAssetEvents(this._assetIds, (event) => this._onAssetEvent(event));+ this._attributeSubscriptionId = await eventProviderFactory.getEventProvider()!.subscribeAttributeEvents(this._assetIds, false, (event) => this._onAttributeEvent(event));}public disconnect() {@@ -70,15 +76,17 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte}public _doDisconnect() {- if (!this._subscriptionId) {+ if (!this._assetSubscriptionId) {return;}- eventProviderFactory.getEventProvider()!.unsubscribe(this._subscriptionId);- this._subscriptionId = undefined;+ eventProviderFactory.getEventProvider()!.unsubscribe(this._assetSubscriptionId);+ eventProviderFactory.getEventProvider()!.unsubscribe(this._attributeSubscriptionId!);+ this._assetSubscriptionId = undefined;+ this._attributeSubscriptionId = undefined;}- public set assetIds(assetIds: string[]) {+ public set assetIds(assetIds: string[] | undefined) {if (arraysEqual(this._assetIds, assetIds)) {return;}@@ -100,14 +108,25 @@ export const subscribe = (eventProviderFactory: EventProviderFactory) => <T exte}public _onAttributeEvent(event: AttributeEvent) {- if (!this._connectRequested || !this._subscriptionId) {+ if (!this._connectRequested || !this._assetSubscriptionId) {return;}this.onAttributeEvent(event);}+ public _onAssetEvent(event: AssetEvent) {+ if (!this._connectRequested || !this._assetSubscriptionId) {+ return;+ }++ this.onAssetEvent(event);+ }+// noinspection JSUnusedLocalSymbolspublic onAttributeEvent(event: AttributeEvent) {}++ // noinspection JSUnusedLocalSymbols+ public onAssetEvent(event: AssetEvent) {}};};diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.tsindex a9c07750a..55e091687 100644--- a/ui/component/core/src/event.ts+++ b/ui/component/core/src/event.ts@@ -6,7 +6,9 @@ import {EventSubscription,RenewEventSubscriptions,SharedEvent,- ReadAssetAttributesEvent+ ReadAssetAttributesEvent,+ AssetEvent,+ ReadAssetEvent} from "@openremote/model";export enum EventProviderStatus {@@ -30,7 +32,9 @@ export interface EventProvider {unsubscribe<T extends SharedEvent>(subscriptionId: string): void;- subscribeAttributeEvents(assetIds: string[], callback: (event: AttributeEvent) => void): Promise<string>;+ subscribeAssetEvents(assetIds: string[] | null, callback: (event: AssetEvent) => void): Promise<string>;++ subscribeAttributeEvents(assetIds: string[], requestCurrentValues: boolean, callback: (event: AttributeEvent) => void): Promise<string>;sendEvent<T extends SharedEvent>(event: T): void;}@@ -207,12 +211,51 @@ abstract class EventProviderImpl implements EventProvider {this._doSend(event);}- public async subscribeAttributeEvents(assetIds: string[], callback: (event: AttributeEvent) => void): Promise<string> {+ public async subscribeAssetEvents(assetIds: string[] | null, callback: (event: AssetEvent) => void): Promise<string> {+ let subscription: EventSubscription<AssetEvent> = {+ eventType: "asset"+ };++ if (assetIds && assetIds.length > 0) {+ subscription.filter = {+ filterType: "asset-id",+ assetIds: assetIds+ };+ }++ let subscriptionId: string | null = null;++ try {+ subscriptionId = await this.subscribe(subscription, callback);++ // Get the current state of each asset+ if (assetIds) {+ assetIds.forEach(assetId => {+ let readEvent: ReadAssetEvent = {+ assetId: assetId,+ eventType: "read-asset",+ subscriptionId: subscriptionId!+ };+ this.sendEvent(readEvent);+ });+ }+ } catch (e) {+ console.error("Failed to subscribe to asset events for assets: " + assetIds);+ if (subscriptionId) {+ this.unsubscribe(subscriptionId);+ }+ throw e;+ }++ return subscriptionId!;+ }++ public async subscribeAttributeEvents(assetIds: string[], requestCurrentValues: boolean, callback: (event: AttributeEvent) => void): Promise<string> {let subscription: EventSubscription<AttributeEvent> = {eventType: "attribute",filter: {- filterType: "attribute-entity-id",- entityIds: assetIds+ filterType: "asset-id",+ assetIds: assetIds}};@@ -222,14 +265,16 @@ abstract class EventProviderImpl implements EventProvider {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);- });+ if (requestCurrentValues) {+ assetIds.forEach(assetId => {+ let readEvent: ReadAssetAttributesEvent = {+ assetId: assetId,+ eventType: "read-asset-attributes",+ subscriptionId: subscriptionId!+ };+ this.sendEvent(readEvent);+ });+ }} catch (e) {console.error("Failed to subscribe to attribute events for assets: " + assetIds);if (subscriptionId) {@@ -242,7 +287,7 @@ abstract class EventProviderImpl implements EventProvider {}protected _processNextSubscription() {- if (this._status != EventProviderStatus.CONNECTED || this._queuedSubscriptions.length === 0) {+ if (this._status !== EventProviderStatus.CONNECTED || this._queuedSubscriptions.length === 0) {return;}diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/mapwidget.tsindex 183d0b91f..6b60677e5 100644--- a/ui/component/or-map/src/mapwidget.ts+++ b/ui/component/or-map/src/mapwidget.ts@@ -174,7 +174,9 @@ export class MapWidget {}public addMarker(marker: OrMapMarker) {- this._updateMarkerElement(marker, true);+ if (marker.lat && marker.lng) {+ this._updateMarkerElement(marker, true);+ }}public removeMarker(marker: OrMapMarker) {@@ -189,7 +191,15 @@ export class MapWidget {switch (prop) {case "lat":case "lng":- this._updateMarkerPosition(marker);+ if (marker.lat && marker.lng) {+ if (marker._actualMarkerElement) {+ this._updateMarkerPosition(marker);+ } else {+ this._updateMarkerElement(marker, true);+ }+ } else if (marker._actualMarkerElement) {+ this._updateMarkerElement(marker, false);+ }break;}}@@ -199,13 +209,13 @@ export class MapWidget {case Type.RASTER:const m: MarkerJS | undefined = this._markersJs.get(marker);if (m) {- m.setLatLng([marker.lat, marker.lng]);+ m.setLatLng([marker.lat!, marker.lng!]);}break;case Type.VECTOR:const mGl: MarkerGL | undefined = this._markersGl.get(marker);if (mGl) {- mGl.setLngLat([marker.lng, marker.lat]);+ mGl.setLngLat([marker.lng!, marker.lat!]);}break;}@@ -227,7 +237,7 @@ export class MapWidget {const elem = marker._createMarkerElement();if (elem) {const icon = L.divIcon({html: elem.outerHTML, className: "or-marker-raster"});- m = L.marker([marker.lat, marker.lng], {icon: icon, clickable: marker.interactive});+ m = L.marker([marker.lat!, marker.lng!], {icon: icon, clickable: marker.interactive});m.addTo(this._mapJs!);marker._actualMarkerElement = m.getElement() ? m.getElement().firstElementChild as HTMLDivElement : undefined;if (marker.interactive) {@@ -255,7 +265,7 @@ export class MapWidget {element: elem,anchor: "top-left"})- .setLngLat([marker.lng, marker.lat])+ .setLngLat([marker.lng!, marker.lat!]).addTo(this._mapGl!);this._markersGl.set(marker, mGl);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 485a59e6a..d02db9984 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,38 +1,41 @@import {customElement, property, PropertyValues} from "lit-element";import {OrMapMarker} from "./or-map-marker";-import rest from "@openremote/rest";-import {Asset, AssetAttribute, GeoJSONPoint} from "@openremote/model";-import {GenericAxiosResponse} from "axios";+import {AttributeEvent, Attribute, AttributeType, GeoJSONPoint, AssetType, AssetEvent, AssetEventCause} from "@openremote/model";+import {subscribe} from "@openremote/core/dist/asset-mixin";+import openremote, {AssetModelUtil} from "@openremote/core";@customElement("or-map-marker-asset")-export class OrMapMarkerAsset extends OrMapMarker {+export class OrMapMarkerAsset extends subscribe(openremote)(OrMapMarker) {- @property({type: String})+ @property({type: String, reflect: true, attribute: true})public asset?: string;public assetTypeAsIcon: boolean = true;constructor() {super();+ this.visible = false;}- public connectedCallback(): void {- super.connectedCallback();- }-- public disconnectedCallback(): void {- super.disconnectedCallback();- }-- protected firstUpdated(_changedProperties: PropertyValues): void {- if (_changedProperties.has("asset")) {- this.refreshMarker();+ protected set type(type: string | undefined) {+ if (!type) {+ this.visible = false;+ return;}++ const descriptor = AssetModelUtil.getAssetDescriptor(type);+ const icon = descriptor ? descriptor.icon : AssetType.THING.icon;+ this.icon = icon;+ this.visible = true;}protected shouldUpdate(_changedProperties: PropertyValues): boolean {if (_changedProperties.has("asset")) {- this.refreshMarker();++ this.lat = undefined;+ this.lng = undefined;+ this.type = undefined;+ this.assetIds = this.asset && this.asset.length > 0 ? [this.asset] : undefined;if (Object.keys(_changedProperties).length === 1) {return false;@@ -41,47 +44,34 @@ export class OrMapMarkerAsset extends OrMapMarker {return super.shouldUpdate(_changedProperties);}- protected refreshMarker() {-- if (this.asset && this.asset.length > 0) {- this.getAsset().then((asset) => {- const attrs = asset.attributes as any;- const attr: AssetAttribute | undefined = attrs.location;-- if (!attr) {- this.visible = false;- return;- }+ public onAttributeEvent(event: AttributeEvent) {+ if (event.attributeState!.attributeRef!.attributeName !== AttributeType.LOCATION.attributeName) {+ return;+ }- const location: GeoJSONPoint | null = attr.value as GeoJSONPoint;+ this._updateLocation(event.attributeState!.value as GeoJSONPoint);- if (!location) {- this.visible = false;- return;- }+ }- // Model d.ts is clearly not perfect need to sort out Jackson annotations- this.lat = (location.coordinates as any)[1] || 0;- this.lng = (location.coordinates as any)[0] || 0;- if (this.assetTypeAsIcon) {- if (asset.type) {- // TODO: Get hold of icon from asset type- this.icon = "office-building";- } else {- this.icon = undefined;- }- }- this.visible = true;- }).catch(() => {- this.visible = false;- });- } else {- this.visible = false;+ public onAssetEvent(event: AssetEvent) {+ switch (event.cause) {+ case AssetEventCause.READ:+ const attr = event.asset && event.asset.attributes && event.asset.attributes.hasOwnProperty("location") ? event.asset.attributes.location as Attribute : null;+ this._updateLocation(attr ? attr.value as GeoJSONPoint : null);+ case AssetEventCause.CREATE:+ case AssetEventCause.UPDATE:+ this.type = event.asset!.type;+ break;+ case AssetEventCause.DELETE:+ this.type = undefined;+ this.lat = undefined;+ this.lng = undefined;+ break;}}- protected async getAsset(): Promise<Asset> {- const response: GenericAxiosResponse<Asset> = await rest.api.AssetResource.get(this.asset!);- return response.data;+ protected _updateLocation(location: GeoJSONPoint | null) {+ this.lat = location && location.coordinates ? (location.coordinates as any)[1] : undefined;+ this.lng = location && location.coordinates ? (location.coordinates as any)[0] : undefined;}}diff --git a/ui/component/or-map/src/markers/or-map-marker.ts b/ui/component/or-map/src/markers/or-map-marker.tsindex 7e48af8e0..6a7feb4e2 100644--- a/ui/component/or-map/src/markers/or-map-marker.ts+++ b/ui/component/or-map/src/markers/or-map-marker.ts@@ -97,11 +97,11 @@ export class OrMapMarker extends LitElement {<or-icon class="marker-icon" icon="${icon || ""}"></or-icon>`- @property({type: Number})- public lat: number = 0;+ @property({type: Number, reflect: true, attribute: true})+ public lat?: number;- @property({type: Number})- public lng: number = 0;+ @property({type: Number, reflect: true})+ public lng?: number;@property({type: Boolean})public visible: boolean = true;diff --git a/ui/demo/demo-or-map/index.html b/ui/demo/demo-or-map/index.htmlindex b8c922b56..79c0ee1d6 100644--- a/ui/demo/demo-or-map/index.html+++ b/ui/demo/demo-or-map/index.html@@ -40,7 +40,7 @@<or-map-marker lat="51.445990" lng="5.454250" class="marker" icon="or:logo-plain"></or-map-marker></or-map><or-map id="vector" center="5.454250, 51.445990" style="height: 500px; width: 100%;">- <or-map-marker lat="51.445990" lng="5.454250" class="marker" icon="or:logo-plain"></or-map-marker>+ <or-map-marker id="demo-marker" lng="5.454250" class="marker" icon="or:logo-plain"></or-map-marker></or-map></template></demo-snippet>@@ -64,6 +64,7 @@ insert our 'bundle.js'.})();</script><script src="modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>-+<button onclick="document.getElementById('demo-marker').setAttribute('lat','51.445990');">Set Marker Latitude</button>+<button onclick="document.getElementById('demo-marker').removeAttribute('lat');">Remove Marker Latitude</button></body></html>diff --git a/ui/demo/demo-or-map/package.json b/ui/demo/demo-or-map/package.jsonindex b3af7a8f9..350ffb695 100644--- a/ui/demo/demo-or-map/package.json+++ b/ui/demo/demo-or-map/package.json@@ -8,7 +8,7 @@"modelWatch": "node ../../model-watch.js","build": "npx tsc -b && npx cross-env NODE_ENV=production webpack","serve": "npx webpack-dev-server",- "watch": "node ../../model-build.js && npx tsc -b -w",+ "watch": "npx tsc -b -w","test": "echo \"Error: no test specified\" && exit 1"},"author": "OpenRemote",