1 2 | let mqttClient = CocoaMQTT(clientID: Credentials.WatsonIOTClientID, host: Credentials.WatsonIOTHost, port: UInt16(Credentials.WatsonIOTPort)) |
1 2 | extension ViewController : CocoaMQTTDelegate { } |
1 2 3 4 | mqttClient.username = Credentials.WatsonIOTUsername mqttClient.password = Credentials.WatsonIOTPassword mqttClient.keepAlive = 60 mqttClient.delegate = self |
1 2 3 | func applicationDidBecomeActive(_ application: UIApplication) { mqttClient.connect() } |
1 2 3 | func applicationDidEnterBackground(_ application: UIApplication) { mqttClient.disconnect() } |
1 2 3 | func mqtt(_ mqtt: CocoaMQTT, didConnect host: String, port: Int) { mqttClient.subscribe(eventTopic) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) { var json : JSON = JSON.null if let message = message.string { json = JSON.init(parseJSON: message) } else { return // do nothing } let cameraTopic = "iot-2/type/\(Credentials.DevType)/id/\(Credentials.DevId)/evt/camera/fmt/json" let lightTopic = "iot-2/type/\(Credentials.DevType)/id/\(Credentials.DevId)/evt/light/fmt/json" switch message.topic { case cameraTopic: //ObjectStorage if let objectname = json["d"]["objectname"].string { if let containername = json["d"]["containername"].string { self.downloadPictureFromObjectStorage(containername: containername, objectname: objectname) } } case lightTopic: if let status = json["d"]["status"].string { switch status { case "on": self.didReceiveConversationResponse(["Light is on"]) case "off": self.didReceiveConversationResponse(["Light is off"]) default: break } } default: break } } |
1 2 3 4 5 6 7 8 | func sendToDevice(_ command: Command, subtopic: String) { if let json = command.toJSON() { let topic = "iot-2/type/\(Credentials.DevType)/id/\(Credentials.DevId)/cmd/\(subtopic)/fmt/json" let message = CocoaMQTTMessage(topic: topic, string: json) print("publish message \(json)") mqttClient.publish(message) } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |