]> git.basschouten.com Git - openhab-addons.git/blob
7f3f99998421724e9799f6a0bcf007d9335c5674
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.io.openhabcloud.internal;
14
15 import java.io.File;
16 import java.io.FileInputStream;
17 import java.io.FileNotFoundException;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.util.Arrays;
23 import java.util.Collections;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28
29 import org.apache.commons.io.IOUtils;
30 import org.apache.commons.lang.RandomStringUtils;
31 import org.apache.commons.lang.StringUtils;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.core.OpenHAB;
34 import org.openhab.core.config.core.ConfigurableService;
35 import org.openhab.core.events.Event;
36 import org.openhab.core.events.EventFilter;
37 import org.openhab.core.events.EventPublisher;
38 import org.openhab.core.events.EventSubscriber;
39 import org.openhab.core.id.InstanceUUID;
40 import org.openhab.core.io.net.http.HttpClientFactory;
41 import org.openhab.core.items.Item;
42 import org.openhab.core.items.ItemNotFoundException;
43 import org.openhab.core.items.ItemRegistry;
44 import org.openhab.core.items.events.ItemEventFactory;
45 import org.openhab.core.items.events.ItemStateEvent;
46 import org.openhab.core.library.items.RollershutterItem;
47 import org.openhab.core.library.items.SwitchItem;
48 import org.openhab.core.library.types.OnOffType;
49 import org.openhab.core.library.types.UpDownType;
50 import org.openhab.core.model.script.engine.action.ActionService;
51 import org.openhab.core.net.HttpServiceUtil;
52 import org.openhab.core.types.Command;
53 import org.openhab.core.types.TypeParser;
54 import org.openhab.io.openhabcloud.NotificationAction;
55 import org.osgi.framework.BundleContext;
56 import org.osgi.framework.Constants;
57 import org.osgi.service.component.annotations.Activate;
58 import org.osgi.service.component.annotations.Component;
59 import org.osgi.service.component.annotations.Deactivate;
60 import org.osgi.service.component.annotations.Modified;
61 import org.osgi.service.component.annotations.Reference;
62 import org.osgi.service.component.annotations.ReferenceCardinality;
63 import org.osgi.service.component.annotations.ReferencePolicy;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 /**
68  * This class starts the cloud connection service and implements interface to communicate with the cloud.
69  *
70  * @author Victor Belov - Initial contribution
71  * @author Kai Kreuzer - migrated code to new Jetty client and ESH APIs
72  */
73 @Component(service = { EventSubscriber.class,
74         ActionService.class }, configurationPid = "org.openhab.openhabcloud", property = Constants.SERVICE_PID
75                 + "=org.openhab.openhabcloud")
76 @ConfigurableService(category = "io", label = "openHAB Cloud", description_uri = "io:openhabcloud")
77 public class CloudService implements ActionService, CloudClientListener, EventSubscriber {
78
79     private static final String CFG_EXPOSE = "expose";
80     private static final String CFG_BASE_URL = "baseURL";
81     private static final String CFG_MODE = "mode";
82     private static final String SECRET_FILE_NAME = "openhabcloud" + File.separator + "secret";
83     private static final String DEFAULT_URL = "https://myopenhab.org/";
84     private static final int DEFAULT_LOCAL_OPENHAB_MAX_CONCURRENT_REQUESTS = 200;
85     private static final int DEFAULT_LOCAL_OPENHAB_REQUEST_TIMEOUT = 30000;
86     private static final String HTTPCLIENT_NAME = "openhabcloud";
87
88     private Logger logger = LoggerFactory.getLogger(CloudService.class);
89
90     public static String clientVersion = null;
91     private CloudClient cloudClient;
92     private String cloudBaseUrl = null;
93     private HttpClient httpClient;
94     protected ItemRegistry itemRegistry = null;
95     protected EventPublisher eventPublisher = null;
96
97     private boolean remoteAccessEnabled = true;
98     private Set<String> exposedItems = null;
99     private int localPort;
100
101     public CloudService() {
102     }
103
104     /**
105      * This method sends notification message to mobile app through the openHAB Cloud service
106      *
107      * @param userId the {@link String} containing the openHAB Cloud user id to send message to
108      * @param message the {@link String} containing a message to send to specified user id
109      * @param icon the {@link String} containing a name of the icon to be used with this notification
110      * @param severity the {@link String} containing severity (good, info, warning, error) of notification
111      */
112     public void sendNotification(String userId, String message, String icon, String severity) {
113         logger.debug("Sending message '{}' to user id {}", message, userId);
114         cloudClient.sendNotification(userId, message, icon, severity);
115     }
116
117     /**
118      * Sends an advanced notification to log. Log notifications are not pushed to user
119      * devices but are shown to all account users in notifications log
120      *
121      * @param message the {@link String} containing a message to send to specified user id
122      * @param icon the {@link String} containing a name of the icon to be used with this notification
123      * @param severity the {@link String} containing severity (good, info, warning, error) of notification
124      */
125     public void sendLogNotification(String message, String icon, String severity) {
126         logger.debug("Sending log message '{}'", message);
127         cloudClient.sendLogNotification(message, icon, severity);
128     }
129
130     /**
131      * Sends a broadcast notification. Broadcast notifications are pushed to all
132      * mobile devices of all users of the account
133      *
134      * @param message the {@link String} containing a message to send to specified user id
135      * @param icon the {@link String} containing a name of the icon to be used with this notification
136      * @param severity the {@link String} containing severity (good, info, warning, error) of notification
137      */
138     public void sendBroadcastNotification(String message, String icon, String severity) {
139         logger.debug("Sending broadcast message '{}' to all users", message);
140         cloudClient.sendBroadcastNotification(message, icon, severity);
141     }
142
143     @Activate
144     protected void activate(BundleContext context, Map<String, ?> config) {
145         clientVersion = StringUtils.substringBefore(context.getBundle().getVersion().toString(), ".qualifier");
146         localPort = HttpServiceUtil.getHttpServicePort(context);
147         if (localPort == -1) {
148             logger.warn("openHAB Cloud connector not started, since no local HTTP port could be determined");
149         } else {
150             logger.debug("openHAB Cloud connector activated");
151             checkJavaVersion();
152             modified(config);
153         }
154     }
155
156     private void checkJavaVersion() {
157         String version = System.getProperty("java.version");
158         if (version.charAt(2) == '8') {
159             // we are on Java 8, let's check the update
160             String update = version.substring(version.indexOf('_') + 1);
161             try {
162                 Integer uVersion = Integer.valueOf(update);
163                 if (uVersion < 101) {
164                     logger.warn(
165                             "You are running Java {} - the openhab Cloud connection requires at least Java 1.8.0_101, if your cloud server uses Let's Encrypt certificates!",
166                             version);
167                 }
168             } catch (NumberFormatException e) {
169                 logger.debug("Could not determine update version of java {}", version);
170             }
171         }
172     }
173
174     @Deactivate
175     protected void deactivate() {
176         logger.debug("openHAB Cloud connector deactivated");
177         cloudClient.shutdown();
178         try {
179             httpClient.stop();
180         } catch (Exception e) {
181             logger.debug("Could not stop Jetty http client", e);
182         }
183     }
184
185     @Modified
186     protected void modified(Map<String, ?> config) {
187         if (config != null && config.get(CFG_MODE) != null) {
188             remoteAccessEnabled = "remote".equals(config.get(CFG_MODE));
189         } else {
190             logger.debug("remoteAccessEnabled is not set, keeping value '{}'", remoteAccessEnabled);
191         }
192
193         if (config.get(CFG_BASE_URL) != null) {
194             cloudBaseUrl = (String) config.get(CFG_BASE_URL);
195         } else {
196             cloudBaseUrl = DEFAULT_URL;
197         }
198
199         exposedItems = new HashSet<>();
200         Object expCfg = config.get(CFG_EXPOSE);
201         if (expCfg instanceof String) {
202             String value = (String) expCfg;
203             while (value.startsWith("[")) {
204                 value = value.substring(1);
205             }
206             while (value.endsWith("]")) {
207                 value = value.substring(0, value.length() - 1);
208             }
209             for (String itemName : Arrays.asList((value).split(","))) {
210                 exposedItems.add(itemName.trim());
211             }
212         } else if (expCfg instanceof Iterable) {
213             for (Object entry : ((Iterable<?>) expCfg)) {
214                 exposedItems.add(entry.toString());
215             }
216         }
217
218         logger.debug("UUID = {}, secret = {}", InstanceUUID.get(), getSecret());
219
220         if (cloudClient != null) {
221             cloudClient.shutdown();
222         }
223
224         httpClient.setMaxConnectionsPerDestination(DEFAULT_LOCAL_OPENHAB_MAX_CONCURRENT_REQUESTS);
225         httpClient.setConnectTimeout(DEFAULT_LOCAL_OPENHAB_REQUEST_TIMEOUT);
226         httpClient.setFollowRedirects(false);
227         if (!httpClient.isRunning()) {
228             try {
229                 httpClient.start();
230             } catch (Exception e) {
231                 logger.error("Could not start Jetty http client", e);
232             }
233         }
234
235         String localBaseUrl = "http://localhost:" + localPort;
236         cloudClient = new CloudClient(httpClient, InstanceUUID.get(), getSecret(), cloudBaseUrl, localBaseUrl,
237                 remoteAccessEnabled, exposedItems);
238         cloudClient.setOpenHABVersion(OpenHAB.getVersion());
239         cloudClient.connect();
240         cloudClient.setListener(this);
241         NotificationAction.cloudService = this;
242     }
243
244     @Override
245     public String getActionClassName() {
246         return NotificationAction.class.getCanonicalName();
247     }
248
249     @Override
250     public Class<?> getActionClass() {
251         return NotificationAction.class;
252     }
253
254     /**
255      * Reads the first line from specified file
256      */
257
258     private String readFirstLine(File file) {
259         List<String> lines = null;
260         try (InputStream fis = new FileInputStream(file)) {
261             lines = IOUtils.readLines(fis);
262         } catch (IOException ioe) {
263             // no exception handling - we just return the empty String
264         }
265         return lines != null && !lines.isEmpty() ? lines.get(0) : "";
266     }
267
268     /**
269      * Writes a String to a specified file
270      */
271
272     private void writeFile(File file, String content) {
273         // create intermediary directories
274         file.getParentFile().mkdirs();
275         try (OutputStream fos = new FileOutputStream(file)) {
276             IOUtils.write(content, fos);
277             logger.debug("Created file '{}' with content '{}'", file.getAbsolutePath(), content);
278         } catch (FileNotFoundException e) {
279             logger.error("Couldn't create file '{}'.", file.getPath(), e);
280         } catch (IOException e) {
281             logger.error("Couldn't write to file '{}'.", file.getPath(), e);
282         }
283     }
284
285     /**
286      * Creates a random secret and writes it to the <code>userdata/openhabcloud</code>
287      * directory. An existing <code>secret</code> file won't be overwritten.
288      * Returns either existing secret from the file or newly created secret.
289      */
290     private String getSecret() {
291         File file = new File(OpenHAB.getUserDataFolder() + File.separator + SECRET_FILE_NAME);
292         String newSecretString = "";
293
294         if (!file.exists()) {
295             newSecretString = RandomStringUtils.randomAlphanumeric(20);
296             logger.debug("New secret = {}", newSecretString);
297             writeFile(file, newSecretString);
298         } else {
299             newSecretString = readFirstLine(file);
300             logger.debug("Using secret at '{}' with content '{}'", file.getAbsolutePath(), newSecretString);
301         }
302
303         return newSecretString;
304     }
305
306     @Override
307     public void sendCommand(String itemName, String commandString) {
308         try {
309             if (itemRegistry != null) {
310                 Item item = itemRegistry.getItem(itemName);
311                 Command command = null;
312                 if (item != null) {
313                     if (this.eventPublisher != null) {
314                         if ("toggle".equalsIgnoreCase(commandString)
315                                 && (item instanceof SwitchItem || item instanceof RollershutterItem)) {
316                             if (OnOffType.ON.equals(item.getStateAs(OnOffType.class))) {
317                                 command = OnOffType.OFF;
318                             }
319                             if (OnOffType.OFF.equals(item.getStateAs(OnOffType.class))) {
320                                 command = OnOffType.ON;
321                             }
322                             if (UpDownType.UP.equals(item.getStateAs(UpDownType.class))) {
323                                 command = UpDownType.DOWN;
324                             }
325                             if (UpDownType.DOWN.equals(item.getStateAs(UpDownType.class))) {
326                                 command = UpDownType.UP;
327                             }
328                         } else {
329                             command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandString);
330                         }
331                         if (command != null) {
332                             logger.debug("Received command '{}' for item '{}'", commandString, itemName);
333                             this.eventPublisher.post(ItemEventFactory.createCommandEvent(itemName, command));
334                         } else {
335                             logger.warn("Received invalid command '{}' for item '{}'", commandString, itemName);
336                         }
337                     }
338                 } else {
339                     logger.warn("Received command '{}' for non-existent item '{}'", commandString, itemName);
340                 }
341             } else {
342                 return;
343             }
344         } catch (ItemNotFoundException e) {
345             logger.warn("Received command for a non-existent item '{}'", itemName);
346         }
347     }
348
349     @Reference
350     protected void setHttpClientFactory(HttpClientFactory httpClientFactory) {
351         this.httpClient = httpClientFactory.createHttpClient(HTTPCLIENT_NAME);
352         this.httpClient.setStopTimeout(0);
353     }
354
355     protected void unsetHttpClientFactory(HttpClientFactory httpClientFactory) {
356         this.httpClient = null;
357     }
358
359     @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
360     public void setItemRegistry(ItemRegistry itemRegistry) {
361         this.itemRegistry = itemRegistry;
362     }
363
364     public void unsetItemRegistry(ItemRegistry itemRegistry) {
365         this.itemRegistry = null;
366     }
367
368     @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
369     public void setEventPublisher(EventPublisher eventPublisher) {
370         this.eventPublisher = eventPublisher;
371     }
372
373     public void unsetEventPublisher(EventPublisher eventPublisher) {
374         this.eventPublisher = null;
375     }
376
377     @Override
378     public Set<String> getSubscribedEventTypes() {
379         return Collections.singleton(ItemStateEvent.TYPE);
380     }
381
382     @Override
383     public EventFilter getEventFilter() {
384         return null;
385     }
386
387     @Override
388     public void receive(Event event) {
389         ItemStateEvent ise = (ItemStateEvent) event;
390         if (exposedItems != null && exposedItems.contains(ise.getItemName())) {
391             cloudClient.sendItemUpdate(ise.getItemName(), ise.getItemState().toString());
392         }
393     }
394 }