Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

344 wiersze
12 KiB

  1. using MQTTnet.Core;
  2. using MQTTnet.Core.Client;
  3. using MQTTnet.Core.Diagnostics;
  4. using MQTTnet.Core.Packets;
  5. using MQTTnet.Core.Protocol;
  6. using MQTTnet.Core.Server;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MQTTnet.TestApp.NetCore
  14. {
  15. public static class Program
  16. {
  17. public static void Main(string[] args)
  18. {
  19. Console.WriteLine("MQTTnet - TestApp.NetFramework");
  20. Console.WriteLine("1 = Start client");
  21. Console.WriteLine("2 = Start queued client");
  22. Console.WriteLine("3 = Start server");
  23. Console.WriteLine("4 = Start performance test");
  24. var pressedKey = Console.ReadKey(true);
  25. if (pressedKey.Key == ConsoleKey.D1)
  26. {
  27. Task.Run(() => RunClientAsync(args));
  28. Thread.Sleep(Timeout.Infinite);
  29. }
  30. if (pressedKey.Key == ConsoleKey.D2)
  31. {
  32. Task.Run(() => RunClientQueuedAsync(args));
  33. Thread.Sleep(Timeout.Infinite);
  34. }
  35. else if (pressedKey.Key == ConsoleKey.D3)
  36. {
  37. Task.Run(() => RunServerAsync(args));
  38. Thread.Sleep(Timeout.Infinite);
  39. }
  40. else if (pressedKey.Key == ConsoleKey.D4)
  41. {
  42. Task.Run(PerformanceTest.RunAsync);
  43. Thread.Sleep(Timeout.Infinite);
  44. }
  45. }
  46. private static async Task RunClientQueuedAsync(string[] arguments)
  47. {
  48. MqttNetTrace.TraceMessagePublished += (s, e) =>
  49. {
  50. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  51. if (e.Exception != null)
  52. {
  53. Console.WriteLine(e.Exception);
  54. }
  55. };
  56. try
  57. {
  58. var options = new MqttClientQueuedOptions
  59. {
  60. Server = "192.168.0.14",
  61. ClientId = "XYZ",
  62. CleanSession = true,
  63. UserName = "lobu",
  64. Password = "passworda",
  65. KeepAlivePeriod = TimeSpan.FromSeconds(31),
  66. DefaultCommunicationTimeout = TimeSpan.FromSeconds(20),
  67. UsePersistence = true,
  68. Storage = new TestStorage(),
  69. };
  70. var client = new MqttClientFactory().CreateMqttQueuedClient();
  71. client.ApplicationMessageReceived += (s, e) =>
  72. {
  73. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  74. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  75. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  76. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  77. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  78. Console.WriteLine();
  79. };
  80. client.Connected += async (s, e) =>
  81. {
  82. Console.WriteLine("### CONNECTED WITH SERVER ###");
  83. await client.SubscribeAsync(new List<TopicFilter>
  84. {
  85. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  86. });
  87. Console.WriteLine("### SUBSCRIBED ###");
  88. };
  89. client.Disconnected += async (s, e) =>
  90. {
  91. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  92. await Task.Delay(TimeSpan.FromSeconds(5));
  93. try
  94. {
  95. await client.ConnectAsync(options);
  96. }
  97. catch
  98. {
  99. Console.WriteLine("### RECONNECTING FAILED ###");
  100. }
  101. };
  102. try
  103. {
  104. await client.ConnectAsync(options);
  105. }
  106. catch (Exception exception)
  107. {
  108. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  109. }
  110. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  111. int i = 0;
  112. while (true)
  113. {
  114. Console.ReadLine();
  115. i++;
  116. var applicationMessage = new MqttApplicationMessage(
  117. "PLNMAIN",
  118. Encoding.UTF8.GetBytes(string.Format("Hello World {0}", i)),
  119. MqttQualityOfServiceLevel.ExactlyOnce,
  120. false
  121. );
  122. await client.PublishAsync(applicationMessage);
  123. }
  124. }
  125. catch (Exception exception)
  126. {
  127. Console.WriteLine(exception);
  128. }
  129. }
  130. private static async Task RunClientAsync(string[] arguments)
  131. {
  132. MqttNetTrace.TraceMessagePublished += (s, e) =>
  133. {
  134. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  135. if (e.Exception != null)
  136. {
  137. Console.WriteLine(e.Exception);
  138. }
  139. };
  140. try
  141. {
  142. var options = new MqttClientWebSocketOptions
  143. {
  144. Uri = "localhost",
  145. ClientId = "XYZ",
  146. CleanSession = true,
  147. };
  148. var client = new MqttClientFactory().CreateMqttClient();
  149. client.ApplicationMessageReceived += (s, e) =>
  150. {
  151. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  152. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  153. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  154. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  155. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  156. Console.WriteLine();
  157. };
  158. client.Connected += async (s, e) =>
  159. {
  160. Console.WriteLine("### CONNECTED WITH SERVER ###");
  161. await client.SubscribeAsync(new List<TopicFilter>
  162. {
  163. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  164. });
  165. Console.WriteLine("### SUBSCRIBED ###");
  166. };
  167. client.Disconnected += async (s, e) =>
  168. {
  169. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  170. await Task.Delay(TimeSpan.FromSeconds(5));
  171. try
  172. {
  173. await client.ConnectAsync(options);
  174. }
  175. catch
  176. {
  177. Console.WriteLine("### RECONNECTING FAILED ###");
  178. }
  179. };
  180. try
  181. {
  182. await client.ConnectAsync(options);
  183. }
  184. catch (Exception exception)
  185. {
  186. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  187. }
  188. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  189. while (true)
  190. {
  191. Console.ReadLine();
  192. var applicationMessage = new MqttApplicationMessage(
  193. "A/B/C",
  194. Encoding.UTF8.GetBytes("Hello World"),
  195. MqttQualityOfServiceLevel.AtLeastOnce,
  196. false
  197. );
  198. await client.PublishAsync(applicationMessage);
  199. }
  200. }
  201. catch (Exception exception)
  202. {
  203. Console.WriteLine(exception);
  204. }
  205. }
  206. private static void RunServerAsync(string[] arguments)
  207. {
  208. MqttNetTrace.TraceMessagePublished += (s, e) =>
  209. {
  210. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  211. if (e.Exception != null)
  212. {
  213. Console.WriteLine(e.Exception);
  214. }
  215. };
  216. try
  217. {
  218. var options = new MqttServerOptions
  219. {
  220. ConnectionValidator = p =>
  221. {
  222. if (p.ClientId == "SpecialClient")
  223. {
  224. if (p.Username != "USER" || p.Password != "PASS")
  225. {
  226. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  227. }
  228. }
  229. return MqttConnectReturnCode.ConnectionAccepted;
  230. }
  231. };
  232. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  233. mqttServer.StartAsync();
  234. Console.WriteLine("Press any key to exit.");
  235. Console.ReadLine();
  236. mqttServer.StopAsync();
  237. }
  238. catch (Exception e)
  239. {
  240. Console.WriteLine(e);
  241. }
  242. Console.ReadLine();
  243. }
  244. [Serializable]
  245. public sealed class TemporaryApplicationMessage
  246. {
  247. public TemporaryApplicationMessage(string topic, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, bool retain)
  248. {
  249. Topic = topic ?? throw new ArgumentNullException(nameof(topic));
  250. Payload = payload ?? throw new ArgumentNullException(nameof(payload));
  251. QualityOfServiceLevel = qualityOfServiceLevel;
  252. Retain = retain;
  253. }
  254. public string Topic { get; }
  255. public byte[] Payload { get; }
  256. public MqttQualityOfServiceLevel QualityOfServiceLevel { get; }
  257. public bool Retain { get; }
  258. }
  259. private class TestStorage : IMqttClientQueuedStorage
  260. {
  261. string serializationFile = Path.Combine(Environment.CurrentDirectory, "messages.bin");
  262. private IList<MqttApplicationMessage> _messages = new List<MqttApplicationMessage>();
  263. public Task<IList<MqttApplicationMessage>> LoadInflightMessagesAsync()
  264. {
  265. //deserialize
  266. // MqttApplicationMessage is not serializable
  267. if (File.Exists(serializationFile))
  268. {
  269. using (Stream stream = File.Open(serializationFile, FileMode.Open))
  270. {
  271. var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  272. var temp = (List<TemporaryApplicationMessage>)bformatter.Deserialize(stream);
  273. foreach (var a in temp)
  274. {
  275. _messages.Add(new MqttApplicationMessage(a.Topic, a.Payload, a.QualityOfServiceLevel, a.Retain));
  276. }
  277. }
  278. }
  279. return Task.FromResult(_messages);
  280. }
  281. public Task SaveInflightMessagesAsync(IList<MqttApplicationMessage> messages)
  282. {
  283. _messages = messages;
  284. //serialize
  285. // MqttApplicationMessage is not serializable
  286. using (System.IO.Stream stream = File.Open(serializationFile, FileMode.Create))
  287. {
  288. var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  289. IList<TemporaryApplicationMessage> temp = new List<TemporaryApplicationMessage>();
  290. foreach (var m in _messages)
  291. {
  292. temp.Add(new TemporaryApplicationMessage(m.Topic, m.Payload, m.QualityOfServiceLevel, m.Retain));
  293. }
  294. bformatter.Serialize(stream, temp);
  295. }
  296. return Task.FromResult(0);
  297. }
  298. }
  299. }
  300. }