2 * Copyright (c) 2010-2024 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.homewizard.internal;
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.io.net.http.HttpUtil;
22 import org.openhab.core.thing.Thing;
23 import org.openhab.core.thing.ThingStatus;
24 import org.openhab.core.thing.ThingStatusDetail;
27 * The {@link HomeWizardStatefulDeviceHandler} extends the base class
28 * to provide support for devices that also have a 'state' interface.
29 * This interface can be used to query and control the state of a device.
31 * @author Daniƫl van Os - Initial contribution
34 public abstract class HomeWizardStatefulDeviceHandler extends HomeWizardDeviceHandler {
39 * @param thing The thing to handle
41 public HomeWizardStatefulDeviceHandler(Thing thing) {
46 * Device specific handling of the returned state payload.
48 * @param payload The data parsed from the state Json file
50 protected abstract void handleStatePayload(StatePayload payload);
52 protected void pollState() {
53 final String stateResult;
56 stateResult = HttpUtil.executeUrl("GET", apiURL + "state", 30000);
57 } catch (IOException e) {
58 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
59 String.format("Unable to query device state: %s", e.getMessage()));
63 if (stateResult.trim().isEmpty()) {
64 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Device returned empty state");
68 StatePayload statePayload = gson.fromJson(stateResult, StatePayload.class);
69 if (statePayload == null) {
70 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
71 "Unable to parse state response from device");
75 handleStatePayload(statePayload);
79 * Sends a command to the state interface of the device.
81 * @param command The command to send.
83 protected @Nullable StatePayload sendStateCommand(String command) {
84 try (InputStream is = new ByteArrayInputStream(command.getBytes())) {
85 String updatedState = HttpUtil.executeUrl("PUT", apiURL + "state", is, "application/json", 30000);
86 return gson.fromJson(updatedState, StatePayload.class);
87 } catch (IOException e) {
88 logger.warn("Failed to send command {} to {}", command, apiURL + "state");
94 * This overrides the original polling loop by including a request for the current state..
97 protected void pollingCode() {