]> git.basschouten.com Git - openhab-addons.git/blob
d1e636b50ae6967080adf712714d708e44f95f2e
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Objects;
22 import java.util.concurrent.TimeUnit;
23
24 import org.eclipse.jetty.client.HttpClient;
25 import org.eclipse.jetty.client.api.ContentResponse;
26 import org.eclipse.jetty.client.util.StringContentProvider;
27 import org.eclipse.jetty.http.HttpHeader;
28 import org.openhab.binding.homematic.internal.common.HomematicConfig;
29 import org.openhab.binding.homematic.internal.communicator.client.UnknownParameterSetException;
30 import org.openhab.binding.homematic.internal.communicator.client.UnknownRpcFailureException;
31 import org.openhab.binding.homematic.internal.communicator.parser.CcuLoadDeviceNamesParser;
32 import org.openhab.binding.homematic.internal.communicator.parser.CcuParamsetDescriptionParser;
33 import org.openhab.binding.homematic.internal.communicator.parser.CcuValueParser;
34 import org.openhab.binding.homematic.internal.communicator.parser.CcuVariablesAndScriptsParser;
35 import org.openhab.binding.homematic.internal.model.HmChannel;
36 import org.openhab.binding.homematic.internal.model.HmDatapoint;
37 import org.openhab.binding.homematic.internal.model.HmDevice;
38 import org.openhab.binding.homematic.internal.model.HmParamsetType;
39 import org.openhab.binding.homematic.internal.model.HmResult;
40 import org.openhab.binding.homematic.internal.model.TclScript;
41 import org.openhab.binding.homematic.internal.model.TclScriptDataList;
42 import org.openhab.binding.homematic.internal.model.TclScriptList;
43 import org.osgi.framework.Bundle;
44 import org.osgi.framework.FrameworkUtil;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.thoughtworks.xstream.XStream;
49 import com.thoughtworks.xstream.io.xml.StaxDriver;
50
51 /**
52  * HomematicGateway implementation for a CCU.
53  *
54  * @author Gerhard Riegler - Initial contribution
55  */
56 public class CcuGateway extends AbstractHomematicGateway {
57     private final Logger logger = LoggerFactory.getLogger(CcuGateway.class);
58
59     private Map<String, String> tclregaScripts;
60     private XStream xStream = new XStream(new StaxDriver());
61
62     protected CcuGateway(String id, HomematicConfig config, HomematicGatewayAdapter gatewayAdapter,
63             HttpClient httpClient) {
64         super(id, config, gatewayAdapter, httpClient);
65
66         xStream.allowTypesByWildcard(new String[] { HmDevice.class.getPackageName() + ".**" });
67         xStream.setClassLoader(CcuGateway.class.getClassLoader());
68         xStream.autodetectAnnotations(true);
69         xStream.alias("scripts", TclScriptList.class);
70         xStream.alias("list", TclScriptDataList.class);
71         xStream.alias("result", HmResult.class);
72     }
73
74     @Override
75     protected void startClients() throws IOException {
76         super.startClients();
77
78         tclregaScripts = loadTclRegaScripts();
79     }
80
81     @Override
82     protected void stopClients() {
83         super.stopClients();
84         tclregaScripts = null;
85     }
86
87     @Override
88     protected void loadVariables(HmChannel channel) throws IOException {
89         TclScriptDataList resultList = sendScriptByName("getAllVariables", TclScriptDataList.class);
90         new CcuVariablesAndScriptsParser(channel).parse(resultList);
91     }
92
93     @Override
94     protected void loadScripts(HmChannel channel) throws IOException {
95         TclScriptDataList resultList = sendScriptByName("getAllPrograms", TclScriptDataList.class);
96         new CcuVariablesAndScriptsParser(channel).parse(resultList);
97     }
98
99     @Override
100     protected void loadDeviceNames(Collection<HmDevice> devices) throws IOException {
101         TclScriptDataList resultList = sendScriptByName("getAllDeviceNames", TclScriptDataList.class);
102         new CcuLoadDeviceNamesParser(devices).parse(resultList);
103     }
104
105     @Override
106     protected void setChannelDatapointValues(HmChannel channel, HmParamsetType paramsetType) throws IOException {
107         try {
108             super.setChannelDatapointValues(channel, paramsetType);
109         } catch (UnknownRpcFailureException ex) {
110             logger.debug(
111                     "RpcMessage unknown RPC failure (-1 Failure), fetching values with TclRega script for device {}, channel: {}, paramset: {}",
112                     channel.getDevice().getAddress(), channel.getNumber(), paramsetType);
113
114             Collection<String> dpNames = new ArrayList<>();
115             for (HmDatapoint dp : channel.getDatapoints()) {
116                 if (!dp.isVirtual() && dp.isReadable() && dp.getParamsetType() == HmParamsetType.VALUES) {
117                     dpNames.add(dp.getName());
118                 }
119             }
120             if (!dpNames.isEmpty()) {
121                 HmDevice device = channel.getDevice();
122                 String channelName = String.format("%s.%s:%s.", device.getHmInterface().getName(), device.getAddress(),
123                         channel.getNumber());
124                 String datapointNames = String.join("\\t", dpNames);
125                 TclScriptDataList resultList = sendScriptByName("getAllChannelValues", TclScriptDataList.class,
126                         new String[] { "channel_name", "datapoint_names" },
127                         new String[] { channelName, datapointNames });
128                 new CcuValueParser(channel).parse(resultList);
129                 channel.setInitialized(true);
130             }
131         }
132     }
133
134     @Override
135     protected void addChannelDatapoints(HmChannel channel, HmParamsetType paramsetType) throws IOException {
136         try {
137             getRpcClient(channel.getDevice().getHmInterface()).addChannelDatapoints(channel, paramsetType);
138         } catch (UnknownParameterSetException ex) {
139             logger.debug(
140                     "RpcMessage RPC failure (-3 Unknown paramset), fetching metadata with TclRega script for device: {}, channel: {}, paramset: {}",
141                     channel.getDevice().getAddress(), channel.getNumber(), paramsetType);
142
143             TclScriptDataList resultList = sendScriptByName("getParamsetDescription", TclScriptDataList.class,
144                     new String[] { "device_address", "channel_number" },
145                     new String[] { channel.getDevice().getAddress(), channel.getNumber().toString() });
146             new CcuParamsetDescriptionParser(channel, paramsetType).parse(resultList);
147         }
148     }
149
150     @Override
151     protected void setVariable(HmDatapoint dp, Object value) throws IOException {
152         String strValue = Objects.toString(value, "").replace("\"", "\\\"");
153         if (dp.isStringType()) {
154             strValue = "\"" + strValue + "\"";
155         }
156         HmResult result = sendScriptByName("setVariable", HmResult.class,
157                 new String[] { "variable_name", "variable_state" }, new String[] { dp.getInfo(), strValue });
158         if (!result.isValid()) {
159             throw new IOException("Unable to set CCU variable " + dp.getInfo());
160         }
161     }
162
163     @Override
164     protected void executeScript(HmDatapoint dp) throws IOException {
165         HmResult result = sendScriptByName("executeProgram", HmResult.class, new String[] { "program_name" },
166                 new String[] { dp.getInfo() });
167         if (!result.isValid()) {
168             throw new IOException("Unable to start CCU program: " + dp.getInfo());
169         }
170     }
171
172     /**
173      * Sends a TclRega script to the CCU.
174      */
175     private <T> T sendScriptByName(String scriptName, Class<T> clazz) throws IOException {
176         return sendScriptByName(scriptName, clazz, new String[] {}, null);
177     }
178
179     /**
180      * Sends a TclRega script with the specified variables to the CCU.
181      */
182     private <T> T sendScriptByName(String scriptName, Class<T> clazz, String[] variableNames, String[] values)
183             throws IOException {
184         String script = tclregaScripts.get(scriptName);
185         if (script != null) {
186             for (int i = 0; i < variableNames.length; i++) {
187                 script = script.replace("{" + variableNames[i] + "}", values[i]);
188             }
189         }
190         return sendScript(script, clazz);
191     }
192
193     /**
194      * Main method for sending a TclRega script and parsing the XML result.
195      */
196     @SuppressWarnings("unchecked")
197     private synchronized <T> T sendScript(String script, Class<T> clazz) throws IOException {
198         try {
199             script = script == null ? null : script.trim();
200             if (script == null || script.isEmpty()) {
201                 throw new RuntimeException("Homematic TclRegaScript is empty!");
202             }
203             if (logger.isTraceEnabled()) {
204                 logger.trace("TclRegaScript: {}", script);
205             }
206
207             StringContentProvider content = new StringContentProvider(script, config.getEncoding());
208             ContentResponse response = httpClient.POST(config.getTclRegaUrl()).content(content)
209                     .timeout(config.getTimeout(), TimeUnit.SECONDS)
210                     .header(HttpHeader.CONTENT_TYPE, "text/plain;charset=" + config.getEncoding()).send();
211
212             String result = new String(response.getContent(), config.getEncoding());
213             int lastPos = result.lastIndexOf("<xml><exec>");
214             if (lastPos != -1) {
215                 result = result.substring(0, lastPos);
216             }
217             if (logger.isTraceEnabled()) {
218                 logger.trace("Result TclRegaScript: {}", result);
219             }
220
221             return (T) xStream.fromXML(result);
222         } catch (Exception ex) {
223             throw new IOException(ex.getMessage(), ex);
224         }
225     }
226
227     /**
228      * Load predefined scripts from an XML file.
229      */
230     private Map<String, String> loadTclRegaScripts() throws IOException {
231         Bundle bundle = FrameworkUtil.getBundle(getClass());
232         try (InputStream stream = bundle.getResource("homematic/tclrega-scripts.xml").openStream()) {
233             TclScriptList scriptList = (TclScriptList) xStream.fromXML(stream);
234             Map<String, String> result = new HashMap<>();
235             if (scriptList.getScripts() != null) {
236                 for (TclScript script : scriptList.getScripts()) {
237                     String value = script.data.trim();
238                     result.put(script.name, value.isEmpty() ? null : value);
239                 }
240             }
241             return result;
242         } catch (IllegalStateException | IOException e) {
243             throw new IOException("The resource homematic/tclrega-scripts.xml could not be loaded!", e);
244         }
245     }
246 }