2 * Copyright (c) 2010-2022 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.ipp.internal.discovery;
15 import static org.openhab.binding.ipp.internal.IppBindingConstants.*;
17 import java.net.InetAddress;
21 import javax.jmdns.ServiceInfo;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.core.config.discovery.DiscoveryResult;
26 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
27 import org.openhab.core.config.discovery.mdns.MDNSDiscoveryParticipant;
28 import org.openhab.core.thing.ThingTypeUID;
29 import org.openhab.core.thing.ThingUID;
30 import org.osgi.service.component.annotations.Component;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * discovers ipp printers announced by mDNS
37 * @author Tobias Bräutigam - Initial contribution
41 public class IppPrinterDiscoveryParticipant implements MDNSDiscoveryParticipant {
43 private final Logger logger = LoggerFactory.getLogger(IppPrinterDiscoveryParticipant.class);
46 public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
47 return Set.of(PRINTER_THING_TYPE);
51 public String getServiceType() {
52 return "_ipp._tcp.local.";
56 public @Nullable ThingUID getThingUID(ServiceInfo service) {
57 logger.trace("ServiceInfo: {}", service);
58 if (getServiceType().equals(service.getType())) {
59 String uidName = getUIDName(service);
60 return new ThingUID(PRINTER_THING_TYPE, uidName);
65 private String getUIDName(ServiceInfo service) {
66 return service.getName().replaceAll("[^A-Za-z0-9_]", "_");
69 private @Nullable InetAddress getIpAddress(ServiceInfo service) {
70 for (InetAddress addr : service.getInet4Addresses()) {
73 // Fallback for Inet6addresses
74 for (InetAddress addr : service.getInet6Addresses()) {
81 public @Nullable DiscoveryResult createResult(ServiceInfo service) {
82 String rp = service.getPropertyString("rp");
86 ThingUID uid = getThingUID(service);
88 // remove the domain from the name
89 InetAddress ip = getIpAddress(service);
93 String inetAddress = ip.toString().substring(1); // trim leading slash
94 String label = service.getName();
95 int port = service.getPort();
96 String uuid = service.getPropertyString("UUID");
98 Map<String, Object> properties = Map.of( //
99 PRINTER_PARAMETER_URL, "http://" + inetAddress + ":" + port + "/" + rp, //
100 PRINTER_PARAMETER_NAME, label, //
101 PRINTER_PARAMETER_UUID, uuid //
104 return DiscoveryResultBuilder.create(uid).withProperties(properties)
105 .withRepresentationProperty(PRINTER_PARAMETER_UUID).withLabel(label).build();