Skip to content

will message automatically call and facing error CocoaMQTT(error): Sending buffer is full, frame PUBLISH #606

Description

@HardikKMT

Hello Team,

I am facing issue that CocoaMQTT(error): Sending buffer is full, frame PUBLISH and sometime automatically willMessage call again and again means connect then again call now again connect and again call team please help me.

@emqx-ci-robot @skidnight @snr_lab @ItAldoRaine @abhinavsigh89
@turtleDeng
@jan-bednar
@jmiltner
@manucheri
@cyrus Ingraham

@feng Lee
@ CrazyWisdom
@alex Yu
@ Leeway
I am stuck from last week so please help me.

I am using mqtt version 3.1.1
my code is as below
////
//// BLE_Manager.swift
//// Oom-Cardio Monitor
////
//// Created by projects on 22/06/23.
////

import Foundation
import CoreBluetooth
import DGCharts


    //import CocoaMQTT
import SwiftyJSON
import UIKit
import SwiftUI
import CocoaMQTT
import Combine

//extension Notification.Name {
//    static let didUpdateConnectionStatus = Notification.Name("didUpdateConnectionStatus")
//}

class BLEConnection : NSObject,CBCentralManagerDelegate,ObservableObject, CBPeripheralDelegate,CocoaMQTTDelegate {

    private var dateLive: Date?
    private var dateLiveOffline: Date?

// var hashMap: [Date: [String: Any]] = [:]
var hashMap: [Date: JSON] = [:]
var hashMapOffline: [Date: JSON] = [:]

    let OOM_CAM_SERVICE_UUID_FU = CBUUID(string: "f000ffd0-0451-4000-b000-000000000000")
    let OOM_CAM_NOTIFY_WRITE_UUID_FU = CBUUID(string: "f000ffd1-0451-4000-b000-000000000000")
    func scheduleLocalNotification(with message: String) {
            let content = UNMutableNotificationContent()
            content.title = "Connection Status"
            content.body = message
            content.sound = UNNotificationSound.default

            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }

        // Function to decode JSON string to AlertResponse
    func decodeAlertResponse(from jsonString: String) -> AlertResponse? {
        let decoder = JSONDecoder()
        guard let jsonData = jsonString.data(using: .utf8) else { return nil }
        do {
            let alertResponse = try decoder.decode(AlertResponse.self, from: jsonData)
            return alertResponse
        } catch {
            print("Decoding error: \(error)")
            return nil
        }
    }

    func getSerialNoInBytes1(isLive: Bool, reset: Bool = false) -> String {
        var stringBuilder = ""

        let standardHighSpeedSync = UserDefaults.standard.bool(forKey: "StandardHighSpeedSync")
            // console("EndlessService", "standardHighSpeedSync -> \(standardHighSpeedSync)")
            // console("EndlessService", "isLive -> \(isLive)")
        print("EndlessService standardHighSpeedSync \(standardHighSpeedSync)")
        print("EndlessService isLive \(isLive)")
        if isLive && !standardHighSpeedSync {
            stringBuilder.append("01")
            stringBuilder.append("01")
        } else if isLive && standardHighSpeedSync {
            stringBuilder.append("01")
            stringBuilder.append("02")
        } else {
            stringBuilder.append("02")
            stringBuilder.append("00")
        }
        
//        stringBuilder.append("01")
//        stringBuilder.append("01")

        if reset {
            stringBuilder.append("01")
        } else {
            stringBuilder.append("00")
        }

            // console("EndlessService", "bytes -> \(stringBuilder)")
        print("EndlessService stringBuilder \(stringBuilder)")
        return stringBuilder
    }

