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.shelly.internal.api2;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.*;
18 import static org.openhab.binding.shelly.internal.discovery.ShellyThingCreator.THING_TYPE_SHELLYPRO2_RELAY_STR;
19 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.UncheckedIOException;
26 import java.util.ArrayList;
27 import java.util.List;
29 import java.util.stream.Collectors;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.eclipse.jetty.http.HttpStatus;
35 import org.eclipse.jetty.websocket.api.StatusCode;
36 import org.openhab.binding.shelly.internal.api.ShellyApiException;
37 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
38 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
39 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyInputState;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyRollerStatus;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySensorSleepMode;
44 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
45 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDimmer;
46 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsEMeter;
47 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsLogin;
48 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsMeter;
49 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
50 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
51 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsUpdate;
52 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsWiFiNetwork;
53 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
54 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortStatusRelay;
55 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusLight;
56 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusRelay;
57 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor;
58 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2APClientList;
59 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2AuthChallenge;
60 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2ConfigParms;
61 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2DeviceConfigSta;
62 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfig.Shelly2GetConfigResult;
63 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfigAp;
64 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceConfigAp.Shelly2DeviceConfigApRE;
65 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceSettings;
66 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusLight;
67 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusResult;
68 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2DeviceStatus.Shelly2DeviceStatusSys.Shelly2DeviceStatusSysAvlUpdate;
69 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2NotifyEvent;
70 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcBaseMessage;
71 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcNotifyEvent;
72 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcNotifyStatus;
73 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcNotifyStatus.Shelly2NotifyStatus;
74 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcRequest;
75 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2RpcRequest.Shelly2RpcRequestParams;
76 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2WsConfigResponse;
77 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.Shelly2WsConfigResponse.Shelly2WsConfigResult;
78 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.ShellyScriptListResponse;
79 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.ShellyScriptListResponse.ShellyScriptListEntry;
80 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.ShellyScriptPutCodeParams;
81 import org.openhab.binding.shelly.internal.api2.Shelly2ApiJsonDTO.ShellyScriptResponse;
82 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
83 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
84 import org.openhab.binding.shelly.internal.handler.ShellyThingTable;
85 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
86 import org.openhab.core.library.unit.SIUnits;
87 import org.openhab.core.thing.ThingStatusDetail;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 * {@link Shelly2ApiRpc} implements Gen2 RPC interface
94 * @author Markus Michels - Initial contribution
97 public class Shelly2ApiRpc extends Shelly2ApiClient implements ShellyApiInterface, Shelly2RpctInterface {
98 private final Logger logger = LoggerFactory.getLogger(Shelly2ApiRpc.class);
99 private final @Nullable ShellyThingTable thingTable;
101 protected boolean initialized = false;
102 private boolean discovery = false;
103 private Shelly2RpcSocket rpcSocket = new Shelly2RpcSocket();
104 private @Nullable Shelly2AuthChallenge authInfo;
107 * Regular constructor - called by Thing handler
109 * @param thingName Symbolic thing name
110 * @param thing Thing Handler (ThingHandlerInterface)
112 public Shelly2ApiRpc(String thingName, ShellyThingTable thingTable, ShellyThingInterface thing) {
113 super(thingName, thing);
114 this.thingName = thingName;
116 this.thingTable = thingTable;
120 * Simple initialization - called by discovery handler
122 * @param thingName Symbolic thing name
123 * @param config Thing Configuration
124 * @param httpClient HTTP Client to be passed to ShellyHttpClient
126 public Shelly2ApiRpc(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
127 super(thingName, config, httpClient);
128 this.thingName = thingName;
129 this.thingTable = null;
130 this.discovery = true;
134 public void initialize() throws ShellyApiException {
136 logger.debug("{}: Disconnect Rpc Socket on initialize", thingName);
139 rpcSocket = new Shelly2RpcSocket(thingName, thingTable, config.deviceIp);
140 rpcSocket.addMessageHandler(this);
145 public boolean isInitialized() {
150 public void startScan() {
152 if (getProfile().isBlu) {
153 installScript(SHELLY2_BLU_GWSCRIPT, config.enableBluGateway);
155 } catch (ShellyApiException e) {
159 @SuppressWarnings("null")
161 public ShellyDeviceProfile getDeviceProfile(String thingType, @Nullable ShellySettingsDevice devInfo)
162 throws ShellyApiException {
163 ShellyDeviceProfile profile = thing != null ? getProfile() : new ShellyDeviceProfile();
165 if (devInfo != null) {
166 profile.device = devInfo;
168 if (profile.device.type == null) {
169 profile.device = getDeviceInfo();
172 Shelly2GetConfigResult dc = apiRequest(SHELLYRPC_METHOD_GETCONFIG, null, Shelly2GetConfigResult.class);
173 profile.isGen2 = true;
174 profile.settingsJson = gson.toJson(dc);
175 profile.thingName = thingName;
176 profile.settings.name = profile.status.name = dc.sys.device.name;
177 profile.name = getString(profile.settings.name);
178 profile.settings.timezone = getString(dc.sys.location.tz);
179 profile.settings.discoverable = getBool(dc.sys.device.discoverable);
180 if (dc.wifi != null && dc.wifi.ap != null && dc.wifi.ap.rangeExtender != null) {
181 profile.settings.wifiAp.rangeExtender = getBool(dc.wifi.ap.rangeExtender.enable);
183 if (dc.cloud != null) {
184 profile.settings.cloud.enabled = getBool(dc.cloud.enable);
186 if (dc.mqtt != null) {
187 profile.settings.mqtt.enable = getBool(dc.mqtt.enable);
189 if (dc.sys.sntp != null) {
190 profile.settings.sntp.server = dc.sys.sntp.server;
193 profile.isRoller = dc.cover0 != null;
194 profile.settings.relays = fillRelaySettings(profile, dc);
195 profile.settings.inputs = fillInputSettings(profile, dc);
196 profile.settings.rollers = fillRollerSettings(profile, dc);
198 profile.isEMeter = true;
199 profile.numInputs = profile.settings.inputs != null ? profile.settings.inputs.size() : 0;
200 profile.numRelays = profile.settings.relays != null ? profile.settings.relays.size() : 0;
201 profile.numRollers = profile.settings.rollers != null ? profile.settings.rollers.size() : 0;
202 profile.hasRelays = profile.numRelays > 0 || profile.numRollers > 0;
203 if (getString(profile.device.mode).isEmpty() && profile.hasRelays) {
204 profile.device.mode = profile.isRoller ? SHELLY_CLASS_ROLLER : SHELLY_CLASS_RELAY;
207 ShellySettingsDevice device = profile.device;
208 profile.isGen2 = device.gen == 2;
209 if (config.serviceName.isEmpty()) {
210 config.serviceName = getString(profile.device.hostname);
212 profile.settings.fw = device.fw;
213 profile.fwDate = substringBefore(substringBefore(device.fw, "/"), "-");
214 profile.fwVersion = profile.status.update.oldVersion = ShellyDeviceProfile.extractFwVersion(device.fw);
215 profile.status.hasUpdate = profile.status.update.hasUpdate = false;
217 if (dc.eth != null) {
218 profile.settings.ethernet = getBool(dc.eth.enable);
220 if (dc.ble != null) {
221 profile.settings.bluetooth = getBool(dc.ble.enable);
224 profile.settings.wifiSta = new ShellySettingsWiFiNetwork();
225 profile.settings.wifiSta1 = new ShellySettingsWiFiNetwork();
226 fillWiFiSta(dc.wifi.sta, profile.settings.wifiSta);
227 fillWiFiSta(dc.wifi.sta1, profile.settings.wifiSta1);
228 if (dc.wifi.ap != null && dc.wifi.ap.rangeExtender != null) {
229 profile.settings.rangeExtender = getBool(dc.wifi.ap.rangeExtender.enable);
232 profile.numMeters = 0;
233 if (profile.hasRelays) {
234 profile.status.relays = new ArrayList<>();
235 relayStatus.relays = new ArrayList<>();
236 profile.numMeters = profile.isRoller ? profile.numRollers : profile.numRelays;
237 for (int i = 0; i < profile.numRelays; i++) {
238 profile.status.relays.add(new ShellySettingsRelay());
239 relayStatus.relays.add(new ShellyShortStatusRelay());
243 if (profile.numInputs > 0) {
244 profile.status.inputs = new ArrayList<>();
245 relayStatus.inputs = new ArrayList<>();
246 for (int i = 0; i < profile.numInputs; i++) {
247 ShellyInputState input = new ShellyInputState();
250 input.eventCount = 0;
251 profile.status.inputs.add(input);
252 relayStatus.inputs.add(input);
256 // handle special cases, because there is no indicator for a meter in GetConfig
257 // Pro 3EM has 3 meters
258 // Pro 2 has 2 relays, but no meters
259 // Mini PM has 1 meter, but no relay
260 if (thingType.equals(THING_TYPE_SHELLYPRO2_RELAY_STR)) {
261 profile.numMeters = 0;
262 } else if (dc.pm10 != null) {
263 profile.numMeters = 1;
264 } else if (dc.em0 != null) {
265 profile.numMeters = 3;
266 } else if (dc.em10 != null) {
267 profile.numMeters = 2;
270 if (profile.numMeters > 0) {
271 profile.status.meters = new ArrayList<>();
272 profile.status.emeters = new ArrayList<>();
273 relayStatus.meters = new ArrayList<>();
275 for (int i = 0; i < profile.numMeters; i++) {
276 profile.status.meters.add(new ShellySettingsMeter());
277 profile.status.emeters.add(new ShellySettingsEMeter());
278 relayStatus.meters.add(new ShellySettingsMeter());
282 if (profile.isRoller) {
283 profile.status.rollers = new ArrayList<>();
284 for (int i = 0; i < profile.numRollers; i++) {
285 ShellyRollerStatus rs = new ShellyRollerStatus();
286 profile.status.rollers.add(rs);
287 rollerStatus.add(rs);
291 if (profile.isDimmer) {
292 profile.settings.dimmers = new ArrayList<>();
293 profile.settings.dimmers.add(new ShellySettingsDimmer());
294 profile.status.dimmers = new ArrayList<>();
295 profile.status.dimmers.add(new ShellyShortLightStatus());
296 fillDimmerSettings(profile, dc);
298 profile.status.lights = profile.isBulb ? new ArrayList<>() : null;
299 profile.status.thermostats = profile.isTRV ? new ArrayList<>() : null;
301 if (profile.hasBattery) {
302 profile.settings.sleepMode = new ShellySensorSleepMode();
303 profile.settings.sleepMode.unit = "m";
304 profile.settings.sleepMode.period = dc.sys.sleep != null ? dc.sys.sleep.wakeupPeriod / 60 : 720;
305 checkSetWsCallback();
308 if (dc.led != null) {
309 profile.settings.ledStatusDisable = !getBool(dc.led.sysLedEnable);
310 profile.settings.ledPowerDisable = "off".equals(getString(dc.led.powerLed));
313 profile.initialized = true;
315 getStatus(); // make sure profile.status is initialized (e.g,. relay/meter status)
316 asyncApiRequest(SHELLYRPC_METHOD_GETSTATUS); // request periodic status updates from device
319 if (profile.alwaysOn && config.enableBluGateway != null) {
320 logger.debug("{}: BLU Gateway support is {} for this device", thingName,
321 config.enableBluGateway ? "enabled" : "disabled");
322 if (config.enableBluGateway) {
323 boolean bluetooth = getBool(profile.settings.bluetooth);
324 if (config.enableBluGateway && !bluetooth) {
325 logger.info("{}: Bluetooth needs to be enabled to activate BLU Gateway mode", thingName);
327 installScript(SHELLY2_BLU_GWSCRIPT, config.enableBluGateway && bluetooth);
330 } catch (ShellyApiException e) {
331 logger.debug("{}: Device config failed", thingName, e);
338 private void fillWiFiSta(@Nullable Shelly2DeviceConfigSta from, ShellySettingsWiFiNetwork to) {
339 to.enabled = from != null && !getString(from.ssid).isEmpty();
343 to.mask = from.netmask;
344 to.dns = from.nameserver;
348 private void checkSetWsCallback() throws ShellyApiException {
349 Shelly2ConfigParms wsConfig = apiRequest(SHELLYRPC_METHOD_WSGETCONFIG, null, Shelly2ConfigParms.class);
350 String url = "ws://" + config.localIp + ":" + config.localPort + "/shelly/wsevent";
351 if (!config.localIp.isEmpty() && !getBool(wsConfig.enable)
352 || !url.equalsIgnoreCase(getString(wsConfig.server))) {
353 logger.debug("{}: A battery device was detected without correct callback, fix it", thingName);
354 wsConfig.enable = true;
355 wsConfig.server = url;
356 Shelly2RpcRequest request = new Shelly2RpcRequest();
358 request.method = SHELLYRPC_METHOD_WSSETCONFIG;
359 request.params.config = wsConfig;
360 Shelly2WsConfigResponse response = apiRequest(SHELLYRPC_METHOD_WSSETCONFIG, request.params,
361 Shelly2WsConfigResponse.class);
362 if (response.result != null && response.result.restartRequired) {
363 logger.info("{}: WebSocket callback was updated, device is restarting", thingName);
364 getThing().getApi().deviceReboot();
365 getThing().reinitializeThing();
370 protected void installScript(String script, boolean install) throws ShellyApiException {
372 ShellyScriptListResponse scriptList = apiRequest(
373 new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_SCRIPT_LIST), ShellyScriptListResponse.class);
378 logger.debug("{}: Install or restart script {} on Shelly Device", thingName, script);
380 boolean running = false, upload = false;
381 for (ShellyScriptListEntry s : scriptList.scripts) {
382 if (s.name.startsWith(script)) {
385 logger.debug("{}: Script {} is already installed, id={}", thingName, script, ourId);
392 startScript(ourId, false);
393 enableScript(script, false);
395 logger.debug("{}: Script {} was disabledd, id={}", thingName, script, ourId);
400 // get script code from bundle resources
401 String file = BUNDLE_RESOURCE_SCRIPTS + "/" + script;
402 ClassLoader cl = Shelly2ApiRpc.class.getClassLoader();
404 try (InputStream inputStream = cl.getResourceAsStream(file)) {
405 if (inputStream != null) {
406 code = new BufferedReader(new InputStreamReader(inputStream)).lines()
407 .collect(Collectors.joining("\n"));
409 } catch (IOException | UncheckedIOException e) {
410 logger.debug("{}: Installation of script {} failed: Unable to read {} from bundle resources!",
411 thingName, script, file, e);
415 boolean restart = false;
417 // script not installed -> install it
421 // verify that the same code version is active (avoid unnesesary flash updates)
422 ShellyScriptResponse rsp = apiRequest(
423 new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_SCRIPT_GETCODE).withId(ourId),
424 ShellyScriptResponse.class);
425 if (!rsp.data.trim().equals(code.trim())) {
426 logger.debug("{}: A script version was found, update to newest one", thingName);
429 logger.debug("{}: Same script version was found, restart", thingName);
432 } catch (ShellyApiException e) {
433 logger.debug("{}: Unable to read current script code -> force update (deviced returned: {})",
434 thingName, e.getMessage());
439 if (restart || (running && upload)) {
440 // first stop running script
441 startScript(ourId, false);
444 if (upload && ourId != -1) {
445 // Delete existing script
450 logger.debug("{}: Script will be installed...", thingName);
452 // Create new script, get id
453 ShellyScriptResponse rsp = apiRequest(
454 new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_SCRIPT_CREATE).withName(script),
455 ShellyScriptResponse.class);
457 logger.debug("{}: Script has been created, id={}", thingName, ourId);
462 // Put script code for generated id
463 ShellyScriptPutCodeParams parms = new ShellyScriptPutCodeParams();
465 parms.append = false;
466 int length = code.length(), processed = 0, chunk = 1;
468 int nextlen = Math.min(1024, length - processed);
469 parms.code = code.substring(processed, processed + nextlen);
470 logger.debug("{}: Uploading chunk {} of script (total {} chars, {} processed)", thingName, chunk,
472 apiRequest(SHELLYRPC_METHOD_SCRIPT_PUTCODE, parms, String.class);
473 processed += nextlen;
476 } while (processed < length);
479 if (enableScript(script, true) && upload) {
480 logger.info("{}: Script {} was {} installed successful", thingName, thingName, script);
484 running = startScript(ourId, true);
485 logger.debug("{}: Script {} {}", thingName, script,
486 running ? "was successfully started" : "failed to start");
488 } catch (ShellyApiException e) {
489 ShellyApiResult res = e.getApiResult();
490 if (res.httpCode == HttpStatus.NOT_FOUND_404) { // Shely 4Pro
491 logger.debug("{}: Script {} was not installed, device doesn't support scripts", thingName, script);
493 logger.debug("{}: Unable to install script {}: {}", thingName, script, res.toString());
498 private boolean startScript(int ourId, boolean start) {
501 apiRequest(new Shelly2RpcRequest()
502 .withMethod(start ? SHELLYRPC_METHOD_SCRIPT_START : SHELLYRPC_METHOD_SCRIPT_STOP)
505 } catch (ShellyApiException e) {
511 private boolean enableScript(String script, boolean enable) {
513 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams().withConfig();
514 params.config.name = script;
515 params.config.enable = enable;
516 apiRequest(SHELLYRPC_METHOD_SCRIPT_SETCONFIG, params, String.class);
518 } catch (ShellyApiException e) {
519 logger.debug("{}: Unable to enable script {}", thingName, script, e);
524 private boolean deleteScript(int id) {
526 throw new IllegalArgumentException("Invalid Script Id");
529 logger.debug("{}: Delete existing script with id{}", thingName, id);
530 apiRequest(new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_SCRIPT_DELETE).withId(id));
532 } catch (ShellyApiException e) {
533 logger.debug("{}: Unable to delete script with id {}", thingName, id);
539 public void onConnect(String deviceIp, boolean connected) {
540 if (thing == null && thingTable != null) {
541 thing = thingTable.getThing(deviceIp);
542 logger.debug("{}: Get thing from thingTable", thingName);
547 public void onNotifyStatus(Shelly2RpcNotifyStatus message) {
548 logger.debug("{}: NotifyStatus update received: {}", thingName, gson.toJson(message));
550 ShellyThingInterface t = thing;
552 logger.debug("{}: No matching thing on NotifyStatus for {}, ignore (src={}, dst={}, discovery={})",
553 thingName, thingName, message.src, message.dst, discovery);
556 if (t.isStopping()) {
557 logger.debug("{}: Thing is shutting down, ignore WebSocket message", thingName);
560 if (!t.isThingOnline() && t.getThingStatusDetail() != ThingStatusDetail.CONFIGURATION_PENDING) {
561 logger.debug("{}: Thing is not in online state/connectable, ignore NotifyStatus", thingName);
565 getThing().incProtMessages();
566 if (message.error != null) {
567 if (message.error.code == HttpStatus.UNAUTHORIZED_401 && !getString(message.error.message).isEmpty()) {
568 // Save nonce for notification
569 Shelly2AuthChallenge auth = gson.fromJson(message.error.message, Shelly2AuthChallenge.class);
570 if (auth != null && auth.realm == null) {
571 logger.debug("{}: Authentication data received: {}", thingName, message.error.message);
575 logger.debug("{}: Error status received - {} {}", thingName, message.error.code,
576 message.error.message);
581 Shelly2NotifyStatus params = message.params;
582 if (params != null) {
583 if (getThing().getThingStatusDetail() != ThingStatusDetail.FIRMWARE_UPDATING) {
584 getThing().setThingOnline();
587 boolean updated = false;
588 ShellyDeviceProfile profile = getProfile();
589 ShellySettingsStatus status = profile.status;
590 if (params.sys != null) {
591 if (getBool(params.sys.restartRequired)) {
592 logger.warn("{}: Device requires restart to activate changes", thingName);
594 status.uptime = params.sys.uptime;
596 status.temperature = SHELLY_API_INVTEMP; // mark invalid
597 updated |= fillDeviceStatus(status, message.params, true);
598 if (getDouble(status.temperature) == SHELLY_API_INVTEMP) {
599 // no device temp available
600 status.temperature = null;
602 updated |= updateChannel(CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_ITEMP,
603 toQuantityType(getDouble(status.tmp.tC), DIGITS_NONE, SIUnits.CELSIUS));
606 profile.status = status;
608 getThing().restartWatchdog();
611 } catch (ShellyApiException e) {
612 logger.debug("{}: Unable to process status update", thingName, e);
618 public void onNotifyEvent(Shelly2RpcNotifyEvent message) {
620 logger.debug("{}: NotifyEvent received: {}", thingName, gson.toJson(message));
621 ShellyDeviceProfile profile = getProfile();
623 getThing().incProtMessages();
624 getThing().restartWatchdog();
626 for (Shelly2NotifyEvent e : message.params.events) {
628 case SHELLY2_EVENT_BTNUP:
629 case SHELLY2_EVENT_BTNDOWN:
630 String bgroup = getProfile().getInputGroup(e.id);
631 updateChannel(bgroup, CHANNEL_INPUT + profile.getInputSuffix(e.id),
632 getOnOff(SHELLY2_EVENT_BTNDOWN.equals(getString(e.event))));
633 getThing().triggerButton(profile.getInputGroup(e.id), e.id,
634 mapValue(MAP_INPUT_EVENT_ID, e.event));
637 case SHELLY2_EVENT_1PUSH:
638 case SHELLY2_EVENT_2PUSH:
639 case SHELLY2_EVENT_3PUSH:
640 case SHELLY2_EVENT_LPUSH:
641 case SHELLY2_EVENT_SLPUSH:
642 case SHELLY2_EVENT_LSPUSH:
643 if (e.id < profile.numInputs) {
644 ShellyInputState input = relayStatus.inputs.get(e.id);
645 input.event = getString(MAP_INPUT_EVENT_TYPE.get(e.event));
646 input.eventCount = getInteger(input.eventCount) + 1;
647 relayStatus.inputs.set(e.id, input);
648 profile.status.inputs.set(e.id, input);
650 String group = getProfile().getInputGroup(e.id);
651 updateChannel(group, CHANNEL_STATUS_EVENTTYPE + profile.getInputSuffix(e.id),
652 getStringType(input.event));
653 updateChannel(group, CHANNEL_STATUS_EVENTCOUNT + profile.getInputSuffix(e.id),
654 getDecimal(input.eventCount));
655 getThing().triggerButton(profile.getInputGroup(e.id), e.id,
656 mapValue(MAP_INPUT_EVENT_ID, e.event));
659 case SHELLY2_EVENT_CFGCHANGED:
660 logger.debug("{}: Configuration update detected, re-initialize", thingName);
661 getThing().requestUpdates(1, true); // refresh config
664 case SHELLY2_EVENT_OTASTART:
665 logger.debug("{}: Firmware update started: {}", thingName, getString(e.msg));
666 getThing().postEvent(e.event, true);
667 getThing().setThingOffline(ThingStatusDetail.FIRMWARE_UPDATING,
668 "offline.status-error-fwupgrade");
670 case SHELLY2_EVENT_OTAPROGRESS:
671 logger.debug("{}: Firmware update in progress: {}", thingName, getString(e.msg));
672 getThing().postEvent(e.event, false);
674 case SHELLY2_EVENT_OTADONE:
675 logger.debug("{}: Firmware update completed: {}", thingName, getString(e.msg));
676 getThing().setThingOffline(ThingStatusDetail.CONFIGURATION_PENDING,
677 "offline.status-error-restarted");
678 getThing().requestUpdates(1, true); // refresh config
680 case SHELLY2_EVENT_SLEEP:
681 logger.debug("{}: Connection terminated, e.g. device in sleep mode", thingName);
683 case SHELLY2_EVENT_WIFICONNFAILED:
684 logger.debug("{}: WiFi connect failed, check setup, reason {}", thingName,
685 getInteger(e.reason));
686 getThing().postEvent(e.event, false);
688 case SHELLY2_EVENT_WIFIDISCONNECTED:
689 logger.debug("{}: WiFi disconnected, reason {}", thingName, getInteger(e.reason));
690 getThing().postEvent(e.event, false);
693 logger.debug("{}: Event {} was not handled", thingName, e.event);
696 } catch (ShellyApiException e) {
697 logger.debug("{}: Unable to process event", thingName, e);
703 public void onMessage(String message) {
704 logger.debug("{}: Unexpected RPC message received: {}", thingName, message);
709 public void onClose(int statusCode, String description) {
711 String reason = getString(description);
712 logger.debug("{}: WebSocket connection closed, status = {}/{}", thingName, statusCode, reason);
713 if ("Bye".equalsIgnoreCase(reason)) {
714 logger.debug("{}: Device went to sleep mode", thingName);
715 } else if (statusCode == StatusCode.ABNORMAL && !discovery && getProfile().alwaysOn) {
716 // e.g. device rebooted
717 thingOffline("WebSocket connection closed abnormal");
719 } catch (ShellyApiException e) {
720 logger.debug("{}: Exception on onClose()", thingName, e);
726 public void onError(Throwable cause) {
727 logger.debug("{}: WebSocket error: {}", thingName, cause.getMessage());
728 if (thing != null && thing.getProfile().alwaysOn) {
729 thingOffline("WebSocket error");
733 private void thingOffline(String reason) {
734 if (thing != null) { // do not reinit of battery powered devices with sleep mode
735 thing.setThingOffline(ThingStatusDetail.COMMUNICATION_ERROR, "offline.status-error-unexpected-error",
741 public ShellySettingsDevice getDeviceInfo() throws ShellyApiException {
742 Shelly2DeviceSettings device = callApi("/shelly", Shelly2DeviceSettings.class);
743 ShellySettingsDevice info = new ShellySettingsDevice();
744 info.hostname = getString(device.id);
745 info.name = getString(device.name);
746 info.fw = getString(device.fw);
747 info.type = getString(device.model);
748 info.mac = getString(device.mac);
749 info.auth = getBool(device.auth);
750 info.gen = getInteger(device.gen);
751 info.mode = mapValue(MAP_PROFILE, device.profile);
756 public ShellySettingsStatus getStatus() throws ShellyApiException {
757 ShellyDeviceProfile profile = getProfile();
758 ShellySettingsStatus status = profile.status;
759 Shelly2DeviceStatusResult ds = apiRequest(SHELLYRPC_METHOD_GETSTATUS, null, Shelly2DeviceStatusResult.class);
760 status.time = ds.sys.time;
761 status.uptime = ds.sys.uptime;
762 status.cloud.connected = getBool(ds.cloud.connected);
763 status.mqtt.connected = getBool(ds.mqtt.connected);
764 status.wifiSta.ssid = getString(ds.wifi.ssid);
765 status.wifiSta.enabled = !status.wifiSta.ssid.isEmpty();
766 status.wifiSta.ip = getString(ds.wifi.staIP);
767 status.wifiSta.rssi = getInteger(ds.wifi.rssi);
768 status.fsFree = ds.sys.fsFree;
769 status.fsSize = ds.sys.fsSize;
770 status.discoverable = getBool(profile.settings.discoverable);
772 if (ds.sys.wakeupPeriod != null) {
773 profile.settings.sleepMode.period = ds.sys.wakeupPeriod / 60;
776 if (ds.sys.availableUpdates != null) {
777 status.update.hasUpdate = ds.sys.availableUpdates.stable != null;
778 if (ds.sys.availableUpdates.stable != null) {
779 status.update.newVersion = ShellyDeviceProfile
780 .extractFwVersion(getString(ds.sys.availableUpdates.stable.version));
781 status.hasUpdate = new ShellyVersionDTO().compare(profile.fwVersion, status.update.newVersion) < 0;
783 if (ds.sys.availableUpdates.beta != null) {
784 status.update.betaVersion = ShellyDeviceProfile
785 .extractFwVersion(getString(ds.sys.availableUpdates.beta.version));
786 status.hasUpdate = new ShellyVersionDTO().compare(profile.fwVersion, status.update.betaVersion) < 0;
790 if (ds.sys.wakeUpReason != null && ds.sys.wakeUpReason.boot != null)
793 List<Object> values = new ArrayList<>();
794 String boot = getString(ds.sys.wakeUpReason.boot);
795 String cause = getString(ds.sys.wakeUpReason.cause);
797 // Index 0 is aggregated status, 1 boot, 2 cause
798 String reason = boot.equals(SHELLY2_WAKEUPO_BOOT_RESTART) ? ALARM_TYPE_RESTARTED : cause;
800 values.add(ds.sys.wakeUpReason.boot);
801 values.add(ds.sys.wakeUpReason.cause);
802 getThing().updateWakeupReason(values);
805 fillDeviceStatus(status, ds, false);
806 if (getBool(profile.settings.rangeExtender)) {
808 // Get List of AP clients
809 profile.status.rangeExtender = apiRequest(SHELLYRPC_METHOD_WIFILISTAPCLIENTS, null,
810 Shelly2APClientList.class);
811 logger.debug("{}: Range extender is enabled, {} clients connected", thingName,
812 profile.status.rangeExtender.apClients.size());
813 } catch (ShellyApiException e) {
814 logger.debug("{}: Range extender is enabled, but unable to read AP client list", thingName, e);
815 profile.settings.rangeExtender = false;
823 public void setSleepTime(int value) throws ShellyApiException {
827 public ShellyStatusRelay getRelayStatus(int relayIndex) throws ShellyApiException {
828 if (getProfile().status.wifiSta.ssid == null) {
829 // Update status when not yet initialized
836 public void setRelayTurn(int id, String turnMode) throws ShellyApiException {
837 ShellyDeviceProfile profile = getProfile();
839 if (profile.settings.relays != null) {
840 Integer rid = profile.settings.relays.get(id).id;
845 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams();
847 params.on = SHELLY_API_ON.equals(turnMode);
848 apiRequest(SHELLYRPC_METHOD_SWITCH_SET, params, String.class);
852 public ShellyRollerStatus getRollerStatus(int rollerIndex) throws ShellyApiException {
853 if (rollerIndex < rollerStatus.size()) {
854 return rollerStatus.get(rollerIndex);
856 throw new IllegalArgumentException("Invalid rollerIndex on getRollerStatus");
860 public void setRollerTurn(int relayIndex, String turnMode) throws ShellyApiException {
861 String operation = "";
863 case SHELLY_ALWD_ROLLER_TURN_OPEN:
864 operation = SHELLY2_COVER_CMD_OPEN;
866 case SHELLY_ALWD_ROLLER_TURN_CLOSE:
867 operation = SHELLY2_COVER_CMD_CLOSE;
869 case SHELLY_ALWD_ROLLER_TURN_STOP:
870 operation = SHELLY2_COVER_CMD_STOP;
874 apiRequest(new Shelly2RpcRequest().withMethod("Cover." + operation).withId(relayIndex));
878 public void setRollerPos(int relayIndex, int position) throws ShellyApiException {
880 new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_COVER_SETPOS).withId(relayIndex).withPos(position));
884 public ShellyStatusLight getLightStatus() throws ShellyApiException {
885 throw new ShellyApiException("API call not implemented");
889 public ShellyShortLightStatus getLightStatus(int index) throws ShellyApiException {
890 ShellyShortLightStatus status = new ShellyShortLightStatus();
891 Shelly2DeviceStatusLight ls = apiRequest(
892 new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_LIGHT_STATUS).withId(index),
893 Shelly2DeviceStatusLight.class);
894 status.ison = ls.output;
895 status.hasTimer = ls.timerStartedAt != null;
896 status.timerDuration = getDuration(ls.timerStartedAt, ls.timerDuration);
897 if (ls.brightness != null) {
898 status.brightness = ls.brightness.intValue();
904 public void setBrightness(int id, int brightness, boolean autoOn) throws ShellyApiException {
905 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams();
907 params.brightness = brightness;
908 params.on = brightness > 0;
909 apiRequest(SHELLYRPC_METHOD_LIGHT_SET, params, String.class);
913 public ShellyShortLightStatus setLightTurn(int id, String turnMode) throws ShellyApiException {
914 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams();
916 params.on = turnMode.equals(SHELLY_API_ON);
917 apiRequest(SHELLYRPC_METHOD_LIGHT_SET, params, String.class);
918 return getLightStatus(id);
922 public ShellyStatusSensor getSensorStatus() throws ShellyApiException {
927 public void setAutoTimer(int index, String timerName, double value) throws ShellyApiException {
928 ShellyDeviceProfile profile = getProfile();
929 boolean isLight = profile.isLight || profile.isDimmer;
930 String method = isLight ? SHELLYRPC_METHOD_LIGHT_SETCONFIG : SHELLYRPC_METHOD_SWITCH_SETCONFIG;
931 String component = isLight ? "Light" : "Switch";
932 Shelly2RpcRequest req = new Shelly2RpcRequest().withMethod(method).withId(index);
933 req.params.withConfig();
934 req.params.config.name = component + index;
935 if (timerName.equals(SHELLY_TIMER_AUTOON)) {
936 req.params.config.autoOn = value > 0;
937 req.params.config.autoOnDelay = value;
939 req.params.config.autoOff = value > 0;
940 req.params.config.autoOffDelay = value;
946 public void setLedStatus(String ledName, boolean value) throws ShellyApiException {
947 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams().withConfig();
949 if (ledName.equals(SHELLY_LED_STATUS_DISABLE)) {
950 params.config.sysLedEnable = value;
951 } else if (ledName.equals(SHELLY_LED_POWER_DISABLE)) {
952 params.config.powerLed = value ? SHELLY2_POWERLED_OFF : SHELLY2_POWERLED_MATCH;
954 throw new ShellyApiException("API call not implemented for this LED type");
956 apiRequest(SHELLYRPC_METHOD_LED_SETCONFIG, params, Shelly2WsConfigResult.class);
960 public void resetMeterTotal(int id) throws ShellyApiException {
961 apiRequest(new Shelly2RpcRequest()
962 .withMethod(getProfile().is3EM ? SHELLYRPC_METHOD_EMDATARESET : SHELLYRPC_METHOD_EM1DATARESET)
967 public void muteSmokeAlarm(int index) throws ShellyApiException {
968 apiRequest(new Shelly2RpcRequest().withMethod(SHELLYRPC_METHOD_SMOKE_MUTE).withId(index));
972 public ShellySettingsLogin getLoginSettings() throws ShellyApiException {
973 return new ShellySettingsLogin();
977 public ShellySettingsLogin setLoginCredentials(String user, String password) throws ShellyApiException {
978 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams();
979 params.user = "admin";
980 params.realm = config.serviceName;
981 params.ha1 = sha256(params.user + ":" + params.realm + ":" + password);
982 apiRequest(SHELLYRPC_METHOD_AUTHSET, params, String.class);
984 ShellySettingsLogin res = new ShellySettingsLogin();
986 res.username = params.user;
987 res.password = password;
988 return new ShellySettingsLogin();
992 public boolean setWiFiRangeExtender(boolean enable) throws ShellyApiException {
993 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams().withConfig();
994 params.config.ap = new Shelly2DeviceConfigAp();
995 params.config.ap.rangeExtender = new Shelly2DeviceConfigApRE();
996 params.config.ap.rangeExtender.enable = enable;
997 Shelly2WsConfigResult res = apiRequest(SHELLYRPC_METHOD_WIFISETCONG, params, Shelly2WsConfigResult.class);
998 return res.restartRequired;
1002 public boolean setEthernet(boolean enable) throws ShellyApiException {
1003 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams().withConfig();
1004 params.config.enable = enable;
1005 Shelly2WsConfigResult res = apiRequest(SHELLYRPC_METHOD_ETHSETCONG, params, Shelly2WsConfigResult.class);
1006 return res.restartRequired;
1010 public boolean setBluetooth(boolean enable) throws ShellyApiException {
1011 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams().withConfig();
1012 params.config.enable = enable;
1013 Shelly2WsConfigResult res = apiRequest(SHELLYRPC_METHOD_BLESETCONG, params, Shelly2WsConfigResult.class);
1014 return res.restartRequired;
1018 public String deviceReboot() throws ShellyApiException {
1019 return apiRequest(SHELLYRPC_METHOD_REBOOT, null, String.class);
1023 public String factoryReset() throws ShellyApiException {
1024 return apiRequest(SHELLYRPC_METHOD_RESET, null, String.class);
1028 public ShellyOtaCheckResult checkForUpdate() throws ShellyApiException {
1029 Shelly2DeviceStatusSysAvlUpdate status = apiRequest(SHELLYRPC_METHOD_CHECKUPD, null,
1030 Shelly2DeviceStatusSysAvlUpdate.class);
1031 ShellyOtaCheckResult result = new ShellyOtaCheckResult();
1032 result.status = status.stable != null || status.beta != null ? "new" : "ok";
1037 public ShellySettingsUpdate firmwareUpdate(String fwurl) throws ShellyApiException {
1038 ShellySettingsUpdate res = new ShellySettingsUpdate();
1039 boolean prod = fwurl.contains("update");
1040 boolean beta = fwurl.contains("beta");
1042 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams();
1044 params.stage = prod ? "stable" : "beta";
1048 apiRequest(SHELLYRPC_METHOD_UPDATE, params, String.class);
1049 res.status = "Update initiated";
1054 public String setCloud(boolean enable) throws ShellyApiException {
1055 Shelly2RpcRequestParams params = new Shelly2RpcRequestParams().withConfig();
1056 params.config.enable = enable;
1057 Shelly2WsConfigResult res = apiRequest(SHELLYRPC_METHOD_CLOUDSET, params, Shelly2WsConfigResult.class);
1058 return res.restartRequired ? "restart required" : "ok";
1062 public String setDebug(boolean enabled) throws ShellyApiException {
1067 public String getDebugLog(String id) throws ShellyApiException {
1068 return ""; // Gen2 uses WS to publish debug log
1072 * The following API calls are not yet relevant, because currently there a no Plus/Pro (Gen2) devices of those
1073 * categories (e.g. bulbs)
1077 public void setLightParm(int lightIndex, String parm, String value) throws ShellyApiException {
1078 throw new ShellyApiException("API call not implemented");
1082 public void setLightParms(int lightIndex, Map<String, String> parameters) throws ShellyApiException {
1083 throw new ShellyApiException("API call not implemented");
1087 public void setLightMode(String mode) throws ShellyApiException {
1088 throw new ShellyApiException("API call not implemented");
1092 public void setValveMode(int valveId, boolean auto) throws ShellyApiException {
1093 throw new ShellyApiException("API call not implemented");
1097 public void setValvePosition(int valveId, double value) throws ShellyApiException {
1098 throw new ShellyApiException("API call not implemented");
1102 public void setValveTemperature(int valveId, int value) throws ShellyApiException {
1103 throw new ShellyApiException("API call not implemented");
1107 public void setValveProfile(int valveId, int value) throws ShellyApiException {
1108 throw new ShellyApiException("API call not implemented");
1112 public void setValveBoostTime(int valveId, int value) throws ShellyApiException {
1113 throw new ShellyApiException("API call not implemented");
1117 public void startValveBoost(int valveId, int value) throws ShellyApiException {
1118 throw new ShellyApiException("API call not implemented");
1122 public String resetStaCache() throws ShellyApiException {
1123 throw new ShellyApiException("API call not implemented");
1127 public void setActionURLs() throws ShellyApiException {
1128 // not relevant for Gen2
1132 public ShellySettingsLogin setCoIoTPeer(String peer) throws ShellyApiException {
1133 // not relevant for Gen2
1134 return new ShellySettingsLogin();
1138 public String getCoIoTDescription() {
1139 return ""; // not relevant to Gen2
1143 public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
1144 throw new ShellyApiException("API call not implemented");
1148 public String setWiFiRecovery(boolean enable) throws ShellyApiException {
1149 return "failed"; // not supported by Gen2
1153 public String setApRoaming(boolean enable) throws ShellyApiException {
1154 return "false";// not supported by Gen2
1157 private void asyncApiRequest(String method) throws ShellyApiException {
1158 Shelly2RpcBaseMessage request = buildRequest(method, null);
1160 rpcSocket.sendMessage(gson.toJson(request)); // submit, result wull be async
1163 @SuppressWarnings("null")
1164 public <T> T apiRequest(String method, @Nullable Object params, Class<T> classOfT) throws ShellyApiException {
1166 Shelly2RpcBaseMessage req = buildRequest(method, params);
1168 reconnect(); // make sure WS is connected
1169 json = rpcPost(gson.toJson(req));
1170 } catch (ShellyApiException e) {
1171 ShellyApiResult res = e.getApiResult();
1172 String auth = getString(res.authChallenge);
1173 if (res.isHttpAccessUnauthorized() && !auth.isEmpty()) {
1174 String[] options = auth.split(",");
1175 authInfo = new Shelly2AuthChallenge();
1176 for (String o : options) {
1177 String key = substringBefore(o, "=").stripLeading().trim();
1178 String value = substringAfter(o, "=").replace("\"", "").trim();
1181 authInfo.authType = SHELLY2_AUTHTTYPE_DIGEST;
1184 authInfo.realm = value;
1187 // authInfo.nonce = Long.parseLong(value, 16);
1188 authInfo.nonce = value;
1191 authInfo.algorithm = value;
1195 json = rpcPost(gson.toJson(req));
1200 Shelly2RpcBaseMessage response = gson.fromJson(json, Shelly2RpcBaseMessage.class);
1201 if (response == null) {
1202 throw new IllegalArgumentException("Unable to cover API result to obhect");
1204 if (response.result != null) {
1205 // return sub element result as requested class type
1206 json = gson.toJson(gson.fromJson(json, Shelly2RpcBaseMessage.class).result);
1207 boolean isString = response.result instanceof String;
1208 return fromJson(gson, isString && "null".equalsIgnoreCase(((String) response.result)) ? "{}" : json,
1211 // return direct format
1212 return gson.fromJson(json, classOfT == String.class ? Shelly2RpcBaseMessage.class : classOfT);
1216 public <T> T apiRequest(Shelly2RpcRequest request, Class<T> classOfT) throws ShellyApiException {
1217 return apiRequest(request.method, request.params, classOfT);
1220 public void apiRequest(Shelly2RpcRequest request) throws ShellyApiException {
1221 apiRequest(request.method, request.params, Shelly2RpcBaseMessage.class);
1224 private String rpcPost(String postData) throws ShellyApiException {
1225 return httpPost(authInfo, postData);
1228 private void reconnect() throws ShellyApiException {
1229 if (!rpcSocket.isConnected()) {
1230 logger.debug("{}: Connect Rpc Socket (discovery = {})", thingName, discovery);
1231 rpcSocket.connect();
1235 private void disconnect() {
1236 if (rpcSocket.isConnected()) {
1237 logger.debug("{}: Disconnect Rpc Socket", thingName);
1239 rpcSocket.disconnect();
1242 public Shelly2RpctInterface getRpcHandler() {
1247 public void close() {
1248 if (initialized || rpcSocket.isConnected()) {
1249 logger.debug("{}: Closing Rpc API (socket is {}, discovery={})", thingName,
1250 rpcSocket.isConnected() ? "connected" : "disconnected", discovery);
1253 initialized = false;
1256 private void incProtErrors() {
1257 if (thing != null) {
1258 thing.incProtErrors();