Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

7 роки тому
7 роки тому
7 роки тому
7 роки тому
3 роки тому
6 роки тому
5 роки тому
6 роки тому
7 роки тому
6 роки тому
7 роки тому
5 роки тому
7 роки тому
3 роки тому
3 роки тому
4 роки тому
3 роки тому
6 роки тому
6 роки тому
7 роки тому
6 роки тому
7 роки тому
7 роки тому
6 роки тому
7 роки тому
7 роки тому
7 роки тому
6 роки тому
7 роки тому
7 роки тому
6 роки тому
7 роки тому
7 роки тому
7 роки тому
7 роки тому
6 роки тому
7 роки тому
6 роки тому
7 роки тому
7 роки тому
6 роки тому
7 роки тому
6 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
7 роки тому
3 роки тому
5 роки тому
7 роки тому
7 роки тому
7 роки тому
7 роки тому
6 роки тому
7 роки тому
6 роки тому
7 роки тому
3 роки тому
7 роки тому
3 роки тому
3 роки тому
7 роки тому
5 роки тому
6 роки тому
3 роки тому
7 роки тому
5 роки тому
7 роки тому
3 роки тому
3 роки тому
3 роки тому
7 роки тому
3 роки тому
7 роки тому
7 роки тому
3 роки тому
5 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
7 роки тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using Microsoft.VisualStudio.TestTools.UnitTesting;
  8. using MQTTnet.Adapter;
  9. using MQTTnet.Diagnostics;
  10. using MQTTnet.Exceptions;
  11. using MQTTnet.Formatter;
  12. using MQTTnet.Formatter.V3;
  13. using MQTTnet.Formatter.V5;
  14. using MQTTnet.Internal;
  15. using MQTTnet.Packets;
  16. using MQTTnet.Protocol;
  17. namespace MQTTnet.Tests
  18. {
  19. [TestClass]
  20. public class MqttPacketSerializer_Tests
  21. {
  22. [TestMethod]
  23. public void DetectVersionFromMqttConnectPacket()
  24. {
  25. var packet = new MqttConnectPacket
  26. {
  27. ClientId = "XYZ",
  28. Password = Encoding.UTF8.GetBytes("PASS"),
  29. Username = "USER",
  30. KeepAlivePeriod = 123,
  31. CleanSession = true
  32. };
  33. Assert.AreEqual(
  34. MqttProtocolVersion.V310,
  35. DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttPacketWriter()), Serialize(packet, MqttProtocolVersion.V310)));
  36. Assert.AreEqual(
  37. MqttProtocolVersion.V311,
  38. DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttPacketWriter()), Serialize(packet, MqttProtocolVersion.V311)));
  39. Assert.AreEqual(
  40. MqttProtocolVersion.V500,
  41. DeserializeAndDetectVersion(new MqttPacketFormatterAdapter(new MqttPacketWriter()), Serialize(packet, MqttProtocolVersion.V500)));
  42. var adapter = new MqttPacketFormatterAdapter(new MqttPacketWriter());
  43. var ex = Assert.ThrowsException<MqttProtocolViolationException>(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[0])));
  44. Assert.AreEqual("CONNECT packet must have at least 7 bytes.", ex.Message);
  45. ex = Assert.ThrowsException<MqttProtocolViolationException>(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[7])));
  46. Assert.AreEqual("Protocol '' not supported.", ex.Message);
  47. ex = Assert.ThrowsException<MqttProtocolViolationException>(() => DeserializeAndDetectVersion(adapter, WriterFactory().AddMqttHeader(MqttControlPacketType.Connect, new byte[] { 255, 255, 0, 0, 0, 0, 0 })));
  48. Assert.AreEqual("Expected at least 65537 bytes but there are only 7 bytes", ex.Message);
  49. }
  50. [TestMethod]
  51. public void SerializeV310_MqttConnectPacket()
  52. {
  53. var p = new MqttConnectPacket
  54. {
  55. ClientId = "XYZ",
  56. Password = Encoding.UTF8.GetBytes("PASS"),
  57. Username = "USER",
  58. KeepAlivePeriod = 123,
  59. CleanSession = true
  60. };
  61. SerializeAndCompare(p, "EB0ABk1RSXNkcAPCAHsAA1hZWgAEVVNFUgAEUEFTUw==", MqttProtocolVersion.V310);
  62. }
  63. [TestMethod]
  64. public void SerializeV311_MqttConnectPacket()
  65. {
  66. var p = new MqttConnectPacket
  67. {
  68. ClientId = "XYZ",
  69. Password = Encoding.UTF8.GetBytes("PASS"),
  70. Username = "USER",
  71. KeepAlivePeriod = 123,
  72. CleanSession = true
  73. };
  74. SerializeAndCompare(p, "EBsABE1RVFQEwgB7AANYWVoABFVTRVIABFBBU1M=");
  75. }
  76. [TestMethod]
  77. public void SerializeV311_MqttConnectPacketWithWillMessage()
  78. {
  79. var p = new MqttConnectPacket
  80. {
  81. ClientId = "XYZ",
  82. Password = Encoding.UTF8.GetBytes("PASS"),
  83. Username = "USER",
  84. KeepAlivePeriod = 123,
  85. CleanSession = true,
  86. WillMessage = new MqttApplicationMessage
  87. {
  88. Topic = "My/last/will",
  89. Payload = Encoding.UTF8.GetBytes("Good byte."),
  90. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  91. Retain = true
  92. }
  93. };
  94. SerializeAndCompare(p, "EDUABE1RVFQE7gB7AANYWVoADE15L2xhc3Qvd2lsbAAKR29vZCBieXRlLgAEVVNFUgAEUEFTUw==");
  95. }
  96. [TestMethod]
  97. public void DeserializeV311_MqttConnectPacket()
  98. {
  99. var p = new MqttConnectPacket
  100. {
  101. ClientId = "XYZ",
  102. Password = Encoding.UTF8.GetBytes("PASS"),
  103. Username = "USER",
  104. KeepAlivePeriod = 123,
  105. CleanSession = true
  106. };
  107. DeserializeAndCompare(p, "EBsABE1RVFQEwgB7AANYWVoABFVTRVIABFBBU1M=");
  108. }
  109. [TestMethod]
  110. public void DeserializeV311_MqttConnectPacketWithWillMessage()
  111. {
  112. var p = new MqttConnectPacket
  113. {
  114. ClientId = "XYZ",
  115. Password = Encoding.UTF8.GetBytes("PASS"),
  116. Username = "USER",
  117. KeepAlivePeriod = 123,
  118. CleanSession = true,
  119. WillMessage = new MqttApplicationMessage
  120. {
  121. Topic = "My/last/will",
  122. Payload = Encoding.UTF8.GetBytes("Good byte."),
  123. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  124. Retain = true
  125. }
  126. };
  127. DeserializeAndCompare(p, "EDUABE1RVFQE7gB7AANYWVoADE15L2xhc3Qvd2lsbAAKR29vZCBieXRlLgAEVVNFUgAEUEFTUw==");
  128. }
  129. [TestMethod]
  130. public void SerializeV311_MqttConnAckPacket()
  131. {
  132. var p = new MqttConnAckPacket
  133. {
  134. IsSessionPresent = true,
  135. ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
  136. };
  137. SerializeAndCompare(p, "IAIBBQ==");
  138. }
  139. [TestMethod]
  140. public void SerializeV310_MqttConnAckPacket()
  141. {
  142. var p = new MqttConnAckPacket
  143. {
  144. ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
  145. };
  146. SerializeAndCompare(p, "IAIABQ==", MqttProtocolVersion.V310);
  147. }
  148. [TestMethod]
  149. public void DeserializeV311_MqttConnAckPacket()
  150. {
  151. var p = new MqttConnAckPacket
  152. {
  153. IsSessionPresent = true,
  154. ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
  155. };
  156. DeserializeAndCompare(p, "IAIBBQ==");
  157. }
  158. [TestMethod]
  159. public void DeserializeV310_MqttConnAckPacket()
  160. {
  161. var p = new MqttConnAckPacket
  162. {
  163. ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized
  164. };
  165. DeserializeAndCompare(p, "IAIABQ==", MqttProtocolVersion.V310);
  166. }
  167. [TestMethod]
  168. public void Serialize_LargePacket()
  169. {
  170. var serializer = new MqttV311PacketFormatter(WriterFactory());
  171. const int payloadLength = 80000;
  172. var payload = new byte[payloadLength];
  173. var value = 0;
  174. for (var i = 0; i < payloadLength; i++)
  175. {
  176. if (value > 255)
  177. {
  178. value = 0;
  179. }
  180. payload[i] = (byte)value;
  181. }
  182. var publishPacket = new MqttPublishPacket
  183. {
  184. Topic = "abcdefghijklmnopqrstuvwxyz0123456789",
  185. Payload = payload
  186. };
  187. var publishPacketCopy = Roundtrip(publishPacket);
  188. //var buffer = serializer.Encode(publishPacket);
  189. //var testChannel = new TestMqttChannel(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count));
  190. //var header = new MqttPacketReader(testChannel).ReadFixedHeaderAsync(
  191. // new byte[2],
  192. // CancellationToken.None).GetAwaiter().GetResult().FixedHeader;
  193. //var eof = buffer.Offset + buffer.Count;
  194. //var receivedPacket = new ReceivedMqttPacket(
  195. // header.Flags,
  196. // new MqttPacketBodyReader(buffer.Array, eof - header.RemainingLength, buffer.Count + buffer.Offset),
  197. // 0);
  198. //var packet = (MqttPublishPacket)serializer.Decode(receivedPacket);
  199. Assert.AreEqual(publishPacket.Topic, publishPacketCopy.Topic);
  200. Assert.IsTrue(publishPacket.Payload.SequenceEqual(publishPacketCopy.Payload));
  201. }
  202. [TestMethod]
  203. public void SerializeV311_MqttDisconnectPacket()
  204. {
  205. SerializeAndCompare(new MqttDisconnectPacket(), "4AA=");
  206. }
  207. [TestMethod]
  208. public void SerializeV311_MqttPingReqPacket()
  209. {
  210. SerializeAndCompare(new MqttPingReqPacket(), "wAA=");
  211. }
  212. [TestMethod]
  213. public void SerializeV311_MqttPingRespPacket()
  214. {
  215. SerializeAndCompare(new MqttPingRespPacket(), "0AA=");
  216. }
  217. [TestMethod]
  218. public void SerializeV311_MqttPublishPacket()
  219. {
  220. var p = new MqttPublishPacket
  221. {
  222. PacketIdentifier = 123,
  223. Dup = true,
  224. Retain = true,
  225. Payload = Encoding.ASCII.GetBytes("HELLO"),
  226. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  227. Topic = "A/B/C"
  228. };
  229. SerializeAndCompare(p, "Ow4ABUEvQi9DAHtIRUxMTw==");
  230. }
  231. [TestMethod]
  232. public void SerializeV500_MqttPublishPacket()
  233. {
  234. var prop = new MqttPublishPacketProperties { UserProperties = new List<MqttUserProperty>() };
  235. prop.ResponseTopic = "/Response";
  236. prop.UserProperties.Add(new MqttUserProperty("Foo", "Bar"));
  237. var p = new MqttPublishPacket
  238. {
  239. PacketIdentifier = 123,
  240. Dup = true,
  241. Retain = true,
  242. Payload = Encoding.ASCII.GetBytes("HELLO"),
  243. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  244. Topic = "A/B/C",
  245. Properties = prop
  246. };
  247. var deserialized = Roundtrip(p, MqttProtocolVersion.V500);
  248. Assert.AreEqual(prop.ResponseTopic, deserialized.Properties.ResponseTopic);
  249. Assert.IsTrue(deserialized.Properties.UserProperties.Any(x => x.Name == "Foo"));
  250. }
  251. [TestMethod]
  252. public void SerializeV500_MqttPublishPacket_CorrelationData()
  253. {
  254. var data = "123456789";
  255. var req = new MqttApplicationMessageBuilder()
  256. .WithTopic("Foo")
  257. .WithResponseTopic($"_")
  258. .WithCorrelationData(Guid.NewGuid().ToByteArray())
  259. .WithPayload(data)
  260. .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
  261. .Build();
  262. var p = new MqttV500DataConverter().CreatePublishPacket(req);
  263. var deserialized = Roundtrip(p, MqttProtocolVersion.V500);
  264. Assert.IsTrue(p.Payload.SequenceEqual(deserialized.Payload));
  265. }
  266. [TestMethod]
  267. public void DeserializeV311_MqttPublishPacket()
  268. {
  269. var p = new MqttPublishPacket
  270. {
  271. PacketIdentifier = 123,
  272. Dup = true,
  273. Retain = true,
  274. Payload = Encoding.ASCII.GetBytes("HELLO"),
  275. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  276. Topic = "A/B/C"
  277. };
  278. DeserializeAndCompare(p, "Ow4ABUEvQi9DAHtIRUxMTw==");
  279. }
  280. [TestMethod]
  281. public void DeserializeV311_MqttPublishPacket_Qos1()
  282. {
  283. var p = new MqttPublishPacket
  284. {
  285. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
  286. };
  287. var p2 = Roundtrip(p);
  288. Assert.AreEqual(p.QualityOfServiceLevel, p2.QualityOfServiceLevel);
  289. Assert.AreEqual(p.Dup, p2.Dup);
  290. }
  291. [TestMethod]
  292. public void DeserializeV311_MqttPublishPacket_Qos2()
  293. {
  294. var p = new MqttPublishPacket
  295. {
  296. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  297. PacketIdentifier = 1
  298. };
  299. var p2 = Roundtrip(p);
  300. Assert.AreEqual(p.QualityOfServiceLevel, p2.QualityOfServiceLevel);
  301. Assert.AreEqual(p.Dup, p2.Dup);
  302. }
  303. [TestMethod]
  304. public void DeserializeV311_MqttPublishPacket_Qos3()
  305. {
  306. var p = new MqttPublishPacket
  307. {
  308. QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
  309. PacketIdentifier = 1
  310. };
  311. var p2 = Roundtrip(p);
  312. Assert.AreEqual(p.QualityOfServiceLevel, p2.QualityOfServiceLevel);
  313. Assert.AreEqual(p.Dup, p2.Dup);
  314. }
  315. [TestMethod]
  316. public void DeserializeV311_MqttPublishPacket_DupFalse()
  317. {
  318. var p = new MqttPublishPacket
  319. {
  320. Dup = false,
  321. };
  322. var p2 = Roundtrip(p);
  323. Assert.AreEqual(p.Dup, p2.Dup);
  324. }
  325. [TestMethod]
  326. public void SerializeV311_MqttPubAckPacket()
  327. {
  328. var p = new MqttPubAckPacket
  329. {
  330. PacketIdentifier = 123
  331. };
  332. SerializeAndCompare(p, "QAIAew==");
  333. }
  334. [TestMethod]
  335. public void DeserializeV311_MqttPubAckPacket()
  336. {
  337. var p = new MqttPubAckPacket
  338. {
  339. PacketIdentifier = 123
  340. };
  341. DeserializeAndCompare(p, "QAIAew==");
  342. }
  343. [TestMethod]
  344. public void SerializeV311_MqttPubRecPacket()
  345. {
  346. var p = new MqttPubRecPacket
  347. {
  348. PacketIdentifier = 123
  349. };
  350. SerializeAndCompare(p, "UAIAew==");
  351. }
  352. [TestMethod]
  353. public void DeserializeV311_MqttPubRecPacket()
  354. {
  355. var p = new MqttPubRecPacket
  356. {
  357. PacketIdentifier = 123
  358. };
  359. DeserializeAndCompare(p, "UAIAew==");
  360. }
  361. [TestMethod]
  362. public void SerializeV311_MqttPubRelPacket()
  363. {
  364. var p = new MqttPubRelPacket
  365. {
  366. PacketIdentifier = 123
  367. };
  368. SerializeAndCompare(p, "YgIAew==");
  369. }
  370. [TestMethod]
  371. public void DeserializeV311_MqttPubRelPacket()
  372. {
  373. var p = new MqttPubRelPacket
  374. {
  375. PacketIdentifier = 123
  376. };
  377. DeserializeAndCompare(p, "YgIAew==");
  378. }
  379. [TestMethod]
  380. public void SerializeV311_MqttPubCompPacket()
  381. {
  382. var p = new MqttPubCompPacket
  383. {
  384. PacketIdentifier = 123
  385. };
  386. SerializeAndCompare(p, "cAIAew==");
  387. }
  388. [TestMethod]
  389. public void DeserializeV311_MqttPubCompPacket()
  390. {
  391. var p = new MqttPubCompPacket
  392. {
  393. PacketIdentifier = 123
  394. };
  395. DeserializeAndCompare(p, "cAIAew==");
  396. }
  397. [TestMethod]
  398. public void SerializeV311_MqttSubscribePacket()
  399. {
  400. var p = new MqttSubscribePacket
  401. {
  402. PacketIdentifier = 123
  403. };
  404. p.TopicFilters.Add(new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce });
  405. p.TopicFilters.Add(new MqttTopicFilter { Topic = "1/2/3", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce });
  406. p.TopicFilters.Add(new MqttTopicFilter { Topic = "x/y/z", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
  407. SerializeAndCompare(p, "ghoAewAFQS9CL0MCAAUxLzIvMwEABXgveS96AA==");
  408. }
  409. [TestMethod]
  410. public void DeserializeV311_MqttSubscribePacket()
  411. {
  412. var p = new MqttSubscribePacket
  413. {
  414. PacketIdentifier = 123
  415. };
  416. p.TopicFilters.Add(new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce });
  417. p.TopicFilters.Add(new MqttTopicFilter { Topic = "1/2/3", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce });
  418. p.TopicFilters.Add(new MqttTopicFilter { Topic = "x/y/z", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
  419. DeserializeAndCompare(p, "ghoAewAFQS9CL0MCAAUxLzIvMwEABXgveS96AA==");
  420. }
  421. [TestMethod]
  422. public void SerializeV311_MqttSubAckPacket()
  423. {
  424. var p = new MqttSubAckPacket
  425. {
  426. PacketIdentifier = 123
  427. };
  428. p.ReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS0);
  429. p.ReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS1);
  430. p.ReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS2);
  431. p.ReturnCodes.Add(MqttSubscribeReturnCode.Failure);
  432. SerializeAndCompare(p, "kAYAewABAoA=");
  433. }
  434. [TestMethod]
  435. public void DeserializeV311_MqttSubAckPacket()
  436. {
  437. var p = new MqttSubAckPacket
  438. {
  439. PacketIdentifier = 123
  440. };
  441. p.ReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS0);
  442. p.ReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS1);
  443. p.ReturnCodes.Add(MqttSubscribeReturnCode.SuccessMaximumQoS2);
  444. p.ReturnCodes.Add(MqttSubscribeReturnCode.Failure);
  445. DeserializeAndCompare(p, "kAYAewABAoA=");
  446. }
  447. [TestMethod]
  448. public void SerializeV311_MqttUnsubscribePacket()
  449. {
  450. var p = new MqttUnsubscribePacket
  451. {
  452. PacketIdentifier = 123
  453. };
  454. p.TopicFilters.Add("A/B/C");
  455. p.TopicFilters.Add("1/2/3");
  456. p.TopicFilters.Add("x/y/z");
  457. SerializeAndCompare(p, "ohcAewAFQS9CL0MABTEvMi8zAAV4L3kveg==");
  458. }
  459. [TestMethod]
  460. public void DeserializeV311_MqttUnsubscribePacket()
  461. {
  462. var p = new MqttUnsubscribePacket
  463. {
  464. PacketIdentifier = 123
  465. };
  466. p.TopicFilters.Add("A/B/C");
  467. p.TopicFilters.Add("1/2/3");
  468. p.TopicFilters.Add("x/y/z");
  469. DeserializeAndCompare(p, "ohcAewAFQS9CL0MABTEvMi8zAAV4L3kveg==");
  470. }
  471. [TestMethod]
  472. public void SerializeV311_MqttUnsubAckPacket()
  473. {
  474. var p = new MqttUnsubAckPacket
  475. {
  476. PacketIdentifier = 123
  477. };
  478. SerializeAndCompare(p, "sAIAew==");
  479. }
  480. [TestMethod]
  481. public void DeserializeV311_MqttUnsubAckPacket()
  482. {
  483. var p = new MqttUnsubAckPacket
  484. {
  485. PacketIdentifier = 123
  486. };
  487. DeserializeAndCompare(p, "sAIAew==");
  488. }
  489. void SerializeAndCompare(MqttBasePacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
  490. {
  491. Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Serialize(packet, protocolVersion)));
  492. }
  493. byte[] Serialize(MqttBasePacket packet, MqttProtocolVersion protocolVersion)
  494. {
  495. return MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, WriterFactory()).Encode(packet).ToArray();
  496. }
  497. protected virtual IMqttPacketWriter WriterFactory()
  498. {
  499. return new MqttPacketWriter();
  500. }
  501. protected virtual IMqttPacketBodyReader ReaderFactory(byte[] data)
  502. {
  503. return new MqttPacketBodyReader(data, 0, data.Length);
  504. }
  505. void DeserializeAndCompare(MqttBasePacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
  506. {
  507. var writer = WriterFactory();
  508. var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, writer);
  509. var buffer1 = serializer.Encode(packet);
  510. using (var headerStream = new MemoryStream(buffer1.ToArray()))
  511. {
  512. var channel = new TestMqttChannel(headerStream);
  513. var adapter = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(protocolVersion, writer), null, new MqttNetLogger());
  514. var receivedPacket = adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
  515. var buffer2 = serializer.Encode(receivedPacket);
  516. Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(buffer2.ToArray()));
  517. //adapter.ReceivePacketAsync(CancellationToken.None);
  518. //var fixedHeader = new byte[2];
  519. //var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader;
  520. //using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, header.RemainingLength))
  521. //{
  522. // var reader = ReaderFactory(bodyStream.ToArray());
  523. // var deserializedPacket = serializer.Decode(new ReceivedMqttPacket(header.Flags, reader, 0));
  524. // var buffer2 = serializer.Encode(deserializedPacket);
  525. // Assert.AreEqual(expectedBase64Value, Convert.ToBase64String(Join(buffer2)));
  526. //}
  527. }
  528. }
  529. TPacket Roundtrip<TPacket>(TPacket packet, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
  530. where TPacket : MqttBasePacket
  531. {
  532. var writer = WriterFactory();
  533. var serializer = MqttPacketFormatterAdapter.GetMqttPacketFormatter(protocolVersion, writer);
  534. var buffer = serializer.Encode(packet);
  535. var channel = new TestMqttChannel(buffer.ToArray());
  536. var adapter = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(protocolVersion, writer), null, new MqttNetLogger());
  537. return (TPacket)adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
  538. //using (var headerStream = new MemoryStream(buffer1.ToArray()))
  539. //{
  540. // //var fixedHeader = new byte[2];
  541. // //var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader;
  542. // //using (var bodyStream = new MemoryStream(Join(buffer1), (int)headerStream.Position, (int)header.RemainingLength))
  543. // //{
  544. // // var reader = ReaderFactory(bodyStream.ToArray());
  545. // // return (T)serializer.Decode(new ReceivedMqttPacket(header.Flags, reader, 0));
  546. // //}
  547. //}
  548. }
  549. MqttProtocolVersion DeserializeAndDetectVersion(MqttPacketFormatterAdapter packetFormatterAdapter, byte[] buffer)
  550. {
  551. var channel = new TestMqttChannel(buffer);
  552. var adapter = new MqttChannelAdapter(channel, packetFormatterAdapter, null, new MqttNetLogger());
  553. adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
  554. return packetFormatterAdapter.ProtocolVersion;
  555. //using (var headerStream = new MemoryStream(buffer))
  556. //{
  557. // //var fixedHeader = new byte[2];
  558. // //var header = new MqttPacketReader(channel).ReadFixedHeaderAsync(fixedHeader, CancellationToken.None).GetAwaiter().GetResult().FixedHeader;
  559. // //using (var bodyStream = new MemoryStream(buffer, (int)headerStream.Position, (int)header.RemainingLength))
  560. // //{
  561. // // var reader = ReaderFactory(bodyStream.ToArray());
  562. // // var packet = new ReceivedMqttPacket(header.Flags, reader, 0);
  563. // // packetFormatterAdapter.DetectProtocolVersion(packet);
  564. // // return adapter.ProtocolVersion;
  565. // //}
  566. //}
  567. }
  568. }
  569. }