]> git.basschouten.com Git - openhab-addons.git/blob
dfb912396fe0ddb9d6e7685682f2badbc5f7ad9b
[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.millheat.internal.handler;
14
15 import java.nio.charset.StandardCharsets;
16 import java.security.MessageDigest;
17 import java.security.NoSuchAlgorithmException;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.eclipse.jetty.client.HttpClient;
28 import org.eclipse.jetty.client.api.ContentResponse;
29 import org.eclipse.jetty.client.api.Request;
30 import org.eclipse.jetty.client.util.BytesContentProvider;
31 import org.eclipse.jetty.http.HttpMethod;
32 import org.eclipse.jetty.http.HttpStatus;
33 import org.openhab.binding.millheat.internal.MillheatCommunicationException;
34 import org.openhab.binding.millheat.internal.client.BooleanSerializer;
35 import org.openhab.binding.millheat.internal.client.RequestLogger;
36 import org.openhab.binding.millheat.internal.config.MillheatAccountConfiguration;
37 import org.openhab.binding.millheat.internal.dto.AbstractRequest;
38 import org.openhab.binding.millheat.internal.dto.AbstractResponse;
39 import org.openhab.binding.millheat.internal.dto.DeviceDTO;
40 import org.openhab.binding.millheat.internal.dto.GetHomesRequest;
41 import org.openhab.binding.millheat.internal.dto.GetHomesResponse;
42 import org.openhab.binding.millheat.internal.dto.GetIndependentDevicesByHomeRequest;
43 import org.openhab.binding.millheat.internal.dto.GetIndependentDevicesByHomeResponse;
44 import org.openhab.binding.millheat.internal.dto.HomeDTO;
45 import org.openhab.binding.millheat.internal.dto.LoginRequest;
46 import org.openhab.binding.millheat.internal.dto.LoginResponse;
47 import org.openhab.binding.millheat.internal.dto.RoomDTO;
48 import org.openhab.binding.millheat.internal.dto.SelectDeviceByRoomRequest;
49 import org.openhab.binding.millheat.internal.dto.SelectDeviceByRoomResponse;
50 import org.openhab.binding.millheat.internal.dto.SelectRoomByHomeRequest;
51 import org.openhab.binding.millheat.internal.dto.SelectRoomByHomeResponse;
52 import org.openhab.binding.millheat.internal.dto.SetDeviceTempRequest;
53 import org.openhab.binding.millheat.internal.dto.SetHolidayParameterRequest;
54 import org.openhab.binding.millheat.internal.dto.SetHolidayParameterResponse;
55 import org.openhab.binding.millheat.internal.dto.SetRoomTempRequest;
56 import org.openhab.binding.millheat.internal.dto.SetRoomTempResponse;
57 import org.openhab.binding.millheat.internal.model.Heater;
58 import org.openhab.binding.millheat.internal.model.Home;
59 import org.openhab.binding.millheat.internal.model.MillheatModel;
60 import org.openhab.binding.millheat.internal.model.ModeType;
61 import org.openhab.binding.millheat.internal.model.Room;
62 import org.openhab.core.library.types.DateTimeType;
63 import org.openhab.core.library.types.OnOffType;
64 import org.openhab.core.library.types.QuantityType;
65 import org.openhab.core.thing.Bridge;
66 import org.openhab.core.thing.ChannelUID;
67 import org.openhab.core.thing.Thing;
68 import org.openhab.core.thing.ThingStatus;
69 import org.openhab.core.thing.ThingStatusDetail;
70 import org.openhab.core.thing.binding.BaseBridgeHandler;
71 import org.openhab.core.thing.binding.ThingHandler;
72 import org.openhab.core.types.Command;
73 import org.openhab.core.util.HexUtils;
74 import org.openhab.core.util.StringUtils;
75 import org.osgi.framework.BundleContext;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 import com.google.gson.Gson;
80 import com.google.gson.GsonBuilder;
81
82 /**
83  * The {@link MillheatAccountHandler} is responsible for handling commands, which are
84  * sent to one of the channels.
85  *
86  * @author Arne Seime - Initial contribution
87  */
88 @NonNullByDefault
89 public class MillheatAccountHandler extends BaseBridgeHandler {
90     private static final String SHA_1_ALGORITHM = "SHA-1";
91     private static final int MIN_TIME_BETWEEEN_MODEL_UPDATES_MS = 30_000;
92     private static final int NUM_NONCE_CHARS = 16;
93     private static final String CONTENT_TYPE = "application/x-zc-object";
94     private static final String ALLOWED_NONCE_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
95     private static final String REQUEST_TIMEOUT = "300";
96     public static String authEndpoint = "https://eurouter.ablecloud.cn:9005/zc-account/v1/";
97     public static String serviceEndpoint = "https://eurouter.ablecloud.cn:9005/millService/v1/";
98     private final Logger logger = LoggerFactory.getLogger(MillheatAccountHandler.class);
99     private @Nullable String userId;
100     private @Nullable String token;
101     private final HttpClient httpClient;
102     private final RequestLogger requestLogger;
103     private final Gson gson;
104     private MillheatModel model = new MillheatModel(0);
105     private @Nullable ScheduledFuture<?> statusFuture;
106     private @NonNullByDefault({}) MillheatAccountConfiguration config;
107
108     public MillheatAccountHandler(final Bridge bridge, final HttpClient httpClient, final BundleContext context) {
109         super(bridge);
110         this.httpClient = httpClient;
111         final BooleanSerializer serializer = new BooleanSerializer();
112
113         gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd HH:mm:ss")
114                 .registerTypeAdapter(Boolean.class, serializer).registerTypeAdapter(boolean.class, serializer)
115                 .setLenient().create();
116         requestLogger = new RequestLogger(bridge.getUID().getId(), gson);
117     }
118
119     private boolean allowModelUpdate() {
120         final long timeSinceLastUpdate = System.currentTimeMillis() - model.getLastUpdated();
121         return timeSinceLastUpdate > MIN_TIME_BETWEEEN_MODEL_UPDATES_MS;
122     }
123
124     public MillheatModel getModel() {
125         return model;
126     }
127
128     @Override
129     public void handleCommand(final ChannelUID channelUID, final Command command) {
130         logger.debug("Bridge does not support any commands, but received command {} for channelUID {}", command,
131                 channelUID);
132     }
133
134     public boolean doLogin() {
135         try {
136             final LoginResponse rsp = sendLoginRequest(new LoginRequest(config.username, config.password),
137                     LoginResponse.class);
138             final int errorCode = rsp.errorCode;
139             if (errorCode != 0) {
140                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
141                         String.format("Error login in: code=%s, type=%s, message=%s", errorCode, rsp.errorName,
142                                 rsp.errorDescription));
143             } else {
144                 // No error provided on login, proceed to find token and userid
145                 String localToken = rsp.token.trim();
146                 userId = rsp.userId == null ? null : rsp.userId.toString();
147                 if (localToken == null || localToken.isEmpty()) {
148                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
149                             "error login in, no token provided");
150                 } else if (userId == null) {
151                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
152                             "error login in, no userId provided");
153                 } else {
154                     token = localToken;
155                     return true;
156                 }
157             }
158         } catch (final MillheatCommunicationException e) {
159             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Error login: " + e.getMessage());
160         }
161         return false;
162     }
163
164     @Override
165     public void initialize() {
166         config = getConfigAs(MillheatAccountConfiguration.class);
167         scheduler.execute(() -> {
168             if (doLogin()) {
169                 try {
170                     model = refreshModel();
171                     updateStatus(ThingStatus.ONLINE);
172                     initPolling();
173                 } catch (final MillheatCommunicationException e) {
174                     model = new MillheatModel(0); // Empty model
175                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
176                             "error fetching initial data " + e.getMessage());
177                     logger.debug("Error initializing Millheat data", e);
178                     // Reschedule init
179                     scheduler.schedule(() -> {
180                         initialize();
181                     }, 30, TimeUnit.SECONDS);
182                 }
183             }
184         });
185         logger.debug("Finished initializing!");
186     }
187
188     @Override
189     public void dispose() {
190         stopPolling();
191         super.dispose();
192     }
193
194     /**
195      * starts this things polling future
196      */
197     private void initPolling() {
198         stopPolling();
199         statusFuture = scheduler.scheduleWithFixedDelay(() -> {
200             try {
201                 updateModelFromServerWithRetry(true);
202             } catch (final RuntimeException e) {
203                 logger.debug("Error refreshing model", e);
204             }
205         }, config.refreshInterval, config.refreshInterval, TimeUnit.SECONDS);
206     }
207
208     private <T> T sendLoginRequest(final AbstractRequest req, final Class<T> responseType)
209             throws MillheatCommunicationException {
210         final Request request = httpClient.newRequest(authEndpoint + req.getRequestUrl());
211         addStandardHeadersAndPayload(request, req);
212         return sendRequest(request, req, responseType);
213     }
214
215     private <T> T sendLoggedInRequest(final AbstractRequest req, final Class<T> responseType)
216             throws MillheatCommunicationException {
217         try {
218             final Request request = buildLoggedInRequest(req);
219             return sendRequest(request, req, responseType);
220         } catch (NoSuchAlgorithmException e) {
221             throw new MillheatCommunicationException("Error building Millheat request: " + e.getMessage(), e);
222         }
223     }
224
225     @SuppressWarnings("unchecked")
226     private <T> T sendRequest(final Request request, final AbstractRequest req, final Class<T> responseType)
227             throws MillheatCommunicationException {
228         try {
229             final ContentResponse contentResponse = request.send();
230             final String responseJson = contentResponse.getContentAsString();
231             if (contentResponse.getStatus() == HttpStatus.OK_200) {
232                 final AbstractResponse rsp = (AbstractResponse) gson.fromJson(responseJson, responseType);
233                 if (rsp == null) {
234                     return (T) null;
235                 } else if (rsp.errorCode == 0) {
236                     return (T) rsp;
237                 } else {
238                     throw new MillheatCommunicationException(req, rsp);
239                 }
240             } else {
241                 throw new MillheatCommunicationException(
242                         "Error sending request to Millheat server. Server responded with " + contentResponse.getStatus()
243                                 + " and payload " + responseJson);
244             }
245         } catch (InterruptedException | TimeoutException | ExecutionException e) {
246             throw new MillheatCommunicationException("Error sending request to Millheat server: " + e.getMessage(), e);
247         }
248     }
249
250     public MillheatModel refreshModel() throws MillheatCommunicationException {
251         final MillheatModel model = new MillheatModel(System.currentTimeMillis());
252         final GetHomesResponse homesRsp = sendLoggedInRequest(new GetHomesRequest(), GetHomesResponse.class);
253         for (final HomeDTO dto : homesRsp.homes) {
254             model.addHome(new Home(dto));
255         }
256         for (final Home home : model.getHomes()) {
257             final SelectRoomByHomeResponse roomRsp = sendLoggedInRequest(
258                     new SelectRoomByHomeRequest(home.getId(), home.getTimezone()), SelectRoomByHomeResponse.class);
259             for (final RoomDTO dto : roomRsp.rooms) {
260                 home.addRoom(new Room(dto, home));
261             }
262
263             for (final Room room : home.getRooms()) {
264                 final SelectDeviceByRoomResponse deviceRsp = sendLoggedInRequest(
265                         new SelectDeviceByRoomRequest(room.getId(), home.getTimezone()),
266                         SelectDeviceByRoomResponse.class);
267                 for (final DeviceDTO dto : deviceRsp.devices) {
268                     room.addHeater(new Heater(dto, room));
269                 }
270             }
271             final GetIndependentDevicesByHomeResponse independentRsp = sendLoggedInRequest(
272                     new GetIndependentDevicesByHomeRequest(home.getId(), home.getTimezone()),
273                     GetIndependentDevicesByHomeResponse.class);
274             for (final DeviceDTO dto : independentRsp.devices) {
275                 home.addHeater(new Heater(dto));
276             }
277         }
278         return model;
279     }
280
281     /**
282      * Stops this thing's polling future
283      */
284     @SuppressWarnings("null")
285     private void stopPolling() {
286         if (statusFuture != null && !statusFuture.isCancelled()) {
287             statusFuture.cancel(true);
288             statusFuture = null;
289         }
290     }
291
292     public void updateModelFromServerWithRetry(boolean forceUpdate) {
293         if (allowModelUpdate() || forceUpdate) {
294             try {
295                 updateModel();
296             } catch (final MillheatCommunicationException e) {
297                 try {
298                     if (AbstractResponse.ERROR_CODE_ACCESS_TOKEN_EXPIRED == e.getErrorCode()
299                             || AbstractResponse.ERROR_CODE_INVALID_SIGNATURE == e.getErrorCode()
300                             || AbstractResponse.ERROR_CODE_AUTHENTICATION_FAILURE == e.getErrorCode()) {
301                         logger.debug("Token expired, will refresh token, then retry state refresh", e);
302                         if (doLogin()) {
303                             updateModel();
304                         }
305                     } else {
306                         logger.debug("Initiating retry due to error {}", e.getMessage(), e);
307                         updateModel();
308                     }
309                 } catch (MillheatCommunicationException e1) {
310                     logger.debug("Retry failed, waiting for next refresh cycle: {}", e.getMessage(), e);
311                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e1.getMessage());
312                 }
313             }
314         }
315     }
316
317     private void updateModel() throws MillheatCommunicationException {
318         model = refreshModel();
319         updateThingStatuses();
320         updateStatus(ThingStatus.ONLINE);
321     }
322
323     private void updateThingStatuses() {
324         final List<Thing> subThings = getThing().getThings();
325         for (final Thing thing : subThings) {
326             final ThingHandler handler = thing.getHandler();
327             if (handler != null) {
328                 final MillheatBaseThingHandler mHandler = (MillheatBaseThingHandler) handler;
329                 mHandler.updateState(model);
330             }
331         }
332     }
333
334     private Request buildLoggedInRequest(final AbstractRequest req) throws NoSuchAlgorithmException {
335         final String nonce = StringUtils.getRandomString(NUM_NONCE_CHARS, ALLOWED_NONCE_CHARACTERS);
336         final String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
337         final String signatureBasis = REQUEST_TIMEOUT + timestamp + nonce + token;
338         MessageDigest md = MessageDigest.getInstance(SHA_1_ALGORITHM);
339         byte[] sha1Hash = md.digest(signatureBasis.getBytes(StandardCharsets.UTF_8));
340         final String signature = HexUtils.bytesToHex(sha1Hash).toLowerCase();
341         final String reqJson = gson.toJson(req);
342
343         final Request request = httpClient.newRequest(serviceEndpoint + req.getRequestUrl());
344
345         return addStandardHeadersAndPayload(request, req).header("X-Zc-Timestamp", timestamp)
346                 .header("X-Zc-Timeout", REQUEST_TIMEOUT).header("X-Zc-Nonce", nonce).header("X-Zc-User-Id", userId)
347                 .header("X-Zc-User-Signature", signature).header("X-Zc-Content-Length", "" + reqJson.length());
348     }
349
350     private Request addStandardHeadersAndPayload(final Request req, final AbstractRequest payload) {
351         requestLogger.listenTo(req);
352
353         return req.header("Connection", "Keep-Alive").header("X-Zc-Major-Domain", "seanywell")
354                 .header("X-Zc-Msg-Name", "millService").header("X-Zc-Sub-Domain", "milltype").header("X-Zc-Seq-Id", "1")
355                 .header("X-Zc-Version", "1").method(HttpMethod.POST).timeout(30, TimeUnit.SECONDS)
356                 .content(new BytesContentProvider(gson.toJson(payload).getBytes(StandardCharsets.UTF_8)), CONTENT_TYPE);
357     }
358
359     public void updateRoomTemperature(final Long roomId, final Command command, final ModeType mode) {
360         final Optional<Home> optionalHome = model.findHomeByRoomId(roomId);
361         final Optional<Room> optionalRoom = model.findRoomById(roomId);
362         if (optionalHome.isPresent() && optionalRoom.isPresent()) {
363             final SetRoomTempRequest req = new SetRoomTempRequest(optionalHome.get(), optionalRoom.get());
364             if (command instanceof QuantityType<?> quantityCommand) {
365                 final int newTemp = (int) quantityCommand.longValue();
366                 switch (mode) {
367                     case SLEEP:
368                         req.sleepTemp = newTemp;
369                         break;
370                     case AWAY:
371                         req.awayTemp = newTemp;
372                         break;
373                     case COMFORT:
374                         req.comfortTemp = newTemp;
375                         break;
376                     default:
377                         logger.info("Cannot set room temp for mode {}", mode);
378                 }
379                 try {
380                     sendLoggedInRequest(req, SetRoomTempResponse.class);
381                 } catch (final MillheatCommunicationException e) {
382                     logger.debug("Error updating temperature for room {}", roomId, e);
383                 }
384             } else {
385                 logger.debug("Error updating temperature for room {}, expected QuantityType but got {}", roomId,
386                         command);
387             }
388         }
389     }
390
391     public void updateIndependentHeaterProperties(@Nullable final String macAddress, @Nullable final Long heaterId,
392             @Nullable final Command temperatureCommand, @Nullable final Command masterOnOffCommand,
393             @Nullable final Command fanCommand) {
394         model.findHeaterByMacOrId(macAddress, heaterId).ifPresent(heater -> {
395             int setTemp = heater.getTargetTemp();
396             if (temperatureCommand instanceof QuantityType<?> temperature) {
397                 setTemp = (int) temperature.longValue();
398             }
399             boolean masterOnOff = heater.powerStatus();
400             if (masterOnOffCommand != null) {
401                 masterOnOff = masterOnOffCommand == OnOffType.ON;
402             }
403             boolean fanActive = heater.fanActive();
404             if (fanCommand != null) {
405                 fanActive = fanCommand == OnOffType.ON;
406             }
407             final SetDeviceTempRequest req = new SetDeviceTempRequest(heater, setTemp, masterOnOff, fanActive);
408             try {
409                 sendLoggedInRequest(req, SetRoomTempResponse.class);
410                 heater.setTargetTemp(setTemp);
411                 heater.setPowerStatus(masterOnOff);
412                 heater.setFanActive(fanActive);
413             } catch (final MillheatCommunicationException e) {
414                 logger.debug("Error updating temperature for heater {}", macAddress, e);
415             }
416         });
417     }
418
419     public void updateVacationProperty(Home home, String property, Command command) {
420         try {
421             switch (property) {
422                 case SetHolidayParameterRequest.PROP_START: {
423                     long epoch = ((DateTimeType) command).getZonedDateTime().toEpochSecond();
424                     SetHolidayParameterRequest req = new SetHolidayParameterRequest(home.getId(), home.getTimezone(),
425                             SetHolidayParameterRequest.PROP_START, epoch);
426                     if (sendLoggedInRequest(req, SetHolidayParameterResponse.class).isSuccess()) {
427                         home.setVacationModeStart(epoch);
428                     }
429                     break;
430                 }
431                 case SetHolidayParameterRequest.PROP_END: {
432                     long epoch = ((DateTimeType) command).getZonedDateTime().toEpochSecond();
433                     SetHolidayParameterRequest req = new SetHolidayParameterRequest(home.getId(), home.getTimezone(),
434                             SetHolidayParameterRequest.PROP_END, epoch);
435                     if (sendLoggedInRequest(req, SetHolidayParameterResponse.class).isSuccess()) {
436                         home.setVacationModeEnd(epoch);
437                     }
438                     break;
439                 }
440                 case SetHolidayParameterRequest.PROP_TEMP: {
441                     int holidayTemp = ((QuantityType<?>) command).intValue();
442                     SetHolidayParameterRequest req = new SetHolidayParameterRequest(home.getId(), home.getTimezone(),
443                             SetHolidayParameterRequest.PROP_TEMP, holidayTemp);
444                     if (sendLoggedInRequest(req, SetHolidayParameterResponse.class).isSuccess()) {
445                         home.setHolidayTemp(holidayTemp);
446                     }
447                     break;
448                 }
449                 case SetHolidayParameterRequest.PROP_MODE_ADVANCED: {
450                     if (home.getMode().getMode() == ModeType.VACATION) {
451                         int value = OnOffType.ON == command ? 0 : 1;
452                         SetHolidayParameterRequest req = new SetHolidayParameterRequest(home.getId(),
453                                 home.getTimezone(), SetHolidayParameterRequest.PROP_MODE_ADVANCED, value);
454                         if (sendLoggedInRequest(req, SetHolidayParameterResponse.class).isSuccess()) {
455                             home.setVacationModeAdvanced((OnOffType) command);
456                         }
457                     } else {
458                         logger.debug("Must enable vaction mode before advanced vacation mode can be enabled");
459                     }
460                     break;
461                 }
462                 case SetHolidayParameterRequest.PROP_MODE: {
463                     if (home.getVacationModeStart() != null && home.getVacationModeEnd() != null) {
464                         int value = OnOffType.ON == command ? 1 : 0;
465                         SetHolidayParameterRequest req = new SetHolidayParameterRequest(home.getId(),
466                                 home.getTimezone(), SetHolidayParameterRequest.PROP_MODE, value);
467                         if (sendLoggedInRequest(req, SetHolidayParameterResponse.class).isSuccess()) {
468                             updateModelFromServerWithRetry(true);
469                         }
470                     } else {
471                         logger.debug("Cannot enable vacation mode unless start and end time is already set");
472                     }
473                     break;
474                 }
475             }
476         } catch (MillheatCommunicationException e) {
477             logger.debug("Failure trying to set holiday properties: {}", e.getMessage());
478         }
479     }
480 }