]> git.basschouten.com Git - openhab-addons.git/blob
77c82cc66f8fddca780ac32cd51ce48bea0fbee0
[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.netatmo.internal.handler.capability;
14
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Optional;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.binding.netatmo.internal.api.RestManager;
21 import org.openhab.binding.netatmo.internal.api.dto.Device;
22 import org.openhab.binding.netatmo.internal.api.dto.Module;
23 import org.openhab.binding.netatmo.internal.api.dto.NAObject;
24 import org.openhab.binding.netatmo.internal.deserialization.NAObjectMap;
25 import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler;
26 import org.openhab.binding.netatmo.internal.handler.CommonInterface;
27
28 /**
29  * The {@link RestCapability} is the base class for handler capabilities
30  *
31  * @author GaĆ«l L'hopital - Initial contribution
32  *
33  */
34 @NonNullByDefault
35 public abstract class RestCapability<T extends RestManager> extends DeviceCapability {
36     private Optional<T> api = Optional.empty();
37     private Class<T> restManagerClass;
38
39     RestCapability(CommonInterface handler, Class<T> restManagerClazz) {
40         super(handler);
41         this.restManagerClass = restManagerClazz;
42     }
43
44     @Override
45     protected void updateNADevice(Device newData) {
46         super.updateNADevice(newData);
47         NAObjectMap<Module> modules = newData.getModules();
48         handler.getActiveChildren().forEach(child -> {
49             Module childData = modules.get(child.getId());
50             if (childData != null) {
51                 child.setNewData(childData);
52             }
53         });
54     }
55
56     @Override
57     public final List<NAObject> updateReadings() {
58         List<NAObject> result = new ArrayList<>();
59         getApi().ifPresent(api -> result.addAll(updateReadings(api)));
60         return result;
61     }
62
63     protected List<NAObject> updateReadings(T api) {
64         return List.of();
65     }
66
67     protected Optional<T> getApi() {
68         if (api.isEmpty()) {
69             ApiBridgeHandler bridgeApi = handler.getAccountHandler();
70             if (bridgeApi != null) {
71                 api = Optional.ofNullable(bridgeApi.getRestManager(restManagerClass));
72             }
73         }
74         return api;
75     }
76 }