]> git.basschouten.com Git - openhab-addons.git/blob
0c78e75cd323057c332c30b7e5ae6148f3e61cbd
[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.core.config.discovery.AbstractDiscoveryService;
35 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
36 import org.openhab.core.thing.ThingUID;
37 import org.openhab.core.thing.binding.ThingHandler;
38 import org.openhab.core.thing.binding.ThingHandlerService;
39 import org.osgi.service.component.ComponentContext;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * The {@link WindcentraleDiscoveryService} discovers windmills using the participations in projects provided by the
45  * Windcentrale API.
46  *
47  * @author Wouter Born - Initial contribution
48  */
49 @NonNullByDefault
50 public class WindcentraleDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
51
52     private final Logger logger = LoggerFactory.getLogger(WindcentraleDiscoveryService.class);
53     private @NonNullByDefault({}) WindcentraleAccountHandler accountHandler;
54     private @Nullable Future<?> discoveryJob;
55
56     public WindcentraleDiscoveryService() {
57         super(Set.of(THING_TYPE_WINDMILL), 10, false);
58     }
59
60     protected void activate(ComponentContext context) {
61     }
62
63     @Override
64     public void deactivate() {
65         cancelDiscoveryJob();
66         super.deactivate();
67     }
68
69     @Override
70     public @Nullable ThingHandler getThingHandler() {
71         return accountHandler;
72     }
73
74     @Override
75     public void setThingHandler(ThingHandler handler) {
76         if (handler instanceof WindcentraleAccountHandler accountHandler) {
77             this.accountHandler = accountHandler;
78         }
79     }
80
81     @Override
82     protected void startScan() {
83         cancelDiscoveryJob();
84         discoveryJob = scheduler.submit(this::discoverWindmills);
85     }
86
87     @Override
88     protected synchronized void stopScan() {
89         cancelDiscoveryJob();
90         super.stopScan();
91     }
92
93     private void cancelDiscoveryJob() {
94         Future<?> localDiscoveryJob = discoveryJob;
95         if (localDiscoveryJob != null) {
96             localDiscoveryJob.cancel(true);
97         }
98     }
99
100     private void discoverWindmills() {
101         ThingUID bridgeUID = accountHandler.getThing().getUID();
102         WindcentraleAPI api = accountHandler.getAPI();
103
104         if (api == null) {
105             logger.debug("Cannot discover windmills because API is null for {}", bridgeUID);
106             return;
107         }
108
109         logger.debug("Starting discovery scan for {}", bridgeUID);
110         try {
111             calculateWindmillShares(api.getProjects()).entrySet()
112                     .forEach(windmillShares -> addWindmillDiscoveryResult(bridgeUID, windmillShares.getKey(),
113                             windmillShares.getValue()));
114         } catch (FailedGettingDataException | InvalidAccessTokenException e) {
115             logger.debug("Exception during discovery scan for {}", bridgeUID, e);
116         }
117         logger.debug("Finished discovery scan for {}", bridgeUID);
118     }
119
120     private Map<Windmill, Integer> calculateWindmillShares(List<Project> projects) {
121         Map<Windmill, Integer> windmillShares = new HashMap<>();
122
123         for (Project project : projects) {
124             Windmill windmill = Windmill.fromProjectCode(project.projectCode);
125             if (windmill != null) {
126                 int shares = Objects.requireNonNullElse(windmillShares.get(windmill), 0);
127                 shares += project.participations.stream()
128                         .collect(Collectors.summingInt(participation -> participation.share));
129                 windmillShares.put(windmill, shares);
130             } else {
131                 logger.debug("Unsupported project code: {}", project.projectCode);
132             }
133         }
134
135         return windmillShares;
136     }
137
138     private void addWindmillDiscoveryResult(ThingUID bridgeUID, Windmill windmill, int shares) {
139         String deviceId = windmill.getName().toLowerCase().replaceAll(" ", "-");
140         ThingUID thingUID = new ThingUID(THING_TYPE_WINDMILL, bridgeUID, deviceId);
141
142         thingDiscovered(DiscoveryResultBuilder.create(thingUID) //
143                 .withThingType(THING_TYPE_WINDMILL) //
144                 .withLabel(windmill.getName()) //
145                 .withBridge(bridgeUID) //
146                 .withProperty(PROPERTY_NAME, windmill.getName()) //
147                 .withProperty(PROPERTY_SHARES, shares) //
148                 .withProperties(new HashMap<>(WindcentraleWindmillHandler.getWindmillProperties(windmill))) //
149                 .withRepresentationProperty(PROPERTY_PROJECT_CODE) //
150                 .build() //
151         );
152     }
153 }