AWS IoT
Developer Guide
Protocols
message broker는 발행하고 구독을 위한 MQTT 프로토콜과 발행을 위한 HTTPS 프로토콜의 사용을 지원한다. 두 프로토콜 모두 IP v4와 IP v6를 통해 지원된다. message broker는 또한 WebSocket 프로토콜을 통해 MQTT를 지원한다.
MQTT는 constrained device를 위해 고안된 널리 채용되는 가벼운 메시징 프로토콜이다. 더 많은 정보는 MQTT 를 방문해라. AWS IoT message broker 구현은 MQTT 버전 3.1.1에 기반하고 있지만 다음과 같이 규격으로부터 벗어난다:
- AWS IoT에서 Qaulity of Service (QoS) 0으로 topic에 구독하는 것은 메시지가 0번 이상 전달될 것이라는 것을 의미한다. 메시지는 한 번 이상 전달될 수 있다. 메시지는 다른 ID를 가지고 한번 이상 전달될 것이다. 이러한 경우 DUP 플래그는 셋팅되지 않는다.
- AWS IoT는 QoS 2로 배포하고 구독하는 것을 지원하지 않는다. AWS IoT message broker는 QoS 2 가 요청될 때 PUBACK 나 SUBACK를 보내지 않는다.
- topic 에 대해 구독하고 발행하기 위한 QoS 레벨은 서로 관련이 없다. 한 클라이언트는 다른 클라이언트가 QoS0으로 동일한 topic에 대해 발행하더라도 QoS 1을 이용해 topic을 구독할 수 있다.
-
connection 요청에 대해 응답할 때 message broker는 CONNACK 메시지를 보낸다. 이 메시지는 connection이 이전 세션을 재시작하는지를 가리키는 플래그를 포함한다. 이 플래그의 값은 두 MQTT 클라이언트가 동시에 동일한 클라이언트 ID를 가지고 접속할 때 부정확할 수 있다.
- 클라이언트가 topic을 구독할 때 message broker가 SUBACK를 보내는 시간과 클라이언트가 새로운 매칭 메시지를 수신하기 시작하는 시간 사이에 지연이 발생할 수 있다.
- MQTT 규격은 발행인이 broker가 topic에 대해 보낸 마지막 메시지를 유지하고 그것을 모든 미래 topic 구독자에게 보내도록 요청하는 것을 제공한다. AWS IoT는 메시지를 유지하는 것을 지원하지 않는다. 메시지를 유지하는 요청이 만들어지면 접속이 해제된다.
-
The message broker uses the client ID to identify each client. The client ID
is passed in from the client to the message broker as part of the MQTT payload.
Two clients with the same client ID are not allowed to be connected concurrently
to the message broker. When a client connects to the message broker using a
client ID that another client is using, a CONNACK message will be sent to both
clients and the currently connected client will be disconnected.
-
The message broker does not support persistent sessions (clean session set to
0). All sessions are assumed to be clean sessions and messages are not stored
across sessions. If an MQTT client sends a message with the clean session
attribute set to false, the client will be disconnected.
-
On rare occasions, the message broker may resend the same logical publish
message with a different packet ID.
- The message broker does not guarantee the order in which messages and ACK are received.
HTTP
<AWS IoT Endpoint>
/topics/<url_encoded_topic_name>
?qos=1"
.MQTT Over the WebSocket Protocol
A WebSocket connection is initiated on a client by sending an HTTP GET request. The URL you use is of the following form:
wss://<endpoint
>.iot.<region
>.amazonaws.com/mqtt
- wss
- Specifies the WebSocket protocol.
- endpoint
- Your AWS account-specific AWS IoT endpoint. You can use the AWS IoT CLI describe-endpoint command to find this endpoint.
- region
- The AWS region of your AWS account.
- mqtt
- Specifies you will be sending MQTT messages over the WebSocket protocol.
Using the WebSocket Protocol in a Web Application
The following JavaScript defines some utility functions used in generating a signature version 4 request.
/**
* utilities to do sigv4
* @class SigV4Utils
*/
function SigV4Utils(){}
SigV4Utils.sign = function(key, msg){
var hash = CryptoJS.HmacSHA256(msg, key);
return hash.toString(CryptoJS.enc.Hex);
};
SigV4Utils.sha256 = function(msg) {
var hash = CryptoJS.SHA256(msg);
return hash.toString(CryptoJS.enc.Hex);
};
SigV4Utils.getSignatureKey = function(key, dateStamp, regionName, serviceName) {
var kDate = CryptoJS.HmacSHA256(dateStamp, 'AWS4' + key);
var kRegion = CryptoJS.HmacSHA256(regionName, kDate);
var kService = CryptoJS.HmacSHA256(serviceName, kRegion);
var kSigning = CryptoJS.HmacSHA256('aws4_request', kService);
return kSigning;
};
To create a Signature Version 4 request
-
Create a canonical request for Signature Version 4.
The following JavaScript code creates a canonical request:
var time = moment.utc(); var dateStamp = time.format('YYYYMMDD'); var amzdate = dateStamp + 'T' + time.format('HHmmss') + 'Z'; var service = 'iotdevicegateway'; var region = this.options.regionName; var secretKey = this.options.secretKey; var accessKey = this.options.accessKey; var algorithm = 'AWS4-HMAC-SHA256'; var method = 'GET'; var canonicalUri = '/mqtt'; var host = this.options.endpoint; var credentialScope = dateStamp + '/' + region + '/' + service + '/' + 'aws4_request'; var canonicalQuerystring = 'X-Amz-Algorithm=AWS4-HMAC-SHA256'; canonicalQuerystring += '&X-Amz-Credential=' + encodeURIComponent(accessKey + '/' + credentialScope); canonicalQuerystring += '&X-Amz-Date=' + amzdate; canonicalQuerystring += '&X-Amz-SignedHeaders=host'; var canonicalHeaders = 'host:' + host + '\n'; var payloadHash = SigV4Utils.sha256(''); var canonicalRequest = method + '\n' + canonicalUri + '\n' + canonicalQuerystring + '\n' + canonicalHeaders + '\nhost\n' + payloadHash; console.log('canonicalRequest ' + canonicalRequest);
-
Create a string to sign, generate a signing key, and sign the string.
Take the canonical URL you created in the previous step and assemble it into a string to sign. You do this by creating a string composed of the hashing algorithm, the date, the credential scope, and the SHA of the canonical request. Next, generate the signing key and sign the string, as shown in the following JavaScript code.
var stringToSign = algorithm + '\n' + amzdate + '\n' + credentialScope + '\n' + SigV4Utils.sha256(canonicalRequest); var signingKey = SigV4Utils.getSignatureKey(secretKey, dateStamp, region, service); var signature = SigV4Utils.sign(signingKey, stringToSign);
-
Add the signing information to the request.
The following JavaScript code shows how to add the signing information to the query string.
canonicalQuerystring += '&X-Amz-Signature=' + signature; var requestUrl = 'wss://' + host + canonicalUri + '?' + canonicalQuerystring;
-
If you have session credentials (from an STS server, AssumeRole, or Amazon
Cognito), append the session token to the end of the URL string after
signing:
requestUrl += "&X-Amz-Security-Token=" + encodeURIComponent(sessionToken);
-
Open the WebSocket.
The following JavaScript code shows how to create a Paho MQTT client and call CONNECT to AWS IoT. Theendpoint
argument is your AWS account-specific endpoint. TheclientId
is a text identifier that is unique among all clients simultaneously connected in your AWS account.
var client = new Paho.MQTT.Client(requestUrl, clientId); var connectOptions = { onSuccess: function(){ // connect succeeded }, useSSL: true, timeout: 3, mqttVersion: 4, onFailure: function() { // connect failed } }; client.connect(connectOptions);
Using the WebSocket Protocol in a Mobile Application
You can find a reference implementation for connecting a web application to AWS IoT using MQTT over the WebSocket protocol here: AWS Labs WebSocket sample.
If you are using a programming or scripting language that is not currently supported, any existing WebSocket library can be used as long as the initial WebSocket upgrade request (HTTP POST) is signed using AWS Signature Version 4. Some MQTT clients, such as Eclipse Paho for JavaScript, support the WebSocket protocol natively.
댓글 없음:
댓글 쓰기