DataBroker.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. Debug.Log("Mqtt Server started");
  39. //await PublishBla();
  40. }
  41. public async Task AwaitServerStarted()
  42. {
  43. await serverStarted;
  44. }
  45. public async Task Publish(string topic, string payload)
  46. {
  47. Debug.Assert(server.IsStarted);
  48. await server.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(topic)
  49. .WithPayload($"{payload}\0").Build());
  50. }
  51. private async void Dispose()
  52. {
  53. if (!server.IsStarted) return;
  54. await server.StopAsync();
  55. disposed = true;
  56. }
  57. }
  58. }