]> git.basschouten.com Git - openhab-addons.git/blob
960496e9e59aeced5880dc1bca69d30fcef1eab4
[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.ojelectronics.internal.services;
14
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.concurrent.TimeUnit;
18 import java.util.function.Consumer;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.eclipse.jetty.client.HttpClient;
23 import org.eclipse.jetty.client.api.Request;
24 import org.eclipse.jetty.client.api.Result;
25 import org.eclipse.jetty.client.util.BufferingResponseListener;
26 import org.eclipse.jetty.client.util.StringContentProvider;
27 import org.eclipse.jetty.http.HttpHeader;
28 import org.openhab.binding.ojelectronics.internal.ThermostatHandler;
29 import org.openhab.binding.ojelectronics.internal.common.OJGSonBuilder;
30 import org.openhab.binding.ojelectronics.internal.config.OJElectronicsBridgeConfiguration;
31 import org.openhab.binding.ojelectronics.internal.models.SimpleResponseModel;
32 import org.openhab.binding.ojelectronics.internal.models.thermostat.ThermostatModel;
33 import org.openhab.binding.ojelectronics.internal.models.thermostat.UpdateThermostatRequestModel;
34 import org.openhab.core.thing.Thing;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import com.google.gson.Gson;
39
40 /**
41  * Handles the update of the devices of a session
42  *
43  * @author Christian Kittel - Initial Contribution
44  */
45 @NonNullByDefault
46 public final class UpdateService {
47     private static final int REQUEST_TIMEOUT_MS = 10_000;
48     private final Gson gson = OJGSonBuilder.getGSon();
49     private final Logger logger = LoggerFactory.getLogger(UpdateService.class);
50
51     private final HttpClient httpClient;
52     private final OJElectronicsBridgeConfiguration configuration;
53     private final Runnable unauthorized;
54     private final Consumer<@Nullable String> connectionLost;
55
56     public UpdateService(OJElectronicsBridgeConfiguration configuration, HttpClient httpClient,
57             Consumer<@Nullable String> connectionLost, Runnable unauthorized) {
58         this.configuration = configuration;
59         this.httpClient = httpClient;
60         this.unauthorized = unauthorized;
61         this.connectionLost = connectionLost;
62     }
63
64     /**
65      * Sends all changes of all {@link ThermostatHandler} to the API
66      *
67      * @param things
68      */
69     public void updateAllThermostats(List<Thing> things) {
70         new SignInService(configuration, httpClient).signIn((sessionId) -> updateAllThermostats(things, sessionId),
71                 connectionLost, unauthorized);
72     }
73
74     private void updateAllThermostats(List<Thing> things, String sessionId) {
75         things.stream().filter(thing -> thing.getHandler() instanceof ThermostatHandler)
76                 .map(thing -> (ThermostatHandler) thing.getHandler())
77                 .map(handler -> handler.tryHandleAndGetUpdatedThermostat())
78                 .forEach((thermostat) -> updateThermostat(thermostat, sessionId));
79     }
80
81     private void updateThermostat(@Nullable ThermostatModel thermostat, String sessionId) {
82         if (thermostat == null) {
83             return;
84         }
85         String jsonPayload = gson.toJson(new UpdateThermostatRequestModel(thermostat).withApiKey(configuration.apiKey));
86         Request request = httpClient.POST(configuration.getRestApiUrl() + "/Thermostat/UpdateThermostat")
87                 .timeout(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS).param("sessionid", sessionId)
88                 .header(HttpHeader.CONTENT_TYPE, "application/json").content(new StringContentProvider(jsonPayload));
89         logger.trace("updateThermostat payload for themostat with serial {} is {}", thermostat.serialNumber,
90                 jsonPayload);
91
92         request.send(new BufferingResponseListener() {
93             @Override
94             public void onComplete(@Nullable Result result) {
95                 if (result != null) {
96                     logger.trace("onComplete Http Status {} {}", result.getResponse().getStatus(), result);
97                     if (result.isFailed()) {
98                         logger.warn("updateThermostat failed for themostat with serial {}", thermostat.serialNumber);
99                         return;
100                     }
101                     SimpleResponseModel responseModel = Objects
102                             .requireNonNull(gson.fromJson(getContentAsString(), SimpleResponseModel.class));
103                     if (responseModel.errorCode != 0) {
104                         logger.warn("updateThermostat failed with errorCode {} for thermostat with serial {}",
105                                 responseModel.errorCode, thermostat.serialNumber);
106                     }
107                 }
108             }
109         });
110     }
111 }