U
    ÉZj€ ã                
   @  s  U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZmZmZmZmZmZmZmZmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. dd	l/m0Z0 dd
l1m2Z2m3Z3 ddl4m5Z5 zddlm6Z6 W n" e7k
�rl   ddl8m6Z6 Y nX e�rzddlm9Z9 W n" e7k
�r¦   ddl8m9Z9 Y nX zddlm:Z: W n" e7k
�rÚ   ddl8m:Z: Y nX G dd„ de9ƒZ;G dd„ de9ƒZ<G dd„ de:ƒZ=zddl>Z>W n e7k
�r2   dZ>Y nX zddl?Z?W n e7k
�rZ   dZ?Y nX z
ej@ZAW n eBk
�r‚   ejZAY nX zddlCZDdZEW n e7k
�r®   dZEY nX e	 F¡ dk�rÆejGZHnejHZHe3ZIe(jJZJe(jKZKe(jLZLe(jMZMe(jNZNe(jOZOe(jPZPe(jQZQe(jRZRe(jSZSe(jTZTe(jUZUe(jVZVe(jWZWe(jXZXe&jYZYe&jZZZe&j[Z[e&j\Z\e&j]Z]e&j]ej^e&jYej_e&jZej_e&j[ej`e&j\ejaiZbe%jcZce%jdZde%jeZee%jfZfe%jgZge%jhZhe'jiZje'jkZle'jmZne'joZpe'jqZre'jsZte'juZve'jwZxe'jyZze'j{Z|e)j}Z}e)j~Z~e)jZe)j€Z€e)j�Z�e)j‚Z‚e)jƒZƒe)j„Z„e)j…Z…e)j†Z†e)j‡Z‡e)jˆZˆe)j‰Z‰e)jŠZŠe)j‹Z‹e)jŒZŒe)j�Z�e)jŽZŽe*j�Z�e*j�Z�e*j‘Z‘e+j’Z’e+j“Z“dZ”de•d< dZ–ee—e˜e™eše›df Zœee—e—f Z�eee�ge�f e�f ZžeeŸe6d f Z G dd„ deƒZ¡G dd„ deƒZ¢ed eee—ef e)gdf Z£ed eee—ef e2ee0df gdf Z¤ee¤e£f Z¥ed ee¡e2ee0df gdf Z¦ee¥e¦f Z§ed egdf Z¨ed ee)gdf Z©ed eee2ešdf ee0df gdf Zªee©eªf Z«ed ee¢e2ee0df gdf Z¬ee«e¬f Z­ed eeše—gdf Z®ed ed!gdf Z¯ed egdf Z°ed eešgdf Z±ed eeše2e0gdf Z²ee±e²f Z³ed edgdf Z´ed eešeešd"f gdf Zµed eešee2 e0gdf Z¶eeµe¶f Z·ed eešee2 ee0df gdf Z¸ee·e¸f Z¹ed eešgdf Zºed eeše0ee2ee2 f gdf Z»eeºe»f Z¼ed eešee2 ee0df gdf Z½ee¼e½f Z¾eZ¿G d#d$„ d$eÀƒZÁd%d&d'œd(d)„ZÂd*d&d+œd,d-„ZÃd.d/d+œd0d1„ZÄd2d/d3œd4d5„ZÅejÆejÇ dfd6d&d6d&d7œd8d9„ZÈd&d&d:d;œd<d=„ZÉd>d?œd@dA„ZÊdBdCdDœdEdF„ZËdGdHdIœdJdK„ZÌG dLdM„ dMƒZÍG dNd!„ d!ƒZÎG dOd „ d ƒZÏG dPdQ„ dQƒZÐdS )Rz‘
This is an MQTT client module. MQTT is a lightweight pub/sub messaging
protocol that is easy to implement and suitable for low powered devices.
é    )ÚannotationsN)ÚTYPE_CHECKINGÚAnyÚCallableÚDictÚIteratorÚListÚ
NamedTupleÚSequenceÚTupleÚUnionÚcast)ÚPacketTypesé   )	ÚCallbackAPIVersionÚConnackCodeÚLogLevelÚMessageStateÚMessageTypeÚMQTTErrorCodeÚMQTTProtocolVersionÚPahoClientModeÚ_ConnectionState)ÚMQTTMatcher)Ú
Properties)Ú
ReasonCodeÚReasonCodes)ÚSubscribeOptions)ÚLiteral)Ú	TypedDict)ÚProtocolc                   @  sN   e Zd ZU ded< ded< ded< ded< ded< ded	< ded
< ded< dS )Ú	_InPacketÚintÚcommandÚhave_remainingz	list[int]Úremaining_countÚremaining_multÚremaining_lengthÚ	bytearrayÚpacketÚ
to_processÚposN©Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© r1   r1   úS/var/www/html/TRUCKING_PROJECT/venv/lib/python3.8/site-packages/paho/mqtt/client.pyr!   @   s   
r!   c                   @  sF   e Zd ZU ded< ded< ded< ded< ded< ded< d	ed
< dS )Ú
_OutPacketr"   r#   ÚmidÚqosr+   r*   Úbytesr)   úMQTTMessageInfo | NoneÚinfoNr,   r1   r1   r1   r2   r3   K   s   
r3   c                   @  sX   e Zd Zdddœdd„Zdddœdd„Zd	d
œdd„Zdd
œdd„Zdd	dœdd„ZdS )Ú
SocketLiker"   r6   )Úbuffer_sizeÚreturnc                 C  s   d S ©Nr1   )Úselfr:   r1   r1   r2   ÚrecvU   s    zSocketLike.recv)Úbufferr;   c                 C  s   d S r<   r1   )r=   r?   r1   r1   r2   ÚsendW   s    zSocketLike.sendÚNone©r;   c                 C  s   d S r<   r1   ©r=   r1   r1   r2   ÚcloseY   s    zSocketLike.closec                 C  s   d S r<   r1   rC   r1   r1   r2   Úfileno[   s    zSocketLike.filenoÚbool©Úflagr;   c                 C  s   d S r<   r1   ©r=   rH   r1   r1   r2   Úsetblocking]   s    zSocketLike.setblockingN)r-   r.   r/   r>   r@   rD   rE   rJ   r1   r1   r1   r2   r9   T   s
   r9   TFÚWindowsé   ÚCleanStartOptionÚMQTT_CLEAN_START_FIRST_ONLYó   0c                   @  s   e Zd ZU dZded< dS )ÚConnectFlagsz?Contains additional information passed to `on_connect` callbackrF   Úsession_presentN©r-   r.   r/   Ú__doc__r0   r1   r1   r1   r2   rP   á   s   
rP   c                   @  s   e Zd ZU dZded< dS )ÚDisconnectFlagszBContains additional information passed to `on_disconnect` callbackrF   Ú is_disconnect_packet_from_serverNrR   r1   r1   r1   r2   rT   î   s   
rT   ÚClientÚMQTTMessage.c                   @  s   e Zd ZdZdS )ÚWebsocketConnectionErrorz… WebsocketConnectionError is a subclass of ConnectionError.

        It's raised when unable to perform the Websocket handshake.
    N)r-   r.   r/   rS   r1   r1   r1   r2   rX     s   rX   úMQTTErrorCode | intÚstr)Ú
mqtt_errnor;   c                 C  sÔ   | t krdS | tkrdS | tkr$dS | tkr0dS | tkr<dS | tkrHdS | tkrTdS | tkr`dS | tkrld	S | t	krxd
S | t
kr„dS | tkr�dS | tkrœdS | tkr¨dS | tkr´dS | tkrÀdS | tkrÌdS dS dS )z=Return the error string associated with an mqtt error number.z	No error.zOut of memory.zEA network protocol error occurred when communicating with the broker.z$Invalid function arguments provided.z&The client is not currently connected.zThe connection was refused.z#Message not found (internal error).zThe connection was lost.zA TLS error occurred.úPayload too large.zThis feature is not supported.zAuthorisation failed.zAccess denied by ACL.zUnknown error.zError defined by errno.zMessage queue full.z?Client or broker did not communicate in the keepalive interval.N)ÚMQTT_ERR_SUCCESSÚMQTT_ERR_NOMEMÚMQTT_ERR_PROTOCOLÚMQTT_ERR_INVALÚMQTT_ERR_NO_CONNÚMQTT_ERR_CONN_REFUSEDÚMQTT_ERR_NOT_FOUNDÚMQTT_ERR_CONN_LOSTÚMQTT_ERR_TLSÚMQTT_ERR_PAYLOAD_SIZEÚMQTT_ERR_NOT_SUPPORTEDÚMQTT_ERR_AUTHÚMQTT_ERR_ACL_DENIEDÚMQTT_ERR_UNKNOWNÚMQTT_ERR_ERRNOÚMQTT_ERR_QUEUE_SIZEÚMQTT_ERR_KEEPALIVE)r[   r1   r1   r2   Úerror_string#  sF    rn   zint | ReasonCode)Úconnack_coder;   c                 C  sb   t | tƒrt| ƒS | tkrdS | tkr*dS | tkr6dS | tkrBdS | tkrNdS | tkrZdS dS dS )	zJReturn the string associated with a CONNACK result or CONNACK reason code.zConnection Accepted.z2Connection Refused: unacceptable protocol version.z(Connection Refused: identifier rejected.z'Connection Refused: broker unavailable.z.Connection Refused: bad user name or password.z#Connection Refused: not authorised.z#Connection Refused: unknown reason.N)	Ú
isinstancer   rZ   ÚCONNACK_ACCEPTEDÚ CONNACK_REFUSED_PROTOCOL_VERSIONÚ#CONNACK_REFUSED_IDENTIFIER_REJECTEDÚ"CONNACK_REFUSED_SERVER_UNAVAILABLEÚ%CONNACK_REFUSED_BAD_USERNAME_PASSWORDÚCONNACK_REFUSED_NOT_AUTHORIZED©ro   r1   r1   r2   Úconnack_stringK  s    
rx   r   r   c                 C  s�   | t jkrttjdƒS | t jkr,ttjdƒS | t jkrBttjdƒS | t jkrXttjdƒS | t jkrnttjdƒS | t j	kr„ttjdƒS ttjdƒS )aK  Convert a MQTTv3 / MQTTv3.1.1 connack result to `ReasonCode`.

    This is used in `on_connect` callback to have a consistent API.

    Be careful that the numeric value isn't the same, for example:

    >>> ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE == 3
    >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == 136

    It's recommended to compare by names

    >>> code_to_test = ReasonCode(PacketTypes.CONNACK, "Server unavailable")
    >>> convert_connack_rc_to_reason_code(ConnackCode.CONNACK_REFUSED_SERVER_UNAVAILABLE) == code_to_test
    ÚSuccessúUnsupported protocol versionzClient identifier not validzServer unavailablezBad user name or passwordzNot authorizedúUnspecified error)
r   rq   r   r   ÚCONNACKrr   rs   rt   ru   rv   rw   r1   r1   r2   Ú!convert_connack_rc_to_reason_code`  s    





r}   r   ©Úrcr;   c                 C  sN   | t jkrttjdƒS | t jkr,ttjdƒS | t jkrBttjdƒS ttjdƒS )a!  Convert an MQTTErrorCode to Reason code.

    This is used in `on_disconnect` callback to have a consistent API.

    Be careful that the numeric value isn't the same, for example:

    >>> MQTTErrorCode.MQTT_ERR_PROTOCOL == 2
    >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == 130

    It's recommended to compare by names

    >>> code_to_test = ReasonCode(PacketTypes.DISCONNECT, "Protocol error")
    >>> convert_disconnect_error_code_to_reason_code(MQTTErrorCode.MQTT_ERR_PROTOCOL) == code_to_test
    ry   zKeep alive timeoutr{   )r   r]   r   r   Ú
DISCONNECTrm   rd   )r   r1   r1   r2   Ú,convert_disconnect_error_code_to_reason_code  s    


r�   r"   )ÚnumÚbaseÚpaddingr;   c                   sf   | dk rt dƒ‚g }| r6t| dƒ\} }| ˆ | ¡ q| ‡ fdd„tt|ƒ|ƒD ƒ¡ d t|ƒ¡S )z+Convert a number to base-62 representation.r   zNumber must be positive or zeroé>   c                 3  s   | ]}ˆ d  V  qdS )r   Nr1   )Ú.0Ú_©rƒ   r1   r2   Ú	<genexpr>£  s     z_base62.<locals>.<genexpr>Ú )Ú
ValueErrorÚdivmodÚappendÚextendÚrangeÚlenÚjoinÚreversed)r‚   rƒ   r„   ÚdigitsÚrestr1   rˆ   r2   Ú_base62—  s    "r•   rF   )ÚsubÚtopicr;   c                 C  s>   t ƒ }d|| < zt| |¡ƒ W dS  tk
r8   Y dS X dS )zÑCheck whether a topic matches a subscription.

    For example:

    * Topic "foo/bar" would match the subscription "foo/#" or "+/bar"
    * Topic "non/matching" would not match the subscription "non/+/+"
    TFN)r   ÚnextÚ
iter_matchÚStopIteration)r–   r—   Úmatcherr1   r1   r2   Útopic_matches_sub§  s    rœ   z#tuple[socket.socket, socket.socket]rB   c                  C  s²   t   t jt jt j¡} |  t jt jd¡ |  d¡ |  d¡ |  	¡ \}}t   t jt jt j¡}| 
d¡ z| d|f¡ W n tk
rŠ   Y nX |  ¡ \}}| 
d¡ |  ¡  ||fS )z+TCP/IP socketpair including Windows supportr   )ú	127.0.0.1r   Fr�   )ÚsocketÚAF_INETÚSOCK_STREAMÚ
IPPROTO_IPÚ
setsockoptÚ
SOL_SOCKETÚSO_REUSEADDRÚbindÚlistenÚgetsocknamerJ   ÚconnectÚBlockingIOErrorÚacceptrD   )Z
listensockZifaceÚportZsock1Zsock2Úaddressr1   r1   r2   Ú_socketpair_compat¸  s.      ÿ

  ÿ

r­   zstr | bytesr6   )Úsr;   c                 C  s   t | tƒr|  d¡S | S )Núutf-8)rp   rZ   Úencode)r®   r1   r1   r2   Ú_force_bytesÎ  s    

r±   z,str | bytes | bytearray | int | float | Noneúbytes | bytearray)Úpayloadr;   c                 C  sV   t | tƒr|  d¡S t | ttfƒr0t| ƒ d¡S | d kr<dS t | ttfƒsRtdƒ‚| S )Nr¯   Úasciió    z8payload must be a string, bytearray, int, float or None.)rp   rZ   r°   r"   Úfloatr6   r(   Ú	TypeError)r³   r1   r1   r2   Ú_encode_payloadÔ  s    

ÿr¸   c                   @  s˜   e Zd ZdZdZddœdd„Zddœd	d
„Zddœdd„Zddœdd„Zddœdd„Z	dddœdd„Z
ddœdd„Zd!dddœdd„Zddœdd „ZdS )"ÚMQTTMessageInfozàThis is a class returned from `Client.publish()` and can be used to find
    out the mid of the message that was published, and to determine whether the
    message has been published, and/or wait until it is published.
    )r4   Ú
_publishedÚ
_conditionr   Ú_iterposr"   )r4   c                 C  s(   || _ d| _t ¡ | _tj| _d| _d S ©NFr   )	r4   rº   Ú	threadingÚ	Conditionr»   r   r]   r   r¼   ©r=   r4   r1   r1   r2   Ú__init__î  s
    
zMQTTMessageInfo.__init__rZ   rB   c                 C  s   t | j| jfƒS r<   )rZ   r   r4   rC   r1   r1   r2   Ú__str__ø  s    zMQTTMessageInfo.__str__zIterator[MQTTErrorCode | int]c                 C  s
   d| _ | S ©Nr   )r¼   rC   r1   r1   r2   Ú__iter__û  s    zMQTTMessageInfo.__iter__rY   c                 C  s   |   ¡ S r<   )r˜   rC   r1   r1   r2   Ú__next__ÿ  s    zMQTTMessageInfo.__next__c                 C  s4   | j dkrd| _ | jS | j dkr,d| _ | jS t‚d S )Nr   r   é   )r¼   r   r4   rš   rC   r1   r1   r2   r˜     s    

zMQTTMessageInfo.next)Úindexr;   c                 C  s(   |dkr| j S |dkr| jS tdƒ‚d S )Nr   r   zindex out of range)r   r4   Ú
IndexError)r=   rÇ   r1   r1   r2   Ú__getitem__  s
    zMQTTMessageInfo.__getitem__rA   c              	   C  s&   | j � d| _| j  ¡  W 5 Q R X d S )NT)r»   rº   ÚnotifyrC   r1   r1   r2   Ú_set_as_published  s    z!MQTTMessageInfo._set_as_publishedNzfloat | None©Útimeoutr;   c              	     sÈ   | j tkrtdƒ‚n*| j tkr n| j dkr>tdt| j ƒ› �ƒ‚|dkrJdntƒ | ‰ |dkr`dn|d }ddœ‡ fdd	„}| j�  | jsœ|ƒ sœ| j 	|¡ q‚W 5 Q R X | j dkrÄtdt| j ƒ› �ƒ‚dS )
aÈ  Block until the message associated with this object is published, or
        until the timeout occurs. If timeout is None, this will never time out.
        Set timeout to a positive number of seconds, e.g. 1.2, to enable the
        timeout.

        :raises ValueError: if the message was not queued due to the outgoing
            queue being full.

        :raises RuntimeError: if the message was not published for another
            reason.
        ú+Message is not queued due to ERR_QUEUE_SIZEr   úMessage publish failed: Ng      $@rF   rB   c                     s   ˆ d krdS t ƒ ˆ kS )NF)Ú	time_funcr1   ©Ztimeout_timer1   r2   Ú	timed_out.  s    z3MQTTMessageInfo.wait_for_publish.<locals>.timed_out)
r   rl   r‹   ÚMQTT_ERR_AGAINÚRuntimeErrorrn   rÐ   r»   rº   Úwait)r=   rÍ   Ztimeout_tenthrÒ   r1   rÑ   r2   Úwait_for_publish  s    




z MQTTMessageInfo.wait_for_publishrF   c              
   C  sf   | j tjkrtdƒ‚n,| j tjkr$n| j dkrBtdt| j ƒ› �ƒ‚| j� | jW  5 Q R £ S Q R X dS )z¶Returns True if the message associated with this object has been
        published, else returns False.

        To wait for this to become true, look at `wait_for_publish`.
        rÎ   r   rÏ   N)	r   r   rl   r‹   rÓ   rÔ   rn   r»   rº   rC   r1   r1   r2   Úis_published8  s    

zMQTTMessageInfo.is_published)N)r-   r.   r/   rS   Ú	__slots__rÁ   rÂ   rÄ   rÅ   r˜   rÉ   rË   rÖ   r×   r1   r1   r1   r2   r¹   æ  s   

r¹   c                   @  sn   e Zd ZdZdZddddœdd	„Zd
ddœdd„Zd
ddœdd„Zeddœdd„ƒZ	e	j
dddœdd„ƒZ	dS )rW   z� This is a class that describes an incoming message. It is
    passed to the `on_message` callback as the message parameter.
    )
