Skip to content

Commit

Permalink
[insteon] Add modem database backup restore console commands
Browse files Browse the repository at this point in the history
Signed-off-by: jsetton <[email protected]>
  • Loading branch information
jsetton committed Dec 23, 2024
1 parent 1b75e03 commit 7ec79ca
Show file tree
Hide file tree
Showing 14 changed files with 253 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
*/
package org.openhab.binding.insteon.internal;

import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -34,7 +34,7 @@
@NonNullByDefault
public class InsteonBindingConstants {
public static final String BINDING_ID = "insteon";
public static final String BINDING_DATA_DIR = OpenHAB.getUserDataFolder() + File.separator + BINDING_ID;
public static final Path BINDING_DATA_DIR = Path.of(OpenHAB.getUserDataFolder(), BINDING_ID);

// List of all thing type uids
public static final ThingTypeUID THING_TYPE_DEVICE = new ThingTypeUID(BINDING_ID, "device");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
package org.openhab.binding.insteon.internal.command;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
Expand All @@ -27,7 +27,6 @@
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.insteon.internal.InsteonBindingConstants;
import org.openhab.binding.insteon.internal.device.InsteonAddress;
import org.openhab.binding.insteon.internal.device.InsteonScene;
import org.openhab.binding.insteon.internal.device.X10Address;
Expand Down Expand Up @@ -71,7 +70,7 @@ public class DebugCommand extends InsteonCommand implements PortListener {

private static final String ALL_OPTION = "--all";

private static final String MSG_EVENTS_FILE_PREFIX = "messageEvents";
private static final String MSG_EVENTS_FILE_PREFIX = "message-events";

private static enum MessageType {
STANDARD,
Expand Down Expand Up @@ -195,9 +194,16 @@ public boolean complete(String[] args, int cursorArgumentIndex, int cursorPositi
} else if (cursorArgumentIndex == 1) {
switch (args[0]) {
case START_MONITORING:
strings = monitorAllDevices ? List.of()
: Stream.concat(Stream.of(ALL_OPTION),
getModem().getDB().getDevices().stream()
.filter(address -> !monitoredAddresses.contains(address))
.map(InsteonAddress::toString))
.toList();
break;
case STOP_MONITORING:
strings = Stream.concat(Stream.of(ALL_OPTION),
getModem().getDB().getDevices().stream().map(InsteonAddress::toString)).toList();
strings = monitorAllDevices ? List.of(ALL_OPTION)
: monitoredAddresses.stream().map(InsteonAddress::toString).toList();
break;
case SEND_BROADCAST_MESSAGE:
strings = getModem().getDB().getBroadcastGroups().stream().map(String::valueOf).toList();
Expand Down Expand Up @@ -251,40 +257,25 @@ public void messageSent(Msg msg) {
}
}

private String getMsgEventsFileName(String address) {
return MSG_EVENTS_FILE_PREFIX + "-" + address.replace(".", "") + ".log";
}

private String getMsgEventsFilePath(String address) {
return InsteonBindingConstants.BINDING_DATA_DIR + File.separator + getMsgEventsFileName(address);
private Path getMsgEventsFilePath(String address) {
return getBindingDataFilePath(MSG_EVENTS_FILE_PREFIX + "-" + address.toLowerCase().replace(".", "") + ".log");
}

private void clearMonitorFiles(String address) {
File folder = new File(InsteonBindingConstants.BINDING_DATA_DIR);
String prefix = ALL_OPTION.equals(address) ? MSG_EVENTS_FILE_PREFIX : getMsgEventsFileName(address);
String prefix = ALL_OPTION.equals(address) ? MSG_EVENTS_FILE_PREFIX
: getMsgEventsFilePath(address).getFileName().toString();

if (folder.isDirectory()) {
Arrays.asList(folder.listFiles()).stream().filter(file -> file.getName().startsWith(prefix))
.forEach(File::delete);
}
getBindingDataFilePaths(prefix).map(Path::toFile).forEach(File::delete);
}

private void logMessageEvent(InsteonAddress address, Msg msg) {
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
String pathname = getMsgEventsFilePath(address.toString());
String line = timestamp + " " + msg + System.lineSeparator();
Path path = getMsgEventsFilePath(address.toString());

try {
File file = new File(pathname);
File parent = file.getParentFile();
if (parent == null) {
throw new IOException(pathname + " does not name a parent directory");
}
parent.mkdirs();
file.createNewFile();

PrintStream ps = new PrintStream(new FileOutputStream(file, true));
ps.println(timestamp + " " + msg.toString());
ps.close();
Files.createDirectories(path.getParent());
Files.writeString(path, line, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
logger.warn("failed to write to message event file", e);
}
Expand All @@ -307,7 +298,7 @@ private void startMonitoring(Console console, String address) {
monitorAllDevices = true;
monitoredAddresses.clear();
console.println("Started monitoring all devices.");
console.println("Message events logged in " + InsteonBindingConstants.BINDING_DATA_DIR);
console.println("Message events logged in " + getBindingDataDirPath());
clearMonitorFiles(address);
} else {
console.println("Already monitoring all devices.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
*/
package org.openhab.binding.insteon.internal.command;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
Expand All @@ -20,6 +23,7 @@

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.insteon.internal.InsteonBindingConstants;
import org.openhab.binding.insteon.internal.device.Device;
import org.openhab.binding.insteon.internal.device.InsteonAddress;
import org.openhab.binding.insteon.internal.device.InsteonDevice;
Expand Down Expand Up @@ -171,4 +175,21 @@ protected InsteonEngine getInsteonEngine(String thingId) {
InsteonDevice device = getInsteonDevice(thingId);
return device != null ? device.getInsteonEngine() : InsteonEngine.UNKNOWN;
}

protected Path getBindingDataDirPath() {
return InsteonBindingConstants.BINDING_DATA_DIR;
}

protected Path getBindingDataFilePath(String filename) {
return InsteonBindingConstants.BINDING_DATA_DIR.resolve(filename);
}

protected Stream<Path> getBindingDataFilePaths(String prefix) {
try {
return Files.list(InsteonBindingConstants.BINDING_DATA_DIR)
.filter(path -> path.getFileName().toString().startsWith(prefix));
} catch (IOException e) {
return Stream.of();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
*/
package org.openhab.binding.insteon.internal.command;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -41,23 +46,28 @@ public class ModemCommand extends InsteonCommand {
private static final String LIST_ALL = "listAll";
private static final String LIST_DATABASE = "listDatabase";
private static final String RELOAD_DATABASE = "reloadDatabase";
private static final String BACKUP_DATABASE = "backupDatabase";
private static final String RESTORE_DATABASE = "restoreDatabase";
private static final String ADD_DATABASE_CONTROLLER = "addDatabaseController";
private static final String ADD_DATABASE_RESPONDER = "addDatabaseResponder";
private static final String DELETE_DATABASE_RECORD = "deleteDatabaseRecord";
private static final String APPLY_DATABASE_CHANGES = "applyDatabaseChanges";
private static final String CLEAR_DATABASE_CHANGES = "clearDatabaseChanges";
private static final String ADD_DEVICE = "addDevice";
private static final String REMOVE_DEVICE = "removeDevice";
private static final String RESET = "reset";
private static final String SWITCH = "switch";

private static final List<String> SUBCMDS = List.of(LIST_ALL, LIST_DATABASE, RELOAD_DATABASE,
ADD_DATABASE_CONTROLLER, ADD_DATABASE_RESPONDER, DELETE_DATABASE_RECORD, APPLY_DATABASE_CHANGES,
CLEAR_DATABASE_CHANGES, ADD_DEVICE, REMOVE_DEVICE, SWITCH);
private static final List<String> SUBCMDS = List.of(LIST_ALL, LIST_DATABASE, RELOAD_DATABASE, BACKUP_DATABASE,
RESTORE_DATABASE, ADD_DATABASE_CONTROLLER, ADD_DATABASE_RESPONDER, DELETE_DATABASE_RECORD,
APPLY_DATABASE_CHANGES, CLEAR_DATABASE_CHANGES, ADD_DEVICE, REMOVE_DEVICE, RESET, SWITCH);

private static final String CONFIRM_OPTION = "--confirm";
private static final String FORCE_OPTION = "--force";
private static final String RECORDS_OPTION = "--records";

private static final String MODEM_DATABASE_FILE_PREFIX = "modem-database";

public ModemCommand(InsteonCommandExtension commandExtension) {
super(NAME, DESCRIPTION, commandExtension);
}
Expand All @@ -69,6 +79,9 @@ public List<String> getUsages() {
buildCommandUsage(LIST_DATABASE + " [" + RECORDS_OPTION + "]",
"list all-link database summary or records and pending changes for the Insteon modem"),
buildCommandUsage(RELOAD_DATABASE, "reload all-link database from the Insteon modem"),
buildCommandUsage(BACKUP_DATABASE, "backup all-link database from the Insteon modem to a file"),
buildCommandUsage(RESTORE_DATABASE + " <filename> " + CONFIRM_OPTION,
"restore all-link database to the Insteon modem from a specific file"),
buildCommandUsage(ADD_DATABASE_CONTROLLER + " <address> <group> [<devCat> <subCat> <firmware>]",
"add a controller record to all-link database for the Insteon modem"),
buildCommandUsage(ADD_DATABASE_RESPONDER + " <address> <group>",
Expand All @@ -83,6 +96,7 @@ public List<String> getUsages() {
"add an Insteon device to the modem, optionally providing its address"),
buildCommandUsage(REMOVE_DEVICE + " <address> [" + FORCE_OPTION + "]",
"remove an Insteon device from the modem"),
buildCommandUsage(RESET + " " + CONFIRM_OPTION, "reset the Insteon modem to factory defaults"),
buildCommandUsage(SWITCH + " <thingId>",
"switch Insteon modem bridge to use if more than one configured and enabled"));
}
Expand Down Expand Up @@ -118,6 +132,20 @@ public void execute(String[] args, Console console) {
printUsage(console, args[0]);
}
break;
case BACKUP_DATABASE:
if (args.length == 1) {
backupDatabase(console);
} else {
printUsage(console, args[0]);
}
break;
case RESTORE_DATABASE:
if (args.length == 2 || args.length == 3 && CONFIRM_OPTION.equals(args[2])) {
restoreDatabase(console, args[1], args.length == 3);
} else {
printUsage(console, args[0]);
}
break;
case ADD_DATABASE_CONTROLLER:
if (args.length == 3 || args.length == 6) {
addDatabaseRecord(console, args, true);
Expand Down Expand Up @@ -167,6 +195,13 @@ public void execute(String[] args, Console console) {
printUsage(console, args[0]);
}
break;
case RESET:
if (args.length == 1 || args.length == 2 && CONFIRM_OPTION.equals(args[1])) {
resetModem(console, args.length == 2);
} else {
printUsage(console, args[0]);
}
break;
case SWITCH:
if (args.length == 2) {
switchModem(console, args[1]);
Expand All @@ -191,6 +226,10 @@ public boolean complete(String[] args, int cursorArgumentIndex, int cursorPositi
case LIST_DATABASE:
strings = List.of(RECORDS_OPTION);
break;
case RESTORE_DATABASE:
strings = getBindingDataFilePaths(MODEM_DATABASE_FILE_PREFIX).map(Path::getFileName)
.map(Path::toString).toList();
break;
case ADD_DATABASE_CONTROLLER:
case ADD_DATABASE_RESPONDER:
case REMOVE_DEVICE:
Expand All @@ -200,13 +239,20 @@ public boolean complete(String[] args, int cursorArgumentIndex, int cursorPositi
strings = getModem().getDB().getRecords().stream().map(record -> record.getAddress().toString())
.distinct().toList();
break;
case APPLY_DATABASE_CHANGES:
case RESET:
strings = List.of(CONFIRM_OPTION);
break;
case SWITCH:
strings = getBridgeHandlers().map(InsteonBridgeHandler::getThingId).toList();
break;
}
} else if (cursorArgumentIndex == 2) {
InsteonAddress address = InsteonAddress.isValid(args[1]) ? new InsteonAddress(args[1]) : null;
switch (args[0]) {
case RESTORE_DATABASE:
strings = List.of(CONFIRM_OPTION);
break;
case DELETE_DATABASE_RECORD:
if (address != null) {
strings = getModem().getDB().getRecords(address).stream()
Expand Down Expand Up @@ -285,6 +331,69 @@ private void reloadDatabase(Console console) {
}
}

private void backupDatabase(Console console) {
InsteonAddress address = getModem().getAddress();
int count = getModem().getDB().getRecords().size();
if (InsteonAddress.UNKNOWN.equals(address)) {
console.println("No modem found!");
} else if (count == 0) {
console.println("The all-link database for modem " + address + " is empty");
} else {
String timestamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String id = address.toString().toLowerCase().replace(".", "");
Path path = getBindingDataFilePath(MODEM_DATABASE_FILE_PREFIX + "-" + id + "-" + timestamp + ".dmp");
byte[] dump = getModem().getDB().getRecordDump();

try {
Files.createDirectories(path.getParent());
Files.write(path, dump);
console.println("Backed up " + count + " database records from modem " + address + " to " + path);
} catch (IOException e) {
console.println("Failed to write backup file: " + e.getMessage());
}
}
}

private void restoreDatabase(Console console, String filename, boolean isConfirmed) {
InsteonAddress address = getModem().getAddress();
if (InsteonAddress.UNKNOWN.equals(address)) {
console.println("No modem found!");
} else {
Path path = Path.of(filename);
if (!path.isAbsolute()) {
path = getBindingDataFilePath(filename);
}

try {
if (!Files.exists(path)) {
console.println("The restore file " + path + " does not exist.");
} else if (Files.size(path) == 0) {
console.println("The restore file " + path + " is empty.");
} else {
byte[] dump = Files.readAllBytes(path);
List<ModemDBRecord> records = ModemDBRecord.fromRecordDump(dump);
if (!isConfirmed) {
console.println(
"The restore file " + path + " contains " + records.size() + " database records:");
print(console, records.stream().map(ModemDBRecord::toString).toList());
console.println("Please run the same command with " + CONFIRM_OPTION
+ " option to have these database records restored to modem " + address + ".");
} else {
console.println("Restoring " + records.size() + " database records to modem " + address
+ " from " + path + "...");
records.forEach(record -> getModem().getDB().markRecordForAddOrModify(record.getAddress(),
record.getGroup(), record.isController(), record.getData()));
getModem().getDB().update();
}
}
} catch (IllegalArgumentException e) {
console.println("The restore file " + path + " is invalid.");
} catch (IOException e) {
console.println("Failed to read restore file: " + e.getMessage());
}
}
}

private void addDatabaseRecord(Console console, String[] args, boolean isController) {
if (!getModem().getDB().isComplete()) {
console.println("The modem database is not loaded yet.");
Expand Down Expand Up @@ -405,6 +514,19 @@ private void removeDevice(Console console, String address, boolean force) {
}
}

private void resetModem(Console console, boolean isConfirmed) {
InsteonAddress address = getModem().getAddress();
if (InsteonAddress.UNKNOWN.equals(address)) {
console.println("No modem found!");
} else if (!isConfirmed) {
console.println("Please run the same command with " + CONFIRM_OPTION + " option to reset modem " + address
+ " to factory defaults.");
} else {
console.println("Resetting modem " + address + " to factory defaults...");
getModem().reset();
}
}

private void switchModem(Console console, String thingId) {
InsteonBridgeHandler handler = getBridgeHandler(thingId);
if (handler == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -980,7 +980,7 @@ public static InsteonDevice makeDevice(InsteonAddress address, @Nullable Insteon
device.setFlags(deviceType.getFlags());
}
int location = productData.getFirstRecordLocation();
if (location != LinkDBRecord.LOCATION_ZERO) {
if (location != 0) {
device.getLinkDB().setFirstRecordLocation(location);
}
device.setProductData(productData);
Expand Down
Loading

0 comments on commit 7ec79ca

Please sign in to comment.