
    >qa^V             
       F   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
 ddlmZ ddlm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Z	 d dlZn# e$ r Y nw xY wdZ	 d dlZn# e$ r Y nw xY w	 d dlmZ d dlmZ n# e$ r d dlZd dlZY nw xY w	 ej         Z!n# e"$ r
 ej        Z!Y nw xY w	 d dl#Z$d	Z%n# e$ r d
Z%Y nw xY w ej&                    dk    rej'        Z(nej(        Z(	 e) n# e*$ r e+Z)Y nw xY wdZ,dZ-dZ.ej/        d          dk    re0Z1e0Z2dZ3dZ4dZ5dZ6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ>dZ?dZ@dZAdZBdZCdZDdZEdZFeFejG        eBejH        eCejH        eDejI        eEejJ        iZKd ZLdZMdZNdZOdZPdZQd ZRdZSdZTdZUd ZVdZWdZXdZYdZZdZ[d Z\d!Z]dZ^d"Z_d#Z`d ZadZbdZcdZddZedZfd Zgd!ZhdZid"Zjd$Zkd%Zld&Zmd'Znd(Zod)ZpdZqd ZrdZsdZtd*Zu G d+ d,ev          Zwd- Zxd. Zyejz        ej{        z   dfd/Z|d0 Z}d1 Z~ G d2 d3e          Z G d4 d5e          Z G d6 d7e          Z G d8 d9e          ZdS ):    N   )MQTTMatcher)
Properties)ReasonCodes)SubscribeOptions)parse)requestTFWindows                0   @   P   `   p                                       	   
                     0c                       e Zd ZdS )WebsocketConnectionErrorN)__name__
__module____qualname__     D/opt/windhager/venv/lib/python3.11/site-packages/paho/mqtt/client.pyr+   r+      s        Dr0   r+   c                    | 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 | 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 | t          k    rdS | t          k    rdS | t           k    r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.)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)
mqtt_errnos    r1   error_stringrF      s4   %%%{	~	%	%	(	(	(VV	~	%	%55	'	'	'77	,	,	,,,	)	)	)44	)	)	)))	|	#	#&&	,	,	,##	-	-	-//	}	$	$&&	*	*	*&&	'	'	'	~	%	%((	*	*	*$$	)	)	)PPr0   c                     | 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 )z3Return the string associated with a CONNACK result.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.)CONNACK_ACCEPTED CONNACK_REFUSED_PROTOCOL_VERSION#CONNACK_REFUSED_IDENTIFIER_REJECTED"CONNACK_REFUSED_SERVER_UNAVAILABLE%CONNACK_REFUSED_BAD_USERNAME_PASSWORDCONNACK_REFUSED_NOT_AUTHORIZED)connack_codes    r1   connack_stringrO      st    '''%%	9	9	9CC	<	<	<99	;	;	;88	>	>	>??	7	7	74444r0   c                 8   | dk    sJ g }| r0t          | d          \  } }|                    |                    | 0|                    fdt          t	          |          |          D                        d                    t          |                    S )z+Convert a number to base-62 representation.r   >   c              3   (   K   | ]}d          V  dS )r   Nr/   ).0_bases     r1   	<genexpr>zbase62.<locals>.<genexpr>   s'      ??a$q'??????r0    )divmodappendextendrangelenjoinreversed)numrU   paddingdigitsrests    `   r1   base62rc      s    !8888F
 "3OO	Td4j!!!  " MM????5Vg#>#>??????778F##$$$r0   c                     t                      }d|| <   	 t          |                    |                     dS # t          $ r Y dS w xY w)zCheck whether a topic matches a subscription.

    For example:

    foo/bar would match the subscription foo/# or +/bar
    non/matching would not match the subscription non/+/+
    TF)r   next
iter_matchStopIteration)subtopicmatchers      r1   topic_matches_subrk     s^     mmGGCLW&&'''t   uus   "9 
AAc                     t          j         t           j        t           j        t           j                  } |                     t           j        t           j        d           |                     d           |                     d           | 	                                \  }}t          j         t           j        t           j        t           j                  }|
                    d           	 |                    d|f           n# t          $ r Y nw xY w|                                 \  }}|
                    d           |                                  ||fS )z+TCP/IP socketpair including Windows supportr   )	127.0.0.1r   r   rm   )socketAF_INETSOCK_STREAM
IPPROTO_IP
setsockopt
SOL_SOCKETSO_REUSEADDRbindlistengetsocknamesetblockingconnectBlockingIOErroracceptclose)
listensockifaceportsock1sock2addresss         r1   _socketpair_compatr     s4   *F,=? ?J&+V-@!DDDOO$%%%a((**KE4M*F,=? ?E	a{D)****   &&((NE7	a5>s   +D 
DDc                   N    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
d	 ZddZd Zd
S )MQTTMessageInfozThis 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.
    )mid
_published
_conditionrc_iterposc                 n    || _         d| _        t          j                    | _        d| _        d| _        d S NFr   )r   r   	threading	Conditionr   r   r   selfr   s     r1   __init__zMQTTMessageInfo.__init__1  s2    #-//r0   c                 8    t          | j        | j        f          S N)strr   r   r   s    r1   __str__zMQTTMessageInfo.__str__8  s    DGTX&'''r0   c                     d| _         | S Nr   )r   r   s    r1   __iter__zMQTTMessageInfo.__iter__;  s    r0   c                 *    |                                  S r   )re   r   s    r1   __next__zMQTTMessageInfo.__next__?  s    yy{{r0   c                 t    | j         dk    rd| _         | j        S | j         dk    rd| _         | j        S t          )Nr   r   r   )r   r   r   rg   r   s    r1   re   zMQTTMessageInfo.nextB  s>    =ADM7N]aDM8Or0   c                 T    |dk    r| j         S |dk    r| j        S t          d          )Nr   r   zindex out of range)r   r   
IndexError)r   indexs     r1   __getitem__zMQTTMessageInfo.__getitem__L  s1    A::7NaZZ8O1222r0   c                     | j         5  d| _        | j                                          d d d            d S # 1 swxY w Y   d S )NT)r   r   notifyr   s    r1   _set_as_publishedz!MQTTMessageInfo._set_as_publishedT  s    _ 	% 	%"DOO""$$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%s   !6::Nc                    | j         t          k    rt          d          | j         t          k    rn/| j         dk    r$t	          dt          | j                   z            dnt          j                    z   dndz  }fd}| j        5  | j        s5 |            s+| j        	                    |           | j        s
 |            +ddd           dS # 1 swxY w Y   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: %sNg      $@c                  :     dnt          j                     k    S NF)time)timeouttimeout_times   r1   	timed_outz3MQTTMessageInfo.wait_for_publish.<locals>.timed_outn  s    #O55|1KKr0   )
r   rC   
ValueErrorMQTT_ERR_AGAINRuntimeErrorrF   r   r   r   wait)r   r   timeout_tenthr   r   s    `  @r1   wait_for_publishz MQTTMessageInfo.wait_for_publishY  s]    7)))JKKKW&&Wq[[;|DG?T?TUVVV&ttDIKK'4I 'Ws]	L 	L 	L 	L 	L 	L _ 	4 	4o 4iikk 4$$]333 o 4iikk 4	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4s   =CC #C c                    | j         t          k    rt          d          | j         t          k    rn/| j         dk    r$t	          dt          | j                   z            | j        5  | j        cddd           S # 1 swxY w Y   dS )zgReturns True if the message associated with this object has been
        published, else returns False.r   r   r   N)r   rC   r   r   r   rF   r   r   r   s    r1   is_publishedzMQTTMessageInfo.is_publishedu  s     7)))JKKKW&&Wq[[;|DG?T?TUVVV_ 	# 	#?	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	#s   'A;;A?A?r   )r,   r-   r.   __doc__	__slots__r   r   r   r   re   r   r   r   r   r/   r0   r1   r   r   )  s         
 DI  ( ( (         3 3 3% % %
4 4 4 48# # # # #r0   r   c                   `    e Zd ZdZdZddZd Zd Zed             Z	e	j
        d	             Z	d
S )MQTTMessagea   This is a class that describes an incoming or outgoing message. It is
    passed to the on_message callback as the message parameter.

    Members:

    topic : String. topic that the message was published on.
    payload : Bytes/Byte array. the message payload.
    qos : Integer. The message Quality of Service 0, 1 or 2.
    retain : Boolean. If true, the message is a retained message and not fresh.
    mid : Integer. The message id.
    properties: Properties class. In MQTT v5.0, the properties associated with the message.
    )
	timestampstatedupr   _topicpayloadqosretaininfo
propertiesr   r0   c                     d| _         t          | _        d| _        || _        || _        d| _        d| _        d| _        t          |          | _
        d S )Nr   Fr0   )r   mqtt_ms_invalidr   r   r   r   r   r   r   r   r   )r   r   ri   s      r1   r   zMQTTMessage.__init__  sM    $
