2 * Copyright (c) 2010-2022 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.nuki.internal.handler;
15 import java.time.OffsetDateTime;
16 import java.time.ZoneId;
17 import java.time.ZonedDateTime;
18 import java.time.format.DateTimeParseException;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21 import java.util.function.Consumer;
22 import java.util.function.Function;
23 import java.util.regex.Pattern;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.nuki.internal.configuration.NukiDeviceConfiguration;
28 import org.openhab.binding.nuki.internal.constants.NukiBindingConstants;
29 import org.openhab.binding.nuki.internal.dataexchange.BridgeListResponse;
30 import org.openhab.binding.nuki.internal.dataexchange.BridgeLockStateResponse;
31 import org.openhab.binding.nuki.internal.dataexchange.NukiBaseResponse;
32 import org.openhab.binding.nuki.internal.dataexchange.NukiHttpClient;
33 import org.openhab.binding.nuki.internal.dto.BridgeApiDeviceStateDto;
34 import org.openhab.binding.nuki.internal.dto.BridgeApiListDeviceDto;
35 import org.openhab.core.config.core.Configuration;
36 import org.openhab.core.library.types.DateTimeType;
37 import org.openhab.core.library.types.DecimalType;
38 import org.openhab.core.library.types.OnOffType;
39 import org.openhab.core.thing.Bridge;
40 import org.openhab.core.thing.Channel;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.thing.Thing;
43 import org.openhab.core.thing.ThingStatus;
44 import org.openhab.core.thing.ThingStatusDetail;
45 import org.openhab.core.thing.ThingStatusInfo;
46 import org.openhab.core.thing.binding.BaseThingHandler;
47 import org.openhab.core.thing.binding.BridgeHandler;
48 import org.openhab.core.thing.binding.ThingHandler;
49 import org.openhab.core.types.Command;
50 import org.openhab.core.types.RefreshType;
51 import org.openhab.core.types.State;
52 import org.openhab.core.types.UnDefType;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * The {@link AbstractNukiDeviceHandler} is a base class for implementing ThingHandlers for Nuki devices
59 * @author Jan Vybíral - Initial contribution
62 public abstract class AbstractNukiDeviceHandler<T extends NukiDeviceConfiguration> extends BaseThingHandler {
64 protected final Logger logger = LoggerFactory.getLogger(getClass());
65 private static final int JOB_INTERVAL = 60;
66 private static final Pattern NUKI_ID_HEX_PATTERN = Pattern.compile("[A-F\\d]{8}", Pattern.CASE_INSENSITIVE);
69 protected ScheduledFuture<?> reInitJob;
70 protected T configuration;
72 private NukiHttpClient nukiHttpClient;
74 public AbstractNukiDeviceHandler(Thing thing) {
76 this.configuration = getConfigAs(getConfigurationClass());
79 private static String hexToDecimal(String hexString) {
80 return String.valueOf(Integer.parseInt(hexString, 16));
83 protected void withHttpClient(Consumer<NukiHttpClient> consumer) {
84 withHttpClient(client -> {
85 consumer.accept(client);
90 protected <U> U withHttpClient(Function<NukiHttpClient, U> consumer, U defaultValue) {
91 NukiHttpClient client = this.nukiHttpClient;
93 logger.warn("Nuki HTTP client is null. This is a bug in Nuki Binding, please report it",
94 new IllegalStateException());
97 return consumer.apply(client);
102 * Performs migration of old device configuration
104 * @return true if configuration was change and reload is needed
106 protected boolean migrateConfiguration() {
107 String nukiId = getConfig().get(NukiBindingConstants.PROPERTY_NUKI_ID).toString();
108 // legacy support - check if nukiId is hexadecimal (which might have been set by previous binding version)
109 // and convert it to decimal
110 if (NUKI_ID_HEX_PATTERN.matcher(nukiId).matches()) {
112 "SmartLock '{}' was created by old version of binding. It is recommended to delete it and discover again",
114 Configuration newConfig = editConfiguration();
115 newConfig.put(NukiBindingConstants.PROPERTY_NUKI_ID, hexToDecimal(nukiId));
116 updateConfiguration(newConfig);
124 public void initialize() {
125 this.configuration = getConfigAs(getConfigurationClass());
126 if (migrateConfiguration()) {
127 this.configuration = getConfigAs(getConfigurationClass());
129 scheduler.execute(this::initializeHandler);
133 public void dispose() {
137 private void initializeHandler() {
138 Bridge bridge = getBridge();
139 if (bridge == null) {
140 initializeHandler(null, null);
142 initializeHandler(bridge.getHandler(), bridge.getStatus());
146 private void initializeHandler(@Nullable ThingHandler handler, @Nullable ThingStatus bridgeStatus) {
147 if (handler instanceof NukiBridgeHandler && bridgeStatus != null) {
148 NukiBridgeHandler bridgeHandler = (NukiBridgeHandler) handler;
149 if (bridgeStatus == ThingStatus.ONLINE) {
150 this.nukiHttpClient = bridgeHandler.getNukiHttpClient();
151 withHttpClient(client -> {
152 BridgeListResponse bridgeListResponse = client.getList();
153 if (handleResponse(bridgeListResponse, null, null)) {
154 BridgeApiListDeviceDto device = bridgeListResponse.getDevice(configuration.nukiId);
155 if (device == null) {
156 logger.warn("Configured Smart Lock [{}] not present in bridge device list",
157 configuration.nukiId);
159 updateStatus(ThingStatus.ONLINE);
166 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
170 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
175 protected void refreshData(BridgeApiListDeviceDto device) {
176 updateProperty(NukiBindingConstants.PROPERTY_NAME, device.getName());
177 if (device.getFirmwareVersion() != null) {
178 updateProperty(NukiBindingConstants.PROPERTY_FIRMWARE_VERSION, device.getFirmwareVersion());
181 if (device.getLastKnownState() != null) {
182 refreshState(device.getLastKnownState());
187 * Method to refresh state of this thing. Implementors should read values from state and update corresponding
190 * @param state Current state of this thing as obtained from Bridge API
192 public abstract void refreshState(BridgeApiDeviceStateDto state);
194 protected <U> void updateState(String channelId, U state, Function<U, State> transform) {
195 Channel channel = thing.getChannel(channelId);
196 if (channel != null) {
197 updateState(channel.getUID(), state, transform);
201 protected void triggerChannel(String channelId, String event) {
202 Channel channel = thing.getChannel(channelId);
203 if (channel != null) {
204 triggerChannel(channel.getUID(), event);
208 protected <U> void updateState(ChannelUID channel, U state, Function<U, State> transform) {
209 updateState(channel, state == null ? UnDefType.NULL : transform.apply(state));
212 protected State toDateTime(String dateTimeString) {
214 ZonedDateTime date = OffsetDateTime.parse(dateTimeString).atZoneSameInstant(ZoneId.systemDefault());
215 return new DateTimeType(date);
216 } catch (DateTimeParseException e) {
217 logger.debug("Failed to parse date from '{}'", dateTimeString);
218 return UnDefType.UNDEF;
223 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
224 scheduler.execute(() -> {
225 Bridge bridge = getBridge();
226 if (bridge == null) {
227 initializeHandler(null, bridgeStatusInfo.getStatus());
229 initializeHandler(bridge.getHandler(), bridgeStatusInfo.getStatus());
235 public void handleCommand(ChannelUID channelUID, Command command) {
236 logger.trace("handleCommand({}, {})", channelUID, command);
238 if (getThing().getStatus() != ThingStatus.ONLINE) {
239 logger.debug("Thing is not ONLINE; command[{}] for channelUID[{}] is ignored", command, channelUID);
240 } else if (command instanceof RefreshType) {
241 scheduler.execute(() -> {
242 withHttpClient(client -> {
243 BridgeLockStateResponse bridgeLockStateResponse = client.getBridgeLockState(configuration.nukiId,
245 if (handleResponse(bridgeLockStateResponse, channelUID.getAsString(), command.toString())) {
246 if (!doHandleRefreshCommand(channelUID, command, bridgeLockStateResponse)) {
247 logger.debug("Command[{}] for channelUID[{}] not implemented!", command, channelUID);
253 scheduler.execute(() -> {
254 if (!doHandleCommand(channelUID, command)) {
255 logger.debug("Unexpected command[{}] for channelUID[{}]!", command, channelUID);
262 * Get type of this device
264 * @return Device type
266 protected abstract int getDeviceType();
269 * Get class of configuration
271 * @return Configuration class
273 protected abstract Class<T> getConfigurationClass();
276 * Method to handle channel command - will not receive REFRESH command
278 * @param channelUID Channel which received command
279 * @param command Command received
280 * @return true if command was handled
282 protected abstract boolean doHandleCommand(ChannelUID channelUID, Command command);
285 * Method for handlign {@link RefreshType} command
287 * @param channelUID Channel which received command
288 * @param command Command received, will always be {@link RefreshType}
289 * @param response Response from /lockState endpoint of Bridge API
290 * @return true if command was handled
292 protected boolean doHandleRefreshCommand(ChannelUID channelUID, Command command, BridgeLockStateResponse response) {
293 refreshState(response.getBridgeApiLockStateDto());
297 protected boolean handleResponse(NukiBaseResponse nukiBaseResponse, @Nullable String channelUID,
298 @Nullable String command) {
299 if (nukiBaseResponse.getStatus() == 200 && nukiBaseResponse.isSuccess()) {
300 logger.debug("Command[{}] succeeded for channelUID[{}] on nukiId[{}]!", command, channelUID,
301 configuration.nukiId);
303 } else if (nukiBaseResponse.getStatus() != 200) {
304 logger.debug("Request to Bridge failed! status[{}] - message[{}]", nukiBaseResponse.getStatus(),
305 nukiBaseResponse.getMessage());
306 } else if (!nukiBaseResponse.isSuccess()) {
308 "Request from Bridge to Smart Lock failed! status[{}] - message[{}] - isSuccess[{}]. Check if Nuki Smart Lock is powered on!",
309 nukiBaseResponse.getStatus(), nukiBaseResponse.getMessage(), nukiBaseResponse.isSuccess());
311 logger.debug("Could not handle command[{}] for channelUID[{}] on nukiId[{}]!", command, channelUID,
312 configuration.nukiId);
314 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, nukiBaseResponse.getMessage());
316 updateState(NukiBindingConstants.CHANNEL_SMARTLOCK_LOCK, OnOffType.OFF, Function.identity());
317 updateState(NukiBindingConstants.CHANNEL_SMARTLOCK_STATE, NukiBindingConstants.LOCK_STATES_UNDEFINED,
319 updateState(NukiBindingConstants.CHANNEL_SMARTLOCK_DOOR_STATE, NukiBindingConstants.DOORSENSOR_STATES_UNKNOWN,
322 withBridgeAsync(bridge -> {
323 bridge.checkBridgeOnline();
329 private void withBridgeAsync(Consumer<NukiBridgeHandler> handler) {
330 Bridge bridge = getBridge();
331 if (bridge != null) {
332 BridgeHandler bridgeHandler = bridge.getHandler();
333 if (bridgeHandler instanceof NukiBridgeHandler) {
334 scheduler.execute(() -> handler.accept((NukiBridgeHandler) bridgeHandler));
339 private void startReInitJob() {
340 logger.trace("Starting reInitJob with interval of {}secs for Smart Lock[{}].", JOB_INTERVAL,
341 configuration.nukiId);
342 if (reInitJob != null) {
343 logger.trace("Already started reInitJob for Smart Lock[{}].", configuration.nukiId);
346 reInitJob = scheduler.scheduleWithFixedDelay(this::initializeHandler, 1, JOB_INTERVAL, TimeUnit.SECONDS);
349 private void stopReInitJob() {
350 logger.trace("Stopping reInitJob for Smart Lock[{}].", configuration.nukiId);
351 ScheduledFuture<?> job = reInitJob;
354 logger.trace("Stopped reInitJob for Smart Lock[{}].", configuration.nukiId);