Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

75 linhas
2.2 KiB

  1. using System;
  2. using System.Threading.Tasks;
  3. using MQTTnet.Adapter;
  4. using MQTTnet.Client;
  5. using MQTTnet.Diagnostics;
  6. using MQTTnet.Server;
  7. namespace MQTTnet.Core.Tests
  8. {
  9. public class TestMqttServerAdapter : IMqttServerAdapter
  10. {
  11. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  12. public async Task<IMqttClient> 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(
  19. new TestMqttCommunicationAdapterFactory(adapterA),
  20. new MqttNetLogger());
  21. var connected = WaitForClientToConnect(server, clientId);
  22. FireClientAcceptedEvent(adapterB);
  23. var options = new MqttClientOptions
  24. {
  25. ClientId = clientId,
  26. WillMessage = willMessage,
  27. ChannelOptions = new MqttClientTcpOptions()
  28. };
  29. await client.ConnectAsync(options);
  30. await connected;
  31. return client;
  32. }
  33. private static Task WaitForClientToConnect(IMqttServer s, string clientId)
  34. {
  35. var tcs = new TaskCompletionSource<object>();
  36. void Handler(object sender, Server.MqttClientConnectedEventArgs args)
  37. {
  38. if (args.Client.ClientId == clientId)
  39. {
  40. s.ClientConnected -= Handler;
  41. tcs.SetResult(null);
  42. }
  43. }
  44. s.ClientConnected += Handler;
  45. return tcs.Task;
  46. }
  47. private void FireClientAcceptedEvent(IMqttChannelAdapter adapter)
  48. {
  49. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(adapter));
  50. }
  51. public Task StartAsync(IMqttServerOptions options)
  52. {
  53. return Task.FromResult(0);
  54. }
  55. public Task StopAsync()
  56. {
  57. return Task.FromResult(0);
  58. }
  59. }
  60. }