Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

MainPage.xaml.cs 11 KiB

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