using System; using System.Net; using System.Threading.Tasks; using Makaretu.Dns; using MQTTnet; using MQTTnet.Server; using Sensors; using UnityEngine; namespace SicknessReduction.Haptic { public sealed class DataBroker { #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 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()); Debug.Log($"Mqtt Server started at {Helpers.GetIPAddress()}"); //await PublishBla(); } 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 async void Dispose() { if (!server.IsStarted) return; await server.StopAsync(); disposed = true; } } }