Ú	timestampÚstateÚdupr4   Ú_topicr³   r5   Úretainr8   Ú
propertiesr   rµ   r"   r6   )r4   r—   c                 C  sD   d| _ t| _d| _|| _|| _d| _d| _d| _t	|ƒ| _
d | _d S )Nç        Frµ   r   )rÙ   Úmqtt_ms_invalidrÚ   rÛ   r4   rÜ   r³   r5   rÝ   r¹   r8   rÞ   )r=   r4   r—   r1   r1   r2   rÁ   O  s    
zMQTTMessage.__init__ÚobjectrF   )Úotherr;   c                 C  s   t || jƒr| j|jkS dS )z$Override the default Equals behaviorF)rp   Ú	__class__r4   ©r=   râ   r1   r1   r2   Ú__eq__`  s    zMQTTMessage.__eq__c                 C  s   |   |¡ S )zDefine a non-equality test)rå   rä   r1   r1   r2   Ú__ne__f  s    zMQTTMessage.__ne__rZ   rB   c                 C  s   | j  d¡S )zVtopic that the message was published on.

        This property is read-only.
        r¯   )rÜ   ÚdecoderC   r1   r1   r2   r—   j  s    zMQTTMessage.topicrA   ©Úvaluer;   c                 C  s
   || _ d S r<   )rÜ   ©r=   ré   r1   r1   r2   r—   r  s    N)r   rµ   )r-   r.   r/   rS   rØ   rÁ   rå   ræ   Úpropertyr—   Úsetterr1   r1   r1   r2   rW   I  s   c                   @  sÄ  e Zd ZdZejdddedddfddd	d
ddddddœ	dd„Zddœdd„Ze	ddœdd„ƒZ
e
jdddœdd„ƒZ
e	ddœdd„ƒZejdddœdd„ƒZe	ddœdd„ƒZejdddœd d„ƒZe	ddœd!d"„ƒZejd#ddœd$d"„ƒZe	ddœd%d&„ƒZe	d'dœd(d)„ƒZejd'ddœd*d)„ƒZe	ddœd+d,„ƒZejdddœd-d,„ƒZe	ddœd.d/„ƒZejdddœd0d/„ƒZe	ddœd1d2„ƒZejdddœd3d2„ƒZe	ddœd4d5„ƒZejdddœd6d5„ƒZe	ddœd7d8„ƒZe	d9dœd:d;„ƒZe	d<dœd=d>„ƒZejd<ddœd?d>„ƒZdd@dAœdBdC„Zd@ddDœdEdF„ZddœdGdH„Z�d»dddIœdJdK„Z�d¼ddd
ddLœdMdN„Z�d½ddPddQœdRdS„Z�d¾dTddUœdVdW„Z�d¿ddddXdYdddZdd[œ	d\d]„Zdddœd^d_„Z d
dd`œdadb„Z!�dÀd<ddcœddde„Z"ddœdfdg„Z#dhdiddje$dfddddddkdldmdnœdodp„Z%ddiddje$dfdddddkdldmdqœdrds„Z&dhdiddje$dfddddddkdlddnœdtdu„Z'�dÁddddxœdydz„Z(dmdœd{d|„Z)�dÂd'dmd~œdd€„Z*�dÃd'dmd~œd�d‚„Z+�dÄddƒdddld„d…œd†d‡„Z,�dÅddddˆœd‰dŠ„Z-ddœd‹dŒ„Z.ddœd�dŽ„Z/ddœd�d�„Z0�dÆd‘dldmd’œd“d”„Z1�dÇd•dd–dld—d˜œd™dš„Z2�dÈd›dld—dœœd�dž„Z3�dÉddmdŸœd d¡„Z4dmdœd¢d£„Z5ddœd¤d¥„Z6dmdœd¦d§„Z7ddd¨œd©dª„Z8dd d«œd¬d­„Z9d
dd®œd¯d°„Z:d
dœd±d²„Z;�dÊddƒdddldd…œd³d´„Z<ddœdµd¶„Z=d·dœd¸d¹„Z>�dËd'ddmdºœd»d¼„Z?dmdœd½d¾„Z@dmdœd¿dÀ„ZAe	ddœdÁdÂ„ƒZBe	dÃdœdÄdÅ„ƒZCeCjdÃddÆœdÇdÅ„ƒZCdÈdœdÉdÊ„ZDe	dËdœdÌdÍ„ƒZEeEjdËddÆœdÎdÍ„ƒZEdÏdœdÐdÑ„ZFe	dÒdœdÓdÔ„ƒZGeGjdÒddÆœdÕdÔ„ƒZGdÖdœd×dØ„ZHe	dÙdœdÚdÛ„ƒZIeIjdÙddÆœdÜdÛ„ƒZIdÝdœdÞdß„ZJe	dàdœdádâ„ƒZKeKjdàddÆœdãdâ„ƒZKdädœdådæ„ZLe	dçdœdèdé„ƒZMeMjdçddÆœdêdé„ƒZMdëdœdìdí„ZNe	dîdœdïdð„ƒZOeOjdîddÆœdñdð„ƒZOdòdœdódô„ZPe	dõdœdöd÷„ƒZQeQjdõddÆœdød÷„ƒZQdùdœdúdû„ZRe	düdœdýdþ„ƒZSeSjdüddÆœdÿdþ„ƒZS�d dœ�d�d„ZTe	�ddœ�d�d„ƒZUeUj�dddÆœ�d�d„ƒZU�ddœ�d�d	„ZV�d
d�dœ�d�d„ZWe	�ddœ�d�d„ƒZXeXj�dddÆœ�d�d„ƒZX�ddœ�d�d„ZY�d
d�dœ�d�d„ZZe	�ddœ�d�d„ƒZ[e[j�dddÆœ�d�d„ƒZ[�ddœ�d�d„Z\ddœ�d�d„Z]e	�ddœ�d�d„ƒZ^e^j�dddÆœ�d�d„ƒZ^�ddœ�d�d „Z_�dÌd·d�dœ�d!�d"„Z`d�d#d�d$œ�d%�d&„Zaddë�d'œ�d(�d)„Zbdd�d'œ�d*�d+„Zcdmdm�d,œ�d-�d.„Zddmdœ�d/�d0„Zedmdœ�d1�d2„Zf�d3dd
d�d4œ�d5�d6„Zgddœ�d7�d8„Zhddœ�d9�d:„Ziejd@d�d;œ�d<�d=„ƒZkejd@dm�d'œ�d>�d?„ƒZldmdœ�d@�dA„Zmdmdœ�dB�dC„Znddm�dDœ�dE�dF„Zoddm�dDœ�dG�dH„Zp�dId�dI�dJœ�dK�dL„Zq�dI�dMd�dNœ�dO�dP„Zr�dÍdd@�dRddd�dSdldm�dTœ	�dU�dV„Zsddm�dDœ�dW�dX„Ztddm�dDœ�dY�dZ„Zuddddm�d[œ�d\�d]„Zvddm�d^œ�d_�d`„Zwddm�daœ�db�dc„Zx�dÎd‘dldmd’œ�dd�de„Zy�dÏd�dfdl�dg�dhœ�di�dj„Zz�dÐd�dkdl�dg�dhœ�dl�dm„Z{ddœ�dn�do„Z|ddœ�dp�dq„Z}ddœ�dr�ds„Z~ddœ�dt�du„Z�dÑdd@dd�dSdm�dvœ�dw�dx„Z€dmdœ�dy�dz„Z�dmdœ�d{�d|„Z‚dmdœ�d}�d~„Zƒdmdœ�d�d€„Z„ddœ�d��d‚„Z…ddœ�dƒ�d„„Z†dmdœ�d…�d†„Z‡dddm�d‡œ�dˆ�d‰„Zˆdd�dŠœ�d‹�dŒ„Z‰dmdœ�d��dŽ„ZŠdmdœ�d��d�„Z‹dmdœ�d‘�d’„ZŒdmdœ�d“�d”„Z��dÒddmd‘dld�d•œ�d–�d—„ZŽd�d˜�d™dm�dšœ�d›�dœ„Z��d�dm�džœ�dŸ�d „Z��d¡d�d¢œ�d£�d¤„Z‘ddœ�d¥�d¦„Z’ddœ�d§�d¨„Z“ddœ�d©�dª„Z”ejddœ�d«�d¬„ƒZ•�d­dœ�d®�d¯„Z–�d
dœ�d°�d±„Z—�d²dœ�d³�d´„Z˜�d²dœ�dµ�d¶„Z™�d²�d·�d¸œ�d¹�dº„ZšdS (Ó  rV   aó  MQTT version 3.1/3.1.1/5.0 client class.

    This is the main class for use communicating with an MQTT broker.

    General usage flow:

    * Use `connect()`, `connect_async()` or `connect_srv()` to connect to a broker
    * Use `loop_start()` to set a thread running to call `loop()` for you.
    * Or use `loop_forever()` to handle calling `loop()` for you in a blocking function.
    * Or call `loop()` frequently to maintain network traffic flow with the broker
    * Use `subscribe()` to subscribe to a topic and receive messages
    * Use `publish()` to send messages
    * Use `disconnect()` to disconnect from the broker

    Data returned from the broker is made available with the use of callback
    functions as described below.

    :param CallbackAPIVersion callback_api_version: define the API version for user-callback (on_connect, on_publish,...).
        This field is required and it's recommended to use the latest version (CallbackAPIVersion.API_VERSION2).
        See each callback for description of API for each version. The file docs/migrations.rst contains details on
        how to migrate between version.

    :param str client_id: the unique client id string used when connecting to the
        broker. If client_id is zero length or None, then the behaviour is
        defined by which protocol version is in use. If using MQTT v3.1.1, then
        a zero length client id will be sent to the broker and the broker will
        generate a random for the client. If using MQTT v3.1 then an id will be
        randomly generated. In both cases, clean_session must be True. If this
        is not the case a ValueError will be raised.

    :param bool clean_session: a boolean that determines the client type. If True,
        the broker will remove all information about this client when it
        disconnects. If False, the client is a persistent client and
        subscription information and queued messages will be retained when the
        client disconnects.
        Note that a client will never discard its own outgoing messages on
        disconnect. Calling connect() or reconnect() will cause the messages to
        be resent.  Use reinitialise() to reset a client to its original state.
        The clean_session argument only applies to MQTT versions v3.1.1 and v3.1.
        It is not accepted if the MQTT version is v5.0 - use the clean_start
        argument on connect() instead.

    :param userdata: user defined data of any type that is passed as the "userdata"
        parameter to callbacks. It may be updated at a later point with the
        user_data_set() function.

    :param int protocol: allows explicit setting of the MQTT version to
        use for this client. Can be paho.mqtt.client.MQTTv311 (v3.1.1),
        paho.mqtt.client.MQTTv31 (v3.1) or paho.mqtt.client.MQTTv5 (v5.0),
        with the default being v3.1.1.

    :param transport: use "websockets" to use WebSockets as the transport
        mechanism. Set to "tcp" to use raw TCP, which is the default.
        Use "unix" to use Unix sockets as the transport mechanism; note that
        this option is only available on platforms that support Unix sockets,
        and the "host" argument is interpreted as the path to the Unix socket
        file in this case.

    :param bool manual_ack: normally, when a message is received, the library automatically
        acknowledges after on_message callback returns.  manual_ack=True allows the application to
        acknowledge receipt after it has completed processing of a message
        using a the ack() method. This addresses vulnerability to message loss
        if applications fails while processing a message, or while it pending
        locally.

    Callbacks
    =========

    A number of callback functions are available to receive data back from the
    broker. To use a callback, define a function and then assign it to the
    client::

        def on_connect(client, userdata, flags, reason_code, properties):
            print(f"Connected with result code {reason_code}")

        client.on_connect = on_connect

    Callbacks can also be attached using decorators::

        mqttc = paho.mqtt.Client()

        @mqttc.connect_callback()
        def on_connect(client, userdata, flags, reason_code, properties):
            print(f"Connected with result code {reason_code}")

    All of the callbacks as described below have a "client" and an "userdata"
    argument. "client" is the `Client` instance that is calling the callback.
    userdata" is user data of any type and can be set when creating a new client
    instance or with `user_data_set()`.

    If you wish to suppress exceptions within a callback, you should set
    ``mqttc.suppress_exceptions = True``

    The callbacks are listed below, documentation for each of them can be found
    at the same function name:

    `on_connect`, `on_connect_fail`, `on_disconnect`, `on_message`, `on_publish`,
    `on_subscribe`, `on_unsubscribe`, `on_log`, `on_socket_open`, `on_socket_close`,
    `on_socket_register_write`, `on_socket_unregister_write`
    rŠ   NÚtcpTFr   z
str | Nonezbool | Noner   r   z&Literal[('tcp', 'websockets', 'unix')]rF   rA   )	Úcallback_api_versionÚ	client_idÚclean_sessionÚuserdataÚprotocolÚ	transportÚreconnect_on_failureÚ
manual_ackr;   c	           	   	   C  s  |  ¡ }|dkr$ttdƒs$tdƒ‚n|dkr:td|› �ƒ‚|| _|| _|| _|| _d | _d | _	d | _
d| _d| _t| _|| _| jtjkr˜tjdtd	d
� t| jtƒr¬tdƒ‚| jtkr¾tdƒ‚t| _|tkrÞ|d k	rÜtdƒ‚n4|d krêd}|�s|dk�s|d k�rtdƒ‚|| _|dk�s&|d k�rT|tk�rLtt ¡ jdd�  d¡| _!nd| _!n
t"|ƒ| _!d | _#d | _$ddg ddt%dƒdddœ| _&t' (¡ | _)t*ƒ | _+t*ƒ | _,d| _-d| _.d | _/|| _0d| _1d| _2t3j4| _5t' 6¡ | _7t' 6¡ | _8d| _9d| _:d| _;d | _<d | _=d| _>d| _?d| _@d| _Ad| _BtCƒ | _Dd| _Ed| _Fd| _Gd| _Hi | _ItJ K¡ | _LtJ M¡ | _NtJ K¡ | _OtJ M¡ | _PtJ K¡ | _QtJ K¡ | _RtJ K¡ | _Sd | _Td| _Ud| _Vd | _Wd| _Xd | _Yd| _Zd | _[d | _\d | _]d | _^d | __d | _`d | _ad | _bd | _cd | _dd | _ed | _fd | _gd| _hd | _id| _jd| _kd S )NÚunixÚAF_UNIXz"unix" transport not supported)Ú
websocketsrí   rö   z5transport must be "websockets", "tcp" or "unix", not é<   g      @z>Callback API version 1 is deprecated, update to latest versionrÆ   )ÚcategoryÚ
stacklevelzoUnsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for detailsú Unsupported callback API versionz&Clean session is not used for MQTT 5.0TrŠ   z7A client id must be provided if clean session is False.é   ©r„   Úutf8rµ   r   r   ©r#   r$   r%   r&   r'   r)   r*   r+   éx   rß   é   Fé[  ú/mqtt)lÚlowerÚhasattrrž   r‹   Ú_manual_ackÚ
_transportÚ	_protocolÚ	_userdataÚ_sockÚ
_sockpairRÚ
_sockpairWÚ
_keepaliveÚ_connect_timeoutÚMQTT_CLIENTÚ_client_modeÚ_callback_api_versionr   ÚVERSION1ÚwarningsÚwarnÚDeprecationWarningrp   rZ   rN   Ú_clean_startÚMQTTv5Ú_clean_sessionÚMQTTv31r•   ÚuuidÚuuid4r"   r°   Ú
_client_idr±   Ú	_usernameÚ	_passwordr(   Ú
_in_packetÚcollectionsÚdequeÚ_out_packetrÐ   Ú_last_msg_inÚ_last_msg_outÚ_reconnect_min_delayÚ_reconnect_max_delayÚ_reconnect_delayÚ_reconnect_on_failureÚ_ping_tÚ	_last_midr   ÚMQTT_CS_NEWÚ_stateÚOrderedDictÚ_out_messagesÚ_in_messagesÚ_max_inflight_messagesÚ_inflight_messagesÚ_max_queued_messagesÚ_connect_propertiesÚ_will_propertiesÚ_willÚ_will_topicÚ_will_payloadÚ	_will_qosÚ_will_retainr   Ú_on_message_filteredÚ_hostÚ_portÚ_bind_addressÚ
_bind_portÚ_proxyr¾   ÚLockÚ_in_callback_mutexÚRLockÚ_callback_mutexÚ_msgtime_mutexÚ_out_message_mutexÚ_in_message_mutexÚ_reconnect_delay_mutexÚ_mid_generate_mutexÚ_threadÚ_thread_terminateÚ_sslÚ_ssl_contextÚ_tls_insecureÚ_loggerÚ_registered_writeÚ_on_logÚ_on_pre_connectÚ_on_connectÚ_on_connect_failÚ_on_subscribeÚ_on_messageÚ_on_publishÚ_on_unsubscribeÚ_on_disconnectÚ_on_socket_openÚ_on_socket_closeÚ_on_socket_register_writeÚ_on_socket_unregister_writeÚ_websocket_pathÚ_websocket_extra_headersÚ_mqttv5_first_connectÚsuppress_exceptions)	r=   rî   rï   rð   rñ   rò   ró   rô   rõ   r1   r1   r2   rÁ   Ý  sì    
ÿýÿ

ÿ

ø

þþ






zClient.__init__rB   c                 C  s   |   ¡  d S r<   )Ú_reset_socketsrC   r1   r1   r2   Ú__del__o  s    zClient.__del__rZ   c                 C  s   | j S )z²
        Host to connect to. If `connect()` hasn't been called yet, returns an empty string.

        This property may not be changed if the connection is already open.
        )r<  rC   r1   r1   r2   Úhostr  s    zClient.hostrè   c                 C  s&   |   ¡ stdƒ‚|stdƒ‚|| _d S )Nz8updating host on established connection is not supportedúInvalid host.)Ú_connection_closedrÔ   r‹   r<  rê   r1   r1   r2   rd  {  s
    r"   c                 C  s   | j S )z}
        Broker TCP port to connect to.

        This property may not be changed if the connection is already open.
        )r=  rC   r1   r1   r2   r«   „  s    zClient.portc                 C  s*   |   ¡ stdƒ‚|dkr tdƒ‚|| _d S )Nz8updating port on established connection is not supportedr   úInvalid port number.)rf  rÔ   r‹   r=  rê   r1   r1   r2   r«   �  s
    c                 C  s   | j S )z†
        Client keepalive interval (in seconds).

        This property may not be changed if the connection is already open.
        )r  rC   r1   r1   r2   Ú	keepalive–  s    zClient.keepalivec                 C  s*   |   ¡ stdƒ‚|dk r tdƒ‚|| _d S )Nz=updating keepalive on established connection is not supportedr   zKeepalive must be >=0.)rf  rÔ   r‹   r  rê   r1   r1   r2   rh  Ÿ  s
    c                 C  s   | j S )z 
        Transport method used for the connection ("tcp" or "websockets").

        This property may not be changed if the connection is already open.
        )r  rC   r1   r1   r2   ró   «  s    zClient.transportzLiteral[('tcp', 'websockets')]c                 C  s   |   ¡ stdƒ‚|| _d S )Nz=updating transport on established connection is not supported)rf  rÔ   r  rê   r1   r1   r2   ró   ´  s    c                 C  s   | j S )zj
        Protocol version used (MQTT v3, MQTT v3.11, MQTTv5)

        This property is read-only.
        )r	  rC   r1   r1   r2   rò   »  s    zClient.protocolr¶   c                 C  s   | j S )z‹
        Connection establishment timeout in seconds.

        This property may not be changed if the connection is already open.
        )r  rC   r1   r1   r2   Úconnect_timeoutÄ  s    zClient.connect_timeoutc                 C  s*   |   ¡ stdƒ‚|dkr tdƒ‚|| _d S )NzCupdating connect_timeout on established connection is not supportedrß   z!timeout must be a positive number)rf  rÔ   r‹   r  rê   r1   r1   r2   ri  Í  s
    c                 C  s   | j dkrdS | j  d¡S )z¦The username used to connect to the MQTT broker, or None if no username is used.

        This property may not be changed if the connection is already open.
        Nr¯   )r  rç   rC   r1   r1   r2   Úusername×  s    
