Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

626 строки
22 KiB

  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Core.Channel;
  6. using MQTTnet.Core.Exceptions;
  7. using MQTTnet.Core.Packets;
  8. using MQTTnet.Core.Protocol;
  9. namespace MQTTnet.Core.Serializer
  10. {
  11. public sealed class MqttPacketSerializer : IMqttPacketSerializer
  12. {
  13. private static byte[] ProtocolVersionV311Name { get; } = Encoding.UTF8.GetBytes("MQTT");
  14. private static byte[] ProtocolVersionV310Name { get; } = Encoding.UTF8.GetBytes("MQIs");
  15. public MqttProtocolVersion ProtocolVersion { get; set; } = MqttProtocolVersion.V311;
  16. public Task SerializeAsync(MqttBasePacket packet, IMqttCommunicationChannel destination)
  17. {
  18. if (packet == null) throw new ArgumentNullException(nameof(packet));
  19. if (destination == null) throw new ArgumentNullException(nameof(destination));
  20. if (packet is MqttConnectPacket connectPacket)
  21. {
  22. return SerializeAsync(connectPacket, destination);
  23. }
  24. if (packet is MqttConnAckPacket connAckPacket)
  25. {
  26. return SerializeAsync(connAckPacket, destination);
  27. }
  28. if (packet is MqttDisconnectPacket disconnectPacket)
  29. {
  30. return SerializeAsync(disconnectPacket, destination);
  31. }
  32. if (packet is MqttPingReqPacket pingReqPacket)
  33. {
  34. return SerializeAsync(pingReqPacket, destination);
  35. }
  36. if (packet is MqttPingRespPacket pingRespPacket)
  37. {
  38. return SerializeAsync(pingRespPacket, destination);
  39. }
  40. if (packet is MqttPublishPacket publishPacket)
  41. {
  42. return SerializeAsync(publishPacket, destination);
  43. }
  44. if (packet is MqttPubAckPacket pubAckPacket)
  45. {
  46. return SerializeAsync(pubAckPacket, destination);
  47. }
  48. if (packet is MqttPubRecPacket pubRecPacket)
  49. {
  50. return SerializeAsync(pubRecPacket, destination);
  51. }
  52. if (packet is MqttPubRelPacket pubRelPacket)
  53. {
  54. return SerializeAsync(pubRelPacket, destination);
  55. }
  56. if (packet is MqttPubCompPacket pubCompPacket)
  57. {
  58. return SerializeAsync(pubCompPacket, destination);
  59. }
  60. if (packet is MqttSubscribePacket subscribePacket)
  61. {
  62. return SerializeAsync(subscribePacket, destination);
  63. }
  64. if (packet is MqttSubAckPacket subAckPacket)
  65. {
  66. return SerializeAsync(subAckPacket, destination);
  67. }
  68. if (packet is MqttUnsubscribePacket unsubscribePacket)
  69. {
  70. return SerializeAsync(unsubscribePacket, destination);
  71. }
  72. if (packet is MqttUnsubAckPacket unsubAckPacket)
  73. {
  74. return SerializeAsync(unsubAckPacket, destination);
  75. }
  76. throw new MqttProtocolViolationException("Packet type invalid.");
  77. }
  78. public async Task<MqttBasePacket> DeserializeAsync(IMqttCommunicationChannel source)
  79. {
  80. if (source == null) throw new ArgumentNullException(nameof(source));
  81. using (var mqttPacketReader = new MqttPacketReader(source))
  82. {
  83. await mqttPacketReader.ReadToEndAsync().ConfigureAwait(false);
  84. switch (mqttPacketReader.ControlPacketType)
  85. {
  86. case MqttControlPacketType.Connect:
  87. {
  88. return DeserializeConnect(mqttPacketReader);
  89. }
  90. case MqttControlPacketType.ConnAck:
  91. {
  92. return DeserializeConnAck(mqttPacketReader);
  93. }
  94. case MqttControlPacketType.Disconnect:
  95. {
  96. return new MqttDisconnectPacket();
  97. }
  98. case MqttControlPacketType.Publish:
  99. {
  100. return DeserializePublish(mqttPacketReader);
  101. }
  102. case MqttControlPacketType.PubAck:
  103. {
  104. return new MqttPubAckPacket
  105. {
  106. PacketIdentifier = mqttPacketReader.ReadRemainingDataUShort()
  107. };
  108. }
  109. case MqttControlPacketType.PubRec:
  110. {
  111. return new MqttPubRecPacket
  112. {
  113. PacketIdentifier = mqttPacketReader.ReadRemainingDataUShort()
  114. };
  115. }
  116. case MqttControlPacketType.PubRel:
  117. {
  118. return new MqttPubRelPacket
  119. {
  120. PacketIdentifier = mqttPacketReader.ReadRemainingDataUShort()
  121. };
  122. }
  123. case MqttControlPacketType.PubComp:
  124. {
  125. return new MqttPubCompPacket
  126. {
  127. PacketIdentifier = mqttPacketReader.ReadRemainingDataUShort()
  128. };
  129. }
  130. case MqttControlPacketType.PingReq:
  131. {
  132. return new MqttPingReqPacket();
  133. }
  134. case MqttControlPacketType.PingResp:
  135. {
  136. return new MqttPingRespPacket();
  137. }
  138. case MqttControlPacketType.Subscribe:
  139. {
  140. return DeserializeSubscribe(mqttPacketReader);
  141. }
  142. case MqttControlPacketType.SubAck:
  143. {
  144. return DeserializeSubAck(mqttPacketReader);
  145. }
  146. case MqttControlPacketType.Unsubscibe:
  147. {
  148. return DeserializeUnsubscribe(mqttPacketReader);
  149. }
  150. case MqttControlPacketType.UnsubAck:
  151. {
  152. return new MqttUnsubAckPacket
  153. {
  154. PacketIdentifier = mqttPacketReader.ReadRemainingDataUShort()
  155. };
  156. }
  157. default:
  158. {
  159. throw new MqttProtocolViolationException($"Packet type ({(int)mqttPacketReader.ControlPacketType}) not supported.");
  160. }
  161. }
  162. }
  163. }
  164. private static MqttBasePacket DeserializeUnsubscribe(MqttPacketReader reader)
  165. {
  166. var packet = new MqttUnsubscribePacket
  167. {
  168. PacketIdentifier = reader.ReadRemainingDataUShort(),
  169. };
  170. while (!reader.EndOfRemainingData)
  171. {
  172. packet.TopicFilters.Add(reader.ReadRemainingDataStringWithLengthPrefix());
  173. }
  174. return packet;
  175. }
  176. private static MqttBasePacket DeserializeSubscribe(MqttPacketReader reader)
  177. {
  178. var packet = new MqttSubscribePacket
  179. {
  180. PacketIdentifier = reader.ReadRemainingDataUShort()
  181. };
  182. while (!reader.EndOfRemainingData)
  183. {
  184. packet.TopicFilters.Add(new TopicFilter(
  185. reader.ReadRemainingDataStringWithLengthPrefix(),
  186. (MqttQualityOfServiceLevel)reader.ReadRemainingDataByte()));
  187. }
  188. return packet;
  189. }
  190. private static MqttBasePacket DeserializePublish(MqttPacketReader reader)
  191. {
  192. var fixedHeader = new ByteReader(reader.FixedHeader);
  193. var retain = fixedHeader.Read();
  194. var qualityOfServiceLevel = (MqttQualityOfServiceLevel)fixedHeader.Read(2);
  195. var dup = fixedHeader.Read();
  196. var topic = reader.ReadRemainingDataStringWithLengthPrefix();
  197. ushort packetIdentifier = 0;
  198. if (qualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
  199. {
  200. packetIdentifier = reader.ReadRemainingDataUShort();
  201. }
  202. var packet = new MqttPublishPacket
  203. {
  204. Retain = retain,
  205. QualityOfServiceLevel = qualityOfServiceLevel,
  206. Dup = dup,
  207. Topic = topic,
  208. Payload = reader.ReadRemainingData(),
  209. PacketIdentifier = packetIdentifier
  210. };
  211. return packet;
  212. }
  213. private static MqttBasePacket DeserializeConnect(MqttPacketReader reader)
  214. {
  215. reader.ReadRemainingData(2); // Skip 2 bytes
  216. MqttProtocolVersion protocolVersion;
  217. var protocolName = reader.ReadRemainingData(4);
  218. if (protocolName.SequenceEqual(ProtocolVersionV310Name))
  219. {
  220. reader.ReadRemainingData(2);
  221. protocolVersion = MqttProtocolVersion.V310;
  222. }
  223. else if (protocolName.SequenceEqual(ProtocolVersionV311Name))
  224. {
  225. protocolVersion = MqttProtocolVersion.V311;
  226. }
  227. else
  228. {
  229. throw new MqttProtocolViolationException("Protocol name is not supported.");
  230. }
  231. var protocolLevel = reader.ReadRemainingDataByte();
  232. var connectFlags = reader.ReadRemainingDataByte();
  233. var connectFlagsReader = new ByteReader(connectFlags);
  234. connectFlagsReader.Read(); // Reserved.
  235. var packet = new MqttConnectPacket
  236. {
  237. ProtocolVersion = protocolVersion,
  238. CleanSession = connectFlagsReader.Read()
  239. };
  240. var willFlag = connectFlagsReader.Read();
  241. var willQoS = connectFlagsReader.Read(2);
  242. var willRetain = connectFlagsReader.Read();
  243. var passwordFlag = connectFlagsReader.Read();
  244. var usernameFlag = connectFlagsReader.Read();
  245. packet.KeepAlivePeriod = reader.ReadRemainingDataUShort();
  246. packet.ClientId = reader.ReadRemainingDataStringWithLengthPrefix();
  247. if (willFlag)
  248. {
  249. packet.WillMessage = new MqttApplicationMessage(
  250. reader.ReadRemainingDataStringWithLengthPrefix(),
  251. reader.ReadRemainingDataWithLengthPrefix(),
  252. (MqttQualityOfServiceLevel)willQoS,
  253. willRetain);
  254. }
  255. if (usernameFlag)
  256. {
  257. packet.Username = reader.ReadRemainingDataStringWithLengthPrefix();
  258. }
  259. if (passwordFlag)
  260. {
  261. packet.Password = reader.ReadRemainingDataStringWithLengthPrefix();
  262. }
  263. ValidateConnectPacket(packet);
  264. return packet;
  265. }
  266. private static MqttBasePacket DeserializeSubAck(MqttPacketReader reader)
  267. {
  268. var packet = new MqttSubAckPacket
  269. {
  270. PacketIdentifier = reader.ReadRemainingDataUShort()
  271. };
  272. while (!reader.EndOfRemainingData)
  273. {
  274. packet.SubscribeReturnCodes.Add((MqttSubscribeReturnCode)reader.ReadRemainingDataByte());
  275. }
  276. return packet;
  277. }
  278. private static MqttBasePacket DeserializeConnAck(MqttPacketReader reader)
  279. {
  280. var variableHeader1 = reader.ReadRemainingDataByte();
  281. var variableHeader2 = reader.ReadRemainingDataByte();
  282. var packet = new MqttConnAckPacket
  283. {
  284. IsSessionPresent = new ByteReader(variableHeader1).Read(),
  285. ConnectReturnCode = (MqttConnectReturnCode)variableHeader2
  286. };
  287. return packet;
  288. }
  289. private static void ValidateConnectPacket(MqttConnectPacket packet)
  290. {
  291. if (string.IsNullOrEmpty(packet.ClientId) && !packet.CleanSession)
  292. {
  293. throw new MqttProtocolViolationException("CleanSession must be set if ClientId is empty [MQTT-3.1.3-7].");
  294. }
  295. }
  296. private static void ValidatePublishPacket(MqttPublishPacket packet)
  297. {
  298. if (packet.QualityOfServiceLevel == 0 && packet.Dup)
  299. {
  300. throw new MqttProtocolViolationException("Dup flag must be false for QoS 0 packets [MQTT-3.3.1-2].");
  301. }
  302. }
  303. private Task SerializeAsync(MqttConnectPacket packet, IMqttCommunicationChannel destination)
  304. {
  305. ValidateConnectPacket(packet);
  306. using (var output = new MqttPacketWriter())
  307. {
  308. // Write variable header
  309. output.Write(0x00, 0x04); // 3.1.2.1 Protocol Name
  310. if (ProtocolVersion == MqttProtocolVersion.V311)
  311. {
  312. output.Write(ProtocolVersionV311Name);
  313. output.Write(0x04); // 3.1.2.2 Protocol Level (4)
  314. }
  315. else
  316. {
  317. output.Write(ProtocolVersionV310Name);
  318. output.Write(0x64);
  319. output.Write(0x70);
  320. output.Write(0x03); // Protocol Level (3)
  321. }
  322. var connectFlags = new ByteWriter(); // 3.1.2.3 Connect Flags
  323. connectFlags.Write(false); // Reserved
  324. connectFlags.Write(packet.CleanSession);
  325. connectFlags.Write(packet.WillMessage != null);
  326. if (packet.WillMessage != null)
  327. {
  328. connectFlags.Write((int)packet.WillMessage.QualityOfServiceLevel, 2);
  329. connectFlags.Write(packet.WillMessage.Retain);
  330. }
  331. else
  332. {
  333. connectFlags.Write(0, 2);
  334. connectFlags.Write(false);
  335. }
  336. connectFlags.Write(packet.Password != null);
  337. connectFlags.Write(packet.Username != null);
  338. output.Write(connectFlags);
  339. output.Write(packet.KeepAlivePeriod);
  340. output.WriteWithLengthPrefix(packet.ClientId);
  341. if (packet.WillMessage != null)
  342. {
  343. output.WriteWithLengthPrefix(packet.WillMessage.Topic);
  344. output.WriteWithLengthPrefix(packet.WillMessage.Payload);
  345. }
  346. if (packet.Username != null)
  347. {
  348. output.WriteWithLengthPrefix(packet.Username);
  349. }
  350. if (packet.Password != null)
  351. {
  352. output.WriteWithLengthPrefix(packet.Password);
  353. }
  354. output.InjectFixedHeader(MqttControlPacketType.Connect);
  355. return output.WriteToAsync(destination);
  356. }
  357. }
  358. private Task SerializeAsync(MqttConnAckPacket packet, IMqttCommunicationChannel destination)
  359. {
  360. using (var output = new MqttPacketWriter())
  361. {
  362. var connectAcknowledgeFlags = new ByteWriter();
  363. if (ProtocolVersion == MqttProtocolVersion.V311)
  364. {
  365. connectAcknowledgeFlags.Write(packet.IsSessionPresent);
  366. }
  367. output.Write(connectAcknowledgeFlags);
  368. output.Write((byte)packet.ConnectReturnCode);
  369. output.InjectFixedHeader(MqttControlPacketType.ConnAck);
  370. return output.WriteToAsync(destination);
  371. }
  372. }
  373. private static async Task SerializeAsync(MqttPubRelPacket packet, IMqttCommunicationChannel destination)
  374. {
  375. using (var output = new MqttPacketWriter())
  376. {
  377. output.Write(packet.PacketIdentifier);
  378. output.InjectFixedHeader(MqttControlPacketType.PubRel, 0x02);
  379. await output.WriteToAsync(destination);
  380. }
  381. }
  382. private static Task SerializeAsync(MqttDisconnectPacket packet, IMqttCommunicationChannel destination)
  383. {
  384. return SerializeEmptyPacketAsync(MqttControlPacketType.Disconnect, destination);
  385. }
  386. private static Task SerializeAsync(MqttPingReqPacket packet, IMqttCommunicationChannel destination)
  387. {
  388. return SerializeEmptyPacketAsync(MqttControlPacketType.PingReq, destination);
  389. }
  390. private static Task SerializeAsync(MqttPingRespPacket packet, IMqttCommunicationChannel destination)
  391. {
  392. return SerializeEmptyPacketAsync(MqttControlPacketType.PingResp, destination);
  393. }
  394. private static Task SerializeAsync(MqttPublishPacket packet, IMqttCommunicationChannel destination)
  395. {
  396. ValidatePublishPacket(packet);
  397. using (var output = new MqttPacketWriter())
  398. {
  399. output.WriteWithLengthPrefix(packet.Topic);
  400. if (packet.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
  401. {
  402. output.Write(packet.PacketIdentifier);
  403. }
  404. else
  405. {
  406. if (packet.PacketIdentifier > 0)
  407. {
  408. throw new MqttProtocolViolationException("Packet identifier must be empty if QoS == 0 [MQTT-2.3.1-5].");
  409. }
  410. }
  411. if (packet.Payload?.Length > 0)
  412. {
  413. output.Write(packet.Payload);
  414. }
  415. var fixedHeader = new ByteWriter();
  416. fixedHeader.Write(packet.Retain);
  417. fixedHeader.Write((byte)packet.QualityOfServiceLevel, 2);
  418. fixedHeader.Write(packet.Dup);
  419. output.InjectFixedHeader(MqttControlPacketType.Publish, fixedHeader.Value);
  420. return output.WriteToAsync(destination);
  421. }
  422. }
  423. private static Task SerializeAsync(MqttPubAckPacket packet, IMqttCommunicationChannel destination)
  424. {
  425. using (var output = new MqttPacketWriter())
  426. {
  427. output.Write(packet.PacketIdentifier);
  428. output.InjectFixedHeader(MqttControlPacketType.PubAck);
  429. return output.WriteToAsync(destination);
  430. }
  431. }
  432. private static Task SerializeAsync(MqttPubRecPacket packet, IMqttCommunicationChannel destination)
  433. {
  434. using (var output = new MqttPacketWriter())
  435. {
  436. output.Write(packet.PacketIdentifier);
  437. output.InjectFixedHeader(MqttControlPacketType.PubRec);
  438. return output.WriteToAsync(destination);
  439. }
  440. }
  441. private static Task SerializeAsync(MqttPubCompPacket packet, IMqttCommunicationChannel destination)
  442. {
  443. using (var output = new MqttPacketWriter())
  444. {
  445. output.Write(packet.PacketIdentifier);
  446. output.InjectFixedHeader(MqttControlPacketType.PubComp);
  447. return output.WriteToAsync(destination);
  448. }
  449. }
  450. private static Task SerializeAsync(MqttSubscribePacket packet, IMqttCommunicationChannel destination)
  451. {
  452. using (var output = new MqttPacketWriter())
  453. {
  454. output.Write(packet.PacketIdentifier);
  455. if (packet.TopicFilters?.Count > 0)
  456. {
  457. foreach (var topicFilter in packet.TopicFilters)
  458. {
  459. output.WriteWithLengthPrefix(topicFilter.Topic);
  460. output.Write((byte)topicFilter.QualityOfServiceLevel);
  461. }
  462. }
  463. output.InjectFixedHeader(MqttControlPacketType.Subscribe, 0x02);
  464. return output.WriteToAsync(destination);
  465. }
  466. }
  467. private static Task SerializeAsync(MqttSubAckPacket packet, IMqttCommunicationChannel destination)
  468. {
  469. using (var output = new MqttPacketWriter())
  470. {
  471. output.Write(packet.PacketIdentifier);
  472. if (packet.SubscribeReturnCodes?.Any() == true)
  473. {
  474. foreach (var packetSubscribeReturnCode in packet.SubscribeReturnCodes)
  475. {
  476. output.Write((byte)packetSubscribeReturnCode);
  477. }
  478. }
  479. output.InjectFixedHeader(MqttControlPacketType.SubAck);
  480. return output.WriteToAsync(destination);
  481. }
  482. }
  483. private static Task SerializeAsync(MqttUnsubscribePacket packet, IMqttCommunicationChannel destination)
  484. {
  485. using (var output = new MqttPacketWriter())
  486. {
  487. output.Write(packet.PacketIdentifier);
  488. if (packet.TopicFilters?.Any() == true)
  489. {
  490. foreach (var topicFilter in packet.TopicFilters)
  491. {
  492. output.WriteWithLengthPrefix(topicFilter);
  493. }
  494. }
  495. output.InjectFixedHeader(MqttControlPacketType.Unsubscibe, 0x02);
  496. return output.WriteToAsync(destination);
  497. }
  498. }
  499. private static Task SerializeAsync(MqttUnsubAckPacket packet, IMqttCommunicationChannel destination)
  500. {
  501. using (var output = new MqttPacketWriter())
  502. {
  503. output.Write(packet.PacketIdentifier);
  504. output.InjectFixedHeader(MqttControlPacketType.UnsubAck);
  505. return output.WriteToAsync(destination);
  506. }
  507. }
  508. private static Task SerializeEmptyPacketAsync(MqttControlPacketType type, IMqttCommunicationChannel destination)
  509. {
  510. using (var output = new MqttPacketWriter())
  511. {
  512. output.InjectFixedHeader(type);
  513. return output.WriteToAsync(destination);
  514. }
  515. }
  516. }
  517. }