#C((			r0   c                 P    t          || j                  r| j        |j        k    S dS )z$Override the default Equals behaviorF)
isinstance	__class__r   r   others     r1   __eq__zMQTTMessage.__eq__  s*    eT^,, 	)8uy((ur0   c                 .    |                      |           S )zDefine a non-equality test)r   r   s     r1   __ne__zMQTTMessage.__ne__  s    ;;u%%%%r0   c                 6    | j                             d          S )Nutf-8)r   decoder   s    r1   ri   zMQTTMessage.topic  s    {!!'***r0   c                     || _         d S r   )r   r   values     r1   ri   zMQTTMessage.topic  s    r0   N)r   r0   )r,   r-   r.   r   r   r   r   r   propertyri   setterr/   r0   r1   r   r     s          oI	) 	) 	) 	)  & & & + + X+ \  \  r0   r   c                      e Zd ZdZdddeddfdZd Zd Zd	 Zd
 Z	ddZ
ddZddZddZddZd Zd ZddZd ZddddedfdZdddedfdZddddedfdZddZd Zdd!Zdd"Zdd#Zdd$Zd% Zd& Zdd'Zdd(Z dd)Z!dd*Z"dd+Z#d, Z$d- Z%d. Z&d/ Z'd0 Z(d1 Z)dd2Z*d3 Z+d4 Z,dd5Z-d6 Z.dd7Z/e0d8             Z1e1j2        d9             Z1d: Z3e0d;             Z4e4j2        d<             Z4d= Z5e0d>             Z6e6j2        d?             Z6d@ Z7e0dA             Z8e8j2        dB             Z8dC Z9e0dD             Z:e:j2        dE             Z:dF Z;e0dG             Z<e<j2        dH             Z<dI Z=e0dJ             Z>e>j2        dK             Z>dL Z?e0dM             Z@e@j2        dN             Z@dO ZAe0dP             ZBeBj2        dQ             ZBdR ZCdS ZDe0dT             ZEeEj2        dU             ZEdV ZFdW ZGe0dX             ZHeHj2        dY             ZHdZ ZId[ ZJe0d\             ZKeKj2        d]             ZKd^ ZLdd_ZMd` ZNda ZOdb ZPddcZQdd ZRde ZSdf ZTdg ZUdh ZVeWdi             ZXeWdj             ZYdk ZZdl Z[dm Z\dn Z]do Z^dp Z_ddrZ`ds Zadt Zbdu Zcdv Zddw ZeddxZfddyZgddzZhd{ Zid| Zjd} Zkd~ ZlddZmd Znd Zod Zpd Zqd Zrd Zsd Ztd Zud Zvd Zwd ZxddZyd Zzd Z{d Z|d Z}d Z~d ZeWd             Zd Zd ZdS )Clientat  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() to connect to a broker
    * Call loop() frequently to maintain network traffic flow with the broker
    * Or 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.
    * 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.

    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, rc):
        print("Connection returned " + str(rc))

    client.on_connect = on_connect

    Callbacks can also be attached using decorators:

    client = paho.mqtt.Client()

    @client.connect_callback()
    def on_connect(client, userdata, flags, rc):
        print("Connection returned " + str(rc))


    **IMPORTANT** the required function signature for a callback can differ
    depending on whether you are using MQTT v5 or MQTT v3.1.1/v3.1. See the
    documentation for each callback.

    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(userdata).

    If you wish to suppress exceptions within a callback, you should set
    `client.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
    rW   NtcpTc           	         |                                 dvrt          d|z            |                                 | _        || _        || _        d| _        d\  | _        | _        d| _        d| _	        t          | _        |t          k    r|t          d          n$|d}|s|d	k    s|t          d
          || _        |d	k    s|@|t          k    r-t          t!          j                    j        d          | _        nd| _        n|| _        t)          | j        t*                    r| j                            d          | _        d| _        d| _        ddg ddt3          d          ddd| _        t7          j                    | _        t=                      | _        t=                      | _         d| _!        d| _"        d| _#        || _$        d| _%        d| _&        tN          | _(        t7          j)                    | _*        t7          j)                    | _+        d| _,        d| _-        d| _.        d| _/        d| _0        d| _1        d| _2        d| _3        d| _4        d| _5        tm                      | _7        d	| _8        d| _9        d	| _:        d| _;        i | _<        t{          j>                    | _?        t{          j@                    | _A        t{          j>                    | _B        t{          j@                    | _C        t{          j>                    | _D        t{          j>                    | _E        t{          j>                    | _F        d| _G        d| _H        d| _I        d| _J        d| _K        d| _L        d| _M        d| _N        d| _O        d| _P        d| _Q        d| _R        d| _S        d| _T        d| _U        d| _V        d| _W        d| _X        d| _Y        d| _Z        d| _[        d| _\        d| _]        dS )a]  client_id is 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.

        clean_session is 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.

        userdata is 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.

        The protocol argument 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.

        Set transport to "websockets" to use WebSockets as the transport
        mechanism. Set to "tcp" to use raw TCP, which is the default.
        )
websocketsr   z/transport must be "websockets" or "tcp", not %sNNN<   g      @z&Clean session is not used for MQTT 5.0TrW   z7A client id must be provided if clean session is False.   r`   r0   r   r   r   commandhave_remainingremaining_countremaining_multremaining_lengthpacket
to_processposx      F[  /mqtt)^lowerr   
_transport	_protocol	_userdata_sock
_sockpairR
_sockpairW
_keepalive_connect_timeoutMQTT_CLIENT_client_modeMQTTv5_clean_sessionMQTTv31rc   uuiduuid4int
_client_idr   unicodeencode	_username	_password	bytearray
_in_packetcollectionsdeque_out_packet	time_func_last_msg_in_last_msg_out_reconnect_min_delay_reconnect_max_delay_reconnect_delay_reconnect_on_failure_ping_t	_last_mid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_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   	client_idclean_sessionuserdataprotocol	transportreconnect_on_failures          r1   r   zClient.__init__  s   F ??$999AIMO O O#//++!!
+8( #'v( !IJJJ ) $ $  Oi2oo9J MO O O"/D ??i/7"""()92"F"F"F"%'DOdow// 	>"o44W==DO! !nn  ',..%KK&[[$%!$'! $%9"!(466'355&(#"#$%!#'  $
 !$/MM!

"+."2"2(00'n.."+/"3"3!*!1!1&/n&6&6##,>#3#3 !&	 "!& $!#"# $)-&+/(&(,%%)"#(   r0   c                 .    |                                   d S r   )_reset_socketsr   s    r1   __del__zClient.__del__{  s    r0   c                     	 | j                             |          S # t          j        $ r t          t          j        $ r |                                  t          w xY wr   )r   recvsslSSLWantReadErrorrz   SSLWantWriteError_call_socket_register_write)r   bufsizes     r1   
_sock_recvzClient._sock_recv~  sl    	":??7+++# 	" 	" 	"!!$ 	" 	" 	",,...!!	"s
    A Ac                    	 | j                             |          S # t          j        $ r t          t          j        $ r |                                  t          t          $ r |                                  t          w xY wr   )r   sendrN  rO  rz   rP  rQ  )r   bufs     r1   
_sock_sendzClient._sock_send  s    		":??3'''# 	" 	" 	"!!$ 	" 	" 	",,...!! 	" 	" 	",,...!!	"s
    A$B c                     | j         sdS 	 | j         }d| _         |                     |           |                     |           |                                 dS # |                                 w xY w)z#Close the connection to the server.N)r   _call_socket_unregister_write_call_socket_closer|   )r   socks     r1   _sock_closezClient._sock_close  sq    z 	F	:DDJ..t444##D))) JJLLLLLDJJLLLLs   8A A/Fc                     |dk    r|                                   | j        r | j                                         d | _        | j        r"| j                                         d | _        d S d S r   )r\  r   r|   r   )r   sockpair_onlys     r1   rJ  zClient._reset_sockets  sw    E!!? 	#O!!###"DO? 	#O!!###"DOOO	# 	#r0   c                 \    |                                   |                     |||           d S r   )rJ  r   )r   rC  rD  rE  s       r1   reinitialisezClient.reinitialise  s0    i99999r0   r   c                     || _         |<t          |t                    st          |          r	|| _        dS t          d          dS )a   Set the path and headers for a websocket connection

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

        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?  r   dictcallabler@  r   )r   pathheaderss      r1   ws_set_optionszClient.ws_set_options  sc      $'4(( dHW,=,= d07--- bd d d	 r0   c                     | j         t          d          |8t          t          d          rt          j                    }nt          d          d| _        || _         t          |d          r|j         | _        dS dS )a  Configure network encryption and authentication context. Enables SSL/TLS support.

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

        Must be called before connect() or connect_async().Nz$SSL/TLS has already been configured.create_default_contextz!SSL/TLS context must be specifiedTcheck_hostname)r/  r   hasattrrN  rh  r.  ri  r0  )r   contexts     r1   tls_set_contextzClient.tls_set_context  s     (CDDD
 ?s455 F466 !DEEE	# 7,-- 	<%,%;!;D	< 	<r0   c                 (   t           t          d          t          t           d          st          d          |)t          t           j        d          st          d          |-t           j        }t          t           d          rt           j        }t          j        |          }||                    |||           |t           j        k    rt          |d          rd	|_        |t           j	        n||_
        ||                    |           n|                                 ||                    |           |                     |           |t           j        k    r|                     d	           dS |                     d
           dS )a"	  Configure network encryption and authentication options. Enables SSL/TLS support.

        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.

        certfile and keyfile are strings pointing to the PEM encoded client
        certificate and private keys respectively. If these arguments are not
        None then they will be used as client information for TLS based
        authentication.  Support for this feature is broker dependent. Note
        that if either of these 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.

        cert_reqs allows 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.

        tls_version allows 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.

        ciphers is a string specifying which encryption ciphers are allowable
        for this connection, or None to use the defaults. See the ssl pydoc for
        more information.

        Must be called before connect() or connect_async().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_TLSri  FT)rN  r   rj  rn  PROTOCOL_TLSv1_2rp  load_cert_chain	CERT_NONEri  CERT_REQUIREDverify_modeload_verify_locationsro  set_ciphersrl  tls_insecure_set)	r   ca_certscertfilekeyfile	cert_reqstls_versioncipherskeyfile_passwordrk  s	            r1   tls_setzClient.tls_set  s   P ;<===sL)) 	TRT T T GCN<P$Q$Q9::: .KsN++ /!..-- ##Hg7GHHH%%'';K*L*L%%*G"3<3Dc//)))(3333&&((((((W%%%%% !!%((((( !!$'''''r0   c                     | j         t          d          || _        t          | j         d          r| | j         _        dS dS )aj  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.ri  )r/  r   r0  rj  ri  r   s     r1   rx  zClient.tls_insecure_set5  sf     $KM M M # 4$&677 	9 49yD,,,	9 	9r0   c                     t           t          d          |                     |          st          d          || _        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)
        proxy_type: One of {socks.HTTP, socks.SOCKS4, or socks.SOCKS5}
        proxy_addr: IP address or DNS name of proxy server

        (Optional)
        proxy_rdns: boolean indicating whether proxy lookup should be performed
            remotely (True, default) or locally (False)
        proxy_username: username for SOCKS5 proxy, or userid for SOCKS4 proxy
        proxy_password: password for SOCKS5 proxy

        Must be called before connect() or connect_async().Nz,PySocks must be installed for proxy support.z)proxy_type and/or proxy_addr are invalid.)socksr   _proxy_is_validr"  )r   
proxy_argss     r1   	proxy_setzClient.proxy_setP  sH    $ =KLLL%%j11 	%HIII$DKKKr0   c                 \    |"| j         dS t          j        t                    }|| _         dS )z* Enables a logger to send log messages to N)r1  logging	getLoggerr,   )r   loggers     r1   enable_loggerzClient.enable_loggeri  s/    >|'&x00Fr0   c                     d | _         d S r   )r1  r   s    r1   disable_loggerzClient.disable_loggerr  s    r0   r   r   r   c           	          | j         t          k    rd| _        n/|t          k    rt	          d          |dk    rt	          d          |                     |||||||           |                                 S )a  Connect to a remote broker.

        host is the hostname or IP address of the remote broker.
        port is 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.
        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.
        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.
        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 V5Nz Properties only apply to MQTT V5)r   r   rA  MQTT_CLEAN_START_FIRST_ONLYr   connect_async	reconnectr   hostr   	keepalivebind_address	bind_portclean_startr   s           r1   ry   zClient.connectu  s    & >V##)-D&&999 !FGGGT!! !CDDD4y'K	M 	M 	M~~r0   c           	         t           du rt          d          |3t          j                    }||                    d          dz   d         }	 d|z  }| j        rd|z  }g }t          j                            |t          j	        j
                  D ]K}|j                                        dd         }	|                    |	|j        |j        |j        f           LnK# t          j        j        t          j        j        t          j        j        f$ r t          d	|z            w xY w|D ]5}|\  }
}}}	 |                     |
|||||          c S # t*          $ r Y 2w xY wt          d
          )zConnect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive, bind_address, clean_start and properties are as for connect()
        FzXNo DNS resolver library found, try "pip install dnspython" or "pip3 install dnspython3".N.r   z_mqtt._tcp.%sz_secure-mqtt._tcp.%sr"   z No answer/NXDOMAIN for SRV in %szNo SRV hosts responded)HAVE_DNSr   rn   getfqdnfindr.  dnsresolverquery	rdatatypeSRVtargetto_textrY   r   priorityweightNXDOMAINNoAnswerNoNameserversry   	Exception)r   domainr  r  r  r   rranswersansweraddrr  r   prior  s                 r1   connect_srvzClient.connect_srv  s    ujl l l >^%%FFKK,,q0112F	L 6)By 5+f4G,,,R1BCC I I},,..ss36;GI I I II %s|'<cl>XY 	L 	L 	L?6JKKK	L  	 	F'-$D$f||D$	<V`aaaaa    1222s    BC AD&5E
EEc                    |t          |          dk    rt          d          |dk    rt          d          |dk     rt          d          |dk    r;|9t          j        dk     sdt          j        cxk     rd	k     rn nt          d
          |dk     rt          d          || _        || _        || _        || _        || _        || _	        || _
        t          | _        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.

        host is the hostname or IP address of the remote broker.
        port is 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.
        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.
        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.
        properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
        MQTT connect packet.  Use the Properties class.
        Nr   Invalid host.Invalid port number.zKeepalive must be >=0.rW   r   r    r   r   r   r   z(bind_address requires Python 2.7 or 3.2.zInvalid bind port number.)r\   r   sysversion_infor  r  r   r   r!  _clean_startr  mqtt_cs_connect_asyncr  r  s           r1   r  zClient.connect_async  s    ( <3t99>>_---1993444q==56662,":&((FS5E,N,N,N,N,N,N,N,N,N !KLLLq==8999

#)#'#- +r0   r   r   c                 p    | j         5  || _        || _        d| _        ddd           dS # 1 swxY w Y   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)r*  r  r	  r
  )r   	min_delay	max_delays      r1   reconnect_delay_setzClient.reconnect_delay_set  s     ( 	) 	)(1D%(1D%$(D!	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)s   +//c           	      @   t          | j                  dk    rt          d          | j        dk    rt          d          ddg ddt	          d          ddd| _        t          j                    | _        | j	        5  t                      | _        t                      | _        ddd           n# 1 swxY w Y   d| _        t          | _        |                                  |                                  |                                 }| j        r| j         }	 | j                            || j        d	          }t/          | j        d
          r| j        j        rd}n;# t2          j        $ r  t          $ r | j                            |d          }Y nw xY w|                    | j                   |                                 |r,t3          j        |                                | j                   | j         dk    rG|                    | j                   tC          || j        | j        | j        | j"        | j#                  }|| _$        | j$        %                    d           d| _&        | '                                 | (                    | j                  S )zdReconnect the client after a disconnect. Can only be called after
        connect()/connect_async().r   r  r  r   r0   r   NF)server_hostnamedo_handshake_on_connectri  )r  r   ))r\   r  r   r  r   r  r  r  r  r'  r  r  r  r  r  r  r\  _messages_reconnect_reset_create_socket_connectionr.  r0  r/  wrap_socketrj  ri  rN  CertificateError
settimeoutr   do_handshakematch_hostnamegetpeercertr   WebsocketWrapperr?  r@  r   rx   r2  _call_socket_open_send_connect)r   r[  verify_hosts      r1   r  zClient.reconnect  s    tz??a_---:??3444 ! !nn  ',..  	- 	- )D!*D	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- ! 	&&(((--//9 	C #00K((44$(J,1 5    D-/?@@ ()8("'K '      (44,1 5   OODO,,, C"4#3#3#5#5tzBBB?l**OODO,,,#D$*dj$)$($8$:WY YD 

q!!!!&   !!$/222s$   >'B11B58B5"E! !5FF      ?c                     | j         | j        1|                     d           t                      \  | _         | _        |                     |          S )am  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.

        timeout: The time in seconds to wait for incoming/outgoing network
            traffic before timing out and returning.
        max_packets: Not currently used.

        Returns MQTT_ERR_SUCCESS on success.
        Returns >0 on error.

        A ValueError will be raised if timeout < 0NT)r^  )r   r   rJ  r   _loop)r   r   max_packetss      r1   loopzClient.loopB  sP    4 ?"do&=d333/A/C/C,DOT_zz'"""r0   c                    |dk     rt          d          	 | j                                        }| j                            |           | j        g}n# t
          $ r g }Y nw xY wd}t          | j        d          r| j                                        }|dk    rd}| j        	| j        g}n| j        | j        g}	 t          j	        ||g |          }n;# t          $ r
 t          cY S t           $ r
 t          cY S t          $ r
 t          cY S w xY w| j        |d         v s|dk    r|                                 }|s| j        |S | j        r\| j        |d         v rM|d                             d| j                   	 | j                            d           n# t"          $ r Y nw xY w| j        |d         v r|                                 }|s| j        |S |                                 S )Ng        zInvalid timeout.r   pendingr   i'  )r   r  popleft
appendleftr   r   rj  r  r   select	TypeErrorr;   r  rA   	loop_readinsertrM  rz   
loop_write	loop_misc)r   r   r   wlistpending_bytesrlistsocklistr   s           r1   r  zClient._loopb  s]   S==/000	%--//F''///ZLEE 	 	 	EEE	 4:y)) 	1 J..00M 1G ?"ZLEEZ1E	$}UE2w??HH 	& 	& 	&%%%% 	& 	& 	& &%%% 	$ 	$ 	$ $###	$
 :!$$(9(9!!B TZ'	? 
	t(1+== QKq$*--- $$U++++"    :!$$""B TZ'	~~sA   ;A A"!A"<C D'D9DD;F 
F#"F#c                 
   | j         t          k    r$|t          |          dk    rt          d          |                    d          }|                     |          t          k    rt          d          |dk     s|dk    rt          d          t          |t                    r|                    d          }nrt          |t          t          f          r|}nSt          |t          t          f          r#t          |                              d          }n|d	}nt          d
          t          |          dk    rt          d          |                                 }|dk    r4t!          |          }|                     |||||d||          }	|	|_        |S t'          ||          }
