Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disconnected from MQTT, error: Optional(Error Domain=MGCDAsyncSocketErrorDomain Code=8 "Error in SSLSetCertificate" UserInfo={NSLocalizedDescription=Error in SSLSetCertificate}) #616

Open
Shahanshah-TA opened this issue Oct 9, 2024 · 2 comments

Comments

@Shahanshah-TA
Copy link

Shahanshah-TA commented Oct 9, 2024

I am trying to connect with MQTT with .crt certificate, I am getting this error.
Disconnected from MQTT, error: Optional(Error Domain=MGCDAsyncSocketErrorDomain Code=8 "Error in SSLSetCertificate" UserInfo={NSLocalizedDescription=Error in SSLSetCertificate})
Anything which I am doing wrong here

import Foundation
import CocoaMQTT

class MQTTManager: CocoaMQTTDelegate {
    func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: (any Error)?) {
        print("Disconnected from MQTT, error: \(String(describing: err))\n")
    }
    
    var mqtt: CocoaMQTT!

    func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) {
        print("Published message with ID: \(id)")
    }

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

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

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

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

    func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: (Error?)?) {
        print("Disconnected from MQTT, error: \(String(describing: err))")
    }

    func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) {
        if ack == .accept {
            print("Connected to the MQTT broker!")
            // Subscribe to a topic only after a successful connection
            subscribeToTopic(topic: "your-topic")
        } else {
            print("Failed to connect to MQTT")
        }
    }

    func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) {
        print("Published message: \(message.string ?? "") with ID: \(id)")
    }

    func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) {
        if let messageString = message.string {
            print("Received message on topic \(message.topic): \(messageString)")
        }
    }

    func connectMQTT(sasToken: String, assignedHub: String, registrationId: String,uuid: String, certificate: String, otp: String,deviceKey: String, modelId: String) {
        mqtt = CocoaMQTT(clientID: registrationId, host: assignedHub, port: 8883)
        print("Attempting to connect to MQTT broker... with client ID:\(String(describing: mqtt)) & \(mqtt.clientID)")
        mqtt.delegate = self
        mqtt.username = "\(assignedHub)/\(registrationId)/?api-version=2021-04-12";
        mqtt.password = sasToken;
        
        let certPath = Bundle.main.path(forResource: "DigiCertGlobalRootG2", ofType: "crt")!
              let certData = try? Data(contentsOf: URL(fileURLWithPath: certPath))
             let certArray = [certData] as CFArray
              let sslSettings: [String: NSObject] = [
                  kCFStreamSSLLevel as String: kCFStreamSocketSecurityLevelNegotiatedSSL,
                  kCFStreamSSLValidatesCertificateChain as String: true as NSObject,
                  kCFStreamSSLCertificates as String: certArray as NSObject
              ]
            mqtt.enableSSL = true
        mqtt.allowUntrustCACertificate = true
        mqtt.sslSettings=sslSettings
        
        
        mqtt.connect()
    }

}

@zmstone @ptescher @gabrielPeart @nobre84

@Shahanshah-TA Shahanshah-TA changed the title Disconnected from MQTT, error: Optional(Error Domain=MGCDAsyncSocketErrorDomain Code=7 "Socket closed by remote peer" UserInfo={NSLocalizedDescription=Socket closed by remote peer}) Disconnected from MQTT, error: Optional(Error Domain=MGCDAsyncSocketErrorDomain Code=8 "Error in SSLSetCertificate" UserInfo={NSLocalizedDescription=Error in SSLSetCertificate}) Oct 10, 2024
@mert-akan
Copy link

@Shahanshah-TA have you found a solution?

I am trying for the first time to connect to an MQTT server with certificates and I am not sure what to change

@Shahanshah-TA
Copy link
Author

@mert-akan I used this package and it worked. https://github.com/swift-server-community/mqtt-nio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants