Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[tr064] Enhancements, code improvements and fixes #14468

Merged
merged 10 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@
/bundles/org.openhab.binding.touchwand/ @roieg
/bundles/org.openhab.binding.tplinkrouter/ @olivierkeke
/bundles/org.openhab.binding.tplinksmarthome/ @Hilbrand
/bundles/org.openhab.binding.tr064/ @openhab/add-ons-maintainers
/bundles/org.openhab.binding.tr064/ @J-N-K
/bundles/org.openhab.binding.tradfri/ @cweitkamp @kaikreuzer
/bundles/org.openhab.binding.twitter/ @computergeek1507
/bundles/org.openhab.binding.unifi/ @mgbowman @Hilbrand
Expand Down
107 changes: 70 additions & 37 deletions bundles/org.openhab.binding.tr064/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,31 @@
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.tr064.internal.phonebook;
package org.openhab.binding.tr064.internal;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import javax.xml.soap.SOAPMessage;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.tr064.internal.Tr064RootHandler;
import org.eclipse.jetty.client.api.ContentResponse;
import org.openhab.binding.tr064.internal.dto.scpd.root.SCPDServiceType;
import org.openhab.binding.tr064.internal.phonebook.Phonebook;
import org.openhab.binding.tr064.internal.soap.SOAPRequest;
import org.openhab.binding.tr064.internal.util.SCPDUtil;
import org.openhab.binding.tr064.internal.util.Util;
import org.openhab.core.automation.annotation.ActionInput;
import org.openhab.core.automation.annotation.ActionOutput;
import org.openhab.core.automation.annotation.RuleAction;
Expand All @@ -28,14 +45,16 @@
import org.slf4j.LoggerFactory;

/**
* The {@link PhonebookActions} is responsible for handling phonebook actions
* The {@link FritzboxActions} is responsible for handling phone book actions
*
* @author Jan N. Klug - Initial contribution
*/
@ThingActionsScope(name = "tr064")
@NonNullByDefault
public class PhonebookActions implements ThingActions {
private final Logger logger = LoggerFactory.getLogger(PhonebookActions.class);
public class FritzboxActions implements ThingActions {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy_HHmm");

private final Logger logger = LoggerFactory.getLogger(FritzboxActions.class);

private @Nullable Tr064RootHandler handler;

Expand Down Expand Up @@ -76,16 +95,67 @@ public class PhonebookActions implements ThingActions {
} else {
int matchCountInt = matchCount == null ? 0 : matchCount;
if (phonebook != null && !phonebook.isEmpty()) {
return handler.getPhonebookByName(phonebook).flatMap(p -> p.lookupNumber(phonenumber, matchCountInt))
.orElse(phonenumber);
return Objects.requireNonNull(handler.getPhonebookByName(phonebook)
.flatMap(p -> p.lookupNumber(phonenumber, matchCountInt)).orElse(phonenumber));
} else {
Collection<Phonebook> phonebooks = handler.getPhonebooks();
return phonebooks.stream().map(p -> p.lookupNumber(phonenumber, matchCountInt))
.filter(Optional::isPresent).map(Optional::get).findAny().orElse(phonenumber);
return Objects.requireNonNull(phonebooks.stream().map(p -> p.lookupNumber(phonenumber, matchCountInt))
.filter(Optional::isPresent).map(Optional::get).findAny().orElse(phonenumber));
}
}
}

@RuleAction(label = "create configuration backup", description = "Creates a configuration backup")
J-N-K marked this conversation as resolved.
Show resolved Hide resolved
public void createConfigurationBackup() {
Tr064RootHandler handler = this.handler;

if (handler == null) {
logger.warn("TR064 action service ThingHandler is null!");
return;
}

SCPDUtil scpdUtil = handler.getSCPDUtil();
if (scpdUtil == null) {
logger.warn("Could not get SCPDUtil, handler seems to be uninitialized.");
return;
}

Optional<SCPDServiceType> scpdService = scpdUtil.getDevice("")
.flatMap(deviceType -> deviceType.getServiceList().stream().filter(
service -> service.getServiceId().equals("urn:DeviceConfig-com:serviceId:DeviceConfig1"))
.findFirst());
if (scpdService.isEmpty()) {
logger.warn("Could not get service.");
return;
}

BackupConfiguration configuration = handler.getBackupConfiguration();
try {
SOAPRequest soapRequest = new SOAPRequest(scpdService.get(), "X_AVM-DE_GetConfigFile",
Map.of("NewX_AVM-DE_Password", configuration.password));
SOAPMessage soapMessage = handler.getSOAPConnector().doSOAPRequestUncached(soapRequest);
String configBackupURL = Util.getSOAPElement(soapMessage, "NewX_AVM-DE_ConfigFileUrl")
.orElseThrow(() -> new Tr064CommunicationException("Empty URL"));

ContentResponse content = handler.getUrl(configBackupURL);

String fileName = String.format("%s %s.export", handler.getFriendlyName(),
DATE_TIME_FORMATTER.format(LocalDateTime.now()));
Path filePath = FileSystems.getDefault().getPath(configuration.directory, fileName);
Path folder = filePath.getParent();
if (folder != null) {
Files.createDirectories(folder);
}
Files.write(filePath, content.getContent());
} catch (Tr064CommunicationException e) {
logger.warn("Failed to get configuration backup URL: {}", e.getMessage());
} catch (InterruptedException | ExecutionException | TimeoutException e) {
logger.warn("Failed to get remote backup file: {}", e.getMessage());
} catch (IOException e) {
logger.warn("Failed to create backup file: {}", e.getMessage());
}
}

public static String phonebookLookup(ThingActions actions, @Nullable String phonenumber,
@Nullable Integer matchCount) {
return phonebookLookup(actions, phonenumber, null, matchCount);
Expand All @@ -102,18 +172,23 @@ public static String phonebookLookup(ThingActions actions, @Nullable String phon

public static String phonebookLookup(ThingActions actions, @Nullable String phonenumber, @Nullable String phonebook,
@Nullable Integer matchCount) {
return ((PhonebookActions) actions).phonebookLookup(phonenumber, phonebook, matchCount);
return ((FritzboxActions) actions).phonebookLookup(phonenumber, phonebook, matchCount);
}

public static void createConfigurationBackup(ThingActions actions) {
((FritzboxActions) actions).createConfigurationBackup();
}

@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof Tr064RootHandler) {
this.handler = (Tr064RootHandler) handler;
}
this.handler = (Tr064RootHandler) handler;
}

@Override
public @Nullable ThingHandler getThingHandler() {
return handler;
}

public record BackupConfiguration(String directory, String password) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public Tr064CommunicationException(String s, Integer httpError, String soapError
super(s);
this.httpError = httpError;
this.soapError = soapError;
};
}

