2 * Copyright (c) 2010-2020 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.io.openhabcloud.internal;
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;
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;
68 * This class starts the cloud connection service and implements interface to communicate with the cloud.
70 * @author Victor Belov - Initial contribution
71 * @author Kai Kreuzer - migrated code to new Jetty client and ESH APIs
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 {
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";
88 private Logger logger = LoggerFactory.getLogger(CloudService.class);
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;
97 private boolean remoteAccessEnabled = true;
98 private Set<String> exposedItems = null;
99 private int localPort;
101 public CloudService() {
105 * This method sends notification message to mobile app through the openHAB Cloud service
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
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);
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
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
125 public void sendLogNotification(String message, String icon, String severity) {
126 logger.debug("Sending log message '{}'", message);
127 cloudClient.sendLogNotification(message, icon, severity);
131 * Sends a broadcast notification. Broadcast notifications are pushed to all
132 * mobile devices of all users of the account
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
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);
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");
150 logger.debug("openHAB Cloud connector activated");
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);
162 Integer uVersion = Integer.valueOf(update);
163 if (uVersion < 101) {
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!",
168 } catch (NumberFormatException e) {
169 logger.debug("Could not determine update version of java {}", version);
175 protected void deactivate() {
176 logger.debug("openHAB Cloud connector deactivated");
177 cloudClient.shutdown();
180 } catch (Exception e) {
181 logger.debug("Could not stop Jetty http client", e);
186 protected void modified(Map<String, ?> config) {
187 if (config != null && config.get(CFG_MODE) != null) {
188 remoteAccessEnabled = "remote".equals(config.get(CFG_MODE));
190 logger.debug("remoteAccessEnabled is not set, keeping value '{}'", remoteAccessEnabled);
193 if (config.get(CFG_BASE_URL) != null) {
194 cloudBaseUrl = (String) config.get(CFG_BASE_URL);
196 cloudBaseUrl = DEFAULT_URL;
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);
206 while (value.endsWith("]")) {
207 value = value.substring(0, value.length() - 1);
209 for (String itemName : Arrays.asList((value).split(","))) {
210 exposedItems.add(itemName.trim());
212 } else if (expCfg instanceof Iterable) {
213 for (Object entry : ((Iterable<?>) expCfg)) {
214 exposedItems.add(entry.toString());
218 logger.debug("UUID = {}, secret = {}", InstanceUUID.get(), getSecret());
220 if (cloudClient != null) {
221 cloudClient.shutdown();
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()) {
230 } catch (Exception e) {
231 logger.error("Could not start Jetty http client", e);
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;
245 public String getActionClassName() {
246 return NotificationAction.class.getCanonicalName();
250 public Class<?> getActionClass() {
251 return NotificationAction.class;
255 * Reads the first line from specified file
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
265 return lines != null && !lines.isEmpty() ? lines.get(0) : "";
269 * Writes a String to a specified file
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);
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.
290 private String getSecret() {
291 File file = new File(OpenHAB.getUserDataFolder() + File.separator + SECRET_FILE_NAME);
292 String newSecretString = "";
294 if (!file.exists()) {
295 newSecretString = RandomStringUtils.randomAlphanumeric(20);
296 logger.debug("New secret = {}", newSecretString);
297 writeFile(file, newSecretString);
299 newSecretString = readFirstLine(file);
300 logger.debug("Using secret at '{}' with content '{}'", file.getAbsolutePath(), newSecretString);
303 return newSecretString;
307 public void sendCommand(String itemName, String commandString) {
309 if (itemRegistry != null) {
310 Item item = itemRegistry.getItem(itemName);
311 Command command = 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;
319 if (OnOffType.OFF.equals(item.getStateAs(OnOffType.class))) {
320 command = OnOffType.ON;
322 if (UpDownType.UP.equals(item.getStateAs(UpDownType.class))) {
323 command = UpDownType.DOWN;
325 if (UpDownType.DOWN.equals(item.getStateAs(UpDownType.class))) {
326 command = UpDownType.UP;
329 command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandString);
331 if (command != null) {
332 logger.debug("Received command '{}' for item '{}'", commandString, itemName);
333 this.eventPublisher.post(ItemEventFactory.createCommandEvent(itemName, command));
335 logger.warn("Received invalid command '{}' for item '{}'", commandString, itemName);
339 logger.warn("Received command '{}' for non-existent item '{}'", commandString, itemName);
344 } catch (ItemNotFoundException e) {
345 logger.warn("Received command for a non-existent item '{}'", itemName);
350 protected void setHttpClientFactory(HttpClientFactory httpClientFactory) {
351 this.httpClient = httpClientFactory.createHttpClient(HTTPCLIENT_NAME);
352 this.httpClient.setStopTimeout(0);
355 protected void unsetHttpClientFactory(HttpClientFactory httpClientFactory) {
356 this.httpClient = null;
359 @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
360 public void setItemRegistry(ItemRegistry itemRegistry) {
361 this.itemRegistry = itemRegistry;
364 public void unsetItemRegistry(ItemRegistry itemRegistry) {
365 this.itemRegistry = null;
368 @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
369 public void setEventPublisher(EventPublisher eventPublisher) {
370 this.eventPublisher = eventPublisher;
373 public void unsetEventPublisher(EventPublisher eventPublisher) {
374 this.eventPublisher = null;
378 public Set<String> getSubscribedEventTypes() {
379 return Collections.singleton(ItemStateEvent.TYPE);
383 public EventFilter getEventFilter() {
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());