nodejsで、AWSIoTのDevice SDKを用いてMacBookをデバイスに登録する

# 必要な環境

| パッケージ | Version |
|:--|:--|
| Node.js | V4.4.3 |

https://nodejs.org/en/

v4.4.3をインストールしておく　

> $ node -v
  v4.4.3

# aws-iot-device-sdkのインストール

> npm install aws-iot-device-sdk

# サンプルのソースコード

```js:device.js
awsIot = require('aws-iot-device-sdk');

//
// Replace the values of '<YourUniqueClientIdentifier>' and '<YourAWSRegion>'
// with a unique client identifier and the AWS region you created your
// certificate in (e.g. 'us-east-1').  NOTE: client identifiers must be
// unique within your AWS account; if a client attempts to connect with a
// client identifier which is already in use, the existing connection will
// be terminated.
//
var device = awsIot.device({
   keyPath: <YourPrivateKeyPath>,
  certPath: <YourCertificatePath>,
    caPath: <YourRootCACertificatePath>,
  clientId: <YourUniqueClientIdentifier>,
    region: <YourAWSRegion>
});

//
// Device is an instance returned by mqtt.Client(), see mqtt.js for full
// documentation.
//
device
  .on('connect', function() {
    console.log('connect');
    device.subscribe('topic_1');
    device.publish('topic_2', JSON.stringify({ test_data: 1}));
    });

device
  .on('message', function(topic, payload) {
    console.log('message', topic, payload.toString());
  });
```

## 必要なファイル

| 項目| 概要 | 解説場所 |
|:--|:--|:--|
| keyPath | SSL証明書のprivate-key | Thingsの作成で説明 |
| certPath | SSL証明書のcertificate | Thingsの作成で説明 |
| caPath | Root証明書 | ルート証明書の取得で説明 |
| clientId | ClientID | Things名(この例の場合MacBook) |
| region | Tokyoならap-northeast-1 | |


# Thingsの作成

![awsiot001.png](https://qiita-image-store.s3.amazonaws.com/0/63450/830b3e2c-75d4-0951-5284-d98405459c17.png)

![awsiot002.png](https://qiita-image-store.s3.amazonaws.com/0/63450/7270ec16-93f4-9b9c-89b8-af4c5791ffce.png)

![awsiot003.png](https://qiita-image-store.s3.amazonaws.com/0/63450/1e943b65-e122-cafa-f0b6-44be1696b636.png)

![awsiot004.png](https://qiita-image-store.s3.amazonaws.com/0/63450/82fbe1db-02e9-d9c2-10a0-6e42c5ce0a05.png)

![awsiot005.png](https://qiita-image-store.s3.amazonaws.com/0/63450/90b1211d-ba03-2b8a-f5b4-1da4d849a0db.png)

![awsiot006.png](https://qiita-image-store.s3.amazonaws.com/0/63450/c6bb5ec8-5ff4-9223-a570-76d684f56b0f.png)

![awsiot007.png](https://qiita-image-store.s3.amazonaws.com/0/63450/3b41bfde-6398-f532-115f-d2b84ee46630.png)

ここまでの手順で　

- SSL証明書のprivate-key
- SSL証明書のcertificate 

が取得できる。

> $ mkdir cert

keyというフォルダを作成し、そこに保存しておく。

また、AWSIoTのDashboardには、MacBook, MacBookPolicy,certificate が生成される。

<img width="538" alt="MacBook001.png" src="https://qiita-image-store.s3.amazonaws.com/0/63450/2c5f3083-867a-b263-95a2-17fc79adb1f2.png">


# ルート証明書の取得
https://www.symantec.com/page.jsp?id=roots

![root002.png](https://qiita-image-store.s3.amazonaws.com/0/63450/c9169708-9af6-94c1-1dfa-be0cfca881dc.png)

> $ cd cert
> $ wget http://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem

これでルート証明書が取得できた。

```shell-session
$ ls
57555c6996-certificate.pem.crt
57555c6996-private.pem.key
VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem
```

# サンプルのソースコードの修正

```js:device.js
awsIot = require('aws-iot-device-sdk');

//
// Replace the values of '<YourUniqueClientIdentifier>' and '<YourAWSRegion>'
// with a unique client identifier and the AWS region you created your
// certificate in (e.g. 'us-east-1').  NOTE: client identifiers must be
// unique within your AWS account; if a client attempts to connect with a
// client identifier which is already in use, the existing connection will
// be terminated.
//
var device = awsIot.device({
   keyPath: './cert/57555c6996-private.pem.key',
  certPath: './cert/57555c6996-certificate.pem.crt',
    caPath: './cert/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem',
  clientId: 'MacBook',
    region: 'ap-northeast-1'
});

//
// Device is an instance returned by mqtt.Client(), see mqtt.js for full
// documentation.
//
device
  .on('connect', function() {
    console.log('connect');
    device.subscribe('topic_1');
    device.publish('topic_2', JSON.stringify({ test_data: 1}));
    });

device
  .on('message', function(topic, payload) {
    console.log('message', topic, payload.toString());
  });
```

# TestClientの作成　

![mqtt001.png](https://qiita-image-store.s3.amazonaws.com/0/63450/7108b52d-8570-e1d4-10ec-c7ba4d975797.png)

![mqtt002.png](https://qiita-image-store.s3.amazonaws.com/0/63450/2c1d00e1-fd85-d4fa-1213-76b7f86e2a97.png)

![mqtt003.png](https://qiita-image-store.s3.amazonaws.com/0/63450/14cf135e-f42c-8f4f-1fa6-b6bf01defba6.png)

![mqtt004.png](https://qiita-image-store.s3.amazonaws.com/0/63450/b468e7a0-e408-e7b5-0624-88d95a5dae0d.png)


# 実行
```shell-session
$ ls 
device.js	cert		node_modules
```

> $node device.js 
connect

Publishした{ test_data:1}がMQTT Clientのtopic_2に反映される。

![mqtt007.png](https://qiita-image-store.s3.amazonaws.com/0/63450/910dbd71-8bc8-a6f4-9574-03328abc646e.png)

プログラムでは、この部分でtopic_2にPublishしている。

```js
device.publish('topic_2', JSON.stringify({ test_data: 1}));
```


今度は、{key: "value"}という値をMQTT ClientからMacBookに、topic_1でPublishする。

![mqtt101.png](https://qiita-image-store.s3.amazonaws.com/0/63450/9f34fc44-453a-bc46-05df-d80a90c32272.png)

```js
device
  .on('message', function(topic, payload) {
    console.log('message', topic, payload.toString());
  });
```

```shell-session
$ node device.js 
connected
message topic_1 {key: "value"}
```