public String getSoapError() {
return soapError;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@

import static org.openhab.binding.tr064.internal.Tr064BindingConstants.*;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -44,7 +42,7 @@
@NonNullByDefault
public class Tr064DiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
private static final int SEARCH_TIME = 5;
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SUBDEVICE);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SUBDEVICE);

private final Logger logger = LoggerFactory.getLogger(Tr064DiscoveryService.class);
private @Nullable Tr064RootHandler bridgeHandler;
Expand Down Expand Up @@ -101,13 +99,12 @@ public void startScan() {
}
ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, UIDUtils.encode(udn));

Map<String, Object> properties = new HashMap<>(2);
properties.put("uuid", udn);
properties.put("deviceType", device.getDeviceType());

DiscoveryResult result = DiscoveryResultBuilder.create(thingUID).withLabel(device.getFriendlyName())
.withBridge(bridgeHandler.getThing().getUID()).withProperties(properties)
.withRepresentationProperty("uuid").build();
DiscoveryResult result = DiscoveryResultBuilder.create(thingUID) //
.withLabel(device.getFriendlyName()) //
.withBridge(bridgeUID) //
.withProperties(Map.of("uuid", udn, "deviceType", device.getDeviceType())) //
.withRepresentationProperty("uuid") //
.build();
thingDiscovered(result);
}
});
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {

if (Tr064RootHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
Tr064RootHandler handler = new Tr064RootHandler((Bridge) thing, httpClient);
if (thingTypeUID.equals(THING_TYPE_FRITZBOX)) {
if (THING_TYPE_FRITZBOX.equals(thingTypeUID)) {
phonebookProfileFactory.registerPhonebookProvider(handler);
}
return handler;
Expand Down
Loading