DataBroker.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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) 7})});
  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("Fan/0/Control")
  27. .WithPayload("Hallihallo\0").Build());
  28. }
  29. private async void Update()
  30. {
  31. var dif = Time.time - lastTime;
  32. if (dif > 4f)
  33. {
  34. lastTime = Time.time;
  35. //TODO: publish proper data
  36. //await PublishBla();
  37. }
  38. }
  39. private async void OnDestroy()
  40. {
  41. if (!server.IsStarted) return;
  42. await server.StopAsync();
  43. }
  44. }
  45. }