AWS Amplify と Eclipse Mosquitto を連携した MQTT メッセージング

AWS Amplify と Eclipse Mosquitto を連携した MQTT メッセージング

AWS Amplify の PubSub モジュールを AWS IoT Core に接続する前に、ローカルの Eclipse Mosquitto ブローカーでテストする方法を紹介します。

Takahiro Iwasa
3 min read

Eclipse Mosquitto をローカルの MQTT ブローカーとして使うと、AWS Amplify の PubSub モジュールを AWS IoT Core へ接続する前に動作を確認できます。

Eclipse Mosquitto のセットアップ

以下の内容で docker/docker-compose.yml ファイルを作成します。

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 コンテナを起動します。

Terminal window
docker-compose up -d

Angular アプリケーションの構築

新しい Angular アプリケーションを作成し、必要な依存関係をインストールします。

Terminal window
ng new angular-mosquitto-sample

src/polyfills.ts を更新します。

src/polyfills.ts
/**
* ...
*/
/***************************************************************************************************
* APPLICATION IMPORTS
*/
// Add the following:
(window as any).global = window;

src/app/app.component.html を編集します。

src/app/app.component.html
<h1>Received messages</h1>
<hr/>
<div *ngFor="let message of messages">
{{ message }}
</div>

src/app/app.component.ts を編集します。

src/app/app.component.ts
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);
});
}
}

アプリケーションのテスト

以下のコマンドで mqtt をインストールします。

Terminal window
npm i --save-dev mqtt

ローカルの Mosquitto ブローカーに MQTT メッセージを送信します。

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

Angular アプリケーションに、受信したメッセージがリアルタイムで表示されます。

まとめ

docker-compose でローカルの Mosquitto ブローカーを起動し、Amplify の PubSub モジュールを介して Angular アプリケーションへ接続すると、AWS IoT Core のリソースを作成せずに MQTT メッセージの送受信を確認できます。MqttOverWSProvider は MQTT over WebSocket に対応するブローカーで利用できるため、接続先が localhost:9001 の Mosquitto でも AWS IoT Core でも、window.global のポリフィルと PubSub.subscribe('test-topic') の呼び出しは変わりません。

ローカルテストを終えたら、aws_appsync_dangerously_connect_to_http_endpoint_for_testing を削除してください。このオプションは例で使用する非セキュアな接続を許可するものであり、本番環境では有効にしないでください。

About the author

Takahiro Iwasa

Takahiro Iwasa

Software Developer

This blog shares technical notes from hands-on projects—architecture, implementation, and AWS service integrations.