123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- 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;
- public Action<string, string> onClientSubscribed { set; get; }
- 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());
- server.ClientSubscribedTopicHandler =
- new MqttServerClientSubscribedHandlerDelegate(OnClientSubscribedTopic);
- 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 void OnClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs args)
- {
- Debug.Log($"Client {args.ClientId} subscribed to topic {args.TopicFilter.Topic}");
- onClientSubscribed?.Invoke(args.ClientId, args.TopicFilter.Topic);
- }
- private async void Dispose()
- {
- if (server == null || !server.IsStarted) return;
- await server.StopAsync();
- disposed = true;
- }
- }
- }
|