MqttClient.cs 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631
  1. /*
  2. Copyright (c) 2013, 2014 Paolo Patierno
  3. All rights reserved. This program and the accompanying materials
  4. are made available under the terms of the Eclipse Public License v1.0
  5. and Eclipse Distribution License v1.0 which accompany this distribution.
  6. The Eclipse Public License is available at
  7. http://www.eclipse.org/legal/epl-v10.html
  8. and the Eclipse Distribution License is available at
  9. http://www.eclipse.org/org/documents/edl-v10.php.
  10. Contributors:
  11. Paolo Patierno - initial API and implementation and/or initial documentation
  12. */
  13. using System;
  14. using System.Net;
  15. #if !(WINDOWS_APP || WINDOWS_PHONE_APP)
  16. using System.Net.Sockets;
  17. using System.Security.Cryptography.X509Certificates;
  18. #endif
  19. using System.Threading;
  20. using uPLibrary.Networking.M2Mqtt.Exceptions;
  21. using uPLibrary.Networking.M2Mqtt.Messages;
  22. using uPLibrary.Networking.M2Mqtt.Session;
  23. using uPLibrary.Networking.M2Mqtt.Utility;
  24. using uPLibrary.Networking.M2Mqtt.Internal;
  25. // if .Net Micro Framework
  26. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
  27. using Microsoft.SPOT;
  28. #if SSL
  29. using Microsoft.SPOT.Net.Security;
  30. #endif
  31. // else other frameworks (.Net, .Net Compact, Mono, Windows Phone)
  32. #else
  33. using System.Collections.Generic;
  34. #if (SSL && !(WINDOWS_APP || WINDOWS_PHONE_APP))
  35. using System.Security.Authentication;
  36. using System.Net.Security;
  37. #endif
  38. #endif
  39. #if (WINDOWS_APP || WINDOWS_PHONE_APP)
  40. using Windows.Networking.Sockets;
  41. #endif
  42. using System.Collections;
  43. // alias needed due to Microsoft.SPOT.Trace in .Net Micro Framework
  44. // (it's ambiguos with uPLibrary.Networking.M2Mqtt.Utility.Trace)
  45. using MqttUtility = uPLibrary.Networking.M2Mqtt.Utility;
  46. using System.IO;
  47. namespace uPLibrary.Networking.M2Mqtt
  48. {
  49. /// <summary>
  50. /// MQTT Client
  51. /// </summary>
  52. public class MqttClient
  53. {
  54. #if BROKER
  55. #region Constants ...
  56. // thread names
  57. private const string RECEIVE_THREAD_NAME = "ReceiveThread";
  58. private const string RECEIVE_EVENT_THREAD_NAME = "DispatchEventThread";
  59. private const string PROCESS_INFLIGHT_THREAD_NAME = "ProcessInflightThread";
  60. private const string KEEP_ALIVE_THREAD = "KeepAliveThread";
  61. #endregion
  62. #endif
  63. /// <summary>
  64. /// Delagate that defines event handler for PUBLISH message received
  65. /// </summary>
  66. public delegate void MqttMsgPublishEventHandler(object sender, MqttMsgPublishEventArgs e);
  67. /// <summary>
  68. /// Delegate that defines event handler for published message
  69. /// </summary>
  70. public delegate void MqttMsgPublishedEventHandler(object sender, MqttMsgPublishedEventArgs e);
  71. /// <summary>
  72. /// Delagate that defines event handler for subscribed topic
  73. /// </summary>
  74. public delegate void MqttMsgSubscribedEventHandler(object sender, MqttMsgSubscribedEventArgs e);
  75. /// <summary>
  76. /// Delagate that defines event handler for unsubscribed topic
  77. /// </summary>
  78. public delegate void MqttMsgUnsubscribedEventHandler(object sender, MqttMsgUnsubscribedEventArgs e);
  79. #if BROKER
  80. /// <summary>
  81. /// Delagate that defines event handler for SUBSCRIBE message received
  82. /// </summary>
  83. public delegate void MqttMsgSubscribeEventHandler(object sender, MqttMsgSubscribeEventArgs e);
  84. /// <summary>
  85. /// Delagate that defines event handler for UNSUBSCRIBE message received
  86. /// </summary>
  87. public delegate void MqttMsgUnsubscribeEventHandler(object sender, MqttMsgUnsubscribeEventArgs e);
  88. /// <summary>
  89. /// Delagate that defines event handler for CONNECT message received
  90. /// </summary>
  91. public delegate void MqttMsgConnectEventHandler(object sender, MqttMsgConnectEventArgs e);
  92. /// <summary>
  93. /// Delegate that defines event handler for client disconnection (DISCONNECT message or not)
  94. /// </summary>
  95. public delegate void MqttMsgDisconnectEventHandler(object sender, EventArgs e);
  96. #endif
  97. /// <summary>
  98. /// Delegate that defines event handler for cliet/peer disconnection
  99. /// </summary>
  100. public delegate void ConnectionClosedEventHandler(object sender, EventArgs e);
  101. // broker hostname (or ip address) and port
  102. private string brokerHostName;
  103. private int brokerPort;
  104. // running status of threads
  105. private bool isRunning;
  106. // event for raising received message event
  107. private AutoResetEvent receiveEventWaitHandle;
  108. // event for starting process inflight queue asynchronously
  109. private AutoResetEvent inflightWaitHandle;
  110. // event for signaling synchronous receive
  111. AutoResetEvent syncEndReceiving;
  112. // message received
  113. MqttMsgBase msgReceived;
  114. // exeption thrown during receiving
  115. Exception exReceiving;
  116. // keep alive period (in ms)
  117. private int keepAlivePeriod;
  118. // events for signaling on keep alive thread
  119. private AutoResetEvent keepAliveEvent;
  120. private AutoResetEvent keepAliveEventEnd;
  121. // last communication time in ticks
  122. private int lastCommTime;
  123. // event for PUBLISH message received
  124. public event MqttMsgPublishEventHandler MqttMsgPublishReceived;
  125. // event for published message
  126. public event MqttMsgPublishedEventHandler MqttMsgPublished;
  127. // event for subscribed topic
  128. public event MqttMsgSubscribedEventHandler MqttMsgSubscribed;
  129. // event for unsubscribed topic
  130. public event MqttMsgUnsubscribedEventHandler MqttMsgUnsubscribed;
  131. #if BROKER
  132. // event for SUBSCRIBE message received
  133. public event MqttMsgSubscribeEventHandler MqttMsgSubscribeReceived;
  134. // event for USUBSCRIBE message received
  135. public event MqttMsgUnsubscribeEventHandler MqttMsgUnsubscribeReceived;
  136. // event for CONNECT message received
  137. public event MqttMsgConnectEventHandler MqttMsgConnected;
  138. // event for DISCONNECT message received
  139. public event MqttMsgDisconnectEventHandler MqttMsgDisconnected;
  140. #endif
  141. // event for peer/client disconnection
  142. public event ConnectionClosedEventHandler ConnectionClosed;
  143. // channel to communicate over the network
  144. private IMqttNetworkChannel channel;
  145. // inflight messages queue
  146. private Queue inflightQueue;
  147. // internal queue for received messages about inflight messages
  148. private Queue internalQueue;
  149. // internal queue for dispatching events
  150. private Queue eventQueue;
  151. // session
  152. private MqttClientSession session;
  153. // reference to avoid access to singleton via property
  154. private MqttSettings settings;
  155. // current message identifier generated
  156. private ushort messageIdCounter = 0;
  157. // connection is closing due to peer
  158. private bool isConnectionClosing;
  159. /// <summary>
  160. /// Connection status between client and broker
  161. /// </summary>
  162. public bool IsConnected { get; private set; }
  163. /// <summary>
  164. /// Client identifier
  165. /// </summary>
  166. public string ClientId { get; private set; }
  167. /// <summary>
  168. /// Clean session flag
  169. /// </summary>
  170. public bool CleanSession { get; private set; }
  171. /// <summary>
  172. /// Will flag
  173. /// </summary>
  174. public bool WillFlag { get; private set; }
  175. /// <summary>
  176. /// Will QOS level
  177. /// </summary>
  178. public byte WillQosLevel { get; private set; }
  179. /// <summary>
  180. /// Will topic
  181. /// </summary>
  182. public string WillTopic { get; private set; }
  183. /// <summary>
  184. /// Will message
  185. /// </summary>
  186. public string WillMessage { get; private set; }
  187. /// <summary>
  188. /// MQTT protocol version
  189. /// </summary>
  190. public MqttProtocolVersion ProtocolVersion { get; set; }
  191. #if BROKER
  192. /// <summary>
  193. /// MQTT Client Session
  194. /// </summary>
  195. public MqttClientSession Session
  196. {
  197. get { return this.session; }
  198. set { this.session = value; }
  199. }
  200. #endif
  201. /// <summary>
  202. /// MQTT client settings
  203. /// </summary>
  204. public MqttSettings Settings
  205. {
  206. get { return this.settings; }
  207. }
  208. #if !(WINDOWS_APP || WINDOWS_PHONE_APP)
  209. /// <summary>
  210. /// Constructor
  211. /// </summary>
  212. /// <param name="brokerIpAddress">Broker IP address</param>
  213. [Obsolete("Use this ctor MqttClient(string brokerHostName) insted")]
  214. public MqttClient(IPAddress brokerIpAddress) :
  215. this(brokerIpAddress, MqttSettings.MQTT_BROKER_DEFAULT_PORT, false, null, null, MqttSslProtocols.None)
  216. {
  217. }
  218. /// <summary>
  219. /// Constructor
  220. /// </summary>
  221. /// <param name="brokerIpAddress">Broker IP address</param>
  222. /// <param name="brokerPort">Broker port</param>
  223. /// <param name="secure">Using secure connection</param>
  224. /// <param name="caCert">CA certificate for secure connection</param>
  225. /// <param name="clientCert">Client certificate</param>
  226. /// <param name="sslProtocol">SSL/TLS protocol version</param>
  227. [Obsolete("Use this ctor MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert) insted")]
  228. public MqttClient(IPAddress brokerIpAddress, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
  229. {
  230. #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  231. this.Init(brokerIpAddress.ToString(), brokerPort, secure, caCert, clientCert, sslProtocol, null, null);
  232. #else
  233. this.Init(brokerIpAddress.ToString(), brokerPort, secure, caCert, clientCert, sslProtocol);
  234. #endif
  235. }
  236. #endif
  237. /// <summary>
  238. /// Constructor
  239. /// </summary>
  240. /// <param name="brokerHostName">Broker Host Name or IP Address</param>
  241. public MqttClient(string brokerHostName) :
  242. #if !(WINDOWS_APP || WINDOWS_PHONE_APP)
  243. this(brokerHostName, MqttSettings.MQTT_BROKER_DEFAULT_PORT, false, null, null, MqttSslProtocols.None)
  244. #else
  245. this(brokerHostName, MqttSettings.MQTT_BROKER_DEFAULT_PORT, false, MqttSslProtocols.None)
  246. #endif
  247. {
  248. }
  249. /// <summary>
  250. /// Constructor
  251. /// </summary>
  252. /// <param name="brokerHostName">Broker Host Name or IP Address</param>
  253. /// <param name="brokerPort">Broker port</param>
  254. /// <param name="secure">Using secure connection</param>
  255. /// <param name="sslProtocol">SSL/TLS protocol version</param>
  256. #if !(WINDOWS_APP || WINDOWS_PHONE_APP)
  257. /// <param name="caCert">CA certificate for secure connection</param>
  258. /// <param name="clientCert">Client certificate</param>
  259. public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
  260. #else
  261. public MqttClient(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol)
  262. #endif
  263. {
  264. #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP)
  265. this.Init(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol, null, null);
  266. #elif (WINDOWS_APP || WINDOWS_PHONE_APP)
  267. this.Init(brokerHostName, brokerPort, secure, sslProtocol);
  268. #else
  269. this.Init(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol);
  270. #endif
  271. }
  272. #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP)
  273. /// <summary>
  274. /// Constructor
  275. /// </summary>
  276. /// <param name="brokerHostName">Broker Host Name or IP Address</param>
  277. /// <param name="brokerPort">Broker port</param>
  278. /// <param name="secure">Using secure connection</param>
  279. /// <param name="caCert">CA certificate for secure connection</param>
  280. /// <param name="clientCert">Client certificate</param>
  281. /// <param name="sslProtocol">SSL/TLS protocol version</param>
  282. /// <param name="userCertificateValidationCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
  283. public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol,
  284. RemoteCertificateValidationCallback userCertificateValidationCallback)
  285. : this(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol, userCertificateValidationCallback, null)
  286. {
  287. }
  288. /// <summary>
  289. /// Constructor
  290. /// </summary>
  291. /// <param name="brokerHostName">Broker Host Name or IP Address</param>
  292. /// <param name="brokerPort">Broker port</param>
  293. /// <param name="secure">Using secure connection</param>
  294. /// <param name="sslProtocol">SSL/TLS protocol version</param>
  295. /// <param name="userCertificateValidationCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
  296. /// <param name="userCertificateSelectionCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
  297. public MqttClient(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol,
  298. RemoteCertificateValidationCallback userCertificateValidationCallback,
  299. LocalCertificateSelectionCallback userCertificateSelectionCallback)
  300. : this(brokerHostName, brokerPort, secure, null, null, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback)
  301. {
  302. }
  303. /// <summary>
  304. /// Constructor
  305. /// </summary>
  306. /// <param name="brokerHostName">Broker Host Name or IP Address</param>
  307. /// <param name="brokerPort">Broker port</param>
  308. /// <param name="secure">Using secure connection</param>
  309. /// <param name="caCert">CA certificate for secure connection</param>
  310. /// <param name="clientCert">Client certificate</param>
  311. /// <param name="sslProtocol">SSL/TLS protocol version</param>
  312. /// <param name="userCertificateValidationCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
  313. /// <param name="userCertificateSelectionCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
  314. public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol,
  315. RemoteCertificateValidationCallback userCertificateValidationCallback,
  316. LocalCertificateSelectionCallback userCertificateSelectionCallback)
  317. {
  318. this.Init(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback);
  319. }
  320. #endif
  321. #if BROKER
  322. /// <summary>
  323. /// Constructor
  324. /// </summary>
  325. /// <param name="channel">Network channel for communication</param>
  326. public MqttClient(IMqttNetworkChannel channel)
  327. {
  328. // set default MQTT protocol version (default is 3.1.1)
  329. this.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
  330. this.channel = channel;
  331. // reference to MQTT settings
  332. this.settings = MqttSettings.Instance;
  333. // client not connected yet (CONNACK not send from client), some default values
  334. this.IsConnected = false;
  335. this.ClientId = null;
  336. this.CleanSession = true;
  337. this.keepAliveEvent = new AutoResetEvent(false);
  338. // queue for handling inflight messages (publishing and acknowledge)
  339. this.inflightWaitHandle = new AutoResetEvent(false);
  340. this.inflightQueue = new Queue();
  341. // queue for received message
  342. this.receiveEventWaitHandle = new AutoResetEvent(false);
  343. this.eventQueue = new Queue();
  344. this.internalQueue = new Queue();
  345. // session
  346. this.session = null;
  347. }
  348. #endif
  349. /// <summary>
  350. /// MqttClient initialization
  351. /// </summary>
  352. /// <param name="brokerHostName">Broker Host Name or IP Address</param>
  353. /// <param name="brokerPort">Broker port</param>
  354. /// <param name="secure">>Using secure connection</param>
  355. /// <param name="caCert">CA certificate for secure connection</param>
  356. /// <param name="clientCert">Client certificate</param>
  357. /// <param name="sslProtocol">SSL/TLS protocol version</param>
  358. #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP)
  359. /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
  360. /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
  361. private void Init(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol,
  362. RemoteCertificateValidationCallback userCertificateValidationCallback,
  363. LocalCertificateSelectionCallback userCertificateSelectionCallback)
  364. #elif (WINDOWS_APP || WINDOWS_PHONE_APP)
  365. private void Init(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol)
  366. #else
  367. private void Init(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
  368. #endif
  369. {
  370. // set default MQTT protocol version (default is 3.1.1)
  371. this.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
  372. #if !SSL
  373. // check security parameters
  374. if (secure)
  375. throw new ArgumentException("Library compiled without SSL support");
  376. #endif
  377. this.brokerHostName = brokerHostName;
  378. this.brokerPort = brokerPort;
  379. // reference to MQTT settings
  380. this.settings = MqttSettings.Instance;
  381. // set settings port based on secure connection or not
  382. if (!secure)
  383. this.settings.Port = this.brokerPort;
  384. else
  385. this.settings.SslPort = this.brokerPort;
  386. this.syncEndReceiving = new AutoResetEvent(false);
  387. this.keepAliveEvent = new AutoResetEvent(false);
  388. // queue for handling inflight messages (publishing and acknowledge)
  389. this.inflightWaitHandle = new AutoResetEvent(false);
  390. this.inflightQueue = new Queue();
  391. // queue for received message
  392. this.receiveEventWaitHandle = new AutoResetEvent(false);
  393. this.eventQueue = new Queue();
  394. this.internalQueue = new Queue();
  395. // session
  396. this.session = null;
  397. // create network channel
  398. #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP)
  399. this.channel = new MqttNetworkChannel(this.brokerHostName, this.brokerPort, secure, caCert, clientCert, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback);
  400. #elif (WINDOWS_APP || WINDOWS_PHONE_APP)
  401. this.channel = new MqttNetworkChannel(this.brokerHostName, this.brokerPort, secure, sslProtocol);
  402. #else
  403. this.channel = new MqttNetworkChannel(this.brokerHostName, this.brokerPort, secure, caCert, clientCert, sslProtocol);
  404. #endif
  405. }
  406. /// <summary>
  407. /// Connect to broker
  408. /// </summary>
  409. /// <param name="clientId">Client identifier</param>
  410. /// <returns>Return code of CONNACK message from broker</returns>
  411. public byte Connect(string clientId)
  412. {
  413. return this.Connect(clientId, null, null, false, MqttMsgConnect.QOS_LEVEL_AT_MOST_ONCE, false, null, null, true, MqttMsgConnect.KEEP_ALIVE_PERIOD_DEFAULT);
  414. }
  415. /// <summary>
  416. /// Connect to broker
  417. /// </summary>
  418. /// <param name="clientId">Client identifier</param>
  419. /// <param name="username">Username</param>
  420. /// <param name="password">Password</param>
  421. /// <returns>Return code of CONNACK message from broker</returns>
  422. public byte Connect(string clientId,
  423. string username,
  424. string password)
  425. {
  426. return this.Connect(clientId, username, password, false, MqttMsgConnect.QOS_LEVEL_AT_MOST_ONCE, false, null, null, true, MqttMsgConnect.KEEP_ALIVE_PERIOD_DEFAULT);
  427. }
  428. /// <summary>
  429. /// Connect to broker
  430. /// </summary>
  431. /// <param name="clientId">Client identifier</param>
  432. /// <param name="username">Username</param>
  433. /// <param name="password">Password</param>
  434. /// <param name="cleanSession">Clean sessione flag</param>
  435. /// <param name="keepAlivePeriod">Keep alive period</param>
  436. /// <returns>Return code of CONNACK message from broker</returns>
  437. public byte Connect(string clientId,
  438. string username,
  439. string password,
  440. bool cleanSession,
  441. ushort keepAlivePeriod)
  442. {
  443. return this.Connect(clientId, username, password, false, MqttMsgConnect.QOS_LEVEL_AT_MOST_ONCE, false, null, null, cleanSession, keepAlivePeriod);
  444. }
  445. /// <summary>
  446. /// Connect to broker
  447. /// </summary>
  448. /// <param name="clientId">Client identifier</param>
  449. /// <param name="username">Username</param>
  450. /// <param name="password">Password</param>
  451. /// <param name="willRetain">Will retain flag</param>
  452. /// <param name="willQosLevel">Will QOS level</param>
  453. /// <param name="willFlag">Will flag</param>
  454. /// <param name="willTopic">Will topic</param>
  455. /// <param name="willMessage">Will message</param>
  456. /// <param name="cleanSession">Clean sessione flag</param>
  457. /// <param name="keepAlivePeriod">Keep alive period</param>
  458. /// <returns>Return code of CONNACK message from broker</returns>
  459. public byte Connect(string clientId,
  460. string username,
  461. string password,
  462. bool willRetain,
  463. byte willQosLevel,
  464. bool willFlag,
  465. string willTopic,
  466. string willMessage,
  467. bool cleanSession,
  468. ushort keepAlivePeriod)
  469. {
  470. // create CONNECT message
  471. MqttMsgConnect connect = new MqttMsgConnect(clientId,
  472. username,
  473. password,
  474. willRetain,
  475. willQosLevel,
  476. willFlag,
  477. willTopic,
  478. willMessage,
  479. cleanSession,
  480. keepAlivePeriod,
  481. (byte)this.ProtocolVersion);
  482. try
  483. {
  484. // connect to the broker
  485. this.channel.Connect();
  486. }
  487. catch (Exception ex)
  488. {
  489. throw new MqttConnectionException("Exception connecting to the broker", ex);
  490. }
  491. this.lastCommTime = 0;
  492. this.isRunning = true;
  493. this.isConnectionClosing = false;
  494. // start thread for receiving messages from broker
  495. Fx.StartThread(this.ReceiveThread);
  496. MqttMsgConnack connack = (MqttMsgConnack)this.SendReceive(connect);
  497. // if connection accepted, start keep alive timer and
  498. if (connack.ReturnCode == MqttMsgConnack.CONN_ACCEPTED)
  499. {
  500. // set all client properties
  501. this.ClientId = clientId;
  502. this.CleanSession = cleanSession;
  503. this.WillFlag = willFlag;
  504. this.WillTopic = willTopic;
  505. this.WillMessage = willMessage;
  506. this.WillQosLevel = willQosLevel;
  507. this.keepAlivePeriod = keepAlivePeriod * 1000; // convert in ms
  508. // restore previous session
  509. this.RestoreSession();
  510. // keep alive period equals zero means turning off keep alive mechanism
  511. if (this.keepAlivePeriod != 0)
  512. {
  513. // start thread for sending keep alive message to the broker
  514. Fx.StartThread(this.KeepAliveThread);
  515. }
  516. // start thread for raising received message event from broker
  517. Fx.StartThread(this.DispatchEventThread);
  518. // start thread for handling inflight messages queue to broker asynchronously (publish and acknowledge)
  519. Fx.StartThread(this.ProcessInflightThread);
  520. this.IsConnected = true;
  521. }
  522. return connack.ReturnCode;
  523. }
  524. /// <summary>
  525. /// Disconnect from broker
  526. /// </summary>
  527. public void Disconnect()
  528. {
  529. MqttMsgDisconnect disconnect = new MqttMsgDisconnect();
  530. this.Send(disconnect);
  531. // close client
  532. this.OnConnectionClosing();
  533. }
  534. #if BROKER
  535. /// <summary>
  536. /// Open client communication
  537. /// </summary>
  538. public void Open()
  539. {
  540. this.isRunning = true;
  541. // start thread for receiving messages from client
  542. Fx.StartThread(this.ReceiveThread);
  543. // start thread for raising received message event from client
  544. Fx.StartThread(this.DispatchEventThread);
  545. // start thread for handling inflight messages queue to client asynchronously (publish and acknowledge)
  546. Fx.StartThread(this.ProcessInflightThread);
  547. }
  548. #endif
  549. /// <summary>
  550. /// Close client
  551. /// </summary>
  552. #if BROKER
  553. public void Close()
  554. #else
  555. private void Close()
  556. #endif
  557. {
  558. // stop receiving thread
  559. this.isRunning = false;
  560. // wait end receive event thread
  561. if (this.receiveEventWaitHandle != null)
  562. this.receiveEventWaitHandle.Set();
  563. // wait end process inflight thread
  564. if (this.inflightWaitHandle != null)
  565. this.inflightWaitHandle.Set();
  566. #if BROKER
  567. // unlock keep alive thread
  568. this.keepAliveEvent.Set();
  569. #else
  570. // unlock keep alive thread and wait
  571. this.keepAliveEvent.Set();
  572. if (this.keepAliveEventEnd != null)
  573. this.keepAliveEventEnd.WaitOne();
  574. #endif
  575. // clear all queues
  576. this.inflightQueue.Clear();
  577. this.internalQueue.Clear();
  578. this.eventQueue.Clear();
  579. // close network channel
  580. this.channel.Close();
  581. this.IsConnected = false;
  582. }
  583. /// <summary>
  584. /// Execute ping to broker for keep alive
  585. /// </summary>
  586. /// <returns>PINGRESP message from broker</returns>
  587. private MqttMsgPingResp Ping()
  588. {
  589. MqttMsgPingReq pingreq = new MqttMsgPingReq();
  590. try
  591. {
  592. // broker must send PINGRESP within timeout equal to keep alive period
  593. return (MqttMsgPingResp)this.SendReceive(pingreq, this.keepAlivePeriod);
  594. }
  595. catch (Exception e)
  596. {
  597. #if TRACE
  598. MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString());
  599. #endif
  600. // client must close connection
  601. this.OnConnectionClosing();
  602. return null;
  603. }
  604. }
  605. #if BROKER
  606. /// <summary>
  607. /// Send CONNACK message to the client (connection accepted or not)
  608. /// </summary>
  609. /// <param name="connect">CONNECT message with all client information</param>
  610. /// <param name="returnCode">Return code for CONNACK message</param>
  611. /// <param name="clientId">If not null, client id assigned by broker</param>
  612. /// <param name="sessionPresent">Session present on the broker</param>
  613. public void Connack(MqttMsgConnect connect, byte returnCode, string clientId, bool sessionPresent)
  614. {
  615. this.lastCommTime = 0;
  616. // create CONNACK message and ...
  617. MqttMsgConnack connack = new MqttMsgConnack();
  618. connack.ReturnCode = returnCode;
  619. // [v3.1.1] session present flag
  620. if (this.ProtocolVersion == MqttProtocolVersion.Version_3_1_1)
  621. connack.SessionPresent = sessionPresent;
  622. // ... send it to the client
  623. this.Send(connack);
  624. // connection accepted, start keep alive thread checking
  625. if (connack.ReturnCode == MqttMsgConnack.CONN_ACCEPTED)
  626. {
  627. // [v3.1.1] if client id isn't null, the CONNECT message has a cliend id with zero bytes length
  628. // and broker assigned a unique identifier to the client
  629. this.ClientId = (clientId == null) ? connect.ClientId : clientId;
  630. this.CleanSession = connect.CleanSession;
  631. this.WillFlag = connect.WillFlag;
  632. this.WillTopic = connect.WillTopic;
  633. this.WillMessage = connect.WillMessage;
  634. this.WillQosLevel = connect.WillQosLevel;
  635. this.keepAlivePeriod = connect.KeepAlivePeriod * 1000; // convert in ms
  636. // broker has a tolerance of 1.5 specified keep alive period
  637. this.keepAlivePeriod += (this.keepAlivePeriod / 2);
  638. // start thread for checking keep alive period timeout
  639. Fx.StartThread(this.KeepAliveThread);
  640. this.isConnectionClosing = false;
  641. this.IsConnected = true;
  642. }
  643. // connection refused, close TCP/IP channel
  644. else
  645. {
  646. this.Close();
  647. }
  648. }
  649. /// <summary>
  650. /// Send SUBACK message to the client
  651. /// </summary>
  652. /// <param name="messageId">Message Id for the SUBSCRIBE message that is being acknowledged</param>
  653. /// <param name="grantedQosLevels">Granted QoS Levels</param>
  654. public void Suback(ushort messageId, byte[] grantedQosLevels)
  655. {
  656. MqttMsgSuback suback = new MqttMsgSuback();
  657. suback.MessageId = messageId;
  658. suback.GrantedQoSLevels = grantedQosLevels;
  659. this.Send(suback);
  660. }
  661. /// <summary>
  662. /// Send UNSUBACK message to the client
  663. /// </summary>
  664. /// <param name="messageId">Message Id for the UNSUBSCRIBE message that is being acknowledged</param>
  665. public void Unsuback(ushort messageId)
  666. {
  667. MqttMsgUnsuback unsuback = new MqttMsgUnsuback();
  668. unsuback.MessageId = messageId;
  669. this.Send(unsuback);
  670. }
  671. #endif
  672. /// <summary>
  673. /// Subscribe for message topics
  674. /// </summary>
  675. /// <param name="topics">List of topics to subscribe</param>
  676. /// <param name="qosLevels">QOS levels related to topics</param>
  677. /// <returns>Message Id related to SUBSCRIBE message</returns>
  678. public ushort Subscribe(string[] topics, byte[] qosLevels)
  679. {
  680. MqttMsgSubscribe subscribe =
  681. new MqttMsgSubscribe(topics, qosLevels);
  682. subscribe.MessageId = this.GetMessageId();
  683. // enqueue subscribe request into the inflight queue
  684. this.EnqueueInflight(subscribe, MqttMsgFlow.ToPublish);
  685. return subscribe.MessageId;
  686. }
  687. /// <summary>
  688. /// Unsubscribe for message topics
  689. /// </summary>
  690. /// <param name="topics">List of topics to unsubscribe</param>
  691. /// <returns>Message Id in UNSUBACK message from broker</returns>
  692. public ushort Unsubscribe(string[] topics)
  693. {
  694. MqttMsgUnsubscribe unsubscribe =
  695. new MqttMsgUnsubscribe(topics);
  696. unsubscribe.MessageId = this.GetMessageId();
  697. // enqueue unsubscribe request into the inflight queue
  698. this.EnqueueInflight(unsubscribe, MqttMsgFlow.ToPublish);
  699. return unsubscribe.MessageId;
  700. }
  701. /// <summary>
  702. /// Publish a message asynchronously (QoS Level 0 and not retained)
  703. /// </summary>
  704. /// <param name="topic">Message topic</param>
  705. /// <param name="message">Message data (payload)</param>
  706. /// <returns>Message Id related to PUBLISH message</returns>
  707. public ushort Publish(string topic, byte[] message)
  708. {
  709. return this.Publish(topic, message, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
  710. }
  711. /// <summary>
  712. /// Publish a message asynchronously
  713. /// </summary>
  714. /// <param name="topic">Message topic</param>
  715. /// <param name="message">Message data (payload)</param>
  716. /// <param name="qosLevel">QoS Level</param>
  717. /// <param name="retain">Retain flag</param>
  718. /// <returns>Message Id related to PUBLISH message</returns>
  719. public ushort Publish(string topic, byte[] message, byte qosLevel, bool retain)
  720. {
  721. MqttMsgPublish publish =
  722. new MqttMsgPublish(topic, message, false, qosLevel, retain);
  723. publish.MessageId = this.GetMessageId();
  724. // enqueue message to publish into the inflight queue
  725. bool enqueue = this.EnqueueInflight(publish, MqttMsgFlow.ToPublish);
  726. // message enqueued
  727. if (enqueue)
  728. return publish.MessageId;
  729. // infligh queue full, message not enqueued
  730. else
  731. throw new MqttClientException(MqttClientErrorCode.InflightQueueFull);
  732. }
  733. /// <summary>
  734. /// Wrapper method for raising events
  735. /// </summary>
  736. /// <param name="internalEvent">Internal event</param>
  737. private void OnInternalEvent(InternalEvent internalEvent)
  738. {
  739. lock (this.eventQueue)
  740. {
  741. this.eventQueue.Enqueue(internalEvent);
  742. }
  743. this.receiveEventWaitHandle.Set();
  744. }
  745. /// <summary>
  746. /// Wrapper method for raising closing connection event
  747. /// </summary>
  748. private void OnConnectionClosing()
  749. {
  750. if (!this.isConnectionClosing)
  751. {
  752. this.isConnectionClosing = true;
  753. this.receiveEventWaitHandle.Set();
  754. }
  755. }
  756. /// <summary>
  757. /// Wrapper method for raising PUBLISH message received event
  758. /// </summary>
  759. /// <param name="publish">PUBLISH message received</param>
  760. private void OnMqttMsgPublishReceived(MqttMsgPublish publish)
  761. {
  762. if (this.MqttMsgPublishReceived != null)
  763. {
  764. this.MqttMsgPublishReceived(this,
  765. new MqttMsgPublishEventArgs(publish.Topic, publish.Message, publish.DupFlag, publish.QosLevel, publish.Retain));
  766. }
  767. }
  768. /// <summary>
  769. /// Wrapper method for raising published message event
  770. /// </summary>
  771. /// <param name="messageId">Message identifier for published message</param>
  772. /// <param name="isPublished">Publish flag</param>
  773. private void OnMqttMsgPublished(ushort messageId, bool isPublished)
  774. {
  775. if (this.MqttMsgPublished != null)
  776. {
  777. this.MqttMsgPublished(this,
  778. new MqttMsgPublishedEventArgs(messageId, isPublished));
  779. }
  780. }
  781. /// <summary>
  782. /// Wrapper method for raising subscribed topic event
  783. /// </summary>
  784. /// <param name="suback">SUBACK message received</param>
  785. private void OnMqttMsgSubscribed(MqttMsgSuback suback)
  786. {
  787. if (this.MqttMsgSubscribed != null)
  788. {
  789. this.MqttMsgSubscribed(this,
  790. new MqttMsgSubscribedEventArgs(suback.MessageId, suback.GrantedQoSLevels));
  791. }
  792. }
  793. /// <summary>
  794. /// Wrapper method for raising unsubscribed topic event
  795. /// </summary>
  796. /// <param name="messageId">Message identifier for unsubscribed topic</param>
  797. private void OnMqttMsgUnsubscribed(ushort messageId)
  798. {
  799. if (this.MqttMsgUnsubscribed != null)
  800. {
  801. this.MqttMsgUnsubscribed(this,
  802. new MqttMsgUnsubscribedEventArgs(messageId));
  803. }
  804. }
  805. #if BROKER
  806. /// <summary>
  807. /// Wrapper method for raising SUBSCRIBE message event
  808. /// </summary>
  809. /// <param name="messageId">Message identifier for subscribe topics request</param>
  810. /// <param name="topics">Topics requested to subscribe</param>
  811. /// <param name="qosLevels">List of QOS Levels requested</param>
  812. private void OnMqttMsgSubscribeReceived(ushort messageId, string[] topics, byte[] qosLevels)
  813. {
  814. if (this.MqttMsgSubscribeReceived != null)
  815. {
  816. this.MqttMsgSubscribeReceived(this,
  817. new MqttMsgSubscribeEventArgs(messageId, topics, qosLevels));
  818. }
  819. }
  820. /// <summary>
  821. /// Wrapper method for raising UNSUBSCRIBE message event
  822. /// </summary>
  823. /// <param name="messageId">Message identifier for unsubscribe topics request</param>
  824. /// <param name="topics">Topics requested to unsubscribe</param>
  825. private void OnMqttMsgUnsubscribeReceived(ushort messageId, string[] topics)
  826. {
  827. if (this.MqttMsgUnsubscribeReceived != null)
  828. {
  829. this.MqttMsgUnsubscribeReceived(this,
  830. new MqttMsgUnsubscribeEventArgs(messageId, topics));
  831. }
  832. }
  833. /// <summary>
  834. /// Wrapper method for raising CONNECT message event
  835. /// </summary>
  836. private void OnMqttMsgConnected(MqttMsgConnect connect)
  837. {
  838. if (this.MqttMsgConnected != null)
  839. {
  840. this.ProtocolVersion = (MqttProtocolVersion)connect.ProtocolVersion;
  841. this.MqttMsgConnected(this, new MqttMsgConnectEventArgs(connect));
  842. }
  843. }
  844. /// <summary>
  845. /// Wrapper method for raising DISCONNECT message event
  846. /// </summary>
  847. private void OnMqttMsgDisconnected()
  848. {
  849. if (this.MqttMsgDisconnected != null)
  850. {
  851. this.MqttMsgDisconnected(this, EventArgs.Empty);
  852. }
  853. }
  854. #endif
  855. /// <summary>
  856. /// Wrapper method for peer/client disconnection
  857. /// </summary>
  858. private void OnConnectionClosed()
  859. {
  860. if (this.ConnectionClosed != null)
  861. {
  862. this.ConnectionClosed(this, EventArgs.Empty);
  863. }
  864. }
  865. /// <summary>
  866. /// Send a message
  867. /// </summary>
  868. /// <param name="msgBytes">Message bytes</param>
  869. private void Send(byte[] msgBytes)
  870. {
  871. try
  872. {
  873. // send message
  874. this.channel.Send(msgBytes);
  875. #if !BROKER
  876. // update last message sent ticks
  877. this.lastCommTime = Environment.TickCount;
  878. #endif
  879. }
  880. catch (Exception e)
  881. {
  882. #if TRACE
  883. MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString());
  884. #endif
  885. throw new MqttCommunicationException(e);
  886. }
  887. }
  888. /// <summary>
  889. /// Send a message
  890. /// </summary>
  891. /// <param name="msg">Message</param>
  892. private void Send(MqttMsgBase msg)
  893. {
  894. #if TRACE
  895. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "SEND {0}", msg);
  896. #endif
  897. this.Send(msg.GetBytes((byte)this.ProtocolVersion));
  898. }
  899. /// <summary>
  900. /// Send a message to the broker and wait answer
  901. /// </summary>
  902. /// <param name="msgBytes">Message bytes</param>
  903. /// <returns>MQTT message response</returns>
  904. private MqttMsgBase SendReceive(byte[] msgBytes)
  905. {
  906. return this.SendReceive(msgBytes, MqttSettings.MQTT_DEFAULT_TIMEOUT);
  907. }
  908. /// <summary>
  909. /// Send a message to the broker and wait answer
  910. /// </summary>
  911. /// <param name="msgBytes">Message bytes</param>
  912. /// <param name="timeout">Timeout for receiving answer</param>
  913. /// <returns>MQTT message response</returns>
  914. private MqttMsgBase SendReceive(byte[] msgBytes, int timeout)
  915. {
  916. // reset handle before sending
  917. this.syncEndReceiving.Reset();
  918. try
  919. {
  920. // send message
  921. this.channel.Send(msgBytes);
  922. // update last message sent ticks
  923. this.lastCommTime = Environment.TickCount;
  924. }
  925. catch (Exception e)
  926. {
  927. #if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP)
  928. if (typeof(SocketException) == e.GetType())
  929. {
  930. // connection reset by broker
  931. if (((SocketException)e).SocketErrorCode == SocketError.ConnectionReset)
  932. this.IsConnected = false;
  933. }
  934. #endif
  935. #if TRACE
  936. MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString());
  937. #endif
  938. throw new MqttCommunicationException(e);
  939. }
  940. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  941. // wait for answer from broker
  942. if (this.syncEndReceiving.WaitOne(timeout, false))
  943. #else
  944. // wait for answer from broker
  945. if (this.syncEndReceiving.WaitOne(timeout))
  946. #endif
  947. {
  948. // message received without exception
  949. if (this.exReceiving == null)
  950. return this.msgReceived;
  951. // receiving thread catched exception
  952. else
  953. throw this.exReceiving;
  954. }
  955. else
  956. {
  957. // throw timeout exception
  958. throw new MqttCommunicationException();
  959. }
  960. }
  961. /// <summary>
  962. /// Send a message to the broker and wait answer
  963. /// </summary>
  964. /// <param name="msg">Message</param>
  965. /// <returns>MQTT message response</returns>
  966. private MqttMsgBase SendReceive(MqttMsgBase msg)
  967. {
  968. return this.SendReceive(msg, MqttSettings.MQTT_DEFAULT_TIMEOUT);
  969. }
  970. /// <summary>
  971. /// Send a message to the broker and wait answer
  972. /// </summary>
  973. /// <param name="msg">Message</param>
  974. /// <param name="timeout">Timeout for receiving answer</param>
  975. /// <returns>MQTT message response</returns>
  976. private MqttMsgBase SendReceive(MqttMsgBase msg, int timeout)
  977. {
  978. #if TRACE
  979. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "SEND {0}", msg);
  980. #endif
  981. return this.SendReceive(msg.GetBytes((byte)this.ProtocolVersion), timeout);
  982. }
  983. /// <summary>
  984. /// Enqueue a message into the inflight queue
  985. /// </summary>
  986. /// <param name="msg">Message to enqueue</param>
  987. /// <param name="flow">Message flow (publish, acknowledge)</param>
  988. /// <returns>Message enqueued or not</returns>
  989. private bool EnqueueInflight(MqttMsgBase msg, MqttMsgFlow flow)
  990. {
  991. // enqueue is needed (or not)
  992. bool enqueue = true;
  993. // if it is a PUBLISH message with QoS Level 2
  994. if ((msg.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) &&
  995. (msg.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE))
  996. {
  997. lock (this.inflightQueue)
  998. {
  999. // if it is a PUBLISH message already received (it is in the inflight queue), the publisher
  1000. // re-sent it because it didn't received the PUBREC. In this case, we have to re-send PUBREC
  1001. // NOTE : I need to find on message id and flow because the broker could be publish/received
  1002. // to/from client and message id could be the same (one tracked by broker and the other by client)
  1003. MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToAcknowledge);
  1004. MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find);
  1005. // the PUBLISH message is alredy in the inflight queue, we don't need to re-enqueue but we need
  1006. // to change state to re-send PUBREC
  1007. if (msgCtx != null)
  1008. {
  1009. msgCtx.State = MqttMsgState.QueuedQos2;
  1010. msgCtx.Flow = MqttMsgFlow.ToAcknowledge;
  1011. enqueue = false;
  1012. }
  1013. }
  1014. }
  1015. if (enqueue)
  1016. {
  1017. // set a default state
  1018. MqttMsgState state = MqttMsgState.QueuedQos0;
  1019. // based on QoS level, the messages flow between broker and client changes
  1020. switch (msg.QosLevel)
  1021. {
  1022. // QoS Level 0
  1023. case MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE:
  1024. state = MqttMsgState.QueuedQos0;
  1025. break;
  1026. // QoS Level 1
  1027. case MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE:
  1028. state = MqttMsgState.QueuedQos1;
  1029. break;
  1030. // QoS Level 2
  1031. case MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE:
  1032. state = MqttMsgState.QueuedQos2;
  1033. break;
  1034. }
  1035. // [v3.1.1] SUBSCRIBE and UNSUBSCRIBE aren't "officially" QOS = 1
  1036. // so QueuedQos1 state isn't valid for them
  1037. if (msg.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE)
  1038. state = MqttMsgState.SendSubscribe;
  1039. else if (msg.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE)
  1040. state = MqttMsgState.SendUnsubscribe;
  1041. // queue message context
  1042. MqttMsgContext msgContext = new MqttMsgContext()
  1043. {
  1044. Message = msg,
  1045. State = state,
  1046. Flow = flow,
  1047. Attempt = 0
  1048. };
  1049. lock (this.inflightQueue)
  1050. {
  1051. // check number of messages inside inflight queue
  1052. enqueue = (this.inflightQueue.Count < this.settings.InflightQueueSize);
  1053. if (enqueue)
  1054. {
  1055. // enqueue message and unlock send thread
  1056. this.inflightQueue.Enqueue(msgContext);
  1057. #if TRACE
  1058. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "enqueued {0}", msg);
  1059. #endif
  1060. // PUBLISH message
  1061. if (msg.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE)
  1062. {
  1063. // to publish and QoS level 1 or 2
  1064. if ((msgContext.Flow == MqttMsgFlow.ToPublish) &&
  1065. ((msg.QosLevel == MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE) ||
  1066. (msg.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE)))
  1067. {
  1068. if (this.session != null)
  1069. this.session.InflightMessages.Add(msgContext.Key, msgContext);
  1070. }
  1071. // to acknowledge and QoS level 2
  1072. else if ((msgContext.Flow == MqttMsgFlow.ToAcknowledge) &&
  1073. (msg.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE))
  1074. {
  1075. if (this.session != null)
  1076. this.session.InflightMessages.Add(msgContext.Key, msgContext);
  1077. }
  1078. }
  1079. }
  1080. }
  1081. }
  1082. this.inflightWaitHandle.Set();
  1083. return enqueue;
  1084. }
  1085. /// <summary>
  1086. /// Enqueue a message into the internal queue
  1087. /// </summary>
  1088. /// <param name="msg">Message to enqueue</param>
  1089. private void EnqueueInternal(MqttMsgBase msg)
  1090. {
  1091. // enqueue is needed (or not)
  1092. bool enqueue = true;
  1093. // if it is a PUBREL message (for QoS Level 2)
  1094. if (msg.Type == MqttMsgBase.MQTT_MSG_PUBREL_TYPE)
  1095. {
  1096. lock (this.inflightQueue)
  1097. {
  1098. // if it is a PUBREL but the corresponding PUBLISH isn't in the inflight queue,
  1099. // it means that we processed PUBLISH message and received PUBREL and we sent PUBCOMP
  1100. // but publisher didn't receive PUBCOMP so it re-sent PUBREL. We need only to re-send PUBCOMP.
  1101. // NOTE : I need to find on message id and flow because the broker could be publish/received
  1102. // to/from client and message id could be the same (one tracked by broker and the other by client)
  1103. MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToAcknowledge);
  1104. MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find);
  1105. // the PUBLISH message isn't in the inflight queue, it was already processed so
  1106. // we need to re-send PUBCOMP only
  1107. if (msgCtx == null)
  1108. {
  1109. MqttMsgPubcomp pubcomp = new MqttMsgPubcomp();
  1110. pubcomp.MessageId = msg.MessageId;
  1111. this.Send(pubcomp);
  1112. enqueue = false;
  1113. }
  1114. }
  1115. }
  1116. // if it is a PUBCOMP message (for QoS Level 2)
  1117. else if (msg.Type == MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE)
  1118. {
  1119. lock (this.inflightQueue)
  1120. {
  1121. // if it is a PUBCOMP but the corresponding PUBLISH isn't in the inflight queue,
  1122. // it means that we sent PUBLISH message, sent PUBREL (after receiving PUBREC) and already received PUBCOMP
  1123. // but publisher didn't receive PUBREL so it re-sent PUBCOMP. We need only to ignore this PUBCOMP.
  1124. // NOTE : I need to find on message id and flow because the broker could be publish/received
  1125. // to/from client and message id could be the same (one tracked by broker and the other by client)
  1126. MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToPublish);
  1127. MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find);
  1128. // the PUBLISH message isn't in the inflight queue, it was already sent so we need to ignore this PUBCOMP
  1129. if (msgCtx == null)
  1130. {
  1131. enqueue = false;
  1132. }
  1133. }
  1134. }
  1135. // if it is a PUBREC message (for QoS Level 2)
  1136. else if (msg.Type == MqttMsgBase.MQTT_MSG_PUBREC_TYPE)
  1137. {
  1138. lock (this.inflightQueue)
  1139. {
  1140. // if it is a PUBREC but the corresponding PUBLISH isn't in the inflight queue,
  1141. // it means that we sent PUBLISH message more times (retries) but broker didn't send PUBREC in time
  1142. // the publish is failed and we need only to ignore this PUBREC.
  1143. // NOTE : I need to find on message id and flow because the broker could be publish/received
  1144. // to/from client and message id could be the same (one tracked by broker and the other by client)
  1145. MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToPublish);
  1146. MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find);
  1147. // the PUBLISH message isn't in the inflight queue, it was already sent so we need to ignore this PUBREC
  1148. if (msgCtx == null)
  1149. {
  1150. enqueue = false;
  1151. }
  1152. }
  1153. }
  1154. if (enqueue)
  1155. {
  1156. lock (this.internalQueue)
  1157. {
  1158. this.internalQueue.Enqueue(msg);
  1159. #if TRACE
  1160. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "enqueued {0}", msg);
  1161. #endif
  1162. this.inflightWaitHandle.Set();
  1163. }
  1164. }
  1165. }
  1166. /// <summary>
  1167. /// Thread for receiving messages
  1168. /// </summary>
  1169. private void ReceiveThread()
  1170. {
  1171. int readBytes = 0;
  1172. byte[] fixedHeaderFirstByte = new byte[1];
  1173. byte msgType;
  1174. while (this.isRunning)
  1175. {
  1176. try
  1177. {
  1178. // read first byte (fixed header)
  1179. readBytes = this.channel.Receive(fixedHeaderFirstByte);
  1180. if (readBytes > 0)
  1181. {
  1182. #if BROKER
  1183. // update last message received ticks
  1184. this.lastCommTime = Environment.TickCount;
  1185. #endif
  1186. // extract message type from received byte
  1187. msgType = (byte)((fixedHeaderFirstByte[0] & MqttMsgBase.MSG_TYPE_MASK) >> MqttMsgBase.MSG_TYPE_OFFSET);
  1188. switch (msgType)
  1189. {
  1190. // CONNECT message received
  1191. case MqttMsgBase.MQTT_MSG_CONNECT_TYPE:
  1192. #if BROKER
  1193. MqttMsgConnect connect = MqttMsgConnect.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1194. #if TRACE
  1195. Trace.WriteLine(TraceLevel.Frame, "RECV {0}", connect);
  1196. #endif
  1197. // raise message received event
  1198. this.OnInternalEvent(new MsgInternalEvent(connect));
  1199. break;
  1200. #else
  1201. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1202. #endif
  1203. // CONNACK message received
  1204. case MqttMsgBase.MQTT_MSG_CONNACK_TYPE:
  1205. #if BROKER
  1206. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1207. #else
  1208. this.msgReceived = MqttMsgConnack.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1209. #if TRACE
  1210. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", this.msgReceived);
  1211. #endif
  1212. this.syncEndReceiving.Set();
  1213. break;
  1214. #endif
  1215. // PINGREQ message received
  1216. case MqttMsgBase.MQTT_MSG_PINGREQ_TYPE:
  1217. #if BROKER
  1218. this.msgReceived = MqttMsgPingReq.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1219. #if TRACE
  1220. Trace.WriteLine(TraceLevel.Frame, "RECV {0}", this.msgReceived);
  1221. #endif
  1222. MqttMsgPingResp pingresp = new MqttMsgPingResp();
  1223. this.Send(pingresp);
  1224. break;
  1225. #else
  1226. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1227. #endif
  1228. // PINGRESP message received
  1229. case MqttMsgBase.MQTT_MSG_PINGRESP_TYPE:
  1230. #if BROKER
  1231. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1232. #else
  1233. this.msgReceived = MqttMsgPingResp.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1234. #if TRACE
  1235. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", this.msgReceived);
  1236. #endif
  1237. this.syncEndReceiving.Set();
  1238. break;
  1239. #endif
  1240. // SUBSCRIBE message received
  1241. case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE:
  1242. #if BROKER
  1243. MqttMsgSubscribe subscribe = MqttMsgSubscribe.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1244. #if TRACE
  1245. Trace.WriteLine(TraceLevel.Frame, "RECV {0}", subscribe);
  1246. #endif
  1247. // raise message received event
  1248. this.OnInternalEvent(new MsgInternalEvent(subscribe));
  1249. break;
  1250. #else
  1251. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1252. #endif
  1253. // SUBACK message received
  1254. case MqttMsgBase.MQTT_MSG_SUBACK_TYPE:
  1255. #if BROKER
  1256. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1257. #else
  1258. // enqueue SUBACK message received (for QoS Level 1) into the internal queue
  1259. MqttMsgSuback suback = MqttMsgSuback.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1260. #if TRACE
  1261. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", suback);
  1262. #endif
  1263. // enqueue SUBACK message into the internal queue
  1264. this.EnqueueInternal(suback);
  1265. break;
  1266. #endif
  1267. // PUBLISH message received
  1268. case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE:
  1269. MqttMsgPublish publish = MqttMsgPublish.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1270. #if TRACE
  1271. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", publish);
  1272. #endif
  1273. // enqueue PUBLISH message to acknowledge into the inflight queue
  1274. this.EnqueueInflight(publish, MqttMsgFlow.ToAcknowledge);
  1275. break;
  1276. // PUBACK message received
  1277. case MqttMsgBase.MQTT_MSG_PUBACK_TYPE:
  1278. // enqueue PUBACK message received (for QoS Level 1) into the internal queue
  1279. MqttMsgPuback puback = MqttMsgPuback.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1280. #if TRACE
  1281. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", puback);
  1282. #endif
  1283. // enqueue PUBACK message into the internal queue
  1284. this.EnqueueInternal(puback);
  1285. break;
  1286. // PUBREC message received
  1287. case MqttMsgBase.MQTT_MSG_PUBREC_TYPE:
  1288. // enqueue PUBREC message received (for QoS Level 2) into the internal queue
  1289. MqttMsgPubrec pubrec = MqttMsgPubrec.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1290. #if TRACE
  1291. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", pubrec);
  1292. #endif
  1293. // enqueue PUBREC message into the internal queue
  1294. this.EnqueueInternal(pubrec);
  1295. break;
  1296. // PUBREL message received
  1297. case MqttMsgBase.MQTT_MSG_PUBREL_TYPE:
  1298. // enqueue PUBREL message received (for QoS Level 2) into the internal queue
  1299. MqttMsgPubrel pubrel = MqttMsgPubrel.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1300. #if TRACE
  1301. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", pubrel);
  1302. #endif
  1303. // enqueue PUBREL message into the internal queue
  1304. this.EnqueueInternal(pubrel);
  1305. break;
  1306. // PUBCOMP message received
  1307. case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE:
  1308. // enqueue PUBCOMP message received (for QoS Level 2) into the internal queue
  1309. MqttMsgPubcomp pubcomp = MqttMsgPubcomp.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1310. #if TRACE
  1311. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", pubcomp);
  1312. #endif
  1313. // enqueue PUBCOMP message into the internal queue
  1314. this.EnqueueInternal(pubcomp);
  1315. break;
  1316. // UNSUBSCRIBE message received
  1317. case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE:
  1318. #if BROKER
  1319. MqttMsgUnsubscribe unsubscribe = MqttMsgUnsubscribe.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1320. #if TRACE
  1321. Trace.WriteLine(TraceLevel.Frame, "RECV {0}", unsubscribe);
  1322. #endif
  1323. // raise message received event
  1324. this.OnInternalEvent(new MsgInternalEvent(unsubscribe));
  1325. break;
  1326. #else
  1327. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1328. #endif
  1329. // UNSUBACK message received
  1330. case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE:
  1331. #if BROKER
  1332. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1333. #else
  1334. // enqueue UNSUBACK message received (for QoS Level 1) into the internal queue
  1335. MqttMsgUnsuback unsuback = MqttMsgUnsuback.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1336. #if TRACE
  1337. MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", unsuback);
  1338. #endif
  1339. // enqueue UNSUBACK message into the internal queue
  1340. this.EnqueueInternal(unsuback);
  1341. break;
  1342. #endif
  1343. // DISCONNECT message received
  1344. case MqttMsgDisconnect.MQTT_MSG_DISCONNECT_TYPE:
  1345. #if BROKER
  1346. MqttMsgDisconnect disconnect = MqttMsgDisconnect.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel);
  1347. #if TRACE
  1348. Trace.WriteLine(TraceLevel.Frame, "RECV {0}", disconnect);
  1349. #endif
  1350. // raise message received event
  1351. this.OnInternalEvent(new MsgInternalEvent(disconnect));
  1352. break;
  1353. #else
  1354. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1355. #endif
  1356. default:
  1357. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1358. }
  1359. this.exReceiving = null;
  1360. }
  1361. // zero bytes read, peer gracefully closed socket
  1362. else
  1363. {
  1364. // wake up thread that will notify connection is closing
  1365. this.OnConnectionClosing();
  1366. }
  1367. }
  1368. catch (Exception e)
  1369. {
  1370. #if TRACE
  1371. MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString());
  1372. #endif
  1373. this.exReceiving = new MqttCommunicationException(e);
  1374. bool close = false;
  1375. if (e.GetType() == typeof(MqttClientException))
  1376. {
  1377. // [v3.1.1] scenarios the receiver MUST close the network connection
  1378. MqttClientException ex = e as MqttClientException;
  1379. close = ((ex.ErrorCode == MqttClientErrorCode.InvalidFlagBits) ||
  1380. (ex.ErrorCode == MqttClientErrorCode.InvalidProtocolName) ||
  1381. (ex.ErrorCode == MqttClientErrorCode.InvalidConnectFlags));
  1382. }
  1383. #if !(WINDOWS_APP || WINDOWS_PHONE_APP)
  1384. else if ((e.GetType() == typeof(IOException)) || (e.GetType() == typeof(SocketException)) ||
  1385. ((e.InnerException != null) && (e.InnerException.GetType() == typeof(SocketException)))) // added for SSL/TLS incoming connection that use SslStream that wraps SocketException
  1386. {
  1387. close = true;
  1388. }
  1389. #endif
  1390. if (close)
  1391. {
  1392. // wake up thread that will notify connection is closing
  1393. this.OnConnectionClosing();
  1394. }
  1395. }
  1396. }
  1397. }
  1398. /// <summary>
  1399. /// Thread for handling keep alive message
  1400. /// </summary>
  1401. private void KeepAliveThread()
  1402. {
  1403. int delta = 0;
  1404. int wait = this.keepAlivePeriod;
  1405. // create event to signal that current thread is end
  1406. this.keepAliveEventEnd = new AutoResetEvent(false);
  1407. while (this.isRunning)
  1408. {
  1409. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  1410. // waiting...
  1411. this.keepAliveEvent.WaitOne(wait, false);
  1412. #else
  1413. // waiting...
  1414. this.keepAliveEvent.WaitOne(wait);
  1415. #endif
  1416. if (this.isRunning)
  1417. {
  1418. delta = Environment.TickCount - this.lastCommTime;
  1419. // if timeout exceeded ...
  1420. if (delta >= this.keepAlivePeriod)
  1421. {
  1422. #if BROKER
  1423. // client must close connection
  1424. this.OnConnectionClosing();
  1425. #else
  1426. // ... send keep alive
  1427. this.Ping();
  1428. wait = this.keepAlivePeriod;
  1429. #endif
  1430. }
  1431. else
  1432. {
  1433. // update waiting time
  1434. wait = this.keepAlivePeriod - delta;
  1435. }
  1436. }
  1437. }
  1438. // signal thread end
  1439. this.keepAliveEventEnd.Set();
  1440. }
  1441. /// <summary>
  1442. /// Thread for raising event
  1443. /// </summary>
  1444. private void DispatchEventThread()
  1445. {
  1446. while (this.isRunning)
  1447. {
  1448. #if BROKER
  1449. if ((this.eventQueue.Count == 0) && !this.isConnectionClosing)
  1450. {
  1451. // broker need to receive the first message (CONNECT)
  1452. // within a reasonable amount of time after TCP/IP connection
  1453. if (!this.IsConnected)
  1454. {
  1455. // wait on receiving message from client with a connection timeout
  1456. if (!this.receiveEventWaitHandle.WaitOne(this.settings.TimeoutOnConnection))
  1457. {
  1458. // client must close connection
  1459. this.Close();
  1460. // client raw disconnection
  1461. this.OnConnectionClosed();
  1462. }
  1463. }
  1464. else
  1465. {
  1466. // wait on receiving message from client
  1467. this.receiveEventWaitHandle.WaitOne();
  1468. }
  1469. }
  1470. #else
  1471. if ((this.eventQueue.Count == 0) && !this.isConnectionClosing)
  1472. // wait on receiving message from client
  1473. this.receiveEventWaitHandle.WaitOne();
  1474. #endif
  1475. // check if it is running or we are closing client
  1476. if (this.isRunning)
  1477. {
  1478. // get event from queue
  1479. InternalEvent internalEvent = null;
  1480. lock (this.eventQueue)
  1481. {
  1482. if (this.eventQueue.Count > 0)
  1483. internalEvent = (InternalEvent)this.eventQueue.Dequeue();
  1484. }
  1485. // it's an event with a message inside
  1486. if (internalEvent != null)
  1487. {
  1488. MqttMsgBase msg = ((MsgInternalEvent)internalEvent).Message;
  1489. if (msg != null)
  1490. {
  1491. switch (msg.Type)
  1492. {
  1493. // CONNECT message received
  1494. case MqttMsgBase.MQTT_MSG_CONNECT_TYPE:
  1495. #if BROKER
  1496. // raise connected client event (CONNECT message received)
  1497. this.OnMqttMsgConnected((MqttMsgConnect)msg);
  1498. break;
  1499. #else
  1500. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1501. #endif
  1502. // SUBSCRIBE message received
  1503. case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE:
  1504. #if BROKER
  1505. MqttMsgSubscribe subscribe = (MqttMsgSubscribe)msg;
  1506. // raise subscribe topic event (SUBSCRIBE message received)
  1507. this.OnMqttMsgSubscribeReceived(subscribe.MessageId, subscribe.Topics, subscribe.QoSLevels);
  1508. break;
  1509. #else
  1510. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1511. #endif
  1512. // SUBACK message received
  1513. case MqttMsgBase.MQTT_MSG_SUBACK_TYPE:
  1514. // raise subscribed topic event (SUBACK message received)
  1515. this.OnMqttMsgSubscribed((MqttMsgSuback)msg);
  1516. break;
  1517. // PUBLISH message received
  1518. case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE:
  1519. // PUBLISH message received in a published internal event, no publish succeeded
  1520. if (internalEvent.GetType() == typeof(MsgPublishedInternalEvent))
  1521. this.OnMqttMsgPublished(msg.MessageId, false);
  1522. else
  1523. // raise PUBLISH message received event
  1524. this.OnMqttMsgPublishReceived((MqttMsgPublish)msg);
  1525. break;
  1526. // PUBACK message received
  1527. case MqttMsgBase.MQTT_MSG_PUBACK_TYPE:
  1528. // raise published message event
  1529. // (PUBACK received for QoS Level 1)
  1530. this.OnMqttMsgPublished(msg.MessageId, true);
  1531. break;
  1532. // PUBREL message received
  1533. case MqttMsgBase.MQTT_MSG_PUBREL_TYPE:
  1534. // raise message received event
  1535. // (PUBREL received for QoS Level 2)
  1536. this.OnMqttMsgPublishReceived((MqttMsgPublish)msg);
  1537. break;
  1538. // PUBCOMP message received
  1539. case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE:
  1540. // raise published message event
  1541. // (PUBCOMP received for QoS Level 2)
  1542. this.OnMqttMsgPublished(msg.MessageId, true);
  1543. break;
  1544. // UNSUBSCRIBE message received from client
  1545. case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE:
  1546. #if BROKER
  1547. MqttMsgUnsubscribe unsubscribe = (MqttMsgUnsubscribe)msg;
  1548. // raise unsubscribe topic event (UNSUBSCRIBE message received)
  1549. this.OnMqttMsgUnsubscribeReceived(unsubscribe.MessageId, unsubscribe.Topics);
  1550. break;
  1551. #else
  1552. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1553. #endif
  1554. // UNSUBACK message received
  1555. case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE:
  1556. // raise unsubscribed topic event
  1557. this.OnMqttMsgUnsubscribed(msg.MessageId);
  1558. break;
  1559. // DISCONNECT message received from client
  1560. case MqttMsgDisconnect.MQTT_MSG_DISCONNECT_TYPE:
  1561. #if BROKER
  1562. // raise disconnected client event (DISCONNECT message received)
  1563. this.OnMqttMsgDisconnected();
  1564. break;
  1565. #else
  1566. throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
  1567. #endif
  1568. }
  1569. }
  1570. }
  1571. // all events for received messages dispatched, check if there is closing connection
  1572. if ((this.eventQueue.Count == 0) && this.isConnectionClosing)
  1573. {
  1574. // client must close connection
  1575. this.Close();
  1576. // client raw disconnection
  1577. this.OnConnectionClosed();
  1578. }
  1579. }
  1580. }
  1581. }
  1582. /// <summary>
  1583. /// Process inflight messages queue
  1584. /// </summary>
  1585. private void ProcessInflightThread()
  1586. {
  1587. MqttMsgContext msgContext = null;
  1588. MqttMsgBase msgInflight = null;
  1589. MqttMsgBase msgReceived = null;
  1590. InternalEvent internalEvent = null;
  1591. bool acknowledge = false;
  1592. int timeout = Timeout.Infinite;
  1593. int delta;
  1594. bool msgReceivedProcessed = false;
  1595. try
  1596. {
  1597. while (this.isRunning)
  1598. {
  1599. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  1600. // wait on message queueud to inflight
  1601. this.inflightWaitHandle.WaitOne(timeout, false);
  1602. #else
  1603. // wait on message queueud to inflight
  1604. this.inflightWaitHandle.WaitOne(timeout);
  1605. #endif
  1606. // it could be unblocked because Close() method is joining
  1607. if (this.isRunning)
  1608. {
  1609. lock (this.inflightQueue)
  1610. {
  1611. // message received and peeked from internal queue is processed
  1612. // NOTE : it has the corresponding message in inflight queue based on messageId
  1613. // (ex. a PUBREC for a PUBLISH, a SUBACK for a SUBSCRIBE, ...)
  1614. // if it's orphan we need to remove from internal queue
  1615. msgReceivedProcessed = false;
  1616. acknowledge = false;
  1617. msgReceived = null;
  1618. // set timeout tu MaxValue instead of Infinte (-1) to perform
  1619. // compare with calcultad current msgTimeout
  1620. timeout = Int32.MaxValue;
  1621. // a message inflight could be re-enqueued but we have to
  1622. // analyze it only just one time for cycle
  1623. int count = this.inflightQueue.Count;
  1624. // process all inflight queued messages
  1625. while (count > 0)
  1626. {
  1627. count--;
  1628. acknowledge = false;
  1629. msgReceived = null;
  1630. // check to be sure that client isn't closing and all queues are now empty !
  1631. if (!this.isRunning)
  1632. break;
  1633. // dequeue message context from queue
  1634. msgContext = (MqttMsgContext)this.inflightQueue.Dequeue();
  1635. // get inflight message
  1636. msgInflight = (MqttMsgBase)msgContext.Message;
  1637. switch (msgContext.State)
  1638. {
  1639. case MqttMsgState.QueuedQos0:
  1640. // QoS 0, PUBLISH message to send to broker, no state change, no acknowledge
  1641. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  1642. {
  1643. this.Send(msgInflight);
  1644. }
  1645. // QoS 0, no need acknowledge
  1646. else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge)
  1647. {
  1648. internalEvent = new MsgInternalEvent(msgInflight);
  1649. // notify published message from broker (no need acknowledged)
  1650. this.OnInternalEvent(internalEvent);
  1651. }
  1652. #if TRACE
  1653. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight);
  1654. #endif
  1655. break;
  1656. case MqttMsgState.QueuedQos1:
  1657. // [v3.1.1] SUBSCRIBE and UNSIBSCRIBE aren't "officially" QOS = 1
  1658. case MqttMsgState.SendSubscribe:
  1659. case MqttMsgState.SendUnsubscribe:
  1660. // QoS 1, PUBLISH or SUBSCRIBE/UNSUBSCRIBE message to send to broker, state change to wait PUBACK or SUBACK/UNSUBACK
  1661. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  1662. {
  1663. msgContext.Timestamp = Environment.TickCount;
  1664. msgContext.Attempt++;
  1665. if (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE)
  1666. {
  1667. // PUBLISH message to send, wait for PUBACK
  1668. msgContext.State = MqttMsgState.WaitForPuback;
  1669. // retry ? set dup flag [v3.1.1] only for PUBLISH message
  1670. if (msgContext.Attempt > 1)
  1671. msgInflight.DupFlag = true;
  1672. }
  1673. else if (msgInflight.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE)
  1674. // SUBSCRIBE message to send, wait for SUBACK
  1675. msgContext.State = MqttMsgState.WaitForSuback;
  1676. else if (msgInflight.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE)
  1677. // UNSUBSCRIBE message to send, wait for UNSUBACK
  1678. msgContext.State = MqttMsgState.WaitForUnsuback;
  1679. this.Send(msgInflight);
  1680. // update timeout : minimum between delay (based on current message sent) or current timeout
  1681. timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout;
  1682. // re-enqueue message (I have to re-analyze for receiving PUBACK, SUBACK or UNSUBACK)
  1683. this.inflightQueue.Enqueue(msgContext);
  1684. }
  1685. // QoS 1, PUBLISH message received from broker to acknowledge, send PUBACK
  1686. else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge)
  1687. {
  1688. MqttMsgPuback puback = new MqttMsgPuback();
  1689. puback.MessageId = msgInflight.MessageId;
  1690. this.Send(puback);
  1691. internalEvent = new MsgInternalEvent(msgInflight);
  1692. // notify published message from broker and acknowledged
  1693. this.OnInternalEvent(internalEvent);
  1694. #if TRACE
  1695. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight);
  1696. #endif
  1697. }
  1698. break;
  1699. case MqttMsgState.QueuedQos2:
  1700. // QoS 2, PUBLISH message to send to broker, state change to wait PUBREC
  1701. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  1702. {
  1703. msgContext.Timestamp = Environment.TickCount;
  1704. msgContext.Attempt++;
  1705. msgContext.State = MqttMsgState.WaitForPubrec;
  1706. // retry ? set dup flag
  1707. if (msgContext.Attempt > 1)
  1708. msgInflight.DupFlag = true;
  1709. this.Send(msgInflight);
  1710. // update timeout : minimum between delay (based on current message sent) or current timeout
  1711. timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout;
  1712. // re-enqueue message (I have to re-analyze for receiving PUBREC)
  1713. this.inflightQueue.Enqueue(msgContext);
  1714. }
  1715. // QoS 2, PUBLISH message received from broker to acknowledge, send PUBREC, state change to wait PUBREL
  1716. else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge)
  1717. {
  1718. MqttMsgPubrec pubrec = new MqttMsgPubrec();
  1719. pubrec.MessageId = msgInflight.MessageId;
  1720. msgContext.State = MqttMsgState.WaitForPubrel;
  1721. this.Send(pubrec);
  1722. // re-enqueue message (I have to re-analyze for receiving PUBREL)
  1723. this.inflightQueue.Enqueue(msgContext);
  1724. }
  1725. break;
  1726. case MqttMsgState.WaitForPuback:
  1727. case MqttMsgState.WaitForSuback:
  1728. case MqttMsgState.WaitForUnsuback:
  1729. // QoS 1, waiting for PUBACK of a PUBLISH message sent or
  1730. // waiting for SUBACK of a SUBSCRIBE message sent or
  1731. // waiting for UNSUBACK of a UNSUBSCRIBE message sent or
  1732. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  1733. {
  1734. acknowledge = false;
  1735. lock (this.internalQueue)
  1736. {
  1737. if (this.internalQueue.Count > 0)
  1738. msgReceived = (MqttMsgBase)this.internalQueue.Peek();
  1739. }
  1740. // it is a PUBACK message or a SUBACK/UNSUBACK message
  1741. if (msgReceived != null)
  1742. {
  1743. // PUBACK message or SUBACK/UNSUBACK message for the current message
  1744. if (((msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBACK_TYPE) && (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && (msgReceived.MessageId == msgInflight.MessageId)) ||
  1745. ((msgReceived.Type == MqttMsgBase.MQTT_MSG_SUBACK_TYPE) && (msgInflight.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE) && (msgReceived.MessageId == msgInflight.MessageId)) ||
  1746. ((msgReceived.Type == MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE) && (msgInflight.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE) && (msgReceived.MessageId == msgInflight.MessageId)))
  1747. {
  1748. lock (this.internalQueue)
  1749. {
  1750. // received message processed
  1751. this.internalQueue.Dequeue();
  1752. acknowledge = true;
  1753. msgReceivedProcessed = true;
  1754. #if TRACE
  1755. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived);
  1756. #endif
  1757. }
  1758. // if PUBACK received, confirm published with flag
  1759. if (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBACK_TYPE)
  1760. internalEvent = new MsgPublishedInternalEvent(msgReceived, true);
  1761. else
  1762. internalEvent = new MsgInternalEvent(msgReceived);
  1763. // notify received acknowledge from broker of a published message or subscribe/unsubscribe message
  1764. this.OnInternalEvent(internalEvent);
  1765. // PUBACK received for PUBLISH message with QoS Level 1, remove from session state
  1766. if ((msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) &&
  1767. (this.session != null) &&
  1768. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  1769. (this.session.InflightMessages.Contains(msgContext.Key)))
  1770. #else
  1771. (this.session.InflightMessages.ContainsKey(msgContext.Key)))
  1772. #endif
  1773. {
  1774. this.session.InflightMessages.Remove(msgContext.Key);
  1775. }
  1776. #if TRACE
  1777. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight);
  1778. #endif
  1779. }
  1780. }
  1781. // current message not acknowledged, no PUBACK or SUBACK/UNSUBACK or not equal messageid
  1782. if (!acknowledge)
  1783. {
  1784. delta = Environment.TickCount - msgContext.Timestamp;
  1785. // check timeout for receiving PUBACK since PUBLISH was sent or
  1786. // for receiving SUBACK since SUBSCRIBE was sent or
  1787. // for receiving UNSUBACK since UNSUBSCRIBE was sent
  1788. if (delta >= this.settings.DelayOnRetry)
  1789. {
  1790. // max retry not reached, resend
  1791. if (msgContext.Attempt < this.settings.AttemptsOnRetry)
  1792. {
  1793. msgContext.State = MqttMsgState.QueuedQos1;
  1794. // re-enqueue message
  1795. this.inflightQueue.Enqueue(msgContext);
  1796. // update timeout (0 -> reanalyze queue immediately)
  1797. timeout = 0;
  1798. }
  1799. else
  1800. {
  1801. // if PUBACK for a PUBLISH message not received after retries, raise event for not published
  1802. if (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE)
  1803. {
  1804. // PUBACK not received in time, PUBLISH retries failed, need to remove from session inflight messages too
  1805. if ((this.session != null) &&
  1806. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  1807. (this.session.InflightMessages.Contains(msgContext.Key)))
  1808. #else
  1809. (this.session.InflightMessages.ContainsKey(msgContext.Key)))
  1810. #endif
  1811. {
  1812. this.session.InflightMessages.Remove(msgContext.Key);
  1813. }
  1814. internalEvent = new MsgPublishedInternalEvent(msgInflight, false);
  1815. // notify not received acknowledge from broker and message not published
  1816. this.OnInternalEvent(internalEvent);
  1817. }
  1818. // NOTE : not raise events for SUBACK or UNSUBACK not received
  1819. // for the user no event raised means subscribe/unsubscribe failed
  1820. }
  1821. }
  1822. else
  1823. {
  1824. // re-enqueue message (I have to re-analyze for receiving PUBACK, SUBACK or UNSUBACK)
  1825. this.inflightQueue.Enqueue(msgContext);
  1826. // update timeout
  1827. int msgTimeout = (this.settings.DelayOnRetry - delta);
  1828. timeout = (msgTimeout < timeout) ? msgTimeout : timeout;
  1829. }
  1830. }
  1831. }
  1832. break;
  1833. case MqttMsgState.WaitForPubrec:
  1834. // QoS 2, waiting for PUBREC of a PUBLISH message sent
  1835. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  1836. {
  1837. acknowledge = false;
  1838. lock (this.internalQueue)
  1839. {
  1840. if (this.internalQueue.Count > 0)
  1841. msgReceived = (MqttMsgBase)this.internalQueue.Peek();
  1842. }
  1843. // it is a PUBREC message
  1844. if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREC_TYPE))
  1845. {
  1846. // PUBREC message for the current PUBLISH message, send PUBREL, wait for PUBCOMP
  1847. if (msgReceived.MessageId == msgInflight.MessageId)
  1848. {
  1849. lock (this.internalQueue)
  1850. {
  1851. // received message processed
  1852. this.internalQueue.Dequeue();
  1853. acknowledge = true;
  1854. msgReceivedProcessed = true;
  1855. #if TRACE
  1856. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived);
  1857. #endif
  1858. }
  1859. MqttMsgPubrel pubrel = new MqttMsgPubrel();
  1860. pubrel.MessageId = msgInflight.MessageId;
  1861. msgContext.State = MqttMsgState.WaitForPubcomp;
  1862. msgContext.Timestamp = Environment.TickCount;
  1863. msgContext.Attempt = 1;
  1864. this.Send(pubrel);
  1865. // update timeout : minimum between delay (based on current message sent) or current timeout
  1866. timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout;
  1867. // re-enqueue message
  1868. this.inflightQueue.Enqueue(msgContext);
  1869. }
  1870. }
  1871. // current message not acknowledged
  1872. if (!acknowledge)
  1873. {
  1874. delta = Environment.TickCount - msgContext.Timestamp;
  1875. // check timeout for receiving PUBREC since PUBLISH was sent
  1876. if (delta >= this.settings.DelayOnRetry)
  1877. {
  1878. // max retry not reached, resend
  1879. if (msgContext.Attempt < this.settings.AttemptsOnRetry)
  1880. {
  1881. msgContext.State = MqttMsgState.QueuedQos2;
  1882. // re-enqueue message
  1883. this.inflightQueue.Enqueue(msgContext);
  1884. // update timeout (0 -> reanalyze queue immediately)
  1885. timeout = 0;
  1886. }
  1887. else
  1888. {
  1889. // PUBREC not received in time, PUBLISH retries failed, need to remove from session inflight messages too
  1890. if ((this.session != null) &&
  1891. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  1892. (this.session.InflightMessages.Contains(msgContext.Key)))
  1893. #else
  1894. (this.session.InflightMessages.ContainsKey(msgContext.Key)))
  1895. #endif
  1896. {
  1897. this.session.InflightMessages.Remove(msgContext.Key);
  1898. }
  1899. // if PUBREC for a PUBLISH message not received after retries, raise event for not published
  1900. internalEvent = new MsgPublishedInternalEvent(msgInflight, false);
  1901. // notify not received acknowledge from broker and message not published
  1902. this.OnInternalEvent(internalEvent);
  1903. }
  1904. }
  1905. else
  1906. {
  1907. // re-enqueue message
  1908. this.inflightQueue.Enqueue(msgContext);
  1909. // update timeout
  1910. int msgTimeout = (this.settings.DelayOnRetry - delta);
  1911. timeout = (msgTimeout < timeout) ? msgTimeout : timeout;
  1912. }
  1913. }
  1914. }
  1915. break;
  1916. case MqttMsgState.WaitForPubrel:
  1917. // QoS 2, waiting for PUBREL of a PUBREC message sent
  1918. if (msgContext.Flow == MqttMsgFlow.ToAcknowledge)
  1919. {
  1920. lock (this.internalQueue)
  1921. {
  1922. if (this.internalQueue.Count > 0)
  1923. msgReceived = (MqttMsgBase)this.internalQueue.Peek();
  1924. }
  1925. // it is a PUBREL message
  1926. if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREL_TYPE))
  1927. {
  1928. // PUBREL message for the current message, send PUBCOMP
  1929. if (msgReceived.MessageId == msgInflight.MessageId)
  1930. {
  1931. lock (this.internalQueue)
  1932. {
  1933. // received message processed
  1934. this.internalQueue.Dequeue();
  1935. msgReceivedProcessed = true;
  1936. #if TRACE
  1937. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived);
  1938. #endif
  1939. }
  1940. MqttMsgPubcomp pubcomp = new MqttMsgPubcomp();
  1941. pubcomp.MessageId = msgInflight.MessageId;
  1942. this.Send(pubcomp);
  1943. internalEvent = new MsgInternalEvent(msgInflight);
  1944. // notify published message from broker and acknowledged
  1945. this.OnInternalEvent(internalEvent);
  1946. // PUBREL received (and PUBCOMP sent) for PUBLISH message with QoS Level 2, remove from session state
  1947. if ((msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) &&
  1948. (this.session != null) &&
  1949. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  1950. (this.session.InflightMessages.Contains(msgContext.Key)))
  1951. #else
  1952. (this.session.InflightMessages.ContainsKey(msgContext.Key)))
  1953. #endif
  1954. {
  1955. this.session.InflightMessages.Remove(msgContext.Key);
  1956. }
  1957. #if TRACE
  1958. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight);
  1959. #endif
  1960. }
  1961. else
  1962. {
  1963. // re-enqueue message
  1964. this.inflightQueue.Enqueue(msgContext);
  1965. }
  1966. }
  1967. else
  1968. {
  1969. // re-enqueue message
  1970. this.inflightQueue.Enqueue(msgContext);
  1971. }
  1972. }
  1973. break;
  1974. case MqttMsgState.WaitForPubcomp:
  1975. // QoS 2, waiting for PUBCOMP of a PUBREL message sent
  1976. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  1977. {
  1978. acknowledge = false;
  1979. lock (this.internalQueue)
  1980. {
  1981. if (this.internalQueue.Count > 0)
  1982. msgReceived = (MqttMsgBase)this.internalQueue.Peek();
  1983. }
  1984. // it is a PUBCOMP message
  1985. if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE))
  1986. {
  1987. // PUBCOMP message for the current message
  1988. if (msgReceived.MessageId == msgInflight.MessageId)
  1989. {
  1990. lock (this.internalQueue)
  1991. {
  1992. // received message processed
  1993. this.internalQueue.Dequeue();
  1994. acknowledge = true;
  1995. msgReceivedProcessed = true;
  1996. #if TRACE
  1997. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived);
  1998. #endif
  1999. }
  2000. internalEvent = new MsgPublishedInternalEvent(msgReceived, true);
  2001. // notify received acknowledge from broker of a published message
  2002. this.OnInternalEvent(internalEvent);
  2003. // PUBCOMP received for PUBLISH message with QoS Level 2, remove from session state
  2004. if ((msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) &&
  2005. (this.session != null) &&
  2006. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  2007. (this.session.InflightMessages.Contains(msgContext.Key)))
  2008. #else
  2009. (this.session.InflightMessages.ContainsKey(msgContext.Key)))
  2010. #endif
  2011. {
  2012. this.session.InflightMessages.Remove(msgContext.Key);
  2013. }
  2014. #if TRACE
  2015. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight);
  2016. #endif
  2017. }
  2018. }
  2019. // it is a PUBREC message
  2020. else if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREC_TYPE))
  2021. {
  2022. // another PUBREC message for the current message due to a retransmitted PUBLISH
  2023. // I'm in waiting for PUBCOMP, so I can discard this PUBREC
  2024. if (msgReceived.MessageId == msgInflight.MessageId)
  2025. {
  2026. lock (this.internalQueue)
  2027. {
  2028. // received message processed
  2029. this.internalQueue.Dequeue();
  2030. acknowledge = true;
  2031. msgReceivedProcessed = true;
  2032. #if TRACE
  2033. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived);
  2034. #endif
  2035. // re-enqueue message
  2036. this.inflightQueue.Enqueue(msgContext);
  2037. }
  2038. }
  2039. }
  2040. // current message not acknowledged
  2041. if (!acknowledge)
  2042. {
  2043. delta = Environment.TickCount - msgContext.Timestamp;
  2044. // check timeout for receiving PUBCOMP since PUBREL was sent
  2045. if (delta >= this.settings.DelayOnRetry)
  2046. {
  2047. // max retry not reached, resend
  2048. if (msgContext.Attempt < this.settings.AttemptsOnRetry)
  2049. {
  2050. msgContext.State = MqttMsgState.SendPubrel;
  2051. // re-enqueue message
  2052. this.inflightQueue.Enqueue(msgContext);
  2053. // update timeout (0 -> reanalyze queue immediately)
  2054. timeout = 0;
  2055. }
  2056. else
  2057. {
  2058. // PUBCOMP not received, PUBREL retries failed, need to remove from session inflight messages too
  2059. if ((this.session != null) &&
  2060. #if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
  2061. (this.session.InflightMessages.Contains(msgContext.Key)))
  2062. #else
  2063. (this.session.InflightMessages.ContainsKey(msgContext.Key)))
  2064. #endif
  2065. {
  2066. this.session.InflightMessages.Remove(msgContext.Key);
  2067. }
  2068. // if PUBCOMP for a PUBLISH message not received after retries, raise event for not published
  2069. internalEvent = new MsgPublishedInternalEvent(msgInflight, false);
  2070. // notify not received acknowledge from broker and message not published
  2071. this.OnInternalEvent(internalEvent);
  2072. }
  2073. }
  2074. else
  2075. {
  2076. // re-enqueue message
  2077. this.inflightQueue.Enqueue(msgContext);
  2078. // update timeout
  2079. int msgTimeout = (this.settings.DelayOnRetry - delta);
  2080. timeout = (msgTimeout < timeout) ? msgTimeout : timeout;
  2081. }
  2082. }
  2083. }
  2084. break;
  2085. case MqttMsgState.SendPubrec:
  2086. // TODO : impossible ? --> QueuedQos2 ToAcknowledge
  2087. break;
  2088. case MqttMsgState.SendPubrel:
  2089. // QoS 2, PUBREL message to send to broker, state change to wait PUBCOMP
  2090. if (msgContext.Flow == MqttMsgFlow.ToPublish)
  2091. {
  2092. MqttMsgPubrel pubrel = new MqttMsgPubrel();
  2093. pubrel.MessageId = msgInflight.MessageId;
  2094. msgContext.State = MqttMsgState.WaitForPubcomp;
  2095. msgContext.Timestamp = Environment.TickCount;
  2096. msgContext.Attempt++;
  2097. // retry ? set dup flag [v3.1.1] no needed
  2098. if (this.ProtocolVersion == MqttProtocolVersion.Version_3_1)
  2099. {
  2100. if (msgContext.Attempt > 1)
  2101. pubrel.DupFlag = true;
  2102. }
  2103. this.Send(pubrel);
  2104. // update timeout : minimum between delay (based on current message sent) or current timeout
  2105. timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout;
  2106. // re-enqueue message
  2107. this.inflightQueue.Enqueue(msgContext);
  2108. }
  2109. break;
  2110. case MqttMsgState.SendPubcomp:
  2111. // TODO : impossible ?
  2112. break;
  2113. case MqttMsgState.SendPuback:
  2114. // TODO : impossible ? --> QueuedQos1 ToAcknowledge
  2115. break;
  2116. default:
  2117. break;
  2118. }
  2119. }
  2120. // if calculated timeout is MaxValue, it means that must be Infinite (-1)
  2121. if (timeout == Int32.MaxValue)
  2122. timeout = Timeout.Infinite;
  2123. // if message received is orphan, no corresponding message in inflight queue
  2124. // based on messageId, we need to remove from the queue
  2125. if ((msgReceived != null) && !msgReceivedProcessed)
  2126. {
  2127. this.internalQueue.Dequeue();
  2128. #if TRACE
  2129. MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0} orphan", msgReceived);
  2130. #endif
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. catch (MqttCommunicationException e)
  2137. {
  2138. // possible exception on Send, I need to re-enqueue not sent message
  2139. if (msgContext != null)
  2140. // re-enqueue message
  2141. this.inflightQueue.Enqueue(msgContext);
  2142. #if TRACE
  2143. MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString());
  2144. #endif
  2145. // raise disconnection client event
  2146. this.OnConnectionClosing();
  2147. }
  2148. }
  2149. /// <summary>
  2150. /// Restore session
  2151. /// </summary>
  2152. private void RestoreSession()
  2153. {
  2154. // if not clean session
  2155. if (!this.CleanSession)
  2156. {
  2157. // there is a previous session
  2158. if (this.session != null)
  2159. {
  2160. lock (this.inflightQueue)
  2161. {
  2162. foreach (MqttMsgContext msgContext in this.session.InflightMessages.Values)
  2163. {
  2164. this.inflightQueue.Enqueue(msgContext);
  2165. // if it is a PUBLISH message to publish
  2166. if ((msgContext.Message.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) &&
  2167. (msgContext.Flow == MqttMsgFlow.ToPublish))
  2168. {
  2169. // it's QoS 1 and we haven't received PUBACK
  2170. if ((msgContext.Message.QosLevel == MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE) &&
  2171. (msgContext.State == MqttMsgState.WaitForPuback))
  2172. {
  2173. // we haven't received PUBACK, we need to resend PUBLISH message
  2174. msgContext.State = MqttMsgState.QueuedQos1;
  2175. }
  2176. // it's QoS 2
  2177. else if (msgContext.Message.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE)
  2178. {
  2179. // we haven't received PUBREC, we need to resend PUBLISH message
  2180. if (msgContext.State == MqttMsgState.WaitForPubrec)
  2181. {
  2182. msgContext.State = MqttMsgState.QueuedQos2;
  2183. }
  2184. // we haven't received PUBCOMP, we need to resend PUBREL for it
  2185. else if (msgContext.State == MqttMsgState.WaitForPubcomp)
  2186. {
  2187. msgContext.State = MqttMsgState.SendPubrel;
  2188. }
  2189. }
  2190. }
  2191. }
  2192. }
  2193. // unlock process inflight queue
  2194. this.inflightWaitHandle.Set();
  2195. }
  2196. else
  2197. {
  2198. // create new session
  2199. this.session = new MqttClientSession(this.ClientId);
  2200. }
  2201. }
  2202. // clean any previous session
  2203. else
  2204. {
  2205. if (this.session != null)
  2206. this.session.Clear();
  2207. }
  2208. }
  2209. #if BROKER
  2210. /// <summary>
  2211. /// Load a given session
  2212. /// </summary>
  2213. /// <param name="session">MQTT Client session to load</param>
  2214. public void LoadSession(MqttClientSession session)
  2215. {
  2216. // if not clean session
  2217. if (!this.CleanSession)
  2218. {
  2219. // set the session ...
  2220. this.session = session;
  2221. // ... and restore it
  2222. this.RestoreSession();
  2223. }
  2224. }
  2225. #endif
  2226. /// <summary>
  2227. /// Generate the next message identifier
  2228. /// </summary>
  2229. /// <returns>Message identifier</returns>
  2230. private ushort GetMessageId()
  2231. {
  2232. // if 0 or max UInt16, it becomes 1 (first valid messageId)
  2233. this.messageIdCounter = ((this.messageIdCounter % UInt16.MaxValue) != 0) ? (ushort)(this.messageIdCounter + 1) : (ushort)1;
  2234. return this.messageIdCounter;
  2235. }
  2236. /// <summary>
  2237. /// Finder class for PUBLISH message inside a queue
  2238. /// </summary>
  2239. internal class MqttMsgContextFinder
  2240. {
  2241. // PUBLISH message id
  2242. internal ushort MessageId { get; set; }
  2243. // message flow into inflight queue
  2244. internal MqttMsgFlow Flow { get; set; }
  2245. /// <summary>
  2246. /// Constructor
  2247. /// </summary>
  2248. /// <param name="messageId">Message Id</param>
  2249. /// <param name="flow">Message flow inside inflight queue</param>
  2250. internal MqttMsgContextFinder(ushort messageId, MqttMsgFlow flow)
  2251. {
  2252. this.MessageId = messageId;
  2253. this.Flow = flow;
  2254. }
  2255. internal bool Find(object item)
  2256. {
  2257. MqttMsgContext msgCtx = (MqttMsgContext)item;
  2258. return ((msgCtx.Message.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) &&
  2259. (msgCtx.Message.MessageId == this.MessageId) &&
  2260. msgCtx.Flow == this.Flow);
  2261. }
  2262. }
  2263. }
  2264. /// <summary>
  2265. /// MQTT protocol version
  2266. /// </summary>
  2267. public enum MqttProtocolVersion
  2268. {
  2269. Version_3_1 = MqttMsgConnect.PROTOCOL_VERSION_V3_1,
  2270. Version_3_1_1 = MqttMsgConnect.PROTOCOL_VERSION_V3_1_1
  2271. }
  2272. }