Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI updates: Added Bar Chart widget (#1996)

Martin Peeters64c49351bc56
diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt
index 9d14f51fe..4293eb4c5 100644
--- a/CONTRIBUTORS.txt
+++ b/CONTRIBUTORS.txt
@@ -32,3 +32,4 @@ Mihaela Aleksandrova
Kevin Lin
Sam Sulaimanov
Igor Melnyk
+Wouter Voorberg
diff --git a/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java b/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java
index dc38a60c5..04d885e0c 100644
--- a/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java
+++ b/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java
@@ -16,7 +16,7 @@ public class AssetDatapointIntervalQuery extends AssetDatapointQuery {
public Formula formula;
public enum Formula {
- MIN, AVG, MAX
+ MIN, AVG, MAX, DIFFERENCE, COUNT, SUM, MODE, MEDIAN
}
public AssetDatapointIntervalQuery() {
@@ -40,14 +40,112 @@ public class AssetDatapointIntervalQuery extends AssetDatapointQuery {
public String getSQLQuery(String tableName, Class<?> attributeType) throws IllegalStateException {
boolean isNumber = Number.class.isAssignableFrom(attributeType);
boolean isBoolean = Boolean.class.isAssignableFrom(attributeType);
- String function = (gapFill ? "public.time_bucket_gapfill" : "public.time_bucket");
- if (isNumber) {
- return "select " + function + "(cast(? as interval), timestamp) AS x, " + this.formula.toString().toLowerCase() + "(cast(value as numeric)) FROM " + tableName + " WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? GROUP BY x ORDER by x ASC";
- } else if (isBoolean) {
- return "select " + function + "(cast(? as interval), timestamp) AS x, " + this.formula.toString().toLowerCase() + "(case when cast(cast(value as text) as boolean) is true then 1 else 0 end) FROM " + tableName + " WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? GROUP BY x ORDER by x ASC";
- } else {
+ if (!isNumber && !isBoolean) {
throw new IllegalStateException("Query of type Interval requires either a number or a boolean attribute.");
}
+
+ String function = (gapFill ? "public.time_bucket_gapfill" : "public.time_bucket");
+ return isNumber ? getSQLQueryForNumbers(tableName, function) : getSQLQueryForBooleans(tableName, function);
+ }
+
+ protected String getSQLQueryForNumbers(String tableName, String function) {
+ switch (this.formula) {
+ case DIFFERENCE:
+ return "WITH interval_data AS (" +
+ "SELECT " + function +
+ "(cast(? as interval), timestamp) AS x, public.locf(public.last(value::DOUBLE PRECISION, timestamp)) AS numeric_value " +
+ "FROM " + tableName + " " + "WHERE ENTITY_ID = ? AND ATTRIBUTE_NAME = ? AND TIMESTAMP >= ? AND TIMESTAMP <= ? GROUP BY x )" +
+ "SELECT x, COALESCE(numeric_value - LAG(numeric_value, 1, numeric_value) OVER (ORDER BY x), numeric_value) AS delta FROM interval_data ORDER BY x ASC";
+ case COUNT:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ "COUNT(*) AS datapoint_count " +
+ "FROM " + tableName + " " +
+ "WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ "GROUP BY x ORDER by x ASC";
+ case SUM:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ "SUM(cast(value as numeric)) AS total_sum " +
+ "FROM " + tableName + " " +
+ "WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ "GROUP BY x ORDER by x ASC";
+ case MODE:
+ return "WITH bucketed AS ( " +
+ " SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ " cast(value as numeric) AS num_value " +
+ " FROM " + tableName + " " +
+ " WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ ") " +
+ "SELECT d.x, ( " +
+ " SELECT num_value FROM ( " +
+ " SELECT num_value, COUNT(*) AS freq " +
+ " FROM bucketed b2 " +
+ " WHERE b2.x = d.x " +
+ " GROUP BY num_value " +
+ " ORDER BY freq DESC, num_value " +
+ " LIMIT 1 " +
+ " ) AS mode_sub " +
+ ") AS mode_value " +
+ "FROM (SELECT DISTINCT x FROM bucketed) d " +
+ "ORDER BY d.x ASC";
+ case MEDIAN:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ "PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY cast(value as numeric)) as median_value " +
+ "FROM " + tableName + " " +
+ "WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ "GROUP BY x ORDER by x ASC";
+ default:
+ return "SELECT " + function +
+ "(cast(? as interval), timestamp) AS x, " + this.formula.toString().toLowerCase() +
+ "(cast(value as numeric)) FROM " + tableName +
+ " WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? GROUP BY x ORDER by x ASC";
+ }
+ }
+
+ protected String getSQLQueryForBooleans(String tableName, String function) {
+ switch (this.formula) {
+ case DIFFERENCE:
+ throw new IllegalStateException("Query of type DIFFERENCE is not applicable for boolean attributes.");
+ case COUNT:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ "COUNT(*) AS datapoint_count " +
+ "FROM " + tableName + " " +
+ "WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ "GROUP BY x ORDER by x ASC";
+ case SUM:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ "SUM(CASE WHEN cast(value as text)::boolean THEN 1 ELSE 0 END) AS true_count_sum " +
+ "FROM " + tableName + " " +
+ "WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ "GROUP BY x ORDER by x ASC";
+ case MODE:
+ return "WITH bucketed AS ( " +
+ " SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ " cast(value as text)::boolean AS bool_value " +
+ " FROM " + tableName + " " +
+ " WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ ") " +
+ "SELECT d.x, ( " +
+ " SELECT bool_value FROM ( " +
+ " SELECT bool_value, COUNT(*) AS freq " +
+ " FROM bucketed b2 " +
+ " WHERE b2.x = d.x " +
+ " GROUP BY bool_value " +
+ " ORDER BY freq DESC, bool_value DESC " +
+ " LIMIT 1 " +
+ " ) AS mode_sub " +
+ ") AS mode_value " +
+ "FROM (SELECT DISTINCT x FROM bucketed) d " +
+ "ORDER BY d.x ASC";
+ case MEDIAN:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " +
+ "CASE WHEN PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY (CASE WHEN cast(value as text)::boolean THEN 1 ELSE 0 END)) >= 0.5 " +
+ "THEN true ELSE false END AS median_value " +
+ "FROM " + tableName + " " +
+ "WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? " +
+ "GROUP BY x ORDER by x ASC";
+ default:
+ return "SELECT " + function + "(cast(? as interval), timestamp) AS x, " + this.formula.toString().toLowerCase() + "(case when cast(cast(value as text) as boolean) is true then 1 else 0 end) FROM " + tableName + " WHERE ENTITY_ID = ? and ATTRIBUTE_NAME = ? and TIMESTAMP >= ? and TIMESTAMP <= ? GROUP BY x ORDER by x ASC";
+ }
}
@Override
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointQueryTest.groovy
index 55dc82ada..51b211484 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointQueryTest.groovy
@@ -26,9 +26,9 @@ import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import java.time.LocalDateTime
+import java.time.Month
import java.time.ZoneId
-
-import static java.util.concurrent.TimeUnit.HOURS
+import java.time.temporal.ChronoUnit
class AssetDatapointQueryTest extends Specification implements ManagerContainerTrait {
@@ -223,7 +223,7 @@ class AssetDatapointQueryTest extends Specification implements ManagerContainerT
- def "Interval query should be returned in chronological order"() {
+ def "Interval query should be returned correctly and in chronological order"() {
given: "expected conditions"
def conditions = new PollingConditions(timeout: 10, delay: 0.2)
@@ -247,7 +247,13 @@ class AssetDatapointQueryTest extends Specification implements ManagerContainerT
then: "asset should exist and be correct"
def assetName = "Light 1"
def attributeName = "brightness"
- def dateTime = LocalDateTime.now()
+ def dateTime = LocalDateTime.of(2025, Month.AUGUST, 7, 9, 00);
+ def queryTime30 = dateTime.minus(30, ChronoUnit.MINUTES)
+ def queryTime60 = dateTime.minus(60, ChronoUnit.MINUTES)
+ def queryTimeNow = dateTime
+ def time30 = queryTime30.atZone(ZoneId.systemDefault()).toInstant()
+ def time60 = queryTime60.atZone(ZoneId.systemDefault()).toInstant()
+ def timeNow = queryTimeNow.atZone(ZoneId.systemDefault()).toInstant()
assert asset != null // light 1, 2 and 3
assert asset.name == assetName
assert asset.attributes.has(attributeName)
@@ -261,18 +267,13 @@ class AssetDatapointQueryTest extends Specification implements ManagerContainerT
/* ------------------------- */
- when: "the first datapoints are added to the asset"
- assetDatapointService.upsertValue(asset.getId(), attributeName, 25d, dateTime.minusMinutes(10))
- assetDatapointService.upsertValue(asset.getId(), attributeName, 30d, dateTime.minusMinutes(5))
- assetDatapointService.upsertValue(asset.getId(), attributeName, 10d, dateTime.minusMinutes(30))
-
- and: "the clock advances by an hour"
- advancePseudoClock(1, HOURS, container)
-
- and: "the other datapoints are added to the asset, using an timestamp earlier than the previous ones"
- assetDatapointService.upsertValue(asset.getId(), attributeName, 90d, dateTime.minusMinutes(20))
- assetDatapointService.upsertValue(asset.getId(), attributeName, 15d, dateTime.minusMinutes(25))
- assetDatapointService.upsertValue(asset.getId(), attributeName, 20d, dateTime.minusMinutes(15))
+ when: "the first datapoints are added to the asset in random order"
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 25d, dateTime.minus(10, ChronoUnit.MINUTES))
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 30d, dateTime.minus(5, ChronoUnit.MINUTES))
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 10d, dateTime.minus(30, ChronoUnit.MINUTES))
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 90d, dateTime.minus(20, ChronoUnit.MINUTES))
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 15d, dateTime.minus(25, ChronoUnit.MINUTES))
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 20d, dateTime.minus(15, ChronoUnit.MINUTES))
then: "datapoints should exist"
def allDatapoints = new ArrayList<AssetDatapoint>()
@@ -287,7 +288,7 @@ class AssetDatapointQueryTest extends Specification implements ManagerContainerT
def intervalDatapoints1 = assetDatapointService.queryDatapoints(
asset.getId(),
asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
- new AssetDatapointIntervalQuery(dateTime.minusMinutes(60), dateTime, "1 minute", AssetDatapointIntervalQuery.Formula.AVG, false)
+ new AssetDatapointIntervalQuery(queryTime60, queryTimeNow, "1 minute", AssetDatapointIntervalQuery.Formula.AVG, false)
)
assert intervalDatapoints1.size() == 6
def index = 0
@@ -302,9 +303,9 @@ class AssetDatapointQueryTest extends Specification implements ManagerContainerT
def intervalDatapoints2 = assetDatapointService.queryDatapoints(
asset.getId(),
asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
- new AssetDatapointIntervalQuery(dateTime.minusMinutes(60), dateTime, "1 minute", AssetDatapointIntervalQuery.Formula.AVG, true)
+ new AssetDatapointIntervalQuery(queryTime60, queryTimeNow, "1 minute", AssetDatapointIntervalQuery.Formula.AVG, true)
)
- assert intervalDatapoints2.size() == 61
+ assert intervalDatapoints2.size() == 61 // because 60/1=60, plus an extra datapoint for the spare milliseconds of time
def index2 = 0
intervalDatapoints2.toList().stream().forEach { dp -> {
if(index2 > 0) {
@@ -313,6 +314,136 @@ class AssetDatapointQueryTest extends Specification implements ManagerContainerT
index2++
}}
+ when: "requesting interval datapoints using DIFFERENCE"
+ def diffDatapoints1 = assetDatapointService.queryDatapoints(
+ asset.getId(),
+ asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
+ new AssetDatapointIntervalQuery(queryTime30, queryTimeNow, "5 minutes", AssetDatapointIntervalQuery.Formula.DIFFERENCE, true)
+ )
+
+ then: "DIFFERENCE datapoints should be correct"
+ assert diffDatapoints1.size() == 7 // Because 30/5=6, plus an extra datapoint for the spare milliseconds of time.
+ assert diffDatapoints1[0].timestamp == time30.toEpochMilli()
+ assert diffDatapoints1[1].timestamp == time30.plus(5, ChronoUnit.MINUTES).toEpochMilli()
+ assert diffDatapoints1[2].timestamp == time30.plus(10, ChronoUnit.MINUTES).toEpochMilli()
+ assert diffDatapoints1[3].timestamp == time30.plus(15, ChronoUnit.MINUTES).toEpochMilli()
+ assert diffDatapoints1[4].timestamp == time30.plus(20, ChronoUnit.MINUTES).toEpochMilli()
+ assert diffDatapoints1[5].timestamp == time30.plus(25, ChronoUnit.MINUTES).toEpochMilli()
+ assert diffDatapoints1[6].timestamp == timeNow.toEpochMilli()
+ assert diffDatapoints1[0].value == 0 // Initial value was 10, nothing happened since
+ assert diffDatapoints1[1].value == 5 // First bump from 10 -> 15, so difference is 5.
+ assert diffDatapoints1[2].value == 75 // 15 -> 90
+ assert diffDatapoints1[3].value == -70 // 90 -> 20
+ assert diffDatapoints1[4].value == 5 // 20 -> 25
+ assert diffDatapoints1[5].value == 5 // 25 -> 30
+ assert diffDatapoints1[6].value == 0 // Because nothing happened the spare milliseconds of time
+
+ when: "requesting interval datapoints using COUNT"
+ def countDatapoints1 = assetDatapointService.queryDatapoints(
+ asset.getId(),
+ asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
+ new AssetDatapointIntervalQuery(queryTime60, queryTimeNow, "5 minutes", AssetDatapointIntervalQuery.Formula.COUNT, true)
+ )
+
+ then: "COUNT datapoints should be correct"
+ assert countDatapoints1.size() == 13 // Because 60/5=12, plus an extra datapoint for the spare milliseconds of time.
+ assert countDatapoints1[0].timestamp == time60.toEpochMilli()
+ assert countDatapoints1[1].timestamp == time60.plus(5, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[2].timestamp == time60.plus(10, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[3].timestamp == time60.plus(15, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[4].timestamp == time60.plus(20, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[5].timestamp == time60.plus(25, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[6].timestamp == time60.plus(30, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[7].timestamp == time60.plus(35, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[8].timestamp == time60.plus(40, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[9].timestamp == time60.plus(45, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[10].timestamp == time60.plus(50, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[11].timestamp == time60.plus(55, ChronoUnit.MINUTES).toEpochMilli()
+ assert countDatapoints1[12].timestamp == timeNow.toEpochMilli()
+ assert countDatapoints1[0].value == null
+ assert countDatapoints1[1].value == null
+ assert countDatapoints1[2].value == null
+ assert countDatapoints1[3].value == null
+ assert countDatapoints1[4].value == null
+ assert countDatapoints1[5].value == null
+ assert countDatapoints1[6].value == 1
+ assert countDatapoints1[7].value == 1
+ assert countDatapoints1[8].value == 1
+ assert countDatapoints1[9].value == 1
+ assert countDatapoints1[10].value == 1
+ assert countDatapoints1[11].value == 1
+ assert countDatapoints1[12].value == null // Spare milliseconds of time
+
+ when: "requesting interval datapoints using SUM"
+ def sumDatapoints1 = assetDatapointService.queryDatapoints(
+ asset.getId(),
+ asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
+ new AssetDatapointIntervalQuery(queryTime30, queryTimeNow, "10 minutes", AssetDatapointIntervalQuery.Formula.SUM, true)
+ )
+
+ then: "SUM datapoints should be correct"
+ assert sumDatapoints1.size() == 4 // Because 30/10=3, plus an extra datapoint for the spare milliseconds of time.
+ assert sumDatapoints1[0].timestamp == time30.toEpochMilli()
+ assert sumDatapoints1[1].timestamp == time30.plus(10, ChronoUnit.MINUTES).toEpochMilli()
+ assert sumDatapoints1[2].timestamp == time30.plus(20, ChronoUnit.MINUTES).toEpochMilli()
+ assert sumDatapoints1[3].timestamp == timeNow.toEpochMilli()
+ assert sumDatapoints1[0].value == (10 + 15)
+ assert sumDatapoints1[1].value == (90 + 20)
+ assert sumDatapoints1[2].value == (25 + 30)
+ assert sumDatapoints1[3].value == null // Spare milliseconds of time
+
+ when: "requesting interval datapoints using MODE"
+ def modeDatapoints1 = assetDatapointService.queryDatapoints(
+ asset.getId(),
+ asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
+ new AssetDatapointIntervalQuery(queryTime30, queryTimeNow, "5 minutes", AssetDatapointIntervalQuery.Formula.MODE, true)
+ )
+
+ then: "MODE datapoints should be correct"
+ assert modeDatapoints1.size() == 6
+ assert modeDatapoints1[0].timestamp == time30.toEpochMilli()
+ assert modeDatapoints1[1].timestamp == time30.plus(5, ChronoUnit.MINUTES).toEpochMilli()
+ assert modeDatapoints1[2].timestamp == time30.plus(10, ChronoUnit.MINUTES).toEpochMilli()
+ assert modeDatapoints1[3].timestamp == time30.plus(15, ChronoUnit.MINUTES).toEpochMilli()
+ assert modeDatapoints1[4].timestamp == time30.plus(20, ChronoUnit.MINUTES).toEpochMilli()
+ assert modeDatapoints1[5].timestamp == time30.plus(25, ChronoUnit.MINUTES).toEpochMilli()
+ assert modeDatapoints1[0].value == 10
+ assert modeDatapoints1[1].value == 15
+ assert modeDatapoints1[2].value == 90
+ assert modeDatapoints1[3].value == 20
+ assert modeDatapoints1[4].value == 25
+ assert modeDatapoints1[5].value == 30
+
+ when: "requesting interval datapoints using MEDIAN"
+ def medianDatapoints1 = assetDatapointService.queryDatapoints(
+ asset.getId(),
+ asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
+ new AssetDatapointIntervalQuery(queryTime30, queryTimeNow, "15 minutes", AssetDatapointIntervalQuery.Formula.MEDIAN, true)
+ )
+
+ then: "MEDIAN datapoints should be correct"
+ assert medianDatapoints1.size() == 3 // Because 30/15=2, plus an extra datapoint for the spare milliseconds of time.
+ assert medianDatapoints1[0].timestamp == time30.toEpochMilli()
+ assert medianDatapoints1[1].timestamp == time30.plus(15, ChronoUnit.MINUTES).toEpochMilli()
+ assert medianDatapoints1[2].timestamp == timeNow.toEpochMilli()
+ assert medianDatapoints1[0].value == 15
+ assert medianDatapoints1[1].value == 25
+ assert medianDatapoints1[2].value == null // Spare milliseconds of time
+
+ when: "adding an additional datapoint of 90"
+ assetDatapointService.upsertValue(asset.getId(), attributeName, 90d, dateTime.minus(1, ChronoUnit.MINUTES))
+
+ and: "requesting interval datapoints using MODE with a full interval"
+ def modeDatapoints2 = assetDatapointService.queryDatapoints(
+ asset.getId(),
+ asset.getAttribute(attributeName).orElseThrow({ new RuntimeException("Missing attribute") }),
+ new AssetDatapointIntervalQuery(queryTime30, queryTimeNow, "60 minutes", AssetDatapointIntervalQuery.Formula.MODE, true)
+ )
+
+ then: "MODE datapoints should return 90, because it is most common within the interval"
+ assert modeDatapoints2.size() == 1
+ assert modeDatapoints2[0].timestamp == time60.toEpochMilli()
+ assert modeDatapoints2[0].value == 90
}
def "All query should return the correct data when the maximum is respected"() {
diff --git a/ui/app/manager/package.json b/ui/app/manager/package.json
index e71bd8c63..2e3f9a4f1 100644
--- a/ui/app/manager/package.json
+++ b/ui/app/manager/package.json
@@ -28,6 +28,7 @@
},
"dependencies": {
"@openremote/or-app": "workspace:*",
+ "@openremote/or-attribute-barchart": "workspace:*",
"iso-639-1": "^3.1.3"
},
"devDependencies": {
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index 98d715768..416073cf6 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -162,9 +162,41 @@
"prefixDefault": "Default prefix",
"timeframe": "Timeframe",
"timeframeDefault": "Default timeframe",
+ "intervalBy": "Per {{interval}}",
+ "intervalByauto": "Auto",
+ "intervalBy1minute": "Per minute",
+ "intervalBy5minutes": "Per 5 minutes",
+ "intervalBy5minutes-auto": "Auto (5min)",
+ "intervalBy30minutes": "Per 30 minutes",
+ "intervalBy30minutes-auto": "Auto (30min)",
+ "intervalByhour": "Per hour",
+ "intervalByhour-auto": "Auto (hour)",
+ "intervalByday": "Per day",
+ "intervalByday-auto": "Auto (day)",
+ "intervalByweek": "Per week",
+ "intervalByweek-auto": "Auto (week)",
+ "intervalBymonth": "Per month",
+ "intervalBymonth-auto": "Auto (month)",
+ "intervalByyear": "Per year",
"dataSampling": "Data sampling",
"algorithm": "Algorithm",
"algorithmMethod": "Method per interval",
+ "methodMaxAttributes": "Maximum",
+ "methodMaxAttributes-short": "MAX",
+ "methodMinAttributes": "Minimum",
+ "methodMinAttributes-short": "MIN",
+ "methodAvgAttributes": "Average",
+ "methodAvgAttributes-short": "AVG",
+ "methodDifferenceAttributes": "Difference",
+ "methodDifferenceAttributes-short": "DIFF",
+ "methodMedianAttributes": "Median",
+ "methodMedianAttributes-short": "MEDIAN",
+ "methodModeAttributes": "Mode",
+ "methodModeAttributes-short": "MOD",
+ "methodSumAttributes": "Sum",
+ "methodSumAttributes-short": "SUM",
+ "methodCountAttributes": "Count",
+ "methodCountAttributes-short": "COUNT",
"addAttribute": "Add attribute",
"selectAttributes": "Select attributes",
"selectAttribute": "Select attribute",
@@ -776,12 +808,15 @@
"center": "Center",
"imageUrl": "Image URL",
"noImageSelected": "No image selected",
+ "noData": "No data",
+ "selectMethod": "Select aggregation method",
"faint": "Faint",
"smooth": "Smooth",
"stepped": "Stepped",
"fill": "Fill",
"extendData": "Extend latest datapoint",
- "lineColor": "Line color"
+ "lineColor": "Line color",
+ "barColor": "Bar color"
},
"south": "South",
"east": "East",
@@ -875,6 +910,11 @@
"AVG": "Average (mean)",
"MIN": "Minimum",
"MAX": "Maximum",
+ "DIFFERENCE": "Difference",
+ "COUNT": "Count",
+ "MEDIAN": "Median",
+ "MODE": "Mode",
+ "SUM": "Sum",
"alarm": {
"": "Alarm",
"alarm_plural": "Alarms",
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index 9121b5f5c..24a529303 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -162,9 +162,41 @@
"prefixDefault": "Standaard prefix",
"timeframe": "Tijdvak",
"timeframeDefault": "Standaard tijdvak",
+ "intervalBy": "Per {{interval}}",
+ "intervalByauto": "Auto",
+ "intervalBy1minute": "Per minuut",
+ "intervalBy5minutes": "Per 5 minuten",
+ "intervalBy5minutes-auto": "Auto (5min)",
+ "intervalBy30minutes": "Per 30 minuten",
+ "intervalBy30minutes-auto": "Auto (30min)",
+ "intervalByhour": "Per uur",
+ "intervalByhour-auto": "Auto (uur)",
+ "intervalByday": "Per dag",
+ "intervalByday-auto": "Auto (dag)",
+ "intervalByweek": "Per week",
+ "intervalByweek-auto": "Auto (week)",
+ "intervalBymonth": "Per maand",
+ "intervalBymonth-auto": "Auto (maand)",
+ "intervalByyear": "Per jaar",
"dataSampling": "Data weergave",
"algorithm": "Algoritme",
"algorithmMethod": "Methode per interval",
+ "methodMaxAttributes": "Maximum",
+ "methodMaxAttributes-short": "MAX",
+ "methodMinAttributes": "Minimum",
+ "methodMinAttributes-short": "MIN",
+ "methodAvgAttributes": "Gemiddeld",
+ "methodAvgAttributes-short": "GEM",
+ "methodDifferenceAttributes": "Verschil",
+ "methodDifferenceAttributes-short": "VERSCHIL",
+ "methodMedianAttributes": "Mediaan",
+ "methodMedianAttributes-short": "MEDIAAN",
+ "methodModeAttributes": "Modus",
+ "methodModeAttributes-short": "MOD",
+ "methodSumAttributes": "Som",
+ "methodSumAttributes-short": "SOM",
+ "methodCountAttributes": "Aantal",
+ "methodCountAttributes-short": "AANTAL",
"addAttribute": "Attribuut toevoegen",
"selectAttributes": "Kies attributen",
"selectAttribute": "Kies attribuut",
@@ -775,12 +807,15 @@
"center": "Middelpunt",
"imageUrl": "Afbeelding URL",
"noImageSelected": "Geen afbeelding geselecteerd",
+ "noData": "No data",
+ "selectMethod": "Selecteer aggregatie methode",
"faint": "Vervagen",
"smooth": "Gladstrijken",
"stepped": "Treden",
"fill": "Vullen",
"extendData": "Verleng laatste datapunt",
- "lineColor": "Lijnkleur"
+ "lineColor": "Lijnkleur",
+ "barColor": "Kleur van de balk"
},
"south": "Zuid",
"east": "Oost",
@@ -874,6 +909,11 @@
"AVG": "Gemiddelde",
"MIN": "Minimum",
"MAX": "Maximum",
+ "DIFFERENCE": "Verschil",
+ "COUNT": "Aantal",
+ "MEDIAN": "Mediaan",
+ "MODE": "Modus",
+ "SUM": "Som",
"alarm": {
"": "Alarm",
"alarm_plural": "Alarmen",
diff --git a/ui/component/or-app/tsconfig.json b/ui/component/or-app/tsconfig.json
index 99e2258fe..b18281966 100644
--- a/ui/component/or-app/tsconfig.json
+++ b/ui/component/or-app/tsconfig.json
@@ -15,6 +15,7 @@
{ "path": "../../component/or-map" },
{ "path": "../../component/or-attribute-input" },
{ "path": "../../component/or-attribute-picker" },
+ { "path": "../../component/or-attribute-barchart" },
{ "path": "../../component/or-asset-tree" },
{ "path": "../../component/or-asset-viewer" },
{ "path": "../../component/or-data-viewer" },
diff --git a/ui/component/or-attribute-barchart/.npmignore b/ui/component/or-attribute-barchart/.npmignore
new file mode 100644
index 000000000..e4d5a449c
--- /dev/null
+++ b/ui/component/or-attribute-barchart/.npmignore
@@ -0,0 +1,8 @@
+build/
+build.gradle
+test/
+src/
+webpack.config.js
+tsconfig.json
+dist/*.map
+*.tsbuildinfo
diff --git a/ui/component/or-attribute-barchart/README.md b/ui/component/or-attribute-barchart/README.md
new file mode 100644
index 000000000..a838fb668
--- /dev/null
+++ b/ui/component/or-attribute-barchart/README.md
@@ -0,0 +1,31 @@
+# @openremote/or-attribute-barchart \<or-attribute-barchart\>
+[![NPM Version][npm-image]][npm-url]
+[![Linux Build][travis-image]][travis-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
+
+Web Component for showing aggregated values at intervals of attribute datapoints.
+
+## Install
+```bash
+npm i @openremote/or-attribute-barchart
+yarn add @openremote/or-attribute-barchart
+```
+
+## Usage
+For a full list of properties, methods and options refer to the TypeDoc generated [documentation]().
+
+
+## Supported Browsers
+The last 2 versions of all modern browsers are supported, including Chrome, Safari, Opera, Firefox, Edge. In addition,
+Internet Explorer 11 is also supported.
+
+
+## License
+[GNU AGPL](https://www.gnu.org/licenses/agpl-3.0.en.html)
+
+[npm-image]: https://img.shields.io/npm/v/live-xxx.svg
+[npm-url]: https://npmjs.org/package/@openremote/or-attribute-barchart
+[travis-image]: https://img.shields.io/travis/live-js/live-xxx/master.svg
+[travis-url]: https://travis-ci.org/live-js/live-xxx
+[coveralls-image]: https://img.shields.io/coveralls/live-js/live-xxx/master.svg
+[coveralls-url]: https://coveralls.io/r/live-js/live-xxx?branch=master
diff --git a/ui/component/or-attribute-barchart/build.gradle b/ui/component/or-attribute-barchart/build.gradle
new file mode 100644
index 000000000..98cdcb8e2
--- /dev/null
+++ b/ui/component/or-attribute-barchart/build.gradle
@@ -0,0 +1,15 @@
+buildDir = "dist"
+
+task clean() {
+ doLast {
+ delete "dist"
+ }
+}
+
+task prepareUi() {
+ dependsOn clean, npmPrepare
+}
+
+task publishUi() {
+ dependsOn clean, npmPublish
+}
\ No newline at end of file
diff --git a/ui/component/or-attribute-barchart/package.json b/ui/component/or-attribute-barchart/package.json
new file mode 100644
index 000000000..87e840908
--- /dev/null
+++ b/ui/component/or-attribute-barchart/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@openremote/or-attribute-barchart",
+ "version": "1.8.0-snapshot",
+ "description": "OpenRemote attribute bar chart",
+ "main": "dist/umd/index.bundle.js",
+ "module": "lib/index.js",
+ "exports": {
+ ".": "./lib/index.js",
+ "./*": "./lib/*.js"
+ },
+ "types": "lib/index.d.ts",
+ "scripts": {
+ "test": "echo \"No tests\" && exit 0",
+ "prepack": "npx rspack"
+ },
+ "author": "OpenRemote",
+ "license": "AGPL-3.0-or-later",
+ "dependencies": {
+ "@openremote/core": "workspace:*",
+ "@openremote/or-icon": "workspace:*",
+ "@openremote/or-mwc-components": "workspace:*",
+ "@openremote/or-translate": "workspace:*",
+ "echarts": "~5.6.0",
+ "lit": "^3.3.1",
+ "moment": "^2.29.4"
+ },
+ "devDependencies": {
+ "@openremote/util": "workspace:*"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/ui/component/or-attribute-barchart/rspack.config.js b/ui/component/or-attribute-barchart/rspack.config.js
new file mode 100644
index 000000000..8d24333fc
--- /dev/null
+++ b/ui/component/or-attribute-barchart/rspack.config.js
@@ -0,0 +1,13 @@
+const util = require("@openremote/util");
+
+bundles = {
+ "index": {
+ excludeOr: true
+ },
+ "index.bundle": {
+ excludeOr: true,
+ },
+ "index.orbundle": undefined
+};
+
+module.exports = util.generateExports(__dirname);
diff --git a/ui/component/or-attribute-barchart/src/index.ts b/ui/component/or-attribute-barchart/src/index.ts
new file mode 100644
index 000000000..7d8d229c8
--- /dev/null
+++ b/ui/component/or-attribute-barchart/src/index.ts
@@ -0,0 +1,1358 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
+import {customElement, property, state, query} from "lit/decorators.js";
+import i18next from "i18next";
+import {
+ Asset, AssetDatapointIntervalQuery,
+ AssetDatapointIntervalQueryFormula,
+ AssetDatapointQueryUnion,
+ AssetModelUtil,
+ Attribute,
+ AttributeRef,
+ DatapointInterval,
+ ValueDatapoint
+} from "@openremote/model";
+import manager, {DefaultColor3, DefaultColor4, Util} from "@openremote/core";
+import * as echarts from "echarts/core";
+import {DatasetComponentOption, DataZoomComponent, DataZoomComponentOption, GridComponent, GridComponentOption, TooltipComponent, TooltipComponentOption} from "echarts/components";
+import {BarChart, BarSeriesOption} from "echarts/charts";
+import {CanvasRenderer} from "echarts/renderers";
+import {UniversalTransition} from "echarts/features";
+import {InputType, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";
+import moment from "moment";
+import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
+import {isAxiosError} from "@openremote/rest";
+import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {cache} from "lit/directives/cache.js";
+import "@openremote/or-mwc-components/or-mwc-menu";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
+import {when} from "lit/directives/when.js";
+import {createRef, Ref, ref} from "lit/directives/ref.js";
+
+echarts.use([GridComponent, TooltipComponent, DataZoomComponent, BarChart, CanvasRenderer, UniversalTransition]);
+
+/**
+ * Bar chart configuration with options for individual attributes.
+ * For example, a list of attributes aligned to the axis on the right side.
+ */
+export interface BarChartAttributeConfig {
+ rightAxisAttributes?: AttributeRef[];
+ faintAttributes?: AttributeRef[];
+ methodMaxAttributes?: AttributeRef[];
+ methodMinAttributes?: AttributeRef[];
+ methodAvgAttributes?: AttributeRef[];
+ methodDifferenceAttributes?: AttributeRef[];
+ methodMedianAttributes?: AttributeRef[];
+ methodModeAttributes?: AttributeRef[];
+ methodSumAttributes?: AttributeRef[];
+ methodCountAttributes?: AttributeRef[];
+}
+
+/**
+ * Interval configuration for a user to select from.
+ * It contains a {@link displayName}, together with a step+interval like "6 hours".
+ */
+export interface IntervalConfig {
+ displayName: string;
+ steps: number;
+ orFormat: DatapointInterval;
+ momentFormat: moment.unitOfTime.DurationConstructor;
+ millis: number;
+}
+
+/**
+ * List of interval options
+ */
+export enum BarChartInterval {
+ AUTO = "auto",
+ NONE = "none",
+ ONE_MINUTE = "1Minute",
+ FIVE_MINUTES = "5Minutes",
+ THIRTY_MINUTES = "30Minutes",
+ ONE_HOUR = "hour",
+ ONE_DAY = "day",
+ ONE_WEEK = "week",
+ ONE_MONTH = "month",
+ ONE_YEAR = "year"
+}
+
+/**
+ * ECharts dataset object with additional optional fields for visualization purposes.
+ * For example, {@link assetId} and {@link attrName} can be specified, so their information can be shown alongside the data itself.
+ */
+export interface BarChartData extends BarSeriesOption {
+ index?: number;
+ assetId?: string;
+ attrName?: string;
+ unit?: string;
+ yAxisIndex?: number;
+ color?: string;
+}
+
+export type ECChartOption = echarts.ComposeOption<
+ | BarSeriesOption
+ | TooltipComponentOption
+ | GridComponentOption
+ | DatasetComponentOption
+ | DataZoomComponentOption
+>;
+
+// language=CSS
+const style = css`
+ :host {
+ --internal-or-chart-text-color: var(--or-chart-text-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));
+ --internal-or-chart-graph-fill-color: var(--or-chart-graph-fill-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
+ --internal-or-chart-graph-point-hover-border-color: var(--or-chart-graph-point-hover-border-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));
+ width: 100%;
+ display: block;
+ }
+
+ .button-icon {
+ align-self: center;
+ padding: 10px;
+ cursor: pointer;
+ }
+
+ .mdc-dialog .mdc-dialog__surface {
+ min-width: 600px;
+ height: calc(100vh - 50%);
+ }
+
+ :host([hidden]) {
+ display: none;
+ }
+
+ #container {
+ display: flex;
+ min-width: 0;
+ flex-direction: row;
+ height: 100%;
+ }
+
+ #period-controls {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ }
+
+ #period-dropdown-controls {
+ flex: 0;
+ display: flex;
+ }
+
+ #period-dropdown-controls > *:first-child {
+ margin-right: -2px;
+ }
+
+ #period-dropdown-controls > *:last-child {
+ margin-left: -2px;
+ }
+
+ .navigate {
+ flex-direction: column;
+ }
+
+ #controls {
+ display: flex;
+ flex-wrap: wrap;
+ width: 100%;
+ flex-direction: column;
+ justify-content: center;
+ }
+
+ #attribute-list {
+ overflow: hidden auto;
+ min-height: 50px;
+ flex: 1 1 0;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .attribute-list-dense {
+ flex-wrap: wrap;
+ }
+
+ .attribute-list-item {
+ cursor: pointer;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ padding: 0;
+ min-height: 50px;
+ }
+
+ .attribute-list-item-dense {
+ min-height: 28px;
+ }
+
+ .attribute-list-item-label {
+ display: flex;
+ flex: 1 1 0;
+ line-height: 16px;
+ flex-direction: column;
+ }
+
+ .attribute-list-item-bullet {
+ width: 12px;
+ height: 12px;
+ border-radius: 7px;
+ margin-right: 10px;
+ }
+
+ .attribute-list-item .button.delete {
+ display: none;
+ }
+
+ .attribute-list-item:hover .button.delete {
+ display: block;
+ }
+
+ #controls > * {
+ margin-top: 5px;
+ margin-bottom: 5px;
+ }
+
+ .dialog-container {
+ display: flex;
+ flex-direction: row;
+ flex: 1 1 0;
+ }
+
+ .dialog-container > * {
+ flex: 1 1 0;
+ }
+
+ .dialog-container > or-mwc-input {
+ background-color: var(--or-app-color2);
+ border-left: 3px solid var(--or-app-color4);
+ }
+
+ #chart-container {
+ flex: 1 1 0;
+ position: relative;
+ overflow: hidden;
+ /*min-height: 400px;
+ max-height: 550px;*/
+ }
+
+ #chart-controls {
+ display: flex;
+ flex-direction: column;
+ margin-top: 10px;
+ margin-right: -4px;
+ }
+
+ #chart {
+ width: 100%;
+ height: 100%;
+ }
+
+ @media screen and (max-width: 1280px) {
+ #chart-container {
+ }
+ }
+
+ @media screen and (max-width: 769px) {
+ .mdc-dialog .mdc-dialog__surface {
+ min-width: auto;
+
+ max-width: calc(100vw - 32px);
+ max-height: calc(100% - 32px);
+ }
+
+ #container {
+ flex-direction: column;
+ }
+
+ #controls {
+ min-width: 100%;
+ padding-left: 0;
+ }
+
+ .interval-controls,
+ #period-controls {
+ flex-direction: row;
+ justify-content: left;
+ align-items: center;
+ gap: 8px;
+ }
+ }
+`;
+
+@customElement("or-attribute-barchart")
+export class OrAttributeBarChart extends LitElement {
+
+ public static readonly DEFAULT_COLORS = ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"];
+
+ /**
+ * Asset data to display in the bar chart. This array needs to be populated.
+ * Used for the chart legend, information about units, and retrieval of data points.
+ */
+ @property({type: Object})
+ public assets: Asset[] = [];
+
+ /**
+ * List of attributes to display in the bar chart. This array needs to be populated.
+ * Used for the chart legend, and the retrieval of data points.
+ * Formatted as a JSON array of;
+ *
+ * ```[<index of {@link assets}>, {@link Attribute}]```
+ */
+ @property({type: Object})
+ public assetAttributes: [number, Attribute<any>][] = [];
+
+ /**
+ * Realm name to associate all the chart data with.
+ */
+ @property({type: String})
+ public realm: string | undefined = manager?.displayRealm;
+
+ /**
+ * The list of HEX colors representing the line color for each {@link AttributeRef}.
+ * Acts as an override, and will fall back to the {@link colors} attribute if not specified.
+ * The {@link AttributeRef} object with Asset ID and Attribute name need to be present in the Chart to work.
+ * The HEX color should be put in without '#' prefix. For example, you'd use '4d9d2a' instead of '#4d9d2a'.
+ */
+ @property({type: Array})
+ public readonly attributeColors: [AttributeRef, string][] = [];
+
+ /**
+ * The attribute configuration object with, for example, a list of right-axis attributes.
+ * See {@link BarChartAttributeConfig} for full documentation on the options.
+ */
+ @property({type: Object})
+ public readonly attributeConfig?: BarChartAttributeConfig;
+
+ /**
+ * List of colors to display attributes values with inside the bar chart.
+ * The array corresponds with {@link assetAttributes}, so the 1st color will be used for the 1st attribute.
+ */
+ @property({type: Array})
+ public readonly colors: string[] = OrAttributeBarChart.DEFAULT_COLORS;
+
+ /**
+ * The query object to request attribute data / data points with.
+ * Normally, it's of type {@link AssetDatapointIntervalQuery}, including a start- and end time.
+ */
+ @property({type: Object})
+ public readonly datapointQuery!: AssetDatapointQueryUnion;
+
+ /**
+ * Selected timeframe using a [start date, end date] array format.
+ */
+ @property({type: Array})
+ public timeframe?: [Date, Date];
+
+ /**
+ * Custom ECharts options object to configure the chart appearance.
+ * See their documentation for more info: https://echarts.apache.org/en/option.html
+ */
+ @property({type: Object})
+ public chartOptions?: ECChartOption;
+
+ /**
+ * Shows a right-side legend with the list of visible attributes.
+ */
+ @property({type: Boolean})
+ public showLegend = false;
+
+ /**
+ * Shows the right-side legend (toggled with {@link showLegend}) in a compact / dense format.
+ */
+ @property({type: Boolean})
+ public denseLegend = false;
+
+ /**
+ * Displays the bar chart in a vertically "stacked" configuration.
+ * It will display a cumulative effect of all data series on top of each other.
+ */
+ @property({type: Boolean})
+ public stacked = false;
+
+ /**
+ * Enables time control for the user, allowing them to customize the {@link timeframe} shown.
+ * Leaving this disabled/unset will show them in a "read-only" state.
+ */
+ @property({type: Boolean})
+ public timestampControls = true;
+
+ /**
+ * Number of decimals to display for attributes.
+ */
+ @property({type: Number})
+ public decimals = 2;
+
+ /**
+ * A JSON array list of strings that represent the prefix options in the UI, such as "current" or "last".
+ * In combination with {@link timeWindowOptions}, it provides a timeframe like "current 1 hour" to display data of.
+ */
+ @property({type: Array})
+ public timePrefixOptions: string[] = OrAttributeBarChart.getDefaultTimePrefixOptions();
+
+ /**
+ * The selected option from {@link timePrefixOptions}, such as "current" or "last".
+ * In combination with {@link timeWindowOptions}, it provides a timeframe like "current 1 hour" to display data of.
+ */
+ @property({type: String})
+ public timePrefixKey?: string;
+
+ /**
+ * A JSON object containing a list of time window options, like "1 day", "6 hours" or "52 weeks".
+ * In combination with {@link timePrefixOptions}, it provides a timeframe like "last 6 hours" to display data of.
+ * The input should contain a JavaScript {@link Map}, containing the following:
+ * - A {@link string} with a unique key like "6hours",
+ * - A combination of any {@link moment.unitOfTime.DurationConstructor} and {@link number}, like ["hours", 6]
+ *
+ * Example input: `{"6hours": ["hours", 6], "4weeks": ["weeks", 4]}`
+ */
+ @property({type: Object})
+ public timeWindowOptions: Map<string, [moment.unitOfTime.DurationConstructor, number]> = OrAttributeBarChart.getDefaultTimeWindowOptions();
+
+ /**
+ * The key value of the selected option from {@link timeWindowOptions}, such as "1day", "6hours" or "52weeks".
+ * In combination with {@link timePrefixOptions}, it provides a timeframe like "last 6 hours" to display data of.
+ */
+ @property({type: String})
+ public timeWindowKey?: string;
+
+ /**
+ * A JSON object containing a list of interval options, like "30minutes", "hour" or "day".
+ * It determines the interval to display data in sections. For example, split the data every 5 minutes of the past hour.
+ * In combination with the active formula in {@link datapointQuery}, such as AVG and MIN/MAX, it will show a '5 minute' average of the past hour.
+ * The input should contain a JavaScript {@link Map}, containing the following:
+ * - A {@link BarChartInterval} string with a unique key like "hour" or "day",
+ * - A {@link IntervalConfig} object with details on the interval, such as the display name and the unit of time.
+ *
+ * Example input:
+ * ```
+ * {"30minutes": {
+ * displayName: "30Minutes", // translated automatically
+ * steps: 30,
+ * orFormat: "minute",
+ * momentFormat: "minutes", // using moment.js format
+ * millis: 1800000
+ * }}
+ * ```
+ */
+ @property({type: Object})
+ public intervalOptions: Map<BarChartInterval, IntervalConfig> = OrAttributeBarChart.getDefaultIntervalOptions();
+
+ /**
+ * The key value of the selected option from {@link intervalOptions}, such as "30minute", "hour" or "week".
+ * In combination with the active formula in {@link datapointQuery}, such as AVG and MIN/MAX, it will show a '5 minute' average of the past hour.
+ */
+ @property({type: String})
+ public interval?: BarChartInterval;
+
+ /**
+ * Whether a custom {@link timeframe} has been configured by the user or not.
+ * If it's a default value provided by us, it will be `false`.
+ * If a user customized the timeframe, it will be `true`.
+ * @protected
+ */
+ @state()
+ protected _isCustomWindow = false;
+
+ /**
+ * Loading state when fetching data from a remote source.
+ * Show a "loading indicator" in the UI when set to `true`.
+ * @protected
+ */
+ @state()
+ protected _loading = false;
+
+ /**
+ * Cached array of {@link BarChartData} objects to display in the chart.
+ * It contains custom data, but data from the ECharts library as well (see {@link BarSeriesOption} for details)
+ * @protected
+ */
+ @state()
+ protected _data?: BarChartData[];
+
+ @query("#chart")
+ protected _chartElem!: HTMLDivElement;
+
+ protected _chart?: echarts.ECharts;
+ protected _style!: CSSStyleDeclaration;
+ protected _startOfPeriod?: number; // Start timestamp of the visible period
+ protected _endOfPeriod?: number; // End timestamp of the visible period
+ protected _latestError?: string;
+ protected _dataAbortController?: AbortController;
+ protected _containerResizeObserver?: ResizeObserver;
+
+ protected _intervalConfig?: IntervalConfig;
+
+ static get styles() {
+ return [style];
+ }
+
+ connectedCallback() {
+ super.connectedCallback();
+ this._style = window.getComputedStyle(this);
+ }
+
+ disconnectedCallback(): void {
+ super.disconnectedCallback();
+ this._cleanup();
+ }
+
+ willUpdate(changedProps: PropertyValues) {
+ if (changedProps.has("realm") && changedProps.get("realm")) {
+ this.assets = [];
+ this.assetAttributes = [];
+ }
+ if (changedProps.has("timePrefixOptions") && this.timePrefixOptions) {
+ this.timePrefixKey ??= this.timePrefixOptions[0];
+ }
+ if (changedProps.has("timeWindowOptions") && this.timeWindowOptions) {
+ this.timeWindowKey ??= Array.from(this.timeWindowOptions.keys())[0];
+ }
+ if (changedProps.has("intervalOptions") && this.intervalOptions) {
+ this.interval ??= Array.from(this.intervalOptions.keys())[0];
+ }
+ return super.willUpdate(changedProps);
+ }
+
+ updated(changedProps: PropertyValues) {
+ super.updated(changedProps);
+
+ // When certain state is changed, rerender the bar chart
+ const reloadData = changedProps.has("attributeColors") || changedProps.has("datapointQuery") || changedProps.has("timeframe") || changedProps.has("interval") ||
+ changedProps.has("timePrefixKey") || changedProps.has("timeWindowKey") || changedProps.has("attributeConfig") || changedProps.has("assetAttributes") || changedProps.has("realm");
+ if (reloadData) {
+ this._data = undefined;
+ if (this._chart) {
+ this._cleanup(); // destroy chart if one exists
+ }
+ // Gather information to use for loading
+ const dates: [Date, Date] = this._getTimeSelectionDates(this.timePrefixKey!, this.timeWindowKey!);
+ this._startOfPeriod = this.timeframe ? this.timeframe[0].getTime() : dates[0].getTime();
+ this._endOfPeriod = this.timeframe ? this.timeframe[1].getTime() : dates[1].getTime();
+ this._intervalConfig = this._getInterval(this._startOfPeriod, this._endOfPeriod, this.interval!);
+ this._loadData();
+ }
+ // Abort when no data is present
+ if (!this._data) {
+ return;
+ }
+ // Generate chart element if not done yet
+ if (!this._chart) {
+ console.debug("Initializing chart...");
+ this.chartOptions = {...this._getDefaultChartOptions(), ...this.chartOptions};
+ this._chart = echarts.init(this._chartElem);
+ this._chart.setOption(this.chartOptions);
+ this._toggleChartEventListeners(true);
+ }
+ // If data has changed (and there is data present), update the chart element.
+ if (changedProps.has("_data") && this._data?.[0]?.data?.length) {
+ this._updateChartData();
+ }
+ }
+
+ render() {
+ const disabled = this._loading || !!this._latestError;
+ return html`
+ <div id="container">
+ ${when(this._loading, () => html`
+ <div style="position: absolute; height: 100%; width: 100%;">
+ <or-loading-indicator ?overlay="false"></or-loading-indicator>
+ </div>
+ `)}
+ ${when(this._latestError, () => html`
+ <div style="position: absolute; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;">
+ <or-translate .value="${this._latestError ?? "errorOccurred"}"></or-translate>
+ </div>
+ `)}
+ ${when(Object.keys(this.attributeConfig || {}).filter(key => key.startsWith("method")).every(key => (this.attributeConfig as any)[key].length === 0), () => html`
+ <div style="position: inherit; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; z-index: 1; pointer-events: none;">
+ <or-translate .value="${"dashboard.selectMethod"}"></or-translate>
+ </div>
+ `)}
+ ${when(this._data?.every(entry => !entry.data?.length), () => html`
+ <div style="position: inherit; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; z-index: 1; pointer-events: none;">
+ <or-translate .value="${"dashboard.noData"}"></or-translate>
+ </div>
+ `)}
+ <div id="chart-container">
+ <div id="chart" style="visibility: ${disabled ? "hidden" : "visible"}"></div>
+ </div>
+
+ ${when(this.timestampControls || this.showLegend, () => html`
+ <div id="chart-controls">
+ <div id="controls">
+ ${when(this.timestampControls && this.timePrefixKey && this.timePrefixOptions && this.timeWindowKey && this.timeWindowOptions,
+ () => this._getTimeControlsTemplate(disabled || !!this.timeframe),
+ () => html`
+ <div style="display: flex; justify-content: center;">
+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t(this.timePrefixKey?.toLowerCase() ?? '???')}" disabled style="margin-right: -2px;"></or-mwc-input>
+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t(this.timeWindowKey?.toLowerCase() ?? '???')}" disabled style="margin-left: -2px;"></or-mwc-input>
+ </div>
+ `
+ )}
+ ${when(this.timeframe, () => this._getTimeframeStatusTemplate(this.timeframe))}
+ </div>
+ ${cache(when(this.showLegend, () => this._getLegendTemplate()))}
+ </div>
+ `)}
+ </div>
+ `;
+ }
+
+ protected _getTimeControlsTemplate(disabled = true): TemplateResult {
+ return html`
+ <div id="period-controls">
+ <div id="period-dropdown-controls">
+ <!-- Time prefix selection -->
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" label="${this.timeframe ? "dashboard.customTimeSpan" : this.timePrefixKey}" ?disabled="${disabled}"></or-mwc-input>`,
+ disabled ? null as any : this.timePrefixOptions.map(option => ({value: option} as ListItem)),
+ this.timePrefixKey,
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timePrefixKey = value.toString();
+ },
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ <!-- Time window selection -->
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" label="${this._isCustomWindow ? "timeframe" : i18next.t(this.timeWindowKey?.toLowerCase() ?? "")}" ?disabled="${disabled}"></or-mwc-input>`,
+ disabled ? null as any : Array.from(this.timeWindowOptions.keys()).map(key => ({value: key, text: key.toLowerCase(), translate: true} as ListItem)),
+ this.timeWindowKey,
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timeWindowKey = value.toString();
+ },
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ </div>
+ <!-- Interval selection -->
+ ${getContentWithMenuTemplate(html`<or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t(`intervalBy${this._intervalConfig?.displayName?.toLowerCase()}`)}"></or-mwc-input>`,
+ Array.from(this.intervalOptions.keys()).map(key => ({value: key, text: `intervalBy${key.toLowerCase()}`, translate: true} as ListItem)),
+ this.interval,
+ value => this.interval = value as BarChartInterval,
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ </div>
+ <div class="navigate" style="text-align: right">
+ <!-- Scroll left button -->
+ <or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-left"
+ @click="${() => this._shiftTimeframe(this.timeframe ? this.timeframe[0] : new Date(this._startOfPeriod!), this.timeframe ? this.timeframe[1] : new Date(this._endOfPeriod!), this.timeWindowKey!, "previous")}"></or-icon>
+ <!-- Scroll right button -->
+ <or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-right"
+ @click="${() => this._shiftTimeframe(this.timeframe ? this.timeframe[0] : new Date(this._startOfPeriod!), this.timeframe ? this.timeframe[1] : new Date(this._endOfPeriod!), this.timeWindowKey!, "next")}"></or-icon>
+ <!-- Button that opens custom time selection or restores to widget setting-->
+ <or-icon class="button button-icon" ?disabled="${disabled}" icon="${this.timeframe ? "restore" : "calendar-clock"}"
+ @click="${() => this.timeframe ? (this._isCustomWindow = false, this.timeframe = undefined) : this._openTimeDialog(this._startOfPeriod, this._endOfPeriod)}"></or-icon>
+ </div>
+ `;
+ }
+
+ protected _getTimeframeStatusTemplate(timeframe = this.timeframe): TemplateResult {
+ return html`
+ <div style="margin-left: 18px; font-size: 12px; display: flex; justify-content: flex-end;">
+ <table style="text-align: right;">
+ <thead>
+ <tr>
+ <th style="font-weight: normal; text-align: right;"><or-translate value="from"></or-translate></th>
+ <th style="font-weight: normal; text-align: right;">${moment(timeframe![0]).format("lll")}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td style="text-align: right;"><or-translate value="to"></or-translate></td>
+ <td style="text-align: right;">${moment(timeframe![1]).format("lll")}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ `;
+ }
+
+ protected _getLegendTemplate(): TemplateResult {
+ return html`
+ <div id="attribute-list" class="${this.denseLegend ? "attribute-list-dense" : undefined}">
+ ${when(this.assetAttributes == null || this.assetAttributes.length === 0, () => html`
+ <div>
+ <or-translate value="noAttributesConnected"></or-translate>
+ </div>
+ `)}
+ ${this.assetAttributes && this.assetAttributes.map(([assetIndex, attr], index) => {
+ const asset: Asset | undefined = this.assets[assetIndex];
+ if (!asset) {
+ return html`Error`;
+ }
+ const colourIndex = index % this.colors.length;
+ const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attr.name)?.[1];
+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attr.name, attr);
+ const label = Util.getAttributeLabel(attr, descriptors[0], asset.type, true);
+ const axisNote = (this.attributeConfig?.rightAxisAttributes?.find(ar => asset.id === ar.id && attr.name === ar.name)) ? i18next.t("right") : undefined;
+ const bgColor = (color ?? this.colors[colourIndex]) || "";
+ // Find which aggregation methods are active
+
+ const methodList: string[] = Object.entries(this.attributeConfig || {})
+ .filter(([key]) => key.includes("method"))
+ .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
+ .reduce<string[]>((list, [key, attributeRefs]) => {
+ const isActive = attributeRefs.some((attrRef: AttributeRef) => attrRef.id === asset.id && attrRef.name === attr.name);
+ if (isActive) {
+ list.push(i18next.t(`${key}-short`));
+ }
+ return list;
+ }, []);
+
+ return html`
+ <div class="attribute-list-item ${this.denseLegend ? "attribute-list-item-dense" : undefined}"
+ @mouseenter="${() => this._addDatasetHighlight({id: this.assets[assetIndex].id, name: attr.name})}"
+ @mouseleave="${()=> this._removeDatasetHighlights()}">
+ <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex].type), undefined, undefined, bgColor.split("#")[1])}</span>
+ <div class="attribute-list-item-label ${this.denseLegend ? "attribute-list-item-label-dense" : undefined}">
+ <div style="display: flex; justify-content: space-between;">
+ <span style="font-size:12px; ${this.denseLegend ? "margin-right: 8px" : undefined}">${this.assets[assetIndex].name}</span>
+ ${when(axisNote, () => html`<span style="font-size:12px; color:grey">(${axisNote})</span>`)}
+ </div>
+ <span style="font-size:12px; color:grey; white-space:pre-line;">${label} <br> (${methodList.join(", ")})</span>
+ </div>
+ </div>
+ `;
+ })}
+ </div>
+ `;
+ }
+
+ protected _openTimeDialog(startTimestamp?: number, endTimestamp?: number) {
+ const startRef: Ref<OrMwcInput> = createRef();
+ const endRef: Ref<OrMwcInput> = createRef();
+ showDialog(new OrMwcDialog()
+ .setHeading(i18next.t("timeframe"))
+ .setContent(() => html`
+ <div>
+ <or-mwc-input ${ref(startRef)} type="${InputType.DATETIME}" required label="${i18next.t("start")}" .value="${startTimestamp}"></or-mwc-input>
+ <or-mwc-input ${ref(endRef)} type="${InputType.DATETIME}" required label="${i18next.t("ending")}" .value="${endTimestamp}"></or-mwc-input>
+ </div>
+ `)
+ .setActions([{
+ actionName: "cancel",
+ content: "cancel"
+ }, {
+ actionName: "ok",
+ content: "ok",
+ action: () => {
+ if(startRef.value?.value && endRef.value?.value && startRef.value.value < endRef.value.value) {
+ this._isCustomWindow = true;
+ this.timeframe = [new Date(startRef.value.value), new Date(endRef.value.value)];
+ } else {
+ showSnackbar(undefined, i18next.t("errorOccurred"));
+ }
+ }
+ }])
+ );
+ }
+
+ /**
+ * Removes all active Chart bars color highlights, by reducing/increasing opacity.
+ * @protected
+ */
+ protected _removeDatasetHighlights(chart = this._chart) {
+ if(chart){
+ const options = chart.getOption();
+ (options.series as BarChartData[] | undefined)?.forEach(series => {
+ series.itemStyle ??= {};
+ if (series.itemStyle.opacity === 0.2 || series.itemStyle.opacity === 0.99) {
+ series.itemStyle.opacity = 0.31;
+ } else {
+ series.itemStyle.opacity = 1;
+ }
+ });
+ chart.setOption(options);
+ }
+ }
+
+ /**
+ * Adds a Chart bar color highlight, by reducing/increasing opacity.
+ * So the given bar (represented by {@link assetId} and {@link attrName} will be emphasized, while others are less visible.
+ * @param attrRef - Asset ID and attribute name to be highlighted
+ * @param chart - ECharts instance to add the highlight to.
+ */
+ protected _addDatasetHighlight(attrRef: AttributeRef, chart = this._chart) {
+ if (chart) {
+ const options = chart.getOption();
+ (options.series as BarChartData[] | undefined)?.forEach(series => {
+ series.itemStyle ??= {};
+ if (series.assetId !== attrRef.id || series.attrName !== attrRef.name) {
+ if (series.itemStyle.opacity === 0.31) { // 0.31 is faint setting, 1 is normal
+ series.itemStyle.opacity = 0.2;
+ } else {
+ series.itemStyle.opacity = 0.3;
+ }
+ } else if (series.itemStyle.opacity === 0.31) { // extra highlight if selected is faint
+ series.itemStyle.opacity = 0.99;
+ }
+ });
+ chart.setOption(options);
+ }
+ }
+
+ // Not the best implementation, but it changes the legend & controls to wrap under the chart.
+ // Also sorts the attribute lists horizontally when it is below the chart
+ protected _applyChartResponsiveness(): void {
+ if(this.shadowRoot) {
+ const container = this.shadowRoot.getElementById("container");
+ if(container) {
+ const bottomLegend: boolean = (container.clientWidth < 600);
+ container.style.flexDirection = bottomLegend ? "column" : "row";
+ const controls = this.shadowRoot.getElementById("controls");
+ if(controls) {
+ controls.style.flexDirection = bottomLegend ? "row" : "column";
+ }
+ const periodControls = this.shadowRoot.getElementById("period-controls");
+ if(periodControls) {
+ periodControls.style.flexDirection = bottomLegend ? "row" : "column";
+ }
+ const attributeList = this.shadowRoot.getElementById("attribute-list");
+ if(attributeList) {
+ attributeList.style.gap = bottomLegend ? "4px 12px" : "";
+ attributeList.style.maxHeight = bottomLegend ? "90px" : "";
+ attributeList.style.flexFlow = bottomLegend ? "row wrap" : "column nowrap";
+ attributeList.style.padding = bottomLegend ? "0" : "5px 0";
+ }
+ this.shadowRoot.querySelectorAll(".attribute-list-item").forEach((item: Element) => {
+ (item as HTMLElement).style.minHeight = bottomLegend ? "0px" : "44px";
+ (item as HTMLElement).style.paddingLeft = bottomLegend ? "" : "16px";
+ (item.children[1] as HTMLElement).style.flexDirection = bottomLegend ? "row" : "column";
+ (item.children[1] as HTMLElement).style.gap = bottomLegend ? "4px" : "";
+ });
+ this._chart?.resize();
+ }
+ }
+ // Update ticks / labels
+ const xAxisTicks = Math.max(1, (this._endOfPeriod! - this._startOfPeriod!) / this._intervalConfig!.millis - 1);
+ const recommendedTicks = this._chartElem?.clientWidth ? (this._chartElem.clientWidth / 50) : Number.MAX_SAFE_INTEGER;
+ const maxTicks = Math.floor(recommendedTicks * 1.5);
+ const splitNumber = Math.max(1, Math.min(xAxisTicks, maxTicks));
+ this._chart?.setOption({
+ xAxis: {
+ show: splitNumber > 1,
+ splitNumber: splitNumber,
+ minInterval: this._intervalConfig!.millis,
+ axisLabel: {
+ rotate: splitNumber > recommendedTicks ? 45 : 0,
+ }
+ }
+ });
+ }
+
+ protected _cleanup() {
+ if (this._chart) {
+ console.debug("Destroying bar chart...");
+ this._toggleChartEventListeners(false);
+ this._chart.dispose();
+ this._chart = undefined;
+ this.requestUpdate();
+ }
+ }
+
+ protected _getTimeSelectionDates(timePrefixSelected: string, timeWindowSelected: string): [Date, Date] {
+ let startDate: moment.Moment = moment();
+ let endDate: moment.Moment = moment();
+
+ const timeWindow: [moment.unitOfTime.DurationConstructor, number] | undefined = this.timeWindowOptions?.get(timeWindowSelected);
+
+ if (!timeWindow) {
+ throw new Error(`Unsupported time window selected: ${timeWindowSelected}`);
+ }
+
+ const [unit , value]: [moment.unitOfTime.DurationConstructor, number] = timeWindow;
+
+ switch (timePrefixSelected) {
+ case "this": {
+ if (value === 1) { // For singulars like this hour
+ startDate = moment().startOf(unit);
+ endDate = moment().endOf(unit);
+ } else { // For multiples like this 5 min, put now in the middle
+ startDate = moment().subtract(value * 0.5, unit);
+ endDate = moment().add(value * 0.5, unit);
+ }
+ break;
+ }
+ case "last": {
+ startDate = moment().subtract(value, unit).startOf(unit);
+ if (value === 1) { // For singulars like last hour
+ endDate = moment().startOf(unit);
+ } else { //For multiples like last 5 min
+ endDate = moment();
+ }
+ break;
+ }
+ default: {
+ console.error("Could not get time selection dates. The time prefix was not set correctly.");
+ break;
+ }
+ }
+ return [startDate.toDate(), endDate.toDate()];
+ }
+
+ protected _shiftTimeframe(currentStart: Date, currentEnd: Date, timeWindowSelected: string, direction: string) {
+ const timeWindow = this.timeWindowOptions.get(timeWindowSelected);
+
+ if (!timeWindow) {
+ throw new Error(`Unsupported time window selected: ${timeWindowSelected}`);
+ }
+
+ const [unit, value] = timeWindow;
+ const newStart = moment(currentStart);
+ direction === "previous" ? newStart.subtract(value, unit) : newStart.add(value, unit);
+ const newEnd = moment(currentEnd);
+ direction === "previous" ? newEnd.subtract(value, unit) : newEnd.add(value, unit);
+ this.timeframe = [newStart.toDate(), newEnd.toDate()];
+ }
+
+ protected _getInterval(start: number, end: number, selectedInterval: BarChartInterval, exact = false): IntervalConfig {
+ const hoursDiff = (end - start) / 1000 / 60 / 60;
+ const diffInHours = exact ? hoursDiff : Math.round(hoursDiff);
+ if (selectedInterval === BarChartInterval.AUTO) {
+ // Returns number of steps, interval size and moment.js time format
+ if(diffInHours <= 1) {
+ return { displayName: "5Minutes-auto", steps: 5, orFormat: DatapointInterval.MINUTE, momentFormat: "minutes", millis: 300000 };
+ } else if(diffInHours <= 6) {
+ return {displayName: "30Minutes-auto", steps: 30, orFormat: DatapointInterval.MINUTE, momentFormat: "minutes", millis: 1800000};
+ } else if(diffInHours <= 24) { // hour if up to one day
+ return {displayName: "hour-auto", steps: 1, orFormat: DatapointInterval.HOUR, momentFormat: "hours", millis: 3600000};
+ } else if(diffInHours <= 744) { // one day if up to one month
+ return {displayName: "day-auto", steps: 1, orFormat: DatapointInterval.DAY, momentFormat: "days", millis: 86400000};
+ } else if(diffInHours <= 8760) { // one week if up to 1 year
+ return {displayName: "week-auto", steps: 1, orFormat: DatapointInterval.WEEK, momentFormat: "weeks", millis: 604800000};
+ } else { // one month if more than a year
+ return {displayName: "month-auto", steps: 1, orFormat: DatapointInterval.MONTH, momentFormat: "months", millis: 2592000000};
+ }
+ } else if (selectedInterval === BarChartInterval.NONE) {
+ // Set interval to total time span
+ const millis = this._endOfPeriod! - this._startOfPeriod!;
+ const steps = Math.ceil(millis / 60000);
+ return {displayName: "none", steps: steps, orFormat: DatapointInterval.MINUTE, momentFormat: "minutes", millis: millis};
+ }
+ // Otherwise, check if select interval is a valid combination with set time window
+ const intervalProp: IntervalConfig = this.intervalOptions.get(selectedInterval)!;
+ const selectedIntervalHours = moment.duration(intervalProp.steps, intervalProp.momentFormat).asHours();
+
+ if (selectedIntervalHours <= diffInHours) {
+ return intervalProp; // Already valid so quit
+ }
+
+ // If no selected interval is larger than timeframe, switch to the first next valid timeframe.
+ console.warn("Selected interval is larger than the timeframe! Changing to a valid timeframe...");
+ const intervalOptions = Array.from(this.intervalOptions.entries());
+
+ for (let i = intervalOptions.length - 1; i >= 0; i--) {
+ const [_, value] = intervalOptions[i];
+ const intervalHours = moment.duration(value.steps, value.momentFormat).asHours();
+
+ if (intervalHours <= diffInHours) {
+ return value; // Found a valid option
+ }
+ }
+ // If no valid option is found, return the smallest available option
+ return intervalOptions[0][1];
+ }
+
+ protected async _loadData() {
+ if (this._data || !this.assetAttributes || !this.assets || (this.assets.length === 0) || (this.assetAttributes.length === 0) || !this.datapointQuery) {
+ return;
+ }
+
+ if (this._loading) {
+ if (this._dataAbortController) {
+ this._dataAbortController.abort("Data request overridden");
+ delete this._dataAbortController;
+ } else {
+ return;
+ }
+ }
+
+ this._loading = true;
+ this._latestError = undefined;
+ const data: BarChartData[] = [];
+ let promises;
+
+ try {
+ this._dataAbortController = new AbortController();
+ promises = this.assetAttributes.map(async ([assetIndex, attribute], index) => {
+
+ const asset = this.assets[assetIndex];
+ const shownOnRightAxis = !!this.attributeConfig?.rightAxisAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attribute.name)?.[1];
+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute.name, attribute);
+ const faint = !!this.attributeConfig?.faintAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);
+ const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);
+ const unit = Util.resolveUnits(Util.getAttributeUnits(attribute, descriptors[0], asset.type));
+ const colourIndex = index % this.colors.length;
+ const options = {signal: this._dataAbortController?.signal};
+
+ // Map calculation methods to their corresponding attribute arrays and formulas
+ const methodMapping: { [key: string]: { active: boolean; formula: AssetDatapointIntervalQueryFormula } } = {
+ AVG: {active: !!this.attributeConfig?.methodAvgAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.AVG},
+ COUNT: {active: !!this.attributeConfig?.methodCountAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.COUNT},
+ DIFFERENCE: {active: !!this.attributeConfig?.methodDifferenceAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.DIFFERENCE},
+ MAX: {active: !!this.attributeConfig?.methodMaxAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.MAX},
+ MEDIAN: {active: !!this.attributeConfig?.methodMedianAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.MEDIAN},
+ MIN: {active: !!this.attributeConfig?.methodMinAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.MIN},
+ MODE: {active: !!this.attributeConfig?.methodModeAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.MODE},
+ SUM: {active: !!this.attributeConfig?.methodSumAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name), formula: AssetDatapointIntervalQueryFormula.SUM}
+ };
+ // Iterate over the mapping, make a dataset for every active method
+ for (const [key, value] of (Object.entries(methodMapping)).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))) {
+ if (value.active) {
+ //Initiate query Attribute Data
+ const dataset = await this._loadAttributeData(asset, attribute, color ?? this.colors[colourIndex], this._startOfPeriod!, this._endOfPeriod!, value.formula, faint, `${asset.name} | ${label} \n${i18next.t(value.formula)}`, options, unit);
+ dataset.index = (Object.keys(methodMapping).indexOf(key) * 1000) + (index + 1);
+ dataset.assetId = asset.id;
+ dataset.attrName = attribute.name;
+ dataset.unit = unit;
+ dataset.yAxisIndex = shownOnRightAxis ? 1 : 0;
+ dataset.color = color ?? this.colors[colourIndex];
+ data.push(dataset);
+
+ }
+ }
+ });
+ // Await HTTP requests
+ if (promises) {
+ await Promise.all(promises);
+ }
+ // Sort data in correct order, for inserting it into the chart.
+ const sortedData = data.sort((a, b) => b.index! - a.index!).reverse();
+
+ // If stacked, remove all labels for every fill except the top
+ if (this.stacked) {
+ const formulas = new Set(sortedData.map(d => d.stack));
+ if(formulas.size > 1) {
+ formulas.forEach(formula => {
+ const lastEntry = [...sortedData].reverse().find(d => d.stack === formula);
+ if(lastEntry) lastEntry.label!.show = true;
+ });
+ }
+ }
+
+ // Sort data in correct order, and insert data in the chart
+ this._data = sortedData;
+ this._loading = false;
+
+ } catch (ex) {
+ console.error(ex);
+ if ((ex as Error)?.message === "canceled") {
+ return; // If request has been canceled (using AbortController); return, and prevent _loading is set to false.
+ }
+ this._loading = false;
+
+ if (isAxiosError(ex)) {
+ if (ex.message.includes("timeout")) {
+ this._latestError = "noAttributeDataTimeout";
+ return;
+ } else if (ex.response?.status === 413) {
+ this._latestError = "datapointRequestTooLarge";
+ return;
+ }
+ }
+ this._latestError = "errorOccurred";
+ }
+ }
+
+ protected async _loadAttributeData(asset: Asset, attribute: Attribute<any>, color: string, from: number, to: number, formula: AssetDatapointIntervalQueryFormula, faint = false, label?: string, options?: any, _unit?: any): Promise<BarChartData> {
+ const dataset = this._getDefaultDatasetOptions(label ?? "", formula, color, faint);
+
+ if (asset.id && attribute.name && this.datapointQuery) {
+ const datapointQuery = structuredClone(this.datapointQuery) as AssetDatapointIntervalQuery; // recreating object, since the changes shouldn't apply to parent components; only or-attribute-barchart itself.
+
+ datapointQuery.fromTimestamp = from;
+ datapointQuery.toTimestamp = to - 1; // subtract 1 millisecond
+ datapointQuery.formula = formula;
+ datapointQuery.gapFill = true;
+ datapointQuery.interval = `${this._intervalConfig?.steps ?? "???"} ${this._intervalConfig?.orFormat ?? "???"}`; // for example: "5 minute"
+
+ console.debug(`Requesting datapoints for '${attribute.name}' of ${asset.id}, between ${moment(from).format('lll')} and ${moment(to - 1).format('lll')}...`);
+ const response = await manager.rest.api.AssetDatapointResource.getDatapoints(asset.id, attribute.name, datapointQuery, options);
+
+ let data: ValueDatapoint<any>[] = [];
+
+ if (response.status === 200) {
+ data = response.data.map(point => ({x: point.x, y: point.y} as ValueDatapoint<any>));
+
+ // map to dataset and position to the middle of interval instead of start time
+ dataset.data = data.map(point => [(point.x ?? 0) + 0.5 * this._intervalConfig!.millis, point.y?.toFixed(this.decimals)]);
+ }
+ }
+ return dataset;
+ }
+
+ protected _updateChartData() {
+ if(!this._chart) {
+ console.error("Could not update bar chart data; the bar chart is not initialized yet.");
+ return;
+ }
+ // When data retrieved from HTTP API uses different start-end times, update them.
+ // For example, if 'endOfPeriod' is 18:03, but the interval is 15 min, the latest API datapoint will be from 18:15.
+ const firstEntry = this._data?.[0]?.data as [number, number][] | undefined;
+ if(firstEntry) {
+ const firstTimestamp = firstEntry[0][0];
+ if(firstTimestamp !== this._startOfPeriod) {
+ this._startOfPeriod = firstTimestamp;
+ }
+ const endTimestamp = [...firstEntry].reverse()[0][0];
+ if(endTimestamp !== this._endOfPeriod) {
+ this._endOfPeriod = endTimestamp;
+ }
+ }
+
+ // Update ticks / labels
+ const xAxisTicks = Math.max(1, (this._endOfPeriod! - this._startOfPeriod!) / this._intervalConfig!.millis - 1);
+ const recommendedTicks = this._chartElem?.clientWidth ? (this._chartElem.clientWidth / 50) : Number.MAX_SAFE_INTEGER;
+ const maxTicks = Math.floor(recommendedTicks * 1.5);
+ const splitNumber = Math.max(1, Math.min(xAxisTicks, maxTicks));
+
+ // Update chart
+ this._chart.setOption({
+ xAxis: {
+ show: splitNumber > 1,
+ splitNumber: splitNumber,
+ minInterval: this._intervalConfig!.millis,
+ min: this._startOfPeriod,
+ max: this._endOfPeriod,
+ axisLabel: {
+ interval: this._intervalConfig?.millis,
+ rotate: splitNumber > recommendedTicks ? 45 : 0,
+ }
+ },
+ dataZoom: {
+ minValueSpan: (this._intervalConfig?.millis ?? 0) * 4
+ },
+ series: [
+ ...(this._data ?? []).map(series => ({
+ ...series
+ }))
+ ]
+ } as ECChartOption);
+ }
+
+
+ protected _toggleChartEventListeners(connect: boolean){
+ if (connect) {
+ this._containerResizeObserver = new ResizeObserver(() => this._applyChartResponsiveness());
+ this._containerResizeObserver.observe(this.shadowRoot!.getElementById("container") as HTMLElement);
+ } else {
+ this._containerResizeObserver?.disconnect();
+ this._containerResizeObserver = undefined;
+ }
+ }
+
+ protected _getDefaultChartOptions(): ECChartOption {
+ const xAxisTicks = Math.max(1, (this._endOfPeriod! - this._startOfPeriod!) / this._intervalConfig!.millis - 1);
+ const recommendedTicks = this._chartElem?.clientWidth ? (this._chartElem.clientWidth / 50) : Number.MAX_SAFE_INTEGER;
+ const maxTicks = Math.floor(recommendedTicks * 1.5);
+ const splitNumber = Math.max(1, Math.min(xAxisTicks, maxTicks));
+ return {
+ grid: {
+ show: true,
+ backgroundColor: this._style.getPropertyValue("--internal-or-asset-tree-background-color"),
+ borderColor: this._style.getPropertyValue("--internal-or-chart-text-color"),
+ left: 10,
+ right: 10,
+ top: 10,
+ bottom: 10,
+ containLabel: true
+ },
+ backgroundColor: this._style.getPropertyValue("--internal-or-asset-tree-background-color"),
+ tooltip: {
+ trigger: "axis",
+ confine: true, //make tooltip not go outside frame bounds
+ axisPointer: {
+ type: "cross",
+ label: {
+ show: true,
+ formatter: params => {
+ if(params.axisDimension === "x") {
+ const time = moment(params.value as number);
+ const startTime: moment.Moment = time.clone().subtract((this._intervalConfig?.millis ?? 0) / 2, "milliseconds");
+ const endTime: moment.Moment = time.clone().add((this._intervalConfig?.millis ?? 0) / 2, "milliseconds");
+ switch (this._intervalConfig?.orFormat) {
+ case DatapointInterval.MINUTE:
+ case DatapointInterval.HOUR: {
+ return `${startTime.format("lll")} - ${endTime.format("lll")}`;
+ }
+ case DatapointInterval.DAY: {
+ return `${time.format("dddd, LL")}`;
+ }
+ case DatapointInterval.WEEK: {
+ return `${i18next.t("week")} ${startTime.format("w, LL")} - ${endTime.format("LL")}`;
+ }
+ default: {
+ return `${startTime.format("LL")} - ${endTime.format("LL")}`;
+ }
+ }
+ } else {
+ return Number(params.value).toFixed(this.decimals).toString();
+ }
+ }
+ }
+ }
+ },
+ xAxis: {
+ type: "time",
+ show: xAxisTicks > 1,
+ axisLine: {
+ lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}
+ },
+ splitNumber: splitNumber,
+ minInterval: this._intervalConfig!.millis,
+ min: this._startOfPeriod,
+ max: this._endOfPeriod,
+ boundaryGap: false,
+ splitArea: {
+ show: true,
+ areaStyle: {
+ color: ["transparent", "rgba(0, 0, 0, 0.05)"]
+ }
+ },
+ axisLabel: {
+ rotate: splitNumber > recommendedTicks ? 45 : 0,
+ interval: this._intervalConfig?.millis,
+ fontSize: 10,
+ formatter: {
+ year: "{yyyy}",
+ month: "{MMMM} '{yy}",
+ day: "{MMM} {d}th",
+ hour: "{HH}:{mm}",
+ minute: "{HH}:{mm}",
+ second: "{HH}:{mm}:{ss}",
+ millisecond: "{d}-{MMM} {HH}:{mm}",
+ // @ts-ignore
+ none: "{MMM}-{dd} {HH}:{mm}"
+ }
+ }
+ },
+ yAxis: [
+ {
+ type: "value",
+ axisLine: { lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}},
+ boundaryGap: ["10%", "10%"],
+ scale: true,
+ min: (this.chartOptions?.options as any)?.scales?.y?.min,
+ max: (this.chartOptions?.options as any)?.scales?.y?.max
+ },
+ {
+ type: "value",
+ show: (this.attributeConfig?.rightAxisAttributes?.length ?? 0) > 0,
+ axisLine: { lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}},
+ boundaryGap: ["10%", "10%"],
+ scale: true,
+ min: (this.chartOptions?.options as any)?.scales?.y1?.min,
+ max: (this.chartOptions?.options as any)?.scales?.y1?.max
+ }
+ ],
+ dataZoom: [
+ {
+ type: "inside",
+ minValueSpan: (this._intervalConfig?.millis ?? 0) * 4
+ }
+ ],
+ series: []
+ };
+ }
+
+ protected _getDefaultDatasetOptions(name: string, formula: string, color: string, faint = false): BarChartData {
+ const hasMultipleMethods = Object.entries(this.attributeConfig || {}).filter(([key, value]) => key.startsWith("method") && value?.length > 0).length > 1;
+ return {
+ name: name,
+ type: "bar",
+ data: [] as [number, number][],
+ stack: this.stacked ? `${formula}` : undefined,
+ itemStyle: {
+ color: color,
+ opacity: faint ? 0.31 : 1,
+ },
+ emphasis: {},
+ label: {
+ show: this.stacked ? false : true,
+ align: "left",
+ verticalAlign: "middle",
+ position: "top",
+ fontStyle: "italic",
+ fontSize: 10,
+ rotate: 90,
+ distance: 10,
+ formatter: (params): string => {
+ if(hasMultipleMethods) {
+ const data = this._data?.[params.seriesIndex ?? 0]?.data;
+ const firstIndex = data?.findIndex(x => (x as [number, number])[1] != null);
+ if(firstIndex === params.dataIndex) {
+ return formula;
+ }
+ }
+ return "";
+ }
+ }
+ } as BarChartData;
+ }
+
+ public static getDefaultTimePrefixOptions(): string[] {
+ return ["this", "last"];
+ }
+
+ public static getDefaultTimeWindowOptions(): Map<string, [moment.unitOfTime.DurationConstructor, number]> {
+ return new Map<string, [moment.unitOfTime.DurationConstructor, number]>([
+ ["Hour", ["hours", 1]],
+ ["6Hours", ["hours", 6]],
+ ["24Hours", ["hours", 24]],
+ ["Day", ["days", 1]],
+ ["7Days", ["days", 7]],
+ ["Week", ["weeks", 1]],
+ ["30Days", ["days", 30]],
+ ["Month", ["months", 1]],
+ ["365Days", ["days", 365]],
+ ["Year", ["years", 1]]
+ ]);
+ }
+
+ public static getDefaultIntervalOptions(): Map<BarChartInterval, IntervalConfig> {
+ return new Map<BarChartInterval, IntervalConfig>([
+ [BarChartInterval.AUTO, {displayName:"auto", steps: 1, orFormat: DatapointInterval.MINUTE, momentFormat: "minutes", millis: 60000}],
+ [BarChartInterval.ONE_MINUTE, {displayName:"1Minute", steps:1, orFormat:DatapointInterval.MINUTE,momentFormat:"minutes", millis: 60000}],
+ [BarChartInterval.FIVE_MINUTES, {displayName:"5Minutes", steps:5, orFormat:DatapointInterval.MINUTE,momentFormat:"minutes", millis: 300000}],
+ [BarChartInterval.THIRTY_MINUTES, {displayName:"30Minutes", steps:30, orFormat:DatapointInterval.MINUTE,momentFormat:"minutes", millis: 1800000}],
+ [BarChartInterval.ONE_HOUR, {displayName:"hour", steps:1, orFormat:DatapointInterval.HOUR,momentFormat:"hours", millis: 3600000}],
+ [BarChartInterval.ONE_DAY, {displayName:"day", steps:1, orFormat:DatapointInterval.DAY,momentFormat:"days", millis: 86400000}],
+ [BarChartInterval.ONE_WEEK, {displayName:"week", steps:1, orFormat:DatapointInterval.WEEK,momentFormat:"weeks", millis: 604800000}],
+ [BarChartInterval.ONE_MONTH, {displayName:"month", steps:1, orFormat:DatapointInterval.MONTH,momentFormat:"months", millis: 2592000000}],
+ [BarChartInterval.ONE_YEAR, {displayName:"year", steps:1, orFormat:DatapointInterval.YEAR,momentFormat:"years", millis: 31536000000}]
+ ]);
+ }
+
+}
diff --git a/ui/component/or-attribute-barchart/tsconfig.json b/ui/component/or-attribute-barchart/tsconfig.json
new file mode 100644
index 000000000..0568c6681
--- /dev/null
+++ b/ui/component/or-attribute-barchart/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../../tsconfig",
+ "compilerOptions": {
+ "outDir": "./lib",
+ "rootDir": "src",
+ },
+ "include": [
+ "./src"
+ ]
+}
diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.ts
index eb92d48e5..e19349d14 100644
--- a/ui/component/or-chart/src/index.ts
+++ b/ui/component/or-chart/src/index.ts
@@ -19,7 +19,7 @@ import "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-components/or-panel";
import "@openremote/or-translate";
import * as echarts from "echarts/core";
-import {DatasetComponentOption, DataZoomComponent, DataZoomComponentOption, GridComponent, GridComponentOption, TooltipComponent, TooltipComponentOption} from "echarts/components";
+import {DatasetComponentOption, DataZoomComponent, DataZoomComponentOption, GridComponent, GridComponentOption, MarkLineComponent, TooltipComponent, TooltipComponentOption} from "echarts/components";
import {LineChart, LineSeriesOption} from "echarts/charts";
import {CanvasRenderer} from "echarts/renderers";
import {UniversalTransition} from "echarts/features";
@@ -38,7 +38,7 @@ import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import { when } from "lit/directives/when.js";
import {createRef, Ref, ref } from "lit/directives/ref.js";
-echarts.use([GridComponent, TooltipComponent, DataZoomComponent, LineChart, CanvasRenderer, UniversalTransition]);
+echarts.use([GridComponent, TooltipComponent, DataZoomComponent, MarkLineComponent, LineChart, CanvasRenderer, UniversalTransition]);
export type ECChartOption = echarts.ComposeOption<
| LineSeriesOption
@@ -213,11 +213,25 @@ const style = css`
#msg:not([hidden]) {
display: flex;
}
+
#period-controls {
display: flex;
flex-direction: column;
align-items: center;
}
+
+ #period-dropdown-controls {
+ flex: 0;
+ display: flex;
+ }
+
+ #period-dropdown-controls > *:first-child {
+ margin-right: -2px;
+ }
+
+ #period-dropdown-controls > *:last-child {
+ margin-left: -2px;
+ }
#controls {
@@ -587,7 +601,6 @@ export class OrChart extends translate(i18next)(LitElement) {
return this._tooltipCache[1];
}
},
- toolbox: {},
xAxis: {
type: "time",
axisLine: {
@@ -597,6 +610,11 @@ export class OrChart extends translate(i18next)(LitElement) {
splitLine: {show: true},
min: this._startOfPeriod,
max: this._endOfPeriod,
+ markLine: {
+ data: [{name: 'now', xAxis: Date.now()}],
+ silent: true,
+ lineStyle: {color: this._style.getPropertyValue("--internal-or-chart-text-color")}
+ },
axisLabel: {
hideOverlap: true,
fontSize: 10,
@@ -752,34 +770,36 @@ export class OrChart extends translate(i18next)(LitElement) {
${this.timePrefixKey && this.timePrefixOptions && this.timeWindowKey && this.timeWindowOptions ? html`
${this.timestampControls ? html`
<div id="period-controls">
- <!-- Time prefix selection -->
- ${getContentWithMenuTemplate(
- html`<or-mwc-input .type="${InputType.BUTTON}" label="${this.timeframe ? "dashboard.customTimeSpan" : this.timePrefixKey.toLowerCase()}"></or-mwc-input>`,
- this.timePrefixOptions.map(option => ({value: option, text: option.toLowerCase() } as ListItem)),
- this.timePrefixKey,
- (value: string | string[]) => {
- this.timeframe = undefined; // remove any custom start & end times
- this.timePrefixKey = value.toString();
- },
- undefined,
- undefined,
- undefined,
- true
- )}
- <!-- Time window selection -->
- ${getContentWithMenuTemplate(
- html`<or-mwc-input .type="${InputType.BUTTON}" label="${this._isCustomWindow ? "timeframe" : this.timeWindowKey.toLowerCase()}"></or-mwc-input>`,
- Array.from(this.timeWindowOptions!.keys()).map(key => ({ value: key, text: key.toLowerCase() } as ListItem)),
- this.timeWindowKey,
- (value: string | string[]) => {
- this.timeframe = undefined; // remove any custom start & end times
- this.timeWindowKey = value.toString();
- },
- undefined,
- undefined,
- undefined,
- true
- )}
+ <div id="period-dropdown-controls">
+ <!-- Time prefix selection -->
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" label="${this.timeframe ? "dashboard.customTimeSpan" : this.timePrefixKey.toLowerCase()}"></or-mwc-input>`,
+ this.timePrefixOptions.map(option => ({value: option, text: option.toLowerCase() } as ListItem)),
+ this.timePrefixKey,
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timePrefixKey = value.toString();
+ },
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ <!-- Time window selection -->
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" label="${this._isCustomWindow ? "timeframe" : this.timeWindowKey.toLowerCase()}"></or-mwc-input>`,
+ Array.from(this.timeWindowOptions!.keys()).map(key => ({ value: key, text: key.toLowerCase() } as ListItem)),
+ this.timeWindowKey,
+ (value: string | string[]) => {
+ this.timeframe = undefined; // remove any custom start & end times
+ this.timeWindowKey = value.toString();
+ },
+ undefined,
+ undefined,
+ undefined,
+ true
+ )}
+ </div>
</div>
<div style="text-align: center">
<!-- Scroll left button -->
@@ -1231,6 +1251,7 @@ export class OrChart extends translate(i18next)(LitElement) {
}
this._loading = true;
+ this._latestError = undefined;
const dates: [Date, Date] = this._getTimeSelectionDates(this.timePrefixKey!, this.timeWindowKey!);
const data: LineChartData[] = [];
let promises;
@@ -1266,7 +1287,7 @@ export class OrChart extends translate(i18next)(LitElement) {
const options = { signal: this._dataAbortController?.signal };
// Load Historic Data
- let dataset = await this._loadAttributeData(asset, attribute, color ?? this.colors[colourIndex], false, smooth, stacked, stepped, area, faint, false, `${asset.name} ${label}`, options, unit);
+ let dataset = await this._loadAttributeData(asset, attribute, color ?? this.colors[colourIndex], false, smooth, stacked, stepped, area, faint, false, `${asset.name} | ${label}`, options, unit);
dataset.assetId = asset.id;
dataset.attrName = attribute.name;
dataset.unit = unit;
@@ -1274,12 +1295,12 @@ export class OrChart extends translate(i18next)(LitElement) {
data.push(dataset);
// Load Predicted Data
- dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, color ?? this.colors[colourIndex], true, smooth, stacked, stepped, area, faint, false , `${asset.name} ${label} ${i18next.t("predicted")}`, options, unit);
+ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, color ?? this.colors[colourIndex], true, smooth, stacked, stepped, area, faint, false , `${asset.name} | ${label} ${i18next.t("predicted")}`, options, unit);
data.push(dataset);
// If necessary, load Extended Data
if (extended) {
- dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, color ?? this.colors[colourIndex], false, false, stacked, false, area, faint, extended, `${asset.name} ${label} lastKnown`, options, unit);
+ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, color ?? this.colors[colourIndex], false, false, stacked, false, area, faint, extended, `${asset.name} | ${label} lastKnown`, options, unit);
dataset.yAxisIndex = shownOnRightAxis ? 1 : 0;
data.push(dataset);
}
@@ -1506,7 +1527,7 @@ export class OrChart extends translate(i18next)(LitElement) {
if (connect) {
// Add resize eventlisteners to make chart size responsive
window.addEventListener("resize", () => this._chart!.resize());
- this._containerResizeObserver = new ResizeObserver(() => { this._chart!.resize(); this.applyChartResponsiveness();});
+ this._containerResizeObserver = new ResizeObserver(() => { this.applyChartResponsiveness(); this._chart!.resize();});
if (this.shadowRoot) {
this._containerResizeObserver.observe(this.shadowRoot!.getElementById('container') as HTMLElement);
}
@@ -1579,7 +1600,7 @@ export class OrChart extends translate(i18next)(LitElement) {
displayValue = pastDatapoint.value;
}
}
- if (displayValue) {
+ if (displayValue != null) {
tooltipArray.push({
value: displayValue,
text: `<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color: ${dataset.lineStyle?.color}"></span> ${name}: <b>${displayValue}${dataset.unit ?? ""}</b></div>`
diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.ts
index 278338dda..67b7a9a29 100644
--- a/ui/component/or-dashboard-builder/src/index.ts
+++ b/ui/component/or-dashboard-builder/src/index.ts
@@ -31,6 +31,7 @@ import {MapWidget} from "./widgets/map-widget";
import {AttributeInputWidget} from "./widgets/attribute-input-widget";
import {TableWidget} from "./widgets/table-widget";
import {GatewayWidget} from "./widgets/gateway-widget";
+import {BarChartWidget} from "./widgets/barchart-widget";
// language=CSS
const styling = css`
@@ -218,6 +219,7 @@ export function registerWidgetTypes() {
widgetTypes.set("attributeinput", AttributeInputWidget.getManifest());
widgetTypes.set("table", TableWidget.getManifest());
widgetTypes.set("gateway", GatewayWidget.getManifest());
+ widgetTypes.set("barchart", BarChartWidget.getManifest());
}
@customElement("or-dashboard-builder")
diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts
index 2782785cb..90c9032cc 100644
--- a/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts
+++ b/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts
@@ -43,7 +43,7 @@ export class AttributesChartPanel extends AttributesPanel {
<or-icon icon="close-circle"></or-icon>
</button>
</div>
- ${when(!!this.attributeIconCallback, () => html`
+ ${when(!!this.attributeActionCallback, () => html`
<div class="attribute-list-item-actions" style="margin-left: 18px; justify-content: start;">
<!-- Custom actions defined by callback -->
${this.attributeActionCallback!(attributeRef).map(action => this._getAttributeActionTemplate(action, asset, attributeRef))}
@@ -57,7 +57,7 @@ export class AttributesChartPanel extends AttributesPanel {
if(action.icon === "palette") {
return html`
<div style="position: relative;">
- <input id="chart-color-${attributeRef.id}-${attributeRef.name}" type="color" style="position: absolute; visibility: hidden; height: 24px; width: 24px; padding: 0;" />
+ <input id="chart-color-${attributeRef.id}-${attributeRef.name}" type="color" value="${action.color}" style="position: absolute; visibility: hidden; height: 24px; width: 24px; padding: 0;" />
${super._getAttributeActionTemplate(action, asset, attributeRef)}
</div>
`;
diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
index 79421a8ad..ec3972712 100644
--- a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
+++ b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
@@ -25,7 +25,7 @@ export interface AttributeAction {
export class AttributeActionEvent extends CustomEvent<{ asset: Asset, attributeRef: AttributeRef, action: AttributeAction }> {
- public static readonly NAME = "attribute-action"
+ public static readonly NAME = "attribute-action";
constructor(asset: Asset, attributeRef: AttributeRef, action: AttributeAction) {
super(AttributeActionEvent.NAME, {
@@ -145,12 +145,17 @@ const styling = css`
visibility: visible;
}
+ .button-action[disabled] {
+ opacity: 0.5;
+ cursor: initial;
+ }
+
.button-action:hover {
--or-icon-fill: var(--or-icon-fill--hover, var(--or-app-color4));
}
-`
+`;
-@customElement('attributes-panel')
+@customElement("attributes-panel")
export class AttributesPanel extends LitElement {
@property({type: Array})
@@ -172,7 +177,7 @@ export class AttributesPanel extends LitElement {
protected attributeLabelCallback?: (asset: Asset, attribute: Attribute<any>, attributeLabel: string) => TemplateResult;
@property()
- protected attributeActionCallback?: (attribute: AttributeRef) => AttributeAction[]
+ protected attributeActionCallback?: (attribute: AttributeRef) => AttributeAction[];
@state()
protected loadedAssets: Asset[] = [];
@@ -189,19 +194,19 @@ export class AttributesPanel extends LitElement {
this.attributeRefs = [];
}
if (changedProps.has("attributeRefs") && this.attributeRefs) {
- this.loadAssets().then((assets) => {
+ this.loadAssets().then(assets => {
// Only dispatch event when it CHANGED, so not from 'undefined' to [];
if(changedProps.get("attributeRefs")) {
- this.dispatchEvent(new AttributesSelectEvent(assets, this.attributeRefs))
+ this.dispatchEvent(new AttributesSelectEvent(assets, this.attributeRefs));
}
- })
+ });
}
}
protected getLoadedAsset(attrRef: AttributeRef): Asset | undefined {
- return this.loadedAssets?.find((asset) => asset.id === attrRef.id)
+ return this.loadedAssets?.find(asset => asset.id === attrRef.id);
}
protected removeWidgetAttribute(attributeRef: AttributeRef) {
@@ -232,7 +237,7 @@ export class AttributesPanel extends LitElement {
}
}).then(response => {
assets = response.data;
- }).catch((reason) => {
+ }).catch(reason => {
console.error(reason);
showSnackbar(undefined, "errorOccurred");
});
@@ -248,11 +253,11 @@ export class AttributesPanel extends LitElement {
if (attributeRefs != null) {
dialog = showDialog(new OrAssetAttributePicker().setMultiSelect(multi).setSelectedAttributes(attributeRefs).setShowOnlyDatapointAttrs(onlyDataAttrs).setAttributeFilter(attributeFilter));
} else {
- dialog = showDialog(new OrAssetAttributePicker().setMultiSelect(multi).setShowOnlyDatapointAttrs(onlyDataAttrs))
+ dialog = showDialog(new OrAssetAttributePicker().setMultiSelect(multi).setShowOnlyDatapointAttrs(onlyDataAttrs));
}
dialog.addEventListener(OrAssetAttributePickerPickedEvent.NAME, (event: CustomEvent) => {
this.attributeRefs = event.detail;
- })
+ });
}
protected render(): TemplateResult {
@@ -316,7 +321,7 @@ export class AttributesPanel extends LitElement {
action => this._getAttributeActionTemplate(action, asset, attributeRef)
))}
<!-- Remove attribute button -->
- <button class="button-action" title="${i18next.t('delete')}" @click="${() => this.removeWidgetAttribute(attributeRef)}">
+ <button class="button-action" title="${i18next.t("delete")}" @click="${() => this.removeWidgetAttribute(attributeRef)}">
<or-icon icon="close-circle"></or-icon>
</button>
</div>
@@ -325,7 +330,7 @@ export class AttributesPanel extends LitElement {
protected _getAttributeActionTemplate(action: AttributeAction, asset: Asset, attributeRef: AttributeRef): TemplateResult {
const styles = styleMap({
- "--or-icon-fill": action.active ? action?.color || "inherit" : "inherit",
+ "--or-icon-fill": action.active ? action?.color ?? "inherit" : "inherit",
"--or-icon-fill--hover": action?.color ?? "unset"
});
return html`
diff --git a/ui/component/or-dashboard-builder/src/settings/barchart-settings.ts b/ui/component/or-dashboard-builder/src/settings/barchart-settings.ts
new file mode 100644
index 000000000..5335f3562
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/barchart-settings.ts
@@ -0,0 +1,561 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {css, html, TemplateResult} from "lit";
+import {customElement, query} from "lit/decorators.js";
+import {WidgetSettings} from "../util/widget-settings";
+import "../panels/attributes-chart-panel";
+import "../util/settings-panel";
+import {i18next} from "@openremote/or-translate";
+import {AttributeAction, AttributeActionEvent, AttributesSelectEvent} from "../panels/attributes-panel";
+import {Asset, AssetDescriptor, Attribute, AttributeRef} from "@openremote/model";
+import {BarChartWidgetConfig} from "../widgets/barchart-widget";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {when} from "lit/directives/when.js";
+import moment from "moment/moment";
+import {ListItem, ListType, OrMwcList} from "@openremote/or-mwc-components/or-mwc-list";
+import {showDialog, OrMwcDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {BarChartAttributeConfig, BarChartInterval, IntervalConfig, OrAttributeBarChart} from "@openremote/or-attribute-barchart";
+import {OrChart} from "@openremote/or-chart";
+import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
+import {createRef, Ref, ref} from "lit/directives/ref.js";
+import {AttributesChartPanel} from "../panels/attributes-chart-panel";
+import {debounce} from "lodash";
+
+const styling = css`
+ .switch-container {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`;
+
+
+@customElement("barchart-settings")
+export class BarChartSettings extends WidgetSettings {
+
+ @query("attributes-chart-panel")
+ protected _attributesPanelElem?: AttributesChartPanel;
+
+ protected readonly widgetConfig!: BarChartWidgetConfig;
+
+ protected timeWindowOptions: Map<string, [moment.unitOfTime.DurationConstructor, number]> = new Map<string, [moment.unitOfTime.DurationConstructor, number]>;
+ protected timePrefixOptions: string[] = [];
+ protected intervalOptions: Map<BarChartInterval, IntervalConfig> = new Map<BarChartInterval, IntervalConfig>();
+
+ public setTimeWindowOptions(options: Map<string, [moment.unitOfTime.DurationConstructor, number]>) {
+ this.timeWindowOptions = options;
+ }
+
+ public setTimePrefixOptions(options: string[]) {
+ this.timePrefixOptions = options;
+ }
+
+ public setIntervalOptions(options: Map<BarChartInterval, IntervalConfig>) {
+ this.intervalOptions = options;
+ }
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ protected render(): TemplateResult {
+ const attributeFilter: (attr: Attribute<any>) => boolean = (attr): boolean =>
+ ["boolean", "positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"].includes(attr.type!);
+
+ const attrSettings = this.widgetConfig.attributeSettings;
+ const min = this.widgetConfig.chartOptions.options?.scales?.y?.min;
+ const max = this.widgetConfig.chartOptions.options?.scales?.y?.max;
+ const isMultiAxis = !!attrSettings.rightAxisAttributes?.length;
+
+ const attributeIconCallback = (asset: Asset, attribute: Attribute<any>, descriptor?: AssetDescriptor) => {
+ let color = this.widgetConfig.attributeColors?.find(a => a[0].id === asset.id && a[0].name === attribute?.name)?.[1]?.replace("#", "");
+ if(!color) {
+ const index = this.widgetConfig.attributeRefs?.findIndex(ref => ref.id === asset.id && ref.name === attribute?.name);
+ if(index >= 0) color = OrChart.DEFAULT_COLORS?.[index]?.replace("#", "");
+ }
+ return html`<span>${getAssetDescriptorIconTemplate(descriptor, undefined, undefined, color)}</span>`;
+ };
+
+ const attributeActionCallback = (attributeRef: AttributeRef): AttributeAction[] => {
+ const faint = !!this.widgetConfig?.attributeSettings?.faintAttributes?.find(ref => ref.id === attributeRef.id && ref.name === attributeRef.name);
+ let color = this.widgetConfig?.attributeColors?.find(([ref, _]) => ref.id === attributeRef.id && ref.name === attributeRef.name)?.[1];
+ let customColor = false;
+ if (!color) {
+ const index = this.widgetConfig?.attributeRefs?.findIndex(ref => ref.id === attributeRef.id && ref.name === attributeRef.name);
+ if (index >= 0) color = OrAttributeBarChart.DEFAULT_COLORS[index];
+ } else {
+ customColor = true;
+ }
+ return [
+ {
+ icon: "arrow-up-circle",
+ tooltip: "Order up",
+ active: false,
+ disabled: this.widgetConfig.attributeRefs.indexOf(attributeRef) === 0
+ },
+ {
+ icon: "arrow-down-circle",
+ tooltip: "Order down",
+ active: false,
+ disabled: this.widgetConfig.attributeRefs.indexOf(attributeRef) === (this.widgetConfig.attributeRefs.length - 1)
+ },
+ {
+ icon: "calculator-variant-outline",
+ tooltip: i18next.t("algorithmMethod"),
+ active: true,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: "palette",
+ tooltip: i18next.t("dashboard.barColor"),
+ active: customColor,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: "arrange-send-backward",
+ tooltip: i18next.t("dashboard.faint"),
+ active: faint,
+ color: color,
+ disabled: false
+ },
+ {
+ icon: this.widgetConfig.attributeSettings.rightAxisAttributes?.includes(attributeRef) ? "arrow-right-bold" : "arrow-left-bold",
+ tooltip: i18next.t("dashboard.toggleAxis"),
+ active: false,
+ color: color,
+ disabled: false
+ }
+ ];
+ };
+ const timeWindowOpts = Array.from(this.timeWindowOptions.keys()).map(o => ([o, i18next.t(o.toLowerCase())] as [string, string]));
+ const intervalOpts = Array.from(this.intervalOptions.keys()).map(o => ([o, i18next.t(`intervalBy${o.toLowerCase()}`)] as [string, string]));
+ return html`
+ <div>
+ <!-- Attribute selection -->
+ <settings-panel displayName="attributes" expanded="${true}">
+ <attributes-chart-panel .attributeRefs="${this.widgetConfig.attributeRefs}" multi onlyDataAttrs .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;"
+ .attributeIconCallback=${attributeIconCallback} .attributeActionCallback="${attributeActionCallback}"
+ @attribute-action="${(ev: AttributeActionEvent) => this.onAttributeAction(ev)}"
+ @attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></attributes-chart-panel>
+ </settings-panel>
+
+ <!-- Time options -->
+ <settings-panel displayName="time" expanded="${true}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 6px;">
+
+ <!-- Timeframe & interval -->
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t("prefixDefault")}" style="width: 100%;"
+ .options="${this.timePrefixOptions}" value="${this.widgetConfig.defaultTimePrefixKey}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimePrefixSelect(ev)}"
+ ></or-mwc-input>
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t("timeframeDefault")}" style="width: 100%;"
+ .options="${timeWindowOpts}" value="${this.widgetConfig.defaultTimeWindowKey}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimeWindowSelect(ev)}"
+ ></or-mwc-input>
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t("withInterval")}" style="width: 100%;"
+ .options="${intervalOpts}" value="${this.widgetConfig.defaultInterval}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onIntervalSelect(ev)}"
+ ></or-mwc-input>
+ </div>
+ </settings-panel>
+
+ <!-- Display options -->
+ <settings-panel displayName="display" expanded="${false}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 16px;">
+ <!-- Stacked -->
+ <div class="switch-container">
+ <span><or-translate value="dashboard.toggleStackView"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.stacked}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onDefaultStackedToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <!-- Time range selection -->
+ <div class="switch-container">
+ <span><or-translate value="dashboard.allowTimerangeSelect"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${!this.widgetConfig.showTimestampControls}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimestampControlsToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <!-- Show legend -->
+ <div class="switch-container">
+ <span><or-translate value="dashboard.showLegend"></or-translate></span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showLegend}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowLegendToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <!-- Decimal places -->
+ <div>
+ <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;" .value="${this.widgetConfig.decimals}" label="${i18next.t("decimals")}" .min="${0}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onDecimalsChange(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+
+ <!-- Axis configuration -->
+ <settings-panel displayName="dashboard.axisConfig" expanded="${false}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 16px;">
+
+ <!-- Left axis configuration -->
+ <div>
+ ${when(isMultiAxis, () => html`
+ <div style="margin-bottom: 8px;">
+ <span><or-translate value="dashboard.leftAxis"></or-translate></span>
+ </div>
+ `)}
+ <div style="display: flex;">
+ ${when(max !== undefined, () => html`
+ <or-mwc-input .type="${InputType.NUMBER}" label="${`${i18next.t("yAxis")} ${i18next.t("max")}`}" .value="${max}" style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange("left", "max", ev)}"
+ ></or-mwc-input>
+ `, () => html`
+ <or-mwc-input .type="${InputType.TEXT}" label="${`${i18next.t("yAxis")} ${i18next.t("max")}`}" disabled value="auto" style="width: 100%;"></or-mwc-input>
+ `)}
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${max !== undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueToggle("left", "max", ev)}"
+ ></or-mwc-input>
+ </div>
+ <div style="display: flex; margin-top: 12px;">
+ ${when(min !== undefined, () => html`
+ <or-mwc-input .type="${InputType.NUMBER}" label="${`${i18next.t("yAxis")} ${i18next.t("min")}`}" .value="${min}" style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange("left", "min", ev)}"
+ ></or-mwc-input>
+ `, () => html`
+ <or-mwc-input .type="${InputType.TEXT}" label="${`${i18next.t("yAxis")} ${i18next.t("min")}`}" disabled value="auto" style="width: 100%;"></or-mwc-input>
+ `)}
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${min !== undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueToggle("left", "min", ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+
+ <!-- Right axis configuration -->
+ ${when(isMultiAxis, () => {
+ const rightMin = this.widgetConfig.chartOptions.options?.scales?.y1?.min;
+ const rightMax = this.widgetConfig.chartOptions.options?.scales?.y1?.max;
+ return html`
+ <div>
+ <div style="margin-bottom: 8px;">
+ <span><or-translate value="dashboard.rightAxis"></or-translate></span>
+ </div>
+ <div style="display: flex;">
+ ${when(rightMax !== undefined, () => html`
+ <or-mwc-input .type="${InputType.NUMBER}" label="${`${i18next.t("yAxis")} ${i18next.t("max")}`}" .value="${rightMax}" style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange("right", "max", ev)}"
+ ></or-mwc-input>
+ `, () => html`
+ <or-mwc-input .type="${InputType.TEXT}" label="${`${i18next.t("yAxis")} ${i18next.t("max")}`}" disabled="true" value="auto"
+ style="width: 100%;"></or-mwc-input>
+ `)}
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${rightMax !== undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueToggle("right", "max", ev)}"
+ ></or-mwc-input>
+ </div>
+ <div style="display: flex; margin-top: 12px;">
+ ${when(rightMin !== undefined, () => html`
+ <or-mwc-input .type="${InputType.NUMBER}" label="${`${i18next.t("yAxis")} ${i18next.t("min")}`}" .value="${rightMin}" style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange("right", "min", ev)}"
+ ></or-mwc-input>
+ `, () => html`
+ <or-mwc-input .type="${InputType.TEXT}" label="${`${i18next.t("yAxis")} ${i18next.t("min")}`}" disabled="true" value="auto"
+ style="width: 100%;"></or-mwc-input>
+ `)}
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${rightMin !== undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueToggle("right", "min", ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ `;
+ })}
+ </div>
+ </settings-panel>
+ </div>
+ `;
+ }
+
+ // Check which icon was pressed and act accordingly.
+ protected onAttributeAction(ev: AttributeActionEvent) {
+ const {attributeRef, action} = ev.detail;
+ switch (action.icon) {
+ case "palette": // Change color
+ this.openColorPickDialog(attributeRef);
+ break;
+ case "arrow-right-bold":
+ case "arrow-left-bold":
+ this.toggleAttributeSetting("rightAxisAttributes", attributeRef);
+ break;
+ case "calculator-variant-outline":
+ this.openAlgorithmMethodsDialog(attributeRef);
+ break;
+ case "arrange-send-backward":
+ this.onFaintClick(attributeRef);
+ break;
+ case "arrow-up-circle":
+ this.onArrowUpClick(attributeRef);
+ break;
+ case "arrow-down-circle":
+ this.onArrowDownClick(attributeRef);
+ break;
+ default:
+ console.warn("Unknown attribute panel action:", action);
+ }
+ }
+
+ protected onFaintClick(attrRef: AttributeRef) {
+ this.widgetConfig.attributeSettings.faintAttributes ??= [];
+ const index = this.widgetConfig.attributeSettings.faintAttributes.findIndex(attr => attr.id === attrRef.id && attr.name === attrRef.name);
+ if (index >= 0) {
+ this.widgetConfig.attributeSettings.faintAttributes = this.widgetConfig.attributeSettings.faintAttributes.filter(attr => attr.id !== attrRef.id && attr.name !== attrRef.name);
+ } else {
+ this.widgetConfig.attributeSettings.faintAttributes.push(attrRef);
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onArrowUpClick(attrRef: AttributeRef) {
+ const index = this.widgetConfig.attributeRefs.indexOf(attrRef);
+ if (index > 0) {
+ const temp = this.widgetConfig.attributeRefs[index - 1];
+ this.widgetConfig.attributeRefs[index - 1] = attrRef;
+ this.widgetConfig.attributeRefs[index] = temp;
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onArrowDownClick(attrRef: AttributeRef) {
+ const index = this.widgetConfig.attributeRefs.indexOf(attrRef);
+ if (index < this.widgetConfig.attributeRefs.length - 1) {
+ const temp = this.widgetConfig.attributeRefs[index + 1];
+ this.widgetConfig.attributeRefs[index + 1] = attrRef;
+ this.widgetConfig.attributeRefs[index] = temp;
+ }
+ this.notifyConfigUpdate();
+ }
+
+ // When the list of attributeRefs is changed by the asset selector,
+ // we should remove the settings references for the attributes that got removed.
+ // Also update the WidgetConfig attributeRefs field as usual
+ protected onAttributesSelect(ev: AttributesSelectEvent) {
+ const removedAttributeRefs = this.widgetConfig.attributeRefs.filter(ar => !ev.detail.attributeRefs.find(newRefs => newRefs.id === ar.id && newRefs.name === ar.name));
+ removedAttributeRefs.forEach(ref => {
+ this.removeFromAttributeSettings(ref);
+ this.removeFromAttributeColors(ref);
+ });
+ this.widgetConfig.attributeRefs = ev.detail.attributeRefs;
+
+ // Add colors
+ this.widgetConfig.attributeColors ??= [];
+ ev.detail.attributeRefs.forEach(((attrRef, index) => {
+ const color = this.widgetConfig.attributeColors.find(x => x[0].id === attrRef.id && x[0].name === ref.name);
+ if(!color) {
+ const newColor = OrAttributeBarChart.DEFAULT_COLORS[index] ?? "#000000";
+ this.widgetConfig.attributeColors.push([attrRef, newColor]);
+ }
+ }));
+
+ // Loop through attribute methods (MIN, AVG, MAX etc), and place attributes in 'AVG' if not in any yet.
+ const settings = this.widgetConfig.attributeSettings;
+ const methodRefsList = [...settings.methodAvgAttributes ?? [], ...settings.methodMinAttributes ?? [], ...settings.methodMaxAttributes ?? [],
+ ...settings.methodDifferenceAttributes ?? [], ...settings.methodMedianAttributes ?? [], ...settings.methodModeAttributes ?? [],
+ ...settings.methodSumAttributes ?? [], ...settings.methodCountAttributes ?? []
+ ];
+ this.widgetConfig.attributeRefs.forEach(ref => {
+ if(!methodRefsList.find(methodRef => methodRef.id === ref.id && methodRef.name === ref.name)) {
+ this.widgetConfig.attributeSettings.methodAvgAttributes ??= [];
+ this.widgetConfig.attributeSettings.methodAvgAttributes.push(ref);
+ }
+ });
+ this.notifyConfigUpdate();
+ }
+
+ protected removeFromAttributeSettings(attributeRef: AttributeRef) {
+ const settings = this.widgetConfig.attributeSettings;
+ (Object.keys(settings) as (keyof typeof settings)[]).forEach(key => {
+ settings[key] = settings[key]!.filter((ar: AttributeRef) => (ar.id !== attributeRef.id && ar.name !== attributeRef.name));
+ });
+ }
+
+ /**
+ * Adds or removes an {@link AttributeRef} from a field in the {@link BarChartAttributeConfig}.
+ * For example, you can modify the list of 'right aligned attributes', or attributes that are displaying their 'AVG value'.
+ * If the {@link AttributeRef} is already present, it'll be removed. Otherwise, it will be added.
+ * @param setting - Field of {@link BarChartWidgetConfig} to append/remove the attribute from.
+ * @param attributeRef - The {@link AttributeRef} to add/remove.
+ * @protected
+ */
+ protected toggleAttributeSetting(setting: keyof BarChartWidgetConfig["attributeSettings"], attributeRef: AttributeRef, notify = true): void {
+ this.widgetConfig.attributeSettings[setting] ??= [];
+ const attributes = this.widgetConfig.attributeSettings[setting];
+ const index = attributes.findIndex(
+ (item: AttributeRef) => item.id === attributeRef.id && item.name === attributeRef.name
+ );
+ if (index < 0) {
+ attributes.push(attributeRef);
+ } else {
+ attributes.splice(index, 1);
+ if(attributes && attributes.length === 0) {
+ delete this.widgetConfig.attributeSettings[setting];
+ }
+ }
+ if(notify) {
+ this.notifyConfigUpdate();
+ }
+ }
+
+ protected openColorPickDialog(attributeRef: AttributeRef) {
+ const inputElem = this._attributesPanelElem?.shadowRoot?.querySelector(`#chart-color-${attributeRef.id}-${attributeRef.name}`) as HTMLInputElement | undefined;
+ if(inputElem) {
+
+ // Listen for changes
+ inputElem.addEventListener("input", debounce(() => {
+ const color = inputElem.value;
+ this.widgetConfig.attributeColors ??= [];
+ const existingColor = this.widgetConfig.attributeColors.find(x => x[0].id === attributeRef.id && x[0].name === attributeRef.name);
+ if(existingColor) {
+ existingColor[1] = color;
+ } else {
+ this.widgetConfig.attributeColors.push([attributeRef, color]);
+ }
+ this.notifyConfigUpdate();
+ }, 200));
+
+ // Open color picker
+ inputElem.click();
+ }
+ }
+
+
+ protected removeFromAttributeColors(attributeRef: AttributeRef) {
+ this.widgetConfig.attributeColors = this.widgetConfig.attributeColors.filter(
+ ([ref, _]) => ref.id !== attributeRef.id || ref.name !== attributeRef.name
+ );
+ }
+
+
+ protected openAlgorithmMethodsDialog(attributeRef: AttributeRef) {
+ const methodKeys: (keyof BarChartAttributeConfig)[] = [
+ "methodAvgAttributes", "methodCountAttributes", "methodDifferenceAttributes", "methodMaxAttributes",
+ "methodMedianAttributes", "methodMinAttributes", "methodModeAttributes", "methodSumAttributes"
+ ];
+ const methodList: ListItem[] = methodKeys.map(key => {
+ const attributeRefs = this.widgetConfig.attributeSettings[key];
+ const isActive = attributeRefs?.some(attrRef => attrRef.id === attributeRef.id && attrRef.name === attributeRef.name);
+ return {
+ text: key,
+ value: key,
+ data: isActive ? key : undefined,
+ translate: true
+ };
+ });
+
+ const listRef: Ref<OrMwcList> = createRef();
+
+ showDialog(new OrMwcDialog()
+ .setContent(html`
+ <div id="method-creator">
+ <or-mwc-list ${ref(listRef)} id="method-creator-list" .type="${ListType.MULTI_CHECKBOX}"
+ .listItems="${methodList}"
+ .values="${methodList.map(item => item.data)}"
+ ></or-mwc-list>
+ </div>
+ `)
+ .setHeading(i18next.t("algorithmMethod"))
+ .setActions([
+ {
+ actionName: "cancel",
+ content: "cancel"
+ },
+ {
+ default: true,
+ actionName: "ok",
+ action: () => {
+ if(listRef.value) {
+ // Find all "active" methods for this AttributeRef, and remove them all. (so they become empty arrays)
+ methodKeys.filter(oldKey => !!this.widgetConfig.attributeSettings[oldKey]?.find(attrRef => attrRef.id === attributeRef.id && attrRef.name === attributeRef.name))
+ .forEach(oldKey => this.toggleAttributeSetting(oldKey, attributeRef, false));
+
+ // Add the methods that were checked in the checkbox list
+ (listRef.value.values as (keyof BarChartAttributeConfig)[] | undefined)?.forEach(s => {
+ this.toggleAttributeSetting(s, attributeRef, false);
+ });
+ this.notifyConfigUpdate();
+ }
+ },
+ content: "ok"
+ }
+ ])
+ .setDismissAction(null));
+ }
+
+ protected onTimePrefixSelect(ev: OrInputChangedEvent) {
+ this.widgetConfig.defaultTimePrefixKey = ev.detail.value.toString();
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimeWindowSelect(ev: OrInputChangedEvent) {
+ this.widgetConfig.defaultTimeWindowKey = ev.detail.value.toString();
+ this.notifyConfigUpdate();
+ }
+
+ protected onIntervalSelect(ev: OrInputChangedEvent) {
+ this.widgetConfig.defaultInterval = ev.detail.value.toString();
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimestampControlsToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showTimestampControls = !ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onShowLegendToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showLegend = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onDefaultStackedToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.stacked = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected setAxisMinMaxValue(axis: "left" | "right", type: "min" | "max", value?: number) {
+ if (axis === "left") {
+ this.widgetConfig.chartOptions.options.scales.y[type] = value;
+ } else {
+ this.widgetConfig.chartOptions.options.scales.y1[type] = value;
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onMinMaxValueChange(axis: "left" | "right", type: "min" | "max", ev: OrInputChangedEvent) {
+ this.setAxisMinMaxValue(axis, type, ev.detail.value);
+ }
+
+ protected onMinMaxValueToggle(axis: "left" | "right", type: "min" | "max", ev: OrInputChangedEvent) {
+ this.setAxisMinMaxValue(axis, type, (ev.detail.value ? (type === "min" ? 0 : 100) : undefined));
+ }
+
+ protected onDecimalsChange(ev: OrInputChangedEvent) {
+ this.widgetConfig.decimals = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
index 2f7153858..3d371ef5b 100644
--- a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
+++ b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
@@ -203,7 +203,6 @@ export class ChartSettings extends WidgetSettings {
<!-- Axis configuration -->
<settings-panel displayName="dashboard.axisConfig" expanded>
<div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 16px;">
-
<!-- Left axis configuration -->
<div>
${when(isMultiAxis, () => html`
@@ -332,9 +331,11 @@ export class ChartSettings extends WidgetSettings {
this._toggleAttributeSetting("rightAxisAttributes", attributeRef);
break;
case "chart-bell-curve-cumulative":
+ if(!action.active) { this._removeAttributeSetting("steppedAttributes", attributeRef); }
this._toggleAttributeSetting("smoothAttributes", attributeRef);
break;
case "square-wave":
+ if(!action.active) { this._removeAttributeSetting("smoothAttributes", attributeRef); }
this._toggleAttributeSetting("steppedAttributes", attributeRef);
break;
case "chart-areaspline-variant":
@@ -385,24 +386,63 @@ export class ChartSettings extends WidgetSettings {
* @protected
*/
protected _toggleAttributeSetting(setting: keyof ChartAttributeConfig, attributeRef: AttributeRef) {
+ const attributes = this.widgetConfig.attributeConfig?.[setting];
+ const index = attributes?.findIndex((item: AttributeRef) => item.id === attributeRef.id && item.name === attributeRef.name);
+ if (index == null || index < 0) {
+ this._addAttributeSetting(setting, attributeRef);
+ } else {
+ this._removeAttributeSetting(setting, attributeRef);
+ }
+ this.notifyConfigUpdate();
+ }
+
+ /**
+ * Internal function that adds an {@link AttributeRef} to a category of the {@link AttributeConfig}.
+ * For example, you can add an attribute to the array of 'rightAxisAttributes'.
+ * @param setting The key / category to add the attribute to. (for example, 'rightAxisAttributes')
+ * @param attributeRef The asset-attribute combination to add.
+ * @protected
+ */
+ protected _addAttributeSetting(setting: keyof ChartAttributeConfig, attributeRef: AttributeRef) {
this.widgetConfig.attributeConfig ??= {};
this.widgetConfig.attributeConfig[setting] ??= [];
const attributes = this.widgetConfig.attributeConfig[setting]!;
- const index = attributes.findIndex(
- (item: AttributeRef) => item.id === attributeRef.id && item.name === attributeRef.name
- );
- if (index < 0) {
- // Adding the attribute setting
+ const exists = !!attributes.find((item: AttributeRef) => item.id === attributeRef.id && item.name === attributeRef.name);
+ if(!exists) {
+ console.debug(`Adding attribute ${attributeRef.name} to setting ${setting} in widget config.`);
attributes.push(attributeRef);
} else {
- // Removing the attribute setting
- if (attributes.length === 1) {
- delete this.widgetConfig.attributeConfig[setting];
- } else {
- attributes.splice(index, 1);
- }
+ console.warn(`Could not add attribute ${attributeRef.name}; attribute already exists in attribute setting ${setting}.`, attributes);
}
- this.notifyConfigUpdate();
+ }
+
+ /**
+ * Internal function that removes an {@link AttributeRef} from a category of the {@link AttributeConfig}.
+ * For example, you can remove an attribute from the array of 'rightAxisAttributes'.
+ * @param setting The key / category to remove the attribute from. (for example, 'rightAxisAttributes')
+ * @param attributeRef The asset-attribute combination to remove.
+ * @protected
+ */
+ protected _removeAttributeSetting(setting: keyof ChartAttributeConfig, attributeRef: AttributeRef) {
+ const attributes = this.widgetConfig.attributeConfig?.[setting];
+ if(!attributes) {
+ console.warn(`Could not remove attribute; attribute setting ${setting} not found in widget config.`, attributes);
+ return;
+ }
+ // Check if attribute exists in the configuration for this setting
+ const index = attributes?.findIndex((item: AttributeRef) => item.id === attributeRef.id && item.name === attributeRef.name);
+ if(index == null || index < 0) {
+ console.warn(`Could not remove attribute; attribute ${attributeRef.name} not found in attribute setting ${setting}.`, attributes);
+ return;
+ }
+ // Remove attribute
+ console.debug(`Removing attribute ${attributeRef.name} from setting ${setting} in widget config.`);
+ if (attributes.length === 1) {
+ delete this.widgetConfig.attributeConfig![setting];
+ } else {
+ attributes.splice(index, 1);
+ }
+
}
protected removeFromAttributeColors(attributeRef: AttributeRef) {
diff --git a/ui/component/or-dashboard-builder/src/widgets/barchart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/barchart-widget.ts
new file mode 100644
index 000000000..622aa2c2b
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/barchart-widget.ts
@@ -0,0 +1,222 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {AssetDatapointIntervalQuery, AssetDatapointQueryUnion, Attribute, AttributeRef} from "@openremote/model";
+import {html, PropertyValues, TemplateResult} from "lit";
+import {when} from "lit/directives/when.js";
+import moment from "moment";
+import {OrAssetWidget} from "../util/or-asset-widget";
+import {customElement, state} from "lit/decorators.js";
+import {AssetWidgetConfig} from "../util/widget-config";
+import {OrWidget, WidgetManifest} from "../util/or-widget";
+import {BarChartSettings} from "../settings/barchart-settings";
+import {WidgetSettings} from "../util/widget-settings";
+import "@openremote/or-attribute-barchart";
+import {BarChartAttributeConfig, BarChartInterval, OrAttributeBarChart} from "@openremote/or-attribute-barchart";
+
+export interface BarChartWidgetConfig extends AssetWidgetConfig {
+ attributeColors: [AttributeRef, string][];
+ attributeSettings: BarChartAttributeConfig,
+ datapointQuery: AssetDatapointQueryUnion;
+ chartOptions?: any;
+ showTimestampControls: boolean;
+ defaultTimeWindowKey: string;
+ defaultTimePrefixKey: string;
+ defaultInterval: BarChartInterval;
+ showLegend: boolean;
+ stacked: boolean;
+ decimals: number;
+}
+
+function getDefaultWidgetConfig(): BarChartWidgetConfig {
+ const preset = "Day"; // Default time preset, "current" prefix is hardcoded in startDate and endDate below.
+ const dateFunc = OrAttributeBarChart.getDefaultTimeWindowOptions().get(preset);
+ const startDate = moment().subtract(dateFunc![1], dateFunc![0]).startOf(dateFunc![0]);
+ const endDate = dateFunc![1] === 1 ? moment().endOf(dateFunc![0]) : moment();
+ return {
+ attributeRefs: [],
+ attributeColors: [],
+ attributeSettings: {},
+ datapointQuery: {
+ type: "interval",
+ fromTimestamp: startDate.toDate().getTime(),
+ toTimestamp: endDate.toDate().getTime()
+ },
+ chartOptions: {
+ options: {
+ scales: {
+ y: {
+ min: undefined,
+ max: undefined
+ },
+ y1: {
+ min: undefined,
+ max: undefined
+ }
+ }
+ }
+ },
+ showTimestampControls: false,
+ defaultTimeWindowKey: preset,
+ defaultTimePrefixKey: "this",
+ defaultInterval: BarChartInterval.AUTO,
+ showLegend: true,
+ stacked: false,
+ decimals: 2
+ };
+}
+
+/* --------------------------------------------------- */
+
+@customElement("barchart-widget")
+export class BarChartWidget extends OrAssetWidget {
+
+ @state()
+ protected datapointQuery!: AssetDatapointQueryUnion;
+
+ @state()
+ protected _loading = false;
+
+ // Override of widgetConfig with extended type
+ protected widgetConfig!: BarChartWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Bar Chart",
+ displayIcon: "chart-bar",
+ minColumnWidth: 2,
+ minColumnHeight: 2,
+ getContentHtml(config: BarChartWidgetConfig): OrWidget {
+ return new BarChartWidget(config);
+ },
+ getSettingsHtml(config: BarChartWidgetConfig): WidgetSettings {
+ const settings = new BarChartSettings(config);
+ settings.setTimeWindowOptions(OrAttributeBarChart.getDefaultTimeWindowOptions());
+ settings.setTimePrefixOptions(OrAttributeBarChart.getDefaultTimePrefixOptions());
+ settings.setIntervalOptions(OrAttributeBarChart.getDefaultIntervalOptions());
+ return settings;
+ },
+ getDefaultConfig(): BarChartWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ };
+ }
+
+ // Method called on every refresh/reload of the widget
+ // We either refresh the datapointQuery or the full widgetConfig depending on the force parameter.
+ // TODO: Improve this to a more efficient approach, instead of duplicating the object
+ public refreshContent(force: boolean) {
+ if(!force) {
+ const datapointQuery = structuredClone(this.widgetConfig.datapointQuery);
+ datapointQuery.fromTimestamp = undefined;
+ datapointQuery.toTimestamp = undefined;
+ this.datapointQuery = datapointQuery;
+ } else {
+ this.widgetConfig = structuredClone(this.widgetConfig);
+ }
+ }
+
+
+ /* ---------------------------------- */
+
+ // WebComponent lifecycle method, that occurs DURING every state update
+ protected willUpdate(changedProps: PropertyValues) {
+
+ // Add datapointQuery if not set yet (due to migration)
+ if(!this.widgetConfig.datapointQuery) {
+ this.widgetConfig.datapointQuery = this.getDefaultQuery();
+ if(!changedProps.has("widgetConfig")) {
+ changedProps.set("widgetConfig", this.widgetConfig);
+ }
+ }
+
+ if(changedProps.has("widgetConfig") && this.widgetConfig) {
+ this.datapointQuery = this.widgetConfig.datapointQuery;
+
+ const attributeRefs = this.widgetConfig.attributeRefs;
+ if(attributeRefs.length === 0) {
+ this._error = "noAttributesConnected";
+ } else {
+ const missingAssets = attributeRefs?.filter((attrRef: AttributeRef) => !this.isAttributeRefLoaded(attrRef));
+ if (missingAssets.length > 0) {
+ this.loadAssets(attributeRefs);
+ }
+ }
+ }
+
+ return super.willUpdate(changedProps);
+ }
+
+ protected loadAssets(attributeRefs: AttributeRef[]): void {
+ if(attributeRefs.length === 0) {
+ this._error = "noAttributesConnected";
+ return;
+ }
+ this._loading = true;
+ this._error = undefined;
+ this.fetchAssets(attributeRefs).then(assets => {
+ this.loadedAssets = assets;
+ this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {
+ const assetIndex = assets.findIndex(asset => asset.id === attrRef.id);
+ const foundAsset = assetIndex >= 0 ? assets[assetIndex] : undefined;
+ return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;
+ }).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];
+ }).catch(e => {
+ this._error = e.message;
+ }).finally(() => {
+ this._loading = false;
+ });
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ ${when(this._loading, () => html`
+ <or-loading-indicator></or-loading-indicator>
+
+ `, () => when(this._error, () => html`
+ <div style="height: 100%; display: flex; justify-content: center; align-items: center; text-align: center;">
+ <span><or-translate .value="${this._error}"></or-translate></span>
+ </div>
+
+ `, () => {
+ return html`
+ <or-attribute-barchart .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}"
+ .attributeColors="${this.widgetConfig?.attributeColors}" .attributeConfig="${this.widgetConfig?.attributeSettings}"
+ ?showLegend=${this.widgetConfig?.showLegend} ?stacked=${this.widgetConfig?.stacked}
+ .timestampControls="${!this.widgetConfig?.showTimestampControls}"
+ .interval="${this.widgetConfig?.defaultInterval}"
+ .timePrefixKey="${this.widgetConfig?.defaultTimePrefixKey}"
+ .timeWindowKey="${this.widgetConfig?.defaultTimeWindowKey}"
+ .datapointQuery="${this.datapointQuery}" .chartOptions="${this.widgetConfig?.chartOptions}"
+ .decimals="${this.widgetConfig?.decimals}"
+ style="height: 100%"
+ ></or-attribute-barchart>
+ `;
+ }))}
+ `;
+ }
+
+ protected getDefaultQuery(): AssetDatapointIntervalQuery {
+ return {
+ type: "interval",
+ fromTimestamp: moment().subtract(30, "days").toDate().getTime(),
+ toTimestamp: moment().toDate().getTime()
+ };
+ }
+}
diff --git a/yarn.lock b/yarn.lock
index 2102347d9..a526e9a0d 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -335,6 +335,13 @@ __metadata:
languageName: node
linkType: hard
+"@lit-labs/ssr-dom-shim@npm:^1.4.0":
+ version: 1.4.0
+ resolution: "@lit-labs/ssr-dom-shim@npm:1.4.0"
+ checksum: 10c0/eb8b4c6ed83db48e2f2c8c038f88e0ac302214918e5c1209458cb82a35ce27ce586100c5692885b2c5520f6941b2c3512f26c4d7b7dd48f13f17f1668553395a
+ languageName: node
+ linkType: hard
+
"@lit/reactive-element@npm:^1.0.0 || ^2.0.0, @lit/reactive-element@npm:^2.0.4":
version: 2.0.4
resolution: "@lit/reactive-element@npm:2.0.4"
@@ -353,6 +360,15 @@ __metadata:
languageName: node
linkType: hard
+"@lit/reactive-element@npm:^2.1.0":
+ version: 2.1.1
+ resolution: "@lit/reactive-element@npm:2.1.1"
+ dependencies:
+ "@lit-labs/ssr-dom-shim": "npm:^1.4.0"
+ checksum: 10c0/200d72c3d1bb8babc88123f3684e52cf490ec20cc7974002d666b092afa18e4a7c1ca15883c84c0b8671361a9875905eb18c1f03d20ecbbbaefdaec6e0c7c4eb
+ languageName: node
+ linkType: hard
+
"@lit/task@npm:^1.0.0":
version: 1.0.0
resolution: "@lit/task@npm:1.0.0"
@@ -1295,6 +1311,7 @@ __metadata:
resolution: "@openremote/manager@workspace:ui/app/manager"
dependencies:
"@openremote/or-app": "workspace:*"
+ "@openremote/or-attribute-barchart": "workspace:*"
"@openremote/util": "workspace:*"
iso-639-1: "npm:^3.1.3"
languageName: unknown
@@ -1377,6 +1394,21 @@ __metadata:
languageName: unknown
linkType: soft
+"@openremote/or-attribute-barchart@workspace:*, @openremote/or-attribute-barchart@workspace:ui/component/or-attribute-barchart":
+ version: 0.0.0-use.local
+ resolution: "@openremote/or-attribute-barchart@workspace:ui/component/or-attribute-barchart"
+ dependencies:
+ "@openremote/core": "workspace:*"
+ "@openremote/or-icon": "workspace:*"
+ "@openremote/or-mwc-components": "workspace:*"
+ "@openremote/or-translate": "workspace:*"
+ "@openremote/util": "workspace:*"
+ echarts: "npm:~5.6.0"
+ lit: "npm:^3.3.1"
+ moment: "npm:^2.29.4"
+ languageName: unknown
+ linkType: soft
+
"@openremote/or-attribute-card@workspace:*, @openremote/or-attribute-card@workspace:ui/component/or-attribute-card":
version: 0.0.0-use.local
resolution: "@openremote/or-attribute-card@workspace:ui/component/or-attribute-card"
@@ -6321,6 +6353,17 @@ __metadata:
languageName: node
linkType: hard
+"lit-element@npm:^4.2.0":
+ version: 4.2.1
+ resolution: "lit-element@npm:4.2.1"
+ dependencies:
+ "@lit-labs/ssr-dom-shim": "npm:^1.4.0"
+ "@lit/reactive-element": "npm:^2.1.0"
+ lit-html: "npm:^3.3.0"
+ checksum: 10c0/2cb30cc7c5a006cd7995f882c5e9ed201638dc3513fdee989dd7b78d8ceb201cf6930abe5ebc5185d7fc3648933a6b6187742d5534269961cd20b9a78617068d
+ languageName: node
+ linkType: hard
+
"lit-html@npm:^2.8.0":
version: 2.8.0
resolution: "lit-html@npm:2.8.0"
@@ -6339,6 +6382,15 @@ __metadata:
languageName: node
linkType: hard
+"lit-html@npm:^3.3.0":
+ version: 3.3.1
+ resolution: "lit-html@npm:3.3.1"
+ dependencies:
+ "@types/trusted-types": "npm:^2.0.2"
+ checksum: 10c0/0dfb645f35c2ae129a40c09550b4d0e60617b715af7f2e0b825cdfd0624118fc4bf16e9cfaabdfbe43469522e145057d3cc46c64ca1019681480e4b9ae8f52cd
+ languageName: node
+ linkType: hard
+
"lit@npm:^2.0.2":
version: 2.8.0
resolution: "lit@npm:2.8.0"
@@ -6361,6 +6413,17 @@ __metadata:
languageName: node
linkType: hard
+"lit@npm:^3.3.1":
+ version: 3.3.1
+ resolution: "lit@npm:3.3.1"
+ dependencies:
+ "@lit/reactive-element": "npm:^2.1.0"
+ lit-element: "npm:^4.2.0"
+ lit-html: "npm:^3.3.0"
+ checksum: 10c0/9f3e171e211be7cd3e01693eac4ba4752fc7bafebc8298fc5b9cb70ff279dd4dc292f1cb425ca42f61c3767a75b7557295c2f6b16335719bc8cf1ca6f3622fb7
+ languageName: node
+ linkType: hard
+
"loader-runner@npm:^4.2.0":
version: 4.3.0
resolution: "loader-runner@npm:4.3.0"