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.
 
 
 
 

293 lines
8.6 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using Windows.Security.Cryptography.Certificates;
  5. using Windows.UI.Core;
  6. using Windows.UI.Xaml;
  7. using MQTTnet.Core;
  8. using MQTTnet.Core.Client;
  9. using MQTTnet.Core.Diagnostics;
  10. using MQTTnet.Core.Packets;
  11. using MQTTnet.Core.Protocol;
  12. using MQTTnet.Core.Server;
  13. using MQTTnet.Implementations;
  14. namespace MQTTnet.TestApp.UniversalWindows
  15. {
  16. public sealed partial class MainPage
  17. {
  18. private IMqttClient _mqttClient;
  19. public MainPage()
  20. {
  21. InitializeComponent();
  22. MqttNetTrace.TraceMessagePublished += OnTraceMessagePublished;
  23. }
  24. private async void OnTraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
  25. {
  26. await Trace.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
  27. {
  28. var text = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{e.Level}] [{e.Source}] [{e.ThreadId}] [{e.Message}]{Environment.NewLine}";
  29. if (e.Exception != null)
  30. {
  31. text += $"{e.Exception}{Environment.NewLine}";
  32. }
  33. Trace.Text += text;
  34. });
  35. }
  36. private async void Connect(object sender, RoutedEventArgs e)
  37. {
  38. MqttClientOptions options = null;
  39. if (UseTcp.IsChecked == true)
  40. {
  41. options = new MqttClientTcpOptions
  42. {
  43. Server = Server.Text
  44. };
  45. }
  46. if (UseWs.IsChecked == true)
  47. {
  48. options = new MqttClientWebSocketOptions
  49. {
  50. Uri = Server.Text
  51. };
  52. }
  53. if (options == null)
  54. {
  55. throw new InvalidOperationException();
  56. }
  57. options.UserName = User.Text;
  58. options.Password = Password.Text;
  59. options.ClientId = ClientId.Text;
  60. options.TlsOptions.UseTls = UseTls.IsChecked == true;
  61. options.TlsOptions.IgnoreCertificateChainErrors = true;
  62. options.TlsOptions.IgnoreCertificateRevocationErrors = true;
  63. options.TlsOptions.AllowUntrustedCertificates = true;
  64. try
  65. {
  66. if (_mqttClient != null)
  67. {
  68. await _mqttClient.DisconnectAsync();
  69. }
  70. var factory = new MqttClientFactory();
  71. _mqttClient = factory.CreateMqttClient();
  72. await _mqttClient.ConnectAsync(options);
  73. }
  74. catch (Exception exception)
  75. {
  76. Trace.Text += exception + Environment.NewLine;
  77. }
  78. }
  79. private async void Publish(object sender, RoutedEventArgs e)
  80. {
  81. if (_mqttClient == null)
  82. {
  83. return;
  84. }
  85. try
  86. {
  87. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  88. if (QoS1.IsChecked == true)
  89. {
  90. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  91. }
  92. if (QoS2.IsChecked == true)
  93. {
  94. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  95. }
  96. var payload = new byte[0];
  97. if (Text.IsChecked == true)
  98. {
  99. payload = Encoding.UTF8.GetBytes(Payload.Text);
  100. }
  101. if (Base64.IsChecked == true)
  102. {
  103. payload = Convert.FromBase64String(Payload.Text);
  104. }
  105. var message = new MqttApplicationMessage(
  106. Topic.Text,
  107. payload,
  108. qos,
  109. Retain.IsChecked == true);
  110. await _mqttClient.PublishAsync(message);
  111. }
  112. catch (Exception exception)
  113. {
  114. Trace.Text += exception + Environment.NewLine;
  115. }
  116. }
  117. private async void Disconnect(object sender, RoutedEventArgs e)
  118. {
  119. try
  120. {
  121. await _mqttClient.DisconnectAsync();
  122. }
  123. catch (Exception exception)
  124. {
  125. Trace.Text += exception + Environment.NewLine;
  126. }
  127. }
  128. private void Clear(object sender, RoutedEventArgs e)
  129. {
  130. Trace.Text = string.Empty;
  131. }
  132. private async void Subscribe(object sender, RoutedEventArgs e)
  133. {
  134. if (_mqttClient == null)
  135. {
  136. return;
  137. }
  138. try
  139. {
  140. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  141. if (SubscribeQoS1.IsChecked == true)
  142. {
  143. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  144. }
  145. if (SubscribeQoS2.IsChecked == true)
  146. {
  147. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  148. }
  149. await _mqttClient.SubscribeAsync(new TopicFilter(SubscribeTopic.Text, qos));
  150. }
  151. catch (Exception exception)
  152. {
  153. Trace.Text += exception + Environment.NewLine;
  154. }
  155. }
  156. private async void Unsubscribe(object sender, RoutedEventArgs e)
  157. {
  158. if (_mqttClient == null)
  159. {
  160. return;
  161. }
  162. try
  163. {
  164. await _mqttClient.UnsubscribeAsync(SubscribeTopic.Text);
  165. }
  166. catch (Exception exception)
  167. {
  168. Trace.Text += exception + Environment.NewLine;
  169. }
  170. }
  171. private async Task WikiCode()
  172. {
  173. var mqttClient = new MqttClientFactory().CreateMqttClient();
  174. // ----------------------------------
  175. var tcpOptions = new MqttClientTcpOptions
  176. {
  177. Server = "broker.hivemq.org",
  178. ClientId = "TestClient"
  179. };
  180. await mqttClient.ConnectAsync(tcpOptions);
  181. // ----------------------------------
  182. var secureTcpOptions = new MqttClientTcpOptions
  183. {
  184. Server = "broker.hivemq.org",
  185. ClientId = "TestClient",
  186. TlsOptions = new MqttClientTlsOptions
  187. {
  188. UseTls = true,
  189. IgnoreCertificateChainErrors = true,
  190. IgnoreCertificateRevocationErrors = true,
  191. AllowUntrustedCertificates = true
  192. }
  193. };
  194. // ----------------------------------
  195. var wsOptions = new MqttClientWebSocketOptions
  196. {
  197. Uri = "broker.hivemq.com:8000/mqtt",
  198. ClientId = "TestClient"
  199. };
  200. await mqttClient.ConnectAsync(wsOptions);
  201. // ----------------------------------
  202. {
  203. var options = new MqttServerOptions();
  204. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  205. await mqttServer.StartAsync();
  206. Console.WriteLine("Press any key to exit.");
  207. Console.ReadLine();
  208. await mqttServer.StopAsync();
  209. }
  210. // ----------------------------------
  211. {
  212. var options = new MqttServerOptions
  213. {
  214. ConnectionValidator = c =>
  215. {
  216. if (c.ClientId.Length < 10)
  217. {
  218. return MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
  219. }
  220. if (c.Username != "mySecretUser")
  221. {
  222. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  223. }
  224. if (c.Password != "mySecretPassword")
  225. {
  226. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  227. }
  228. return MqttConnectReturnCode.ConnectionAccepted;
  229. }
  230. };
  231. }
  232. // ----------------------------------
  233. // For UWP apps:
  234. MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
  235. {
  236. if (o.Server == "server_with_revoked_cert")
  237. {
  238. return new[] { ChainValidationResult.Revoked };
  239. }
  240. return new ChainValidationResult[0];
  241. };
  242. }
  243. }
  244. }