Help us understand the problem. What is going on with this article?

Amplify (js)の PubSubを使ってAWS IoT Core にメッセージをPublishする

More than 1 year has passed since last update.

基本的なやりかた

https://aws-amplify.github.io/docs/js/pubsub

MQTT 接続

Auth.currentCredentials().then(info => {
  const cognitoIdentityId = info._identityId;
  console.log("cognito identity id", cognitoIdentityId); // debug
    Amplify.addPluggable(new AWSIoTProvider({
        aws_pubsub_region: 'ap-northeast-1',
        aws_pubsub_endpoint: 'wss://xxxxx.iot.ap-northeast-1.amazonaws.com/mqtt',
        clientId: 'your-client-id'
       }));
});

Cognito ログイン画面

    <amplify-authenticator></amplify-authenticator>

publish

import { PubSub } from 'aws-amplify';
export default {
  // 中略
  methods: {
    publish: async function () {
        await PubSub.publish('v1/topic/abc', {
            "key": "value"
        });
    }
  }

ハマったところ

errorCode: 8, errorMessage: AMQJS0008I Socket closed.

PubSub.publishのエラーで上記が出た。

こちらの記事を参考にして、Cognito のIdentity IDに対して、コマンドライン上からIoTのポリシーをアタッチすることで解決しました。
https://qiita.com/poruruba/items/34d4d7247d152b1ec933

aws iot attach-policy --policy-name "<IoT Coreで作成したポリシー>" --target <Identity ID>

Identity ID は、GUI上で、CognitoのFederated Identity のページで、Identity Browserを選択すると表示されます。上述のMQTT接続のところで、 info._identityId; でも取得できます。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away