Skip to content

armgit / core

Public Imported from GitHub
0

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

Rules page Feature: Time condition (#792)

Martin Peeters29ef10b32bb5
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index b03030fe0..f787044ab 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -46,8 +46,6 @@ import org.openremote.model.value.MetaItemType;
import org.quartz.CronExpression;
import org.shredzone.commons.suncalc.SunTimes;
-import java.time.Duration;
-import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
@@ -126,12 +124,13 @@ public class JsonRulesBuilder extends RulesBuilder {
} else if (!TextUtil.isNullOrEmpty(ruleCondition.cron)) {
try {
CronExpression timerExpression = new CronExpression(ruleCondition.cron);
+ timerExpression.setTimeZone(TimeZone.getTimeZone("UTC"));
AtomicLong nextExecuteMillis = new AtomicLong(timerExpression.getNextValidTimeAfter(new Date(timerService.getCurrentTimeMillis())).getTime());
timePredicate = (time) -> {
long nextExecute = nextExecuteMillis.get();
if (time >= nextExecute) {
- nextExecuteMillis.set(timerExpression.getNextInvalidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecute))).getTime());
+ nextExecuteMillis.set(timerExpression.getNextValidTimeAfter(timerExpression.getNextInvalidTimeAfter(new Date(nextExecute))).getTime());
return true;
}
return false;
@@ -146,7 +145,12 @@ public class JsonRulesBuilder extends RulesBuilder {
// Calculate the next occurrence
AtomicReference<SunTimes> sunTimes = new AtomicReference<>(sunCalculator.execute());
- ZonedDateTime occurrence = ruleCondition.sun.getPosition() == SunPositionTrigger.Position.SUNSET ? sunTimes.get().getSet() : sunTimes.get().getRise();
+ ZonedDateTime occurrence;
+ if(ruleCondition.sun.getPosition() == SunPositionTrigger.Position.SUNRISE || ruleCondition.sun.getPosition().toString().startsWith(SunPositionTrigger.MORNING_TWILIGHT_PREFIX)) {
+ occurrence = sunTimes.get().getRise();
+ } else {
+ occurrence = sunTimes.get().getSet();
+ }
if (occurrence == null) {
Exception e = new IllegalStateException("Rule condition requested sun position never occurs at the specified location: " + ruleCondition.sun);
@@ -1150,7 +1154,7 @@ public class JsonRulesBuilder extends RulesBuilder {
SunTimes.Twilight twilight = null;
if (position.name().startsWith(SunPositionTrigger.TWILIGHT_PREFIX)) {
- String lookupValue = position.name().substring(SunPositionTrigger.TWILIGHT_PREFIX.length());
+ String lookupValue = position.name().replace(SunPositionTrigger.MORNING_TWILIGHT_PREFIX, "").replace(SunPositionTrigger.EVENING_TWILIGHT_PREFIX, "").replace(SunPositionTrigger.TWILIGHT_PREFIX, "");
twilight = EnumUtil.enumFromString(SunTimes.Twilight.class, lookupValue).orElseThrow(() -> {
IllegalStateException e = new IllegalStateException("Rule condition un-supported twilight position value '" + lookupValue + "'");
log(Level.SEVERE, e.getMessage(), e);
@@ -1159,9 +1163,9 @@ public class JsonRulesBuilder extends RulesBuilder {
}
SunTimes.Parameters sunCalculator = SunTimes.compute()
- .at(location.getY(), location.getX())
- .utc()
- .on(timerService.getNow());
+ .on(timerService.getNow())
+ .utc()
+ .at(location.getX(), location.getY());
if (twilight != null) {
sunCalculator.twilight(twilight);
diff --git a/manager/src/web/shared/locales/ar/or.json b/manager/src/web/shared/locales/ar/or.json
index 800728774..f90a69d6c 100644
--- a/manager/src/web/shared/locales/ar/or.json
+++ b/manager/src/web/shared/locales/ar/or.json
@@ -74,7 +74,6 @@
"then": "إذن",
"orWhen": "أو عندما",
"datetime": "حذف التوقيت",
- "timer": "المؤقت",
"rulesEditorAddCondition": "أضف شرط آخر",
"rulesEditorAddGroup": "إضافة مجموعة",
"rulesEditorAddAction": "إضافة فعل",
diff --git a/manager/src/web/shared/locales/cn/or.json b/manager/src/web/shared/locales/cn/or.json
index 066434092..4a454e489 100644
--- a/manager/src/web/shared/locales/cn/or.json
+++ b/manager/src/web/shared/locales/cn/or.json
@@ -74,7 +74,6 @@
"then": "则",
"orWhen": "或当",
"datetime": "时间",
- "timer": "计时器",
"rulesEditorAddCondition": "添加另一个条件",
"rulesEditorAddGroup": "添加组",
"rulesEditorAddAction": "添加动作",
diff --git a/manager/src/web/shared/locales/de/or.json b/manager/src/web/shared/locales/de/or.json
index 58ae71d75..06b133395 100644
--- a/manager/src/web/shared/locales/de/or.json
+++ b/manager/src/web/shared/locales/de/or.json
@@ -82,7 +82,6 @@
"then": "Dann",
"orWhen": "Oder wenn",
"datetime": "Datum und Zeit",
- "timer": "Timer",
"rulesEditorAddCondition": "Bedingung hinzufügen",
"rulesEditorAddGroup": "Gruppe hinzufügen",
"rulesEditorAddAction": "Aktion hinzufügen",
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 301237ae7..d8ce024f4 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -73,6 +73,7 @@
"lengthLessThan": "Array length less than",
"valueChanges": "Value changes",
"save": "Save",
+ "close": "Close",
"active": "Active",
"deleteRulesetsConfirm": "Remove ruleset(s)?",
"deleteRulesetsFailed": "Failed to delete one or more requested rulesets(s)",
@@ -82,7 +83,15 @@
"then": "Then",
"orWhen": "Or when",
"datetime": "Datetime",
- "timer": "Timer",
+ "time": "Time",
+ "pickLocation": "Pick a location",
+ "triggerType": "Trigger Type",
+ "timeOfDay": "Time of Day",
+ "offsetInMinutes": "Offset in minutes",
+ "sunrise": "Sunrise",
+ "sunset": "Sunset",
+ "twilight_morning_civil": "Morning twilight",
+ "twilight_evening_civil": "Evening twilight",
"rulesEditorAddCondition": "Add condition",
"rulesEditorAddGroup": "Add group",
"rulesEditorAddAction": "Add action",
@@ -415,8 +424,8 @@
"allDay": "All day",
"apply": "apply",
"to": "to",
- "from": "from",
- "never": "Never",
+ "from": "from",
+ "never": "Never",
"repetitionEnds": "Repetition ends",
"repeatOccurrenceEvery": "Repeat occurrence every",
"daysOfTheWeek": "days of the week",
diff --git a/manager/src/web/shared/locales/es/or.json b/manager/src/web/shared/locales/es/or.json
index 1424fce40..d3651683a 100644
--- a/manager/src/web/shared/locales/es/or.json
+++ b/manager/src/web/shared/locales/es/or.json
@@ -74,7 +74,6 @@
"then": "Entonces",
"orWhen": "O cuando",
"datetime": "Fecha y hora",
- "timer": "Timer",
"rulesEditorAddCondition": "Añadir condición",
"rulesEditorAddGroup": "Añadir grupo",
"rulesEditorAddAction": "Añadir acción",
diff --git a/manager/src/web/shared/locales/fr/or.json b/manager/src/web/shared/locales/fr/or.json
index b9c7b0e65..1b4313582 100644
--- a/manager/src/web/shared/locales/fr/or.json
+++ b/manager/src/web/shared/locales/fr/or.json
@@ -74,7 +74,6 @@
"then": "Alors",
"orWhen": "Ou quand",
"datetime": "Date et heure",
- "timer": "Minuteur",
"rulesEditorAddCondition": "Ajouter une condition",
"rulesEditorAddGroup": "Ajouter un groupe",
"rulesEditorAddAction": "Ajouter une action",
diff --git a/manager/src/web/shared/locales/it/or.json b/manager/src/web/shared/locales/it/or.json
index 1bedefb80..06ed51372 100644
--- a/manager/src/web/shared/locales/it/or.json
+++ b/manager/src/web/shared/locales/it/or.json
@@ -74,7 +74,6 @@
"then": "Poi",
"orWhen": "O quando",
"datetime": "Datetime",
- "timer": "Timer",
"rulesEditorAddCondition": "Aggiungi un'altra condizione",
"rulesEditorAddGroup": "Aggiungi gruppo",
"rulesEditorAddAction": "Aggiungi azione",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index ee9b7f029..88a82f9ea 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -73,6 +73,7 @@
"lengthLessThan": "Aantal elementen kleiner dan",
"valueChanges": "Waarde verandert",
"save": "Opslaan",
+ "close": "Sluiten",
"active": "Actief",
"deleteRulesetsConfirm": "Regels verwijderen?",
"deleteRulesetsFailed": "Het verwijderen van een of meerdere regels is niet geukt",
@@ -82,7 +83,15 @@
"then": "Dan",
"orWhen": "Of als",
"datetime": "Datum en tijd",
- "timer": "Timer",
+ "time": "Tijd",
+ "pickLocation": "Kies een locatie",
+ "triggerType": "Trigger Type",
+ "timeOfDay": "Tijdstip",
+ "offsetInMinutes": "Afwijking in minuten",
+ "sunrise": "Zonsopgang",
+ "sunset": "Zonsondergang",
+ "twilight_morning_civil": "Ochtendschemering",
+ "twilight_evening_civil": "Avondschemering",
"rulesEditorAddCondition": "Voeg voorwaarde toe",
"rulesEditorAddGroup": "Groep",
"rulesEditorAddAction": "Voeg actie toe",
diff --git a/manager/src/web/shared/locales/pt/or.json b/manager/src/web/shared/locales/pt/or.json
index 586083159..13f50589b 100644
--- a/manager/src/web/shared/locales/pt/or.json
+++ b/manager/src/web/shared/locales/pt/or.json
@@ -74,7 +74,6 @@
"then": "Então",
"orWhen": "Ou quando",
"datetime": "Data hora",
- "timer": "Timer",
"rulesEditorAddCondition": "Adicionar outra condição",
"rulesEditorAddGroup": "Adicionar grupo",
"rulesEditorAddAction": "Adicionar ação",
diff --git a/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java b/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java
index f88ebc0fc..c11be2fba 100644
--- a/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java
+++ b/model/src/main/java/org/openremote/model/rules/SunPositionTrigger.java
@@ -25,6 +25,8 @@ import org.openremote.model.geo.GeoJSONPoint;
public class SunPositionTrigger {
public static final String TWILIGHT_PREFIX = "TWILIGHT_";
+ public static final String MORNING_TWILIGHT_PREFIX = "TWILIGHT_MORNING_";
+ public static final String EVENING_TWILIGHT_PREFIX = "TWILIGHT_EVENING_";
/**
* The astronomical position of the sun
@@ -32,15 +34,24 @@ public class SunPositionTrigger {
public enum Position {
SUNRISE,
SUNSET,
- TWILIGHT_VISUAL,
- TWILIGHT_VISUAL_LOWER,
- TWILIGHT_HORIZON,
- TWILIGHT_CIVIL,
- TWILIGHT_NAUTICAL,
- TWILIGHT_ASTRONOMICAL,
- TWILIGHT_GOLDEN_HOUR,
- TWILIGHT_BLUE_HOUR,
- TWILIGHT_NIGHT_HOUR
+ TWILIGHT_MORNING_VISUAL,
+ TWILIGHT_MORNING_VISUAL_LOWER,
+ TWILIGHT_MORNING_HORIZON,
+ TWILIGHT_MORNING_CIVIL,
+ TWILIGHT_MORNING_NAUTICAL,
+ TWILIGHT_MORNING_ASTRONOMICAL,
+ TWILIGHT_MORNING_GOLDEN_HOUR,
+ TWILIGHT_MORNING_BLUE_HOUR,
+ TWILIGHT_MORNING_NIGHT_HOUR,
+ TWILIGHT_EVENING_VISUAL,
+ TWILIGHT_EVENING_VISUAL_LOWER,
+ TWILIGHT_EVENING_HORIZON,
+ TWILIGHT_EVENING_CIVIL,
+ TWILIGHT_EVENING_NAUTICAL,
+ TWILIGHT_EVENING_ASTRONOMICAL,
+ TWILIGHT_EVENING_GOLDEN_HOUR,
+ TWILIGHT_EVENING_BLUE_HOUR,
+ TWILIGHT_EVENING_NIGHT_HOUR,
}
Position position;
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
index 5c5127162..e53e58190 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
@@ -26,7 +26,7 @@ import org.openremote.model.rules.SunPositionTrigger;
* Consists of one of the following triggers in order of precedence:
* <ol>
* <li>{@link #duration} - ISO8601 duration expression (e.g. 'PT1H') after which the condition becomes true - 1min precision</li>
- * <li>{@link #cron} - CRON expression (e.g. "*&#47;5 * * * *") at which time the condition becomes true - 1min precision</li>
+ * <li>{@link #cron} - CRON expression (e.g. "*&#47;5 * * * *") in UTC at which time the condition becomes true - 1min precision</li>
* <li>{@link #sun} - {@link SunPositionTrigger} at which time the condition becomes true - 1min precision</li>
* <li>{@link #assets} - {@link AssetQuery} to be applied to the {@link org.openremote.model.rules.AssetState}s
* available within the rule engine this rule is loaded into. Evaluates to true when one or more
@@ -45,7 +45,7 @@ public class RuleCondition {
public String duration;
/**
- * CRON expression (e.g. *&#47;5 * * * *)
+ * CRON expression in UTC (e.g. *&#47;5 * * * *)
*/
public String cron;
diff --git a/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json b/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json
index b545c19d0..4accd8ef4 100644
--- a/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json
+++ b/test/src/test/resources/org/openremote/test/rules/JsonRuleTwilight.json
@@ -10,7 +10,7 @@
"items": [
{
"sun": {
- "position": "TWILIGHT_HORIZON",
+ "position": "TWILIGHT_MORNING_HORIZON",
"location": {
"type": "Point",
"coordinates": [0,0]
diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.ts
index df8a24eba..6e8fd9a33 100644
--- a/ui/component/core/src/util.ts
+++ b/ui/component/core/src/util.ts
@@ -393,6 +393,106 @@ export function getWeekNumber(date: Date): number {
return weekNo;
}
+
+
+const monthNames = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
+
+/* Creates a cron string based on the input parameters.
+* You can for example trigger an expression once a month on friday, or on a specific date ass March 1st.
+*
+* Useful URLs for understanding cron:
+* - https://en.wikipedia.org/wiki/Cron
+* - https://www.freeformatter.com/cron-expression-generator-quartz.html
+*
+* @param years What years it should trigger. For example ['2022','2023'] or a string to inject.
+* @param months What months of the year it should trigger. For example ['JAN','FEB'] or [0,1,2,3,4,5] or a string to inject.
+* @param days What days of the month it should trigger. For example [7,14,21,28] or a string to inject.
+* @param hours What hours of the day it should trigger. For example [3,6,9,12,15,18,21] or a string to inject.
+* @param minutes What minutes of the hour it should trigger. For example [0,15,30,45] or a string to inject.
+* @param seconds What seconds of the minute it should trigger. For example [0,15,30,45] or a string to inject.
+* @param daysOfTheWeek String to inject for specifying specific days such as '1st monday of the month'.
+* */
+export function formatCronString(years?: string | number | string[], months?: string | string[] | number[], days?: string | number[], hours?: string | number[], minutes?: string | number[], seconds?: string | number[], daysOfTheWeek?: string): string {
+ let cron = "";
+ if(seconds) {
+ if(Array.isArray(seconds)) { cron += (seconds.toString().replace(" ", "")); }
+ else { cron += seconds.toString(); }
+ } else { cron += "0"}
+ cron += " ";
+ if(minutes) {
+ if(Array.isArray(minutes)) { cron += (minutes.toString().replace(" ", "")); }
+ else { cron += minutes.toString(); }
+ } else { cron += "0"}
+ cron += " ";
+ if(hours) {
+ if(Array.isArray(hours)) { cron += (hours.toString().replace(" ", "")); }
+ else { cron += hours.toString(); }
+ } else { cron += "0"}
+ cron += " "
+ if(days) {
+ if(Array.isArray(days)) { cron += (days.toString().replace(" ", "")); }
+ else { cron += days.toString(); }
+ } else { cron += "*"}
+ cron += " ";
+ if(months) {
+ if(Array.isArray(months)) {
+ if(typeof months[0] == 'number') {
+ const monthStrings: string[] = [];
+ months.forEach(month => { monthStrings.push(monthNames[month as number].toString()); })
+ cron += (monthStrings.toString().replace(" ", ""));
+ } else {
+ cron += (months.toString().replace(" ", ""));
+ }
+ }
+ else { cron += months.toString(); }
+ } else { cron += "*"}
+ cron += " ";
+ if(daysOfTheWeek) { cron += daysOfTheWeek.toString(); }
+ else { cron += "?" }
+ cron += " ";
+ if(years) {
+ if (Array.isArray(years)) { cron += (years.toString().replace(" ", "")); }
+ else { cron += years; }
+ } else { cron += "*"}
+ return cron;
+}
+/* Transforms an JS date to a cron string, to trigger ONCE A YEAR on that specific date */
+export function dateToCronString(date: Date): string {
+ return formatCronString(date.getFullYear(), monthNames[date.getMonth()], [date.getDate()], [date.getHours()], [date.getMinutes()]);
+}
+/*
+* Transforms a cron expression string into an ISO String.
+* Input for example would be `0 00 11 * * ? *` for every day at 11am.
+* If the input is '*', it will be replaced by 1. (month parameter of '*' becomes January)
+*/
+export function cronStringToISOString(cronString: String, isUTC: boolean): string | undefined {
+ const splStr = cronString.split(" ");
+ if(!Number.isNaN(Number(splStr[0])) && !Number.isNaN(Number(splStr[1])) && !Number.isNaN(Number(splStr[2])) && (!Number.isNaN(Number(splStr[3])) || splStr[3] == '*')) {
+ const year: string = (!Number.isNaN(Number(splStr[6])) ? splStr[6] : new Date().getFullYear()).toString();
+ let month: string = "";
+ if(splStr[4] != '*') {
+ month = monthNames.indexOf(splStr[4]).toString();
+ } else {
+ month = new Date().getMonth().toString();
+ }
+ month = (month.length == 1 ? ("0" + month) : month);
+ const date: string = ((splStr[3].length == 1 && splStr[3] != '*') ? ("0" + splStr[3]) : splStr[3].replace('*', '01'));
+ const hour: string = ((splStr[2].length == 1 && splStr[2] != '*') ? ("0" + splStr[2]) : splStr[2].replace('*', '00'));
+ const minute: string = ((splStr[1].length == 1 && splStr[1] != '*') ? ("0" + splStr[1]) : splStr[1].replace('*', '00'));
+ const second: string = ((splStr[0].length == 1 && splStr[0] != '*') ? ("0" + splStr[0]) : splStr[0].replace('*', '00'));
+ if(year.length > 0 && month.length > 0) {
+ if(isUTC) {
+ return moment.utc({year: Number(year), month: Number(month), date: Number(date), hour: Number(hour), minute: Number(minute), second: Number(second)}).toISOString();
+ } else {
+ return moment({year: Number(year), month: Number(month), date: Number(date), hour: Number(hour), minute: Number(minute), second: Number(second)}).toISOString();
+ }
+ }
+ }
+ return undefined;
+}
+
+
+
export function getMetaValue(name: string | NameHolder, attribute: Attribute<any> | undefined, descriptor?: ValueDescriptorHolder | ValueDescriptor | string): any | undefined {
const metaName = typeof name === "string" ? name : (name as NameHolder).name!;
@@ -727,7 +827,7 @@ function getValueFormatConstraintOrUnits<T>(lookup: WellknownMetaItems.FORMAT |
let matched: T | undefined;
const formats: ValueFormat[] = [];
-
+
const name = nameValueHolder && typeof nameValueHolder === "string" ? nameValueHolder : nameValueHolder ? (nameValueHolder as NameHolder).name : descriptor ? typeof (descriptor) === "string" ? descriptor : descriptor.name : undefined;
const str = doStandardTranslationLookup(lookup, name, descriptor, assetType, isAttribute);
if (str) {
@@ -776,12 +876,12 @@ function getValueFormatConstraintOrUnits<T>(lookup: WellknownMetaItems.FORMAT |
if (lookup !== WellknownMetaItems.FORMAT || formats.length === 0) {
return matched;
}
-
+
let mergedFormat: ValueFormat = {};
formats.reverse().forEach((format) => {
mergedFormat = {...mergedFormat,...format};
})
-
+
return mergedFormat as T;
}
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index bbec4b56a..6bbcacc9b 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -45,7 +45,7 @@ export {buttonStyle} from "./style";
export const enum ConditionType {
AGENT_QUERY = "agentQuery",
ASSET_QUERY = "assetQuery",
- DURATION = "duration"
+ TIME = "time"
}
export const enum ActionType {
@@ -54,7 +54,9 @@ export const enum ActionType {
PUSH_NOTIFICATION = "push",
ATTRIBUTE = "attribute"
}
-
+export enum TimeTriggerType {
+ TIME_OF_DAY = "TIME_OF_DAY"
+}
export enum AssetQueryOperator {
VALUE_EMPTY = "empty",
VALUE_NOT_EMPTY = "notEmpty",
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-condition.ts b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
index b223f3398..2b58e4e63 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
@@ -3,6 +3,7 @@ import {customElement, property, query} from "lit/decorators.js";
import {AssetTypeInfo, RuleCondition, WellknownAssets, AssetModelUtil} from "@openremote/model";
import {ConditionType, getAssetTypeFromQuery, RulesConfig} from "../index";
import "./or-rule-asset-query";
+import "./or-rule-trigger-query";
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";
@@ -26,7 +27,7 @@ export function getWhenTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInf
if (config && config.controls && config.controls.allowedConditionTypes) {
addAssetTypes = config.controls.allowedConditionTypes.indexOf(ConditionType.ASSET_QUERY) >= 0;
addAgentTypes = config.controls.allowedConditionTypes.indexOf(ConditionType.AGENT_QUERY) >= 0;
- addTimer = config.controls.allowedConditionTypes.indexOf(ConditionType.DURATION) >= 0;
+ addTimer = config.controls.allowedConditionTypes.indexOf(ConditionType.TIME) >= 0;
}
const menu: (ListItem | null)[] = [];
@@ -75,10 +76,11 @@ export function getWhenTypesMenu(config?: RulesConfig, assetInfos?: AssetTypeInf
}
if (addTimer) {
+ menu.push(null);
menu.push({
- text: i18next.t("timer"),
+ text: i18next.t("time"),
icon: "timer",
- value: ConditionType.DURATION,
+ value: ConditionType.TIME,
styleMap: {"--or-icon-fill": "#" + TIMER_COLOR}
} as ListItem);
}
@@ -90,12 +92,14 @@ export function updateRuleConditionType(ruleCondition: RuleCondition, value: str
if (!value) {
ruleCondition.assets = undefined;
- ruleCondition.duration = undefined;
- } else if (value === ConditionType.DURATION) {
+ ruleCondition.cron = undefined;
+ ruleCondition.sun = undefined;
+ } else if (value === ConditionType.TIME) {
ruleCondition.assets = undefined;
- ruleCondition.duration = "1h";
+ const date = new Date();
+ ruleCondition.cron = Util.formatCronString(undefined, undefined, undefined, date.getUTCHours().toString(), date.getUTCMinutes().toString());
} else {
- ruleCondition.duration = undefined;
+ ruleCondition.cron = undefined;
if (config && config.json && config.json.whenAssetQuery) {
ruleCondition.assets = JSON.parse(JSON.stringify(config.json.whenAssetQuery));
@@ -158,13 +162,13 @@ class OrRuleCondition extends translate(i18next)(LitElement) {
let template: TemplateResult | string = ``;
if (showTypeSelect) {
-
+
let buttonIcon;
let buttonColor = "inherit";
if (type) {
switch (type) {
- case ConditionType.DURATION:
+ case ConditionType.TIME:
buttonIcon = "timer";
buttonColor = TIMER_COLOR;
break;
@@ -192,13 +196,13 @@ class OrRuleCondition extends translate(i18next)(LitElement) {
</div>
`;
}
-
+
}
-
+
if (type) {
switch (type) {
- case ConditionType.DURATION:
- template = html`<span>TIMER NOT IMPLEMENTED</span>`;
+ case ConditionType.TIME:
+ template = html`<or-rule-trigger-query id="asset-query" .condition="${this.ruleCondition}"></or-rule-trigger-query>`;
break;
default:
template = html`<or-rule-asset-query id="asset-query" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}" .condition="${this.ruleCondition}"></or-rule-asset-query>`;
@@ -219,8 +223,8 @@ class OrRuleCondition extends translate(i18next)(LitElement) {
return assetType;
}
- if (this.ruleCondition.duration) {
- return ConditionType.DURATION;
+ if (this.ruleCondition.cron || this.ruleCondition.sun) {
+ return ConditionType.TIME;
}
}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
index b02105e48..0aac905c0 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
@@ -273,11 +273,15 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
if (group.items) {
for (const condition of group.items) {
- if (!condition.assets && !condition.duration) {
+ if (!condition.assets && !condition.cron && !condition.sun) {
return false;
}
- if (condition.duration && !Util.isTimeDuration(condition.duration)) {
+ if(condition.cron && !Util.cronStringToISOString(condition.cron, true)) {
+ return false;
+ }
+
+ if(condition.sun && (!condition.sun.position || !condition.sun.location)) {
return false;
}
@@ -344,7 +348,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
if (!target) {
return true;
}
-
+
if (target.assets) {
return this._validateAssetQuery(target.assets, false, false);
}
@@ -352,7 +356,7 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
if (target.matchedAssets) {
return this._validateAssetQuery(target.matchedAssets, false, true);
}
-
+
if (target.conditionAssets && getTypeAndTagsFromGroup(rule.when!).findIndex((typeAndTag) => target.conditionAssets === typeAndTag[1]) < 0) {
return false;
}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-trigger-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-trigger-query.ts
new file mode 100644
index 000000000..c2edecd7c
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/or-rule-trigger-query.ts
@@ -0,0 +1,242 @@
+import {GeoJSONPoint, RuleCondition, SunPositionTriggerPosition} from "@openremote/model";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {css, html, LitElement, PropertyValues} from "lit";
+import {customElement, property, state} from "lit/decorators.js";
+import moment from "moment";
+import {buttonStyle} from "../style";
+import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
+import {TimeTriggerType} from "../index";
+import {Util} from "@openremote/core";
+import {DialogAction, OrMwcDialog, OrMwcDialogOpenedEvent} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {OrMap, OrMapClickedEvent} from "@openremote/or-map";
+import {i18next} from "@openremote/or-translate";
+
+// language=CSS
+const style = css`
+
+ ${buttonStyle}
+
+ :host {
+ display: block;
+ }
+
+ .trigger-group {
+ flex-grow: 1;
+ display: flex;
+ align-items: center;
+ flex-direction: row;
+ flex-wrap: wrap;
+ }
+ .min-width {
+ min-width: 200px;
+ }
+ .width {
+ width: 200px;
+ }
+
+ .trigger-group > * {
+ margin: 10px 3px 6px 3px;
+ }
+`;
+
+interface TimeTrigger {
+ key: TimeTriggerType | SunPositionTriggerPosition,
+ value: string
+}
+
+@customElement("or-rule-trigger-query")
+export class OrRuleTriggerQuery extends LitElement {
+
+ static get styles() {
+ return style;
+ }
+
+ @property({type: Object, attribute: false})
+ public condition!: RuleCondition;
+
+ @property()
+ public readonly: boolean = false;
+
+ /* ---------- */
+
+ @state()
+ protected selectedTrigger: TimeTrigger;
+
+ @state()
+ protected triggerOptions: TimeTrigger[];
+
+ constructor() {
+ super();
+ this.triggerOptions = [];
+ Object.values(TimeTriggerType).forEach((type) => { this.triggerOptions.push({ key: type, value: this.triggerToString(type)}); });
+ this.getSunPositions().forEach((opt) => { this.triggerOptions.push({ key: opt, value: this.triggerToString(opt)}); });
+ this.selectedTrigger = this.triggerOptions[0];
+
+ this.addEventListener(OrMwcDialogOpenedEvent.NAME, this.initMap);
+ }
+
+ updated(changedProperties: PropertyValues) {
+ if(changedProperties.has('condition')) {
+ if(this.condition.cron) { this.selectedTrigger = { key: TimeTriggerType.TIME_OF_DAY, value: this.triggerToString(TimeTriggerType.TIME_OF_DAY) }}
+ else if(this.condition.sun) { this.selectedTrigger = { key: this.condition.sun.position!, value: this.triggerToString(this.condition.sun.position!) }}
+ }
+ }
+
+ /* ---------------------- */
+
+ initMap() {
+ const modal = this.shadowRoot!.getElementById('map-modal');
+ if (!modal) return;
+
+ const map = modal.shadowRoot!.querySelector('.or-map') as OrMap;
+ if (map) {
+ map.addEventListener(OrMapClickedEvent.NAME, (evt: CustomEvent) => {
+ const lngLat: any = evt.detail.lngLat;
+ this.setLocation({ type: 'Point', coordinates: [lngLat.lat, lngLat.lng] });
+ const latElement = modal.shadowRoot!.querySelector('.location-lat') as HTMLInputElement;
+ const lngElement = modal.shadowRoot!.querySelector('.location-lng') as HTMLInputElement;
+ latElement.value = lngLat.lat;
+ lngElement.value = lngLat.lng;
+ });
+ }
+ }
+
+ renderDialogHTML(point: GeoJSONPoint | undefined) {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("map-modal") as OrMwcDialog;
+ if (dialog) {
+ dialog.content = html`
+ <div style="display:grid">
+ <or-map class="or-map" type="VECTOR" style="border: 1px solid #d5d5d5; height: 400px; min-width: 300px; margin-bottom: 20px;">
+ ${(point && point.coordinates) ? html`
+ <or-map-marker class="or-map-marker" active color="#FF0000" icon="white-balance-sunny" lat="${point.coordinates[0]}" lng="${point.coordinates[1]}"></or-map-marker>
+ `: undefined}
+ </or-map>
+ <div class="layout horizontal">
+ <input hidden class="location-lng" required placeholder=" " type="text" .value="${point && point.coordinates ? point.coordinates[0] : null}" />
+ <input hidden class="location-lat" required placeholder=" " type="text" .value="${point && point.coordinates ? point.coordinates[1] : null}" />
+ </div>
+ </div>
+ `;
+ }
+ }
+
+
+
+ /* ----------------------------- */
+
+ render() {
+ const modalActions: DialogAction[] = [
+ { actionName: "close", default: true, content: html`<or-mwc-input class="button" .type="${InputType.BUTTON}" label="${i18next.t('close')}"></or-mwc-input>`, action: () => {} }
+ ];
+ const onMapModalOpen = () => {
+ const dialog: OrMwcDialog = this.shadowRoot!.getElementById("map-modal") as OrMwcDialog;
+ if(dialog) {
+ dialog.dismissAction = null;
+ dialog.open();
+ this.renderDialogHTML(this.condition.sun?.location)
+ }
+ }
+ // Render dialog on every update (for example when changing location in the modal itself)
+ this.renderDialogHTML(this.condition.sun?.location);
+
+ return html`
+ <div class="trigger-group">
+ <or-mwc-input class="min-width" type="${InputType.SELECT}" .options="${this.triggerOptions.map((t) => t.value)}" .value="${this.selectedTrigger.value}" label="${i18next.t('triggerType')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => { this.setTrigger(this.triggerOptions.find((t) => t.value == ev.detail.value)!); }}">
+ </or-mwc-input>
+ ${this.selectedTrigger ? html`
+ ${this.selectedTrigger.key == this.triggerOptions[0].key ? html`
+ <or-mwc-input class="min-width" type="${InputType.TIME}" .value="${(this.condition.cron ? moment(Util.cronStringToISOString(this.condition.cron, true)).format('HH:mm') : undefined)}" label="${i18next.t('timeOfDay')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => { this.setTime(ev.detail.value) }}">
+ </or-mwc-input>
+ ` : html`
+ <or-mwc-input class="min-width width" type="${InputType.NUMBER}" .value="${this.condition.sun?.offsetMins}" label="${i18next.t('offsetInMinutes')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => { this.setOffset(ev.detail.value) }}">
+ </or-mwc-input>
+ <or-mwc-input type="${InputType.BUTTON}" class="min-width" @or-mwc-input-changed="${onMapModalOpen}" label="${i18next.t('location')}"></or-mwc-input>
+ <or-mwc-dialog id="map-modal" heading="${i18next.t('pickLocation')}" .actions="${modalActions}"></or-mwc-dialog>
+ `}
+ ` : undefined}
+ </div>
+ `
+ }
+
+
+
+
+
+
+ /* ---------------------------------------------------- */
+
+
+ // Getters/setters of the file
+
+ setTrigger(trigger: TimeTrigger) {
+ if(trigger) {
+ if(trigger.key == TimeTriggerType.TIME_OF_DAY) {
+ this.condition.sun = undefined;
+ } else if(this.getSunPositions().includes(trigger.key)) {
+ this.condition.cron = undefined;
+ if(this.getSunPositions().includes(this.selectedTrigger.key as SunPositionTriggerPosition)) {
+ this.condition.sun = { position: trigger.key, offsetMins: this.condition.sun!.offsetMins, location: this.condition.sun!.location };
+ } else {
+ this.condition.sun = { position: trigger.key, offsetMins: 0 };
+ }
+ }
+ this.selectedTrigger = trigger;
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+ }
+ setTime(time: string) {
+ if(time) {
+ const splittedTime = time.split(':');
+ const date = new Date();
+ date.setHours(Number(splittedTime[0]));
+ date.setMinutes(Number(splittedTime[1]));
+ this.condition.cron = Util.formatCronString(undefined, undefined, undefined, date.getUTCHours().toString(), date.getUTCMinutes().toString());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+ }
+ setOffset(offset: number) {
+ this.condition.sun = {
+ position: this.condition.sun?.position,
+ location: this.condition.sun?.location,
+ offsetMins: offset
+ }
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+ setLocation(point: GeoJSONPoint) {
+ this.condition.sun = {
+ position: this.condition.sun?.position,
+ location: point,
+ offsetMins: this.condition.sun?.offsetMins
+ }
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
+ this.requestUpdate();
+ }
+
+ getSunPositions(): SunPositionTriggerPosition[] {
+ return [
+ SunPositionTriggerPosition.TWILIGHT_MORNING_CIVIL,
+ SunPositionTriggerPosition.SUNRISE, SunPositionTriggerPosition.SUNSET,
+ SunPositionTriggerPosition.TWILIGHT_EVENING_CIVIL
+ ];
+ }
+
+
+
+
+ /* --------------------------------- */
+
+ // Utility stuff
+
+ triggerToString(position: TimeTriggerType | SunPositionTriggerPosition): string {
+ if(position == TimeTriggerType.TIME_OF_DAY) { return i18next.t("timeOfDay"); }
+ else {
+ return i18next.t(position.toLowerCase());
+ }
+ }
+}