Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ma2shita/4985fa47129d956a530923104c091bc6 to your computer and use it in GitHub Desktop.
Save ma2shita/4985fa47129d956a530923104c091bc6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MQTT console for AWS IoT Core with MQTT over WebSocket</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/aws-sdk/2.404.0/aws-sdk.min.js" integrity="sha256-5j5NcghceMlKBa2qXSGw6l24mOkiXOsdi9sB21pBips=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.min.js" integrity="sha256-UplsBBNj5zR16Nyo1bVLLVd0ndtLYs0A5c4WrbK/etU=" crossorigin="anonymous"></script>
<script>/* from https://docs.aws.amazon.com/ja_jp/iot/latest/developerguide/protocols.html */
/**
* utilities to do sigv4
* @class SigV4Utils
*/
function SigV4Utils() { }
SigV4Utils.getSignatureKey = function (key, date, region, service) {
var kDate = AWS.util.crypto.hmac('AWS4' + key, date, 'buffer');
var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
var kCredentials = AWS.util.crypto.hmac(kService, 'aws4_request', 'buffer');
return kCredentials;
};
SigV4Utils.getSignedUrl = function (host, region, credentials) {
var datetime = AWS.util.date.iso8601(new Date()).replace(/[:\-]|\.\d{3}/g, '');
var date = datetime.substr(0, 8);
var method = 'GET';
var protocol = 'wss';
var uri = '/mqtt';
var service = 'iotdevicegateway';
var algorithm = 'AWS4-HMAC-SHA256';
var credentialScope = date + '/' + region + '/' + service + '/' + 'aws4_request';
var canonicalQuerystring = 'X-Amz-Algorithm=' + algorithm;
canonicalQuerystring += '&X-Amz-Credential=' + encodeURIComponent(credentials.accessKeyId + '/' + credentialScope);
canonicalQuerystring += '&X-Amz-Date=' + datetime;
canonicalQuerystring += '&X-Amz-SignedHeaders=host';
var canonicalHeaders = 'host:' + host + '\n';
var payloadHash = AWS.util.crypto.sha256('', 'hex')
var canonicalRequest = method + '\n' + uri + '\n' + canonicalQuerystring + '\n' + canonicalHeaders + '\nhost\n' + payloadHash;
var stringToSign = algorithm + '\n' + datetime + '\n' + credentialScope + '\n' + AWS.util.crypto.sha256(canonicalRequest, 'hex');
var signingKey = SigV4Utils.getSignatureKey(credentials.secretAccessKey, date, region, service);
var signature = AWS.util.crypto.hmac(signingKey, stringToSign, 'hex');
canonicalQuerystring += '&X-Amz-Signature=' + signature;
if (credentials.sessionToken) {
canonicalQuerystring += '&X-Amz-Security-Token=' + encodeURIComponent(credentials.sessionToken);
}
var requestUrl = protocol + '://' + host + uri + '?' + canonicalQuerystring;
return requestUrl;
};
</script>
</head>
<body>
Open `Inspector window`
</body>
<script>
var cognitoIdentityPoolId = 'YOUR_AMAZONCOGNITO_POOL_ID';
var awsiotcoreEndpoint = 'YOUR_AWSIOTCORE_CUSTOM_ENDPOINT';
var clientName = 'webclient0';
/* Policy document; (attach to Cognito's role)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "iot1",
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": [
"arn:aws:iot:*:*:client/webclient0"
]
},
{
"Sid": "iot2",
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": [
"arn:aws:iot:*:*:topic/$aws/things/my_thing0/shadow/update",
"arn:aws:iot:*:*:topic/$aws/things/my_thing0/shadow/get"
]
},
{
"Sid": "iot3",
"Effect": "Allow",
"Action": "iot:Receive",
"Resource": [
"arn:aws:iot:*:*:topic/$aws/things/my_thing0/shadow/update/documents",
"arn:aws:iot:*:*:topic/$aws/things/my_thing0/shadow/get/accepted"
]
},
{
"Sid": "iot4",
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": [
"arn:aws:iot:*:*:topicfilter/$aws/things/+/shadow/update/documents",
"arn:aws:iot:*:*:topicfilter/$aws/things/+/shadow/get/accepted"
]
}
]
}
*/
</script>
<script>
var mqtt = null;
window.onload = function () {
AWS.config.region = cognitoIdentityPoolId.split(':')[0];
AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: cognitoIdentityPoolId });
AWS.config.credentials.get(function () {
var endpoint = SigV4Utils.getSignedUrl(awsiotcoreEndpoint, AWS.config.region, AWS.config.credentials);
mqtt = new Paho.MQTT.Client(endpoint, clientName);
mqtt.connect({
useSSL: true,
mqttVersion: 4,
onSuccess: function () {
console.log(`MQTT (over WebSocket) connect Success`);
console.log(`Usage:
MQTT operation;
Subscribe> mqtt.subscribe("my_topic/#")
Publish> mqtt.send('my_topic/bar', '{"payload":"data"}')
AWS IoT Core Thing shadow topic;
GET>
mqtt.subscribe('$aws/things/+/shadow/get/accepted')
mqtt.send('$aws/things/my_thing0/shadow/get', '{}')
UPDATE>
mqtt.subscribe('$aws/things/+/shadow/update/documents')
mqtt.send('$aws/things/my_thing0/shadow/update', '{"state":{"reported":{"status":"check"}}}')
`);
},
onFailure: function (e) {
console.log(e);
}
});
mqtt.onConnectionLost = function (e) {
console.log(e);
console.log('Your need reload (reconnect)');
};
mqtt.onMessageArrived = function (message) {
console.log(message);
};
});
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment