No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

296 líneas
8.8 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 = $"[{e.TraceMessage.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{e.TraceMessage.Level}] [{e.TraceMessage.Source}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Message}]{Environment.NewLine}";
  29. if (e.TraceMessage.Exception != null)
  30. {
  31. text += $"{e.TraceMessage.Exception}{Environment.NewLine}";
  32. }
  33. Trace.Text += text;
  34. });
  35. }
  36. private async void Connect(object sender, RoutedEventArgs e)
  37. {
  38. BaseMqttClientOptions 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 MqttApplicationMessageBuilder()
  106. .WithTopic(Topic.Text)
  107. .WithPayload(payload)
  108. .WithQualityOfServiceLevel(qos)
  109. .WithRetainFlag(Retain.IsChecked == true)
  110. .Build();
  111. await _mqttClient.PublishAsync(message);
  112. }
  113. catch (Exception exception)
  114. {
  115. Trace.Text += exception + Environment.NewLine;
  116. }
  117. }
  118. private async void Disconnect(object sender, RoutedEventArgs e)
  119. {
  120. try
  121. {
  122. await _mqttClient.DisconnectAsync();
  123. }
  124. catch (Exception exception)
  125. {
  126. Trace.Text += exception + Environment.NewLine;
  127. }
  128. }
  129. private void Clear(object sender, RoutedEventArgs e)
  130. {
  131. Trace.Text = string.Empty;
  132. }
  133. private async void Subscribe(object sender, RoutedEventArgs e)
  134. {
  135. if (_mqttClient == null)
  136. {
  137. return;
  138. }
  139. try
  140. {
  141. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  142. if (SubscribeQoS1.IsChecked == true)
  143. {
  144. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  145. }
  146. if (SubscribeQoS2.IsChecked == true)
  147. {
  148. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  149. }
  150. await _mqttClient.SubscribeAsync(new TopicFilter(SubscribeTopic.Text, qos));
  151. }
  152. catch (Exception exception)
  153. {
  154. Trace.Text += exception + Environment.NewLine;
  155. }
  156. }
  157. private async void Unsubscribe(object sender, RoutedEventArgs e)
  158. {
  159. if (_mqttClient == null)
  160. {
  161. return;
  162. }
  163. try
  164. {
  165. await _mqttClient.UnsubscribeAsync(SubscribeTopic.Text);
  166. }
  167. catch (Exception exception)
  168. {
  169. Trace.Text += exception + Environment.NewLine;
  170. }
  171. }
  172. // This code is for the Wiki at GitHub!
  173. // ReSharper disable once UnusedMember.Local
  174. private async Task WikiCode()
  175. {
  176. var mqttClient = new MqttClientFactory().CreateMqttClient();
  177. // ----------------------------------
  178. var tcpOptions = new MqttClientTcpOptions
  179. {
  180. Server = "broker.hivemq.org",
  181. ClientId = "TestClient"
  182. };
  183. await mqttClient.ConnectAsync(tcpOptions);
  184. // ----------------------------------
  185. var secureTcpOptions = new MqttClientTcpOptions
  186. {
  187. Server = "broker.hivemq.org",
  188. ClientId = "TestClient",
  189. TlsOptions = new MqttClientTlsOptions
  190. {
  191. UseTls = true,
  192. IgnoreCertificateChainErrors = true,
  193. IgnoreCertificateRevocationErrors = true,
  194. AllowUntrustedCertificates = true
  195. }
  196. };
  197. // ----------------------------------
  198. var wsOptions = new MqttClientWebSocketOptions
  199. {
  200. Uri = "broker.hivemq.com:8000/mqtt",
  201. ClientId = "TestClient"
  202. };
  203. await mqttClient.ConnectAsync(wsOptions);
  204. // ----------------------------------
  205. {
  206. var options = new MqttServerOptions();
  207. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  208. await mqttServer.StartAsync();
  209. Console.WriteLine("Press any key to exit.");
  210. Console.ReadLine();
  211. await mqttServer.StopAsync();
  212. }
  213. // ----------------------------------
  214. {
  215. var options = new MqttServerOptions
  216. {
  217. ConnectionValidator = c =>
  218. {
  219. if (c.ClientId.Length < 10)
  220. {
  221. return MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
  222. }
  223. if (c.Username != "mySecretUser")
  224. {
  225. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  226. }
  227. if (c.Password != "mySecretPassword")
  228. {
  229. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  230. }
  231. return MqttConnectReturnCode.ConnectionAccepted;
  232. }
  233. };
  234. }
  235. // ----------------------------------
  236. // For UWP apps:
  237. MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
  238. {
  239. if (o.Server == "server_with_revoked_cert")
  240. {
  241. return new[] { ChainValidationResult.Revoked };
  242. }
  243. return new ChainValidationResult[0];
  244. };
  245. }
  246. }
  247. }