【发布时间】:2019-02-13 20:43:29
【问题描述】:
如何检查客户端是否连接?
从 Device 类示例中,我了解到 Device 是 mqtt.Client() 返回的实例mqtt.js 有一个连接标志 https://github.com/mqttjs/MQTT.js#connected
但是,device.connected 给了我undefined
【问题讨论】:
如何检查客户端是否连接?
从 Device 类示例中,我了解到 Device 是 mqtt.Client() 返回的实例mqtt.js 有一个连接标志 https://github.com/mqttjs/MQTT.js#connected
但是,device.connected 给了我undefined
【问题讨论】:
我发现了一个获取当前状态的技巧 要在之后监视该状态,您应该使用先前答案中建议的设备连接主题 如果您启用了队列索引设置 确保您启用了“事物连接性”:在事物索引中包含事物连接性数据。
然后您可以运行搜索(针对特定 Thing 或一组事物)并获取每个 Thing 的连接状态:
` AWS = require('aws-sdk');
var iot = new this.AWS.Iot({
accessKeyId: this.AccessKeyId,
secretAccessKey: this.SecretAccessKey,
//endpoint: this.host,
maxResults: 500,
region: this.regionData
});
var params = {
queryString: 'shadow.reported.isConnected.connected = *',
indexName: 'AWS_Things',
nextToken: nexttoken
};
iot.searchIndex(params, function(err, data)
for (const robot of data.things[0])
connectivity = robot.connectivity.connected;`
注意 - 上面的代码不是一个有效的例子,只是为了展示原理 注意 2 - 记住搜索结果是在页面中出现的,需要这样处理
【讨论】:
在 IoT 规则引擎中创建规则并监听生命周期事件。连接物联网设备时,设备连接主题将收到一条消息。
https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html
【讨论】:
因为它不存在。
DeviceClient {
publish: [Function],
subscribe: [Function],
unsubscribe: [Function],
end: [Function],
handleMessage: [Function: bound ],
updateWebSocketCredentials: [Function],
getWebsocketHeaders: [Function],
updateCustomAuthHeaders: [Function],
simulateNetworkFailure: [Function],
_events:
{ connect: [Function],
close: [Function],
reconnect: [Function],
offline: [Function],
error: [Function],
message: [Function] },
_eventsCount: 6 }
虽然您可以监听“connect”事件并自己添加“connected”属性,如下所示
device.on('connect', function() {
device.connected = true;
});
再次检查 DeviceClient,现在您拥有它。
DeviceClient {
publish: [Function],
subscribe: [Function],
unsubscribe: [Function],
end: [Function],
handleMessage: [Function: bound ],
updateWebSocketCredentials: [Function],
getWebsocketHeaders: [Function],
updateCustomAuthHeaders: [Function],
simulateNetworkFailure: [Function],
_events:
{ connect: [Function],
close: [Function],
reconnect: [Function],
offline: [Function],
error: [Function],
message: [Function] },
_eventsCount: 6,
connected: true }
【讨论】:
mqtt 那样维护connected 属性