DataBroker.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Threading.Tasks;
  3. using Makaretu.Dns;
  4. using MQTTnet;
  5. using MQTTnet.Server;
  6. using UnityEngine;
  7. namespace SicknessReduction.Haptic
  8. {
  9. public sealed class DataBroker
  10. {
  11. private readonly IMqttServer server;
  12. private readonly Task serverStarted;
  13. private bool disposed;
  14. private DataBroker()
  15. {
  16. server = new MqttFactory().CreateMqttServer();
  17. var service = new ServiceProfile("VRCyclingControllers", "_mqtt._tcp", 1883,
  18. new[] {Helpers.GetIPAddress()});
  19. var sd = new ServiceDiscovery();
  20. sd.Advertise(service);
  21. serverStarted = server.StartAsync(new MqttServerOptions());
  22. server.ClientSubscribedTopicHandler =
  23. new MqttServerClientSubscribedHandlerDelegate(OnClientSubscribedTopic);
  24. Debug.Log($"Mqtt Server started at {Helpers.GetIPAddress()}");
  25. //await PublishBla();
  26. }
  27. public Action<string, string> onClientSubscribed { set; get; }
  28. public async Task AwaitServerStarted()
  29. {
  30. await serverStarted;
  31. }
  32. public async Task Publish(string topic, string payload)
  33. {
  34. Debug.Assert(server.IsStarted);
  35. await server.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic)
  36. .WithPayload($"{payload}\0").Build());
  37. }
  38. private void OnClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs args)
  39. {
  40. Debug.Log($"Client {args.ClientId} subscribed to topic {args.TopicFilter.Topic}");
  41. onClientSubscribed?.Invoke(args.ClientId, args.TopicFilter.Topic);
  42. }
  43. private async void Dispose()
  44. {
  45. if (server == null || !server.IsStarted) return;
  46. await server.StopAsync();
  47. disposed = true;
  48. }
  49. #region signleton
  50. private static readonly Lazy<DataBroker>
  51. lazy =
  52. new Lazy<DataBroker>
  53. (() => new DataBroker());
  54. public static DataBroker Instance => lazy.Value;
  55. public static void DisposeInstance()
  56. {
  57. if (!Instance.disposed) Instance.Dispose();
  58. }
  59. #endregion
  60. }
  61. }