zClient.usernamec                 C  s0   |   ¡ stdƒ‚|d kr d | _n| d¡| _d S )Nz<updating username on established connection is not supportedr¯   )rf  rÔ   r  r°   rê   r1   r1   r2   rj  á  s
    c                 C  s   | j dkrdS | j  d¡S )z¦The password used to connect to the MQTT broker, or None if no password is used.

        This property may not be changed if the connection is already open.
        Nr¯   )r  rç   rC   r1   r1   r2   Úpasswordë  s    
zClient.passwordc                 C  s0   |   ¡ stdƒ‚|d kr d | _n| d¡| _d S )Nz<updating password on established connection is not supportedr¯   )rf  rÔ   r  r°   rê   r1   r1   r2   rk  õ  s
    c                 C  s   | j S )z»
        Maximum number of messages with QoS > 0 that can be partway through the network flow at once

        This property may not be changed if the connection is already open.
        )r1  rC   r1   r1   r2   Úmax_inflight_messagesÿ  s    zClient.max_inflight_messagesc                 C  s*   |   ¡ stdƒ‚|dk r tdƒ‚|| _d S )NzIupdating max_inflight_messages on established connection is not supportedr   zInvalid inflight.)rf  rÔ   r‹   r1  rê   r1   r1   r2   rl    s
    c                 C  s   | j S )z©
        Maximum number of message in the outgoing message queue, 0 means unlimited

        This property may not be changed if the connection is already open.
        )r3  rC   r1   r1   r2   Úmax_queued_messages  s    zClient.max_queued_messagesc                 C  s*   |   ¡ stdƒ‚|dk r tdƒ‚|| _d S )NzGupdating max_queued_messages on established connection is not supportedr   zInvalid queue size.)rf  rÔ   r‹   r3  rê   r1   r1   r2   rm    s
    c                 C  s   | j dkrdS | j  d¡S )zÈ
        The topic name a will message is sent to when disconnecting unexpectedly. None if a will shall not be sent.

        This property is read-only. Use `will_set()` to change its value.
        Nr¯   )r7  rç   rC   r1   r1   r2   Ú
will_topic(  s    
zClient.will_topiczbytes | Nonec                 C  s   | j S )zÍ
        The payload for the will message that is sent when disconnecting unexpectedly. None if a will shall not be sent.

        This property is read-only. Use `will_set()` to change its value.
        )r8  rC   r1   r1   r2   Úwill_payload4  s    zClient.will_payloadzlogging.Logger | Nonec                 C  s   | j S r<   ©rO  rC   r1   r1   r2   Úlogger=  s    zClient.loggerc                 C  s
   || _ d S r<   rp  rê   r1   r1   r2   rq  A  s    r6   )Úbufsizer;   c              
   C  sº   | j d krtdƒ‚z| j  |¡W S  tjk
rL } ztƒ |‚W 5 d }~X Y nj tjk
r~ } z|  ¡  tƒ |‚W 5 d }~X Y n8 tk
r´ } z|  	t
d|¡ tƒ |‚W 5 d }~X Y nX d S )Núself._sock is Nonezsocket was None: %s)r  ÚConnectionErrorr>   ÚsslÚSSLWantReadErrorr©   ÚSSLWantWriteErrorÚ_call_socket_register_writeÚAttributeErrorÚ	_easy_logÚMQTT_LOG_DEBUG)r=   rr  Úerrr1   r1   r2   Ú
_sock_recvE  s     
  ÿzClient._sock_recv)Úbufr;   c              
   C  s´   | j d krtdƒ‚z| j  |¡W S  tjk
rL } ztƒ |‚W 5 d }~X Y nd tjk
r~ } z|  ¡  tƒ |‚W 5 d }~X Y n2 tk
r® } z|  ¡  tƒ |‚W 5 d }~X Y nX d S )Nrs  )r  rt  r@   ru  rv  r©   rw  rx  )r=   r~  r|  r1   r1   r2   Ú
_sock_sendT  s    
zClient._sock_sendc                 C  s>   | j s
dS z$| j }d| _ |  |¡ |  |¡ W 5 | ¡  X dS )z#Close the connection to the server.N)r  rD   Ú_call_socket_unregister_writeÚ_call_socket_close©r=   Úsockr1   r1   r2   Ú_sock_closec  s    
zClient._sock_close)Úsockpair_onlyr;   c                 C  s<   |s|   ¡  | jr"| j ¡  d | _| jr8| j ¡  d | _d S r<   )r„  r  rD   r  )r=   r…  r1   r1   r2   rb  q  s    

zClient._reset_sockets)rï   rð   rñ   r;   c                 C  s   |   ¡  |  |||¡ d S r<   )rb  rÁ   )r=   rï   rð   rñ   r1   r1   r2   Úreinitialise|  s    zClient.reinitialiser  úWebSocketHeaders | None)ÚpathÚheadersr;   c                 C  s4   || _ |dk	r0t|tƒs t|ƒr(|| _ntdƒ‚dS )a   Set the path and headers for a websocket connection

        :param str path: a string starting with / which should be the endpoint of the
            mqtt connection on the remote server

        :param headers:  can be either a dict or a callable object. If it is a dict then
            the extra items in the dict are added to the websocket headers. If it is
            a callable, then the default websocket headers are passed into this
            function and the result is used as the new headers.
        NzL'headers' option to ws_set_options has to be either a dictionary or callable)r^  rp   ÚdictÚcallabler_  r‹   )r=   rˆ  r‰  r1   r1   r2   Úws_set_options†  s    ÿzClient.ws_set_optionszssl.SSLContext | None)Úcontextr;   c                 C  sF   | j dk	rtdƒ‚|dkr"t ¡ }d| _|| _ t|dƒrB|j | _dS )a.  Configure network encryption and authentication context. Enables SSL/TLS support.

        :param context: an ssl.SSLContext object. By default this is given by
            ``ssl.create_default_context()``, if available.

        Must be called before `connect()`, `connect_async()` or `connect_srv()`.Nz$SSL/TLS has already been configured.TÚcheck_hostname)rM  r‹   ru  Úcreate_default_contextrL  r  rŽ  rN  )r=   r�  r1   r1   r2   Útls_set_contextž  s    


zClient.tls_set_contextzssl.VerifyMode | Nonez
int | Nonezlist[str] | None)	Úca_certsÚcertfileÚkeyfileÚ	cert_reqsÚtls_versionÚciphersÚkeyfile_passwordÚalpn_protocolsr;   c	           
      C  sD  t dkrtdƒ‚tt dƒs"tdƒ‚|dkr>tt jdƒs>tdƒ‚|dkrnt j}tt dƒr^t j}ntt dƒrnt j}t  |¡}	|dk	rŠ|	 |¡ |dk	r |	 |||¡ |t j	krºt|	d	ƒrºd
|	_
|dkrÈt jn||	_|dk	râ|	 |¡ n|	 ¡  |dk	�rtt ddƒ�s
tdƒ‚|	 |¡ |  |	¡ |t j	k�r6|  d
¡ n
|  d¡ dS )a�  Configure network encryption and authentication options. Enables SSL/TLS support.

        :param str ca_certs: a string path to the Certificate Authority certificate files
            that are to be treated as trusted by this client. If this is the only
            option given then the client will operate in a similar manner to a web
            browser. That is to say it will require the broker to have a
            certificate signed by the Certificate Authorities in ca_certs and will
            communicate using TLS v1,2, but will not attempt any form of
            authentication. This provides basic network encryption but may not be
            sufficient depending on how the broker is configured.

            By default, on Python 2.7.9+ or 3.4+, the default certification
            authority of the system is used. On older Python version this parameter
            is mandatory.
        :param str certfile: PEM encoded client certificate filename. Used with
            keyfile for client TLS based authentication. Support for this feature is
            broker dependent. Note that if the files in encrypted and needs a password to
            decrypt it, then this can be passed using the keyfile_password argument - you
            should take precautions to ensure that your password is
            not hard coded into your program by loading the password from a file
            for example. If you do not provide keyfile_password, the password will
            be requested to be typed in at a terminal window.
        :param str keyfile: PEM encoded client private keys filename. Used with
            certfile for client TLS based authentication. Support for this feature is
            broker dependent. Note that if the files in encrypted and needs a password to
            decrypt it, then this can be passed using the keyfile_password argument - you
            should take precautions to ensure that your password is
            not hard coded into your program by loading the password from a file
            for example. If you do not provide keyfile_password, the password will
            be requested to be typed in at a terminal window.
        :param cert_reqs: the certificate requirements that the client imposes
            on the broker to be changed. By default this is ssl.CERT_REQUIRED,
            which means that the broker must provide a certificate. See the ssl
            pydoc for more information on this parameter.
        :param tls_version: the version of the SSL/TLS protocol used to be
            specified. By default TLS v1.2 is used. Previous versions are allowed
            but not recommended due to possible security problems.
        :param str ciphers: encryption ciphers that are allowed
            for this connection, or None to use the defaults. See the ssl pydoc for
            more information.

        Must be called before `connect()`, `connect_async()` or `connect_srv()`.NzThis platform has no SSL/TLS.Ú
SSLContextz@Python 2.7.9 and 3.2 are the minimum supported versions for TLS.Úload_default_certszca_certs must not be None.ÚPROTOCOL_TLS_CLIENTÚPROTOCOL_TLSrŽ  FÚHAS_ALPNz#SSL library has no support for ALPNT)ru  r‹   r  r™  ÚPROTOCOL_TLSv1_2r›  rœ  Úset_ciphersÚload_cert_chainÚ	CERT_NONErŽ  ÚCERT_REQUIREDÚverify_modeÚload_verify_locationsrš  ÚgetattrÚset_alpn_protocolsr�  Útls_insecure_set)
r=   r‘  r’  r“  r”  r•  r–  r—  r˜  r�  r1   r1   r2   Útls_setµ  sB    5
ÿ






zClient.tls_setc                 C  s2   | j dkrtdƒ‚|| _t| j dƒr.| | j _dS )ap  Configure verification of the server hostname in the server certificate.

        If value is set to true, it is impossible to guarantee that the host
        you are connecting to is not impersonating your server. This can be
        useful in initial server testing, but makes it possible for a malicious
        third party to impersonate your server through DNS spoofing, for
        example.

        Do not use this function in a real system. Setting value to true means
        there is no point using encryption.

        Must be called before `connect()` and after either `tls_set()` or
        `tls_set_context()`.Nz9Must configure SSL context before using tls_insecure_set.rŽ  )rM  r‹   rN  r  rŽ  rê   r1   r1   r2   r§     s    
ÿzClient.tls_insecure_set)Ú
proxy_argsr;   c                 K  s0   t dkrtdƒ‚n|  |¡s&tdƒ‚n|| _dS )aõ  Configure proxying of MQTT connection. Enables support for SOCKS or
        HTTP proxies.

        Proxying is done through the PySocks library. Brief descriptions of the
        proxy_args parameters are below; see the PySocks docs for more info.

        (Required)

        :param proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5}
        :param proxy_addr: IP address or DNS name of proxy server

        (Optional)

        :param proxy_port: (int) port number of the proxy server. If not provided,
            the PySocks package default value will be utilized, which differs by proxy_type.
        :param proxy_rdns: boolean indicating whether proxy lookup should be performed
            remotely (True, default) or locally (False)
        :param proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy
        :param proxy_password: password for SOCKS5 proxy

        Example::

            mqttc.proxy_set(proxy_type=socks.HTTP, proxy_addr='1.2.3.4', proxy_port=4231)
        Nz,PySocks must be installed for proxy support.z)proxy_type and/or proxy_addr are invalid.)Úsocksr‹   Ú_proxy_is_validr@  )r=   r©  r1   r1   r2   Ú	proxy_set;  s
    


zClient.proxy_set)rq  r;   c                 C  s*   |dkr | j dk	rdS t t¡}|| _dS )a  
        Enables a logger to send log messages to

        :param logging.Logger logger: if specified, that ``logging.Logger`` object will be used, otherwise
            one will be created automatically.

        See `disable_logger` to undo this action.
        N)rO  ÚloggingÚ	getLoggerr-   rq  )r=   rq  r1   r1   r2   Úenable_logger[  s
    	

zClient.enable_loggerc                 C  s
   d| _ dS )zu
        Disable logging using standard python logging package. This has no effect on the `on_log` callback.
        Nrp  rC   r1   r1   r2   Údisable_loggerk  s    zClient.disable_loggerr  rù   r   rM   zProperties | Noner   )rd  r«   rh  Úbind_addressÚ	bind_portÚclean_startrÞ   r;   c              	   C  sL   | j tkrd| _n|tkr"tdƒ‚|r.tdƒ‚|  |||||||¡ |  ¡ S )aé  Connect to a remote broker. This is a blocking call that establishes
        the underlying connection and transmits a CONNECT packet.
        Note that the connection status will not be updated until a CONNACK is received and
        processed (this requires a running network loop, see `loop_start`, `loop_forever`, `loop`...).

        :param str host: the hostname or IP address of the remote broker.
        :param int port: the network port of the server host to connect to. Defaults to
            1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
            are using `tls_set()` the port may need providing.
        :param int keepalive: Maximum period in seconds between communications with the
            broker. If no other messages are being exchanged, this controls the
            rate at which the client will send ping messages to the broker.
        :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
            Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
            respectively.  MQTT session data (such as outstanding messages and subscriptions)
            is cleared on successful connect when the clean_start flag is set.
            For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar
            result.
        :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
            MQTT connect packet.
        Tz#Clean start only applies to MQTT V5z Properties only apply to MQTT V5)r	  r  r`  rN   r‹   Úconnect_asyncÚ	reconnect©r=   rd  r«   rh  r±  r²  r³  rÞ   r1   r1   r2   r¨   q  s     

   ÿzClient.connect)Údomainrh  r±  r²  r³  rÞ   r;   c              
   C  s6  t dkrtdƒ‚|dkr6t ¡ }|| d¡d d… }zdd|› �}| jrRd|› �}g }tj |tj	j
¡D ].}	|	j ¡ dd… }
| |
|	j|	j|	jf¡ qhW nD tjjtjjtjjfk
rÞ } ztd	|› �ƒ|‚W 5 d}~X Y nX |D ]D}	|	\}}}}z|  |||||||¡W   S  tk
�r&   Y qäX qätd
ƒ‚dS )z÷Connect to a remote broker.

        :param str domain: the DNS domain to search for SRV records; if None,
            try to determine local domain name.
        :param keepalive, bind_address, clean_start and properties: see `connect()`
        Fz;No DNS resolver library found, try "pip install dnspython".NÚ.r   z_mqtt._tcp.z_secure-mqtt._tcp.éÿÿÿÿzNo answer/NXDOMAIN for SRV in zNo SRV hosts responded)ÚHAVE_DNSr‹   rž   ÚgetfqdnÚfindrL  ÚdnsÚresolverÚqueryZ	rdatatypeZSRVÚtargetZto_textr�   r«   ÚpriorityÚweightZNXDOMAINZNoAnswerZNoNameserversr¨   Ú	Exception)r=   r·  rh  r±  r²  r³  rÞ   ZrrZanswersZanswerÚaddrr|  rd  r«   ÚpriorÂ  r1   r1   r2   Úconnect_srv�  s4    ÿ

ÿ
""zClient.connect_srvc                 C  sV   |dk rt dƒ‚|  ¡  tj| _|| _|| _|| _|| _|| _	|| _
|| _tj| _dS )aŒ  Connect to a remote broker asynchronously. This is a non-blocking
        connect call that can be used with `loop_start()` to provide very quick
        start.

        Any already established connection will be terminated immediately.

        :param str host: the hostname or IP address of the remote broker.
        :param int port: the network port of the server host to connect to. Defaults to
            1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
            are using `tls_set()` the port may need providing.
        :param int keepalive: Maximum period in seconds between communications with the
            broker. If no other messages are being exchanged, this controls the
            rate at which the client will send ping messages to the broker.
        :param bool clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.
            Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
            respectively.  MQTT session data (such as outstanding messages and subscriptions)
            is cleared on successful connect when the clean_start flag is set.
            For MQTT v3.1.1, the ``clean_session`` argument of `Client` should be used for similar
            result.
        :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
            MQTT connect packet.
        r   zInvalid bind port number.N)r‹   r„  r   r,  r-  rd  r«   rh  r>  r?  r  r4  ÚMQTT_CS_CONNECT_ASYNCr¶  r1   r1   r2   r´  Í  s     zClient.connect_asyncr   r  )Ú	min_delayÚ	max_delayr;   c              	   C  s(   | j � || _|| _d| _W 5 Q R X dS )ah   Configure the exponential reconnect delay

            When connection is lost, wait initially min_delay seconds and
            double this time every attempt. The wait is capped at max_delay.
            Once the client is fully connected (e.g. not only TCP socket, but
            received a success CONNACK), the wait timer is reset to min_delay.
        N)rH  r&  r'  r(  )r=   rÈ  rÉ  r1   r1   r2   Úreconnect_delay_setý  s    zClient.reconnect_delay_setc              
   C  sx  t | jƒdkrtdƒ‚| jdkr(tdƒ‚ddg ddtdƒdddœ| _d| _tj| _	|  
¡  | jD ]B}|d d	@ tkr`|d
 dkr`|d dk	r`t|d _|d  ¡  q`| j ¡  | j� tƒ | _tƒ | _W 5 Q R X |  ¡  | j� | j}W 5 Q R X |�rDz|| | jƒ W n< tk
�rB } z|  td|¡ | j�s2‚ W 5 d}~X Y nX |  ¡ | _| j d¡ d| _ |  !| j¡ |  "| j#¡S )zdReconnect the client after a disconnect. Can only be called after
        connect()/connect_async().r   re  rg  r   rµ   r   rß   r#   éð   r5   r8   Nz&Caught exception in on_pre_connect: %sF)$r�   r<  r‹   r=  r(   r   r*  r   ZMQTT_CS_CONNECTINGr-  r„  r#  ÚPUBLISHrd   r   rË   ÚclearrE  rÐ   r$  r%  Ú_messages_reconnect_resetrD  Úon_pre_connectr
  rÃ  rz  ÚMQTT_LOG_ERRra  Ú_create_socketr  rJ   rP  Ú_call_socket_openÚ_send_connectr  )r=   ZpktrÏ  r|  r1   r1   r2   rµ  
  sV    