    func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
            //        TRACE("ack: \(ack)")
        print("ack: \(ack)")
        reconnectAttempts = 0
        if ack == .accept {
            mqtt.subscribe("oom/ecg/ecg-position/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
            mqtt.subscribe("oom/ecg/processedDataThreeSec/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
            mqtt.subscribe("oom/ecg/processedData/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
            mqtt.subscribe("oom/ecg/ecgConnectionStatus/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
            mqtt.subscribe("oom/ecg/recordingLength/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
            mqtt.subscribe("oom/ecg/promptArrhythmiaCount/"+patientMongoId, qos: CocoaMQTTQoS.qos0)
            mqtt.subscribe("oom/ecg/promptArrhythmia/"+patientMongoId, qos: CocoaMQTTQoS.qos0)
        }
    }
    func mqtt(_ mqtt: CocoaMQTT, didDisconnectWithError err: Error?) {
           print("MQTT disconnected with error: \(String(describing: err))")
           
           // Attempt to reconnect if the disconnection was unexpected
           if reconnectAttempts < maxReconnectAttempts {
               reconnectAttempts += 1
               print("Attempting to reconnect (\(reconnectAttempts)/\(maxReconnectAttempts))...")
               mqtt.autoReconnectTimeInterval = UInt16(reconnectAttempts * 5) // Exponential backoff
               mqtt.connect()
           } else {
               print("Max reconnect attempts reached. Could not reconnect to MQTT broker.")
           }
       }
    func mqtt(_ mqtt: CocoaMQTT, didStateChangeTo state: CocoaMQTTConnState) {
            //        TRACE("new state: \(state)")
        let date = Date()

        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd hh:mm a"
        let result = formatter.string(from: date)
        print("new state: : \(state.description)")
        print("new state date: : \(result)")
        mqttConnectionStatus=state.description
        if(state.description=="connected"){
            if(connectedDevicePeri != nil){
                print("new state: : again \(state.description)")
                sendBluetoothStatus(value: "Connected")
                lastDataArray=0
                let hexa = getSerialNoInBytes1(isLive: true)
                peripheralWriteDataClear(peripheral: (connectedDevicePeri)!, command: (hexStringToByteArray(hexa)))

            }
                //            65c49aea29f6a5db52a526e2�

// mqtt.subscribe("oom/ecg/ecg-position/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
// mqtt.subscribe("oom/ecg/processedDataThreeSec/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
// mqtt.subscribe("oom/ecg/processedData/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
// mqtt.subscribe("oom/ecg/ecgConnectionStatus/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
// mqtt.subscribe("oom/ecg/recordingLength/"+patientMongoId, qos: CocoaMQTTQoS.qos1)
// mqtt.subscribe("oom/ecg/promptArrhythmiaCount/"+patientMongoId, qos: CocoaMQTTQoS.qos0)
// mqtt.subscribe("oom/ecg/promptArrhythmia/"+patientMongoId, qos: CocoaMQTTQoS.qos0)
// sendBluetoothStatus(value: "Connected")
// mqtt.subscribe("oom/ecg/ecg-position/"+patientMongoId, qos: CocoaMQTTQoS.qos1)

        }
        else{
            if(state.description=="disconnected"){
                //TODO here set islive not send command
                let hexa = getSerialNoInBytes1(isLive: false)
                if(connectedDevicePeri != nil){
                    peripheralWriteDataClear(peripheral: (connectedDevicePeri)!, command: (hexStringToByteArray(hexa)))
                }
            }
        }
    }

    func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
            //        TRACE("message: \(message.string.description), id: \(id)")
//        print("message: \(message.description), id: \(id)")
        
    }

    func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
            //        TRACE("id: \(id)")
//        print("id: \(id)")
    }

    func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16 ) {
            //        TRACE("message: \(message.string.description), id: \(id)")
//        print("message data: \(message), id: \(id)")
//        print("message topic name: \(message.topic), id: \(id)")
            //        print("message data: \(message), id: \(id)")

            // Directly use the payload without optional binding
        if(message.topic==("oom/ecg/ecgConnectionStatus/"+patientMongoId)){

            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)

            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("ecgConnectionStatus Received message payload as string: \(payloadString)")
                    //                let json = JSON(parseJSON: payloadString)
                let json = JSON(parseJSON: payloadString)
//                print("ecgConnectionStatus json string \(json)")


                if json["status"].stringValue != nil {
//                    print("status \(json["status"])")
                    delegate?.ecgConnectionStatus(json["status"].stringValue)
                }

            }
        }
        else if(message.topic==("oom/ecg/ecg-position/"+patientMongoId)){

            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)

            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("ecg-position Received message payload as string: \(payloadString)")
                    //                let json = JSON(parseJSON: payloadString)
//                delegate?.positionValueFun(payloadString)

            }
        }


        else if(message.topic==("oom/ecg/promptArrhythmiaCount/"+patientMongoId)){

            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)

            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("promptArrhythmiaCount Received message payload as string: \(payloadString)")
                    //                let json = JSON(parseJSON: payloadString)

