Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

64 righe
2.0 KiB

  1. using System;
  2. using System.Threading.Tasks;
  3. using MQTTnet.Core.Adapter;
  4. using MQTTnet.Core.Server;
  5. using MQTTnet.Core.Client;
  6. using MQTTnet.Core.Diagnostics;
  7. namespace MQTTnet.Core.Tests
  8. {
  9. public class TestMqttServerAdapter : IMqttServerAdapter
  10. {
  11. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  12. public async Task<MqttClient> ConnectTestClient(IMqttServer server, string clientId, MqttApplicationMessage willMessage = null)
  13. {
  14. var adapterA = new TestMqttCommunicationAdapter();
  15. var adapterB = new TestMqttCommunicationAdapter();
  16. adapterA.Partner = adapterB;
  17. adapterB.Partner = adapterA;
  18. var client = new MqttClient(new MqttCommunicationAdapterFactory(adapterA), new MqttNetTrace());
  19. var connected = WaitForClientToConnect(server, clientId);
  20. FireClientAcceptedEvent(adapterB);
  21. await client.ConnectAsync(new MqttClientTcpOptions { ClientId = clientId, WillMessage = willMessage });
  22. await connected;
  23. return client;
  24. }
  25. private static Task WaitForClientToConnect(IMqttServer s, string clientId)
  26. {
  27. var tcs = new TaskCompletionSource<object>();
  28. void Handler(object sender, Server.MqttClientConnectedEventArgs args)
  29. {
  30. if (args.Client.ClientId == clientId)
  31. {
  32. s.ClientConnected -= Handler;
  33. tcs.SetResult(null);
  34. }
  35. }
  36. s.ClientConnected += Handler;
  37. return tcs.Task;
  38. }
  39. private void FireClientAcceptedEvent(IMqttCommunicationAdapter adapter)
  40. {
  41. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(adapter));
  42. }
  43. public Task StartAsync(MqttServerOptions options)
  44. {
  45. return Task.FromResult(0);
  46. }
  47. public Task StopAsync()
  48. {
  49. return Task.FromResult(0);
  50. }
  51. }
  52. }