t)                      |
_        ||
_        ||
_        ||
_        d|
_        ||
_        | j        5  | j        dk    rAt          | j                  | j        k    r$t<          |
j        _        |
j        cddd           S || j        v r$t<          |
j        _        |
j        cddd           S |
| j        |
j         <   | j!        dk    s| j"        | j!        k     r| xj"        dz  c_"        |dk    rtF          |
_$        n|dk    rtJ          |
_$        |                     |
j         ||
j        |
j        |
j        |
j        |
j        |
j                  }	|	tL          u r| xj"        dz  c_"        tN          |
_$        |	|
j        _        |
j        cddd           S tP          |
_$        t          |
j        _        |
j        cddd           S # 1 swxY w Y   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.

        topic: The topic that the message should be published on.
        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.
        qos: The quality of service level to use.
        retain: If set to true, the message will be set as the "last known
        good"/retained message for the topic.
        properties: (MQTT v5.0 only) the MQTT v5.0 properties to be included.
        Use the Properties class.

        Returns a MQTTMessageInfo class, which can be used to determine whether
        the message has been delivered (using info.is_published()) or to block
        waiting for the message to be delivered (info.wait_for_publish()). The
        message ID and return code of the publish() call can be found at
        info.mid and info.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.

        A ValueError will be raised 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.

        A ValueError will be raised if qos is not one of 0, 1 or 2, or if
        the length of the payload is greater than 268435455 bytes.Nr   Invalid topic.r   z'Publish topic cannot contain wildcards.r   Invalid QoS level.asciir0   8payload must be a string, bytearray, int, float or None.ir3   Fr   ))r   r   r\   r   r   _topic_wildcard_len_checkr4   r   r   bytesr   r   floatr   r  _mid_generater   _send_publishr   r   r  r   r   r   r   r   r   r(  r  r  rC   r   r   r  r  mqtt_ms_wait_for_pubackr   mqtt_ms_wait_for_pubrecr8   mqtt_ms_publishmqtt_ms_queued)r   ri   r   r   r   r   local_payload	local_midr   r   messages              r1   publishzClient.publish  s   N >V##}E

a !1222W%%))%004DDDFGGG77cAgg1222gw'' 
	L#NN733MM%!344 	L#MM#u.. 	LLL//88MM_MMJL L L }	))1222&&((	!88"9--D##5-feT:W WBDGK!)U33G )G+GOGK#GNGK!+G( ( (,q00S9K5L5LPTPi5i5i&9GLO"<( ( ( ( ( ( ( (
  222&9GLO"<( ( ( ( ( ( ( ( 3:"7;/.!33t7NQUQl7l7l++q0++axx(?(?++GKQXQ\^e^l,3KwGY[ [B ---//14//(7&(GLO"<5( ( ( ( ( ( ( (8 %3GM&6GLO"<=( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (s&   ,A M89 M8&CM8#M88M<?M<c                     |dn|                     d          | _        || _        t          | j        t                    r!| j                             d          | _        dS dS )aN  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.

        username: The username to authenticate with. Need have no relationship to the client id. Must be unicode
            [MQTT-3.1.3-11].
            Set to None to reset client back to not using username/password for broker authentication.
        password: The password to authenticate with. Optional, set to None if not required. If it is unicode, then it
            will be encoded as UTF-8.
        Nr   )r   r   r   r   r   )r   usernamepasswords      r1   username_pw_setzClient.username_pw_set  s`     "*!1xw7O7O!dng.. 	<!^227;;DNNN	< 	<r0   c                     t           | _        dS )aM  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   r   s    r1   enable_bridge_modezClient.enable_bridge_mode)  s     (r0   c                 "    | j         t          k    S )z~Returns the current status of the connection

        True if connection exists
        False if connection is closed
        )r  mqtt_cs_connectedr   s    r1   is_connectedzClient.is_connected9  s     {///r0   c                 b    t           | _        | j        t          S |                     ||          S )a  Disconnect a connected client from the broker.
        reasoncode: (MQTT v5.0 only) a ReasonCodes instance setting the MQTT v5.0
        reasoncode to be sent with the disconnect.  It is optional, the receiver
        then assuming that 0 (success) is the value.
        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.
        )mqtt_cs_disconnectingr  r   r8   _send_disconnect)r   
reasoncoder   s      r1   
disconnectzClient.disconnectA  s/     ,:##$$Z<<<r0   c                 ~    d}t          |t                    r? j        t          k    r*|\  }}t          |t                    st          d          n|\  }}t          |t                    r|dk     s|dk    rt          d           j        t          k    rf|t	          |          }n|dk    rt          d          t          |t                    st          d          |                    d          |fg}n_|t          |          dk    rt          d	          |                    d          |fg}n!t          |t                    rg } j        t          k    rs|D ]o\  }}t          |t                    s+|dk     s|dk    rt          d          t	          |          }|
                    |                    d          |f           pn|D ]\  }}|dk     s|dk    rt          d          |(t          |          dk    st          |t                    st          d	          |
                    |                    d          |f           |t          d
          t           fd|D                       rt          d           j        	t          dfS                      d||          S )aL  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  )r   z8Subscribe options and qos parameters cannot be combined.r   r  ,No topic specified, or incorrect topic type.c              3   Z   K   | ]%\  }}                     |          t          k    V  &d S r   )_filter_wildcard_len_checkr4   )rS   ri   rT   r   s      r1   rV   z#Client.subscribe.<locals>.<genexpr>  s<      iiheUVt..u559IIiiiiiir0   zInvalid subscription filter.F)r   tupler   r   r   r   
basestringr   r\   listrY   anyr   r8   _send_subscribe)	r   ri   r   optionsr   topic_qos_listtoqs	   `        r1   	subscribezClient.subscribeP  s   ` eU## 	#~''!&w!'+;<< Y$WY Y YY #
seZ(( "	BQww#'' !5666~''?.3777GGAXX$RT T T!'+;<< Y$WY Y Y#(<<#8#8'"B!C=CJJ!OO$%5666#(<<#8#8#">!?t$$ 	BN~''! B BDAq%a)9:: 4q55AEE",-A"B"BB,333"))188G+<+<a*@AAAAB " B BDAq1uuA()=>>>yCFFaKKz!Z7P7PK()9:::"))188G+<+<a*@AAAA!KLLLiiiiZhiiiii 	=;<<<:$d++##E>:FFFr0   c                 *   d}|t          d          t          |t                    r9t          |          dk    rt          d          |                    d          g}n{t          |t
                    rfg }|D ]a}t          |          dk    st          |t                    st          d          |                    |                    d                     b|t          d          | j        	t          dfS | 	                    d||          S )aR  Unsubscribe the client from one or more topics.

        topic: A single string, or list of strings that are the subscription
               topics to unsubscribe from.
        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 a ValueError if topic is None or has zero string length, or is
        not a string or list.
        Nr  r   r   r  F)
r   r   r  r\   r   r  rY   r   r8   _send_unsubscribe)r   ri   r   
topic_listr  s        r1   unsubscribezClient.unsubscribe  s   $ 
=-...eZ(( 		55zzQ !1222,,w//0JJt$$ 	5J 5 5q66Q;;jJ&?&?;$%5666!!!((7"3"34444KLLL:$d++%%eZDDDr0   c                 ^   | j         t          S t          | j                  t          | j                  z   }|dk     rd}t          d|          D ]W}| j         	t          c S |                                 }|dk    r|                     |          c S |t          k    r	t          c S Xt          S )a3  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 the threaded interface loop_start().Nr   r   )
r   r8   r\   r  r  r[   _packet_read_loop_rc_handler   r4   )r   r  rT   r   s       r1   r  zClient.loop_read  s     :##$,--D4E0F0FF??Kq+&& 	( 	(Az!''''""$$BAvv++B/////~%%'''' &r0   c                    | j         t          S 	 |                                 }|t          k    rDt          |                                 r|                                  S |                                  S |dk    rR|                     |          |                                 r|                                  S |                                  S t          |                                 r|                                  S |                                  S # |                                 r|                                  w |                                  w xY w)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 the threaded interface loop_start().Nr   )	r   r8   _packet_writer   r4   
want_writerQ  rY  r  )r   r  r   s      r1   r  zClient.loop_write  sQ    :##	5##%%B^##'    5002222224444 a++B//    5002222224444 (   5002222224444    5002222224444s   %D 3D D ?Ec                     	 | j                                         }| j                             |           dS # t          $ r Y dS w xY w)zCall to determine if there is network data waiting to be written.
        Useful if you are calling select() yourself rather than using loop().
        TF)r  r  r  r   )r   r   s     r1   r  zClient.want_write6  sY    	%--//F''///4 	 	 	55	s   37 
AAc                 J   | j         t          S t                      }|                                  | j        dk    rb|| j        z
  | j        k    rO|                                  | j        t          k    rt          }nt          }|                     |           t          S t          S )zProcess 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 the threaded interface loop_start().Nr   )r   r8   r  _check_keepaliver  r   r\  r  r  r4   rD   _do_on_disconnectr;   )r   nowr   s      r1   r  zClient.loop_miscA  s    
 :##kk<!dl 2do E E {333%'""2&&&%%r0   c                 >    |dk     rt          d          || _        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.r   zInvalid inflight.N)r   r  )r   inflights     r1   max_inflight_messages_setz Client.max_inflight_messages_set\  s*     a<<0111&.###r0   c                     |dk     rt          d          t          |t                    st          d          || _        | S )z\Set the maximum number of messages in the outgoing message queue.
        0 means unlimited.r   zInvalid queue size.zInvalid type of queue size.)r   r   r   r  )r   
queue_sizes     r1   max_queued_messages_setzClient.max_queued_messages_setc  sJ     >>2333*c** 	<:;;;$.!r0   c                     dS )z%No longer used, remove in version 2.0Nr/   )r   retrys     r1   message_retry_setzClient.message_retry_setm  s    r0   c                     || _         dS )zESet the user data variable passed to callbacks. May be any data type.N)r   )r   rE  s     r1   user_data_setzClient.user_data_setq  s    !r0   c                    |t          |          dk    rt          d          |dk     s|dk    rt          d          |dk    r$t          |t                    st          d          t          |t                    r|                    d          | _        nt          |t          t          f          r|| _        n]t          |t          t          f          r(t          |                              d          | _        n|d	| _        nt          d
          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.

        topic: The topic that the will message should be published on.
        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.
        qos: The quality of service level to use for the will.
        retain: If set to true, the will message will be set as the "last known
        good"/retained message for the topic.
        properties: (MQTT v5.0 only) a Properties instance setting the MQTT v5.0 properties
        to be included with the will message. Optional - if not set, no properties are sent.

        Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has
        zero string length.
        Nr   r  r   r  zDThe properties argument must be an instance of the Properties class.r   r  r0   r  T)r\   r   r   r   r   r   r  r  r   r   r  r   r  r  r  r  r  r  )r   ri   r   r   r   r   s         r1   will_setzClient.will_setu  s_   ( =CJJ!OO-...77cAgg1222jZ&H&HVX X X gw'' 
	L!(!8!8D%!344 	L!(D#u.. 	L!$W!4!4W!=!=D_!$DJL L L 
 <<00" *r0   c                 L    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.Fr0   r   N)r  r  r  r  r  r   s    r1   
will_clearzClient.will_clear  s0     
 !r0   c                     | j         S )z0Return the socket or ssl object for this client.)r   r   s    r1   rn   zClient.socket  s
    zr0   c                 J    dr j         du rn j        t          k    rs	                                   n^# t          t
          f$ rI                                   |s                      t          d            	                                 Y nw xY wnr	t          }|t          k    r]                     |          } j         du r4t           j                  dk    rt           j                  dk    rd}d|t          k    ] fd} |            s j        sdn} 	                                  |            rdn\	                                   nF# t          t
          f$ r2                                                        t          d           Y nw xY w	|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.


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

        Raises OSError/WebsocketConnectionError on first connection failures unless retry_first_connection=True
        TzConnection failed, retryingr   r   Fc                  >    j         t          k    p du pj        du S )NFT)r  r  r-  )runr   s   r1   should_exitz(Client.loop_forever.<locals>.should_exit  s(    {&;;mse|mtOeimOmmr0   )r-  r  r  r  OSErrorr+   _handle_on_connect_fail	_easy_logMQTT_LOG_DEBUG_reconnect_waitr4   r  r\   r  r  r  )r   r   r  retry_first_connectionr   r3  r2  s   `     @r1   loop_foreverzClient.loop_forever  sL   &  	%--{333+NN$$$$!9: + + +002221 NN&(EG G G((*****+   	"  	K!B(((ZZ((
 *d22D,--22 233q88BC (((n n n n n n {}} KD$> K$$&&&;== KCCK((((#%=> K K K44666*,IK K K K KK7  	K@ 	s#   7 ABBE A FFc                     | j         t          S t                      \  | _        | _        d| _        t          j        | j                  | _         d| j         _	        | j         
                                 dS )zThis 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.
        NF)r  T)r,  r7   r   r   r   r-  r   Thread_thread_maindaemonstartr   s    r1   
loop_startzClient.loop_start  sj    
 <#!!+=+?+?(!& 't/@AAA"r0   c                     | j         t          S d| _        t          j                    | j         k    r"| j                                          d| _         dS dS )a  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.

        The force parameter is currently ignored.
        NT)r,  r7   r-  r   current_threadr]   )r   forces     r1   	loop_stopzClient.loop_stop	  sW     <!!!%#%%55LDLLL 65r0   c                     | j         S )z_If implemented, called when the client has log information.
        Defined to allow debugging.r3  r   s    r1   on_logzClient.on_log  s     |r0   c                     || _         dS )a   Define the logging callback implementation.

        Expected signature is:
            log_callback(client, userdata, level, buf)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        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.
        buf:        the message itself

        Decorator: @client.log_callback() (```client``` is the name of the
            instance which this callback is being attached to)
        NrF  r   funcs     r1   rG  zClient.on_log  s    " r0   c                       fd}|S )Nc                     | _         | S r   )rG  rJ  r   s    r1   	decoratorz&Client.log_callback.<locals>.decorator2  s    DKKr0   r/   r   rN  s   ` r1   log_callbackzClient.log_callback1  $    	 	 	 	 	 r0   c                     | j         S )zRIf implemented, called when the broker responds to our connection
        request.)r4  r   s    r1   
on_connectzClient.on_connect7  s     r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a   Define the connect callback implementation.

        Expected signature for MQTT v3.1 and v3.1.1 is:
            connect_callback(client, userdata, flags, rc)

        and for MQTT v5.0:
            connect_callback(client, userdata, flags, reasonCode, properties)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        flags:      response flags sent by the broker
        rc:         the connection result
        reasonCode: the MQTT v5.0 reason code: an instance of the ReasonCode class.
                    ReasonCode may be compared to integer.
        properties: the MQTT v5.0 properties returned from the broker.  An instance
                    of the Properties class.
                    For MQTT v3.1 and v3.1.1 properties is not provided but for compatibility
                    with MQTT v5.0, we recommend adding properties=None.

        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)

        N)r&  r4  rI  s     r1   rS  zClient.on_connect=  sz    R ! 	$ 	$#D	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$   !!c                       fd}|S )Nc                     | _         | S r   )rS  rM  s    r1   rN  z*Client.connect_callback.<locals>.decoratorj      "DOKr0   r/   rO  s   ` r1   connect_callbackzClient.connect_callbacki  rQ  r0   c                     | j         S )zOIf implemented, called when the client failed to connect
        to the broker.)r5  r   s    r1   on_connect_failzClient.on_connect_failo  s     $$r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a   Define the connection failure callback implementation

        Expected signature is:
            on_connect_fail(client, userdata)

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

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

        N)r&  r5  rI  s     r1   r[  zClient.on_connect_failu  sy     ! 	) 	)$(D!	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)rU  c                       fd}|S )Nc                     | _         | S r   )r[  rM  s    r1   rN  z/Client.connect_fail_callback.<locals>.decorator      #'D Kr0   r/   rO  s   ` r1   connect_fail_callbackzClient.connect_fail_callback  rQ  r0   c                     | j         S )zOIf implemented, called when the broker responds to a subscribe
        request.)r6  r   s    r1   on_subscribezClient.on_subscribe  s     !!r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a   Define the subscribe callback implementation.

        Expected signature for MQTT v3.1.1 and v3.1 is:
            subscribe_callback(client, userdata, mid, granted_qos)

        and for MQTT v5.0:
            subscribe_callback(client, userdata, mid, reasonCodes, properties)

        client:         the client instance for this callback
        userdata:       the private user data as set in Client() or userdata_set()
        mid:            matches the mid variable returned from the corresponding
                        subscribe() call.
        granted_qos:    list of integers that give the QoS level the broker has
                        granted for each of the different subscription requests.
        reasonCodes:    the MQTT v5.0 reason codes received from the broker for each
                        subscription.  A list of ReasonCodes instances.
        properties:     the MQTT v5.0 properties received from the broker.  A
                        list of Properties class instances.

        Decorator: @client.subscribe_callback() (```client``` is the name of the
            instance which this callback is being attached to)
        N)r&  r6  rI  s     r1   rb  zClient.on_subscribe  sy    0 ! 	& 	&!%D	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&rU  c                       fd}|S )Nc                     | _         | S r   )rb  rM  s    r1   rN  z,Client.subscribe_callback.<locals>.decorator  s     $DKr0   r/   rO  s   ` r1   subscribe_callbackzClient.subscribe_callback  rQ  r0   c                     | j         S )a#  If implemented, called when a message has been received on a topic
        that the client subscribes to.

        This callback will be called for every message received. Use
        message_callback_add() to define multiple callbacks that will be called
        for specific topic filters.)r7  r   s    r1   
on_messagezClient.on_message  s     r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a1   Define the message received callback implementation.

        Expected signature is:
            on_message_callback(client, userdata, message)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        message:    an instance of MQTTMessage.
                    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)

        N)r&  r7  rI  s     r1   rh  zClient.on_message  y      ! 	$ 	$#D	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$rU  c                       fd}|S )Nc                     | _         | S r   )rh  rM  s    r1   rN  z*Client.message_callback.<locals>.decorator  rX  r0   r/   rO  s   ` r1   message_callbackzClient.message_callback  rQ  r0   c                     | j         S )a  If implemented, 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.)r8  r   s    r1   