ø
(

  ÿ
zClient.reconnectç      ð?rÌ   c                 C  s8   | j dks| jdkr.| jdd� tƒ \| _ | _|  |¡S )a[  Process network events.

        It is strongly recommended that you use `loop_start()`, or
        `loop_forever()`, or if you are using an external event loop using
        `loop_read()`, `loop_write()`, and `loop_misc()`. Using loop() on it's own is
        no longer recommended.

        This function must be called regularly to ensure communication with the
        broker is carried out. It calls select() on the network socket to wait
        for network events. If incoming data is present it will then be
        processed. Outgoing commands, from e.g. `publish()`, are normally sent
        immediately that their function is called, but this is not always
        possible. loop() will also attempt to send any remaining outgoing
        messages, which also includes commands that are part of the flow for
        messages with QoS>0.

        :param int timeout: The time in seconds to wait for incoming/outgoing network
            traffic before timing out and returning.

        Returns MQTT_ERR_SUCCESS on success.
        Returns >0 on error.

        A ValueError will be raised if timeout < 0NT)r…  )r  r  rb  r­   Ú_loop)r=   rÍ   r1   r1   r2   ÚloopF  s    zClient.loopc                 C  sÂ  |dk rt dƒ‚|  ¡ r"| jg}ng }d}t| jdƒr@| j ¡ }|dkrLd}| jd kr`| jg}n| j| jg}zt ||g |¡}W n€ tk
r´   | jt	j
t	jfkrªt	j| _tj Y S  t k
ræ   | jt	j
t	jfkrÜt	j| _tj Y S  tk
�r    tj Y S X | j|d k�s|dk�r:|  ¡ }|�s6| jd k�r:|S | j�rŒ| j|d k�rŒ|d  d| j¡ z| j d¡ W n tk
�rŠ   Y nX | j|d k�rº|  ¡ }|�s¶| jd k�rº|S |  ¡ S )Nrß   zInvalid timeout.r   Úpendingr   i'  )r‹   Ú
want_writer  r  r×  r  Úselectr·   r-  r   ÚMQTT_CS_DISCONNECTINGÚMQTT_CS_DISCONNECTEDÚMQTT_CS_CONNECTION_LOSTr   rd   rÃ  rj   Ú	loop_readÚinsertr>   r©   Ú
loop_writeÚ	loop_misc)r=   rÍ   ZwlistZpending_bytesZrlistZsocklistr   r1   r1   r2   rÕ  e  sP    





zClient._loopÚPayloadTyper¹   )r—   r³   r5   rÝ   rÞ   r;   c                 C  s*  | j tkr&|dkst|ƒdkr&tdƒ‚| d¡}|  |¡ |dk sJ|dkrRtdƒ‚t|ƒ}t|ƒdkrntdƒ‚|  ¡ }|dkr¨t|ƒ}	|  	|||||d	|	|¡}
|
|	_
|	S t||ƒ}tƒ |_||_||_||_d	|_||_| j��@ | jdk�rt| jƒ| jk�rtj|j_
|jW  5 Q R £ S || jk�rDtj|j_
|jW  5 Q R £ S || j|j< | jdk�sj| j| jk �rú|  jd
7  _|d
k�rŠt|_n|dk�ršt|_|  	|j||j|j|j|j|j|j¡}
|
tjk�rà|  jd
8  _t |_|
|j_
|jW  5 Q R £ S t!|_tj"|j_
|jW  5 Q R £ S W 5 Q R X dS )a’  Publish a message on a topic.

        This causes a message to be sent to the broker and subsequently from
        the broker to any clients subscribing to matching topics.

        :param str topic: The topic that the message should be published on.
        :param payload: The actual message to send. If not given, or set to None a
            zero length message will be used. Passing an int or float will result
            in the payload being converted to a string representing that number. If
            you wish to send a true int/float, use struct.pack() to create the
            payload you require.
        :param int qos: The quality of service level to use.
        :param bool retain: If set to true, the message will be set as the "last known
            good"/retained message for the topic.
        :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included.

        Returns a `MQTTMessageInfo` class, which can be used to determine whether
        the message has been delivered (using `is_published()`) or to block
        waiting for the message to be delivered (`wait_for_publish()`). The
        message ID and return code of the publish() call can be found at
        :py:attr:`info.mid <MQTTMessage.mid>` and :py:attr:`info.rc <MQTTMessage.rc>`.

        For backwards compatibility, the `MQTTMessageInfo` class is iterable so
        the old construct of ``(rc, mid) = client.publish(...)`` is still valid.

        rc is MQTT_ERR_SUCCESS to indicate success or MQTT_ERR_NO_CONN if the
        client is not currently connected.  mid is the message ID for the
        publish request. The mid value can be used to track the publish request
        by checking against the mid argument in the on_publish() callback if it
        is defined.

        :raises ValueError: if topic is None, has zero length or is
            invalid (contains a wildcard), except if the MQTT version used is v5.0.
            For v5.0, a zero length topic can be used when a Topic Alias has been set.
        :raises ValueError: if qos is not one of 0, 1 or 2
        :raises ValueError: if the length of the payload is greater than 268435455 bytes.
        Nr   úInvalid topic.r¯   rÆ   úInvalid QoS level.iÿÿÿr\   Fr   )#r	  r  r�   r‹   r°   Ú_raise_for_invalid_topicr¸   Ú_mid_generater¹   Ú_send_publishr   rW   rÐ   rÙ   r³   r5   rÝ   rÛ   rÞ   rF  r3  r/  r   rl   r8   r4   r1  r2  Úmqtt_ms_wait_for_pubackrÚ   Úmqtt_ms_wait_for_pubrecra   Úmqtt_ms_publishÚmqtt_ms_queuedr]   )r=   r—   r³   r5   rÝ   rÞ   Ztopic_bytesZlocal_payloadÚ	local_midr8   r   Úmessager1   r1   r2   Úpublish­  sv    -


       ÿ





  ÿ
zClient.publish)rj  rk  r;   c                 C  s:   |dkrdn|  d¡| _t|tƒr0|  d¡| _n|| _dS )ad  Set a username and optionally a password for broker authentication.

        Must be called before connect() to have any effect.
        Requires a broker that supports MQTT v3.1 or more.

        :param str username: The username to authenticate with. Need have no relationship to the client id. Must be str
            [MQTT-3.1.3-11].
            Set to None to reset client back to not using username/password for broker authentication.
        :param str password: The password to authenticate with. Optional, set to None if not required. If it is str, then it
            will be encoded as UTF-8.
        Nr¯   )r°   r  rp   rZ   r  )r=   rj  rk  r1   r1   r2   Úusername_pw_set  s    
zClient.username_pw_setc                 C  s
   t | _dS )aO  Sets the client in a bridge mode instead of client mode.

        Must be called before `connect()` to have any effect.
        Requires brokers that support bridge mode.

        Under bridge mode, the broker will identify the client as a bridge and
        not send it's own messages back to it. Hence a subsciption of # is
        possible without message loops. This feature also correctly propagates
        the retain flag on the messages.

        Currently Mosquitto and RSMB support this feature. This feature can
        be used to create a bridge between multiple broker.
        N)ÚMQTT_BRIDGEr  rC   r1   r1   r2   Úenable_bridge_mode1  s    zClient.enable_bridge_modec                 C  s(   | j tjkp&| j tjtjfko&| jdkS )zX
        Return true if the connection is closed (and not trying to be opened).
        N)r-  r   r,  rÚ  rÛ  r  rC   r1   r1   r2   rf  A  s    þzClient._connection_closedc                 C  s   | j tjkS )z~Returns the current status of the connection

        True if connection exists
        False if connection is closed
        )r-  r   ÚMQTT_CS_CONNECTEDrC   r1   r1   r2   Úis_connectedI  s    zClient.is_connectedzReasonCode | None)Ú
reasoncoderÞ   r;   c                 C  s*   | j dkrtj| _tS tj| _|  ||¡S )aè  Disconnect a connected client from the broker.

        :param ReasonCode reasoncode: (MQTT v5.0 only) a ReasonCode instance setting the MQTT v5.0
            reasoncode to be sent with the disconnect packet. It is optional, the receiver
            then assuming that 0 (success) is the value.
        :param Properties properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
            to be included. Optional - if not set, no properties are sent.
        N)r  r   rÛ  r-  ra   rÚ  Ú_send_disconnect)r=   ró  rÞ   r1   r1   r2   Ú
disconnectQ  s
    
zClient.disconnectzqstr | tuple[str, int] | tuple[str, SubscribeOptions] | list[tuple[str, int]] | list[tuple[str, SubscribeOptions]]zSubscribeOptions | Nonez tuple[MQTTErrorCode, int | None])r—   r5   ÚoptionsrÞ   r;   c           	        s>  d}t |tƒr<ˆ jtkr4|\}}t |tƒs<tdƒ‚n|\}}t |ttfƒrä|dk sZ|dkrbtdƒ‚ˆ jtkr´|dkr€t|d�}n|dkr�tdƒ‚t |tƒs¢tdƒ‚| d¡|fg}n,|dksÈt	|ƒdkrÐtd	ƒ‚| d¡|fg}�nt |t
ƒ�rêt	|ƒdk�rtd
ƒ‚g }ˆ jtk�rn|D ]P\}}t |tƒ�sT|dk �sB|dk�rJtdƒ‚t|d�}| | d¡|f¡ �qn||D ]v\}}t |tƒ�sš|dk �sš|dk�r¢tdƒ‚|dk�sÊt	|ƒdk�sÊt |ttfƒ�sÒtd	ƒ‚| | d¡|f¡ �qr|dk�rütdƒ‚t‡ fdd„|D ƒƒ�rtdƒ‚ˆ jdk�r0tdfS ˆ  d||¡S )am  Subscribe the client to one or more topics.

        This function may be called in three different ways (and a further three for MQTT v5.0):

        Simple string and integer
        -------------------------
        e.g. subscribe("my/topic", 2)

        :topic: A string specifying the subscription topic to subscribe to.
        :qos: The desired quality of service level for the subscription.
            Defaults to 0.
        :options and properties: Not used.

        Simple string and subscribe options (MQTT v5.0 only)
        ----------------------------------------------------
        e.g. subscribe("my/topic", options=SubscribeOptions(qos=2))

        :topic: A string specifying the subscription topic to subscribe to.
        :qos: Not used.
        :options: The MQTT v5.0 subscribe options.
        :properties: a Properties instance setting the MQTT v5.0 properties
            to be included. Optional - if not set, no properties are sent.

        String and integer tuple
        ------------------------
        e.g. subscribe(("my/topic", 1))

        :topic: A tuple of (topic, qos). Both topic and qos must be present in
               the tuple.
        :qos and options: Not used.
        :properties: Only used for MQTT v5.0.  A Properties instance setting the
            MQTT v5.0 properties. Optional - if not set, no properties are sent.

        String and subscribe options tuple (MQTT v5.0 only)
        ---------------------------------------------------
        e.g. subscribe(("my/topic", SubscribeOptions(qos=1)))

        :topic: A tuple of (topic, SubscribeOptions). Both topic and subscribe
                options must be present in the tuple.
        :qos and options: Not used.
        :properties: a Properties instance setting the MQTT v5.0 properties
            to be included. Optional - if not set, no properties are sent.

        List of string and integer tuples
        ---------------------------------
        e.g. subscribe([("my/topic", 0), ("another/topic", 2)])

        This allows multiple topic subscriptions in a single SUBSCRIPTION
        command, which is more efficient than using multiple calls to
        subscribe().

        :topic: A list of tuple of format (topic, qos). Both topic and qos must
               be present in all of the tuples.
        :qos, options and properties: Not used.

        List of string and subscribe option tuples (MQTT v5.0 only)
        -----------------------------------------------------------
        e.g. subscribe([("my/topic", SubscribeOptions(qos=0), ("another/topic", SubscribeOptions(qos=2)])

        This allows multiple topic subscriptions in a single SUBSCRIPTION
        command, which is more efficient than using multiple calls to
        subscribe().

        :topic: A list of tuple of format (topic, SubscribeOptions). Both topic and subscribe
                options must be present in all of the tuples.
        :qos and options: Not used.
        :properties: a Properties instance setting the MQTT v5.0 properties
            to be included. Optional - if not set, no properties are sent.

        The function returns a tuple (result, mid), where result is
        MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the
        client is not currently connected.  mid is the message ID for the
        subscribe request. The mid value can be used to track the subscribe
        request by checking against the mid argument in the on_subscribe()
        callback if it is defined.

        Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
        zero string length, or if topic is not a string, tuple or list.
        Nz=Subscribe options must be instance of SubscribeOptions class.r   rÆ   rã  )r5   z8Subscribe options and qos parameters cannot be combined.r¯   râ  zEmpty topic listú,No topic specified, or incorrect topic type.c                 3  s    | ]\}}ˆ   |¡tkV  qd S r<   )Ú_filter_wildcard_len_checkr]   )r†   r—   r‡   rC   r1   r2   r‰   ð  s     z#Client.subscribe.<locals>.<genexpr>zInvalid subscription filter.F)rp   Útupler	  r  r   r‹   r6   rZ   r°   r�   Úlistr�   Úanyr  ra   Ú_send_subscribe)	r=   r—   r5   rö  rÞ   Ztopic_qos_listÚtÚoÚqr1   rC   r2   Ú	subscribef  sf    V


ÿ
ÿ
ÿ
 (
zClient.subscribezstr | list[str])r—   rÞ   r;   c                 C  sÀ   d}|dkrt dƒ‚t|ttfƒrDt|ƒdkr6t dƒ‚| d¡g}nJt|tƒrŽg }|D ]6}t|ƒdkstt|ttfƒs|t dƒ‚| | d¡¡ qV|dkržt dƒ‚| jdkr²t	j
dfS |  d||¡S )ae  Unsubscribe the client from one or more topics.

        :param topic: A single string, or list of strings that are the subscription
            topics to unsubscribe from.
        :param properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
            to be included. Optional - if not set, no properties are sent.

        Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
        to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not
        currently connected.
        mid is the message ID for the unsubscribe request. The mid value can be
        used to track the unsubscribe request by checking against the mid
        argument in the on_unsubscribe() callback if it is defined.

        :raises ValueError: if topic is None or has zero string length, or is
            not a string or list.
        Nrâ  r   r¯   r÷  F)r‹   rp   r6   rZ   r�   r°   rú  r�   r  r   ra   Ú_send_unsubscribe)r=   r—   rÞ   Z
topic_listrý  r1   r1   r2   Úunsubscribeø  s$    


zClient.unsubscribe)Úmax_packetsr;   c                 C  sŒ   | j dkrtjS t| jƒt| jƒ }|dk r0d}td|ƒD ]J}| j dkrRtj  S |  ¡ }|dkrp|  |¡  S |tj	kr:tj
  S q:tj
S )a6  Process read network events. Use in place of calling `loop()` if you
        wish to handle your client reads as part of your own application.

        Use `socket()` to obtain the client socket to call select() or equivalent
        on.

        Do not use if you are using `loop_start()` or `loop_forever()`.Nr   r   )r  r   ra   r�   r/  r0  r�   Ú_packet_readÚ_loop_rc_handlerÓ   r]   )r=   r  r‡   r   r1   r1   r2   rÝ  "  s    



zClient.loop_readc                 C  sr   | j dkrtjS z@|  ¡ }|tjkr.tjW ¢&S |dkrD|  	|¡W ¢S tjW ¢S W 5 |  ¡ rd|  ¡  n|  ¡  X dS )a‰  Process write network events. Use in place of calling `loop()` if you
        wish to handle your client writes as part of your own application.

        Use `socket()` to obtain the client socket to call select() or equivalent
        on.

        Use `want_write()` to determine if there is data waiting to be written.

        Do not use if you are using `loop_start()` or `loop_forever()`.Nr   )
r  r   ra   rØ  rx  r€  Ú_packet_writerÓ   r]   r  ©r=   r   r1   r1   r2   rß  ;  s    




zClient.loop_writec                 C  s   t | jƒdkS )z¾Call to determine if there is network data waiting to be written.
        Useful if you are calling select() yourself rather than using `loop()`, `loop_start()` or `loop_forever()`.
        r   )r�   r#  rC   r1   r1   r2   rØ  V  s    zClient.want_writec                 C  sŠ   | j dkrtjS tƒ }|  ¡  | jdkr„|| j | jkr„|  ¡  | jt	j
t	jfkrbt	j| _tj}nt	j| _tj}| jd|d� tjS tjS )zÆProcess miscellaneous network events. Use in place of calling `loop()` if you
        wish to call select() or equivalent on.

        Do not use if you are using `loop_start()` or `loop_forever()`.Nr   F©Úpacket_from_brokerÚv1_rc)r  r   ra   rÐ   Ú_check_keepaliver*  r  r„  r-  r   rÚ  rÛ  r]   rÜ  rm   Ú_do_on_disconnectrd   )r=   Únowr   r1   r1   r2   rà  \  s"    
þzClient.loop_misc)Úinflightr;   c                 C  s
   || _ dS )z~Set the maximum number of messages with QoS>0 that can be part way
        through their network flow at once. Defaults to 20.N)rl  )r=   r  r1   r1   r2   Úmax_inflight_messages_set|  s    z Client.max_inflight_messages_set)Ú
queue_sizer;   c                 C  s   t |tƒstdƒ‚|| _| S )z\Set the maximum number of messages in the outgoing message queue.
        0 means unlimited.zInvalid type of queue size.)rp   r"   r‹   rm  )r=   r  r1   r1   r2   Úmax_queued_messages_set�  s    
zClient.max_queued_messages_set)rñ   r;   c                 C  s
   || _ dS )zESet the user data variable passed to callbacks. May be any data type.N©r
  )r=   rñ   r1   r1   r2   Úuser_data_set‰  s    zClient.user_data_setc                 C  s   | j S )zEGet the user data variable passed to callbacks. May be any data type.r  rC   r1   r1   r2   Úuser_data_get�  s    zClient.user_data_getc                 C  s|   |dkst |ƒdkrtdƒ‚|dk s,|dkr4tdƒ‚|rJt|tƒsJtdƒ‚t|ƒ| _d| _| d¡| _|| _	|| _
|| _dS )	aõ  Set a Will to be sent by the broker in case the client disconnects unexpectedly.

        This must be called before connect() to have any effect.

        :param str topic: The topic that the will message should be published on.
        :param payload: The message to send as a will. If not given, or set to None a
            zero length message will be used as the will. Passing an int or float
            will result in the payload being converted to a string representing
            that number. If you wish to send a true int/float, use struct.pack() to
            create the payload you require.
        :param int qos: The quality of service level to use for the will.
        :param bool retain: If set to true, the will message will be set as the "last known
            good"/retained message for the topic.
        :param Properties properties: (MQTT v5.0 only) the MQTT v5.0 properties
            to be included with the will message. Optional - if not set, no properties are sent.

        :raises ValueError: if qos is not 0, 1 or 2, or if topic is None or has
            zero string length.

        See `will_clear` to clear will. Note that will are NOT send if the client disconnect cleanly
        for example by calling `disconnect()`.
        Nr   râ  rÆ   rã  zDThe properties argument must be an instance of the Properties class.Tr¯   )r�   r‹   rp   r   r¸   r8  r6  r°   r7  r9  r:  r5  )r=   r—   r³   r5   rÝ   rÞ   r1   r1   r2   Úwill_set‘  s    ÿ
zClient.will_setc                 C  s"   d| _ d| _d| _d| _d| _dS )z~ Removes a will that was previously configured with `will_set()`.

        Must be called before connect() to have any effect.Frµ   r   N)r6  r7  r8  r9  r:  rC   r1   r1   r2   Ú
will_clearÀ  s
    zClient.will_clearzSocketLike | Nonec                 C  s   | j S )z0Return the socket or ssl object for this client.)r  rC   r1   r1   r2   rž   Ê  s    zClient.socket)rÍ   Úretry_first_connectionr;   c                   s4  d‰ ˆ rjˆj dkrqjˆjtjkrjzˆ ¡  W qh tk
rb   ˆ ¡  |sJ‚ ˆ td¡ ˆ 	¡  Y qhX qqjqˆ �r0t
j}|t
jkr¼ˆ |¡}ˆj dkrvtˆjƒdkrvtˆjƒdkrvt
j}d‰ qvddœ‡ ‡fdd„}|ƒ sÜˆjsâd‰ qjˆ 	¡  |ƒ röd‰ qjzˆ ¡  W qj tk
�r,   ˆ ¡  ˆ td¡ Y qjX qj|S )	a  This function calls the network loop functions for you in an
        infinite blocking loop. It is useful for the case where you only want
        to run the MQTT client loop in your program.

        loop_forever() will handle reconnecting for you if reconnect_on_failure is
        true (this is the default behavior). If you call `disconnect()` in a callback
        it will return.

        :param int timeout: The time in seconds to wait for incoming/outgoing network
          traffic before timing out and returning.
        :param bool retry_first_connection: Should the first connection attempt be retried on failure.
          This is independent of the reconnect_on_failure setting.

        :raises OSError: if the first connection fail unless retry_first_connection=True
        TzConnection failed, retryingr   FrF   rB   c                     s$   ˆj tjtjfkp"ˆ dkp"ˆjdkS )NFT)r-  r   rÚ  rÛ  rK  r1   ©Úrunr=   r1   r2   Úshould_exit	  s
    ÿýz(Client.loop_forever.<locals>.should_exit)rK  r-  r   rÇ  rµ  ÚOSErrorÚ_handle_on_connect_failrz  r{  Ú_reconnect_waitr   r]   rÕ  r�   r#  r/  r^   r)  )r=   rÍ   r  r   r  r1   r  r2   Úloop_foreverÎ  sV    
 ÿ


ÿþ ÿzClient.loop_foreverc                 C  sZ   | j dk	rtjS tƒ \| _| _d| _tj| j	d| j
 ¡ › �d�| _ d| j _| j  ¡  tjS )a`  This is part of the threaded client interface. Call this once to
        start a new thread to process network traffic. This provides an
        alternative to repeatedly calling `loop()` yourself.

        Under the hood, this will call `loop_forever` in a thread, which means that
        the thread will terminate if you call `disconnect()`
        NFzpaho-mqtt-client-)rÀ  ÚnameT)rJ  r   r`   r­   r  r  rK  r¾   ÚThreadÚ_thread_mainr  rç   ÚdaemonÚstartr]   rC   r1   r1   r2   Ú
loop_start	  s    

zClient.loop_startc                 C  s4   | j dkrtjS d| _t ¡ | j kr.| j  ¡  tjS )aZ  This is part of the threaded client interface. Call this once to
        stop the network thread previously created with `loop_start()`. This call
        will block until the network thread finishes.

        This don't guarantee that publish packet are sent, use `wait_for_publish` or
        `on_publish` to ensure `publish` are sent.
        NT)rJ  r   r`   rK  r¾   Úcurrent_threadr‘   r]   rC   r1   r1   r2   Ú	loop_stop/	  s    

zClient.loop_stopc                 C  s   | j S )zÊ
        Return the callback API version used for user-callback. See docstring for
        each user-callback (`on_connect`, `on_publish`, ...) for details.

        This property is read-only.
        )r  rC   r1   r1   r2   rî   @	  s    zClient.callback_api_versionzCallbackOnLog | Nonec                 C  s   | j S )a×  The callback called when the client has log information.
        Defined to allow debugging.

        Expected signature is::

            log_callback(client, userdata, level, buf)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param int level: gives the severity of the message and will be one of
                    MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING,
                    MQTT_LOG_ERR, and MQTT_LOG_DEBUG.
        :param str buf: the message itself

        Decorator: @client.log_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        ©rQ  rC   r1   r1   r2   Úon_logJ	  s    zClient.on_log©Úfuncr;   c                 C  s
   || _ d S r<   r'  ©r=   r*  r1   r1   r2   r(  _	  s    z(Callable[[CallbackOnLog], CallbackOnLog]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnLogr)  c                   s
   | ˆ _ | S r<   )r(  ©r*  rC   r1   r2   Ú	decoratord	  s    z&Client.log_callback.<locals>.decoratorr1   ©r=   r.  r1   rC   r2   Úlog_callbackc	  s    zClient.log_callbackzCallbackOnPreConnect | Nonec                 C  s   | j S )aô  The callback called immediately prior to the connection is made
        request.

        Expected signature (for all callback API version)::

            connect_callback(client, userdata)

        :parama Client client: the client instance for this callback
        :parama userdata: the private user data as set in Client() or user_data_set()

        Decorator: @client.pre_connect_callback() (``client`` is the name of the
            instance which this callback is being attached to)

        )rR  rC   r1   r1   r2   rÏ  i	  s    zClient.on_pre_connectc              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rR  r+  r1   r1   r2   rÏ  {	  s    z6Callable[[CallbackOnPreConnect], CallbackOnPreConnect]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnPreConnectr)  c                   s
   | ˆ _ | S r<   )rÏ  r-  rC   r1   r2   r.  ƒ	  s    z.Client.pre_connect_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úpre_connect_callback€	  s    zClient.pre_connect_callbackzCallbackOnConnect | Nonec                 C  s   | j S )a
  The callback called when the broker reponds to our connection request.

        Expected signature for callback API version 2::

            connect_callback(client, userdata, connect_flags, reason_code, properties)

        Expected signature for callback API version 1 change with MQTT protocol version:
            * For MQTT v3.1 and v3.1.1 it's::

                connect_callback(client, userdata, flags, rc)

            * For MQTT v5.0 it's::

                connect_callback(client, userdata, flags, reason_code, properties)


        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param ConnectFlags connect_flags: the flags for this connection
        :param ReasonCode reason_code: the connection reason code received from the broken.
                       In MQTT v5.0 it's the reason code defined by the standard.
                       In MQTT v3, we convert return code to a reason code, see
                       `convert_connack_rc_to_reason_code()`.
                       `ReasonCode` may be compared to integer.
        :param Properties properties: the MQTT v5.0 properties received from the broker.
                       For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
                       object is always used.
        :param dict flags: response flags sent by the broker
        :param int rc: the connection result, should have a value of `ConnackCode`

        flags is a dict that contains response flags from the broker:
            flags['session present'] - this flag is useful for clients that are
                using clean session set to 0 only. If a client with clean
                session=0, that reconnects to a broker that it has previously
                connected to, this flag indicates whether the broker still has the
                session information for the client. If 1, the session still exists.

        The value of rc indicates success or not:
            - 0: Connection successful
            - 1: Connection refused - incorrect protocol version
            - 2: Connection refused - invalid client identifier
            - 3: Connection refused - server unavailable
            - 4: Connection refused - bad username or password
            - 5: Connection refused - not authorised
            - 6-255: Currently unused.

        Decorator: @client.connect_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )rS  rC   r1   r1   r2   Ú
on_connectˆ	  s    3zClient.on_connectc              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rS  r+  r1   r1   r2   r3  ½	  s    z0Callable[[CallbackOnConnect], CallbackOnConnect]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnConnectr)  c                   s
   | ˆ _ | S r<   )r3  r-  rC   r1   r2   r.  Å	  s    z*Client.connect_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úconnect_callbackÂ	  s    zClient.connect_callbackzCallbackOnConnectFail | Nonec                 C  s   | j S )a÷  The callback called when the client failed to connect
        to the broker.

        Expected signature is (for all callback_api_version)::

            connect_fail_callback(client, userdata)

        :param Client client: the client instance for this callback
        :parama userdata: the private user data as set in Client() or user_data_set()

        Decorator: @client.connect_fail_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )rT  rC   r1   r1   r2   Úon_connect_failÊ	  s    zClient.on_connect_failc              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rT  r+  r1   r1   r2   r6  Û	  s    z8Callable[[CallbackOnConnectFail], CallbackOnConnectFail]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnConnectFailr)  c                   s
   | ˆ _ | S r<   )r6  r-  rC   r1   r2   r.  ã	  s    z/Client.connect_fail_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úconnect_fail_callbackà	  s    zClient.connect_fail_callbackzCallbackOnSubscribe | Nonec                 C  s   | j S )aÉ  The callback called when the broker responds to a subscribe
        request.

        Expected signature for callback API version 2::

            subscribe_callback(client, userdata, mid, reason_code_list, properties)

        Expected signature for callback API version 1 change with MQTT protocol version:
            * For MQTT v3.1 and v3.1.1 it's::

                subscribe_callback(client, userdata, mid, granted_qos)

            * For MQTT v5.0 it's::

                subscribe_callback(client, userdata, mid, reason_code_list, properties)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param int mid: matches the mid variable returned from the corresponding
                          subscribe() call.
        :param list[ReasonCode] reason_code_list: reason codes received from the broker for each subscription.
                          In MQTT v5.0 it's the reason code defined by the standard.
                          In MQTT v3, we convert granted QoS to a reason code.
                          It's a list of ReasonCode instances.
        :param Properties properties: the MQTT v5.0 properties received from the broker.
                          For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
                          object is always used.
        :param list[int] granted_qos: list of integers that give the QoS level the broker has
                          granted for each of the different subscription requests.

        Decorator: @client.subscribe_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )rU  rC   r1   r1   r2   Úon_subscribeè	  s    #zClient.on_subscribec              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rU  r+  r1   r1   r2   r9  
  s    z4Callable[[CallbackOnSubscribe], CallbackOnSubscribe]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnSubscriber)  c                   s
   | ˆ _ | S r<   )r9  r-  rC   r1   r2   r.  
  s    z,Client.subscribe_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úsubscribe_callback
  s    zClient.subscribe_callbackzCallbackOnMessage | Nonec                 C  s   | j S )a  The callback called when a message has been received on a topic
        that the client subscribes to.

        This callback will be called for every message received unless a
        `message_callback_add()` matched the message.

        Expected signature is (for all callback API version):
            message_callback(client, userdata, message)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param MQTTMessage message: the received message.
                    This is a class with members topic, payload, qos, retain.

        Decorator: @client.message_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )rV  rC   r1   r1   r2   Ú
on_message
  s    zClient.on_messagec              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rV  r+  r1   r1   r2   r<  /
  s    z0Callable[[CallbackOnMessage], CallbackOnMessage]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnMessager)  c                   s
   | ˆ _ | S r<   )r<  r-  rC   r1   r2   r.  7
  s    z*Client.message_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úmessage_callback4
  s    zClient.message_callbackzCallbackOnPublish | Nonec                 C  s   | j S )a*  The callback called when a message that was to be sent using the
        `publish()` call has completed transmission to the broker.

        For messages with QoS levels 1 and 2, this means that the appropriate
        handshakes have completed. For QoS 0, this simply means that the message
        has left the client.
        This callback is important because even if the `publish()` call returns
        success, it does not always mean that the message has been sent.

        See also `wait_for_publish` which could be simpler to use.

        Expected signature for callback API version 2::

            publish_callback(client, userdata, mid, reason_code, properties)

        Expected signature for callback API version 1::

            publish_callback(client, userdata, mid)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param int mid: matches the mid variable returned from the corresponding
                     `publish()` call, to allow outgoing messages to be tracked.
        :param ReasonCode reason_code: the connection reason code received from the broken.
                     In MQTT v5.0 it's the reason code defined by the standard.
                     In MQTT v3 it's always the reason code Success
        :parama Properties properties: the MQTT v5.0 properties received from the broker.
                     For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
                     object is always used.

        Note: for QoS = 0, the reason_code and the properties don't really exist, it's the client
        library that generate them. It's always an empty properties and a success reason code.
        Because the (MQTTv5) standard don't have reason code for PUBLISH packet, the library create them
        at PUBACK packet, as if the message was sent with QoS = 1.

        Decorator: @client.publish_callback() (``client`` is the name of the
            instance which this callback is being attached to)

        )rW  rC   r1   r1   r2   Ú
on_publish<
  s    )zClient.on_publishc              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rW  r+  r1   r1   r2   r?  g
  s    z0Callable[[CallbackOnPublish], CallbackOnPublish]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnPublishr)  c                   s
   | ˆ _ | S r<   )r?  r-  rC   r1   r2   r.  o
  s    z*Client.publish_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úpublish_callbackl
  s    zClient.publish_callbackzCallbackOnUnsubscribe | Nonec                 C  s   | j S )a  The callback called when the broker responds to an unsubscribe
        request.

        Expected signature for callback API version 2::

            unsubscribe_callback(client, userdata, mid, reason_code_list, properties)

        Expected signature for callback API version 1 change with MQTT protocol version:
            * For MQTT v3.1 and v3.1.1 it's::

                unsubscribe_callback(client, userdata, mid)

            * For MQTT v5.0 it's::

                unsubscribe_callback(client, userdata, mid, properties, v1_reason_codes)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param mid: matches the mid variable returned from the corresponding
                          unsubscribe() call.
        :param list[ReasonCode] reason_code_list: reason codes received from the broker for each unsubscription.
                          In MQTT v5.0 it's the reason code defined by the standard.
                          In MQTT v3, there is not equivalent from broken and empty list
                          is always used.
        :param Properties properties: the MQTT v5.0 properties received from the broker.
                          For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
                          object is always used.
        :param v1_reason_codes: the MQTT v5.0 reason codes received from the broker for each
                          unsubscribe topic.  A list of ReasonCode instances OR a single
                          ReasonCode when we unsubscribe from a single topic.

        Decorator: @client.unsubscribe_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )rX  rC   r1   r1   r2   Úon_unsubscribet
  s    $zClient.on_unsubscribec              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rX  r+  r1   r1   r2   rB  š
  s    z8Callable[[CallbackOnUnsubscribe], CallbackOnUnsubscribe]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnUnsubscriber)  c                   s
   | ˆ _ | S r<   )rB  r-  rC   r1   r2   r.  ¢
  s    z.Client.unsubscribe_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úunsubscribe_callbackŸ
  s    zClient.unsubscribe_callbackzCallbackOnDisconnect | Nonec                 C  s   | j S )aÖ  The callback called when the client disconnects from the broker.

        Expected signature for callback API version 2::

            disconnect_callback(client, userdata, disconnect_flags, reason_code, properties)

        Expected signature for callback API version 1 change with MQTT protocol version:
            * For MQTT v3.1 and v3.1.1 it's::

                disconnect_callback(client, userdata, rc)

            * For MQTT v5.0 it's::

                disconnect_callback(client, userdata, reason_code, properties)

        :param Client client: the client instance for this callback
        :param userdata:  the private user data as set in Client() or user_data_set()
        :param DisconnectFlag disconnect_flags: the flags for this disconnection.
        :param ReasonCode reason_code:  the disconnection reason code possibly received from the broker (see disconnect_flags).
                          In MQTT v5.0 it's the reason code defined by the standard.
                          In MQTT v3 it's never received from the broker, we convert an MQTTErrorCode,
                          see `convert_disconnect_error_code_to_reason_code()`.
                          `ReasonCode` may be compared to integer.
        :param Properties properties: the MQTT v5.0 properties received from the broker.
                          For MQTT v3.1 and v3.1.1 properties is not provided and an empty Properties
                          object is always used.
        :param int rc: the disconnection result
                          The rc parameter indicates the disconnection state. If
                          MQTT_ERR_SUCCESS (0), the callback was called in response to
                          a disconnect() call. If any other value the disconnection
                          was unexpected, such as might be caused by a network error.

        Decorator: @client.disconnect_callback() (``client`` is the name of the
            instance which this callback is being attached to)

        )rY  rC   r1   r1   r2   Úon_disconnect§
  s    &zClient.on_disconnectc              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rY  r+  r1   r1   r2   rE  Ï
  s    z6Callable[[CallbackOnDisconnect], CallbackOnDisconnect]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnDisconnectr)  c                   s
   | ˆ _ | S r<   )rE  r-  rC   r1   r2   r.  ×
  s    z-Client.disconnect_callback.<locals>.decoratorr1   r/  r1   rC   r2   Údisconnect_callbackÔ
  s    zClient.disconnect_callbackzCallbackOnSocket | Nonec                 C  s   | j S )a‡  The callback called just after the socket was opend.

        This should be used to register the socket to an external event loop for reading.

        Expected signature is (for all callback API version)::

            socket_open_callback(client, userdata, socket)

        :param Client client:     the client instance for this callback
        :param userdata:   the private user data as set in Client() or user_data_set()
        :param SocketLike sock: the socket which was just opened.

        Decorator: @client.socket_open_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )rZ  rC   r1   r1   r2   Úon_socket_openÜ
  s    zClient.on_socket_openc              	   C  s   | j � || _W 5 Q R X d S r<   )rD  rZ  r+  r1   r1   r2   rH  ï
  s    z.Callable[[CallbackOnSocket], CallbackOnSocket]c                   s   dddœ‡ fdd„}|S )NÚCallbackOnSocketr)  c                   s
   | ˆ _ | S r<   )rH  r-  rC   r1   r2   r.  ÷
  s    z.Client.socket_open_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úsocket_open_callbackô
  s    zClient.socket_open_callbackr9   )rƒ  r;   c                 C  s~   | j � | j}W 5 Q R X |rz| j�R z|| | j|ƒ W n8 tk
rn } z|  td|¡ | js^‚ W 5 d}~X Y nX W 5 Q R X dS )z9Call the socket_open callback with the just-opened socketz&Caught exception in on_socket_open: %sN)rD  rH  rB  r
  rÃ  rz  rÐ  ra  )r=   rƒ  rH  r|  r1   r1   r2   rÒ  ü
  s      ÿzClient._call_socket_openc                 C  s   | j S )aŽ  The callback called just before the socket is closed.

        This should be used to unregister the socket from an external event loop for reading.

        Expected signature is (for all callback API version)::

            socket_close_callback(client, userdata, socket)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param SocketLike sock: the socket which is about to be closed.

        Decorator: @client.socket_close_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        )r[  rC   r1   r1   r2   Úon_socket_close  s    zClient.on_socket_closec              	   C  s   | j � || _W 5 Q R X d S r<   )rD  r[  r+  r1   r1   r2   rK    s    c                   s   dddœ‡ fdd„}|S )NrI  r)  c                   s
   | ˆ _ | S r<   )rK  r-  rC   r1   r2   r.  &  s    z/Client.socket_close_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úsocket_close_callback#  s    zClient.socket_close_callbackc                 C  s~   | j � | j}W 5 Q R X |rz| j�R z|| | j|ƒ W n8 tk
rn } z|  td|¡ | js^‚ W 5 d}~X Y nX W 5 Q R X dS )zACall the socket_close callback with the about-to-be-closed socketz'Caught exception in on_socket_close: %sN)rD  rK  rB  r
  rÃ  rz  rÐ  ra  )r=   rƒ  rK  r|  r1   r1   r2   r�  +  s      ÿzClient._call_socket_closec                 C  s   | j S )a¯  The callback called when the socket needs writing but can't.

        This should be used to register the socket with an external event loop for writing.

        Expected signature is (for all callback API version)::

            socket_register_write_callback(client, userdata, socket)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param SocketLike sock: the socket which should be registered for writing

        Decorator: @client.socket_register_write_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        ©r\  rC   r1   r1   r2   Úon_socket_register_write:  s    zClient.on_socket_register_writec              	   C  s   | j � || _W 5 Q R X d S r<   )rD  r\  r+  r1   r1   r2   rN  M  s    c                   s   dddœ‡ fdd„}|S )NrI  r)  c                   s
   | ˆ _ | S r<   rM  r-  rC   r1   r2   r.  U  s    z8Client.socket_register_write_callback.<locals>.decoratorr1   r/  r1   rC   r2   Úsocket_register_write_callbackR  s    z%Client.socket_register_write_callbackc              
   C  s„   | j r| jrdS d| _| j� | j}W 5 Q R X |r€z|| | j| j ƒ W n8 tk
r~ } z|  td|¡ | jsn‚ W 5 d}~X Y nX dS )zBCall the socket_register_write callback with the unwritable socketNTz0Caught exception in on_socket_register_write: %s)	r  rP  rD  rN  r
  rÃ  rz  rÐ  ra  )r=   rN  r|  r1   r1   r2   rx  Z  s(      ÿ  ÿz"Client._call_socket_register_writec                 C  s   | j S )a¼  The callback called when the socket doesn't need writing anymore.

        This should be used to unregister the socket from an external event loop for writing.

        Expected signature is (for all callback API version)::

            socket_unregister_write_callback(client, userdata, socket)

        :param Client client: the client instance for this callback
        :param userdata: the private user data as set in Client() or user_data_set()
        :param SocketLike sock: the socket which should be unregistered for writing

        Decorator: @client.socket_unregister_write_callback() (``client`` is the name of the
            instance which this callback is being attached to)
        ©r]  rC   r1   r1   r2   Úon_socket_unregister_writel  s    z!Client.on_socket_unregister_writec              	   C  s   | j � || _W 5 Q R X d S r<   )rD  r]  r+  r1   r1   r2   rQ  �  s    c                   s   dddœ‡ fdd„}|S )NrI  r)  c                   s
   | ˆ _ | S r<   rP  r-  rC   r1   r2   r.  ‹  s    z:Client.socket_unregister_write_callback.<locals>.decoratorr1   r/  r1   rC   r2   Ú socket_unregister_write_callbackˆ  s    z'Client.socket_unregister_write_callbackc              
   C  sŠ   |p| j }|r| jsdS d| _| j� | j}W 5 Q R X |r†z|| | j|ƒ W n8 tk
r„ } z|  td|¡ | jst‚ W 5 d}~X Y nX dS )zBCall the socket_unregister_write callback with the writable socketNFz2Caught exception in on_socket_unregister_write: %s)	r  rP  rD  rQ  r
  rÃ  rz  rÐ  ra  )r=   rƒ  rQ  r|  r1   r1   r2   r€  ’  s"    

  ÿz$Client._call_socket_unregister_writer=  )r–   Úcallbackr;   c              	   C  s8   |dks|dkrt dƒ‚| j� || j|< W 5 Q R X dS )a  Register a message callback for a specific topic.
        Messages that match 'sub' will be passed to 'callback'. Any
        non-matching messages will be passed to the default `on_message`
        callback.

        Call multiple times with different 'sub' to define multiple topic
        specific callbacks.

        Topic specific callbacks may be removed with
        `message_callback_remove()`.

        See `on_message` for the expected signature of the callback.

        Decorator: @client.topic_callback(sub) (``client`` is the name of the
            instance which this callback is being attached to)

        Example::

            @client.topic_callback("mytopic/#")
            def handle_mytopic(client, userdata, message):
                ...
        Nz&sub and callback must both be defined.)r‹   rD  r;  )r=   r–   rS  r1   r1   r2   Úmessage_callback_add§  s    zClient.message_callback_add)r–   r;   c                   s   dddœ‡ ‡fdd„}|S )Nr=  r)  c                   s   ˆ   ˆ| ¡ | S r<   )rT  r-  ©r=   r–   r1   r2   r.  Ç  s    z(Client.topic_callback.<locals>.decoratorr1   )r=   r–   r.  r1   rU  r2   Útopic_callbackÄ  s    zClient.topic_callbackc              	   C  sH   |dkrt dƒ‚| j�( z| j|= W n tk
r8   Y nX W 5 Q R X dS )zVRemove a message callback previously registered with
        `message_callback_add()`.Nzsub must defined.)r‹   rD  r;  ÚKeyErrorrU  r1   r1   r2   Úmessage_callback_removeÌ  s    zClient.message_callback_remover~   c                 C  sN   |r:|   ¡  | jtjtjfkr,tj| _tj}| jd|d� |tkrJtj	| _|S )NFr  )
r„  r-  r   rÚ  rÛ  r   r]   r  rd   rÜ  r  r1   r1   r2   r  Ü  s    zClient._loop_rc_handlec              
   C  s"  | j d dkrÈz|  d¡}W nŠ tk
r6   tj Y S  tk
rn } z|  td|¡ tj W Y ¢S d }~X Y nZ t	k
r¦ } z|  td|¡ tj W Y ¢S d }~X Y n"X t
|ƒdkrºtjS |d | j d< | j d dk�räz|  d¡}W nV tk
�r   tj Y S  t	k
�r< } z|  td|¡ tj W Y ¢S d }~X Y n|X t
|ƒdk�rRtjS |d }| j d  |¡ t
| j d ƒdk�r„tjS | j d	  |d
@ | j d  7  < | j d d | j d< |d@ dkrØ�qÊqØd| j d< | j d	 | j d< d}| j d dk�rÖz|  | j d ¡}W nV tk
�r(   tj Y S  t	k
�rb } z|  td|¡ tj W Y ¢S d }~X Y n>X t
|ƒdk�rxtjS | j d  t
|ƒ8  < | j d  |7  < |d8 }|dk�rè| j� tƒ | _W 5 Q R X tjS �qèd| j d< |  ¡ }ddg ddtdƒdddœ| _ | j� tƒ | _W 5 Q R X |S )Nr#   r   r   ztimeout on socket: %súfailed to receive on socket: %sr$   r%   é   r'   é   r&   é€   r*   éd   r)   r+   rµ   r   )r   r}  r©   r   rÓ   ÚTimeoutErrorrz  rÐ  rd   r  r�   r�   r_   rE  rÐ   r$  Ú_packet_handler(   )r=   r#   r|  ÚbyteZ
byte_valueÚcountÚdatar   r1   r1   r2   r  î  sª    
  ÿ  ÿ
  ÿ
 ÿ

  ÿ


øzClient._packet_readc                 C  s¸  z| j  ¡ }W n tk
r(   tj Y S X z|  |d |d d … ¡}W n’ ttfk
rr   | j  |¡ tj Y S  t	k
r–   | j  |¡ tj
 Y S  tk
rÚ } z(| j  |¡ |  td|¡ tj W Y ¢S d }~X Y nX |dk�r˜|d  |8  < |d  |7  < |d dk�r„|d d@ tk�r"|d dk�r"| j� | j}W 5 Q R X |�r| j�¸ zt| jtjk�rˆtt|ƒ}|| | j|d	 ƒ nD| jtjk�rÄtt|ƒ}|| | j|d	 ttjƒttjƒƒ ntd
ƒ‚W n< t k
�r
 } z|  td|¡ | j!�sú‚ W 5 d }~X Y nX W 5 Q R X |d  "¡  |d d@ t#k�r�| j$� t%ƒ | _&W 5 Q R X | j'dtjd� |  (¡  | j)t*j+k�r|t*j,| _)tjS n| j  |¡ q �q˜q | j$� t%ƒ | _&W 5 Q R X tjS )Nr)   r+   rY  r   r*   r#   rË  r5   r4   rü   ú"Caught exception in on_publish: %sr8   Fr  )-r#  ÚpopleftrÈ   r   r]   r  ry  r‹   Ú
appendleftr©   rÓ   r  rz  rÐ  rd   rÌ  rD  r?  rB  r  r   r  r   ÚCallbackOnPublish_v1r
  ÚVERSION2ÚCallbackOnPublish_v2r   r   ÚPUBACKr   rÔ   rÃ  ra  rË   r€   rE  rÐ   r%  r  r„  r-  r   rÚ  rÛ  )r=   r)   Zwrite_lengthr|  r?  r1   r1   r2   r  X  sŒ    ÿ

  ÿ
 

û  ÿþzClient._packet_writer   )ÚlevelÚfmtÚargsr;   c                 G  sh   | j d k	r>|| }z|   | | j||¡ W n tk
r<   Y nX | jd k	rdt| }| jj||f|žŽ  d S r<   )r(  r
  rÃ  rO  ÚLOGGING_LEVELÚlog)r=   rj  rk  rl  r~  Z	level_stdr1   r1   r2   rz  ±  s    

zClient._easy_logc              	   C  s  | j dkrd S tƒ }| j� | j}| j}W 5 Q R X | jd k	�r
|| | j ks\|| | j k�r
| jtjkrÌ| j	dkrÌz|  
¡  W n, tk
rª   |  ¡  | jdtjd� Y n X | j� || _|| _W 5 Q R X n>|  ¡  | jtjtjfkrötj| _tj}ntj}| jd|d� d S )Nr   Fr  )r  rÐ   rE  r%  r$  r  r-  r   rñ  r*  Ú_send_pingreqrÃ  r„  r  r   rd   rÚ  rÛ  r]   rm   )r=   r  Zlast_msg_outZlast_msg_inr   r1   r1   r2   r  ½  s8    
*þþzClient._check_keepalivec              
   C  sB   | j �2 |  jd7  _| jdkr&d| _| jW  5 Q R £ S Q R X d S )Nr   é   )rI  r+  rC   r1   r1   r2   rå  ã  s
    
zClient._mid_generate)r—   r;   c                 C  s0   d| ksd| krt dƒ‚t| ƒdkr,t dƒ‚dS )z‚ Check if the topic is a topic without wildcard and valid length.

            Raise ValueError if the topic isn't valid.
        ó   +ó   #z'Publish topic cannot contain wildcards.éÿÿ  zPublish topic is too long.N)r‹   r�   )r—   r1   r1   r2   rä  ê  s    zClient._raise_for_invalid_topicc                 C  sH   t | ƒdks8t | ƒdks8tdd„ |  d¡D ƒƒs8d| kr>tjS tjS d S )Nr   rs  c                 s  s*   | ]"}t |ƒd krd|kp d|kV  qdS )r   rq  rr  N)r�   )r†   Úpr1   r1   r2   r‰   ø  s      z4Client._filter_wildcard_len_check.<locals>.<genexpr>ó   /s   #/)r�   rû  Úsplitr   r`   r]   )r–   r1   r1   r2   rø  õ  s    ÿþz!Client._filter_wildcard_len_checkc                 C  s,   |   td¡ |  t¡}|tjkr(tƒ | _|S )NzSending PINGREQ)rz  r{  Ú_send_simple_commandÚPINGREQr   r]   rÐ   r*  r  r1   r1   r2   ro  þ  s
    

