]> git.basschouten.com Git - openhab-addons.git/blob
008cecf55a5d9e62d8a84a5c4840a0709661084b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.windcentrale.internal;
14
15 import static org.openhab.binding.windcentrale.internal.WindcentraleBindingConstants.*;
16
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Objects;
21 import java.util.Set;
22 import java.util.concurrent.Future;
23 import java.util.stream.Collectors;
24
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;
45
46 /**
47  * The {@link WindcentraleDiscoveryService} discovers windmills using the participations in projects provided by the
48  * Windcentrale API.
49  *
50  * @author Wouter Born - Initial contribution
51  */
52 @NonNullByDefault
53 public class WindcentraleDiscoveryService extends AbstractDiscoveryService
54         implements ThingHandlerService, ThingStatusListener {
55
56     private final Logger logger = LoggerFactory.getLogger(WindcentraleDiscoveryService.class);
57     private @NonNullByDefault({}) WindcentraleAccountHandler accountHandler;
58     private @Nullable Future<?> discoveryJob;
59
60     public WindcentraleDiscoveryService() {
61         super(Set.of(THING_TYPE_WINDMILL), 10, false);
62     }
63
64     protected void activate(ComponentContext context) {
65     }
66
67     @Override
68     public void deactivate() {
69         cancelDiscoveryJob();
70         super.deactivate();
71         accountHandler.removeThingStatusListener(this);
72     }
73
74     @Override
75     public @Nullable ThingHandler getThingHandler() {
76         return accountHandler;
77     }
78
79     @Override
80     public void setThingHandler(ThingHandler handler) {
81         if (handler instanceof WindcentraleAccountHandler accountHandler) {
82             accountHandler.addThingStatusListener(this);
83             this.accountHandler = accountHandler;
84         }
85     }
86
87     @Override
88     protected void startScan() {
89         logger.debug("Discover windmills (manual discovery)");
90         cancelDiscoveryJob();
91         discoveryJob = scheduler.submit(this::discoverWindmills);
92     }
93
94     @Override
95     protected synchronized void stopScan() {
96         cancelDiscoveryJob();
97         super.stopScan();
98     }
99
100     @Override
101     public void thingStatusChanged(Thing thing, ThingStatus status) {
102         if (ThingStatus.ONLINE.equals(status)) {
103             logger.debug("Discover windmills (account online)");
104             discoverWindmills();
105         }
106     }
107
108     private void cancelDiscoveryJob() {
109         Future<?> localDiscoveryJob = discoveryJob;
110         if (localDiscoveryJob != null) {
111             localDiscoveryJob.cancel(true);
112         }
113     }
114
115     private void discoverWindmills() {
116         ThingUID bridgeUID = accountHandler.getThing().getUID();
117         WindcentraleAPI api = accountHandler.getAPI();
118
119         if (api == null) {
120             logger.debug("Cannot discover windmills because API is null for {}", bridgeUID);
121             return;
122         }
123
124         logger.debug("Starting discovery scan for {}", bridgeUID);
125         try {
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);
131         }
132         logger.debug("Finished discovery scan for {}", bridgeUID);
133     }
134
135     private Map<Windmill, Integer> calculateWindmillShares(List<Project> projects) {
136         Map<Windmill, Integer> windmillShares = new HashMap<>();
137
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);
145             } else {
146                 logger.debug("Unsupported project code: {}", project.projectCode);
147             }
148         }
149
150         return windmillShares;
151     }
152
153     private void addWindmillDiscoveryResult(ThingUID bridgeUID, Windmill windmill, int shares) {
154         String deviceId = windmill.getName().toLowerCase().replace(" ", "-");
155         ThingUID thingUID = new ThingUID(THING_TYPE_WINDMILL, bridgeUID, deviceId);
156
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) //
165                 .build() //
166         );
167     }
168 }