//                if json["status"].stringValue != nil {
                        //                    print("status \(json["status"])")
                    delegate?.alertCountValueData(payloadString)
//                }
            }
        }

        else if(message.topic==("oom/ecg/promptArrhythmia/"+patientMongoId)){

            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)

//            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("promptArrhythmia Received message payload as string: \(payloadString)")
//
//                    // Decode the JSON string to AlertResponse
//                if let alertResponse = decodeAlertResponse(from: payloadString) {
//                    print("Decoded AlertResponse: \(alertResponse)")
//                    delegate?.alertObjectPass(alertResponse)
//                } else {
//                    print("Failed to decode AlertResponse from payload string")
//                }
//            }
            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("promptArrhythmia Received message payload as string: \(payloadString)")
                if let alert = try? JSONDecoder().decode(AlertResponse.self, from: Data(payloadString.utf8)) {
//                    viewModel?.updateAlertObject(alert)
                    delegate?.alertObjectPass(alert)
                }
            }

        }

        else if(message.topic==("oom/ecg/processedData/"+patientMongoId)){
//            print("connected processdata")
            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)

            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("Received message payload as string: \(payloadString)")
                let json = JSON(parseJSON: payloadString)
//                print("processedData json string \(json)")

                    //                if (!jsonObject.getString("Arrhythmia")
                    //                                                .equals("Artifacts")
                    //                                        ) binding?.tvThreasold?.text = jsonObject.getString("Arrhythmia")
                if(json["Arrhythmia"].stringValue != nil && !json["Arrhythmia"].stringValue.isEmpty){
                    delegate?.arrethemiaValueFun(json["Arrhythmia"].stringValue)
                    if(json["Arrhythmia"].stringValue != "Normal") {
                        if json["Arrhythmia"].stringValue != "Artifacts" {
                            delegate?.arrethemiaColor(Color.red)
                        }
                    }
                    else
                    {
                     if json["Arrhythmia"].stringValue != "Artifacts" {
                         delegate?.arrethemiaColor(Color.black)
                     }
                    }
                }

                if(json["MI"].stringValue != nil && !json["MI"].stringValue.isEmpty){
                    delegate?.MIValueFun(json["MI"].stringValue)
                }
            }
        }

        else if(message.topic==("oom/ecg/recordingLength/"+patientMongoId)){
                //            print("connected processdata")
            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)
//            print("Received recordingLength payloadData \(payloadData)")
            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("Received recordingLength message payload as string: \(payloadString)")
                let formattedDuration = formatDuration(from: payloadString) // Assume "1.5" is your payload string
//                print("formattedDuration\(formattedDuration)")
                delegate?.recordingTimeValue(formattedDuration)
