You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

75 regels
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(
  18. new TestMqttCommunicationAdapterFactory(adapterA),
  19. new TestLogger<MqttClient>(),
  20. new MqttPacketDispatcher(new TestLogger<MqttPacketDispatcher>()));
  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(IMqttCommunicationAdapter adapter)
  48. {
  49. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(adapter));
  50. }
  51. public Task StartAsync(MqttServerOptions options)
  52. {
  53. return Task.FromResult(0);
  54. }
  55. public Task StopAsync()
  56. {
  57. return Task.FromResult(0);
  58. }
  59. }
  60. }