]> git.basschouten.com Git - openhab-addons.git/blob
040cd83675741e1d8cbf3903716c90e4a4a1ca7b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.homematic.internal.communicator.client;
14
15 import static org.openhab.binding.homematic.internal.HomematicBindingConstants.*;
16
17 import java.io.IOException;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22
23 import org.apache.commons.lang.StringUtils;
24 import org.openhab.binding.homematic.internal.HomematicBindingConstants;
25 import org.openhab.binding.homematic.internal.common.HomematicConfig;
26 import org.openhab.binding.homematic.internal.communicator.message.RpcRequest;
27 import org.openhab.binding.homematic.internal.communicator.parser.GetAllScriptsParser;
28 import org.openhab.binding.homematic.internal.communicator.parser.GetAllSystemVariablesParser;
29 import org.openhab.binding.homematic.internal.communicator.parser.GetDeviceDescriptionParser;
30 import org.openhab.binding.homematic.internal.communicator.parser.GetParamsetDescriptionParser;
31 import org.openhab.binding.homematic.internal.communicator.parser.GetParamsetParser;
32 import org.openhab.binding.homematic.internal.communicator.parser.GetValueParser;
33 import org.openhab.binding.homematic.internal.communicator.parser.HomegearLoadDeviceNamesParser;
34 import org.openhab.binding.homematic.internal.communicator.parser.ListBidcosInterfacesParser;
35 import org.openhab.binding.homematic.internal.communicator.parser.ListDevicesParser;
36 import org.openhab.binding.homematic.internal.communicator.parser.RssiInfoParser;
37 import org.openhab.binding.homematic.internal.model.HmChannel;
38 import org.openhab.binding.homematic.internal.model.HmDatapoint;
39 import org.openhab.binding.homematic.internal.model.HmDevice;
40 import org.openhab.binding.homematic.internal.model.HmGatewayInfo;
41 import org.openhab.binding.homematic.internal.model.HmInterface;
42 import org.openhab.binding.homematic.internal.model.HmParamsetType;
43 import org.openhab.binding.homematic.internal.model.HmRssiInfo;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Client implementation for sending messages via BIN-RPC to a Homematic gateway.
49  *
50  * @author Gerhard Riegler - Initial contribution
51  */
52 public abstract class RpcClient<T> {
53     private final Logger logger = LoggerFactory.getLogger(RpcClient.class);
54     protected static final int MAX_RPC_RETRY = 3;
55     protected static final int RESP_BUFFER_SIZE = 8192;
56
57     protected HomematicConfig config;
58
59     public RpcClient(HomematicConfig config) {
60         this.config = config;
61     }
62
63     /**
64      * Disposes the client.
65      */
66     public abstract void dispose();
67
68     /**
69      * Returns a RpcRequest for this client.
70      */
71     protected abstract RpcRequest<T> createRpcRequest(String methodName);
72
73     /**
74      * Returns the callback url for this client.
75      */
76     protected abstract String getRpcCallbackUrl();
77
78     /**
79      * Sends the RPC message to the gateway.
80      */
81     protected abstract Object[] sendMessage(int port, RpcRequest<T> request) throws IOException;
82
83     /**
84      * Register a callback for the specified interface where the Homematic gateway can send its events.
85      */
86     public void init(HmInterface hmInterface, String clientId) throws IOException {
87         RpcRequest<T> request = createRpcRequest("init");
88         request.addArg(getRpcCallbackUrl());
89         request.addArg(clientId);
90         if (config.getGatewayInfo().isHomegear()) {
91             request.addArg(new Integer(0x22));
92         }
93         sendMessage(config.getRpcPort(hmInterface), request);
94     }
95
96     /**
97      * Release a callback for the specified interface.
98      */
99     public void release(HmInterface hmInterface) throws IOException {
100         RpcRequest<T> request = createRpcRequest("init");
101         request.addArg(getRpcCallbackUrl());
102         sendMessage(config.getRpcPort(hmInterface), request);
103     }
104
105     /**
106      * Sends a ping to the specified interface.
107      */
108     public void ping(HmInterface hmInterface, String callerId) throws IOException {
109         RpcRequest<T> request = createRpcRequest("ping");
110         request.addArg(callerId);
111         sendMessage(config.getRpcPort(hmInterface), request);
112     }
113
114     /**
115      * Returns the info of all BidCos interfaces available on the gateway.
116      */
117     public ListBidcosInterfacesParser listBidcosInterfaces(HmInterface hmInterface) throws IOException {
118         RpcRequest<T> request = createRpcRequest("listBidcosInterfaces");
119         return new ListBidcosInterfacesParser().parse(sendMessage(config.getRpcPort(hmInterface), request));
120     }
121
122     /**
123      * Returns some infos of the gateway.
124      */
125     private GetDeviceDescriptionParser getDeviceDescription(HmInterface hmInterface) throws IOException {
126         RpcRequest<T> request = createRpcRequest("getDeviceDescription");
127         request.addArg("BidCoS-RF");
128         return new GetDeviceDescriptionParser().parse(sendMessage(config.getRpcPort(hmInterface), request));
129     }
130
131     /**
132      * Returns all variable metadata and values from a Homegear gateway.
133      */
134     public void getAllSystemVariables(HmChannel channel) throws IOException {
135         RpcRequest<T> request = createRpcRequest("getAllSystemVariables");
136         new GetAllSystemVariablesParser(channel).parse(sendMessage(config.getRpcPort(channel), request));
137     }
138
139     /**
140      * Loads all device names from a Homegear gateway.
141      */
142     public void loadDeviceNames(HmInterface hmInterface, Collection<HmDevice> devices) throws IOException {
143         RpcRequest<T> request = createRpcRequest("getDeviceInfo");
144         new HomegearLoadDeviceNamesParser(devices).parse(sendMessage(config.getRpcPort(hmInterface), request));
145     }
146
147     /**
148      * Returns true, if the interface is available on the gateway.
149      */
150     public void checkInterface(HmInterface hmInterface) throws IOException {
151         RpcRequest<T> request = createRpcRequest("init");
152         request.addArg("http://openhab.validation:1000");
153         sendMessage(config.getRpcPort(hmInterface), request);
154     }
155
156     /**
157      * Returns all script metadata from a Homegear gateway.
158      */
159     public void getAllScripts(HmChannel channel) throws IOException {
160         RpcRequest<T> request = createRpcRequest("getAllScripts");
161         new GetAllScriptsParser(channel).parse(sendMessage(config.getRpcPort(channel), request));
162     }
163
164     /**
165      * Returns all device and channel metadata.
166      */
167     public Collection<HmDevice> listDevices(HmInterface hmInterface) throws IOException {
168         RpcRequest<T> request = createRpcRequest("listDevices");
169         return new ListDevicesParser(hmInterface, config).parse(sendMessage(config.getRpcPort(hmInterface), request));
170     }
171
172     /**
173      * Loads all datapoint metadata into the given channel.
174      */
175     public void addChannelDatapoints(HmChannel channel, HmParamsetType paramsetType) throws IOException {
176         if (isConfigurationChannel(channel) && paramsetType != HmParamsetType.MASTER) {
177             // The configuration channel only has a MASTER Paramset, so there is nothing to load
178             return;
179         }
180         RpcRequest<T> request = createRpcRequest("getParamsetDescription");
181         request.addArg(getRpcAddress(channel.getDevice().getAddress()) + getChannelSuffix(channel));
182         request.addArg(paramsetType.toString());
183         new GetParamsetDescriptionParser(channel, paramsetType).parse(sendMessage(config.getRpcPort(channel), request));
184     }
185
186     /**
187      * Sets all datapoint values for the given channel.
188      */
189     public void setChannelDatapointValues(HmChannel channel, HmParamsetType paramsetType) throws IOException {
190         if (isConfigurationChannel(channel) && paramsetType != HmParamsetType.MASTER) {
191             // The configuration channel only has a MASTER Paramset, so there is nothing to load
192             return;
193         }
194
195         RpcRequest<T> request = createRpcRequest("getParamset");
196         request.addArg(getRpcAddress(channel.getDevice().getAddress()) + getChannelSuffix(channel));
197         request.addArg(paramsetType.toString());
198         if (channel.getDevice().getHmInterface() == HmInterface.CUXD && paramsetType == HmParamsetType.VALUES) {
199             setChannelDatapointValues(channel);
200         } else {
201             try {
202                 new GetParamsetParser(channel, paramsetType).parse(sendMessage(config.getRpcPort(channel), request));
203             } catch (UnknownRpcFailureException ex) {
204                 if (paramsetType == HmParamsetType.VALUES) {
205                     logger.debug(
206                             "RpcResponse unknown RPC failure (-1 Failure), fetching values with another API method for device: {}, channel: {}, paramset: {}",
207                             channel.getDevice().getAddress(), channel.getNumber(), paramsetType);
208                     setChannelDatapointValues(channel);
209                 } else {
210                     throw ex;
211                 }
212             }
213         }
214     }
215
216     /**
217      * Reads all VALUES datapoints individually, fallback method if setChannelDatapointValues throws a -1 Failure
218      * exception.
219      */
220     private void setChannelDatapointValues(HmChannel channel) throws IOException {
221         for (HmDatapoint dp : channel.getDatapoints()) {
222             getDatapointValue(dp);
223         }
224     }
225
226     /**
227      * Tries to identify the gateway and returns the GatewayInfo.
228      */
229     public HmGatewayInfo getGatewayInfo(String id) throws IOException {
230         boolean isHomegear = false;
231         GetDeviceDescriptionParser ddParser;
232         ListBidcosInterfacesParser biParser;
233
234         try {
235             ddParser = getDeviceDescription(HmInterface.RF);
236             isHomegear = StringUtils.equalsIgnoreCase(ddParser.getType(), "Homegear");
237         } catch (IOException ex) {
238             // can't load gateway infos via RF interface
239             ddParser = new GetDeviceDescriptionParser();
240         }
241
242         try {
243             biParser = listBidcosInterfaces(HmInterface.RF);
244         } catch (IOException ex) {
245             biParser = listBidcosInterfaces(HmInterface.HMIP);
246         }
247
248         HmGatewayInfo gatewayInfo = new HmGatewayInfo();
249         gatewayInfo.setAddress(biParser.getGatewayAddress());
250         if (isHomegear) {
251             gatewayInfo.setId(HmGatewayInfo.ID_HOMEGEAR);
252             gatewayInfo.setType(ddParser.getType());
253             gatewayInfo.setFirmware(ddParser.getFirmware());
254         } else if ((StringUtils.startsWithIgnoreCase(biParser.getType(), "CCU")
255                 || StringUtils.startsWithIgnoreCase(biParser.getType(), "HMIP_CCU")
256                 || StringUtils.startsWithIgnoreCase(ddParser.getType(), "HM-RCV-50") || config.isCCUType())
257                 && !config.isNoCCUType()) {
258             gatewayInfo.setId(HmGatewayInfo.ID_CCU);
259             String type = StringUtils.isBlank(biParser.getType()) ? "CCU" : biParser.getType();
260             gatewayInfo.setType(type);
261             gatewayInfo.setFirmware(ddParser.getFirmware() != null ? ddParser.getFirmware() : biParser.getFirmware());
262         } else {
263             gatewayInfo.setId(HmGatewayInfo.ID_DEFAULT);
264             gatewayInfo.setType(biParser.getType());
265             gatewayInfo.setFirmware(biParser.getFirmware());
266         }
267
268         if (gatewayInfo.isCCU() || config.hasRfPort()) {
269             gatewayInfo.setRfInterface(hasInterface(HmInterface.RF, id));
270         }
271
272         if (gatewayInfo.isCCU() || config.hasWiredPort()) {
273             gatewayInfo.setWiredInterface(hasInterface(HmInterface.WIRED, id));
274         }
275
276         if (gatewayInfo.isCCU() || config.hasHmIpPort()) {
277             gatewayInfo.setHmipInterface(hasInterface(HmInterface.HMIP, id));
278         }
279
280         if (gatewayInfo.isCCU() || config.hasCuxdPort()) {
281             gatewayInfo.setCuxdInterface(hasInterface(HmInterface.CUXD, id));
282         }
283
284         if (gatewayInfo.isCCU() || config.hasGroupPort()) {
285             gatewayInfo.setGroupInterface(hasInterface(HmInterface.GROUP, id));
286         }
287
288         return gatewayInfo;
289     }
290
291     /**
292      * Returns true, if a connection is possible with the given interface.
293      */
294     private boolean hasInterface(HmInterface hmInterface, String id) throws IOException {
295         try {
296             checkInterface(hmInterface);
297             return true;
298         } catch (IOException ex) {
299             logger.info("Interface '{}' on gateway '{}' not available, disabling support", hmInterface, id);
300             return false;
301         }
302     }
303
304     /**
305      * Sets the value of the datapoint using the provided rx transmission mode.
306      *
307      * @param dp The datapoint to set
308      * @param value The new value to set on the datapoint
309      * @param rxMode The rx mode to use for the transmission of the datapoint value
310      *            ({@link HomematicBindingConstants#RX_BURST_MODE "BURST"} for burst mode,
311      *            {@link HomematicBindingConstants#RX_WAKEUP_MODE "WAKEUP"} for wakeup mode, or null for the default
312      *            mode)
313      */
314     public void setDatapointValue(HmDatapoint dp, Object value, String rxMode) throws IOException {
315         if (dp.isIntegerType() && value instanceof Double) {
316             value = ((Number) value).intValue();
317         }
318
319         RpcRequest<T> request;
320         if (HmParamsetType.VALUES == dp.getParamsetType()) {
321             request = createRpcRequest("setValue");
322             request.addArg(getRpcAddress(dp.getChannel().getDevice().getAddress()) + getChannelSuffix(dp.getChannel()));
323             request.addArg(dp.getName());
324             request.addArg(value);
325             configureRxMode(request, rxMode);
326         } else {
327             request = createRpcRequest("putParamset");
328             request.addArg(getRpcAddress(dp.getChannel().getDevice().getAddress()) + getChannelSuffix(dp.getChannel()));
329             request.addArg(HmParamsetType.MASTER.toString());
330             Map<String, Object> paramSet = new HashMap<>();
331             paramSet.put(dp.getName(), value);
332             request.addArg(paramSet);
333             configureRxMode(request, rxMode);
334         }
335         sendMessage(config.getRpcPort(dp.getChannel()), request);
336     }
337
338     protected void configureRxMode(RpcRequest<T> request, String rxMode) {
339         if (rxMode != null) {
340             if (RX_BURST_MODE.equals(rxMode) || RX_WAKEUP_MODE.equals(rxMode)) {
341                 request.addArg(rxMode);
342             }
343         }
344     }
345
346     /**
347      * Retrieves the value of a single {@link HmDatapoint} from the device. Can only be used for the paramset "VALUES".
348      *
349      * @param dp The HmDatapoint that shall be loaded
350      * @throws IOException If there is a problem while communicating to the gateway
351      */
352     public void getDatapointValue(HmDatapoint dp) throws IOException {
353         if (dp.isReadable() && !dp.isVirtual() && dp.getParamsetType() == HmParamsetType.VALUES) {
354             RpcRequest<T> request = createRpcRequest("getValue");
355             request.addArg(getRpcAddress(dp.getChannel().getDevice().getAddress()) + getChannelSuffix(dp.getChannel()));
356             request.addArg(dp.getName());
357             new GetValueParser(dp).parse(sendMessage(config.getRpcPort(dp.getChannel()), request));
358         }
359     }
360
361     /**
362      * Sets the value of a system variable on a Homegear gateway.
363      */
364     public void setSystemVariable(HmDatapoint dp, Object value) throws IOException {
365         RpcRequest<T> request = createRpcRequest("setSystemVariable");
366         request.addArg(dp.getInfo());
367         request.addArg(value);
368         sendMessage(config.getRpcPort(dp.getChannel()), request);
369     }
370
371     /**
372      * Executes a script on the Homegear gateway.
373      */
374     public void executeScript(HmDatapoint dp) throws IOException {
375         RpcRequest<T> request = createRpcRequest("runScript");
376         request.addArg(dp.getInfo());
377         sendMessage(config.getRpcPort(dp.getChannel()), request);
378     }
379
380     /**
381      * Enables/disables the install mode for given seconds.
382      *
383      * @param hmInterface specifies the interface to enable / disable install mode on
384      * @param enable if <i>true</i> it will be enabled, otherwise disabled
385      * @param seconds desired duration of install mode
386      * @throws IOException if RpcClient fails to propagate command
387      */
388     public void setInstallMode(HmInterface hmInterface, boolean enable, int seconds) throws IOException {
389         RpcRequest<T> request = createRpcRequest("setInstallMode");
390         request.addArg(enable);
391         request.addArg(seconds);
392         request.addArg(INSTALL_MODE_NORMAL);
393         logger.debug("Submitting setInstallMode(on={}, time={}, mode={}) ", enable, seconds, INSTALL_MODE_NORMAL);
394         sendMessage(config.getRpcPort(hmInterface), request);
395     }
396
397     /**
398      * Returns the remaining time of <i>install_mode==true</i>
399      *
400      * @param hmInterface specifies the interface on which install mode status is requested
401      * @return current duration in seconds that the controller will remain in install mode,
402      *         value of 0 means that the install mode is disabled
403      * @throws IOException if RpcClient fails to propagate command
404      */
405     public int getInstallMode(HmInterface hmInterface) throws IOException {
406         RpcRequest<T> request = createRpcRequest("getInstallMode");
407         Object[] result = sendMessage(config.getRpcPort(hmInterface), request);
408         if (logger.isTraceEnabled()) {
409             logger.trace(
410                     "Checking InstallMode: getInstallMode() request returned {} (remaining seconds in InstallMode=true)",
411                     result);
412         }
413         try {
414             return (int) result[0];
415         } catch (Exception cause) {
416             IOException wrappedException = new IOException(
417                     "Failed to request install mode from interface " + hmInterface);
418             wrappedException.initCause(cause);
419             throw wrappedException;
420         }
421     }
422
423     /**
424      * Deletes the device from the gateway.
425      */
426     public void deleteDevice(HmDevice device, int flags) throws IOException {
427         RpcRequest<T> request = createRpcRequest("deleteDevice");
428         request.addArg(device.getAddress());
429         request.addArg(flags);
430         sendMessage(config.getRpcPort(device.getHmInterface()), request);
431     }
432
433     /**
434      * Returns the rpc address from a device address, correctly handling groups.
435      */
436     private String getRpcAddress(String address) {
437         if (address != null && address.startsWith("T-")) {
438             address = "*" + address.substring(2);
439         }
440         return address;
441     }
442
443     /**
444      * Returns the rssi values for all devices.
445      */
446     public List<HmRssiInfo> loadRssiInfo(HmInterface hmInterface) throws IOException {
447         RpcRequest<T> request = createRpcRequest("rssiInfo");
448         return new RssiInfoParser(config).parse(sendMessage(config.getRpcPort(hmInterface), request));
449     }
450
451     /**
452      * Returns the address suffix that specifies the channel for a given HmChannel. This is either a colon ":" followed
453      * by the channel number, or the empty string for a configuration channel.
454      */
455     private String getChannelSuffix(HmChannel channel) {
456         return isConfigurationChannel(channel) ? "" : ":" + channel.getNumber();
457     }
458
459     /**
460      * Checks whether a channel is a configuration channel. The configuration channel of a device encapsulates the
461      * MASTER Paramset that does not belong to one of its actual channels.
462      */
463     private boolean isConfigurationChannel(HmChannel channel) {
464         return channel.getNumber() == CONFIGURATION_CHANNEL_NUMBER;
465     }
466 }