54 lines
1.7 KiB
Java
54 lines
1.7 KiB
Java
package de.ph87.homeautomation.channel;
|
|
|
|
import de.ph87.homeautomation.property.Property;
|
|
import de.ph87.homeautomation.property.PropertyReadService;
|
|
import lombok.RequiredArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.boot.context.event.ApplicationStartedEvent;
|
|
import org.springframework.context.event.EventListener;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
import java.util.List;
|
|
import java.util.Optional;
|
|
|
|
@Slf4j
|
|
@Service
|
|
@Transactional
|
|
@RequiredArgsConstructor
|
|
public class ChannelService {
|
|
|
|
private final List<IChannelOwner> channelOwners;
|
|
|
|
private final PropertyReadService propertyReadService;
|
|
|
|
@EventListener(ApplicationStartedEvent.class)
|
|
public void readAllPropertyChannels() {
|
|
propertyReadService.findAllByReadChannelNotNull().forEach(property -> {
|
|
final Optional<IChannelOwner> ownerOptional = findByChannel(property.getReadChannel());
|
|
if (ownerOptional.isPresent()) {
|
|
ownerOptional.get().read(property.getReadChannel());
|
|
} else {
|
|
log.error("No Owner for Property: {}", property);
|
|
}
|
|
});
|
|
}
|
|
|
|
public Optional<IChannelOwner> findByChannel(final Channel channel) {
|
|
return channelOwners.stream().filter(owner -> channel.getChannelOwnerClass().isInstance(owner)).findFirst();
|
|
}
|
|
|
|
public IChannelOwner getByChannel(final Channel channel) {
|
|
return findByChannel(channel).orElseThrow(RuntimeException::new);
|
|
}
|
|
|
|
public void write(final Property property, final double value) {
|
|
final Channel channel = property.getWriteChannel();
|
|
if (channel == null) {
|
|
return;
|
|
}
|
|
getByChannel(channel).write(property.getWriteChannel(), value);
|
|
}
|
|
|
|
}
|