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.minecraft.internal.discovery;
15 import java.util.Collections;
16 import java.util.HashMap;
20 import javax.jmdns.ServiceInfo;
22 import org.openhab.binding.minecraft.internal.MinecraftBindingConstants;
23 import org.openhab.core.config.discovery.DiscoveryResult;
24 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
25 import org.openhab.core.config.discovery.mdns.MDNSDiscoveryParticipant;
26 import org.openhab.core.thing.ThingTypeUID;
27 import org.openhab.core.thing.ThingUID;
28 import org.osgi.service.component.annotations.Component;
31 * The {@link MinecraftMDNSDiscoveryParticipant} is responsible for discovering Minecraft servers
32 * {@link MDNSDiscoveryService}.
34 * @author Mattias Markehed - Initial contribution
37 public class MinecraftMDNSDiscoveryParticipant implements MDNSDiscoveryParticipant {
40 public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
41 return Collections.singleton(MinecraftBindingConstants.THING_TYPE_SERVER);
45 public String getServiceType() {
46 return "_http._tcp.local.";
50 public DiscoveryResult createResult(ServiceInfo service) {
51 if (service.getName().equals("wc-minecraft")) {
52 ThingUID uid = getThingUID(service);
55 Map<String, Object> properties = new HashMap<>();
56 int port = service.getPort();
57 String host = service.getInetAddresses()[0].getHostAddress();
59 properties.put(MinecraftBindingConstants.PARAMETER_HOSTNAME, host);
60 properties.put(MinecraftBindingConstants.PARAMETER_PORT, port);
62 return DiscoveryResultBuilder.create(uid).withProperties(properties)
63 .withRepresentationProperty(uid.getId()).withLabel("Minecraft Server (" + host + ")").build();
70 * Check if service is a minecraft server.
72 * @param service the service to check.
73 * @return true if minecraft server, else false.
75 private boolean isMinecraftServer(ServiceInfo service) {
76 return (service != null && service.getType() != null && service.getType().equals(getServiceType()));
80 public ThingUID getThingUID(ServiceInfo service) {
81 if (isMinecraftServer(service) && service.getInetAddresses().length > 0) {
82 String host = service.getInetAddresses()[0].getHostAddress();
83 host = host.replace('.', '_');
85 return new ThingUID(MinecraftBindingConstants.THING_TYPE_SERVER, host);