使用 Watson 和 IoT Platform 服务构建家庭助理移动应用程序(9)
 
- UID
- 1066743
|

使用 Watson 和 IoT Platform 服务构建家庭助理移动应用程序(9)
初始化- 在 AppDelegate.swift 文件中声明一个全局变量,因为 MQTT 连接必须在应用程序级别上进行处理,而不是在视图级别上。使用主机名、端口和客户端 ID 初始化 MQTT 客户端。
1
2
| let mqttClient = CocoaMQTT(clientID: Credentials.WatsonIOTClientID,
host: Credentials.WatsonIOTHost, port: UInt16(Credentials.WatsonIOTPort))
|
- host name:[ORG_ID].messaging.internetofthings.ibmcloud.com
- port:1883
- client ID:a:[ORG_ID]:[API_KEY]
- 创建一个名为 MqttExt.swift 的文件,以包含连接 Watson IoT Platform 服务的代码。为 ViewController 声明一个扩展并实现 CocoaMQTTDelegate。
1
2
| extension ViewController : CocoaMQTTDelegate {
}
|
- 将用户名初始化为 [API_KEY],将密码初始化为 [AUTH_TOKEN],并将它自己设置为代理。
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()
}
|
实现 MQTT 回调- 实现下面的回调来接收连接成功事件。连接后,调用该回调来订阅该事件主题,主题的格式为 iot-2/type/[DEV_TYPE]/id/[DEV_ID]/evt/+/fmt/json,其中 + 是通配符。
1
2
3
| func mqtt(_ mqtt: CocoaMQTT, didConnect host: String, port: Int) {
mqttClient.subscribe(eventTopic)
}
|
- 实现 didReceiveMessage() 回调函数来处理来自设备的事件。如果该函数从相机收到一个状态,则从 Object Storage 服务下载该照片。否则,如果该函数从 light 收到一个状态,则向对话附加一条消息。
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
}
}
|
向设备发送命令实现此函数来向设备发送命令。主题的格式为 iot-2/type/[DEV_TYPE]/id/[DEV_ID]/cmd/[light|camera]/fmt/json。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)
}
}
|
|
|
|
|
|
|