//                let json = JSON(parseJSON: payloadString)
//                print("processedData json string \(json)")
            }
        }

        else if(message.topic==("oom/ecg/processedDataThreeSec/"+patientMongoId)){
            let payloadBytes = message.payload
            let payloadData = Data(payloadBytes)

            if let payloadString = String(data: payloadData, encoding: .utf8) {
//                print("Received message payload as string: \(payloadString)")
                let json = JSON(parseJSON: payloadString)
//                print("json string \(json)")
                let HR = json["HR"].intValue
//                print("HR Value\(HR)")


                    //                HRValueAppend()
                    //                delegate?.HRValueAppend(HR)

                delegate?.hrValueData(HR)

                if json["RRInterval"] != nil {
                    let RRValue = json["RRInterval"].doubleValue
                    if RRValue <= 0 {
                            // Set the text to "-" if RRInterval is less than or equal to 0
                        delegate?.rrValueData("-")
                    } else {
                            // Convert RRInterval to seconds and format the text to display with 2 decimal places
                        let d = RRValue / 1000
                        let formattedString = String(format: "%.2f", d)
//                        print("formattedString\(formattedString)")
                        delegate?.rrValueData(formattedString)

                    }
                } else {
                        // Handle the case where RRInterval key doesn't exist
//                    print("RRInterval key doesn't exist")
                    delegate?.rrValueData("-")
                }

                if json["PRInterval"] != nil {
                    let PRInterval = json["PRInterval"].doubleValue
                    if PRInterval <= 0 {
                            // Set the text to "-" if RRInterval is less than or equal to 0
                        delegate?.prValueData("-")
                    } else {
                            // Convert RRInterval to seconds and format the text to display with 2 decimal places
                        let d = PRInterval / 1000
                        let formattedString = String(format: "%.2f", d)
//                        print("formattedString PRInterval\(formattedString)")
                        delegate?.prValueData(formattedString)
                    }
                } else {
                        // Handle the case where RRInterval key doesn't exist
//                    print("PRInterval key doesn't exist")
                    delegate?.prValueData("-")
                }

                if json["QTInterval"] != nil {
                    let QTInterval = json["QTInterval"].doubleValue
                    if QTInterval <= 0 {
                            // Set the text to "-" if RRInterval is less than or equal to 0
                        delegate?.qtValueData("-")
                    } else {
                            // Convert RRInterval to seconds and format the text to display with 2 decimal places
                        let d = QTInterval / 1000
                        let formattedString = String(format: "%.2f", d)
//                        print("formattedString QTInterval\(formattedString)")
                        delegate?.qtValueData(formattedString)
                    }
                } else {
                        // Handle the case where RRInterval key doesn't exist
//                    print("QTInterval key doesn't exist")
                    delegate?.qtValueData("-")
                }

                if json["QRSComplex"] != nil {
                    let QRSComplex = json["QRSComplex"].doubleValue
                    if QRSComplex <= 0 {
                            // Set the text to "-" if RRInterval is less than or equal to 0
                        delegate?.qrValueData("-")
                    } else {
                            // Convert RRInterval to seconds and format the text to display with 2 decimal places
                        let d = QRSComplex / 1000
                        let formattedString = String(format: "%.2f", d)
//                        print("formattedString QRSComplex\(formattedString)")
                        delegate?.qrValueData(formattedString)
                    }
                } else {
                        // Handle the case where RRInterval key doesn't exist
//                    print("QRSComplex key doesn't exist")
                    delegate?.qrValueData("-")
                }


                if json["PRseg"] != nil {
                    let PRseg = json["PRseg"].doubleValue
                    if PRseg <= 0 {
                            // Set the text to "-" if RRInterval is less than or equal to 0
                        delegate?.prSegValueData("-")
                    } else {
                            // Convert RRInterval to seconds and format the text to display with 2 decimal places
                        let d = PRseg / 1000
                        let formattedString = String(format: "%.2f", d)
//                        print("formattedString PRseg\(formattedString)")
                        delegate?.prSegValueData(formattedString)
                    }
                } else {
                        // Handle the case where RRInterval key doesn't exist
//                    print("PRseg key doesn't exist")
                    delegate?.prSegValueData("-")
                }


                if json["STseg"] != nil {
                    let STseg = json["STseg"].doubleValue
                    if STseg <= 0 {
                            // Set the text to "-" if RRInterval is less than or equal to 0
                        delegate?.stSegValueData("-")
                    } else {
                            // Convert RRInterval to seconds and format the text to display with 2 decimal places
                        let d = STseg / 1000
                        let formattedString = String(format: "%.2f", d)
//                        print("formattedString STseg\(formattedString)")
                        delegate?.stSegValueData(formattedString)
                    }
                } else {
                        // Handle the case where RRInterval key doesn't exist
//                    print("STseg key doesn't exist")
                    delegate?.stSegValueData("-")
                }




            } else {
//                print("Failed to convert message payload to string")

            }



        }

    }

    func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopics success: NSDictionary, failed: [String]) {
//        print("subscribed: \(success), failed: \(failed)")
    }

    func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopics topics: [String]) {
//        print("topic: \(topics)")
    }

    func mqttDidPing(_ mqtt: CocoaMQTT) {
//        print("mqttDidPing")
    }

    func mqttDidReceivePong(_ mqtt: CocoaMQTT) {
//        print("mqttDidReceivePong")
    }

    func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) {
        print("mqttDidDisconnect")
        let hexa = getSerialNoInBytes1(isLive: false)
        if(connectedDevicePeri != nil){
            peripheralWriteDataClear(peripheral: (connectedDevicePeri)!, command: (hexStringToByteArray(hexa)))
        }
    }
    func mqtt(_ mqtt: CocoaMQTT, didReceiveTrust trust: SecTrust, completionHandler: @escaping (Bool) -> Void) {
        print("didReceiveTrust callled...")
            completionHandler(true)
        }

    var isBtnTrigger: Bool = false
    var mqttConnectionStatus=""
    var patchevent:Int = 0
    var findIntervals: [FindInterval] = []
    var findIntervals_threesec: [FindInterval] = []
    var findIntervalsOffline: [FindInterval] = []
    var positionXYZlist: [PositionXYZ] = []
    var positionXYZlistOffline: [PositionXYZ] = []
        //27 number patch
        //let patientMongoId:String="65c49aea29f6a5db52a526e2"
        //66 patch
    var patientMongoId:String=""
    var rpmMongoId:String=""
    var kitMongoId:String=""
