DataBroker.cs 2.3 KB

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