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: Upgraded chart.js to latest version and improved charting components
Rich Turnerda54a22bd068
diff --git a/ui/component/or-attribute-card/src/index.ts b/ui/component/or-attribute-card/src/index.tsindex f716757cd..d22dcad2b 100644--- a/ui/component/or-attribute-card/src/index.ts+++ b/ui/component/or-attribute-card/src/index.ts@@ -10,7 +10,8 @@ import {WellknownMetaItems} from "@openremote/model";import {AssetModelUtil, DefaultColor3, DefaultColor4, manager, Util} from "@openremote/core";-import Chart, {ChartTooltipCallback} from "chart.js";+import {Chart, ChartDataset, ChartOptions, ScatterDataPoint, LineController, LineElement, PointElement, LinearScale, TimeSeriesScale, Title} from "chart.js";+import "chartjs-adapter-moment";import {OrChartConfig} from "@openremote/or-chart";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";@@ -22,6 +23,8 @@ import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-mexport type ContextMenuOptions = "editAttribute" | "editDelta" | "editCurrentValue";+Chart.register(LineController, LineElement, PointElement, LinearScale, Title, TimeSeriesScale);+// language=CSSconst style = css`@@ -223,7 +226,7 @@ export class OrAttributeCard extends LitElement {@query("#chart")private _chartElem!: HTMLCanvasElement;- private _chart?: Chart;+ private _chart?: Chart<"line", ScatterDataPoint[]>;@query("#mdc-dialog")private _dialog!: OrMwcDialog;@@ -267,13 +270,13 @@ export class OrAttributeCard extends LitElement {}if (!this._chart) {- this._chart = new Chart(this._chartElem, {+ this._chart = new Chart(this._chartElem.getContext("2d")!, {type: "line",data: {datasets: [{- data: this.data.filter(value => value.y != null),- lineTension: 0.1,+ data: this.data.filter(value => value.y != null) as ScatterDataPoint[],+ tension: 0.1,spanGaps: true,backgroundColor: "transparent",borderColor: this._style.getPropertyValue("--internal-or-attribute-history-graph-line-color"),@@ -284,37 +287,39 @@ export class OrAttributeCard extends LitElement {options: {responsive: true,maintainAspectRatio: false,- legend: {- display: false- },- tooltips: {- displayColors: false,- callbacks: {- title: (tooltipItems, data) => {- return "";- },- label: (tooltipItem, data) => {- return tooltipItem.yLabel; // Removes the colon before the label- },- footer: () => {- return ""; // Hack the broken vertical alignment of body with footerFontSize: 0+ plugins: {+ legend: {+ display: false+ },+ tooltip: {+ displayColors: false,+ callbacks: {+ title: (context) => {+ return "";+ },+ // label: (context) => {+ // return context.parsed.y; // Removes the colon before the label+ // },+ footer: () => {+ return ""; // Hack the broken vertical alignment of body with footerFontSize: 0+ }}- } as ChartTooltipCallback+ }},scales: {- yAxes: [{+ y: {display: false- }],- xAxes: [{+ },+ x: {type: "time",display: false,- }]+ }}}});} else {if (changedProperties.has("data")) {- this._chart.data.datasets![0].data = this.data.filter(value => value.y != null);+ this._chart.data.datasets![0].data = this.data.filter(value => value.y != null) as ScatterDataPoint[];this._chart.update();this.delta = this.getFormattedDelta(this.getFirstKnownMeasurement(this.data), this.getLastKnownMeasurement(this.data));}diff --git a/ui/component/or-attribute-history/package.json b/ui/component/or-attribute-history/package.jsonindex 16fde90a3..bd3c8d587 100644--- a/ui/component/or-attribute-history/package.json+++ b/ui/component/or-attribute-history/package.json@@ -17,13 +17,12 @@"@openremote/or-mwc-components": "^1.0.3","@openremote/or-panel": "^1.0.3","@openremote/or-translate": "^1.0.3",- "chart.js": "^2.8.0",+ "@openremote/or-chart": "^1.0.4","jsonpath-plus": "^5.0.2",- "lit-element": "^2.4.0",- "moment": "^2.24.0"+ "lit-element": "^2.4.0"},"devDependencies": {- "@types/chart.js": "^2.8.5",+ "@types/chart.js": "^2.9.32","tslint": ">=5.11.0","typescript": ">=4.1.3","webpack": "^5.16.0",diff --git a/ui/component/or-attribute-history/src/index.ts b/ui/component/or-attribute-history/src/index.tsindex 27883961a..22ade483a 100644--- a/ui/component/or-attribute-history/src/index.ts+++ b/ui/component/or-attribute-history/src/index.ts@@ -19,7 +19,9 @@ import manager, {AssetModelUtil, DefaultColor2, DefaultColor3, DefaultColor4, Deimport "@openremote/or-mwc-components/or-mwc-input";import "@openremote/or-panel";import "@openremote/or-translate";-import Chart, {ChartTooltipCallback} from "chart.js";+import "@openremote/or-chart";+import {Chart, ScatterDataPoint, ChartConfiguration, TimeUnit, TimeScaleOptions} from "chart.js";+import "chartjs-adapter-moment";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";import {MDCDataTable} from "@material/data-table";import {JSONPath} from "jsonpath-plus";@@ -256,11 +258,15 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {@query("#table")protected _tableElem!: HTMLDivElement;protected _table?: MDCDataTable;- protected _chart?: Chart;+ protected _chart?: Chart<"line", ScatterDataPoint[]>;protected _type?: ValueDescriptor;protected _style!: CSSStyleDeclaration;-+ protected _startOfPeriod?: number;+ protected _endOfPeriod?: number;+ protected _timeUnits?: TimeUnit;+ protected _stepSize?: number;protected _updateTimestampTimer: number | null = null;+connectedCallback() {super.connectedCallback();this._style = window.getComputedStyle(this);@@ -350,6 +356,8 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {const isChart = this._type && (this._type.jsonType === "number" || this._type.jsonType === "boolean");if (isChart) {+ const data = this._data as ScatterDataPoint[];+if (!this._chart) {let bgColor = this._style.getPropertyValue("--internal-or-attribute-history-graph-fill-color").trim();const opacity = Number(this._style.getPropertyValue("--internal-or-attribute-history-graph-fill-opacity").trim());@@ -361,12 +369,12 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {}}- this._chart = new Chart(this._chartElem, {+ const options = {type: "line",data: {datasets: [{- data: this._data.filter(value => value.y != null),+ data: data,backgroundColor: bgColor,borderColor: this._style.getPropertyValue("--internal-or-attribute-history-graph-line-color"),pointBorderColor: this._style.getPropertyValue("--internal-or-attribute-history-graph-point-border-color"),@@ -383,29 +391,31 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {]},options: {- // maintainAspectRatio: false,- // REMOVED AS DOESN'T SIZE CORRECTLY responsive: true,+ responsive: true,+ maintainAspectRatio: false,onResize:() => this.dispatchEvent(new OrAttributeHistoryEvent('resize')),- legend: {- display: false- },- tooltips: {- displayColors: false,- xPadding: 10,- yPadding: 10,- titleMarginBottom: 10+ plugins: {+ legend: {+ display: false+ },+ tooltip: {+ displayColors: false,+ xPadding: 10,+ yPadding: 10,+ titleMarginBottom: 10+ }},scales: {- yAxes: [{- ticks: {- beginAtZero: true- },- gridLines: {+ y: {+ beginAtZero: true,+ grid: {color: "#cccccc"}- }],- xAxes: [{+ },+ x: {type: "time",+ min: this._startOfPeriod,+ max: this._endOfPeriod,time: {tooltipFormat: 'MMM D, YYYY, HH:mm:ss',displayFormats: {@@ -414,26 +424,35 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {minute: "HH:mm",hour: "HH:mm",week: "w"- }+ },+ unit: this._timeUnits,+ stepSize: this._stepSize},ticks: {autoSkip: true,- maxTicksLimit: 30,- fontColor: "#000",- fontFamily: "'Open Sans', Helvetica, Arial, Lucida, sans-serif",- fontSize: 9,- fontStyle: "normal"+ color: "#000",+ font: {+ family: "'Open Sans', Helvetica, Arial, Lucida, sans-serif",+ size: 9,+ style: "normal"+ }},gridLines: {color: "#cccccc"}- }]+ }}}- });+ } as ChartConfiguration<"line", ScatterDataPoint[]>;++ this._chart = new Chart<"line", ScatterDataPoint[]>(this._chartElem.getContext("2d")!, options);} else {if (changedProperties.has("_data")) {- this._chart.data.datasets![0].data = this._data.filter(value => value.y != null);+ this._chart.options.scales!.x!.min = this._startOfPeriod;+ this._chart.options!.scales!.x!.max = this._endOfPeriod;+ (this._chart.options!.scales!.x! as TimeScaleOptions).time!.unit = this._timeUnits!;+ (this._chart.options!.scales!.x! as TimeScaleOptions).time!.stepSize = this._stepSize!;+ this._chart.data.datasets![0].data = data;this._chart.update();}}@@ -506,7 +525,7 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {config.columns = [];- const dp = this._data!.find((dp) => dp.y !== undefined || dp.y !== null);+ const dp = this._data!.find((dp) => dp.y !== undefined);if (dp) {if (typeof(dp.y) === "object" && !Array.isArray(dp.y)) {config.columns = Object.entries(dp.y as {}).map(([prop, value]) => {@@ -626,30 +645,8 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {];}- protected _getInterval() {- let interval: DatapointInterval = DatapointInterval.HOUR;- switch (this.period) {- case "hour":- interval = DatapointInterval.MINUTE;- break;- case "day":- interval = DatapointInterval.HOUR;- break;- case "week":- interval = DatapointInterval.HOUR;- break;- case "month":- interval = DatapointInterval.DAY;- break;- case "year":- interval = DatapointInterval.MONTH;- break;- }- return interval;- }-protected async _loadData() {- if (this._loading || this._data || !this.assetType || !this.assetId || (!this.attribute && !this.attributeRef)) {+ if (this._loading || this._data || !this.assetType || !this.assetId || (!this.attribute && !this.attributeRef) || !this.period || !this.fromTimestamp) {return;}@@ -686,27 +683,53 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {return;}- if (!this.period || !this.fromTimestamp) {- this._loading = false;- return;++ let interval: DatapointInterval = DatapointInterval.HOUR;+ let stepSize = 1;++ switch (this.period) {+ case "hour":+ interval = DatapointInterval.MINUTE;+ stepSize = 5;+ break;+ case "day":+ interval = DatapointInterval.HOUR;+ stepSize = 1;+ break;+ case "week":+ interval = DatapointInterval.HOUR;+ stepSize = 6;+ break;+ case "month":+ interval = DatapointInterval.DAY;+ stepSize = 1;+ break;+ case "year":+ interval = DatapointInterval.MONTH;+ stepSize = 1;+ break;}- const startOfPeriod = moment(this.fromTimestamp).subtract(1, this.period).toDate().getTime();- const endOfPeriod = moment(this.fromTimestamp).toDate().getTime();++ const lowerCaseInterval = interval.toLowerCase();+ this._startOfPeriod = moment(this.fromTimestamp).subtract(1, this.period).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ this._endOfPeriod = moment(this.toTimestamp).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ this._timeUnits = lowerCaseInterval as TimeUnit;+ this._stepSize = stepSize;const response = await manager.rest.api.AssetDatapointResource.getDatapoints(assetId,attributeName,{- interval: this._getInterval(),- fromTimestamp: startOfPeriod,- toTimestamp: endOfPeriod+ interval: interval,+ fromTimestamp: this._startOfPeriod,+ toTimestamp: this._endOfPeriod});this._loading = false;if (response.status === 200) {- this._data = response.data;+ this._data = response.data.filter(value => value.y !== null && value.y !== undefined) as ScatterDataPoint[];}}protected _updateTimestamp(timestamp: Date, forward?: boolean, timeout=1500) {diff --git a/ui/component/or-chart/package.json b/ui/component/or-chart/package.jsonindex dd1d89366..26f15a327 100644--- a/ui/component/or-chart/package.json+++ b/ui/component/or-chart/package.json@@ -21,14 +21,15 @@"@openremote/or-panel": "^1.0.3","@openremote/or-translate": "^1.0.3","@types/chartjs-plugin-annotation": "^0.5.1",- "chart.js": "2.9.4",- "chartjs-plugin-annotation": "0.5.7",+ "chart.js": "^3.1.0",+ "chartjs-adapter-moment": "^1.0.0",+ "chartjs-plugin-annotation": "next","jsonpath-plus": "^5.0.2","lit-element": "^2.4.0","moment": "^2.24.0"},"devDependencies": {- "@types/chart.js": "^2.8.5",+ "@types/chart.js": "^2.9.32","tslint": ">=5.11.0","typescript": ">=4.1.3","webpack": "^5.16.0",diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.tsindex eae7f0398..230c0b81c 100644--- a/ui/component/or-chart/src/index.ts+++ b/ui/component/or-chart/src/index.ts@@ -11,7 +11,7 @@ import {} from "lit-element";import i18next from "i18next";import {translate} from "@openremote/or-translate";-import {Asset, Attribute, AttributeRef, DatapointInterval, WellknownMetaItems, ReadAssetEvent, AssetEvent} from "@openremote/model";+import {Asset, Attribute, AttributeRef, DatapointInterval, WellknownMetaItems, ReadAssetEvent, AssetEvent, ValueDatapoint} from "@openremote/model";import manager, {AssetModelUtil,DefaultColor2,@@ -25,13 +25,24 @@ import "@openremote/or-mwc-components/or-mwc-input";import "@openremote/or-panel";import {MDCDialog} from '@material/dialog';import "@openremote/or-translate";-import Chart, {ChartDataSets, ChartOptions} from "chart.js";+import {Chart, ChartDataset, TimeUnit, ScatterDataPoint, ScatterController, LineController, LineElement, PointElement, LinearScale, TimeScale,+ Filler,+ Legend,+ Title,+ Tooltip,+ ChartConfiguration,+ TimeScaleOptions} from "chart.js";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";import moment from "moment";import {OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";-import * as ChartAnnotation from "chartjs-plugin-annotation";+import ChartAnnotation, { AnnotationOptions } from "chartjs-plugin-annotation";+import "chartjs-adapter-moment";+import {GenericAxiosResponse } from "@openremote/rest";++Chart.register(LineController, ScatterController, LineElement, PointElement, LinearScale, TimeScale, Title, Filler, Legend, Tooltip, ChartAnnotation);+export class OrChartEvent extends CustomEvent<OrChartEventDetail> {public static readonly NAME = "or-chart-event";@@ -50,8 +61,8 @@ export class OrChartEvent extends CustomEvent<OrChartEventDetail> {export interface ChartViewConfig {assetIds?: string[];attributes?: string[];- timestamp?: Date;- compareTimestamp?: Date;+ timestamp?: number;+ compareTimestamp?: number;period?: moment.unitOfTime.Base;deltaFormat?: string;decimals?: number;@@ -306,10 +317,6 @@ const style = css`}`;-export interface ChartValueDatapoint<T> {- x?: number | string;- y?: T;-}@customElement("or-chart")export class OrChart extends translate(i18next)(LitElement) {@@ -361,12 +368,9 @@ export class OrChart extends translate(i18next)(LitElement) {@property()protected _loading: boolean = false;-- @property()- protected _baseData?: ChartValueDatapoint<any>[] | any = [];@property()- protected _data?: ChartValueDatapoint<any>[] | any = [];+ protected _data?: ChartDataset<"line", ScatterDataPoint[]>[] = undefined;@property()protected _tableTemplate?: TemplateResult;@@ -380,9 +384,11 @@ export class OrChart extends translate(i18next)(LitElement) {protected _dialogElem!: HTMLElement;protected _dialog!: MDCDialog;-protected _style!: CSSStyleDeclaration;-+ protected _startOfPeriod?: number;+ protected _endOfPeriod?: number;+ protected _timeUnits?: TimeUnit;+ protected _stepSize?: number;protected _updateTimestampTimer: number | null = null;firstUpdated() {@@ -609,9 +615,10 @@ export class OrChart extends translate(i18next)(LitElement) {});}- let reloadData = changedProperties.has("period") || changedProperties.has("compareTimestamp") || changedProperties.has("timestamp") || changedProperties.has("assetAttributes");+ const reloadData = changedProperties.has("period") || changedProperties.has("compareTimestamp") || changedProperties.has("timestamp") || changedProperties.has("assetAttributes");+if (reloadData) {- this._data = [];+ this._data = undefined;this._loadData();}@@ -619,84 +626,98 @@ export class OrChart extends translate(i18next)(LitElement) {return;}+ const now = moment().toDate().getTime();+if (!this._chart) {- this._chart = new Chart(this._chartElem, {+ const options = {type: "line",data: {datasets: this._data},- plugins: [- ChartAnnotation- ],options: {- annotation: {- annotations: [- {- type: 'line',- mode: 'vertical',- scaleID: 'x-axis-0',- value: moment(),- borderColor: "#275582",- borderWidth: 2- }- ]- },- showLines: true,- maintainAspectRatio: false,- // REMOVED AS DOESN'T SIZE CORRECTLYresponsive: true,- onResize:() => this.dispatchEvent(new OrChartEvent('resize')),- legend: {- display: false- },- tooltips: {- mode: 'x',- intersect: false,- xPadding: 10,- yPadding: 10,- titleMarginBottom: 10+ maintainAspectRatio: false,+ onResize:() => this.dispatchEvent(new OrChartEvent("resize")),+ showLines: true,+ plugins: {+ legend: {+ display: false+ },+ tooltip: {+ mode: "x",+ intersect: false,+ xPadding: 10,+ yPadding: 10,+ titleMarginBottom: 10+ },+ annotation: {+ annotations: [+ {+ type: "line",+ xMin: now,+ xMax: now,+ borderColor: "#275582",+ borderWidth: 2+ }+ ]+ },},hover: {mode: 'x',intersect: false},scales: {- yAxes: [{+ y: {ticks: {beginAtZero: true},- gridLines: {+ grid: {color: "#cccccc"}- }],- xAxes: [{+ },+ x: {type: "time",+ min: this._startOfPeriod,+ max: this._endOfPeriod,time: {tooltipFormat: 'MMM D, YYYY, HH:mm:ss',displayFormats: {- quarter: 'MMM YYYY',+ millisecond: 'HH:mm:ss.SSS',+ second: 'HH:mm:ss',minute: "HH:mm",hour: "HH:mm",week: "w"- }+ },+ unit: this._timeUnits,+ stepSize: this._stepSize},ticks: {autoSkip: true,maxTicksLimit: 30,- fontColor: "#000",- fontFamily: "'Open Sans', Helvetica, Arial, Lucida, sans-serif",- fontSize: 9,- fontStyle: "normal"+ color: "#000",+ font: {+ family: "'Open Sans', Helvetica, Arial, Lucida, sans-serif",+ size: 9,+ style: "normal"+ }},gridLines: {color: "#cccccc"}- }]+ }}- } as ChartOptions- });+ }+ } as ChartConfiguration<"line", ScatterDataPoint[]>;++ this._chart = new Chart<"line", ScatterDataPoint[]>(this._chartElem.getContext("2d")!, options);} else {if (changedProperties.has("_data")) {+ this._chart.options.scales!.x!.min = this._startOfPeriod;+ this._chart.options!.scales!.x!.max = this._endOfPeriod;+ (this._chart.options!.scales!.x! as TimeScaleOptions).time!.unit = this._timeUnits!;+ (this._chart.options!.scales!.x! as TimeScaleOptions).time!.stepSize = this._stepSize!;+ (this._chart.options!.plugins!.annotation!.annotations![0] as AnnotationOptions<"line">).xMin = now;+ (this._chart.options!.plugins!.annotation!.annotations![0] as AnnotationOptions<"line">).xMax = now;this._chart.data.datasets = this._data;this._chart.update();}@@ -707,14 +728,19 @@ export class OrChart extends translate(i18next)(LitElement) {}- getSettings() {- const configStr = window.localStorage.getItem('OrChartConfig')- if(!configStr || !this.panelName) return+ async getSettings() {+ const configStr = await manager.console.retrieveData("OrChartConfig");++ if(!configStr || !this.panelName) {+ return;+ }const viewSelector = this.activeAssetId ? this.activeAssetId : window.location.hash;const config = JSON.parse(configStr) as OrChartConfig;const view = config.views[viewSelector][this.panelName];- if (!view) return;+ if (!view) {+ return;+ }const query = {ids: view.assetIds}@@ -729,18 +755,21 @@ export class OrChart extends translate(i18next)(LitElement) {this.assets = view.assetIds.map((assetId: string) => assets.find(x => x.id === assetId)!);this.assetAttributes = view.attributes.map((attr: string, index: number) => assets[index] && assets[index].attributes ? assets[index].attributes![attr] : undefined).filter(attr => !!attr) as Attribute<any>[];this.period = view.period;- if(typeof view.periodCompare != 'undefined') this.periodCompare = view.periodCompare;-+ this.timestamp = view.timestamp ? new Date(view.timestamp) : new Date();+ this.compareTimestamp = view.compareTimestamp ? new Date(view.compareTimestamp) : new Date();+ this.periodCompare = !!view.periodCompare;});}- saveSettings() {+ async saveSettings() {+ if(!this.panelName) {+ return;+ }const viewSelector = this.activeAssetId ? this.activeAssetId : window.location.hash;const assets: Asset[] = this.assets ? this.assets.filter(asset => !!asset.id) : [];const assetIds = assets.map(asset => asset.id!);const attributes = this.assetAttributes ? this.assetAttributes.map(attr => attr.name!) : [];- const configStr = window.localStorage.getItem('OrChartConfig')- if(!this.panelName) return+ const configStr = await manager.console.retrieveData("OrChartConfig");let config:OrChartConfig;if (configStr) {@@ -761,16 +790,11 @@ export class OrChart extends translate(i18next)(LitElement) {assetIds: assetIds,attributes: attributes,period: this.period,- periodCompare: this.periodCompare+ periodCompare: this.periodCompare,+ timestamp: this.timestamp ? this.timestamp.getTime() : undefined,+ compareTimestamp: this.compareTimestamp ? this.compareTimestamp.getTime() : undefined};- const message = {- provider: "STORAGE",- action: "STORE",- key: "OrChartConfig",- value: JSON.stringify(config)-- }- manager.console._doSendProviderMessage(message)+ manager.console.storeData("OrChartConfig", JSON.stringify(config));}_openDialog() {@@ -842,7 +866,7 @@ export class OrChart extends translate(i18next)(LitElement) {elm.value = '';}- let attributes = Object.values(this.activeAsset.attributes);+ const attributes = Object.values(this.activeAsset.attributes);if (attributes && attributes.length > 0) {return attributes.filter((attribute) => attribute.meta && (attribute.meta.hasOwnProperty(WellknownMetaItems.STOREDATAPOINTS) ? attribute.meta[WellknownMetaItems.STOREDATAPOINTS] : attribute.meta.hasOwnProperty(WellknownMetaItems.AGENTLINK)))@@ -882,112 +906,92 @@ export class OrChart extends translate(i18next)(LitElement) {setPeriodCompare(periodCompare:boolean) {this.periodCompare = periodCompare;- this._loadData();this.saveSettings();++ if (periodCompare) {+ this._data = undefined;+ this._loadData();+ } else {+ this._data = this._data ? this._data.map((dataset) => (dataset as any).isComparisonDataset ? undefined : dataset).filter((dataset) => !!dataset) as ChartDataset<"line", ScatterDataPoint[]>[] : undefined;+ }}protected async _loadData() {- if(!this.assetAttributes || !this.assets || this.assets.length === 0) {+ if(this._loading || this._data || !this.assetAttributes || !this.assets || this.assets.length === 0 || this.assetAttributes.length !== this.assets.length || !this.period || !this.timestamp) {return;}- const datasetBases = this.assetAttributes.map(attribute => {- const bgColor = this.getAttrColor(attribute);- const dataset: ChartDataSets = {- borderColor: bgColor,- pointRadius: 2,- backgroundColor: bgColor,- fill: false- };- return dataset;- });-- let data = this.assetAttributes.map(async (attribute, index) => {- var valuepoints = await this._loadAttributeData(this.assets[index], attribute, this.timestamp);- if (valuepoints) {- valuepoints = valuepoints.filter(value => value.y != null);- }- const dataset = {...datasetBases[index],- data: valuepoints- };- if(this.assets[index]) {- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.assets[index]!.type, attribute.name, attribute);- const label = Util.getAttributeLabel(attribute, descriptors[0], this.assets[index]!.type, false);- dataset["label"] = this.assets[index]!.name + " " + label;- }- return dataset;- });-+ this._loading = true;- Promise.all(data).then((completed => {- this._baseData = [...completed];- }));+ let interval: DatapointInterval = DatapointInterval.HOUR;+ let stepSize = 1;- const predictedData = this.assetAttributes.map(async (attribute, index) => {- var valuepoints = await this._loadPredictedAttributeData(this.assets[index], attribute, this.timestamp);- if (valuepoints) {- valuepoints = valuepoints.filter(value => value.y != null);- }- const dataset = {...datasetBases[index],- data: valuepoints,- borderDash: [2, 4]- };+ switch (this.period) {+ case "hour":+ interval = DatapointInterval.MINUTE;+ stepSize = 5;+ break;+ case "day":+ interval = DatapointInterval.HOUR;+ stepSize = 1;+ break;+ case "week":+ interval = DatapointInterval.HOUR;+ stepSize = 6;+ break;+ case "month":+ interval = DatapointInterval.DAY;+ stepSize = 1;+ break;+ case "year":+ interval = DatapointInterval.MONTH;+ stepSize = 1;+ break;+ }- if(this.assets[index]) {- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.assets[index]!.type, attribute.name, attribute);- const label = Util.getAttributeLabel(attribute, descriptors[0], this.assets[index]!.type, false);- dataset["label"] = this.assets[index]!.name + " " + label + " " + i18next.t("predicted");+ const lowerCaseInterval = interval.toLowerCase();+ this._startOfPeriod = moment(this.timestamp).startOf(this.period).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ this._endOfPeriod = moment(this.timestamp).endOf(this.period).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ this._timeUnits = lowerCaseInterval as TimeUnit;+ this._stepSize = stepSize;+ const now = moment().toDate().getTime();+ let predictedFromTimestamp = now < this._startOfPeriod ? this._startOfPeriod : now;++ const data: ChartDataset<"line", ScatterDataPoint[]>[] = [];+ const promises = this.assetAttributes.map(async (attribute, index) => {++ const asset = this.assets[index];+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute.name, attribute);+ const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);++ let dataset = await this._loadAttributeData(asset, attribute, interval, this._startOfPeriod!, this._endOfPeriod!, false, asset.name + " " + label);+ data.push(dataset);++ dataset = await this._loadAttributeData(this.assets[index], attribute, interval, predictedFromTimestamp, this._endOfPeriod!, true, asset.name + " " + label + " " + i18next.t("predicted"));+ data.push(dataset);++ if (this.periodCompare) {+ const startOfPeriod = moment(this.compareTimestamp).startOf(this.period!).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ const endOfPeriod = moment(this.compareTimestamp).endOf(this.period!).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ const offset = this._startOfPeriod! - startOfPeriod;++ dataset = await this._loadAttributeData(this.assets[index], attribute, interval, startOfPeriod, endOfPeriod, false, asset.name + " " + label + " " + i18next.t("compare"));+ dataset.data.forEach((dp) => dp.x += offset);+ dataset.borderDash = [10, 10];+ (dataset as any).isComparisonDataset = true;+ data.push(dataset);++ predictedFromTimestamp = now < startOfPeriod ? startOfPeriod : now;+ dataset = await this._loadAttributeData(this.assets[index], attribute, interval, startOfPeriod, endOfPeriod, true, asset.name + " " + label + " " + i18next.t("compare") + " " + i18next.t("predicted"));+ dataset.data.forEach((dp) => dp.x += offset);+ dataset.borderDash = [6, 8];+ (dataset as any).isComparisonDataset = true;+ data.push(dataset);}- return dataset;});-- data = data.concat(predictedData);- if(this.periodCompare) {- const cData = this.assetAttributes.map(async (attribute, index) => {- var valuepoints = await this._loadAttributeData(this.assets[index], attribute, this.compareTimestamp);- if (valuepoints) {- valuepoints = valuepoints.filter(value => value.y != null);- }- const dataset = {...datasetBases[index],- data: valuepoints,- borderDash: [10, 10]- };-- if(this.assets[index]) {- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.assets[index]!.type, attribute.name, attribute);- const label = Util.getAttributeLabel(attribute, descriptors[0], this.assets[index]!.type, false);- dataset["label"] = this.assets[index]!.name + " " + label + " " + i18next.t("compare");- }-- return dataset;- });-- let cPredictedData = this.assetAttributes.map(async (attribute, index) => {- var valuepoints = await this._loadPredictedAttributeData(this.assets[index], attribute, this.compareTimestamp);- if (valuepoints) {- valuepoints = valuepoints.filter(value => value.y != null);- }- const dataset = {...datasetBases[index],- data: valuepoints,- borderDash: [2, 4]- };- if(this.assets[index]) {- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.assets[index]!.type, attribute.name, attribute);- const label = Util.getAttributeLabel(attribute, descriptors[0], this.assets[index]!.type, false);- dataset["label"] = this.assets[index]!.name + " " + label + " " + i18next.t("compare") + " " + i18next.t("predicted");- }- return dataset;- });-- data = data.concat(cPredictedData);-- data = data.concat(cData);- }-- Promise.all(data).then((completed=> {- this._data = completed;- }))+ await Promise.all(promises);+ this._data = data;}protected _timestampLabel(timestamp: Date | number | undefined) {@@ -1017,129 +1021,54 @@ export class OrChart extends translate(i18next)(LitElement) {return newMoment.format();}- protected async _loadAttributeData(asset: Asset, attribute:Attribute<any>, timestamp: Date | undefined) {- if (!attribute) {- return [];- }-- this._loading = true;-- if (!this.period || !timestamp) {- this._loading = false;- return [];- }-- const startOfPeriod = moment(timestamp).startOf(this.period).toDate().getTime();- const endOfPeriod = moment(timestamp).endOf(this.period).toDate().getTime();+ protected async _loadAttributeData(asset: Asset, attribute: Attribute<any>, interval: DatapointInterval, from: number, to: number, predicted: boolean, label: string | undefined): Promise<ChartDataset<"line", ScatterDataPoint[]>> {++ const bgColor = this.getAttrColor(attribute);++ const dataset: ChartDataset<"line", ScatterDataPoint[]> = {+ label: label,+ borderColor: bgColor,+ pointRadius: 2,+ backgroundColor: bgColor,+ fill: false,+ data: [],+ borderDash: predicted ? [2, 4] : undefined+ };if (asset.id && attribute.name) {- const response = await manager.rest.api.AssetDatapointResource.getDatapoints(- asset.id,- attribute.name,- {- interval: this._getInterval(),- fromTimestamp: startOfPeriod,- toTimestamp: endOfPeriod- }- );-- const data = response.data;-- this._loading = false;-- if (response.status === 200) {- data.map((datapoint: any) => {- if (datapoint['x']) {- datapoint['x'] = this._timestampLabel(datapoint['x'])- }+ const queryParams = {+ interval: interval,+ fromTimestamp: from,+ toTimestamp: to+ };- if (typeof datapoint['y'] !== 'undefined') {- datapoint['y'] = Math.round(datapoint['y'] * 100) / 100- } else {- delete datapoint['y']- }- });- return data;+ let response: GenericAxiosResponse<ValueDatapoint<any>[]>;++ if (!predicted) {+ response = await manager.rest.api.AssetDatapointResource.getDatapoints(+ asset.id,+ attribute.name,+ queryParams+ );+ } else {+ response = await manager.rest.api.AssetPredictedDatapointResource.getPredictedDatapoints(+ asset.id,+ attribute.name,+ queryParams+ );}- }- }- protected async _loadPredictedAttributeData(asset: Asset, attribute:Attribute<any>, timestamp: Date | undefined) {- if (!attribute) {- return [];- }-- this._loading = true;-- if (!this.period || !timestamp) {this._loading = false;- return [];- }-- const now = moment().toDate().valueOf();- const startOfPeriod = moment(timestamp).startOf(this.period).toDate().valueOf();- const endOfPeriod = moment(timestamp).endOf(this.period).toDate().valueOf();- const fromTimestamp = now < startOfPeriod ? startOfPeriod : now;-- if(asset && asset.id && attribute.name && endOfPeriod){- const response = await manager.rest.api.AssetPredictedDatapointResource.getPredictedDatapoints(- asset.id,- attribute.name,- {- interval: this._getInterval(),- fromTimestamp: fromTimestamp,- toTimestamp: endOfPeriod- }- );- this._loading = false;- const data = response.data;if (response.status === 200) {- data.sort((a, b) => {- if(a.x && b.x) {- return (a.x - b.x);- } else {- return 0;- }- });- data.map((datapoint: any) => {- if (datapoint['x']) {- datapoint['x'] = this._timestampLabel(datapoint['x'])- }- if (typeof datapoint['y'] !== 'undefined') {- datapoint['y'] = Math.round(datapoint['y'] * 100) / 100- } else {- delete datapoint['y'];- }- });- return data;+ dataset.data = response.data.filter(value => value.y !== null && value.y !== undefined) as ScatterDataPoint[];}}- }- protected _getInterval() {- let interval: DatapointInterval = DatapointInterval.HOUR;- switch (this.period) {- case "hour":- interval = DatapointInterval.MINUTE;- break;- case "day":- interval = DatapointInterval.HOUR;- break;- case "week":- interval = DatapointInterval.HOUR;- break;- case "month":- interval = DatapointInterval.DAY;- break;- case "year":- interval = DatapointInterval.MONTH;- break;- }- return interval;+ return dataset;}- protected _updateTimestamp(timestamp: Date, forward?: boolean, compare=false, timeout=1500) {+ protected _updateTimestamp(timestamp: Date, forward?: boolean, compare= false, timeout= 1500) {if (this._updateTimestampTimer) {window.clearTimeout(this._updateTimestampTimer);@@ -1151,8 +1080,9 @@ export class OrChart extends translate(i18next)(LitElement) {if (forward !== undefined) {newMoment.add(forward ? 1 : -1, this.period);}- if(compare) {+ if (compare) {this.compareTimestamp = newMoment.toDate()+ this.saveSettings();} else {this.timestamp = newMoment.toDate()}diff --git a/yarn.lock b/yarn.lockindex 2aa1e6fb0..a0996bb32 100644--- a/yarn.lock+++ b/yarn.lock@@ -2284,13 +2284,20 @@redux-thunk "^2.3.0"reselect "^4.0.0"-"@types/chart.js@*", "@types/chart.js@^2.8.5":+"@types/chart.js@*":version "2.9.31"resolved "https://registry.yarnpkg.com/@types/chart.js/-/chart.js-2.9.31.tgz#e8ebc7ed18eb0e5114c69bd46ef8e0037c89d39d"integrity sha512-hzS6phN/kx3jClk3iYqEHNnYIRSi4RZrIGJ8CDLjgatpHoftCezvC44uqB3o3OUm9ftU1m7sHG8+RLyPTlACrA==dependencies:moment "^2.10.2"+"@types/chart.js@^2.9.32":+ version "2.9.32"+ resolved "https://registry.yarnpkg.com/@types/chart.js/-/chart.js-2.9.32.tgz#b17d9a8c41ad348183a2ce041ebdeef892998251"+ integrity sha512-d45JiRQwEOlZiKwukjqmqpbqbYzUX2yrXdH9qVn6kXpPDsTYCo6YbfFOlnUaJ8S/DhJwbBJiLsMjKpW5oP8B2A==+ dependencies:+ moment "^2.10.2"+"@types/chartjs-plugin-annotation@^0.5.1":version "0.5.1"resolved "https://registry.yarnpkg.com/@types/chartjs-plugin-annotation/-/chartjs-plugin-annotation-0.5.1.tgz#f560fc9e2dc15aa595b6b6043c7f7789dc890a90"@@ -3257,35 +3264,20 @@ chardet@^0.7.0:resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e"integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==[email protected], chart.js@^2.4.0, chart.js@^2.8.0:- version "2.9.4"- resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-2.9.4.tgz#0827f9563faffb2dc5c06562f8eb10337d5b9684"- integrity sha512-B07aAzxcrikjAPyV+01j7BmOpxtQETxTSlQ26BEYJ+3iUkbNKaOJ/nDbT6JjyqYxseM0ON12COHYdU2cTIjC7A==- dependencies:- chartjs-color "^2.1.0"- moment "^2.10.2"--chartjs-color-string@^0.6.0:- version "0.6.0"- resolved "https://registry.yarnpkg.com/chartjs-color-string/-/chartjs-color-string-0.6.0.tgz#1df096621c0e70720a64f4135ea171d051402f71"- integrity sha512-TIB5OKn1hPJvO7JcteW4WY/63v6KwEdt6udfnDE9iCAZgy+V4SrbSxoIbTw/xkUIapjEI4ExGtD0+6D3KyFd7A==- dependencies:- color-name "^1.0.0"+chart.js@^3.1.0:+ version "3.1.0"+ resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-3.1.0.tgz#b99cfe712fa0059134a4ad3a3515135fbb20bcea"+ integrity sha512-bKJi2VbC4fqZXlLbK7LKVvmG9crjoG9anfp96utZLyIGPuCx+YN+5/HDXy98QGt3lf74T8gKUPISUZL222tDJQ==-chartjs-color@^2.1.0:- version "2.4.1"- resolved "https://registry.yarnpkg.com/chartjs-color/-/chartjs-color-2.4.1.tgz#6118bba202fe1ea79dd7f7c0f9da93467296c3b0"- integrity sha512-haqOg1+Yebys/Ts/9bLo/BqUcONQOdr/hoEr2LLTRl6C5LXctUdHxsCYfvQVg5JIxITrfCNUDr4ntqmQk9+/0w==- dependencies:- chartjs-color-string "^0.6.0"- color-convert "^1.9.3"+chartjs-adapter-moment@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/chartjs-adapter-moment/-/chartjs-adapter-moment-1.0.0.tgz#9174b1093c68bcfe285aff24f7388ad60d44e8f7"+ integrity sha512-PqlerEvQcc5hZLQ/NQWgBxgVQ4TRdvkW3c/t+SUEQSj78ia3hgLkf2VZ2yGJtltNbEEFyYGm+cA6XXevodYvWA==- version "0.5.7"- resolved "https://registry.yarnpkg.com/chartjs-plugin-annotation/-/chartjs-plugin-annotation-0.5.7.tgz#1bf0e30199a6a9ff9889ce0f37a1e755a80d10bf"- integrity sha1-G/DjAZmmqf+Yic4PN6HnVagNEL8=- dependencies:- chart.js "^2.4.0"+chartjs-plugin-annotation@next:+ version "1.0.0-rc"+ resolved "https://registry.yarnpkg.com/chartjs-plugin-annotation/-/chartjs-plugin-annotation-1.0.0-rc.tgz#8eb16169de4f9bf69e6bbae41caf03476dca60ad"+ integrity sha512-ielNXFh3DSRu2FkM4fgQvFwKP8EAzfUYBb8ZuQoobSK89HMUyDfoCcDlw/uCFoaL3uuhA9YBrbEdfi6ZNZUc7g==chokidar@^2.1.8:version "2.1.8"@@ -3388,7 +3380,7 @@ collection-visit@^1.0.0:map-visit "^1.0.0"object-visit "^1.0.0"-color-convert@^1.9.0, color-convert@^1.9.3:+color-convert@^1.9.0:version "1.9.3"resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==@@ -3400,11 +3392,6 @@ [email protected]:resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=-color-name@^1.0.0:- version "1.1.4"- resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"- integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==-colorette@^1.2.1, colorette@^1.2.2:version "1.2.2"resolved "https://registry.yarnpkg.com/colorette/-/colorette-1.2.2.tgz#cbcc79d5e99caea2dbf10eb3a26fd8b3e6acfa94"