2
0

DataBroker.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.Net;
  2. using System.Threading.Tasks;
  3. using Makaretu.Dns;
  4. using MQTTnet;
  5. using MQTTnet.Server;
  6. using UnityEngine;
  7. namespace SicknessReduction.Haptic
  8. {
  9. public class DataBroker : MonoBehaviour
  10. {
  11. private IMqttServer server;
  12. private float lastTime = 0f;
  13. private async void Start()
  14. {
  15. server = new MqttFactory().CreateMqttServer();
  16. var service = new ServiceProfile("blabla", "_mqtt._tcp", 1883,
  17. new[] {new IPAddress(new[] {(byte) 192, (byte) 168, (byte) 1, (byte) 4})});
  18. var sd = new ServiceDiscovery();
  19. sd.Advertise(service);
  20. await server.StartAsync(new MqttServerOptions());
  21. Debug.Log("Mqtt Server started");
  22. await PublishBla();
  23. }
  24. public async Task PublishBla()
  25. {
  26. await server.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("Test/Bla")
  27. .WithPayload("Hallihallo").Build());
  28. }
  29. private async void Update()
  30. {
  31. var dif = Time.time - lastTime;
  32. if (dif > 4f)
  33. {
  34. lastTime = Time.time;
  35. await PublishBla();
  36. }
  37. }
  38. private async void OnDestroy()
  39. {
  40. if (!server.IsStarted) return;
  41. await server.StopAsync();
  42. }
  43. }
  44. }