client.py 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958
  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 v2.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-v20.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. """
  16. This is an MQTT client module. MQTT is a lightweight pub/sub messaging
  17. protocol that is easy to implement and suitable for low powered devices.
  18. """
  19. from __future__ import annotations
  20. import base64
  21. import collections
  22. import errno
  23. import hashlib
  24. import logging
  25. import os
  26. import platform
  27. import select
  28. import socket
  29. import string
  30. import struct
  31. import threading
  32. import time
  33. import urllib.parse
  34. import urllib.request
  35. import uuid
  36. import warnings
  37. from collections.abc import Iterator, Sequence
  38. from typing import TYPE_CHECKING, Any, Callable, NamedTuple, Union, cast, overload
  39. from paho.mqtt import _packet
  40. from paho.mqtt.exception import MalformedPacket
  41. from paho.mqtt.packettypes import PacketTypes
  42. from .enums import CallbackAPIVersion, ConnackCode, LogLevel, MessageState, MessageType, MQTTErrorCode, MQTTProtocolVersion, PahoClientMode, _ConnectionState
  43. from .matcher import MQTTMatcher
  44. from .properties import Properties
  45. from .reasoncodes import ReasonCode, ReasonCodes
  46. from .subscribeoptions import SubscribeOptions
  47. try:
  48. from typing import Literal
  49. except ImportError:
  50. from typing_extensions import Literal # type: ignore
  51. if TYPE_CHECKING:
  52. try:
  53. from typing import TypedDict # type: ignore
  54. except ImportError:
  55. from typing_extensions import TypedDict
  56. try:
  57. from typing import Protocol # type: ignore
  58. except ImportError:
  59. from typing_extensions import Protocol # type: ignore
  60. class _InPacket(TypedDict):
  61. command: int
  62. have_remaining: int
  63. remaining_count: list[int]
  64. remaining_mult: int
  65. remaining_length: int
  66. packet: bytearray
  67. to_process: int
  68. pos: int
  69. class _OutPacket(TypedDict):
  70. command: int
  71. mid: int
  72. qos: int
  73. pos: int
  74. to_process: int
  75. packet: bytes | bytearray
  76. info: MQTTMessageInfo | None
  77. class SocketLike(Protocol):
  78. def recv(self, buffer_size: int) -> bytes:
  79. ...
  80. def send(self, buffer: bytes | bytearray) -> int:
  81. ...
  82. def close(self) -> None:
  83. ...
  84. def fileno(self) -> int:
  85. ...
  86. def setblocking(self, flag: bool) -> None:
  87. ...
  88. try:
  89. import ssl
  90. except ImportError:
  91. ssl = None # type: ignore[assignment]
  92. try:
  93. import socks # type: ignore[import-untyped]
  94. except ImportError:
  95. socks = None # type: ignore[assignment]
  96. try:
  97. # Use monotonic clock if available
  98. time_func = time.monotonic
  99. except AttributeError:
  100. time_func = time.time
  101. try:
  102. import dns.resolver
  103. HAVE_DNS = True
  104. except ImportError:
  105. HAVE_DNS = False
  106. if platform.system() == 'Windows':
  107. EAGAIN = errno.WSAEWOULDBLOCK # type: ignore[attr-defined]
  108. else:
  109. EAGAIN = errno.EAGAIN
  110. # Avoid linter complain. We kept importing it as ReasonCodes (plural) for compatibility
  111. _ = ReasonCodes
  112. # Keep copy of enums values for compatibility.
  113. CONNECT = MessageType.CONNECT
  114. CONNACK = MessageType.CONNACK
  115. PUBLISH = MessageType.PUBLISH
  116. PUBACK = MessageType.PUBACK
  117. PUBREC = MessageType.PUBREC
  118. PUBREL = MessageType.PUBREL
  119. PUBCOMP = MessageType.PUBCOMP
  120. SUBSCRIBE = MessageType.SUBSCRIBE
  121. SUBACK = MessageType.SUBACK
  122. UNSUBSCRIBE = MessageType.UNSUBSCRIBE
  123. UNSUBACK = MessageType.UNSUBACK
  124. PINGREQ = MessageType.PINGREQ
  125. PINGRESP = MessageType.PINGRESP
  126. DISCONNECT = MessageType.DISCONNECT
  127. AUTH = MessageType.AUTH
  128. # Log levels
  129. MQTT_LOG_INFO = LogLevel.MQTT_LOG_INFO
  130. MQTT_LOG_NOTICE = LogLevel.MQTT_LOG_NOTICE
  131. MQTT_LOG_WARNING = LogLevel.MQTT_LOG_WARNING
  132. MQTT_LOG_ERR = LogLevel.MQTT_LOG_ERR
  133. MQTT_LOG_DEBUG = LogLevel.MQTT_LOG_DEBUG
  134. LOGGING_LEVEL = {
  135. LogLevel.MQTT_LOG_DEBUG: logging.DEBUG,
  136. LogLevel.MQTT_LOG_INFO: logging.INFO,
  137. LogLevel.MQTT_LOG_NOTICE: logging.INFO, # This has no direct equivalent level
  138. LogLevel.MQTT_LOG_WARNING: logging.WARNING,
  139. LogLevel.MQTT_LOG_ERR: logging.ERROR,
  140. }
  141. # CONNACK codes
  142. CONNACK_ACCEPTED = ConnackCode.CONNACK_ACCEPTED
  143. CONNACK_REFUSED_PROTOCOL_VERSION = ConnackCode.CONNACK_REFUSED_PROTOCOL_VERSION
  144. CONNACK_REFUSED_IDENTIFIER_REJECTED = ConnackCode.CONNACK_REFUSED_IDENTIFIER_REJECTED
  145. CONNACK_REFUSED_SERVER_UNAVAILABLE = ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE
  146. CONNACK_REFUSED_BAD_USERNAME_PASSWORD = ConnackCode.CONNACK_REFUSED_BAD_USERNAME_PASSWORD
  147. CONNACK_REFUSED_NOT_AUTHORIZED = ConnackCode.CONNACK_REFUSED_NOT_AUTHORIZED
  148. # Message state
  149. mqtt_ms_invalid = MessageState.MQTT_MS_INVALID
  150. mqtt_ms_publish = MessageState.MQTT_MS_PUBLISH
  151. mqtt_ms_wait_for_puback = MessageState.MQTT_MS_WAIT_FOR_PUBACK
  152. mqtt_ms_wait_for_pubrec = MessageState.MQTT_MS_WAIT_FOR_PUBREC
  153. mqtt_ms_resend_pubrel = MessageState.MQTT_MS_RESEND_PUBREL
  154. mqtt_ms_wait_for_pubrel = MessageState.MQTT_MS_WAIT_FOR_PUBREL
  155. mqtt_ms_resend_pubcomp = MessageState.MQTT_MS_RESEND_PUBCOMP
  156. mqtt_ms_wait_for_pubcomp = MessageState.MQTT_MS_WAIT_FOR_PUBCOMP
  157. mqtt_ms_send_pubrec = MessageState.MQTT_MS_SEND_PUBREC
  158. mqtt_ms_queued = MessageState.MQTT_MS_QUEUED
  159. MQTT_ERR_AGAIN = MQTTErrorCode.MQTT_ERR_AGAIN
  160. MQTT_ERR_SUCCESS = MQTTErrorCode.MQTT_ERR_SUCCESS
  161. MQTT_ERR_NOMEM = MQTTErrorCode.MQTT_ERR_NOMEM
  162. MQTT_ERR_PROTOCOL = MQTTErrorCode.MQTT_ERR_PROTOCOL
  163. MQTT_ERR_INVAL = MQTTErrorCode.MQTT_ERR_INVAL
  164. MQTT_ERR_NO_CONN = MQTTErrorCode.MQTT_ERR_NO_CONN
  165. MQTT_ERR_CONN_REFUSED = MQTTErrorCode.MQTT_ERR_CONN_REFUSED
  166. MQTT_ERR_NOT_FOUND = MQTTErrorCode.MQTT_ERR_NOT_FOUND
  167. MQTT_ERR_CONN_LOST = MQTTErrorCode.MQTT_ERR_CONN_LOST
  168. MQTT_ERR_TLS = MQTTErrorCode.MQTT_ERR_TLS
  169. MQTT_ERR_PAYLOAD_SIZE = MQTTErrorCode.MQTT_ERR_PAYLOAD_SIZE
  170. MQTT_ERR_NOT_SUPPORTED = MQTTErrorCode.MQTT_ERR_NOT_SUPPORTED
  171. MQTT_ERR_AUTH = MQTTErrorCode.MQTT_ERR_AUTH
  172. MQTT_ERR_ACL_DENIED = MQTTErrorCode.MQTT_ERR_ACL_DENIED
  173. MQTT_ERR_UNKNOWN = MQTTErrorCode.MQTT_ERR_UNKNOWN
  174. MQTT_ERR_ERRNO = MQTTErrorCode.MQTT_ERR_ERRNO
  175. MQTT_ERR_QUEUE_SIZE = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE
  176. MQTT_ERR_KEEPALIVE = MQTTErrorCode.MQTT_ERR_KEEPALIVE
  177. MQTTv31 = MQTTProtocolVersion.MQTTv31
  178. MQTTv311 = MQTTProtocolVersion.MQTTv311
  179. MQTTv5 = MQTTProtocolVersion.MQTTv5
  180. MQTT_CLIENT = PahoClientMode.MQTT_CLIENT
  181. MQTT_BRIDGE = PahoClientMode.MQTT_BRIDGE
  182. # For MQTT V5, use the clean start flag only on the first successful connect
  183. MQTT_CLEAN_START_FIRST_ONLY: CleanStartOption = 3
  184. sockpair_data = b"0"
  185. # Payload support all those type and will be converted to bytes:
  186. # * str are utf8 encoded
  187. # * int/float are converted to string and utf8 encoded (e.g. 1 is converted to b"1")
  188. # * None is converted to a zero-length payload (i.e. b"")
  189. PayloadType = Union[str, bytes, bytearray, int, float, None]
  190. HTTPHeader = dict[str, str]
  191. WebSocketHeaders = Union[Callable[[HTTPHeader], HTTPHeader], HTTPHeader]
  192. CleanStartOption = Union[bool, Literal[3]]
  193. class ConnectFlags(NamedTuple):
  194. """Contains additional information passed to `on_connect` callback"""
  195. session_present: bool
  196. """
  197. this flag is useful for clients that are
  198. using clean session set to False only (MQTTv3) or clean_start = False (MQTTv5).
  199. In that case, if client that reconnects to a broker that it has previously
  200. connected to, this flag indicates whether the broker still has the
  201. session information for the client. If true, the session still exists.
  202. """
  203. class DisconnectFlags(NamedTuple):
  204. """Contains additional information passed to `on_disconnect` callback"""
  205. is_disconnect_packet_from_server: bool
  206. """
  207. tells whether this on_disconnect call is the result
  208. of receiving an DISCONNECT packet from the broker or if the on_disconnect is only
  209. generated by the client library.
  210. When true, the reason code is generated by the broker.
  211. """
  212. CallbackOnConnect_v1_mqtt3 = Callable[["Client", Any, dict[str, Any], MQTTErrorCode], None]
  213. CallbackOnConnect_v1_mqtt5 = Callable[["Client", Any, dict[str, Any], ReasonCode, Union[Properties, None]], None]
  214. CallbackOnConnect_v1 = Union[CallbackOnConnect_v1_mqtt5, CallbackOnConnect_v1_mqtt3]
  215. CallbackOnConnect_v2 = Callable[["Client", Any, ConnectFlags, ReasonCode, Union[Properties, None]], None]
  216. CallbackOnConnect = Union[CallbackOnConnect_v1, CallbackOnConnect_v2]
  217. CallbackOnConnectFail = Callable[["Client", Any], None]
  218. CallbackOnDisconnect_v1_mqtt3 = Callable[["Client", Any, MQTTErrorCode], None]
  219. CallbackOnDisconnect_v1_mqtt5 = Callable[["Client", Any, Union[ReasonCode, int, None], Union[Properties, None]], None]
  220. CallbackOnDisconnect_v1 = Union[CallbackOnDisconnect_v1_mqtt3, CallbackOnDisconnect_v1_mqtt5]
  221. CallbackOnDisconnect_v2 = Callable[["Client", Any, DisconnectFlags, ReasonCode, Union[Properties, None]], None]
  222. CallbackOnDisconnect = Union[CallbackOnDisconnect_v1, CallbackOnDisconnect_v2]
  223. CallbackOnLog = Callable[["Client", Any, int, str], None]
  224. CallbackOnMessage = Callable[["Client", Any, "MQTTMessage"], None]
  225. CallbackOnPreConnect = Callable[["Client", Any], None]
  226. CallbackOnPublish_v1 = Callable[["Client", Any, int], None]
  227. CallbackOnPublish_v2 = Callable[["Client", Any, int, ReasonCode, Properties], None]
  228. CallbackOnPublish = Union[CallbackOnPublish_v1, CallbackOnPublish_v2]
  229. CallbackOnSocket = Callable[["Client", Any, "SocketLike"], None]
  230. CallbackOnSubscribe_v1_mqtt3 = Callable[["Client", Any, int, tuple[int, ...]], None]
  231. CallbackOnSubscribe_v1_mqtt5 = Callable[["Client", Any, int, list[ReasonCode], Properties], None]
  232. CallbackOnSubscribe_v1 = Union[CallbackOnSubscribe_v1_mqtt3, CallbackOnSubscribe_v1_mqtt5]
  233. CallbackOnSubscribe_v2 = Callable[["Client", Any, int, list[ReasonCode], Union[Properties, None]], None]
  234. CallbackOnSubscribe = Union[CallbackOnSubscribe_v1, CallbackOnSubscribe_v2]
  235. CallbackOnUnsubscribe_v1_mqtt3 = Callable[["Client", Any, int], None]
  236. CallbackOnUnsubscribe_v1_mqtt5 = Callable[["Client", Any, int, Properties, Union[ReasonCode, list[ReasonCode]]], None]
  237. CallbackOnUnsubscribe_v1 = Union[CallbackOnUnsubscribe_v1_mqtt3, CallbackOnUnsubscribe_v1_mqtt5]
  238. CallbackOnUnsubscribe_v2 = Callable[["Client", Any, int, list[ReasonCode], Union[Properties, None]], None]
  239. CallbackOnUnsubscribe = Union[CallbackOnUnsubscribe_v1, CallbackOnUnsubscribe_v2]
  240. # This is needed for typing because class Client redefined the name "socket"
  241. _socket = socket
  242. class WebsocketConnectionError(ConnectionError):
  243. """ WebsocketConnectionError is a subclass of ConnectionError.
  244. It's raised when unable to perform the Websocket handshake.
  245. """
  246. def error_string(mqtt_errno: MQTTErrorCode | int) -> str:
  247. """Return the error string associated with an mqtt error number."""
  248. if mqtt_errno == MQTT_ERR_SUCCESS:
  249. return "No error."
  250. elif mqtt_errno == MQTT_ERR_NOMEM:
  251. return "Out of memory."
  252. elif mqtt_errno == MQTT_ERR_PROTOCOL:
  253. return "A network protocol error occurred when communicating with the broker."
  254. elif mqtt_errno == MQTT_ERR_INVAL:
  255. return "Invalid function arguments provided."
  256. elif mqtt_errno == MQTT_ERR_NO_CONN:
  257. return "The client is not currently connected."
  258. elif mqtt_errno == MQTT_ERR_CONN_REFUSED:
  259. return "The connection was refused."
  260. elif mqtt_errno == MQTT_ERR_NOT_FOUND:
  261. return "Message not found (internal error)."
  262. elif mqtt_errno == MQTT_ERR_CONN_LOST:
  263. return "The connection was lost."
  264. elif mqtt_errno == MQTT_ERR_TLS:
  265. return "A TLS error occurred."
  266. elif mqtt_errno == MQTT_ERR_PAYLOAD_SIZE:
  267. return "Payload too large."
  268. elif mqtt_errno == MQTT_ERR_NOT_SUPPORTED:
  269. return "This feature is not supported."
  270. elif mqtt_errno == MQTT_ERR_AUTH:
  271. return "Authorisation failed."
  272. elif mqtt_errno == MQTT_ERR_ACL_DENIED:
  273. return "Access denied by ACL."
  274. elif mqtt_errno == MQTT_ERR_UNKNOWN:
  275. return "Unknown error."
  276. elif mqtt_errno == MQTT_ERR_ERRNO:
  277. return "Error defined by errno."
  278. elif mqtt_errno == MQTT_ERR_QUEUE_SIZE:
  279. return "Message queue full."
  280. elif mqtt_errno == MQTT_ERR_KEEPALIVE:
  281. return "Client or broker did not communicate in the keepalive interval."
  282. else:
  283. return "Unknown error."
  284. def connack_string(connack_code: int|ReasonCode) -> str:
  285. """Return the string associated with a CONNACK result or CONNACK reason code."""
  286. if isinstance(connack_code, ReasonCode):
  287. return str(connack_code)
  288. if connack_code == CONNACK_ACCEPTED:
  289. return "Connection Accepted."
  290. elif connack_code == CONNACK_REFUSED_PROTOCOL_VERSION:
  291. return "Connection Refused: unacceptable protocol version."
  292. elif connack_code == CONNACK_REFUSED_IDENTIFIER_REJECTED:
  293. return "Connection Refused: identifier rejected."
  294. elif connack_code == CONNACK_REFUSED_SERVER_UNAVAILABLE:
  295. return "Connection Refused: broker unavailable."
  296. elif connack_code == CONNACK_REFUSED_BAD_USERNAME_PASSWORD:
  297. return "Connection Refused: bad user name or password."
  298. elif connack_code == CONNACK_REFUSED_NOT_AUTHORIZED:
  299. return "Connection Refused: not authorised."
  300. else:
  301. return "Connection Refused: unknown reason."
  302. # convert_connack_rc_to_reason_code was exposed in public API. Kept it exposed.
  303. convert_connack_rc_to_reason_code = _packet.convert_connack_rc_to_reason_code
  304. def convert_disconnect_error_code_to_reason_code(rc: MQTTErrorCode) -> ReasonCode:
  305. """Convert an MQTTErrorCode to Reason code.
  306. This is used in `on_disconnect` callback to have a consistent API.
  307. Be careful that the numeric value isn't the same, for example:
  308. >>> MQTTErrorCode.MQTT_ERR_PROTOCOL == 2
  309. >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == 130
  310. It's recommended to compare by names
  311. >>> code_to_test = ReasonCode(PacketTypes.DISCONNECT, "Protocol error")
  312. >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == code_to_test
  313. """
  314. if rc == MQTTErrorCode.MQTT_ERR_SUCCESS:
  315. return ReasonCode(PacketTypes.DISCONNECT, "Success")
  316. if rc == MQTTErrorCode.MQTT_ERR_KEEPALIVE:
  317. return ReasonCode(PacketTypes.DISCONNECT, "Keep alive timeout")
  318. if rc == MQTTErrorCode.MQTT_ERR_CONN_LOST:
  319. return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error")
  320. if rc == MQTTErrorCode.MQTT_ERR_PROTOCOL:
  321. return ReasonCode(PacketTypes.DISCONNECT, "Protocol error")
  322. return ReasonCode(PacketTypes.DISCONNECT, "Unspecified error")
  323. def _base62(
  324. num: int,
  325. base: str = string.digits + string.ascii_letters,
  326. padding: int = 1,
  327. ) -> str:
  328. """Convert a number to base-62 representation."""
  329. if num < 0:
  330. raise ValueError("Number must be positive or zero")
  331. digits = []
  332. while num:
  333. num, rest = divmod(num, 62)
  334. digits.append(base[rest])
  335. digits.extend(base[0] for _ in range(len(digits), padding))
  336. return ''.join(reversed(digits))
  337. def topic_matches_sub(sub: str, topic: str) -> bool:
  338. """Check whether a topic matches a subscription.
  339. For example:
  340. * Topic "foo/bar" would match the subscription "foo/#" or "+/bar"
  341. * Topic "non/matching" would not match the subscription "non/+/+"
  342. """
  343. matcher = MQTTMatcher()
  344. matcher[sub] = True
  345. try:
  346. next(matcher.iter_match(topic))
  347. return True
  348. except StopIteration:
  349. return False
  350. def _socketpair_compat() -> tuple[socket.socket, socket.socket]:
  351. """TCP/IP socketpair including Windows support"""
  352. listensock = socket.socket(
  353. socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
  354. listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  355. listensock.bind(("127.0.0.1", 0))
  356. listensock.listen(1)
  357. _iface, port = listensock.getsockname()
  358. sock1 = socket.socket(
  359. socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
  360. sock1.setblocking(False)
  361. try:
  362. sock1.connect(("127.0.0.1", port))
  363. except BlockingIOError:
  364. pass
  365. sock2, _address = listensock.accept()
  366. sock2.setblocking(False)
  367. listensock.close()
  368. return (sock1, sock2)
  369. @overload
  370. def _force_bytes(s: str) -> bytes: ...
  371. @overload
  372. def _force_bytes(s: bytes) -> bytes: ...
  373. @overload
  374. def _force_bytes(s: bytearray) -> bytearray: ...
  375. def _force_bytes(s: str | bytes | bytearray) -> bytes | bytearray:
  376. if isinstance(s, str):
  377. return s.encode("utf-8")
  378. return s
  379. def _encode_payload(payload: str | bytes | bytearray | float | None) -> bytes | bytearray:
  380. if isinstance(payload, str):
  381. return payload.encode("utf-8")
  382. if isinstance(payload, (int, float)):
  383. return str(payload).encode("ascii")
  384. if payload is None:
  385. return b""
  386. if not isinstance(payload, (bytes, bytearray)):
  387. raise TypeError(
  388. "payload must be a string, bytearray, int, float or None."
  389. )
  390. return payload
  391. class MQTTMessageInfo:
  392. """This is a class returned from `Client.publish()` and can be used to find
  393. out the mid of the message that was published, and to determine whether the
  394. message has been published, and/or wait until it is published.
  395. """
  396. __slots__ = '_condition', '_iterpos', '_published', 'mid', 'rc'
  397. def __init__(self, mid: int):
  398. self.mid = mid
  399. """ The message Id (int)"""
  400. self._published = False
  401. self._condition = threading.Condition()
  402. self.rc: MQTTErrorCode = MQTTErrorCode.MQTT_ERR_SUCCESS
  403. """ The `MQTTErrorCode` that give status for this message.
  404. This value could change until the message `is_published`"""
  405. self._iterpos = 0
  406. def __str__(self) -> str:
  407. return str((self.rc, self.mid))
  408. def __iter__(self) -> Iterator[MQTTErrorCode | int]:
  409. self._iterpos = 0
  410. return self
  411. def __next__(self) -> MQTTErrorCode | int:
  412. return self.next()
  413. def next(self) -> MQTTErrorCode | int:
  414. if self._iterpos == 0:
  415. self._iterpos = 1
  416. return self.rc
  417. elif self._iterpos == 1:
  418. self._iterpos = 2
  419. return self.mid
  420. else:
  421. raise StopIteration
  422. def __getitem__(self, index: int) -> MQTTErrorCode | int:
  423. if index == 0:
  424. return self.rc
  425. elif index == 1:
  426. return self.mid
  427. else:
  428. raise IndexError("index out of range")
  429. def _set_as_published(self) -> None:
  430. with self._condition:
  431. self._published = True
  432. self._condition.notify()
  433. def wait_for_publish(self, timeout: float | None = None) -> None:
  434. """Block until the message associated with this object is published, or
  435. until the timeout occurs. If timeout is None, this will never time out.
  436. Set timeout to a positive number of seconds, e.g. 1.2, to enable the
  437. timeout.
  438. :raises ValueError: if the message was not queued due to the outgoing
  439. queue being full.
  440. :raises RuntimeError: if the message was not published for another
  441. reason.
  442. """
  443. if self.rc == MQTT_ERR_QUEUE_SIZE:
  444. raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
  445. elif self.rc == MQTT_ERR_AGAIN:
  446. pass
  447. elif self.rc > 0:
  448. raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')
  449. timeout_time = None if timeout is None else time_func() + timeout
  450. timeout_tenth = None if timeout is None else timeout / 10.
  451. def timed_out() -> bool:
  452. return False if timeout_time is None else time_func() > timeout_time
  453. with self._condition:
  454. while not self._published and not timed_out():
  455. self._condition.wait(timeout_tenth)
  456. if self.rc > 0:
  457. raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')
  458. def is_published(self) -> bool:
  459. """Returns True if the message associated with this object has been
  460. published, else returns False.
  461. Returning False does not mean the publication failed; it means the
  462. publication has not completed yet. To wait for this to become true,
  463. look at `wait_for_publish`.
  464. :raises ValueError: if the message was not queued due to the outgoing
  465. queue being full.
  466. :raises RuntimeError: if the message was not published for another
  467. reason.
  468. """
  469. if self.rc == MQTTErrorCode.MQTT_ERR_QUEUE_SIZE:
  470. raise ValueError('Message is not queued due to ERR_QUEUE_SIZE')
  471. elif self.rc == MQTTErrorCode.MQTT_ERR_AGAIN:
  472. pass
  473. elif self.rc > 0:
  474. raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')
  475. with self._condition:
  476. return self._published
  477. class MQTTMessage:
  478. """ This is a class that describes an incoming message. It is
  479. passed to the `on_message` callback as the message parameter.
  480. """
  481. __slots__ = '_topic', 'dup', 'info', 'mid', 'payload', 'properties', 'qos', 'retain', 'state', 'timestamp'
  482. def __init__(self, mid: int = 0, topic: bytes = b""):
  483. self.timestamp = 0.0
  484. self.state = mqtt_ms_invalid
  485. self.dup = False
  486. self.mid = mid
  487. """ The message id (int)."""
  488. self._topic = topic
  489. self.payload: bytes | bytearray = b""
  490. """the message payload (bytes)"""
  491. self.qos = 0
  492. """ The message Quality of Service (0, 1 or 2)."""
  493. self.retain = False
  494. """ If true, the message is a retained message and not fresh."""
  495. self.info = MQTTMessageInfo(mid)
  496. self.properties: Properties | None = None
  497. """ In MQTT v5.0, the properties associated with the message. (`Properties`)"""
  498. def __eq__(self, other: object) -> bool:
  499. """Override the default Equals behavior"""
  500. if isinstance(other, self.__class__):
  501. return self.mid == other.mid
  502. return False
  503. def __ne__(self, other: object) -> bool:
  504. """Define a non-equality test"""
  505. return not self.__eq__(other)
  506. @property
  507. def topic(self) -> str:
  508. """topic that the message was published on.
  509. This property is read-only.
  510. """
  511. return self._topic.decode('utf-8')
  512. @topic.setter
  513. def topic(self, value: bytes) -> None:
  514. self._topic = value
  515. class Client:
  516. """MQTT version 3.1/3.1.1/5.0 client class.
  517. This is the main class for use communicating with an MQTT broker.
  518. General usage flow:
  519. * Use `connect()`, `connect_async()` or `connect_srv()` to connect to a broker
  520. * Use `loop_start()` to set a thread running to call `loop()` for you.
  521. * Or use `loop_forever()` to handle calling `loop()` for you in a blocking function.
  522. * Or call `loop()` frequently to maintain network traffic flow with the broker
  523. * Use `subscribe()` to subscribe to a topic and receive messages
  524. * Use `publish()` to send messages
  525. * Use `disconnect()` to disconnect from the broker
  526. Data returned from the broker is made available with the use of callback
  527. functions as described below.
  528. :param CallbackAPIVersion callback_api_version: define the API version for user-callback (on_connect, on_publish,...).
  529. This field defaults to CallbackAPIVersion.VERSION1 to avoid breaking user's code. However it's recommended
  530. to migrate to the latest version (CallbackAPIVersion.VERSION2).
  531. See each callback for description of API for each version. The file docs/migrations.rst contains details on
  532. how to migrate between version.
  533. :param str client_id: the unique client id string used when connecting to the
  534. broker. If client_id is zero length or None, then the behaviour is
  535. defined by which protocol version is in use. If using MQTT v3.1.1, then
  536. a zero length client id will be sent to the broker and the broker will
  537. generate a random for the client. If using MQTT v3.1 then an id will be
  538. randomly generated. In both cases, clean_session must be True. If this
  539. is not the case a ValueError will be raised.
  540. :param bool clean_session: a boolean that determines the client type. If True,
  541. the broker will remove all information about this client when it
  542. disconnects. If False, the client is a persistent client and
  543. subscription information and queued messages will be retained when the
  544. client disconnects.
  545. Note that a client will never discard its own outgoing messages on
  546. disconnect. Calling connect() or reconnect() will cause the messages to
  547. be resent. Use reinitialise() to reset a client to its original state.
  548. The clean_session argument only applies to MQTT versions v3.1.1 and v3.1.
  549. It is not accepted if the MQTT version is v5.0 - use the clean_start
  550. argument on connect() instead.
  551. :param userdata: user defined data of any type that is passed as the "userdata"
  552. parameter to callbacks. It may be updated at a later point with the
  553. user_data_set() function.
  554. :param int protocol: allows explicit setting of the MQTT version to
  555. use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1),
  556. paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0),
  557. with the default being v3.1.1.
  558. :param transport: use "websockets" to use WebSockets as the transport
  559. mechanism. Set to "tcp" to use raw TCP, which is the default.
  560. Use "unix" to use Unix sockets as the transport mechanism; note that
  561. this option is only available on platforms that support Unix sockets,
  562. and the "host" argument is interpreted as the path to the Unix socket
  563. file in this case.
  564. :param bool manual_ack: normally, when a message is received, the library automatically
  565. acknowledges after on_message callback returns. manual_ack=True allows the application to
  566. acknowledge receipt after it has completed processing of a message
  567. using a the ack() method. This addresses vulnerability to message loss
  568. if applications fails while processing a message, or while it pending
  569. locally.
  570. Callbacks
  571. =========
  572. A number of callback functions are available to receive data back from the
  573. broker. To use a callback, define a function and then assign it to the
  574. client::
  575. def on_connect(client, userdata, flags, reason_code, properties):
  576. print(f"Connected with result code {reason_code}")
  577. client.on_connect = on_connect
  578. Callbacks can also be attached using decorators::
  579. mqttc = paho.mqtt.Client()
  580. @mqttc.connect_callback()
  581. def on_connect(client, userdata, flags, reason_code, properties):
  582. print(f"Connected with result code {reason_code}")
  583. All of the callbacks as described below have a "client" and an "userdata"
  584. argument. "client" is the `Client` instance that is calling the callback.
  585. userdata" is user data of any type and can be set when creating a new client
  586. instance or with `user_data_set()`.
  587. If you wish to suppress exceptions within a callback, you should set
  588. ``mqttc.suppress_exceptions = True``
  589. The callbacks are listed below, documentation for each of them can be found
  590. at the same function name:
  591. `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`,
  592. `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`,
  593. `on_socket_register_write`, `on_socket_unregister_write`
  594. """
  595. def __init__(
  596. self,
  597. callback_api_version: CallbackAPIVersion = CallbackAPIVersion.VERSION1,
  598. client_id: str | None = "",
  599. clean_session: bool | None = None,
  600. userdata: Any = None,
  601. protocol: MQTTProtocolVersion = MQTTv311,
  602. transport: Literal["tcp", "websockets", "unix"] = "tcp",
  603. reconnect_on_failure: bool = True,
  604. manual_ack: bool = False,
  605. ) -> None:
  606. transport = transport.lower() # type: ignore
  607. if transport == "unix" and not hasattr(socket, "AF_UNIX"):
  608. raise ValueError('"unix" transport not supported')
  609. elif transport not in ("websockets", "tcp", "unix"):
  610. raise ValueError(
  611. f'transport must be "websockets", "tcp" or "unix", not {transport}')
  612. self._manual_ack = manual_ack
  613. self._transport = transport
  614. self._protocol = protocol
  615. self._userdata = userdata
  616. self._sock: SocketLike | None = None
  617. self._sockpairR: socket.socket | None = None
  618. self._sockpairW: socket.socket | None = None
  619. self._keepalive = 60
  620. self._connect_timeout = 5.0
  621. self._client_mode = MQTT_CLIENT
  622. self._callback_api_version = callback_api_version
  623. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  624. warnings.warn(
  625. "Callback API version 1 is deprecated, update to latest version",
  626. category=DeprecationWarning,
  627. stacklevel=2,
  628. )
  629. if isinstance(self._callback_api_version, str):
  630. # Help user to migrate, it probably provided a client id
  631. # as first arguments
  632. raise TypeError(
  633. "Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details"
  634. )
  635. if self._callback_api_version not in CallbackAPIVersion:
  636. raise ValueError("Unsupported callback API version")
  637. self._clean_start: int = MQTT_CLEAN_START_FIRST_ONLY
  638. if protocol == MQTTv5:
  639. if clean_session is not None:
  640. raise ValueError('Clean session is not used for MQTT 5.0')
  641. else:
  642. if clean_session is None:
  643. clean_session = True
  644. if not clean_session and (client_id == "" or client_id is None):
  645. raise ValueError(
  646. 'A client id must be provided if clean session is False.')
  647. self._clean_session = clean_session
  648. # [MQTT-3.1.3-4] Client Id must be UTF-8 encoded string.
  649. if client_id == "" or client_id is None:
  650. if protocol == MQTTv31:
  651. self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8")
  652. else:
  653. self._client_id = b""
  654. else:
  655. self._client_id = _force_bytes(client_id)
  656. self._username: bytes | None = None
  657. self._password: bytes | None = None
  658. self._in_packet: _InPacket = {
  659. "command": 0,
  660. "have_remaining": 0,
  661. "remaining_count": [],
  662. "remaining_mult": 1,
  663. "remaining_length": 0,
  664. "packet": bytearray(b""),
  665. "to_process": 0,
  666. "pos": 0,
  667. }
  668. self._out_packet: collections.deque[_OutPacket] = collections.deque()
  669. self._last_bytes_received = time_func()
  670. self._last_msg_out = time_func()
  671. self._reconnect_min_delay = 1
  672. self._reconnect_max_delay = 120
  673. self._reconnect_delay: int | None = None
  674. self._reconnect_on_failure = reconnect_on_failure
  675. self._ping_t = 0.0
  676. self._last_mid = 0
  677. self._state = _ConnectionState.MQTT_CS_NEW
  678. self._out_messages: collections.OrderedDict[
  679. int, MQTTMessage
  680. ] = collections.OrderedDict()
  681. self._in_messages: collections.OrderedDict[
  682. int, MQTTMessage
  683. ] = collections.OrderedDict()
  684. self._max_inflight_messages = 20
  685. self._inflight_messages = 0
  686. self._max_queued_messages = 0
  687. self._connect_properties: Properties | None = None
  688. self._will_properties: Properties | None = None
  689. self._will = False
  690. self._will_topic = b""
  691. self._will_payload: bytes | bytearray = b""
  692. self._will_qos = 0
  693. self._will_retain = False
  694. self._on_message_filtered = MQTTMatcher()
  695. self._host = ""
  696. self._port = 1883
  697. self._bind_address = ""
  698. self._bind_port = 0
  699. self._proxy: Any = {}
  700. self._in_callback_mutex = threading.Lock()
  701. self._callback_mutex = threading.RLock()
  702. self._msgtime_mutex = threading.Lock()
  703. self._out_message_mutex = threading.RLock()
  704. self._in_message_mutex = threading.Lock()
  705. self._reconnect_delay_mutex = threading.Lock()
  706. self._mid_generate_mutex = threading.Lock()
  707. self._thread: threading.Thread | None = None
  708. self._thread_terminate = False
  709. self._ssl = False
  710. self._ssl_context: ssl.SSLContext | None = None
  711. # Only used when SSL context does not have check_hostname attribute
  712. self._tls_insecure = False
  713. self._logger: logging.Logger | None = None
  714. self._registered_write = False
  715. # No default callbacks
  716. self._on_log: CallbackOnLog | None = None
  717. self._on_pre_connect: CallbackOnPreConnect | None = None
  718. self._on_connect: CallbackOnConnect | None = None
  719. self._on_connect_fail: CallbackOnConnectFail | None = None
  720. self._on_subscribe: CallbackOnSubscribe | None = None
  721. self._on_message: CallbackOnMessage | None = None
  722. self._on_publish: CallbackOnPublish | None = None
  723. self._on_unsubscribe: CallbackOnUnsubscribe | None = None
  724. self._on_disconnect: CallbackOnDisconnect | None = None
  725. self._on_socket_open: CallbackOnSocket | None = None
  726. self._on_socket_close: CallbackOnSocket | None = None
  727. self._on_socket_register_write: CallbackOnSocket | None = None
  728. self._on_socket_unregister_write: CallbackOnSocket | None = None
  729. self._websocket_path = "/mqtt"
  730. self._websocket_extra_headers: WebSocketHeaders | None = None
  731. # for clean_start == MQTT_CLEAN_START_FIRST_ONLY
  732. self._mqttv5_first_connect = True
  733. self.suppress_exceptions = False # For callbacks
  734. def __del__(self) -> None:
  735. self._reset_sockets()
  736. @property
  737. def host(self) -> str:
  738. """
  739. Host to connect to. If `connect()` hasn't been called yet, returns an empty string.
  740. This property may not be changed if the connection is already open.
  741. """
  742. return self._host
  743. @host.setter
  744. def host(self, value: str) -> None:
  745. if not self._connection_closed():
  746. raise RuntimeError("updating host on established connection is not supported")
  747. if not value:
  748. raise ValueError("Invalid host.")
  749. self._host = value
  750. @property
  751. def port(self) -> int:
  752. """
  753. Broker TCP port to connect to.
  754. This property may not be changed if the connection is already open.
  755. """
  756. return self._port
  757. @port.setter
  758. def port(self, value: int) -> None:
  759. if not self._connection_closed():
  760. raise RuntimeError("updating port on established connection is not supported")
  761. if value <= 0:
  762. raise ValueError("Invalid port number.")
  763. self._port = value
  764. @property
  765. def keepalive(self) -> int:
  766. """
  767. Client keepalive interval (in seconds).
  768. This property may not be changed if the connection is already open.
  769. """
  770. return self._keepalive
  771. @keepalive.setter
  772. def keepalive(self, value: int) -> None:
  773. if not self._connection_closed():
  774. # The issue here is that the previous value of keepalive matter to possibly
  775. # sent ping packet.
  776. raise RuntimeError("updating keepalive on established connection is not supported")
  777. if value < 0:
  778. raise ValueError("Keepalive must be >=0.")
  779. self._keepalive = value
  780. @property
  781. def transport(self) -> Literal["tcp", "websockets", "unix"]:
  782. """
  783. Transport method used for the connection ("tcp" or "websockets").
  784. This property may not be changed if the connection is already open.
  785. """
  786. return self._transport
  787. @transport.setter
  788. def transport(self, value: Literal["tcp", "websockets"]) -> None:
  789. if not self._connection_closed():
  790. raise RuntimeError("updating transport on established connection is not supported")
  791. self._transport = value
  792. @property
  793. def protocol(self) -> MQTTProtocolVersion:
  794. """
  795. Protocol version used (MQTT v3, MQTT v3.11, MQTTv5)
  796. This property is read-only.
  797. """
  798. return self._protocol
  799. @property
  800. def connect_timeout(self) -> float:
  801. """
  802. Connection establishment timeout in seconds.
  803. This property may not be changed if the connection is already open.
  804. """
  805. return self._connect_timeout
  806. @connect_timeout.setter
  807. def connect_timeout(self, value: float) -> None:
  808. if not self._connection_closed():
  809. raise RuntimeError("updating connect_timeout on established connection is not supported")
  810. if value <= 0.0:
  811. raise ValueError("timeout must be a positive number")
  812. self._connect_timeout = value
  813. @property
  814. def username(self) -> str | None:
  815. """The username used to connect to the MQTT broker, or None if no username is used.
  816. This property may not be changed if the connection is already open.
  817. """
  818. if self._username is None:
  819. return None
  820. return self._username.decode("utf-8")
  821. @username.setter
  822. def username(self, value: str | None) -> None:
  823. if not self._connection_closed():
  824. raise RuntimeError("updating username on established connection is not supported")
  825. if value is None:
  826. self._username = None
  827. else:
  828. self._username = value.encode("utf-8")
  829. @property
  830. def password(self) -> str | None:
  831. """The password used to connect to the MQTT broker, or None if no password is used.
  832. This property may not be changed if the connection is already open.
  833. """
  834. if self._password is None:
  835. return None
  836. return self._password.decode("utf-8")
  837. @password.setter
  838. def password(self, value: str | None) -> None:
  839. if not self._connection_closed():
  840. raise RuntimeError("updating password on established connection is not supported")
  841. if value is None:
  842. self._password = None
  843. else:
  844. self._password = value.encode("utf-8")
  845. @property
  846. def max_inflight_messages(self) -> int:
  847. """
  848. Maximum number of messages with QoS > 0 that can be partway through the network flow at once
  849. This property may not be changed if the connection is already open.
  850. """
  851. return self._max_inflight_messages
  852. @max_inflight_messages.setter
  853. def max_inflight_messages(self, value: int) -> None:
  854. if not self._connection_closed():
  855. # Not tested. Some doubt that everything is okay when max_inflight change between 0
  856. # and > 0 value because _update_inflight is skipped when _max_inflight_messages == 0
  857. raise RuntimeError("updating max_inflight_messages on established connection is not supported")
  858. if value < 0:
  859. raise ValueError("Invalid inflight.")
  860. self._max_inflight_messages = value
  861. @property
  862. def max_queued_messages(self) -> int:
  863. """
  864. Maximum number of message in the outgoing message queue, 0 means unlimited
  865. This property may not be changed if the connection is already open.
  866. """
  867. return self._max_queued_messages
  868. @max_queued_messages.setter
  869. def max_queued_messages(self, value: int) -> None:
  870. if not self._connection_closed():
  871. # Not tested.
  872. raise RuntimeError("updating max_queued_messages on established connection is not supported")
  873. if value < 0:
  874. raise ValueError("Invalid queue size.")
  875. self._max_queued_messages = value
  876. @property
  877. def will_topic(self) -> str | None:
  878. """
  879. The topic name a will message is sent to when disconnecting unexpectedly. None if a will shall not be sent.
  880. This property is read-only. Use `will_set()` to change its value.
  881. """
  882. if self._will_topic is None:
  883. return None
  884. return self._will_topic.decode("utf-8")
  885. @property
  886. def will_payload(self) -> bytes | bytearray | None:
  887. """
  888. The payload for the will message that is sent when disconnecting unexpectedly. None if a will shall not be sent.
  889. This property is read-only. Use `will_set()` to change its value.
  890. """
  891. return self._will_payload
  892. @property
  893. def logger(self) -> logging.Logger | None:
  894. return self._logger
  895. @logger.setter
  896. def logger(self, value: logging.Logger | None) -> None:
  897. self._logger = value
  898. def _sock_recv(self, bufsize: int) -> bytes:
  899. if self._sock is None:
  900. raise ConnectionError("self._sock is None")
  901. try:
  902. return self._sock.recv(bufsize)
  903. except ssl.SSLWantReadError as err:
  904. raise BlockingIOError() from err
  905. except ssl.SSLWantWriteError as err:
  906. self._call_socket_register_write()
  907. raise BlockingIOError() from err
  908. except AttributeError as err:
  909. self._easy_log(
  910. MQTT_LOG_DEBUG, "socket was None: %s", err)
  911. raise ConnectionError() from err
  912. def _sock_send(self, buf: bytes | bytearray) -> int:
  913. if self._sock is None:
  914. raise ConnectionError("self._sock is None")
  915. try:
  916. return self._sock.send(buf)
  917. except ssl.SSLWantReadError as err:
  918. raise BlockingIOError() from err
  919. except ssl.SSLWantWriteError as err:
  920. self._call_socket_register_write()
  921. raise BlockingIOError() from err
  922. except BlockingIOError as err:
  923. self._call_socket_register_write()
  924. raise BlockingIOError() from err
  925. def _sock_close(self) -> None:
  926. """Close the connection to the server."""
  927. if not self._sock:
  928. return
  929. try:
  930. sock = self._sock
  931. self._sock = None
  932. self._call_socket_unregister_write(sock)
  933. self._call_socket_close(sock)
  934. finally:
  935. # In case a callback fails, still close the socket to avoid leaking the file descriptor.
  936. sock.close()
  937. def _reset_sockets(self, sockpair_only: bool = False) -> None:
  938. if not sockpair_only:
  939. self._sock_close()
  940. if self._sockpairR:
  941. self._sockpairR.close()
  942. self._sockpairR = None
  943. if self._sockpairW:
  944. self._sockpairW.close()
  945. self._sockpairW = None
  946. def reinitialise(
  947. self,
  948. client_id: str = "",
  949. clean_session: bool = True,
  950. userdata: Any = None,
  951. ) -> None:
  952. self._reset_sockets()
  953. self.__init__(self.callback_api_version, client_id, clean_session, userdata) # type: ignore[misc]
  954. def ws_set_options(
  955. self,
  956. path: str = "/mqtt",
  957. headers: WebSocketHeaders | None = None,
  958. ) -> None:
  959. """ Set the path and headers for a websocket connection
  960. :param str path: a string starting with / which should be the endpoint of the
  961. mqtt connection on the remote server
  962. :param headers: can be either a dict or a callable object. If it is a dict then
  963. the extra items in the dict are added to the websocket headers. If it is
  964. a callable, then the default websocket headers are passed into this
  965. function and the result is used as the new headers.
  966. """
  967. self._websocket_path = path
  968. if headers is not None:
  969. if isinstance(headers, dict) or callable(headers):
  970. self._websocket_extra_headers = headers
  971. else:
  972. raise ValueError(
  973. "'headers' option to ws_set_options has to be either a dictionary or callable")
  974. def tls_set_context(
  975. self,
  976. context: ssl.SSLContext | None = None,
  977. ) -> None:
  978. """Configure network encryption and authentication context. Enables SSL/TLS support.
  979. :param context: an ssl.SSLContext object. By default this is given by
  980. ``ssl.create_default_context()``, if available.
  981. Must be called before `connect()`, `connect_async()` or `connect_srv()`."""
  982. if self._ssl_context is not None:
  983. raise ValueError('SSL/TLS has already been configured.')
  984. if context is None:
  985. context = ssl.create_default_context()
  986. self._ssl = True
  987. self._ssl_context = context
  988. # Ensure _tls_insecure is consistent with check_hostname attribute
  989. if hasattr(context, 'check_hostname'):
  990. self._tls_insecure = not context.check_hostname
  991. def tls_set(
  992. self,
  993. ca_certs: str | None = None,
  994. certfile: str | None = None,
  995. keyfile: str | None = None,
  996. cert_reqs: ssl.VerifyMode | None = None,
  997. tls_version: int | None = None,
  998. ciphers: str | None = None,
  999. keyfile_password: str | None = None,
  1000. alpn_protocols: list[str] | None = None,
  1001. ) -> None:
  1002. """Configure network encryption and authentication options. Enables SSL/TLS support.
  1003. :param str ca_certs: a string path to the Certificate Authority certificate files
  1004. that are to be treated as trusted by this client. If this is the only
  1005. option given then the client will operate in a similar manner to a web
  1006. browser. That is to say it will require the broker to have a
  1007. certificate signed by the Certificate Authorities in ca_certs and will
  1008. communicate using TLS v1,2, but will not attempt any form of
  1009. authentication. This provides basic network encryption but may not be
  1010. sufficient depending on how the broker is configured.
  1011. By default, on Python 2.7.9+ or 3.4+, the default certification
  1012. authority of the system is used. On older Python version this parameter
  1013. is mandatory.
  1014. :param str certfile: PEM encoded client certificate filename. Used with
  1015. keyfile for client TLS based authentication. Support for this feature is
  1016. broker dependent. Note that if the file is encrypted and needs a password to
  1017. decrypt it, then this can be passed using the keyfile_password argument - you
  1018. should take precautions to ensure that your password is
  1019. not hard coded into your program by loading the password from a file
  1020. for example. If you do not provide keyfile_password, the password will
  1021. be requested to be typed in at a terminal window.
  1022. :param str keyfile: PEM encoded client private keys filename. Used with
  1023. certfile for client TLS based authentication. Support for this feature is
  1024. broker dependent. Note that if the file is encrypted and needs a password to
  1025. decrypt it, then this can be passed using the keyfile_password argument - you
  1026. should take precautions to ensure that your password is
  1027. not hard coded into your program by loading the password from a file
  1028. for example. If you do not provide keyfile_password, the password will
  1029. be requested to be typed in at a terminal window.
  1030. :param cert_reqs: the certificate requirements that the client imposes
  1031. on the broker to be changed. By default this is ssl.CERT_REQUIRED,
  1032. which means that the broker must provide a certificate. See the ssl
  1033. pydoc for more information on this parameter.
  1034. :param tls_version: the version of the SSL/TLS protocol used to be
  1035. specified. By default TLS v1.2 is used. Previous versions are allowed
  1036. but not recommended due to possible security problems.
  1037. :param str ciphers: encryption ciphers that are allowed
  1038. for this connection, or None to use the defaults. See the ssl pydoc for
  1039. more information.
  1040. Must be called before `connect()`, `connect_async()` or `connect_srv()`."""
  1041. if ssl is None:
  1042. raise ValueError('This platform has no SSL/TLS.')
  1043. if not hasattr(ssl, 'SSLContext'):
  1044. # Require Python version that has SSL context support in standard library
  1045. raise ValueError(
  1046. 'Python 2.7.9 and 3.2 are the minimum supported versions for TLS.')
  1047. if ca_certs is None and not hasattr(ssl.SSLContext, 'load_default_certs'):
  1048. raise ValueError('ca_certs must not be None.')
  1049. # Create SSLContext object
  1050. if tls_version is None:
  1051. if hasattr(ssl, "PROTOCOL_TLSv1_2"):
  1052. tls_version = ssl.PROTOCOL_TLSv1_2
  1053. # If the python version supports it, use highest TLS version automatically
  1054. if hasattr(ssl, "PROTOCOL_TLS_CLIENT"):
  1055. # This also enables CERT_REQUIRED and check_hostname by default.
  1056. tls_version = ssl.PROTOCOL_TLS_CLIENT
  1057. elif hasattr(ssl, "PROTOCOL_TLS"):
  1058. tls_version = ssl.PROTOCOL_TLS
  1059. context = ssl.SSLContext(tls_version)
  1060. # Configure context
  1061. if ciphers is not None:
  1062. context.set_ciphers(ciphers)
  1063. if certfile is not None:
  1064. context.load_cert_chain(certfile, keyfile, keyfile_password)
  1065. if cert_reqs == ssl.CERT_NONE and hasattr(context, 'check_hostname'):
  1066. context.check_hostname = False
  1067. context.verify_mode = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
  1068. if ca_certs is not None:
  1069. context.load_verify_locations(ca_certs)
  1070. else:
  1071. context.load_default_certs()
  1072. if alpn_protocols is not None:
  1073. if not getattr(ssl, "HAS_ALPN", None):
  1074. raise ValueError("SSL library has no support for ALPN")
  1075. context.set_alpn_protocols(alpn_protocols)
  1076. self.tls_set_context(context)
  1077. if cert_reqs != ssl.CERT_NONE:
  1078. # Default to secure, sets context.check_hostname attribute
  1079. # if available
  1080. self.tls_insecure_set(False)
  1081. else:
  1082. # But with ssl.CERT_NONE, we can not check_hostname
  1083. self.tls_insecure_set(True)
  1084. def tls_insecure_set(self, value: bool) -> None:
  1085. """Configure verification of the server hostname in the server certificate.
  1086. If value is set to true, it is impossible to guarantee that the host
  1087. you are connecting to is not impersonating your server. This can be
  1088. useful in initial server testing, but makes it possible for a malicious
  1089. third party to impersonate your server through DNS spoofing, for
  1090. example.
  1091. Do not use this function in a real system. Setting value to true means
  1092. there is no point using encryption.
  1093. Must be called before `connect()` and after either `tls_set()` or
  1094. `tls_set_context()`."""
  1095. if self._ssl_context is None:
  1096. raise ValueError(
  1097. 'Must configure SSL context before using tls_insecure_set.')
  1098. self._tls_insecure = value
  1099. # Ensure check_hostname is consistent with _tls_insecure attribute
  1100. if hasattr(self._ssl_context, 'check_hostname'):
  1101. # Rely on SSLContext to check host name
  1102. # If verify_mode is CERT_NONE then the host name will never be checked
  1103. self._ssl_context.check_hostname = not value
  1104. def proxy_set(self, **proxy_args: Any) -> None:
  1105. """Configure proxying of MQTT connection. Enables support for SOCKS or
  1106. HTTP proxies.
  1107. Proxying is done through the PySocks library. Brief descriptions of the
  1108. proxy_args parameters are below; see the PySocks docs for more info.
  1109. (Required)
  1110. :param proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5}
  1111. :param proxy_addr: IP address or DNS name of proxy server
  1112. (Optional)
  1113. :param proxy_port: (int) port number of the proxy server. If not provided,
  1114. the PySocks package default value will be utilized, which differs by proxy_type.
  1115. :param proxy_rdns: boolean indicating whether proxy lookup should be performed
  1116. remotely (True, default) or locally (False)
  1117. :param proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy
  1118. :param proxy_password: password for SOCKS5 proxy
  1119. Example::
  1120. mqttc.proxy_set(proxy_type=socks.HTTP, proxy_addr='1.2.3.4', proxy_port=4231)
  1121. """
  1122. if socks is None:
  1123. raise ValueError("PySocks must be installed for proxy support.")
  1124. elif not self._proxy_is_valid(proxy_args):
  1125. raise ValueError("proxy_type and/or proxy_addr are invalid.")
  1126. else:
  1127. self._proxy = proxy_args
  1128. def enable_logger(self, logger: logging.Logger | None = None) -> None:
  1129. """
  1130. Enables a logger to send log messages to
  1131. :param logging.Logger logger: if specified, that ``logging.Logger`` object will be used, otherwise
  1132. one will be created automatically.
  1133. See `disable_logger` to undo this action.
  1134. """
  1135. if logger is None:
  1136. if self._logger is not None:
  1137. # Do not replace existing logger
  1138. return
  1139. logger = logging.getLogger(__name__)
  1140. self.logger = logger
  1141. def disable_logger(self) -> None:
  1142. """
  1143. Disable logging using standard python logging package. This has no effect on the `on_log` callback.
  1144. """
  1145. self._logger = None
  1146. def connect(
  1147. self,
  1148. host: str,
  1149. port: int = 1883,
  1150. keepalive: int = 60,
  1151. bind_address: str = "",
  1152. bind_port: int = 0,
  1153. clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY,
  1154. properties: Properties | None = None,
  1155. ) -> MQTTErrorCode:
  1156. """Connect to a remote broker. This is a blocking call that establishes
  1157. the underlying connection and transmits a CONNECT packet.
  1158. Note that the connection status will not be updated until a CONNACK is received and
  1159. processed (this requires a running network loop, see `loop_start`, `loop_forever`, `loop`...).
  1160. :param str host: the hostname or IP address of the remote broker.
  1161. :param int port: the network port of the server host to connect to. Defaults to
  1162. 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
  1163. are using `tls_set()` the port may need providing.
  1164. :param int keepalive: Maximum period in seconds between communications with the
  1165. broker. If no other messages are being exchanged, this controls the
  1166. rate at which the client will send ping messages to the broker.
  1167. :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
  1168. Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
  1169. respectively. MQTT session data (such as outstanding messages and subscriptions)
  1170. is cleared on successful connect when the clean_start flag is set.
  1171. For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar
  1172. result.
  1173. :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
  1174. MQTT connect packet.
  1175. """
  1176. if self._protocol == MQTTv5:
  1177. self._mqttv5_first_connect = True
  1178. else:
  1179. if clean_start != MQTT_CLEAN_START_FIRST_ONLY:
  1180. raise ValueError("Clean start only applies to MQTT V5")
  1181. if properties:
  1182. raise ValueError("Properties only apply to MQTT V5")
  1183. self.connect_async(host, port, keepalive,
  1184. bind_address, bind_port, clean_start, properties)
  1185. return self.reconnect()
  1186. def connect_srv(
  1187. self,
  1188. domain: str | None = None,
  1189. keepalive: int = 60,
  1190. bind_address: str = "",
  1191. bind_port: int = 0,
  1192. clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY,
  1193. properties: Properties | None = None,
  1194. ) -> MQTTErrorCode:
  1195. """Connect to a remote broker.
  1196. :param str domain: the DNS domain to search for SRV records; if None,
  1197. try to determine local domain name.
  1198. :param keepalive, bind_address, clean_start and properties: see `connect()`
  1199. """
  1200. if HAVE_DNS is False:
  1201. raise ValueError(
  1202. 'No DNS resolver library found, try "pip install dnspython".')
  1203. if domain is None:
  1204. domain = socket.getfqdn()
  1205. domain = domain[domain.find('.') + 1:]
  1206. try:
  1207. rr = f'_mqtt._tcp.{domain}'
  1208. if self._ssl:
  1209. # IANA specifies secure-mqtt (not mqtts) for port 8883
  1210. rr = f'_secure-mqtt._tcp.{domain}'
  1211. answers = []
  1212. for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
  1213. addr = answer.target.to_text()[:-1]
  1214. answers.append(
  1215. (addr, answer.port, answer.priority, answer.weight))
  1216. except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers) as err:
  1217. raise ValueError(f"No answer/NXDOMAIN for SRV in {domain}") from err
  1218. # FIXME: doesn't account for weight
  1219. for answer in answers:
  1220. host, port, _prio, _weight = answer
  1221. try:
  1222. return self.connect(host, port, keepalive, bind_address, bind_port, clean_start, properties)
  1223. except Exception: # noqa: S110,BLE001
  1224. pass
  1225. raise ValueError("No SRV hosts responded")
  1226. def connect_async(
  1227. self,
  1228. host: str,
  1229. port: int = 1883,
  1230. keepalive: int = 60,
  1231. bind_address: str = "",
  1232. bind_port: int = 0,
  1233. clean_start: CleanStartOption = MQTT_CLEAN_START_FIRST_ONLY,
  1234. properties: Properties | None = None,
  1235. ) -> None:
  1236. """Connect to a remote broker asynchronously. This is a non-blocking
  1237. connect call that can be used with `loop_start()` to provide very quick
  1238. start.
  1239. Any already established connection will be terminated immediately.
  1240. :param str host: the hostname or IP address of the remote broker.
  1241. :param int port: the network port of the server host to connect to. Defaults to
  1242. 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
  1243. are using `tls_set()` the port may need providing.
  1244. :param int keepalive: Maximum period in seconds between communications with the
  1245. broker. If no other messages are being exchanged, this controls the
  1246. rate at which the client will send ping messages to the broker.
  1247. :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
  1248. Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
  1249. respectively. MQTT session data (such as outstanding messages and subscriptions)
  1250. is cleared on successful connect when the clean_start flag is set.
  1251. For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar
  1252. result.
  1253. :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
  1254. MQTT connect packet.
  1255. """
  1256. if bind_port < 0:
  1257. raise ValueError('Invalid bind port number.')
  1258. # Switch to state NEW to allow update of host, port & co.
  1259. self._sock_close()
  1260. self._state = _ConnectionState.MQTT_CS_NEW
  1261. self.host = host
  1262. self.port = port
  1263. self.keepalive = keepalive
  1264. self._bind_address = bind_address
  1265. self._bind_port = bind_port
  1266. self._clean_start = clean_start
  1267. self._connect_properties = properties
  1268. self._state = _ConnectionState.MQTT_CS_CONNECT_ASYNC
  1269. def reconnect_delay_set(self, min_delay: int = 1, max_delay: int = 120) -> None:
  1270. """ Configure the exponential reconnect delay
  1271. When connection is lost, wait initially min_delay seconds and
  1272. double this time every attempt. The wait is capped at max_delay.
  1273. Once the client is fully connected (e.g. not only TCP socket, but
  1274. received a success CONNACK), the wait timer is reset to min_delay.
  1275. """
  1276. with self._reconnect_delay_mutex:
  1277. self._reconnect_min_delay = min_delay
  1278. self._reconnect_max_delay = max_delay
  1279. self._reconnect_delay = None
  1280. def reconnect(self) -> MQTTErrorCode:
  1281. """Reconnect the client after a disconnect. Can only be called after
  1282. connect()/connect_async()."""
  1283. if len(self._host) == 0:
  1284. raise ValueError('Invalid host.')
  1285. if self._port <= 0:
  1286. raise ValueError('Invalid port number.')
  1287. self._in_packet = {
  1288. "command": 0,
  1289. "have_remaining": 0,
  1290. "remaining_count": [],
  1291. "remaining_mult": 1,
  1292. "remaining_length": 0,
  1293. "packet": bytearray(b""),
  1294. "to_process": 0,
  1295. "pos": 0,
  1296. }
  1297. self._ping_t = 0.0
  1298. self._state = _ConnectionState.MQTT_CS_CONNECTING
  1299. self._sock_close()
  1300. # Mark all currently outgoing QoS = 0 packets as lost,
  1301. # or `wait_for_publish()` could hang forever
  1302. for pkt in self._out_packet:
  1303. if pkt["command"] & 0xF0 == PUBLISH and pkt["qos"] == 0 and pkt["info"] is not None:
  1304. pkt["info"].rc = MQTT_ERR_CONN_LOST
  1305. pkt["info"]._set_as_published()
  1306. self._out_packet.clear()
  1307. with self._msgtime_mutex:
  1308. self._last_bytes_received = time_func()
  1309. self._last_msg_out = time_func()
  1310. # Put messages in progress in a valid state.
  1311. self._messages_reconnect_reset()
  1312. with self._callback_mutex:
  1313. on_pre_connect = self.on_pre_connect
  1314. if on_pre_connect:
  1315. try:
  1316. on_pre_connect(self, self._userdata)
  1317. except Exception as err:
  1318. self._easy_log(
  1319. MQTT_LOG_ERR, 'Caught exception in on_pre_connect: %s', err)
  1320. if not self.suppress_exceptions:
  1321. raise
  1322. self._sock = self._create_socket()
  1323. self._sock.setblocking(False) # type: ignore[attr-defined]
  1324. self._registered_write = False
  1325. self._call_socket_open(self._sock)
  1326. return self._send_connect(self._keepalive)
  1327. def loop(self, timeout: float = 1.0) -> MQTTErrorCode:
  1328. """Process network events.
  1329. It is strongly recommended that you use `loop_start()`, or
  1330. `loop_forever()`, or if you are using an external event loop using
  1331. `loop_read()`, `loop_write()`, and `loop_misc()`. Using loop() on it's own is
  1332. no longer recommended.
  1333. This function must be called regularly to ensure communication with the
  1334. broker is carried out. It calls select() on the network socket to wait
  1335. for network events. If incoming data is present it will then be
  1336. processed. Outgoing commands, from e.g. `publish()`, are normally sent
  1337. immediately that their function is called, but this is not always
  1338. possible. loop() will also attempt to send any remaining outgoing
  1339. messages, which also includes commands that are part of the flow for
  1340. messages with QoS>0.
  1341. :param int timeout: The time in seconds to wait for incoming/outgoing network
  1342. traffic before timing out and returning.
  1343. Returns MQTT_ERR_SUCCESS on success.
  1344. Returns >0 on error.
  1345. A ValueError will be raised if timeout < 0"""
  1346. if self._sockpairR is None or self._sockpairW is None:
  1347. self._reset_sockets(sockpair_only=True)
  1348. self._sockpairR, self._sockpairW = _socketpair_compat()
  1349. return self._loop(timeout)
  1350. def _loop(self, timeout: float = 1.0) -> MQTTErrorCode:
  1351. if timeout < 0.0:
  1352. raise ValueError('Invalid timeout.')
  1353. # Tell mypy 2.2.0 self._sock is not None,
  1354. # avoiding: error: Value of type variable "_R" of "select" cannot be "SocketLike | None" [type-var]
  1355. # (and for "_W") in select.select(rlist, wlist, [], timeout) below.
  1356. if self._sock is None:
  1357. msg=(
  1358. f"Client is not connected. Socket: {self._sock!r}). "
  1359. f"Last known Connection State: {self._state.name}"
  1360. )
  1361. self._easy_log(MQTT_LOG_ERR, msg)
  1362. return MQTT_ERR_NO_CONN
  1363. if self.want_write():
  1364. wlist = [self._sock]
  1365. else:
  1366. wlist = []
  1367. # used to check if there are any bytes left in the (SSL) socket
  1368. pending_bytes = 0
  1369. if hasattr(self._sock, 'pending'):
  1370. pending_bytes = self._sock.pending() # type: ignore[union-attr]
  1371. # if bytes are pending do not wait in select
  1372. if pending_bytes > 0:
  1373. timeout = 0.0
  1374. # sockpairR is used to break out of select() before the timeout, on a
  1375. # call to publish() etc.
  1376. if self._sockpairR is None:
  1377. rlist = [self._sock]
  1378. else:
  1379. rlist = [self._sock, self._sockpairR]
  1380. try:
  1381. socklist = select.select(rlist, wlist, [], timeout)
  1382. except TypeError:
  1383. # Socket isn't correct type, in likelihood connection is lost
  1384. # ... or we called disconnect(). In that case the socket will
  1385. # be closed but some loop (like loop_forever) will continue to
  1386. # call _loop(). We still want to break that loop by returning an
  1387. # rc != MQTT_ERR_SUCCESS and we don't want state to change from
  1388. # mqtt_cs_disconnecting.
  1389. if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED):
  1390. self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST
  1391. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  1392. except ValueError:
  1393. # Can occur if we just reconnected but rlist/wlist contain a -1 for
  1394. # some reason.
  1395. if self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED):
  1396. self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST
  1397. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  1398. except Exception: # noqa: BLE001
  1399. # Note that KeyboardInterrupt, etc. can still terminate since they
  1400. # are not derived from Exception
  1401. return MQTTErrorCode.MQTT_ERR_UNKNOWN
  1402. if self._sock in socklist[0] or pending_bytes > 0:
  1403. rc = self.loop_read()
  1404. if rc or self._sock is None:
  1405. return rc
  1406. if self._sockpairR in socklist[0] and self._sockpairR:
  1407. # Stimulate output write even though we didn't ask for it, because
  1408. # at that point the publish or other command wasn't present.
  1409. socklist[1].insert(0, self._sock)
  1410. # Clear sockpairR - only ever a single byte written.
  1411. try:
  1412. # Read many bytes at once - this allows up to 10000 calls to
  1413. # publish() inbetween calls to loop().
  1414. self._sockpairR.recv(10000)
  1415. except BlockingIOError:
  1416. pass
  1417. if self._sock in socklist[1]:
  1418. rc = self.loop_write()
  1419. if rc or self._sock is None:
  1420. return rc
  1421. return self.loop_misc()
  1422. def publish(
  1423. self,
  1424. topic: str,
  1425. payload: PayloadType = None,
  1426. qos: int = 0,
  1427. retain: bool = False,
  1428. properties: Properties | None = None,
  1429. ) -> MQTTMessageInfo:
  1430. """Publish a message on a topic.
  1431. This causes a message to be sent to the broker and subsequently from
  1432. the broker to any clients subscribing to matching topics.
  1433. :param str topic: The topic that the message should be published on.
  1434. :param payload: The actual message to send. If not given, or set to None a
  1435. zero length message will be used. Passing an int or float will result
  1436. in the payload being converted to a string representing that number. If
  1437. you wish to send a true int/float, use struct.pack() to create the
  1438. payload you require.
  1439. :param int qos: The quality of service level to use.
  1440. :param bool retain: If set to true, the message will be set as the "last known
  1441. good"/retained message for the topic.
  1442. :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included.
  1443. Returns a `MQTTMessageInfo` class, which can be used to determine whether
  1444. the message has been delivered (using `is_published()`) or to block
  1445. waiting for the message to be delivered (`wait_for_publish()`). The
  1446. message ID and return code of the publish() call can be found at
  1447. :py:attr:`info.mid <MQTTMessage.mid>` and :py:attr:`info.rc <MQTTMessage.rc>`.
  1448. For backwards compatibility, the `MQTTMessageInfo` class is iterable so
  1449. the old construct of ``(rc, mid) = client.publish(...)`` is still valid.
  1450. rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the
  1451. client is not currently connected. mid is the message ID for the
  1452. publish request. The mid value can be used to track the publish request
  1453. by checking against the mid argument in the on_publish() callback if it
  1454. is defined.
  1455. :raises ValueError: if topic is None, has zero length or is
  1456. invalid (contains a wildcard), except if the MQTT version used is v5.0.
  1457. For v5.0, a zero length topic can be used when a Topic Alias has been set.
  1458. :raises ValueError: if qos is not one of 0, 1 or 2
  1459. :raises ValueError: if the length of the payload is greater than 268435455 bytes.
  1460. """
  1461. if self._protocol != MQTTv5 and (topic is None or len(topic) == 0):
  1462. raise ValueError('Invalid topic.')
  1463. topic_bytes = topic.encode('utf-8')
  1464. self._raise_for_invalid_topic(topic_bytes)
  1465. if qos < 0 or qos > 2:
  1466. raise ValueError('Invalid QoS level.')
  1467. local_payload = _encode_payload(payload)
  1468. if len(local_payload) > 268435455:
  1469. raise ValueError('Payload too large.')
  1470. local_mid = self._mid_generate()
  1471. if qos == 0:
  1472. info = MQTTMessageInfo(local_mid)
  1473. rc = self._send_publish(
  1474. local_mid, topic_bytes, local_payload, qos, retain, False, info, properties)
  1475. info.rc = rc
  1476. return info
  1477. else:
  1478. message = MQTTMessage(local_mid, topic_bytes)
  1479. message.timestamp = time_func()
  1480. message.payload = local_payload
  1481. message.qos = qos
  1482. message.retain = retain
  1483. message.dup = False
  1484. message.properties = properties
  1485. with self._out_message_mutex:
  1486. if self._max_queued_messages > 0 and len(self._out_messages) >= self._max_queued_messages:
  1487. message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE
  1488. return message.info
  1489. if local_mid in self._out_messages:
  1490. message.info.rc = MQTTErrorCode.MQTT_ERR_QUEUE_SIZE
  1491. return message.info
  1492. self._out_messages[message.mid] = message
  1493. if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
  1494. self._inflight_messages += 1
  1495. if qos == 1:
  1496. message.state = mqtt_ms_wait_for_puback
  1497. elif qos == 2:
  1498. message.state = mqtt_ms_wait_for_pubrec
  1499. rc = self._send_publish(message.mid, topic_bytes, message.payload, message.qos, message.retain,
  1500. message.dup, message.info, message.properties)
  1501. # remove from inflight messages so it will be send after a connection is made
  1502. if rc == MQTTErrorCode.MQTT_ERR_NO_CONN:
  1503. self._inflight_messages -= 1
  1504. message.state = mqtt_ms_publish
  1505. message.info.rc = rc
  1506. return message.info
  1507. else:
  1508. message.state = mqtt_ms_queued
  1509. message.info.rc = MQTTErrorCode.MQTT_ERR_SUCCESS
  1510. return message.info
  1511. def username_pw_set(
  1512. self, username: str | None, password: str | None = None
  1513. ) -> None:
  1514. """Set a username and optionally a password for broker authentication.
  1515. Must be called before connect() to have any effect.
  1516. Requires a broker that supports MQTT v3.1 or more.
  1517. :param str username: The username to authenticate with. Need have no relationship to the client id. Must be str
  1518. [MQTT-3.1.3-11].
  1519. Set to None to reset client back to not using username/password for broker authentication.
  1520. :param str password: The password to authenticate with. Optional, set to None if not required. If it is str, then it
  1521. will be encoded as UTF-8.
  1522. """
  1523. # [MQTT-3.1.3-11] User name must be UTF-8 encoded string
  1524. self._username = None if username is None else username.encode('utf-8')
  1525. if isinstance(password, str):
  1526. self._password = password.encode('utf-8')
  1527. else:
  1528. self._password = password
  1529. def enable_bridge_mode(self) -> None:
  1530. """Sets the client in a bridge mode instead of client mode.
  1531. Must be called before `connect()` to have any effect.
  1532. Requires brokers that support bridge mode.
  1533. Under bridge mode, the broker will identify the client as a bridge and
  1534. not send it's own messages back to it. Hence a subscription of # is
  1535. possible without message loops. This feature also correctly propagates
  1536. the retain flag on the messages.
  1537. Currently Mosquitto and RSMB support this feature. This feature can
  1538. be used to create a bridge between multiple broker.
  1539. """
  1540. self._client_mode = MQTT_BRIDGE
  1541. def _connection_closed(self) -> bool:
  1542. """
  1543. Return true if the connection is closed (and not trying to be opened).
  1544. """
  1545. return (
  1546. self._state == _ConnectionState.MQTT_CS_NEW
  1547. or (self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) and self._sock is None))
  1548. def is_connected(self) -> bool:
  1549. """Returns the current status of the connection
  1550. True if connection exists
  1551. False if connection is closed
  1552. """
  1553. return self._state == _ConnectionState.MQTT_CS_CONNECTED
  1554. def disconnect(
  1555. self,
  1556. reasoncode: ReasonCode | None = None,
  1557. properties: Properties | None = None,
  1558. ) -> MQTTErrorCode:
  1559. """Disconnect a connected client from the broker.
  1560. :param ReasonCode reasoncode: (MQTT v5.0 only) a ReasonCode instance setting the MQTT v5.0
  1561. reasoncode to be sent with the disconnect packet. It is optional, the receiver
  1562. then assuming that 0 (success) is the value.
  1563. :param Properties properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
  1564. to be included. Optional - if not set, no properties are sent.
  1565. """
  1566. if self._sock is None:
  1567. self._state = _ConnectionState.MQTT_CS_DISCONNECTED
  1568. return MQTT_ERR_NO_CONN
  1569. else:
  1570. self._state = _ConnectionState.MQTT_CS_DISCONNECTING
  1571. return self._send_disconnect(reasoncode, properties)
  1572. def subscribe(
  1573. self,
  1574. topic: str | tuple[str, int] | tuple[str, SubscribeOptions] | list[tuple[str, int]] | list[tuple[str, SubscribeOptions]],
  1575. qos: int = 0,
  1576. options: SubscribeOptions | None = None,
  1577. properties: Properties | None = None,
  1578. ) -> tuple[MQTTErrorCode, int | None]:
  1579. """Subscribe the client to one or more topics.
  1580. This function may be called in three different ways (and a further three for MQTT v5.0):
  1581. Simple string and integer
  1582. -------------------------
  1583. e.g. subscribe("my/topic", 2)
  1584. :topic: A string specifying the subscription topic to subscribe to.
  1585. :qos: The desired quality of service level for the subscription.
  1586. Defaults to 0.
  1587. :options and properties: Not used.
  1588. Simple string and subscribe options (MQTT v5.0 only)
  1589. ----------------------------------------------------
  1590. e.g. subscribe("my/topic", options=SubscribeOptions(qos=2))
  1591. :topic: A string specifying the subscription topic to subscribe to.
  1592. :qos: Not used.
  1593. :options: The MQTT v5.0 subscribe options.
  1594. :properties: a Properties instance setting the MQTT v5.0 properties
  1595. to be included. Optional - if not set, no properties are sent.
  1596. String and integer tuple
  1597. ------------------------
  1598. e.g. subscribe(("my/topic", 1))
  1599. :topic: A tuple of (topic, qos). Both topic and qos must be present in
  1600. the tuple.
  1601. :qos and options: Not used.
  1602. :properties: Only used for MQTT v5.0. A Properties instance setting the
  1603. MQTT v5.0 properties. Optional - if not set, no properties are sent.
  1604. String and subscribe options tuple (MQTT v5.0 only)
  1605. ---------------------------------------------------
  1606. e.g. subscribe(("my/topic", SubscribeOptions(qos=1)))
  1607. :topic: A tuple of (topic, SubscribeOptions). Both topic and subscribe
  1608. options must be present in the tuple.
  1609. :qos and options: Not used.
  1610. :properties: a Properties instance setting the MQTT v5.0 properties
  1611. to be included. Optional - if not set, no properties are sent.
  1612. List of string and integer tuples
  1613. ---------------------------------
  1614. e.g. subscribe([("my/topic", 0), ("another/topic", 2)])
  1615. This allows multiple topic subscriptions in a single SUBSCRIPTION
  1616. command, which is more efficient than using multiple calls to
  1617. subscribe().
  1618. :topic: A list of tuple of format (topic, qos). Both topic and qos must
  1619. be present in all of the tuples.
  1620. :qos, options and properties: Not used.
  1621. List of string and subscribe option tuples (MQTT v5.0 only)
  1622. -----------------------------------------------------------
  1623. e.g. subscribe([("my/topic", SubscribeOptions(qos=0), ("another/topic", SubscribeOptions(qos=2)])
  1624. This allows multiple topic subscriptions in a single SUBSCRIPTION
  1625. command, which is more efficient than using multiple calls to
  1626. subscribe().
  1627. :topic: A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe
  1628. options must be present in all of the tuples.
  1629. :qos and options: Not used.
  1630. :properties: a Properties instance setting the MQTT v5.0 properties
  1631. to be included. Optional - if not set, no properties are sent.
  1632. The function returns a tuple (result, mid), where result is
  1633. MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
  1634. client is not currently connected. mid is the message ID for the
  1635. subscribe request. The mid value can be used to track the subscribe
  1636. request by checking against the mid argument in the on_subscribe()
  1637. callback if it is defined.
  1638. Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
  1639. zero string length, or if topic is not a string, tuple or list.
  1640. """
  1641. topic_qos_list = None
  1642. if isinstance(topic, tuple):
  1643. if self._protocol == MQTTv5:
  1644. topic, options = topic # type: ignore
  1645. if not isinstance(options, SubscribeOptions):
  1646. raise ValueError(
  1647. 'Subscribe options must be instance of SubscribeOptions class.')
  1648. else:
  1649. topic, qos = topic # type: ignore
  1650. if isinstance(topic, (bytes, str)):
  1651. if qos < 0 or qos > 2:
  1652. raise ValueError('Invalid QoS level.')
  1653. if self._protocol == MQTTv5:
  1654. if options is None:
  1655. # if no options are provided, use the QoS passed instead
  1656. options = SubscribeOptions(qos=qos)
  1657. elif qos != 0:
  1658. raise ValueError(
  1659. 'Subscribe options and qos parameters cannot be combined.')
  1660. if not isinstance(options, SubscribeOptions):
  1661. raise ValueError(
  1662. 'Subscribe options must be instance of SubscribeOptions class.')
  1663. topic_qos_list = [(topic.encode('utf-8'), options)]
  1664. else:
  1665. if topic is None or len(topic) == 0:
  1666. raise ValueError('Invalid topic.')
  1667. topic_qos_list = [(topic.encode('utf-8'), qos)] # type: ignore
  1668. elif isinstance(topic, list):
  1669. if len(topic) == 0:
  1670. raise ValueError('Empty topic list')
  1671. topic_qos_list = []
  1672. if self._protocol == MQTTv5:
  1673. for t, o in topic:
  1674. if not isinstance(o, SubscribeOptions):
  1675. # then the second value should be QoS
  1676. if o < 0 or o > 2:
  1677. raise ValueError('Invalid QoS level.')
  1678. o = SubscribeOptions(qos=o)
  1679. topic_qos_list.append((t.encode('utf-8'), o))
  1680. else:
  1681. for t, q in topic:
  1682. if isinstance(q, SubscribeOptions) or q < 0 or q > 2:
  1683. raise ValueError('Invalid QoS level.')
  1684. if t is None or len(t) == 0 or not isinstance(t, (bytes, str)):
  1685. raise ValueError('Invalid topic.')
  1686. topic_qos_list.append((t.encode('utf-8'), q)) # type: ignore
  1687. if topic_qos_list is None:
  1688. raise ValueError("No topic specified, or incorrect topic type.")
  1689. if any(self._filter_wildcard_len_check(topic) != MQTT_ERR_SUCCESS for topic, _ in topic_qos_list):
  1690. raise ValueError('Invalid subscription filter.')
  1691. if self._sock is None:
  1692. return (MQTT_ERR_NO_CONN, None)
  1693. return self._send_subscribe(False, topic_qos_list, properties)
  1694. def unsubscribe(
  1695. self, topic: str | list[str], properties: Properties | None = None
  1696. ) -> tuple[MQTTErrorCode, int | None]:
  1697. """Unsubscribe the client from one or more topics.
  1698. :param topic: A single string, or list of strings that are the subscription
  1699. topics to unsubscribe from.
  1700. :param properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
  1701. to be included. Optional - if not set, no properties are sent.
  1702. Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
  1703. to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
  1704. currently connected.
  1705. mid is the message ID for the unsubscribe request. The mid value can be
  1706. used to track the unsubscribe request by checking against the mid
  1707. argument in the on_unsubscribe() callback if it is defined.
  1708. :raises ValueError: if topic is None or has zero string length, or is
  1709. not a string or list.
  1710. """
  1711. topic_list = None
  1712. if topic is None:
  1713. raise ValueError('Invalid topic.')
  1714. if isinstance(topic, (bytes, str)):
  1715. if len(topic) == 0:
  1716. raise ValueError('Invalid topic.')
  1717. topic_list = [topic.encode('utf-8')]
  1718. elif isinstance(topic, list):
  1719. topic_list = []
  1720. for t in topic:
  1721. if len(t) == 0 or not isinstance(t, (bytes, str)):
  1722. raise ValueError('Invalid topic.')
  1723. topic_list.append(t.encode('utf-8'))
  1724. if topic_list is None:
  1725. raise ValueError("No topic specified, or incorrect topic type.")
  1726. if self._sock is None:
  1727. return (MQTTErrorCode.MQTT_ERR_NO_CONN, None)
  1728. return self._send_unsubscribe(False, topic_list, properties)
  1729. def loop_read(self, max_packets: int = 1) -> MQTTErrorCode:
  1730. """Process read network events. Use in place of calling `loop()` if you
  1731. wish to handle your client reads as part of your own application.
  1732. Use `socket()` to obtain the client socket to call select() or equivalent
  1733. on.
  1734. Do not use if you are using `loop_start()` or `loop_forever()`."""
  1735. if self._sock is None:
  1736. return MQTTErrorCode.MQTT_ERR_NO_CONN
  1737. max_packets = len(self._out_messages) + len(self._in_messages)
  1738. max_packets = max(max_packets, 1)
  1739. for _ in range(max_packets):
  1740. if self._sock is None:
  1741. return MQTTErrorCode.MQTT_ERR_NO_CONN
  1742. rc = self._packet_read()
  1743. if rc > 0:
  1744. return self._loop_rc_handle(rc)
  1745. elif rc == MQTTErrorCode.MQTT_ERR_AGAIN:
  1746. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1747. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1748. def loop_write(self) -> MQTTErrorCode:
  1749. """Process write network events. Use in place of calling `loop()` if you
  1750. wish to handle your client writes as part of your own application.
  1751. Use `socket()` to obtain the client socket to call select() or equivalent
  1752. on.
  1753. Use `want_write()` to determine if there is data waiting to be written.
  1754. Do not use if you are using `loop_start()` or `loop_forever()`."""
  1755. if self._sock is None:
  1756. return MQTTErrorCode.MQTT_ERR_NO_CONN
  1757. try:
  1758. rc = self._packet_write()
  1759. if rc == MQTTErrorCode.MQTT_ERR_AGAIN:
  1760. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1761. elif rc > 0:
  1762. return self._loop_rc_handle(rc)
  1763. else:
  1764. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1765. finally:
  1766. if self.want_write():
  1767. self._call_socket_register_write()
  1768. else:
  1769. self._call_socket_unregister_write()
  1770. def want_write(self) -> bool:
  1771. """Call to determine if there is network data waiting to be written.
  1772. Useful if you are calling select() yourself rather than using `loop()`, `loop_start()` or `loop_forever()`.
  1773. """
  1774. return len(self._out_packet) > 0
  1775. def loop_misc(self) -> MQTTErrorCode:
  1776. """Process miscellaneous network events. Use in place of calling `loop()` if you
  1777. wish to call select() or equivalent on.
  1778. Do not use if you are using `loop_start()` or `loop_forever()`."""
  1779. if self._sock is None:
  1780. return MQTTErrorCode.MQTT_ERR_NO_CONN
  1781. now = time_func()
  1782. self._check_keepalive()
  1783. if self._ping_t > 0 and now - self._ping_t >= self._keepalive:
  1784. # client->ping_t != 0 means we are waiting for a pingresp.
  1785. # This hasn't happened in the keepalive time so we should disconnect.
  1786. self._sock_close()
  1787. if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED):
  1788. self._state = _ConnectionState.MQTT_CS_DISCONNECTED
  1789. rc = MQTTErrorCode.MQTT_ERR_SUCCESS
  1790. else:
  1791. self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST
  1792. rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE
  1793. self._do_on_disconnect(
  1794. packet_from_broker=False,
  1795. v1_rc=rc,
  1796. )
  1797. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  1798. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1799. def max_inflight_messages_set(self, inflight: int) -> None:
  1800. """Set the maximum number of messages with QoS>0 that can be part way
  1801. through their network flow at once. Defaults to 20."""
  1802. self.max_inflight_messages = inflight
  1803. def max_queued_messages_set(self, queue_size: int) -> Client:
  1804. """Set the maximum number of messages in the outgoing message queue.
  1805. 0 means unlimited."""
  1806. if not isinstance(queue_size, int):
  1807. raise TypeError("queue_size should be an int")
  1808. self.max_queued_messages = queue_size
  1809. return self
  1810. def user_data_set(self, userdata: Any) -> None:
  1811. """Set the user data variable passed to callbacks. May be any data type."""
  1812. self._userdata = userdata
  1813. def user_data_get(self) -> Any:
  1814. """Get the user data variable passed to callbacks. May be any data type."""
  1815. return self._userdata
  1816. def will_set(
  1817. self,
  1818. topic: str,
  1819. payload: PayloadType = None,
  1820. qos: int = 0,
  1821. retain: bool = False,
  1822. properties: Properties | None = None,
  1823. ) -> None:
  1824. """Set a Will to be sent by the broker in case the client disconnects unexpectedly.
  1825. This must be called before connect() to have any effect.
  1826. :param str topic: The topic that the will message should be published on.
  1827. :param payload: The message to send as a will. If not given, or set to None a
  1828. zero length message will be used as the will. Passing an int or float
  1829. will result in the payload being converted to a string representing
  1830. that number. If you wish to send a true int/float, use struct.pack() to
  1831. create the payload you require.
  1832. :param int qos: The quality of service level to use for the will.
  1833. :param bool retain: If set to true, the will message will be set as the "last known
  1834. good"/retained message for the topic.
  1835. :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties
  1836. to be included with the will message. Optional - if not set, no properties are sent.
  1837. :raises ValueError: if qos is not 0, 1 or 2, or if topic is None or has
  1838. zero string length.
  1839. See `will_clear` to clear will. Note that will are NOT send if the client disconnect cleanly
  1840. for example by calling `disconnect()`.
  1841. """
  1842. if topic is None or len(topic) == 0:
  1843. raise ValueError('Invalid topic.')
  1844. if qos < 0 or qos > 2:
  1845. raise ValueError('Invalid QoS level.')
  1846. if properties and not isinstance(properties, Properties):
  1847. raise ValueError(
  1848. "The properties argument must be an instance of the Properties class.")
  1849. self._will_payload = _encode_payload(payload)
  1850. self._will = True
  1851. self._will_topic = topic.encode('utf-8')
  1852. self._will_qos = qos
  1853. self._will_retain = retain
  1854. self._will_properties = properties
  1855. def will_clear(self) -> None:
  1856. """ Removes a will that was previously configured with `will_set()`.
  1857. Must be called before connect() to have any effect."""
  1858. self._will = False
  1859. self._will_topic = b""
  1860. self._will_payload = b""
  1861. self._will_qos = 0
  1862. self._will_retain = False
  1863. def socket(self) -> SocketLike | None:
  1864. """Return the socket or ssl object for this client."""
  1865. return self._sock
  1866. def loop_forever(
  1867. self,
  1868. timeout: float = 1.0,
  1869. retry_first_connection: bool = False,
  1870. ) -> MQTTErrorCode:
  1871. """This function calls the network loop functions for you in an
  1872. infinite blocking loop. It is useful for the case where you only want
  1873. to run the MQTT client loop in your program.
  1874. loop_forever() will handle reconnecting for you if reconnect_on_failure is
  1875. true (this is the default behavior). If you call `disconnect()` in a callback
  1876. it will return.
  1877. :param int timeout: The time in seconds to wait for incoming/outgoing network
  1878. traffic before timing out and returning.
  1879. :param bool retry_first_connection: Should the first connection attempt be retried on failure.
  1880. This is independent of the reconnect_on_failure setting.
  1881. :raises OSError: if the first connection fail unless retry_first_connection=True
  1882. """
  1883. run = True
  1884. while run:
  1885. if self._thread_terminate is True:
  1886. break
  1887. if self._state == _ConnectionState.MQTT_CS_CONNECT_ASYNC:
  1888. try:
  1889. self.reconnect()
  1890. except OSError:
  1891. self._handle_on_connect_fail()
  1892. if not retry_first_connection:
  1893. raise
  1894. self._easy_log(
  1895. MQTT_LOG_DEBUG, "Connection failed, retrying")
  1896. self._reconnect_wait()
  1897. else:
  1898. break
  1899. while run:
  1900. rc = MQTTErrorCode.MQTT_ERR_SUCCESS
  1901. while rc == MQTTErrorCode.MQTT_ERR_SUCCESS:
  1902. rc = self._loop(timeout)
  1903. # We don't need to worry about locking here, because we've
  1904. # either called loop_forever() when in single threaded mode, or
  1905. # in multi threaded mode when loop_stop() has been called and
  1906. # so no other threads can access _out_packet or _messages.
  1907. if (self._thread_terminate is True
  1908. and len(self._out_packet) == 0
  1909. and len(self._out_messages) == 0):
  1910. rc = MQTTErrorCode.MQTT_ERR_NOMEM
  1911. run = False
  1912. def should_exit() -> bool:
  1913. return (
  1914. self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED) or
  1915. run is False or # noqa: B023 (uses the run variable from the outer scope on purpose)
  1916. self._thread_terminate is True
  1917. )
  1918. if should_exit() or not self._reconnect_on_failure:
  1919. run = False
  1920. else:
  1921. self._reconnect_wait()
  1922. if should_exit():
  1923. run = False
  1924. else:
  1925. try:
  1926. self.reconnect()
  1927. except OSError:
  1928. self._handle_on_connect_fail()
  1929. self._easy_log(
  1930. MQTT_LOG_DEBUG, "Connection failed, retrying")
  1931. return rc
  1932. def loop_start(self) -> MQTTErrorCode:
  1933. """This is part of the threaded client interface. Call this once to
  1934. start a new thread to process network traffic. This provides an
  1935. alternative to repeatedly calling `loop()` yourself.
  1936. Under the hood, this will call `loop_forever` in a thread, which means that
  1937. the thread will terminate if you call `disconnect()`
  1938. """
  1939. if self._thread is not None:
  1940. return MQTTErrorCode.MQTT_ERR_INVAL
  1941. self._sockpairR, self._sockpairW = _socketpair_compat()
  1942. self._thread_terminate = False
  1943. self._thread = threading.Thread(target=self._thread_main, name=f"paho-mqtt-client-{self._client_id.decode()}")
  1944. self._thread.daemon = True
  1945. self._thread.start()
  1946. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1947. def loop_stop(self) -> MQTTErrorCode:
  1948. """This is part of the threaded client interface. Call this once to
  1949. stop the network thread previously created with `loop_start()`. This call
  1950. will block until the network thread finishes.
  1951. This don't guarantee that publish packet are sent, use `wait_for_publish` or
  1952. `on_publish` to ensure `publish` are sent.
  1953. """
  1954. if self._thread is None:
  1955. return MQTTErrorCode.MQTT_ERR_INVAL
  1956. self._thread_terminate = True
  1957. if threading.current_thread() != self._thread:
  1958. self._thread.join()
  1959. return MQTTErrorCode.MQTT_ERR_SUCCESS
  1960. @property
  1961. def callback_api_version(self) -> CallbackAPIVersion:
  1962. """
  1963. Return the callback API version used for user-callback. See docstring for
  1964. each user-callback (`on_connect`, `on_publish`, ...) for details.
  1965. This property is read-only.
  1966. """
  1967. return self._callback_api_version
  1968. @property
  1969. def on_log(self) -> CallbackOnLog | None:
  1970. """The callback called when the client has log information.
  1971. Defined to allow debugging.
  1972. Expected signature is::
  1973. log_callback(client, userdata, level, buf)
  1974. :param Client client: the client instance for this callback
  1975. :param userdata: the private user data as set in Client() or user_data_set()
  1976. :param int level: gives the severity of the message and will be one of
  1977. MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING,
  1978. MQTT_LOG_ERR, and MQTT_LOG_DEBUG.
  1979. :param str buf: the message itself
  1980. Decorator: @client.log_callback() (``client`` is the name of the
  1981. instance which this callback is being attached to)
  1982. """
  1983. return self._on_log
  1984. @on_log.setter
  1985. def on_log(self, func: CallbackOnLog | None) -> None:
  1986. self._on_log = func
  1987. def log_callback(self) -> Callable[[CallbackOnLog], CallbackOnLog]:
  1988. def decorator(func: CallbackOnLog) -> CallbackOnLog:
  1989. self.on_log = func
  1990. return func
  1991. return decorator
  1992. @property
  1993. def on_pre_connect(self) -> CallbackOnPreConnect | None:
  1994. """The callback called immediately prior to the connection is made
  1995. request.
  1996. Expected signature (for all callback API version)::
  1997. connect_callback(client, userdata)
  1998. :parama Client client: the client instance for this callback
  1999. :parama userdata: the private user data as set in Client() or user_data_set()
  2000. Decorator: @client.pre_connect_callback() (``client`` is the name of the
  2001. instance which this callback is being attached to)
  2002. """
  2003. return self._on_pre_connect
  2004. @on_pre_connect.setter
  2005. def on_pre_connect(self, func: CallbackOnPreConnect | None) -> None:
  2006. with self._callback_mutex:
  2007. self._on_pre_connect = func
  2008. def pre_connect_callback(
  2009. self,
  2010. ) -> Callable[[CallbackOnPreConnect], CallbackOnPreConnect]:
  2011. def decorator(func: CallbackOnPreConnect) -> CallbackOnPreConnect:
  2012. self.on_pre_connect = func
  2013. return func
  2014. return decorator
  2015. @property
  2016. def on_connect(self) -> CallbackOnConnect | None:
  2017. """The callback called when the broker responds to our connection request.
  2018. Expected signature for callback API version 2::
  2019. connect_callback(client, userdata, connect_flags, reason_code, properties)
  2020. Expected signature for callback API version 1 change with MQTT protocol version:
  2021. * For MQTT v3.1 and v3.1.1 it's::
  2022. connect_callback(client, userdata, flags, rc)
  2023. * For MQTT v5.0 it's::
  2024. connect_callback(client, userdata, flags, reason_code, properties)
  2025. :param Client client: the client instance for this callback
  2026. :param userdata: the private user data as set in Client() or user_data_set()
  2027. :param ConnectFlags connect_flags: the flags for this connection
  2028. :param ReasonCode reason_code: the connection reason code received from the broker.
  2029. In MQTT v5.0 it's the reason code defined by the standard.
  2030. In MQTT v3, we convert return code to a reason code, see
  2031. `convert_connack_rc_to_reason_code()`.
  2032. `ReasonCode` may be compared to integer.
  2033. :param Properties properties: the MQTT v5.0 properties received from the broker.
  2034. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
  2035. object is always used.
  2036. :param dict flags: response flags sent by the broker
  2037. :param int rc: the connection result, should have a value of `ConnackCode`
  2038. flags is a dict that contains response flags from the broker:
  2039. flags['session present'] - this flag is useful for clients that are
  2040. using clean session set to 0 only. If a client with clean
  2041. session=0, that reconnects to a broker that it has previously
  2042. connected to, this flag indicates whether the broker still has the
  2043. session information for the client. If 1, the session still exists.
  2044. The value of rc indicates success or not:
  2045. - 0: Connection successful
  2046. - 1: Connection refused - incorrect protocol version
  2047. - 2: Connection refused - invalid client identifier
  2048. - 3: Connection refused - server unavailable
  2049. - 4: Connection refused - bad username or password
  2050. - 5: Connection refused - not authorised
  2051. - 6-255: Currently unused.
  2052. Decorator: @client.connect_callback() (``client`` is the name of the
  2053. instance which this callback is being attached to)
  2054. """
  2055. return self._on_connect
  2056. @on_connect.setter
  2057. def on_connect(self, func: CallbackOnConnect | None) -> None:
  2058. with self._callback_mutex:
  2059. self._on_connect = func
  2060. def connect_callback(
  2061. self,
  2062. ) -> Callable[[CallbackOnConnect], CallbackOnConnect]:
  2063. def decorator(func: CallbackOnConnect) -> CallbackOnConnect:
  2064. self.on_connect = func
  2065. return func
  2066. return decorator
  2067. @property
  2068. def on_connect_fail(self) -> CallbackOnConnectFail | None:
  2069. """The callback called when the client failed to connect
  2070. to the broker.
  2071. Expected signature is (for all callback_api_version)::
  2072. connect_fail_callback(client, userdata)
  2073. :param Client client: the client instance for this callback
  2074. :parama userdata: the private user data as set in Client() or user_data_set()
  2075. Decorator: @client.connect_fail_callback() (``client`` is the name of the
  2076. instance which this callback is being attached to)
  2077. """
  2078. return self._on_connect_fail
  2079. @on_connect_fail.setter
  2080. def on_connect_fail(self, func: CallbackOnConnectFail | None) -> None:
  2081. with self._callback_mutex:
  2082. self._on_connect_fail = func
  2083. def connect_fail_callback(
  2084. self,
  2085. ) -> Callable[[CallbackOnConnectFail], CallbackOnConnectFail]:
  2086. def decorator(func: CallbackOnConnectFail) -> CallbackOnConnectFail:
  2087. self.on_connect_fail = func
  2088. return func
  2089. return decorator
  2090. @property
  2091. def on_subscribe(self) -> CallbackOnSubscribe | None:
  2092. """The callback called when the broker responds to a subscribe
  2093. request.
  2094. Expected signature for callback API version 2::
  2095. subscribe_callback(client, userdata, mid, reason_code_list, properties)
  2096. Expected signature for callback API version 1 change with MQTT protocol version:
  2097. * For MQTT v3.1 and v3.1.1 it's::
  2098. subscribe_callback(client, userdata, mid, granted_qos)
  2099. * For MQTT v5.0 it's::
  2100. subscribe_callback(client, userdata, mid, reason_code_list, properties)
  2101. :param Client client: the client instance for this callback
  2102. :param userdata: the private user data as set in Client() or user_data_set()
  2103. :param int mid: matches the mid variable returned from the corresponding
  2104. subscribe() call.
  2105. :param list[ReasonCode] reason_code_list: reason codes received from the broker for each subscription.
  2106. In MQTT v5.0 it's the reason code defined by the standard.
  2107. In MQTT v3, we convert granted QoS to a reason code.
  2108. It's a list of ReasonCode instances.
  2109. :param Properties properties: the MQTT v5.0 properties received from the broker.
  2110. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
  2111. object is always used.
  2112. :param list[int] granted_qos: list of integers that give the QoS level the broker has
  2113. granted for each of the different subscription requests.
  2114. Decorator: @client.subscribe_callback() (``client`` is the name of the
  2115. instance which this callback is being attached to)
  2116. """
  2117. return self._on_subscribe
  2118. @on_subscribe.setter
  2119. def on_subscribe(self, func: CallbackOnSubscribe | None) -> None:
  2120. with self._callback_mutex:
  2121. self._on_subscribe = func
  2122. def subscribe_callback(
  2123. self,
  2124. ) -> Callable[[CallbackOnSubscribe], CallbackOnSubscribe]:
  2125. def decorator(func: CallbackOnSubscribe) -> CallbackOnSubscribe:
  2126. self.on_subscribe = func
  2127. return func
  2128. return decorator
  2129. @property
  2130. def on_message(self) -> CallbackOnMessage | None:
  2131. """The callback called when a message has been received on a topic
  2132. that the client subscribes to.
  2133. This callback will be called for every message received unless a
  2134. `message_callback_add()` matched the message.
  2135. Expected signature is (for all callback API version):
  2136. message_callback(client, userdata, message)
  2137. :param Client client: the client instance for this callback
  2138. :param userdata: the private user data as set in Client() or user_data_set()
  2139. :param MQTTMessage message: the received message.
  2140. This is a class with members topic, payload, qos, retain.
  2141. Decorator: @client.message_callback() (``client`` is the name of the
  2142. instance which this callback is being attached to)
  2143. """
  2144. return self._on_message
  2145. @on_message.setter
  2146. def on_message(self, func: CallbackOnMessage | None) -> None:
  2147. with self._callback_mutex:
  2148. self._on_message = func
  2149. def message_callback(
  2150. self,
  2151. ) -> Callable[[CallbackOnMessage], CallbackOnMessage]:
  2152. def decorator(func: CallbackOnMessage) -> CallbackOnMessage:
  2153. self.on_message = func
  2154. return func
  2155. return decorator
  2156. @property
  2157. def on_publish(self) -> CallbackOnPublish | None:
  2158. """The callback called when a message that was to be sent using the
  2159. `publish()` call has completed transmission to the broker.
  2160. For messages with QoS levels 1 and 2, this means that the appropriate
  2161. handshakes have completed. For QoS 0, this simply means that the message
  2162. has left the client.
  2163. This callback is important because even if the `publish()` call returns
  2164. success, it does not always mean that the message has been sent.
  2165. See also `wait_for_publish` which could be simpler to use.
  2166. Expected signature for callback API version 2::
  2167. publish_callback(client, userdata, mid, reason_code, properties)
  2168. Expected signature for callback API version 1::
  2169. publish_callback(client, userdata, mid)
  2170. :param Client client: the client instance for this callback
  2171. :param userdata: the private user data as set in Client() or user_data_set()
  2172. :param int mid: matches the mid variable returned from the corresponding
  2173. `publish()` call, to allow outgoing messages to be tracked.
  2174. :param ReasonCode reason_code: the connection reason code received from the broker.
  2175. In MQTT v5.0 it's the reason code defined by the standard.
  2176. In MQTT v3 it's always the reason code Success
  2177. :parama Properties properties: the MQTT v5.0 properties received from the broker.
  2178. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
  2179. object is always used.
  2180. Note: for QoS = 0, the reason_code and the properties don't really exist, it's the client
  2181. library that generate them. It's always an empty properties and a success reason code.
  2182. Because the (MQTTv5) standard don't have reason code for PUBLISH packet, the library create them
  2183. at PUBACK packet, as if the message was sent with QoS = 1.
  2184. Decorator: @client.publish_callback() (``client`` is the name of the
  2185. instance which this callback is being attached to)
  2186. """
  2187. return self._on_publish
  2188. @on_publish.setter
  2189. def on_publish(self, func: CallbackOnPublish | None) -> None:
  2190. with self._callback_mutex:
  2191. self._on_publish = func
  2192. def publish_callback(
  2193. self,
  2194. ) -> Callable[[CallbackOnPublish], CallbackOnPublish]:
  2195. def decorator(func: CallbackOnPublish) -> CallbackOnPublish:
  2196. self.on_publish = func
  2197. return func
  2198. return decorator
  2199. @property
  2200. def on_unsubscribe(self) -> CallbackOnUnsubscribe | None:
  2201. """The callback called when the broker responds to an unsubscribe
  2202. request.
  2203. Expected signature for callback API version 2::
  2204. unsubscribe_callback(client, userdata, mid, reason_code_list, properties)
  2205. Expected signature for callback API version 1 change with MQTT protocol version:
  2206. * For MQTT v3.1 and v3.1.1 it's::
  2207. unsubscribe_callback(client, userdata, mid)
  2208. * For MQTT v5.0 it's::
  2209. unsubscribe_callback(client, userdata, mid, properties, v1_reason_codes)
  2210. :param Client client: the client instance for this callback
  2211. :param userdata: the private user data as set in Client() or user_data_set()
  2212. :param mid: matches the mid variable returned from the corresponding
  2213. unsubscribe() call.
  2214. :param list[ReasonCode] reason_code_list: reason codes received from the broker for each unsubscription.
  2215. In MQTT v5.0 it's the reason code defined by the standard.
  2216. In MQTT v3, there is not equivalent from broken and empty list
  2217. is always used.
  2218. :param Properties properties: the MQTT v5.0 properties received from the broker.
  2219. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
  2220. object is always used.
  2221. :param v1_reason_codes: the MQTT v5.0 reason codes received from the broker for each
  2222. unsubscribe topic. A list of ReasonCode instances OR a single
  2223. ReasonCode when we unsubscribe from a single topic.
  2224. Decorator: @client.unsubscribe_callback() (``client`` is the name of the
  2225. instance which this callback is being attached to)
  2226. """
  2227. return self._on_unsubscribe
  2228. @on_unsubscribe.setter
  2229. def on_unsubscribe(self, func: CallbackOnUnsubscribe | None) -> None:
  2230. with self._callback_mutex:
  2231. self._on_unsubscribe = func
  2232. def unsubscribe_callback(
  2233. self,
  2234. ) -> Callable[[CallbackOnUnsubscribe], CallbackOnUnsubscribe]:
  2235. def decorator(func: CallbackOnUnsubscribe) -> CallbackOnUnsubscribe:
  2236. self.on_unsubscribe = func
  2237. return func
  2238. return decorator
  2239. @property
  2240. def on_disconnect(self) -> CallbackOnDisconnect | None:
  2241. """The callback called when the client disconnects from the broker.
  2242. Expected signature for callback API version 2::
  2243. disconnect_callback(client, userdata, disconnect_flags, reason_code, properties)
  2244. Expected signature for callback API version 1 change with MQTT protocol version:
  2245. * For MQTT v3.1 and v3.1.1 it's::
  2246. disconnect_callback(client, userdata, rc)
  2247. * For MQTT v5.0 it's::
  2248. disconnect_callback(client, userdata, reason_code, properties)
  2249. :param Client client: the client instance for this callback
  2250. :param userdata: the private user data as set in Client() or user_data_set()
  2251. :param DisconnectFlag disconnect_flags: the flags for this disconnection.
  2252. :param ReasonCode reason_code: the disconnection reason code possibly received from the broker (see disconnect_flags).
  2253. In MQTT v5.0 it's the reason code defined by the standard.
  2254. In MQTT v3 it's never received from the broker, we convert an MQTTErrorCode,
  2255. see `convert_disconnect_error_code_to_reason_code()`.
  2256. `ReasonCode` may be compared to integer.
  2257. :param Properties properties: the MQTT v5.0 properties received from the broker.
  2258. For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
  2259. object is always used.
  2260. :param int rc: the disconnection result
  2261. The rc parameter indicates the disconnection state. If
  2262. MQTT_ERR_SUCCESS (0), the callback was called in response to
  2263. a disconnect() call. If any other value the disconnection
  2264. was unexpected, such as might be caused by a network error.
  2265. Decorator: @client.disconnect_callback() (``client`` is the name of the
  2266. instance which this callback is being attached to)
  2267. """
  2268. return self._on_disconnect
  2269. @on_disconnect.setter
  2270. def on_disconnect(self, func: CallbackOnDisconnect | None) -> None:
  2271. with self._callback_mutex:
  2272. self._on_disconnect = func
  2273. def disconnect_callback(
  2274. self,
  2275. ) -> Callable[[CallbackOnDisconnect], CallbackOnDisconnect]:
  2276. def decorator(func: CallbackOnDisconnect) -> CallbackOnDisconnect:
  2277. self.on_disconnect = func
  2278. return func
  2279. return decorator
  2280. @property
  2281. def on_socket_open(self) -> CallbackOnSocket | None:
  2282. """The callback called just after the socket was opened.
  2283. This should be used to register the socket to an external event loop for reading.
  2284. Expected signature is (for all callback API version)::
  2285. socket_open_callback(client, userdata, socket)
  2286. :param Client client: the client instance for this callback
  2287. :param userdata: the private user data as set in Client() or user_data_set()
  2288. :param SocketLike sock: the socket which was just opened.
  2289. Decorator: @client.socket_open_callback() (``client`` is the name of the
  2290. instance which this callback is being attached to)
  2291. """
  2292. return self._on_socket_open
  2293. @on_socket_open.setter
  2294. def on_socket_open(self, func: CallbackOnSocket | None) -> None:
  2295. with self._callback_mutex:
  2296. self._on_socket_open = func
  2297. def socket_open_callback(
  2298. self,
  2299. ) -> Callable[[CallbackOnSocket], CallbackOnSocket]:
  2300. def decorator(func: CallbackOnSocket) -> CallbackOnSocket:
  2301. self.on_socket_open = func
  2302. return func
  2303. return decorator
  2304. def _call_socket_open(self, sock: SocketLike) -> None:
  2305. """Call the socket_open callback with the just-opened socket"""
  2306. with self._callback_mutex:
  2307. on_socket_open = self.on_socket_open
  2308. if on_socket_open:
  2309. with self._in_callback_mutex:
  2310. try:
  2311. on_socket_open(self, self._userdata, sock)
  2312. except Exception as err:
  2313. self._easy_log(
  2314. MQTT_LOG_ERR, 'Caught exception in on_socket_open: %s', err)
  2315. if not self.suppress_exceptions:
  2316. raise
  2317. @property
  2318. def on_socket_close(self) -> CallbackOnSocket | None:
  2319. """The callback called just before the socket is closed.
  2320. This should be used to unregister the socket from an external event loop for reading.
  2321. Expected signature is (for all callback API version)::
  2322. socket_close_callback(client, userdata, socket)
  2323. :param Client client: the client instance for this callback
  2324. :param userdata: the private user data as set in Client() or user_data_set()
  2325. :param SocketLike sock: the socket which is about to be closed.
  2326. Decorator: @client.socket_close_callback() (``client`` is the name of the
  2327. instance which this callback is being attached to)
  2328. """
  2329. return self._on_socket_close
  2330. @on_socket_close.setter
  2331. def on_socket_close(self, func: CallbackOnSocket | None) -> None:
  2332. with self._callback_mutex:
  2333. self._on_socket_close = func
  2334. def socket_close_callback(
  2335. self,
  2336. ) -> Callable[[CallbackOnSocket], CallbackOnSocket]:
  2337. def decorator(func: CallbackOnSocket) -> CallbackOnSocket:
  2338. self.on_socket_close = func
  2339. return func
  2340. return decorator
  2341. def _call_socket_close(self, sock: SocketLike) -> None:
  2342. """Call the socket_close callback with the about-to-be-closed socket"""
  2343. with self._callback_mutex:
  2344. on_socket_close = self.on_socket_close
  2345. if on_socket_close:
  2346. with self._in_callback_mutex:
  2347. try:
  2348. on_socket_close(self, self._userdata, sock)
  2349. except Exception as err:
  2350. self._easy_log(
  2351. MQTT_LOG_ERR, 'Caught exception in on_socket_close: %s', err)
  2352. if not self.suppress_exceptions:
  2353. raise
  2354. @property
  2355. def on_socket_register_write(self) -> CallbackOnSocket | None:
  2356. """The callback called when the socket needs writing but can't.
  2357. This should be used to register the socket with an external event loop for writing.
  2358. Expected signature is (for all callback API version)::
  2359. socket_register_write_callback(client, userdata, socket)
  2360. :param Client client: the client instance for this callback
  2361. :param userdata: the private user data as set in Client() or user_data_set()
  2362. :param SocketLike sock: the socket which should be registered for writing
  2363. Decorator: @client.socket_register_write_callback() (``client`` is the name of the
  2364. instance which this callback is being attached to)
  2365. """
  2366. return self._on_socket_register_write
  2367. @on_socket_register_write.setter
  2368. def on_socket_register_write(self, func: CallbackOnSocket | None) -> None:
  2369. with self._callback_mutex:
  2370. self._on_socket_register_write = func
  2371. def socket_register_write_callback(
  2372. self,
  2373. ) -> Callable[[CallbackOnSocket], CallbackOnSocket]:
  2374. def decorator(func: CallbackOnSocket) -> CallbackOnSocket:
  2375. self._on_socket_register_write = func
  2376. return func
  2377. return decorator
  2378. def _call_socket_register_write(self) -> None:
  2379. """Call the socket_register_write callback with the unwritable socket"""
  2380. if not self._sock or self._registered_write:
  2381. return
  2382. self._registered_write = True
  2383. with self._callback_mutex:
  2384. on_socket_register_write = self.on_socket_register_write
  2385. if on_socket_register_write:
  2386. try:
  2387. on_socket_register_write(
  2388. self, self._userdata, self._sock)
  2389. except Exception as err:
  2390. self._easy_log(
  2391. MQTT_LOG_ERR, 'Caught exception in on_socket_register_write: %s', err)
  2392. if not self.suppress_exceptions:
  2393. raise
  2394. @property
  2395. def on_socket_unregister_write(
  2396. self,
  2397. ) -> CallbackOnSocket | None:
  2398. """The callback called when the socket doesn't need writing anymore.
  2399. This should be used to unregister the socket from an external event loop for writing.
  2400. Expected signature is (for all callback API version)::
  2401. socket_unregister_write_callback(client, userdata, socket)
  2402. :param Client client: the client instance for this callback
  2403. :param userdata: the private user data as set in Client() or user_data_set()
  2404. :param SocketLike sock: the socket which should be unregistered for writing
  2405. Decorator: @client.socket_unregister_write_callback() (``client`` is the name of the
  2406. instance which this callback is being attached to)
  2407. """
  2408. return self._on_socket_unregister_write
  2409. @on_socket_unregister_write.setter
  2410. def on_socket_unregister_write(
  2411. self, func: CallbackOnSocket | None
  2412. ) -> None:
  2413. with self._callback_mutex:
  2414. self._on_socket_unregister_write = func
  2415. def socket_unregister_write_callback(
  2416. self,
  2417. ) -> Callable[[CallbackOnSocket], CallbackOnSocket]:
  2418. def decorator(
  2419. func: CallbackOnSocket,
  2420. ) -> CallbackOnSocket:
  2421. self._on_socket_unregister_write = func
  2422. return func
  2423. return decorator
  2424. def _call_socket_unregister_write(
  2425. self, sock: SocketLike | None = None
  2426. ) -> None:
  2427. """Call the socket_unregister_write callback with the writable socket"""
  2428. sock = sock or self._sock
  2429. if not sock or not self._registered_write:
  2430. return
  2431. self._registered_write = False
  2432. with self._callback_mutex:
  2433. on_socket_unregister_write = self.on_socket_unregister_write
  2434. if on_socket_unregister_write:
  2435. try:
  2436. on_socket_unregister_write(self, self._userdata, sock)
  2437. except Exception as err:
  2438. self._easy_log(
  2439. MQTT_LOG_ERR, 'Caught exception in on_socket_unregister_write: %s', err)
  2440. if not self.suppress_exceptions:
  2441. raise
  2442. def message_callback_add(self, sub: str, callback: CallbackOnMessage) -> None:
  2443. """Register a message callback for a specific topic.
  2444. Messages that match 'sub' will be passed to 'callback'. Any
  2445. non-matching messages will be passed to the default `on_message`
  2446. callback.
  2447. Call multiple times with different 'sub' to define multiple topic
  2448. specific callbacks.
  2449. Topic specific callbacks may be removed with
  2450. `message_callback_remove()`.
  2451. See `on_message` for the expected signature of the callback.
  2452. Decorator: @client.topic_callback(sub) (``client`` is the name of the
  2453. instance which this callback is being attached to)
  2454. Example::
  2455. @client.topic_callback("mytopic/#")
  2456. def handle_mytopic(client, userdata, message):
  2457. ...
  2458. """
  2459. if callback is None or sub is None:
  2460. raise ValueError("sub and callback must both be defined.")
  2461. with self._callback_mutex:
  2462. self._on_message_filtered[sub] = callback
  2463. def topic_callback(
  2464. self, sub: str
  2465. ) -> Callable[[CallbackOnMessage], CallbackOnMessage]:
  2466. def decorator(func: CallbackOnMessage) -> CallbackOnMessage:
  2467. self.message_callback_add(sub, func)
  2468. return func
  2469. return decorator
  2470. def message_callback_remove(self, sub: str) -> None:
  2471. """Remove a message callback previously registered with
  2472. `message_callback_add()`."""
  2473. if sub is None:
  2474. raise ValueError("sub must defined.")
  2475. with self._callback_mutex:
  2476. try:
  2477. del self._on_message_filtered[sub]
  2478. except KeyError: # no such subscription
  2479. pass
  2480. # ============================================================
  2481. # Private functions
  2482. # ============================================================
  2483. def _loop_rc_handle(
  2484. self,
  2485. rc: MQTTErrorCode,
  2486. ) -> MQTTErrorCode:
  2487. if rc:
  2488. self._sock_close()
  2489. if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED):
  2490. self._state = _ConnectionState.MQTT_CS_DISCONNECTED
  2491. rc = MQTTErrorCode.MQTT_ERR_SUCCESS
  2492. self._do_on_disconnect(packet_from_broker=False, v1_rc=rc)
  2493. if rc == MQTT_ERR_CONN_LOST:
  2494. self._state = _ConnectionState.MQTT_CS_CONNECTION_LOST
  2495. return rc
  2496. def _packet_read(self) -> MQTTErrorCode:
  2497. # This gets called if pselect() indicates that there is network data
  2498. # available - ie. at least one byte. What we do depends on what data we
  2499. # already have.
  2500. # If we've not got a command, attempt to read one and save it. This should
  2501. # always work because it's only a single byte.
  2502. # Then try to read the remaining length. This may fail because it is may
  2503. # be more than one byte - will need to save data pending next read if it
  2504. # does fail.
  2505. # Then try to read the remaining payload, where 'payload' here means the
  2506. # combined variable header and actual payload. This is the most likely to
  2507. # fail due to longer length, so save current data and current position.
  2508. # After all data is read, send to _mqtt_handle_packet() to deal with.
  2509. # Finally, free the memory and reset everything to starting conditions.
  2510. if self._in_packet['command'] == 0:
  2511. try:
  2512. command = self._sock_recv(1)
  2513. except BlockingIOError:
  2514. return MQTTErrorCode.MQTT_ERR_AGAIN
  2515. except TimeoutError as err:
  2516. self._easy_log(
  2517. MQTT_LOG_ERR, 'timeout on socket: %s', err)
  2518. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2519. except OSError as err:
  2520. self._easy_log(
  2521. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  2522. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2523. else:
  2524. if len(command) == 0:
  2525. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2526. self._in_packet['command'] = command[0]
  2527. if self._in_packet['have_remaining'] == 0:
  2528. # Read remaining
  2529. # Algorithm for decoding taken from pseudo code at
  2530. # http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/topic/com.ibm.etools.mft.doc/ac10870_.htm
  2531. while True:
  2532. try:
  2533. byte = self._sock_recv(1)
  2534. except BlockingIOError:
  2535. return MQTTErrorCode.MQTT_ERR_AGAIN
  2536. except OSError as err:
  2537. self._easy_log(
  2538. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  2539. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2540. else:
  2541. if len(byte) == 0:
  2542. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2543. byte_value = byte[0]
  2544. self._in_packet['remaining_count'].append(byte_value)
  2545. # Max 4 bytes length for remaining length as defined by protocol.
  2546. # Anything more likely means a broken/malicious client.
  2547. if len(self._in_packet['remaining_count']) > 4:
  2548. return MQTTErrorCode.MQTT_ERR_PROTOCOL
  2549. self._in_packet['remaining_length'] += (
  2550. byte_value & 127) * self._in_packet['remaining_mult']
  2551. self._in_packet['remaining_mult'] = self._in_packet['remaining_mult'] * 128
  2552. if (byte_value & 128) == 0:
  2553. break
  2554. self._in_packet['have_remaining'] = 1
  2555. self._in_packet['to_process'] = self._in_packet['remaining_length']
  2556. count = 100 # Don't get stuck in this loop if we have a huge message.
  2557. while self._in_packet['to_process'] > 0:
  2558. try:
  2559. data = self._sock_recv(self._in_packet['to_process'])
  2560. except BlockingIOError:
  2561. return MQTTErrorCode.MQTT_ERR_AGAIN
  2562. except OSError as err:
  2563. self._easy_log(
  2564. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  2565. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2566. else:
  2567. if len(data) == 0:
  2568. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2569. self._in_packet['to_process'] -= len(data)
  2570. self._in_packet['packet'] += data
  2571. with self._msgtime_mutex:
  2572. self._last_bytes_received = time_func()
  2573. count -= 1
  2574. if count == 0:
  2575. return MQTTErrorCode.MQTT_ERR_AGAIN
  2576. # All data for this packet is read.
  2577. self._in_packet['pos'] = 0
  2578. try:
  2579. rc = self._packet_handle()
  2580. except MalformedPacket as exc:
  2581. self._easy_log(MQTT_LOG_DEBUG, "Received malformed packet: %s", exc)
  2582. rc = MQTTErrorCode.MQTT_ERR_PROTOCOL
  2583. # Free data and reset values
  2584. self._in_packet = {
  2585. "command": 0,
  2586. "have_remaining": 0,
  2587. "remaining_count": [],
  2588. "remaining_mult": 1,
  2589. "remaining_length": 0,
  2590. "packet": bytearray(b""),
  2591. "to_process": 0,
  2592. "pos": 0,
  2593. }
  2594. with self._msgtime_mutex:
  2595. self._last_bytes_received = time_func()
  2596. return rc
  2597. def _packet_write(self) -> MQTTErrorCode:
  2598. while True:
  2599. try:
  2600. packet = self._out_packet.popleft()
  2601. except IndexError:
  2602. return MQTTErrorCode.MQTT_ERR_SUCCESS
  2603. try:
  2604. write_length = self._sock_send(
  2605. packet['packet'][packet['pos']:])
  2606. except (AttributeError, ValueError):
  2607. self._out_packet.appendleft(packet)
  2608. return MQTTErrorCode.MQTT_ERR_SUCCESS
  2609. except BlockingIOError:
  2610. self._out_packet.appendleft(packet)
  2611. return MQTTErrorCode.MQTT_ERR_AGAIN
  2612. except OSError as err:
  2613. self._out_packet.appendleft(packet)
  2614. self._easy_log(
  2615. MQTT_LOG_ERR, 'failed to receive on socket: %s', err)
  2616. return MQTTErrorCode.MQTT_ERR_CONN_LOST
  2617. if write_length > 0:
  2618. packet['to_process'] -= write_length
  2619. packet['pos'] += write_length
  2620. if packet['to_process'] == 0:
  2621. if (packet['command'] & 0xF0) == PUBLISH and packet['qos'] == 0:
  2622. with self._callback_mutex:
  2623. on_publish = self.on_publish
  2624. if on_publish:
  2625. with self._in_callback_mutex:
  2626. try:
  2627. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  2628. on_publish = cast(CallbackOnPublish_v1, on_publish)
  2629. on_publish(self, self._userdata, packet["mid"])
  2630. elif self._callback_api_version == CallbackAPIVersion.VERSION2:
  2631. on_publish = cast(CallbackOnPublish_v2, on_publish)
  2632. on_publish(
  2633. self,
  2634. self._userdata,
  2635. packet["mid"],
  2636. ReasonCode(PacketTypes.PUBACK),
  2637. Properties(PacketTypes.PUBACK),
  2638. )
  2639. else:
  2640. raise RuntimeError("Unsupported callback API version")
  2641. except Exception as err:
  2642. self._easy_log(
  2643. MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err)
  2644. if not self.suppress_exceptions:
  2645. raise
  2646. # TODO: Something is odd here. I don't see why packet["info"] can't be None.
  2647. # A packet could be produced by _handle_connack with qos=0 and no info
  2648. # (around line 3645). Ignore the mypy check for now but I feel there is a bug
  2649. # somewhere.
  2650. packet['info']._set_as_published() # type: ignore
  2651. if (packet['command'] & 0xF0) == DISCONNECT:
  2652. with self._msgtime_mutex:
  2653. self._last_msg_out = time_func()
  2654. self._do_on_disconnect(
  2655. packet_from_broker=False,
  2656. v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS,
  2657. )
  2658. self._sock_close()
  2659. # Only change to disconnected if the disconnection was wanted
  2660. # by the client (== state was disconnecting). If the broker disconnected
  2661. # use unilaterally don't change the state and client may reconnect.
  2662. if self._state == _ConnectionState.MQTT_CS_DISCONNECTING:
  2663. self._state = _ConnectionState.MQTT_CS_DISCONNECTED
  2664. return MQTTErrorCode.MQTT_ERR_SUCCESS
  2665. else:
  2666. # We haven't finished with this packet
  2667. self._out_packet.appendleft(packet)
  2668. else:
  2669. break
  2670. with self._msgtime_mutex:
  2671. self._last_msg_out = time_func()
  2672. return MQTTErrorCode.MQTT_ERR_SUCCESS
  2673. def _easy_log(self, level: LogLevel, fmt: str, *args: Any) -> None:
  2674. if self.on_log is not None:
  2675. buf = fmt % args
  2676. try:
  2677. self.on_log(self, self._userdata, level, buf)
  2678. except Exception: # noqa: S110,BLE001
  2679. # Can't _easy_log this, as we'll recurse until we break
  2680. pass # self._logger will pick this up, so we're fine
  2681. if self._logger is not None:
  2682. level_std = LOGGING_LEVEL[level]
  2683. self._logger.log(level_std, fmt, *args)
  2684. def _check_keepalive(self) -> None:
  2685. if self._keepalive == 0:
  2686. return
  2687. now = time_func()
  2688. with self._msgtime_mutex:
  2689. last_msg_out = self._last_msg_out
  2690. last_bytes_received = self._last_bytes_received
  2691. if self._sock is not None and (now - last_msg_out >= self._keepalive or now - last_bytes_received >= self._keepalive):
  2692. if self._state == _ConnectionState.MQTT_CS_CONNECTED and (self._ping_t == 0 or now - last_bytes_received < self.keepalive):
  2693. try:
  2694. if self._ping_t == 0 or now - self._ping_t >= self._keepalive:
  2695. self._send_pingreq()
  2696. except Exception: # noqa: BLE001
  2697. self._sock_close()
  2698. self._do_on_disconnect(
  2699. packet_from_broker=False,
  2700. v1_rc=MQTTErrorCode.MQTT_ERR_CONN_LOST,
  2701. )
  2702. else:
  2703. with self._msgtime_mutex:
  2704. self._last_msg_out = now
  2705. self._last_bytes_received = now
  2706. else:
  2707. self._sock_close()
  2708. if self._state in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED):
  2709. self._state = _ConnectionState.MQTT_CS_DISCONNECTED
  2710. rc = MQTTErrorCode.MQTT_ERR_SUCCESS
  2711. else:
  2712. rc = MQTTErrorCode.MQTT_ERR_KEEPALIVE
  2713. self._do_on_disconnect(
  2714. packet_from_broker=False,
  2715. v1_rc=rc,
  2716. )
  2717. def _mid_generate(self) -> int:
  2718. with self._mid_generate_mutex:
  2719. self._last_mid += 1
  2720. if self._last_mid == 65536:
  2721. self._last_mid = 1
  2722. return self._last_mid
  2723. @staticmethod
  2724. def _raise_for_invalid_topic(topic: bytes) -> None:
  2725. """ Check if the topic is a topic without wildcard and valid length.
  2726. Raise ValueError if the topic isn't valid.
  2727. """
  2728. if b'+' in topic or b'#' in topic:
  2729. raise ValueError('Publish topic cannot contain wildcards.')
  2730. if len(topic) > 65535:
  2731. raise ValueError('Publish topic is too long.')
  2732. @staticmethod
  2733. def _filter_wildcard_len_check(sub: bytes) -> MQTTErrorCode:
  2734. if (len(sub) == 0 or len(sub) > 65535
  2735. or any(b'+' in p or b'#' in p for p in sub.split(b'/') if len(p) > 1)
  2736. or b'#/' in sub):
  2737. return MQTTErrorCode.MQTT_ERR_INVAL
  2738. else:
  2739. return MQTTErrorCode.MQTT_ERR_SUCCESS
  2740. def _send_pingreq(self) -> MQTTErrorCode:
  2741. self._easy_log(MQTT_LOG_DEBUG, "Sending PINGREQ")
  2742. rc = self._send_simple_command(PINGREQ)
  2743. if rc == MQTTErrorCode.MQTT_ERR_SUCCESS:
  2744. self._ping_t = time_func()
  2745. return rc
  2746. def _send_pingresp(self) -> MQTTErrorCode:
  2747. self._easy_log(MQTT_LOG_DEBUG, "Sending PINGRESP")
  2748. return self._send_simple_command(PINGRESP)
  2749. def _send_puback(self, mid: int) -> MQTTErrorCode:
  2750. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBACK (Mid: %d)", mid)
  2751. return self._send_command_with_mid(PUBACK, mid, False)
  2752. def _send_pubcomp(self, mid: int) -> MQTTErrorCode:
  2753. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBCOMP (Mid: %d)", mid)
  2754. return self._send_command_with_mid(PUBCOMP, mid, False)
  2755. def _pack_remaining_length(
  2756. self, packet: bytearray, remaining_length: int
  2757. ) -> bytearray:
  2758. remaining_bytes = []
  2759. if remaining_length > 268_435_455:
  2760. raise ValueError("Packet too large")
  2761. while True:
  2762. byte = remaining_length % 128
  2763. remaining_length = remaining_length // 128
  2764. # If there are more digits to encode, set the top bit of this digit
  2765. if remaining_length > 0:
  2766. byte |= 0x80
  2767. remaining_bytes.append(byte)
  2768. packet.append(byte)
  2769. if remaining_length == 0:
  2770. return packet
  2771. def _pack_str16(self, packet: bytearray, data: bytearray | bytes | str) -> None:
  2772. data = _force_bytes(data)
  2773. packet.extend(struct.pack("!H", len(data)))
  2774. packet.extend(data)
  2775. def _send_publish(
  2776. self,
  2777. mid: int,
  2778. topic: bytes,
  2779. payload: bytes | bytearray = b"",
  2780. qos: int = 0,
  2781. retain: bool = False,
  2782. dup: bool = False,
  2783. info: MQTTMessageInfo | None = None,
  2784. properties: Properties | None = None,
  2785. ) -> MQTTErrorCode:
  2786. # we assume that topic and payload are already properly encoded
  2787. if not isinstance(topic, bytes):
  2788. raise TypeError('topic must be bytes, not str')
  2789. if payload and not isinstance(payload, (bytes, bytearray)):
  2790. raise TypeError('payload must be bytes if set')
  2791. if self._sock is None:
  2792. return MQTTErrorCode.MQTT_ERR_NO_CONN
  2793. command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain
  2794. packet = bytearray()
  2795. packet.append(command)
  2796. payloadlen = len(payload)
  2797. remaining_length = 2 + len(topic) + payloadlen
  2798. if payloadlen == 0:
  2799. if self._protocol == MQTTv5:
  2800. self._easy_log(
  2801. MQTT_LOG_DEBUG,
  2802. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s (NULL payload)",
  2803. dup, qos, retain, mid, topic, properties
  2804. )
  2805. else:
  2806. self._easy_log(
  2807. MQTT_LOG_DEBUG,
  2808. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s' (NULL payload)",
  2809. dup, qos, retain, mid, topic
  2810. )
  2811. else:
  2812. if self._protocol == MQTTv5:
  2813. self._easy_log(
  2814. MQTT_LOG_DEBUG,
  2815. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)",
  2816. dup, qos, retain, mid, topic, properties, payloadlen
  2817. )
  2818. else:
  2819. self._easy_log(
  2820. MQTT_LOG_DEBUG,
  2821. "Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)",
  2822. dup, qos, retain, mid, topic, payloadlen
  2823. )
  2824. if qos > 0:
  2825. # For message id
  2826. remaining_length += 2
  2827. if self._protocol == MQTTv5:
  2828. if properties is None:
  2829. packed_properties = b'\x00'
  2830. else:
  2831. packed_properties = properties.pack()
  2832. remaining_length += len(packed_properties)
  2833. self._pack_remaining_length(packet, remaining_length)
  2834. self._pack_str16(packet, topic)
  2835. if qos > 0:
  2836. # For message id
  2837. packet.extend(struct.pack("!H", mid))
  2838. if self._protocol == MQTTv5:
  2839. packet.extend(packed_properties)
  2840. packet.extend(payload)
  2841. return self._packet_queue(PUBLISH, packet, mid, qos, info)
  2842. def _send_pubrec(self, mid: int) -> MQTTErrorCode:
  2843. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREC (Mid: %d)", mid)
  2844. return self._send_command_with_mid(PUBREC, mid, False)
  2845. def _send_pubrel(self, mid: int) -> MQTTErrorCode:
  2846. self._easy_log(MQTT_LOG_DEBUG, "Sending PUBREL (Mid: %d)", mid)
  2847. return self._send_command_with_mid(PUBREL | 2, mid, False)
  2848. def _send_command_with_mid(self, command: int, mid: int, dup: int) -> MQTTErrorCode:
  2849. # For PUBACK, PUBCOMP, PUBREC, and PUBREL
  2850. if dup:
  2851. command |= 0x8
  2852. remaining_length = 2
  2853. packet = struct.pack('!BBH', command, remaining_length, mid)
  2854. return self._packet_queue(command, packet, mid, 1)
  2855. def _send_simple_command(self, command: int) -> MQTTErrorCode:
  2856. # For DISCONNECT, PINGREQ and PINGRESP
  2857. remaining_length = 0
  2858. packet = struct.pack('!BB', command, remaining_length)
  2859. return self._packet_queue(command, packet, 0, 0)
  2860. def _send_connect(self, keepalive: int) -> MQTTErrorCode:
  2861. proto_ver = int(self._protocol)
  2862. # hard-coded UTF-8 encoded string
  2863. protocol = b"MQTT" if proto_ver >= MQTTv311 else b"MQIsdp"
  2864. remaining_length = 2 + len(protocol) + 1 + \
  2865. 1 + 2 + 2 + len(self._client_id)
  2866. connect_flags = 0
  2867. if self._protocol == MQTTv5:
  2868. if self._clean_start is True or (self._clean_start == MQTT_CLEAN_START_FIRST_ONLY and self._mqttv5_first_connect):
  2869. connect_flags |= 0x02
  2870. elif self._clean_session:
  2871. connect_flags |= 0x02
  2872. if self._will:
  2873. remaining_length += 2 + \
  2874. len(self._will_topic) + 2 + len(self._will_payload)
  2875. connect_flags |= 0x04 | ((self._will_qos & 0x03) << 3) | (
  2876. (self._will_retain & 0x01) << 5)
  2877. if self._username is not None:
  2878. remaining_length += 2 + len(self._username)
  2879. connect_flags |= 0x80
  2880. if self._password is not None:
  2881. connect_flags |= 0x40
  2882. remaining_length += 2 + len(self._password)
  2883. if self._protocol == MQTTv5:
  2884. if self._connect_properties is None:
  2885. packed_connect_properties = b'\x00'
  2886. else:
  2887. packed_connect_properties = self._connect_properties.pack()
  2888. remaining_length += len(packed_connect_properties)
  2889. if self._will:
  2890. if self._will_properties is None:
  2891. packed_will_properties = b'\x00'
  2892. else:
  2893. packed_will_properties = self._will_properties.pack()
  2894. remaining_length += len(packed_will_properties)
  2895. command = CONNECT
  2896. packet = bytearray()
  2897. packet.append(command)
  2898. # as per the mosquitto broker, if the MSB of this version is set
  2899. # to 1, then it treats the connection as a bridge
  2900. if self._client_mode == MQTT_BRIDGE:
  2901. proto_ver |= 0x80
  2902. self._pack_remaining_length(packet, remaining_length)
  2903. packet.extend(struct.pack(
  2904. f"!H{len(protocol)}sBBH",
  2905. len(protocol), protocol, proto_ver, connect_flags, keepalive,
  2906. ))
  2907. if self._protocol == MQTTv5:
  2908. packet += packed_connect_properties
  2909. self._pack_str16(packet, self._client_id)
  2910. if self._will:
  2911. if self._protocol == MQTTv5:
  2912. packet += packed_will_properties
  2913. self._pack_str16(packet, self._will_topic)
  2914. self._pack_str16(packet, self._will_payload)
  2915. if self._username is not None:
  2916. self._pack_str16(packet, self._username)
  2917. if self._password is not None:
  2918. self._pack_str16(packet, self._password)
  2919. self._keepalive = keepalive
  2920. if self._protocol == MQTTv5:
  2921. self._easy_log(
  2922. MQTT_LOG_DEBUG,
  2923. "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%s",
  2924. (connect_flags & 0x80) >> 7,
  2925. (connect_flags & 0x40) >> 6,
  2926. (connect_flags & 0x20) >> 5,
  2927. (connect_flags & 0x18) >> 3,
  2928. (connect_flags & 0x4) >> 2,
  2929. (connect_flags & 0x2) >> 1,
  2930. keepalive,
  2931. self._client_id,
  2932. self._connect_properties
  2933. )
  2934. else:
  2935. self._easy_log(
  2936. MQTT_LOG_DEBUG,
  2937. "Sending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s",
  2938. (connect_flags & 0x80) >> 7,
  2939. (connect_flags & 0x40) >> 6,
  2940. (connect_flags & 0x20) >> 5,
  2941. (connect_flags & 0x18) >> 3,
  2942. (connect_flags & 0x4) >> 2,
  2943. (connect_flags & 0x2) >> 1,
  2944. keepalive,
  2945. self._client_id
  2946. )
  2947. return self._packet_queue(command, packet, 0, 0)
  2948. def _send_disconnect(
  2949. self,
  2950. reasoncode: ReasonCode | None = None,
  2951. properties: Properties | None = None,
  2952. ) -> MQTTErrorCode:
  2953. if self._protocol == MQTTv5:
  2954. self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT reasonCode=%s properties=%s",
  2955. reasoncode,
  2956. properties
  2957. )
  2958. else:
  2959. self._easy_log(MQTT_LOG_DEBUG, "Sending DISCONNECT")
  2960. remaining_length = 0
  2961. command = DISCONNECT
  2962. packet = bytearray()
  2963. packet.append(command)
  2964. if self._protocol == MQTTv5 and (properties is not None or reasoncode is not None):
  2965. if reasoncode is None:
  2966. reasoncode = ReasonCode(DISCONNECT >> 4, identifier=0)
  2967. remaining_length += 1
  2968. if properties is not None:
  2969. packed_props = properties.pack()
  2970. remaining_length += len(packed_props)
  2971. self._pack_remaining_length(packet, remaining_length)
  2972. if self._protocol == MQTTv5 and reasoncode is not None:
  2973. packet += reasoncode.pack()
  2974. if properties is not None:
  2975. packet += packed_props
  2976. return self._packet_queue(command, packet, 0, 0)
  2977. def _send_subscribe(
  2978. self,
  2979. dup: int,
  2980. topics: Sequence[tuple[bytes, SubscribeOptions | int]],
  2981. properties: Properties | None = None,
  2982. ) -> tuple[MQTTErrorCode, int]:
  2983. remaining_length = 2
  2984. if self._protocol == MQTTv5:
  2985. if properties is None:
  2986. packed_subscribe_properties = b'\x00'
  2987. else:
  2988. packed_subscribe_properties = properties.pack()
  2989. remaining_length += len(packed_subscribe_properties)
  2990. for t, _ in topics:
  2991. remaining_length += 2 + len(t) + 1
  2992. command = SUBSCRIBE | (dup << 3) | 0x2
  2993. packet = bytearray()
  2994. packet.append(command)
  2995. self._pack_remaining_length(packet, remaining_length)
  2996. local_mid = self._mid_generate()
  2997. packet.extend(struct.pack("!H", local_mid))
  2998. if self._protocol == MQTTv5:
  2999. packet += packed_subscribe_properties
  3000. for t, q in topics:
  3001. self._pack_str16(packet, t)
  3002. if self._protocol == MQTTv5:
  3003. packet += q.pack() # type: ignore
  3004. else:
  3005. packet.append(q) # type: ignore
  3006. self._easy_log(
  3007. MQTT_LOG_DEBUG,
  3008. "Sending SUBSCRIBE (d%d, m%d) %s",
  3009. dup,
  3010. local_mid,
  3011. topics,
  3012. )
  3013. return (self._packet_queue(command, packet, local_mid, 1), local_mid)
  3014. def _send_unsubscribe(
  3015. self,
  3016. dup: int,
  3017. topics: list[bytes],
  3018. properties: Properties | None = None,
  3019. ) -> tuple[MQTTErrorCode, int]:
  3020. remaining_length = 2
  3021. if self._protocol == MQTTv5:
  3022. if properties is None:
  3023. packed_unsubscribe_properties = b'\x00'
  3024. else:
  3025. packed_unsubscribe_properties = properties.pack()
  3026. remaining_length += len(packed_unsubscribe_properties)
  3027. for t in topics:
  3028. remaining_length += 2 + len(t)
  3029. command = UNSUBSCRIBE | (dup << 3) | 0x2
  3030. packet = bytearray()
  3031. packet.append(command)
  3032. self._pack_remaining_length(packet, remaining_length)
  3033. local_mid = self._mid_generate()
  3034. packet.extend(struct.pack("!H", local_mid))
  3035. if self._protocol == MQTTv5:
  3036. packet += packed_unsubscribe_properties
  3037. for t in topics:
  3038. self._pack_str16(packet, t)
  3039. # topics_repr = ", ".join("'"+topic.decode('utf8')+"'" for topic in topics)
  3040. if self._protocol == MQTTv5:
  3041. self._easy_log(
  3042. MQTT_LOG_DEBUG,
  3043. "Sending UNSUBSCRIBE (d%d, m%d) %s %s",
  3044. dup,
  3045. local_mid,
  3046. properties,
  3047. topics,
  3048. )
  3049. else:
  3050. self._easy_log(
  3051. MQTT_LOG_DEBUG,
  3052. "Sending UNSUBSCRIBE (d%d, m%d) %s",
  3053. dup,
  3054. local_mid,
  3055. topics,
  3056. )
  3057. return (self._packet_queue(command, packet, local_mid, 1), local_mid)
  3058. def _check_clean_session(self) -> bool:
  3059. if self._protocol == MQTTv5:
  3060. if self._clean_start == MQTT_CLEAN_START_FIRST_ONLY:
  3061. return self._mqttv5_first_connect
  3062. else:
  3063. return self._clean_start # type: ignore
  3064. else:
  3065. return self._clean_session
  3066. def _messages_reconnect_reset_out(self) -> None:
  3067. with self._out_message_mutex:
  3068. self._inflight_messages = 0
  3069. for m in self._out_messages.values():
  3070. m.timestamp = 0
  3071. if self._max_inflight_messages == 0 or self._inflight_messages < self._max_inflight_messages:
  3072. if m.qos == 0:
  3073. m.state = mqtt_ms_publish
  3074. elif m.qos == 1:
  3075. if m.state == mqtt_ms_wait_for_puback:
  3076. m.dup = True
  3077. m.state = mqtt_ms_publish
  3078. elif m.qos == 2:
  3079. if self._check_clean_session():
  3080. if m.state != mqtt_ms_publish:
  3081. m.dup = True
  3082. m.state = mqtt_ms_publish
  3083. else:
  3084. if m.state == mqtt_ms_wait_for_pubcomp:
  3085. m.state = mqtt_ms_resend_pubrel
  3086. else:
  3087. if m.state == mqtt_ms_wait_for_pubrec:
  3088. m.dup = True
  3089. m.state = mqtt_ms_publish
  3090. else:
  3091. m.state = mqtt_ms_queued
  3092. def _messages_reconnect_reset_in(self) -> None:
  3093. with self._in_message_mutex:
  3094. if self._check_clean_session():
  3095. self._in_messages = collections.OrderedDict()
  3096. return
  3097. for m in self._in_messages.values():
  3098. m.timestamp = 0
  3099. if m.qos != 2:
  3100. self._in_messages.pop(m.mid)
  3101. else:
  3102. # Preserve current state
  3103. pass
  3104. def _messages_reconnect_reset(self) -> None:
  3105. self._messages_reconnect_reset_out()
  3106. self._messages_reconnect_reset_in()
  3107. def _packet_queue(
  3108. self,
  3109. command: int,
  3110. packet: bytes | bytearray,
  3111. mid: int,
  3112. qos: int,
  3113. info: MQTTMessageInfo | None = None,
  3114. ) -> MQTTErrorCode:
  3115. mpkt: _OutPacket = {
  3116. "command": command,
  3117. "mid": mid,
  3118. "qos": qos,
  3119. "pos": 0,
  3120. "to_process": len(packet),
  3121. "packet": packet,
  3122. "info": info,
  3123. }
  3124. self._out_packet.append(mpkt)
  3125. # Write a single byte to sockpairW (connected to sockpairR) to break
  3126. # out of select() if in threaded mode.
  3127. if self._sockpairW is not None:
  3128. try:
  3129. self._sockpairW.send(sockpair_data)
  3130. except BlockingIOError:
  3131. pass
  3132. # If we have an external event loop registered, use that instead
  3133. # of calling loop_write() directly.
  3134. if self._thread is None and self._on_socket_register_write is None and self._in_callback_mutex.acquire(False):
  3135. self._in_callback_mutex.release()
  3136. return self.loop_write()
  3137. self._call_socket_register_write()
  3138. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3139. def _packet_handle(self) -> MQTTErrorCode:
  3140. cmd = self._in_packet['command'] & 0xF0
  3141. if cmd == PINGREQ:
  3142. return self._handle_pingreq()
  3143. elif cmd == PINGRESP:
  3144. return self._handle_pingresp()
  3145. elif cmd == PUBACK:
  3146. return self._handle_pubackcomp("PUBACK")
  3147. elif cmd == PUBCOMP:
  3148. return self._handle_pubackcomp("PUBCOMP")
  3149. elif cmd == PUBLISH:
  3150. return self._handle_publish()
  3151. elif cmd == PUBREC:
  3152. return self._handle_pubrec()
  3153. elif cmd == PUBREL:
  3154. return self._handle_pubrel()
  3155. elif cmd == CONNACK:
  3156. return self._handle_connack()
  3157. elif cmd == SUBACK:
  3158. self._handle_suback()
  3159. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3160. elif cmd == UNSUBACK:
  3161. return self._handle_unsuback()
  3162. elif cmd == DISCONNECT and self._protocol == MQTTv5: # only allowed in MQTT 5.0
  3163. self._handle_disconnect()
  3164. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3165. else:
  3166. # If we don't recognise the command, return an error straight away.
  3167. self._easy_log(MQTT_LOG_ERR, "Error: Unrecognised command %s", cmd)
  3168. return MQTTErrorCode.MQTT_ERR_PROTOCOL
  3169. def _handle_pingreq(self) -> MQTTErrorCode:
  3170. if self._in_packet['remaining_length'] != 0:
  3171. return MQTTErrorCode.MQTT_ERR_PROTOCOL
  3172. self._easy_log(MQTT_LOG_DEBUG, "Received PINGREQ")
  3173. return self._send_pingresp()
  3174. def _handle_pingresp(self) -> MQTTErrorCode:
  3175. if self._in_packet['remaining_length'] != 0:
  3176. return MQTTErrorCode.MQTT_ERR_PROTOCOL
  3177. # No longer waiting for a PINGRESP.
  3178. self._ping_t = 0
  3179. self._easy_log(MQTT_LOG_DEBUG, "Received PINGRESP")
  3180. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3181. def _handle_connack(self) -> MQTTErrorCode:
  3182. result = _packet.decode_connack(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3183. flags = result.flags
  3184. reason = result.reason
  3185. properties = result.properties
  3186. connack_rc = result.rc
  3187. if properties is not None and hasattr(properties, "ServerKeepAlive"):
  3188. # MQTT 5.0: when the server returns a Server Keep Alive in
  3189. # CONNACK, the client must use that value instead of the one
  3190. # it sent (MQTT 5.0 spec 3.2.2.3.14).
  3191. self._keepalive = properties.ServerKeepAlive
  3192. if self._protocol == MQTTv311:
  3193. if connack_rc == CONNACK_REFUSED_PROTOCOL_VERSION:
  3194. if not self._reconnect_on_failure:
  3195. return MQTT_ERR_PROTOCOL
  3196. self._easy_log(
  3197. MQTT_LOG_DEBUG,
  3198. "Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.",
  3199. flags, connack_rc
  3200. )
  3201. # Downgrade to MQTT v3.1
  3202. self._protocol = MQTTv31
  3203. return self.reconnect()
  3204. elif (connack_rc == CONNACK_REFUSED_IDENTIFIER_REJECTED
  3205. and self._client_id == b''):
  3206. if not self._reconnect_on_failure:
  3207. return MQTT_ERR_PROTOCOL
  3208. self._easy_log(
  3209. MQTT_LOG_DEBUG,
  3210. "Received CONNACK (%s, %s), attempting to use non-empty CID",
  3211. flags, connack_rc,
  3212. )
  3213. self._client_id = _base62(uuid.uuid4().int, padding=22).encode("utf8")
  3214. return self.reconnect()
  3215. if connack_rc == 0:
  3216. self._state = _ConnectionState.MQTT_CS_CONNECTED
  3217. self._reconnect_delay = None
  3218. if self._protocol == MQTTv5:
  3219. self._easy_log(
  3220. MQTT_LOG_DEBUG, "Received CONNACK (%s, %s) properties=%s", flags, reason, properties)
  3221. else:
  3222. self._easy_log(
  3223. MQTT_LOG_DEBUG, "Received CONNACK (%s, %s)", flags, connack_rc)
  3224. # it won't be the first successful connect any more
  3225. self._mqttv5_first_connect = False
  3226. with self._callback_mutex:
  3227. on_connect = self.on_connect
  3228. if on_connect:
  3229. flags_dict = {}
  3230. flags_dict['session present'] = flags & 0x01
  3231. with self._in_callback_mutex:
  3232. try:
  3233. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  3234. if self._protocol == MQTTv5:
  3235. on_connect = cast(CallbackOnConnect_v1_mqtt5, on_connect)
  3236. on_connect(self, self._userdata,
  3237. flags_dict, reason, properties)
  3238. else:
  3239. on_connect = cast(CallbackOnConnect_v1_mqtt3, on_connect)
  3240. on_connect(
  3241. self,
  3242. self._userdata,
  3243. flags_dict,
  3244. # TODO: ideally we should update the on_connect signature
  3245. # this "rc" never was an MQTTErrorCode but always an ConnackCode
  3246. cast(MQTTErrorCode, connack_rc),
  3247. )
  3248. elif self._callback_api_version == CallbackAPIVersion.VERSION2:
  3249. on_connect = cast(CallbackOnConnect_v2, on_connect)
  3250. connect_flags = ConnectFlags(
  3251. session_present=flags_dict['session present'] > 0
  3252. )
  3253. if properties is None:
  3254. properties = Properties(PacketTypes.CONNACK)
  3255. on_connect(
  3256. self,
  3257. self._userdata,
  3258. connect_flags,
  3259. reason,
  3260. properties,
  3261. )
  3262. else:
  3263. raise RuntimeError("Unsupported callback API version")
  3264. except Exception as err:
  3265. self._easy_log(
  3266. MQTT_LOG_ERR, 'Caught exception in on_connect: %s', err)
  3267. if not self.suppress_exceptions:
  3268. raise
  3269. if connack_rc == 0:
  3270. rc = MQTTErrorCode.MQTT_ERR_SUCCESS
  3271. with self._out_message_mutex:
  3272. for m in self._out_messages.values():
  3273. m.timestamp = time_func()
  3274. if m.state == mqtt_ms_queued:
  3275. self.loop_write() # Process outgoing messages that have just been queued up
  3276. return MQTT_ERR_SUCCESS
  3277. if m.qos == 0:
  3278. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  3279. rc = self._send_publish(
  3280. m.mid,
  3281. m.topic.encode('utf-8'),
  3282. m.payload,
  3283. m.qos,
  3284. m.retain,
  3285. m.dup,
  3286. properties=m.properties
  3287. )
  3288. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3289. return rc
  3290. elif m.qos == 1:
  3291. if m.state == mqtt_ms_publish:
  3292. self._inflight_messages += 1
  3293. m.state = mqtt_ms_wait_for_puback
  3294. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  3295. rc = self._send_publish(
  3296. m.mid,
  3297. m.topic.encode('utf-8'),
  3298. m.payload,
  3299. m.qos,
  3300. m.retain,
  3301. m.dup,
  3302. properties=m.properties
  3303. )
  3304. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3305. return rc
  3306. elif m.qos == 2:
  3307. if m.state == mqtt_ms_publish:
  3308. self._inflight_messages += 1
  3309. m.state = mqtt_ms_wait_for_pubrec
  3310. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  3311. rc = self._send_publish(
  3312. m.mid,
  3313. m.topic.encode('utf-8'),
  3314. m.payload,
  3315. m.qos,
  3316. m.retain,
  3317. m.dup,
  3318. properties=m.properties
  3319. )
  3320. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3321. return rc
  3322. elif m.state == mqtt_ms_resend_pubrel:
  3323. self._inflight_messages += 1
  3324. m.state = mqtt_ms_wait_for_pubcomp
  3325. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  3326. rc = self._send_pubrel(m.mid)
  3327. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3328. return rc
  3329. self.loop_write() # Process outgoing messages that have just been queued up
  3330. return rc
  3331. elif connack_rc > 0 and connack_rc < 6:
  3332. return MQTTErrorCode.MQTT_ERR_CONN_REFUSED
  3333. else:
  3334. return MQTTErrorCode.MQTT_ERR_PROTOCOL
  3335. def drop_out_messages(self) -> list[MQTTMessage]:
  3336. """ Drops all unacknowledged QoS >= 1 messages, and returns them.
  3337. For example, call this in on_connect to clear pending
  3338. messages with a topic alias before the Client
  3339. attempts to republish them on reconnection,
  3340. possibly to a rebooted new Broker instance
  3341. that may not know the old alias. This would then
  3342. kick the client, causing an infinite reconnection loop.
  3343. The message ids of the returned MQTTMessage instances
  3344. are stored in their .mid attributes.
  3345. """
  3346. retval = []
  3347. with self._out_message_mutex:
  3348. retval = list(self._out_messages.values())
  3349. self._out_messages.clear()
  3350. return retval
  3351. def _handle_disconnect(self) -> None:
  3352. result = _packet.decode_disconnect(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3353. reasonCode, properties = result.reason, result.properties
  3354. self._easy_log(MQTT_LOG_DEBUG, "Received DISCONNECT %s %s",
  3355. reasonCode,
  3356. properties
  3357. )
  3358. self._sock_close()
  3359. self._do_on_disconnect(
  3360. packet_from_broker=True,
  3361. v1_rc=MQTTErrorCode.MQTT_ERR_SUCCESS, # If reason is absent (remaining length < 1), it means normal disconnection
  3362. reason=reasonCode,
  3363. properties=properties,
  3364. )
  3365. def _handle_suback(self) -> None:
  3366. result = _packet.decode_suback(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3367. mid = result.mid
  3368. reasoncodes = result.reason_codes
  3369. properties = result.properties
  3370. granted_qos = result.granted_qos
  3371. self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK")
  3372. with self._callback_mutex:
  3373. on_subscribe = self.on_subscribe
  3374. if on_subscribe:
  3375. with self._in_callback_mutex: # Don't call loop_write after _send_publish()
  3376. try:
  3377. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  3378. if self._protocol == MQTTv5:
  3379. on_subscribe = cast(CallbackOnSubscribe_v1_mqtt5, on_subscribe)
  3380. on_subscribe(
  3381. self, self._userdata, mid, reasoncodes, properties)
  3382. else:
  3383. on_subscribe = cast(CallbackOnSubscribe_v1_mqtt3, on_subscribe)
  3384. on_subscribe(
  3385. self, self._userdata, mid, granted_qos)
  3386. elif self._callback_api_version == CallbackAPIVersion.VERSION2:
  3387. on_subscribe = cast(CallbackOnSubscribe_v2, on_subscribe)
  3388. on_subscribe(
  3389. self,
  3390. self._userdata,
  3391. mid,
  3392. reasoncodes,
  3393. properties,
  3394. )
  3395. else:
  3396. raise RuntimeError("Unsupported callback API version")
  3397. except Exception as err:
  3398. self._easy_log(
  3399. MQTT_LOG_ERR, 'Caught exception in on_subscribe: %s', err)
  3400. if not self.suppress_exceptions:
  3401. raise
  3402. def _handle_publish(self) -> MQTTErrorCode:
  3403. result = _packet.decode_publish(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3404. message = MQTTMessage(
  3405. mid=result.mid,
  3406. topic=result.topic,
  3407. )
  3408. message.dup = result.dup
  3409. message.qos = result.qos
  3410. message.retain = result.retain
  3411. message.properties = result.properties
  3412. message.payload = result.payload
  3413. # Handle topics with invalid UTF-8
  3414. # This replaces an invalid topic with a message and the hex
  3415. # representation of the topic for logging. When the user attempts to
  3416. # access message.topic in the callback, an exception will be raised.
  3417. try:
  3418. print_topic = result.topic.decode('utf-8')
  3419. except UnicodeDecodeError:
  3420. print_topic = f"TOPIC WITH INVALID UTF-8: {result.topic!r}"
  3421. if self._protocol == MQTTv5:
  3422. self._easy_log(
  3423. MQTT_LOG_DEBUG,
  3424. "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)",
  3425. message.dup, message.qos, message.retain, message.mid,
  3426. print_topic, message.properties, len(message.payload)
  3427. )
  3428. else:
  3429. self._easy_log(
  3430. MQTT_LOG_DEBUG,
  3431. "Received PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)",
  3432. message.dup, message.qos, message.retain, message.mid,
  3433. print_topic, len(message.payload)
  3434. )
  3435. message.timestamp = time_func()
  3436. if message.qos == 0:
  3437. self._handle_on_message(message)
  3438. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3439. elif message.qos == 1:
  3440. self._handle_on_message(message)
  3441. if self._manual_ack:
  3442. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3443. else:
  3444. return self._send_puback(message.mid)
  3445. elif message.qos == 2:
  3446. rc = self._send_pubrec(message.mid)
  3447. message.state = mqtt_ms_wait_for_pubrel
  3448. with self._in_message_mutex:
  3449. self._in_messages[message.mid] = message
  3450. return rc
  3451. else:
  3452. return MQTTErrorCode.MQTT_ERR_PROTOCOL
  3453. def ack(self, mid: int, qos: int) -> MQTTErrorCode:
  3454. """
  3455. send an acknowledgement for a given message id (stored in :py:attr:`message.mid <MQTTMessage.mid>`).
  3456. only useful in QoS>=1 and ``manual_ack=True`` (option of `Client`)
  3457. """
  3458. if self._manual_ack :
  3459. if qos == 1:
  3460. return self._send_puback(mid)
  3461. elif qos == 2:
  3462. return self._send_pubcomp(mid)
  3463. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3464. def manual_ack_set(self, on: bool) -> None:
  3465. """
  3466. The paho library normally acknowledges messages as soon as they are delivered to the caller.
  3467. If manual_ack is turned on, then the caller MUST manually acknowledge every message once
  3468. application processing is complete using `ack()`
  3469. """
  3470. self._manual_ack = on
  3471. def _handle_pubrel(self) -> MQTTErrorCode:
  3472. result = _packet.decode_pubrel(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3473. (mid, reasonCode, properties) = result.mid, result.reason, result.properties
  3474. # TODO: by ignoring reason code & properties, we might probably not being
  3475. # MQTTv5 compliant.
  3476. _ = reasonCode
  3477. _ = properties
  3478. self._easy_log(MQTT_LOG_DEBUG, "Received PUBREL (Mid: %d)", mid)
  3479. with self._in_message_mutex:
  3480. if mid in self._in_messages:
  3481. # Only pass the message on if we have removed it from the queue - this
  3482. # prevents multiple callbacks for the same message.
  3483. message = self._in_messages.pop(mid)
  3484. self._handle_on_message(message)
  3485. if self._max_inflight_messages > 0:
  3486. with self._out_message_mutex:
  3487. rc = self._update_inflight()
  3488. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3489. return rc
  3490. # FIXME: this should only be done if the message is known
  3491. # If unknown it's a protocol error and we should close the connection.
  3492. # But since we don't have (on disk) persistence for the session, it
  3493. # is possible that we must known about this message.
  3494. # Choose to acknowledge this message (thus losing a message) but
  3495. # avoid hanging. See #284.
  3496. if self._manual_ack:
  3497. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3498. else:
  3499. return self._send_pubcomp(mid)
  3500. def _update_inflight(self) -> MQTTErrorCode:
  3501. # Dont lock message_mutex here
  3502. for m in self._out_messages.values():
  3503. if self._inflight_messages < self._max_inflight_messages:
  3504. if m.qos > 0 and m.state == mqtt_ms_queued:
  3505. self._inflight_messages += 1
  3506. if m.qos == 1:
  3507. m.state = mqtt_ms_wait_for_puback
  3508. elif m.qos == 2:
  3509. m.state = mqtt_ms_wait_for_pubrec
  3510. rc = self._send_publish(
  3511. m.mid,
  3512. m.topic.encode('utf-8'),
  3513. m.payload,
  3514. m.qos,
  3515. m.retain,
  3516. m.dup,
  3517. properties=m.properties,
  3518. )
  3519. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3520. return rc
  3521. else:
  3522. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3523. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3524. def _handle_pubrec(self) -> MQTTErrorCode:
  3525. result = _packet.decode_pubrec(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3526. (mid, reasonCode, properties) = result.mid, result.reason, result.properties
  3527. # TODO: by ignoring reason code & properties, we might probably not being
  3528. # MQTTv5 compliant.
  3529. _ = reasonCode
  3530. _ = properties
  3531. self._easy_log(MQTT_LOG_DEBUG, "Received PUBREC (Mid: %d)", mid)
  3532. with self._out_message_mutex:
  3533. if mid in self._out_messages:
  3534. msg = self._out_messages[mid]
  3535. msg.state = mqtt_ms_wait_for_pubcomp
  3536. msg.timestamp = time_func()
  3537. return self._send_pubrel(mid)
  3538. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3539. def _handle_unsuback(self) -> MQTTErrorCode:
  3540. result = _packet.decode_unsuback(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3541. mid = result.mid
  3542. reasoncodes_list = result.reason_codes
  3543. properties = result.properties
  3544. self._easy_log(MQTT_LOG_DEBUG, "Received UNSUBACK (Mid: %d)", mid)
  3545. with self._callback_mutex:
  3546. on_unsubscribe = self.on_unsubscribe
  3547. if on_unsubscribe:
  3548. with self._in_callback_mutex:
  3549. try:
  3550. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  3551. if self._protocol == MQTTv5:
  3552. on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt5, on_unsubscribe)
  3553. reasoncodes: ReasonCode | list[ReasonCode] = reasoncodes_list
  3554. if len(reasoncodes_list) == 1:
  3555. reasoncodes = reasoncodes_list[0]
  3556. on_unsubscribe(
  3557. self, self._userdata, mid, properties, reasoncodes)
  3558. else:
  3559. on_unsubscribe = cast(CallbackOnUnsubscribe_v1_mqtt3, on_unsubscribe)
  3560. on_unsubscribe(self, self._userdata, mid)
  3561. elif self._callback_api_version == CallbackAPIVersion.VERSION2:
  3562. on_unsubscribe = cast(CallbackOnUnsubscribe_v2, on_unsubscribe)
  3563. if properties is None:
  3564. properties = Properties(PacketTypes.CONNACK)
  3565. on_unsubscribe(
  3566. self,
  3567. self._userdata,
  3568. mid,
  3569. reasoncodes_list,
  3570. properties,
  3571. )
  3572. else:
  3573. raise RuntimeError("Unsupported callback API version")
  3574. except Exception as err:
  3575. self._easy_log(
  3576. MQTT_LOG_ERR, 'Caught exception in on_unsubscribe: %s', err)
  3577. if not self.suppress_exceptions:
  3578. raise
  3579. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3580. def _do_on_disconnect(
  3581. self,
  3582. packet_from_broker: bool,
  3583. v1_rc: MQTTErrorCode,
  3584. reason: ReasonCode | None = None,
  3585. properties: Properties | None = None,
  3586. ) -> None:
  3587. with self._callback_mutex:
  3588. on_disconnect = self.on_disconnect
  3589. if on_disconnect:
  3590. with self._in_callback_mutex:
  3591. try:
  3592. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  3593. if self._protocol == MQTTv5:
  3594. on_disconnect = cast(CallbackOnDisconnect_v1_mqtt5, on_disconnect)
  3595. if packet_from_broker:
  3596. on_disconnect(self, self._userdata, reason, properties)
  3597. else:
  3598. on_disconnect(self, self._userdata, v1_rc, None)
  3599. else:
  3600. on_disconnect = cast(CallbackOnDisconnect_v1_mqtt3, on_disconnect)
  3601. on_disconnect(self, self._userdata, v1_rc)
  3602. elif self._callback_api_version == CallbackAPIVersion.VERSION2:
  3603. on_disconnect = cast(CallbackOnDisconnect_v2, on_disconnect)
  3604. disconnect_flags = DisconnectFlags(
  3605. is_disconnect_packet_from_server=packet_from_broker
  3606. )
  3607. if reason is None:
  3608. reason = convert_disconnect_error_code_to_reason_code(v1_rc)
  3609. if properties is None:
  3610. properties = Properties(PacketTypes.DISCONNECT)
  3611. on_disconnect(
  3612. self,
  3613. self._userdata,
  3614. disconnect_flags,
  3615. reason,
  3616. properties,
  3617. )
  3618. else:
  3619. raise RuntimeError("Unsupported callback API version")
  3620. except Exception as err:
  3621. self._easy_log(
  3622. MQTT_LOG_ERR, 'Caught exception in on_disconnect: %s', err)
  3623. if not self.suppress_exceptions:
  3624. raise
  3625. def _do_on_publish(self, mid: int, reason_code: ReasonCode, properties: Properties) -> MQTTErrorCode:
  3626. with self._callback_mutex:
  3627. on_publish = self.on_publish
  3628. if on_publish:
  3629. with self._in_callback_mutex:
  3630. try:
  3631. if self._callback_api_version == CallbackAPIVersion.VERSION1:
  3632. on_publish = cast(CallbackOnPublish_v1, on_publish)
  3633. on_publish(self, self._userdata, mid)
  3634. elif self._callback_api_version == CallbackAPIVersion.VERSION2:
  3635. on_publish = cast(CallbackOnPublish_v2, on_publish)
  3636. on_publish(
  3637. self,
  3638. self._userdata,
  3639. mid,
  3640. reason_code,
  3641. properties,
  3642. )
  3643. else:
  3644. raise RuntimeError("Unsupported callback API version")
  3645. except Exception as err:
  3646. self._easy_log(
  3647. MQTT_LOG_ERR, 'Caught exception in on_publish: %s', err)
  3648. if not self.suppress_exceptions:
  3649. raise
  3650. msg = self._out_messages.pop(mid)
  3651. msg.info._set_as_published()
  3652. if msg.qos > 0:
  3653. self._inflight_messages -= 1
  3654. if self._max_inflight_messages > 0:
  3655. rc = self._update_inflight()
  3656. if rc != MQTTErrorCode.MQTT_ERR_SUCCESS:
  3657. return rc
  3658. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3659. def _handle_pubackcomp(
  3660. self, cmd: Literal['PUBACK', 'PUBCOMP']
  3661. ) -> MQTTErrorCode:
  3662. result: _packet.PubackPacket|_packet.PubcompPacket
  3663. if cmd == "PUBACK":
  3664. result = _packet.decode_puback(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3665. else:
  3666. result = _packet.decode_pubcomp(self._in_packet["command"], self._in_packet["packet"], self._protocol)
  3667. (mid, reasonCode, properties) = result.mid, result.reason, result.properties
  3668. self._easy_log(MQTT_LOG_DEBUG, "Received %s (Mid: %d)", cmd, mid)
  3669. with self._out_message_mutex:
  3670. if mid in self._out_messages:
  3671. # Only inform the client the message has been sent once.
  3672. rc = self._do_on_publish(mid, reasonCode, properties)
  3673. return rc
  3674. return MQTTErrorCode.MQTT_ERR_SUCCESS
  3675. def _handle_on_message(self, message: MQTTMessage) -> None:
  3676. try:
  3677. topic = message.topic
  3678. except UnicodeDecodeError:
  3679. topic = None
  3680. on_message_callbacks = []
  3681. with self._callback_mutex:
  3682. if topic is not None:
  3683. on_message_callbacks = list(self._on_message_filtered.iter_match(message.topic))
  3684. if len(on_message_callbacks) == 0:
  3685. on_message = self.on_message
  3686. else:
  3687. on_message = None
  3688. for callback in on_message_callbacks:
  3689. with self._in_callback_mutex:
  3690. try:
  3691. callback(self, self._userdata, message)
  3692. except Exception as err:
  3693. self._easy_log(
  3694. MQTT_LOG_ERR,
  3695. 'Caught exception in user defined callback function %s: %s',
  3696. callback.__name__,
  3697. err
  3698. )
  3699. if not self.suppress_exceptions:
  3700. raise
  3701. if on_message:
  3702. with self._in_callback_mutex:
  3703. try:
  3704. on_message(self, self._userdata, message)
  3705. except Exception as err:
  3706. self._easy_log(
  3707. MQTT_LOG_ERR, 'Caught exception in on_message: %s', err)
  3708. if not self.suppress_exceptions:
  3709. raise
  3710. def _handle_on_connect_fail(self) -> None:
  3711. with self._callback_mutex:
  3712. on_connect_fail = self.on_connect_fail
  3713. if on_connect_fail:
  3714. with self._in_callback_mutex:
  3715. try:
  3716. on_connect_fail(self, self._userdata)
  3717. except Exception as err: # noqa: BLE001
  3718. self._easy_log(
  3719. MQTT_LOG_ERR, 'Caught exception in on_connect_fail: %s', err)
  3720. def _thread_main(self) -> None:
  3721. try:
  3722. self.loop_forever(retry_first_connection=True)
  3723. finally:
  3724. self._thread = None
  3725. def _reconnect_wait(self) -> None:
  3726. # See reconnect_delay_set for details
  3727. now = time_func()
  3728. with self._reconnect_delay_mutex:
  3729. if self._reconnect_delay is None:
  3730. self._reconnect_delay = self._reconnect_min_delay
  3731. else:
  3732. self._reconnect_delay = min(
  3733. self._reconnect_delay * 2,
  3734. self._reconnect_max_delay,
  3735. )
  3736. target_time = now + self._reconnect_delay
  3737. remaining = target_time - now
  3738. while (self._state not in (_ConnectionState.MQTT_CS_DISCONNECTING, _ConnectionState.MQTT_CS_DISCONNECTED)
  3739. and not self._thread_terminate
  3740. and remaining > 0):
  3741. time.sleep(min(remaining, 1))
  3742. remaining = target_time - time_func()
  3743. @staticmethod
  3744. def _proxy_is_valid(p) -> bool: # type: ignore[no-untyped-def]
  3745. def check(t, a) -> bool: # type: ignore[no-untyped-def]
  3746. return (socks is not None and
  3747. t in {socks.HTTP, socks.SOCKS4, socks.SOCKS5} and a)
  3748. if isinstance(p, dict):
  3749. return check(p.get("proxy_type"), p.get("proxy_addr"))
  3750. elif isinstance(p, (list, tuple)):
  3751. return len(p) == 6 and check(p[0], p[1])
  3752. else:
  3753. return False
  3754. def _get_proxy(self) -> dict[str, Any] | None:
  3755. if socks is None:
  3756. return None
  3757. # First, check if the user explicitly passed us a proxy to use
  3758. if self._proxy_is_valid(self._proxy):
  3759. return self._proxy
  3760. # Next, check for an mqtt_proxy environment variable as long as the host
  3761. # we're trying to connect to isn't listed under the no_proxy environment
  3762. # variable (matches built-in module urllib's behavior)
  3763. if not (hasattr(urllib.request, "proxy_bypass") and
  3764. urllib.request.proxy_bypass(self._host)):
  3765. env_proxies = urllib.request.getproxies()
  3766. if "mqtt" in env_proxies:
  3767. parts = urllib.parse.urlparse(env_proxies["mqtt"])
  3768. if parts.scheme == "http":
  3769. proxy = {
  3770. "proxy_type": socks.HTTP,
  3771. "proxy_addr": parts.hostname,
  3772. "proxy_port": parts.port
  3773. }
  3774. return proxy
  3775. elif parts.scheme == "socks":
  3776. proxy = {
  3777. "proxy_type": socks.SOCKS5,
  3778. "proxy_addr": parts.hostname,
  3779. "proxy_port": parts.port
  3780. }
  3781. return proxy
  3782. # Finally, check if the user has monkeypatched the PySocks library with
  3783. # a default proxy
  3784. socks_default = socks.get_default_proxy()
  3785. if self._proxy_is_valid(socks_default):
  3786. proxy_keys = ("proxy_type", "proxy_addr", "proxy_port",
  3787. "proxy_rdns", "proxy_username", "proxy_password")
  3788. return dict(zip(proxy_keys, socks_default))
  3789. # If we didn't find a proxy through any of the above methods, return
  3790. # None to indicate that the connection should be handled normally
  3791. return None
  3792. def _create_socket(self) -> SocketLike:
  3793. if self._transport == "unix":
  3794. sock = self._create_unix_socket_connection()
  3795. else:
  3796. sock = self._create_socket_connection()
  3797. if self._ssl:
  3798. sock = self._ssl_wrap_socket(sock)
  3799. if self._transport == "websockets":
  3800. sock.settimeout(self._connect_timeout)
  3801. return _WebsocketWrapper(
  3802. socket=sock,
  3803. host=self._host,
  3804. port=self._port,
  3805. is_ssl=self._ssl,
  3806. path=self._websocket_path,
  3807. extra_headers=self._websocket_extra_headers,
  3808. )
  3809. return sock
  3810. def _create_unix_socket_connection(self) -> _socket.socket:
  3811. unix_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  3812. unix_socket.connect(self._host)
  3813. return unix_socket
  3814. def _create_socket_connection(self) -> _socket.socket:
  3815. proxy = self._get_proxy()
  3816. addr = (self._host, self._port)
  3817. source = (self._bind_address, self._bind_port)
  3818. if proxy:
  3819. return socks.create_connection(addr, timeout=self._connect_timeout, source_address=source, **proxy)
  3820. else:
  3821. return socket.create_connection(addr, timeout=self._connect_timeout, source_address=source)
  3822. def _ssl_wrap_socket(self, tcp_sock: _socket.socket) -> ssl.SSLSocket:
  3823. if self._ssl_context is None:
  3824. raise ValueError(
  3825. "Impossible condition. _ssl_context should never be None if _ssl is True"
  3826. )
  3827. verify_host = not self._tls_insecure
  3828. try:
  3829. # Try with server_hostname, even it's not supported in certain scenarios
  3830. ssl_sock = self._ssl_context.wrap_socket(
  3831. tcp_sock,
  3832. server_hostname=self._host,
  3833. do_handshake_on_connect=False,
  3834. )
  3835. except ssl.CertificateError:
  3836. # CertificateError is derived from ValueError
  3837. raise
  3838. except ValueError:
  3839. # Python version requires SNI in order to handle server_hostname, but SNI is not available
  3840. ssl_sock = self._ssl_context.wrap_socket(
  3841. tcp_sock,
  3842. do_handshake_on_connect=False,
  3843. )
  3844. else:
  3845. # If SSL context has already checked hostname, then don't need to do it again
  3846. if getattr(self._ssl_context, 'check_hostname', False): # type: ignore
  3847. verify_host = False
  3848. ssl_sock.settimeout(self._connect_timeout)
  3849. ssl_sock.do_handshake()
  3850. if verify_host:
  3851. # TODO: this type error is a true error:
  3852. # error: Module has no attribute "match_hostname" [attr-defined]
  3853. # Python 3.12 no longer have this method.
  3854. ssl.match_hostname(ssl_sock.getpeercert(), self._host) # type: ignore
  3855. return ssl_sock
  3856. class _WebsocketWrapper:
  3857. OPCODE_CONTINUATION = 0x0
  3858. OPCODE_TEXT = 0x1
  3859. OPCODE_BINARY = 0x2
  3860. OPCODE_CONNCLOSE = 0x8
  3861. OPCODE_PING = 0x9
  3862. OPCODE_PONG = 0xa
  3863. def __init__(
  3864. self,
  3865. socket: socket.socket | ssl.SSLSocket,
  3866. host: str,
  3867. port: int,
  3868. is_ssl: bool,
  3869. path: str,
  3870. extra_headers: WebSocketHeaders | None,
  3871. ):
  3872. self.connected = False
  3873. self._ssl = is_ssl
  3874. self._host = host
  3875. self._port = port
  3876. self._socket = socket
  3877. self._path = path
  3878. self._sendbuffer = bytearray()
  3879. self._readbuffer = bytearray()
  3880. self._requested_size = 0
  3881. self._payload_head = 0
  3882. self._readbuffer_head = 0
  3883. self._do_handshake(extra_headers)
  3884. def __del__(self) -> None:
  3885. self._sendbuffer = bytearray()
  3886. self._readbuffer = bytearray()
  3887. def _do_handshake(self, extra_headers: WebSocketHeaders | None) -> None:
  3888. sec_websocket_key = uuid.uuid4().bytes
  3889. sec_websocket_key = base64.b64encode(sec_websocket_key)
  3890. if self._ssl:
  3891. default_port = 443
  3892. http_schema = "https"
  3893. else:
  3894. default_port = 80
  3895. http_schema = "http"
  3896. if default_port == self._port:
  3897. host_port = f"{self._host}"
  3898. else:
  3899. host_port = f"{self._host}:{self._port}"
  3900. websocket_headers = {
  3901. "Host": host_port,
  3902. "Upgrade": "websocket",
  3903. "Connection": "Upgrade",
  3904. "Origin": f"{http_schema}://{host_port}",
  3905. "Sec-WebSocket-Key": sec_websocket_key.decode("utf8"),
  3906. "Sec-Websocket-Version": "13",
  3907. "Sec-Websocket-Protocol": "mqtt",
  3908. }
  3909. # This is checked in ws_set_options so it will either be None, a
  3910. # dictionary, or a callable
  3911. if isinstance(extra_headers, dict):
  3912. websocket_headers.update(extra_headers)
  3913. elif callable(extra_headers):
  3914. websocket_headers = extra_headers(websocket_headers)
  3915. header = "\r\n".join([
  3916. f"GET {self._path} HTTP/1.1",
  3917. "\r\n".join(f"{i}: {j}" for i, j in websocket_headers.items()),
  3918. "\r\n",
  3919. ]).encode("utf8")
  3920. self._socket.send(header)
  3921. has_secret = False
  3922. has_upgrade = False
  3923. while True:
  3924. # read HTTP response header as lines
  3925. try:
  3926. byte = self._socket.recv(1)
  3927. except ConnectionResetError:
  3928. byte = b""
  3929. self._readbuffer.extend(byte)
  3930. # line end
  3931. if byte == b"\n":
  3932. if len(self._readbuffer) > 2:
  3933. # check upgrade
  3934. if b"connection" in str(self._readbuffer).lower().encode('utf-8'):
  3935. if b"upgrade" not in str(self._readbuffer).lower().encode('utf-8'):
  3936. raise WebsocketConnectionError(
  3937. "WebSocket handshake error, connection not upgraded")
  3938. else:
  3939. has_upgrade = True
  3940. # check key hash
  3941. if b"sec-websocket-accept" in str(self._readbuffer).lower().encode('utf-8'):
  3942. GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  3943. server_hash_str = self._readbuffer.decode(
  3944. 'utf-8').split(": ", 1)[1]
  3945. server_hash = server_hash_str.strip().encode('utf-8')
  3946. client_hash_key = sec_websocket_key.decode('utf-8') + GUID
  3947. # Use of SHA-1 is OK here; it's according to the Websocket spec.
  3948. client_hash_digest = hashlib.sha1(client_hash_key.encode('utf-8')) # noqa: S324
  3949. client_hash = base64.b64encode(client_hash_digest.digest())
  3950. if server_hash != client_hash:
  3951. raise WebsocketConnectionError(
  3952. "WebSocket handshake error, invalid secret key")
  3953. else:
  3954. has_secret = True
  3955. else:
  3956. # ending linebreak
  3957. break
  3958. # reset linebuffer
  3959. self._readbuffer = bytearray()
  3960. # connection reset
  3961. elif not byte:
  3962. raise WebsocketConnectionError("WebSocket handshake error")
  3963. if not has_upgrade or not has_secret:
  3964. raise WebsocketConnectionError("WebSocket handshake error")
  3965. self._readbuffer = bytearray()
  3966. self.connected = True
  3967. def _create_frame(
  3968. self, opcode: int, data: bytearray, do_masking: int = 1
  3969. ) -> bytearray:
  3970. header = bytearray()
  3971. length = len(data)
  3972. mask_key = bytearray(os.urandom(4))
  3973. mask_flag = do_masking
  3974. # 1 << 7 is the final flag, we don't send continuated data
  3975. header.append(1 << 7 | opcode)
  3976. if length < 126:
  3977. header.append(mask_flag << 7 | length)
  3978. elif length < 65536:
  3979. header.append(mask_flag << 7 | 126)
  3980. header += struct.pack("!H", length)
  3981. elif length < 0x8000000000000001:
  3982. header.append(mask_flag << 7 | 127)
  3983. header += struct.pack("!Q", length)
  3984. else:
  3985. raise ValueError("Maximum payload size is 2^63")
  3986. if mask_flag == 1:
  3987. for index in range(length):
  3988. data[index] ^= mask_key[index % 4]
  3989. data = mask_key + data
  3990. return header + data
  3991. def _buffered_read(self, length: int) -> bytearray:
  3992. # try to recv and store needed bytes
  3993. wanted_bytes = length - (len(self._readbuffer) - self._readbuffer_head)
  3994. if wanted_bytes > 0:
  3995. data = self._socket.recv(wanted_bytes)
  3996. if not data:
  3997. raise ConnectionAbortedError
  3998. else:
  3999. self._readbuffer.extend(data)
  4000. if len(data) < wanted_bytes:
  4001. raise BlockingIOError
  4002. self._readbuffer_head += length
  4003. return self._readbuffer[self._readbuffer_head - length:self._readbuffer_head]
  4004. def _recv_impl(self, length: int) -> bytes:
  4005. # try to decode websocket payload part from data
  4006. try:
  4007. self._readbuffer_head = 0
  4008. result = b""
  4009. chunk_startindex = self._payload_head
  4010. chunk_endindex = self._payload_head + length
  4011. header1 = self._buffered_read(1)
  4012. header2 = self._buffered_read(1)
  4013. opcode = (header1[0] & 0x0f)
  4014. maskbit = (header2[0] & 0x80) == 0x80
  4015. lengthbits = (header2[0] & 0x7f)
  4016. payload_length = lengthbits
  4017. mask_key = None
  4018. # read length
  4019. if lengthbits == 0x7e:
  4020. value = self._buffered_read(2)
  4021. payload_length, = struct.unpack("!H", value)
  4022. elif lengthbits == 0x7f:
  4023. value = self._buffered_read(8)
  4024. payload_length, = struct.unpack("!Q", value)
  4025. # read mask
  4026. if maskbit:
  4027. mask_key = self._buffered_read(4)
  4028. # if frame payload is shorter than the requested data, read only the possible part
  4029. readindex = chunk_endindex
  4030. readindex = min(readindex, payload_length)
  4031. if readindex > 0:
  4032. # get payload chunk
  4033. payload = self._buffered_read(readindex)
  4034. # unmask only the needed part
  4035. if mask_key is not None:
  4036. for index in range(chunk_startindex, readindex):
  4037. payload[index] ^= mask_key[index % 4]
  4038. result = bytes(payload[chunk_startindex:readindex])
  4039. self._payload_head = readindex
  4040. else:
  4041. payload = bytearray()
  4042. # check if full frame arrived and reset readbuffer and payloadhead if needed
  4043. if readindex == payload_length:
  4044. self._readbuffer = bytearray()
  4045. self._payload_head = 0
  4046. # respond to non-binary opcodes, their arrival is not guaranteed because of non-blocking sockets
  4047. if opcode == _WebsocketWrapper.OPCODE_CONNCLOSE:
  4048. frame = self._create_frame(
  4049. _WebsocketWrapper.OPCODE_CONNCLOSE, payload, 0)
  4050. self._socket.send(frame)
  4051. if opcode == _WebsocketWrapper.OPCODE_PING:
  4052. frame = self._create_frame(
  4053. _WebsocketWrapper.OPCODE_PONG, payload, 0)
  4054. self._socket.send(frame)
  4055. # This isn't *proper* handling of continuation frames, but given
  4056. # that we only support binary frames, it is *probably* good enough.
  4057. if (opcode == _WebsocketWrapper.OPCODE_BINARY or opcode == _WebsocketWrapper.OPCODE_CONTINUATION) \
  4058. and payload_length > 0:
  4059. return result
  4060. else:
  4061. raise BlockingIOError
  4062. except ConnectionError:
  4063. self.connected = False
  4064. return b''
  4065. def _send_impl(self, data: bytes | bytearray) -> int:
  4066. # if previous frame was sent successfully
  4067. if len(self._sendbuffer) == 0:
  4068. # create websocket frame
  4069. frame = self._create_frame(
  4070. _WebsocketWrapper.OPCODE_BINARY, bytearray(data))
  4071. self._sendbuffer.extend(frame)
  4072. self._requested_size = len(data)
  4073. # try to write out as much as possible
  4074. length = self._socket.send(self._sendbuffer)
  4075. self._sendbuffer = self._sendbuffer[length:]
  4076. if len(self._sendbuffer) == 0:
  4077. # buffer sent out completely, return with payload's size
  4078. return self._requested_size
  4079. else:
  4080. # couldn't send whole data, request the same data again with 0 as sent length
  4081. return 0
  4082. def recv(self, length: int) -> bytes:
  4083. return self._recv_impl(length)
  4084. def read(self, length: int) -> bytes:
  4085. return self._recv_impl(length)
  4086. def send(self, data: bytes | bytearray) -> int:
  4087. return self._send_impl(data)
  4088. def write(self, data: bytes) -> int:
  4089. return self._send_impl(data)
  4090. def close(self) -> None:
  4091. self._socket.close()
  4092. def fileno(self) -> int:
  4093. return self._socket.fileno()
  4094. def pending(self) -> int:
  4095. # Fix for bug #131: a SSL socket may still have data available
  4096. # for reading without select() being aware of it.
  4097. if self._ssl:
  4098. return self._socket.pending() # type: ignore[union-attr]
  4099. else:
  4100. # normal socket rely only on select()
  4101. return 0
  4102. def setblocking(self, flag: bool) -> None:
  4103. self._socket.setblocking(flag)