zClient._send_pingreqc                 C  s   |   td¡ |  t¡S )NzSending PINGRESP)rz  r{  rw  ÚPINGRESPrC   r1   r1   r2   Ú_send_pingresp  s    zClient._send_pingresp)r4   r;   c                 C  s   |   td|¡ |  t|d¡S )NzSending PUBACK (Mid: %d)F)rz  r{  Ú_send_command_with_midri  rÀ   r1   r1   r2   Ú_send_puback	  s    zClient._send_pubackc                 C  s   |   td|¡ |  t|d¡S )NzSending PUBCOMP (Mid: %d)F)rz  r{  r{  ÚPUBCOMPrÀ   r1   r1   r2   Ú_send_pubcomp  s    zClient._send_pubcompr(   )r)   r'   r;   c                 C  sJ   g }|d }|d }|dkr$|dO }|  |¡ |  |¡ |dkr|S qd S )Nr\  r   )r�   )r=   r)   r'   Zremaining_bytesr`  r1   r1   r2   Ú_pack_remaining_length  s    

zClient._pack_remaining_lengthzbytes | str)r)   rb  r;   c                 C  s,   t |ƒ}| t dt|ƒ¡¡ | |¡ d S )Nú!H)r±   rŽ   ÚstructÚpackr�   )r=   r)   rb  r1   r1   r2   Ú_pack_str16"  s    zClient._pack_str16rµ   r²   r7   )	r4   r—   r³   r5   rÝ   rÛ   r8   rÞ   r;   c	                 C  sª  t |tƒstdƒ‚|r,t |ttfƒs,tdƒ‚| jd kr<tjS t|d@ d> B |d> B |B }	tƒ }
|
 |	¡ t	|ƒ}dt	|ƒ | }|dkrÄ| j
tkr¬|  td||||||¡ n|  td|||||¡ n>| j
tkrê|  td	|||||||¡	 n|  td
||||||¡ |dk�r|d7 }| j
tk�rD|d k�r0d}n| ¡ }|t	|ƒ7 }|  |
|¡ |  |
|¡ |dk�rx|
 t d|¡¡ | j
tk�rŽ|
 |¡ |
 |¡ |  t|
|||¡S )Nztopic must be bytes, not strzpayload must be bytes if setr   rL   rÆ   r   zHSending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s (NULL payload)z9Sending PUBLISH (d%d, q%d, r%d, m%d), '%s' (NULL payload)zISending PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ... (%d bytes)z:Sending PUBLISH (d%d, q%d, r%d, m%d), '%s', ... (%d bytes)ó    r€  )rp   r6   r·   r(   r  r   ra   rÌ  r�   r�   r	  r  rz  r{  r‚  r  rƒ  rŽ   r�  Ú_packet_queue)r=   r4   r—   r³   r5   rÝ   rÛ   r8   rÞ   r#   r)   Z
payloadlenr'   Zpacked_propertiesr1   r1   r2   ræ  '  sŠ    



     ý    ý
      ý     ý




zClient._send_publishc                 C  s   |   td|¡ |  t|d¡S )NzSending PUBREC (Mid: %d)F)rz  r{  r{  ÚPUBRECrÀ   r1   r1   r2   Ú_send_pubrecv  s    zClient._send_pubrecc                 C  s    |   td|¡ |  tdB |d¡S )NzSending PUBREL (Mid: %d)rÆ   F)rz  r{  r{  ÚPUBRELrÀ   r1   r1   r2   Ú_send_pubrelz  s    zClient._send_pubrel)r#   r4   rÛ   r;   c                 C  s0   |r|dO }d}t  d|||¡}|  |||d¡S )Né   rÆ   z!BBHr   ©r�  r‚  r…  )r=   r#   r4   rÛ   r'   r)   r1   r1   r2   r{  ~  s
    zClient._send_command_with_mid)r#   r;   c                 C  s"   d}t  d||¡}|  ||dd¡S )Nr   ú!BBr‹  )r=   r#   r'   r)   r1   r1   r2   rw  ‡  s    zClient._send_simple_command)rh  r;   c           
      C  s4  t | jƒ}|tkrdnd}dt|ƒ d d d d t| jƒ }d}| jtkr|| jdkrb|dO }qŠ| jtkrŠ| jrŠ|dO }n| j	rŠ|dO }| j
rÔ|dt| jƒ d t| jƒ 7 }|d| jd@ d> B | jd@ d	> B O }| jd k	�r |dt| jƒ 7 }|d
O }| jd k	�r |dO }|dt| jƒ 7 }| jtk�r„| jd k�r>d}n
| j ¡ }|t|ƒ7 }| j
�r„| jd k�rnd}n
| j ¡ }|t|ƒ7 }t}tƒ }	|	 |¡ | jtk�r¬|d
O }|  |	|¡ |	 t dt|ƒ› d�t|ƒ||||¡¡ | jtk�rö|	|7 }	|  |	| j¡ | j
�r<| jtk�r |	|7 }	|  |	| j¡ |  |	| j¡ | jd k	�rp|  |	| j¡ | jd k	�rp|  |	| j¡ || _| jtk�rÖ|  td|d
@ d? |d@ d? |d@ d	? |d@ d? |d@ d? |d@ d? || j| j¡ nN|  td|d
@ d? |d@ d? |d@ d	? |d@ d? |d@ d? |d@ d? || j¡
 |   ||	dd¡S )Ns   MQTTs   MQIsdprÆ   r   r   TrZ  rL   é   r\  é@   r„  r€  ZsBBHzQSending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%sé   é   é    é   zCSending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s)!r"   r	  ÚMQTTv311r�   r  r  r  rN   r`  r  r6  r7  r8  r9  r:  r  r  r4  r‚  r5  ÚCONNECTr(   r�   r  rï  r  rŽ   r�  rƒ  r  rz  r{  r…  )
r=   rh  Z	proto_verrò   r'   Úconnect_flagsZpacked_connect_propertiesZpacked_will_propertiesr#   r)   r1   r1   r2   rÓ  �  sÈ    
ÿÿÿÿ



ÿÿÿÿ


    þ





õ





özClient._send_connectc                 C  sà   | j tkr|  td||¡ n|  td¡ d}t}tƒ }| |¡ | j tkr–|d k	sZ|d k	r–|d krrttd? dd�}|d7 }|d k	r–| ¡ }|t	|ƒ7 }|  
||¡ | j tkrÐ|d k	rÐ|| ¡ 7 }|d k	rÐ||7 }|  ||dd¡S )Nz.Sending DISCONNECT reasonCode=%s properties=%szSending DISCONNECTr   rZ  ©Ú
identifierr   )r	  r  rz  r{  r€   r(   r�   r   r‚  r�   r  r…  )r=   ró  rÞ   r'   r#   r)   Zpacked_propsr1   r1   r2   rô  ö  s2    
þ


zClient._send_disconnectz.Sequence[tuple[bytes, SubscribeOptions | int]]ztuple[MQTTErrorCode, int])rÛ   ÚtopicsrÞ   r;   c                 C  s  d}| j tkr0|d krd}n| ¡ }|t|ƒ7 }|D ]\}}|dt|ƒ d 7 }q4t|d> B dB }tƒ }	|	 |¡ |  |	|¡ |  ¡ }
|	 	t
 d|
