[apps/tidep0084.git] / example / iot-gateway / node_modules / aws-iot-device-sdk / examples / browser / mqtt-explorer / index.js
1 /*
2 * Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
16 //
17 // Instantiate the AWS SDK and configuration objects. The AWS SDK for
18 // JavaScript (aws-sdk) is used for Cognito Identity/Authentication, and
19 // the AWS IoT SDK for JavaScript (aws-iot-device-sdk) is used for the
20 // WebSocket connection to AWS IoT and device shadow APIs.
21 //
22 var AWS = require('aws-sdk');
23 var AWSIoTData = require('aws-iot-device-sdk');
24 var AWSConfiguration = require('./aws-configuration.js');
26 console.log('Loaded AWS SDK for JavaScript and AWS IoT SDK for Node.js');
28 //
29 // Remember our current subscription topic here.
30 //
31 var currentlySubscribedTopic = 'subscribe-topic';
33 //
34 // Remember our message history here.
35 //
36 var messageHistory = '';
38 //
39 // Create a client id to use when connecting to AWS IoT.
40 //
41 var clientId = 'mqtt-explorer-' + (Math.floor((Math.random() * 100000) + 1));
43 //
44 // Initialize our configuration.
45 //
46 AWS.config.region = AWSConfiguration.region;
48 AWS.config.credentials = new AWS.CognitoIdentityCredentials({
49 IdentityPoolId: AWSConfiguration.poolId
50 });
52 //
53 // Create the AWS IoT device object. Note that the credentials must be
54 // initialized with empty strings; when we successfully authenticate to
55 // the Cognito Identity Pool, the credentials will be dynamically updated.
56 //
57 const mqttClient = AWSIoTData.device({
58 //
59 // Set the AWS region we will operate in.
60 //
61 region: AWS.config.region,
62 //
63 // Use the clientId created earlier.
64 //
65 clientId: clientId,
66 //
67 // Connect via secure WebSocket
68 //
69 protocol: 'wss',
70 //
71 // Set the maximum reconnect time to 8 seconds; this is a browser application
72 // so we don't want to leave the user waiting too long for reconnection after
73 // re-connecting to the network/re-opening their laptop/etc...
74 //
75 maximumReconnectTimeMs: 8000,
76 //
77 // Enable console debugging information (optional)
78 //
79 debug: true,
80 //
81 // IMPORTANT: the AWS access key ID, secret key, and sesion token must be
82 // initialized with empty strings.
83 //
84 accessKeyId: '',
85 secretKey: '',
86 sessionToken: ''
87 });
89 //
90 // Attempt to authenticate to the Cognito Identity Pool. Note that this
91 // example only supports use of a pool which allows unauthenticated
92 // identities.
93 //
94 var cognitoIdentity = new AWS.CognitoIdentity();
95 AWS.config.credentials.get(function(err, data) {
96 if (!err) {
97 console.log('retrieved identity: ' + AWS.config.credentials.identityId);
98 var params = {
99 IdentityId: AWS.config.credentials.identityId
100 };
101 cognitoIdentity.getCredentialsForIdentity(params, function(err, data) {
102 if (!err) {
103 //
104 // Update our latest AWS credentials; the MQTT client will use these
105 // during its next reconnect attempt.
106 //
107 mqttClient.updateWebSocketCredentials(data.Credentials.AccessKeyId,
108 data.Credentials.SecretKey,
109 data.Credentials.SessionToken);
110 } else {
111 console.log('error retrieving credentials: ' + err);
112 alert('error retrieving credentials: ' + err);
113 }
114 });
115 } else {
116 console.log('error retrieving identity:' + err);
117 alert('error retrieving identity: ' + err);
118 }
119 });
121 //
122 // Connect handler; update div visibility and fetch latest shadow documents.
123 // Subscribe to lifecycle events on the first connect event.
124 //
125 window.mqttClientConnectHandler = function() {
126 console.log('connect');
127 document.getElementById("connecting-div").style.visibility = 'hidden';
128 document.getElementById("explorer-div").style.visibility = 'visible';
129 document.getElementById('subscribe-div').innerHTML = '<p><br></p>';
130 messageHistory = '';
132 //
133 // Subscribe to our current topic.
134 //
135 mqttClient.subscribe(currentlySubscribedTopic);
136 };
138 //
139 // Reconnect handler; update div visibility.
140 //
141 window.mqttClientReconnectHandler = function() {
142 console.log('reconnect');
143 document.getElementById("connecting-div").style.visibility = 'visible';
144 document.getElementById("explorer-div").style.visibility = 'hidden';
145 };
147 //
148 // Utility function to determine if a value has been defined.
149 //
150 window.isUndefined = function( value ) {
151 return typeof value === 'undefined' || typeof value === null;
152 };
154 //
155 // Message handler for lifecycle events; create/destroy divs as clients
156 // connect/disconnect.
157 //
158 window.mqttClientMessageHandler = function( topic, payload ) {
159 console.log('message: '+topic+':'+payload.toString());
160 messageHistory = messageHistory + topic + ':' + payload.toString() + '</br>';
161 document.getElementById('subscribe-div').innerHTML = '<p>'+messageHistory+'</p>';
162 };
164 //
165 // Handle the UI for the current topic subscription
166 //
167 window.updateSubscriptionTopic = function() {
168 var subscribeTopic = document.getElementById('subscribe-topic').value;
169 document.getElementById('subscribe-div').innerHTML = '';
170 mqttClient.unsubscribe(currentlySubscribedTopic);
171 currentlySubscribedTopic = subscribeTopic;
172 mqttClient.subscribe(currentlySubscribedTopic);
173 };
175 //
176 // Handle the UI to clear the history window
177 //
178 window.clearHistory= function() {
179 if (confirm('Delete message history?') === true) {
180 document.getElementById('subscribe-div').innerHTML = '<p><br></p>';
181 messageHistory = '';
182 }
183 };
185 //
186 // Handle the UI to update the topic we're publishing on
187 //
188 window.updatePublishTopic= function() {
189 };
191 //
192 // Handle the UI to update the data we're publishing
193 //
194 window.updatePublishData= function() {
195 var publishText = document.getElementById('publish-data').value;
196 var publishTopic = document.getElementById('publish-topic').value;
198 mqttClient.publish( publishTopic, publishText );
199 document.getElementById('publish-data').value = '';
200 };
202 //
203 // Install connect/reconnect event handlers.
204 //
205 mqttClient.on('connect', window.mqttClientConnectHandler);
206 mqttClient.on('reconnect', window.mqttClientReconnectHandler);
207 mqttClient.on('message', window.mqttClientMessageHandler);
209 //
210 // Initialize divs.
211 //
212 document.getElementById('connecting-div').style.visibility = 'visible';
213 document.getElementById('explorer-div').style.visibility = 'hidden';
214 document.getElementById('connecting-div').innerHTML = '<p>attempting to connect to aws iot...</p>';