on_publishzClient.on_publish  s     r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )aK   Define the published message callback implementation.

        Expected signature is:
            on_publish_callback(client, userdata, mid)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        mid:        matches the mid variable returned from the corresponding
                    publish() call, to allow outgoing messages to be tracked.

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

        N)r&  r8  rI  s     r1   ro  zClient.on_publish  rj  rU  c                       fd}|S )Nc                     | _         | S r   )ro  rM  s    r1   rN  z*Client.publish_callback.<locals>.decorator  rX  r0   r/   rO  s   ` r1   publish_callbackzClient.publish_callback  rQ  r0   c                     | j         S )zRIf implemented, called when the broker responds to an unsubscribe
        request.)r9  r   s    r1   on_unsubscribezClient.on_unsubscribe  s     ##r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a   Define the unsubscribe callback implementation.

        Expected signature for MQTT v3.1.1 and v3.1 is:
            unsubscribe_callback(client, userdata, mid)

        and for MQTT v5.0:
            unsubscribe_callback(client, userdata, mid, properties, reasonCodes)

        client:         the client instance for this callback
        userdata:       the private user data as set in Client() or userdata_set()
        mid:            matches the mid variable returned from the corresponding
                        unsubscribe() call.
        properties:     the MQTT v5.0 properties received from the broker.  A
                        list of Properties class instances.
        reasonCodes:    the MQTT v5.0 reason codes received from the broker for each
                        unsubscribe topic.  A list of ReasonCodes instances

        Decorator: @client.unsubscribe_callback() (```client``` is the name of the
            instance which this callback is being attached to)
        N)r&  r9  rI  s     r1   ru  zClient.on_unsubscribe  sy    , ! 	( 	(#'D 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(rU  c                       fd}|S )Nc                     | _         | S r   )ru  rM  s    r1   rN  z.Client.unsubscribe_callback.<locals>.decorator      "&DKr0   r/   rO  s   ` r1   unsubscribe_callbackzClient.unsubscribe_callback  rQ  r0   c                     | j         S )zLIf implemented, called when the client disconnects from the broker.
        )r:  r   s    r1   on_disconnectzClient.on_disconnect   s     ""r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a   Define the disconnect callback implementation.

        Expected signature for MQTT v3.1.1 and v3.1 is:
            disconnect_callback(client, userdata, rc)

        and for MQTT v5.0:
            disconnect_callback(client, userdata, reasonCode, properties)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        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)

        N)r&  r:  rI  s     r1   r|  zClient.on_disconnect&  sy    , ! 	' 	'"&D	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	'rU  c                       fd}|S )Nc                     | _         | S r   )r|  rM  s    r1   rN  z-Client.disconnect_callback.<locals>.decorator@  s    !%DKr0   r/   rO  s   ` r1   disconnect_callbackzClient.disconnect_callback?  rQ  r0   c                     | j         S )z7If implemented, called just after the socket was opend.)r;  r   s    r1   on_socket_openzClient.on_socket_openE  s     ##r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )aA  Define the socket_open callback implementation.

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

        Expected signature is:
            socket_open_callback(client, userdata, socket)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        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)
        N)r&  r;  rI  s     r1   r  zClient.on_socket_openJ  sy      ! 	( 	(#'D 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(rU  c                       fd}|S )Nc                     | _         | S r   )r  rM  s    r1   rN  z.Client.socket_open_callback.<locals>.decorator^  ry  r0   r/   rO  s   ` r1   socket_open_callbackzClient.socket_open_callback]  rQ  r0   c                 B   | j         5  | j        }ddd           n# 1 swxY w Y   |rv| j        5  	  || | j        | j                   n;# t
          $ r.}|                     t          d|           | j        s Y d}~nd}~ww xY wddd           dS # 1 swxY w Y   dS dS )z9Call the socket_open callback with the just-opened socketNz&Caught exception in on_socket_open: %s)	r&  r  r$  r   r   r  r6  MQTT_LOG_ERRrB  )r   r  errs      r1   r  zClient._call_socket_openc  sq   ! 	1 	1!0N	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1  	(  "N4DDDD    NN$&NPSU U U3                      	 	sF     BA
	B

B$A=8B=BBBBc                     | j         S )z8If implemented, called just before the socket is closed.)r<  r   s    r1   on_socket_closezClient.on_socket_closer  s     $$r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )aN  Define the socket_close callback implementation.

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

        Expected signature is:
            socket_close_callback(client, userdata, socket)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        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)
        N)r&  r<  rI  s     r1   r  zClient.on_socket_closew  sy      ! 	) 	)$(D!	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)rU  c                       fd}|S )Nc                     | _         | S r   )r  rM  s    r1   rN  z/Client.socket_close_callback.<locals>.decorator  r_  r0   r/   rO  s   ` r1   socket_close_callbackzClient.socket_close_callback  rQ  r0   c                 8   | j         5  | j        }ddd           n# 1 swxY w Y   |rq| j        5  	  || | j        |           n;# t          $ r.}|                     t          d|           | j        s Y d}~nd}~ww xY wddd           dS # 1 swxY w Y   dS dS )zACall the socket_close callback with the about-to-be-closed socketNz'Caught exception in on_socket_close: %s)r&  r  r$  r   r  r6  r  rB  )r   r[  r  r  s       r1   rZ  zClient._call_socket_close  so   ! 	3 	3"2O	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3  	(  #OD$.$????    NN$&OQTV V V3                      	 	sF     BAB
A=$A83B8A==BBBc                     | j         S )z?If implemented, called when the socket needs writing but can't.r=  r   s    r1   on_socket_register_writezClient.on_socket_register_write  s     --r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )aq  Define the socket_register_write callback implementation.

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

        Expected signature is:
            socket_register_write_callback(client, userdata, socket)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        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)
        N)r&  r=  rI  s     r1   r  zClient.on_socket_register_write  sy      ! 	2 	2-1D*	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2rU  c                       fd}|S )Nc                     | _         | S r   r  rM  s    r1   rN  z8Client.socket_register_write_callback.<locals>.decorator  s    -1D*Kr0   r/   rO  s   ` r1   socket_register_write_callbackz%Client.socket_register_write_callback  rQ  r0   c                 0   | j         r| j        rdS d| _        | j        5  | j        }ddd           n# 1 swxY w Y   |rV	  || | j        | j                    dS # t
          $ r/}|                     t          d|           | j        s Y d}~dS d}~ww xY wdS )zBCall the socket_register_write callback with the unwritable socketNTz0Caught exception in on_socket_register_write: %s)	r   r2  r&  r  r   r  r6  r  rB  )r   r  r  s      r1   rQ  z"Client._call_socket_register_write  sK   z 	T3 	F!%! 	E 	E'+'D$	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E $ 	(($.$*6 6 6 6 6    "TVY[ [ [/      		 	s$   377A 
B$$BBc                     | j         S )zDIf implemented, called when the socket doesn't need writing anymore.r>  r   s    r1   on_socket_unregister_writez!Client.on_socket_unregister_write  s     //r0   c                 T    | j         5  || _        ddd           dS # 1 swxY w Y   dS )a{  Define the socket_unregister_write callback implementation.

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

        Expected signature is:
            socket_unregister_write_callback(client, userdata, socket)

        client:     the client instance for this callback
        userdata:   the private user data as set in Client() or userdata_set()
        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)
        N)r&  r>  rI  s     r1   r  z!Client.on_socket_unregister_write  sy      ! 	4 	4/3D,	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4rU  c                       fd}|S )Nc                     | _         | S r   r  rM  s    r1   rN  z:Client.socket_unregister_write_callback.<locals>.decorator  s    /3D,Kr0   r/   rO  s   ` r1    socket_unregister_write_callbackz'Client.socket_unregister_write_callback  rQ  r0   c                 .   |p| j         }|r| j        sdS d| _        | j        5  | j        }ddd           n# 1 swxY w Y   |rQ	  || | j        |           dS # t
          $ r/}|                     t          d|           | j        s Y d}~dS d}~ww xY wdS )zBCall the socket_unregister_write callback with the writable socketNFz2Caught exception in on_socket_unregister_write: %s)	r   r2  r&  r  r   r  r6  r  rB  )r   r[  r  r  s       r1   rY  z$Client._call_socket_unregister_write  sH   !tz 	41 	F!&! 	I 	I)-)H&	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I & 	**4FFFFF    "VX[] ] ]/      	 	s$   7;;A 
B#$BBc                     ||t          d          | j        5  || j        |<   ddd           dS # 1 swxY w Y   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().Nz&sub and callback must both be defined.)r   r&  r  )r   rh   callbacks      r1   message_callback_addzClient.message_callback_add 	  s     s{EFFF! 	6 	6-5D%c*	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6s   377c                       fd}|S )Nc                 4                         |            | S r   )r  )rJ  r   rh   s    r1   rN  z(Client.topic_callback.<locals>.decorator	  s    %%c4000Kr0   r/   )r   rh   rN  s   `` r1   topic_callbackzClient.topic_callback	  s*    	 	 	 	 	 	 r0   c                     |t          d          | j        5  	 | j        |= n# t          $ r Y nw xY wddd           dS # 1 swxY w Y   dS )zTRemove a message callback previously registered with
        message_callback_add().Nzsub must defined.)r   r&  r  KeyError)r   rh   s     r1   message_callback_removezClient.message_callback_remove	  s     ;0111! 	 	-c22   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s,   A$A
1A1AAAc                     |rA|                                   | j        t          k    rt          }|                     ||           |S r   )r\  r  r  r4   r  )r   r   r   s      r1   r  zClient._loop_rc_handle'	  sJ     	3{333%""2z222	r0   c           	      :   | j         d         dk    r	 |                     d          }t          |          dk    rt          S t	          j        d|          \  }|| j         d<   nL# t          $ r
 t          cY S t          $ r-}| 	                    t          d|           t          cY d }~S d }~ww xY w| j         d         dk    rC	 	 |                     d          }t          |          dk    rt          S t	          j        d|          \  }| j         d                             |           t          | j         d                   d	k    rt          S | j         d
xx         |dz  | j         d         z  z  cc<   | j         d         dz  | j         d<   nL# t          $ r
 t          cY S t          $ r-}| 	                    t          d|           t          cY d }~S d }~ww xY w|dz  dk    rn#d| j         d<   | j         d
         | j         d<   d}| j         d         dk    r	 |                     | j         d                   }t          |          dk    rt          S | j         dxx         t          |          z  cc<   | j         dxx         |z  cc<   nL# t          $ r
 t          cY S t          $ r-}| 	                    t          d|           t          cY d }~S d }~ww xY w|dz  }|dk    r9| j        5  t                      | _        d d d            n# 1 swxY w Y   t          S | j         d         dk    d| j         d<   |                                 }ddg ddt#          d          ddd| _         | j        5  t                      | _        d d d            n# 1 swxY w Y   |S )Nr   r   r   z!Bfailed to receive on socket: %sr   Tr   r   r      r   r   r   d   r   r   r0   r   )r  rS  r\   r;   structunpackrz   r   ConnectionErrorr6  r  rY   r6   r'  r  r  _packet_handler   )r   r   r  bytecountdatar   s          r1   r  zClient._packet_read2	  s    ?9%**5//!,, w<<1$$--!=w77-4	** # & & &%%%%" * * * "CSJ J J)))))))* ?+,11`??1--D 4yyA~~11"M$55EDO$56==dCCC 4?+<=>>BB00O$6777s
