]> git.basschouten.com Git - openhab-addons.git/blob
c6dc11eb6917e3ca2d693368b4888c99f2cc34be
[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
14 package org.openhab.binding.miio.internal.basic;
15
16 import static java.nio.file.StandardWatchEventKinds.*;
17 import static org.openhab.binding.miio.internal.MiIoBindingConstants.BINDING_DATABASE_PATH;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.net.URISyntaxException;
22 import java.net.URL;
23 import java.nio.file.Path;
24 import java.nio.file.Paths;
25 import java.nio.file.WatchEvent;
26 import java.nio.file.WatchEvent.Kind;
27 import java.util.ArrayList;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.openhab.binding.miio.internal.MiIoBindingConstants;
36 import org.openhab.binding.miio.internal.Utils;
37 import org.openhab.core.service.AbstractWatchService;
38 import org.osgi.framework.Bundle;
39 import org.osgi.framework.FrameworkUtil;
40 import org.osgi.service.component.annotations.Activate;
41 import org.osgi.service.component.annotations.Component;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.google.gson.Gson;
46 import com.google.gson.GsonBuilder;
47 import com.google.gson.JsonObject;
48 import com.google.gson.JsonParseException;
49
50 /**
51  * The {@link MiIoDatabaseWatchService} creates a registry of database file per ModelId
52  *
53  * @author Marcel Verpaalen - Initial contribution
54  */
55 @Component(service = MiIoDatabaseWatchService.class)
56 @NonNullByDefault
57 public class MiIoDatabaseWatchService extends AbstractWatchService {
58     private static final String DATABASE_FILES = ".json";
59     private static final Gson GSON = new GsonBuilder().serializeNulls().create();
60
61     private final Logger logger = LoggerFactory.getLogger(MiIoDatabaseWatchService.class);
62     private Map<String, URL> databaseList = new HashMap<>();
63
64     @Activate
65     public MiIoDatabaseWatchService() {
66         super(BINDING_DATABASE_PATH);
67         logger.debug(
68                 "Started miio basic devices local databases watch service. Watching for database files at path: {}",
69                 BINDING_DATABASE_PATH);
70         processWatchEvent(null, null, Paths.get(BINDING_DATABASE_PATH));
71         populateDatabase();
72         if (logger.isTraceEnabled()) {
73             for (String device : databaseList.keySet()) {
74                 logger.trace("Device: {} using URL: {}", device, databaseList.get(device));
75             }
76         }
77     }
78
79     @Override
80     protected boolean watchSubDirectories() {
81         return true;
82     }
83
84     @Override
85     protected Kind<?>[] getWatchEventKinds(@Nullable Path directory) {
86         return new Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
87     }
88
89     @Override
90     protected void processWatchEvent(@Nullable WatchEvent<?> event, @Nullable Kind<?> kind, @Nullable Path path) {
91         if (path != null) {
92             final Path p = path.getFileName();
93             if (p != null && p.toString().endsWith(DATABASE_FILES)) {
94                 logger.debug("Local Databases file {} changed. Refreshing device database.", p.getFileName());
95                 populateDatabase();
96             }
97         }
98     }
99
100     /**
101      * Return the database file URL for a given modelId
102      *
103      * @param modelId the model
104      * @return URL with the definition for the model
105      */
106     public @Nullable URL getDatabaseUrl(String modelId) {
107         return databaseList.get(modelId);
108     }
109
110     private void populateDatabase() {
111         Map<String, URL> workingDatabaseList = new HashMap<>();
112         List<URL> urlEntries = findDatabaseFiles();
113         for (URL db : urlEntries) {
114             logger.trace("Adding devices for db file: {}", db);
115             try {
116                 JsonObject deviceMapping = Utils.convertFileToJSON(db);
117                 MiIoBasicDevice devdb = GSON.fromJson(deviceMapping, MiIoBasicDevice.class);
118                 for (String id : devdb.getDevice().getId()) {
119                     workingDatabaseList.put(id, db);
120                 }
121             } catch (JsonParseException | IOException | URISyntaxException e) {
122                 logger.debug("Error while processing database '{}': {}", db, e.getMessage());
123             }
124             databaseList = workingDatabaseList;
125         }
126     }
127
128     private List<URL> findDatabaseFiles() {
129         List<URL> urlEntries = new ArrayList<>();
130         Bundle bundle = FrameworkUtil.getBundle(getClass());
131         urlEntries.addAll(Collections.list(bundle.findEntries(MiIoBindingConstants.DATABASE_PATH, "*.json", false)));
132         try {
133             File[] userDbFiles = new File(BINDING_DATABASE_PATH).listFiles((dir, name) -> name.endsWith(".json"));
134             if (userDbFiles != null) {
135                 for (File f : userDbFiles) {
136                     urlEntries.add(f.toURI().toURL());
137                     logger.debug("Adding local json db file: {}, {}", f.getName(), f.toURI().toURL());
138                 }
139             }
140         } catch (IOException e) {
141             logger.debug("Error while searching for database files: {}", e.getMessage());
142         }
143         return urlEntries;
144     }
145 }