001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.net;
006
007import edu.wpi.first.util.WPICleaner;
008import java.lang.ref.Cleaner.Cleanable;
009import java.util.Map;
010
011/** Class to announce over mDNS that a service is available. */
012public class MulticastServiceAnnouncer implements AutoCloseable {
013  private final int m_handle;
014  private final Cleanable m_cleanable;
015
016  private static Runnable cleanupAction(int handle) {
017    return () -> WPINetJNI.freeMulticastServiceAnnouncer(handle);
018  }
019
020  /**
021   * Creates a MulticastServiceAnnouncer.
022   *
023   * @param serviceName service name
024   * @param serviceType service type
025   * @param port port
026   * @param txt txt
027   */
028  public MulticastServiceAnnouncer(
029      String serviceName, String serviceType, int port, Map<String, String> txt) {
030    String[] keys = txt.keySet().toArray(String[]::new);
031    String[] values = txt.values().toArray(String[]::new);
032    m_handle =
033        WPINetJNI.createMulticastServiceAnnouncer(serviceName, serviceType, port, keys, values);
034    m_cleanable = WPICleaner.register(this, cleanupAction(m_handle));
035  }
036
037  /**
038   * Creates a MulticastServiceAnnouncer.
039   *
040   * @param serviceName service name
041   * @param serviceType service type
042   * @param port port
043   */
044  public MulticastServiceAnnouncer(String serviceName, String serviceType, int port) {
045    m_handle =
046        WPINetJNI.createMulticastServiceAnnouncer(serviceName, serviceType, port, null, null);
047    m_cleanable = WPICleaner.register(this, cleanupAction(m_handle));
048  }
049
050  @Override
051  public void close() {
052    m_cleanable.clean();
053  }
054
055  public void start() {
056    WPINetJNI.startMulticastServiceAnnouncer(m_handle);
057  }
058
059  public void stop() {
060    WPINetJNI.stopMulticastServiceAnnouncer(m_handle);
061  }
062
063  public boolean hasImplementation() {
064    return WPINetJNI.getMulticastServiceAnnouncerHasImplementation(m_handle);
065  }
066}