Compare commits

..

11 Commits

31 changed files with 423 additions and 247 deletions

View File

@ -66,6 +66,12 @@
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>

View File

@ -72,6 +72,38 @@ export abstract class Device {
return d => d.areaId === areaId && d.roomId === roomId;
}
getSwitchClassList(): object {
if (!(this instanceof DeviceSwitch)) {
throw Error();
}
const value: number | null | undefined = (this as DeviceSwitch).stateProperty?.readChannel?.value;
return {
deviceSwitchOnBack: value === 1,
deviceSwitchOffBack: value === 0,
disabledBack: value === null || value === undefined,
};
}
getStateSceneClassList(): object {
if (!(this instanceof DeviceStateScene)) {
throw Error();
}
return this.getSwitchClassList();
}
getShutterClassList(): object {
if (!(this instanceof DeviceShutter)) {
throw Error();
}
const value: number | null | undefined = (this as DeviceShutter).positionProperty?.readChannel?.value;
return {
deviceShutterOpenBack: value === 0,
deviceShutterIntermediateBack: value !== null && value !== undefined && value > 0 && value < 100,
deviceShutterClosedBack: value === 100,
disabledBack: value === null || value === undefined,
};
}
}
export class DeviceSwitch extends Device {

View File

@ -1,8 +1,16 @@
import {validateListOrEmpty, validateNumberNotNull, validateStringEmptyToNull, validateStringNotEmptyNotNull} from "../validators";
import {undefinedOrNull, validateListOrEmpty, validateNumberNotNull, validateStringEmptyToNull, validateStringNotEmptyNotNull} from "../validators";
import {Channel} from "../channel/Channel";
import {SearchResult} from "../SearchResult";
import {environment} from "../../../environments/environment";
export enum PropertyType {
BOOLEAN = 'BOOLEAN',
SHUTTER = 'SHUTTER',
BRIGHTNESS_PERCENT = 'BRIGHTNESS_PERCENT',
COLOR_TEMPERATURE = 'COLOR_TEMPERATURE',
LUX = 'LUX',
}
export class Property {
readonly hrefId: string | null;
@ -11,7 +19,7 @@ export class Property {
constructor(
public id: number,
public type: string,
public type: PropertyType,
public title: string,
public slug: string | null,
public readChannel: Channel | null,
@ -36,7 +44,7 @@ export class Property {
static fromJson(json: any): Property {
return new Property(
validateNumberNotNull(json['id']),
validateStringNotEmptyNotNull(json['type']),
validateStringNotEmptyNotNull(json['type']) as PropertyType,
validateStringNotEmptyNotNull(json['title']),
validateStringEmptyToNull(json['slug']),
Channel.fromJsonAllowNull(json['readChannel']),
@ -63,4 +71,32 @@ export class Property {
}
return a.title.localeCompare(b.title);
}
getStateClassList() {
const value = this.readChannel?.value;
switch (this.type) {
case PropertyType.BOOLEAN:
return {
propertyStateBooleanUnknown: undefinedOrNull(value),
propertyStateBooleanTrue: value > 0,
propertyStateBooleanFalse: value === 0,
};
case PropertyType.SHUTTER:
return {
propertyStatePercentUnknown: undefinedOrNull(value),
propertyStatePercentActive: value === 0,
propertyStatePercentBetween: value > 0 && value < 100,
propertyStatePercentInactive: value === 100,
};
case PropertyType.BRIGHTNESS_PERCENT:
return {
propertyStatePercentUnknown: undefinedOrNull(value),
propertyStatePercentActive: value === 100,
propertyStatePercentBetween: value > 0 && value < 100,
propertyStatePercentInactive: value === 0,
};
}
return {};
}
}

View File

@ -87,3 +87,7 @@ export function validateMap<T>(json: any, valueFromJson: (json: any) => T): Map<
}
return map;
}
export function undefinedOrNull(value: any) {
return value === undefined || value === null;
}

View File

@ -1,24 +1,24 @@
<table>
<tr>
<th>Titel</th>
<th>Typ</th>
<th colspan="3">Adresse</th>
<th>DPT</th>
<th colspan="2">Wert</th>
</tr>
<tr *ngFor="let channel of channels">
<td>{{channel.title}}</td>
<td>{{channel.type}}</td>
<div class="tiles">
<div class="tile" *ngFor="let channel of channels">
<div>
{{ channel.title }}
</div>
<div class="left">
{{ channel.type }}
</div>
<ng-container *ngIf="channel.type === 'KnxGroup'">
<td class="first number">{{asKnxGroup(channel).addresMain}}&nbsp;/&nbsp;</td>
<td class="middle number">{{asKnxGroup(channel).addresMid}}&nbsp;/&nbsp;</td>
<td class="last number">{{asKnxGroup(channel).addresSub}}</td>
<td class="number">{{asKnxGroup(channel).dpt}}</td>
<div class="left">
{{ asKnxGroup(channel).addresMain }}&nbsp;/&nbsp;{{ asKnxGroup(channel).addresMid }}&nbsp;/&nbsp;{{ asKnxGroup(channel).addresSub }}
</div>
<div class="right">
DPT {{ asKnxGroup(channel).dpt }}
</div>
</ng-container>
<ng-container *ngIf="channel.type === 'Logic'">
<td colspan="4">{{asLogic(channel).operator}}</td>
</ng-container>
<td class="number">{{channel.value}}</td>
<td>{{channel.timestamp | date:'yyyy-MM-dd HH:mm:ss'}}</td>
</tr>
</table>
<div class="timestamp">
{{ channel.timestamp | date:'yyyy-MM-dd HH:mm:ss' || '-' }}
</div>
<div class="value">
{{ channel.value || '-' }}
</div>
</div>
</div>

View File

@ -1,3 +1,23 @@
table {
width: 100%;
@import "../../../../config";
div {
padding: @padding;
}
.left {
float: left;
}
.right {
float: right;
}
.timestamp {
clear: left;
float: left;
}
.value {
clear: right;
float: right;
}

View File

@ -2,7 +2,7 @@
<ng-container *ngFor="let device of devices; trackBy: Device.trackBy">
<div class="tile" *ngIf="device.type == 'DeviceSwitch'" [ngClass]="getSwitchClassList(device)">
<div class="tile" *ngIf="device.type == 'DeviceSwitch'" [ngClass]="device.getSwitchClassList()">
<div class="tileHead">
<div class="flexGrow">
<app-text [initial]="device.title" (valueChange)="set(device, 'title', $event)"></app-text>
@ -17,7 +17,7 @@
</div>
</div>
<div class="tile" *ngIf="device.type === 'DeviceStateScene'" [ngClass]="getStateSceneClassList(device)">
<div class="tile" *ngIf="device.type === 'DeviceStateScene'" [ngClass]="device.getStateSceneClassList()">
<div class="tileHead">
<div class="flexGrow">
<app-text [initial]="device.title" (valueChange)="set(device, 'title', $event)"></app-text>
@ -33,7 +33,7 @@
</div>
</div>
<div class="tile" *ngIf="device.type === 'DeviceShutter'" [ngClass]="getShutterClassList(device)">
<div class="tile" *ngIf="device.type === 'DeviceShutter'" [ngClass]="device.getShutterClassList()">
<div class="tileHead">
<div class="flexGrow">
<app-text [initial]="device.title" (valueChange)="set(device, 'title', $event)"></app-text>

View File

@ -1,7 +1,7 @@
import {Component, OnInit} from '@angular/core';
import {DeviceService} from "../../../api/device/device.service";
import {PropertyService} from "../../../api/property/property.service";
import {Device, DeviceShutter, DeviceStateScene, DeviceSwitch} from "../../../api/device/Device";
import {Device, DeviceStateScene} from "../../../api/device/Device";
import {faEdit} from '@fortawesome/free-regular-svg-icons';
import {Scene} from "../../../api/scene/Scene";
import {SceneService} from "../../../api/scene/scene.service";
@ -78,32 +78,9 @@ export class DeviceListComponent implements OnInit {
}
}
getSwitchClassList(device: Device): object {
const value: number | null | undefined = (device as DeviceSwitch).stateProperty?.readChannel?.value;
return {
deviceSwitchOnBack: value === 1,
deviceSwitchOffBack: value === 0,
disabledBack: value === null || value === undefined,
};
}
getStateSceneClassList(device: Device): object {
return this.getSwitchClassList(device);
}
getShutterClassList(device: Device): object {
const value: number | null | undefined = (device as DeviceShutter).positionProperty?.readChannel?.value;
return {
deviceShutterOpenBack: value === 0,
deviceShutterIntermediateBack: value !== null && value !== undefined && value > 0 && value < 100,
deviceShutterClosedBack: value === 100,
disabledBack: value === null || value === undefined,
};
}
getStateScenes(d: Device): Scene[] {
const device: DeviceStateScene = d as DeviceStateScene;
return device.sceneNumbers.map(sceneNumber => this.scenes.find(scene => scene.number === sceneNumber)).filter(scene => scene !== undefined).map(s => s as Scene);
getStateScenes(device: Device): Scene[] {
const casted: DeviceStateScene = device as DeviceStateScene;
return casted.sceneNumbers.map(sceneNumber => this.scenes.find(scene => scene.number === sceneNumber)).filter(scene => scene !== undefined).map(s => s as Scene);
}
set(device: Device, key: string, value: any): void {

View File

@ -2,49 +2,17 @@
<td class="empty">-</td>
</ng-template>
<table>
<tr>
<th>Bezeichnung</th>
<th>Slug</th>
<th>Typ</th>
<th>Wert</th>
<th>Zeitstempel</th>
<th>Lesekanal</th>
<th>Schreibkanal</th>
<th>
<fa-icon title="Löschen" [icon]="faTimes"></fa-icon>
</th>
</tr>
<ng-container *ngFor="let property of properties.sort(Property.compareTypeThenTitle)">
<tr>
<div class="tiles">
<td>
<div *ngFor="let list of listLists()">
<div class="tile" *ngFor="let property of list">
<div class="tileHead" [ngClass]="property.getStateClassList()">
<app-text [initial]="property.title" (valueChange)="edit(property, 'title', $event)"></app-text>
<div class="links" *ngIf="property.type === 'BOOLEAN'">
<div *ngIf="property.hrefId">{{property.hrefId}}0</div>
<div *ngIf="property.hrefId">{{property.hrefId}}1</div>
</div>
<div class="links" *ngIf="property.type === 'SHUTTER'">
<div *ngIf="property.hrefId">{{property.hrefId}}0</div>
<div *ngIf="property.hrefId">{{property.hrefId}}90</div>
<div *ngIf="property.hrefId">{{property.hrefId}}100</div>
</div>
</td>
<td>
<app-text [initial]="property.slug" (valueChange)="edit(property, 'slug', $event)"></app-text>
<div class="links" *ngIf="property.type === 'BOOLEAN'">
<div *ngIf="property.hrefSlug">{{property.hrefSlug}}0</div>
<div *ngIf="property.hrefSlug">{{property.hrefSlug}}1</div>
</div>
<div class="links" *ngIf="property.type === 'SHUTTER'">
<div *ngIf="property.hrefSlug">{{property.hrefSlug}}0</div>
<div *ngIf="property.hrefSlug">{{property.hrefSlug}}90</div>
<div *ngIf="property.hrefSlug">{{property.hrefSlug}}100</div>
</div>
</td>
<div class="tileBody">
<td>
<select [(ngModel)]="property.type" (ngModelChange)="edit(property, 'type', property.type)">
<option value="BOOLEAN">Schalter</option>
<option value="SHUTTER">Rollladen</option>
@ -53,47 +21,21 @@
<option value="LUX">Helligkeit [lux]</option>
<option value="SCENE">Szene</option>
</select>
</td>
<ng-container *ngIf="property.readChannel?.value !== null else empty">
<td *ngIf="property.type === 'BOOLEAN'" class="boolean" [class.true]="property.readChannel?.value" [class.false]="!property.readChannel?.value" (click)="edit(property, 'value', property.readChannel?.value > 0 ? 0 : 1)">
{{property.readChannel?.value ? "An" : "Aus"}}
</td>
<td *ngIf="property.type === 'SHUTTER'" class="number" [class.true]="property.readChannel?.value === 0" [class.false]="property.readChannel?.value === 100" [class.tristate]="0 < property.readChannel?.value && property.readChannel?.value < 100">
{{property.readChannel?.value}} %
</td>
<td *ngIf="property.type === 'BRIGHTNESS_PERCENT'" class="number">
{{property.readChannel?.value}} %
</td>
<td *ngIf="property.type === 'COLOR_TEMPERATURE'" class="number">
{{property.readChannel?.value}} K
</td>
<td *ngIf="property.type === 'LUX'" class="number">
{{property.readChannel?.value | number:'0.0-0'}} lux
</td>
<td *ngIf="property.type === 'SCENE'">
{{findScene(property)?.title || "Unbekannt: " + property.readChannel?.value}}
</td>
</ng-container>
<td *ngIf="property.readChannel?.timestamp !== null else empty">
{{property.readChannel?.timestamp | date:'yyyy-MM-dd HH:mm:ss'}}
</td>
<td class="full">
<app-search [searchService]="channelService" [initial]="property.readChannel?.id" (valueChange)="set(property, 'readChannel', $event)"></app-search>
</td>
<td class="full">
<app-search [searchService]="channelService" [initial]="property.writeChannel?.id" (valueChange)="set(property, 'writeChannel', $event)"></app-search>
</td>
<td class="delete">
<div class="delete">
<fa-icon title="Löschen" *ngIf="property.usages.length === 0" [icon]="faTimes" (click)="delete(property)"></fa-icon>
</td>
</div>
</tr>
</ng-container>
</table>
</div>
</div>
</div>
</div>
<div class="config">
<button (click)="create()">+ Hinzufügen</button>

View File

@ -1,8 +1,29 @@
table {
width: 100%;
@import "../../../../config";
.propertyStateBooleanUnknown {
background-color: @COLOR_UNKNOWN;
}
.links {
color: gray;
font-size: 80%;
.propertyStateBooleanTrue {
background-color: @COLOR_ACTIVE;
}
.propertyStateBooleanFalse {
background-color: @COLOR_INACTIVE;
}
.propertyStatePercentUnknown {
background-color: @COLOR_UNKNOWN;
}
.propertyStatePercentActive {
background-color: @COLOR_ACTIVE;
}
.propertyStatePercentBetween {
background-color: @COLOR_BETWEEN;
}
.propertyStatePercentInactive {
background-color: @COLOR_INACTIVE;
}

View File

@ -1,5 +1,5 @@
import {Component, OnInit} from '@angular/core';
import {Property} from "../../../api/property/Property";
import {Property, PropertyType} from "../../../api/property/Property";
import {PropertyService} from "../../../api/property/property.service";
import {Scene} from "../../../api/scene/Scene";
import {SceneService} from "../../../api/scene/scene.service";
@ -14,16 +14,18 @@ import {environment} from 'src/environments/environment';
})
export class PropertyListComponent implements OnInit {
readonly environment = environment;
readonly faTimes = faTimesCircle;
protected booleans: Property[] = [];
protected shutters: Property[] = [];
Property = Property;
properties: Property[] = [];
scenes: Scene[] = [];
readonly environment = environment;
constructor(
readonly propertyService: PropertyService,
readonly sceneService: SceneService,
@ -33,7 +35,10 @@ export class PropertyListComponent implements OnInit {
}
ngOnInit(): void {
this.propertyService.findAll(properties => this.properties = properties, Property.compareTypeThenTitle);
this.propertyService.findAll(properties => {
this.booleans = properties.filter(p => p.type === PropertyType.BOOLEAN).sort(Property.compareTypeThenTitle);
this.shutters = properties.filter(p => p.type === PropertyType.SHUTTER).sort(Property.compareTypeThenTitle);
}, Property.compareTypeThenTitle);
this.propertyService.subscribe(update => this.updateProperty(update.payload, update.existing));
this.sceneService.findAll(scenes => this.scenes = scenes, Scene.compareNumber);
@ -49,15 +54,23 @@ export class PropertyListComponent implements OnInit {
}
private updateProperty(property: Property, existing: boolean): void {
const index: number = this.properties.findIndex(p => p.id === property.id);
if (property.type === PropertyType.BOOLEAN) {
this.updateProperty2(this.booleans, property, existing);
} else if (property.type === PropertyType.SHUTTER) {
this.updateProperty2(this.shutters, property, existing);
}
}
private updateProperty2(properties: Property[], property: Property, existing: boolean) {
const index: number = properties.findIndex(p => p.id === property.id);
if (index >= 0) {
if (existing) {
this.properties[index] = property;
properties[index] = property;
} else {
this.properties.slice(index, 1);
properties.slice(index, 1);
}
} else if (existing) {
this.properties.push(property);
properties.push(property);
}
}
@ -88,8 +101,22 @@ export class PropertyListComponent implements OnInit {
delete(property: Property): void {
if (confirm(`Eigenschaft "${property.title}" wirklich löschen?`)) {
this.propertyService.delete(property, () => this.properties.splice(this.properties.findIndex(p => p.id === property.id), 1));
this.propertyService.delete(property, () => {
this.delete2(this.booleans, property);
this.delete2(this.shutters, property);
});
}
}
private delete2(properties: Property[], property: Property) {
const index = properties.findIndex(p => p.id === property.id);
if (index >= 0) {
properties.splice(index, 1);
}
}
listLists(): Property[][] {
return [this.shutters, this.booleans];
}
}

View File

@ -75,7 +75,7 @@
<div class="tileBodyFlex" *ngIf="entry.type === 'SUNRISE' || entry.type === 'SUNSET'">
<div class="flexGrow sun">
<div *ngFor="let zenith of getZenithEntries(entry.type); trackBy: trackByZenith">
<div *ngFor="let zenith of getZenithEntries(entry.type)">
<app-bool [label]="zenith.title" [value]="entry.zenith === zenith.value" (onChange)="entryService.set(entry, 'zenith', zenith.value)"></app-bool>
</div>
<div>

View File

@ -16,6 +16,18 @@ import {faCheckCircle, faCircle, faTimesCircle} from "@fortawesome/free-regular-
const DAY_MINUTES: number = 24 * 60;
const ZENITH_ENTRIES: Zenith[] = [
new Zenith("Astr.", 107, true, true),
new Zenith("Naut.", 102, true, true),
new Zenith("Bürg.", 96, true, true),
new Zenith("Aufg.", 90.8, true, false),
new Zenith("Unterg.", 90.8, false, true),
];
const ZENITH_SUNRISE = ZENITH_ENTRIES.filter(zenith => zenith.sunrise);
const ZENITH_SUNSET = ZENITH_ENTRIES.filter(zenith => zenith.sunset).reverse();
@Component({
selector: 'app-schedule-editor',
templateUrl: './schedule-editor.component.html',
@ -23,6 +35,12 @@ const DAY_MINUTES: number = 24 * 60;
})
export class ScheduleEditorComponent implements OnInit {
protected readonly faCheckCircle = faCheckCircle;
protected readonly faTimesCircle = faTimesCircle;
protected readonly faCircle = faCircle;
protected readonly ScheduleEntry = ScheduleEntry;
protected readonly Schedule = Schedule;
@ -39,14 +57,6 @@ export class ScheduleEditorComponent implements OnInit {
protected bulks: Bulk[] = [];
protected readonly ZENITH_ENTRIES: Zenith[] = [
new Zenith("Astr.", 107, true, true),
new Zenith("Naut.", 102, true, true),
new Zenith("Bürg.", 96, true, true),
new Zenith("Aufg.", 90.8, true, false),
new Zenith("Unterg.", 90.8, false, true),
];
constructor(
readonly router: Router,
readonly activatedRoute: ActivatedRoute,
@ -99,17 +109,6 @@ export class ScheduleEditorComponent implements OnInit {
}
}
getZenithEntries(type: string): Zenith[] {
if (type === 'SUNRISE') {
return this.ZENITH_ENTRIES.filter(zenith => zenith.sunrise);
}
return this.ZENITH_ENTRIES.reverse().filter(zenith => zenith.sunset);
}
trackByZenith(index: number, zenith: Zenith) {
return zenith.value;
}
timeFromString(entry: ScheduleEntry, time: string) {
const parts = time.split(':');
const hour = parseInt(parts[0]);
@ -119,7 +118,6 @@ export class ScheduleEditorComponent implements OnInit {
second = parseInt(parts[2]);
}
const daySecond = (hour * 24 + minute) * 60 + second;
console.log(hour, minute, second, daySecond);
this.entryService.set(entry, 'daySecond', daySecond);
}
@ -131,9 +129,11 @@ export class ScheduleEditorComponent implements OnInit {
this.entryService.set(entry, 'daySecond', newMinutes * 60);
}
protected readonly faCheckCircle = faCheckCircle;
protected readonly faCircle = faCircle;
protected readonly faTimesCircle = faTimesCircle;
getZenithEntries(type: string) {
if (type === 'SUNRISE') {
return ZENITH_SUNRISE;
}
return ZENITH_SUNSET;
}
}

View File

@ -7,9 +7,8 @@
<ng-container *ngIf="!selected">-</ng-container>
</div>
<div *ngIf="searching" class="resultList">
<input #input type="text" *ngIf="searching" [(ngModel)]="term" (ngModelChange)="changed()" (keydown.enter)="doSearch()" (keydown.escape)="cancelSearch()" (focus)="cancelOnBlur=true" (blur)="blur()">
<div #resultList *ngIf="searching" class="resultList">
<div *ngIf="allowEmpty" class="result" (mousedown)="dontCancelOnBlur()" (click)="select(undefined)">
-
</div>

View File

@ -1,6 +1,7 @@
@import "../../../config";
.all {
.initial {
padding: @padding;
height: 100%;
@ -12,7 +13,12 @@
}
.resultList {
position: absolute;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: lightgray;
min-width: 10em;
border: @border solid black;

View File

@ -7,7 +7,7 @@ import {ISearchService} from "../../api/ISearchService";
templateUrl: './search.component.html',
styleUrls: ['./search.component.less']
})
export class SearchComponent<T> implements OnInit {
export class SearchComponent implements OnInit {
private changedTimeout: number | undefined;
@ -19,9 +19,6 @@ export class SearchComponent<T> implements OnInit {
@ViewChild('input')
input?: HTMLInputElement;
@ViewChild('resultList')
resultList?: HTMLDivElement;
@Input()
searchService!: ISearchService;
@ -75,9 +72,6 @@ export class SearchComponent<T> implements OnInit {
start(): void {
this.term = this.selected?.title || "";
if (this.resultList && this.input) {
this.resultList.style.left = this.input.style.left;
}
this.searching = true;
setTimeout(() => this.input2?.nativeElement.focus(), 0);
this.doSearch();

View File

@ -3,12 +3,17 @@
@border: 0.05em;
@border-radius: 0.2em;
@COLOR_UNKNOWN: gray;
@COLOR_ACTIVE: #8fbc8f;
@COLOR_BETWEEN: #e4db9c;
@COLOR_INACTIVE: #bc8f8f;
.disabledBack {
background-color: gray;
background-color: @COLOR_UNKNOWN;
}
.enabledBack {
background-color: #8fbc8f;
background-color: @COLOR_ACTIVE;
}
.skipBack {
@ -28,21 +33,21 @@
}
.deviceSwitchOnBack {
background-color: #8fbc8f;
background-color: @COLOR_ACTIVE;
}
.deviceSwitchOffBack {
background-color: #bc8f8f;
background-color: @COLOR_INACTIVE;
}
.deviceShutterOpenBack {
background-color: #8fbc8f;
background-color: @COLOR_ACTIVE;
}
.deviceShutterIntermediateBack {
background-color: #e4db9c;
background-color: @COLOR_BETWEEN;
}
.deviceShutterClosedBack {
background-color: #bc8f8f;
background-color: @COLOR_INACTIVE;
}

View File

@ -13,8 +13,6 @@ public class Config {
private double longitude = 6.9645334;
private String timezone = "Europe/Berlin";
private boolean insertDemoData = false;
}

View File

@ -2,6 +2,7 @@ package de.ph87.homeautomation.channel;
import de.ph87.homeautomation.property.Property;
import de.ph87.homeautomation.shared.Helpers;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@ -29,12 +30,11 @@ public class ChannelReader {
return findByChannel(channel).orElseThrow(RuntimeException::new);
}
public Double read(final Property property) {
final Channel channel = property.getReadChannel();
if (channel == null) {
return null;
}
return getByChannel(channel).read(property.getReadChannel().getId());
@NonNull
public Optional<Double> read(@NonNull final Property property) {
return Optional.ofNullable(property.getReadChannel())
.map(this::getByChannel)
.map(owner -> owner.read(property.getReadChannel().getId()));
}
public ChannelDto toDtoAllowNull(final Channel channel) {

View File

@ -0,0 +1,20 @@
package de.ph87.homeautomation.knx.group;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("knx/group")
public class KnxGroupImportController {
private final KnxGroupImportService knxGroupImportService;
@GetMapping("import")
public void doImport() {
knxGroupImportService.importGroups();
}
}

View File

@ -1,5 +1,6 @@
package de.ph87.homeautomation.knx.group;
import de.ph87.homeautomation.property.PropertyReader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
@ -23,6 +24,8 @@ public class KnxGroupImportService {
private final KnxGroupRepository knxGroupRepository;
private final PropertyReader propertyReader;
public void importGroups() {
try {
execute("/usr/bin/git", "fetch", "--all");
@ -34,6 +37,18 @@ public class KnxGroupImportService {
knxGroupRepository.findAll().forEach(knxGroup -> knxGroup.setEts(false));
try {
Jsoup.parse(new File(ETS_HOME, "G"), "UTF-8").select("GA").forEach(this::importGroup);
knxGroupRepository.findAllByEtsFalse().forEach(group -> {
log.warn("Removing obsolete group: {}", group);
propertyReader.findAllByReadChannel_Id(group.getId()).forEach(property -> {
property.setReadChannel(null);
log.warn(" - removed group as Property readChannel: {}", property);
});
propertyReader.findAllByWriteChannel_Id(group.getId()).forEach(property -> {
property.setWriteChannel(null);
log.warn(" - removed group as Property writeChannel: {}", property);
});
knxGroupRepository.delete(group);
});
} catch (IOException e) {
log.error("Failed to import KnxGroups: {}", e.toString());
}
@ -73,7 +88,13 @@ public class KnxGroupImportService {
private void setDpt(final KnxGroup knxGroup, final String dptString) {
final Matcher mainSub = Pattern.compile("^DPST-(?<main>\\d+)-(?<sub>\\d+)$").matcher(dptString);
if (mainSub.matches()) {
knxGroup.setDptMain(Integer.parseInt(mainSub.group("main")));
final int main = Integer.parseInt(mainSub.group("main"));
if (knxGroup.getDptMain() != main) {
knxGroup.setLastTelegram(null);
knxGroup.setValue(null);
knxGroup.setTimestamp(null);
}
knxGroup.setDptMain(main);
knxGroup.setDptSub(Integer.parseInt(mainSub.group("sub")));
return;
}

View File

@ -4,10 +4,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tuwien.auto.calimero.GroupAddress;
import tuwien.auto.calimero.KNXException;
import tuwien.auto.calimero.KNXFormatException;
import tuwien.auto.calimero.KNXTimeoutException;
import tuwien.auto.calimero.*;
import tuwien.auto.calimero.datapoint.StateDP;
import tuwien.auto.calimero.dptxlator.TranslatorTypes;
import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
@ -74,6 +71,12 @@ public class KnxGroupLinkService {
knxGroup.getRead().setNextTimestamp(null);
log.debug("Successfully sent KnxGroup: {}", knxGroup);
return true;
} catch (KNXIllegalArgumentException e) {
log.error("Failed to read KnxGroup {}", knxGroup);
knxGroup.getRead().setErrorCount(knxGroup.getRead().getErrorCount() + 1);
knxGroup.getRead().setErrorMessage(e.getMessage());
knxGroup.getRead().setNextTimestamp(null);
return true;
} catch (KNXTimeoutException | KNXFormatException e) {
log.error("Failed to read KnxGroup {}", knxGroup);
knxGroup.getRead().setErrorCount(knxGroup.getRead().getErrorCount() + 1);

View File

@ -1,18 +1,16 @@
package de.ph87.homeautomation.knx.group;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.ListCrudRepository;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
public interface KnxGroupRepository extends CrudRepository<KnxGroup, Long>, JpaSpecificationExecutor<KnxGroup> {
public interface KnxGroupRepository extends ListCrudRepository<KnxGroup, Long>, JpaSpecificationExecutor<KnxGroup> {
Optional<KnxGroup> findByAddressRaw(int rawAddress);
List<KnxGroup> findAll();
Optional<KnxGroup> findFirstBySend_NextTimestampNotNullOrderBySend_NextTimestampAsc();
Optional<KnxGroup> findFirstByRead_NextTimestampLessThanEqualOrderByRead_NextTimestampAsc(ZonedDateTime timestamp);
@ -21,4 +19,6 @@ public interface KnxGroupRepository extends CrudRepository<KnxGroup, Long>, JpaS
List<KnxGroup> findAllByNameContainsIgnoreCaseOrAddressStrContainsIgnoreCase(String name, String addressStr);
List<KnxGroup> findAllByEtsFalse();
}

View File

@ -44,6 +44,11 @@ public class PropertyController implements ISearchController {
return propertyWriter.set(id, Property::setSlug, value == null || value.isEmpty() ? null : value);
}
@GetMapping("get/{id}/value")
public Double getValue(@PathVariable final long id) {
return channelReader.read(propertyReader.getById(id)).orElse(null);
}
@PostMapping("set/{id}/value")
public PropertyDto setValue(@PathVariable final long id, @RequestBody final double value) {
return propertyWriter.set(id, propertyWriter::writeToChannel, value);
@ -66,18 +71,10 @@ public class PropertyController implements ISearchController {
@PostMapping("toggle/{id}")
public PropertyDto setValue(@PathVariable final long id) {
final boolean oldState = getOldStateBoolean(id, false);
final boolean oldState = channelReader.read(propertyReader.getById(id)).map(v -> v > 0.0).orElse(false);
return propertyWriter.set(id, propertyWriter::writeToChannel, oldState ? 0.0 : 1.0);
}
private boolean getOldStateBoolean(final long id, final boolean orElse) {
final Double oldValue = channelReader.read(propertyReader.getById(id));
if (oldValue == null || oldValue.isNaN()) {
return orElse;
}
return oldValue > 0.0;
}
@Override
@GetMapping("searchById/{id}")
public SearchResult searchById(@PathVariable final long id) {

View File

@ -23,6 +23,10 @@ public class PropertyReader {
return propertyRepository.findAllByReadChannel_Id(readChannelId);
}
public List<Property> findAllByWriteChannel_Id(final long writeChannelId) {
return propertyRepository.findAllByWriteChannel_Id(writeChannelId);
}
public List<PropertyDto> search(final String term) {
return RepositorySearchHelper.search(term, propertyRepository, "title", propertyMapper::toDto);
}

View File

@ -12,7 +12,7 @@ public interface PropertyRepository extends JpaRepository<Property, Long>, JpaSp
List<Property> findAllByReadChannel_Id(long readChannelId);
List<Property> findAllByTitleLikeIgnoreCase(final String like);
List<Property> findAllByWriteChannel_Id(final long writeChannelId);
boolean existsByTitle(String title);

View File

@ -11,6 +11,8 @@ import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Comparator;
import java.util.Optional;
@ -55,12 +57,12 @@ public class ScheduleCalculator {
entry.setNextClearTimestamp(null);
return;
}
ZonedDateTime midnight = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
ZonedDateTime next = calculateEntryForDay(entry, midnight);
LocalDate day = now.toLocalDate();
ZonedDateTime next = calculateEntryForDay(entry, day);
while (next != null && (!next.isAfter(now) || !isAfterLast(entry, next) || !isWeekdayEnabled(entry, next))) {
log.debug(" -- skipping: next={}", next);
midnight = midnight.plusDays(1);
next = calculateEntryForDay(entry, midnight);
day = day.plusDays(1);
next = calculateEntryForDay(entry, day);
}
log.debug(" => {}", next);
entry.setNextClearTimestamp(next);
@ -70,14 +72,14 @@ public class ScheduleCalculator {
return entry.getLastClearTimestamp() == null || next.isAfter(entry.getLastClearTimestamp());
}
private ZonedDateTime calculateEntryForDay(final ScheduleEntry entry, final ZonedDateTime midnight) {
private ZonedDateTime calculateEntryForDay(final ScheduleEntry entry, final LocalDate day) {
switch (entry.getType()) {
case TIME:
return midnight.withHour(entry.getHour()).withMinute(entry.getMinute()).withSecond(entry.getSecond());
return day.atStartOfDay().atZone(ZoneId.systemDefault()).withHour(entry.getHour()).withMinute(entry.getMinute()).withSecond(entry.getSecond());
case SUNRISE:
case SUNSET:
final boolean sunrise = entry.getType() == ScheduleEntryType.SUNRISE;
return astroCalculator.forDay(midnight, sunrise, entry.getZenith());
return astroCalculator.forDay(day, sunrise, entry.getZenith()).withLaterOffsetAtOverlap();
default:
log.error("AstroEvent not implemented: {}", entry.getType());
break;

View File

@ -8,10 +8,12 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
@Service
@RequiredArgsConstructor
@ -19,25 +21,15 @@ public class AstroCalculator {
private final Config config;
public ZonedDateTime next(final ZonedDateTime now, final boolean sunrise, final double zenith) {
ZonedDateTime day = now.truncatedTo(ChronoUnit.DAYS);
ZonedDateTime next;
do {
next = forDay(day, sunrise, zenith);
day = day.plusDays(1);
} while (next != null && !next.isAfter(now));
return next;
}
public ZonedDateTime forDay(final ZonedDateTime midnight, final boolean sunrise, final double zenith) {
public ZonedDateTime forDay(final LocalDate day, final boolean sunrise, final double zenith) {
final Location location = new Location(config.getLatitude(), config.getLongitude());
final SolarEventCalculator calculator = new SolarEventCalculator(location, config.getTimezone());
final Calendar calendar = GregorianCalendar.from(midnight);
final SolarEventCalculator calculator = new SolarEventCalculator(location, TimeZone.getTimeZone("UTC"));
final Calendar calendar = GregorianCalendar.from(day.atStartOfDay(ZoneId.of("UTC")));
final Calendar nextCalendar = forDay(calculator, sunrise, new Zenith(zenith), calendar);
if (nextCalendar == null) {
return null;
}
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(nextCalendar.getTimeInMillis()), midnight.getZone());
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(nextCalendar.getTimeInMillis()), ZoneId.systemDefault());
}
private Calendar forDay(final SolarEventCalculator calculator, final boolean sunrise, final Zenith solarZenith, final Calendar calendar) {

View File

@ -92,14 +92,16 @@ public class ScheduleEntry {
public void setNextClearTimestamp(final ZonedDateTime next) {
nextClearTimestamp = next;
if (nextClearTimestamp == null) {
nextFuzzyTimestamp = null;
} else {
if (nextClearTimestamp != null) {
final int rangeFull = 2 * fuzzySeconds;
final ZonedDateTime min = ZonedDateTime.now().plusMinutes(1);
while (nextFuzzyTimestamp == null || nextFuzzyTimestamp.isBefore(min)) {
final int fuzzySeconds = rangeFull > 0 ? RANDOM.nextInt(rangeFull) - this.fuzzySeconds : 0;
nextFuzzyTimestamp = nextClearTimestamp.plusSeconds(fuzzySeconds);
}
}
}
@Override
public String toString() {

View File

@ -2,12 +2,10 @@ package de.ph87.homeautomation.web;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@CrossOrigin
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

View File

@ -0,0 +1,70 @@
package de.ph87.homeautomation.schedule;
import de.ph87.homeautomation.Config;
import de.ph87.homeautomation.schedule.astro.AstroCalculator;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Slf4j
class ScheduleCalculatorDaylightSavingTimeTransitionTest {
private static final ZonedDateTime DAY_OF_DST_SET_BACK = ZonedDateTime.of(2024, 10, 27, 0, 0, 0, 0, ZoneId.of("Europe/Berlin"));
private static final AstroCalculator astroCalculator = new AstroCalculator(new Config());
@Test
void withHour() {
final ZonedDateTime morning = DAY_OF_DST_SET_BACK.withHour(6);
assertEquals(6, morning.getHour());
assertEquals(0, morning.getMinute());
assertEquals(0, morning.getSecond());
assertEquals(0, morning.getNano());
assertEquals(3600, morning.getOffset().getTotalSeconds());
}
@Test
void sunrise_dstSetBack() {
final ZonedDateTime morning = astroCalculator.forDay(DAY_OF_DST_SET_BACK.toLocalDate(), true, 90);
assertEquals(7, morning.getHour());
assertEquals(19, morning.getMinute());
assertEquals(0, morning.getSecond());
assertEquals(0, morning.getNano());
assertEquals(3600, morning.getOffset().getTotalSeconds());
}
@Test
void sunset_dstSetBack() {
final ZonedDateTime morning = astroCalculator.forDay(DAY_OF_DST_SET_BACK.toLocalDate(), false, 90);
assertEquals(17, morning.getHour());
assertEquals(13, morning.getMinute());
assertEquals(0, morning.getSecond());
assertEquals(0, morning.getNano());
assertEquals(3600, morning.getOffset().getTotalSeconds());
}
@Test
void sunrise_noDstChange() {
final ZonedDateTime morning = astroCalculator.forDay(DAY_OF_DST_SET_BACK.minusDays(1).toLocalDate(), true, 90);
assertEquals(8, morning.getHour());
assertEquals(17, morning.getMinute());
assertEquals(0, morning.getSecond());
assertEquals(0, morning.getNano());
assertEquals(7200, morning.getOffset().getTotalSeconds());
}
@Test
void sunset_noDstChange() {
final ZonedDateTime morning = astroCalculator.forDay(DAY_OF_DST_SET_BACK.minusDays(1).toLocalDate(), false, 90);
assertEquals(18, morning.getHour());
assertEquals(14, morning.getMinute());
assertEquals(0, morning.getSecond());
assertEquals(0, morning.getNano());
assertEquals(7200, morning.getOffset().getTotalSeconds());
}
}