do6F&G<H H7778<HX8Y\_8_DO$455% ' * * *))))& . . .NN$&GN N N-------.$ 3J1$$14 12DO,-,0O<N,ODOL)ol+a//2t|'DEE t99>>-----T:---)))T1)))) # & & &%%%%" * * * "CSJ J J)))))))* QJEzz( 4 4(1D%4 4 4 4 4 4 4 4 4 4 4 4 4 4 4%%% ol+a//* "#  "" ! !nn    	, 	, )D	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	,	s   A$ $B-7	B- "B("B-(B-F G!	G*"GGG J K	K("K
KK*L

LL0NNNc                    	 	 | j                                         }n# t          $ r
 t          cY S w xY w	 |                     |d         |d         d                    }n# t
          t          f$ r$ | j                             |           t          cY S t          $ r$ | j                             |           t          cY S t          $ rG}| j                             |           |                     t          d|           t          cY d }~S d }~ww xY w|dk    r|dxx         |z  cc<   |dxx         |z  cc<   |d         dk    rR|d         dz  t          k    r|d	         dk    r| j        5  | j        }d d d            n# 1 swxY w Y   |rt| j        5  	  || | j        |d
                    n;# t&          $ r.}|                     t          d|           | j        s Y d }~nd }~ww xY wd d d            n# 1 swxY w Y   |d                                          |d         dz  t,          k    rg| j        5  t1                      | _        d d d            n# 1 swxY w Y   |                     t                     |                                  t          S n| j                             |           nn| j        5  t1                      | _        d d d            n# 1 swxY w Y   t          S )NTr   r   r  r   r   r   r   r   r   "Caught exception in on_publish: %sr   )r  r  r   r4   rW  AttributeErrorr   r  rz   r   r  r6  r  r;   PUBLISHr&  ro  r$  r   r  rB  r   
