Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

355 linhas
11 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 Microsoft.Extensions.DependencyInjection;
  8. using MQTTnet.Core;
  9. using MQTTnet.Core.Client;
  10. using MQTTnet.Core.Diagnostics;
  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. private IMqttServer _mqttServer;
  20. public MainPage()
  21. {
  22. InitializeComponent();
  23. MqttNetTrace.TraceMessagePublished += OnTraceMessagePublished;
  24. }
  25. private async void OnTraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
  26. {
  27. await Trace.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
  28. {
  29. 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}";
  30. if (e.TraceMessage.Exception != null)
  31. {
  32. text += $"{e.TraceMessage.Exception}{Environment.NewLine}";
  33. }
  34. Trace.Text += text;
  35. });
  36. }
  37. private async void Connect(object sender, RoutedEventArgs e)
  38. {
  39. var tlsOptions = new MqttClientTlsOptions
  40. {
  41. UseTls = UseTls.IsChecked == true,
  42. IgnoreCertificateChainErrors = true,
  43. IgnoreCertificateRevocationErrors = true,
  44. AllowUntrustedCertificates = true
  45. };
  46. var options = new MqttClientOptions { ClientId = ClientId.Text };
  47. if (UseTcp.IsChecked == true)
  48. {
  49. options.ChannelOptions = new MqttClientTcpOptions
  50. {
  51. Server = Server.Text,
  52. TlsOptions = tlsOptions
  53. };
  54. }
  55. if (UseWs.IsChecked == true)
  56. {
  57. options.ChannelOptions = new MqttClientWebSocketOptions
  58. {
  59. Uri = Server.Text,
  60. TlsOptions = tlsOptions
  61. };
  62. }
  63. if (options.ChannelOptions == null)
  64. {
  65. throw new InvalidOperationException();
  66. }
  67. options.Credentials = new MqttClientCredentials
  68. {
  69. Username = User.Text,
  70. Password = Password.Text
  71. };
  72. options.CleanSession = CleanSession.IsChecked == true;
  73. try
  74. {
  75. if (_mqttClient != null)
  76. {
  77. await _mqttClient.DisconnectAsync();
  78. }
  79. var factory = new MqttFactory();
  80. _mqttClient = factory.CreateMqttClient();
  81. await _mqttClient.ConnectAsync(options);
  82. }
  83. catch (Exception exception)
  84. {
  85. Trace.Text += exception + Environment.NewLine;
  86. }
  87. }
  88. private async void Publish(object sender, RoutedEventArgs e)
  89. {
  90. if (_mqttClient == null)
  91. {
  92. return;
  93. }
  94. try
  95. {
  96. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  97. if (QoS1.IsChecked == true)
  98. {
  99. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  100. }
  101. if (QoS2.IsChecked == true)
  102. {
  103. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  104. }
  105. var payload = new byte[0];
  106. if (Text.IsChecked == true)
  107. {
  108. payload = Encoding.UTF8.GetBytes(Payload.Text);
  109. }
  110. if (Base64.IsChecked == true)
  111. {
  112. payload = Convert.FromBase64String(Payload.Text);
  113. }
  114. var message = new MqttApplicationMessageBuilder()
  115. .WithTopic(Topic.Text)
  116. .WithPayload(payload)
  117. .WithQualityOfServiceLevel(qos)
  118. .WithRetainFlag(Retain.IsChecked == true)
  119. .Build();
  120. await _mqttClient.PublishAsync(message);
  121. }
  122. catch (Exception exception)
  123. {
  124. Trace.Text += exception + Environment.NewLine;
  125. }
  126. }
  127. private async void Disconnect(object sender, RoutedEventArgs e)
  128. {
  129. try
  130. {
  131. await _mqttClient.DisconnectAsync();
  132. }
  133. catch (Exception exception)
  134. {
  135. Trace.Text += exception + Environment.NewLine;
  136. }
  137. }
  138. private void Clear(object sender, RoutedEventArgs e)
  139. {
  140. Trace.Text = string.Empty;
  141. }
  142. private async void Subscribe(object sender, RoutedEventArgs e)
  143. {
  144. if (_mqttClient == null)
  145. {
  146. return;
  147. }
  148. try
  149. {
  150. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  151. if (SubscribeQoS1.IsChecked == true)
  152. {
  153. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  154. }
  155. if (SubscribeQoS2.IsChecked == true)
  156. {
  157. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  158. }
  159. await _mqttClient.SubscribeAsync(new TopicFilter(SubscribeTopic.Text, qos));
  160. }
  161. catch (Exception exception)
  162. {
  163. Trace.Text += exception + Environment.NewLine;
  164. }
  165. }
  166. private async void Unsubscribe(object sender, RoutedEventArgs e)
  167. {
  168. if (_mqttClient == null)
  169. {
  170. return;
  171. }
  172. try
  173. {
  174. await _mqttClient.UnsubscribeAsync(SubscribeTopic.Text);
  175. }
  176. catch (Exception exception)
  177. {
  178. Trace.Text += exception + Environment.NewLine;
  179. }
  180. }
  181. // This code is for the Wiki at GitHub!
  182. // ReSharper disable once UnusedMember.Local
  183. private async Task WikiCode()
  184. {
  185. {
  186. // Create a new MQTT client
  187. var services = new ServiceCollection()
  188. .AddMqttClient()
  189. .BuildServiceProvider();
  190. var factory = new MqttFactory(services);
  191. var client = factory.CreateMqttClient();
  192. {
  193. // Create TCP based options using the builder
  194. var options = new MqttClientOptionsBuilder()
  195. .WithClientId("Client1")
  196. .WithTcpServer("broker.hivemq.com")
  197. .WithCredentials("bud", "%spencer%")
  198. .WithTls()
  199. .WithCleanSession()
  200. .Build();
  201. await client.ConnectAsync(options);
  202. }
  203. {
  204. // Create TCP based options manually
  205. var options = new MqttClientOptions
  206. {
  207. ClientId = "Client1",
  208. Credentials = new MqttClientCredentials
  209. {
  210. Username = "bud",
  211. Password = "%spencer%"
  212. },
  213. ChannelOptions = new MqttClientTcpOptions
  214. {
  215. Server = "broker.hivemq.org",
  216. TlsOptions = new MqttClientTlsOptions
  217. {
  218. UseTls = true
  219. }
  220. },
  221. };
  222. }
  223. {
  224. // Subscribe to a topic
  225. await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());
  226. // Unsubscribe from a topic
  227. await client.UnsubscribeAsync("my/topic");
  228. // Publish an application message
  229. var applicationMessage = new MqttApplicationMessageBuilder()
  230. .WithTopic("A/B/C")
  231. .WithPayload("Hello World")
  232. .WithAtLeastOnceQoS()
  233. .Build();
  234. await client.PublishAsync(applicationMessage);
  235. }
  236. }
  237. // ----------------------------------
  238. {
  239. var services = new ServiceCollection()
  240. .AddMqttServer(options =>
  241. {
  242. options.ConnectionValidator = c =>
  243. {
  244. if (c.ClientId.Length < 10)
  245. {
  246. return MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
  247. }
  248. if (c.Username != "mySecretUser")
  249. {
  250. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  251. }
  252. if (c.Password != "mySecretPassword")
  253. {
  254. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  255. }
  256. return MqttConnectReturnCode.ConnectionAccepted;
  257. };
  258. })
  259. .BuildServiceProvider();
  260. var factory = new MqttFactory(services);
  261. var mqttServer = factory.CreateMqttServer();
  262. await mqttServer.StartAsync();
  263. Console.WriteLine("Press any key to exit.");
  264. Console.ReadLine();
  265. await mqttServer.StopAsync();
  266. }
  267. // ----------------------------------
  268. // For UWP apps:
  269. MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
  270. {
  271. if (o.Server == "server_with_revoked_cert")
  272. {
  273. return new[] { ChainValidationResult.Revoked };
  274. }
  275. return new ChainValidationResult[0];
  276. };
  277. }
  278. private async void StartServer(object sender, RoutedEventArgs e)
  279. {
  280. if (_mqttServer != null)
  281. {
  282. return;
  283. }
  284. _mqttServer = new MqttFactory().CreateMqttServer(o =>
  285. {
  286. o.DefaultEndpointOptions.Port = int.Parse(ServerPort.Text);
  287. });
  288. await _mqttServer.StartAsync();
  289. }
  290. private async void StopServer(object sender, RoutedEventArgs e)
  291. {
  292. if (_mqttServer == null)
  293. {
  294. return;
  295. }
  296. await _mqttServer.StopAsync();
  297. _mqttServer = null;
  298. }
  299. }
  300. }