AWS Amplify で Eclipse Mosquitto に接続

AWS Amplify で Eclipse Mosquitto に接続

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
3 min read
Amplify Angular

AWS Amplify は、ローカル環境で Eclipse Mosquitto を MQTT メッセージブローカーとして利用できます。 Docker イメージも提供されています。 AWS IoT Core に接続するアプリケーションを開発する際、 Mosquitto をローカルで実行することで、他の Subscriber にメッセージを Publish せずにアプリケーションの動作を確認できます。

前提条件

この投稿は、以下のソフトウェアを利用しました。

SoftwareVersion
Node.js12.13.1
Angular9.0.7
aws-amplify3.0.9
aws-amplify-angular5.0.9
mqtt3.0.0

Angular アプリケーション作成

ディレクトリ構成

/
|-- docker/
|   |-- mosquitto/
|   |   `-- mosquitto.conf
|   `-- docker-compose.yml
|-- src/
|   |-- app/
|   |   |-- app.component.html
|   |   |-- app.component.ts
|   |   `-- ...
|   `-- ...
|-- package.json
`-- ...

Project 作成

以下のコマンドで Angular アプリケーションプロジェクトを作成してください。

ng new angular-mosquitto-sample
npm i --save [email protected] [email protected] [email protected]

Mosquitto コンテナ作成

以下の内容で docker/docker-compose.yml を作成してください。

version: '3.4'

services:
  mosquitto:
    image: eclipse-mosquitto:1.6.9
    ports:
      - 1883:1883 # MQTT
      - 9001:9001 # WebSocket
    volumes:
      - ./mosquitto:/mosquitto/config

以下の内容で docker/mosquitto/mosquitto.conf を作成してください。

listener 1883
listener 9001
protocol websockets

以下のコマンドで、 Mosquitto コンテナをメッセージブローカーとして起動してください。

docker-compose up -d

Angular コーディング

src/polyfills.ts を編集し、 (window as any).global = window; を追加してください。

/**
 * ...
 */

/***************************************************************************************************
 * APPLICATION IMPORTS
 */

// Add
(window as any).global = window;

src/app/app.component.html を以下の内容で編集してください。

<h1>Received messages</h1>
<hr/>
<div *ngFor="let message of messages">
  {{message}}
</div>

src/app/app.component.ts を以下のコードで編集してください。 AWS Amplify は PubSubMqttOverWSProvider を提供しています。

import {Component, OnInit} from '@angular/core';
import { PubSub } from 'aws-amplify';
import { MqttOverWSProvider } from '@aws-amplify/pubsub/lib/Providers';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  messages = [];

  ngOnInit() {
    PubSub.addPluggable(new MqttOverWSProvider({
      aws_pubsub_endpoint: 'ws://localhost:9001/',
      // Do not use SSL
      aws_appsync_dangerously_connect_to_http_endpoint_for_testing: true,
    }));

    PubSub.subscribe('test-topic').subscribe(payload => {
      console.log(payload);
      this.messages.push(payload.value.message);
    });
  }
}

テスト

以下のコマンドで、ローカルの Mosquitto メッセージブローカーに MQTT メッセージをパブリッシュしてください。

mqtt pub -t 'test-topic' -h localhost -p 1883 -m '{"message": "Hello World"}'

Angular アプリケーションがメッセージを受信しているのを確認できるはずです。

Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at iret, Inc.
主に AWS を利用したクラウドネイティブアプリケーションの設計および開発をしています。 Japan AWS Top Engineers 2020-2023