¡¡ | j tkrª|	|7 }	|D ]6\}}|  |	|¡ | j tkrÚ|	| ¡ 7 }	q®|	 |¡ q®|  td||
|¡ |  ||	|
d¡|
fS )NrÆ   r„  r   rL   r€  zSending SUBSCRIBE (d%d, m%d) %s)r	  r  r‚  r�   Ú	SUBSCRIBEr(   r�   r  rå  rŽ   r�  rƒ  rz  r{  r…  )r=   rÛ   r˜  rÞ   r'   Zpacked_subscribe_propertiesrý  r‡   r#   r)   rë  rÿ  r1   r1   r2   rü    s:    



ûzClient._send_subscribezlist[bytes]c           
      C  sþ   d}| j tkr0|d krd}n| ¡ }|t|ƒ7 }|D ]}|dt|ƒ 7 }q4t|d> B dB }tƒ }| |¡ |  ||¡ |  ¡ }	| 	t
 d|	¡¡ | j tkr¢||7 }|D ]}|  ||¡ q¦| j tkrØ|  td||	||¡ n|  td||	|¡ |  |||	d¡|	fS )NrÆ   r„  rL   r€  z$Sending UNSUBSCRIBE (d%d, m%d) %s %sz!Sending UNSUBSCRIBE (d%d, m%d) %sr   )r	  r  r‚  r�   ÚUNSUBSCRIBEr(   r�   r  rå  rŽ   r�  rƒ  rz  r{  r…  )
r=   rÛ   r˜  rÞ   r'   Zpacked_unsubscribe_propertiesrý  r#   r)   rë  r1   r1   r2   r  F  sF    



ú	ûzClient._send_unsubscribec                 C  s,   | j tkr"| jtkr| jS | jS n| jS d S r<   )r	  r  r  rN   r`  r  rC   r1   r1   r2   Ú_check_clean_sessionw  s
    

zClient._check_clean_sessionc              	   C  sÖ   | j �Æ d| _| j ¡ D ]®}d|_| jdks8| j| jk rÀ|jdkrJt|_qÆ|jdkrl|jt	krdd|_
t|_qÆ|jdkrÆ|  ¡ r–|jtkrŽd|_
t|_qÆ|jtkr¨t|_qÆ|jtkr¸d|_
t|_qt|_qW 5 Q R X d S )Nr   r   TrÆ   )rF  r2  r/  ÚvaluesrÙ   r1  r5   ré  rÚ   rç  rÛ   r›  Úmqtt_ms_wait_for_pubcompÚmqtt_ms_resend_pubrelrè  rê  ©r=   Úmr1   r1   r2   Ú_messages_reconnect_reset_out€  s,    






z$Client._messages_reconnect_reset_outc              	   C  sf   | j �V |  ¡ r(t ¡ | _W 5 Q R £ d S | j ¡ D ]$}d|_|jdkr2| j |j	¡ q2q2W 5 Q R X d S )Nr   rÆ   )
rG  r›  r!  r.  r0  rœ  rÙ   r5   Úpopr4   rŸ  r1   r1   r2   Ú_messages_reconnect_reset_in�  s    

z#Client._messages_reconnect_reset_inc                 C  s   |   ¡  |  ¡  d S r<   )r¡  r£  rC   r1   r1   r2   rÎ  ª  s    z Client._messages_reconnect_reset)r#   r)   r4   r5   r8   r;   c                 C  s”   |||dt |ƒ||dœ}| j |¡ | jd k	rTz| j t¡ W n tk
rR   Y nX | jd kr†| jd kr†| j	 
d¡r†| j	 ¡  |  ¡ S |  ¡  tjS )Nr   )r#   r4   r5   r+   r*   r)   r8   F)r�   r#  r�   r  r@   Úsockpair_datar©   rJ  r\  rB  ÚacquireÚreleaserß  rx  r   r]   )r=   r#   r)   r4   r5   r8   Zmpktr1   r1   r2   r…  ®  s(    	ù


zClient._packet_queuec                 C  sð   | j d d@ }|tkr|  ¡ S |tkr.|  ¡ S |tkr@|  d¡S |tkrR|  d¡S |tkrb|  	¡ S |t
krr|  ¡ S |tkr‚|  ¡ S |tkr’|  ¡ S |tkr¨|  ¡  tjS |tkr¸|  ¡ S |tkrØ| jtkrØ|  ¡  tjS |  td|¡ tjS d S )Nr#   rË  ri  r}  zError: Unrecognised command %s)r   rx  Ú_handle_pingreqry  Ú_handle_pingrespri  Ú_handle_pubackcompr}  rÌ  Ú_handle_publishr†  Ú_handle_pubrecrˆ  Ú_handle_pubrelr|   Ú_handle_connackÚSUBACKÚ_handle_subackr   r]   ÚUNSUBACKÚ_handle_unsubackr€   r	  r  Ú_handle_disconnectrz  rÐ  r_   )r=   Úcmdr1   r1   r2   r_  Õ  s6    

zClient._packet_handlec                 C  s(   | j d dkrtjS |  td¡ |  ¡ S )Nr'   r   zReceived PINGREQ)r   r   r_   rz  r{  rz  rC   r1   r1   r2   r§  ô  s    zClient._handle_pingreqc                 C  s,   | j d dkrtjS d| _|  td¡ tjS )Nr'   r   zReceived PINGRESP)r   r   r_   r*  rz  r{  r]   rC   r1   r1   r2   r¨  û  s
    zClient._handle_pingrespc                 C  s^  | j tkr | jd dk r4tjS n| jd dkr4tjS | j tkr°t d| jd d d… ¡\}}|dkrzttd? dd�}d }qÒttd? |d	�}t	td? ƒ}| | jd dd … ¡ n"t d| jd ¡\}}t
|ƒ}d }| j tk�rd|tk�r| jsòtS |  td
||¡ t| _ |  ¡ S |tk�rd| jdk�rd| j�s2tS |  td||¡ tt ¡ jdd� d¡| _|  ¡ S |dk�r|tj| _d | _| j tk�rœ|  td|||¡ n|  td||¡ d| _| j� | j}W 5 Q R X |�râi }|d@ |d< | j �ö z²| j!t"j#k�r>| j tk�r"t$t%|ƒ}|| | j&|||ƒ nt$t'|ƒ}|| | j&||ƒ nZ| j!t"j(k�r�t$t)|ƒ}t*|d dkd�}|d k�r|t	t+jƒ}|| | j&|||ƒ nt,dƒ‚W n< t-k
�rÖ } z|  t.d|¡ | j/�sÆ‚ W 5 d }~X Y nX W 5 Q R X |dk�r:tj0}	| j1��6 | j2 3¡ D �]"}
t4ƒ |
_5|
j6t7k�r<|  8¡  t0  W  5 Q R £ S |
j9dk�rª| j �2 | j:|
j;|
j< d¡|
j=|
j9|
j>|
j?|
j@d�}	W 5 Q R X |	tj0k�r |	  W  5 Q R £ S �nv|
j9dk�r6|
j6tAk�r |  jBd7  _BtC|
_6| j �2 | j:|
j;|
j< d¡|
j=|
j9|
j>|
j?|
j@d�}	W 5 Q R X |	tj0k�r |	  W  5 Q R £ S nê|
j9dk�r |
j6tAk�rÂ|  jBd7  _BtD|
_6| j �2 | j:|
j;|
j< d¡|
j=|
j9|
j>|
j?|
j@d�}	W 5 Q R X |	tj0k�r |	  W  5 Q R £ S n^|
j6tEk�r |  jBd7  _BtF|
_6| j � |  G|
j;¡}	W 5 Q R X |	tj0k�r |	  W  5 Q R £ S |  8¡  �qW 5 Q R X |	S |dk�rT|dk �rTtjHS tjS d S )Nr'   rÆ   rŒ  r)   r   rZ  rz   )ZaNamer–  z=Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.rµ   z:Received CONNACK (%s, %s), attempting to use non-empty CIDrý   rþ   rÿ   r   z'Received CONNACK (%s, %s) properties=%szReceived CONNACK (%s, %s)Fzsession present)rQ   rü   z"Caught exception in on_connect: %sr¯   ©rÞ   r�  )Ir	  r  r   r   r_   r�  Úunpackr   r|   r   r}   r“  rr   r)  rz  r{  r  rµ  rs   r  r•   r  r  r"   r°   r   rñ  r-  r(  r`  rD  r3  rB  r  r   r  r   ÚCallbackOnConnect_v1_mqtt5r
  ÚCallbackOnConnect_v1_mqtt3rg  ÚCallbackOnConnect_v2rP   r   rÔ   rÃ  rÐ  ra  r]   rF  r/  rœ  rÐ   rÙ   rÚ   rê  rß  r5   ræ  r4   r—   r³   rÝ   rÛ   rÞ   ré  r2  rç  rè  rž  r�  r‰  rb   )r=   ÚflagsÚresultÚreasonrÞ   r3  Z
flags_dictr•  r|  r   r   r1   r1   r2   r­    sX   

 ÿ
 ý
ÿ ý
    ÿ   ÿ
  ÿ
   ÿ

ÿ

û  ÿ


ù	
ù	
ù	zClient._handle_connackc                 C  s˜   t d? }d  }}| jd dkrht|ƒ}| | jd ¡ | jd dkrht|ƒ}| | jd dd … ¡\}}|  td||¡ |  ¡  | jdt	j
||d	� d S )
NrZ  r'   rÆ   r)   rL   r   zReceived DISCONNECT %s %sT)r	  r
  r»  rÞ   )r€   r   r   rµ  r   rz  r{  r„  r  r   r]   )r=   Úpacket_typeÚ
reasonCoderÞ   ÚpropsÚ	props_lenr1   r1   r2   r²  ²  s*    ÿþüzClient._handle_disconnectc                 C  s®  |   td¡ dt| jd ƒd › d�}t || jd ¡\}}| jtkrxtt	d? ƒ}| |¡\}}dd„ ||d … D ƒ}n8d	d
t|ƒ › �}t ||¡}dd„ |D ƒ}tt	d? ƒ}| j
� | j}	W 5 Q R X |	�rª| j�Ð zŒ| jtjk�r,| jtk�rtt|	ƒ}	|	| | j|||ƒ ntt|	ƒ}	|	| | j||ƒ n4| jtjk�rXtt|	ƒ}	|	| | j|||ƒ ntdƒ‚W n< tk
�rž }
 z|   td|
¡ | j�sŽ‚ W 5 d }
~
X Y nX W 5 Q R X d S )NzReceived SUBACKr€  r)   rÆ   r®   rZ  c                 S  s   g | ]}t td ? |d�‘qS ©rZ  r–  ©r   r®  ©r†   Úcr1   r1   r2   Ú
<listcomp>Ñ  s     z)Client._handle_suback.<locals>.<listcomp>ú!ÚBc                 S  s   g | ]}t td ? |d�‘qS rÀ  rÁ  rÂ  r1   r1   r2   rÄ  Õ  s     rü   z$Caught exception in on_subscribe: %s)rz  r{  r�   r   r�  rµ  r	  r  r   r®  rD  r9  rB  r  r   r  r   ÚCallbackOnSubscribe_v1_mqtt5r
  ÚCallbackOnSubscribe_v1_mqtt3rg  ÚCallbackOnSubscribe_v2rÔ   rÃ  rÐ  ra  )r=   Úpack_formatr4   r)   rÞ   r¾  r¿  ÚreasoncodesZgranted_qosr9  r|  r1   r1   r2   r¯  É  sf    

    ÿ
   ÿ
û  ÿzClient._handle_subackc                 C  sT  | j d }tƒ }|d@ d? dk|_|d@ d? |_|d@ dk|_dt| j d ƒd	 › d
�}t || j d ¡\}}d|› d
t|ƒ| › d
�}t ||¡\}}| jt	kr´t|ƒdkr´t
jS z| d¡}W n tk
rà   d|›�}Y nX ||_|jdk�rdt|ƒd	 › d
�}t ||¡\|_}| jt	k�rPttd? ƒ|_|j |¡\}}	||	d … }||_| jt	k�rŽ|  td|j|j|j|j||jt|jƒ¡	 n&|  td|j|j|j|j|t|jƒ¡ tƒ |_|jdk�rØ|  |¡ t
jS |jdk�r
|  |¡ | j�rüt
jS |  |j¡S nF|jd	k�rJ|  |j¡}
t|_| j� || j |j< W 5 Q R X |
S t
jS d S )Nr#   rŠ  rL   r   r�  r   r€  r)   rÆ   r®   rÅ  r¯   zTOPIC WITH INVALID UTF-8: rZ  zKReceived PUBLISH (d%d, q%d, r%d, m%d), '%s', properties=%s, ...  (%d bytes)z<Received PUBLISH (d%d, q%d, r%d, m%d), '%s', ...  (%d bytes))!r   rW   rÛ   r5   rÝ   r�   r�  rµ  r	  r  r   r_   rç   ÚUnicodeDecodeErrorr—   r4   r   rÌ  rÞ   r³   rz  r{  rÐ   rÙ   Ú_handle_on_messager]   r  r|  r‡  Úmqtt_ms_wait_for_pubrelrÚ   rG  r0  )r=   Úheaderrì  rÊ  Úslenr)   r—   Zprint_topicr¾  r¿  r   r1   r1   r2   rª  û  s|    
     ü    ü

zClient._handle_publish)r4   r5   r;   c                 C  s0   | j r*|dkr|  |¡S |dkr*|  |¡S tjS )zÇ
           send an acknowledgement for a given message id (stored in :py:attr:`message.mid <MQTTMessage.mid>`).
           only useful in QoS>=1 and ``manual_ack=True`` (option of `Client`)
        r   rÆ   )r  r|  r~  r   r]   )r=   r4   r5   r1   r1   r2   ÚackE  s    

z
Client.ack)Úonr;   c                 C  s
   || _ dS )a  
           The paho library normally acknowledges messages as soon as they are delivered to the caller.
           If manual_ack is turned on, then the caller MUST manually acknowledge every message once
           application processing is complete using `ack()`
        N)r  )r=   rÒ  r1   r1   r2   Úmanual_ack_setR  s    zClient.manual_ack_setc              
   C  sp  | j tkr | jd dk r4tjS n| jd dkr4tjS t d| jd d d… ¡\}| j tkrÂ| jd dkrÂttd? ƒ}| | jd dd … ¡ | jd dkrÂt	td? ƒ}| | jd dd … ¡\}}|  
td|¡ | j�x || jk�rJ| j |¡}|  |¡ |  jd8  _| jd	k�rJ| j� |  ¡ }W 5 Q R X |tjk�rJ|W  5 Q R £ S W 5 Q R X | j�rbtjS |  |¡S d S )
Nr'   rÆ   r€  r)   rZ  rL   zReceived PUBREL (Mid: %d)r   r   )r	  r  r   r   r_   r�  rµ  r   rˆ  r   rz  r{  rG  r0  r¢  rÍ  r2  r1  rF  Ú_update_inflightr]   r  r~  )r=   r4   r½  rÞ   r¾  r¿  rì  r   r1   r1   r2   r¬  [  s:    

ÿ
zClient._handle_pubrelc              
   C  s°   | j  ¡ D ]ž}| j| jk rž|jdkr¨|jtkr¨|  jd7  _|jdkrNt|_n|jdkr^t|_| j	|j
|j d¡|j|j|j|j|jd�}|tjkr¨|  S q
tj  S q
tjS )Nr   r   rÆ   r¯   r´  )r/  rœ  r2  r1  r5   rÚ   rê  rç  rè  ræ  r4   r—   r°   r³   rÝ   rÛ   rÞ   r   r]   )r=   r   r   r1   r1   r2   rÔ  …  s*    


ù	

zClient._update_inflightc              
   C  s"  | j tkr | jd dk r4tjS n| jd dkr4tjS t d| jd d d… ¡\}| j tkrÂ| jd dkrÂttd? ƒ}| | jd dd … ¡ | jd dkrÂt	td? ƒ}| | jd dd … ¡\}}|  
td|¡ | j�@ || jk�r| j| }t|_tƒ |_|  |¡W  5 Q R £ S W 5 Q R X tjS )Nr'   rÆ   r€  r)   rZ  rL   zReceived PUBREC (Mid: %d))r	  r  r   r   r_   r�  rµ  r   r†  r   rz  r{  rF  r/  r�  rÚ   rÐ   rÙ   r‰  r]   )r=   r4   r½  rÞ   r¾  r¿  Úmsgr1   r1   r2   r«  ž  s.    

ÿ
 zClient._handle_pubrecc           
      C  sè  | j tkr | jd dk r4tjS n| jd dkr4tjS t d| jd d d… ¡\}| j tkrž| jd dd … }ttd? ƒ}| |¡\}}dd„ ||d … D ƒ}ng }ttd? ƒ}|  	t
d|¡ | j� | j}W 5 Q R X |�râ| j�ü z¸| jtjk�rP| j tk�r6tt|ƒ}|}t|ƒd	k�r"|d
 }|| | j|||ƒ ntt|ƒ}|| | j|ƒ nH| jtjk�r�tt|ƒ}|d k�r|ttjƒ}|| | j|||ƒ ntdƒ‚W n< tk
�rÖ }	 z|  	td|	¡ | j�sÆ‚ W 5 d }	~	X Y nX W 5 Q R X tjS )Nr'   rZ  rÆ   r€  r)   c                 S  s   g | ]}t td ? |d�‘qS rÀ  )r   r°  rÂ  r1   r1   r2   rÄ  Å  s   ÿz+Client._handle_unsuback.<locals>.<listcomp>zReceived UNSUBACK (Mid: %d)r   r   rü   z&Caught exception in on_unsubscribe: %s)r	  r  r   r   r_   r�  rµ  r   r°  rz  r{  rD  rB  rB  r  r   r  r   ÚCallbackOnUnsubscribe_v1_mqtt5r�   r
  ÚCallbackOnUnsubscribe_v1_mqtt3rg  ÚCallbackOnUnsubscribe_v2r   r|   rÔ   rÃ  rÐ  ra  r]   )
r=   r4   r)   rÞ   r¾  r¿  Zreasoncodes_listrB  rË  r|  r1   r1   r2   r±  ¹  sr    


þ
    ÿ



û  ÿzClient._handle_unsuback)r	  r
  r»  rÞ   r;   c                 C  s8  | j � | j}W 5 Q R X |�r4| j�� zÄ| jtjkrŒ| jtkrrtt	|ƒ}|r`|| | j
||ƒ qŠ|| | j
|d ƒ qêtt|ƒ}|| | j
|ƒ n^| jtjkrâtt|ƒ}t|d�}|d kr¼t|ƒ}|d krÎttjƒ}|| | j
|||ƒ ntdƒ‚W n< tk
�r( } z|  td|¡ | j�s‚ W 5 d }~X Y nX W 5 Q R X d S )N)rU   rü   z%Caught exception in on_disconnect: %s)rD  rE  rB  r  r   r  r	  r  r   ÚCallbackOnDisconnect_v1_mqtt5r
  ÚCallbackOnDisconnect_v1_mqtt3rg  ÚCallbackOnDisconnect_v2rT   r�   r   r   r€   rÔ   rÃ  rz  rÐ  ra  )r=   r	  r
  r»  rÞ   rE  Zdisconnect_flagsr|  r1   r1   r2   r  ù  sL    




ÿ
û  ÿzClient._do_on_disconnectr   r   )r4   Úreason_coderÞ   r;   c                 C  s  | j � | j}W 5 Q R X |rÄ| j�œ z\| jtjkrLtt|ƒ}|| | j|ƒ n2| jtj	krvtt
|ƒ}|| | j|||ƒ ntdƒ‚W n8 tk
r¸ } z|  td|¡ | js¨‚ W 5 d }~X Y nX W 5 Q R X | j |¡}|j ¡  |jdk�r|  jd8  _| jdk�r|  ¡ }|tjk�r|S tjS )Nrü   rc  r   r   )rD  r?  rB  r  r   r  r   rf  r
  rg  rh  rÔ   rÃ  rz  rÐ  ra  r/  r¢  r8   rË   r5   r2  r1  rÔ  r   r]   )r=   r4   rÜ  rÞ   r?  r|  rÕ  r   r1   r1   r2   Ú_do_on_publish.  sF    

