client.py 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877
  1. # Copyright (c) 2012-2019 Roger Light and others
  2. #
  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. #
  7. # The Eclipse Public License is available at
  8. # http://www.eclipse.org/legal/epl-v10.html
  9. # and the Eclipse Distribution License is available at
  10. # http://www.eclipse.org/org/documents/edl-v10.php.
  11. #
  12. # Contributors:
  13. # Roger Light - initial API and implementation
  14. # Ian Craggs - MQTT V5 support
  15. from .subscribeoptions import SubscribeOptions
  16. from .reasoncodes import ReasonCodes
  17. from .properties import Properties
  18. from .matcher import MQTTMatcher
  19. import logging
  20. import hashlib
  21. import string
  22. import base64
  23. import uuid
  24. import time
  25. import threading
  26. import sys
  27. import struct
  28. """
  29. This is an MQTT client module. MQTT is a lightweight pub/sub messaging
  30. protocol that is easy to implement and suitable for low powered devices.
  31. """
  32. import collections
  33. import errno
  34. import os
  35. import platform
  36. import select
  37. import socket
  38. ssl = None
  39. try:
  40. import ssl
  41. except ImportError:
  42. pass
  43. socks = None
  44. try:
  45. import socks
  46. except ImportError:
  47. pass
  48. try:
  49. # Python 3
  50. from urllib import request as urllib_dot_request
  51. from urllib import parse as urllib_dot_parse
  52. except ImportError:
  53. # Python 2
  54. import urllib as urllib_dot_request
  55. import urlparse as urllib_dot_parse
  56. try:
  57. # Use monotonic clock if available
  58. time_func = time.monotonic
  59. except AttributeError:
  60. time_func = time.time
  61. try:
  62. import dns.resolver
  63. except ImportError:
  64. HAVE_DNS = False
  65. else:
  66. HAVE_DNS = True
  67. if platform.system() == 'Windows':
  68. EAGAIN = errno.WSAEWOULDBLOCK
  69. else:
  70. EAGAIN = errno.EAGAIN
  71. MQTTv31 = 3
  72. MQTTv311 = 4
  73. MQTTv5 = 5
  74. if sys.version_info[0] >= 3:
  75. # define some alias for python2 compatibility
  76. unicode = str
  77. basestring = str
  78. # Message types
  79. CONNECT = 0x10
  80. CONNACK = 0x20
  81. PUBLISH = 0x30
  82. PUBACK = 0x40
  83. PUBREC = 0x50
  84. PUBREL = 0x60
  85. PUBCOMP = 0x70
  86. SUBSCRIBE = 0x80
  87. SUBACK = 0x90
  88. UNSUBSCRIBE = 0xA0
  89. UNSUBACK = 0xB0
  90. PINGREQ = 0xC0
  91. PINGRESP = 0xD0
  92. DISCONNECT = 0xE0
  93. AUTH = 0xF0
  94. # Log levels
  95. MQTT_LOG_INFO = 0x01
  96. MQTT_LOG_NOTICE = 0x02
  97. MQTT_LOG_WARNING = 0x04
  98. MQTT_LOG_ERR = 0x08
  99. MQTT_LOG_DEBUG = 0x10
  100. LOGGING_LEVEL = {
  101. MQTT_LOG_DEBUG: logging.DEBUG,
  102. MQTT_LOG_INFO: logging.INFO,
  103. MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level
  104. MQTT_LOG_WARNING: logging.WARNING,
  105. MQTT_LOG_ERR: logging.ERROR,
  106. }
  107. # CONNACK codes
  108. CONNACK_ACCEPTED = 0
  109. CONNACK_REFUSED_PROTOCOL_VERSION = 1
  110. CONNACK_REFUSED_IDENTIFIER_REJECTED = 2
  111. CONNACK_REFUSED_SERVER_UNAVAILABLE = 3
  112. CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4
  113. CONNACK_REFUSED_NOT_AUTHORIZED = 5
  114. # Connection state
  115. mqtt_cs_new = 0
  116. mqtt_cs_connected = 1
  117. mqtt_cs_disconnecting = 2
  118. mqtt_cs_connect_async = 3
  119. # Message state
  120. mqtt_ms_invalid = 0
  121. mqtt_ms_publish = 1
  122. mqtt_ms_wait_for_puback = 2
  123. mqtt_ms_wait_for_pubrec = 3
  124. mqtt_ms_resend_pubrel = 4
  125. mqtt_ms_wait_for_pubrel = 5
  126. mqtt_ms_resend_pubcomp = 6
  127. mqtt_ms_wait_for_pubcomp = 7
  128. mqtt_ms_send_pubrec = 8
  129. mqtt_ms_queued = 9
  130. # Error values
  131. MQTT_ERR_AGAIN = -1
  132. MQTT_ERR_SUCCESS = 0
  133. MQTT_ERR_NOMEM = 1
  134. MQTT_ERR_PROTOCOL = 2
  135. MQTT_ERR_INVAL = 3
  136. MQTT_ERR_NO_CONN = 4
  137. MQTT_ERR_CONN_REFUSED = 5
  138. MQTT_ERR_NOT_FOUND = 6
  139. MQTT_ERR_CONN_LOST = 7
  140. MQTT_ERR_TLS = 8
  141. MQTT_ERR_PAYLOAD_SIZE = 9
  142. MQTT_ERR_NOT_SUPPORTED = 10
  143. MQTT_ERR_AUTH = 11
  144. MQTT_ERR_ACL_DENIED = 12
  145. MQTT_ERR_UNKNOWN = 13
  146. MQTT_ERR_ERRNO = 14
  147. MQTT_ERR_QUEUE_SIZE = 15
  148. MQTT_CLIENT = 0
  149. MQTT_BRIDGE = 1
  150. # For MQTT V5, use the clean start flag only on the first successful connect
  151. MQTT_CLEAN_START_FIRST_ONLY = 3
  152. sockpair_data = b"0"
  153. class WebsocketConnectionError(ValueError):
  154. pass
  155. class WouldBlockError(Exception):
  156. pass
  157. def error_string(mqtt_errno):
  158. """Return the error string associated with an mqtt error number."""
  159. if mqtt_errno == MQTT_ERR_SUCCESS:
  160. return "No error."
  161. elif mqtt_errno == MQTT_ERR_NOMEM:
  162. return "Out of memory."
  163. elif mqtt_errno == MQTT_ERR_PROTOCOL:
  164. return "A network protocol error occurred when communicating with the broker."
  165. elif mqtt_errno == MQTT_ERR_INVAL:
  166. return "Invalid function arguments provided."
  167. elif mqtt_errno == MQTT_ERR_NO_CONN:
  168. return "The client is not currently connected."
  169. elif mqtt_errno == MQTT_ERR_CONN_REFUSED:
  170. return "The connection was refused."
  171. elif mqtt_errno == MQTT_ERR_NOT_FOUND:
  172. return "Message not found (internal error)."
  173. elif mqtt_errno == MQTT_ERR_CONN_LOST:
  174. return "The connection was lost."
  175. elif mqtt_errno == MQTT_ERR_TLS:
  176. return "A TLS error occurred."
  177. elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE:
  178. return "Payload too large."
  179. elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED:
  180. return "This feature is not supported."
  181. elif mqtt_errno == MQTT_ERR_AUTH:
  182. return "Authorisation failed."
  183. elif mqtt_errno == MQTT_ERR_ACL_DENIED:
  184. return "Access denied by ACL."
  185. elif mqtt_errno == MQTT_ERR_UNKNOWN:
  186. return "Unknown error."
  187. elif mqtt_errno == MQTT_ERR_ERRNO:
  188. return "Error defined by errno."
  189. elif mqtt_errno == MQTT_ERR_QUEUE_SIZE:
  190. return "Message queue full."
  191. else:
  192. return "Unknown error."
  193. def connack_string(connack_code):
  194. """Return the string associated with a CONNACK result."""
  195. if connack_code == CONNACK_ACCEPTED:
  196. return "Connection Accepted."
  197. elif connack_code == CONNACK_REFUSED_PROTOCOL_VERSION:
  198. return "Connection Refused: unacceptable protocol version."
  199. elif connack_code == CONNACK_REFUSED_IDENTIFIER_REJECTED:
  200. return "Connection Refused: identifier rejected."
  201. elif connack_code == CONNACK_REFUSED_SERVER_UNAVAILABLE:
  202. return "Connection Refused: broker unavailable."
  203. elif connack_code == CONNACK_REFUSED_BAD_USERNAME_PASSWORD:
  204. return "Connection Refused: bad user name or password."
  205. elif connack_code == CONNACK_REFUSED_NOT_AUTHORIZED:
  206. return "Connection Refused: not authorised."
  207. else:
  208. return "Connection Refused: unknown reason."
  209. def base62(num, base = string.digits + string.ascii_letters, padding = 1):
  210. """Convert a number to base-62 representation."""
  211. assert num >= 0
  212. digits = []
  213. while num:
  214. num, rest = divmod(num, 62)
  215. digits.append(base[rest])
  216. digits.extend(base[0] for _ in range(len(digits), padding))
  217. return ''.join(reversed(digits))
  218. def topic_matches_sub(sub, topic):
  219. """Check whether a topic matches a subscription.
  220. For example:
  221. foo/bar would match the subscription foo/# or +/bar
  222. non/matching would not match the subscription non/+/+
  223. """
  224. matcher = MQTTMatcher()
  225. matcher[sub] = True
  226. try:
  227. next(matcher.iter_match(topic))
  228. return True
  229. except StopIteration:
  230. return False
  231. def _socketpair_compat():
  232. """TCP/IP socketpair including Windows support"""
  233. listensock = socket.socket(
  234. socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
  235. listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  236. listensock.bind(("127.0.0.1", 0))
  237. listensock.listen(1)
  238. iface, port = listensock.getsockname()
  239. sock1 = socket.socket(
  240. socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
  241. sock1.setblocking(0)
  242. try:
  243. sock1.connect(("127.0.0.1", port))
  244. except socket.error as err:
  245. if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
  246. raise
  247. sock2, address = listensock.accept()
  248. sock2.setblocking(0)
  249. listensock.close()
  250. return (sock1, sock2)
  251. class MQTTMessageInfo(object):
  252. """This is a class returned from Client.publish() and can be used to find
  253. out the mid of the message that was published, and to determine whether the
  254. message has been published, and/or wait until it is published.
  255. """
  256. __slots__ = 'mid', '_published', '_condition', 'rc', '_iterpos'
  257. def __init__(self, mid):
  258. self.mid = mid
  259. self._published = False
  260. self._condition = threading.Condition()
  261. self.rc = 0
  262. self._iterpos = 0
  263. def __str__(self):
  264. return str((self.rc, self.mid))
  265. def __iter__(self):
  266. self._iterpos = 0
  267. return self
  268. def __next__(self):
  269. return self.next()
  270. def next(self):
  271. if self._iterpos == 0:
  272. self._iterpos = 1
  273. return self.rc
  274. elif self._iterpos == 1:
  275. self._iterpos = 2
  276. return self.mid
  277. else:
  278. raise StopIteration
  279. def __getitem__(self, index):
  280. if index == 0:
  281. return self.rc
  282. elif index == 1:
  283. return self.mid
  284. else:
  285. raise IndexError("index out of range")
  286. def _set_as_published(self):
  287. with self._condition:
  288. self._published = True
  289. self._condition.notify()
  290. def wait_for_publish(self):
  291. """Block until the message associated with this object is published."""
  292. if self.rc == MQTT_ERR_QUEUE_SIZE:
  293. raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
  294. with self._condition:
  295. while not self._published:
  296. self._condition.wait()
  297. def is_published(self):
  298. """Returns True if the message associated with this object has been
  299. published, else returns False."""
  300. if self.rc == MQTT_ERR_QUEUE_SIZE:
  301. raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
  302. with self._condition:
  303. return self._published
  304. class MQTTMessage(object):
  305. """ This is a class that describes an incoming or outgoing message. It is
  306. passed to the on_message callback as the message parameter.
  307. Members:
  308. topic : String/bytes. topic that the message was published on.
  309. payload : String/bytes the message payload.
  310. qos : Integer. The message Quality of Service 0, 1 or 2.
  311. retain : Boolean. If true, the message is a retained message and not fresh.
  312. mid : Integer. The message id.
  313. properties: Properties class. In MQTT v5.0, the properties associated with the message.
  314. On Python 3, topic must be bytes.
  315. """
  316. __slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info', 'properties'
  317. def __init__(self, mid = 0, topic = b""):
  318. self.timestamp = 0
  319. self.state = mqtt_ms_invalid
  320. self.dup = False
  321. self.mid = mid
  322. self._topic = topic
  323. self.payload = b""
  324. self.qos = 0
  325. self.retain = False
  326. self.info = MQTTMessageInfo(mid)
  327. def __eq__(self, other):
  328. """Override the default Equals behavior"""
  329. if isinstance(other, self.__class__):
  330. return self.mid == other.mid
  331. return False
  332. def __ne__(self, other):
  333. """Define a non-equality test"""
  334. return not self.__eq__(other)
  335. @property
  336. def topic(self):
  337. return self._topic.decode('utf-8')
  338. @topic.setter
  339. def topic(self, value):
  340. self._topic = value
  341. class Client(object):
  342. """MQTT version 3.1/3.1.1/5.0 client class.
  343. This is the main class for use communicating with an MQTT broker.
  344. General usage flow:
  345. * Use connect()/connect_async() to connect to a broker
  346. * Call loop() frequently to maintain network traffic flow with the broker
  347. * Or use loop_start() to set a thread running to call loop() for you.
  348. * Or use loop_forever() to handle calling loop() for you in a blocking
  349. * function.
  350. * Use subscribe() to subscribe to a topic and receive messages
  351. * Use publish() to send messages
  352. * Use disconnect() to disconnect from the broker
  353. Data returned from the broker is made available with the use of callback
  354. functions as described below.
  355. Callbacks
  356. =========
  357. A number of callback functions are available to receive data back from the
  358. broker. To use a callback, define a function and then assign it to the
  359. client:
  360. def on_connect(client, userdata, flags, rc, properties=None):
  361. print("Connection returned " + str(rc))
  362. client.on_connect = on_connect
  363. All of the callbacks as described below have a "client" and an "userdata"
  364. argument. "client" is the Client instance that is calling the callback.
  365. "userdata" is user data of any type and can be set when creating a new client
  366. instance or with user_data_set(userdata).
  367. If you wish to suppress exceptions within a callback, you should set
  368. `client.suppress_exceptions = True`
  369. The callbacks:
  370. on_connect(client, userdata, flags, rc, properties=None): called when the broker responds to our connection
  371. request.
  372. flags is a dict that contains response flags from the broker:
  373. flags['session present'] - this flag is useful for clients that are
  374. using clean session set to 0 only. If a client with clean
  375. session=0, that reconnects to a broker that it has previously
  376. connected to, this flag indicates whether the broker still has the
  377. session information for the client. If 1, the session still exists.
  378. The value of rc determines success or not:
  379. 0: Connection successful
  380. 1: Connection refused - incorrect protocol version
  381. 2: Connection refused - invalid client identifier
  382. 3: Connection refused - server unavailable
  383. 4: Connection refused - bad username or password
  384. 5: Connection refused - not authorised
  385. 6-255: Currently unused.
  386. on_disconnect(client, userdata, rc): called when the client disconnects from the broker.
  387. The rc parameter indicates the disconnection state. If MQTT_ERR_SUCCESS
  388. (0), the callback was called in response to a disconnect() call. If any
  389. other value the disconnection was unexpected, such as might be caused by
  390. a network error.
  391. on_disconnect(client, userdata, rc, properties): called when the MQTT V5 client disconnects from the broker.
  392. When using MQTT V5, the broker can send a disconnect message to the client. The
  393. message can contain a reason code and MQTT V5 properties. The properties parameter could be
  394. None if they do not exist in the disconnect message.
  395. on_message(client, userdata, message): called when a message has been received on a
  396. topic that the client subscribes to. The message variable is a
  397. MQTTMessage that describes all of the message parameters.
  398. on_publish(client, userdata, mid): called when a message that was to be sent using the
  399. publish() call has completed transmission to the broker. For messages
  400. with QoS levels 1 and 2, this means that the appropriate handshakes have
  401. completed. For QoS 0, this simply means that the message has left the
  402. client. The mid variable matches the mid variable returned from the
  403. corresponding publish() call, to allow outgoing messages to be tracked.
  404. This callback is important because even if the publish() call returns
  405. success, it does not always mean that the message has been sent.
  406. on_subscribe(client, userdata, mid, granted_qos, properties=None): called when the broker responds to a
  407. subscribe request. The mid variable matches the mid variable returned
  408. from the corresponding subscribe() call. The granted_qos variable is a
  409. list of integers that give the QoS level the broker has granted for each
  410. of the different subscription requests.
  411. on_unsubscribe(client, userdata, mid): called when the broker responds to an unsubscribe
  412. request. The mid variable matches the mid variable returned from the
  413. corresponding unsubscribe() call.
  414. on_log(client, userdata, level, buf): called when the client has log information. Define
  415. to allow debugging. The level variable gives the severity of the message
  416. and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING,
  417. MQTT_LOG_ERR, and MQTT_LOG_DEBUG. The message itself is in buf.
  418. on_socket_open(client, userdata, sock): Called when the socket has been opened. Use this
  419. to register the socket with an external event loop for reading.
  420. on_socket_close(client, userdata, sock): Called when the socket is about to be closed.
  421. Use this to unregister a socket from an external event loop for reading.
  422. on_socket_register_write(client, userdata, sock): Called when a write operation to the
  423. socket failed because it would have blocked, e.g. output buffer full. Use this to
  424. register the socket with an external event loop for writing.
  425. on_socket_unregister_write(client, userdata, sock): Called when a write operation to the
  426. socket succeeded after it had previously failed. Use this to unregister the socket
  427. from an external event loop for writing.
  428. """
  429. def __init__(self, client_id = "", clean_session = None, userdata = None,
  430. protocol = MQTTv311, transport = "tcp"):
  431. """client_id is the unique client id string used when connecting to the
  432. broker. If client_id is zero length or None, then the behaviour is
  433. defined by which protocol version is in use. If using MQTT v3.1.1, then
  434. a zero length client id will be sent to the broker and the broker will
  435. generate a random for the client. If using MQTT v3.1 then an id will be
  436. randomly generated. In both cases, clean_session must be True. If this
  437. is not the case a ValueError will be raised.
  438. clean_session is a boolean that determines the client type. If True,
  439. the broker will remove all information about this client when it
  440. disconnects. If False, the client is a persistent client and
  441. subscription information and queued messages will be retained when the
  442. client disconnects.
  443. Note that a client will never discard its own outgoing messages on
  444. disconnect. Calling connect() or reconnect() will cause the messages to
  445. be resent. Use reinitialise() to reset a client to its original state.
  446. The clean_session argument only applies to MQTT versions v3.1.1 and v3.1.
  447. It is not accepted if the MQTT version is v5.0 - use the clean_start
  448. argument on connect() instead.
  449. userdata is user defined data of any type that is passed as the "userdata"
  450. parameter to callbacks. It may be updated at a later point with the
  451. user_data_set() function.
  452. The protocol argument allows explicit setting of the MQTT version to
  453. use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1),
  454. paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0),
  455. with the default being v3.1.1.
  456. Set transport to "websockets" to use WebSockets as the transport
  457. mechanism. Set to "tcp" to use raw TCP, which is the default.
  458. """
  459. if protocol == MQTTv5:
  460. if clean_session != None:
  461. raise ValueError('Clean session is not used for MQTT 5.0')
  462. else:
  463. if clean_session == None:
  464. clean_session = True
  465. if not clean_session and (client_id == "" or client_id is None):
  466. raise ValueError(
  467. 'A client id must be provided if clean session is False.')
  468. self._clean_session = clean_session
  469. if transport.lower() not in ('websockets', 'tcp'):
  470. raise ValueError(
  471. 'transport must be "websockets" or "tcp", not %s' % transport)
  472. self._transport = transport.lower()
  473. self._protocol = protocol
  474. self._userdata = userdata
  475. self._sock = None
  476. self._sockpairR, self._sockpairW = (None, None,)
  477. self._sockpairR, self._sockpairW = _socketpair_compat()
  478. self._keepalive = 60
  479. self._message_retry = 20
  480. self._last_retry_check = 0
  481. self._client_mode = MQTT_CLIENT
  482. # [MQTT-3.1.3-4] Client Id must be UTF-8 encoded string.
  483. if client_id == "" or client_id is None:
  484. if protocol == MQTTv31:
  485. self._client_id = base62(uuid.uuid4().int, padding = 22)
  486. else:
  487. self._client_id = b""
  488. else:
  489. self._client_id = client_id
  490. if isinstance(self._client_id, unicode):
  491. self._client_id = self._client_id.encode('utf-8')
  492. self._username = None
  493. self._password = None
  494. self._in_packet = {
  495. "command": 0,
  496. "have_remaining": 0,
  497. "remaining_count": [],
  498. "remaining_mult": 1,
  499. "remaining_length": 0,
  500. "packet": b"",
  501. "to_process": 0,
  502. "pos": 0}
  503. self._out_packet = collections.deque()
  504. self._current_out_packet = None
  505. self._last_msg_in = time_func()
  506. self._last_msg_out = time_func()
  507. self._reconnect_min_delay = 1
  508. self._reconnect_max_delay = 120
  509. self._reconnect_delay = None
  510. self._ping_t = 0
  511. self._last_mid = 0
  512. self._state = mqtt_cs_new
  513. self._out_messages = collections.OrderedDict()
  514. self._in_messages = collections.OrderedDict()
  515. self._max_inflight_messages = 20
  516. self._inflight_messages = 0
  517. self._max_queued_messages = 0
  518. self._connect_properties = None
  519. self._will_properties = None
  520. self._will = False
  521. self._will_topic = b""
  522. self._will_payload = b""
  523. self._will_qos = 0
  524. self._will_retain = False
  525. self._on_message_filtered = MQTTMatcher()
  526. self._host = ""
  527. self._port = 1883
  528. self._bind_address = ""
  529. self._bind_port = 0
  530. self._proxy = {}
  531. self._in_callback_mutex = threading.Lock()
  532. self._callback_mutex = threading.RLock()
  533. self._out_packet_mutex = threading.Lock()
  534. self._current_out_packet_mutex = threading.RLock()
  535. self._msgtime_mutex = threading.Lock()
  536. self._out_message_mutex = threading.RLock()
  537. self._in_message_mutex = threading.Lock()
  538. self._reconnect_delay_mutex = threading.Lock()
  539. self._mid_generate_mutex = threading.Lock()
  540. self._thread = None
  541. self._thread_terminate = False
  542. self._ssl = False
  543. self._ssl_context = None
  544. # Only used when SSL context does not have check_hostname attribute
  545. self._tls_insecure = False
  546. self._logger = None
  547. self._registered_write = False
  548. # No default callbacks
  549. self._on_log = None
  550. self._on_connect = None
  551. self._on_subscribe = None
  552. self._on_message = None
  553. self._on_publish = None
  554. self._on_unsubscribe = None
  555. self._on_disconnect = None
  556. self._on_socket_open = None
  557. self._on_socket_close = None
  558. self._on_socket_register_write = None
  559. self._on_socket_unregister_write = None
  560. self._websocket_path = "/mqtt"
  561. self._websocket_extra_headers = None
  562. # for clean_start == MQTT_CLEAN_START_FIRST_ONLY
  563. self._mqttv5_first_connect = True
  564. self.suppress_exceptions = False # For callbacks
  565. def __del__(self):
  566. self._reset_sockets()
  567. def _sock_recv(self, bufsize):
  568. try:
  569. return self._sock.recv(bufsize)
  570. except socket.error as err:
  571. if self._ssl and err.errno == ssl.SSL_ERROR_WANT_READ:
  572. raise WouldBlockError()
  573. if self._ssl and err.errno == ssl.SSL_ERROR_WANT_WRITE:
  574. self._call_socket_register_write()
  575. raise WouldBlockError()
  576. if err.errno == EAGAIN:
  577. raise WouldBlockError()
  578. raise
  579. def _sock_send(self, buf):
  580. try:
  581. return self._sock.send(buf)
  582. except socket.error as err:
  583. if self._ssl and err.errno == ssl.SSL_ERROR_WANT_READ:
  584. raise WouldBlockError()
  585. if self._ssl and err.errno == ssl.SSL_ERROR_WANT_WRITE:
  586. self._call_socket_register_write()
  587. raise WouldBlockError()
  588. if err.errno == EAGAIN:
  589. self._call_socket_register_write()
  590. raise WouldBlockError()
  591. raise
  592. def _sock_close(self):
  593. """Close the connection to the server."""
  594. if not self._sock:
  595. return
  596. try:
  597. sock = self._sock
  598. self._sock = None
  599. self._call_socket_unregister_write(sock)
  600. self._call_socket_close(sock)
  601. finally:
  602. # In case a callback fails, still close the socket to avoid leaking the file descriptor.
  603. sock.close()
  604. def _reset_sockets(self):
  605. self._sock_close()
  606. if self._sockpairR:
  607. self._sockpairR.close()
  608. self._sockpairR = None
  609. if self._sockpairW:
  610. self._sockpairW.close()
  611. self._sockpairW = None
  612. def reinitialise(self, client_id = "", clean_session = True, userdata = None):
  613. self._reset_sockets()
  614. self.__init__(client_id, clean_session, userdata)
  615. def ws_set_options(self, path = "/mqtt", headers = None):
  616. """ Set the path and headers for a websocket connection
  617. path is a string starting with / which should be the endpoint of the
  618. mqtt connection on the remote server
  619. headers can be either a dict or a callable object. If it is a dict then
  620. the extra items in the dict are added to the websocket headers. If it is
  621. a callable, then the default websocket headers are passed into this
  622. function and the result is used as the new headers.
  623. """
  624. self._websocket_path = path
  625. if headers is not None:
  626. if isinstance(headers, dict) or callable(headers):
  627. self._websocket_extra_headers = headers
  628. else:
  629. raise ValueError(
  630. "'headers' option to ws_set_options has to be either a dictionary or callable")
  631. def tls_set_context(self, context = None):
  632. """Configure network encryption and authentication context. Enables SSL/TLS support.
  633. context : an ssl.SSLContext object. By default this is given by
  634. `ssl.create_default_context()`, if available.
  635. Must be called before connect() or connect_async()."""
  636. if self._ssl_context is not None:
  637. raise ValueError('SSL/TLS has already been configured.')
  638. # Assume that have SSL support, or at least that context input behaves like ssl.SSLContext
  639. # in current versions of Python
  640. if context is None:
  641. if hasattr(ssl, 'create_default_context'):
  642. context = ssl.create_default_context()
  643. else:
  644. raise ValueError('SSL/TLS context must be specified')
  645. self._ssl = True
  646. self._ssl_context = context
  647. # Ensure _tls_insecure is consistent with check_hostname attribute
  648. if hasattr(context, 'check_hostname'):
  649. self._tls_insecure = not context.check_hostname
  650. def tls_set(self, ca_certs = None, certfile = None, keyfile = None, cert_reqs = None, tls_version = None,
  651. ciphers = None):
  652. """Configure network encryption and authentication options. Enables SSL/TLS support.
  653. ca_certs : a string path to the Certificate Authority certificate files
  654. that are to be treated as trusted by this client. If this is the only
  655. option given then the client will operate in a similar manner to a web
  656. browser. That is to say it will require the broker to have a
  657. certificate signed by the Certificate Authorities in ca_certs and will
  658. communicate using TLS v1, but will not attempt any form of
  659. authentication. This provides basic network encryption but may not be
  660. sufficient depending on how the broker is configured.
  661. By default, on Python 2.7.9+ or 3.4+, the default certification
  662. authority of the system is used. On older Python version this parameter
  663. is mandatory.
  664. certfile and keyfile are strings pointing to the PEM encoded client
  665. certificate and private keys respectively. If these arguments are not
  666. None then they will be used as client information for TLS based
  667. authentication. Support for this feature is broker dependent. Note
  668. that if either of these files in encrypted and needs a password to
  669. decrypt it, Python will ask for the password at the command line. It is
  670. not currently possible to define a callback to provide the password.
  671. cert_reqs allows the certificate requirements that the client imposes
  672. on the broker to be changed. By default this is ssl.CERT_REQUIRED,
  673. which means that the broker must provide a certificate. See the ssl
  674. pydoc for more information on this parameter.
  675. tls_version allows the version of the SSL/TLS protocol used to be
  676. specified. By default TLS v1 is used. Previous versions (all versions
  677. beginning with SSL) are possible but not recommended due to possible
  678. security problems.
  679. ciphers is a string specifying which encryption ciphers are allowable
  680. for this connection, or None to use the defaults. See the ssl pydoc for
  681. more information.
  682. Must be called before connect() or connect_async()."""
  683. if ssl is None:
  684. raise ValueError('This platform has no SSL/TLS.')
  685. if not hasattr(ssl, 'SSLContext'):
  686. # Require Python version that has SSL context support in standard library
  687. raise ValueError(
  688. 'Python 2.7.9 and 3.2 are the minimum supported versions for TLS.')
  689. if ca_certs is None and not hasattr(ssl.SSLContext, 'load_default_certs'):
  690. raise ValueError('ca_certs must not be None.')
  691. # Create SSLContext object
  692. if tls_version is None:
  693. tls_version = ssl.PROTOCOL_TLSv1
  694. # If the python version supports it, use highest TLS version automatically
  695. if hasattr(ssl, "PROTOCOL_TLS"):
  696. tls_version = ssl.PROTOCOL_TLS
  697. context = ssl.SSLContext(tls_version)
  698. # Configure context
  699. if certfile is not None:
  700. context.load_cert_chain(certfile, keyfile)
  701. if cert_reqs == ssl.CERT_NONE and hasattr(context, 'check_hostname'):
  702. context.check_hostname = False
  703. context.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
  704. if ca_certs is not None:
  705. context.load_verify_locations(ca_certs)
  706. else:
  707. context.load_default_certs()
  708. if ciphers is not None:
  709. context.set_ciphers(ciphers)
  710. self.tls_set_context(context)
  711. if cert_reqs != ssl.CERT_NONE:
  712. # Default to secure, sets context.check_hostname attribute
  713. # if available
  714. self.tls_insecure_set(False)
  715. else:
  716. # But with ssl.CERT_NONE, we can not check_hostname
  717. self.tls_insecure_set(True)
  718. def tls_insecure_set(self, value):
  719. """Configure verification of the server hostname in the server certificate.
  720. If value is set to true, it is impossible to guarantee that the host
  721. you are connecting to is not impersonating your server. This can be
  722. useful in initial server testing, but makes it possible for a malicious
  723. third party to impersonate your server through DNS spoofing, for
  724. example.
  725. Do not use this function in a real system. Setting value to true means
  726. there is no point using encryption.
  727. Must be called before connect() and after either tls_set() or
  728. tls_set_context()."""
  729. if self._ssl_context is None:
  730. raise ValueError(
  731. 'Must configure SSL context before using tls_insecure_set.')
  732. self._tls_insecure = value
  733. # Ensure check_hostname is consistent with _tls_insecure attribute
  734. if hasattr(self._ssl_context, 'check_hostname'):
  735. # Rely on SSLContext to check host name
  736. # If verify_mode is CERT_NONE then the host name will never be checked
  737. self._ssl_context.check_hostname = not value
  738. def proxy_set(self, **proxy_args):
  739. """Configure proxying of MQTT connection. Enables support for SOCKS or
  740. HTTP proxies.
  741. Proxying is done through the PySocks library. Brief descriptions of the
  742. proxy_args parameters are below; see the PySocks docs for more info.
  743. (Required)
  744. proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5}
  745. proxy_addr: IP address or DNS name of proxy server
  746. (Optional)
  747. proxy_rdns: boolean indicating whether proxy lookup should be performed
  748. remotely (True, default) or locally (False)
  749. proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy
  750. proxy_password: password for SOCKS5 proxy
  751. Must be called before connect() or connect_async()."""
  752. if socks is None:
  753. raise ValueError("PySocks must be installed for proxy support.")
  754. elif not self._proxy_is_valid(proxy_args):
  755. raise ValueError("proxy_type and/or proxy_addr are invalid.")
  756. else:
  757. self._proxy = proxy_args
  758. def enable_logger(self, logger = None):
  759. """ Enables a logger to send log messages to """
  760. if logger is None:
  761. if self._logger is not None:
  762. # Do not replace existing logger
  763. return
  764. logger = logging.getLogger(__name__)
  765. self._logger = logger
  766. def disable_logger(self):
  767. self._logger = None
  768. def connect(self, host, port = 1883, keepalive = 60, bind_address = "", bind_port = 0,
  769. clean_start = MQTT_CLEAN_START_FIRST_ONLY, properties = None):
  770. """Connect to a remote broker.
  771. host is the hostname or IP address of the remote broker.
  772. port is the network port of the server host to connect to. Defaults to
  773. 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
  774. are using tls_set() the port may need providing.
  775. keepalive: Maximum period in seconds between communications with the
  776. broker. If no other messages are being exchanged, this controls the
  777. rate at which the client will send ping messages to the broker.
  778. clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
  779. Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
  780. respectively. MQTT session data (such as outstanding messages and subscriptions)
  781. is cleared on successful connect when the clean_start flag is set.
  782. properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
  783. MQTT connect packet.
  784. """
  785. if self._protocol == MQTTv5:
  786. self._mqttv5_first_connect = True
  787. else:
  788. if clean_start != MQTT_CLEAN_START_FIRST_ONLY:
  789. raise ValueError("Clean start only applies to MQTT V5")
  790. if properties != None:
  791. raise ValueError("Properties only apply to MQTT V5")
  792. self.connect_async(host, port, keepalive,
  793. bind_address, bind_port, clean_start, properties)
  794. return self.reconnect()
  795. def connect_srv(self, domain = None, keepalive = 60, bind_address = "",
  796. clean_start = MQTT_CLEAN_START_FIRST_ONLY, properties = None):
  797. """Connect to a remote broker.
  798. domain is the DNS domain to search for SRV records; if None,
  799. try to determine local domain name.
  800. keepalive, bind_address, clean_start and properties are as for connect()
  801. """
  802. if HAVE_DNS is False:
  803. raise ValueError(
  804. 'No DNS resolver library found, try "pip install dnspython" or "pip3 install dnspython3".')
  805. if domain is None:
  806. domain = socket.getfqdn()
  807. domain = domain[domain.find('.') + 1:]
  808. try:
  809. rr = '_mqtt._tcp.%s' % domain
  810. if self._ssl:
  811. # IANA specifies secure-mqtt (not mqtts) for port 8883
  812. rr = '_secure-mqtt._tcp.%s' % domain
  813. answers = []
  814. for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
  815. addr = answer.target.to_text()[:-1]
  816. answers.append(
  817. (addr, answer.port, answer.priority, answer.weight))
  818. except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
  819. raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))
  820. # FIXME: doesn't account for weight
  821. for answer in answers:
  822. host, port, prio, weight = answer
  823. try:
  824. return self.connect(host, port, keepalive, bind_address, clean_start, properties)
  825. except Exception:
  826. pass
  827. raise ValueError("No SRV hosts responded")
  828. def connect_async(self, host, port = 1883, keepalive = 60, bind_address = "", bind_port = 0,
  829. clean_start = MQTT_CLEAN_START_FIRST_ONLY, properties = None):
  830. """Connect to a remote broker asynchronously. This is a non-blocking
  831. connect call that can be used with loop_start() to provide very quick
  832. start.
  833. host is the hostname or IP address of the remote broker.
  834. port is the network port of the server host to connect to. Defaults to
  835. 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
  836. are using tls_set() the port may need providing.
  837. keepalive: Maximum period in seconds between communications with the
  838. broker. If no other messages are being exchanged, this controls the
  839. rate at which the client will send ping messages to the broker.
  840. clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
  841. Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
  842. respectively. MQTT session data (such as outstanding messages and subscriptions)
  843. is cleared on successful connect when the clean_start flag is set.
  844. properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
  845. MQTT connect packet. Use the Properties class.
  846. """
  847. if host is None or len(host) == 0:
  848. raise ValueError('Invalid host.')
  849. if port <= 0:
  850. raise ValueError('Invalid port number.')
  851. if keepalive < 0:
  852. raise ValueError('Keepalive must be >=0.')
  853. if bind_address != "" and bind_address is not None:
  854. if sys.version_info < (2, 7) or (3, 0) < sys.version_info < (3, 2):
  855. raise ValueError('bind_address requires Python 2.7 or 3.2.')
  856. if bind_port < 0:
  857. raise ValueError('Invalid bind port number.')
  858. self._host = host
  859. self._port = port
  860. self._keepalive = keepalive
  861. self._bind_address = bind_address
  862. self._bind_port = bind_port
  863. self._clean_start = clean_start
  864. self._connect_properties = properties
  865. self._state = mqtt_cs_connect_async
  866. def reconnect_delay_set(self, min_delay = 1, max_delay = 120):
  867. """ Configure the exponential reconnect delay
  868. When connection is lost, wait initially min_delay seconds and
  869. double this time every attempt. The wait is capped at max_delay.
  870. Once the client is fully connected (e.g. not only TCP socket, but
  871. received a success CONNACK), the wait timer is reset to min_delay.
  872. """
  873. with self._reconnect_delay_mutex:
  874. self._reconnect_min_delay = min_delay
  875. self._reconnect_max_delay = max_delay
  876. self._reconnect_delay = None
  877. def reconnect(self):
  878. """Reconnect the client after a disconnect. Can only be called after
  879. connect()/connect_async()."""
  880. if len(self._host) == 0:
  881. raise ValueError('Invalid host.')
  882. if self._port <= 0:
  883. raise ValueError('Invalid port number.')
  884. self._in_packet = {
  885. "command": 0,
  886. "have_remaining": 0,
  887. "remaining_count": [],
  888. "remaining_mult": 1,
  889. "remaining_length": 0,
  890. "packet": b"",
  891. "to_process": 0,
  892. "pos": 0}
  893. with self._out_packet_mutex:
  894. self._out_packet = collections.deque()
  895. with self._current_out_packet_mutex:
  896. self._current_out_packet = None
  897. with self._msgtime_mutex:
  898. self._last_msg_in = time_func()
  899. self._last_msg_out = time_func()
  900. self._ping_t = 0
  901. self._state = mqtt_cs_new
  902. self._sock_close()
  903. # Put messages in progress in a valid state.
  904. self._messages_reconnect_reset()
  905. sock = self._create_socket_connection()
  906. if self._ssl:
  907. # SSL is only supported when SSLContext is available (implies Python >= 2.7.9 or >= 3.2)
  908. verify_host = not self._tls_insecure
  909. try:
  910. # Try with server_hostname, even it's not supported in certain scenarios
  911. sock = self._ssl_context.wrap_socket(
  912. sock,
  913. server_hostname = self._host,
  914. do_handshake_on_connect = False,
  915. )
  916. except ssl.CertificateError:
  917. # CertificateError is derived from ValueError
  918. raise
  919. except ValueError:
  920. # Python version requires SNI in order to handle server_hostname, but SNI is not available
  921. sock = self._ssl_context.wrap_socket(
  922. sock,
  923. do_handshake_on_connect = False,
  924. )
  925. else:
  926. # If SSL context has already checked hostname, then don't need to do it again
  927. if (hasattr(self._ssl_context, 'check_hostname') and
  928. self._ssl_context.check_hostname):
  929. verify_host = False
  930. sock.settimeout(self._keepalive)
  931. sock.do_handshake()
  932. if verify_host:
  933. ssl.match_hostname(sock.getpeercert(), self._host)
  934. if self._transport == "websockets":
  935. sock.settimeout(self._keepalive)
  936. sock = WebsocketWrapper(sock, self._host, self._port, self._ssl,
  937. self._websocket_path, self._websocket_extra_headers)
  938. self._sock = sock
  939. self._sock.setblocking(0)
  940. self._registered_write = False
  941. self._call_socket_open()
  942. return self._send_connect(self._keepalive)
  943. def loop(self, timeout = 1.0, max_packets = 1):
  944. """Process network events.
  945. This function must be called regularly to ensure communication with the
  946. broker is carried out. It calls select() on the network socket to wait
  947. for network events. If incoming data is present it will then be
  948. processed. Outgoing commands, from e.g. publish(), are normally sent
  949. immediately that their function is called, but this is not always
  950. possible. loop() will also attempt to send any remaining outgoing
  951. messages, which also includes commands that are part of the flow for
  952. messages with QoS>0.
  953. timeout: The time in seconds to wait for incoming/outgoing network
  954. traffic before timing out and returning.
  955. max_packets: Not currently used.
  956. Returns MQTT_ERR_SUCCESS on success.
  957. Returns >0 on error.
  958. A ValueError will be raised if timeout < 0"""
  959. if timeout < 0.0:
  960. raise ValueError('Invalid timeout.')
  961. with self._current_out_packet_mutex:
  962. with self._out_packet_mutex:
  963. if self._current_out_packet is None and len(self._out_packet) > 0:
  964. self._current_out_packet = self._out_packet.popleft()
  965. if self._current_out_packet:
  966. wlist = [self._sock]
  967. else:
  968. wlist = []
  969. # used to check if there are any bytes left in the (SSL) socket
  970. pending_bytes = 0
  971. if hasattr(self._sock, 'pending'):
  972. pending_bytes = self._sock.pending()
  973. # if bytes are pending do not wait in select
  974. if pending_bytes > 0:
  975. timeout = 0.0
  976. # sockpairR is used to break out of select() before the timeout, on a
  977. # call to publish() etc.
  978. rlist = [self._sock, self._sockpairR]
  979. try:
  980. socklist = select.select(rlist, wlist, [], timeout)
  981. except TypeError:
  982. # Socket isn't correct type, in likelihood connection is lost
  983. self._easy_log(
  984. MQTT_LOG_DEBUG, "Connection failed, exception = %s", e.message)
  985. return MQTT_ERR_CONN_LOST
  986. except ValueError as e:
  987. self._easy_log(
  988. MQTT_LOG_DEBUG, "Connection failed, exception = %s", e.message)
  989. # Can occur if we just reconnected but rlist/wlist contain a -1 for
  990. # some reason.
  991. return MQTT_ERR_CONN_LOST
  992. except Exception as e:
  993. self._easy_log(
  994. MQTT_LOG_DEBUG, "Connection failed, exception = %s", e.message)
  995. # Note that KeyboardInterrupt, etc. can still terminate since they
  996. # are not derived from Exception
  997. return MQTT_ERR_UNKNOWN
  998. if self._sock in socklist[0] or pending_bytes > 0:
  999. rc = self.loop_read(max_packets)
  1000. if rc or self._sock is None:
  1001. return rc
  1002. if self._sockpairR in socklist[0]:
  1003. # Stimulate output write even though we didn't ask for it, because
  1004. # at that point the publish or other command wasn't present.
  1005. socklist[1].insert(0, self._sock)
  1006. # Clear sockpairR - only ever a single byte written.
  1007. try:
  1008. self._sockpairR.recv(1)
  1009. except socket.error as err:
  1010. if err.errno != EAGAIN:
  1011. raise
  1012. if self._sock in socklist[1]:
  1013. rc = self.loop_write(max_packets)
  1014. if rc or self._sock is None:
  1015. return rc
  1016. return self.loop_misc()
  1017. def publish(self, topic, payload = None, qos = 0, retain = False, properties = None):
  1018. """Publish a message on a topic.
  1019. This causes a message to be sent to the broker and subsequently from
  1020. the broker to any clients subscribing to matching topics.
  1021. topic: The topic that the message should be published on.
  1022. payload: The actual message to send. If not given, or set to None a
  1023. zero length message will be used. Passing an int or float will result
  1024. in the payload being converted to a string representing that number. If
  1025. you wish to send a true int/float, use struct.pack() to create the
  1026. payload you require.
  1027. qos: The quality of service level to use.
  1028. retain: If set to true, the message will be set as the "last known
  1029. good"/retained message for the topic.
  1030. properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included.
  1031. Use the Properties class.
  1032. Returns a MQTTMessageInfo class, which can be used to determine whether
  1033. the message has been delivered (using info.is_published()) or to block
  1034. waiting for the message to be delivered (info.wait_for_publish()). The
  1035. message ID and return code of the publish() call can be found at
  1036. info.mid and info.rc.
  1037. For backwards compatibility, the MQTTMessageInfo class is iterable so
  1038. the old construct of (rc, mid) = client.publish(...) is still valid.
  1039. rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the
  1040. client is not currently connected. mid is the message ID for the
  1041. publish request. The mid value can be used to track the publish request
  1042. by checking against the mid argument in the on_publish() callback if it
  1043. is defined.
  1044. A ValueError will be raised if topic is None, has zero length or is
  1045. invalid (contains a wildcard), except if the MQTT version used is v5.0.
  1046. For v5.0, a zero length topic can be used when a Topic Alias has been set.
  1047. A ValueError will be raised if qos is not one of 0, 1 or 2, or if
  1048. the length of the payload is greater than 268435455 bytes."""
  1049. if self._protocol != MQTTv5:
  1050. if topic is None or len(topic) == 0:
  1051. raise ValueError('Invalid topic.')
  1052. topic = topic.encode('utf-8')
  1053. if self._topic_wildcard_len_check(topic) != MQTT_ERR_SUCCESS:
  1054. raise ValueError('Publish topic cannot contain wildcards.')
  1055. if qos < 0 or qos > 2:
  1056. raise ValueError('Invalid QoS level.')
  1057. if isinstance(payload, unicode):
  1058. local_payload = payload.encode('utf-8')
  1059. elif isinstance(payload, (bytes, bytearray)):
  1060. local_payload = payload
  1061. elif isinstance(payload, (int, float)):
  1062. local_payload = str(payload).encode('ascii')
  1063. elif payload is None:
  1064. local_payload = b''
  1065. else:
  1066. raise TypeError(
  1067. 'payload must be a string, bytearray, int, float or None.')
  1068. if len(local_payload) > 268435455:
  1069. raise ValueError('Payload too large.')
  1070. local_mid = self._mid_generate()
  1071. if qos == 0:
  1072. info = MQTTMessageInfo(local_mid)
  1073. rc = self._send_publish(
  1074. local_mid, topic, local_payload, qos, retain, False, info, properties)
  1075. info.rc = rc
  1076. return info
  1077. else:
  1078. message = MQTTMessage(local_mid, topic)
  1079. message.timestamp = time_func()
  1080. message.payload = local_payload
  1081. message.qos = qos
  1082. message.retain = retain
  1083. message.dup = False
  1084. message.properties = properties
  1085. with self._out_message_mutex:
  1086. if self._max_queued_messages > 0 and len(self._out_messages) >= self._max_queued_messages:
  1087. message.info.rc = MQTT_ERR_QUEUE_SIZE
  1088. return message.info
  1089. if local_mid in self._out_messages:
  1090. message.info.rc = MQTT_ERR_QUEUE_SIZE
  1091. return message.info
  1092. self._out_messages[message.mid] = message
  1093. if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
  1094. self._inflight_messages += 1
  1095. if qos == 1:
  1096. message.state = mqtt_ms_wait_for_puback
  1097. elif qos == 2:
  1098. message.state = mqtt_ms_wait_for_pubrec
  1099. rc = self._send_publish(message.mid, topic, message.payload, message.qos, message.retain,
  1100. message.dup, message.info, message.properties)
  1101. # remove from inflight messages so it will be send after a connection is made
  1102. if rc is MQTT_ERR_NO_CONN:
  1103. self._inflight_messages -= 1
  1104. message.state = mqtt_ms_publish
  1105. message.info.rc = rc
  1106. return message.info
  1107. else:
  1108. message.state = mqtt_ms_queued
  1109. message.info.rc = MQTT_ERR_SUCCESS
  1110. return message.info
  1111. def username_pw_set(self, username, password = None):
  1112. """Set a username and optionally a password for broker authentication.
  1113. Must be called before connect() to have any effect.
  1114. Requires a broker that supports MQTT v3.1.
  1115. username: The username to authenticate with. Need have no relationship to the client id. Must be unicode
  1116. [MQTT-3.1.3-11].
  1117. Set to None to reset client back to not using username/password for broker authentication.
  1118. password: The password to authenticate with. Optional, set to None if not required. If it is unicode, then it
  1119. will be encoded as UTF-8.
  1120. """
  1121. # [MQTT-3.1.3-11] User name must be UTF-8 encoded string
  1122. self._username = None if username is None else username.encode('utf-8')
  1123. self._password = password
  1124. if isinstance(self._password, unicode):
  1125. self._password = self._password.encode('utf-8')
  1126. def enable_bridge_mode(self):
  1127. """Sets the client in a bridge mode instead of client mode.
  1128. Must be called before connect() to have any effect.
  1129. Requires brokers that support bridge mode.
  1130. Under bridge mode, the broker will identify the client as a bridge and
  1131. not send it's own messages back to it. Hence a subsciption of # is
  1132. possible without message loops. This feature also correctly propagates
  1133. the retain flag on the messages.
  1134. Currently Mosquitto and RSMB support this feature. This feature can
  1135. be used to create a bridge between multiple broker.
  1136. """
  1137. self._client_mode = MQTT_BRIDGE
  1138. def is_connected(self):
  1139. """Returns the current status of the connection
  1140. True if connection exists
  1141. False if connection is closed
  1142. """
  1143. return self._state == mqtt_cs_connected
  1144. def disconnect(self, reasoncode = None, properties = None):
  1145. """Disconnect a connected client from the broker.
  1146. reasoncode: (MQTT v5.0 only) a ReasonCodes instance setting the MQTT v5.0
  1147. reasoncode to be sent with the disconnect. It is optional, the receiver
  1148. then assuming that 0 (success) is the value.
  1149. properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
  1150. to be included. Optional - if not set, no properties are sent.
  1151. """
  1152. self._state = mqtt_cs_disconnecting
  1153. if self._sock is None:
  1154. return MQTT_ERR_NO_CONN
  1155. return self._send_disconnect(reasoncode, properties)
  1156. def subscribe(self, topic, qos = 0, options = None, properties = None):
  1157. """Subscribe the client to one or more topics.
  1158. This function may be called in three different ways (and a further three for MQTT v5.0):
  1159. Simple string and integer
  1160. -------------------------
  1161. e.g. subscribe("my/topic", 2)
  1162. topic: A string specifying the subscription topic to subscribe to.
  1163. qos: The desired quality of service level for the subscription.
  1164. Defaults to 0.
  1165. options and properties: Not used.
  1166. Simple string and subscribe options (MQTT v5.0 only)
  1167. ----------------------------------------------------
  1168. e.g. subscribe("my/topic", options=SubscribeOptions(qos=2))
  1169. topic: A string specifying the subscription topic to subscribe to.
  1170. qos: Not used.
  1171. options: The MQTT v5.0 subscribe options.
  1172. properties: a Properties instance setting the MQTT v5.0 properties
  1173. to be included. Optional - if not set, no properties are sent.
  1174. String and integer tuple
  1175. ------------------------
  1176. e.g. subscribe(("my/topic", 1))
  1177. topic: A tuple of (topic, qos). Both topic and qos must be present in
  1178. the tuple.
  1179. qos and options: Not used.
  1180. properties: Only used for MQTT v5.0. A Properties instance setting the
  1181. MQTT v5.0 properties. Optional - if not set, no properties are sent.
  1182. String and subscribe options tuple (MQTT v5.0 only)
  1183. ---------------------------------------------------
  1184. e.g. subscribe(("my/topic", SubscribeOptions(qos=1)))
  1185. topic: A tuple of (topic, SubscribeOptions). Both topic and subscribe
  1186. options must be present in the tuple.
  1187. qos and options: Not used.
  1188. properties: a Properties instance setting the MQTT v5.0 properties
  1189. to be included. Optional - if not set, no properties are sent.
  1190. List of string and integer tuples
  1191. ---------------------------------
  1192. e.g. subscribe([("my/topic", 0), ("another/topic", 2)])
  1193. This allows multiple topic subscriptions in a single SUBSCRIPTION
  1194. command, which is more efficient than using multiple calls to
  1195. subscribe().
  1196. topic: A list of tuple of format (topic, qos). Both topic and qos must
  1197. be present in all of the tuples.
  1198. qos, options and properties: Not used.
  1199. List of string and subscribe option tuples (MQTT v5.0 only)
  1200. -----------------------------------------------------------
  1201. e.g. subscribe([("my/topic", SubscribeOptions(qos=0), ("another/topic", SubscribeOptions(qos=2)])
  1202. This allows multiple topic subscriptions in a single SUBSCRIPTION
  1203. command, which is more efficient than using multiple calls to
  1204. subscribe().
  1205. topic: A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe
  1206. options must be present in all of the tuples.
  1207. qos and options: Not used.
  1208. properties: a Properties instance setting the MQTT v5.0 properties
  1209. to be included. Optional - if not set, no properties are sent.
  1210. The function returns a tuple (result, mid), where result is
  1211. MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
  1212. client is not currently connected. mid is the message ID for the
  1213. subscribe request. The mid value can be used to track the subscribe
  1214. request by checking against the mid argument in the on_subscribe()
  1215. callback if it is defined.
  1216. Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
  1217. zero string length, or if topic is not a string, tuple or list.
  1218. """
  1219. topic_qos_list = None
  1220. if isinstance(topic, tuple):
  1221. if self._protocol == MQTTv5:
  1222. topic, options = topic
  1223. if not isinstance(options, SubscribeOptions):
  1224. raise ValueError(
  1225. 'Subscribe options must be instance of SubscribeOptions class.')
  1226. else:
  1227. topic, qos = topic
  1228. if isinstance(topic, basestring):
  1229. if qos < 0 or qos > 2:
  1230. raise ValueError('Invalid QoS level.')
  1231. if self._protocol == MQTTv5:
  1232. if options == None:
  1233. # if no options are provided, use the QoS passed instead
  1234. options = SubscribeOptions(qos = qos)
  1235. elif qos != 0:
  1236. raise ValueError(
  1237. 'Subscribe options and qos parameters cannot be combined.')
  1238. if not isinstance(options, SubscribeOptions):
  1239. raise ValueError(
  1240. 'Subscribe options must be instance of SubscribeOptions class.')
  1241. topic_qos_list = [(topic.encode('utf-8'), options)]
  1242. else:
  1243. if topic is None or len(topic) == 0:
  1244. raise ValueError('Invalid topic.')
  1245. topic_qos_list = [(topic.encode('utf-8'), qos)]
  1246. elif isinstance(topic, list):
  1247. topic_qos_list = []
  1248. if self._protocol == MQTTv5:
  1249. for t, o in topic:
  1250. if not isinstance(o, SubscribeOptions):
  1251. # then the second value should be QoS
  1252. if o < 0 or o > 2:
  1253. raise ValueError('Invalid QoS level.')
  1254. o = SubscribeOptions(qos = o)
  1255. topic_qos_list.append((t.encode('utf-8'), o))
  1256. else:
  1257. for t, q in topic:
  1258. if q < 0 or q > 2:
  1259. raise ValueError('Invalid QoS level.')
  1260. if t is None or len(t) == 0 or not isinstance(t, basestring):
  1261. raise ValueError('Invalid topic.')
  1262. topic_qos_list.append((t.encode('utf-8'), q))
  1263. if topic_qos_list is None:
  1264. raise ValueError("No topic specified, or incorrect topic type.")
  1265. if any(self._filter_wildcard_len_check(topic) != MQTT_ERR_SUCCESS for topic, _ in topic_qos_list):
  1266. raise ValueError('Invalid subscription filter.')
  1267. if self._sock is None:
  1268. return (MQTT_ERR_NO_CONN, None)
  1269. return self._send_subscribe(False, topic_qos_list, properties)
  1270. def unsubscribe(self, topic, properties = None):
  1271. """Unsubscribe the client from one or more topics.
  1272. topic: A single string, or list of strings that are the subscription
  1273. topics to unsubscribe from.
  1274. properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
  1275. to be included. Optional - if not set, no properties are sent.
  1276. Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
  1277. to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
  1278. currently connected.
  1279. mid is the message ID for the unsubscribe request. The mid value can be
  1280. used to track the unsubscribe request by checking against the mid
  1281. argument in the on_unsubscribe() callback if it is defined.
  1282. Raises a ValueError if topic is None or has zero string length, or is
  1283. not a string or list.
  1284. """
  1285. topic_list = None
  1286. if topic is None:
  1287. raise ValueError('Invalid topic.')
  1288. if isinstance(topic, basestring):
  1289. if len(topic) == 0:
  1290. raise ValueError('Invalid topic.')
  1291. topic_list = [topic.encode('utf-8')]
  1292. elif isinstance(topic, list):
  1293. topic_list = []
  1294. for t in topic:
  1295. if len(t) == 0 or not isinstance(t, basestring):
  1296. raise ValueError('Invalid topic.')
  1297. topic_list.append(t.encode('utf-8'))
  1298. if topic_list is None:
  1299. raise ValueError("No topic specified, or incorrect topic type.")
  1300. if self._sock is None:
  1301. return (MQTT_ERR_NO_CONN, None)
  1302. return self._send_unsubscribe(False, topic_list, properties)
  1303. def loop_read(self, max_packets = 1):
  1304. """Process read network events. Use in place of calling loop() if you
  1305. wish to handle your client reads as part of your own application.
  1306. Use socket() to obtain the client socket to call select() or equivalent
  1307. on.
  1308. Do not use if you are using the threaded interface loop_start()."""
  1309. if self._sock is None:
  1310. return MQTT_ERR_NO_CONN
  1311. max_packets = len(self._out_messages) + len(self._in_messages)
  1312. if max_packets < 1:
  1313. max_packets = 1
  1314. for _ in range(0, max_packets):
  1315. if self._sock is None:
  1316. return MQTT_ERR_NO_CONN
  1317. rc = self._packet_read()
  1318. if rc > 0:
  1319. return self._loop_rc_handle(rc)
  1320. elif rc == MQTT_ERR_AGAIN:
  1321. return MQTT_ERR_SUCCESS
  1322. return MQTT_ERR_SUCCESS
  1323. def loop_write(self, max_packets = 1):
  1324. """Process write network events. Use in place of calling loop() if you
  1325. wish to handle your client writes as part of your own application.
  1326. Use socket() to obtain the client socket to call select() or equivalent
  1327. on.
  1328. Use want_write() to determine if there is data waiting to be written.
  1329. Do not use if you are using the threaded interface loop_start()."""
  1330. if self._sock is None:
  1331. return MQTT_ERR_NO_CONN
  1332. max_packets = len(self._out_packet) + 1
  1333. if max_packets < 1:
  1334. max_packets = 1
  1335. try:
  1336. for _ in range(0, max_packets):
  1337. rc = self._packet_write()
  1338. if rc > 0:
  1339. return self._loop_rc_handle(rc)
  1340. elif rc == MQTT_ERR_AGAIN:
  1341. return MQTT_ERR_SUCCESS
  1342. return MQTT_ERR_SUCCESS
  1343. finally:
  1344. if self.want_write():
  1345. self._call_socket_register_write()
  1346. else:
  1347. self._call_socket_unregister_write()
  1348. def want_write(self):
  1349. """Call to determine if there is network data waiting to be written.
  1350. Useful if you are calling select() yourself rather than using loop().
  1351. """
  1352. if self._current_out_packet or len(self._out_packet) > 0:
  1353. return True
  1354. else:
  1355. return False
  1356. def loop_misc(self):
  1357. """Process miscellaneous network events. Use in place of calling loop() if you
  1358. wish to call select() or equivalent on.
  1359. Do not use if you are using the threaded interface loop_start()."""
  1360. if self._sock is None:
  1361. return MQTT_ERR_NO_CONN
  1362. now = time_func()
  1363. self._check_keepalive()
  1364. if self._last_retry_check + 1 < now:
  1365. # Only check once a second at most
  1366. self._message_retry_check()
  1367. self._last_retry_check = now
  1368. if self._ping_t > 0 and now - self._ping_t >= self._keepalive:
  1369. # client->ping_t != 0 means we are waiting for a pingresp.
  1370. # This hasn't happened in the keepalive time so we should disconnect.
  1371. self._sock_close()
  1372. if self._state == mqtt_cs_disconnecting:
  1373. rc = MQTT_ERR_SUCCESS
  1374. else:
  1375. rc = 1
  1376. self._do_on_disconnect(rc)
  1377. return MQTT_ERR_CONN_LOST
  1378. return MQTT_ERR_SUCCESS
  1379. def max_inflight_messages_set(self, inflight):
  1380. """Set the maximum number of messages with QoS>0 that can be part way
  1381. through their network flow at once. Defaults to 20."""
  1382. if inflight < 0:
  1383. raise ValueError('Invalid inflight.')
  1384. self._max_inflight_messages = inflight
  1385. def max_queued_messages_set(self, queue_size):
  1386. """Set the maximum number of messages in the outgoing message queue.
  1387. 0 means unlimited."""
  1388. if queue_size < 0:
  1389. raise ValueError('Invalid queue size.')
  1390. if not isinstance(queue_size, int):
  1391. raise ValueError('Invalid type of queue size.')
  1392. self._max_queued_messages = queue_size
  1393. return self
  1394. def message_retry_set(self, retry):
  1395. """Set the timeout in seconds before a message with QoS>0 is retried.
  1396. 20 seconds by default."""
  1397. if retry < 0:
  1398. raise ValueError('Invalid retry.')
  1399. self._message_retry = retry
  1400. def user_data_set(self, userdata):
  1401. """Set the user data variable passed to callbacks. May be any data type."""
  1402. self._userdata = userdata
  1403. def will_set(self, topic, payload = None, qos = 0, retain = False, properties = None):
  1404. """Set a Will to be sent by the broker in case the client disconnects unexpectedly.
  1405. This must be called before connect() to have any effect.
  1406. topic: The topic that the will message should be published on.
  1407. payload: The message to send as a will. If not given, or set to None a
  1408. zero length message will be used as the will. Passing an int or float
  1409. will result in the payload being converted to a string representing
  1410. that number. If you wish to send a true int/float, use struct.pack() to
  1411. create the payload you require.
  1412. qos: The quality of service level to use for the will.
  1413. retain: If set to true, the will message will be set as the "last known
  1414. good"/retained message for the topic.
  1415. properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
  1416. to be included with the will message. Optional - if not set, no properties are sent.
  1417. Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
  1418. zero string length.
  1419. """
  1420. if topic is None or len(topic) == 0:
  1421. raise ValueError('Invalid topic.')
  1422. if qos < 0 or qos > 2:
  1423. raise ValueError('Invalid QoS level.')
  1424. if properties != None and not isinstance(properties, Properties):
  1425. raise ValueError(
  1426. "The properties argument must be an instance of the Properties class.")
  1427. if isinstance(payload, unicode):
  1428. self._will_payload = payload.encode('utf-8')
  1429. elif isinstance(payload, (bytes, bytearray)):
  1430. self._will_payload = payload
  1431. elif isinstance(payload, (int, float)):
  1432. self._will_payload = str(payload).encode('ascii')
  1433. elif payload is None:
  1434. self._will_payload = b""
  1435. else:
  1436. raise TypeError(
  1437. 'payload must be a string, bytearray, int, float or None.')
  1438. self._will = True
  1439. self._will_topic = topic.encode('utf-8')
  1440. self._will_qos = qos
  1441. self._will_retain = retain
  1442. self._will_properties = properties
  1443. def will_clear(self):
  1444. """ Removes a will that was previously configured with will_set().
  1445. Must be called before connect() to have any effect."""
  1446. self._will = False
  1447. self._will_topic = b""
  1448. self._will_payload = b""
  1449. self._will_qos = 0
  1450. self._will_retain = False
  1451. def socket(self):
  1452. """Return the socket or ssl object for this client."""
  1453. return self._sock
  1454. def loop_forever(self, timeout = 1.0, max_packets = 1, retry_first_connection = False):
  1455. """This function call loop() for you in an infinite blocking loop. It
  1456. is useful for the case where you only want to run the MQTT client loop
  1457. in your program.
  1458. loop_forever() will handle reconnecting for you. If you call
  1459. disconnect() in a callback it will return.
  1460. timeout: The time in seconds to wait for incoming/outgoing network
  1461. traffic before timing out and returning.
  1462. max_packets: Not currently used.
  1463. retry_first_connection: Should the first connection attempt be retried on failure.
  1464. Raises socket.error on first connection failures unless retry_first_connection=True
  1465. """
  1466. run = True
  1467. while run:
  1468. if self._thread_terminate is True:
  1469. break
  1470. if self._state == mqtt_cs_connect_async:
  1471. try:
  1472. self.reconnect()
  1473. except (socket.error, OSError, WebsocketConnectionError):
  1474. if not retry_first_connection:
  1475. raise
  1476. self._easy_log(
  1477. MQTT_LOG_DEBUG, "Connection failed, retrying")
  1478. self._reconnect_wait()
  1479. else:
  1480. break
  1481. while run:
  1482. rc = MQTT_ERR_SUCCESS
  1483. while rc == MQTT_ERR_SUCCESS:
  1484. rc = self.loop(timeout, max_packets)
  1485. # We don't need to worry about locking here, because we've
  1486. # either called loop_forever() when in single threaded mode, or
  1487. # in multi threaded mode when loop_stop() has been called and
  1488. # so no other threads can access _current_out_packet,
  1489. # _out_packet or _messages.
  1490. if (self._thread_terminate is True
  1491. and self._current_out_packet is None
  1492. and len(self._out_packet) == 0
  1493. and len(self._out_messages) == 0):
  1494. rc = 1
  1495. run = False
  1496. def should_exit():
  1497. return self._state == mqtt_cs_disconnecting or run is False or self._thread_terminate is True
  1498. if should_exit():
  1499. run = False
  1500. else:
  1501. self._reconnect_wait()
  1502. if should_exit():
  1503. run = False
  1504. else:
  1505. try:
  1506. self.reconnect()
  1507. except (socket.error, OSError, WebsocketConnectionError):
  1508. self._easy_log(
  1509. MQTT_LOG_DEBUG, "Connection failed, retrying")
  1510. return rc
  1511. def loop_start(self):
  1512. """This is part of the threaded client interface. Call this once to
  1513. start a new thread to process network traffic. This provides an
  1514. alternative to repeatedly calling loop() yourself.
  1515. """
  1516. if self._thread is not None:
  1517. return MQTT_ERR_INVAL
  1518. self._thread_terminate = False
  1519. self._thread = threading.Thread(target = self._thread_main)
  1520. self._thread.daemon = True
  1521. self._thread.start()
  1522. def loop_stop(self, force = False):
  1523. """This is part of the threaded client interface. Call this once to
  1524. stop the network thread previously created with loop_start(). This call
  1525. will block until the network thread finishes.
  1526. The force parameter is currently ignored.
  1527. """
  1528. if self._thread is None:
  1529. return MQTT_ERR_INVAL
  1530. self._thread_terminate = True
  1531. if threading.current_thread() != self._thread:
  1532. self._thread.join()
  1533. self._thread = None
  1534. @property
  1535. def on_log(self):
  1536. """If implemented, called when the client has log information.
  1537. Defined to allow debugging."""
  1538. return self._on_log
  1539. @on_log.setter
  1540. def on_log(self, func):
  1541. """ Define the logging callback implementation.
  1542. Expected signature is:
  1543. log_callback(client, userdata, level, buf)
  1544. client: the client instance for this callback
  1545. userdata: the private user data as set in Client() or userdata_set()
  1546. level: gives the severity of the message and will be one of
  1547. MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING,
  1548. MQTT_LOG_ERR, and MQTT_LOG_DEBUG.
  1549. buf: the message itself
  1550. """
  1551. self._on_log = func
  1552. @property
  1553. def on_connect(self):
  1554. """If implemented, called when the broker responds to our connection
  1555. request."""
  1556. return self._on_connect
  1557. @on_connect.setter
  1558. def on_connect(self, func):
  1559. """ Define the connect callback implementation.
  1560. Expected signature for MQTT v3.1 and v3.1.1 is:
  1561. connect_callback(client, userdata, flags, rc, properties=None)
  1562. and for MQTT v5.0:
  1563. connect_callback(client, userdata, flags, reasonCode, properties)
  1564. client: the client instance for this callback
  1565. userdata: the private user data as set in Client() or userdata_set()
  1566. flags: response flags sent by the broker
  1567. rc: the connection result
  1568. reasonCode: the MQTT v5.0 reason code: an instance of the ReasonCode class.
  1569. ReasonCode may be compared to interger.
  1570. properties: the MQTT v5.0 properties returned from the broker. An instance
  1571. of the Properties class.
  1572. For MQTT v3.1 and v3.1.1 properties is not provided but for compatibility
  1573. with MQTT v5.0, we recommand adding properties=None.
  1574. flags is a dict that contains response flags from the broker:
  1575. flags['session present'] - this flag is useful for clients that are
  1576. using clean session set to 0 only. If a client with clean
  1577. session=0, that reconnects to a broker that it has previously
  1578. connected to, this flag indicates whether the broker still has the
  1579. session information for the client. If 1, the session still exists.
  1580. The value of rc indicates success or not:
  1581. 0: Connection successful
  1582. 1: Connection refused - incorrect protocol version
  1583. 2: Connection refused - invalid client identifier
  1584. 3: Connection refused - server unavailable
  1585. 4: Connection refused - bad username or password
  1586. 5: Connection refused - not authorised
  1587. 6-255: Currently unused.
  1588. """
  1589. with self._callback_mutex:
  1590. self._on_connect = func
  1591. @property
  1592. def on_subscribe(self):
  1593. """If implemented, called when the broker responds to a subscribe
  1594. request."""
  1595. return self._on_subscribe
  1596. @on_subscribe.setter
  1597. def on_subscribe(self, func):
  1598. """ Define the suscribe callback implementation.
  1599. Expected signature for MQTT v3.1.1 and v3.1 is:
  1600. subscribe_callback(client, userdata, mid, granted_qos, properties=None)
  1601. and for MQTT v5.0:
  1602. subscribe_callback(client, userdata, mid, reasonCodes, properties)
  1603. client: the client instance for this callback
  1604. userdata: the private user data as set in Client() or userdata_set()
  1605. mid: matches the mid variable returned from the corresponding
  1606. subscribe() call.
  1607. granted_qos: list of integers that give the QoS level the broker has
  1608. granted for each of the different subscription requests.
  1609. reasonCodes: the MQTT v5.0 reason codes received from the broker for each
  1610. subscription. A list of ReasonCodes instances.
  1611. properties: the MQTT v5.0 properties received from the broker. A
  1612. list of Properties class instances.
  1613. """
  1614. with self._callback_mutex:
  1615. self._on_subscribe = func
  1616. @property
  1617. def on_message(self):
  1618. """If implemented, called when a message has been received on a topic
  1619. that the client subscribes to.
  1620. This callback will be called for every message received. Use
  1621. message_callback_add() to define multiple callbacks that will be called
  1622. for specific topic filters."""
  1623. return self._on_message
  1624. @on_message.setter
  1625. def on_message(self, func):
  1626. """ Define the message received callback implementation.
  1627. Expected signature is:
  1628. on_message_callback(client, userdata, message)
  1629. client: the client instance for this callback
  1630. userdata: the private user data as set in Client() or userdata_set()
  1631. message: an instance of MQTTMessage.
  1632. This is a class with members topic, payload, qos, retain.
  1633. """
  1634. with self._callback_mutex:
  1635. self._on_message = func
  1636. @property
  1637. def on_publish(self):
  1638. """If implemented, called when a message that was to be sent using the
  1639. publish() call has completed transmission to the broker.
  1640. For messages with QoS levels 1 and 2, this means that the appropriate
  1641. handshakes have completed. For QoS 0, this simply means that the message
  1642. has left the client.
  1643. This callback is important because even if the publish() call returns
  1644. success, it does not always mean that the message has been sent."""
  1645. return self._on_publish
  1646. @on_publish.setter
  1647. def on_publish(self, func):
  1648. """ Define the published message callback implementation.
  1649. Expected signature is:
  1650. on_publish_callback(client, userdata, mid)
  1651. client: the client instance for this callback
  1652. userdata: the private user data as set in Client() or userdata_set()
  1653. mid: matches the mid variable returned from the corresponding
  1654. publish() call, to allow outgoing messages to be tracked.
  1655. """
  1656. with self._callback_mutex:
  1657. self._on_publish = func
  1658. @property
  1659. def on_unsubscribe(self):
  1660. """If implemented, called when the broker responds to an unsubscribe
  1661. request."""
  1662. return self._on_unsubscribe
  1663. @on_unsubscribe.setter
  1664. def on_unsubscribe(self, func):
  1665. """ Define the unsubscribe callback implementation.
  1666. Expected signature for MQTT v3.1.1 and v3.1 is:
  1667. unsubscribe_callback(client, userdata, mid)
  1668. and for MQTT v5.0:
  1669. unsubscribe_callback(client, userdata, mid, properties, reasonCodes)
  1670. client: the client instance for this callback
  1671. userdata: the private user data as set in Client() or userdata_set()
  1672. mid: matches the mid variable returned from the corresponding
  1673. unsubscribe() call.
  1674. properties: the MQTT v5.0 properties received from the broker. A
  1675. list of Properties class instances.
  1676. reasonCodes: the MQTT v5.0 reason codes received from the broker for each
  1677. unsubscribe topic. A list of ReasonCodes instances
  1678. """
  1679. with self._callback_mutex:
  1680. self._on_unsubscribe = func
  1681. @property
  1682. def on_disconnect(self):
  1683. """If implemented, called when the client disconnects from the broker.
  1684. """
  1685. return self._on_disconnect
  1686. @on_disconnect.setter
  1687. def on_disconnect(self, func):
  1688. """ Define the disconnect callback implementation.
  1689. Expected signature for MQTT v3.1.1 and v3.1 is:
  1690. disconnect_callback(client, userdata, rc)
  1691. and for MQTT v5.0:
  1692. disconnect_callback(client, userdata, reasonCode, properties)
  1693. client: the client instance for this callback
  1694. userdata: the private user data as set in Client() or userdata_set()
  1695. rc: the disconnection result
  1696. The rc parameter indicates the disconnection state. If
  1697. MQTT_ERR_SUCCESS (0), the callback was called in response to
  1698. a disconnect() call. If any other value the disconnection
  1699. was unexpected, such as might be caused by a network error.
  1700. """
  1701. with self._callback_mutex:
  1702. self._on_disconnect = func
  1703. @property
  1704. def on_socket_open(self):
  1705. """If implemented, called just after the socket was opend."""
  1706. return self._on_socket_open
  1707. @on_socket_open.setter
  1708. def on_socket_open(self, func):
  1709. """Define the socket_open callback implementation.
  1710. This should be used to register the socket to an external event loop for reading.
  1711. Expected signature is:
  1712. socket_open_callback(client, userdata, socket)
  1713. client: the client instance for this callback
  1714. userdata: the private user data as set in Client() or userdata_set()
  1715. sock: the socket which was just opened.
  1716. """
  1717. with self._callback_mutex:
  1718. self._on_socket_open = func
  1719. def _call_socket_open(self):
  1720. """Call the socket_open callback with the just-opened socket"""
  1721. with self._callback_mutex:
  1722. if self.on_socket_open:
  1723. with self._in_callback_mutex:
  1724. try:
  1725. self.on_socket_open(self, self._userdata, self._sock)
  1726. except Exception as err:
  1727. self._easy_log(
  1728. MQTT_LOG_ERR, 'Caught exception in on_socket_open: %s', err)
  1729. if not self.suppress_exceptions:
  1730. raise
  1731. @property
  1732. def on_socket_close(self):
  1733. """If implemented, called just before the socket is closed."""
  1734. return self._on_socket_close
  1735. @on_socket_close.setter
  1736. def on_socket_close(self, func):
  1737. """Define the socket_close callback implementation.
  1738. This should be used to unregister the socket from an external event loop for reading.
  1739. Expected signature is:
  1740. socket_close_callback(client, userdata, socket)
  1741. client: the client instance for this callback
  1742. userdata: the private user data as set in Client() or userdata_set()
  1743. sock: the socket which is about to be closed.
  1744. """
  1745. with self._callback_mutex:
  1746. self._on_socket_close = func
  1747. def _call_socket_close(self, sock):
  1748. """Call the socket_close callback with the about-to-be-closed socket"""
  1749. with self._callback_mutex:
  1750. if self.on_socket_close:
  1751. with self._in_callback_mutex:
  1752. try:
  1753. self.on_socket_close(self, self._userdata, sock)
  1754. except Exception as err:
  1755. self._easy_log(
  1756. MQTT_LOG_ERR, 'Caught exception in on_socket_close: %s', err)
  1757. if not self.suppress_exceptions:
  1758. raise
  1759. @property
  1760. def on_socket_register_write(self):
  1761. """If implemented, called when the socket needs writing but can't."""
  1762. return self._on_socket_register_write
  1763. @on_socket_register_write.setter
  1764. def on_socket_register_write(self, func):
  1765. """Define the socket_register_write callback implementation.
  1766. This should be used to register the socket with an external event loop for writing.
  1767. Expected signature is:
  1768. socket_register_write_callback(client, userdata, socket)
  1769. client: the client instance for this callback
  1770. userdata: the private user data as set in Client() or userdata_set()
  1771. sock: the socket which should be registered for writing
  1772. """
  1773. with self._callback_mutex:
  1774. self._on_socket_register_write = func
  1775. def _call_socket_register_write(self):
  1776. """Call the socket_register_write callback with the unwritable socket"""
  1777. if not self._sock or self._registered_write:
  1778. return
  1779. self._registered_write = True
  1780. with self._callback_mutex:
  1781. if self.on_socket_register_write:
  1782. try:
  1783. self.on_socket_register_write(
  1784. self, self._userdata, self._sock)
  1785. except Exception as err:
  1786. self._easy_log(
  1787. MQTT_LOG_ERR, 'Caught exception in on_socket_register_write: %s', err)
  1788. if not self.suppress_exceptions:
  1789. raise
  1790. @property
  1791. def on_socket_unregister_write(self):
  1792. """If implemented, called when the socket doesn't need writing anymore."""
  1793. return self._on_socket_unregister_write
  1794. @on_socket_unregister_write.setter
  1795. def on_socket_unregister_write(self, func):
  1796. """Define the socket_unregister_write callback implementation.
  1797. This should be used to unregister the socket from an external event loop for writing.
  1798. Expected signature is:
  1799. socket_unregister_write_callback(client, userdata, socket)
  1800. client: the client instance for this callback
  1801. userdata: the private user data as set in Client() or userdata_set()
  1802. sock: the socket which should be unregistered for writing
  1803. """
  1804. with self._callback_mutex:
  1805. self._on_socket_unregister_write = func
  1806. def _call_socket_unregister_write(self, sock = None):
  1807. """Call the socket_unregister_write callback with the writable socket"""
  1808. sock = sock or self._sock
  1809. if not sock or not self._registered_write:
  1810. return
  1811. self._registered_write = False
  1812. with self._callback_mutex:
  1813. if self.on_socket_unregister_write:
  1814. try:
  1815. self.on_socket_unregister_write(self, self._userdata, sock)
  1816. except Exception as err:
  1817. self._easy_log(
  1818. MQTT_LOG_ERR, 'Caught exception in on_socket_unregister_write: %s', err)
  1819. if not self.suppress_exceptions:
  1820. raise
  1821. def message_callback_add(self, sub, callback):
  1822. """Register a message callback for a specific topic.
  1823. Messages that match 'sub' will be passed to 'callback'. Any
  1824. non-matching messages will be passed to the default on_message
  1825. callback.
  1826. Call multiple times with different 'sub' to define multiple topic
  1827. specific callbacks.
  1828. Topic specific callbacks may be removed with
  1829. message_callback_remove()."""
  1830. if callback is None or sub is None:
  1831. raise ValueError("sub and callback must both be defined.")
  1832. with self._callback_mutex:
  1833. self._on_message_filtered[sub] = callback
  1834. def message_callback_remove(self, sub):
  1835. """Remove a message callback previously registered with
  1836. message_callback_add()."""
  1837. if sub is None:
  1838. raise ValueError("sub must defined.")
  1839. with self._callback_mutex:
  1840. try:
  1841. del self._on_message_filtered[sub]
  1842. except KeyError: # no such subscription
  1843. pass
  1844. # ============================================================
  1845. # Private functions
  1846. # ============================================================
  1847. def _loop_rc_handle(self, rc, properties = None):
  1848. if rc:
  1849. self._sock_close()
  1850. if self._state == mqtt_cs_disconnecting:
  1851. rc = MQTT_ERR_SUCCESS
  1852. self._do_on_disconnect(rc, properties)
  1853. return rc
  1854. def _packet_read(self):
  1855. # This gets called if pselect() indicates that there is network data
  1856. # available - ie. at least one byte. What we do depends on what data we
  1857. # already have.
  1858. # If we've not got a command, attempt to read one and save it. This should
  1859. # always work because it's only a single byte.
  1860. # Then try to read the remaining length. This may fail because it is may
  1861. # be more than one byte - will need to save data pending next read if it
  1862. # does fail.
  1863. # Then try to read the remaining payload, where 'payload' here means the
  1864. # combined variable header and actual payload. This is the most likely to
  1865. # fail due to longer length, so save current data and current position.
  1866. # After all data is read, send to _mqtt_handle_packet() to deal with.
  1867. # Finally, free the memory and reset everything to starting conditions.
  1868. if self._in_packet['command'] == 0:
  1869. try:
  1870. command = self._sock_recv(1)
  1871. except WouldBlockError:
  1872. return MQTT_ERR_AGAIN
  1873. except socket.error as err:
  1874. self._easy_log(
  1875. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  1876. return 1
  1877. else:
  1878. if len(command) == 0:
  1879. return 1
  1880. command, = struct.unpack("!B", command)
  1881. self._in_packet['command'] = command
  1882. if self._in_packet['have_remaining'] == 0:
  1883. # Read remaining
  1884. # Algorithm for decoding taken from pseudo code at
  1885. # http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm
  1886. while True:
  1887. try:
  1888. byte = self._sock_recv(1)
  1889. except WouldBlockError:
  1890. return MQTT_ERR_AGAIN
  1891. except socket.error as err:
  1892. self._easy_log(
  1893. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  1894. return 1
  1895. else:
  1896. if len(byte) == 0:
  1897. return 1
  1898. byte, = struct.unpack("!B", byte)
  1899. self._in_packet['remaining_count'].append(byte)
  1900. # Max 4 bytes length for remaining length as defined by protocol.
  1901. # Anything more likely means a broken/malicious client.
  1902. if len(self._in_packet['remaining_count']) > 4:
  1903. return MQTT_ERR_PROTOCOL
  1904. self._in_packet['remaining_length'] += (
  1905. byte & 127) * self._in_packet['remaining_mult']
  1906. self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128
  1907. if (byte & 128) == 0:
  1908. break
  1909. self._in_packet['have_remaining'] = 1
  1910. self._in_packet['to_process'] = self._in_packet['remaining_length']
  1911. while self._in_packet['to_process'] > 0:
  1912. try:
  1913. data = self._sock_recv(self._in_packet['to_process'])
  1914. except WouldBlockError:
  1915. return MQTT_ERR_AGAIN
  1916. except socket.error as err:
  1917. self._easy_log(
  1918. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  1919. return 1
  1920. else:
  1921. if len(data) == 0:
  1922. return 1
  1923. self._in_packet['to_process'] -= len(data)
  1924. self._in_packet['packet'] += data
  1925. # All data for this packet is read.
  1926. self._in_packet['pos'] = 0
  1927. rc = self._packet_handle()
  1928. # Free data and reset values
  1929. self._in_packet = {
  1930. 'command': 0,
  1931. 'have_remaining': 0,
  1932. 'remaining_count': [],
  1933. 'remaining_mult': 1,
  1934. 'remaining_length': 0,
  1935. 'packet': b"",
  1936. 'to_process': 0,
  1937. 'pos': 0}
  1938. with self._msgtime_mutex:
  1939. self._last_msg_in = time_func()
  1940. return rc
  1941. def _packet_write(self):
  1942. self._current_out_packet_mutex.acquire()
  1943. while self._current_out_packet:
  1944. packet = self._current_out_packet
  1945. try:
  1946. write_length = self._sock_send(
  1947. packet['packet'][packet['pos']:])
  1948. except (AttributeError, ValueError):
  1949. self._current_out_packet_mutex.release()
  1950. return MQTT_ERR_SUCCESS
  1951. except WouldBlockError:
  1952. self._current_out_packet_mutex.release()
  1953. return MQTT_ERR_AGAIN
  1954. except socket.error as err:
  1955. self._current_out_packet_mutex.release()
  1956. self._easy_log(
  1957. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  1958. return 1
  1959. if write_length > 0:
  1960. packet['to_process'] -= write_length
  1961. packet['pos'] += write_length
  1962. if packet['to_process'] == 0:
  1963. if (packet['command'] & 0xF0) == PUBLISH and packet['qos'] == 0:
  1964. with self._callback_mutex:
  1965. if self.on_publish:
  1966. with self._in_callback_mutex:
  1967. try:
  1968. self.on_publish(
  1969. self, self._userdata, packet['mid'])
  1970. except Exception as err:
  1971. self._easy_log(
  1972. MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err)
  1973. if not self.suppress_exceptions:
  1974. raise
  1975. packet['info']._set_as_published()
  1976. if (packet['command'] & 0xF0) == DISCONNECT:
  1977. self._current_out_packet_mutex.release()
  1978. with self._msgtime_mutex:
  1979. self._last_msg_out = time_func()
  1980. self._do_on_disconnect(0)
  1981. self._sock_close()
  1982. return MQTT_ERR_SUCCESS
  1983. with self._out_packet_mutex:
  1984. if len(self._out_packet) > 0:
  1985. self._current_out_packet = self._out_packet.popleft()
  1986. else:
  1987. self._current_out_packet = None
  1988. else:
  1989. break
  1990. self._current_out_packet_mutex.release()
  1991. with self._msgtime_mutex:
  1992. self._last_msg_out = time_func()
  1993. return MQTT_ERR_SUCCESS
  1994. def _easy_log(self, level, fmt, *args):
  1995. if self.on_log is not None:
  1996. buf = fmt % args
  1997. try:
  1998. self.on_log(self, self._userdata, level, buf)
  1999. except Exception:
  2000. # Can't _easy_log this, as we'll recurse until we break
  2001. pass # self._logger will pick this up, so we're fine
  2002. if self._logger is not None:
  2003. level_std = LOGGING_LEVEL[level]
  2004. self._logger.log(level_std, fmt, *args)
  2005. def _check_keepalive(self):
  2006. if self._keepalive == 0:
  2007. return MQTT_ERR_SUCCESS
  2008. now = time_func()
  2009. with self._msgtime_mutex:
  2010. last_msg_out = self._last_msg_out
  2011. last_msg_in = self._last_msg_in
  2012. if self._sock is not None and (now - last_msg_out >= self._keepalive or now - last_msg_in >= self._keepalive):
  2013. if self._state == mqtt_cs_connected and self._ping_t == 0:
  2014. self._send_pingreq()
  2015. with self._msgtime_mutex:
  2016. self._last_msg_out = now
  2017. self._last_msg_in = now
  2018. else:
  2019. self._sock_close()
  2020. if self._state == mqtt_cs_disconnecting:
  2021. rc = MQTT_ERR_SUCCESS
  2022. else:
  2023. rc = 1
  2024. self._do_on_disconnect(rc)
  2025. def _mid_generate(self):
  2026. with self._mid_generate_mutex:
  2027. self._last_mid += 1
  2028. if self._last_mid == 65536:
  2029. self._last_mid = 1
  2030. return self._last_mid
  2031. @staticmethod
  2032. def _topic_wildcard_len_check(topic):
  2033. # Search for + or # in a topic. Return MQTT_ERR_INVAL if found.
  2034. # Also returns MQTT_ERR_INVAL if the topic string is too long.
  2035. # Returns MQTT_ERR_SUCCESS if everything is fine.
  2036. if b'+' in topic or b'#' in topic or len(topic) > 65535:
  2037. return MQTT_ERR_INVAL
  2038. else:
  2039. return MQTT_ERR_SUCCESS
  2040. @staticmethod
  2041. def _filter_wildcard_len_check(sub):
  2042. if (len(sub) == 0 or len(sub) > 65535
  2043. or any(b'+' in p or b'#' in p for p in sub.split(b'/') if len(p) > 1)
  2044. or b'#/' in sub):
  2045. return MQTT_ERR_INVAL
  2046. else:
  2047. return MQTT_ERR_SUCCESS
  2048. def _send_pingreq(self):
  2049. self._easy_log(MQTT_LOG_DEBUG, "Sending PINGREQ")
  2050. rc = self._send_simple_command(PINGREQ)
  2051. if rc == MQTT_ERR_SUCCESS:
  2052. self._ping_t = time_func()
  2053. return rc
  2054. def _send_pingresp(self):
  2055. self._easy_log(MQTT_LOG_DEBUG, "Sending PINGRESP")
  2056. return self._send_simple_command(PINGRESP)
  2057. def _send_puback(self, mid):
  2058. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBACK (Mid: %d)", mid)
  2059. return self._send_command_with_mid(PUBACK, mid, False)
  2060. def _send_pubcomp(self, mid):
  2061. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBCOMP (Mid: %d)", mid)
  2062. return self._send_command_with_mid(PUBCOMP, mid, False)
  2063. def _pack_remaining_length(self, packet, remaining_length):
  2064. remaining_bytes = []
  2065. while True:
  2066. byte = remaining_length % 128
  2067. remaining_length = remaining_length // 128
  2068. # If there are more digits to encode, set the top bit of this digit
  2069. if remaining_length > 0:
  2070. byte |= 0x80
  2071. remaining_bytes.append(byte)
  2072. packet.append(byte)
  2073. if remaining_length == 0:
  2074. # FIXME - this doesn't deal with incorrectly large payloads
  2075. return packet
  2076. def _pack_str16(self, packet, data):
  2077. if isinstance(data, unicode):
  2078. data = data.encode('utf-8')
  2079. packet.extend(struct.pack("!H", len(data)))
  2080. packet.extend(data)
  2081. def _send_publish(self, mid, topic, payload = b'', qos = 0, retain = False, dup = False, info = None,
  2082. properties = None):
  2083. # we assume that topic and payload are already properly encoded
  2084. assert not isinstance(topic, unicode) and not isinstance(
  2085. payload, unicode) and payload is not None
  2086. if self._sock is None:
  2087. return MQTT_ERR_NO_CONN
  2088. command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain
  2089. packet = bytearray()
  2090. packet.append(command)
  2091. payloadlen = len(payload)
  2092. remaining_length = 2 + len(topic) + payloadlen
  2093. if payloadlen == 0:
  2094. if self._protocol == MQTTv5:
  2095. self._easy_log(
  2096. MQTT_LOG_DEBUG,
  2097. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s (NULL payload)",
  2098. dup, qos, retain, mid, topic, properties
  2099. )
  2100. else:
  2101. self._easy_log(
  2102. MQTT_LOG_DEBUG,
  2103. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s' (NULL payload)",
  2104. dup, qos, retain, mid, topic
  2105. )
  2106. else:
  2107. if self._protocol == MQTTv5:
  2108. self._easy_log(
  2109. MQTT_LOG_DEBUG,
  2110. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)",
  2111. dup, qos, retain, mid, topic, properties, payloadlen
  2112. )
  2113. else:
  2114. self._easy_log(
  2115. MQTT_LOG_DEBUG,
  2116. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)",
  2117. dup, qos, retain, mid, topic, payloadlen
  2118. )
  2119. if qos > 0:
  2120. # For message id
  2121. remaining_length += 2
  2122. if self._protocol == MQTTv5:
  2123. if properties == None:
  2124. packed_properties = b'\x00'
  2125. else:
  2126. packed_properties = properties.pack()
  2127. remaining_length += len(packed_properties)
  2128. self._pack_remaining_length(packet, remaining_length)
  2129. self._pack_str16(packet, topic)
  2130. if qos > 0:
  2131. # For message id
  2132. packet.extend(struct.pack("!H", mid))
  2133. if self._protocol == MQTTv5:
  2134. packet.extend(packed_properties)
  2135. packet.extend(payload)
  2136. return self._packet_queue(PUBLISH, packet, mid, qos, info)
  2137. def _send_pubrec(self, mid):
  2138. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREC (Mid: %d)", mid)
  2139. return self._send_command_with_mid(PUBREC, mid, False)
  2140. def _send_pubrel(self, mid):
  2141. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREL (Mid: %d)", mid)
  2142. return self._send_command_with_mid(PUBREL | 2, mid, False)
  2143. def _send_command_with_mid(self, command, mid, dup):
  2144. # For PUBACK, PUBCOMP, PUBREC, and PUBREL
  2145. if dup:
  2146. command |= 0x8
  2147. remaining_length = 2
  2148. packet = struct.pack('!BBH', command, remaining_length, mid)
  2149. return self._packet_queue(command, packet, mid, 1)
  2150. def _send_simple_command(self, command):
  2151. # For DISCONNECT, PINGREQ and PINGRESP
  2152. remaining_length = 0
  2153. packet = struct.pack('!BB', command, remaining_length)
  2154. return self._packet_queue(command, packet, 0, 0)
  2155. def _send_connect(self, keepalive):
  2156. proto_ver = self._protocol
  2157. # hard-coded UTF-8 encoded string
  2158. protocol = b"MQTT" if proto_ver >= MQTTv311 else b"MQIsdp"
  2159. remaining_length = 2 + len(protocol) + 1 + \
  2160. 1 + 2 + 2 + len(self._client_id)
  2161. connect_flags = 0
  2162. if self._protocol == MQTTv5:
  2163. if self._clean_start == True:
  2164. connect_flags |= 0x02
  2165. elif self._clean_start == MQTT_CLEAN_START_FIRST_ONLY and self._mqttv5_first_connect:
  2166. connect_flags |= 0x02
  2167. elif self._clean_session:
  2168. connect_flags |= 0x02
  2169. if self._will:
  2170. remaining_length += 2 + \
  2171. len(self._will_topic) + 2 + len(self._will_payload)
  2172. connect_flags |= 0x04 | ((self._will_qos & 0x03) << 3) | (
  2173. (self._will_retain & 0x01) << 5)
  2174. if self._username is not None:
  2175. remaining_length += 2 + len(self._username)
  2176. connect_flags |= 0x80
  2177. if self._password is not None:
  2178. connect_flags |= 0x40
  2179. remaining_length += 2 + len(self._password)
  2180. if self._protocol == MQTTv5:
  2181. if self._connect_properties == None:
  2182. packed_connect_properties = b'\x00'
  2183. else:
  2184. packed_connect_properties = self._connect_properties.pack()
  2185. remaining_length += len(packed_connect_properties)
  2186. if self._will:
  2187. if self._will_properties == None:
  2188. packed_will_properties = b'\x00'
  2189. else:
  2190. packed_will_properties = self._will_properties.pack()
  2191. remaining_length += len(packed_will_properties)
  2192. command = CONNECT
  2193. packet = bytearray()
  2194. packet.append(command)
  2195. # as per the mosquitto broker, if the MSB of this version is set
  2196. # to 1, then it treats the connection as a bridge
  2197. if self._client_mode == MQTT_BRIDGE:
  2198. proto_ver |= 0x80
  2199. self._pack_remaining_length(packet, remaining_length)
  2200. packet.extend(struct.pack("!H" + str(len(protocol)) + "sBBH", len(protocol), protocol, proto_ver, connect_flags,
  2201. keepalive))
  2202. if self._protocol == MQTTv5:
  2203. packet += packed_connect_properties
  2204. self._pack_str16(packet, self._client_id)
  2205. if self._will:
  2206. if self._protocol == MQTTv5:
  2207. packet += packed_will_properties
  2208. self._pack_str16(packet, self._will_topic)
  2209. self._pack_str16(packet, self._will_payload)
  2210. if self._username is not None:
  2211. self._pack_str16(packet, self._username)
  2212. if self._password is not None:
  2213. self._pack_str16(packet, self._password)
  2214. self._keepalive = keepalive
  2215. if self._protocol == MQTTv5:
  2216. self._easy_log(
  2217. MQTT_LOG_DEBUG,
  2218. "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%s",
  2219. (connect_flags & 0x80) >> 7,
  2220. (connect_flags & 0x40) >> 6,
  2221. (connect_flags & 0x20) >> 5,
  2222. (connect_flags & 0x18) >> 3,
  2223. (connect_flags & 0x4) >> 2,
  2224. (connect_flags & 0x2) >> 1,
  2225. keepalive,
  2226. self._client_id,
  2227. self._connect_properties
  2228. )
  2229. else:
  2230. self._easy_log(
  2231. MQTT_LOG_DEBUG,
  2232. "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s",
  2233. (connect_flags & 0x80) >> 7,
  2234. (connect_flags & 0x40) >> 6,
  2235. (connect_flags & 0x20) >> 5,
  2236. (connect_flags & 0x18) >> 3,
  2237. (connect_flags & 0x4) >> 2,
  2238. (connect_flags & 0x2) >> 1,
  2239. keepalive,
  2240. self._client_id
  2241. )
  2242. return self._packet_queue(command, packet, 0, 0)
  2243. def _send_disconnect(self, reasoncode = None, properties = None):
  2244. if self._protocol == MQTTv5:
  2245. self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT reasonCode=%s properties=%s",
  2246. reasoncode,
  2247. properties
  2248. )
  2249. else:
  2250. self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT")
  2251. remaining_length = 0
  2252. command = DISCONNECT
  2253. packet = bytearray()
  2254. packet.append(command)
  2255. if self._protocol == MQTTv5:
  2256. if properties != None or reasoncode != None:
  2257. if reasoncode == None:
  2258. reasoncode = ReasonCodes(DISCONNECT >> 4, identifier = 0)
  2259. remaining_length += 1
  2260. if properties != None:
  2261. packed_props = properties.pack()
  2262. remaining_length += len(packed_props)
  2263. self._pack_remaining_length(packet, remaining_length)
  2264. if self._protocol == MQTTv5:
  2265. if reasoncode != None:
  2266. packet += reasoncode.pack()
  2267. if properties != None:
  2268. packet += packed_props
  2269. return self._packet_queue(command, packet, 0, 0)
  2270. def _send_subscribe(self, dup, topics, properties = None):
  2271. remaining_length = 2
  2272. if self._protocol == MQTTv5:
  2273. if properties == None:
  2274. packed_subscribe_properties = b'\x00'
  2275. else:
  2276. packed_subscribe_properties = properties.pack()
  2277. remaining_length += len(packed_subscribe_properties)
  2278. for t, _ in topics:
  2279. remaining_length += 2 + len(t) + 1
  2280. command = SUBSCRIBE | (dup << 3) | 0x2
  2281. packet = bytearray()
  2282. packet.append(command)
  2283. self._pack_remaining_length(packet, remaining_length)
  2284. local_mid = self._mid_generate()
  2285. packet.extend(struct.pack("!H", local_mid))
  2286. if self._protocol == MQTTv5:
  2287. packet += packed_subscribe_properties
  2288. for t, q in topics:
  2289. self._pack_str16(packet, t)
  2290. if self._protocol == MQTTv5:
  2291. packet += q.pack()
  2292. else:
  2293. packet.append(q)
  2294. self._easy_log(
  2295. MQTT_LOG_DEBUG,
  2296. "Sending SUBSCRIBE (d%d, m%d) %s",
  2297. dup,
  2298. local_mid,
  2299. topics,
  2300. )
  2301. return (self._packet_queue(command, packet, local_mid, 1), local_mid)
  2302. def _send_unsubscribe(self, dup, topics, properties = None):
  2303. remaining_length = 2
  2304. if self._protocol == MQTTv5:
  2305. if properties == None:
  2306. packed_unsubscribe_properties = b'\x00'
  2307. else:
  2308. packed_unsubscribe_properties = properties.pack()
  2309. remaining_length += len(packed_unsubscribe_properties)
  2310. for t in topics:
  2311. remaining_length += 2 + len(t)
  2312. command = UNSUBSCRIBE | (dup << 3) | 0x2
  2313. packet = bytearray()
  2314. packet.append(command)
  2315. self._pack_remaining_length(packet, remaining_length)
  2316. local_mid = self._mid_generate()
  2317. packet.extend(struct.pack("!H", local_mid))
  2318. if self._protocol == MQTTv5:
  2319. packet += packed_unsubscribe_properties
  2320. for t in topics:
  2321. self._pack_str16(packet, t)
  2322. # topics_repr = ", ".join("'"+topic.decode('utf8')+"'" for topic in topics)
  2323. if self._protocol == MQTTv5:
  2324. self._easy_log(
  2325. MQTT_LOG_DEBUG,
  2326. "Sending UNSUBSCRIBE (d%d, m%d) %s %s",
  2327. dup,
  2328. local_mid,
  2329. properties,
  2330. topics,
  2331. )
  2332. else:
  2333. self._easy_log(
  2334. MQTT_LOG_DEBUG,
  2335. "Sending UNSUBSCRIBE (d%d, m%d) %s",
  2336. dup,
  2337. local_mid,
  2338. topics,
  2339. )
  2340. return (self._packet_queue(command, packet, local_mid, 1), local_mid)
  2341. def _message_retry_check_actual(self, messages, mutex):
  2342. with mutex:
  2343. now = time_func()
  2344. for m in messages.values():
  2345. if m.timestamp + self._message_retry < now:
  2346. if m.state == mqtt_ms_wait_for_puback or m.state == mqtt_ms_wait_for_pubrec:
  2347. m.timestamp = now
  2348. m.dup = True
  2349. self._send_publish(
  2350. m.mid,
  2351. m.topic.encode('utf-8'),
  2352. m.payload,
  2353. m.qos,
  2354. m.retain,
  2355. m.dup,
  2356. properties = m.properties,
  2357. )
  2358. elif m.state == mqtt_ms_wait_for_pubrel:
  2359. m.timestamp = now
  2360. self._send_pubrec(m.mid)
  2361. elif m.state == mqtt_ms_wait_for_pubcomp:
  2362. m.timestamp = now
  2363. self._send_pubrel(m.mid)
  2364. def _message_retry_check(self):
  2365. self._message_retry_check_actual(
  2366. self._out_messages, self._out_message_mutex)
  2367. self._message_retry_check_actual(
  2368. self._in_messages, self._in_message_mutex)
  2369. def _check_clean_session(self):
  2370. if self._protocol == MQTTv5:
  2371. if self._clean_start == MQTT_CLEAN_START_FIRST_ONLY:
  2372. return self._mqttv5_first_connect
  2373. else:
  2374. return self._clean_start
  2375. else:
  2376. return self._clean_session
  2377. def _messages_reconnect_reset_out(self):
  2378. with self._out_message_mutex:
  2379. self._inflight_messages = 0
  2380. for m in self._out_messages.values():
  2381. m.timestamp = 0
  2382. if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
  2383. if m.qos == 0:
  2384. m.state = mqtt_ms_publish
  2385. elif m.qos == 1:
  2386. # self._inflight_messages = self._inflight_messages + 1
  2387. if m.state == mqtt_ms_wait_for_puback:
  2388. m.dup = True
  2389. m.state = mqtt_ms_publish
  2390. elif m.qos == 2:
  2391. # self._inflight_messages = self._inflight_messages + 1
  2392. if self._check_clean_session():
  2393. if m.state != mqtt_ms_publish:
  2394. m.dup = True
  2395. m.state = mqtt_ms_publish
  2396. else:
  2397. if m.state == mqtt_ms_wait_for_pubcomp:
  2398. m.state = mqtt_ms_resend_pubrel
  2399. else:
  2400. if m.state == mqtt_ms_wait_for_pubrec:
  2401. m.dup = True
  2402. m.state = mqtt_ms_publish
  2403. else:
  2404. m.state = mqtt_ms_queued
  2405. def _messages_reconnect_reset_in(self):
  2406. with self._in_message_mutex:
  2407. if self._check_clean_session():
  2408. self._in_messages = collections.OrderedDict()
  2409. return
  2410. for m in self._in_messages.values():
  2411. m.timestamp = 0
  2412. if m.qos != 2:
  2413. self._in_messages.pop(m.mid)
  2414. else:
  2415. # Preserve current state
  2416. pass
  2417. def _messages_reconnect_reset(self):
  2418. self._messages_reconnect_reset_out()
  2419. self._messages_reconnect_reset_in()
  2420. def _packet_queue(self, command, packet, mid, qos, info = None):
  2421. mpkt = {
  2422. 'command': command,
  2423. 'mid': mid,
  2424. 'qos': qos,
  2425. 'pos': 0,
  2426. 'to_process': len(packet),
  2427. 'packet': packet,
  2428. 'info': info}
  2429. with self._out_packet_mutex:
  2430. self._out_packet.append(mpkt)
  2431. if self._current_out_packet_mutex.acquire(False):
  2432. if self._current_out_packet is None and len(self._out_packet) > 0:
  2433. self._current_out_packet = self._out_packet.popleft()
  2434. self._current_out_packet_mutex.release()
  2435. # Write a single byte to sockpairW (connected to sockpairR) to break
  2436. # out of select() if in threaded mode.
  2437. try:
  2438. self._sockpairW.send(sockpair_data)
  2439. except socket.error as err:
  2440. if err.errno != EAGAIN:
  2441. raise
  2442. if self._thread is None:
  2443. if self._in_callback_mutex.acquire(False):
  2444. self._in_callback_mutex.release()
  2445. return self.loop_write()
  2446. self._call_socket_register_write()
  2447. return MQTT_ERR_SUCCESS
  2448. def _packet_handle(self):
  2449. cmd = self._in_packet['command'] & 0xF0
  2450. if cmd == PINGREQ:
  2451. return self._handle_pingreq()
  2452. elif cmd == PINGRESP:
  2453. return self._handle_pingresp()
  2454. elif cmd == PUBACK:
  2455. return self._handle_pubackcomp("PUBACK")
  2456. elif cmd == PUBCOMP:
  2457. return self._handle_pubackcomp("PUBCOMP")
  2458. elif cmd == PUBLISH:
  2459. return self._handle_publish()
  2460. elif cmd == PUBREC:
  2461. return self._handle_pubrec()
  2462. elif cmd == PUBREL:
  2463. return self._handle_pubrel()
  2464. elif cmd == CONNACK:
  2465. return self._handle_connack()
  2466. elif cmd == SUBACK:
  2467. return self._handle_suback()
  2468. elif cmd == UNSUBACK:
  2469. return self._handle_unsuback()
  2470. elif cmd == DISCONNECT and self._protocol == MQTTv5: # only allowed in MQTT 5.0
  2471. return self._handle_disconnect()
  2472. else:
  2473. # If we don't recognise the command, return an error straight away.
  2474. self._easy_log(MQTT_LOG_ERR, "Error: Unrecognised command %s", cmd)
  2475. return MQTT_ERR_PROTOCOL
  2476. def _handle_pingreq(self):
  2477. if self._in_packet['remaining_length'] != 0:
  2478. return MQTT_ERR_PROTOCOL
  2479. self._easy_log(MQTT_LOG_DEBUG, "Received PINGREQ")
  2480. return self._send_pingresp()
  2481. def _handle_pingresp(self):
  2482. if self._in_packet['remaining_length'] != 0:
  2483. return MQTT_ERR_PROTOCOL
  2484. # No longer waiting for a PINGRESP.
  2485. self._ping_t = 0
  2486. self._easy_log(MQTT_LOG_DEBUG, "Received PINGRESP")
  2487. return MQTT_ERR_SUCCESS
  2488. def _handle_connack(self):
  2489. if self._protocol == MQTTv5:
  2490. self._easy_log(
  2491. MQTT_LOG_DEBUG,
  2492. "Received CONNACK, but not invalid protocol = %d",
  2493. MQTT_ERR_PROTOCOL
  2494. )
  2495. if self._in_packet['remaining_length'] < 2:
  2496. return MQTT_ERR_PROTOCOL
  2497. elif self._in_packet['remaining_length'] != 2:
  2498. self._easy_log(
  2499. MQTT_LOG_DEBUG,
  2500. "Received CONNACK, but not invalid protocol = %d",
  2501. MQTT_ERR_PROTOCOL
  2502. )
  2503. return MQTT_ERR_PROTOCOL
  2504. if self._protocol == MQTTv5:
  2505. (flags, result) = struct.unpack(
  2506. "!BB", self._in_packet['packet'][:2])
  2507. reason = ReasonCodes(CONNACK >> 4, identifier = result)
  2508. properties = Properties(CONNACK >> 4)
  2509. properties.unpack(self._in_packet['packet'][2:])
  2510. else:
  2511. (flags, result) = struct.unpack("!BB", self._in_packet['packet'])
  2512. if self._protocol == MQTTv311:
  2513. if result == CONNACK_REFUSED_PROTOCOL_VERSION:
  2514. self._easy_log(
  2515. MQTT_LOG_DEBUG,
  2516. "Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.",
  2517. flags, result
  2518. )
  2519. # Downgrade to MQTT v3.1
  2520. self._protocol = MQTTv31
  2521. return self.reconnect()
  2522. elif (result == CONNACK_REFUSED_IDENTIFIER_REJECTED
  2523. and self._client_id == b''):
  2524. self._easy_log(
  2525. MQTT_LOG_DEBUG,
  2526. "Received CONNACK (%s, %s), attempting to use non-empty CID",
  2527. flags, result,
  2528. )
  2529. self._client_id = base62(uuid.uuid4().int, padding = 22)
  2530. return self.reconnect()
  2531. if result == 0:
  2532. self._state = mqtt_cs_connected
  2533. self._reconnect_delay = None
  2534. if self._protocol == MQTTv5:
  2535. self._easy_log(
  2536. MQTT_LOG_DEBUG, "Received CONNACK (%s, %s) properties=%s", flags, reason, properties)
  2537. else:
  2538. self._easy_log(
  2539. MQTT_LOG_DEBUG, "Received CONNACK (%s, %s)", flags, result)
  2540. # it won't be the first successful connect any more
  2541. self._mqttv5_first_connect = False
  2542. with self._callback_mutex:
  2543. if self.on_connect:
  2544. flags_dict = {}
  2545. flags_dict['session present'] = flags & 0x01
  2546. with self._in_callback_mutex:
  2547. try:
  2548. if self._protocol == MQTTv5:
  2549. self.on_connect(self, self._userdata,
  2550. flags_dict, reason, properties)
  2551. else:
  2552. self.on_connect(
  2553. self, self._userdata, flags_dict, result)
  2554. except Exception as err:
  2555. self._easy_log(
  2556. MQTT_LOG_ERR, 'Caught exception in on_connect: %s', err)
  2557. if not self.suppress_exceptions:
  2558. raise
  2559. if result == 0:
  2560. rc = 0
  2561. with self._out_message_mutex:
  2562. for m in self._out_messages.values():
  2563. m.timestamp = time_func()
  2564. if m.state == mqtt_ms_queued:
  2565. self.loop_write() # Process outgoing messages that have just been queued up
  2566. return MQTT_ERR_SUCCESS
  2567. if m.qos == 0:
  2568. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  2569. rc = self._send_publish(
  2570. m.mid,
  2571. m.topic.encode('utf-8'),
  2572. m.payload,
  2573. m.qos,
  2574. m.retain,
  2575. m.dup,
  2576. properties = m.properties
  2577. )
  2578. if rc != 0:
  2579. return rc
  2580. elif m.qos == 1:
  2581. if m.state == mqtt_ms_publish:
  2582. self._inflight_messages += 1
  2583. m.state = mqtt_ms_wait_for_puback
  2584. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  2585. rc = self._send_publish(
  2586. m.mid,
  2587. m.topic.encode('utf-8'),
  2588. m.payload,
  2589. m.qos,
  2590. m.retain,
  2591. m.dup,
  2592. properties = m.properties
  2593. )
  2594. if rc != 0:
  2595. return rc
  2596. elif m.qos == 2:
  2597. if m.state == mqtt_ms_publish:
  2598. self._inflight_messages += 1
  2599. m.state = mqtt_ms_wait_for_pubrec
  2600. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  2601. rc = self._send_publish(
  2602. m.mid,
  2603. m.topic.encode('utf-8'),
  2604. m.payload,
  2605. m.qos,
  2606. m.retain,
  2607. m.dup,
  2608. properties = m.properties
  2609. )
  2610. if rc != 0:
  2611. return rc
  2612. elif m.state == mqtt_ms_resend_pubrel:
  2613. self._inflight_messages += 1
  2614. m.state = mqtt_ms_wait_for_pubcomp
  2615. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  2616. rc = self._send_pubrel(m.mid)
  2617. if rc != 0:
  2618. return rc
  2619. self.loop_write() # Process outgoing messages that have just been queued up
  2620. return rc
  2621. elif result > 0 and result < 6:
  2622. return MQTT_ERR_CONN_REFUSED
  2623. else:
  2624. return MQTT_ERR_PROTOCOL
  2625. def _handle_disconnect(self):
  2626. packet_type = DISCONNECT >> 4
  2627. reasonCode = properties = None
  2628. if self._in_packet['remaining_length'] > 2:
  2629. reasonCode = ReasonCodes(packet_type)
  2630. reasonCode.unpack(self._in_packet['packet'])
  2631. if self._in_packet['remaining_length'] > 3:
  2632. properties = Properties(packet_type)
  2633. props, props_len = properties.unpack(
  2634. self._in_packet['packet'][1:])
  2635. self._easy_log(MQTT_LOG_DEBUG, "Received DISCONNECT %s %s",
  2636. reasonCode,
  2637. properties
  2638. )
  2639. self._loop_rc_handle(reasonCode, properties)
  2640. return MQTT_ERR_SUCCESS
  2641. def _handle_suback(self):
  2642. self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK")
  2643. pack_format = "!H" + str(len(self._in_packet['packet']) - 2) + 's'
  2644. (mid, packet) = struct.unpack(pack_format, self._in_packet['packet'])
  2645. if self._protocol == MQTTv5:
  2646. properties = Properties(SUBACK >> 4)
  2647. props, props_len = properties.unpack(packet)
  2648. reasoncodes = []
  2649. for c in packet[props_len:]:
  2650. if sys.version_info[0] < 3:
  2651. c = ord(c)
  2652. reasoncodes.append(ReasonCodes(SUBACK >> 4, identifier = c))
  2653. else:
  2654. pack_format = "!" + "B" * len(packet)
  2655. granted_qos = struct.unpack(pack_format, packet)
  2656. with self._callback_mutex:
  2657. if self.on_subscribe:
  2658. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  2659. try:
  2660. if self._protocol == MQTTv5:
  2661. self.on_subscribe(
  2662. self, self._userdata, mid, reasoncodes, properties)
  2663. else:
  2664. self.on_subscribe(
  2665. self, self._userdata, mid, granted_qos)
  2666. except Exception as err:
  2667. self._easy_log(
  2668. MQTT_LOG_ERR, 'Caught exception in on_subscribe: %s', err)
  2669. if not self.suppress_exceptions:
  2670. raise
  2671. return MQTT_ERR_SUCCESS
  2672. def _handle_publish(self):
  2673. rc = 0
  2674. header = self._in_packet['command']
  2675. message = MQTTMessage()
  2676. message.dup = (header & 0x08) >> 3
  2677. message.qos = (header & 0x06) >> 1
  2678. message.retain = (header & 0x01)
  2679. pack_format = "!H" + str(len(self._in_packet['packet']) - 2) + 's'
  2680. (slen, packet) = struct.unpack(pack_format, self._in_packet['packet'])
  2681. pack_format = '!' + str(slen) + 's' + str(len(packet) - slen) + 's'
  2682. (topic, packet) = struct.unpack(pack_format, packet)
  2683. if self._protocol != MQTTv5 and len(topic) == 0:
  2684. return MQTT_ERR_PROTOCOL
  2685. # Handle topics with invalid UTF-8
  2686. # This replaces an invalid topic with a message and the hex
  2687. # representation of the topic for logging. When the user attempts to
  2688. # access message.topic in the callback, an exception will be raised.
  2689. try:
  2690. print_topic = topic.decode('utf-8')
  2691. except UnicodeDecodeError:
  2692. print_topic = "TOPIC WITH INVALID UTF-8: " + str(topic)
  2693. message.topic = topic
  2694. if message.qos > 0:
  2695. pack_format = "!H" + str(len(packet) - 2) + 's'
  2696. (message.mid, packet) = struct.unpack(pack_format, packet)
  2697. if self._protocol == MQTTv5:
  2698. message.properties = Properties(PUBLISH >> 4)
  2699. props, props_len = message.properties.unpack(packet)
  2700. packet = packet[props_len:]
  2701. message.payload = packet
  2702. if self._protocol == MQTTv5:
  2703. self._easy_log(
  2704. MQTT_LOG_DEBUG,
  2705. "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)",
  2706. message.dup, message.qos, message.retain, message.mid,
  2707. print_topic, message.properties, len(message.payload)
  2708. )
  2709. else:
  2710. self._easy_log(
  2711. MQTT_LOG_DEBUG,
  2712. "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)",
  2713. message.dup, message.qos, message.retain, message.mid,
  2714. print_topic, len(message.payload)
  2715. )
  2716. message.timestamp = time_func()
  2717. if message.qos == 0:
  2718. self._handle_on_message(message)
  2719. return MQTT_ERR_SUCCESS
  2720. elif message.qos == 1:
  2721. rc = self._send_puback(message.mid)
  2722. self._handle_on_message(message)
  2723. return rc
  2724. elif message.qos == 2:
  2725. rc = self._send_pubrec(message.mid)
  2726. message.state = mqtt_ms_wait_for_pubrel
  2727. with self._in_message_mutex:
  2728. self._in_messages[message.mid] = message
  2729. return rc
  2730. else:
  2731. return MQTT_ERR_PROTOCOL
  2732. def _handle_pubrel(self):
  2733. if self._protocol == MQTTv5:
  2734. if self._in_packet['remaining_length'] < 2:
  2735. return MQTT_ERR_PROTOCOL
  2736. elif self._in_packet['remaining_length'] != 2:
  2737. return MQTT_ERR_PROTOCOL
  2738. mid, = struct.unpack("!H", self._in_packet['packet'])
  2739. self._easy_log(MQTT_LOG_DEBUG, "Received PUBREL (Mid: %d)", mid)
  2740. with self._in_message_mutex:
  2741. if mid in self._in_messages:
  2742. # Only pass the message on if we have removed it from the queue - this
  2743. # prevents multiple callbacks for the same message.
  2744. message = self._in_messages.pop(mid)
  2745. self._handle_on_message(message)
  2746. self._inflight_messages -= 1
  2747. if self._max_inflight_messages > 0:
  2748. with self._out_message_mutex:
  2749. rc = self._update_inflight()
  2750. if rc != MQTT_ERR_SUCCESS:
  2751. return rc
  2752. # FIXME: this should only be done if the message is known
  2753. # If unknown it's a protocol error and we should close the connection.
  2754. # But since we don't have (on disk) persistence for the session, it
  2755. # is possible that we must known about this message.
  2756. # Choose to acknwoledge this messsage (and thus losing a message) but
  2757. # avoid hanging. See #284.
  2758. return self._send_pubcomp(mid)
  2759. def _update_inflight(self):
  2760. # Dont lock message_mutex here
  2761. for m in self._out_messages.values():
  2762. if self._inflight_messages < self._max_inflight_messages:
  2763. if m.qos > 0 and m.state == mqtt_ms_queued:
  2764. self._inflight_messages += 1
  2765. if m.qos == 1:
  2766. m.state = mqtt_ms_wait_for_puback
  2767. elif m.qos == 2:
  2768. m.state = mqtt_ms_wait_for_pubrec
  2769. rc = self._send_publish(
  2770. m.mid,
  2771. m.topic.encode('utf-8'),
  2772. m.payload,
  2773. m.qos,
  2774. m.retain,
  2775. m.dup,
  2776. properties = m.properties,
  2777. )
  2778. if rc != 0:
  2779. return rc
  2780. else:
  2781. return MQTT_ERR_SUCCESS
  2782. return MQTT_ERR_SUCCESS
  2783. def _handle_pubrec(self):
  2784. if self._protocol == MQTTv5:
  2785. if self._in_packet['remaining_length'] < 2:
  2786. return MQTT_ERR_PROTOCOL
  2787. elif self._in_packet['remaining_length'] != 2:
  2788. return MQTT_ERR_PROTOCOL
  2789. mid, = struct.unpack("!H", self._in_packet['packet'][:2])
  2790. if self._protocol == MQTTv5:
  2791. if self._in_packet['remaining_length'] > 2:
  2792. reasonCode = ReasonCodes(PUBREC >> 4)
  2793. reasonCode.unpack(self._in_packet['packet'][2:])
  2794. if self._in_packet['remaining_length'] > 3:
  2795. properties = Properties(PUBREC >> 4)
  2796. props, props_len = properties.unpack(
  2797. self._in_packet['packet'][3:])
  2798. self._easy_log(MQTT_LOG_DEBUG, "Received PUBREC (Mid: %d)", mid)
  2799. with self._out_message_mutex:
  2800. if mid in self._out_messages:
  2801. msg = self._out_messages[mid]
  2802. msg.state = mqtt_ms_wait_for_pubcomp
  2803. msg.timestamp = time_func()
  2804. return self._send_pubrel(mid)
  2805. return MQTT_ERR_SUCCESS
  2806. def _handle_unsuback(self):
  2807. if self._protocol == MQTTv5:
  2808. if self._in_packet['remaining_length'] < 4:
  2809. return MQTT_ERR_PROTOCOL
  2810. elif self._in_packet['remaining_length'] != 2:
  2811. return MQTT_ERR_PROTOCOL
  2812. mid, = struct.unpack("!H", self._in_packet['packet'][:2])
  2813. if self._protocol == MQTTv5:
  2814. packet = self._in_packet['packet'][2:]
  2815. properties = Properties(UNSUBACK >> 4)
  2816. props, props_len = properties.unpack(packet)
  2817. reasoncodes = []
  2818. for c in packet[props_len:]:
  2819. if sys.version_info[0] < 3:
  2820. c = ord(c)
  2821. reasoncodes.append(ReasonCodes(UNSUBACK >> 4, identifier = c))
  2822. if len(reasoncodes) == 1:
  2823. reasoncodes = reasoncodes[0]
  2824. self._easy_log(MQTT_LOG_DEBUG, "Received UNSUBACK (Mid: %d)", mid)
  2825. with self._callback_mutex:
  2826. if self.on_unsubscribe:
  2827. with self._in_callback_mutex:
  2828. try:
  2829. if self._protocol == MQTTv5:
  2830. self.on_unsubscribe(
  2831. self, self._userdata, mid, properties, reasoncodes)
  2832. else:
  2833. self.on_unsubscribe(self, self._userdata, mid)
  2834. except Exception as err:
  2835. self._easy_log(
  2836. MQTT_LOG_ERR, 'Caught exception in on_unsubscribe: %s', err)
  2837. if not self.suppress_exceptions:
  2838. raise
  2839. return MQTT_ERR_SUCCESS
  2840. def _do_on_disconnect(self, rc, properties = None):
  2841. with self._callback_mutex:
  2842. if self.on_disconnect:
  2843. with self._in_callback_mutex:
  2844. try:
  2845. if properties:
  2846. self.on_disconnect(
  2847. self, self._userdata, rc, properties)
  2848. else:
  2849. self.on_disconnect(self, self._userdata, rc)
  2850. except Exception as err:
  2851. self._easy_log(
  2852. MQTT_LOG_ERR, 'Caught exception in on_disconnect: %s', err)
  2853. if not self.suppress_exceptions:
  2854. raise
  2855. def _do_on_publish(self, mid):
  2856. with self._callback_mutex:
  2857. if self.on_publish:
  2858. with self._in_callback_mutex:
  2859. try:
  2860. self.on_publish(self, self._userdata, mid)
  2861. except Exception as err:
  2862. self._easy_log(
  2863. MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err)
  2864. if not self.suppress_exceptions:
  2865. raise
  2866. msg = self._out_messages.pop(mid)
  2867. msg.info._set_as_published()
  2868. if msg.qos > 0:
  2869. self._inflight_messages -= 1
  2870. if self._max_inflight_messages > 0:
  2871. rc = self._update_inflight()
  2872. if rc != MQTT_ERR_SUCCESS:
  2873. return rc
  2874. return MQTT_ERR_SUCCESS
  2875. def _handle_pubackcomp(self, cmd):
  2876. if self._protocol == MQTTv5:
  2877. if self._in_packet['remaining_length'] < 2:
  2878. return MQTT_ERR_PROTOCOL
  2879. elif self._in_packet['remaining_length'] != 2:
  2880. return MQTT_ERR_PROTOCOL
  2881. packet_type = PUBACK if cmd == "PUBACK" else PUBCOMP
  2882. packet_type = packet_type >> 4
  2883. mid, = struct.unpack("!H", self._in_packet['packet'][:2])
  2884. if self._protocol == MQTTv5:
  2885. if self._in_packet['remaining_length'] > 2:
  2886. reasonCode = ReasonCodes(packet_type)
  2887. reasonCode.unpack(self._in_packet['packet'][2:])
  2888. if self._in_packet['remaining_length'] > 3:
  2889. properties = Properties(packet_type)
  2890. props, props_len = properties.unpack(
  2891. self._in_packet['packet'][3:])
  2892. self._easy_log(MQTT_LOG_DEBUG, "Received %s (Mid: %d)", cmd, mid)
  2893. with self._out_message_mutex:
  2894. if mid in self._out_messages:
  2895. # Only inform the client the message has been sent once.
  2896. rc = self._do_on_publish(mid)
  2897. return rc
  2898. return MQTT_ERR_SUCCESS
  2899. def _handle_on_message(self, message):
  2900. matched = False
  2901. with self._callback_mutex:
  2902. try:
  2903. topic = message.topic
  2904. except UnicodeDecodeError:
  2905. topic = None
  2906. if topic is not None:
  2907. for callback in self._on_message_filtered.iter_match(message.topic):
  2908. with self._in_callback_mutex:
  2909. try:
  2910. callback(self, self._userdata, message)
  2911. except Exception as err:
  2912. self._easy_log(
  2913. MQTT_LOG_ERR,
  2914. 'Caught exception in user defined callback function %s: %s',
  2915. callback.__name__,
  2916. err
  2917. )
  2918. if not self.suppress_exceptions:
  2919. raise
  2920. matched = True
  2921. if matched == False and self.on_message:
  2922. with self._in_callback_mutex:
  2923. try:
  2924. self.on_message(self, self._userdata, message)
  2925. except Exception as err:
  2926. self._easy_log(
  2927. MQTT_LOG_ERR, 'Caught exception in on_message: %s', err)
  2928. if not self.suppress_exceptions:
  2929. raise
  2930. def _thread_main(self):
  2931. self.loop_forever(retry_first_connection = True)
  2932. def _reconnect_wait(self):
  2933. # See reconnect_delay_set for details
  2934. now = time_func()
  2935. with self._reconnect_delay_mutex:
  2936. if self._reconnect_delay is None:
  2937. self._reconnect_delay = self._reconnect_min_delay
  2938. else:
  2939. self._reconnect_delay = min(
  2940. self._reconnect_delay * 2,
  2941. self._reconnect_max_delay,
  2942. )
  2943. target_time = now + self._reconnect_delay
  2944. remaining = target_time - now
  2945. while (self._state != mqtt_cs_disconnecting
  2946. and not self._thread_terminate
  2947. and remaining > 0):
  2948. time.sleep(min(remaining, 1))
  2949. remaining = target_time - time_func()
  2950. @staticmethod
  2951. def _proxy_is_valid(p):
  2952. def check(t, a):
  2953. return (socks is not None and
  2954. t in set([socks.HTTP, socks.SOCKS4, socks.SOCKS5]) and a)
  2955. if isinstance(p, dict):
  2956. return check(p.get("proxy_type"), p.get("proxy_addr"))
  2957. elif isinstance(p, (list, tuple)):
  2958. return len(p) == 6 and check(p[0], p[1])
  2959. else:
  2960. return False
  2961. def _get_proxy(self):
  2962. if socks is None:
  2963. return None
  2964. # First, check if the user explicitly passed us a proxy to use
  2965. if self._proxy_is_valid(self._proxy):
  2966. return self._proxy
  2967. # Next, check for an mqtt_proxy environment variable as long as the host
  2968. # we're trying to connect to isn't listed under the no_proxy environment
  2969. # variable (matches built-in module urllib's behavior)
  2970. if not (hasattr(urllib_dot_request, "proxy_bypass") and
  2971. urllib_dot_request.proxy_bypass(self._host)):
  2972. env_proxies = urllib_dot_request.getproxies()
  2973. if "mqtt" in env_proxies:
  2974. parts = urllib_dot_parse.urlparse(env_proxies["mqtt"])
  2975. if parts.scheme == "http":
  2976. proxy = {
  2977. "proxy_type": socks.HTTP,
  2978. "proxy_addr": parts.hostname,
  2979. "proxy_port": parts.port
  2980. }
  2981. return proxy
  2982. elif parts.scheme == "socks":
  2983. proxy = {
  2984. "proxy_type": socks.SOCKS5,
  2985. "proxy_addr": parts.hostname,
  2986. "proxy_port": parts.port
  2987. }
  2988. return proxy
  2989. # Finally, check if the user has monkeypatched the PySocks library with
  2990. # a default proxy
  2991. socks_default = socks.get_default_proxy()
  2992. if self._proxy_is_valid(socks_default):
  2993. proxy_keys = ("proxy_type", "proxy_addr", "proxy_port",
  2994. "proxy_rdns", "proxy_username", "proxy_password")
  2995. return dict(zip(proxy_keys, socks_default))
  2996. # If we didn't find a proxy through any of the above methods, return
  2997. # None to indicate that the connection should be handled normally
  2998. return None
  2999. def _create_socket_connection(self):
  3000. proxy = self._get_proxy()
  3001. addr = (self._host, self._port)
  3002. source = (self._bind_address, self._bind_port)
  3003. if sys.version_info < (2, 7) or (3, 0) < sys.version_info < (3, 2):
  3004. # Have to short-circuit here because of unsupported source_address
  3005. # param in earlier Python versions.
  3006. return socket.create_connection(addr, timeout = self._keepalive)
  3007. if proxy:
  3008. return socks.create_connection(addr, source_address = source, timeout = self._keepalive, **proxy)
  3009. else:
  3010. return socket.create_connection(addr, source_address = source, timeout = self._keepalive)
  3011. # Compatibility class for easy porting from mosquitto.py.
  3012. class Mosquitto(Client):
  3013. def __init__(self, client_id = "", clean_session = True, userdata = None):
  3014. super(Mosquitto, self).__init__(client_id, clean_session, userdata)
  3015. class WebsocketWrapper(object):
  3016. OPCODE_CONTINUATION = 0x0
  3017. OPCODE_TEXT = 0x1
  3018. OPCODE_BINARY = 0x2
  3019. OPCODE_CONNCLOSE = 0x8
  3020. OPCODE_PING = 0x9
  3021. OPCODE_PONG = 0xa
  3022. def __init__(self, socket, host, port, is_ssl, path, extra_headers):
  3023. self.connected = False
  3024. self._ssl = is_ssl
  3025. self._host = host
  3026. self._port = port
  3027. self._socket = socket
  3028. self._path = path
  3029. self._sendbuffer = bytearray()
  3030. self._readbuffer = bytearray()
  3031. self._requested_size = 0
  3032. self._payload_head = 0
  3033. self._readbuffer_head = 0
  3034. self._do_handshake(extra_headers)
  3035. def __del__(self):
  3036. self._sendbuffer = None
  3037. self._readbuffer = None
  3038. def _do_handshake(self, extra_headers):
  3039. sec_websocket_key = uuid.uuid4().bytes
  3040. sec_websocket_key = base64.b64encode(sec_websocket_key)
  3041. websocket_headers = {
  3042. "Host": "{self._host:s}:{self._port:d}".format(self = self),
  3043. "Upgrade": "websocket",
  3044. "Connection": "Upgrade",
  3045. "Origin": "https://{self._host:s}:{self._port:d}".format(self = self),
  3046. "Sec-WebSocket-Key": sec_websocket_key.decode("utf8"),
  3047. "Sec-Websocket-Version": "13",
  3048. "Sec-Websocket-Protocol": "mqtt",
  3049. }
  3050. # This is checked in ws_set_options so it will either be None, a
  3051. # dictionary, or a callable
  3052. if isinstance(extra_headers, dict):
  3053. websocket_headers.update(extra_headers)
  3054. elif callable(extra_headers):
  3055. websocket_headers = extra_headers(websocket_headers)
  3056. header = "\r\n".join([
  3057. "GET {self._path} HTTP/1.1".format(self = self),
  3058. "\r\n".join("{}: {}".format(i, j)
  3059. for i, j in websocket_headers.items()),
  3060. "\r\n",
  3061. ]).encode("utf8")
  3062. self._socket.send(header)
  3063. has_secret = False
  3064. has_upgrade = False
  3065. while True:
  3066. # read HTTP response header as lines
  3067. byte = self._socket.recv(1)
  3068. self._readbuffer.extend(byte)
  3069. # line end
  3070. if byte == b"\n":
  3071. if len(self._readbuffer) > 2:
  3072. # check upgrade
  3073. if b"connection" in str(self._readbuffer).lower().encode('utf-8'):
  3074. if b"upgrade" not in str(self._readbuffer).lower().encode('utf-8'):
  3075. raise WebsocketConnectionError(
  3076. "WebSocket handshake error, connection not upgraded")
  3077. else:
  3078. has_upgrade = True
  3079. # check key hash
  3080. if b"sec-websocket-accept" in str(self._readbuffer).lower().encode('utf-8'):
  3081. GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  3082. server_hash = self._readbuffer.decode(
  3083. 'utf-8').split(": ", 1)[1]
  3084. server_hash = server_hash.strip().encode('utf-8')
  3085. client_hash = sec_websocket_key.decode('utf-8') + GUID
  3086. client_hash = hashlib.sha1(client_hash.encode('utf-8'))
  3087. client_hash = base64.b64encode(client_hash.digest())
  3088. if server_hash != client_hash:
  3089. raise WebsocketConnectionError(
  3090. "WebSocket handshake error, invalid secret key")
  3091. else:
  3092. has_secret = True
  3093. else:
  3094. # ending linebreak
  3095. break
  3096. # reset linebuffer
  3097. self._readbuffer = bytearray()
  3098. # connection reset
  3099. elif not byte:
  3100. raise WebsocketConnectionError("WebSocket handshake error")
  3101. if not has_upgrade or not has_secret:
  3102. raise WebsocketConnectionError("WebSocket handshake error")
  3103. self._readbuffer = bytearray()
  3104. self.connected = True
  3105. def _create_frame(self, opcode, data, do_masking = 1):
  3106. header = bytearray()
  3107. length = len(data)
  3108. mask_key = bytearray(os.urandom(4))
  3109. mask_flag = do_masking
  3110. # 1 << 7 is the final flag, we don't send continuated data
  3111. header.append(1 << 7 | opcode)
  3112. if length < 126:
  3113. header.append(mask_flag << 7 | length)
  3114. elif length < 65536:
  3115. header.append(mask_flag << 7 | 126)
  3116. header += struct.pack("!H", length)
  3117. elif length < 0x8000000000000001:
  3118. header.append(mask_flag << 7 | 127)
  3119. header += struct.pack("!Q", length)
  3120. else:
  3121. raise ValueError("Maximum payload size is 2^63")
  3122. if mask_flag == 1:
  3123. for index in range(length):
  3124. data[index] ^= mask_key[index % 4]
  3125. data = mask_key + data
  3126. return header + data
  3127. def _buffered_read(self, length):
  3128. # try to recv and strore needed bytes
  3129. wanted_bytes = length - (len(self._readbuffer) - self._readbuffer_head)
  3130. if wanted_bytes > 0:
  3131. data = self._socket.recv(wanted_bytes)
  3132. if not data:
  3133. raise socket.error(errno.ECONNABORTED, 0)
  3134. else:
  3135. self._readbuffer.extend(data)
  3136. if len(data) < wanted_bytes:
  3137. raise socket.error(EAGAIN, 0)
  3138. self._readbuffer_head += length
  3139. return self._readbuffer[self._readbuffer_head - length:self._readbuffer_head]
  3140. def _recv_impl(self, length):
  3141. # try to decode websocket payload part from data
  3142. try:
  3143. self._readbuffer_head = 0
  3144. result = None
  3145. chunk_startindex = self._payload_head
  3146. chunk_endindex = self._payload_head + length
  3147. header1 = self._buffered_read(1)
  3148. header2 = self._buffered_read(1)
  3149. opcode = (header1[0] & 0x0f)
  3150. maskbit = (header2[0] & 0x80) == 0x80
  3151. lengthbits = (header2[0] & 0x7f)
  3152. payload_length = lengthbits
  3153. mask_key = None
  3154. # read length
  3155. if lengthbits == 0x7e:
  3156. value = self._buffered_read(2)
  3157. payload_length, = struct.unpack("!H", value)
  3158. elif lengthbits == 0x7f:
  3159. value = self._buffered_read(8)
  3160. payload_length, = struct.unpack("!Q", value)
  3161. # read mask
  3162. if maskbit:
  3163. mask_key = self._buffered_read(4)
  3164. # if frame payload is shorter than the requested data, read only the possible part
  3165. readindex = chunk_endindex
  3166. if payload_length < readindex:
  3167. readindex = payload_length
  3168. if readindex > 0:
  3169. # get payload chunk
  3170. payload = self._buffered_read(readindex)
  3171. # unmask only the needed part
  3172. if maskbit:
  3173. for index in range(chunk_startindex, readindex):
  3174. payload[index] ^= mask_key[index % 4]
  3175. result = payload[chunk_startindex:readindex]
  3176. self._payload_head = readindex
  3177. else:
  3178. payload = bytearray()
  3179. # check if full frame arrived and reset readbuffer and payloadhead if needed
  3180. if readindex == payload_length:
  3181. self._readbuffer = bytearray()
  3182. self._payload_head = 0
  3183. # respond to non-binary opcodes, their arrival is not guaranteed beacause of non-blocking sockets
  3184. if opcode == WebsocketWrapper.OPCODE_CONNCLOSE:
  3185. frame = self._create_frame(
  3186. WebsocketWrapper.OPCODE_CONNCLOSE, payload, 0)
  3187. self._socket.send(frame)
  3188. if opcode == WebsocketWrapper.OPCODE_PING:
  3189. frame = self._create_frame(
  3190. WebsocketWrapper.OPCODE_PONG, payload, 0)
  3191. self._socket.send(frame)
  3192. if opcode == WebsocketWrapper.OPCODE_BINARY and payload_length > 0:
  3193. return result
  3194. else:
  3195. raise socket.error(EAGAIN, 0)
  3196. except socket.error as err:
  3197. if err.errno == errno.ECONNABORTED:
  3198. self.connected = False
  3199. return b''
  3200. else:
  3201. # no more data
  3202. raise
  3203. def _send_impl(self, data):
  3204. # if previous frame was sent successfully
  3205. if len(self._sendbuffer) == 0:
  3206. # create websocket frame
  3207. frame = self._create_frame(
  3208. WebsocketWrapper.OPCODE_BINARY, bytearray(data))
  3209. self._sendbuffer.extend(frame)
  3210. self._requested_size = len(data)
  3211. # try to write out as much as possible
  3212. length = self._socket.send(self._sendbuffer)
  3213. self._sendbuffer = self._sendbuffer[length:]
  3214. if len(self._sendbuffer) == 0:
  3215. # buffer sent out completely, return with payload's size
  3216. return self._requested_size
  3217. else:
  3218. # couldn't send whole data, request the same data again with 0 as sent length
  3219. return 0
  3220. def recv(self, length):
  3221. return self._recv_impl(length)
  3222. def read(self, length):
  3223. return self._recv_impl(length)
  3224. def send(self, data):
  3225. return self._send_impl(data)
  3226. def write(self, data):
  3227. return self._send_impl(data)
  3228. def close(self):
  3229. self._socket.close()
  3230. def fileno(self):
  3231. return self._socket.fileno()
  3232. def pending(self):
  3233. # Fix for bug #131: a SSL socket may still have data available
  3234. # for reading without select() being aware of it.
  3235. if self._ssl:
  3236. return self._socket.pending()
  3237. else:
  3238. # normal socket rely only on select()
  3239. return 0
  3240. def setblocking(self, flag):
  3241. self._socket.setblocking(flag)