1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- using System;
- using System.Net;
- using System.Threading.Tasks;
- using Makaretu.Dns;
- using MQTTnet;
- using MQTTnet.Server;
- using Sensors;
- using UnityEngine;
- namespace SicknessReduction.Haptic
- {
- public sealed class DataBroker
- {
- #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
-
- 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());
- Debug.Log($"Mqtt Server started at {Helpers.GetIPAddress()}");
- //await PublishBla();
- }
- 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 async void Dispose()
- {
- if (!server.IsStarted) return;
- await server.StopAsync();
- disposed = true;
- }
- }
- }
|