2 * Copyright (c) 2010-2023 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.binding.miio.internal.basic;
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.BINDING_DATABASE_PATH;
18 import java.io.IOException;
19 import java.net.URISyntaxException;
21 import java.nio.file.Path;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.miio.internal.MiIoBindingConstants;
31 import org.openhab.binding.miio.internal.Utils;
32 import org.openhab.core.OpenHAB;
33 import org.openhab.core.service.WatchService;
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.FrameworkUtil;
36 import org.osgi.service.component.annotations.Activate;
37 import org.osgi.service.component.annotations.Component;
38 import org.osgi.service.component.annotations.Deactivate;
39 import org.osgi.service.component.annotations.Reference;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 import com.google.gson.Gson;
44 import com.google.gson.GsonBuilder;
45 import com.google.gson.JsonObject;
46 import com.google.gson.JsonParseException;
49 * The {@link MiIoDatabaseWatchService} creates a registry of database file per ModelId
51 * @author Marcel Verpaalen - Initial contribution
52 * @author Jan N. Klug - Refactored to new WatchService
54 @Component(service = MiIoDatabaseWatchService.class)
56 public class MiIoDatabaseWatchService implements WatchService.WatchEventListener {
57 private static final String DATABASE_FILES = ".json";
58 private static final Gson GSON = new GsonBuilder().serializeNulls().create();
60 private final Logger logger = LoggerFactory.getLogger(MiIoDatabaseWatchService.class);
61 private final WatchService watchService;
62 private Map<String, URL> databaseList = new HashMap<>();
63 private final Path watchPath;
66 public MiIoDatabaseWatchService(@Reference(target = WatchService.CONFIG_WATCHER_FILTER) WatchService watchService) {
67 this.watchService = watchService;
68 this.watchPath = Path.of(BINDING_DATABASE_PATH).relativize(Path.of(OpenHAB.getConfigFolder()));
69 watchService.registerListener(this, watchPath);
72 "Started miio basic devices local databases watch service. Watching for database files at path: {}",
73 BINDING_DATABASE_PATH);
74 processWatchEvent(WatchService.Kind.CREATE, watchPath);
76 if (logger.isTraceEnabled()) {
77 for (String device : databaseList.keySet()) {
78 logger.trace("Device: {} using URL: {}", device, databaseList.get(device));
84 public void deactivate() {
85 watchService.unregisterListener(this);
89 public void processWatchEvent(WatchService.Kind kind, Path path) {
90 final Path p = path.getFileName();
91 if (p != null && p.toString().endsWith(DATABASE_FILES)) {
92 logger.debug("Local Databases file {} changed. Refreshing device database.", p.getFileName());
98 * Return the database file URL for a given modelId
100 * @param modelId the model
101 * @return URL with the definition for the model
103 public @Nullable URL getDatabaseUrl(String modelId) {
104 return databaseList.get(modelId);
107 private void populateDatabase() {
108 Map<String, URL> workingDatabaseList = new HashMap<>();
109 List<URL> urlEntries = findDatabaseFiles();
110 for (URL db : urlEntries) {
111 logger.trace("Adding devices for db file: {}", db);
113 JsonObject deviceMapping = Utils.convertFileToJSON(db);
114 MiIoBasicDevice devdb = GSON.fromJson(deviceMapping, MiIoBasicDevice.class);
118 for (String id : devdb.getDevice().getId()) {
119 workingDatabaseList.put(id, db);
121 } catch (JsonParseException | IOException | URISyntaxException e) {
122 logger.debug("Error while processing database '{}': {}", db, e.getMessage());
124 databaseList = workingDatabaseList;
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)));
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());
140 } catch (IOException e) {
141 logger.debug("Error while searching for database files: {}", e.getMessage());