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.

TestMqttServerAdapter.cs 2.3 KiB

7 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. }