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.mynice.internal.discovery;
15 import static org.openhab.binding.mynice.internal.MyNiceBindingConstants.BRIDGE_TYPE_IT4WIFI;
16 import static org.openhab.binding.mynice.internal.config.It4WifiConfiguration.HOSTNAME;
17 import static org.openhab.core.thing.Thing.PROPERTY_MAC_ADDRESS;
21 import java.util.regex.Pattern;
23 import javax.jmdns.ServiceInfo;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.core.config.discovery.DiscoveryResult;
28 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
29 import org.openhab.core.config.discovery.mdns.MDNSDiscoveryParticipant;
30 import org.openhab.core.thing.ThingTypeUID;
31 import org.openhab.core.thing.ThingUID;
32 import org.osgi.service.component.annotations.Component;
35 * The {@link MyNiceDiscoveryParticipant} is responsible for discovering the IT4Wifi bridge using mDNS discovery service
37 * @author Gaƫl L'hopital - Initial contribution
41 public class MyNiceDiscoveryParticipant implements MDNSDiscoveryParticipant {
42 private static final String PROPERTY_MODEL = "model";
43 private static final String PROPERTY_DEVICE_ID = "deviceid";
44 private static final String MAC_REGEX = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}\\.[0-9a-fA-F]{4}\\.[0-9a-fA-F]{4})$";
45 private static final Pattern MAC_PATTERN = Pattern.compile(MAC_REGEX);
48 public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
49 return Set.of(BRIDGE_TYPE_IT4WIFI);
53 public String getServiceType() {
54 return "_nap._tcp.local.";
58 public @Nullable DiscoveryResult createResult(ServiceInfo service) {
59 ThingUID thingUID = getThingUID(service);
60 String[] hostNames = service.getHostAddresses();
61 if (thingUID != null && hostNames.length > 0) {
62 String label = service.getPropertyString(PROPERTY_MODEL);
63 String macAddress = service.getPropertyString(PROPERTY_DEVICE_ID);
65 return DiscoveryResultBuilder.create(thingUID).withLabel(label)
66 .withRepresentationProperty(PROPERTY_MAC_ADDRESS).withThingType(BRIDGE_TYPE_IT4WIFI)
67 .withProperties(Map.of(HOSTNAME, hostNames[0], PROPERTY_MAC_ADDRESS, macAddress)).build();
73 public @Nullable ThingUID getThingUID(ServiceInfo service) {
74 String macAddress = service.getPropertyString(PROPERTY_DEVICE_ID);
75 if (macAddress != null && validate(macAddress)) {
76 macAddress = macAddress.replaceAll("[^a-fA-F0-9]", "").toLowerCase();
77 return new ThingUID(BRIDGE_TYPE_IT4WIFI, macAddress);
82 private boolean validate(String mac) {
83 return MAC_PATTERN.matcher(mac).find();