DataBroker.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. private DataBroker()
  31. {
  32. server = new MqttFactory().CreateMqttServer();
  33. var service = new ServiceProfile("VRCyclingControllers", "_mqtt._tcp", 1883,
  34. new[] {Helpers.GetIPAddress()});
  35. var sd = new ServiceDiscovery();
  36. sd.Advertise(service);
  37. serverStarted = server.StartAsync(new MqttServerOptions());
  38. server.ClientSubscribedTopicHandler =
  39. new MqttServerClientSubscribedHandlerDelegate(OnClientSubscribedTopic);
  40. Debug.Log($"Mqtt Server started at {Helpers.GetIPAddress()}");
  41. //await PublishBla();
  42. }
  43. public async Task AwaitServerStarted()
  44. {
  45. await serverStarted;
  46. }
  47. public async Task Publish(string topic, string payload)
  48. {
  49. Debug.Assert(server.IsStarted);
  50. await server.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic)
  51. .WithPayload($"{payload}\0").Build());
  52. }
  53. private void OnClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs args)
  54. {
  55. //TODO: show in game!
  56. Debug.Log($"Client {args.ClientId} subscribed to topic {args.TopicFilter.Topic}");
  57. }
  58. private async void Dispose()
  59. {
  60. if (!server.IsStarted) return;
  61. await server.StopAsync();
  62. disposed = true;
  63. }
  64. }
  65. }