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