//    let defaultHost = "oomcardiodev.projectkmt.com"

// let defaultHost = "oomcardiotest.projectkmt.com"
// var mqtt: CocoaMQTT5?

    var mqtt: CocoaMQTT?
    
//    var mqttDelivery: CocoaM
    var centralManager:CBCentralManager?
    @Published var bleDevices:Array<CBPeripheral> = []
    @Published var isConnected:Bool = false
    var serialNumber:String = ""
    var connectedDevice:CBPeripheral?
    var manufactureData:Any?
    var characteristic1801:CBCharacteristic?
    var characteristic1807:CBCharacteristic?
    var writeCharacteristic1802:CBCharacteristic?
    
    var firmwareUpdateService:CBService?
    var firmWareUpdateCharacteristices:CBCharacteristic?
    
    var OADService:CBService?
    var OADCharacteristices1:CBCharacteristic?
    var OADCharacteristices3:CBCharacteristic?
    var OADCharacteristices5:CBCharacteristic?
    
    var ydata:Array<Double> = [1,1.2,1.3,1.0,1,1.0,]
    @Published var chartData: [(wave:Int,voltage:Double)] = []
    @Published var dataValues:ChartDataEntry = ChartDataEntry(x: 0, y: 0)

    var dataPublisher: AnyPublisher<ChartDataEntry, Never> {
        $dataValues.eraseToAnyPublisher()
    }

    @Published var scanning:Bool = true
    var removeDataSize:Int?=1000;
    @Published  var connectedDevicePeri: CBPeripheral? = nil
    var wave1: Double = 0
    var wave1one: Double = 0
    var wave1Two: Double = 0
    var wave1Tthree: Double = 0
    var wave1Four: Double = 0
    var wave1Five: Double = 0
    var wave1Six: Double = 0
    var wave1Seven: Double = 0
    var wave1Eight: Double = 0
    var wave1Nine: Double = 0
    var wave1Ten: Double = 0
    var wave1Eleven: Double = 0
    var wave1Twelve: Double = 0

    weak var delegate: BLEManagerDelegate?
    weak var delegateFlashMemory: BLEManagerDelegate?
    weak var delegateSyncPending: BLEManagerDelegate?

    weak var delegate12lead: BLEManagerDelegate?
    weak var delegate12lead2: BLEManagerDelegate?
    weak var delegate12lead3: BLEManagerDelegate?

    weak var delegate12leadv1: BLEManagerDelegate?
    weak var delegate12leadv2: BLEManagerDelegate?
    weak var delegate12leadv3: BLEManagerDelegate?
    weak var delegate12leadv4: BLEManagerDelegate?
    weak var delegate12leadv5: BLEManagerDelegate?
    weak var delegate12leadv6: BLEManagerDelegate?
    weak var delegate12leadvavr: BLEManagerDelegate?
    weak var delegate12leadvavl: BLEManagerDelegate?
    weak var delegate12leadvavf: BLEManagerDelegate?

    var forcefullyDisconnect: Bool? = false

// var mqttSession: MQTTSession!

    private var mTimer10Sec:Timer?
    private var mTimer3Sec:Timer?
    private var mTimer1Sec:Timer?
    private var mTimerOffline15Sec:Timer?

    var userObject:UserData?=nil

    var createdDate:Date?=nil

    let encoder = JSONEncoder()

    var ecgVersion:String=""

    var isInternetConnected = true

    //position custom
    var position: Int? = 0
    let positionDetection = PositionDetection()

    @Published var flashValue: Int = 0
    @Published var lastDataArray: Int64 = 0
    @Published var dataArray: Int64 = 0
    
    var reconnectAttempts = 0
        let maxReconnectAttempts = 10

    func formatDuration(from payload: String) -> String {
        guard let random = Double(payload) else { return "Invalid input" }
        let durationInMilliseconds = random * 60 * 60
        var seconds = Int(durationInMilliseconds)

        let days = seconds / (24 * 3600)
        seconds %= 24 * 3600
        let hours = seconds / 3600
        seconds %= 3600
        let minutes = seconds / 60
        seconds %= 60

        var stringBuilder = ""
        if days > 0 {
            stringBuilder += " Day: \(days)"
        }
        if hours > 0 {
            stringBuilder += " Hour: \(hours)"
        }
        if minutes > 0 {
            stringBuilder += " Min: \(minutes)"
        }
        if seconds > 0 {
            stringBuilder += " Sec: \(seconds)"
        }

        return stringBuilder
    }
    func mqttSetting() {

        print("mqttSetting ...\(patientMongoId)")
        let msg: [String: Any] = ["status": "Disconnected", "reason": 6]
            //        for MQTT 3.1.1
        let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
//        mqtt = CocoaMQTT(clientID: clientID, host: defaultHost, port: 1883)
        mqtt = CocoaMQTT(clientID: clientID, host: Constants.defaultHost, port: UInt16(Constants.port))

// mqtt!.logLevel = .debug
mqtt!.username = Constants.mqttUsername
mqtt!.password = Constants.mqttPassword
// mqtt!.username = "kmt"
// mqtt!.password = "Kmt123"

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: msg, options: [])
            if let jsonString = String(data: jsonData, encoding: .utf8) {

// print("JSON string:", jsonString)
mqtt!.willMessage = CocoaMQTTMessage(topic: "oom/ecg/ecgConnectionStatus/"+patientMongoId, string: jsonString, qos: .qos1,retained:true)
}
} catch {
print("Error converting to JSON:", error)
}

