<commit_before># ----------------------------------------------------------------------
# Copyright (C) 2015 by <NAME> 
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# ----------------------------------------------------------------------

# ----------------
# Standard modules
# ----------------

# ----------------
# Twisted  modules
# ----------------

from zope.interface   import implementer
from twisted.internet import defer, reactor, error
from twisted.logger   import Logger

# -----------
# Own modules
# -----------

from ..          import v31
from ..pdu       import PUBLISH, PUBREL
from .interfaces import IMQTTPublisher
from .base       import MQTTBaseProtocol, MQTTWindowError 
from .base       import ConnectingState as BaseConnectingState, ConnectedState as BaseConnectedState
from .interval   import Interval

log = Logger()



class MQTTSessionCleared(Exception):
    '''MQTT persitent session cleared and message could not be published.'''
    def __str__(self):
        return self.__doc__
    
# ---------------------------------------
# MQTT Client Connecting State Class
# ---------------------------------------

class ConnectingState(BaseConnectingState):

    def handleCONNACK(self, response):
        self.protocol.handleCONNACK(response)

    # The standard allows publishing data without waiting for CONNACK
    def publish(self, request):
        return self.protocol.doPublish(request)


# ---------------------------------
# MQTT Client Connected State Class
# ---------------------------------

class ConnectedState(BaseConnectedState):

    def publish(self, request):
        return self.protocol.doPublish(request)

    def handlePUBACK(self, response):
        self.protocol.handlePUBACK(response)

    def handlePUBREC(self, response):
        self.protocol.handlePUBREC(response)

    def handlePUBCOMP(self, response):
        self.protocol.handlePUBCOMP(response)

   

# ------------------------
# MQTT Client Protocol Class
# ------------------------

@implementer(IMQTTPublisher)
class MQTTProtocol(MQTTBaseProtocol):
    '''
    Publisher role MQTT Client Protocol
    '''
    

    def __init__(self, factory):
        MQTTBaseProtocol.__init__(self, factory)
        # patches the state machine
        MQTTBaseProtocol.CONNECTING = ConnectingState(self) 
        MQTTBaseProtocol.CONNECTED  = ConnectedState(self)   
        

    # -----------------------------
    # IMQTTPublisher Implementation
    # -----------------------------
  
    # --------------------------------------------------------------------------
    
    def publish(self, topic, message, qos=0, retain=False):
        '''
        API entry point.
        '''
        request = PUBLISH()
        request.qos     = qos
        request.topic   = topic
        request.payload = message
        request.retain  = retain
        request.dup     = False
        return self.state.publish(request)
    
    # ---------------------------
    # Protocol API for subclasses
    # ---------------------------

    def mqttConnectionMade(self):
        '''
        Called when a CONNACK has been received.
        '''
        if self._cleanStart:
            self._purgeSession()
        else:
            self._syncSession()

    # ------------------------------------------
    # Southbound interface: Network entry points
    # ------------------------------------------

    def handlePUBACK(self, response):
        '''
        Handle PUBACK control packet received (QoS=1).
        '''
        # By design PUBACK cannot arrive unordered, and we always pop the oldest one from the queue,
        # so:  response.msgId == queuePublishTx[0].msgId
        log.debug("<==  {packet} (id={response.msgId:04x})", packet="PUBACK", response=response)
        request = self.factory.queuePublishTx.popleft()
        request.alarm.cancel()
        request.deferred.callback(request.msgId)

    # --------------------------------------------------------------------------

    def handlePUBREC(self, response):
        '''
        Handle PUBREC control packet received (QoS=2).
        '''
        # By design PUBREC cannot arrive unordered, and we always pop the oldest one from the queue,
        # so:  response.msgId == queuePublishTx[0].msgId
        log.debug("<==  {packet} (id={response.msgId:04x})", packet="PUBREC", response=response)
        request = self.factory.queuePublishTx.popleft()
        request.alarm.cancel()
        reply = PUBREL()
        reply.msgId = response.msgId
        reply.interval = Interval()
        reply.deferred = request.deferred       # Transfer the deferred to PUBREL
        reply.encode()
        self.factory.queuePubRelease.append(reply)
        self._retryRelease(reply, False)


    # --------------------------------------------------------------------------

    def handlePUBCOMP(self, response):
        '''
        Handle PUBCOMP control packet received (QoS=2).
        '''
        # Same comment as PUBACK
        log.debug("<==  {packet} (id={response.msgId:04x})", packet="PUBCOMP", response=response)<commit_msg>cosmetic changes to debugging traces<commit_after># ----------------------------------------------------------------------
# Copyright (C) 2015 by <NAME> 
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# ----------------------------------------------------------------------