DISCONNECTr'  r  r  r  r\  )r   r   write_lengthr  ro  s        r1   r  zClient._packet_write	  s   7	()1133 ( ( (''''(*#8$VE]^^4 6  6"J/ ( ( ( ++F333''''" & & & ++F333%%%%" * * * ++F333 "CSJ J J)))))))	* a|$$$4$$$u-,'1,,y)D0W<<RSASAS!1 9 9)-J9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 & 	.!%!8 . .!.$.J(,dnfUm%M %M %M %M'0 !. !. !.$(NN(46Z\_%a %a %a+/+C %.(-%. %. %. %. %.!.	. . . . . . . . . . . . . . . v88:::y)D0Z??!0 = =1:D.= = = = = = = = = = = = = = = ../?@@@((***// @ $//7777o7	r   	- 	-!*D	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-  s    11)A 2D*D?	D<D
D
D-FFFG7F0/G70
G(:$G#G7#G((G77G;>G;7III=KK!$K!c                     | j         4||z  }	 |                      | | j        ||           n# t          $ r Y nw xY w| j        #t          |         } | j        j        ||g|R   d S d S r   )rG  r   r  r1  LOGGING_LEVELlog)r   levelfmtargsrV  	level_stds         r1   r6  zClient._easy_log	  s    ;"*CD$.%====    <#%e,IDLY3d333333 $#s   , 
99c                    | j         dk    rt          S t                      }| j        5  | j        }| j        }d d d            n# 1 swxY w Y   | j        ||z
  | j         k    s||z
  | j         k    r| j        t          k    r| j	        dk    r	 | 
                                 | j        5  || _        || _        d d d            d S # 1 swxY w Y   d S # t          $ r2 |                                  |                     t                     Y d S w xY w|                                  | j        t          k    rt          }nt           }|                     |           d S d S d S r   )r   r4   r  r'  r  r  r   r  r  r  _send_pingreqr  r\  r  r;   r  rD   )r   r  last_msg_outlast_msg_inr   s        r1   r  zClient._check_keepalive	  s   ?a##kk  	, 	,-L+K	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, :!s\'9T_'L'LPSVaPaeietPtPt{///DLA4E4E0&&(((
 , 0 0-0*,/)0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0	 ! ? ? ?$$&&&**+=>>>>>>?   """;"777)BB+B&&r*****' "!PtPts5   AA
AC )CC	C	8DDc                     | j         5  | xj        dz  c_        | j        dk    rd| _        | j        cd d d            S # 1 swxY w Y   d S )Nr      )r+  r  r   s    r1   r  zClient._mid_generate
  s    % 	" 	"NNaNN~&&!">		" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"s   )>AAc                 T    d| v sd| v st          |           dk    rt          S t          S )N   +   #  )r\   r7   r4   )ri   s    r1   r  z Client._topic_wildcard_len_check	
  s1    
 5==DEMMSZZ%-?-?!!##r0   c                     t          |           dk    sCt          |           dk    s0t          d |                     d          D                       sd| v rt          S t          S )Nr   r  c              3   L   K   | ]}t          |          d k    d|v pd|v V   dS )r   r  r  N)r\   )rS   ps     r1   rV   z4Client._filter_wildcard_len_check.<locals>.<genexpr>
  s9      QQac!ffqjj419)	jjjjQQr0      /s   #/)r\   r	  splitr7   r4   )rh   s    r1   r  z!Client._filter_wildcard_len_check
  s_    HHMMSXX--QQ399T??QQQQQ .C<<!!##r0   c                     |                      t          d           |                     t                    }|t          k    rt                      | _        |S )NzSending PINGREQ)r6  r7  _send_simple_commandPINGREQr4   r  r  )r   r   s     r1   r  zClient._send_pingreq
  sF    ~'8999&&w//!!!$;;DL	r0   c                 l    |                      t          d           |                     t                    S )NzSending PINGRESP)r6  r7  r  PINGRESPr   s    r1   _send_pingrespzClient._send_pingresp#
  s+    ~'9:::((222r0   c                 r    |                      t          d|           |                     t          |d          S )NzSending PUBACK (Mid: %d)F)r6  r7  _send_command_with_midPUBACKr   s     r1   _send_pubackzClient._send_puback'
  1    ~'A3GGG**63>>>r0   c                 r    |                      t          d|           |                     t          |d          S )NzSending PUBCOMP (Mid: %d)F)r6  r7  r  PUBCOMPr   s     r1   _send_pubcompzClient._send_pubcomp+
  s1    ~'BCHHH**7C???r0   c                     g }	 |dz  }|dz  }|dk    r|dz  }|                     |           |                     |           |dk    r|S H)NTr   r   )rY   )r   r   r   remaining_bytesr  s        r1   _pack_remaining_lengthzClient._pack_remaining_length/
  sp    	#c)D/36!##""4(((MM$1$$	r0   c                     t          |t                    r|                    d          }|                    t	          j        dt          |                               |                    |           d S )Nr   !H)r   r   r   rZ   r  packr\   )r   r   r  s      r1   _pack_str16zClient._pack_str16>
  sa    dG$$ 	(;;w''Dfk$D		22333dr0   r0   c	                    t          |t                    st          |t                    s|J | j        t          S t          |dz  dz  z  |dz  z  |z  }	t                      }
|
                    |	           t          |          }dt          |          z   |z   }|dk    rS| j        t          k    r"| 
                    t          d||||||           nu| 
                    t          d|||||           nT| j        t          k    r#| 
                    t          d|||||||	  	         n!| 
                    t          d||||||           |dk    r|dz  }| j        t          k    r+|d	}n|                                }|t          |          z  }|                     |
|           |                     |
|           |dk    r(|
                    t!          j        d
|                     | j        t          k    r|
                    |           |
                    |           |                     t          |
|||          S )Nr   r   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  )r   r   r   r8   r  r   rY   r\   r   r   r6  r7  r  r  r  rZ   r  _packet_queue)r   r   ri   r   r   r   r   r   r   r   r   
payloadlenr   packed_propertiess                 r1   r  zClient._send_publishD
  st   eW-- 	6jW7 7 	6")"5"5"5:##cCiA-.#(;fDg\\
s5zz>J6??~''"^fc5*    "Ofc5    ~''"_fc5*j    "Pfc5*   77!>V##!$+!!$.OO$5$5!$5 6 66##F,<==='''77MM&+dC00111>V##MM+,,,g!!'63TBBBr0   c                 r    |                      t          d|           |                     t          |d          S )NzSending PUBREC (Mid: %d)F)r6  r7  r  PUBRECr   s     r1   _send_pubreczClient._send_pubrec
  r  r0   c                 x    |                      t          d|           |                     t          dz  |d          S )NzSending PUBREL (Mid: %d)r   F)r6  r7  r  PUBRELr   s     r1   _send_pubrelzClient._send_pubrel
  s5    ~'A3GGG**6A:sEBBBr0   c                 r    |r|dz  }d}t          j        d|||          }|                     |||d          S )Nr   r   z!BBHr   r  r  r  )r   r   r   r   r   r   s         r1   r  zClient._send_command_with_mid
  sI     	sNGVW.>DD!!'63:::r0   c                 b    d}t          j        d||          }|                     ||dd          S )Nr   !BBr  )r   r   r   r   s       r1   r  zClient._send_simple_command
  s6    UG-=>>!!'61a888r0   c                    | j         }|t          k    rdnd}dt          |          z   dz   dz   dz   dz   t          | j                  z   }d}| j         t          k    r.| j        dk    r|dz  }n)| j        t          k    r| j        r|dz  }n| j        r|dz  }| j	        rS|dt          | j
                  z   dz   t          | j                  z   z  }|d| j        dz  dz  z  | j        dz  d	z  z  z  }| j        E|dt          | j                  z   z  }|d
z  }| j        |dz  }|dt          | j                  z   z  }| j         t          k    rq| j        d}n| j                                        }|t          |          z  }| j	        r5| j        d}n| j                                        }|t          |          z  }t&          }t)                      }	|	                    |           | j        t.          k    r|d
z  }|                     |	|           |	                    t5          j        dt7          t          |                    z   dz   t          |          ||||                     | j         t          k    r|	|z  }	|                     |	| j                   | j	        rK| j         t          k    r|	|z  }	|                     |	| j
                   |                     |	| j                   | j        =|                     |	| j                   | j        |                     |	| j                   || _        | j         t          k    rS|                     t>          d|d
z  dz	  |dz  dz	  |dz  d	z	  |dz  dz	  |dz  dz	  |dz  dz	  || j        | j                   nL|                     t>          d|d
z  dz	  |dz  dz	  |dz  d	z	  |dz  dz	  |dz  dz	  |dz  dz	  || j        
  
         |                      ||	dd          S )Ns   MQTTs   MQIsdpr   r   r   Tr   r   r   r   r   r  r  sBBHzQSending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s properties=%sr    r   r      zCSending CONNECT (u%d, p%d, wr%d, wq%d, wf%d, c%d, k%d) client_id=%s)!r   MQTTv311r\   r   r   r  r  rA  r   r  r  r  r  r  r   r   r  r  r  CONNECTr   rY   r   r  r  rZ   r  r   r  r   r6  r7  r  )
r   r  	proto_verrF  r   connect_flagspacked_connect_propertiespacked_will_propertiesr   r   s
             r1   r  zClient._send_connect
  s   N	'83377s8}},q0DO,,- >V## D((%"&AAAdF`A%  	"T!M: 	1D$%%!&()!*,/0B,C,C!D DTdnt&;%AB"T)a/1 1M >%C$7$7 77T!M~)% ADN(;(;$;; >V##'/,3)),0,D,I,I,K,K)$= > >>z @(0-4**-1-B-G-G-I-I* C(>$?$?? g ++I##F,<===fk$S]]););";f"Dc(mmU]_hjw"+- - 	. 	. 	. >V##//F111: 	9~''00VT%5666VT%7888>%VT^444~)  888#>V##NNc%!+%!+%!+%!+$*$*(    NNU%!+%!+%!+%!+$*$*   !!'61a888r0   c                 p   | j         t          k    r|                     t          d||           n|                     t          d           d}t          }t                      }|                    |           | j         t          k    rL||H|t          t          dz	  d          }|dz  }|&|                                }|t          |          z  }| 
                    ||           | j         t          k    r(|d k    r"||                                z  }|d k    r||z  }|                     ||dd          S )Nz.Sending DISCONNECT reasonCode=%s properties=%szSending DISCONNECTr   r   
identifierr   )r   r   r6  r7  r  r   rY   r   r  r\   r  r  )r   r   r   r   r   r   packed_propss          r1   r  zClient._send_disconnect  sK   >V##NN>+[%%   
 NN>+?@@@g>V##%)?%!,Z1_!K!K!KJ A% )#-??#4#4L$L(9(99$##F,<===>V##T!!*//+++%%l*F!!'61a888r0   c                    d}| j         t          k    r+|d}n|                                }|t          |          z  }|D ]\  }}|dt          |          z   dz   z  }t          |dz  z  dz  }t                      }	|	                    |           |                     |	|           |                                 }
|		                    t          j        d|
                     | j         t          k    r|	|z  }	|D ]X\  }}|                     |	|           | j         t          k    r|	|                                z  }	C|	                    |           Y|                     t          d||
|           |                     ||	|
d          |
fS )Nr   r  r   r   r  zSending SUBSCRIBE (d%d, m%d) %s)r   r   r  r\   	SUBSCRIBEr   rY   r  r  rZ   r  r  r6  r7  r  )r   r   topicsr   r   packed_subscribe_propertiesr  rT   r   r   r  r  s               r1   r
  zClient._send_subscribe'  s   >V##!.5++.8oo.?.?+$? @ @@ 	/ 	/DAqCFF
Q.sax(3.g##F,<===&&((	fk$	22333>V##11F 	! 	!DAqVQ'''~''!&&(("a    -	
 	
 	
 ""7FIqAA9MMr0   c                    d}| j         t          k    r+|d}n|                                }|t          |          z  }|D ]}|dt          |          z   z  }t          |dz  z  dz  }t                      }|                    |           |                     ||           |                                 }	|	                    t          j        d|	                     | j         t          k    r||z  }|D ]}|                     ||           | j         t          k    r |                     t          d||	||           n|                     t          d||	|           |                     |||	d          |	fS )Nr   r  r   r  z$Sending UNSUBSCRIBE (d%d, m%d) %s %sz!Sending UNSUBSCRIBE (d%d, m%d) %sr   )r   r   r  r\   UNSUBSCRIBEr   rY   r  r  rZ   r  r  r6  r7  r  )
r   r   r  r   r   packed_unsubscribe_propertiesr  r   r   r  s
             r1   r  zClient._send_unsubscribeL  s   >V##!07--0:0A0A-$A B BB 	+ 	+ACFF
**S0g##F,<===&&((	fk$	22333>V##33F 	( 	(AVQ'''' >V##NN6    NN3   ""7FIqAA9MMr0   c                 l    | j         t          k    r| j        t          k    r| j        S | j        S | j        S r   )r   r   r  r  rA  r   r   s    r1   _check_clean_sessionzClient._check_clean_sessionx  s9    >V## $???11((&&r0   c                    | j         5  d| _        | j                                        D ]}d|_        | j        dk    s| j        | j        k     r|j        dk    rt          |_        <|j        dk    r$|j        t          k    rd|_
        t          |_        k|j        dk    rx|                                 r$|j        t          k    rd|_
        t          |_        |j        t          k    rt          |_        |j        t          k    rd|_
        t          |_        t          |_        	 d d d            d S # 1 swxY w Y   d S )Nr   r   Tr   )r(  r  r  valuesr   r  r   r  r   r  r   r  mqtt_ms_wait_for_pubcompmqtt_ms_resend_pubrelr  r  r   ms     r1   _messages_reconnect_reset_outz$Client._messages_reconnect_reset_out  sv   $ 	- 	-&'D#'..00 - -.!33t7NQUQl7l7luzz"1!7&===$(AE"1!4466 
: w/99(,&5AGG w*BBB*?#$7.E#E#E,0AE*9,AGG1-	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s   DD33D7:D7c                 X   | j         5  |                                 r&t          j                    | _        	 d d d            d S | j                                        D ]4}d|_        |j        dk    r | j                            |j	                   45	 d d d            d S # 1 swxY w Y   d S )Nr   r   )
r)  r  r  r  r  r  r   r   popr   r  s     r1   _messages_reconnect_reset_inz#Client._messages_reconnect_reset_in  s   # 
	 
	((** $/$;$=$=!
	 
	 
	 
	 
	 
	 
	 
	 &--//  5A::%))!%0000 	
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	s   .BABB#&B#c                 V    |                                   |                                  d S r   )r  r  r   s    r1   r  z Client._messages_reconnect_reset  s,    **,,,))+++++r0   c                    |||dt          |          ||d}| j                            |           | j        1	 | j                            t
                     n# t          $ r Y nw xY w| j        N| j        G| j	        
                    d          r-| j	                                         |                                 S |                                  t          S )Nr   )r   r   r   r   r   r   r   F)r\   r  rY   r   rU  sockpair_datarz   r,  r=  r$  acquirereleaser  rQ  r4   )r   r   r   r   r   r   mpkts          r1   r  zClient._packet_queue  s    f++  	%%% ?&$$]3333"   
 <D$B$J&..u55 )'//111(((((***s   A 
A'&A'c                 6   | j         d         dz  }|t          k    r|                                 S |t          k    r|                                 S |t
          k    r|                     d          S |t          k    r|                     d          S |t          k    r| 	                                S |t          k    r|                                 S |t          k    r|                                 S |t          k    r|                                 S |t           k    r|                                 S |t$          k    r|                                 S |t(          k    r$| j        t,          k    r|                                 S |                     t2          d|           t4          S )Nr   r   r  r  zError: Unrecognised command %s)r  r  _handle_pingreqr  _handle_pingrespr  _handle_pubackcompr  r  _handle_publishr  _handle_pubrecr  _handle_pubrelCONNACK_handle_connackSUBACK_handle_subackUNSUBACK_handle_unsubackr  r   r   _handle_disconnectr6  r  r6   )r   cmds     r1   r  zClient._packet_handle  sm   oi(4/'>>'')))H__((***F]]**8444G^^**9555G^^'')))F]]&&(((F]]&&(((G^^'')))F]]&&(((H__((***J4>V#;#;**,,, NN<)I3OOO$$r0   c                     | j         d         dk    rt          S |                     t          d           |                                 S )Nr   r   zReceived PINGREQ)r  r6   r6  r7  r  r   s    r1   r  zClient._handle_pingreq  sB    ?-.!33$$~'9:::""$$$r0   c                     | j         d         dk    rt          S d| _        |                     t          d           t
          S )Nr   r   zReceived PINGRESP)r  r6   r  r6  r7  r4   r   s    r1   r  zClient._handle_pingresp  s?    ?-.!33$$ ~':;;;r0   c                    | j         t          k    r| j        d         dk     rt          S n| j        d         dk    rt          S | j         t          k    rt	          j        d| j        d         d d                   \  }}|dk    rd}d }n|t          t          dz	  |          }t          t          dz	            }|                    | j        d         dd                     n#t	          j        d| j        d                   \  }}| j         t          k    r|t          k    rK| j        st          S |                     t          d	||           t          | _         |                                 S |t           k    rv| j        d
k    rk| j        st          S |                     t          d||           t%          t'          j                    j        d          | _        |                                 S |dk    rt,          | _        d | _        | j         t          k    r|                     t          d|||           n|                     t          d||           d| _        | j        5  | j        }d d d            n# 1 swxY w Y   |ri }|dz  |d<   | j        5  	 | j         t          k    r || | j        |||           n || | j        ||           n;# t<          $ r.}|                     t>          d|           | j         s Y d }~nd }~ww xY wd d d            n# 1 swxY w Y   |dk    r1d}| j!        5  | j"        #                                D ]}	tI                      |	_%        |	j&        tN          k    r)| (                                 tR          c cd d d            S |	j*        dk    r| j        5  | +                    |	j,        |	j-        .                    d          |	j/        |	j*        |	j0        |	j1        |	j2                  }d d d            n# 1 swxY w Y   |dk    r|c cd d d            S n|	j*        dk    r|	j&        tf          k    r| xj4        dz  c_4        tj          |	_&        | j        5  | +                    |	j,        |	j-        .                    d          |	j/        |	j*        |	j0        |	j1        |	j2                  }d d d            n# 1 swxY w Y   |dk    r|c cd d d            S n;|	j*        dk    r/|	j&        tf          k    r| xj4        dz  c_4        tl          |	_&        | j        5  | +                    |	j,        |	j-        .                    d          |	j/        |	j*        |	j0        |	j1        |	j2                  }d d d            n# 1 swxY w Y   |dk    r|c cd d d            S n{|	j&        tn          k    rk| xj4        dz  c_4        tp          |	_&        | j        5  | 9                    |	j,                  }d d d            n# 1 swxY w Y   |dk    r|c cd d d            S | (                                 	 d d d            n# 1 swxY w Y   |S |dk    r|dk     rtt          S t          S )Nr   r   r  r   r      r   r   z=Received CONNACK (%s, %s), attempting downgrade to MQTT v3.1.r0   z:Received CONNACK (%s, %s), attempting to use non-empty CIDr   r   r   z'Received CONNACK (%s, %s) properties=%szReceived CONNACK (%s, %s)Fzsession presentz"Caught exception in on_connect: %sr   r   r   );r   r   r  r6   r  r  r   r#  r   r  rI   r  r6  r7  r   r  rJ   r   rc   r   r   r   r  r  r
  rA  r&  rS  r$  r   r  r  rB  r(  r  r  r  r   r   r  r  r4   r   r  r   ri   r   r   r   r   r   r  r  r  r  r  r  r  r9   )
r   flagsresultreasonr   rS  
flags_dictr  r   r  s
             r1   r$  zClient._handle_connack  s(	   >V##12Q66(( 7_/0A55$$>V##$mtx0!46 6OUF{{ !

$W\fEEE'155
!!$/(";ABB"?@@@@$mE4?83LMMOUF>X%%9991 -,,"S6   ")~~'''???3..1 -,,"P6  
 #))92"F"F"F~~'''Q;;+DK$(D!>V##NN I5RXZdf f f f NN ;UFL L L &+"! 	) 	)J	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)  	J,1DLJ()(  ~//"
4(2FJH H H H #
 $.*fF F F    NN$&JCQ Q Q3                    Q;;B( ;& ;&+2244 :& :&A"+++AKw.00)))///;& ;& ;& ;& ;& ;& ;& ;& uzz!4 	 	!%!3!3 ! !w 7 7 !	 ! ! !+,< "4 " "B	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 77#%II';& ;& ;& ;& ;& ;& ;& ;&$ #!7o55 33q833&=AG!%!8 	" 	"%)%7%7$%E$%GNN7$;$;$%I$%E$%H$%E/0| &8 &" &"	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"  "Qww')		G;& ;& ;& ;& ;& ;& ;& ;&H !7o55 33q833&=AG!%!8 	" 	"%)%7%7$%E$%GNN7$;$;$%I$%E$%H$%E/0| &8 &" &"	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"  "Qww')		g;& ;& ;& ;& ;& ;& ;& ;&d  'W(=== 33q833&>AG!%!8 > >%)%6%6qu%=%=> > > > > > > > > > > > > > >!Qww')		u;& ;& ;& ;& ;& ;& ;& ;&v OO%%%%u:&;& ;& ;& ;& ;& ;& ;& ;& ;& ;& ;& ;& ;& ;& ;&z IaZZFQJJ(($$s  I22I69I6L8K
L
L$K>9L>LLLL-AYY(AP;YPYPY(A Y(AS;YSYSY(AY)AV<YVYVY)4YX8YXYXY%YYYc                    t           dz	  }d x}}| j        d         dk    rzt          |          }|                    | j        d                    | j        d         dk    r:t	          |          }|                    | j        d         dd                    \  }}|                     t          d||           |                     ||           t          S )Nr   r   r   r   r   r   zReceived DISCONNECT %s %s)	r  r  r   r  r   r6  r7  r  r4   )r   packet_type
reasonCoder   props	props_lens         r1   r)  zClient._handle_disconnect  s     Ao"&&
Z?-.22$[11Jdoh788812Q66'44
#-#4#4OH-abb1$3 $3 y~'B!!	 	 	
 	Z444r0   c                    |                      t          d           dt          t          | j        d                   dz
            z   dz   }t          j        || j        d                   \  }}| j        t          k    rt          t          dz	            }|                    |          \  }}g }||d          D ]S}t          j        d         dk     rt          |          }|                    t          t          dz	  |	                     Tn*d
dt          |          z  z   }t          j        ||          }	| j        5  | j        }
d d d            n# 1 swxY w Y   |
r| j        5  	 | j        t          k    r |
| | j        |||           n |
| | j        ||	           n;# t(          $ r.}|                      t*          d|           | j        s Y d }~nd }~ww xY wd d d            n# 1 swxY w Y   t.          S )NzReceived SUBACKr  r   r   sr   r   r   r   !Bz$Caught exception in on_subscribe: %s)r6  r7  r   r\   r  r  r  r   r   r   r%  r  r  ordrY   r   r&  rb  r$  r   r  r  rB  r4   )r   pack_formatr   r   r   r7  r8  reasoncodescgranted_qosrb  r  s               r1   r&  zClient._handle_suback  s   ~'8999ST_X%>!?!?!!CDDDsJk4?83LMMf>V###FaK00J)0088E9KIJJ' K K#A&**AA"";v{q#I#I#IJJJJK
 c&kk 11K -V<<K! 	- 	-,L	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-  	(  ~//$ $.#{JP P P P % $.#{D D D    NN$&LcS S S3                     sN    EEE(G**8F#"G*#
G-$GG*GG**G.1G.c                    d}| j         d         }t                      }|dz  dz	  |_        |dz  dz	  |_        |dz  |_        dt          t          | j         d                   d	z
            z   d
z   }t          j        || j         d                   \  }}dt          |          z   d
z   t          t          |          |z
            z   d
z   }t          j        ||          \  }}| j	        t          k    rt          |          dk    rt          S 	 |                    d          }n"# t          $ r dt          |          z   }Y nw xY w||_        |j        dk    rBdt          t          |          d	z
            z   d
z   }t          j        ||          \  |_        }| j	        t          k    rCt!          t"          dz	            |_        |j                            |          \  }	}
||
d          }||_        | j	        t          k    rN|                     t*          d|j        |j        |j        |j        ||j        t          |j                  	  	         nG|                     t*          d|j        |j        |j        |j        |t          |j                             t-                      |_        |j        dk    r|                     |           t2          S |j        dk    r/|                     |           |                     |j                  S |j        d	k    rV|                     |j                  }t8          |_        | j        5  || j        |j        <   d d d            n# 1 swxY w Y   |S t          S )Nr   r   r   r   r   r   r  r   r   r:  r;  r   zTOPIC WITH INVALID UTF-8: r   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  r   r   r   r   r   r\   r  r  r   r   r6   r   UnicodeDecodeErrorri   r   r   r  r   r   r6  r7  r  r   _handle_on_messager4   r  r  mqtt_ms_wait_for_pubrelr   r)  r  )r   r   headerr  r>  slenr   ri   print_topicr7  r8  s              r1   r   zClient._handle_publish  s}   +--}*}* 4-ST_X%>!?!?!!CDDDsJ{DOH4MNNvCIIo+c#f++2D.E.EEK -V<<>V##E

a$$	D,,w//KK! 	D 	D 	D6UCKKK	D ;??S[[1_!5!55;K$*M+v$F$F!W[&>V##!+GqL!9!9G&188@@E9IJJ'F >V##NN]W['.'+W/W_1E1E	    NNNW['.'+S11	   &KK;!##G,,,##[A##G,,,$$W[111[A""7;//B3GM' 9 918!'+.9 9 9 9 9 9 9 9 9 9 9 9 9 9 9I$$s$   D& &EEM##M'*M'c                    | j         t          k    r| j        d         dk     rt          S n| j        d         dk    rt          S t	          j        d| j        d                   \  }|                     t          d|           | j        5  || j	        v r| j	        
                    |          }|                     |           | xj        dz  c_        | j        dk    rL| j        5  |                                 }d d d            n# 1 swxY w Y   |t           k    r|cd d d            S d d d            n# 1 swxY w Y   |                     |          S )Nr   r   r  r   zReceived PUBREL (Mid: %d)r   r   )r   r   r  r6   r  r  r6  r7  r)  r  r  rD  r  r  r(  _update_inflightr4   r  )r   r   r  r   s       r1   r"  zClient._handle_pubrel  s   >V##12Q66(( 7_/0A55$$}T4?8#<==~'BCHHH# 	" 	"d''' +//44''000''1,''.220 5 5!22445 5 5 5 5 5 5 5 5 5 5 5 5 5 5---!	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"& !!#&&&s7   AD3"D7D3D	D3
D	D33D7:D7c           
         | j                                         D ]}| j        | j        k     r|j        dk    r|j        t          k    r| xj        dz  c_        |j        dk    rt          |_        n|j        dk    rt          |_        | 	                    |j
        |j                            d          |j        |j        |j        |j        |j                  }|dk    r|c S t"          c S t"          S )Nr   r   r   r   r/  )r  r  r  r  r   r   r  r  r  r  r   ri   r   r   r   r   r   r4   )r   r  r   s      r1   rJ  zClient._update_inflight,  s    #**,, 	( 	(A&)DDD5199N!:!:++q0++uzz"9!"9++w//	#$< ,  B Qww!			''''r0   c                 p   | j         t          k    r| j        d         dk     rt          S n| j        d         dk    rt          S t	          j        d| j        d         d d                   \  }| j         t          k    r| j        d         dk    rt          t          dz	            }|                    | j        d         dd                     | j        d         dk    rBt          t          dz	            }|                    | j        d         dd                    \  }}| 	                    t          d|           | j        5  || j        v rM| j        |         }t          |_        t                      |_        |                     |          cd d d            S 	 d d d            n# 1 swxY w Y   t$          S )Nr   r   r  r   r   r   zReceived PUBREC (Mid: %d))r   r   r  r6   r  r  r   r  r   r6  r7  r(  r  r  r   r  r   r  r4   )r   r   r6  r   r7  r8  msgs          r1   r!  zClient._handle_pubrecE  s   >V##12Q66(( 7_/0A55$$}T4?8#<RaR#@AA>V##12Q66(155
!!$/(";ABB"?@@@?#56::!+FaK!8!8J'1'8'81!""5(7 (7$E9~'BCHHH$ 	. 	.d((((-4	 )((--	. 	. 	. 	. 	. 	. 	. 	.(	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.  s   A
F&&F*-F*c                 2   | j         t          k    r| j        d         dk     rt          S n| j        d         dk    rt          S t	          j        d| j        d         d d                   \  }| j         t          k    r| j        d         dd          }t          t          dz	            }|                    |          \  }}g }||d          D ]S}t          j	        d         dk     rt          |          }|                    t          t          dz	  |                     Tt          |          d	k    r|d         }|                     t          d
|           | j        5  | j        }d d d            n# 1 swxY w Y   |r| j        5  	 | j         t          k    r || | j        |||           n || | j        |           n;# t(          $ r.}	|                     t*          d|	           | j        s Y d }	~	nd }	~	ww xY wd d d            n# 1 swxY w Y   t.          S )Nr   r   r   r  r   r   r   r   r   zReceived UNSUBACK (Mid: %d)z&Caught exception in on_unsubscribe: %s)r   r   r  r6   r  r  r   r'  r  r  r=  rY   r   r\   r6  r7  r&  ru  r$  r   r  r  rB  r4   )
r   r   r   r   r7  r8  r?  r@  ru  r  s
             r1   r(  zClient._handle_unsuback`  s   >V##12Q66(( 7_/0A55$$}T4?8#<RaR#@AA>V##_X.qrr2F#HM22J)0088E9KIJJ' M M#A&**AA"";x1}#K#K#KLLLL;1$$)!n~'DcJJJ! 	1 	1!0N	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1  	(  
~//& $.#z;P P P P 'tT^SAAA    NN$&NPSU U U3                     sN   E22E69E6H7G ?H 
G8
$G3.H3G88HHHc                    | j         5  | j        }d d d            n# 1 swxY w Y   |r| j        5  	 | j        t          k    r || | j        ||           n || | j        |           n;# t          $ r.}|                     t          d|           | j	        s Y d }~nd }~ww xY wd d d            d S # 1 swxY w Y   d S d S )Nz%Caught exception in on_disconnect: %s)
r&  r|  r$  r   r   r   r  r6  r  rB  )r   r   r   r|  r  s        r1   r  zClient._do_on_disconnect  s   ! 	/ 	/ .M	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/  	(  
~//% $."jB B B B &dDNB???    NN$&MsT T T3                      	 	sF     B16A)(B1)
B!3$BB1B!!B11B58B5c                 0   | j         5  | j        }d d d            n# 1 swxY w Y   |rn| j        5  	  || | j        |           n;# t          $ r.}|                     t          d|           | j        s Y d }~nd }~ww xY wd d d            n# 1 swxY w Y   | j        	                    |          }|j
                                         |j        dk    r<| xj        dz  c_        | j        dk    r!|                                 }|t           k    r|S t           S )Nr  r   r   )r&  ro  r$  r   r  r6  r  rB  r  r  r   r   r   r  r  rJ  r4   )r   r   ro  r  rM  r   s         r1   _do_on_publishzClient._do_on_publish  s   ! 	) 	)J	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)  	(  JtT^S9999    NN$&JCQ Q Q3                     $$S))""$$$7Q;;##q(##*Q..**,,)))IsF     BAB
A=$A83B8A==BBBc                 0   | j         t          k    r| j        d         dk     rt          S n| j        d         dk    rt          S |dk    rt          nt
          }|dz	  }t          j        d| j        d         d d                   \  }| j         t          k    r| j        d         dk    rt          |          }|                    | j        d         dd                     | j        d         dk    r:t          |          }|                    | j        d         dd                    \  }}| 
                    t          d||           | j        5  || j        v r#|                     |          }|cd d d            S 	 d d d            n# 1 swxY w Y   t          S )	Nr   r   r  r   r  r   r   zReceived %s (Mid: %d))r   r   r  r6   r  r  r  r  r   r   r6  r7  r(  r  rQ  r4   )	r   r*  r5  r   r6  r   r7  r8  r   s	            r1   r  zClient._handle_pubackcomp  s   >V##12Q66(( 7_/0A55$$ #xffW!Q&}T4?8#<RaR#@AA>V##12Q66(55
!!$/(";ABB"?@@@?#56::!+K!8!8J'1'8'81!""5(7 (7$E9~'>SIII$ 	 	d(((((--		 	 	 	 	 	 	 	(	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  s    FF
F
c           	         d}	 |j         }n# t          $ r d }Y nw xY wg }| j        5  |7| j                            |j                   D ]}|                    |           t          |          dk    r| j        }nd }d d d            n# 1 swxY w Y   |D ]v}| j        5  	  || | j	        |           nA# t          $ r4}|                     t          d|j        |           | j        s Y d }~nd }~ww xY wd d d            n# 1 swxY w Y   w|rq| j        5  	  || | j	        |           n;# t          $ r.}|                     t          d|           | j        s Y d }~nd }~ww xY wd d d            d S # 1 swxY w Y   d S d S )NFr   z9Caught exception in user defined callback function %s: %sz"Caught exception in on_message: %s)ri   rC  r&  r  rf   rY   r\   rh  r$  r   r  r6  r  r,   rB  )r   r  matchedri   on_message_callbacksr  rh  r  s           r1   rD  zClient._handle_on_message  s   	MEE! 	 	 	EEE	  "! 	" 	"  $ 9 D DW] S S : :H(//9999'((A--!_

!
	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" - 	 	H(  
HT4>7;;;;    NN$S )	    3                     	(  JtT^W====    NN$&JCQ Q Q3                      	 	s    AB

BB D"B54D5
C3?*C.)D.C33DD		D	E4D,+E4,
E$6$EE4E$$E44E8;E8c                 &   | j         5  | j        }d d d            n# 1 swxY w Y   |rh| j        5  	  || | j                   n3# t          $ r&}|                     t          d|           Y d }~nd }~ww xY wd d d            d S # 1 swxY w Y   d S d S )Nz'Caught exception in on_connect_fail: %s)r&  r[  r$  r   r  r6  r  )r   r[  r  s      r1   r5  zClient._handle_on_connect_fail  s   ! 	3 	3"2O	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3  	V( V VV#OD$.9999  V V VNN$&OQTV V V V V V V VVV V V V V V V V V V V V V V V V V V	V 	VsF     BAB
A4A/*B/A44BBBc                 2    |                      d           d S )NT)r9  )r:  r   s    r1   r=  zClient._thread_main  s    66666r0   c                    t                      }| j        5  | j        | j        | _        n"t	          | j        dz  | j                  | _        || j        z   }d d d            n# 1 swxY w Y   ||z
  }| j        t          k    r_| j        s\|dk    rXt          j
        t	          |d                     |t                      z
  }| j        t          k    r| j        s|dk    Pd S d S d S d S d S d S )Nr   r   r   )r  r*  r
  r  minr	  r  r  r-  r   sleep)r   r  target_time	remainings       r1   r8  zClient._reconnect_wait	  sQ   kk( 		6 		6$,(,(A%%(+)A--) )%
  55K		6 		6 		6 		6 		6 		6 		6 		6 		6 		6 		6 		6 		6 		6 		6  #%	{333. 4MMJs9a(()))#ikk1I {333. 4MMMM 433333!M 43s   AA##A'*A'c                 (   d }t          | t                    r2 ||                     d          |                     d                    S t          | t          t          f          r+t          |           dk    o || d         | d                   S dS )Nc                 |    t           d uo3| t          t           j        t           j        t           j        g          v o|S r   )r  setHTTPSOCKS4SOCKS5)r  as     r1   checkz%Client._proxy_is_valid.<locals>.check!  s<    % Mej%,EFFFMKLNr0   
proxy_type
proxy_addrr   r   r   F)r   rb  getr  r  r\   )r  rd  s     r1   r  zClient._proxy_is_valid  s    	N 	N 	N a 	5|,,aeeL.A.ABBBD%=)) 	q66Q;4551qt#4#445r0   c                 B   t           d S |                     | j                  r| j        S t          t          d          rt	          j        | j                  st	          j                    }d|v rht          j	        |d                   }|j
        dk    rt           j        |j        |j        d}|S |j
        dk    rt           j        |j        |j        d}|S t          j                    }|                     |          rd}t!          t#          ||                    S d S )Nproxy_bypassmqtthttp)re  rf  
proxy_portr  )re  rf  rl  
proxy_rdnsproxy_usernameproxy_password)r  r  r"  rj  urllib_dot_requestri  r  
getproxiesurllib_dot_parseurlparseschemer`  hostnamer   rb  get_default_proxyrb  zip)r   env_proxiespartsproxysocks_default
proxy_keyss         r1   
_get_proxyzClient._get_proxy,  s1   =4 ,, 	;
 *N;; 	!"/
;;	!,799K$$(1+f2EFF<6))&+j&+n&+j E
 !L\W,,&+l&+n&+j E
 !L /11.. 	8LJJ66777 tr0   c                 \   |                                  }| j        | j        f}| j        | j        f}t
          j        dk     sdt
          j        cxk     rdk     rn nt          j        || j	                  S |rt          j        |f| j	        |d|S t          j        || j	        |          S )Nr  r  r  )r   )r   source_address)r}  r  r  r   r!  r  r  rn   create_connectionr   r  )r   rz  r  sources       r1   r  z Client._create_socket_connectionW  s    !!
DJ'$do6 f$$1A(J(J(J(JF(J(J(J(J(J +D$:OPPPP 	h*4o9N_eooinooo+D$:O`fggggr0   )F)rW   TN)r   Nr   )NNNNNNN)r   r   )r  r   )r  )Nr   FNr   )r   NNr   )r  r   F)r0   r   FFNN)r,   r-   r.   r   r  r   rK  rS  rW  r\  rJ  r`  rf  rl  r  rx  r  r  r  r  ry   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r"  r%  r(  r*  r,  r.  rn   r:  r@  rD  r   rG  r   rP  rS  rY  r[  r`  rb  rf  rh  rm  ro  rs  ru  rz  r|  r  r  r  r  r  r  rZ  r  r  rQ  r  r  rY  r  r  r  r  r  r  r6  r  r  staticmethodr  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"  rJ  r!  r(  r  rQ  r  rD  r5  r=  r8  r  r}  r  r/   r0   r1   r   r     s
       9 9v "$4$"e$L) L) L) L)\  " " "
" 
" 
"  	# 	# 	# 	#: : : :
d d d d(< < < <4T( T( T( T(l9 9 96% % %2      "&"PQ7D       > "&" ;'3 '3 '3 '3R (,rVW"=$', ', ', ',T) ) ) )L3 L3 L3\# # # #@?  ?  ?  ? Bq( q( q( q(f< < < <&( ( ( 0 0 0= = = =HG HG HG HGT&E &E &E &EP       25 5 5 56	 	 	     6/ / /    " " ".+ .+ .+ .+`" " "  F F F FP            X
 ]  ]$       X 
 )$ )$ )$V   % % X%
 ) ) )    " " X"
 & & &4       X  $ $ $$   	  	  X	  $ $ $$   $ $ X$
 ( ( (0   # # X#
 ' ' '0   $ $ X$ ( ( ($     % % X% ) ) )$     . . X. $2 2 %$2$    $ 0 0 X0  &4 4 '&4$     &6 6 6"  
 
 
 	 	 	 	d d dL=  =  = ~
4 
4 
4+ + +>" " " $ $ \$ $ $ \$  3 3 3? ? ?@ @ @    AC AC AC ACF? ? ?C C C; ; ;9 9 9e9 e9 e9N 9  9  9  9D#N #N #N #NJ*N *N *N *NX' ' '- - -:  , , ,       >% % %:% % %     R% R% R%h     &#  #  # JD% D% D%L' ' '>     2     6&  &  & P   $     0     8) ) )X
V 
V 
V7 7 72 2 2, 
 
 \
) ) )Vh h h h hr0   r   c                       e Zd ZdZdZdZdZdZdZd Z	d Z
d	 Zdd
Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZdS )r  r   r   r   r   r!   r#   c                     d| _         || _        || _        || _        || _        || _        t                      | _        t                      | _        d| _	        d| _
        d| _        |                     |           d S r   )	connectedr.  r  r  _socket_pathr   _sendbuffer_readbuffer_requested_size_payload_head_readbuffer_head_do_handshake)r   rn   r  r   is_sslrd  extra_headerss          r1   r   zWebsocketWrapper.__init__p  sv    	


$;;$;;  !=)))))r0   c                 "    d | _         d | _        d S r   )r  r  r   s    r1   rK  zWebsocketWrapper.__del__  s    r0   c                    t          j                    j        }t          j        |          }d                    |           ddd                    |           |                    d          ddd	}t          |t                    r|	                    |           nt          |          r ||          }d
                    d                    |           d
                    d |                                D                       d
g                              d          }| j                            |           d}d}	 | j                            d          }| j                            |           |dk    rt'          | j                  dk    rdt)          | j                                                                      d          v rLdt)          | j                                                                      d          vrt-          d          d}dt)          | j                                                                      d          v rd}| j                            d                              dd          d         }	|	                                                    d          }	|                    d          |z   }
t3          j        |
                    d                    }
t          j        |
                                          }
|	|
k    rt-          d          d}nn't9                      | _        n|st-          d          |r|st-          d          t9                      | _        d| _        d S )Nz{self._host:s}:{self._port:d}r   	websocketUpgradez%https://{self._host:s}:{self._port:d}utf813rj  )Hostr  
ConnectionOriginzSec-WebSocket-KeyzSec-Websocket-VersionzSec-Websocket-Protocolz
zGET {self._path} HTTP/1.1c              3   H   K   | ]\  }}d                      ||          V  dS )z{}: {}N)format)rS   ijs      r1   rV   z1WebsocketWrapper._do_handshake.<locals>.<genexpr>  sH       ? ? Aq !1-- ? ? ? ? ? ?r0   FTr      
r   s
   connectionr   s   upgradez2WebSocket handshake error, connection not upgradeds   sec-websocket-acceptz$258EAFA5-E914-47DA-95CA-C5AB0DC85B11z: z-WebSocket handshake error, invalid secret keyzWebSocket handshake error)r   r   r  base64	b64encoder  r   r   rb  updaterc  r]   itemsr   r  rU  rM  r  rZ   r\   r   r   r+   r  striphashlibsha1digestr   r  )r   r  sec_websocket_keywebsocket_headersrF  
has_secrethas_upgrader  GUIDserver_hashclient_hashs              r1   r  zWebsocketWrapper._do_handshake  s    JLL.",->?? 4:::EE"#=DD$DOO!2!9!9&!A!A%)&,
 
 mT** 	A$$]3333m$$ 	A -.? @ @'..D.99KK ? ?$5$;$;$=$=? ? ? ? ?	
  
 6&>> 	 	&!!!
+	L<$$Q''D##D))) u}}t'((1,,$D,<(=(=(C(C(E(E(L(LW(U(UUU%S1A-B-B-H-H-J-J-Q-QRY-Z-ZZZ": T#V #V V +/K /#d6F2G2G2M2M2O2O2V2VW^2_2___E&*&6&=&=#'% '%%*U4^^A'7&1&7&7&9&9&@&@&I&I&7&>&>w&G&G$&N&-l;3E3Eg3N3N&O&O&,&6{7I7I7K7K&L&L&+55": O#Q #Q Q *.J  $-;;    L./JKKKW+	LZ  	H* 	H*+FGGG$;;r0   c                 r   t                      }t          |          }t          t          j        d                    }|}|                    d|z             |dk     r|                    |dz  |z             n|dk     r4|                    |dz  dz             |t          j        d|          z  }nI|dk     r4|                    |dz  dz             |t          j        d	|          z  }nt          d
          |dk    r0t          |          D ]}||xx         ||dz           z  cc<   ||z   }||z   S )Nr   r   ~   r    r  r  l           r  !QzMaximum payload size is 2^63r   )	r   r\   osurandomrY   r  r  r   r[   )	r   opcoder  
do_maskingrF  lengthmask_key	mask_flagr   s	            r1   _create_framezWebsocketWrapper._create_frame  sM   TRZ]]++	 	fvo&&&C<<MM)q.612222e^^MM)q.3.///fk$///FF(((MM)q.3.///fk$///FF ;<<<>>v 3 3Ux	22d?D}r0   c                 R   |t          | j                  | j        z
  z
  }|dk    rW| j                            |          }|st
          | j                            |           t          |          |k     rt          | xj        |z  c_        | j        | j        |z
  | j                 S r   )r\   r  r  r  rM  ConnectionAbortedErrorrZ   rz   )r   r  wanted_bytesr  s       r1   _buffered_readzWebsocketWrapper._buffered_read  s     T%5!6!69N!NO!<$$\22D .,, ''---4yy<''%%' 5 >t?T TUUr0   c                    	 d| _         d }| j        }| j        |z   }|                     d          }|                     d          }|d         dz  }|d         dz  dk    }|d         dz  }	|	}
d }|	dk    r-|                     d          }t          j        d|          \  }
n2|	dk    r,|                     d	          }t          j        d
|          \  }
|r|                     d          }|}|
|k     r|
}|dk    rU|                     |          }|r,t          ||          D ]}||xx         ||dz           z  cc<   |||         }|| _        nt                      }||
k    rt                      | _        d| _        |t          j	        k    r;| 
                    t          j	        |d          }| j                            |           |t          j        k    r;| 
                    t          j        |d          }| j                            |           |t          j        k    s|t          j        k    r|
dk    r|S t"          # t$          $ r d| _        Y dS w xY w)Nr   r   r(   r   r  r  r   r  r   r  r   Fr0   )r  r  r  r  r  r[   r   r  r  OPCODE_CONNCLOSEr  r  rU  OPCODE_PINGOPCODE_PONGOPCODE_BINARYOPCODE_CONTINUATIONrz   r  r  )r   r  r1  chunk_startindexchunk_endindexheader1header2r  maskbit
lengthbitspayload_lengthr  r   	readindexr   r   frames                    r1   
_recv_implzWebsocketWrapper._recv_impl  s   N	$%D!F#1!/&8N))!,,G))!,,Gaj4'FqzD(T1G!!*t+J'NH T!!++A.."(-e"<"<t##++A.."(-e"<"<  2..q11 'I	))*	1}}--i88  >!&'7!C!C > >(519*== !1)!;<%.""#++ N**#,;; %&" ->>> ..(97AG GEL%%e,,,-999 ..(4gqB BEL%%e,,, *888FFVFj<j<j&**%% 	 	 	"DN33	s   H9I <I IIc                    t          | j                  dk    r[|                     t          j        t          |                    }| j                            |           t          |          | _        | j        	                    | j                  }| j        |d          | _        t          | j                  dk    r| j        S dS r   )
r\   r  r  r  r  r   rZ   r  r  rU  )r   r  r  r  s       r1   
_send_implzWebsocketWrapper._send_implc  s     t  A%%&& .	$A AE##E***#&t99D  ""4#344+FGG4t  A%%'' 1r0   c                 ,    |                      |          S r   r  r   r  s     r1   rM  zWebsocketWrapper.recvy      v&&&r0   c                 ,    |                      |          S r   r  r  s     r1   readzWebsocketWrapper.read|  r  r0   c                 ,    |                      |          S r   r  r   r  s     r1   rU  zWebsocketWrapper.send      t$$$r0   c                 ,    |                      |          S r   r  r  s     r1   writezWebsocketWrapper.write  r  r0   c                 8    | j                                          d S r   )r  r|   r   s    r1   r|   zWebsocketWrapper.close  s    r0   c                 4    | j                                         S r   )r  filenor   s    r1   r  zWebsocketWrapper.fileno  s    |""$$$r0   c                 F    | j         r| j                                        S dS r   )r.  r  r  r   s    r1   r  zWebsocketWrapper.pending  s)     9 	<''))) 1r0   c                 :    | j                             |           d S r   )r  rx   )r   flags     r1   rx   zWebsocketWrapper.setblocking  s      &&&&&r0   Nr  )r,   r-   r.   r  OPCODE_TEXTr  r  r  r  r   rK  r  r  r  r  r  rM  r  rU  r  r|   r  r  rx   r/   r0   r1   r  r  h  s&       KMKK* * *&     
S S Sj   @V V V&Q Q Qf  ,' ' '' ' '% % %% % %  % % %  ' ' ' ' 'r0   r  )r  r  r  stringr  r  r   r   r   rj   r   r   r   r?  r   subscribeoptionsr   r  errnor  platformr  rn   rN  ImportErrorr  urllibr   rr  r	   rp  rs  	monotonicr  r  dns.resolverr  r  systemWSAEWOULDBLOCKEAGAINrz   	NameErrorIOErrorr   r  r   r  r   r   r  r  r#  r  r  r  r  r  r  r%  r  r'  r  r  r  AUTHMQTT_LOG_INFOMQTT_LOG_NOTICEMQTT_LOG_WARNINGr  r7  DEBUGINFOWARNINGERRORr  rH   rI   rJ   rK   rL   rM   r  r  r  r  r   r  r  r  r  rE  mqtt_ms_resend_pubcompr  mqtt_ms_send_pubrecr  r   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   r   r  r  r  r   r+   rF   rO   ra   ascii_lettersrc   rk   r   objectr   r   r   r  r/   r0   r1   <module>r     s         



                   " " " " " " $ $ $ $ $ $ . . . . . .      				   
	JJJJ 	 	 	D	 		LLLL 	 	 	D	(0000004444444 ( ( (''''''''''	(II   	III HH    HHH 8?	!!!FF\FOO   OOO 	
A!GJ 

			
		

  GM7<W\go'-  #$  &' #%& "() %!"                             	 	 	 	 	z 	 	 	%  %  % P5 5 5$ ]V%991 % % % %  "  ,W# W# W# W# W#f W# W# W#t+ + + + +& + + +\t2h t2h t2h t2h t2hV t2h t2h t2hnem' m' m' m' m'v m' m' m' m' m'sl   A A&%A&,A1 1A98A9=B
 
BBB& &B54B59C   C
	C
0C3 3C=<C=