// mqtt?.deliverTimeout
mqtt!.keepAlive = 60
// mqtt!.keepAlive = 10
mqtt!.delegate = self
mqtt!.autoReconnect = true
// mqtt!.cleanSession=false
mqtt!.autoReconnectTimeInterval = 5
// Configure additional settings for stability
mqtt!.enableSSL = false // Disable SSL for testing (if applicable)
// mqtt!.cleanSession = true // Ensure a clean session
mqtt!.cleanSession = false // Ensure a clean session
// mqtt!.autoReconnectTimeInterval = 60
// mqtt!.autoReconnectTimeInterval = 10
// mqtt!.logLevel = .debug
// mqtt!.didConnectAck
// mqtt!.top

            //        mqtt.bufferSize = 2048
        mqtt?.allowUntrustCACertificate = true
        reconnectAttempts = 0
        _ = mqtt!.connect()

            ///MQTT 5.0
            //        let clientID = "CocoaMQTT-" + String(ProcessInfo().processIdentifier)
            //        mqtt = CocoaMQTT5(clientID: clientID, host: Constants.defaultHost, port: UInt16(Constants.port))
            //
            //        let connectProperties = MqttConnectProperties()
            //        connectProperties.topicAliasMaximum = 0
            //        connectProperties.sessionExpiryInterval = 0
            //        connectProperties.receiveMaximum = 500
            //        connectProperties.maximumPacketSize = 500
            //        mqtt!.connectProperties = connectProperties
            //
            //        mqtt!.logLevel = .debug
            //        mqtt!.username = Constants.mqttUsername
            //        mqtt!.password = Constants.mqttPassword
            //        mqtt!.willMessage = CocoaMQTT5Message(topic: "/will", string: "dieout")
            //        mqtt!.keepAlive = 60
            //        mqtt!.delegate = self
            //        mqtt!.autoReconnect = true
            //        mqtt!.cleanSession=false
            //
            ////        mqtt!.allowUntrustCACertificate = true
            //
            //        _ = mqtt!.connect()

    }
    func  disconnectMQTTCall(){
        
        print("disconnectMQTTCall call")
        if mqtt !== nil {
            mqtt?.disconnect()
        }
        if mTimer1Sec !== nil {
            print("disconnectMQTTCall mTimer1Sec")
            mTimer1Sec?.invalidate()
            mTimer1Sec = nil
        }
        if mTimer10Sec !== nil {
            mTimer10Sec?.invalidate()
            mTimer10Sec = nil
        }

        if mTimer3Sec !== nil {
            mTimer3Sec?.invalidate()
            mTimer3Sec = nil
        }
        if mTimerOffline15Sec !== nil {
            mTimerOffline15Sec?.invalidate()
            mTimerOffline15Sec = nil
        }
        findIntervals.removeAll()
        positionXYZlist.removeAll()
        scanning=false

    }
    func  logoutFromMQTTCall(){
        print("logoutFromMQTTCall call")
        patchevent = 4
        sendBluetoothStatus(value: "Disconnected")
    }


    func randomStringWithLength(_ len: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

        var randomString = String()
        for _ in 0..<len {
            let length = UInt32(letters.count)
            let rand = arc4random_uniform(length)
            let index = String.Index(encodedOffset: Int(rand))
            randomString += String(letters[index])
        }
        return String(randomString)
    }
    func closeApplication(ackgroundTaskIdentifier: UIBackgroundTaskIdentifier?){
        print("AppDelegate terminate call...closeApplication")
        patchevent=0
//        DispatchQueue.main.async {
        sendBluetoothStatusKill(value: "Disconnected",ackgroundTaskIdentifier: ackgroundTaskIdentifier)
//        }
    }

Thanks in Advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions