12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- 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<string, string> 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<DataBroker>
- lazy =
- new Lazy<DataBroker>
- (() => new DataBroker());
- public static DataBroker Instance => lazy.Value;
- public static void DisposeInstance()
- {
- if (!Instance.disposed) Instance.Dispose();
- }
- #endregion
- }
- }
|