diff --git a/ui/.eslintrc.json b/ui/.eslintrc.json index c0fa15fbf26..6d53fb393b4 100644 --- a/ui/.eslintrc.json +++ b/ui/.eslintrc.json @@ -8,6 +8,11 @@ "files": [ "*.ts" ], + "env": { + "browser": true, + "node": true, + "jest": true + }, "parserOptions": { "project": [ "tsconfig.json" @@ -18,6 +23,8 @@ "unused-imports" ], "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", "plugin:@angular-eslint/recommended", "plugin:@angular-eslint/template/process-inline-templates" ], @@ -65,7 +72,26 @@ "error", "always" ], - "no-trailing-spaces": "error" + "no-trailing-spaces": "error", + "@typescript-eslint/no-unused-vars": [ + "error", + { + "args": "none" + } + ], + "@typescript-eslint/no-explicit-any": 0, + "@typescript-eslint/no-namespace": 0, + "@typescript-eslint/ban-types": [ + "error", + { + "extendDefaults": true, + "types": { + "{}": false, + "Object": false, + "Function": false + } + } + ] } }, { diff --git a/ui/package-lock.json b/ui/package-lock.json index 8c30370b73e..cef3d63ec97 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -2765,54 +2765,6 @@ "node": ">=16" } }, - "node_modules/@esbuild/android-arm": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.8.tgz", - "integrity": "sha512-0/rb91GYKhrtbeglJXOhAv9RuYimgI8h623TplY2X+vA4EXnk3Zj1fXZreJ0J3OJJu1bwmb0W7g+2cT/d8/l/w==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.8.tgz", - "integrity": "sha512-oa/N5j6v1svZQs7EIRPqR8f+Bf8g6HBDjD/xHC02radE/NjKHK7oQmtmLxPs1iVwYyvE+Kolo6lbpfEQ9xnhxQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.8.tgz", - "integrity": "sha512-bTliMLqD7pTOoPg4zZkXqCDuzIUguEWLpeqkNfC41ODBHwoUgZ2w5JBeYimv4oP6TDVocoYmEhZrCLQTrH89bg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, "node_modules/@esbuild/darwin-arm64": { "version": "0.17.8", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.8.tgz", @@ -2829,294 +2781,6 @@ "node": ">=12" } }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.8.tgz", - "integrity": "sha512-n5WOpyvZ9TIdv2V1K3/iIkkJeKmUpKaCTdun9buhGRWfH//osmUjlv4Z5mmWdPWind/VGcVxTHtLfLCOohsOXw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.8.tgz", - "integrity": "sha512-a/SATTaOhPIPFWvHZDoZYgxaZRVHn0/LX1fHLGfZ6C13JqFUZ3K6SMD6/HCtwOQ8HnsNaEeokdiDSFLuizqv5A==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.8.tgz", - "integrity": "sha512-xpFJb08dfXr5+rZc4E+ooZmayBW6R3q59daCpKZ/cDU96/kvDM+vkYzNeTJCGd8rtO6fHWMq5Rcv/1cY6p6/0Q==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.8.tgz", - "integrity": "sha512-6Ij8gfuGszcEwZpi5jQIJCVIACLS8Tz2chnEBfYjlmMzVsfqBP1iGmHQPp7JSnZg5xxK9tjCc+pJ2WtAmPRFVA==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.8.tgz", - "integrity": "sha512-v3iwDQuDljLTxpsqQDl3fl/yihjPAyOguxuloON9kFHYwopeJEf1BkDXODzYyXEI19gisEsQlG1bM65YqKSIww==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.8.tgz", - "integrity": "sha512-8svILYKhE5XetuFk/B6raFYIyIqydQi+GngEXJgdPdI7OMKUbSd7uzR02wSY4kb53xBrClLkhH4Xs8P61Q2BaA==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.8.tgz", - "integrity": "sha512-B6FyMeRJeV0NpyEOYlm5qtQfxbdlgmiGdD+QsipzKfFky0K5HW5Td6dyK3L3ypu1eY4kOmo7wW0o94SBqlqBSA==", - "cpu": [ - "loong64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.8.tgz", - "integrity": "sha512-CCb67RKahNobjm/eeEqeD/oJfJlrWyw29fgiyB6vcgyq97YAf3gCOuP6qMShYSPXgnlZe/i4a8WFHBw6N8bYAA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.8.tgz", - "integrity": "sha512-bytLJOi55y55+mGSdgwZ5qBm0K9WOCh0rx+vavVPx+gqLLhxtSFU0XbeYy/dsAAD6xECGEv4IQeFILaSS2auXw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.8.tgz", - "integrity": "sha512-2YpRyQJmKVBEHSBLa8kBAtbhucaclb6ex4wchfY0Tj3Kg39kpjeJ9vhRU7x4mUpq8ISLXRXH1L0dBYjAeqzZAw==", - "cpu": [ - "riscv64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.8.tgz", - "integrity": "sha512-QgbNY/V3IFXvNf11SS6exkpVcX0LJcob+0RWCgV9OiDAmVElnxciHIisoSix9uzYzScPmS6dJFbZULdSAEkQVw==", - "cpu": [ - "s390x" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.8.tgz", - "integrity": "sha512-mM/9S0SbAFDBc4OPoyP6SEOo5324LpUxdpeIUUSrSTOfhHU9hEfqRngmKgqILqwx/0DVJBzeNW7HmLEWp9vcOA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.8.tgz", - "integrity": "sha512-eKUYcWaWTaYr9zbj8GertdVtlt1DTS1gNBWov+iQfWuWyuu59YN6gSEJvFzC5ESJ4kMcKR0uqWThKUn5o8We6Q==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.8.tgz", - "integrity": "sha512-Vc9J4dXOboDyMXKD0eCeW0SIeEzr8K9oTHJU+Ci1mZc5njPfhKAqkRt3B/fUNU7dP+mRyralPu8QUkiaQn7iIg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.8.tgz", - "integrity": "sha512-0xvOTNuPXI7ft1LYUgiaXtpCEjp90RuBBYovdd2lqAFxje4sEucurg30M1WIm03+3jxByd3mfo+VUmPtRSVuOw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.8.tgz", - "integrity": "sha512-G0JQwUI5WdEFEnYNKzklxtBheCPkuDdu1YrtRrjuQv30WsYbkkoixKxLLv8qhJmNI+ATEWquZe/N0d0rpr55Mg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.8.tgz", - "integrity": "sha512-Fqy63515xl20OHGFykjJsMnoIWS+38fqfg88ClvPXyDbLtgXal2DTlhb1TfTX34qWi3u4I7Cq563QcHpqgLx8w==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.17.8", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.8.tgz", - "integrity": "sha512-1iuezdyDNngPnz8rLRDO2C/ZZ/emJLb72OsZeqQ6gL6Avko/XCXZw+NuxBSNhBAP13Hie418V7VMt9et1FMvpg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", @@ -9347,7 +9011,6 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, "hasInstallScript": true, "optional": true, "os": [ @@ -12576,28 +12239,6 @@ "@angular/core": "^15.0.0" } }, - "node_modules/nice-napi": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/nice-napi/-/nice-napi-1.0.2.tgz", - "integrity": "sha512-px/KnJAJZf5RuBGcfD+Sp2pAKq0ytz8j+1NehvgIGFkvtvFrDM3T8E4x/JJODXK9WZow8RRGrbA9QQ3hs+pDhA==", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "!win32" - ], - "dependencies": { - "node-addon-api": "^3.0.0", - "node-gyp-build": "^4.2.2" - } - }, - "node_modules/node-addon-api": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", - "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==", - "dev": true, - "optional": true - }, "node_modules/node-forge": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", @@ -12632,18 +12273,6 @@ "node": "^12.13 || ^14.13 || >=16" } }, - "node_modules/node-gyp-build": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz", - "integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==", - "dev": true, - "optional": true, - "bin": { - "node-gyp-build": "bin.js", - "node-gyp-build-optional": "optional.js", - "node-gyp-build-test": "build-test.js" - } - }, "node_modules/node-gyp/node_modules/glob": { "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", diff --git a/ui/src/app/appupdateservice.ts b/ui/src/app/appupdateservice.ts index 981d2ad335c..7029043c8fa 100644 --- a/ui/src/app/appupdateservice.ts +++ b/ui/src/app/appupdateservice.ts @@ -13,11 +13,6 @@ export class CheckForUpdateService { ) { } init() { - let userId: string; - this.service.metadata.subscribe(entry => { - userId = entry?.user?.id ?? null; - }); - setInterval(async () => { const updateFound = await this.update.checkForUpdate(); console.log(updateFound ? 'A new version is available.' : 'Already on the latest version.'); diff --git a/ui/src/app/edge/history/Controller/ChannelThreshold/chart/totalchart.component.ts b/ui/src/app/edge/history/Controller/ChannelThreshold/chart/totalchart.component.ts index 0fec3b41f12..711bf37fb0c 100644 --- a/ui/src/app/edge/history/Controller/ChannelThreshold/chart/totalchart.component.ts +++ b/ui/src/app/edge/history/Controller/ChannelThreshold/chart/totalchart.component.ts @@ -20,10 +20,10 @@ export class TotalChartComponent extends AbstractHistoryChart { const controller: string[] = config?.getComponentIdsImplementingNature("io.openems.impl.controller.channelthreshold.ChannelThresholdController") .concat(config.getComponentIdsByFactory("Controller.ChannelThreshold")); - let components: { [controllerId: string]: string } = {}; - let input: HistoryUtils.InputChannel[] = []; + const components: { [controllerId: string]: string } = {}; + const input: HistoryUtils.InputChannel[] = []; - for (let controllerId of controller) { + for (const controllerId of controller) { const powerChannel = ChannelAddress.fromString(config.getComponentProperties(controllerId)['outputChannelAddress']); components[controllerId] = powerChannel.channelId; input.push({ name: controllerId, powerChannel: powerChannel, energyChannel: new ChannelAddress(controllerId, 'CumulatedActiveTime') }); @@ -33,7 +33,7 @@ export class TotalChartComponent extends AbstractHistoryChart { input: input, output: (data: HistoryUtils.ChannelData) => { - let output: HistoryUtils.DisplayValues[] = []; + const output: HistoryUtils.DisplayValues[] = []; const colors: string[] = ['rgb(0,0,139)', 'rgb(0,191,255)', 'rgb(0,0,56)', 'rgb(77,77,174)']; diff --git a/ui/src/app/edge/history/Controller/ChannelThreshold/flat/flat.ts b/ui/src/app/edge/history/Controller/ChannelThreshold/flat/flat.ts index 44b85462ce3..a6d91689197 100644 --- a/ui/src/app/edge/history/Controller/ChannelThreshold/flat/flat.ts +++ b/ui/src/app/edge/history/Controller/ChannelThreshold/flat/flat.ts @@ -21,10 +21,10 @@ export class FlatComponent extends AbstractFlatWidget { this.controllers = this.config.getComponentsByFactory('Controller.ChannelThreshold').concat(this.config.getComponentsImplementingNature('io.openems.impl.controller.channelthreshold.ChannelThresholdController')); - let channelAddresses: ChannelAddress[] = []; + const channelAddresses: ChannelAddress[] = []; - for (let controller of this.controllers) { - let output: ChannelAddress | null = ChannelAddress.fromString(controller.properties['outputChannelAddress']); + for (const controller of this.controllers) { + const output: ChannelAddress | null = ChannelAddress.fromString(controller.properties['outputChannelAddress']); this.displayName.set(controller.id, this.getDisplayName(controller, output)); channelAddresses.push(new ChannelAddress(controller.id, 'CumulatedActiveTime')); } diff --git a/ui/src/app/edge/history/abstracthistorychart.ts b/ui/src/app/edge/history/abstracthistorychart.ts index 6685b5d5b3a..d0b96867714 100644 --- a/ui/src/app/edge/history/abstracthistorychart.ts +++ b/ui/src/app/edge/history/abstracthistorychart.ts @@ -82,17 +82,17 @@ export abstract class AbstractHistoryChart { protected queryHistoricTimeseriesData(fromDate: Date, toDate: Date, res?: Resolution): Promise { // Take custom resolution if passed - let resolution = res ?? calculateResolution(this.service, fromDate, toDate).resolution; + const resolution = res ?? calculateResolution(this.service, fromDate, toDate).resolution; this.errorResponse = null; - let result: Promise = new Promise((resolve, reject) => { + const result: Promise = new Promise((resolve, reject) => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { this.setLabel(config); this.getChannelAddresses(edge, config).then(channelAddresses => { - let request = new QueryHistoricTimeseriesDataRequest(DateUtils.maxDate(fromDate, this.edge?.firstSetupProtocol), toDate, channelAddresses, resolution); + const request = new QueryHistoricTimeseriesDataRequest(DateUtils.maxDate(fromDate, this.edge?.firstSetupProtocol), toDate, channelAddresses, resolution); edge.sendRequest(this.service.websocket, request).then(response => { resolve(response as QueryHistoricTimeseriesDataResponse); }).catch(error => { @@ -126,11 +126,11 @@ export abstract class AbstractHistoryChart { protected queryHistoricTimeseriesEnergyPerPeriod(fromDate: Date, toDate: Date, channelAddresses: ChannelAddress[]): Promise { // TODO should be removed, edge delivers too much data - let resolution = calculateResolution(this.service, fromDate, toDate).resolution; + const resolution = calculateResolution(this.service, fromDate, toDate).resolution; this.errorResponse = null; - let response: Promise = new Promise((resolve, reject) => { + const response: Promise = new Promise((resolve, reject) => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { edge.sendRequest(this.service.websocket, new QueryHistoricTimeseriesEnergyPerPeriodRequest(DateUtils.maxDate(fromDate, this.edge?.firstSetupProtocol), toDate, channelAddresses, resolution)).then(response => { @@ -165,7 +165,7 @@ export abstract class AbstractHistoryChart { * @returns period for Tooltip Header */ protected static toTooltipTitle(fromDate: Date, toDate: Date, date: Date, service: Service): string { - let unit = calculateResolution(service, fromDate, toDate).resolution.unit; + const unit = calculateResolution(service, fromDate, toDate).resolution.unit; if (unit == ChronoUnit.Type.MONTHS) { return date.toLocaleDateString('default', { month: 'long' }); @@ -186,7 +186,7 @@ export abstract class AbstractHistoryChart { * @returns the ChartOptions */ protected createDefaultChartOptions(): Chart.ChartOptions { - let options = Utils.deepCopy(DEFAULT_TIME_CHART_OPTIONS); + const options = Utils.deepCopy(DEFAULT_TIME_CHART_OPTIONS); return options; } @@ -323,13 +323,13 @@ export abstract class AbstractHistoryChart { if (tooltipItems?.length === 0) { return null; } - let date = DateUtils.stringToDate(tooltipItems[0]?.label); + const date = DateUtils.stringToDate(tooltipItems[0]?.label); return AbstractHistoryChart.toTooltipTitle(this.service.historyPeriod.value.from, this.service.historyPeriod.value.to, date, this.service); }; options.plugins.tooltip.callbacks.label = function (tooltipItem: Chart.TooltipItem) { - let label = tooltipItem.dataset.label; - let value = tooltipItem.dataset.data[tooltipItem.dataIndex]; + const label = tooltipItem.dataset.label; + const value = tooltipItem.dataset.data[tooltipItem.dataIndex]; const customUnit = tooltipItem.dataset.unit ?? null; return label.split(":")[0] + ": " + NewAbstractHistoryChart.getToolTipsSuffix("", value, formatNumber, customUnit ?? unit, 'line', locale, translate, conf); @@ -349,7 +349,7 @@ export abstract class AbstractHistoryChart { }; options.plugins.legend.labels.generateLabels = function (chart: Chart.Chart) { - let chartLegendLabelItems: Chart.LegendItem[] = []; + const chartLegendLabelItems: Chart.LegendItem[] = []; chart.data.datasets.forEach((dataset, index) => { const color = colors[index]; @@ -378,9 +378,9 @@ export abstract class AbstractHistoryChart { // Remove duplicates from legend, if legendItem with two or more occurrences in legend, use one legendItem to trigger them both options.plugins.legend.onClick = function (event: Chart.ChartEvent, legendItem: Chart.LegendItem, legend) { - let chart: Chart.Chart = this.chart; + const chart: Chart.Chart = this.chart; - let legendItems = chart.data.datasets.reduce((arr, ds, i) => { + const legendItems = chart.data.datasets.reduce((arr, ds, i) => { if (ds.label == legendItem.text) { arr.push({ label: ds.label, index: i }); } @@ -390,7 +390,7 @@ export abstract class AbstractHistoryChart { legendItems.forEach(item => { // original.call(this, event, legendItem1); setLabelVisible(item.label, !chart.isDatasetVisible(legendItem.datasetIndex)); - var meta = chart.getDatasetMeta(item.index); + const meta = chart.getDatasetMeta(item.index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null ? !chart.data.datasets[item.index].hidden : null; }); diff --git a/ui/src/app/edge/history/abstracthistorywidget.ts b/ui/src/app/edge/history/abstracthistorywidget.ts index 9bfcd0a7af9..84b241264cd 100644 --- a/ui/src/app/edge/history/abstracthistorywidget.ts +++ b/ui/src/app/edge/history/abstracthistorywidget.ts @@ -50,14 +50,14 @@ export abstract class AbstractHistoryWidget { */ protected queryHistoricTimeseriesData(fromDate: Date, toDate: Date): Promise { - let resolution = calculateResolution(this.service, fromDate, toDate).resolution; + const resolution = calculateResolution(this.service, fromDate, toDate).resolution; return new Promise((resolve, reject) => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { this.getChannelAddresses(edge, config).then(channelAddresses => { - let request = new QueryHistoricTimeseriesDataRequest(DateUtils.maxDate(fromDate, edge?.firstSetupProtocol), toDate, channelAddresses, resolution); + const request = new QueryHistoricTimeseriesDataRequest(DateUtils.maxDate(fromDate, edge?.firstSetupProtocol), toDate, channelAddresses, resolution); edge.sendRequest(this.service.websocket, request).then(response => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; if (Object.keys(result.data).length != 0 && Object.keys(result.timestamps).length != 0) { resolve(response as QueryHistoricTimeseriesDataResponse); } else { diff --git a/ui/src/app/edge/history/chpsoc/chart.component.ts b/ui/src/app/edge/history/chpsoc/chart.component.ts index b82dd0114de..b825b5d31f0 100644 --- a/ui/src/app/edge/history/chpsoc/chart.component.ts +++ b/ui/src/app/edge/history/chpsoc/chart.component.ts @@ -18,7 +18,7 @@ export class ChpSocChartComponent extends AbstractHistoryChart implements OnInit ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -44,26 +44,26 @@ export class ChpSocChartComponent extends AbstractHistoryChart implements OnInit this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(() => { this.service.getConfig().then(config => { - let outputChannel = config.getComponentProperties(this.componentId)['outputChannelAddress']; - let inputChannel = config.getComponentProperties(this.componentId)['inputChannelAddress']; - let lowThreshold = this.componentId + '/_PropertyLowThreshold'; - let highThreshold = this.componentId + '/_PropertyHighThreshold'; - let result = response.result; + const outputChannel = config.getComponentProperties(this.componentId)['outputChannelAddress']; + const inputChannel = config.getComponentProperties(this.componentId)['inputChannelAddress']; + const lowThreshold = this.componentId + '/_PropertyLowThreshold'; + const highThreshold = this.componentId + '/_PropertyHighThreshold'; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; // convert datasets - for (let channel in result.data) { + for (const channel in result.data) { if (channel == outputChannel) { - let address = ChannelAddress.fromString(channel); - let data = result.data[channel].map(value => { + const address = ChannelAddress.fromString(channel); + const data = result.data[channel].map(value => { if (value == null) { return null; } else { @@ -79,7 +79,7 @@ export class ChpSocChartComponent extends AbstractHistoryChart implements OnInit borderColor: 'rgba(0,191,255,1)', }); } else { - let data = result.data[channel].map(value => { + const data = result.data[channel].map(value => { if (value == null) { return null; } else if (value > 100 || value < 0) { @@ -142,14 +142,14 @@ export class ChpSocChartComponent extends AbstractHistoryChart implements OnInit }).finally(() => { this.unit = YAxisTitle.PERCENTAGE; this.setOptions(this.options); - });; + }); } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { const outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); const inputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['inputChannelAddress']); - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ outputChannel, inputChannel, new ChannelAddress(this.componentId, '_PropertyHighThreshold'), diff --git a/ui/src/app/edge/history/chpsoc/widget.component.ts b/ui/src/app/edge/history/chpsoc/widget.component.ts index 5ef997758be..45bdc7a995e 100644 --- a/ui/src/app/edge/history/chpsoc/widget.component.ts +++ b/ui/src/app/edge/history/chpsoc/widget.component.ts @@ -44,23 +44,23 @@ export class ChpSocWidgetComponent extends AbstractHistoryWidget implements OnIn ngOnChanges() { this.updateValues(); - }; + } // Gather result & timestamps to calculate effective active time in % protected updateValues() { this.queryHistoricTimeseriesData(this.service.historyPeriod.value.from, this.service.historyPeriod.value.to).then(response => { this.service.getConfig().then(config => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; - let outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); + const result = (response as QueryHistoricTimeseriesDataResponse).result; + const outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); this.activeSecondsOverPeriod = calculateActiveTimeOverPeriod(outputChannel, result); }); }); - }; + } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { const outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); - let channeladdresses = [outputChannel]; + const channeladdresses = [outputChannel]; resolve(channeladdresses); }); } diff --git a/ui/src/app/edge/history/common/consumption/chart/chart.constants.spec.ts b/ui/src/app/edge/history/common/consumption/chart/chart.constants.spec.ts index 014c7aff208..d29f93c738f 100644 --- a/ui/src/app/edge/history/common/consumption/chart/chart.constants.spec.ts +++ b/ui/src/app/edge/history/common/consumption/chart/chart.constants.spec.ts @@ -14,4 +14,4 @@ export function expectView(config: EdgeConfig, testContext: TestContext, chartTy DummyConfig.convertDummyEdgeConfigToRealEdgeConfig(config), testContext.translate), chartType, channels, testContext, config))) .toEqual(removeFunctions(view)); -}; +} diff --git a/ui/src/app/edge/history/common/energy/chart/chart.constants.spec.ts b/ui/src/app/edge/history/common/energy/chart/chart.constants.spec.ts index 9828c860aca..cdbafd832f6 100644 --- a/ui/src/app/edge/history/common/energy/chart/chart.constants.spec.ts +++ b/ui/src/app/edge/history/common/energy/chart/chart.constants.spec.ts @@ -11,7 +11,7 @@ export function expectView(config: EdgeConfig, testContext: TestContext, chartTy .apply(ChartComponent .getChartData(DummyConfig.convertDummyEdgeConfigToRealEdgeConfig(config), chartType, testContext.translate), chartType, channels, testContext, config))) .toEqual(removeFunctions(view)); -}; +} export const DATASET = (data: OeChartTester.Dataset.Data, labels: OeChartTester.Dataset.LegendLabel, options: OeChartTester.Dataset.Option) => ({ data: data, diff --git a/ui/src/app/edge/history/common/energy/chart/chart.ts b/ui/src/app/edge/history/common/energy/chart/chart.ts index 9348c1e964e..2e3a22cc496 100644 --- a/ui/src/app/edge/history/common/energy/chart/chart.ts +++ b/ui/src/app/edge/history/common/energy/chart/chart.ts @@ -16,9 +16,9 @@ export class ChartComponent extends AbstractHistoryChart { } public static getChartData(config: EdgeConfig | null, chartType: 'line' | 'bar', translate: TranslateService): HistoryUtils.ChartData { - let input: HistoryUtils.InputChannel[] = + const input: HistoryUtils.InputChannel[] = config?.widgets.classes.reduce((arr: HistoryUtils.InputChannel[], key) => { - let newObj = []; + const newObj = []; switch (key) { case 'Energymonitor': case 'Consumption': diff --git a/ui/src/app/edge/history/common/energy/flat/flat.ts b/ui/src/app/edge/history/common/energy/flat/flat.ts index 7a3305d9152..2ff36ee1489 100644 --- a/ui/src/app/edge/history/common/energy/flat/flat.ts +++ b/ui/src/app/edge/history/common/energy/flat/flat.ts @@ -41,12 +41,12 @@ export class FlatComponent extends AbstractFlatWidget { protected exportToXlxs() { this.service.getCurrentEdge().then(edge => { edge.sendRequest(this.websocket, new QueryHistoricTimeseriesExportXlxsRequest(this.service.historyPeriod.value.from, this.service.historyPeriod.value.to)).then(response => { - let r = response as Base64PayloadResponse; - var binary = atob(r.result.payload.replace(/\s/g, '')); - var len = binary.length; - var buffer = new ArrayBuffer(len); - var view = new Uint8Array(buffer); - for (var i = 0; i < len; i++) { + const r = response as Base64PayloadResponse; + const binary = atob(r.result.payload.replace(/\s/g, '')); + const len = binary.length; + const buffer = new ArrayBuffer(len); + const view = new Uint8Array(buffer); + for (let i = 0; i < len; i++) { view[i] = binary.charCodeAt(i); } const data: Blob = new Blob([view], { @@ -54,8 +54,8 @@ export class FlatComponent extends AbstractFlatWidget { }); let fileName = "Export-" + edge.id + "-"; - let dateFrom = this.service.historyPeriod.value.from; - let dateTo = this.service.historyPeriod.value.to; + const dateFrom = this.service.historyPeriod.value.from; + const dateTo = this.service.historyPeriod.value.to; if (isSameDay(dateFrom, dateTo)) { fileName += format(dateFrom, "dd.MM.yyyy"); } else if (isSameMonth(dateFrom, dateTo)) { diff --git a/ui/src/app/edge/history/common/grid/chart/chart.constants.spec.ts b/ui/src/app/edge/history/common/grid/chart/chart.constants.spec.ts index d53747d4ab1..5c1700683cd 100644 --- a/ui/src/app/edge/history/common/grid/chart/chart.constants.spec.ts +++ b/ui/src/app/edge/history/common/grid/chart/chart.constants.spec.ts @@ -11,4 +11,4 @@ export function expectView(config: EdgeConfig, testContext: TestContext, chartTy .apply(ChartComponent .getChartData(DummyConfig.convertDummyEdgeConfigToRealEdgeConfig(config), chartType, testContext.translate, showPhases), chartType, channels, testContext, config))) .toEqual(removeFunctions(view)); -}; +} diff --git a/ui/src/app/edge/history/common/grid/chart/chart.ts b/ui/src/app/edge/history/common/grid/chart/chart.ts index efd755b9b37..fd5507e76a7 100644 --- a/ui/src/app/edge/history/common/grid/chart/chart.ts +++ b/ui/src/app/edge/history/common/grid/chart/chart.ts @@ -18,7 +18,7 @@ export class ChartComponent extends AbstractHistoryChart { public static getChartData(config: EdgeConfig, chartType: 'line' | 'bar', translate: TranslateService, showPhases: boolean): HistoryUtils.ChartData { - let input: DefaultTypes.History.InputChannel[] = [ + const input: DefaultTypes.History.InputChannel[] = [ { name: 'GridSell', powerChannel: ChannelAddress.fromString('_sum/GridActivePower'), @@ -46,7 +46,7 @@ export class ChartComponent extends AbstractHistoryChart { input: input, output: (data: DefaultTypes.History.ChannelData) => { - let datasets: DefaultTypes.History.DisplayValues[] = [ + const datasets: DefaultTypes.History.DisplayValues[] = [ { name: translate.instant('General.gridSellAdvanced'), nameSuffix: (energyValues: QueryHistoricTimeseriesEnergyResponse) => { diff --git a/ui/src/app/edge/history/common/production/chart/productionMeterChart.ts b/ui/src/app/edge/history/common/production/chart/productionMeterChart.ts index 4df762e4474..798f886c6c4 100644 --- a/ui/src/app/edge/history/common/production/chart/productionMeterChart.ts +++ b/ui/src/app/edge/history/common/production/chart/productionMeterChart.ts @@ -13,7 +13,7 @@ import { ChannelAddress } from '../../../../../shared/shared'; export class ProductionMeterChartComponent extends AbstractHistoryChart { protected override getChartData(): HistoryUtils.ChartData { - let channels: HistoryUtils.InputChannel[] = [{ + const channels: HistoryUtils.InputChannel[] = [{ name: 'ActivePower', powerChannel: ChannelAddress.fromString(this.component.id + '/ActivePower'), energyChannel: ChannelAddress.fromString(this.component.id + '/ActiveProductionEnergy'), @@ -32,7 +32,7 @@ export class ProductionMeterChartComponent extends AbstractHistoryChart { return { input: channels, output: (data: HistoryUtils.ChannelData) => { - let datasets: HistoryUtils.DisplayValues[] = []; + const datasets: HistoryUtils.DisplayValues[] = []; datasets.push({ name: this.translate.instant('General.production'), nameSuffix: (energyPeriodResponse: QueryHistoricTimeseriesEnergyResponse) => { diff --git a/ui/src/app/edge/history/common/production/chart/totalAcChart.ts b/ui/src/app/edge/history/common/production/chart/totalAcChart.ts index c5edd549a4d..af06fd9527c 100644 --- a/ui/src/app/edge/history/common/production/chart/totalAcChart.ts +++ b/ui/src/app/edge/history/common/production/chart/totalAcChart.ts @@ -34,7 +34,7 @@ export class TotalAcChartComponent extends AbstractHistoryChart { }, ], output: (data: HistoryUtils.ChannelData) => { - let datasets: HistoryUtils.DisplayValues[] = []; + const datasets: HistoryUtils.DisplayValues[] = []; datasets.push({ name: this.translate.instant("General.TOTAL"), diff --git a/ui/src/app/edge/history/common/production/chart/totalChart.ts b/ui/src/app/edge/history/common/production/chart/totalChart.ts index 1bc5708a652..2cb1514eb6a 100644 --- a/ui/src/app/edge/history/common/production/chart/totalChart.ts +++ b/ui/src/app/edge/history/common/production/chart/totalChart.ts @@ -12,11 +12,11 @@ import { ChannelAddress } from '../../../../../shared/shared'; export class TotalChartComponent extends AbstractHistoryChart { protected override getChartData(): HistoryUtils.ChartData { - let productionMeterComponents = this.config?.getComponentsImplementingNature("io.openems.edge.meter.api.ElectricityMeter") + const productionMeterComponents = this.config?.getComponentsImplementingNature("io.openems.edge.meter.api.ElectricityMeter") .filter(component => this.config.isProducer(component)); - let chargerComponents = this.config.getComponentsImplementingNature("io.openems.edge.ess.dccharger.api.EssDcCharger"); + const chargerComponents = this.config.getComponentsImplementingNature("io.openems.edge.ess.dccharger.api.EssDcCharger"); - let channels: HistoryUtils.InputChannel[] = [{ + const channels: HistoryUtils.InputChannel[] = [{ name: 'ProductionActivePower', powerChannel: ChannelAddress.fromString('_sum/ProductionActivePower'), energyChannel: ChannelAddress.fromString('_sum/ProductionActiveEnergy'), @@ -48,7 +48,7 @@ export class TotalChartComponent extends AbstractHistoryChart { }); } - for (let component of productionMeterComponents) { + for (const component of productionMeterComponents) { channels.push({ name: component.id, powerChannel: ChannelAddress.fromString(component.id + '/ActivePower'), @@ -56,7 +56,7 @@ export class TotalChartComponent extends AbstractHistoryChart { }); } - for (let component of chargerComponents) { + for (const component of chargerComponents) { channels.push({ name: component.id, powerChannel: ChannelAddress.fromString(component.id + '/ActualPower'), @@ -64,10 +64,10 @@ export class TotalChartComponent extends AbstractHistoryChart { }); } - let chartObject: HistoryUtils.ChartData = { + const chartObject: HistoryUtils.ChartData = { input: channels, output: (data: HistoryUtils.ChannelData) => { - let datasets: HistoryUtils.DisplayValues[] = []; + const datasets: HistoryUtils.DisplayValues[] = []; datasets.push({ name: this.showTotal == false ? this.translate.instant('General.production') : this.translate.instant('General.TOTAL'), nameSuffix: (energyQueryResponse: QueryHistoricTimeseriesEnergyResponse) => { @@ -113,9 +113,9 @@ export class TotalChartComponent extends AbstractHistoryChart { } // ProductionMeters - let productionMeterColors: string[] = ['rgb(253,197,7)', 'rgb(202, 158, 6', 'rgb(228, 177, 6)', 'rgb(177, 138, 5)', 'rgb(152, 118, 4)']; + const productionMeterColors: string[] = ['rgb(253,197,7)', 'rgb(202, 158, 6', 'rgb(228, 177, 6)', 'rgb(177, 138, 5)', 'rgb(152, 118, 4)']; for (let i = 0; i < productionMeterComponents.length; i++) { - let component = productionMeterComponents[i]; + const component = productionMeterComponents[i]; datasets.push({ name: component.alias ?? component.id, nameSuffix: (energyResponse: QueryHistoricTimeseriesEnergyResponse) => { @@ -129,10 +129,10 @@ export class TotalChartComponent extends AbstractHistoryChart { }); } - let chargerColors: string[] = ['rgb(0,223,0)', 'rgb(0,178,0)', 'rgb(0,201,0)', 'rgb(0,134,0)', 'rgb(0,156,0)']; + const chargerColors: string[] = ['rgb(0,223,0)', 'rgb(0,178,0)', 'rgb(0,201,0)', 'rgb(0,134,0)', 'rgb(0,156,0)']; // ChargerComponents for (let i = 0; i < chargerComponents.length; i++) { - let component = chargerComponents[i]; + const component = chargerComponents[i]; datasets.push({ name: component.alias ?? component.id, nameSuffix: (energyValues: QueryHistoricTimeseriesEnergyResponse) => { diff --git a/ui/src/app/edge/history/delayedselltogrid/chart.component.ts b/ui/src/app/edge/history/delayedselltogrid/chart.component.ts index f0821e6b4b1..e6f40fe98a9 100644 --- a/ui/src/app/edge/history/delayedselltogrid/chart.component.ts +++ b/ui/src/app/edge/history/delayedselltogrid/chart.component.ts @@ -18,7 +18,7 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -44,22 +44,22 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem this.colors = []; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getConfig().then(config => { - let meterIdActivePower = config.getComponent(this.componentId).properties['meter.id'] + '/ActivePower'; - let sellToGridPowerLimit = this.componentId + '/_PropertySellToGridPowerLimit'; - let continuousSellToGridPower = this.componentId + '/_PropertyContinuousSellToGridPower'; - let result = response.result; + const meterIdActivePower = config.getComponent(this.componentId).properties['meter.id'] + '/ActivePower'; + const sellToGridPowerLimit = this.componentId + '/_PropertySellToGridPowerLimit'; + const continuousSellToGridPower = this.componentId + '/_PropertyContinuousSellToGridPower'; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; if (meterIdActivePower in result.data) { - let data = result.data[meterIdActivePower].map(value => { + const data = result.data[meterIdActivePower].map(value => { if (value == null) { return null; } else if (value < 0) { @@ -79,7 +79,7 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem }); } if (sellToGridPowerLimit in result.data) { - let data = result.data[sellToGridPowerLimit].map(value => { + const data = result.data[sellToGridPowerLimit].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -100,7 +100,7 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem }); } if (continuousSellToGridPower in result.data) { - let data = result.data[continuousSellToGridPower].map(value => { + const data = result.data[continuousSellToGridPower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -132,7 +132,7 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem } else { effectivePower = result.data['_sum/EssActivePower']; } - let chargeData = effectivePower.map(value => { + const chargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value < 0) { @@ -153,7 +153,7 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem /* * Storage Discharge */ - let dischargeData = effectivePower.map(value => { + const dischargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value > 0) { @@ -194,7 +194,7 @@ export class DelayedSellToGridChartComponent extends AbstractHistoryChart implem protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress(this.componentId, '_PropertySellToGridPowerLimit'), new ChannelAddress(this.componentId, '_PropertyContinuousSellToGridPower'), new ChannelAddress(config.getComponent(this.componentId).properties['meter.id'], 'ActivePower'), diff --git a/ui/src/app/edge/history/fixdigitaloutput/singlechart.component.ts b/ui/src/app/edge/history/fixdigitaloutput/singlechart.component.ts index 2b18cf58c53..136004e5499 100644 --- a/ui/src/app/edge/history/fixdigitaloutput/singlechart.component.ts +++ b/ui/src/app/edge/history/fixdigitaloutput/singlechart.component.ts @@ -45,19 +45,19 @@ export class FixDigitalOutputSingleChartComponent extends AbstractHistoryChart i this.colors = []; this.loading = true; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets: Chart.ChartDataset[] = []; - for (let channel in result.data) { - let address = ChannelAddress.fromString(channel); - let data = result.data[channel].map(value => { + const datasets: Chart.ChartDataset[] = []; + for (const channel in result.data) { + const address = ChannelAddress.fromString(channel); + const data = result.data[channel].map(value => { if (value == null) { return null; } else { @@ -90,7 +90,7 @@ export class FixDigitalOutputSingleChartComponent extends AbstractHistoryChart i protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { const outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); - let channeladdresses = [outputChannel]; + const channeladdresses = [outputChannel]; resolve(channeladdresses); }); } diff --git a/ui/src/app/edge/history/fixdigitaloutput/totalchart.component.ts b/ui/src/app/edge/history/fixdigitaloutput/totalchart.component.ts index 190b6f82a01..3f678bf5ccc 100644 --- a/ui/src/app/edge/history/fixdigitaloutput/totalchart.component.ts +++ b/ui/src/app/edge/history/fixdigitaloutput/totalchart.component.ts @@ -18,7 +18,7 @@ export class FixDigitalOutputTotalChartComponent extends AbstractHistoryChart im ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -43,20 +43,20 @@ export class FixDigitalOutputTotalChartComponent extends AbstractHistoryChart im this.colors = []; this.loading = true; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; - let datasets = []; + const datasets = []; // convert datasets Object.keys(result.data).forEach((channel, index) => { - let address = ChannelAddress.fromString(channel); - let data = result.data[channel]?.map((value) => { + const address = ChannelAddress.fromString(channel); + const data = result.data[channel]?.map((value) => { if (value == null) { return null; } else { @@ -104,7 +104,7 @@ export class FixDigitalOutputTotalChartComponent extends AbstractHistoryChart im protected getChannelAddresses(): Promise { return new Promise((resolve, reject) => { this.service.getConfig().then(config => { - let channeladdresses = []; + const channeladdresses = []; // find all FixIoControllers config.getComponentsByFactory('Controller.Io.FixDigitalOutput').forEach(component => { const outputChannel = ChannelAddress.fromString(config.getComponentProperties(component.id)['outputChannelAddress']); diff --git a/ui/src/app/edge/history/fixdigitaloutput/widget.component.ts b/ui/src/app/edge/history/fixdigitaloutput/widget.component.ts index 305496310dc..8716004c0fb 100644 --- a/ui/src/app/edge/history/fixdigitaloutput/widget.component.ts +++ b/ui/src/app/edge/history/fixdigitaloutput/widget.component.ts @@ -46,23 +46,23 @@ export class FixDigitalOutputWidgetComponent extends AbstractHistoryWidget imple ngOnChanges() { this.updateValues(); - }; + } protected updateValues() { // Gather result & timestamps to calculate effective active time in % this.queryHistoricTimeseriesData(this.service.historyPeriod.value.from, this.service.historyPeriod.value.to).then(response => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; this.service.getConfig().then(config => { - let outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); + const outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); this.activeSecondsOverPeriod = calculateActiveTimeOverPeriod(outputChannel, result); }); }); - }; + } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { const outputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['outputChannelAddress']); - let channeladdresses = [outputChannel]; + const channeladdresses = [outputChannel]; resolve(channeladdresses); }); } diff --git a/ui/src/app/edge/history/grid/chart.component.ts b/ui/src/app/edge/history/grid/chart.component.ts index 4f45266f9d0..43cc204ee76 100644 --- a/ui/src/app/edge/history/grid/chart.component.ts +++ b/ui/src/app/edge/history/grid/chart.component.ts @@ -19,7 +19,7 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -46,19 +46,19 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { - let result = response.result; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; if ('_sum/GridActivePower' in result.data) { - let gridData = result.data['_sum/GridActivePower'].map(value => { + const gridData = result.data['_sum/GridActivePower'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -83,7 +83,7 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, /** * Buy From Grid */ - let gridData = result.data['_sum/GridActivePowerL1'].map(value => { + const gridData = result.data['_sum/GridActivePowerL1'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -103,7 +103,7 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, /** * Buy From Grid */ - let gridData = result.data['_sum/GridActivePowerL2'].map(value => { + const gridData = result.data['_sum/GridActivePowerL2'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -123,7 +123,7 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, /** * Buy From Grid */ - let gridData = result.data['_sum/GridActivePowerL3'].map(value => { + const gridData = result.data['_sum/GridActivePowerL3'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -153,7 +153,7 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress('_sum', 'GridActivePower'), new ChannelAddress('_sum', 'GridActivePowerL1'), new ChannelAddress('_sum', 'GridActivePowerL2'), @@ -164,11 +164,11 @@ export class GridChartComponent extends AbstractHistoryChart implements OnInit, } protected setLabel() { - let translate = this.translate; // enables access to TranslateService - let options = this.createDefaultChartOptions(); + const translate = this.translate; // enables access to TranslateService + const options = this.createDefaultChartOptions(); options.plugins.tooltip.callbacks.label = function (tooltipItem: Chart.TooltipItem) { let label = tooltipItem.dataset.label; - let value = tooltipItem.dataset.data[tooltipItem.dataIndex]; + const value = tooltipItem.dataset.data[tooltipItem.dataIndex]; // 0.005 to prevent showing Charge or Discharge if value is e.g. 0.00232138 if (value < -0.005) { if (label.includes(translate.instant('General.phase'))) { diff --git a/ui/src/app/edge/history/gridoptimizedcharge/chart.component.ts b/ui/src/app/edge/history/gridoptimizedcharge/chart.component.ts index b7b275ec69e..06743192d12 100644 --- a/ui/src/app/edge/history/gridoptimizedcharge/chart.component.ts +++ b/ui/src/app/edge/history/gridoptimizedcharge/chart.component.ts @@ -48,22 +48,22 @@ export class GridOptimizedChargeChartComponent extends AbstractHistoryChart impl this.loading = true; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(() => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; // Delay Charge Limit data if (this.component.id + '/DelayChargeMaximumChargeLimit' in result.data) { - let delayChargeData = result.data[this.component.id + '/DelayChargeMaximumChargeLimit'].map(value => { + const delayChargeData = result.data[this.component.id + '/DelayChargeMaximumChargeLimit'].map(value => { if (value == null) { return null; } else if (value <= 0) { @@ -86,7 +86,7 @@ export class GridOptimizedChargeChartComponent extends AbstractHistoryChart impl // Sell to grid limit - Minimum charge limit data if (this.component.id + '/SellToGridLimitMinimumChargeLimit' in result.data) { - let sellToGridLimitData = result.data[this.component.id + '/SellToGridLimitMinimumChargeLimit'].map(value => { + const sellToGridLimitData = result.data[this.component.id + '/SellToGridLimitMinimumChargeLimit'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -122,7 +122,7 @@ export class GridOptimizedChargeChartComponent extends AbstractHistoryChart impl effectivePower = result.data['_sum/EssActivePower']; } - let chargeData = effectivePower.map(value => { + const chargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value < 0) { @@ -146,7 +146,7 @@ export class GridOptimizedChargeChartComponent extends AbstractHistoryChart impl // State of charge data if ('_sum/EssSoc' in result.data) { - let socData = result.data['_sum/EssSoc'].map(value => { + const socData = result.data['_sum/EssSoc'].map(value => { if (value == null) { return null; } else if (value > 100 || value < 0) { @@ -220,7 +220,7 @@ export class GridOptimizedChargeChartComponent extends AbstractHistoryChart impl protected getChannelAddresses(): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress('_sum', 'EssActivePower'), new ChannelAddress('_sum', 'ProductionDcActualPower'), new ChannelAddress('_sum', 'EssSoc'), diff --git a/ui/src/app/edge/history/gridoptimizedcharge/sellToGridLimitChart.component.ts b/ui/src/app/edge/history/gridoptimizedcharge/sellToGridLimitChart.component.ts index d8b2c4ebaa8..fca488700f2 100644 --- a/ui/src/app/edge/history/gridoptimizedcharge/sellToGridLimitChart.component.ts +++ b/ui/src/app/edge/history/gridoptimizedcharge/sellToGridLimitChart.component.ts @@ -49,23 +49,23 @@ export class SellToGridLimitChartComponent extends AbstractHistoryChart implemen this.loading = true; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(() => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; /* * Sell To Grid */ if (this.gridMeter + '/ActivePower' in result.data) { - let sellToGridData = result.data[this.gridMeter + '/ActivePower'].map(value => { + const sellToGridData = result.data[this.gridMeter + '/ActivePower'].map(value => { if (value == null) { return null; } else if (value < 0) { @@ -90,7 +90,7 @@ export class SellToGridLimitChartComponent extends AbstractHistoryChart implemen */ if (this.component.id + '/_PropertyMaximumSellToGridPower' in result.data) { - let sellToGridLimitData = result.data[this.component.id + '/_PropertyMaximumSellToGridPower'].map(value => { + const sellToGridLimitData = result.data[this.component.id + '/_PropertyMaximumSellToGridPower'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -111,7 +111,7 @@ export class SellToGridLimitChartComponent extends AbstractHistoryChart implemen borderColor: 'rgba(0,0,0,1)', }); - let batterySellToGridLimitData = result.data[this.component.id + '/_PropertyMaximumSellToGridPower'].map(value => { + const batterySellToGridLimitData = result.data[this.component.id + '/_PropertyMaximumSellToGridPower'].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -140,7 +140,7 @@ export class SellToGridLimitChartComponent extends AbstractHistoryChart implemen */ if ('_sum/ProductionActivePower' in result.data) { - let productionData = result.data['_sum/ProductionActivePower'].map(value => { + const productionData = result.data['_sum/ProductionActivePower'].map(value => { if (value == null) { return null; } else { @@ -179,7 +179,7 @@ export class SellToGridLimitChartComponent extends AbstractHistoryChart implemen protected getChannelAddresses(): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [new ChannelAddress('_sum', 'ProductionActivePower')]; + const result: ChannelAddress[] = [new ChannelAddress('_sum', 'ProductionActivePower')]; if (this.component != null && this.gridMeter != null) { result.push(new ChannelAddress(this.gridMeter, 'ActivePower')); } diff --git a/ui/src/app/edge/history/gridoptimizedcharge/widget.component.ts b/ui/src/app/edge/history/gridoptimizedcharge/widget.component.ts index 56b35633eee..122ef28ec7a 100644 --- a/ui/src/app/edge/history/gridoptimizedcharge/widget.component.ts +++ b/ui/src/app/edge/history/gridoptimizedcharge/widget.component.ts @@ -47,14 +47,14 @@ export class GridOptimizedChargeWidgetComponent extends AbstractHistoryWidget im ngOnChanges() { this.updateValues(); - }; + } protected updateValues() { this.service.getConfig().then(config => { this.getChannelAddresses(this.edge, config).then(channels => { this.service.queryEnergy(this.period.from, this.period.to, channels).then(response => { - let result = response.result; + const result = response.result; if (this.componentId + '/DelayChargeTime' in result.data) { this.activeTimeDelayCharge = result.data[this.componentId + '/DelayChargeTime']; } @@ -75,7 +75,7 @@ export class GridOptimizedChargeWidgetComponent extends AbstractHistoryWidget im protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let channeladdresses = [ + const channeladdresses = [ new ChannelAddress(this.componentId, 'DelayChargeTime'), new ChannelAddress(this.componentId, 'SellToGridLimitTime'), new ChannelAddress(this.componentId, 'AvoidLowChargingTime'), diff --git a/ui/src/app/edge/history/heatingelement/chart.component.ts b/ui/src/app/edge/history/heatingelement/chart.component.ts index 8c8483c6bca..3d933402698 100644 --- a/ui/src/app/edge/history/heatingelement/chart.component.ts +++ b/ui/src/app/edge/history/heatingelement/chart.component.ts @@ -48,20 +48,20 @@ export class HeatingelementChartComponent extends AbstractHistoryChart implement this.loading = true; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(() => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; - let level = this.component.id + '/Level'; + const datasets = []; + const level = this.component.id + '/Level'; if (level in result.data) { - let levelData = result.data[level].map(value => { + const levelData = result.data[level].map(value => { if (value == null) { return null; } else { @@ -96,19 +96,18 @@ export class HeatingelementChartComponent extends AbstractHistoryChart implement this.unit = YAxisTitle.NONE; await this.setOptions(this.options); this.applyControllerSpecificOptions(this.options); - });; + }); } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let levels = new ChannelAddress(this.component.id, 'Level'); - let channeladdresses = [levels]; + const levels = new ChannelAddress(this.component.id, 'Level'); + const channeladdresses = [levels]; resolve(channeladdresses); }); } protected applyControllerSpecificOptions(options: ChartOptions) { - const translate = this.translate; options.scales[ChartAxis.LEFT]['title'].text = 'Level'; options.scales[ChartAxis.LEFT]['beginAtZero'] = true; options.scales[ChartAxis.LEFT].max = 3; diff --git a/ui/src/app/edge/history/heatingelement/widget.component.ts b/ui/src/app/edge/history/heatingelement/widget.component.ts index 10a46bf5cc1..0f8c2a62e16 100644 --- a/ui/src/app/edge/history/heatingelement/widget.component.ts +++ b/ui/src/app/edge/history/heatingelement/widget.component.ts @@ -47,12 +47,12 @@ export class HeatingelementWidgetComponent extends AbstractHistoryWidget impleme ngOnChanges() { this.updateValues(); - }; + } public getCumulativeValue(channeladdress: string, response: QueryHistoricTimeseriesDataResponse) { - let array = response.result.data[channeladdress]; - let firstValue = array.find(el => el != null) ?? 0; - let lastValue = array.slice().reverse().find(el => el != null) ?? 0; + const array = response.result.data[channeladdress]; + const firstValue = array.find(el => el != null) ?? 0; + const lastValue = array.slice().reverse().find(el => el != null) ?? 0; return lastValue - firstValue; } @@ -62,11 +62,11 @@ export class HeatingelementWidgetComponent extends AbstractHistoryWidget impleme this.activeTimeOverPeriodLevel2 = this.getCumulativeValue(this.componentId + '/Level2CumulatedTime', response); this.activeTimeOverPeriodLevel3 = this.getCumulativeValue(this.componentId + '/Level3CumulatedTime', response); }); - }; + } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let channeladdresses = [ + const channeladdresses = [ new ChannelAddress(this.componentId, 'Level1CumulatedTime'), new ChannelAddress(this.componentId, 'Level2CumulatedTime'), new ChannelAddress(this.componentId, 'Level3CumulatedTime'), diff --git a/ui/src/app/edge/history/heatpump/chart.component.ts b/ui/src/app/edge/history/heatpump/chart.component.ts index d193aad1e96..5350e669af1 100644 --- a/ui/src/app/edge/history/heatpump/chart.component.ts +++ b/ui/src/app/edge/history/heatpump/chart.component.ts @@ -44,20 +44,20 @@ export class HeatPumpChartComponent extends AbstractHistoryChart implements OnIn this.loading = true; this.colors = []; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { - let result = response.result; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; if (this.component.id + '/Status' in result.data) { - let stateTimeData = result.data[this.component.id + '/Status'].map(value => { + const stateTimeData = result.data[this.component.id + '/Status'].map(value => { if (value == null) { return null; } else { @@ -96,7 +96,7 @@ export class HeatPumpChartComponent extends AbstractHistoryChart implements OnIn } private applyControllerSpecificOptions(options: Chart.ChartOptions) { - let translate = this.translate; + const translate = this.translate; options.scales[ChartAxis.LEFT]['title'].text = this.translate.instant('General.state'); options.scales[ChartAxis.LEFT].ticks.callback = function (label, index, labels) { switch (label) { @@ -114,8 +114,8 @@ export class HeatPumpChartComponent extends AbstractHistoryChart implements OnIn }; options.plugins.tooltip.callbacks.label = function (tooltipItem: Chart.TooltipItem) { - let label = tooltipItem.dataset.label; - let value = tooltipItem.dataset.data[tooltipItem.dataIndex]; + const label = tooltipItem.dataset.label; + const value = tooltipItem.dataset.data[tooltipItem.dataIndex]; let toolTipValue; switch (value) { case -1: diff --git a/ui/src/app/edge/history/heatpump/widget.component.ts b/ui/src/app/edge/history/heatpump/widget.component.ts index 55117953a8e..e8e42316c5b 100644 --- a/ui/src/app/edge/history/heatpump/widget.component.ts +++ b/ui/src/app/edge/history/heatpump/widget.component.ts @@ -49,13 +49,13 @@ export class HeatpumpWidgetComponent extends AbstractHistoryWidget implements On ngOnChanges() { this.updateValues(); - }; + } protected updateValues() { this.service.getConfig().then(config => { this.getChannelAddresses(this.edge, config).then(channels => { this.service.queryEnergy(this.period.from, this.period.to, channels).then(response => { - let result = response.result; + const result = response.result; if (this.componentId + '/ForceOnStateTime' in result.data) { this.activeTimeOverPeriodForceOn = result.data[this.componentId + '/ForceOnStateTime']; } @@ -75,7 +75,7 @@ export class HeatpumpWidgetComponent extends AbstractHistoryWidget implements On protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let channels: ChannelAddress[] = [ + const channels: ChannelAddress[] = [ new ChannelAddress(this.componentId, 'ForceOnStateTime'), new ChannelAddress(this.componentId, 'RegularStateTime'), new ChannelAddress(this.componentId, 'RecommendationStateTime'), diff --git a/ui/src/app/edge/history/history.component.ts b/ui/src/app/edge/history/history.component.ts index c03f40dc456..0441bc8823d 100644 --- a/ui/src/app/edge/history/history.component.ts +++ b/ui/src/app/edge/history/history.component.ts @@ -73,7 +73,7 @@ export class HistoryComponent implements OnInit { } updateOnWindowResize() { - let ref = /* fix proportions */ Math.min(window.innerHeight - 150, + const ref = /* fix proportions */ Math.min(window.innerHeight - 150, /* handle grid breakpoints */(window.innerWidth < 768 ? window.innerWidth - 150 : window.innerWidth - 400)); this.socChartHeight = /* minimum size */ Math.max(150, diff --git a/ui/src/app/edge/history/historydataservice.ts b/ui/src/app/edge/history/historydataservice.ts index 0de2e34ddca..60efc278739 100644 --- a/ui/src/app/edge/history/historydataservice.ts +++ b/ui/src/app/edge/history/historydataservice.ts @@ -24,7 +24,7 @@ export class HistoryDataService extends DataService { public getValues(channelAddresses: ChannelAddress[], edge: Edge, componentId: string) { - for (let channelAddress of channelAddresses) { + for (const channelAddress of channelAddresses) { this.channelAddresses[channelAddress.toString()] = channelAddress; } @@ -36,9 +36,9 @@ export class HistoryDataService extends DataService { this.service.historyPeriod.subscribe(date => { edge.sendRequest(this.websocket, new QueryHistoricTimeseriesEnergyRequest(DateUtils.maxDate(date.from, edge?.firstSetupProtocol), date.to, Object.values(this.channelAddresses))) .then((response) => { - let allComponents = {}; - let result = (response as QueryHistoricTimeseriesEnergyResponse).result; - for (let [key, value] of Object.entries(result.data)) { + const allComponents = {}; + const result = (response as QueryHistoricTimeseriesEnergyResponse).result; + for (const [key, value] of Object.entries(result.data)) { allComponents[key] = value; } this.currentValue.next({ allComponents: allComponents }); diff --git a/ui/src/app/edge/history/peakshaving/asymmetric/chart.component.ts b/ui/src/app/edge/history/peakshaving/asymmetric/chart.component.ts index 69f67dfa923..14c7fc670fa 100644 --- a/ui/src/app/edge/history/peakshaving/asymmetric/chart.component.ts +++ b/ui/src/app/edge/history/peakshaving/asymmetric/chart.component.ts @@ -43,24 +43,24 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im this.loading = true; this.colors = []; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { - let meterIdActivePowerL1 = this.component.properties['meter.id'] + '/ActivePowerL1'; - let meterIdActivePowerL2 = this.component.properties['meter.id'] + '/ActivePowerL2'; - let meterIdActivePowerL3 = this.component.properties['meter.id'] + '/ActivePowerL3'; - let peakshavingPower = this.component.id + '/_PropertyPeakShavingPower'; - let rechargePower = this.component.id + '/_PropertyRechargePower'; - let result = response.result; + const meterIdActivePowerL1 = this.component.properties['meter.id'] + '/ActivePowerL1'; + const meterIdActivePowerL2 = this.component.properties['meter.id'] + '/ActivePowerL2'; + const meterIdActivePowerL3 = this.component.properties['meter.id'] + '/ActivePowerL3'; + const peakshavingPower = this.component.id + '/_PropertyPeakShavingPower'; + const rechargePower = this.component.id + '/_PropertyRechargePower'; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; if (meterIdActivePowerL1 in result.data) { - let data = result.data[meterIdActivePowerL1].map(value => { + const data = result.data[meterIdActivePowerL1].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -77,7 +77,7 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im this.colors.push(this.phase1Color); } if (meterIdActivePowerL2 in result.data) { - let data = result.data[meterIdActivePowerL2].map(value => { + const data = result.data[meterIdActivePowerL2].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -94,7 +94,7 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im this.colors.push(this.phase2Color); } if (meterIdActivePowerL3 in result.data) { - let data = result.data[meterIdActivePowerL3].map(value => { + const data = result.data[meterIdActivePowerL3].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -111,7 +111,7 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im this.colors.push(this.phase3Color); } if (rechargePower in result.data) { - let data = result.data[rechargePower].map(value => { + const data = result.data[rechargePower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -132,7 +132,7 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im }); } if (peakshavingPower in result.data) { - let data = result.data[peakshavingPower].map(value => { + const data = result.data[peakshavingPower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -164,7 +164,7 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im } else { effectivePower = result.data['_sum/EssActivePower']; } - let chargeData = effectivePower.map(value => { + const chargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value < 0) { @@ -184,7 +184,7 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im /* * Storage Discharge */ - let dischargeData = effectivePower.map(value => { + const dischargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value > 0) { @@ -214,12 +214,12 @@ export class AsymmetricPeakshavingChartComponent extends AbstractHistoryChart im this.unit = YAxisTitle.ENERGY; await this.setOptions(this.options); this.stopSpinner(); - });; + }); } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress(this.component.id, '_PropertyPeakShavingPower'), new ChannelAddress(this.component.id, '_PropertyRechargePower'), new ChannelAddress(this.component.properties['meter.id'], 'ActivePowerL1'), diff --git a/ui/src/app/edge/history/peakshaving/symmetric/chart.component.ts b/ui/src/app/edge/history/peakshaving/symmetric/chart.component.ts index c506f522217..11d986d8b25 100644 --- a/ui/src/app/edge/history/peakshaving/symmetric/chart.component.ts +++ b/ui/src/app/edge/history/peakshaving/symmetric/chart.component.ts @@ -43,22 +43,22 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp this.colors = []; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getConfig().then(config => { - let meterIdActivePower = config.getComponent(this.componentId).properties['meter.id'] + '/ActivePower'; - let peakshavingPower = this.componentId + '/_PropertyPeakShavingPower'; - let rechargePower = this.componentId + '/_PropertyRechargePower'; - let result = response.result; + const meterIdActivePower = config.getComponent(this.componentId).properties['meter.id'] + '/ActivePower'; + const peakshavingPower = this.componentId + '/_PropertyPeakShavingPower'; + const rechargePower = this.componentId + '/_PropertyRechargePower'; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; if (meterIdActivePower in result.data) { - let data = result.data[meterIdActivePower].map(value => { + const data = result.data[meterIdActivePower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -78,7 +78,7 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp }); } if (rechargePower in result.data) { - let data = result.data[rechargePower].map(value => { + const data = result.data[rechargePower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -99,7 +99,7 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp }); } if (peakshavingPower in result.data) { - let data = result.data[peakshavingPower].map(value => { + const data = result.data[peakshavingPower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -131,7 +131,7 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp } else { effectivePower = result.data['_sum/EssActivePower']; } - let chargeData = effectivePower.map(value => { + const chargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value < 0) { @@ -152,7 +152,7 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp /* * Storage Discharge */ - let dischargeData = effectivePower.map(value => { + const dischargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value > 0) { @@ -192,7 +192,7 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress(this.componentId, '_PropertyRechargePower'), new ChannelAddress(this.componentId, '_PropertyPeakShavingPower'), new ChannelAddress(config.getComponent(this.componentId).properties['meter.id'], 'ActivePower'), @@ -204,7 +204,7 @@ export class SymmetricPeakshavingChartComponent extends AbstractHistoryChart imp } protected setLabel() { - let options = this.createDefaultChartOptions(); + const options = this.createDefaultChartOptions(); this.options = options; } diff --git a/ui/src/app/edge/history/peakshaving/timeslot/chart.component.ts b/ui/src/app/edge/history/peakshaving/timeslot/chart.component.ts index 85f08d061c4..f933fec6d96 100644 --- a/ui/src/app/edge/history/peakshaving/timeslot/chart.component.ts +++ b/ui/src/app/edge/history/peakshaving/timeslot/chart.component.ts @@ -44,11 +44,11 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl this.colors = []; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getConfig().then(config => { - let meterIdActivePower = config.getComponent(this.componentId).properties['meter.id'] + '/ActivePower'; - let peakshavingPower = this.componentId + '/_PropertyPeakShavingPower'; - let rechargePower = this.componentId + '/_PropertyRechargePower'; - let stateMachine = this.componentId + '/StateMachine'; - let result = response.result; + const meterIdActivePower = config.getComponent(this.componentId).properties['meter.id'] + '/ActivePower'; + const peakshavingPower = this.componentId + '/_PropertyPeakShavingPower'; + const rechargePower = this.componentId + '/_PropertyRechargePower'; + const stateMachine = this.componentId + '/StateMachine'; + const result = response.result; Object.keys(result.data).forEach(key => { @@ -62,17 +62,17 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl }); // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; if (meterIdActivePower in result.data) { - let data = result.data[meterIdActivePower].map(value => { + const data = result.data[meterIdActivePower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -92,7 +92,7 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl }); } if (rechargePower in result.data) { - let data = result.data[rechargePower].map(value => { + const data = result.data[rechargePower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -113,7 +113,7 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl }); } if (peakshavingPower in result.data) { - let data = result.data[peakshavingPower].map(value => { + const data = result.data[peakshavingPower].map(value => { if (value == null) { return null; } else if (value == 0) { @@ -145,7 +145,7 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl } else { effectivePower = result.data['_sum/EssActivePower']; } - let chargeData = effectivePower.map(value => { + const chargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value < 0) { @@ -166,7 +166,7 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl /* * Storage Discharge */ - let dischargeData = effectivePower.map(value => { + const dischargeData = effectivePower.map(value => { if (value == null) { return null; } else if (value > 0) { @@ -202,12 +202,12 @@ export class TimeslotPeakshavingChartComponent extends AbstractHistoryChart impl }).finally(async () => { this.unit = YAxisTitle.ENERGY; await this.setOptions(this.options); - });; + }); } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress(this.componentId, '_PropertyRechargePower'), new ChannelAddress(this.componentId, '_PropertyPeakShavingPower'), new ChannelAddress(this.componentId, 'StateMachine'), diff --git a/ui/src/app/edge/history/shared.ts b/ui/src/app/edge/history/shared.ts index 1bae6f9e240..9c9cddc5bf8 100644 --- a/ui/src/app/edge/history/shared.ts +++ b/ui/src/app/edge/history/shared.ts @@ -285,7 +285,7 @@ export const DEFAULT_TIME_CHART_OPTIONS_WITHOUT_PREDEFINED_Y_AXIS: ChartOptions axis: 'x', callbacks: { title(tooltipItems: Chart.TooltipItem[], data: Data): string { - let date = DateUtils.stringToDate(tooltipItems[0]?.label); + const date = DateUtils.stringToDate(tooltipItems[0]?.label); return date.toLocaleDateString() + " " + date.toLocaleTimeString(); }, }, @@ -293,15 +293,15 @@ export const DEFAULT_TIME_CHART_OPTIONS_WITHOUT_PREDEFINED_Y_AXIS: ChartOptions }; export function calculateActiveTimeOverPeriod(channel: ChannelAddress, queryResult: QueryHistoricTimeseriesDataResponse['result']) { - let startDate = startOfDay(new Date(queryResult.timestamps[0])); - let endDate = new Date(queryResult.timestamps[queryResult.timestamps.length - 1]); + const startDate = startOfDay(new Date(queryResult.timestamps[0])); + const endDate = new Date(queryResult.timestamps[queryResult.timestamps.length - 1]); let activeSum = 0; queryResult.data[channel.toString()].forEach(value => { activeSum += value; }); - let activePercent = activeSum / queryResult.timestamps.length; + const activePercent = activeSum / queryResult.timestamps.length; return (differenceInMinutes(endDate, startDate) * activePercent) * 60; -}; +} /** * Calculates resolution from passed Dates for queryHistoricTime-SeriesData und -EnergyPerPeriod && @@ -313,7 +313,7 @@ export function calculateActiveTimeOverPeriod(channel: ChannelAddress, queryResu * @returns resolution and timeformat */ export function calculateResolution(service: Service, fromDate: Date, toDate: Date): { resolution: Resolution, timeFormat: 'day' | 'month' | 'hour' | 'year' } { - let days = Math.abs(differenceInDays(toDate, fromDate)); + const days = Math.abs(differenceInDays(toDate, fromDate)); let result: { resolution: Resolution, timeFormat: 'day' | 'month' | 'hour' | 'year' }; if (days <= 1) { @@ -382,8 +382,8 @@ export function calculateResolution(service: Service, fromDate: Date, toDate: Da * @returns true for visible labels; hidden otherwise */ export function isLabelVisible(label: string, orElse?: boolean): boolean { - let labelWithoutUnit = "LABEL_" + label.split(":")[0]; - let value = sessionStorage.getItem(labelWithoutUnit); + const labelWithoutUnit = "LABEL_" + label.split(":")[0]; + const value = sessionStorage.getItem(labelWithoutUnit); if (orElse != null && value == null) { return orElse; } else { @@ -401,7 +401,7 @@ export function setLabelVisible(label: string, visible: boolean | null): void { if (visible == null) { return; } - let labelWithoutUnit = "LABEL_" + label.split(":")[0]; + const labelWithoutUnit = "LABEL_" + label.split(":")[0]; sessionStorage.setItem(labelWithoutUnit, visible ? 'true' : 'false'); } diff --git a/ui/src/app/edge/history/singlethreshold/chart.component.ts b/ui/src/app/edge/history/singlethreshold/chart.component.ts index 8717442adfa..32be29b928f 100644 --- a/ui/src/app/edge/history/singlethreshold/chart.component.ts +++ b/ui/src/app/edge/history/singlethreshold/chart.component.ts @@ -21,7 +21,7 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -48,9 +48,9 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getConfig().then(config => { - let outputChannel: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; - let inputChannel = config.getComponentProperties(this.componentId)['inputChannelAddress']; - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const outputChannel: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; + const inputChannel = config.getComponentProperties(this.componentId)['inputChannelAddress']; + const result = (response as QueryHistoricTimeseriesDataResponse).result; let yAxisID; // set yAxis for % values (if there are no other % values: use left yAxis, if there are: use right yAxis - for percent values) @@ -61,19 +61,19 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen } // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; - let datasets = []; + const datasets = []; // convert datasets - for (let channel in result.data) { + for (const channel in result.data) { if ((typeof outputChannel === 'string' && channel == outputChannel) || (typeof outputChannel !== 'string' && outputChannel.includes(channel))) { - let address = ChannelAddress.fromString(channel); - let data = result.data[channel].map(value => { + const address = ChannelAddress.fromString(channel); + const data = result.data[channel].map(value => { if (value == null) { return null; } else { @@ -94,7 +94,7 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen } if (channel == inputChannel) { let inputLabel: string = null; - let address = ChannelAddress.fromString(channel); + const address = ChannelAddress.fromString(channel); switch (address.channelId) { case 'GridActivePower': inputLabel = this.translate.instant('General.grid'); @@ -190,8 +190,8 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { const inputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['inputChannelAddress']); - let result: ChannelAddress[] = [inputChannel]; - let outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; + const result: ChannelAddress[] = [inputChannel]; + const outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; if (typeof outputChannelAddress === 'string') { result.push(ChannelAddress.fromString(outputChannelAddress)); } else { @@ -209,8 +209,8 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen this.service.getConfig().then(config => { - let inputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['inputChannelAddress']); - let outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; + const inputChannel = ChannelAddress.fromString(config.getComponentProperties(this.componentId)['inputChannelAddress']); + const outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; let outputChannel: ChannelAddress; if (typeof outputChannelAddress === 'string') { outputChannel = ChannelAddress.fromString(outputChannelAddress); @@ -249,10 +249,10 @@ export class SinglethresholdChartComponent extends AbstractHistoryChart implemen }; } - let translate = this.translate; + const translate = this.translate; options.plugins.tooltip.callbacks.label = function (item: Chart.TooltipItem) { - let label = item.dataset.label; - let value = item.dataset.data[item.dataIndex]; + const label = item.dataset.label; + const value = item.dataset.data[item.dataIndex]; if (label == outputChannel.channelId || label == translate.instant('General.soc')) { return label + ": " + formatNumber(value, 'de', '1.0-0') + " %"; } else if (label == translate.instant('General.grid') || label == translate.instant('General.production')) { diff --git a/ui/src/app/edge/history/singlethreshold/widget.component.ts b/ui/src/app/edge/history/singlethreshold/widget.component.ts index c5964b2a2f8..5a5b46ec2f1 100644 --- a/ui/src/app/edge/history/singlethreshold/widget.component.ts +++ b/ui/src/app/edge/history/singlethreshold/widget.component.ts @@ -44,13 +44,13 @@ export class SinglethresholdWidgetComponent extends AbstractHistoryWidget implem ngOnChanges() { this.updateValues(); - }; + } // Gather result & timestamps to calculate effective active time in % protected updateValues() { this.queryHistoricTimeseriesData(this.service.historyPeriod.value.from, this.service.historyPeriod.value.to).then(response => { this.service.getConfig().then(config => { - let result = (response as QueryHistoricTimeseriesDataResponse).result; + const result = (response as QueryHistoricTimeseriesDataResponse).result; let outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; if (typeof outputChannelAddress !== 'string') { // Takes only the first output for simplicity reasons @@ -59,11 +59,11 @@ export class SinglethresholdWidgetComponent extends AbstractHistoryWidget implem this.activeSecondsOverPeriod = calculateActiveTimeOverPeriod(ChannelAddress.fromString(outputChannelAddress), result); }); }); - }; + } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; + const outputChannelAddress: string | string[] = config.getComponentProperties(this.componentId)['outputChannelAddress']; if (typeof outputChannelAddress === 'string') { resolve([ChannelAddress.fromString(outputChannelAddress)]); } else { diff --git a/ui/src/app/edge/history/storage/chargerchart.component.ts b/ui/src/app/edge/history/storage/chargerchart.component.ts index 784c5a00eba..8b37ac0cb02 100644 --- a/ui/src/app/edge/history/storage/chargerchart.component.ts +++ b/ui/src/app/edge/history/storage/chargerchart.component.ts @@ -19,7 +19,7 @@ export class StorageChargerChartComponent extends AbstractHistoryChart implement ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -44,20 +44,20 @@ export class StorageChargerChartComponent extends AbstractHistoryChart implement this.colors = []; this.loading = true; this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { - let result = response.result; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; Object.keys(result.data).forEach((channel) => { - let address = ChannelAddress.fromString(channel); - let chargerData = result.data[channel].map(value => { + const address = ChannelAddress.fromString(channel); + const chargerData = result.data[channel].map(value => { if (value == null) { return null; } else { @@ -91,7 +91,7 @@ export class StorageChargerChartComponent extends AbstractHistoryChart implement protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress(this.componentId, 'ActualPower'), ]; resolve(result); diff --git a/ui/src/app/edge/history/storage/esschart.component.ts b/ui/src/app/edge/history/storage/esschart.component.ts index 7ee97b72963..0ad2c4f52b0 100644 --- a/ui/src/app/edge/history/storage/esschart.component.ts +++ b/ui/src/app/edge/history/storage/esschart.component.ts @@ -49,19 +49,19 @@ export class StorageESSChartComponent extends AbstractHistoryChart implements On this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { - let result = response.result; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; this.getChannelAddresses(edge, config).then(channelAddresses => { channelAddresses.forEach(channelAddress => { - let data = result.data[channelAddress.toString()]?.map(value => { + const data = result.data[channelAddress.toString()]?.map(value => { if (value == null) { return null; } else { @@ -133,11 +133,11 @@ export class StorageESSChartComponent extends AbstractHistoryChart implements On } protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { - let component = config.getComponent(this.componentId); - let factoryID = component.factoryId; - let factory = config.factories[factoryID]; + const component = config.getComponent(this.componentId); + const factoryID = component.factoryId; + const factory = config.factories[factoryID]; return new Promise((resolve, reject) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress(this.componentId, 'ActivePower'), ]; if ((factory.natureIds.includes("io.openems.edge.ess.api.AsymmetricEss"))) { @@ -152,7 +152,7 @@ export class StorageESSChartComponent extends AbstractHistoryChart implements On } protected setLabel() { - let options = this.createDefaultChartOptions(); + const options = this.createDefaultChartOptions(); this.options = options; } diff --git a/ui/src/app/edge/history/storage/singlechart.component.ts b/ui/src/app/edge/history/storage/singlechart.component.ts index 2aa0fd4cede..e3ec04397ed 100644 --- a/ui/src/app/edge/history/storage/singlechart.component.ts +++ b/ui/src/app/edge/history/storage/singlechart.component.ts @@ -47,16 +47,16 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { - let result = response.result; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; + const datasets = []; // calculate total charge and discharge let effectivePower = []; @@ -80,7 +80,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements effectivePowerL3 = result.data['_sum/EssActivePowerL3']; } - let totalData = effectivePower.map(value => { + const totalData = effectivePower.map(value => { if (value == null) { return null; } else { @@ -88,7 +88,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements } }); - let totalDataL1 = effectivePowerL1.map(value => { + const totalDataL1 = effectivePowerL1.map(value => { if (value == null) { return null; } else { @@ -96,7 +96,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements } }); - let totalDataL2 = effectivePowerL2.map(value => { + const totalDataL2 = effectivePowerL2.map(value => { if (value == null) { return null; } else { @@ -104,7 +104,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements } }); - let totalDataL3 = effectivePowerL3.map(value => { + const totalDataL3 = effectivePowerL3.map(value => { if (value == null) { return null; } else { @@ -114,7 +114,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements this.getChannelAddresses(edge, config).then(async channelAddresses => { channelAddresses.forEach(channelAddress => { - let data = result.data[channelAddress.toString()]?.map(value => { + const data = result.data[channelAddress.toString()]?.map(value => { if (value == null) { return null; } else { @@ -181,7 +181,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements this.applyControllerSpecificChartOptions(this.options); this.loading = false; this.stopSpinner(); - });; + }); } @@ -191,7 +191,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements options.scales[ChartAxis.LEFT].min = null; options.plugins.tooltip.callbacks.label = function (tooltipItem: Chart.TooltipItem) { let label = tooltipItem.dataset.label; - let value = tooltipItem.dataset.data[tooltipItem.dataIndex]; + const value = tooltipItem.dataset.data[tooltipItem.dataIndex]; // 0.005 to prevent showing Charge or Discharge if value is e.g. 0.00232138 if (value < -0.005) { if (label.includes(translate.instant('General.phase'))) { @@ -218,7 +218,7 @@ export class StorageSingleChartComponent extends AbstractHistoryChart implements protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress('_sum', 'EssActivePower'), new ChannelAddress('_sum', 'ProductionDcActualPower'), new ChannelAddress('_sum', 'EssActivePowerL1'), diff --git a/ui/src/app/edge/history/storage/socchart.component.ts b/ui/src/app/edge/history/storage/socchart.component.ts index 05648a9d981..3dfb4287f6b 100644 --- a/ui/src/app/edge/history/storage/socchart.component.ts +++ b/ui/src/app/edge/history/storage/socchart.component.ts @@ -45,22 +45,22 @@ export class SocStorageChartComponent extends AbstractHistoryChart implements On this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { - let result = response.result; + const result = response.result; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; // convert datasets - let datasets = []; - let moreThanOneESS = Object.keys(result.data).length > 1 ? true : false; + const datasets = []; + const moreThanOneESS = Object.keys(result.data).length > 1 ? true : false; this.getChannelAddresses(edge, config) .then(channelAddresses => { channelAddresses.forEach(channelAddress => { - let component = config.getComponent(channelAddress.componentId); - let data = result.data[channelAddress.toString()]?.map(value => { + const component = config.getComponent(channelAddress.componentId); + const data = result.data[channelAddress.toString()]?.map(value => { if (value == null) { return null; } else if (value > 100 || value < 0) { diff --git a/ui/src/app/edge/history/storage/totalchart.component.ts b/ui/src/app/edge/history/storage/totalchart.component.ts index 3a58ca7da52..0e7f761a8bc 100644 --- a/ui/src/app/edge/history/storage/totalchart.component.ts +++ b/ui/src/app/edge/history/storage/totalchart.component.ts @@ -19,7 +19,7 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -46,11 +46,11 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements this.queryHistoricTimeseriesData(this.period.from, this.period.to).then(response => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(config => { - let result = response.result; + const result = response.result; this.colors = []; // convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; @@ -64,7 +64,7 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements } else { effectivePower = result.data['_sum/EssActivePower']; } - let totalData = effectivePower.map(value => { + const totalData = effectivePower.map(value => { if (value == null) { return null; } else { @@ -73,19 +73,19 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements }); // convert datasets - let datasets = []; + const datasets = []; this.getChannelAddresses(edge, config).then(channelAddresses => { channelAddresses.forEach(channelAddress => { - let component = config.getComponent(channelAddress.componentId); - let data = result.data[channelAddress.toString()]?.map(value => { + const component = config.getComponent(channelAddress.componentId); + const data = result.data[channelAddress.toString()]?.map(value => { if (value == null) { return null; } else { return value / 1000; // convert to kW } }); - let chargerData = result.data[channelAddress.toString()].map(value => { + const chargerData = result.data[channelAddress.toString()].map(value => { if (value == null) { return null; } else { @@ -202,7 +202,7 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress('_sum', 'EssActivePower'), new ChannelAddress('_sum', 'ProductionDcActualPower'), new ChannelAddress('_sum', 'EssActivePowerL1'), @@ -212,8 +212,8 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements config.getComponentsImplementingNature("io.openems.edge.ess.api.SymmetricEss") .filter(component => !component.factoryId.includes("Ess.Cluster")) .forEach(component => { - let factoryID = component.factoryId; - let factory = config.factories[factoryID]; + const factoryID = component.factoryId; + const factory = config.factories[factoryID]; result.push(new ChannelAddress(component.id, 'ActivePower')); if ((factory.natureIds.includes("io.openems.edge.ess.api.AsymmetricEss"))) { result.push( @@ -223,7 +223,7 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements ); } }); - let charger = config.getComponentsImplementingNature("io.openems.edge.ess.dccharger.api.EssDcCharger"); + const charger = config.getComponentsImplementingNature("io.openems.edge.ess.dccharger.api.EssDcCharger"); if (config.getComponentsImplementingNature("io.openems.edge.ess.api.SymmetricEss") .filter(component => !component.factoryId.includes("Ess.Cluster")).length != 1 && charger.length > 0) { charger.forEach(component => { @@ -244,7 +244,7 @@ export class StorageTotalChartComponent extends AbstractHistoryChart implements options.scales[ChartAxis.LEFT].min = null; options.plugins.tooltip.callbacks.label = function (tooltipItem: Chart.TooltipItem) { let label = tooltipItem.dataset.label; - let value = tooltipItem.dataset.data[tooltipItem.dataIndex]; + const value = tooltipItem.dataset.data[tooltipItem.dataIndex]; // 0.005 to prevent showing Charge or Discharge if value is e.g. 0.00232138 if (value < -0.005) { label += ' ' + translate.instant('General.chargePower'); diff --git a/ui/src/app/edge/history/storage/widget.component.ts b/ui/src/app/edge/history/storage/widget.component.ts index b5f79ad4082..3dcdcdcfed7 100644 --- a/ui/src/app/edge/history/storage/widget.component.ts +++ b/ui/src/app/edge/history/storage/widget.component.ts @@ -42,7 +42,7 @@ export class StorageComponent extends AbstractHistoryWidget implements OnInit, O ngOnChanges() { this.updateValues(); - }; + } protected updateValues() { this.service.getConfig().then(config => { @@ -58,7 +58,7 @@ export class StorageComponent extends AbstractHistoryWidget implements OnInit, O protected getChannelAddresses(edge: Edge, config: EdgeConfig): Promise { return new Promise((resolve) => { - let channels: ChannelAddress[] = []; + const channels: ChannelAddress[] = []; channels.push( new ChannelAddress('_sum', 'EssDcChargeEnergy'), new ChannelAddress('_sum', 'EssDcDischargeEnergy'), diff --git a/ui/src/app/edge/live/Controller/Channelthreshold/Channelthreshold.ts b/ui/src/app/edge/live/Controller/Channelthreshold/Channelthreshold.ts index 20ceb907e44..10b64329b18 100644 --- a/ui/src/app/edge/live/Controller/Channelthreshold/Channelthreshold.ts +++ b/ui/src/app/edge/live/Controller/Channelthreshold/Channelthreshold.ts @@ -23,7 +23,7 @@ export class Controller_ChannelthresholdComponent extends AbstractFlatWidget { return [this.outputChannel]; } protected override onCurrentData(currentData: CurrentData) { - let channel = currentData.allComponents[this.outputChannel.toString()]; + const channel = currentData.allComponents[this.outputChannel.toString()]; if (channel != null) { if (channel == 1) { this.icon.name = "radio-button-on-outline"; diff --git a/ui/src/app/edge/live/Controller/ChpSoc/ChpSoc.ts b/ui/src/app/edge/live/Controller/ChpSoc/ChpSoc.ts index 78cbb72bd1d..b7fa89871de 100644 --- a/ui/src/app/edge/live/Controller/ChpSoc/ChpSoc.ts +++ b/ui/src/app/edge/live/Controller/ChpSoc/ChpSoc.ts @@ -57,7 +57,7 @@ export class Controller_ChpSocComponent extends AbstractFlatWidget { this.mode = this.translate.instant('General.automatic'); } - let outputChannelValue = currentData.allComponents[this.outputChannel.toString()]; + const outputChannelValue = currentData.allComponents[this.outputChannel.toString()]; switch (outputChannelValue) { case 0: diff --git a/ui/src/app/edge/live/Controller/ChpSoc/modal/modal.component.ts b/ui/src/app/edge/live/Controller/ChpSoc/modal/modal.component.ts index fad00a41e97..d84bc2e422d 100644 --- a/ui/src/app/edge/live/Controller/ChpSoc/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/ChpSoc/modal/modal.component.ts @@ -37,7 +37,7 @@ export class Controller_ChpSocModalComponent implements OnInit { ngOnInit() { this.thresholds['lower'] = this.component.properties['lowThreshold']; this.thresholds['upper'] = this.component.properties['highThreshold']; - }; + } /** * Updates the Charge-Mode of the EVCS-Controller. @@ -45,7 +45,7 @@ export class Controller_ChpSocModalComponent implements OnInit { * @param event */ updateMode(event: CustomEvent) { - let oldMode = this.component.properties.mode; + const oldMode = this.component.properties.mode; let newMode: mode; switch (event.detail.value) { @@ -80,11 +80,11 @@ export class Controller_ChpSocModalComponent implements OnInit { * @param event */ updateThresholds() { - let oldLowerThreshold = this.component.properties['lowThreshold']; - let oldUpperThreshold = this.component.properties['highThreshold']; + const oldLowerThreshold = this.component.properties['lowThreshold']; + const oldUpperThreshold = this.component.properties['highThreshold']; - let newLowerThreshold = this.thresholds['lower']; - let newUpperThreshold = this.thresholds['upper']; + const newLowerThreshold = this.thresholds['lower']; + const newUpperThreshold = this.thresholds['upper']; // prevents automatic update when no values have changed if (this.edge != null && (oldLowerThreshold != newLowerThreshold || oldUpperThreshold != newUpperThreshold)) { diff --git a/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/modal.ts b/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/modal.ts index ace6d5feb60..0184f951da7 100644 --- a/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/modal.ts +++ b/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/modal.ts @@ -29,7 +29,7 @@ export class ModalComponent extends AbstractModal { protected override getChannelAddresses(): ChannelAddress[] { this.refreshChart = false; - let channels: ChannelAddress[] = []; + const channels: ChannelAddress[] = []; if (this.edge.roleIsAtLeast(Role.ADMIN)) { this.isAtLeastAdmin = true; if ('ess.id' in this.component.properties) { @@ -81,9 +81,7 @@ export class ModalComponent extends AbstractModal { break; case 4: this.state = this.translate.instant('Edge.Index.Widgets.GridOptimizedCharge.State.noLimitPossible'); break; - case 5: - - // Case 6: 'DISABLED' hides 'state-line', so no Message needed + case 5: // Case 6: 'DISABLED' hides 'state-line', so no Message needed case 7: this.state = this.translate.instant('Edge.Index.Widgets.GridOptimizedCharge.State.noLimitActive'); break; diff --git a/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/predictionChart.ts b/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/predictionChart.ts index d639f765133..3c21c751a26 100644 --- a/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/predictionChart.ts +++ b/ui/src/app/edge/live/Controller/Ess/GridOptimizedCharge/modal/predictionChart.ts @@ -24,7 +24,7 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -51,13 +51,13 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On this.colors = []; this.queryHistoricTimeseriesData(PredictionChartComponent.DEFAULT_PERIOD.from, PredictionChartComponent.DEFAULT_PERIOD.to, { unit: ChronoUnit.Type.MINUTES, value: 5 }).then(async response => { - let result = response.result; - let datasets = []; + const result = response.result; + const datasets = []; // Get the 5 min index of the current time - let hours = new Date().getHours(); - let minutes = new Date().getMinutes(); - let currIndex = Math.trunc((hours * 60 + minutes) / 5); + const hours = new Date().getHours(); + const minutes = new Date().getMinutes(); + const currIndex = Math.trunc((hours * 60 + minutes) / 5); // Add one buffer hour at the beginning to see at least one hour of the past soc let startIndex = currIndex - 12; @@ -66,7 +66,7 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On // Calculate soc and predicted soc data if ('_sum/EssSoc' in result.data) { - let socData = result.data['_sum/EssSoc'].map(value => { + const socData = result.data['_sum/EssSoc'].map(value => { if (value == null) { return null; } else if (value > 100 || value < 0) { @@ -85,17 +85,17 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On } } - let targetTime = new Date(0); + const targetTime = new Date(0); targetTime.setUTCSeconds(this.targetEpochSeconds); // Predicted charge start only used, if a value is present. There's no Channel for it in older Openems Versions. - let isChargeStartPresent = this.chargeStartEpochSeconds != null; - let chargeStartTime = new Date(0); + const isChargeStartPresent = this.chargeStartEpochSeconds != null; + const chargeStartTime = new Date(0); let chargeStartIndex = 0; if (isChargeStartPresent) { chargeStartTime.setUTCSeconds(this.chargeStartEpochSeconds); - let chargeStartHours = chargeStartTime.getHours(); - let chargeStartMinutes = chargeStartTime.getMinutes(); + const chargeStartHours = chargeStartTime.getHours(); + const chargeStartMinutes = chargeStartTime.getMinutes(); // Calculate the index of the chargeStart chargeStartIndex = Math.trunc((chargeStartHours * 60 + chargeStartMinutes) / 5); @@ -103,19 +103,19 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On let dataSteps = 0; let targetIndex = 0; - let predictedSocData = Array(288).fill(null); + const predictedSocData = Array(288).fill(null); // Calculate the predicted soc data if (startSoc != null && targetTime != null) { - let targetHours = targetTime.getHours(); - let targetMinutes = targetTime.getMinutes(); + const targetHours = targetTime.getHours(); + const targetMinutes = targetTime.getMinutes(); // Calculate the index of the target minute targetIndex = Math.trunc((targetHours * 60 + targetMinutes) / 5); // Remaining capacity in % - let remainingCapacity = 100 - startSoc; + const remainingCapacity = 100 - startSoc; // Calculate how much time is left in 5 min steps let remainingSteps = 0; @@ -144,7 +144,7 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On } // Add one buffer hour at the end to get more clarity in the chart - let chartEndIndex = targetIndex + 12; + const chartEndIndex = targetIndex + 12; // Remove unimportant values that are after the end index if (chartEndIndex < result.data['_sum/EssSoc'].length - 1) { @@ -161,8 +161,8 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On } // Convert labels - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } this.labels = labels; @@ -209,7 +209,7 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On private applyControllerSpecificOptions() { this.options.scales[ChartAxis.LEFT]['position'] = 'right'; this.options.scales.x.ticks.callback = function (value, index, values) { - var date = new Date(value); + const date = new Date(value); // Display the label only if the minutes are zero (full hour) return date.getMinutes() === 0 ? date.getHours() + ':00' : ''; @@ -219,7 +219,7 @@ export class PredictionChartComponent extends AbstractHistoryChart implements On protected getChannelAddresses(): Promise { return new Promise((resolve) => { - let result: ChannelAddress[] = [ + const result: ChannelAddress[] = [ new ChannelAddress('_sum', 'EssSoc'), ]; if (this.component != null && this.component.id) { diff --git a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/flat/flat.ts b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/flat/flat.ts index 157f5e9d25a..15a99805cd5 100644 --- a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/flat/flat.ts +++ b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/flat/flat.ts @@ -31,8 +31,8 @@ export class FlatComponent extends AbstractFlatWidget implements OnInit { } protected override onCurrentData(currentData: CurrentData): void { - var quarterlyPrice = currentData.allComponents[this.component.id + '/QuarterlyPrices']; - var currencyLabel: string = Currency.getCurrencyLabelByEdgeId(this.edge.id); + const quarterlyPrice = currentData.allComponents[this.component.id + '/QuarterlyPrices']; + const currencyLabel: string = Currency.getCurrencyLabelByEdgeId(this.edge.id); this.priceWithCurrency = Utils.CONVERT_PRICE_TO_CENT_PER_KWH(2, currencyLabel)(quarterlyPrice); } } diff --git a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/modal.ts b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/modal.ts index 6074caa5241..5c5ba73e90a 100644 --- a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/modal.ts +++ b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/modal.ts @@ -39,8 +39,8 @@ export class ModalComponent extends AbstractModal { } protected override onCurrentData(currentData: CurrentData): void { - var quarterlyPrice = currentData.allComponents[this.component.id + '/QuarterlyPrices']; - var currencyLabel: string = Currency.getCurrencyLabelByEdgeId(this.edge?.id); + const quarterlyPrice = currentData.allComponents[this.component.id + '/QuarterlyPrices']; + const currencyLabel: string = Currency.getCurrencyLabelByEdgeId(this.edge?.id); this.priceWithCurrency = this.Utils.CONVERT_PRICE_TO_CENT_PER_KWH(2, currencyLabel)(quarterlyPrice); } } diff --git a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/powerSocChart.ts b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/powerSocChart.ts index bba1865508f..cf839777858 100644 --- a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/powerSocChart.ts +++ b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/powerSocChart.ts @@ -24,7 +24,7 @@ export class SchedulePowerAndSocChartComponent extends AbstractHistoryChart impl public ngOnChanges() { this.updateChart(); - }; + } constructor( protected override service: Service, @@ -194,14 +194,14 @@ export class SchedulePowerAndSocChartComponent extends AbstractHistoryChart impl this.options.scales.x['ticks'] = { source: 'auto', autoSkip: false }; this.options.scales.x.ticks.callback = function (value, index, values) { - var date = new Date(value); + const date = new Date(value); // Display the label only if the minutes are zero (full hour) return date.getMinutes() === 0 ? date.getHours() + ':00' : ''; }; this.options.scales[ChartAxis.RIGHT].grid.display = false; - }; + } protected setLabel() { this.options = this.createDefaultChartOptions(); diff --git a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/statePriceChart.ts b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/statePriceChart.ts index bf900b61e4c..3edc5233d72 100644 --- a/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/statePriceChart.ts +++ b/ui/src/app/edge/live/Controller/Ess/TimeOfUseTariff/modal/statePriceChart.ts @@ -28,7 +28,7 @@ export class ScheduleStateAndPriceChartComponent extends AbstractHistoryChart im public ngOnChanges() { this.currencyLabel = Currency.getCurrencyLabelByEdgeId(this.edge.id); this.updateChart(); - }; + } constructor( protected override service: Service, diff --git a/ui/src/app/edge/live/Controller/Evcs/administration/administration.component.ts b/ui/src/app/edge/live/Controller/Evcs/administration/administration.component.ts index 9bd6e121c86..e1ffd2103e3 100644 --- a/ui/src/app/edge/live/Controller/Evcs/administration/administration.component.ts +++ b/ui/src/app/edge/live/Controller/Evcs/administration/administration.component.ts @@ -36,7 +36,7 @@ export class AdministrationComponent implements OnInit { updateZoeMode(event: CustomEvent) { let newValue = this.evcsComponent.properties['minHwCurrent']; - let oldValue = this.evcsComponent.properties['minHwCurrent']; + const oldValue = this.evcsComponent.properties['minHwCurrent']; if (event.detail.checked == true) { newValue = 10000; diff --git a/ui/src/app/edge/live/Controller/Evcs/flat/flat.ts b/ui/src/app/edge/live/Controller/Evcs/flat/flat.ts index e135023969c..ff43a24e529 100644 --- a/ui/src/app/edge/live/Controller/Evcs/flat/flat.ts +++ b/ui/src/app/edge/live/Controller/Evcs/flat/flat.ts @@ -56,9 +56,9 @@ export class FlatComponent extends AbstractFlatWidget { new ChannelAddress(this.component.id, 'SetChargePowerLimit'), ]; - let controllers = this.config.getComponentsByFactory("Controller.Evcs"); - for (let controller of controllers) { - let properties = controller.properties; + const controllers = this.config.getComponentsByFactory("Controller.Evcs"); + for (const controller of controllers) { + const properties = controller.properties; if ("evcs.id" in properties && properties["evcs.id"] === this.componentId) { this.controller = controller; result.push(new ChannelAddress(controller.id, '_PropertyEnabledCharging')); @@ -164,7 +164,7 @@ export class FlatComponent extends AbstractFlatWidget { } formatNumber(i: number) { - let round = Math.ceil(i / 100) * 100; + const round = Math.ceil(i / 100) * 100; return round; } diff --git a/ui/src/app/edge/live/Controller/Evcs/modal/modal.ts b/ui/src/app/edge/live/Controller/Evcs/modal/modal.ts index 0b15af8a774..2a394e903e1 100644 --- a/ui/src/app/edge/live/Controller/Evcs/modal/modal.ts +++ b/ui/src/app/edge/live/Controller/Evcs/modal/modal.ts @@ -162,7 +162,7 @@ export class ModalComponent extends AbstractModal { */ protected updateForceMinPower(event: CustomEvent, currentController: EdgeConfig.Component, numberOfPhases: number) { - let newMinChargePower = event.detail.value / numberOfPhases; + const newMinChargePower = event.detail.value / numberOfPhases; this.formGroup.controls['forceChargeMinPower'].markAsDirty(); this.formGroup.controls['forceChargeMinPower'].setValue(newMinChargePower); } @@ -173,12 +173,12 @@ export class ModalComponent extends AbstractModal { protected updateRenaultZoeConfig() { if (this.controller && this.evcsComponent.properties['minHwCurrent'] == 10000) { - let oldMinChargePower = this.controller.properties.forceChargeMinPower; - let maxAllowedChargePower = 10 /* Ampere */ * 230; /* Volt */ + const oldMinChargePower = this.controller.properties.forceChargeMinPower; + const maxAllowedChargePower = 10 /* Ampere */ * 230; /* Volt */ if (oldMinChargePower < maxAllowedChargePower) { if (this.edge != null) { - let newMinChargePower = maxAllowedChargePower; + const newMinChargePower = maxAllowedChargePower; this.edge.updateComponentConfig(this.websocket, this.controller.id, [ { name: 'forceChargeMinPower', value: newMinChargePower }, ]).then(() => { @@ -234,7 +234,7 @@ export class ModalComponent extends AbstractModal { } protected formatNumber(i: number) { - let round = Math.ceil(i / 100) * 100; + const round = Math.ceil(i / 100) * 100; return round; } diff --git a/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/Io_ChannelSingleThreshold.ts b/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/Io_ChannelSingleThreshold.ts index 19e0ca5d936..450cd89fc59 100644 --- a/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/Io_ChannelSingleThreshold.ts +++ b/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/Io_ChannelSingleThreshold.ts @@ -31,7 +31,7 @@ export class Controller_Io_ChannelSingleThresholdComponent extends AbstractFlatW public switchConverter = Utils.CONVERT_WATT_TO_KILOWATT; protected override getChannelAddresses() { - let outputChannelAddress: string | string[] = this.component.properties['outputChannelAddress']; + const outputChannelAddress: string | string[] = this.component.properties['outputChannelAddress']; if (typeof outputChannelAddress === 'string') { this.outputChannel = ChannelAddress.fromString(outputChannelAddress); } else { diff --git a/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/modal/modal.component.ts b/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/modal/modal.component.ts index aea8230d957..05f2e79bb9c 100644 --- a/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/Io/ChannelSingleThreshold/modal/modal.component.ts @@ -91,7 +91,6 @@ export class Controller_Io_ChannelSingleThresholdModalComponent implements OnIni this.threshold.setValue(newThreshold); this.threshold.markAsDirty(); } else if (this.component.properties.threshold < 0) { - newThreshold = newThreshold; this.threshold.setValue(newThreshold); this.threshold.markAsDirty(); } @@ -124,7 +123,7 @@ export class Controller_Io_ChannelSingleThresholdModalComponent implements OnIni } public updateMode(event: CustomEvent) { - let oldMode = this.component.properties.mode; + const oldMode = this.component.properties.mode; let newMode: mode; switch (event.detail.value) { @@ -153,7 +152,7 @@ export class Controller_Io_ChannelSingleThresholdModalComponent implements OnIni } } - private convertToChannelAddress(inputMode: inputMode): String { + private convertToChannelAddress(inputMode: inputMode): string { switch (inputMode) { case 'SOC': return '_sum/EssSoc'; @@ -186,7 +185,7 @@ export class Controller_Io_ChannelSingleThresholdModalComponent implements OnIni if (this.edge.roleIsAtLeast('owner')) { if (this.minimumSwitchingTime.valid && this.threshold.valid && this.switchedLoadPower.valid) { if (this.threshold.value > this.switchedLoadPower.value) { - let updateComponentArray = []; + const updateComponentArray = []; Object.keys(this.formGroup.controls).forEach((element, index) => { if (this.formGroup.controls[element].dirty) { // catch inputMode and convert it to inputChannelAddress diff --git a/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/Io_FixDigitalOutput.ts b/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/Io_FixDigitalOutput.ts index 8a44bb877fd..fdaf6d1e271 100644 --- a/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/Io_FixDigitalOutput.ts +++ b/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/Io_FixDigitalOutput.ts @@ -19,7 +19,7 @@ export class Controller_Io_FixDigitalOutputComponent extends AbstractFlatWidget } protected override onCurrentData(currentData: CurrentData) { - let channel = currentData.allComponents[this.outputChannel]; + const channel = currentData.allComponents[this.outputChannel]; if (channel != null) { if (channel == 1) { this.state = this.translate.instant('General.on'); diff --git a/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/modal/modal.component.ts b/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/modal/modal.component.ts index ed67c543f09..aa8c5ece5fd 100644 --- a/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/Io/FixDigitalOutput/modal/modal.component.ts @@ -27,12 +27,12 @@ export class Controller_Io_FixDigitalOutputModalComponent { * @param event */ updateMode(event: CustomEvent) { - let oldMode = this.component.properties.isOn; + const oldMode = this.component.properties.isOn; // ion-segment button only supports string as type // https://ionicframework.com/docs/v4/api/segment-button - let newMode = (event.detail.value.toLowerCase() === 'true'); + const newMode = (event.detail.value.toLowerCase() === 'true'); this.edge.updateComponentConfig(this.websocket, this.component.id, [ { name: 'isOn', value: newMode }, diff --git a/ui/src/app/edge/live/Controller/Io/HeatingElement/flat/flat.ts b/ui/src/app/edge/live/Controller/Io/HeatingElement/flat/flat.ts index 3fbb1cd80a2..afc1d046a05 100644 --- a/ui/src/app/edge/live/Controller/Io/HeatingElement/flat/flat.ts +++ b/ui/src/app/edge/live/Controller/Io/HeatingElement/flat/flat.ts @@ -34,7 +34,7 @@ export class FlatComponent extends AbstractFlatWidget { this.component.properties['outputChannelPhaseL3']), ); - let channelAddresses: ChannelAddress[] = [ + const channelAddresses: ChannelAddress[] = [ new ChannelAddress(this.component.id, 'ForceStartAtSecondsOfDay'), ...this.outputChannelArray, new ChannelAddress(this.component.id, 'Status'), diff --git a/ui/src/app/edge/live/Controller/Io/HeatingElement/modal/modal.ts b/ui/src/app/edge/live/Controller/Io/HeatingElement/modal/modal.ts index ac03bb7e2cc..35a0e239d55 100644 --- a/ui/src/app/edge/live/Controller/Io/HeatingElement/modal/modal.ts +++ b/ui/src/app/edge/live/Controller/Io/HeatingElement/modal/modal.ts @@ -21,15 +21,15 @@ export class ModalComponent extends AbstractModal implements OnInit { protected readonly WorkMode = WorkMode; protected override getChannelAddresses(): ChannelAddress[] { - let outputChannelPhaseOne = ChannelAddress.fromString( + const outputChannelPhaseOne = ChannelAddress.fromString( this.component.properties['outputChannelPhaseL1']); - let outputChannelPhaseTwo = ChannelAddress.fromString( + const outputChannelPhaseTwo = ChannelAddress.fromString( this.component.properties['outputChannelPhaseL2']); - let outputChannelPhaseThree = ChannelAddress.fromString( + const outputChannelPhaseThree = ChannelAddress.fromString( this.component.properties['outputChannelPhaseL3']); this.outputChannelArray = [outputChannelPhaseOne, outputChannelPhaseTwo, outputChannelPhaseThree]; - let channelAddresses: ChannelAddress[] = [ + const channelAddresses: ChannelAddress[] = [ new ChannelAddress(this.component.id, 'ForceStartAtSecondsOfDay'), outputChannelPhaseOne, outputChannelPhaseTwo, diff --git a/ui/src/app/edge/live/Controller/Io/Heatpump/modal/modal.component.ts b/ui/src/app/edge/live/Controller/Io/Heatpump/modal/modal.component.ts index 3c8f5d027eb..5d7e1874d9a 100644 --- a/ui/src/app/edge/live/Controller/Io/Heatpump/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/Io/Heatpump/modal/modal.component.ts @@ -42,11 +42,11 @@ export class Controller_Io_HeatpumpModalComponent implements OnInit { automaticRecommendationSurplusPower: new FormControl(this.component.properties.automaticRecommendationSurplusPower), minimumSwitchingTime: new FormControl(this.component.properties.minimumSwitchingTime), }); - }; + } public updateControllerMode(event: CustomEvent) { - let oldMode = this.component.properties['mode']; - let newMode = event.detail.value; + const oldMode = this.component.properties['mode']; + const newMode = event.detail.value; if (this.edge != null) { this.edge.updateComponentConfig(this.websocket, this.component.id, [ @@ -77,7 +77,7 @@ export class Controller_Io_HeatpumpModalComponent implements OnInit { if (this.edge != null) { if (this.edge.roleIsAtLeast('owner')) { if (this.formGroup.controls['automaticRecommendationSurplusPower'].value < this.formGroup.controls['automaticForceOnSurplusPower'].value) { - let updateComponentArray = []; + const updateComponentArray = []; Object.keys(this.formGroup.controls).forEach((element, index) => { if (this.formGroup.controls[element].dirty) { updateComponentArray.push({ name: Object.keys(this.formGroup.controls)[index], value: this.formGroup.controls[element].value }); diff --git a/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/Asymmetric.ts b/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/Asymmetric.ts index a8f1df8096d..08c2f7cfc1c 100644 --- a/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/Asymmetric.ts +++ b/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/Asymmetric.ts @@ -29,13 +29,13 @@ export class Controller_Asymmetric_PeakShavingComponent extends AbstractFlatWidg protected override onCurrentData(currentData: CurrentData) { - let activePowerArray: number[] = [ + const activePowerArray: number[] = [ currentData.allComponents[this.meterId + '/ActivePowerL1'], currentData.allComponents[this.meterId + '/ActivePowerL2'], currentData.allComponents[this.meterId + '/ActivePowerL3'], ]; - let name: string[] = ['L1', 'L2', 'L3']; + const name: string[] = ['L1', 'L2', 'L3']; this.mostStressedPhase.next({ diff --git a/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/modal/modal.component.ts b/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/modal/modal.component.ts index be3221fbcd6..68988b5cf20 100644 --- a/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/PeakShaving/Asymmetric/modal/modal.component.ts @@ -44,7 +44,7 @@ export class Controller_Asymmetric_PeakShavingModalComponent implements OnInit { if (this.edge.roleIsAtLeast('owner')) { if (this.formGroup.controls['peakShavingPower'].valid && this.formGroup.controls['rechargePower'].valid) { if (this.formGroup.controls['peakShavingPower'].value >= this.formGroup.controls['rechargePower'].value) { - let updateComponentArray = []; + const updateComponentArray = []; Object.keys(this.formGroup.controls).forEach((element, index) => { if (this.formGroup.controls[element].dirty) { updateComponentArray.push({ name: Object.keys(this.formGroup.controls)[index], value: this.formGroup.controls[element].value }); diff --git a/ui/src/app/edge/live/Controller/PeakShaving/Symmetric/modal/modal.component.ts b/ui/src/app/edge/live/Controller/PeakShaving/Symmetric/modal/modal.component.ts index b2983aa49fa..e53c0cc60c5 100644 --- a/ui/src/app/edge/live/Controller/PeakShaving/Symmetric/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/PeakShaving/Symmetric/modal/modal.component.ts @@ -41,11 +41,11 @@ export class Controller_Symmetric_PeakShavingModalComponent implements OnInit { applyChanges() { if (this.edge != null) { if (this.edge.roleIsAtLeast('owner')) { - let peakShavingPower = this.formGroup.controls['peakShavingPower']; - let rechargePower = this.formGroup.controls['rechargePower']; + const peakShavingPower = this.formGroup.controls['peakShavingPower']; + const rechargePower = this.formGroup.controls['rechargePower']; if (peakShavingPower.valid && rechargePower.valid) { if (peakShavingPower.value >= rechargePower.value) { - let updateComponentArray = []; + const updateComponentArray = []; Object.keys(this.formGroup.controls).forEach((element, index) => { if (this.formGroup.controls[element].dirty) { updateComponentArray.push({ name: Object.keys(this.formGroup.controls)[index], value: this.formGroup.controls[element].value }); diff --git a/ui/src/app/edge/live/Controller/PeakShaving/Symmetric_TimeSlot/modal/modal.component.ts b/ui/src/app/edge/live/Controller/PeakShaving/Symmetric_TimeSlot/modal/modal.component.ts index 60ca3ab2c31..ce717a33a0b 100644 --- a/ui/src/app/edge/live/Controller/PeakShaving/Symmetric_TimeSlot/modal/modal.component.ts +++ b/ui/src/app/edge/live/Controller/PeakShaving/Symmetric_TimeSlot/modal/modal.component.ts @@ -67,11 +67,11 @@ export class Controller_Symmetric_TimeSlot_PeakShavingModalComponent implements applyChanges() { if (this.edge != null) { if (this.edge.roleIsAtLeast('owner')) { - let peakShavingPower = this.formGroup.controls['peakShavingPower']; - let rechargePower = this.formGroup.controls['rechargePower']; + const peakShavingPower = this.formGroup.controls['peakShavingPower']; + const rechargePower = this.formGroup.controls['rechargePower']; if (peakShavingPower.valid && rechargePower.valid) { if (peakShavingPower.value >= rechargePower.value) { - let updateComponentArray = []; + const updateComponentArray = []; Object.keys(this.formGroup.controls).forEach((element, index) => { if (this.formGroup.controls[element].dirty) { if (Object.keys(this.formGroup.controls)[index] == 'slowChargePower') { diff --git a/ui/src/app/edge/live/Io/Api_DigitalInput/Io_Api_DigitalInput.ts b/ui/src/app/edge/live/Io/Api_DigitalInput/Io_Api_DigitalInput.ts index 768627dfb99..c0980557c66 100644 --- a/ui/src/app/edge/live/Io/Api_DigitalInput/Io_Api_DigitalInput.ts +++ b/ui/src/app/edge/live/Io/Api_DigitalInput/Io_Api_DigitalInput.ts @@ -15,13 +15,13 @@ export class Io_Api_DigitalInputComponent extends AbstractFlatWidget { public ioComponentCount = 0; protected override getChannelAddresses() { - let channels: ChannelAddress[] = []; + const channels: ChannelAddress[] = []; this.service.getConfig().then(config => { this.ioComponents = config.getComponentsImplementingNature("io.openems.edge.io.api.DigitalInput").filter(component => component.isEnabled); - for (let component of this.ioComponents) { + for (const component of this.ioComponents) { - for (let channel in component.channels) { + for (const channel in component.channels) { channels.push( new ChannelAddress(component.id, channel), ); diff --git a/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/Evcs_Api_Cluster.ts b/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/Evcs_Api_Cluster.ts index f8d286cbf31..4b4bfa0d57f 100644 --- a/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/Evcs_Api_Cluster.ts +++ b/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/Evcs_Api_Cluster.ts @@ -11,7 +11,7 @@ import { Evcs_Api_ClusterModalComponent } from './modal/evcsCluster-modal.page'; export class Evcs_Api_ClusterComponent extends AbstractFlatWidget { public channelAddresses: ChannelAddress[] = []; - public evcsIdsInCluster: String[] = []; + public evcsIdsInCluster: string[] = []; public evcssInCluster: EdgeConfig.Component[] = []; public evcsComponent: EdgeConfig.Component = null; public evcsMap: { [sourceId: string]: EdgeConfig.Component } = {}; @@ -22,9 +22,9 @@ export class Evcs_Api_ClusterComponent extends AbstractFlatWidget { protected override getChannelAddresses() { this.evcsIdsInCluster = this.config.components[this.componentId].properties["evcs.ids"]; - let nature = 'io.openems.edge.evcs.api.Evcs'; + const nature = 'io.openems.edge.evcs.api.Evcs'; - for (let component of this.config.getComponentsImplementingNature(nature)) { + for (const component of this.config.getComponentsImplementingNature(nature)) { if (this.evcsIdsInCluster.includes(component.id)) { this.evcssInCluster.push(component); this.fillChannelAddresses(component.id, this.channelAddresses); @@ -54,7 +54,7 @@ export class Evcs_Api_ClusterComponent extends AbstractFlatWidget { this.evcsMap[evcs.id] = null; }); - let controllers = this.config.getComponentsByFactory("Controller.Evcs"); + const controllers = this.config.getComponentsByFactory("Controller.Evcs"); // Adds the controllers to the each charging stations controllers.forEach(controller => { diff --git a/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcs-chart/evcs.chart.ts b/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcs-chart/evcs.chart.ts index 43997648b4b..ad1ce0727d7 100644 --- a/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcs-chart/evcs.chart.ts +++ b/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcs-chart/evcs.chart.ts @@ -54,10 +54,10 @@ export class EvcsChartComponent implements OnInit, OnChanges { } this.loading = true; let index = 0; - for (let evcsId in this.evcsMap) { - let chargePower = this.edge.currentData.value.channel[evcsId + '/ChargePower']; - let chargePowerKW = chargePower / 1000.0; - let alias = this.evcsConfigMap[evcsId].properties.alias; + for (const evcsId in this.evcsMap) { + const chargePower = this.edge.currentData.value.channel[evcsId + '/ChargePower']; + const chargePowerKW = chargePower / 1000.0; + const alias = this.evcsConfigMap[evcsId].properties.alias; if (this.datasets[index] == null) { this.datasets.push({ label: alias, @@ -70,19 +70,18 @@ export class EvcsChartComponent implements OnInit, OnChanges { this.datasets[index].data = [chargePowerKW != null ? chargePowerKW : 0]; } index++; - }; + } this.loading = false; } getMaxPower() { - let maxPower: number; - let minPower = 22; + const minPower = 22; let maxHW = this.currentData[this.componentId + '/MaximumHardwarePower']; let chargePower = this.currentData[this.componentId + '/ChargePower']; maxHW = maxHW == null ? minPower : maxHW / 1000; chargePower = chargePower == null ? 0 : chargePower / 1000; - maxPower = chargePower < minPower || maxPower < minPower ? minPower : maxHW; + const maxPower: number = chargePower < minPower || maxHW; return Math.round(maxPower); } } @@ -132,7 +131,7 @@ export const DEFAULT_BAR_CHART_OPTIONS: BarChartOptions = { label(tooltipItems: BarChartTooltipItem, data: Data): string { let value: number = tooltipItems.yLabel; //.toFixed(2); value = parseFloat(value.toFixed(2)); - let label = data.datasets[tooltipItems.datasetIndex].label; + const label = data.datasets[tooltipItems.datasetIndex].label; return label + ": " + value.toLocaleString('de-DE') + " kW"; }, }, diff --git a/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcsCluster-modal.page.ts b/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcsCluster-modal.page.ts index 838ccc9e045..2ae12fc26fe 100644 --- a/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcsCluster-modal.page.ts +++ b/ui/src/app/edge/live/Multiple/Evcs_Api_Cluster/modal/evcsCluster-modal.page.ts @@ -63,10 +63,10 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { } doReorder(ev: any) { - let oldListOrder = this.prioritizedEvcsList; + const oldListOrder = this.prioritizedEvcsList; this.prioritizedEvcsList = ev.detail.complete(this.prioritizedEvcsList); - let newListOrder = this.prioritizedEvcsList; + const newListOrder = this.prioritizedEvcsList; if (this.edge != null) { this.edge.updateComponentConfig(this.websocket, this.config.id, [ @@ -92,7 +92,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { * @param event */ updateChargeMode(event: CustomEvent, currentController: EdgeConfig.Component) { - let oldChargeMode = currentController.properties.chargeMode; + const oldChargeMode = currentController.properties.chargeMode; let newChargeMode: ChargeMode; switch (event.detail.value) { @@ -121,7 +121,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { * Changed the Priority between the components of the charging session */ priorityChanged(event: CustomEvent, currentController: EdgeConfig.Component) { - let oldPriority = currentController.properties.priority; + const oldPriority = currentController.properties.priority; let newPriority: Priority; switch (event.detail.value) { @@ -153,7 +153,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { * @param event */ updateForceMinPower(event: CustomEvent, currentController: EdgeConfig.Component, numberOfPhases: number) { - let oldMinChargePower = currentController.properties.forceChargeMinPower; + const oldMinChargePower = currentController.properties.forceChargeMinPower; let newMinChargePower = event.detail.value; newMinChargePower /= numberOfPhases; @@ -177,8 +177,8 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { * @param event */ updateDefaultMinPower(event: CustomEvent, currentController: EdgeConfig.Component) { - let oldMinChargePower = currentController.properties.defaultChargeMinPower; - let newMinChargePower = event.detail.value; + const oldMinChargePower = currentController.properties.defaultChargeMinPower; + const newMinChargePower = event.detail.value; if (this.edge != null) { this.edge.updateComponentConfig(this.websocket, currentController.id, [ @@ -194,7 +194,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { } } - currentLimitChanged(event: CustomEvent, property: String) { + currentLimitChanged(event: CustomEvent, property: string) { } @@ -206,7 +206,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { */ allowMinimumChargePower(event: CustomEvent, phases: number, currentController: EdgeConfig.Component) { - let oldMinChargePower = currentController.properties.defaultChargeMinPower; + const oldMinChargePower = currentController.properties.defaultChargeMinPower; let newMinChargePower = 0; if (oldMinChargePower == null || oldMinChargePower == 0) { @@ -233,8 +233,8 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { */ enableOrDisableCharging(event: CustomEvent, currentController: EdgeConfig.Component) { - let oldChargingState = currentController.properties.enabledCharging; - let newChargingState = !oldChargingState; + const oldChargingState = currentController.properties.enabledCharging; + const newChargingState = !oldChargingState; if (this.edge != null) { this.edge.updateComponentConfig(this.websocket, currentController.id, [ { name: 'enabledCharging', value: newChargingState }, @@ -255,7 +255,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { * @param state * @param plug */ - getState(power: Number, state: number, plug: number, currentController: EdgeConfig.Component) { + getState(power: number, state: number, plug: number, currentController: EdgeConfig.Component) { if (currentController != null) { if (currentController.properties.enabledCharging != null && currentController.properties.enabledCharging == false) { return this.translate.instant('Edge.Index.Widgets.EVCS.chargingStationDeactivated'); @@ -302,7 +302,7 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { * @param i */ formatNumber(i: number) { - let round = Math.ceil(i / 100) * 100; + const round = Math.ceil(i / 100) * 100; return round; } @@ -324,9 +324,9 @@ export class Evcs_Api_ClusterModalComponent implements OnInit { return this.sumOfChannel("ChargePower"); } - private sumOfChannel(channel: String): number { + private sumOfChannel(channel: string): number { - let sum = 0;/* + const sum = 0;/* this.evcsMap.forEach(station => { let channelValue = this.edge.currentData.value.channel[station.id + "/" + channel]; if (channelValue != null) { diff --git a/ui/src/app/edge/live/common/autarchy/modal/modal.spec.ts b/ui/src/app/edge/live/common/autarchy/modal/modal.spec.ts index 22049048563..f21a09ac974 100644 --- a/ui/src/app/edge/live/common/autarchy/modal/modal.spec.ts +++ b/ui/src/app/edge/live/common/autarchy/modal/modal.spec.ts @@ -10,7 +10,7 @@ export function expectView(testContext: TestContext, viewContext: OeFormlyViewTe const generatedView = OeFormlyViewTester.apply(ModalComponent.generateView(testContext.translate), viewContext); expect(generatedView).toEqual(view); -}; +} describe('Autarchy - Modal', () => { let TEST_CONTEXT: TestContext; diff --git a/ui/src/app/edge/live/common/consumption/flat/flat.ts b/ui/src/app/edge/live/common/consumption/flat/flat.ts index efe44a76668..8170a24be7d 100644 --- a/ui/src/app/edge/live/common/consumption/flat/flat.ts +++ b/ui/src/app/edge/live/common/consumption/flat/flat.ts @@ -18,7 +18,7 @@ export class FlatComponent extends AbstractFlatWidget { protected override getChannelAddresses() { - let channelAddresses: ChannelAddress[] = [ + const channelAddresses: ChannelAddress[] = [ new ChannelAddress('_sum', 'ConsumptionActivePower'), // TODO should be moved to Modal @@ -31,7 +31,7 @@ export class FlatComponent extends AbstractFlatWidget { this.consumptionMeters = this.config.getComponentsImplementingNature("io.openems.edge.meter.api.ElectricityMeter") .filter(component => component.isEnabled && this.config.isTypeConsumptionMetered(component)); - for (let component of this.consumptionMeters) { + for (const component of this.consumptionMeters) { channelAddresses.push( new ChannelAddress(component.id, 'ActivePower'), new ChannelAddress(component.id, 'ActivePowerL1'), @@ -45,7 +45,7 @@ export class FlatComponent extends AbstractFlatWidget { .filter(component => !(component.factoryId == 'Evcs.Cluster.SelfConsumption') && !(component.factoryId == 'Evcs.Cluster.PeakShaving') && !component.isEnabled == false); - for (let component of this.evcss) { + for (const component of this.evcss) { channelAddresses.push( new ChannelAddress(component.id, 'ChargePower'), ); @@ -61,14 +61,14 @@ export class FlatComponent extends AbstractFlatWidget { // TODO move sums to Model // Iterate over evcsComponents to get ChargePower for every component - for (let component of this.evcss) { + for (const component of this.evcss) { if (currentData.allComponents[component.id + '/ChargePower']) { this.evcsSumOfChargePower += currentData.allComponents[component.id + '/ChargePower']; } } // Iterate over evcsComponents to get ChargePower for every component - for (let component of this.consumptionMeters) { + for (const component of this.consumptionMeters) { if (currentData.allComponents[component.id + '/ActivePower']) { consumptionMetersSumOfActivePower += currentData.allComponents[component.id + '/ActivePower']; } diff --git a/ui/src/app/edge/live/common/consumption/modal/modal.constants.spec.ts b/ui/src/app/edge/live/common/consumption/modal/modal.constants.spec.ts index 9909b58d850..dbb19594bed 100644 --- a/ui/src/app/edge/live/common/consumption/modal/modal.constants.spec.ts +++ b/ui/src/app/edge/live/common/consumption/modal/modal.constants.spec.ts @@ -10,4 +10,4 @@ export function expectView(config: EdgeConfig, viewContext: OeFormlyViewTester.C const generatedView = OeFormlyViewTester.apply(ModalComponent.generateView(DummyConfig.convertDummyEdgeConfigToRealEdgeConfig(config), testContext.translate), viewContext); expect(generatedView).toEqual(view); -}; +} diff --git a/ui/src/app/edge/live/common/consumption/modal/modal.ts b/ui/src/app/edge/live/common/consumption/modal/modal.ts index 2ca55aba40e..164083897d6 100644 --- a/ui/src/app/edge/live/common/consumption/modal/modal.ts +++ b/ui/src/app/edge/live/common/consumption/modal/modal.ts @@ -26,7 +26,7 @@ export class ModalComponent extends AbstractFormlyComponent { const consumptionMeters: EdgeConfig.Component[] | null = config.getComponentsImplementingNature("io.openems.edge.meter.api.ElectricityMeter") .filter(component => component.isEnabled && config.isTypeConsumptionMetered(component)); - let lines: OeFormlyField[] = []; + const lines: OeFormlyField[] = []; // Total lines.push({ @@ -98,7 +98,7 @@ export class ModalComponent extends AbstractFormlyComponent { lines.push({ type: 'horizontal-line' }); // OtherPower - let channelsToSubscribe: ChannelAddress[] = [new ChannelAddress('_sum', 'ConsumptionActivePower')]; + const channelsToSubscribe: ChannelAddress[] = [new ChannelAddress('_sum', 'ConsumptionActivePower')]; evcss.forEach(evcs => channelsToSubscribe.push(new ChannelAddress(evcs.id, 'ChargePower'))); consumptionMeters.forEach(meter => { diff --git a/ui/src/app/edge/live/common/grid/flat/flat.ts b/ui/src/app/edge/live/common/grid/flat/flat.ts index f899ec73630..c1a86e14098 100644 --- a/ui/src/app/edge/live/common/grid/flat/flat.ts +++ b/ui/src/app/edge/live/common/grid/flat/flat.ts @@ -20,7 +20,7 @@ export class FlatComponent extends AbstractFlatWidget { public gridMode: number; protected override getChannelAddresses(): ChannelAddress[] { - let channelAddresses: ChannelAddress[] = [ + const channelAddresses: ChannelAddress[] = [ FlatComponent.GRID_ACTIVE_POWER, FlatComponent.GRID_MODE, // TODO should be moved to Modal @@ -32,7 +32,7 @@ export class FlatComponent extends AbstractFlatWidget { } protected override onCurrentData(currentData: CurrentData) { this.gridMode = currentData.allComponents[FlatComponent.GRID_MODE.toString()]; - let gridActivePower = currentData.allComponents[FlatComponent.GRID_ACTIVE_POWER.toString()]; + const gridActivePower = currentData.allComponents[FlatComponent.GRID_ACTIVE_POWER.toString()]; this.gridBuyPower = gridActivePower; this.gridSellPower = Utils.multiplySafely(gridActivePower, -1); } diff --git a/ui/src/app/edge/live/common/grid/modal/constants.spec.ts b/ui/src/app/edge/live/common/grid/modal/constants.spec.ts index 8a1361deae9..b5f1150d352 100644 --- a/ui/src/app/edge/live/common/grid/modal/constants.spec.ts +++ b/ui/src/app/edge/live/common/grid/modal/constants.spec.ts @@ -7,4 +7,4 @@ import { ModalComponent } from "./modal"; export function expectView(config: EdgeConfig, role: Role, viewContext: OeFormlyViewTester.Context, testContext: TestContext, view: OeFormlyViewTester.View): void { expect(OeFormlyViewTester.apply(ModalComponent.generateView(config, role, testContext.translate), viewContext)) .toEqual(view); -}; +} diff --git a/ui/src/app/edge/live/common/grid/modal/modal.ts b/ui/src/app/edge/live/common/grid/modal/modal.ts index 7308d88c41e..22edf6859a7 100644 --- a/ui/src/app/edge/live/common/grid/modal/modal.ts +++ b/ui/src/app/edge/live/common/grid/modal/modal.ts @@ -20,7 +20,7 @@ export class ModalComponent extends AbstractFormlyComponent { public static generateView(config: EdgeConfig, role: Role, translate: TranslateService): OeFormlyView { // Grid-Mode - let lines: OeFormlyField[] = [{ + const lines: OeFormlyField[] = [{ type: 'channel-line', name: translate.instant("General.offGrid"), channel: '_sum/GridMode', @@ -28,7 +28,7 @@ export class ModalComponent extends AbstractFormlyComponent { converter: Converter.HIDE_VALUE, }]; - var gridMeters = Object.values(config.components).filter(component => config?.isTypeGrid(component)); + const gridMeters = Object.values(config.components).filter(component => config?.isTypeGrid(component)); // Sum Channels (if more than one meter) if (gridMeters.length > 1) { @@ -50,7 +50,7 @@ export class ModalComponent extends AbstractFormlyComponent { } // Individual Meters - for (var meter of gridMeters) { + for (const meter of gridMeters) { if (gridMeters.length == 1) { // Two lines if there is only one meter (= same visualization as with Sum Channels) lines.push( @@ -113,7 +113,7 @@ export class ModalComponent extends AbstractFormlyComponent { } private static generatePhasesLineItems(role: Role, phase: string, component: EdgeConfig.Component) { - let children: OeFormlyField[] = []; + const children: OeFormlyField[] = []; if (Role.isAtLeast(role, Role.INSTALLER)) { children.push({ type: 'item', diff --git a/ui/src/app/edge/live/common/production/modal/modal.ts b/ui/src/app/edge/live/common/production/modal/modal.ts index d1a62242091..9a3b7e10c01 100644 --- a/ui/src/app/edge/live/common/production/modal/modal.ts +++ b/ui/src/app/edge/live/common/production/modal/modal.ts @@ -16,7 +16,7 @@ export class ModalComponent extends AbstractModal { public isAsymmetric: boolean = false; protected override getChannelAddresses() { - let channelAddresses: ChannelAddress[] = []; + const channelAddresses: ChannelAddress[] = []; // Get Chargers this.chargerComponents = diff --git a/ui/src/app/edge/live/common/selfconsumption/modal/modal.spec.ts b/ui/src/app/edge/live/common/selfconsumption/modal/modal.spec.ts index fb9447c958c..a46a0608e57 100644 --- a/ui/src/app/edge/live/common/selfconsumption/modal/modal.spec.ts +++ b/ui/src/app/edge/live/common/selfconsumption/modal/modal.spec.ts @@ -11,7 +11,7 @@ export function expectView(testContext: TestContext, viewContext: OeFormlyViewTe const generatedView = OeFormlyViewTester.apply(ModalComponent.generateView(testContext.translate), viewContext); expect(generatedView).toEqual(view); -}; +} describe('SelfConsumption - Modal', () => { let TEST_CONTEXT: TestContext; diff --git a/ui/src/app/edge/live/common/storage/modal/modal.component.ts b/ui/src/app/edge/live/common/storage/modal/modal.component.ts index 49cce2ba416..035eb139a8d 100644 --- a/ui/src/app/edge/live/common/storage/modal/modal.component.ts +++ b/ui/src/app/edge/live/common/storage/modal/modal.component.ts @@ -42,10 +42,10 @@ export class StorageModalComponent implements OnInit, OnDestroy { this.controllerIsRequiredEdgeVersion = this.edge.isVersionAtLeast('2023.2.5'); this.isAtLeastInstaller = this.edge.roleIsAtLeast(Role.INSTALLER); - let emergencyReserveCtrl = this.config.getComponentsByFactory('Controller.Ess.EmergencyCapacityReserve'); - let prepareBatteryExtensionCtrl = this.config.getComponentsByFactory("Controller.Ess.PrepareBatteryExtension"); - let components = [...prepareBatteryExtensionCtrl, ...emergencyReserveCtrl].filter(component => component.isEnabled).reduce((result, component) => { - let essId = component.properties['ess.id']; + const emergencyReserveCtrl = this.config.getComponentsByFactory('Controller.Ess.EmergencyCapacityReserve'); + const prepareBatteryExtensionCtrl = this.config.getComponentsByFactory("Controller.Ess.PrepareBatteryExtension"); + const components = [...prepareBatteryExtensionCtrl, ...emergencyReserveCtrl].filter(component => component.isEnabled).reduce((result, component) => { + const essId = component.properties['ess.id']; if (result[essId] == null) { result[essId] = []; } @@ -53,9 +53,9 @@ export class StorageModalComponent implements OnInit, OnDestroy { return result; }, {}); - let channelAddresses: ChannelAddress[] = []; - for (let essId in prepareBatteryExtensionCtrl) { - let controller = prepareBatteryExtensionCtrl[essId]; + const channelAddresses: ChannelAddress[] = []; + for (const essId in prepareBatteryExtensionCtrl) { + const controller = prepareBatteryExtensionCtrl[essId]; channelAddresses.push( new ChannelAddress(controller.id, "_PropertyIsRunning"), new ChannelAddress(controller.id, "_PropertyTargetTime"), @@ -70,16 +70,16 @@ export class StorageModalComponent implements OnInit, OnDestroy { this.edge.currentData .subscribe(currentData => { - let controls: FormGroup = new FormGroup({}); - for (let essId of Object.keys(components)) { - let controllers = components[essId]; + const controls: FormGroup = new FormGroup({}); + for (const essId of Object.keys(components)) { + const controllers = components[essId]; - let controllerFrmGrp: FormGroup = new FormGroup({}); - for (let controller of (controllers as EdgeConfig.Component[])) { + const controllerFrmGrp: FormGroup = new FormGroup({}); + for (const controller of (controllers as EdgeConfig.Component[])) { if (controller.factoryId == 'Controller.Ess.EmergencyCapacityReserve') { - let reserveSoc = currentData.channel[controller.id + "/_PropertyReserveSoc"] ?? 20 /* default Reserve-Soc */; - let isReserveSocEnabled = currentData.channel[controller.id + "/_PropertyIsReserveSocEnabled"] == 1; + const reserveSoc = currentData.channel[controller.id + "/_PropertyReserveSoc"] ?? 20 /* default Reserve-Soc */; + const isReserveSocEnabled = currentData.channel[controller.id + "/_PropertyIsReserveSocEnabled"] == 1; controllerFrmGrp.addControl('emergencyReserveController', this.formBuilder.group({ @@ -90,16 +90,16 @@ export class StorageModalComponent implements OnInit, OnDestroy { ); } else if (controller.factoryId == 'Controller.Ess.PrepareBatteryExtension') { - let isRunning = currentData.channel[controller.id + "/_PropertyIsRunning"] == 1; + const isRunning = currentData.channel[controller.id + "/_PropertyIsRunning"] == 1; // Because of ionic segment buttons only accepting a string value, i needed to convert it - let targetTimeSpecified = (currentData.channel[controller.id + "/_PropertyTargetTimeSpecified"] == 1).toString();; + const targetTimeSpecified = (currentData.channel[controller.id + "/_PropertyTargetTimeSpecified"] == 1).toString(); let targetTime = currentData.channel[controller.id + "/_PropertyTargetTime"]; - let targetSoc = currentData.channel[controller.id + "/_PropertyTargetSoc"]; - let targetTimeBuffer = currentData.channel[controller.id + "/_PropertyTargetTimeBuffer"]; - let epochSeconds = currentData.channel[controller.id + "/ExpectedStartEpochSeconds"]; + const targetSoc = currentData.channel[controller.id + "/_PropertyTargetSoc"]; + const targetTimeBuffer = currentData.channel[controller.id + "/_PropertyTargetTimeBuffer"]; + const epochSeconds = currentData.channel[controller.id + "/ExpectedStartEpochSeconds"]; - let expectedStartOfPreparation = new Date(0); + const expectedStartOfPreparation = new Date(0); expectedStartOfPreparation.setUTCSeconds(epochSeconds ?? 0); // If targetTime not set, not equals 0 or targetTime is no valid time, @@ -150,12 +150,12 @@ export class StorageModalComponent implements OnInit, OnDestroy { return; } - let updateArray: Map>> = new Map(); - for (let essId in this.formGroup.controls) { - let essGroups = this.formGroup.controls[essId]; + const updateArray: Map>> = new Map(); + for (const essId in this.formGroup.controls) { + const essGroups = this.formGroup.controls[essId]; - let emergencyReserveController = (essGroups.get('emergencyReserveController') as FormGroup)?.controls ?? {}; - for (let essGroup of Object.keys(emergencyReserveController)) { + const emergencyReserveController = (essGroups.get('emergencyReserveController') as FormGroup)?.controls ?? {}; + for (const essGroup of Object.keys(emergencyReserveController)) { if (emergencyReserveController[essGroup].dirty) { if (updateArray.get(emergencyReserveController['controllerId'].value)) { updateArray.get(emergencyReserveController['controllerId'].value).push(new Map().set(essGroup, emergencyReserveController[essGroup].value)); @@ -165,8 +165,8 @@ export class StorageModalComponent implements OnInit, OnDestroy { } } - let prepareBatteryExtensionController = (essGroups.get('prepareBatteryExtensionController') as FormGroup)?.controls ?? {}; - for (let essGroup of Object.keys(prepareBatteryExtensionController)) { + const prepareBatteryExtensionController = (essGroups.get('prepareBatteryExtensionController') as FormGroup)?.controls ?? {}; + for (const essGroup of Object.keys(prepareBatteryExtensionController)) { if (prepareBatteryExtensionController[essGroup].dirty) { // For simplicity, split targetTimeSpecified in 2 for template formControlName @@ -179,12 +179,12 @@ export class StorageModalComponent implements OnInit, OnDestroy { } } - for (let controllerId of updateArray.keys()) { - let controllers = updateArray.get(controllerId); - let properties: { name: string, value: any }[] = []; + for (const controllerId of updateArray.keys()) { + const controllers = updateArray.get(controllerId); + const properties: { name: string, value: any }[] = []; controllers.forEach((element) => { - let name = element.keys().next().value; - let value = element.values().next().value; + const name = element.keys().next().value; + const value = element.values().next().value; properties.push({ name: name, value: value, diff --git a/ui/src/app/edge/live/common/storage/storage.component.ts b/ui/src/app/edge/live/common/storage/storage.component.ts index a6041ff980e..f0ee2852496 100644 --- a/ui/src/app/edge/live/common/storage/storage.component.ts +++ b/ui/src/app/edge/live/common/storage/storage.component.ts @@ -25,7 +25,7 @@ export class StorageComponent extends AbstractFlatWidget { protected override getChannelAddresses() { - let channelAddresses: ChannelAddress[] = [ + const channelAddresses: ChannelAddress[] = [ new ChannelAddress('_sum', 'EssSoc'), // TODO should be moved to Modal @@ -44,8 +44,8 @@ export class StorageComponent extends AbstractFlatWidget { }, {}); - for (let essId in this.prepareBatteryExtensionCtrl) { - let controller = this.prepareBatteryExtensionCtrl[essId]; + for (const essId in this.prepareBatteryExtensionCtrl) { + const controller = this.prepareBatteryExtensionCtrl[essId]; channelAddresses.push( new ChannelAddress(controller.id, "CtrlIsBlockingEss"), new ChannelAddress(controller.id, "CtrlIsChargingEss"), @@ -66,7 +66,7 @@ export class StorageComponent extends AbstractFlatWidget { [component.properties['ess.id']]: component, }; }, {}); - for (let component of Object.values(this.emergencyReserveComponents)) { + for (const component of Object.values(this.emergencyReserveComponents)) { channelAddresses.push( new ChannelAddress(component.id, '_PropertyReserveSoc'), @@ -78,7 +78,7 @@ export class StorageComponent extends AbstractFlatWidget { this.chargerComponents = this.config .getComponentsImplementingNature("io.openems.edge.ess.dccharger.api.EssDcCharger") .filter(component => component.isEnabled); - for (let component of this.chargerComponents) { + for (const component of this.chargerComponents) { channelAddresses.push( new ChannelAddress(component.id, 'ActualPower'), ); @@ -91,7 +91,7 @@ export class StorageComponent extends AbstractFlatWidget { .getNatureIdsByFactoryId(component.factoryId) .includes("io.openems.edge.ess.api.MetaEss")); - for (let component of this.config + for (const component of this.config .getComponentsImplementingNature("io.openems.edge.ess.api.SymmetricEss") .filter(component => component.isEnabled && !this.config .getNatureIdsByFactoryId(component.factoryId) @@ -149,8 +149,8 @@ export class StorageComponent extends AbstractFlatWidget { protected override onCurrentData(currentData: CurrentData) { - for (let essId in this.prepareBatteryExtensionCtrl) { - let controller = this.prepareBatteryExtensionCtrl[essId]; + for (const essId in this.prepareBatteryExtensionCtrl) { + const controller = this.prepareBatteryExtensionCtrl[essId]; this.possibleBatteryExtensionMessage.set( essId, @@ -165,11 +165,11 @@ export class StorageComponent extends AbstractFlatWidget { } // Check total State_of_Charge for dynamical icon in widget-header - let soc = currentData.allComponents['_sum/EssSoc']; + const soc = currentData.allComponents['_sum/EssSoc']; this.storageIconStyle = 'storage-' + Utils.getStorageSocSegment(soc); - for (let essId in this.emergencyReserveComponents) { - let controller = this.emergencyReserveComponents[essId]; + for (const essId in this.emergencyReserveComponents) { + const controller = this.emergencyReserveComponents[essId]; controller['currentReserveSoc'] = currentData.allComponents[controller.id + '/_PropertyReserveSoc']; this.isEmergencyReserveEnabled[essId] = currentData.allComponents[controller.id + "/_PropertyIsReserveSocEnabled"] == 1 ? true : false; } @@ -206,7 +206,7 @@ export class StorageComponent extends AbstractFlatWidget { return '-'; } - let thisValue: number = (value / 1000); + const thisValue: number = (value / 1000); // Round thisValue to Integer when decimal place equals 0 if (thisValue > 0) { diff --git a/ui/src/app/edge/live/delayedselltogrid/modal/modal.component.ts b/ui/src/app/edge/live/delayedselltogrid/modal/modal.component.ts index 68b35025d85..b03668fc30c 100644 --- a/ui/src/app/edge/live/delayedselltogrid/modal/modal.component.ts +++ b/ui/src/app/edge/live/delayedselltogrid/modal/modal.component.ts @@ -42,11 +42,11 @@ export class DelayedSellToGridModalComponent implements OnInit { applyChanges() { if (this.edge != null) { if (this.edge.roleIsAtLeast('owner')) { - let continuousSellToGridPower = this.formGroup.controls['continuousSellToGridPower']; - let sellToGridPowerLimit = this.formGroup.controls['sellToGridPowerLimit']; + const continuousSellToGridPower = this.formGroup.controls['continuousSellToGridPower']; + const sellToGridPowerLimit = this.formGroup.controls['sellToGridPowerLimit']; if (continuousSellToGridPower.valid && sellToGridPowerLimit.valid) { if (sellToGridPowerLimit.value > continuousSellToGridPower.value) { - let updateComponentArray = []; + const updateComponentArray = []; Object.keys(this.formGroup.controls).forEach((element, index) => { if (this.formGroup.controls[element].dirty) { updateComponentArray.push({ name: Object.keys(this.formGroup.controls)[index], value: this.formGroup.controls[element].value }); diff --git a/ui/src/app/edge/live/energymonitor/chart/chart.component.ts b/ui/src/app/edge/live/energymonitor/chart/chart.component.ts index a7ba8f8b8e8..25ad7177fab 100644 --- a/ui/src/app/edge/live/energymonitor/chart/chart.component.ts +++ b/ui/src/app/edge/live/energymonitor/chart/chart.component.ts @@ -70,7 +70,7 @@ export class EnergymonitorChartComponent implements OnInit, OnDestroy { /* * Set values for energy monitor */ - let summary = currentData.summary; + const summary = currentData.summary; [this.consumptionSection, this.gridSection, this.productionSection, this.storageSection] .filter(section => section != null) .forEach(section => { @@ -91,8 +91,8 @@ export class EnergymonitorChartComponent implements OnInit, OnDestroy { } this.height = this.width = size; this.translation = `translate(${this.width / 2}, ${this.height / 2})`; - var outerRadius = Math.min(this.width, this.height) / 2; - var innerRadius = outerRadius - (outerRadius * 0.1378); + const outerRadius = Math.min(this.width, this.height) / 2; + const innerRadius = outerRadius - (outerRadius * 0.1378); // All sections from update() in section [this.consumptionSection, this.gridSection, this.productionSection, this.storageSection] .filter(section => section != null) diff --git a/ui/src/app/edge/live/energymonitor/chart/section/abstractsection.component.ts b/ui/src/app/edge/live/energymonitor/chart/section/abstractsection.component.ts index 85db3d1d101..3625b51d42b 100644 --- a/ui/src/app/edge/live/energymonitor/chart/section/abstractsection.component.ts +++ b/ui/src/app/edge/live/energymonitor/chart/section/abstractsection.component.ts @@ -73,7 +73,7 @@ export class EnergyFlow { if (energyFlow == null) { this.points = "0,0 0,0"; } else { - let p = energyFlow; + const p = energyFlow; this.points = p.topLeft.x + "," + p.topLeft.y + (p.middleTop ? " " + p.middleTop.x + "," + p.middleTop.y : "") + " " + p.topRight.x + "," + p.topRight.y @@ -86,7 +86,7 @@ export class EnergyFlow { if (animationEnergyFlow == null) { this.animationPoints = "0,0 0,0"; } else { - let p = animationEnergyFlow; + const p = animationEnergyFlow; this.animationPoints = p.topLeft.x + "," + p.topLeft.y + (p.middleTop ? " " + p.middleTop.x + "," + p.middleTop.y : "") + " " + p.topRight.x + "," + p.topRight.y @@ -253,8 +253,8 @@ export abstract class AbstractSection { valueRatio = Math.min(1, Math.max(-1, valueRatio)); break; } - let valueEndAngle = (this.getEndAngle() - startAngle) * valueRatio + startAngle; - let valueArc = this.getArc() + const valueEndAngle = (this.getEndAngle() - startAngle) * valueRatio + startAngle; + const valueArc = this.getArc() .startAngle(this.deg2rad(startAngle)) .endAngle(this.deg2rad(valueEndAngle)); this.valuePath = valueArc(); @@ -272,8 +272,8 @@ export abstract class AbstractSection { sumRatio *= 10; //radius * 1.2 for longer arrows - let svgEnergyFlow = this.getSvgEnergyFlow(sumRatio, this.energyFlow.radius * 1.2); - let svgAnimationEnergyFlow = this.getSvgAnimationEnergyFlow(sumRatio, this.energyFlow.radius * 1.2); + const svgEnergyFlow = this.getSvgEnergyFlow(sumRatio, this.energyFlow.radius * 1.2); + const svgAnimationEnergyFlow = this.getSvgAnimationEnergyFlow(sumRatio, this.energyFlow.radius * 1.2); this.energyFlow.update(svgEnergyFlow, svgAnimationEnergyFlow); } @@ -285,7 +285,7 @@ export abstract class AbstractSection { this.innerRadius = innerRadius; this.height = height; this.width = width; - let outlineArc = this.getArc() + const outlineArc = this.getArc() .startAngle(this.deg2rad(this.getStartAngle())) .endAngle(this.deg2rad(this.getEndAngle())); this.outlinePath = outlineArc(); @@ -298,7 +298,7 @@ export abstract class AbstractSection { /** * energy flow rectangle */ - let availableInnerRadius = innerRadius - this.square.image.y - this.square.image.length - 10; + const availableInnerRadius = innerRadius - this.square.image.y - this.square.image.length - 10; this.energyFlow = this.initEnergyFlow(availableInnerRadius); // now update also the value specific elements @@ -317,20 +317,20 @@ export abstract class AbstractSection { * ...fontsize of text; */ private getSquare(innerRadius: any): SvgSquare { - let width = innerRadius / 2.5; + const width = innerRadius / 2.5; - let textSize = width / 4; - let yText = textSize; + const textSize = width / 4; + const yText = textSize; - let numberSize = textSize - 3; - let yNumber = yText + 5 + numberSize; + const numberSize = textSize - 3; + const yNumber = yText + 5 + numberSize; - let imageSize = width; - let yImage = yNumber + 5; + const imageSize = width; + const yImage = yNumber + 5; - let length = yImage + imageSize; + const length = yImage + imageSize; - let xText = length / 2; + const xText = length / 2; return new SvgSquare( length, diff --git a/ui/src/app/edge/live/energymonitor/chart/section/consumption.component.ts b/ui/src/app/edge/live/energymonitor/chart/section/consumption.component.ts index ed4be8d24c4..f437f59fb88 100644 --- a/ui/src/app/edge/live/energymonitor/chart/section/consumption.component.ts +++ b/ui/src/app/edge/live/energymonitor/chart/section/consumption.component.ts @@ -86,8 +86,8 @@ export class ConsumptionSectionComponent extends AbstractSection implements OnIn } protected getSquarePosition(square: SvgSquare, innerRadius: number): SvgSquarePosition { - let x = innerRadius - 5 - square.length; - let y = (square.length / 2) * (-1); + const x = innerRadius - 5 - square.length; + const y = (square.length / 2) * (-1); return new SvgSquarePosition(x, y); } protected getImagePath(): string { @@ -111,9 +111,9 @@ export class ConsumptionSectionComponent extends AbstractSection implements OnIn } protected getSvgEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let p = { + const v = Math.abs(ratio); + const r = radius; + const p = { topLeft: { x: v, y: v * -1 }, middleLeft: { x: 0, y: 0 }, bottomLeft: { x: v, y: v }, @@ -132,9 +132,9 @@ export class ConsumptionSectionComponent extends AbstractSection implements OnIn } protected getSvgAnimationEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let animationWidth = (r * -1) - v; + const v = Math.abs(ratio); + const r = radius; + const animationWidth = (r * -1) - v; let p = { topLeft: { x: v, y: v * -1 }, middleLeft: { x: 0, y: 0 }, diff --git a/ui/src/app/edge/live/energymonitor/chart/section/grid.component.ts b/ui/src/app/edge/live/energymonitor/chart/section/grid.component.ts index bd135d15682..f02cef40162 100644 --- a/ui/src/app/edge/live/energymonitor/chart/section/grid.component.ts +++ b/ui/src/app/edge/live/energymonitor/chart/section/grid.component.ts @@ -142,8 +142,8 @@ export class GridSectionComponent extends AbstractSection implements OnInit, OnD } protected getSquarePosition(square: SvgSquare, innerRadius: number): SvgSquarePosition { - let x = (innerRadius - 5) * (-1); - let y = (square.length / 2) * (-1); + const x = (innerRadius - 5) * (-1); + const y = (square.length / 2) * (-1); return new SvgSquarePosition(x, y); } @@ -172,9 +172,9 @@ export class GridSectionComponent extends AbstractSection implements OnInit, OnD } protected getSvgEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let p = { + const v = Math.abs(ratio); + const r = radius; + const p = { bottomRight: { x: v * -1, y: v }, bottomLeft: { x: r * -1, y: v }, topRight: { x: v * -1, y: v * -1 }, @@ -193,9 +193,9 @@ export class GridSectionComponent extends AbstractSection implements OnInit, OnD } protected getSvgAnimationEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let animationWidth = r * -1 + v; + const v = Math.abs(ratio); + const r = radius; + const animationWidth = r * -1 + v; let p = { bottomRight: { x: v * -1, y: v }, bottomLeft: { x: r * -1, y: v }, diff --git a/ui/src/app/edge/live/energymonitor/chart/section/production.component.ts b/ui/src/app/edge/live/energymonitor/chart/section/production.component.ts index 8711e0466f0..becd9c8b94a 100644 --- a/ui/src/app/edge/live/energymonitor/chart/section/production.component.ts +++ b/ui/src/app/edge/live/energymonitor/chart/section/production.component.ts @@ -86,8 +86,8 @@ export class ProductionSectionComponent extends AbstractSection implements OnIni } protected getSquarePosition(square: SvgSquare, innerRadius: number): SvgSquarePosition { - let x = (square.length / 2) * (-1); - let y = (innerRadius - 10) * (-1); + const x = (square.length / 2) * (-1); + const y = (innerRadius - 10) * (-1); return new SvgSquarePosition(x, y); } @@ -113,9 +113,9 @@ export class ProductionSectionComponent extends AbstractSection implements OnIni } protected getSvgEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let p = { + const v = Math.abs(ratio); + const r = radius; + const p = { topLeft: { x: v * -1, y: r * -1 }, bottomLeft: { x: v * -1, y: v * -1 }, topRight: { x: v, y: r * -1 }, @@ -133,9 +133,9 @@ export class ProductionSectionComponent extends AbstractSection implements OnIni } protected getSvgAnimationEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let animationWidth = r * -1 + v; + const v = Math.abs(ratio); + const r = radius; + const animationWidth = r * -1 + v; let p = { topLeft: { x: v * -1, y: r * -1 }, bottomLeft: { x: v * -1, y: v * -1 }, diff --git a/ui/src/app/edge/live/energymonitor/chart/section/storage.component.ts b/ui/src/app/edge/live/energymonitor/chart/section/storage.component.ts index 669c55f4657..12e8f547495 100644 --- a/ui/src/app/edge/live/energymonitor/chart/section/storage.component.ts +++ b/ui/src/app/edge/live/energymonitor/chart/section/storage.component.ts @@ -144,8 +144,8 @@ export class StorageSectionComponent extends AbstractSection implements OnInit, } protected getSquarePosition(square: SvgSquare, innerRadius: number): SvgSquarePosition { - let x = (square.length / 2) * (-1); - let y = innerRadius - 5 - square.length; + const x = (square.length / 2) * (-1); + const y = innerRadius - 5 - square.length; return new SvgSquarePosition(x, y); } @@ -168,9 +168,9 @@ export class StorageSectionComponent extends AbstractSection implements OnInit, protected setElementHeight() { } protected getSvgEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let p = { + const v = Math.abs(ratio); + const r = radius; + const p = { topLeft: { x: v * -1, y: v }, bottomLeft: { x: v * -1, y: r }, topRight: { x: v, y: v }, @@ -189,9 +189,9 @@ export class StorageSectionComponent extends AbstractSection implements OnInit, } protected getSvgAnimationEnergyFlow(ratio: number, radius: number): SvgEnergyFlow { - let v = Math.abs(ratio); - let r = radius; - let animationWidth = r - v; + const v = Math.abs(ratio); + const r = radius; + const animationWidth = r - v; let p = { topLeft: { x: v * -1, y: v }, bottomLeft: { x: v * -1, y: r }, diff --git a/ui/src/app/edge/live/livedataservice.ts b/ui/src/app/edge/live/livedataservice.ts index a861e9a59fe..82f9578245b 100644 --- a/ui/src/app/edge/live/livedataservice.ts +++ b/ui/src/app/edge/live/livedataservice.ts @@ -20,7 +20,7 @@ export class LiveDataService extends DataService implements OnDestroy { public getValues(channelAddresses: ChannelAddress[], edge: Edge, componentId: string) { - for (let channelAddress of channelAddresses) { + for (const channelAddress of channelAddresses) { this.subscribedChannelAddresses.push(channelAddress); } @@ -32,9 +32,9 @@ export class LiveDataService extends DataService implements OnDestroy { // call onCurrentData() with latest data edge.currentData.pipe(takeUntil(this.stopOnDestroy)).subscribe(currentData => { - let allComponents = this.currentValue.value.allComponents; - for (let channelAddress of channelAddresses) { - let ca = channelAddress.toString(); + const allComponents = this.currentValue.value.allComponents; + for (const channelAddress of channelAddresses) { + const ca = channelAddress.toString(); allComponents[ca] = currentData.channel[ca]; } diff --git a/ui/src/app/edge/settings/alerting/alerting.component.ts b/ui/src/app/edge/settings/alerting/alerting.component.ts index d65fe7cdfb4..7aa6608119b 100644 --- a/ui/src/app/edge/settings/alerting/alerting.component.ts +++ b/ui/src/app/edge/settings/alerting/alerting.component.ts @@ -12,7 +12,7 @@ export enum AlertingType { offline = 0, fault = 1, warning = 2 -}; +} type DefaultValues = { [K in AlertingType]: Delay[]; }; type Delay = { value: number, label: string }; @@ -64,7 +64,7 @@ export class AlertingComponent implements OnInit { this.user = metadata.user; }); - let request = new GetUserAlertingConfigsRequest({ edgeId: this.edge.id }); + const request = new GetUserAlertingConfigsRequest({ edgeId: this.edge.id }); this.sendRequest(request).then(response => { const result = response.result; @@ -97,10 +97,10 @@ export class AlertingComponent implements OnInit { this.otherUserInformation = []; this.otherUserForm = new FormGroup({}); - var sorted = this.sortedAlphabetically(response); + const sorted = this.sortedAlphabetically(response); sorted.forEach((r) => { - var setting: AlertingSetting = { + const setting: AlertingSetting = { userLogin: r.userLogin, offlineEdgeDelay: r.offlineEdgeDelay, faultEdgeDelay: r.faultEdgeDelay, @@ -132,7 +132,7 @@ export class AlertingComponent implements OnInit { } private getValueOrDefault(setting: AlertingSetting, type: AlertingType) { - var val = this.getValue(setting, type); + const val = this.getValue(setting, type); return val <= 0 ? this.defaultValues[type][0].value : val; } @@ -205,20 +205,20 @@ export class AlertingComponent implements OnInit { } protected setUsersAlertingConfig() { - let edgeId: string = this.edge.id; + const edgeId: string = this.edge.id; - let dirtyformGroups: FormGroup[] = []; - let changedUserSettings: UserSettingRequest[] = []; + const dirtyformGroups: FormGroup[] = []; + const changedUserSettings: UserSettingRequest[] = []; if (this.currentUserForm.dirty) { - var formGroup = this.currentUserForm; + const formGroup = this.currentUserForm; dirtyformGroups.push(formGroup); - let offlineEdgeDelay = this.currentUserInformation.isOfflineActive ? + const offlineEdgeDelay = this.currentUserInformation.isOfflineActive ? this.currentUserForm.controls["offlineEdgeDelay"].value : 0; - let faultEdgeDelay = this.currentUserInformation.isFaultActive ? + const faultEdgeDelay = this.currentUserInformation.isFaultActive ? this.currentUserForm.controls["faultEdgeDelay"].value : 0; - let warningEdgeDelay = this.currentUserInformation.isWarningActive ? + const warningEdgeDelay = this.currentUserInformation.isWarningActive ? this.currentUserForm.controls["warningEdgeDelay"].value : 0; changedUserSettings.push({ @@ -229,17 +229,17 @@ export class AlertingComponent implements OnInit { }); } - let userOptions: AlertingSetting[] = []; + const userOptions: AlertingSetting[] = []; if (this.otherUserInformation) { if (this.otherUserForm.dirty) { dirtyformGroups.push(this.otherUserForm); - for (let user of this.otherUserInformation) { - let control = this.otherUserForm.controls[user.userLogin]; + for (const user of this.otherUserInformation) { + const control = this.otherUserForm.controls[user.userLogin]; if (control.dirty) { - let offlineEdgeDelay = control.value['offlineEdgeDelay']; - let faultEdgeDelay = control.value['faultEdgeDelay']; - let warningEdgeDelay = control.value['warningEdgeDelay']; + const offlineEdgeDelay = control.value['offlineEdgeDelay']; + const faultEdgeDelay = control.value['faultEdgeDelay']; + const warningEdgeDelay = control.value['warningEdgeDelay']; //let isActivated = control.value['isActivated']; changedUserSettings.push({ userLogin: user.userLogin, @@ -255,7 +255,7 @@ export class AlertingComponent implements OnInit { console.log(changedUserSettings); - let request = new SetUserAlertingConfigsRequest({ edgeId: edgeId, userSettings: changedUserSettings }); + const request = new SetUserAlertingConfigsRequest({ edgeId: edgeId, userSettings: changedUserSettings }); this.sendRequestAndUpdate(request, dirtyformGroups); } @@ -269,12 +269,12 @@ export class AlertingComponent implements OnInit { this.sendRequest(request) .then(() => { this.service.toast(this.translate.instant('General.changeAccepted'), 'success'); - for (let group of formGroup.values()) { + for (const group of formGroup.values()) { group.markAsPristine(); } }) .catch((response) => { - let error = response.error; + const error = response.error; this.errorToast(this.translate.instant('General.changeFailed'), error.message); }); } @@ -290,7 +290,7 @@ export class AlertingComponent implements OnInit { this.websocket.sendRequest(request).then(response => { resolve(response as GetUserAlertingConfigsResponse); }).catch(reason => { - let error = reason.error; + const error = reason.error; console.error(error); this.errorToast(this.translate.instant('Edge.Config.Alerting.toast.error'), error.message); reject(reason); diff --git a/ui/src/app/edge/settings/app/index.component.ts b/ui/src/app/edge/settings/app/index.component.ts index e5b4ac9e39b..e66a84813d1 100644 --- a/ui/src/app/edge/settings/app/index.component.ts +++ b/ui/src/app/edge/settings/app/index.component.ts @@ -184,7 +184,7 @@ export class IndexComponent implements OnInit, OnDestroy { this.installedApps.appCategories = []; this.availableApps.appCategories = []; - var sortedApps = []; + const sortedApps = []; this.apps.forEach(app => { app.categorys.forEach(category => { if (this.selectedBundle >= 0 && this.key) { @@ -198,7 +198,7 @@ export class IndexComponent implements OnInit, OnDestroy { return false; } } - var cat = this.categories.find(c => c.val.name === category.name); + const cat = this.categories.find(c => c.val.name === category.name); if (!cat.isChecked) { return false; } @@ -225,7 +225,7 @@ export class IndexComponent implements OnInit, OnDestroy { private pushIntoCategory(app: GetApps.App, list: AppList): void { app.categorys.forEach(category => { - var catList = list.appCategories.find(l => l.category.name === category.name); + let catList = list.appCategories.find(l => l.category.name === category.name); if (catList === undefined) { catList = { category: category, apps: [] }; list.appCategories.push(catList); diff --git a/ui/src/app/edge/settings/app/install.component.ts b/ui/src/app/edge/settings/app/install.component.ts index 2672d9235ab..6734b5ead43 100644 --- a/ui/src/app/edge/settings/app/install.component.ts +++ b/ui/src/app/edge/settings/app/install.component.ts @@ -64,8 +64,8 @@ export class InstallAppComponent implements OnInit, OnDestroy { this.useMasterKey = state['useMasterKey']; } } - let appId = this.route.snapshot.params['appId']; - let appName = this.route.snapshot.queryParams['name']; + const appId = this.route.snapshot.params['appId']; + const appName = this.route.snapshot.queryParams['name']; this.appId = appId; this.service.setCurrentComponent(appName, this.route).then(edge => { this.edge = edge; @@ -93,7 +93,7 @@ export class InstallAppComponent implements OnInit, OnDestroy { componentId: '_appManager', payload: new GetAppAssistant.Request({ appId: appId }), })).then(response => { - let appAssistant = GetAppAssistant.postprocess((response as GetAppAssistant.Response).result); + const appAssistant = GetAppAssistant.postprocess((response as GetAppAssistant.Response).result); this.fields = GetAppAssistant.setInitialModel(appAssistant.fields, {}); this.appName = appAssistant.name; @@ -120,9 +120,9 @@ export class InstallAppComponent implements OnInit, OnDestroy { this.obtainKey().then(key => { this.service.startSpinnerTransparentBackground(this.appId); // remove alias field from properties - let alias = this.form.value['ALIAS']; + const alias = this.form.value['ALIAS']; const clonedFields = {}; - for (let item in this.form.value) { + for (const item in this.form.value) { if (item !== 'ALIAS') { clonedFields[item] = this.form.value[item]; } @@ -148,7 +148,7 @@ export class InstallAppComponent implements OnInit, OnDestroy { this.isInstalling = true; this.edge.sendRequest(this.websocket, request).then(response => { - let result = (response as AddAppInstance.Response).result; + const result = (response as AddAppInstance.Response).result; if (result.instance) { result.instanceId = result.instance.instanceId; diff --git a/ui/src/app/edge/settings/app/jsonrpc/addAppInstance.ts b/ui/src/app/edge/settings/app/jsonrpc/addAppInstance.ts index 6ed8717ca8b..6f681049dfc 100644 --- a/ui/src/app/edge/settings/app/jsonrpc/addAppInstance.ts +++ b/ui/src/app/edge/settings/app/jsonrpc/addAppInstance.ts @@ -58,7 +58,7 @@ export namespace AddAppInstance { public override readonly result: { instanceId: string, instance: GetAppInstances.AppInstance, - warnings: String[] + warnings: string[] }, ) { super(id, result); diff --git a/ui/src/app/edge/settings/app/jsonrpc/flag/flagType.ts b/ui/src/app/edge/settings/app/jsonrpc/flag/flagType.ts index f01cf50dda1..a844f98c811 100644 --- a/ui/src/app/edge/settings/app/jsonrpc/flag/flagType.ts +++ b/ui/src/app/edge/settings/app/jsonrpc/flag/flagType.ts @@ -1,5 +1,3 @@ -import { Flag } from "./flag"; - -export interface FlagType { +export interface FlagType { name: string, } diff --git a/ui/src/app/edge/settings/app/jsonrpc/flag/flags.ts b/ui/src/app/edge/settings/app/jsonrpc/flag/flags.ts index a7bc5a667fd..e3041790b9e 100644 --- a/ui/src/app/edge/settings/app/jsonrpc/flag/flags.ts +++ b/ui/src/app/edge/settings/app/jsonrpc/flag/flags.ts @@ -3,7 +3,7 @@ import { FlagType } from "./flagType"; export namespace Flags { - export const SHOW_AFTER_KEY_REDEEM: FlagType = { name: 'showAfterKeyRedeem' }; + export const SHOW_AFTER_KEY_REDEEM: FlagType = { name: 'showAfterKeyRedeem' }; /** * Gets a flag by its type from an array of flags. @@ -14,7 +14,7 @@ export namespace Flags { * * @see Flag */ - export function getByType(flags: Flag[], type: FlagType): Type | undefined { + export function getByType(flags: Flag[], type: FlagType): Type | undefined { if (!flags) { return undefined; } diff --git a/ui/src/app/edge/settings/app/jsonrpc/getAppAssistant.ts b/ui/src/app/edge/settings/app/jsonrpc/getAppAssistant.ts index 6ccb7fc12ac..d3c6e1777ff 100644 --- a/ui/src/app/edge/settings/app/jsonrpc/getAppAssistant.ts +++ b/ui/src/app/edge/settings/app/jsonrpc/getAppAssistant.ts @@ -64,17 +64,17 @@ export namespace GetAppAssistant { } export function postprocess(appAssistant: AppAssistant): AppAssistant { - let fields = appAssistant.fields; + const fields = appAssistant.fields; let hasAliasField = false; - for (let field of fields) { + for (const field of fields) { if (eachFieldRecursive(fields, field)) { hasAliasField = true; } } if (!hasAliasField) { // insert alias field into appAssistent fields - let aliasField = { key: 'ALIAS', type: 'input', templateOptions: { label: 'Alias' }, defaultValue: appAssistant.alias }; + const aliasField = { key: 'ALIAS', type: 'input', templateOptions: { label: 'Alias' }, defaultValue: appAssistant.alias }; appAssistant.fields.splice(0, 0, aliasField); } return appAssistant; @@ -91,7 +91,7 @@ export namespace GetAppAssistant { if (!fieldGroup) { return; } - for (let f of fieldGroup) { + for (const f of fieldGroup) { recursivIterate(f); } }); @@ -101,149 +101,6 @@ export namespace GetAppAssistant { }); } - /** - * Iterates over the given field an all child fields. - * - * @param field the current field to iterate thrue - * @returns true if any field has 'ALIAS' as their key - */ - function eachFieldRecursive(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig) { - // 'defaultValue' false for checkboxes - if (field.type === 'checkbox' && !('defaultValue' in field)) { - field['defaultValue'] = false; - } - // this is needed to still show the input as the default style defined by us - if (field.wrappers?.includes('formly-wrapper-default-of-cases') - || field.wrappers?.includes('formly-safe-input-wrapper') - || field.wrappers?.includes('input-with-unit')) { - field.wrappers?.push('form-field'); - } - - if (field.validators) { - for (const [key, value] of Object.entries(field.validators)) { - let expressionString: string = value["expressionString"]; - if (expressionString) { - expressionString = GetAppAssistant.convertStringExpressions(rootFields, field, expressionString); - const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${expressionString};`); - field.validators[key]["expression"] = (control: AbstractControl, f: FormlyFieldConfigWithInitialModel) => { - return func(f.model, f.options.formState, f, control, f.initialModel); - }; - } - let messageExpressionString: string = value['messageString']; - if (messageExpressionString) { - messageExpressionString = GetAppAssistant.convertStringExpressions(rootFields, field, messageExpressionString); - const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${messageExpressionString};`); - field.validators[key]["message"] = (error: any, f: FormlyFieldConfigWithInitialModel) => { - return func(f.model, f.options.formState, f, f.formControl, f.initialModel); - }; - } - } - } - - convertFormlyOptionGroupPicker(rootFields, field); - convertFormlyReorderArray(rootFields, field); - - let childHasAlias = false; - [field.fieldGroup, field.templateOptions?.fields ?? field.props?.fields].forEach(fieldGroup => { - if (!fieldGroup) { - return; - } - for (let f of fieldGroup) { - if (eachFieldRecursive(rootFields, f)) { - childHasAlias = true; - } - } - }); - if (field.key == 'ALIAS') { - return true; - } - return childHasAlias; - } - - /** - * Converts expression strings of a 'formly-option-group-picker' to functions. - * - * e. g. - * { - * group: 'exampleGroup', - * options: [ - * { - * value: 'io0/Relay1', - * expressions: { - * disabledString: "model.OUPUT_CHANNLE_1 !== 'io0/Relay1'" - * } - * } - * ] - * } - * gets converted to: - * { - * group: 'exampleGroup', - * options: [ - * { - * value: 'io0/Relay1', - * expressions: { - * disabled: (field: FormlyFieldConfigWithInitialModel) => f.model.OUPUT_CHANNLE_1 !== 'io0/Relay1' - * } - * } - * ] - * } - * - * @param rootFields the root fields - * @param field the current field - */ - function convertFormlyOptionGroupPicker(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig) { - if (field.type !== 'formly-option-group-picker') { - return; - } - (field.templateOptions ?? field.props).options?.forEach((optionGroup) => { - if (!optionGroup) { - return; - } - (optionGroup['options'] as any[]).forEach((option) => { - for (const [key, value] of Object.entries(option?.expressions ?? {})) { - if (!key.endsWith("String")) { - continue; - } - - const expressionString: string = value as string; - if (expressionString) { - const convertedExpression = GetAppAssistant.convertStringExpressions(rootFields, field, expressionString); - const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${convertedExpression};`); - option['expressions'][key.substring(0, key.indexOf("String"))] = (f: FormlyFieldConfigWithInitialModel) => { - return func(f.model, f.options.formState, f, f.formControl, f.initialModel); - }; - } - } - }); - }); - } - - function convertFormlyReorderArray(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig) { - if (field.type !== 'reorder-array') { - return; - } - (field.templateOptions ?? field.props).selectOptions?.forEach((selectOption) => { - if (!selectOption) { - return; - } - - for (const [key, value] of Object.entries(selectOption?.expressions ?? {})) { - if (!key.endsWith("String")) { - continue; - } - - const expressionString: string = value as string; - if (expressionString) { - const convertedExpression = GetAppAssistant.convertStringExpressions(rootFields, field, expressionString); - const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${convertedExpression};`); - selectOption['expressions'][key.substring(0, key.indexOf("String"))] = (f: FormlyFieldConfigWithInitialModel) => { - return func(f.model, f.options.formState, f, f.formControl, f.initialModel); - }; - } - } - }); - } - export function convertStringExpressions(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig, expression: string): string { return ['model.', 'initialModel.', 'control.value.'].reduce((p, c) => convertStringExpression(rootFields, field, p, c), expression); } @@ -270,7 +127,7 @@ export namespace GetAppAssistant { } const smallestIndex = [' ', ')'].reduce((previous, current) => { - let index = part.indexOf(current); + const index = part.indexOf(current); if (index === -1) { return previous; } @@ -341,4 +198,148 @@ export namespace GetAppAssistant { } +/** + * Iterates over the given field an all child fields. + * + * @param field the current field to iterate thrue + * @returns true if any field has 'ALIAS' as their key + */ +function eachFieldRecursive(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig) { + // 'defaultValue' false for checkboxes + if (field.type === 'checkbox' && !('defaultValue' in field)) { + field['defaultValue'] = false; + } + // this is needed to still show the input as the default style defined by us + if (field.wrappers?.includes('formly-wrapper-default-of-cases') + || field.wrappers?.includes('formly-safe-input-wrapper') + || field.wrappers?.includes('input-with-unit')) { + field.wrappers?.push('form-field'); + } + + if (field.validators) { + for (const [key, value] of Object.entries(field.validators)) { + let expressionString: string = value["expressionString"]; + if (expressionString) { + expressionString = GetAppAssistant.convertStringExpressions(rootFields, field, expressionString); + const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${expressionString};`); + field.validators[key]["expression"] = (control: AbstractControl, f: FormlyFieldConfigWithInitialModel) => { + return func(f.model, f.options.formState, f, control, f.initialModel); + }; + } + let messageExpressionString: string = value['messageString']; + if (messageExpressionString) { + messageExpressionString = GetAppAssistant.convertStringExpressions(rootFields, field, messageExpressionString); + const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${messageExpressionString};`); + field.validators[key]["message"] = (error: any, f: FormlyFieldConfigWithInitialModel) => { + return func(f.model, f.options.formState, f, f.formControl, f.initialModel); + }; + } + } + } + + convertFormlyOptionGroupPicker(rootFields, field); + convertFormlyReorderArray(rootFields, field); + + let childHasAlias = false; + [field.fieldGroup, field.templateOptions?.fields ?? field.props?.fields].forEach(fieldGroup => { + if (!fieldGroup) { + return; + } + for (const f of fieldGroup) { + if (eachFieldRecursive(rootFields, f)) { + childHasAlias = true; + } + } + }); + if (field.key == 'ALIAS') { + return true; + } + return childHasAlias; +} + +/** + * Converts expression strings of a 'formly-option-group-picker' to functions. + * + * e. g. + * { + * group: 'exampleGroup', + * options: [ + * { + * value: 'io0/Relay1', + * expressions: { + * disabledString: "model.OUPUT_CHANNLE_1 !== 'io0/Relay1'" + * } + * } + * ] + * } + * gets converted to: + * { + * group: 'exampleGroup', + * options: [ + * { + * value: 'io0/Relay1', + * expressions: { + * disabled: (field: FormlyFieldConfigWithInitialModel) => f.model.OUPUT_CHANNLE_1 !== 'io0/Relay1' + * } + * } + * ] + * } + * + * @param rootFields the root fields + * @param field the current field + */ +function convertFormlyOptionGroupPicker(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig) { + if (field.type !== 'formly-option-group-picker') { + return; + } + (field.templateOptions ?? field.props).options?.forEach((optionGroup) => { + if (!optionGroup) { + return; + } + (optionGroup['options'] as any[]).forEach((option) => { + for (const [key, value] of Object.entries(option?.expressions ?? {})) { + if (!key.endsWith("String")) { + continue; + } + + const expressionString: string = value as string; + if (expressionString) { + const convertedExpression = GetAppAssistant.convertStringExpressions(rootFields, field, expressionString); + const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${convertedExpression};`); + option['expressions'][key.substring(0, key.indexOf("String"))] = (f: FormlyFieldConfigWithInitialModel) => { + return func(f.model, f.options.formState, f, f.formControl, f.initialModel); + }; + } + } + }); + }); +} + +function convertFormlyReorderArray(rootFields: FormlyFieldConfig[], field: FormlyFieldConfig) { + if (field.type !== 'reorder-array') { + return; + } + (field.templateOptions ?? field.props).selectOptions?.forEach((selectOption) => { + if (!selectOption) { + return; + } + + for (const [key, value] of Object.entries(selectOption?.expressions ?? {})) { + if (!key.endsWith("String")) { + continue; + } + + const expressionString: string = value as string; + if (expressionString) { + const convertedExpression = GetAppAssistant.convertStringExpressions(rootFields, field, expressionString); + const func = Function('model', 'formState', 'field', 'control', 'initialModel', `return ${convertedExpression};`); + selectOption['expressions'][key.substring(0, key.indexOf("String"))] = (f: FormlyFieldConfigWithInitialModel) => { + return func(f.model, f.options.formState, f, f.formControl, f.initialModel); + }; + } + } + }); +} + + type FormlyFieldConfigWithInitialModel = FormlyFieldConfig & { initialModel: {} } diff --git a/ui/src/app/edge/settings/app/jsonrpc/updateAppInstance.ts b/ui/src/app/edge/settings/app/jsonrpc/updateAppInstance.ts index d57970e4787..fad2d31ab79 100644 --- a/ui/src/app/edge/settings/app/jsonrpc/updateAppInstance.ts +++ b/ui/src/app/edge/settings/app/jsonrpc/updateAppInstance.ts @@ -55,7 +55,7 @@ export namespace UpdateAppInstance { public override readonly id: string, public override readonly result: { instance: GetAppInstances.AppInstance, - warnings: String[] + warnings: string[] }, ) { super(id, result); diff --git a/ui/src/app/edge/settings/app/keypopup/modal.component.ts b/ui/src/app/edge/settings/app/keypopup/modal.component.ts index 47e78e3786d..e79bed2646d 100644 --- a/ui/src/app/edge/settings/app/keypopup/modal.component.ts +++ b/ui/src/app/edge/settings/app/keypopup/modal.component.ts @@ -279,10 +279,10 @@ export class KeyModalComponent implements OnInit { } // remove last dash - let hasDashAsLastChar = trimmed.substring(trimmed.length - 1, trimmed.length) == "-"; + const hasDashAsLastChar = trimmed.substring(trimmed.length - 1, trimmed.length) == "-"; trimmed = trimmed.replace(/-/g, ''); - let numbers = []; + const numbers = []; // push single parts into array numbers.push(trimmed.substring(0, 4)); @@ -469,7 +469,7 @@ export class KeyModalComponent implements OnInit { return true; } return this.lastValidKey !== null && this.getRawAppKey() === this.lastValidKey.result.additionalInfo.keyId; - }; + } } diff --git a/ui/src/app/edge/settings/app/single.component.ts b/ui/src/app/edge/settings/app/single.component.ts index f9204f32ab1..0f6ffb92983 100644 --- a/ui/src/app/edge/settings/app/single.component.ts +++ b/ui/src/app/edge/settings/app/single.component.ts @@ -72,7 +72,7 @@ export class SingleAppComponent implements OnInit, OnDestroy { this.appId = this.route.snapshot.params['appId']; this.appName = this.route.snapshot.queryParams['name']; - let appId = this.appId; + const appId = this.appId; this.service.setCurrentComponent(this.appName, this.route).then(edge => { this.edge = edge; @@ -95,8 +95,8 @@ export class SingleAppComponent implements OnInit, OnDestroy { filter(config => config !== null), takeUntil(this.stopOnDestroy), ).subscribe(next => { - let appManager = next.getComponent("_appManager"); - let newKeyForFreeApps = appManager.properties["keyForFreeApps"]; + const appManager = next.getComponent("_appManager"); + const newKeyForFreeApps = appManager.properties["keyForFreeApps"]; if (!newKeyForFreeApps) { // no key in config this.increaseReceivedResponse(); @@ -151,7 +151,7 @@ export class SingleAppComponent implements OnInit, OnDestroy { componentId: '_appManager', payload: new GetApp.Request({ appId: appId }), })).then(response => { - let app = (response as GetApp.Response).result.app; + const app = (response as GetApp.Response).result.app; app.imageUrl = environment.links.APP_CENTER.APP_IMAGE(this.translate.currentLang, app.appId); this.setApp(app); }).catch(reason => { @@ -165,7 +165,7 @@ export class SingleAppComponent implements OnInit, OnDestroy { componentId: '_appManager', payload: new GetAppDescriptor.Request({ appId: appId }), })).then(response => { - let descriptor = (response as GetAppDescriptor.Response).result; + const descriptor = (response as GetAppDescriptor.Response).result; this.descriptor = GetAppDescriptor.postprocess(descriptor, this.sanitizer); }) .catch(InstallAppComponent.errorToast(this.service, error => 'Error while receiving AppDescriptor for App[' + appId + ']: ' + error)) @@ -190,7 +190,7 @@ export class SingleAppComponent implements OnInit, OnDestroy { } protected iFrameStyle() { - let styles = { + const styles = { 'height': (this.isXL) ? '100%' : window.innerHeight + 'px', }; return styles; diff --git a/ui/src/app/edge/settings/app/update.component.ts b/ui/src/app/edge/settings/app/update.component.ts index 5893b29706c..82c1817b320 100644 --- a/ui/src/app/edge/settings/app/update.component.ts +++ b/ui/src/app/edge/settings/app/update.component.ts @@ -47,8 +47,8 @@ export class UpdateAppComponent implements OnInit { public ngOnInit() { this.service.startSpinner(this.spinnerId); - let appId = this.route.snapshot.params["appId"]; - let appName = this.route.snapshot.queryParams['name']; + const appId = this.route.snapshot.params["appId"]; + const appName = this.route.snapshot.queryParams['name']; this.service.setCurrentComponent(appName, this.route).then(edge => { this.edge = edge; edge.sendRequest(this.websocket, @@ -56,17 +56,17 @@ export class UpdateAppComponent implements OnInit { componentId: '_appManager', payload: new GetAppInstances.Request({ appId: appId }), })).then(getInstancesResponse => { - let recInstances = (getInstancesResponse as GetAppInstances.Response).result.instances; + const recInstances = (getInstancesResponse as GetAppInstances.Response).result.instances; edge.sendRequest(this.websocket, new ComponentJsonApiRequest({ componentId: '_appManager', payload: new GetAppAssistant.Request({ appId: appId }), })).then(getAppAssistantResponse => { - let appAssistant = (getAppAssistantResponse as GetAppAssistant.Response).result; + const appAssistant = (getAppAssistantResponse as GetAppAssistant.Response).result; this.appName = appAssistant.name; this.instances = []; - for (let instance of recInstances) { + for (const instance of recInstances) { const form = new FormGroup({}); const model = { 'ALIAS': instance.alias, @@ -92,9 +92,9 @@ export class UpdateAppComponent implements OnInit { this.service.startSpinnerTransparentBackground(instance.instanceId); instance.isUpdating = true; // remove alias field from properties - let alias = instance.form.value['ALIAS']; + const alias = instance.form.value['ALIAS']; const clonedFields = {}; - for (let item in instance.form.value) { + for (const item in instance.form.value) { if (item != 'ALIAS') { clonedFields[item] = instance.form.value[item]; } diff --git a/ui/src/app/edge/settings/channels/channels.component.ts b/ui/src/app/edge/settings/channels/channels.component.ts index a0c297d6691..436173cd76a 100644 --- a/ui/src/app/edge/settings/channels/channels.component.ts +++ b/ui/src/app/edge/settings/channels/channels.component.ts @@ -26,7 +26,7 @@ export class ChannelsComponent { protected channelsToBeSubscribed: ChannelAddress[] = []; private channels: ChannelAddress[] = []; protected componentChannels: ComponentChannels[] = []; - protected componentChannelConfig: Map = new Map(); + protected componentChannelConfig: Map = new Map(); constructor( private service: Service, @@ -58,7 +58,7 @@ export class ChannelsComponent { * @param channelId the channelId */ protected subscribeChannel(componentId: string, channelId: string): void { - let address = new ChannelAddress(componentId, channelId); + const address = new ChannelAddress(componentId, channelId); if (this.componentChannels[componentId]?.filter(element => element.channelId == address.channelId)?.length === 0) { this.componentChannels[componentId].push(address); } else { @@ -70,7 +70,7 @@ export class ChannelsComponent { if (this.config) { const globalPersistencePriority = this.config.getComponentsByFactory("Controller.Api.Backend")?.[0]?.properties['persistencePriority'] ?? PersistencePriority.DEFAULT_GLOBAL_PRIORITY; - let channelConfig = this.config.getChannel(address); + const channelConfig = this.config.getChannel(address); if (channelConfig) { if (channelConfig.accessMode == "WO") { // do not subscribe Write-Only Channels @@ -130,7 +130,7 @@ export class ChannelsComponent { * and navigates to the new route */ private saveChannels(): void { - let data = Object.entries(this.channelsToBeSubscribed).map(([componentId, channels]) => { + const data = Object.entries(this.channelsToBeSubscribed).map(([componentId, channels]) => { return channels.toString(); }).toString(); this.router.navigate(['device/' + (this.edge.id) + '/settings/channels/'], { queryParams: { save: data } }); @@ -140,20 +140,20 @@ export class ChannelsComponent { * Saves channels for the current edge in localstorage */ protected localSave() { - let dataStr = JSON.stringify(this.channelsToBeSubscribed); + const dataStr = JSON.stringify(this.channelsToBeSubscribed); localStorage.setItem(ChannelsComponent.URL_PREFIX + "-" + this.edge.id, dataStr); this.service.toast("Successfully saved subscribed channels", "success"); } protected loadSavedChannels() { this.service.startSpinner(ChannelsComponent.SELECTOR); - let address = this.route.snapshot.queryParamMap.get('save'); - let storedValue = localStorage.getItem(ChannelsComponent.URL_PREFIX + "-" + this.edge.id); + const address = this.route.snapshot.queryParamMap.get('save'); + const storedValue = localStorage.getItem(ChannelsComponent.URL_PREFIX + "-" + this.edge.id); if (address) { this.channels = address.split(',')?.map(element => ChannelAddress.fromString(element)); this.channels.map(el => this.subscribeChannel(el.componentId, el.channelId)); } else if (storedValue) { - let savedData = JSON.parse(storedValue); + const savedData = JSON.parse(storedValue); savedData.map(el => this.subscribeChannel(el.componentId, el.channelId)); this.service.toast("Successfully loaded saved channels", "success"); } diff --git a/ui/src/app/edge/settings/component/install/index.component.ts b/ui/src/app/edge/settings/component/install/index.component.ts index 0cb8df51673..e15b516c35a 100644 --- a/ui/src/app/edge/settings/component/install/index.component.ts +++ b/ui/src/app/edge/settings/component/install/index.component.ts @@ -32,7 +32,7 @@ export class IndexComponent implements OnInit { this.service.setCurrentComponent({ languageKey: 'Edge.Config.Index.addComponents' }, this.route); this.service.getConfig().then(config => { this.list = config.listAvailableFactories(); - for (let entry of this.list) { + for (const entry of this.list) { entry.isClicked = false; entry.filteredFactories = entry.factories; } @@ -42,9 +42,9 @@ export class IndexComponent implements OnInit { updateFilter(completeFilter: string) { // take each space-separated string as an individual and-combined filter - let filters = completeFilter.toLowerCase().split(' '); + const filters = completeFilter.toLowerCase().split(' '); let countFilteredEntries = 0; - for (let entry of this.list) { + for (const entry of this.list) { entry.filteredFactories = entry.factories.filter(entry => // Search for filter strings in Factory-ID, -Name and Description Utils.matchAll(filters, [ diff --git a/ui/src/app/edge/settings/component/install/install.component.ts b/ui/src/app/edge/settings/component/install/install.component.ts index a22917a3c77..40ede1a058a 100644 --- a/ui/src/app/edge/settings/component/install/install.component.ts +++ b/ui/src/app/edge/settings/component/install/install.component.ts @@ -34,20 +34,20 @@ export class ComponentInstallComponent implements OnInit { this.service.setCurrentComponent({ languageKey: 'Edge.Config.Index.addComponents' }, this.route).then(edge => { this.edge = edge; }); - let factoryId = this.route.snapshot.params["factoryId"]; + const factoryId = this.route.snapshot.params["factoryId"]; this.service.getConfig().then(config => { this.factoryId = factoryId; this.factory = config.factories[factoryId]; - let fields: FormlyFieldConfig[] = []; - let model = {}; - for (let property of this.factory.properties) { - let property_id = property.id.replace('.', '_'); + const fields: FormlyFieldConfig[] = []; + const model = {}; + for (const property of this.factory.properties) { + const property_id = property.id.replace('.', '_'); let defaultValue = property.defaultValue; // if the type is an array and there is no defaultValue then set the defaultValue to an empty array if (property.schema["type"] === 'repeat' && defaultValue === null) { defaultValue = []; } - let field: FormlyFieldConfig = { + const field: FormlyFieldConfig = { key: property_id, type: 'input', templateOptions: { @@ -64,16 +64,16 @@ export class ComponentInstallComponent implements OnInit { // Set the next free Component-ID as defaultValue if (property_id == 'id' && property.schema["type"] !== 'repeat') { - let thisMatch = defaultValue.match(/^(.*)(\d+)$/); + const thisMatch = defaultValue.match(/^(.*)(\d+)$/); if (thisMatch) { - let thisPrefix = thisMatch[1]; + const thisPrefix = thisMatch[1]; let highestSuffix = Number.parseInt(thisMatch[2]); - for (let componentId of Object.keys(config.components)) { - let componentMatch = componentId.match(/^(.*)(\d+)$/); + for (const componentId of Object.keys(config.components)) { + const componentMatch = componentId.match(/^(.*)(\d+)$/); if (componentMatch) { - let componentPrefix = componentMatch[1]; + const componentPrefix = componentMatch[1]; if (componentPrefix === thisPrefix) { - let componentSuffix = Number.parseInt(componentMatch[2]); + const componentSuffix = Number.parseInt(componentMatch[2]); highestSuffix = Math.max(highestSuffix, componentSuffix + 1); } } @@ -94,14 +94,14 @@ export class ComponentInstallComponent implements OnInit { this.service.toast("Please fill mandatory fields!", "danger"); return; } - let properties: { name: string, value: any }[] = []; - for (let controlKey in this.form.controls) { - let control = this.form.controls[controlKey]; + const properties: { name: string, value: any }[] = []; + for (const controlKey in this.form.controls) { + const control = this.form.controls[controlKey]; if (control.value === null) { // ignore 'null' values continue; } - let property_id = controlKey.replace('_', '.'); + const property_id = controlKey.replace('_', '.'); properties.push({ name: property_id, value: control.value }); } diff --git a/ui/src/app/edge/settings/component/update/index.component.ts b/ui/src/app/edge/settings/component/update/index.component.ts index a0793dd77a4..c8eb4efa668 100644 --- a/ui/src/app/edge/settings/component/update/index.component.ts +++ b/ui/src/app/edge/settings/component/update/index.component.ts @@ -4,7 +4,7 @@ import { CategorizedComponents } from 'src/app/shared/edge/edgeconfig'; import { EdgeConfig, Service, Utils } from '../../../../shared/shared'; interface MyCategorizedComponents extends CategorizedComponents { - isNatureClicked?: Boolean, + isNatureClicked?: boolean, filteredComponents?: EdgeConfig.Component[] } @@ -31,9 +31,9 @@ export class IndexComponent implements OnInit { this.service.setCurrentComponent({ languageKey: 'Edge.Config.Index.adjustComponents' }, this.route); this.service.getConfig().then(config => { this.config = config; - let categorizedComponentIds: string[] = []; + const categorizedComponentIds: string[] = []; this.list = config.listActiveComponents(categorizedComponentIds); - for (let entry of this.list) { + for (const entry of this.list) { entry.isNatureClicked = false; entry.filteredComponents = entry.components; } @@ -43,9 +43,9 @@ export class IndexComponent implements OnInit { updateFilter(completeFilter: string) { // take each space-separated string as an individual and-combined filter - let filters = completeFilter.toLowerCase().split(' '); + const filters = completeFilter.toLowerCase().split(' '); let countFilteredEntries = 0; - for (let entry of this.list) { + for (const entry of this.list) { entry.filteredComponents = entry.components.filter(entry => // Search for filter strings in Component-ID, -Alias and Factory-ID Utils.matchAll(filters, [ diff --git a/ui/src/app/edge/settings/component/update/update.component.ts b/ui/src/app/edge/settings/component/update/update.component.ts index d710984743f..4e7cb09fc02 100644 --- a/ui/src/app/edge/settings/component/update/update.component.ts +++ b/ui/src/app/edge/settings/component/update/update.component.ts @@ -35,20 +35,20 @@ export class ComponentUpdateComponent implements OnInit { this.service.setCurrentComponent({ languageKey: 'Edge.Config.Index.adjustComponents' }, this.route).then(edge => { this.edge = edge; }); - let componentId = this.route.snapshot.params["componentId"]; + const componentId = this.route.snapshot.params["componentId"]; this.service.getConfig().then(config => { this.componentId = componentId; - let component = config.components[componentId]; + const component = config.components[componentId]; this.factory = config.factories[component.factoryId]; this.componentIcon = config.getFactoryIcon(this.factory); - let fields: FormlyFieldConfig[] = []; - let model = {}; - for (let property of this.factory.properties) { + const fields: FormlyFieldConfig[] = []; + const model = {}; + for (const property of this.factory.properties) { if (property.id === 'id') { continue; // ignore Component-ID } - let property_id = property.id.replace('.', '_'); - let field: FormlyFieldConfig = { + const property_id = property.id.replace('.', '_'); + const field: FormlyFieldConfig = { key: property_id, type: 'input', templateOptions: { @@ -79,11 +79,11 @@ export class ComponentUpdateComponent implements OnInit { } public submit() { - let properties: { name: string, value: any }[] = []; - for (let controlKey in this.form.controls) { - let control = this.form.controls[controlKey]; + const properties: { name: string, value: any }[] = []; + for (const controlKey in this.form.controls) { + const control = this.form.controls[controlKey]; if (control.dirty) { - let property_id = controlKey.replace('_', '.'); + const property_id = controlKey.replace('_', '.'); properties.push({ name: property_id, value: control.value }); } } diff --git a/ui/src/app/edge/settings/network/network.component.ts b/ui/src/app/edge/settings/network/network.component.ts index d5ec98c0961..3be20a409e9 100644 --- a/ui/src/app/edge/settings/network/network.component.ts +++ b/ui/src/app/edge/settings/network/network.component.ts @@ -46,7 +46,7 @@ export class NetworkComponent implements OnInit { new ComponentJsonApiRequest({ componentId: '_host', payload: new GetNetworkConfigRequest() })).then(response => { const result = (response as GetNetworkConfigResponse).result; - for (let name of Object.keys(result.interfaces)) { + for (const name of Object.keys(result.interfaces)) { const iface = result.interfaces[name]; if (this.edge.roleIsAtLeast(Role.ADMIN)) { @@ -77,13 +77,12 @@ export class NetworkComponent implements OnInit { // Converts ["192.168.1.50/24"] -> {label: " ''/'static' ", ip: "192.168.1.50", subnetmask: "255.255.255.0" } // Any ip address entered in the array("Statische IP-Adressen hinzufügen") will be labeled with emty string. for (const addr of iface.model.addressesList) { - if (this.ipRegex.test(addr)) { - var ip = addr.split('/'); - var subnetmask = this.getSubnetmaskAsString(ip[1]); - } else { + if (!this.ipRegex.test(addr)) { this.service.toast(this.translate.instant('Edge.Network.validAddressWarning'), 'danger'); return; } + const ip = addr.split('/'); + const subnetmask = this.getSubnetmaskAsString(ip[1]); addressJson.push({ label: '', //TODO with specific labels with specific systems. @@ -110,7 +109,7 @@ export class NetworkComponent implements OnInit { // updates the addresses array with latest values. iface.model.addresses = addressJson; - let request = { + const request = { interfaces: {}, }; request.interfaces[iface.name] = iface.model; @@ -153,9 +152,9 @@ export class NetworkComponent implements OnInit { * @returns the subnetmask as a string */ protected getSubnetmaskAsString(subnetmask: number): string { - var result = []; - for (var i = 0; i < 4; i++) { - var n = Math.min(subnetmask, 8); + const result = []; + for (let i = 0; i < 4; i++) { + const n = Math.min(subnetmask, 8); result.push(256 - Math.pow(2, 8 - n)); subnetmask -= n; } @@ -169,7 +168,7 @@ export class NetworkComponent implements OnInit { * @param source contains values for individual network. */ private generateInterface(name: string, source: any): void { - let addressArray: string[] = []; + const addressArray: string[] = []; // extracts the addresses json values to form values. if (source.addresses) { @@ -200,7 +199,7 @@ export class NetworkComponent implements OnInit { * * @returns FormlyFieldConfig[]. */ - private fillFields(addressArray: String[]): FormlyFieldConfig[] { + private fillFields(addressArray: string[]): FormlyFieldConfig[] { const fields: FormlyFieldConfig[] = [ { key: 'dhcp', diff --git a/ui/src/app/edge/settings/profile/aliasupdate.component.ts b/ui/src/app/edge/settings/profile/aliasupdate.component.ts index 7d36354c0c5..d916b716704 100644 --- a/ui/src/app/edge/settings/profile/aliasupdate.component.ts +++ b/ui/src/app/edge/settings/profile/aliasupdate.component.ts @@ -30,7 +30,7 @@ export class AliasUpdateComponent implements OnInit { this.edge = edge; }); this.service.getConfig().then(config => { - let componentId = this.route.snapshot.params["componentId"]; + const componentId = this.route.snapshot.params["componentId"]; this.component = config.components[componentId]; this.factory = config.factories[this.component.factoryId]; this.componentIcon = config.getFactoryIcon(this.factory); @@ -41,7 +41,7 @@ export class AliasUpdateComponent implements OnInit { } updateAlias(alias) { - let newAlias = alias; + const newAlias = alias; if (this.edge != null) { if (this.component.id == newAlias) { this.service.toast(this.translate.instant('General.inputNotValid'), 'danger'); diff --git a/ui/src/app/edge/settings/profile/profile.component.ts b/ui/src/app/edge/settings/profile/profile.component.ts index c2870efa671..baba0377806 100644 --- a/ui/src/app/edge/settings/profile/profile.component.ts +++ b/ui/src/app/edge/settings/profile/profile.component.ts @@ -39,7 +39,7 @@ export class ProfileComponent implements OnInit { this.edge = edge; this.service.getConfig().then(config => { this.config = config; - let categorizedComponentIds: string[] = ["_appManager", "_componentManager", "_cycle", "_meta", "_power", "_sum", "_predictorManager", "_host", "_evcsSlowPowerIncreaseFilter"]; + const categorizedComponentIds: string[] = ["_appManager", "_componentManager", "_cycle", "_meta", "_power", "_sum", "_predictorManager", "_host", "_evcsSlowPowerIncreaseFilter"]; this.components = config.listActiveComponents(categorizedComponentIds); }); }); @@ -47,7 +47,7 @@ export class ProfileComponent implements OnInit { public getModbusProtocol(componentId: string) { this.service.getCurrentEdge().then(edge => { - let request = new ComponentJsonApiRequest({ componentId: componentId, payload: new GetModbusProtocolExportXlsxRequest() }); + const request = new ComponentJsonApiRequest({ componentId: componentId, payload: new GetModbusProtocolExportXlsxRequest() }); edge.sendRequest(this.service.websocket, request).then(response => { Utils.downloadXlsx(response as Base64PayloadResponse, "Modbus-TCP-" + edge.id); }).catch(reason => { @@ -58,13 +58,13 @@ export class ProfileComponent implements OnInit { public getChannelExport(componentId: string) { this.service.getCurrentEdge().then(edge => { - let request = new ComponentJsonApiRequest({ componentId: '_componentManager', payload: new ChannelExportXlsxRequest({ componentId: componentId }) }); + const request = new ComponentJsonApiRequest({ componentId: '_componentManager', payload: new ChannelExportXlsxRequest({ componentId: componentId }) }); edge.sendRequest(this.service.websocket, request).then(response => { Utils.downloadXlsx(response as Base64PayloadResponse, "ChannelExport-" + edge.id + "-" + componentId); }).catch(reason => { console.warn(reason); }); }); - }; + } } diff --git a/ui/src/app/edge/settings/system/executeSystemUpdate.ts b/ui/src/app/edge/settings/system/executeSystemUpdate.ts index 25b679e5ebc..b237ec5149b 100644 --- a/ui/src/app/edge/settings/system/executeSystemUpdate.ts +++ b/ui/src/app/edge/settings/system/executeSystemUpdate.ts @@ -53,7 +53,7 @@ export class ExecuteSystemUpdate { // if the version is a SNAPSHOT always set the udpate state // to updated with the current SNAPSHOT version if (this.edge.isSnapshot() && !this.edge.roleIsAtLeast(Role.ADMIN)) { - let updateState = { updated: { version: this.edge.version } }; + const updateState = { updated: { version: this.edge.version } }; this.setSystemUpdateState(updateState); this.stopRefreshSystemUpdateState(); resolve(updateState); @@ -63,7 +63,7 @@ export class ExecuteSystemUpdate { componentId: "_host", payload: new GetSystemUpdateStateRequest(), })).then(response => { - let result = (response as GetSystemUpdateStateResponse).result; + const result = (response as GetSystemUpdateStateResponse).result; this.setSystemUpdateState(result); // Stop regular check if there is no Update available @@ -96,7 +96,7 @@ export class ExecuteSystemUpdate { payload: new ExecuteSystemUpdateRequest({ isDebug: environment.debugMode }), })).then(response => { // Finished System Update (without restart of OpenEMS Edge) - let systemUpdateState = (response as GetSystemUpdateStateResponse).result; + const systemUpdateState = (response as GetSystemUpdateStateResponse).result; this.setSystemUpdateState(systemUpdateState); }).catch(reason => { reject(reason); @@ -135,7 +135,7 @@ export class ExecuteSystemUpdate { if (!error["error"]) { return; } - let errorMessage = error["error"]["message"] as string; + const errorMessage = error["error"]["message"] as string; if (!errorMessage) { return; } diff --git a/ui/src/app/edge/settings/system/maintenance/maintenance.ts b/ui/src/app/edge/settings/system/maintenance/maintenance.ts index 08ab7952400..9f74a0846b0 100644 --- a/ui/src/app/edge/settings/system/maintenance/maintenance.ts +++ b/ui/src/app/edge/settings/system/maintenance/maintenance.ts @@ -172,7 +172,7 @@ export class MaintenanceComponent implements OnInit { async presentAlert(type: Type) { const translate = this.translate; const system = type === Type.HARD ? environment.edgeShortName : 'OpenEMS'; - let alert = this.alertCtrl.create({ + const alert = this.alertCtrl.create({ subHeader: translate.instant('SETTINGS.SYSTEM_UPDATE.RESTART_CONFIRMATION', { system: system }), message: translate.instant('SETTINGS.SYSTEM_UPDATE.RESTART_WARNING', { system: system }), buttons: [{ diff --git a/ui/src/app/edge/settings/systemexecute/systemexecute.component.ts b/ui/src/app/edge/settings/systemexecute/systemexecute.component.ts index decf7d206b0..abbf8083096 100644 --- a/ui/src/app/edge/settings/systemexecute/systemexecute.component.ts +++ b/ui/src/app/edge/settings/systemexecute/systemexecute.component.ts @@ -87,8 +87,8 @@ export class SystemExecuteComponent implements OnInit { if (!this.form.valid) { command = ""; } else { - let m = this.model; - let cmd = COMMANDS[m.predefined]; + const m = this.model; + const cmd = COMMANDS[m.predefined]; switch (m.predefined) { case "ping": command = cmd(m.ping.ip); @@ -102,17 +102,17 @@ export class SystemExecuteComponent implements OnInit { } public submit() { - let username = this.form.controls['username']; - let password = this.form.controls['password']; - let timeoutSeconds = this.form.controls['timeoutSeconds']; - let runInBackground = this.form.controls['runInBackground']; - let command = this.form.controls['command']; + const username = this.form.controls['username']; + const password = this.form.controls['password']; + const timeoutSeconds = this.form.controls['timeoutSeconds']; + const runInBackground = this.form.controls['runInBackground']; + const command = this.form.controls['command']; this.service.getCurrentEdge().then(edge => { this.loading = true; this.stdout = []; this.stderr = []; - let executeSystemCommandRequest = new ExecuteSystemCommandRequest({ + const executeSystemCommandRequest = new ExecuteSystemCommandRequest({ username: username.value, password: password.value, timeoutSeconds: timeoutSeconds.value, @@ -125,7 +125,7 @@ export class SystemExecuteComponent implements OnInit { componentId: "_host", payload: executeSystemCommandRequest, })).then(response => { - let result = (response as ExecuteSystemCommandResponse).result; + const result = (response as ExecuteSystemCommandResponse).result; this.loading = false; if (result.stdout.length == 0) { this.stdout = [""]; diff --git a/ui/src/app/edge/settings/systemlog/systemlog.component.ts b/ui/src/app/edge/settings/systemlog/systemlog.component.ts index afb388aa901..1eac0d407fc 100644 --- a/ui/src/app/edge/settings/systemlog/systemlog.component.ts +++ b/ui/src/app/edge/settings/systemlog/systemlog.component.ts @@ -92,7 +92,7 @@ export class SystemLogComponent implements OnInit, OnDestroy { }); }); this.isSubscribed = true; - }; + } private getColor(level): string { switch (level) { @@ -104,7 +104,7 @@ export class SystemLogComponent implements OnInit, OnDestroy { return 'gray'; case 'ERROR': return 'red'; - }; + } return 'black'; } @@ -115,5 +115,5 @@ export class SystemLogComponent implements OnInit, OnDestroy { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); this.ngUnsubscribe = new Subject(); - }; + } } diff --git a/ui/src/app/index/filter/filter.component.ts b/ui/src/app/index/filter/filter.component.ts index aaf4c3f32d9..9015a779216 100644 --- a/ui/src/app/index/filter/filter.component.ts +++ b/ui/src/app/index/filter/filter.component.ts @@ -25,7 +25,7 @@ export class FilterComponent { */ public searchOnChange(event, filter: Filter): void { - let value = event.target.value; + const value = event.target.value; // If no value provided if (!value) { diff --git a/ui/src/app/index/login.component.ts b/ui/src/app/index/login.component.ts index 8ac3373a0e5..b6f489c6562 100644 --- a/ui/src/app/index/login.component.ts +++ b/ui/src/app/index/login.component.ts @@ -54,7 +54,7 @@ export class LoginComponent implements OnInit, AfterContentChecked, OnDestroy { // Wait for Websocket if (this.websocket.status == 'waiting for credentials') { this.service.startSpinner('loginspinner'); - let lang = this.route.snapshot.queryParamMap.get('lang') ?? null; + const lang = this.route.snapshot.queryParamMap.get('lang') ?? null; if (lang) { localStorage.DEMO_LANGUAGE = lang; } diff --git a/ui/src/app/index/overview/overview.component.ts b/ui/src/app/index/overview/overview.component.ts index f61751a9901..5e8139ce097 100644 --- a/ui/src/app/index/overview/overview.component.ts +++ b/ui/src/app/index/overview/overview.component.ts @@ -95,7 +95,7 @@ export class OverViewComponent implements OnInit, OnDestroy { ) .subscribe(metadata => { - let edgeIds = Object.keys(metadata.edges); + const edgeIds = Object.keys(metadata.edges); this.noEdges = edgeIds.length === 0; this.loggedInUserCanInstall = Role.isAtLeast(metadata.user.globalRole, "installer"); @@ -103,7 +103,7 @@ export class OverViewComponent implements OnInit, OnDestroy { // - Direct local access to Edge // - No installer (i.e. guest or owner) and access to only one Edge if (environment.backend == 'OpenEMS Edge' || (!this.loggedInUserCanInstall && edgeIds.length == 1)) { - let edge = metadata.edges[edgeIds[0]]; + const edge = metadata.edges[edgeIds[0]]; setTimeout(() => { this.router.navigate(['/device', edge.id]); }, 100); @@ -145,7 +145,7 @@ export class OverViewComponent implements OnInit, OnDestroy { return; } - let searchParamsObj = {}; + const searchParamsObj = {}; if (this.searchParams && this.searchParams.size > 0) { for (const [key, value] of this.searchParams) { searchParamsObj[key] = value; diff --git a/ui/src/app/index/shared/sumState.ts b/ui/src/app/index/shared/sumState.ts index c5ecd512fdd..e26f3d72f01 100644 --- a/ui/src/app/index/shared/sumState.ts +++ b/ui/src/app/index/shared/sumState.ts @@ -52,7 +52,7 @@ export class SumStateComponent implements OnInit { constructor(private service: Service) { } ngOnInit() { - let user = this.service.metadata?.value?.user ?? null; + const user = this.service.metadata?.value?.user ?? null; if (user) { this.isAtLeastInstaller = Role.isAtLeast(user.globalRole, Role.INSTALLER); diff --git a/ui/src/app/registration/modal/modal.component.ts b/ui/src/app/registration/modal/modal.component.ts index 26d848cb277..4589f3f6d5a 100644 --- a/ui/src/app/registration/modal/modal.component.ts +++ b/ui/src/app/registration/modal/modal.component.ts @@ -47,23 +47,23 @@ export class RegistrationModalComponent implements OnInit { return; } - let password = this.formGroup.value.password; - let confirmPassword = this.formGroup.value.confirmPassword; + const password = this.formGroup.value.password; + const confirmPassword = this.formGroup.value.confirmPassword; if (password != confirmPassword) { this.service.toast(this.translate.instant("Register.errors.passwordNotEqual"), 'danger'); return; } - let email = this.formGroup.value.email; - let confirmEmail = this.formGroup.value.confirmEmail; + const email = this.formGroup.value.email; + const confirmEmail = this.formGroup.value.confirmEmail; if (email != confirmEmail) { this.service.toast(this.translate.instant("Register.errors.emailNotEqual"), 'danger'); return; } - let request = new RegisterUserRequest({ + const request = new RegisterUserRequest({ user: { firstname: this.formGroup.value.firstname, lastname: this.formGroup.value.lastname, @@ -82,7 +82,7 @@ export class RegistrationModalComponent implements OnInit { oem: environment.theme, }); - let companyName = this.formGroup.value.companyName; + const companyName = this.formGroup.value.companyName; if (companyName) { request.params.user.company = { name: companyName, diff --git a/ui/src/app/shared/chartoptions/chartoptions.component.ts b/ui/src/app/shared/chartoptions/chartoptions.component.ts index 4570bc09e54..713a05edf1f 100644 --- a/ui/src/app/shared/chartoptions/chartoptions.component.ts +++ b/ui/src/app/shared/chartoptions/chartoptions.component.ts @@ -22,7 +22,7 @@ export class ChartOptionsComponent { ) { } async presentPopover(ev: any) { - let componentProps = {}; + const componentProps = {}; if (this.showPhases !== null) { componentProps['showPhases'] = this.showPhases; } diff --git a/ui/src/app/shared/edge/currentdata.ts b/ui/src/app/shared/edge/currentdata.ts index 1a193a12282..fb71949ab7b 100644 --- a/ui/src/app/shared/edge/currentdata.ts +++ b/ui/src/app/shared/edge/currentdata.ts @@ -15,7 +15,7 @@ export class CurrentData { } private getSummary(c: { [channelAddress: string]: any }): DefaultTypes.Summary { - let result: DefaultTypes.Summary = { + const result: DefaultTypes.Summary = { system: { totalPower: null, autarchy: null, diff --git a/ui/src/app/shared/edge/edge.ts b/ui/src/app/shared/edge/edge.ts index ac05c50c7cd..3d4640e5419 100644 --- a/ui/src/app/shared/edge/edge.ts +++ b/ui/src/app/shared/edge/edge.ts @@ -86,9 +86,9 @@ export class Edge { this.isRefreshConfigBlocked = false; }, 1000); - let request = new GetEdgeConfigRequest(); + const request = new GetEdgeConfigRequest(); this.sendRequest(websocket, request).then(response => { - let edgeConfigResponse = response as GetEdgeConfigResponse; + const edgeConfigResponse = response as GetEdgeConfigResponse; this.config.next(new EdgeConfig(this, edgeConfigResponse.result)); }).catch(reason => { console.warn("Unable to refresh config", reason); @@ -198,11 +198,11 @@ export class Edge { this.subscribeChannelsTimeout = null; // merge channels from currentDataSubscribes - let channels: ChannelAddress[] = []; - for (let componentId in this.subscribedChannels) { - channels.push.apply(channels, this.subscribedChannels[componentId]); + const channels: ChannelAddress[] = []; + for (const componentId in this.subscribedChannels) { + channels.push(...this.subscribedChannels[componentId]); } - let request = new SubscribeChannelsRequest(channels); + const request = new SubscribeChannelsRequest(channels); this.sendRequest(websocket, request).then(() => { this.subscribeChannelsSuccessful = true; }).catch(reason => { @@ -243,7 +243,7 @@ export class Edge { * @param properties the properties to be updated. */ public createComponentConfig(ws: Websocket, factoryPid: string, properties: { name: string, value: any }[]): Promise { - let request = new CreateComponentConfigRequest({ factoryPid: factoryPid, properties: properties }); + const request = new CreateComponentConfigRequest({ factoryPid: factoryPid, properties: properties }); return this.sendRequest(ws, request); } @@ -255,7 +255,7 @@ export class Edge { * @param properties the properties to be updated. */ public updateComponentConfig(ws: Websocket, componentId: string, properties: { name: string, value: any }[]): Promise { - let request = new UpdateComponentConfigRequest({ componentId: componentId, properties: properties }); + const request = new UpdateComponentConfigRequest({ componentId: componentId, properties: properties }); return this.sendRequest(ws, request); } @@ -266,7 +266,7 @@ export class Edge { * @param componentId the OpenEMS Edge Component-ID */ public deleteComponentConfig(ws: Websocket, componentId: string): Promise { - let request = new DeleteComponentConfigRequest({ componentId: componentId }); + const request = new DeleteComponentConfigRequest({ componentId: componentId }); return this.sendRequest(ws, request); } @@ -278,7 +278,7 @@ export class Edge { * @param responseCallback the JSON-RPC Response callback */ public sendRequest(ws: Websocket, request: JsonrpcRequest): Promise { - let wrap = new EdgeRpcRequest({ edgeId: this.id, payload: request }); + const wrap = new EdgeRpcRequest({ edgeId: this.id, payload: request }); return new Promise((resolve, reject) => { ws.sendRequest(wrap).then(response => { resolve(response['result']['payload']); diff --git a/ui/src/app/shared/edge/edgeconfig.spec.ts b/ui/src/app/shared/edge/edgeconfig.spec.ts index b918850761d..38233fe962b 100644 --- a/ui/src/app/shared/edge/edgeconfig.spec.ts +++ b/ui/src/app/shared/edge/edgeconfig.spec.ts @@ -16,12 +16,12 @@ export namespace DummyConfig { components: components?.reduce((acc, c) => ({ ...acc, [c.id]: c }), {}), factories: components?.map(c => c.factory), }); - }; + } export function convertDummyEdgeConfigToRealEdgeConfig(edgeConfig: EdgeConfig): EdgeConfig { - let components = Object.values(edgeConfig?.components) ?? null; + const components = Object.values(edgeConfig?.components) ?? null; - let factories = {}; + const factories = {}; components.forEach(obj => { const component = obj as unknown; if (factories[component['factoryId']]) { @@ -206,6 +206,8 @@ export namespace DummyConfig { /** * Factories. */ +// identifier `Factory` is also used in namespace +// eslint-disable-next-line @typescript-eslint/no-unused-vars type Factory = { id: string }; @@ -213,6 +215,8 @@ type Factory = { /** * Components */ +// identifier `Component` is also used in namespace +// eslint-disable-next-line @typescript-eslint/no-unused-vars type Component = { id: string, alias: string, // defaults to id diff --git a/ui/src/app/shared/edge/edgeconfig.ts b/ui/src/app/shared/edge/edgeconfig.ts index 1a8a14a68e9..67084f8d382 100644 --- a/ui/src/app/shared/edge/edgeconfig.ts +++ b/ui/src/app/shared/edge/edgeconfig.ts @@ -8,7 +8,7 @@ export interface CategorizedComponents { icon: string }, components: EdgeConfig.Component[] -}; +} export interface CategorizedFactories { category: { @@ -16,7 +16,7 @@ export interface CategorizedFactories { icon: string }, factories: EdgeConfig.Factory[] -}; +} export class EdgeConfig { @@ -27,8 +27,8 @@ export class EdgeConfig { } // initialize Components - for (let componentId in this.components) { - let component = this.components[componentId]; + for (const componentId in this.components) { + const component = this.components[componentId]; component.id = componentId; if ('enabled' in component.properties) { component.isEnabled = component.properties['enabled']; @@ -38,16 +38,16 @@ export class EdgeConfig { } // initialize Factorys - for (let factoryId in this.factories) { - let factory = this.factories[factoryId]; + for (const factoryId in this.factories) { + const factory = this.factories[factoryId]; factory.id = factoryId; factory.componentIds = []; // Fill 'natures' map - for (let natureId of factory.natureIds) { + for (const natureId of factory.natureIds) { if (!(natureId in this.natures)) { - let parts = natureId.split("."); - let name = parts[parts.length - 1]; + const parts = natureId.split("."); + const name = parts[parts.length - 1]; this.natures[natureId] = { id: natureId, name: name, @@ -61,12 +61,12 @@ export class EdgeConfig { if (Object.keys(this.components).length != 0 && Object.keys(this.factories).length == 0) { console.warn("Factory definitions are missing."); } else { - for (let componentId in this.components) { - let component = this.components[componentId]; + for (const componentId in this.components) { + const component = this.components[componentId]; if (component.factoryId === "") { continue; // Singleton components have no factory-PID } - let factory = this.factories[component.factoryId]; + const factory = this.factories[component.factoryId]; if (!factory) { console.warn("Factory definition [" + component.factoryId + "] for [" + componentId + "] is missing."); continue; @@ -111,7 +111,7 @@ export class EdgeConfig { * @param factoryId the Factory PID. */ public getComponentIdsByFactory(factoryId: string): string[] { - let factory = this.factories[factoryId]; + const factory = this.factories[factoryId]; if (factory) { return factory.componentIds; } else { @@ -125,10 +125,10 @@ export class EdgeConfig { * @param natureId the given Nature. */ public getFactoriesByNature(natureId: string): EdgeConfig.Factory[] { - let result = []; - let nature = this.natures[natureId]; + const result = []; + const nature = this.natures[natureId]; if (nature) { - for (let factoryId of nature.factoryIds) { + for (const factoryId of nature.factoryIds) { if (factoryId in this.factories) { result.push(this.factories[factoryId]); } @@ -143,8 +143,8 @@ export class EdgeConfig { * @param ids the given Factory-IDs. */ public getFactoriesByIds(factoryIds: string[]): EdgeConfig.Factory[] { - let result = []; - for (let factoryId of factoryIds) { + const result = []; + for (const factoryId of factoryIds) { if (factoryId in this.factories) { result.push(this.factories[factoryId]); } @@ -158,9 +158,9 @@ export class EdgeConfig { * @param ids the given Factory-IDs pattern. */ public getFactoriesByIdsPattern(patterns: RegExp[]): EdgeConfig.Factory[] { - let result = []; - for (let pattern of patterns) { - for (let factoryId in this.factories) { + const result = []; + for (const pattern of patterns) { + for (const factoryId in this.factories) { if (pattern.test(factoryId)) { result.push(this.factories[factoryId]); } @@ -175,9 +175,9 @@ export class EdgeConfig { * @param factoryId the Factory PID. */ public getComponentsByFactory(factoryId: string): EdgeConfig.Component[] { - let componentIds = this.getComponentIdsByFactory(factoryId); - let result: EdgeConfig.Component[] = []; - for (let componentId of componentIds) { + const componentIds = this.getComponentIdsByFactory(factoryId); + const result: EdgeConfig.Component[] = []; + for (const componentId of componentIds) { result.push(this.components[componentId]); } return result; @@ -189,11 +189,11 @@ export class EdgeConfig { * @param nature the given Nature. */ public getComponentIdsImplementingNature(natureId: string): string[] { - let result: string[] = []; - let nature = this.natures[natureId]; + const result: string[] = []; + const nature = this.natures[natureId]; if (nature) { - for (let factoryId of nature.factoryIds) { - result.push.apply(result, this.getComponentIdsByFactory(factoryId)); + for (const factoryId of nature.factoryIds) { + result.push(...this.getComponentIdsByFactory(factoryId)); } } @@ -214,11 +214,11 @@ export class EdgeConfig { * @param nature the given Nature. */ public getComponentsImplementingNature(natureId: string): EdgeConfig.Component[] { - let result: EdgeConfig.Component[] = []; - let nature = this.natures[natureId]; + const result: EdgeConfig.Component[] = []; + const nature = this.natures[natureId]; if (nature) { - for (let factoryId of nature.factoryIds) { - result.push.apply(result, this.getComponentsByFactory(factoryId)); + for (const factoryId of nature.factoryIds) { + result.push(...this.getComponentsByFactory(factoryId)); } } @@ -239,7 +239,7 @@ export class EdgeConfig { * @param factoryId the Factory-ID */ public getNatureIdsByFactoryId(factoryId: string): string[] { - let factory = this.factories[factoryId]; + const factory = this.factories[factoryId]; if (factory) { return factory.natureIds; } else { @@ -278,7 +278,7 @@ export class EdgeConfig { return true; } // Do we have a Meter with type PRODUCTION? - for (let component of this.getComponentsImplementingNature("io.openems.edge.meter.api.ElectricityMeter")) { + for (const component of this.getComponentsImplementingNature("io.openems.edge.meter.api.ElectricityMeter")) { if (component.isEnabled && this.isProducer(component)) { return true; } @@ -365,7 +365,7 @@ export class EdgeConfig { * Lists all available Factories, grouped by category. */ public listAvailableFactories(): CategorizedFactories[] { - let allFactories = [ + const allFactories = [ { category: { title: 'Simulatoren', icon: 'flask-outline' }, factories: Object.values(this.factories).filter(factory => factory.id.startsWith('Simulator.')), @@ -495,10 +495,10 @@ export class EdgeConfig { }, ]; - let ignoreFactoryIds: string[] = []; - let result: CategorizedFactories[] = []; + const ignoreFactoryIds: string[] = []; + const result: CategorizedFactories[] = []; allFactories.forEach(item => { - let factories = + const factories = // create one flat array [].concat(...item.factories) // remove Factories from list that have already been listed before @@ -535,11 +535,11 @@ export class EdgeConfig { * Lists all active Components, grouped by category. */ public listActiveComponents(ignoreComponentIds: string[]): CategorizedComponents[] { - let allComponents = []; - let factories = this.listAvailableFactories(); - for (let entry of factories) { - let components = []; - for (let factory of entry.factories) { + const allComponents = []; + const factories = this.listAvailableFactories(); + for (const entry of factories) { + const components = []; + for (const factory of entry.factories) { components.push(this.getComponentsByFactory(factory.id)); // components.concat(...this.getComponentsByFactory(factory.id)); } @@ -548,9 +548,9 @@ export class EdgeConfig { components: components, }); } - let result: CategorizedComponents[] = []; + const result: CategorizedComponents[] = []; allComponents.forEach(item => { - let components = + const components = // create one flat array [].concat(...item.components) // remove Components from list that have already been listed before @@ -576,11 +576,11 @@ export class EdgeConfig { * @param componentId the Component-ID */ public getNatureIdsByComponentId(componentId: string): string[] { - let component = this.components[componentId]; + const component = this.components[componentId]; if (!component) { return []; } - let factoryId = component.factoryId; + const factoryId = component.factoryId; return this.getNatureIdsByFactoryId(factoryId); } @@ -599,7 +599,7 @@ export class EdgeConfig { * @param componentId the Component-ID */ public getComponentProperties(componentId: string): { [key: string]: any } { - let component = this.components[componentId]; + const component = this.components[componentId]; if (component) { return component.properties; } else { @@ -613,7 +613,7 @@ export class EdgeConfig { * @param address the ChannelAddress */ public getChannel(address: ChannelAddress): EdgeConfig.ComponentChannel { - let component = this.components[address.componentId]; + const component = this.components[address.componentId]; if (component) { return component.channels[address.channelId]; } else { @@ -691,7 +691,7 @@ export module EdgeConfig { * @param propertyId the Property-ID */ static getPropertyForId(factory: Factory, propertyId: string): FactoryProperty { - for (let property of factory.properties) { + for (const property of factory.properties) { if (property.id === propertyId) { return property; } diff --git a/ui/src/app/shared/edge/meter/electricity/modal.component.ts b/ui/src/app/shared/edge/meter/electricity/modal.component.ts index 0d625321fc9..167cb484b17 100644 --- a/ui/src/app/shared/edge/meter/electricity/modal.component.ts +++ b/ui/src/app/shared/edge/meter/electricity/modal.component.ts @@ -21,8 +21,8 @@ export class ElectricityMeterComponent extends AbstractModalLine implements OnIn ]; protected override getChannelAddresses(): ChannelAddress[] { - let channelAddresses: ChannelAddress[] = []; - for (let phase of [1, 2, 3]) { + const channelAddresses: ChannelAddress[] = []; + for (const phase of [1, 2, 3]) { channelAddresses.push( new ChannelAddress(this.component.id, 'CurrentL' + phase), new ChannelAddress(this.component.id, 'VoltageL' + phase), @@ -34,7 +34,7 @@ export class ElectricityMeterComponent extends AbstractModalLine implements OnIn protected override onCurrentData(currentData: CurrentData): void { this.phases.forEach((phase) => { - var power = currentData.allComponents[this.component.id + '/ActivePower' + phase.key]; + const power = currentData.allComponents[this.component.id + '/ActivePower' + phase.key]; phase.name = "Phase " + phase.key; phase.power = Utils.absSafely(power); phase.current = currentData.allComponents[this.component.id + '/Current' + phase.key]; diff --git a/ui/src/app/shared/formly/form-field-default-cases.wrapper.ts b/ui/src/app/shared/formly/form-field-default-cases.wrapper.ts index 4b94304007e..e99cb765b1e 100644 --- a/ui/src/app/shared/formly/form-field-default-cases.wrapper.ts +++ b/ui/src/app/shared/formly/form-field-default-cases.wrapper.ts @@ -42,7 +42,7 @@ export class FormlyWrapperDefaultValueWithCasesComponent extends FieldWrapper im if (this.formControl.value) { return; } - let value = this.model[item.field]; + const value = this.model[item.field]; if (!value) { return; } diff --git a/ui/src/app/shared/genericComponents/abstracthistorywidget.ts b/ui/src/app/shared/genericComponents/abstracthistorywidget.ts index bd52d012d96..fef3a8d65a0 100644 --- a/ui/src/app/shared/genericComponents/abstracthistorywidget.ts +++ b/ui/src/app/shared/genericComponents/abstracthistorywidget.ts @@ -52,16 +52,16 @@ export abstract class AbstractHistoryWidget implements OnInit, OnChanges, OnDest this.updateValues(); }); }); - }; + } public updateValues() { - let channelAddresses = this.getChannelAddresses(); + const channelAddresses = this.getChannelAddresses(); this.onCurrentData({ allComponents: {} }); this.service.queryEnergy(this.period.from, this.period.to, channelAddresses).then(response => { - let result = response.result; - let allComponents = {}; - for (let channelAddress of channelAddresses) { - let ca = channelAddress.toString(); + const result = response.result; + const allComponents = {}; + for (const channelAddress of channelAddresses) { + const ca = channelAddress.toString(); allComponents[ca] = result.data[ca]; } this.onCurrentData({ allComponents: allComponents }); diff --git a/ui/src/app/shared/genericComponents/chart/abstractHistoryChartOverview.ts b/ui/src/app/shared/genericComponents/chart/abstractHistoryChartOverview.ts index 3917cd93be4..420d25601c5 100644 --- a/ui/src/app/shared/genericComponents/chart/abstractHistoryChartOverview.ts +++ b/ui/src/app/shared/genericComponents/chart/abstractHistoryChartOverview.ts @@ -46,15 +46,15 @@ export abstract class AbstractHistoryChartOverview implements OnInit, OnChanges, this.updateValues(); }); }); - }; + } public updateValues() { - let channelAddresses = this.getChannelAddresses(); + const channelAddresses = this.getChannelAddresses(); this.service.queryEnergy(this.period.from, this.period.to, channelAddresses).then(response => { - let result = response.result; - let allComponents = {}; - for (let channelAddress of channelAddresses) { - let ca = channelAddress.toString(); + const result = response.result; + const allComponents = {}; + for (const channelAddress of channelAddresses) { + const ca = channelAddress.toString(); allComponents[ca] = result.data[ca]; } this.onCurrentData({ allComponents: allComponents }); diff --git a/ui/src/app/shared/genericComponents/chart/abstracthistorychart.ts b/ui/src/app/shared/genericComponents/chart/abstracthistorychart.ts index 3734575550f..811ccaa256b 100644 --- a/ui/src/app/shared/genericComponents/chart/abstracthistorychart.ts +++ b/ui/src/app/shared/genericComponents/chart/abstracthistorychart.ts @@ -111,11 +111,11 @@ export abstract class AbstractHistoryChart implements OnInit { return; } - let channelData: { data: { [name: string]: number[] } } = { data: {} }; + const channelData: { data: { [name: string]: number[] } } = { data: {} }; - let result = energyPeriodResponse.result; - let labels: Date[] = []; - for (let timestamp of result.timestamps) { + const result = energyPeriodResponse.result; + const labels: Date[] = []; + for (const timestamp of result.timestamps) { labels.push(new Date(timestamp)); } @@ -146,9 +146,9 @@ export abstract class AbstractHistoryChart implements OnInit { }); // Fill datasets, labels and colors - let datasets: Chart.ChartDataset[] = []; - let displayValues: HistoryUtils.DisplayValues[] = chartObject.output(channelData.data); - let legendOptions: { label: string, strokeThroughHidingStyle: boolean, hideLabelInLegend: boolean }[] = []; + const datasets: Chart.ChartDataset[] = []; + const displayValues: HistoryUtils.DisplayValues[] = chartObject.output(channelData.data); + const legendOptions: { label: string, strokeThroughHidingStyle: boolean, hideLabelInLegend: boolean }[] = []; displayValues.forEach((element, index) => { let nameSuffix = null; @@ -157,18 +157,18 @@ export abstract class AbstractHistoryChart implements OnInit { nameSuffix = element.nameSuffix(energyResponse); } - let yAxis = chartObject.yAxes.find(yaxis => yaxis?.yAxisId == (element?.yAxisId ?? chartObject.yAxes[0]?.yAxisId)); + const yAxis = chartObject.yAxes.find(yaxis => yaxis?.yAxisId == (element?.yAxisId ?? chartObject.yAxes[0]?.yAxisId)); // Filter existing values if (element) { - let label = AbstractHistoryChart.getTooltipsLabelName(element.name, yAxis?.unit, nameSuffix); - let data: number[] | null = element.converter(); + const label = AbstractHistoryChart.getTooltipsLabelName(element.name, yAxis?.unit, nameSuffix); + const data: number[] | null = element.converter(); if (data === null || data === undefined) { return; } - let configuration = AbstractHistoryChart.fillData(element, label, chartObject, chartType, data); + const configuration = AbstractHistoryChart.fillData(element, label, chartObject, chartType, data); datasets.push(...configuration.datasets); legendOptions.push(...configuration.legendOptions); } @@ -183,12 +183,12 @@ export abstract class AbstractHistoryChart implements OnInit { public static fillData(element: HistoryUtils.DisplayValues, label: string, chartObject: HistoryUtils.ChartData, chartType: 'line' | 'bar', data: number[] | null): { datasets: Chart.ChartDataset[], legendOptions: { label: string, strokeThroughHidingStyle: boolean, hideLabelInLegend: boolean }[] } { - let legendOptions: { label: string, strokeThroughHidingStyle: boolean, hideLabelInLegend: boolean }[] = []; - let datasets: Chart.ChartDataset[] = []; + const legendOptions: { label: string, strokeThroughHidingStyle: boolean, hideLabelInLegend: boolean }[] = []; + const datasets: Chart.ChartDataset[] = []; // Enable one dataset to be displayed in multiple stacks if (Array.isArray(element.stack)) { - for (let stack of element.stack) { + for (const stack of element.stack) { datasets.push(AbstractHistoryChart.getDataSet(element, label, data, stack, chartObject, element.custom?.type ?? chartType)); legendOptions.push(AbstractHistoryChart.getLegendOptions(label, element)); } @@ -242,8 +242,7 @@ export abstract class AbstractHistoryChart implements OnInit { * @returns a dataset */ public static getDataSet(element: HistoryUtils.DisplayValues, label: string, data: number[], stack: number, chartObject: HistoryUtils.ChartData, chartType: 'line' | 'bar'): Chart.ChartDataset { - let dataset: Chart.ChartDataset; - dataset = { + const dataset: Chart.ChartDataset = { label: label, data: data, hidden: !isLabelVisible(element.name, !(element.hiddenOnInit)), @@ -266,7 +265,7 @@ export abstract class AbstractHistoryChart implements OnInit { protected loadChart() { this.labels = []; this.errorResponse = null; - let unit = calculateResolution(this.service, this.service.historyPeriod.value.from, this.service.historyPeriod.value.to).resolution.unit; + const unit = calculateResolution(this.service, this.service.historyPeriod.value.from, this.service.historyPeriod.value.to).resolution.unit; // Show Barchart if resolution is days or months if (ChronoUnit.isAtLeast(unit, ChronoUnit.Type.DAYS)) { @@ -280,7 +279,7 @@ export abstract class AbstractHistoryChart implements OnInit { // TODO after chartjs migration, look for config energyPeriodResponse = DateTimeUtils.normalizeTimestamps(unit, energyPeriodResponse); - let displayValues = AbstractHistoryChart.fillChart(this.chartType, this.chartObject, energyPeriodResponse, energyResponse); + const displayValues = AbstractHistoryChart.fillChart(this.chartType, this.chartObject, energyPeriodResponse, energyResponse); this.datasets = displayValues.datasets; this.legendOptions = displayValues.legendOptions; this.labels = displayValues.labels; @@ -298,7 +297,7 @@ export abstract class AbstractHistoryChart implements OnInit { dataResponse = DateTimeUtils.normalizeTimestamps(unit, dataResponse); this.chartType = 'line'; this.chartObject = this.getChartData(); - let displayValues = AbstractHistoryChart.fillChart(this.chartType, this.chartObject, dataResponse, energyResponse); + const displayValues = AbstractHistoryChart.fillChart(this.chartType, this.chartObject, dataResponse, energyResponse); this.datasets = displayValues.datasets; this.legendOptions = displayValues.legendOptions; this.labels = displayValues.labels; @@ -315,34 +314,31 @@ export abstract class AbstractHistoryChart implements OnInit { */ public static applyChartTypeSpecificOptionsChanges(chartType: string, options: Chart.ChartOptions, service: Service, chartObject: HistoryUtils.ChartData | null): Chart.ChartOptions { switch (chartType) { - case 'bar': + case 'bar': { options.plugins.tooltip.mode = 'x'; options.scales.x['offset'] = true; options.scales.x.ticks['source'] = 'data'; let barPercentage = 1; - let categoryPercentage = 0; switch (service.periodString) { case DefaultTypes.PeriodString.CUSTOM: { barPercentage = 0.7; - categoryPercentage = 0.4; + break; } case DefaultTypes.PeriodString.MONTH: { if (service.isSmartphoneResolution == true) { barPercentage = 1; - categoryPercentage = 0.6; } else { barPercentage = 0.9; - categoryPercentage = 0.8; } + break; } case DefaultTypes.PeriodString.YEAR: { if (service.isSmartphoneResolution == true) { barPercentage = 1; - categoryPercentage = 0.6; } else { barPercentage = 0.8; - categoryPercentage = 0.8; } + break; } } @@ -350,6 +346,7 @@ export abstract class AbstractHistoryChart implements OnInit { barPercentage: barPercentage, }; break; + } case 'line': options.scales.x['offset'] = false; @@ -357,7 +354,7 @@ export abstract class AbstractHistoryChart implements OnInit { options.plugins.tooltip.mode = 'index'; if (chartObject) { - for (let yAxis of chartObject.yAxes) { + for (const yAxis of chartObject.yAxes) { options.scales[yAxis.yAxisId]['stacked'] = false; } } @@ -378,15 +375,15 @@ export abstract class AbstractHistoryChart implements OnInit { protected queryHistoricTimeseriesData(fromDate: Date, toDate: Date, res?: Resolution): Promise { this.isDataExisting = true; - let resolution = res ?? calculateResolution(this.service, fromDate, toDate).resolution; + const resolution = res ?? calculateResolution(this.service, fromDate, toDate).resolution; - let result: Promise = new Promise((resolve, reject) => { + const result: Promise = new Promise((resolve, reject) => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(async () => { - let channelAddresses = (await this.getChannelAddresses()).powerChannels; - let request = new QueryHistoricTimeseriesDataRequest(DateUtils.maxDate(fromDate, this.edge?.firstSetupProtocol), toDate, channelAddresses, resolution); + const channelAddresses = (await this.getChannelAddresses()).powerChannels; + const request = new QueryHistoricTimeseriesDataRequest(DateUtils.maxDate(fromDate, this.edge?.firstSetupProtocol), toDate, channelAddresses, resolution); edge.sendRequest(this.service.websocket, request).then(response => { - let result = (response as QueryHistoricTimeseriesDataResponse)?.result; + const result = (response as QueryHistoricTimeseriesDataResponse)?.result; if (Object.keys(result).length != 0) { resolve(response as QueryHistoricTimeseriesDataResponse); } else { @@ -425,18 +422,18 @@ export abstract class AbstractHistoryChart implements OnInit { protected queryHistoricTimeseriesEnergyPerPeriod(fromDate: Date, toDate: Date): Promise { this.isDataExisting = true; - let resolution = calculateResolution(this.service, fromDate, toDate).resolution; + const resolution = calculateResolution(this.service, fromDate, toDate).resolution; - let result: Promise = new Promise((resolve, reject) => { + const result: Promise = new Promise((resolve, reject) => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(async () => { - let channelAddresses = (await this.getChannelAddresses()).energyChannels.filter(element => element != null); - let request = new QueryHistoricTimeseriesEnergyPerPeriodRequest(DateUtils.maxDate(fromDate, edge?.firstSetupProtocol), toDate, channelAddresses, resolution); + const channelAddresses = (await this.getChannelAddresses()).energyChannels.filter(element => element != null); + const request = new QueryHistoricTimeseriesEnergyPerPeriodRequest(DateUtils.maxDate(fromDate, edge?.firstSetupProtocol), toDate, channelAddresses, resolution); if (channelAddresses.length > 0) { edge.sendRequest(this.service.websocket, request).then(response => { - let result = (response as QueryHistoricTimeseriesEnergyPerPeriodResponse)?.result; + const result = (response as QueryHistoricTimeseriesEnergyPerPeriodResponse)?.result; if (Object.keys(result).length != 0) { resolve(response as QueryHistoricTimeseriesEnergyPerPeriodResponse); } else { @@ -481,14 +478,14 @@ export abstract class AbstractHistoryChart implements OnInit { this.isDataExisting = true; - let result: Promise = new Promise((resolve, reject) => { + const result: Promise = new Promise((resolve, reject) => { this.service.getCurrentEdge().then(edge => { this.service.getConfig().then(async () => { - let channelAddresses = (await this.getChannelAddresses()).energyChannels?.filter(element => element != null) ?? []; - let request = new QueryHistoricTimeseriesEnergyRequest(DateUtils.maxDate(fromDate, edge?.firstSetupProtocol), toDate, channelAddresses); + const channelAddresses = (await this.getChannelAddresses()).energyChannels?.filter(element => element != null) ?? []; + const request = new QueryHistoricTimeseriesEnergyRequest(DateUtils.maxDate(fromDate, edge?.firstSetupProtocol), toDate, channelAddresses); if (channelAddresses.length > 0) { edge.sendRequest(this.service.websocket, request).then(response => { - let result = (response as QueryHistoricTimeseriesEnergyResponse)?.result; + const result = (response as QueryHistoricTimeseriesEnergyResponse)?.result; if (Object.keys(result).length != 0) { resolve(response as QueryHistoricTimeseriesEnergyResponse); } else { @@ -520,7 +517,7 @@ export abstract class AbstractHistoryChart implements OnInit { * @returns period for Tooltip Header */ protected static toTooltipTitle(fromDate: Date, toDate: Date, date: Date, service: Service): string { - let unit = calculateResolution(service, fromDate, toDate).resolution.unit; + const unit = calculateResolution(service, fromDate, toDate).resolution.unit; switch (unit) { case ChronoUnit.Type.YEARS: @@ -551,7 +548,7 @@ export abstract class AbstractHistoryChart implements OnInit { let tooltipsLabel: string | null = null; let options: Chart.ChartOptions = Utils.deepCopy(Utils.deepCopy(DEFAULT_TIME_CHART_OPTIONS)); - let displayValues: HistoryUtils.DisplayValues[] = chartObject.output(channelData.data); + const displayValues: HistoryUtils.DisplayValues[] = chartObject.output(channelData.data); const showYAxisTitle: boolean = chartObject.yAxes.length > 1; chartObject.yAxes.forEach((element) => { @@ -563,7 +560,7 @@ export abstract class AbstractHistoryChart implements OnInit { if (tooltipItems?.length === 0) { return null; } - let date = DateUtils.stringToDate(tooltipItems[0]?.label); + const date = DateUtils.stringToDate(tooltipItems[0]?.label); return AbstractHistoryChart.toTooltipTitle(service.historyPeriod.value.from, service.historyPeriod.value.to, date, service); }; @@ -572,11 +569,11 @@ export abstract class AbstractHistoryChart implements OnInit { options.scales.x['time'].unit = calculateResolution(service, service.historyPeriod.value.from, service.historyPeriod.value.to).timeFormat; options.plugins.tooltip.callbacks.label = (item: Chart.TooltipItem) => { - let label = item.dataset.label; - let value = item.dataset.data[item.dataIndex]; + const label = item.dataset.label; + const value = item.dataset.data[item.dataIndex]; - let displayValue = displayValues.find(element => element.name === label.split(":")[0]); - let unit = displayValue?.custom?.unit + const displayValue = displayValues.find(element => element.name === label.split(":")[0]); + const unit = displayValue?.custom?.unit ?? chartObject.yAxes[0]?.unit; if (value === null) { @@ -601,17 +598,17 @@ export abstract class AbstractHistoryChart implements OnInit { options.plugins.legend.labels.generateLabels = function (chart: Chart.Chart) { - let chartLegendLabelItems: Chart.LegendItem[] = []; + const chartLegendLabelItems: Chart.LegendItem[] = []; chart.data.datasets.forEach((dataset: Chart.ChartDataset, index) => { - let legendItem = legendOptions?.find(element => element.label == dataset.label); + const legendItem = legendOptions?.find(element => element.label == dataset.label); //Remove duplicates like 'directConsumption' from legend if (chartLegendLabelItems.filter(element => element['text'] == dataset.label).length > 0) { return; } - let isHidden = legendItem?.strokeThroughHidingStyle ?? null; + const isHidden = legendItem?.strokeThroughHidingStyle ?? null; displayValues.filter(element => element.name == dataset.label?.split(":")[0]).forEach(() => { chartLegendLabelItems.push({ @@ -637,22 +634,22 @@ export abstract class AbstractHistoryChart implements OnInit { } // only way to figure out, which stack is active - var tooltipItem = items[0]; // Assuming only one tooltip item is displayed - var datasetIndex = tooltipItem.dataIndex; + const tooltipItem = items[0]; // Assuming only one tooltip item is displayed + const datasetIndex = tooltipItem.dataIndex; // Get the dataset object - var datasets = items.map(element => element.dataset); + const datasets = items.map(element => element.dataset); // Assuming the dataset is a bar chart using the 'stacked' option - var stack = items[0].dataset.stack || datasetIndex; + const stack = items[0].dataset.stack || datasetIndex; // If only one item in stack do not show sum of values if (items.length <= 1) { return null; } - let afterTitle = typeof chartObject.tooltip?.afterTitle == 'function' ? chartObject.tooltip?.afterTitle(stack) : null; + const afterTitle = typeof chartObject.tooltip?.afterTitle == 'function' ? chartObject.tooltip?.afterTitle(stack) : null; - let totalValue = datasets.filter(el => el.stack == stack).reduce((_total, dataset) => Utils.addSafely(_total, Math.abs(dataset.data[datasetIndex])), 0); + const totalValue = datasets.filter(el => el.stack == stack).reduce((_total, dataset) => Utils.addSafely(_total, Math.abs(dataset.data[datasetIndex])), 0); if (afterTitle) { return afterTitle + ": " + formatNumber(totalValue, 'de', chartObject.tooltip.formatNumber) + ' ' + tooltipsLabel; } @@ -662,9 +659,9 @@ export abstract class AbstractHistoryChart implements OnInit { // Remove duplicates from legend, if legendItem with two or more occurrences in legend, use one legendItem to trigger them both options.plugins.legend.onClick = function (event: Chart.ChartEvent, legendItem: Chart.LegendItem, legend) { - let chart: Chart.Chart = this.chart; + const chart: Chart.Chart = this.chart; - let legendItems = chart.data.datasets.reduce((arr, ds, i) => { + const legendItems = chart.data.datasets.reduce((arr, ds, i) => { if (ds.label == legendItem.text) { arr.push({ label: ds.label, index: i }); } @@ -674,7 +671,7 @@ export abstract class AbstractHistoryChart implements OnInit { legendItems.forEach(item => { // original.call(this, event, legendItem1); setLabelVisible(item.label, !chart.isDatasetVisible(legendItem.datasetIndex)); - var meta = chart.getDatasetMeta(item.index); + const meta = chart.getDatasetMeta(item.index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null ? !chart.data.datasets[item.index].hidden : null; }); @@ -853,7 +850,7 @@ export abstract class AbstractHistoryChart implements OnInit { }); } }); - }; + } public static getYAxisTitle(title: YAxisTitle, translate: TranslateService, chartType: 'bar' | 'line', customTitle?: string): string { @@ -924,20 +921,23 @@ export abstract class AbstractHistoryChart implements OnInit { let tooltipsLabel: string | null = null; switch (title) { - case YAxisTitle.RELAY: + case YAxisTitle.RELAY: { if (chartType === 'line') { return Converter.ON_OFF(translate)(value); } const activeTimeOverPeriodPipe = new FormatSecondsToDurationPipe(new DecimalPipe(language)); return activeTimeOverPeriodPipe.transform(value); + } - case YAxisTitle.TIME: + case YAxisTitle.TIME: { const pipe = new FormatSecondsToDurationPipe(new DecimalPipe(language)); return pipe.transform(value); - case YAxisTitle.CURRENCY: + } + case YAxisTitle.CURRENCY: { const currency = config.components['_meta'].properties.currency; tooltipsLabel = Currency.getCurrencyLabelByCurrency(currency); break; + } case YAxisTitle.PERCENTAGE: tooltipsLabel = AbstractHistoryChart.getToolTipsAfterTitleLabel(title, chartType, value, translate); break; @@ -981,10 +981,10 @@ export abstract class AbstractHistoryChart implements OnInit { case YAxisTitle.PERCENTAGE: return baseName + ": " + formatNumber(suffix, 'de', "1.0-1") + " %"; case YAxisTitle.RELAY: - case YAxisTitle.TIME: + case YAxisTitle.TIME: { const pipe = new FormatSecondsToDurationPipe(new DecimalPipe(Language.DE.key)); return baseName + ": " + pipe.transform(suffix); - + } } } } @@ -999,16 +999,16 @@ export abstract class AbstractHistoryChart implements OnInit { */ private showZeroPlugin = { beforeRender: function (chartInstance) { - let datasets = chartInstance.config.data.datasets; + const datasets = chartInstance.config.data.datasets; for (let i = 0; i < datasets.length; i++) { - let meta = datasets[i]._meta; + const meta = datasets[i]._meta; // It counts up every time you change something on the chart so // this is a way to get the info on whichever index it's at - let metaData = meta[Object.keys(meta)[0]]; - let bars = metaData.data; + const metaData = meta[Object.keys(meta)[0]]; + const bars = metaData.data; for (let j = 0; j < bars.length; j++) { - let model = bars[j]._model; + const model = bars[j]._model; if (metaData.type === "horizontalBar" && model.base === model.x) { model.x = model.base + 2; } diff --git a/ui/src/app/shared/genericComponents/flat/abstract-flat-widget-line.ts b/ui/src/app/shared/genericComponents/flat/abstract-flat-widget-line.ts index 7cf848aa4f0..e3929bd9860 100644 --- a/ui/src/app/shared/genericComponents/flat/abstract-flat-widget-line.ts +++ b/ui/src/app/shared/genericComponents/flat/abstract-flat-widget-line.ts @@ -64,7 +64,7 @@ export abstract class AbstractFlatWidgetLine implements OnChanges, OnDestroy { public ngOnChanges() { this.setValue(this.value); - }; + } protected setValue(value: any) { this.displayValue = this.converter(value); diff --git a/ui/src/app/shared/genericComponents/flat/abstract-flat-widget.ts b/ui/src/app/shared/genericComponents/flat/abstract-flat-widget.ts index f2b30f795ac..c4b1adcc878 100644 --- a/ui/src/app/shared/genericComponents/flat/abstract-flat-widget.ts +++ b/ui/src/app/shared/genericComponents/flat/abstract-flat-widget.ts @@ -54,9 +54,9 @@ export abstract class AbstractFlatWidget implements OnInit, OnDestroy { this.isInitialized = true; this.afterIsInitialized(); // get the channel addresses that should be subscribed - let channelAddresses: Set = new Set(this.getChannelAddresses()); - let channelIds = this.getChannelIds(); - for (let channelId of channelIds) { + const channelAddresses: Set = new Set(this.getChannelAddresses()); + const channelIds = this.getChannelIds(); + for (const channelId of channelIds) { channelAddresses.add(new ChannelAddress(this.componentId, channelId)); } this.dataService.getValues(Array.from(channelAddresses), this.edge, this.componentId); @@ -66,7 +66,7 @@ export abstract class AbstractFlatWidget implements OnInit, OnDestroy { }); }); }); - }; + } public ngOnDestroy() { this.dataService.unsubscribeFromChannels(this.getChannelAddresses()); @@ -105,5 +105,5 @@ export abstract class AbstractFlatWidget implements OnInit, OnDestroy { /** * Gets called after {@link onCurrentData}, every time the currentValue changes */ - protected afterOnCurrentData() { }; + protected afterOnCurrentData() { } } diff --git a/ui/src/app/shared/genericComponents/modal/abstract-modal-line.ts b/ui/src/app/shared/genericComponents/modal/abstract-modal-line.ts index 34ab2d1a6fb..11437da9071 100644 --- a/ui/src/app/shared/genericComponents/modal/abstract-modal-line.ts +++ b/ui/src/app/shared/genericComponents/modal/abstract-modal-line.ts @@ -50,7 +50,7 @@ export abstract class AbstractModalLine implements OnInit, OnDestroy, OnChanges } else { this._name = value; } - }; + } @Input() public value: number | string; @Input() public roleIsAtLeast?: Role = Role.GUEST; @@ -113,14 +113,14 @@ export abstract class AbstractModalLine implements OnInit, OnDestroy, OnChanges this.config = config; // get the channel addresses that should be subscribed - let channelAddresses: ChannelAddress[] = [...this.getChannelAddresses()]; + const channelAddresses: ChannelAddress[] = [...this.getChannelAddresses()]; if (typeof this.name == 'object') { channelAddresses.push(this.name.channel); } - let channelIds = this.getChannelIds(); - for (let channelId of channelIds) { + const channelIds = this.getChannelIds(); + for (const channelId of channelIds) { channelAddresses.push(new ChannelAddress(this.component.id, channelId)); } if (channelAddresses.length != 0) { @@ -129,9 +129,9 @@ export abstract class AbstractModalLine implements OnInit, OnDestroy, OnChanges // call onCurrentData() with latest data edge.currentData.pipe(takeUntil(this.stopOnDestroy)).subscribe(currentData => { - let allComponents = {}; - for (let channelAddress of channelAddresses) { - let ca = channelAddress.toString(); + const allComponents = {}; + for (const channelAddress of channelAddresses) { + const ca = channelAddress.toString(); allComponents[ca] = currentData.channel[ca]; } this.onCurrentData({ allComponents: allComponents }); diff --git a/ui/src/app/shared/genericComponents/modal/abstractModal.ts b/ui/src/app/shared/genericComponents/modal/abstractModal.ts index 51774138ddc..e1540757482 100644 --- a/ui/src/app/shared/genericComponents/modal/abstractModal.ts +++ b/ui/src/app/shared/genericComponents/modal/abstractModal.ts @@ -68,8 +68,8 @@ export abstract class AbstractModal implements OnInit, OnDestroy { if (this.component != null) { this.component = config.components[this.component.id]; - let channelIds = this.getChannelIds(); - for (let channelId of channelIds) { + const channelIds = this.getChannelIds(); + for (const channelId of channelIds) { channelAddresses.push(new ChannelAddress(this.component.id, channelId)); } } @@ -79,9 +79,9 @@ export abstract class AbstractModal implements OnInit, OnDestroy { // call onCurrentData() with latest data edge.currentData.pipe(takeUntil(this.stopOnDestroy)).subscribe(currentData => { - let allComponents = {}; - for (let channelAddress of channelAddresses) { - let ca = channelAddress.toString(); + const allComponents = {}; + for (const channelAddress of channelAddresses) { + const ca = channelAddress.toString(); allComponents[ca] = currentData.channel[ca]; } this.onCurrentData({ allComponents: allComponents }); @@ -95,7 +95,7 @@ export abstract class AbstractModal implements OnInit, OnDestroy { }); }); } - protected onIsInitialized() { }; + protected onIsInitialized() { } public ngOnDestroy() { // Unsubscribe from OpenEMS diff --git a/ui/src/app/shared/genericComponents/modal/help-button/help-button.ts b/ui/src/app/shared/genericComponents/modal/help-button/help-button.ts index f318a46f708..fe1fd90e48c 100644 --- a/ui/src/app/shared/genericComponents/modal/help-button/help-button.ts +++ b/ui/src/app/shared/genericComponents/modal/help-button/help-button.ts @@ -19,7 +19,7 @@ export class HelpButtonComponent { return; } - let link = environment.links[key];; + const link = environment.links[key]; if (link === null || link === "") { this.link = null; diff --git a/ui/src/app/shared/genericComponents/modal/modal-phases/modal-phases.ts b/ui/src/app/shared/genericComponents/modal/modal-phases/modal-phases.ts index 8e67e98fd7f..fff720300d9 100644 --- a/ui/src/app/shared/genericComponents/modal/modal-phases/modal-phases.ts +++ b/ui/src/app/shared/genericComponents/modal/modal-phases/modal-phases.ts @@ -22,9 +22,9 @@ export class ModalPhasesComponent extends AbstractModalLine { protected readonly TextIndentation = TextIndentation; protected override getChannelAddresses(): ChannelAddress[] { - let channelAddresses: ChannelAddress[] = []; + const channelAddresses: ChannelAddress[] = []; - for (let phase of this.phases) { + for (const phase of this.phases) { channelAddresses.push( ChannelAddress.fromString(this.component.id + '/ActivePower' + phase.key), ); @@ -33,8 +33,8 @@ export class ModalPhasesComponent extends AbstractModalLine { } protected override onCurrentData(currentData: CurrentData): void { - for (let phase of this.phases) { - let powerPerPhase = currentData.allComponents[this.component.id + '/ActivePower' + phase.key]; + for (const phase of this.phases) { + const powerPerPhase = currentData.allComponents[this.component.id + '/ActivePower' + phase.key]; phase.name = this.translate.instant('General.phase') + " " + phase.key + this.setTranslatedName(powerPerPhase); } } diff --git a/ui/src/app/shared/genericComponents/modal/modal.ts b/ui/src/app/shared/genericComponents/modal/modal.ts index 1eeaa030ded..c4f9d5f4ab7 100644 --- a/ui/src/app/shared/genericComponents/modal/modal.ts +++ b/ui/src/app/shared/genericComponents/modal/modal.ts @@ -51,10 +51,10 @@ export class ModalComponent { // Changes applied together public applyChanges() { - let updateComponentArray: { name: string, value: any }[] = []; + const updateComponentArray: { name: string, value: any }[] = []; this.service.startSpinner('spinner'); - for (let key in this.formGroup.controls) { - let control = this.formGroup.controls[key]; + for (const key in this.formGroup.controls) { + const control = this.formGroup.controls[key]; this.formGroup.controls[key]; // Check if formControl-value didn't change diff --git a/ui/src/app/shared/genericComponents/shared/converter.ts b/ui/src/app/shared/genericComponents/shared/converter.ts index 93447afc438..d6aa1d8fe99 100644 --- a/ui/src/app/shared/genericComponents/shared/converter.ts +++ b/ui/src/app/shared/genericComponents/shared/converter.ts @@ -1,4 +1,3 @@ -import { formatNumber } from "@angular/common"; import { TranslateService } from "@ngx-translate/core"; import { CurrentData, EdgeConfig, Utils } from "../../shared"; @@ -22,26 +21,6 @@ export namespace Converter { return "" + value; }; - - const FORMAT_WATT = (value: number) => { - // TODO apply correct locale - return formatNumber(value, 'de', '1.0-0') + " W"; - }; - - const FORMAT_MILLI_VOLT = (value: number) => { - return formatNumber(value, 'de', '1.0-0') + " mV"; - }; - - const FORMAT_VOLT = (value: number) => { - // TODO apply correct locale - return formatNumber(value, 'de', '1.0-0') + " V"; - }; - - const FORMAT_AMPERE = (value: number) => { - // TODO apply correct locale - return formatNumber(value, 'de', '1.1-1') + " A"; - }; - export const IF_NUMBER = (value: number | string | null, callback: (number: number) => string) => { if (typeof value === 'number') { return callback(value); @@ -126,7 +105,7 @@ export namespace Converter { export const VOLTAGE_TO_VOLT: Converter = (raw) => { return IF_NUMBER(raw, value => - FORMAT_VOLT(value)); + Formatter.FORMAT_VOLT(value)); }; /** @@ -140,7 +119,7 @@ export namespace Converter { */ export const CURRENT_IN_MILLIAMPERE_TO_AMPERE: Converter = (raw) => { return IF_NUMBER(raw, value => - FORMAT_AMPERE(value / 1000)); + Formatter.FORMAT_AMPERE(value / 1000)); }; export const ONLY_POSITIVE_POWER_AND_NEGATIVE_AS_ZERO: Converter = (raw) => { @@ -152,7 +131,7 @@ export namespace Converter { export const CURRENT_TO_AMPERE: Converter = (raw) => { return IF_NUMBER(raw, value => - FORMAT_AMPERE(value)); + Formatter.FORMAT_AMPERE(value)); }; export const CONVERT_TO_EXTERNAL_RECEIVER_LIMITATION: Converter = (raw) => { diff --git a/ui/src/app/shared/genericComponents/shared/oe-formly-component.ts b/ui/src/app/shared/genericComponents/shared/oe-formly-component.ts index 49d049c03c6..54f74ccc739 100644 --- a/ui/src/app/shared/genericComponents/shared/oe-formly-component.ts +++ b/ui/src/app/shared/genericComponents/shared/oe-formly-component.ts @@ -25,7 +25,7 @@ export abstract class AbstractFormlyComponent { edge.getConfig(service.websocket) .pipe(filter(config => !!config)) .subscribe((config) => { - var view = this.generateView(config, edge.role, this.translate); + const view = this.generateView(config, edge.role, this.translate); this.fields = [{ type: "input", diff --git a/ui/src/app/shared/genericComponents/shared/testing/tester.ts b/ui/src/app/shared/genericComponents/shared/testing/tester.ts index 3e6d3bcc9dd..ad4bd140916 100644 --- a/ui/src/app/shared/genericComponents/shared/testing/tester.ts +++ b/ui/src/app/shared/genericComponents/shared/testing/tester.ts @@ -21,18 +21,18 @@ export class OeFormlyViewTester { .map(line => OeFormlyViewTester.applyField(line, context)) .filter(line => line), }; - }; + } private static applyField(field: OeFormlyField, context: OeFormlyViewTester.Context): OeFormlyViewTester.Field { switch (field.type) { /** * OeFormlyField.Line */ - case 'children-line': - let tmp = OeFormlyViewTester.applyLineWithChildren(field, context); + case 'children-line': { + const tmp = OeFormlyViewTester.applyLineWithChildren(field, context); // Prepare result - let result: OeFormlyViewTester.Field.ChildrenLine = { + const result: OeFormlyViewTester.Field.ChildrenLine = { type: field.type, name: tmp.value, }; @@ -49,10 +49,10 @@ export class OeFormlyViewTester { } return result; - + } case "channel-line": { - let tmp = OeFormlyViewTester.applyLineOrItem(field, context); + const tmp = OeFormlyViewTester.applyLineOrItem(field, context); if (tmp == null) { return null; // filter did not pass } @@ -66,7 +66,7 @@ export class OeFormlyViewTester { } // Prepare result - let result: OeFormlyViewTester.Field.ChannelLine = { + const result: OeFormlyViewTester.Field.ChannelLine = { type: field.type, name: name, }; @@ -98,7 +98,7 @@ export class OeFormlyViewTester { const name: string = field.name; // Prepare result - let result: OeFormlyViewTester.Field.ValueLine = { + const result: OeFormlyViewTester.Field.ValueLine = { type: field.type, name: name, }; @@ -118,7 +118,7 @@ export class OeFormlyViewTester { * OeFormlyField.Item */ case "item": { - let tmp = OeFormlyViewTester.applyLineOrItem(field, context); + const tmp = OeFormlyViewTester.applyLineOrItem(field, context); if (tmp == null) { return null; // filter did not pass } @@ -162,7 +162,7 @@ export class OeFormlyViewTester { /* filter did not pass */ | null { // Read value from channels - let rawValue = field.channel && field.channel in context ? context[field.channel] : null; + const rawValue = field.channel && field.channel in context ? context[field.channel] : null; // Apply filter if (field.filter && field.filter(rawValue) === false) { @@ -170,7 +170,7 @@ export class OeFormlyViewTester { } // Apply converter - let value: string = field.converter + const value: string = field.converter ? field.converter(rawValue) : rawValue === null ? null : "" + rawValue; @@ -224,7 +224,7 @@ export class OeChartTester { public static apply(chartData: HistoryUtils.ChartData, chartType: 'line' | 'bar', channels: OeTester.Types.Channels, testContext: TestContext, config: EdgeConfig): OeChartTester.View { - let channelData = OeChartTester.getChannelDataByCharttype(chartType, channels); + const channelData = OeChartTester.getChannelDataByCharttype(chartType, channels); // Set historyPeriod manually with passed timestamps testContext.service.historyPeriod.next({ @@ -234,10 +234,10 @@ export class OeChartTester { }); // Fill Data - let configuration = AbstractHistoryChart.fillChart(chartType, chartData, channelData, channels.energyChannelWithValues); - let data: OeChartTester.Dataset.Data[] = OeChartTester.convertChartDatasetsToDatasets(configuration.datasets); - let labels: OeChartTester.Dataset.LegendLabel = OeChartTester.convertChartLabelsToLegendLabels(configuration.labels); - let options: OeChartTester.Dataset.Option = OeChartTester.convertChartDataToOptions(chartData, chartType, testContext, channels, testContext.translate.currentLang, config, configuration.datasets); + const configuration = AbstractHistoryChart.fillChart(chartType, chartData, channelData, channels.energyChannelWithValues); + const data: OeChartTester.Dataset.Data[] = OeChartTester.convertChartDatasetsToDatasets(configuration.datasets); + const labels: OeChartTester.Dataset.LegendLabel = OeChartTester.convertChartLabelsToLegendLabels(configuration.labels); + const options: OeChartTester.Dataset.Option = OeChartTester.convertChartDataToOptions(chartData, chartType, testContext, channels, testContext.translate.currentLang, config, configuration.datasets); return { datasets: { @@ -246,7 +246,7 @@ export class OeChartTester { options: options, }, }; - }; + } /** * Converts chartLabels to legendLabels @@ -268,9 +268,9 @@ export class OeChartTester { * @returns data from a chartData dataset */ public static convertChartDatasetsToDatasets(datasets: ChartDataset[]): OeChartTester.Dataset.Data[] { - let fields: OeChartTester.Dataset.Data[] = []; + const fields: OeChartTester.Dataset.Data[] = []; - for (let dataset of datasets) { + for (const dataset of datasets) { fields.push( { type: 'data', @@ -293,13 +293,13 @@ export class OeChartTester { */ public static convertChartDataToOptions(chartData: HistoryUtils.ChartData, chartType: 'line' | 'bar', testContext: TestContext, channels: OeTester.Types.Channels, locale: string, config: EdgeConfig, datasets: Chart.ChartDataset[]): OeChartTester.Dataset.Option { - let channelData: QueryHistoricTimeseriesDataResponse | QueryHistoricTimeseriesEnergyPerPeriodResponse = OeChartTester.getChannelDataByCharttype(chartType, channels); - let displayValues = chartData.output(channelData.result.data); - let legendOptions: any[] = []; + const channelData: QueryHistoricTimeseriesDataResponse | QueryHistoricTimeseriesEnergyPerPeriodResponse = OeChartTester.getChannelDataByCharttype(chartType, channels); + const displayValues = chartData.output(channelData.result.data); + const legendOptions: any[] = []; displayValues.forEach(displayValue => { - let yAxis = chartData.yAxes.find(yaxis => yaxis?.yAxisId == (displayValue?.yAxisId ?? chartData.yAxes[0].yAxisId)); - let label = AbstractHistoryChart.getTooltipsLabelName(displayValue.name, yAxis?.unit, typeof displayValue.nameSuffix == 'function' ? displayValue.nameSuffix(channels.energyChannelWithValues) : null); + const yAxis = chartData.yAxes.find(yaxis => yaxis?.yAxisId == (displayValue?.yAxisId ?? chartData.yAxes[0].yAxisId)); + const label = AbstractHistoryChart.getTooltipsLabelName(displayValue.name, yAxis?.unit, typeof displayValue.nameSuffix == 'function' ? displayValue.nameSuffix(channels.energyChannelWithValues) : null); legendOptions.push(AbstractHistoryChart.getLegendOptions(label, displayValue)); }); diff --git a/ui/src/app/shared/header/header.component.ts b/ui/src/app/shared/header/header.component.ts index c58cd17f05c..efd940d50a0 100644 --- a/ui/src/app/shared/header/header.component.ts +++ b/ui/src/app/shared/header/header.component.ts @@ -59,8 +59,8 @@ export class HeaderComponent implements OnInit, OnDestroy, AfterViewChecked { } updateEnableSideMenu(url: string) { - let urlArray = url.split('/'); - let file = urlArray.pop(); + const urlArray = url.split('/'); + const file = urlArray.pop(); if (file == 'user' || file == 'settings' || file == 'changelog' || urlArray.length > 3) { // disable side-menu; show back-button instead @@ -81,7 +81,7 @@ export class HeaderComponent implements OnInit, OnDestroy, AfterViewChecked { // set backUrl for user when an Edge had been selected before - let currentEdge: Edge = this.service.currentEdge.value; + const currentEdge: Edge = this.service.currentEdge.value; if (url === '/user' && currentEdge != null) { this.backUrl = '/device/' + currentEdge.id + "/live"; return; @@ -99,15 +99,14 @@ export class HeaderComponent implements OnInit, OnDestroy, AfterViewChecked { return; } - let urlArray = url.split('/'); + const urlArray = url.split('/'); let backUrl: string | boolean = '/'; - let file = urlArray.pop(); + const file = urlArray.pop(); // disable backUrl for History & EdgeIndex Component ++ Enable Segment Navigation if ((file == 'history' || file == 'live') && urlArray.length == 3) { this.backUrl = false; return; - } else { } // disable backUrl to first 'index' page from Edge index if there is only one Edge in the system @@ -137,7 +136,7 @@ export class HeaderComponent implements OnInit, OnDestroy, AfterViewChecked { } updateCurrentPage(url: string) { - let urlArray = url.split('/'); + const urlArray = url.split('/'); let file = urlArray.pop(); if (urlArray.length >= 4) { file = urlArray[3]; diff --git a/ui/src/app/shared/history-data-error.component.ts b/ui/src/app/shared/history-data-error.component.ts index 8b9b1de94cc..d3874ce0576 100644 --- a/ui/src/app/shared/history-data-error.component.ts +++ b/ui/src/app/shared/history-data-error.component.ts @@ -27,7 +27,7 @@ export class HistoryDataErrorComponent { type ErrorType = 'TEMPORARY' | 'TOO_LONG' | null; function toType(response: JsonrpcResponseError | null): ErrorType { - let message = response?.error?.message; + const message = response?.error?.message; if (message === undefined) { return null; } diff --git a/ui/src/app/shared/interface/interface.ts b/ui/src/app/shared/interface/interface.ts index 8050addee20..21bd8395301 100644 --- a/ui/src/app/shared/interface/interface.ts +++ b/ui/src/app/shared/interface/interface.ts @@ -3,4 +3,4 @@ import { NetworkInterface } from "src/app/edge/settings/network/shared"; export interface Interface { name: string, model: NetworkInterface, -}; +} diff --git a/ui/src/app/shared/jsonrpc/jsonrpcutils.ts b/ui/src/app/shared/jsonrpc/jsonrpcutils.ts index 3d9ff561229..642ffee60c6 100644 --- a/ui/src/app/shared/jsonrpc/jsonrpcutils.ts +++ b/ui/src/app/shared/jsonrpc/jsonrpcutils.ts @@ -6,8 +6,8 @@ export class JsonRpcUtils { * Converts an array of ChannelAddresses to a string array with unique values. */ public static channelsToStringArray(channels: ChannelAddress[]): string[] { - let result = []; - for (let channel of channels) { + const result = []; + for (const channel of channels) { result.push(channel.toString()); } return Array.from(new Set(result)); diff --git a/ui/src/app/shared/pickdate/pickdate.component.spec.ts b/ui/src/app/shared/pickdate/pickdate.component.spec.ts index 9bbeefd21b3..006848d21ba 100644 --- a/ui/src/app/shared/pickdate/pickdate.component.spec.ts +++ b/ui/src/app/shared/pickdate/pickdate.component.spec.ts @@ -6,11 +6,11 @@ import { PickDateComponent } from "./pickdate.component"; export function expectPreviousPeriod(testContext: TestContext, firstSetupProtocol: Date, expectToBe: boolean): void { expect(PickDateComponent.isPreviousPeriodAllowed(testContext.service, firstSetupProtocol)).toBe(expectToBe); -}; +} export function expectNextPeriod(testContext: TestContext, expectToBe: boolean): void { expect(PickDateComponent.isNextPeriodAllowed(testContext.service)).toBe(expectToBe); -}; +} describe('Pickdate', () => { diff --git a/ui/src/app/shared/pickdate/pickdate.component.ts b/ui/src/app/shared/pickdate/pickdate.component.ts index 0819dd7a7b2..5445b50b0eb 100644 --- a/ui/src/app/shared/pickdate/pickdate.component.ts +++ b/ui/src/app/shared/pickdate/pickdate.component.ts @@ -109,6 +109,7 @@ export class PickDateComponent implements OnInit, OnDestroy { } this.disableArrow = false; } + break; } case DefaultTypes.PeriodString.TOTAL: { this.disableArrow = true; @@ -117,7 +118,9 @@ export class PickDateComponent implements OnInit, OnDestroy { case DefaultTypes.PeriodString.CUSTOM: { let dateDistance = Math.floor(Math.abs(this.service.historyPeriod.value.from - this.service.historyPeriod.value.to) / (1000 * 60 * 60 * 24)); - dateDistance == 0 ? dateDistance = 1 : dateDistance = dateDistance; + if (dateDistance == 0) { + dateDistance = 1; + } if (isFuture(addDays(this.service.historyPeriod.value.from, dateDistance * 2))) { this.disableArrow = true; } else { @@ -210,7 +213,9 @@ export class PickDateComponent implements OnInit, OnDestroy { } case DefaultTypes.PeriodString.CUSTOM: { let dateDistance = Math.floor(Math.abs(this.service.historyPeriod.value.from - this.service.historyPeriod.value.to) / (1000 * 60 * 60 * 24)); - dateDistance == 0 ? dateDistance = 1 : dateDistance = dateDistance; + if (dateDistance == 0) { + dateDistance = 1; + } if (isFuture(addDays(this.service.historyPeriod.value.to, dateDistance * 2))) { this.disableArrow = true; } @@ -259,7 +264,9 @@ export class PickDateComponent implements OnInit, OnDestroy { } case DefaultTypes.PeriodString.CUSTOM: { let dateDistance = Math.floor(Math.abs(this.service.historyPeriod.value.from - this.service.historyPeriod.value.to) / (1000 * 60 * 60 * 24)); - dateDistance == 0 ? dateDistance = 1 : dateDistance = dateDistance; + if (dateDistance == 0) { + dateDistance = 1; + } this.setDateRange(new DefaultTypes.HistoryPeriod(subDays(this.service.historyPeriod.value.from, dateDistance), subDays(this.service.historyPeriod.value.to, dateDistance))); break; } @@ -319,23 +326,23 @@ export class PickDateComponent implements OnInit, OnDestroy { // + 1000 to reach the next day switch (this.service.periodString) { case DefaultTypes.PeriodString.DAY: { - let currentDayTime = new Date(); - let endOfDayTime = endOfDay(currentDayTime); + const currentDayTime = new Date(); + const endOfDayTime = endOfDay(currentDayTime); return differenceInMilliseconds(endOfDayTime, currentDayTime) + 1000; } case DefaultTypes.PeriodString.WEEK: { - let currentDayTime = new Date(); - let endOfWeekTime = endOfWeek(currentDayTime, { weekStartsOn: 1 }); + const currentDayTime = new Date(); + const endOfWeekTime = endOfWeek(currentDayTime, { weekStartsOn: 1 }); return differenceInMilliseconds(endOfWeekTime, currentDayTime) + 1000; } case DefaultTypes.PeriodString.MONTH: { - let currentDayTime = new Date(); - let endOfMonthTime = endOfMonth(currentDayTime); + const currentDayTime = new Date(); + const endOfMonthTime = endOfMonth(currentDayTime); return differenceInMilliseconds(endOfMonthTime, currentDayTime) + 1000; } case DefaultTypes.PeriodString.YEAR: { - let currentDayTime = new Date(); - let endOfYearTime = endOfYear(currentDayTime); + const currentDayTime = new Date(); + const endOfYearTime = endOfYear(currentDayTime); return differenceInMilliseconds(endOfYearTime, currentDayTime) + 1000; } } @@ -383,9 +390,10 @@ export class PickDateComponent implements OnInit, OnDestroy { return isBefore(firstSetupProtocol, endOfYear(subWeeks(service.historyPeriod.value.from, 1))); case DefaultTypes.PeriodString.TOTAL: return false; - case DefaultTypes.PeriodString.CUSTOM: - var timeRange: number = differenceInDays(service.historyPeriod.value.to, service.historyPeriod.value.from); + case DefaultTypes.PeriodString.CUSTOM: { + const timeRange: number = differenceInDays(service.historyPeriod.value.to, service.historyPeriod.value.from); return isBefore(startOfDay(firstSetupProtocol), startOfDay(subDays(service.historyPeriod.value.from, timeRange))); + } } } @@ -408,9 +416,10 @@ export class PickDateComponent implements OnInit, OnDestroy { return isAfter(new Date(), startOfYear(addYears(service.historyPeriod.value.to, 1))); case DefaultTypes.PeriodString.TOTAL: return false; - case DefaultTypes.PeriodString.CUSTOM: - var timeRange: number = differenceInDays(service.historyPeriod.value.to, service.historyPeriod.value.from); + case DefaultTypes.PeriodString.CUSTOM: { + const timeRange: number = differenceInDays(service.historyPeriod.value.to, service.historyPeriod.value.from); return isAfter(startOfDay(new Date()), addDays(service.historyPeriod.value.to, timeRange)); + } } } } diff --git a/ui/src/app/shared/pipe/classname/classname.pipe.ts b/ui/src/app/shared/pipe/classname/classname.pipe.ts index 5d761f58ad2..386c9241826 100644 --- a/ui/src/app/shared/pipe/classname/classname.pipe.ts +++ b/ui/src/app/shared/pipe/classname/classname.pipe.ts @@ -5,7 +5,7 @@ import { Pipe, PipeTransform } from '@angular/core'; }) export class ClassnamePipe implements PipeTransform { transform(value, args: string[]): any { - let parts = value.split("."); + const parts = value.split("."); return parts[parts.length - 1]; } } diff --git a/ui/src/app/shared/pipe/formatSecondsToDuration/formatSecondsToDuration.pipe.ts b/ui/src/app/shared/pipe/formatSecondsToDuration/formatSecondsToDuration.pipe.ts index acc42e39c2c..63651148d51 100644 --- a/ui/src/app/shared/pipe/formatSecondsToDuration/formatSecondsToDuration.pipe.ts +++ b/ui/src/app/shared/pipe/formatSecondsToDuration/formatSecondsToDuration.pipe.ts @@ -14,7 +14,7 @@ export class FormatSecondsToDurationPipe implements PipeTransform { return Converter.IF_NUMBER(value, (val) => { let minutes = val / 60; - let hours = Math.floor(minutes / 60); + const hours = Math.floor(minutes / 60); minutes -= hours * 60; if (hours <= 23) { return this.decimalPipe.transform(hours, '1.0-0') + 'h' + " " + this.decimalPipe.transform(minutes, '1.0-0') + 'm'; diff --git a/ui/src/app/shared/pipe/keys/keys.pipe.ts b/ui/src/app/shared/pipe/keys/keys.pipe.ts index 456d615a364..7098244b582 100644 --- a/ui/src/app/shared/pipe/keys/keys.pipe.ts +++ b/ui/src/app/shared/pipe/keys/keys.pipe.ts @@ -9,8 +9,8 @@ export class KeysPipe implements PipeTransform { return value; } - let keys = []; - for (let key in value) { + const keys = []; + for (const key in value) { keys.push({ key: key, value: value[key] }); } return keys; diff --git a/ui/src/app/shared/pipe/sign/sign.pipe.ts b/ui/src/app/shared/pipe/sign/sign.pipe.ts index d7cfffe115e..dafe66279b7 100644 --- a/ui/src/app/shared/pipe/sign/sign.pipe.ts +++ b/ui/src/app/shared/pipe/sign/sign.pipe.ts @@ -5,7 +5,7 @@ import { Pipe, PipeTransform } from '@angular/core'; }) export class SignPipe implements PipeTransform { transform(value, args: string[]): any { - let positive = value * -1; + const positive = value * -1; return positive; } } diff --git a/ui/src/app/shared/service/defaulttypes.ts b/ui/src/app/shared/service/defaulttypes.ts index a2d2a28b946..e9762bda4f4 100644 --- a/ui/src/app/shared/service/defaulttypes.ts +++ b/ui/src/app/shared/service/defaulttypes.ts @@ -92,7 +92,7 @@ export module DefaultTypes { params?: string[] } - export enum PeriodString { DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', TOTAL = 'total', CUSTOM = 'custom' }; + export enum PeriodString { DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', TOTAL = 'total', CUSTOM = 'custom' } /** Values of {@link DefaultTypes.PeriodString} */ export type PeriodStringValues = Exclude<`${DefaultTypes.PeriodString}`, "custom">; diff --git a/ui/src/app/shared/service/myerrorhandler.ts b/ui/src/app/shared/service/myerrorhandler.ts index b6a0bc7a7ed..a4ebbfee278 100644 --- a/ui/src/app/shared/service/myerrorhandler.ts +++ b/ui/src/app/shared/service/myerrorhandler.ts @@ -9,10 +9,10 @@ export class MyErrorHandler implements ErrorHandler { ) { } handleError(error: any) { - let logger = this.injector.get(Logger); + const logger = this.injector.get(Logger); console.error(error); if (error.message) { - let json = { + const json = { error: { message: error.message, }, diff --git a/ui/src/app/shared/service/service.ts b/ui/src/app/shared/service/service.ts index fc01ff93497..5a724cb6fe8 100644 --- a/ui/src/app/shared/service/service.ts +++ b/ui/src/app/shared/service/service.ts @@ -189,14 +189,14 @@ export class Service extends AbstractService { return new Promise((resolve) => { resolve(channels); }); - }; + } public queryEnergy(fromDate: Date, toDate: Date, channels: ChannelAddress[]): Promise { // keep only the date, without time fromDate.setHours(0, 0, 0, 0); toDate.setHours(0, 0, 0, 0); - let promise = { resolve: null, reject: null }; - let response = new Promise((resolve, reject) => { + const promise = { resolve: null, reject: null }; + const response = new Promise((resolve, reject) => { promise.resolve = resolve; promise.reject = reject; }); @@ -210,23 +210,23 @@ export class Service extends AbstractService { this.queryEnergyTimeout = null; // merge requests - let mergedRequests: { + const mergedRequests: { fromDate: Date, toDate: Date, channels: ChannelAddress[], promises: { resolve, reject }[]; }[] = []; let request; - while (request = this.queryEnergyQueue.pop()) { + while ((request = this.queryEnergyQueue.pop())) { if (mergedRequests.length == 0) { mergedRequests.push(request); } else { let merged = false; - for (let mergedRequest of mergedRequests) { + for (const mergedRequest of mergedRequests) { if (mergedRequest.fromDate.valueOf() === request.fromDate.valueOf() && mergedRequest.toDate.valueOf() === request.toDate.valueOf()) { // same date -> merge mergedRequest.promises = mergedRequest.promises.concat(request.promises); - for (let newChannel of request.channels) { + for (const newChannel of request.channels) { let isAlreadyThere = false; - for (let existingChannel of mergedRequest.channels) { + for (const existingChannel of mergedRequest.channels) { if (existingChannel.channelId == newChannel.channelId && existingChannel.componentId == newChannel.componentId) { isAlreadyThere = true; break; @@ -247,27 +247,27 @@ export class Service extends AbstractService { // send merged requests this.getCurrentEdge().then(edge => { - for (let source of mergedRequests) { + for (const source of mergedRequests) { // Jump to next request for empty channelAddresses if (source.channels.length == 0) { continue; } - let request = new QueryHistoricTimeseriesEnergyRequest(DateUtils.maxDate(source.fromDate, edge?.firstSetupProtocol), source.toDate, source.channels); + const request = new QueryHistoricTimeseriesEnergyRequest(DateUtils.maxDate(source.fromDate, edge?.firstSetupProtocol), source.toDate, source.channels); edge.sendRequest(this.websocket, request).then(response => { - let result = (response as QueryHistoricTimeseriesEnergyResponse).result; + const result = (response as QueryHistoricTimeseriesEnergyResponse).result; if (Object.keys(result.data).length != 0) { - for (let promise of source.promises) { + for (const promise of source.promises) { promise.resolve(response as QueryHistoricTimeseriesEnergyResponse); } } else { - for (let promise of source.promises) { + for (const promise of source.promises) { promise.reject(new JsonrpcResponseError(response.id, { code: 0, message: "Result was empty" })); } } }).catch(reason => { - for (let promise of source.promises) { + for (const promise of source.promises) { promise.reject(reason); } }); @@ -299,10 +299,10 @@ export class Service extends AbstractService { const result = (response as GetEdgesResponse).result; // TODO change edges-map to array or other way around - let value = this.metadata.value; - let mappedResult = []; - for (let edge of result.edges) { - let mappedEdge = new Edge( + const value = this.metadata.value; + const mappedResult = []; + for (const edge of result.edges) { + const mappedEdge = new Edge( edge.id, edge.comment, edge.producttype, @@ -340,8 +340,8 @@ export class Service extends AbstractService { return; } this.websocket.sendSafeRequest(new GetEdgeRequest({ edgeId: edgeId })).then((response) => { - let edgeData = (response as GetEdgeResponse).result.edge; - let value = this.metadata.value; + const edgeData = (response as GetEdgeResponse).result.edge; + const value = this.metadata.value; const currentEdge = new Edge( edgeData.id, edgeData.comment, diff --git a/ui/src/app/shared/service/utils.ts b/ui/src/app/shared/service/utils.ts index baea7523ea2..9d1792028c5 100644 --- a/ui/src/app/shared/service/utils.ts +++ b/ui/src/app/shared/service/utils.ts @@ -64,8 +64,8 @@ export class Utils { } else { copy = {}; } - for (let attr in obj) { - if (obj.hasOwnProperty(attr)) { + for (const attr in obj) { + if (Object.prototype.hasOwnProperty.call(obj, attr)) { copy[attr] = this.deepCopy(obj[attr], copy[attr]); } } @@ -214,10 +214,10 @@ export class Utils { * @param bases array of base-strings * @returns true if all filter strings exist in any base-strings */ - public static matchAll(filters: string[], bases: string[]): Boolean { - for (let filter of filters) { + public static matchAll(filters: string[], bases: string[]): boolean { + for (const filter of filters) { let filterMatched = false; - for (let base of bases) { + for (const base of bases) { if (base.includes(filter)) { filterMatched = true; } @@ -255,7 +255,7 @@ export class Utils { if (value == null) { return '-'; } - let thisValue: number = (value / 1000); + const thisValue: number = (value / 1000); if (thisValue >= 0) { return formatNumber(thisValue, 'de', '1.0-1') + ' kW'; @@ -335,7 +335,7 @@ export class Utils { } else { return { name: translate.instant('General.chargePower'), value: power * -1 }; } - }; + } /** @@ -365,7 +365,7 @@ export class Utils { */ public static CONVERT_MINUTE_TO_TIME_OF_DAY = (translate: TranslateService) => { return (value: number): string => { - var date: Date = new Date(); + const date: Date = new Date(); date.setHours(0, 0, 0, 0); date.setMinutes(value); return date.toLocaleTimeString(translate.getBrowserCultureLang(), { hour: '2-digit', minute: '2-digit' }); @@ -434,11 +434,11 @@ export class Utils { public static downloadXlsx(response: Base64PayloadResponse, filename: string) { // decode base64 string, remove space for IE compatibility // source: https://stackoverflow.com/questions/36036280/base64-representing-pdf-to-blob-javascript/45872086 - var binary = atob(response.result.payload.replace(/\s/g, '')); - var len = binary.length; - var buffer = new ArrayBuffer(len); - var view = new Uint8Array(buffer); - for (var i = 0; i < len; i++) { + const binary = atob(response.result.payload.replace(/\s/g, '')); + const len = binary.length; + const buffer = new ArrayBuffer(len); + const view = new Uint8Array(buffer); + for (let i = 0; i < len; i++) { view[i] = binary.charCodeAt(i); } const data: Blob = new Blob([view], { @@ -580,8 +580,8 @@ export class Utils { */ public static calculateOtherConsumption(channelData: HistoryUtils.ChannelData, evcsComponents: EdgeConfig.Component[], consumptionMeterComponents: EdgeConfig.Component[]): number[] { - let totalEvcsConsumption: number[] = []; - let totalMeteredConsumption: number[] = []; + const totalEvcsConsumption: number[] = []; + const totalMeteredConsumption: number[] = []; evcsComponents.forEach(component => { channelData[component.id + '/ChargePower']?.forEach((value, index) => { diff --git a/ui/src/app/shared/service/websocket.ts b/ui/src/app/shared/service/websocket.ts index 7aeceec46e7..65c6e196d99 100644 --- a/ui/src/app/shared/service/websocket.ts +++ b/ui/src/app/shared/service/websocket.ts @@ -79,7 +79,7 @@ export class Websocket implements WebsocketInterface { if (environment.debugMode) { console.info("Websocket connection opened"); } - let token = this.cookieService.get('token'); + const token = this.cookieService.get('token'); if (token) { // Login with Session Token this.login(new AuthenticateWithTokenRequest({ token: token })); @@ -113,7 +113,7 @@ export class Websocket implements WebsocketInterface { ).subscribe(originalMessage => { // Receive message from server - let message: JsonrpcRequest | JsonrpcNotification | JsonrpcResponseSuccess | JsonrpcResponseError = + const message: JsonrpcRequest | JsonrpcNotification | JsonrpcResponseSuccess | JsonrpcResponseError = JsonrpcMessage.from(originalMessage); if (message instanceof JsonrpcRequest) { @@ -159,9 +159,9 @@ export class Websocket implements WebsocketInterface { public login(request: AuthenticateWithPasswordRequest | AuthenticateWithTokenRequest): Promise { return new Promise((resolve) => { this.sendRequest(request).then(r => { - let authenticateResponse = (r as AuthenticateResponse).result; + const authenticateResponse = (r as AuthenticateResponse).result; - let language = Language.getByKey(localStorage.DEMO_LANGUAGE ?? authenticateResponse.user.language.toLocaleLowerCase()); + const language = Language.getByKey(localStorage.DEMO_LANGUAGE ?? authenticateResponse.user.language.toLocaleLowerCase()); localStorage.LANGUAGE = language.key; this.service.setLang(language); this.status = 'online'; @@ -261,7 +261,7 @@ export class Websocket implements WebsocketInterface { console.warn("Request failed [" + request.method + "]", reason.error); if (request instanceof EdgeRpcRequest && reason.error?.code == 3000 /* Edge is not connected */) { - let edges = this.service.metadata.value?.edges ?? {}; + const edges = this.service.metadata.value?.edges ?? {}; if (request.params.edgeId in edges) { edges[request.params.edgeId].isOnline = false; } @@ -288,7 +288,7 @@ export class Websocket implements WebsocketInterface { */ public sendSafeRequest(request: JsonrpcRequest): Promise { return new Promise((resolve, reject) => { - let interval = setInterval(() => { + const interval = setInterval(() => { // TODO: Status should be Observable, furthermore status should be like state-machine if (this.status == 'online') { @@ -359,12 +359,12 @@ export class Websocket implements WebsocketInterface { * @param message the EdgeRpcNotification */ private handleEdgeRpcNotification(edgeRpcNotification: EdgeRpcNotification): void { - let edgeId = edgeRpcNotification.params.edgeId; - let message = edgeRpcNotification.params.payload; + const edgeId = edgeRpcNotification.params.edgeId; + const message = edgeRpcNotification.params.payload; - let edges = this.service.metadata.value?.edges ?? {}; + const edges = this.service.metadata.value?.edges ?? {}; if (edgeId in edges) { - let edge = edges[edgeId]; + const edge = edges[edgeId]; switch (message.method) { case EdgeConfigNotification.METHOD: diff --git a/ui/src/app/shared/service/wsdata.ts b/ui/src/app/shared/service/wsdata.ts index 48585d7686a..a0f8511fa45 100644 --- a/ui/src/app/shared/service/wsdata.ts +++ b/ui/src/app/shared/service/wsdata.ts @@ -34,7 +34,7 @@ export class WsData { // create Promise let promiseResolve: (value?: JsonrpcResponseSuccess | PromiseLike) => void; let promiseReject: (reason?: any) => void; - let promise = new Promise((resolve, reject) => { + const promise = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); @@ -67,7 +67,7 @@ export class WsData { * @param response */ public handleJsonrpcResponse(response: JsonrpcResponse) { - let promise = this.requestPromises[response.id]; + const promise = this.requestPromises[response.id]; if (promise) { // this was a response on a request if (response instanceof JsonrpcResponseSuccess) { diff --git a/ui/src/app/shared/status/single/status.component.spec.ts b/ui/src/app/shared/status/single/status.component.spec.ts index dcafd1a9ee9..cee24623420 100644 --- a/ui/src/app/shared/status/single/status.component.spec.ts +++ b/ui/src/app/shared/status/single/status.component.spec.ts @@ -43,8 +43,3 @@ describe('StatusComponent', () => { }); }); }); - -// TODO dummy classes for needed services -class Dummy { - -} diff --git a/ui/src/app/shared/status/single/status.component.ts b/ui/src/app/shared/status/single/status.component.ts index f3fae8a36b6..4355d6dba50 100644 --- a/ui/src/app/shared/status/single/status.component.ts +++ b/ui/src/app/shared/status/single/status.component.ts @@ -30,7 +30,7 @@ export class StatusSingleComponent implements OnInit, OnDestroy { ngOnInit() { this.service.getConfig().then(config => { this.config = config; - let categorizedComponentIds: string[] = []; + const categorizedComponentIds: string[] = []; this.components = config.listActiveComponents(categorizedComponentIds); this.components.forEach(categorizedComponent => { categorizedComponent.components.forEach(component => { diff --git a/ui/src/app/shared/test/utils.spec.ts b/ui/src/app/shared/test/utils.spec.ts index a94f83dbc00..22138e70405 100644 --- a/ui/src/app/shared/test/utils.spec.ts +++ b/ui/src/app/shared/test/utils.spec.ts @@ -34,7 +34,7 @@ export async function sharedSetup(): Promise { translate: TestBed.inject(TranslateService), service: TestBed.inject(Service), }; -}; +} export function removeFunctions(obj: any): any { if (typeof obj !== 'object' || obj === null) { diff --git a/ui/src/app/shared/type/channeladdress.ts b/ui/src/app/shared/type/channeladdress.ts index 7539bdccb9c..a29f08cd0ab 100644 --- a/ui/src/app/shared/type/channeladdress.ts +++ b/ui/src/app/shared/type/channeladdress.ts @@ -6,7 +6,7 @@ export class ChannelAddress { * @param address in the form 'Component-ID/Channel-ID' */ public static fromString(address: string): ChannelAddress { - let array = address.split('/', 2); + const array = address.split('/', 2); return new ChannelAddress(array[0], array[1]); } diff --git a/ui/src/app/shared/type/language.ts b/ui/src/app/shared/type/language.ts index beb03815b9e..27eb8d133e9 100644 --- a/ui/src/app/shared/type/language.ts +++ b/ui/src/app/shared/type/language.ts @@ -17,7 +17,7 @@ import ja from 'src/assets/i18n/ja.json'; export class MyTranslateLoader implements TranslateLoader { public getTranslation(key: string): Observable { - var language = Language.getByKey(key); + const language = Language.getByKey(key); if (language) { return of(language.json); } @@ -39,7 +39,7 @@ export class Language { public static readonly DEFAULT = Language.DE; public static getByKey(key: string): Language | null { - for (let language of Language.ALL) { + for (const language of Language.ALL) { if (language.key == key) { return language; diff --git a/ui/src/app/shared/type/widget.ts b/ui/src/app/shared/type/widget.ts index 5e94da10de1..474955e1efe 100644 --- a/ui/src/app/shared/type/widget.ts +++ b/ui/src/app/shared/type/widget.ts @@ -44,7 +44,7 @@ export type Icon = { } export class Widget { - public name: WidgetNature | WidgetFactory | String; + public name: WidgetNature | WidgetFactory | string; public componentId: string; } @@ -52,7 +52,7 @@ export class Widgets { public static parseWidgets(edge: Edge, config: EdgeConfig): Widgets { - let classes: String[] = Object.values(WidgetClass) // + const classes: string[] = Object.values(WidgetClass) // .filter(v => typeof v === 'string') .filter(clazz => { if (!edge.isVersionAtLeast('2018.8')) { @@ -78,13 +78,13 @@ export class Widgets { return config.hasProducer(); case 'Controller_ChannelThreshold': return config.getComponentIdsByFactory('Controller.ChannelThreshold')?.length > 0; - }; + } return false; }).map(clazz => clazz.toString()); - let list: Widget[] = []; + const list: Widget[] = []; - for (let nature of Object.values(WidgetNature).filter(v => typeof v === 'string')) { - for (let componentId of config.getComponentIdsImplementingNature(nature.toString())) { + for (const nature of Object.values(WidgetNature).filter(v => typeof v === 'string')) { + for (const componentId of config.getComponentIdsImplementingNature(nature.toString())) { if (nature === 'io.openems.edge.io.api.DigitalInput' && list.some(e => e.name === 'io.openems.edge.io.api.DigitalInput')) { continue; } @@ -93,8 +93,8 @@ export class Widgets { } } } - for (let factory of Object.values(WidgetFactory).filter(v => typeof v === 'string')) { - for (let componentId of config.getComponentIdsByFactory(factory.toString())) { + for (const factory of Object.values(WidgetFactory).filter(v => typeof v === 'string')) { + for (const componentId of config.getComponentIdsByFactory(factory.toString())) { if (config.getComponent(componentId).isEnabled) { list.push({ name: factory, componentId: componentId }); } @@ -137,11 +137,11 @@ export class Widgets { /** * List of Widget-Classes. */ - public readonly classes: String[], + public readonly classes: string[], ) { // fill names - for (let widget of list) { - let name: string = widget.name.toString(); + for (const widget of list) { + const name: string = widget.name.toString(); if (!this.names.includes(name)) { this.names.push(name); } diff --git a/ui/src/app/shared/utils/color/color.utils.ts b/ui/src/app/shared/utils/color/color.utils.ts index cd424a03897..c2041facddf 100644 --- a/ui/src/app/shared/utils/color/color.utils.ts +++ b/ui/src/app/shared/utils/color/color.utils.ts @@ -29,8 +29,8 @@ export namespace ColorUtils { return null; } - var rgba = color.split('(').pop().split(')')[0]; - var rgb = rgba.split(',').slice(0, -1).join(','); + const rgba = color.split('(').pop().split(')')[0]; + const rgb = rgba.split(',').slice(0, -1).join(','); return 'rgba(' + rgb + ',' + (opacity ?? 0) + ')'; } diff --git a/ui/src/app/shared/utils/date/dateutils.ts b/ui/src/app/shared/utils/date/dateutils.ts index 8c4925b181f..9ec1355b01f 100644 --- a/ui/src/app/shared/utils/date/dateutils.ts +++ b/ui/src/app/shared/utils/date/dateutils.ts @@ -9,7 +9,7 @@ export namespace DateUtils { */ export function maxDate(...dates: Date[]) { - if (dates.length === 0 || dates.every(element => typeof element === null)) { + if (dates.length === 0 || dates.every(element => element === null)) { return null; } @@ -26,7 +26,7 @@ export namespace DateUtils { */ export function minDate(...dates: Date[]) { - if (dates.length === 0 || dates.every(element => typeof element === null)) { + if (dates.length === 0 || dates.every(element => element === null)) { return null; } diff --git a/ui/src/app/shared/utils/datetime/datetime-utils.ts b/ui/src/app/shared/utils/datetime/datetime-utils.ts index a3848e93731..76af3902b26 100644 --- a/ui/src/app/shared/utils/datetime/datetime-utils.ts +++ b/ui/src/app/shared/utils/datetime/datetime-utils.ts @@ -18,21 +18,21 @@ export class DateTimeUtils { public static normalizeTimestamps(unit: ChronoUnit.Type, energyPerPeriodResponse: QueryHistoricTimeseriesDataResponse | QueryHistoricTimeseriesEnergyPerPeriodResponse): QueryHistoricTimeseriesDataResponse | QueryHistoricTimeseriesEnergyPerPeriodResponse { switch (unit) { - case ChronoUnit.Type.MONTHS: + case ChronoUnit.Type.MONTHS: { // Change first timestamp to start of month const formattedDate = startOfMonth(DateUtils.stringToDate(energyPerPeriodResponse.result.timestamps[0])); energyPerPeriodResponse.result.timestamps[0] = format(formattedDate, 'yyyy-MM-dd HH:mm:ss', { locale: de })?.toString() ?? energyPerPeriodResponse.result.timestamps[0]; // show 12 stacks, even if no data and timestamps - let newTimestamps: string[] = []; + const newTimestamps: string[] = []; const firstTimestamp = DateUtils.stringToDate(energyPerPeriodResponse.result.timestamps[0]); if (firstTimestamp.getMonth() !== 0) { for (let i = 0; i <= (firstTimestamp.getMonth() - 1); i++) { newTimestamps.push(new Date(firstTimestamp.getFullYear(), i).toString()); - for (let channel of Object.keys(energyPerPeriodResponse.result.data)) { + for (const channel of Object.keys(energyPerPeriodResponse.result.data)) { energyPerPeriodResponse.result.data[channel.toString()]?.unshift(null); } } @@ -40,14 +40,16 @@ export class DateTimeUtils { energyPerPeriodResponse.result.timestamps = newTimestamps.concat(energyPerPeriodResponse.result.timestamps); break; + } - case ChronoUnit.Type.YEARS: + case ChronoUnit.Type.YEARS: { // Change dates to be first day of year const formattedDates = energyPerPeriodResponse.result.timestamps.map((timestamp) => startOfYear(DateUtils.stringToDate(timestamp))); energyPerPeriodResponse.result.timestamps = formattedDates.map(date => format(date, 'yyyy-MM-dd HH:mm:ss', { locale: de })?.toString()); break; + } } return energyPerPeriodResponse; diff --git a/ui/src/app/shared/utils/time/timeutils.ts b/ui/src/app/shared/utils/time/timeutils.ts index b0db593142e..d53491fbc34 100644 --- a/ui/src/app/shared/utils/time/timeutils.ts +++ b/ui/src/app/shared/utils/time/timeutils.ts @@ -18,7 +18,7 @@ export class TimeUtils { const decimalPipe: DecimalPipe = new DecimalPipe(locale ?? Language.DEFAULT.key); let minutes = value / 60; - let hours = Math.floor(minutes / 60); + const hours = Math.floor(minutes / 60); minutes -= hours * 60; if (hours <= 23 && minutes > 0) { diff --git a/ui/src/app/user/user.component.ts b/ui/src/app/user/user.component.ts index 66723bb1178..35d71138e2e 100644 --- a/ui/src/app/user/user.component.ts +++ b/ui/src/app/user/user.component.ts @@ -60,7 +60,7 @@ export class UserComponent implements OnInit { } public applyChanges() { - let user = { + const user = { user: { lastname: this.form.model.lastname, firstname: this.form.model.firstname, @@ -208,10 +208,10 @@ export class UserComponent implements OnInit { public getUserInformation(): Promise { return new Promise(resolve => { - var interval = setInterval(() => { + const interval = setInterval(() => { if (this.websocket.status == 'online') { this.service.websocket.sendRequest(new GetUserInformationRequest()).then((response: GetUserInformationResponse) => { - let user = response.result.user; + const user = response.result.user; resolve({ lastname: user.lastname,