                         messageBuffer = []
                         messageLength = 0
                         messageLengthMultiplier = 1
-                        
+
                         clientState = MQTTClientState.DecodingHeader
                     }
                 }
-                
-                
+
+
             case NSStreamEvent.OpenCompleted:
                 clientState = MQTTClientState.DecodingHeader
             case NSStreamEvent.ErrorOccurred:


import Foundation

enum MQTTMessage : UInt8 {
    case CONNECT = 0x10
    case CONNACK = 0x20
    case PUBLISH = 0x30

        clientState = MQTTClientState.ConnectionClosed
    }

    // MARK: - Keep alive timer

    private func startKeepAliveTimer() {
        keepAliveTimer?.invalidate()
        keepAliveTimer = NSTimer.scheduledTimerWithTimeInterval(
            Double(keepAliveInterval) / 2.0,
            target: self,
            selector: #selector(self.mqttPing),
            userInfo: nil,
            repeats: true)
    }

    private func endKeepAliveTimer() {
        keepAliveTimer?.invalidate()
        keepAliveTimer = nil
    }

    // MARK: - Socket connection

    private func connectSocket(host: String, port: Int) -> Bool {
        NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputStream, outputStream: &outputStream)

        if inputStream == nil || outputStream == nil { return false }

        inputStream?.delegate = self
        outputStream?.delegate = self

        inputStream?.open()
        outputStream?.open()

        inputStream?.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        outputStream?.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)

        return true
    }

    private func disconnectSocket() {
        inputStream?.removeFromRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        outputStream?.removeFromRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)

        inputStream?.close()
        outputStream?.close()

        inputStream?.delegate = nil
        outputStream?.delegate = nil

        inputStream = nil;
        outputStream = nil;
    }

    // MARK: - Stream delegate

    dynamic internal func stream(stream: NSStream, handleEvent eventCode: NSStreamEvent) {
        switch stream {
        case inputStream!:
            switch (eventCode) {
