1
0

DataBroker.cs 1.3 KB

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