我正在使用此库来处理我的 AWS IoT MQTT 主题。但是,在尝试连接到以下格式的 presigned-url 时遇到了问题:
wss://<endpoint>.iot.us-west-2.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>%2Fus-west-2%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=<date>&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>&X-Amz-Security-Token=<security-token>
这是我用于此测试的示例代码:
import * as mqtt from 'mqtt';
try {
const options: Partial<IClientOptions> = {
will: {
topic: 'hello',
payload: JSON.stringify({ clientId: '1', username: 'sean' }),
qos: 1,
retain: true
},
port: 443,
clientId: '1',
username: 'sean'
};
const client = mqtt.connect(
request.url,
options);
console.log(client);
client.on('connect', function() {
client.subscribe('hello', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
});
});
client.on('error', (err) => {
console.log('error', err);
client.end()
});
} catch (error) {
console.log(error);
}
不幸的是,当我启动网页时,我在 Chrome 开发工具中收到以下重复错误:
WebSocket connection to <AWS IoT Url> failed:
通常,在 '... failed:' 字符串后会显示实际的错误消息。在代码中,我看到一个 nop 函数正在记录错误。只是好奇什么错误通常会导致 nop 函数被调用,以及我如何开始测试为什么我的网址无法连接?
发现我的 AWS IoT IAM 凭证无效,因此无法正确连接到云。如果开发人员有时间,如果连接函数能够通知这可能是问题所在,那将会很有用。当前显示空错误消息的功能使得实际调试问题变得困难🤔
https://stackoverflow.com/a/68399355/10403160 - 此评论也是正确的。
我已经用这个方法解决了这个问题!
我的问题是在用户注销后。即使 MQTT 断开连接且客户端被清除后,MQTT 仍会尝试与订阅者重新连接。因此,会发生凭证为空的情况,因为用户已注销并且 MQTT 正在尝试自动重新连接。所以会抛出这个错误。
_setUpMqttClient()是MQTT连接到客户端时执行的函数。
void _setUpMqttClient() {
_url = _prepareWebSocketUrl();
_client = mqttsetup.setup(_url, _clientId);
// Set the protocol to V3.1.1 for AWS IoT Core, if you fail to do this you will not receive a connect ack with the response code
_client.setProtocolV311();
_client.logging(on: _logging);
_client.autoReconnect = true;
_client.port = 443;
_client.keepAlivePeriod = 30;
_client.disconnectOnNoResponsePeriod = 1;
_client.onDisconnected = awsInterface.onDisConnected;
_client.onConnected = awsInterface.onConnected;
_client.onSubscribed = awsInterface.onSubScribed;
_client.onSubscribeFail = awsInterface.onSubscribeFail;
_client.onUnsubscribed = awsInterface.onUnsubscribed;
_client.onAutoReconnect = awsInterface.onAutoReconnect;
_client.onAutoReconnected = awsInterface.onAutoReconnected;
_client.resubscribeOnAutoReconnect = true;
_client.connectionMessage =
MqttConnectMessage().withClientIdentifier(_clientId).startClean();
}
String get clientId => _clientId;
stopAutoReconnect() 在注销用户或您想要禁用自动重新连接时调用此函数。
void stopAutoReconnect() {
_client?.autoReconnect = false;
_client?.resubscribeOnAutoReconnect = false;
}
在注销时写入此代码。
static Future<void> onLogOutTap() async {
AwsMqttConnection.client.stopAutoReconnect();
AwsMqttConnection.instance.disConnect();
AwsMqttConnection.instance.clear();
}