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.
 
 
 
 

79 line
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. public void Dispose()
  60. {
  61. }
  62. }
  63. }