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.
 
 
 
 

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