-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathPubSub5.tsx
More file actions
233 lines (189 loc) · 7.15 KB
/
PubSub5.tsx
File metadata and controls
233 lines (189 loc) · 7.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
import { useEffect} from 'react';
import {mqtt5, auth, iot} from "aws-iot-device-sdk-v2";
import {once} from "events";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
import { CognitoIdentityCredentials } from "@aws-sdk/credential-provider-cognito-identity/dist-types/fromCognitoIdentity"
import {toUtf8} from "@aws-sdk/util-utf8-browser";
// @ts-ignore
import {AWS_REGION, AWS_COGNITO_IDENTITY_POOL_ID, AWS_IOT_ENDPOINT} from './settings';
import jquery from "jquery";
const $: JQueryStatic = jquery;
function log(msg: string) {
let now = new Date();
$('#message').append(`<pre>${now.toString()}: ${msg}</pre>`);
}
/**
* AWSCognitoCredentialOptions. The credentials options used to create AWSCongnitoCredentialProvider.
*/
interface AWSCognitoCredentialOptions
{
IdentityPoolId : string,
Region: string
}
/**
* AWSCognitoCredentialsProvider. The AWSCognitoCredentialsProvider implements AWS.CognitoIdentityCredentials.
*
*/
class AWSCognitoCredentialsProvider extends auth.CredentialsProvider{
private options: AWSCognitoCredentialOptions;
private cachedCredentials? : CognitoIdentityCredentials;
constructor(options: AWSCognitoCredentialOptions, expire_interval_in_ms? : number)
{
super();
this.options = options;
setInterval(async ()=>{
await this.refreshCredentials();
},expire_interval_in_ms?? 3600*1000);
}
getCredentials() : auth.AWSCredentials {
return {
aws_access_id: this.cachedCredentials?.accessKeyId ?? "",
aws_secret_key: this.cachedCredentials?.secretAccessKey ?? "",
aws_sts_token: this.cachedCredentials?.sessionToken,
aws_region: this.options.Region
}
}
async refreshCredentials() {
log('Fetching Cognito credentials');
this.cachedCredentials = await fromCognitoIdentityPool({
// Required. The unique identifier for the identity pool from which an identity should be
// retrieved or generated.
identityPoolId: this.options.IdentityPoolId,
clientConfig: { region: this.options.Region },
})();
}
}
function createClient(provider: AWSCognitoCredentialsProvider) : mqtt5.Mqtt5Client {
let wsConfig : iot.WebsocketSigv4Config = {
credentialsProvider: provider,
region: AWS_REGION
}
let builder: iot.AwsIotMqtt5ClientConfigBuilder = iot.AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth(
AWS_IOT_ENDPOINT,
wsConfig
);
builder.withConnectProperties({
clientId: "test-" + Math.floor(Math.random() * 100000000),
keepAliveIntervalSeconds: 30 // Mandatory field added
});
let client : mqtt5.Mqtt5Client = new mqtt5.Mqtt5Client(builder.build());
client.on('error', (error) => {
log("Error event: " + error.toString());
});
client.on("messageReceived",(eventData: mqtt5.MessageReceivedEvent) : void => {
log("Message Received event: " + JSON.stringify(eventData.message));
if (eventData.message.payload) {
log(" with payload: " + toUtf8(eventData.message.payload as Buffer));
}
} );
client.on('attemptingConnect', (eventData: mqtt5.AttemptingConnectEvent) => {
log("Attempting Connect event");
});
client.on('connectionSuccess', (eventData: mqtt5.ConnectionSuccessEvent) => {
log("Connection Success event");
log ("Connack: " + JSON.stringify(eventData.connack));
log ("Settings: " + JSON.stringify(eventData.settings));
});
client.on('connectionFailure', (eventData: mqtt5.ConnectionFailureEvent) => {
log("Connection failure event: " + eventData.error.toString());
});
client.on('disconnection', (eventData: mqtt5.DisconnectionEvent) => {
log("Disconnection event: " + eventData.error.toString());
if (eventData.disconnect !== undefined) {
log('Disconnect packet: ' + JSON.stringify(eventData.disconnect));
}
});
client.on('stopped', (eventData: mqtt5.StoppedEvent) => {
log("Stopped event");
});
return client;
}
function Mqtt5() {
var client : mqtt5.Mqtt5Client;
var user_msg_count = 0;
const qos0Topic = "/test/qos0";
const qos1Topic = "/test/qos1";
async function testSuccessfulConnection() {
/** Set up the credentialsProvider */
const provider = new AWSCognitoCredentialsProvider({
IdentityPoolId: AWS_COGNITO_IDENTITY_POOL_ID,
Region: AWS_REGION});
/** Make sure the credential provider fetched before setup the connection */
await provider.refreshCredentials();
client = createClient(provider);
const attemptingConnect = once(client, "attemptingConnect");
const connectionSuccess = once(client, "connectionSuccess");
client.start();
await attemptingConnect;
await connectionSuccess;
const suback = await client.subscribe({
subscriptions: [
{ qos: mqtt5.QoS.AtLeastOnce, topicFilter: qos1Topic },
{ qos: mqtt5.QoS.AtMostOnce, topicFilter: qos0Topic }
]
});
log('Suback result: ' + JSON.stringify(suback));
const qos0PublishResult = await client.publish({
qos: mqtt5.QoS.AtMostOnce,
topicName: qos0Topic,
payload: "This is a qos 0 payload"
});
log('QoS 0 Publish result: ' + JSON.stringify(qos0PublishResult));
const qos1PublishResult = await client.publish({
qos: mqtt5.QoS.AtLeastOnce,
topicName: qos1Topic,
payload: "This is a qos 1 payload"
});
log('QoS 1 Publish result: ' + JSON.stringify(qos1PublishResult));
let unsuback = await client.unsubscribe({
topicFilters: [
qos0Topic
]
});
log('Unsuback result: ' + JSON.stringify(unsuback));
}
useEffect(() => {
testSuccessfulConnection();//initial execution
},[]);
async function PublishMessage()
{
const msg = `BUTTON CLICKED {${user_msg_count}}`;
const publishResult = await client.publish({
qos: mqtt5.QoS.AtLeastOnce,
topicName: qos1Topic,
payload: msg
})
.then (() =>
{
log('Button Clicked, Publish result: ' + JSON.stringify(publishResult));
})
.catch((error) => {
log(`Error publishing: ${error}`);
});
user_msg_count++;
}
async function CloseConnection()
{
const disconnection = once(client, "disconnection");
const stopped = once(client, "stopped");
client.stop();
await disconnection;
await stopped;
}
return (
<>
<div>
<button onClick={() => PublishMessage()}>Publish A Message</button>
</div>
<div>
<button onClick={() => CloseConnection()}>Disconnect</button>
</div>
<div id="message">Mqtt5 Pub Sub Sample</div>
</>
);
}
export default Mqtt5;