# ----------------
# Standard modules
# ----------------

# ----------------
# Twisted  modules
# ----------------

from zope.interface   import implementer
from twisted.internet import defer, reactor, error
from twisted.logger   import Logger

# -----------
# Own modules
# -----------

from ..          import v31
from ..pdu       import PUBLISH, PUBREL
from .interfaces import IMQTTPublisher
from .base       import MQTTBaseProtocol, MQTTWindowError 
from .base       import ConnectingState as BaseConnectingState, ConnectedState as BaseConnectedState
from .interval   import Interval

log = Logger()



class MQTTSessionCleared(Exception):
    '''MQTT persitent session cleared and message could not be published.'''
    def __str__(self):
        return self.__doc__
    
# ---------------------------------------
# MQTT Client Connecting State Class
# ---------------------------------------

class ConnectingState(BaseConnectingState):

    def handleCONNACK(self, response):
        self.protocol.handleCONNACK(response)

    # The standard allows publishing data without waiting for CONNACK
    def publish(self, request):
        return self.protocol.doPublish(request)


# ---------------------------------
# MQTT Client Connected State Class
# ---------------------------------

class ConnectedState(BaseConnectedState):

    def publish(self, request):
        return self.protocol.doPublish(request)

    def handlePUBACK(self, response):
        self.protocol.handlePUBACK(response)

    def handlePUBREC(self, response):
        self.protocol.handlePUBREC(response)

    def handlePUBCOMP(self, response):
        self.protocol.handlePUBCOMP(response)

   

# ------------------------
# MQTT Client Protocol Class
# ------------------------

@implementer(IMQTTPublisher)
class MQTTProtocol(MQTTBaseProtocol):
    '''
    Publisher role MQTT Client Protocol
    '''
    

    def __init__(self, factory):
        MQTTBaseProtocol.__init__(self, factory)
        # patches the state machine
        MQTTBaseProtocol.CONNECTING = ConnectingState(self) 
        MQTTBaseProtocol.CONNECTED  = ConnectedState(self)   
        

    # -----------------------------
    # IMQTTPublisher Implementation
    # -----------------------------
  
    # --------------------------------------------------------------------------
    
    def publish(self, topic, message, qos=0, retain=False):
        '''
        API entry point.
        '''
        request = PUBLISH()
        request.qos     = qos
        request.topic   = topic
        request.payload = message
        request.retain  = retain
        request.dup     = False
        return self.state.publish(request)
    
    # ---------------------------
    # Protocol API for subclasses
    # ---------------------------

    def mqttConnectionMade(self):
        '''
        Called when a CONNACK has been received.
        '''
        if self._cleanStart:
            self._purgeSession()
        else:
            self._syncSession()

    # ------------------------------------------
    # Southbound interface: Network entry points
    # ------------------------------------------

    def handlePUBACK(self, response):
        '''
        Handle PUBACK control packet received (QoS=1).
        '''
        # By design PUBACK cannot arrive unordered, and we always pop the oldest one from the queue,
        # so:  response.msgId == queuePublishTx[0].msgId
        log.debug("<== {packet} (id={response.msgId:04x})", packet="PUBACK", response=response)
        request = self.factory.queuePublishTx.popleft()
        request.alarm.cancel()
        request.deferred.callback(request.msgId)

    # --------------------------------------------------------------------------

    def handlePUBREC(self, response):
        '''
        Handle PUBREC control packet received (QoS=2).
        '''
        # By design PUBREC cannot arrive unordered, and we always pop the oldest one from the queue,
        # so:  response.msgId == queuePublishTx[0].msgId
        log.debug("<== {packet} (id={response.msgId:04x})", packet="PUBREC", response=response)
        request = self.factory.queuePublishTx.popleft()
        request.alarm.cancel()
        reply = PUBREL()
        reply.msgId = response.msgId
        reply.interval = Interval()
        reply.deferred = request.deferred       # Transfer the deferred to PUBREL
        reply.encode()
        self.factory.queuePubRelease.append(reply)
        self._retryRelease(reply, False)


    # --------------------------------------------------------------------------

    def handlePUBCOMP(self, response):
        '''
        Handle PUBCOMP control packet received (QoS=2).
        '''
        # Same comment as PUBACK
        log.debug("<== {packet} (id={response.msgId:04x})", packet="PUBCOMP", response=response)
{'fraction_non_alphanumeric': 0.21022447976405045, 'fraction_numerical': 0.0029493691627068656, 'mean_word_length': 1.7605156037991858, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5291012', 'n_tokens_mistral': 3064, 'n_tokens_neox': 2932, 'n_words': 939}