LoginSignup
3
2

More than 3 years have passed since last update.

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

Posted at

基本的なやりかた

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; でも取得できます。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2