û  ÿ
zClient._do_on_publishz&Literal['PUBACK'] | Literal['PUBCOMP'])r³  r;   c           
   
   C  s&  | j tkr | jd dk r4tjS n| jd dkr4tjS |dkr@tnt}|jd? }t 	d| jd d d… ¡\}t
|ƒ}t|ƒ}| j tkrÔ| jd dkrÔ| 	| jd dd … ¡ | jd dkrÔ| 	| jd dd … ¡\}}|  td||¡ | j�0 || jk�r|  |||¡}	|	W  5 Q R £ S W 5 Q R X tjS )	Nr'   rÆ   ri  rZ  r€  r)   rL   zReceived %s (Mid: %d))r	  r  r   r   r_   ri  r}  ré   r�  rµ  r   r   rz  r{  rF  r/  rÝ  r]   )
r=   r³  Zpacket_type_enumr¼  r4   r½  rÞ   r¾  r¿  r   r1   r1   r2   r©  U  s.    


ÿzClient._handle_pubackcomprW   )rì  r;   c                 C  sD  z
|j }W n tk
r"   d }Y nX g }| j�8 |d k	rJt| j |j ¡ƒ}t|ƒdkr^| j}nd }W 5 Q R X |D ]f}| j�V z|| | j	|ƒ W n< t
k
rÊ } z|  td|j|¡ | jsº‚ W 5 d }~X Y nX W 5 Q R X qp|�r@| j�V z|| | j	|ƒ W n< t
k
�r4 } z|  td|¡ | j�s$‚ W 5 d }~X Y nX W 5 Q R X d S )Nr   z9Caught exception in user defined callback function %s: %sz"Caught exception in on_message: %s)r—   rÌ  rD  rú  r;  r™   r�   r<  rB  r
  rÃ  rz  rÐ  r-   ra  )r=   rì  r—   Zon_message_callbacksr<  rS  r|  r1   r1   r2   rÍ  s  sH    

ü   ÿzClient._handle_on_messagec                 C  st   | j � | j}W 5 Q R X |rp| j�H z|| | jƒ W n0 tk
rd } z|  td|¡ W 5 d }~X Y nX W 5 Q R X d S )Nz'Caught exception in on_connect_fail: %s)rD  r6  rB  r
  rÃ  rz  rÐ  )r=   r6  r|  r1   r1   r2   r  �  s      ÿzClient._handle_on_connect_failc                 C  s   z| jdd� W 5 d | _ X d S )NT)r  )rJ  r  rC   r1   r1   r2   r!  ©  s    zClient._thread_mainc              	   C  s’   t ƒ }| j�8 | jd kr"| j| _nt| jd | jƒ| _|| j }W 5 Q R X || }| jtjtj	fkrŽ| j
sŽ|dkrŽt t|dƒ¡ |t ƒ  }qRd S )NrÆ   r   r   )rÐ   rH  r(  r&  Úminr'  r-  r   rÚ  rÛ  rK  ÚtimeÚsleep)r=   r  Ztarget_timeÚ	remainingr1   r1   r2   r  ¯  s"    

þÿþzClient._reconnect_waitc                 C  sb   ddœdd„}t | tƒr.||  d¡|  d¡ƒS t | ttfƒrZt| ƒdkoX|| d | d	 ƒS d
S d S )NrF   rB   c                 S  s    t d k	o| t jt jt jhko|S r<   )rª  ÚHTTPZSOCKS4ÚSOCKS5)rý  Úar1   r1   r2   ÚcheckÇ  s
    ÿÿz%Client._proxy_is_valid.<locals>.checkÚ
proxy_typeÚ
proxy_addrr�  r   r   F)rp   rŠ  Úgetrú  rù  r�   )rt  rå  r1   r1   r2   r«  Å  s    
zClient._proxy_is_validzdict[str, Any] | Nonec                 C  sÂ   t d krd S |  | j¡r| jS ttjdƒr8tj | j¡sštj ¡ }d|krštj	 
|d ¡}|jdkrzt j|j|jdœ}|S |jdkršt j|j|jdœ}|S t  ¡ }|  |¡r¾d}tt||ƒƒS d S )NÚproxy_bypassÚmqttÚhttp)ræ  rç  Ú
proxy_portrª  )ræ  rç  rì  Z
proxy_rdnsZproxy_usernameZproxy_password)rª  r«  r@  r  ÚurllibÚrequestré  r<  Ú
getproxiesÚparseÚurlparseÚschemerâ  Úhostnamer«   rã  Zget_default_proxyrŠ  Úzip)r=   Úenv_proxiesÚpartsÚproxyZsocks_defaultÚ
proxy_keysr1   r1   r2   Ú
_get_proxyÒ  s6    ÿ

ý
ý
zClient._get_proxyc                 C  sd   | j dkr|  ¡ }n|  ¡ }| jr,|  |¡}| j dkr`| | j¡ t|| j| j	| j| j
| jd�S |S )Nrö   rø   ©rž   rd  r«   Úis_sslrˆ  Úextra_headers)r  Ú_create_unix_socket_connectionÚ_create_socket_connectionrL  Ú_ssl_wrap_socketÚ
settimeoutr  Ú_WebsocketWrapperr<  r=  r^  r_  r‚  r1   r1   r2   rÑ  ý  s     



ú	zClient._create_socketz_socket.socketc                 C  s    t   t jt j¡}| | j¡ |S r<   )rž   r÷   r    r¨   r<  )r=   Zunix_socketr1   r1   r2   rý    s    z%Client._create_unix_socket_connectionc                 C  sT   |   ¡ }| j| jf}| j| jf}|r>tj|f| j|dœ|—ŽS tj|| j|d�S d S )N)rÍ   Úsource_address)	rù  r<  r=  r>  r?  rª  Úcreate_connectionr  rž   )r=   r÷  rÄ  Úsourcer1   r1   r2   rþ    s    z Client._create_socket_connectionzssl.SSLSocket)Útcp_sockr;   c                 C  s®   | j d krtdƒ‚| j }z| j j|| jdd�}W n: tjk
rJ   ‚ Y n6 tk
rl   | j j|dd�}Y nX t| j ddƒr€d}| | j	¡ | 
¡  |rªt | ¡ | j¡ |S )NzGImpossible condition. _ssl_context should never be None if _ssl is TrueF)Úserver_hostnameÚdo_handshake_on_connect)r  rŽ  )rM  r‹   rN  Úwrap_socketr<  ru  ÚCertificateErrorr¥  r   r  Údo_handshakeÚmatch_hostnameÚgetpeercert)r=   r  Zverify_hostÚssl_sockr1   r1   r2   rÿ  "  s2    
ÿý
þzClient._ssl_wrap_socket)F)rŠ   TN)r  N)N)NNNNNNNN)N)r   r  )rÔ  )rÔ  )Nr   FN)N)NN)r   NN)N)r   )Nr   FN)rÔ  F)N)rµ   r   FFNN)NN)N)N)N)NN)›r-   r.   r/   rS   r   r  r“  rÁ   rc  rë   rd  rì   r«   rh  ró   rò   ri  rj  rk  rl  rm  rn  ro  rq  r}  r  r„  rb  r†  rŒ  r�  r¨  r§  r¬  r¯  r°  rN   r¨   rÆ  r´  rÊ  rµ  rÖ  rÕ  rí  rî  rð  rf  rò  rõ  r   r  rÝ  rß  rØ  rà  r  r  r  r  r  r  rž   r  r$  r&  rî   r(  r0  rÏ  r2  r3  r5  r6  r8  r9  r;  r<  r>  r?  rA  rB  rD  rE  rG  rH  rJ  rÒ  rK  rL  r�  rN  rO  rx  rQ  rR  r€  rT  rV  rX  r  r  r  rz  r  rå  Ústaticmethodrä  rø  ro  rz  r|  r~  r  rƒ  ræ  r‡  r‰  r{  rw  rÓ  rô  rü  r  r›  r¡  r£  rÎ  r…  r_  r§  r¨  r­  r²  r¯  rª  rÑ  rÓ  r¬  rÔ  r«  r±  r  rÝ  r©  rÍ  r  r!  r  r«  rù  rÑ  rý  rþ  rÿ  r1   r1   r1   r2   rV   w  sN  g÷  					
  ü ýþ       ÷ k 	ø.ù3ø0<K   úoÿ
 ý  û ÿ*    ú/
 ýN	4$*%'ÿjY&
	     ÷*O	k ý*ü .ü 1	
ú"'	 /2J	*D û5'*+
c                   @  s  e Zd ZdZdZdZdZdZdZddd	d
dddœdd„Z	ddœdd„Z
dddœdd„Zd5d	dd	ddœdd„Zd	ddœdd„Zd	ddœdd„Zdd	d œd!d"„Zd	ddœd#d$„Zd	ddœd%d&„Zdd	d œd'd(„Zdd	d œd)d*„Zddœd+d,„Zd	dœd-d.„Zd	dœd/d0„Zd
dd1œd2d3„Zd4S )6r  r   r   rÆ   rŠ  é	   é
   zsocket.socket | ssl.SSLSocketrZ   r"   rF   r‡  rú  c                 C  sT   d| _ || _|| _|| _|| _|| _tƒ | _tƒ | _d| _	d| _
d| _|  |¡ d S r½   )Ú	connectedrL  r<  r=  Ú_socketÚ_pathr(   Ú_sendbufferÚ_readbufferÚ_requested_sizeÚ_payload_headÚ_readbuffer_headÚ_do_handshake)r=   rž   rd  r«   rû  rˆ  rü  r1   r1   r2   rÁ   Q  s    	z_WebsocketWrapper.__init__rA   rB   c                 C  s   t ƒ | _t ƒ | _d S r<   )r(   r  r  rC   r1   r1   r2   rc  k  s    z_WebsocketWrapper.__del__)rü  r;   c                 C  sD  t  ¡ j}t |¡}| jr$d}d}nd}d}|| jkr@| j› }n| j› d| j› �}|dd|› d|› �| d	¡d
ddœ}t	|t
ƒrŒ| |¡ nt|ƒrœ||ƒ}d d| j› d�d dd„ | ¡ D ƒ¡dg¡ d	¡}| j |¡ d}d}	z| j d¡}
W n tk
�r   d}
Y nX | j |
¡ |
dk�rt| jƒdk�rdt| jƒ ¡  d¡k�rxdt| jƒ ¡  d¡k�rttdƒ‚nd}	dt| jƒ ¡  d¡k�rd}| j d¡ dd¡d }| ¡  d¡}| d¡| }t | d¡¡}t | ¡ ¡}||k�rütdƒ‚nd}n�qt ƒ | _qä|
sätd ƒ‚qä|	�r*|�s2td ƒ‚t ƒ | _d| _!d S )!Ni»  ÚhttpséP   rë  ú:Z	websocketÚUpgradez://rÿ   Z13rê  )ÚHostr  Ú
ConnectionZOriginzSec-WebSocket-KeyzSec-Websocket-VersionzSec-Websocket-Protocolz
zGET z	 HTTP/1.1c                 s  s    | ]\}}|› d |› �V  qdS )ú: Nr1   )r†   ÚiÚjr1   r1   r2   r‰   “  s     z2_WebsocketWrapper._do_handshake.<locals>.<genexpr>Fr   rµ   ó   
rÆ   s
   connectionr¯   s   upgradez2WebSocket handshake error, connection not upgradedTs   sec-websocket-acceptz$258EAFA5-E914-47DA-95CA-C5AB0DC85B11r   z-WebSocket handshake error, invalid secret keyzWebSocket handshake error)"r  r  r6   Úbase64Ú	b64encoderL  r=  r<  rç   rp   rŠ  Úupdater‹  r‘   r  Úitemsr°   r  r@   r>   ÚConnectionResetErrorr  rŽ   r�   rZ   r  rX   rv  ÚstripÚhashlibÚsha1Údigestr(   r  )r=   rü  Zsec_websocket_keyÚdefault_portZhttp_schemaÚ	host_portZwebsocket_headersrÏ  Z
has_secretZhas_upgrader`  ZGUIDZserver_hash_strZserver_hashZclient_hash_keyZclient_hash_digestZclient_hashr1   r1   r2   r  o  s�    



ù
ýü

ÿÿ ÿÿ
ÿ

z_WebsocketWrapper._do_handshaker(   )Úopcoderb  Ú
do_maskingr;   c           	      C  sè   t ƒ }t|ƒ}t t d¡ƒ}|}| d|B ¡ |dk rJ| |d> |B ¡ n`|dk rv| |d> dB ¡ |t d|¡7 }n4|dk r¢| |d> dB ¡ |t d	|¡7 }ntd
ƒ‚|dkràt|ƒD ]}||  ||d  N  < qº|| }|| S )NrZ  r\  é~   r�  rp  r€  l           r[  ú!QzMaximum payload size is 2^63r   )	r(   r�   ÚosÚurandomr�   r�  r‚  r‹   r�   )	r=   r/  rb  r0  rÏ  ÚlengthÚmask_keyZ	mask_flagrÇ   r1   r1   r2   Ú_create_frameÓ  s&    z_WebsocketWrapper._create_frame)r5  r;   c                 C  sr   |t | jƒ| j  }|dkrN| j |¡}|s2t‚n| j |¡ t |ƒ|k rNt‚|  j|7  _| j| j| | j… S rÃ   )r�   r  r  r  r>   ÚConnectionAbortedErrorrŽ   r©   )r=   r5  Zwanted_bytesrb  r1   r1   r2   Ú_buffered_readô  s    z _WebsocketWrapper._buffered_readr6   c                 C  sÜ  �z¶d| _ d}| j}| j| }|  d¡}|  d¡}|d d@ }|d d@ dk}|d d@ }	|	}
d }|	dkr„|  d¡}t d	|¡\}
n |	dkr¤|  d
¡}t d|¡\}
|r²|  d¡}|}|
|k rÂ|
}|dk�r|  |¡}|d k	�rt||ƒD ]}||  ||d  N  < qê|||… }|| _ntƒ }||
k�rŠtƒ | _d| _|tj	k�rb|  
tj	|d¡}| j |¡ |tjk�rŠ|  
tj|d¡}| j |¡ |tjk�s¢|tjk�r²|
dk�r²|W S t‚W n tk
�rÖ   d| _Y dS X d S )Nr   rµ   r   é   r\  r[  r1  rÆ   r€  rŠ  r2  rZ  F)r  r  r9  r�  rµ  r�   r(   r  r  ÚOPCODE_CONNCLOSEr7  r  r@   ÚOPCODE_PINGÚOPCODE_PONGÚOPCODE_BINARYÚOPCODE_CONTINUATIONr©   rt  r  )r=   r5  rº  Zchunk_startindexZchunk_endindexZheader1Zheader2r/  ZmaskbitZ
lengthbitsZpayload_lengthr6  ré   Z	readindexr³   rÇ   Úframer1   r1   r2   Ú
_recv_impl  sp    









  ÿ  ÿÿz_WebsocketWrapper._recv_impl)rb  r;   c                 C  sp   t | jƒdkr6|  tjt|ƒ¡}| j |¡ t |ƒ| _| j 	| j¡}| j|d … | _t | jƒdkrh| jS dS d S rÃ   )
r�   r  r7  r  r>  r(   rŽ   r  r  r@   )r=   rb  r@  r5  r1   r1   r2   Ú
_send_implZ  s     ÿ
z_WebsocketWrapper._send_implc                 C  s
   |   |¡S r<   ©rA  ©r=   r5  r1   r1   r2   r>   p  s    z_WebsocketWrapper.recvc                 C  s
   |   |¡S r<   rC  rD  r1   r1   r2   Úreads  s    z_WebsocketWrapper.readc                 C  s
   |   |¡S r<   ©rB  ©r=   rb  r1   r1   r2   r@   v  s    z_WebsocketWrapper.sendc                 C  s
   |   |¡S r<   rF  rG  r1   r1   r2   Úwritey  s    z_WebsocketWrapper.writec                 C  s   | j  ¡  d S r<   )r  rD   rC   r1   r1   r2   rD   |  s    z_WebsocketWrapper.closec                 C  s
   | j  ¡ S r<   )r  rE   rC   r1   r1   r2   rE     s    z_WebsocketWrapper.filenoc                 C  s   | j r| j ¡ S dS d S rÃ   )rL  r  r×  rC   r1   r1   r2   r×  ‚  s    
z_WebsocketWrapper.pendingrG   c                 C  s   | j  |¡ d S r<   )r  rJ   rI   r1   r1   r2   rJ   ‹  s    z_WebsocketWrapper.setblockingN)r   )r-   r.   r/   r?  ZOPCODE_TEXTr>  r;  r<  r=  rÁ   rc  r  r7  r9  rA  rB  r>   rE  r@   rH  rD   rE   r×  rJ   r1   r1   r1   r2   r  I  s,   e ÿ!S	r  )ÑrS   Ú
__future__r   r$  r!  Úerrnor*  r­  r3  ÚplatformrÙ  rž   Ústringr�  r¾   rß  Úurllib.parserí  Úurllib.requestr  r  Útypingr   r   r   r   r   r   r	   r
   r   r   r   Zpaho.mqtt.packettypesr   Úenumsr   r   r   r   r   r   r   r   r   r›   r   rÞ   r   rË  r   r   Zsubscribeoptionsr   r   ÚImportErrorÚtyping_extensionsr   r    r!   r3   r9   ru  rª  Ú	monotonicrÐ   ry  Zdns.resolverr½  rº  ÚsystemZWSAEWOULDBLOCKÚEAGAINr‡   r”  r|   rÌ  ri  r†  rˆ  r}  r™  r®  rš  r°  rx  ry  r€   ZAUTHZMQTT_LOG_INFOZMQTT_LOG_NOTICEZMQTT_LOG_WARNINGrÐ  r{  ÚDEBUGÚINFOÚWARNINGÚERRORrm  rq   rr   rs   rt   ru   rv   ZMQTT_MS_INVALIDrà   ZMQTT_MS_PUBLISHré  ZMQTT_MS_WAIT_FOR_PUBACKrç  ZMQTT_MS_WAIT_FOR_PUBRECrè  ZMQTT_MS_RESEND_PUBRELrž  ZMQTT_MS_WAIT_FOR_PUBRELrÎ  ZMQTT_MS_RESEND_PUBCOMPZmqtt_ms_resend_pubcompZMQTT_MS_WAIT_FOR_PUBCOMPr�  ZMQTT_MS_SEND_PUBRECZmqtt_ms_send_pubrecZMQTT_MS_QUEUEDrê  rÓ   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   r  r“  r  r  rï  rN   r0   r¤  rZ   r6   r(   r"   r¶   rá  Z
HTTPHeaderZWebSocketHeadersrF   rM   rP   rT   r·  r¶  ZCallbackOnConnect_v1r¸  r4  r7  rÚ  rÙ  ZCallbackOnDisconnect_v1rÛ  rF  r,  r=  r1  rf  rh  r@  rI  rÈ  rÇ  ZCallbackOnSubscribe_v1rÉ  r:  r×  rÖ  ZCallbackOnUnsubscribe_v1rØ  rC  r  rt  rX   rn   rx   r}   r�   r“   Úascii_lettersr•   rœ   r­   r±   r¸   r¹   rW   rV   r  r1   r1   r1   r2   Ú<module>   s°  4,	



     û	&&"""(
ýc.                               q