![](/img/trans.png)
[英]How to figure out the country of a device connected to AWS IoT Core
[英]Disconnect AWS IoT device after it's connected
我正在开发一个 web 应用程序,用户可以在其中使用 AWS Cognito 登录。 使用 AWS 凭据登录后,我正在连接到 AWS IoT 设备,例如
var device = AwsIot.device({
clientId: clientID,
host: host,
accessKeyId: credentials.accessKeyId,
secretKey: credentials.secretAccessKey,
protocol: 'wss',
sessionToken: credentials.sessionToken,
offlineQueueing: 'false'
});
然后,一旦用户使用 AWS Cognito 从应用程序注销,使用
cognitoUser.signOut();
然后在注销后我也想断开 AWS IoT 设备。 现在我什至在注销后看到设备正在收听类似的事件
device.on('close', function() {})
device.on('error', function() {})
device.on('offline', function() {})
有人可以指定我应该调用哪个 function 来断开设备连接,这样它也不会监听这些事件。
我正在浏览文档https://github.com/aws/aws-iot-device-sdk-js但我没有为此得到任何具体的 function。
此外,我使用 AWS 凭证连接 AWS IoT 设备,一旦我从 Cognito 注销,我认为设备也应该自动断开连接。 请让我知道这里应该采用什么方法。
我从 AWS IOT 支持团队那里得到了答案。
AwsIot.device
类是 MQTT 类的包装器,具有帮助连接到 AWS 端点的帮助程序。要断开设备连接,您可以调用device.end();
这将关闭您的连接并调用device.on('close')
。 至于 Cognito 注销。 这不会使 Cognito 已经提供的用于建立连接的会话凭据失效。 他们将继续有效,直到他们的担任角色时间到期。
您可以使用 AWS IoT Core 的属性强制客户端断开连接,即任何时候只有一个由 clientId 标识的给定客户端可以连接到代理。
因此,当您需要强制断开某个客户端时,您可以启动与新客户端的连接 - 使用不同的凭据 - 和相同的 clientId。
此代码在附加了必要的 IAM 策略的 Lambda function 中执行此操作; 它通过将AWS_ACCESS_KEY_ID
、 AWS_SECRET_ACCESS_KEY
和AWS_SESSION_TOKEN
传递给AWSClientIoT.device()
function 来使用 AWS session:
import * as AWSClientIoT from 'aws-iot-device-sdk';
import { DescribeEndpointCommand, IoTClient } from '@aws-sdk/client-iot';
// Find out address of endpoint
const endpoint = await new IoTClient({}).send(new DescribeEndpointCommand({ endpointType: 'iot:Data-ATS' }));
const host = endpoint.endpointAddress;
this.logger.info(`Initiating disconnect of device ${deviceUuid.toString()} @ ${host}`);
const client = new AWSClientIoT.device({
protocol: 'wss',
accessKeyId: mustGetEnv('AWS_ACCESS_KEY_ID'),
secretKey: mustGetEnv('AWS_SECRET_ACCESS_KEY'),
sessionToken: mustGetEnv('AWS_SESSION_TOKEN'),
// Using the deviceUuid as the clientId is done by the device. Using this violates
// the requirement that clientIds have to be unique on the device gateway, so the
// original device will be disconnected.
clientId: deviceUuid.toString(),
host,
connectTimeout: 1000,
resubscribe: false,
});
// Wait until connected, when this resolves the "remote" client
// has been forcefully disconnected
await new Promise<void>((resolve, reject) => {
client
.on('connect', () => {
this.logger.debug('Connected!');
resolve();
return;
})
.on('reconnect', () => this.logger.debug('Reconnecting'))
.on('offline', () => this.logger.debug('Offline'))
.on('error', (error) => {
this.logger.error(error);
reject(error);
return;
});
});
// Disconnect ourselves
await new Promise<void>((resolve) =>
client.end(true, () => {
resolve();
}),
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.