websocket 如何在Angular中订阅我的AWS IoT主题?

u3r8eeie  于 2023-05-07  发布在  Angular
关注(0)|答案(1)|浏览(117)

我找了好几个小时,什么都试过了,但就是不行。我有一个ESP 32,它可以发送/接收关于特定主题的物联网消息。这是我当前要发布的代码:

region = "eu-central-1";
identityPoolId = "eu-central-1:83xxxcba-b15f-xxx-bcef-xxxxxxxxx";
iotEndpoint = "wss://axxxxxxdp6-ats.iot.eu-central-1.amazonaws.com";

cognitoCredentials = fromCognitoIdentityPool({
  identityPoolId: this.identityPoolId,
  accountId: "xxxxxxxxxx",
  clientConfig: {
    region: this.region,
  }
});

iotDataClient = new IoTDataPlaneClient({
  region: this.region,
  endpoint: this.iotEndpoint,
  credentials: this.cognitoCredentials,
});

这是我的sendMessage()方法:

sendMessage(topic: string, string: string) {
const params: PublishCommandInput = {
  topic: topic,
  payload: this.stringToByteArray(string),
};

const command = new PublishCommand(params);

this.iotDataClient
  .send(command)
  .then((data) => console.log("Message sent:", data))
  .catch((err) => console.error(err));

}
我问ChatGPT我如何订阅一个主题,它说你可以在IoTClient上调用subscribe(),但它不起作用,我有错误的sdk版本吗?(aws-sdk-v2)。我知道客户端JavaScript不支持MQTT,但使用WebSockets可以做到。我只是还没想明白。有人知道这是怎么回事吗?

hsgswve4

hsgswve41#

经过几个小时的努力,我终于得到了它。我希望我能在这方面帮助到别人

build_connection() {
    const aws_access_id = 'xxxxxxxx';
    const aws_secret_key = 'secret';

    const client_id = 'Angular-Client';
    const config_builder =
         iot.AwsIotMqttConnectionConfigBuilder.new_with_websockets()
    const client_bootstrap = new io.ClientBootstrap();

    config_builder.with_clean_session(false);
    config_builder.with_client_id(client_id);
    config_builder.with_endpoint(this.iotEndpoint.replace("https://", ""));

    config_builder.with_credentials(this.region, aws_access_id, 
        aws_secret_key);
    const config = config_builder.build();
    config.keep_alive = 5;
    config.use_websocket = true;

    const client = new mqtt.MqttClient(client_bootstrap);
    const connection = client.new_connection(config);

    connection.on('error', error => {
       console.log(error);
    });

    connection.on('connect', () => {
       console.log("Connected!");

       connection.subscribe("your/topic", 10);
    })

    connection.on('message', (topic, payload, dup, qos, retain) => {
       console.log("Received: " + this.arrayToString(payload));
    })
}

arrayToString(bufferValue: ArrayBuffer) {
   return new TextDecoder("utf-8").decode(bufferValue);
}

stringToByteArray(string: string): Uint8Array {
  const result = new Uint8Array(string.length);
  for (let i = 0; i < string.length; i++) {
    result[i] = string.charCodeAt(i);
  }
  return result;
}

相关问题