Não pode escolher mais do que 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.
 
 
 
 

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