2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.millheat.internal.handler;
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;
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;
79 import com.google.gson.Gson;
80 import com.google.gson.GsonBuilder;
83 * The {@link MillheatAccountHandler} is responsible for handling commands, which are
84 * sent to one of the channels.
86 * @author Arne Seime - Initial contribution
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;
108 public MillheatAccountHandler(final Bridge bridge, final HttpClient httpClient, final BundleContext context) {
110 this.httpClient = httpClient;
111 final BooleanSerializer serializer = new BooleanSerializer();
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);
119 private boolean allowModelUpdate() {
120 final long timeSinceLastUpdate = System.currentTimeMillis() - model.getLastUpdated();
121 return timeSinceLastUpdate > MIN_TIME_BETWEEEN_MODEL_UPDATES_MS;
124 public MillheatModel getModel() {
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,
134 public boolean doLogin() {
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));
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");
158 } catch (final MillheatCommunicationException e) {
159 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Error login: " + e.getMessage());
165 public void initialize() {
166 config = getConfigAs(MillheatAccountConfiguration.class);
167 scheduler.execute(() -> {
170 model = refreshModel();
171 updateStatus(ThingStatus.ONLINE);
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);
179 scheduler.schedule(() -> {
181 }, 30, TimeUnit.SECONDS);
185 logger.debug("Finished initializing!");
189 public void dispose() {
195 * starts this things polling future
197 private void initPolling() {
199 statusFuture = scheduler.scheduleWithFixedDelay(() -> {
201 updateModelFromServerWithRetry(true);
202 } catch (final RuntimeException e) {
203 logger.debug("Error refreshing model", e);
205 }, config.refreshInterval, config.refreshInterval, TimeUnit.SECONDS);
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);
215 private <T> T sendLoggedInRequest(final AbstractRequest req, final Class<T> responseType)
216 throws MillheatCommunicationException {
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);
225 @SuppressWarnings("unchecked")
226 private <T> T sendRequest(final Request request, final AbstractRequest req, final Class<T> responseType)
227 throws MillheatCommunicationException {
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);
235 } else if (rsp.errorCode == 0) {
238 throw new MillheatCommunicationException(req, rsp);
241 throw new MillheatCommunicationException(
242 "Error sending request to Millheat server. Server responded with " + contentResponse.getStatus()
243 + " and payload " + responseJson);
245 } catch (InterruptedException | TimeoutException | ExecutionException e) {
246 throw new MillheatCommunicationException("Error sending request to Millheat server: " + e.getMessage(), e);
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));
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));
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));
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));
282 * Stops this thing's polling future
284 @SuppressWarnings("null")
285 private void stopPolling() {
286 if (statusFuture != null && !statusFuture.isCancelled()) {
287 statusFuture.cancel(true);
292 public void updateModelFromServerWithRetry(boolean forceUpdate) {
293 if (allowModelUpdate() || forceUpdate) {
296 } catch (final MillheatCommunicationException e) {
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);
306 logger.debug("Initiating retry due to error {}", e.getMessage(), e);
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());
317 private void updateModel() throws MillheatCommunicationException {
318 model = refreshModel();
319 updateThingStatuses();
320 updateStatus(ThingStatus.ONLINE);
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);
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);
343 final Request request = httpClient.newRequest(serviceEndpoint + req.getRequestUrl());
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());
350 private Request addStandardHeadersAndPayload(final Request req, final AbstractRequest payload) {
351 requestLogger.listenTo(req);
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);
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();
368 req.sleepTemp = newTemp;
371 req.awayTemp = newTemp;
374 req.comfortTemp = newTemp;
377 logger.info("Cannot set room temp for mode {}", mode);
380 sendLoggedInRequest(req, SetRoomTempResponse.class);
381 } catch (final MillheatCommunicationException e) {
382 logger.debug("Error updating temperature for room {}", roomId, e);
385 logger.debug("Error updating temperature for room {}, expected QuantityType but got {}", roomId,
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();
399 boolean masterOnOff = heater.powerStatus();
400 if (masterOnOffCommand != null) {
401 masterOnOff = masterOnOffCommand == OnOffType.ON;
403 boolean fanActive = heater.fanActive();
404 if (fanCommand != null) {
405 fanActive = fanCommand == OnOffType.ON;
407 final SetDeviceTempRequest req = new SetDeviceTempRequest(heater, setTemp, masterOnOff, fanActive);
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);
419 public void updateVacationProperty(Home home, String property, Command command) {
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);
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);
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);
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);
458 logger.debug("Must enable vaction mode before advanced vacation mode can be enabled");
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);
471 logger.debug("Cannot enable vacation mode unless start and end time is already set");
476 } catch (MillheatCommunicationException e) {
477 logger.debug("Failure trying to set holiday properties: {}", e.getMessage());