using System; using System.Threading.Tasks; using Makaretu.Dns; using MQTTnet; using MQTTnet.Server; using UnityEngine; namespace SicknessReduction.Haptic { public sealed class DataBroker { private readonly IMqttServer server; private readonly Task serverStarted; private bool disposed; private DataBroker() { server = new MqttFactory().CreateMqttServer(); var service = new ServiceProfile("VRCyclingControllers", "_mqtt._tcp", 1883, new[] {Helpers.GetIPAddress()}); var sd = new ServiceDiscovery(); sd.Advertise(service); serverStarted = server.StartAsync(new MqttServerOptions()); server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(OnClientSubscribedTopic); Debug.Log($"Mqtt Server started at {Helpers.GetIPAddress()}"); //await PublishBla(); } public Action onClientSubscribed { set; get; } public async Task AwaitServerStarted() { await serverStarted; } public async Task Publish(string topic, string payload) { Debug.Assert(server.IsStarted); await server.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic) .WithPayload($"{payload}\0").Build()); } private void OnClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs args) { Debug.Log($"Client {args.ClientId} subscribed to topic {args.TopicFilter.Topic}"); onClientSubscribed?.Invoke(args.ClientId, args.TopicFilter.Topic); } private async void Dispose() { if (server == null || !server.IsStarted) return; await server.StopAsync(); disposed = true; } #region signleton private static readonly Lazy lazy = new Lazy (() => new DataBroker()); public static DataBroker Instance => lazy.Value; public static void DisposeInstance() { if (!Instance.disposed) Instance.Dispose(); } #endregion } }