2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.windcentrale.internal;
15 import static org.openhab.binding.windcentrale.internal.WindcentraleBindingConstants.*;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.Objects;
22 import java.util.concurrent.Future;
23 import java.util.stream.Collectors;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.windcentrale.internal.api.WindcentraleAPI;
28 import org.openhab.binding.windcentrale.internal.dto.Project;
29 import org.openhab.binding.windcentrale.internal.dto.Windmill;
30 import org.openhab.binding.windcentrale.internal.exception.FailedGettingDataException;
31 import org.openhab.binding.windcentrale.internal.exception.InvalidAccessTokenException;
32 import org.openhab.binding.windcentrale.internal.handler.WindcentraleAccountHandler;
33 import org.openhab.binding.windcentrale.internal.handler.WindcentraleWindmillHandler;
34 import org.openhab.binding.windcentrale.internal.listener.ThingStatusListener;
35 import org.openhab.core.config.discovery.AbstractDiscoveryService;
36 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingStatus;
39 import org.openhab.core.thing.ThingUID;
40 import org.openhab.core.thing.binding.ThingHandler;
41 import org.openhab.core.thing.binding.ThingHandlerService;
42 import org.osgi.service.component.ComponentContext;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * The {@link WindcentraleDiscoveryService} discovers windmills using the participations in projects provided by the
50 * @author Wouter Born - Initial contribution
53 public class WindcentraleDiscoveryService extends AbstractDiscoveryService
54 implements ThingHandlerService, ThingStatusListener {
56 private final Logger logger = LoggerFactory.getLogger(WindcentraleDiscoveryService.class);
57 private @NonNullByDefault({}) WindcentraleAccountHandler accountHandler;
58 private @Nullable Future<?> discoveryJob;
60 public WindcentraleDiscoveryService() {
61 super(Set.of(THING_TYPE_WINDMILL), 10, false);
64 protected void activate(ComponentContext context) {
68 public void deactivate() {
71 accountHandler.removeThingStatusListener(this);
75 public @Nullable ThingHandler getThingHandler() {
76 return accountHandler;
80 public void setThingHandler(ThingHandler handler) {
81 if (handler instanceof WindcentraleAccountHandler accountHandler) {
82 accountHandler.addThingStatusListener(this);
83 this.accountHandler = accountHandler;
88 protected void startScan() {
89 logger.debug("Discover windmills (manual discovery)");
91 discoveryJob = scheduler.submit(this::discoverWindmills);
95 protected synchronized void stopScan() {
101 public void thingStatusChanged(Thing thing, ThingStatus status) {
102 if (ThingStatus.ONLINE.equals(status)) {
103 logger.debug("Discover windmills (account online)");
108 private void cancelDiscoveryJob() {
109 Future<?> localDiscoveryJob = discoveryJob;
110 if (localDiscoveryJob != null) {
111 localDiscoveryJob.cancel(true);
115 private void discoverWindmills() {
116 ThingUID bridgeUID = accountHandler.getThing().getUID();
117 WindcentraleAPI api = accountHandler.getAPI();
120 logger.debug("Cannot discover windmills because API is null for {}", bridgeUID);
124 logger.debug("Starting discovery scan for {}", bridgeUID);
126 calculateWindmillShares(api.getProjects()).entrySet()
127 .forEach(windmillShares -> addWindmillDiscoveryResult(bridgeUID, windmillShares.getKey(),
128 windmillShares.getValue()));
129 } catch (FailedGettingDataException | InvalidAccessTokenException e) {
130 logger.debug("Exception during discovery scan for {}", bridgeUID, e);
132 logger.debug("Finished discovery scan for {}", bridgeUID);
135 private Map<Windmill, Integer> calculateWindmillShares(List<Project> projects) {
136 Map<Windmill, Integer> windmillShares = new HashMap<>();
138 for (Project project : projects) {
139 Windmill windmill = Windmill.fromProjectCode(project.projectCode);
140 if (windmill != null) {
141 int shares = Objects.requireNonNullElse(windmillShares.get(windmill), 0);
142 shares += project.participations.stream()
143 .collect(Collectors.summingInt(participation -> participation.share));
144 windmillShares.put(windmill, shares);
146 logger.debug("Unsupported project code: {}", project.projectCode);
150 return windmillShares;
153 private void addWindmillDiscoveryResult(ThingUID bridgeUID, Windmill windmill, int shares) {
154 String deviceId = windmill.getName().toLowerCase().replaceAll(" ", "-");
155 ThingUID thingUID = new ThingUID(THING_TYPE_WINDMILL, bridgeUID, deviceId);
157 thingDiscovered(DiscoveryResultBuilder.create(thingUID) //
158 .withThingType(THING_TYPE_WINDMILL) //
159 .withLabel(windmill.getName()) //
160 .withBridge(bridgeUID) //
161 .withProperty(PROPERTY_NAME, windmill.getName()) //
162 .withProperty(PROPERTY_SHARES, shares) //
163 .withProperties(new HashMap<>(WindcentraleWindmillHandler.getWindmillProperties(windmill))) //
164 .withRepresentationProperty(PROPERTY_PROJECT_CODE) //