AWSIOT: AWS CLI で トピックにパブリッシュ (証明書を使用)

こちらのページと同じことを証明書を使って行ないます。
[AWSIOT: AWS CLI で トピックにパブリッシュ](https://qiita.com/ekzemplaro/items/7deb2c60deb8f64af73e)

## 証明書の作成

次のファイルが出来ます。

```test
AmazonRootCA1.pem
AmazonRootCA3.pem
5a6b*****-certificate.pem.crt
5a6b*****-private.pem.key
5a6b*****-public.pem.key   使いません
```

証明書に policy をアタッチします。
AWS IoT -> セキュリティ -> 証明書　で policy がアタッチしてるか確認。

エンドポイント

```text
b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com
```

トピック

```text
test/topica
```

とします。

## curl

```bash:publish_curl.sh
#
#	publish_curl.sh
#
FOLDER="../certificate"
#
CERTFILE=${FOLDER}"/5a6b*****-certificate.pem.crt"
PRIVATEFILE=${FOLDER}"/5a6b*****-private.pem.key"
#
#
ENDPOINT="b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com"
HOST="https://"${ENDPOINT}":8443"
#
TOPIC="test/topica"
URL=$HOST"/topics/"$TOPIC"?qos=1"
#
curl --tlsv1.2 \
    --cert ${CERTFILE} \
    --key ${PRIVATEFILE} \
    -X POST ${URL} \
    --data '{"x": 124 , "y": 234, "z": 1044}'
#
```

## Httpie

```bash:publish_http.sh
#
#	publish_http.sh
#
FOLDER="../certificate"
#
CERTFILE=${FOLDER}"/5a6b*****-certificate.pem.crt"
PRIVATEFILE=${FOLDER}"/5a6b*****-private.pem.key"
#
ENDPOINT="b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com"
HOST="https://"${ENDPOINT}":8443"
#
TOPIC="esp32b/pub"
URL=$HOST"/topics/"$TOPIC"?qos=1"
#
echo ${URL} 
#
http --ssl tls1.2 \
--cert=${CERTFILE} --cert-key=${PRIVATEFILE} \
	$URL x=25 y=45 z=1203
#
```



## mosquitto

```bash:mos_publish.sh
#
#	mos_publish.sh
#
FOLDER="../certificate"
#
CAFILE=${FOLDER}"/AmazonRootCA1.pem"
CERTFILE=${FOLDER}"/5a6b*****-certificate.pem.crt"
PRIVATEFILE=${FOLDER}"/5a6b*****-private.pem.key"
#
#
ENDPOINT="b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com"
#
TOPIC="test/topica"

mosquitto_pub --cafile $CAFILE \
	--cert $CERTFILE \
	--key $PRIVATEFILE \
    -h $ENDPOINT \
    -p 8883 -q 1 -d -t $TOPIC \
	 -m '{"x": 122 , "y": 232, "z": 1042}'
#
```

## python requests

```py:rest_publish.py
#! /usr/bin/python
#
#	rest_publish.py
#
#					Nov/13/2022
# ------------------------------------------------------------------
import requests

endpoint = "b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com"
topic = "test/topica"
cert = "../certificate/5a6b*****-certificate.pem.crt"
key = "../certificate/5a6b*****-private.pem.key"
message = '{"x": 121 , "y": 231, "z": 1041}'
#
# create and format values for HTTPS request
publish_url = 'https://' + endpoint + ':8443/topics/' + topic + '?qos=1'
publish_msg = message.encode('utf-8')

# make request
publish = requests.request('POST',
	publish_url,
	data=publish_msg,
	cert=[cert, key])

# print results
print("Response status: ", str(publish.status_code))
if publish.status_code == 200:
	print("Response body:", publish.text)
#
# ------------------------------------------------------------------
```

## python sdk

```py:sdk_publish.py
#! /usr/bin/python
#
#	sdk_publish.py
#
#					Nov/13/2022
# ------------------------------------------------------------------
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import time
import json

# ------------------------------------------------------------------
host = "b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com"
#
rootCAPath = "../certificate/AmazonRootCA3.pem"
certificatePath = "../certificate/5a6b*****-certificate.pem.crt"
privateKeyPath = "../certificate/5a6b*****-private.pem.key"
port = 443
useWebsocket = 0
clientId = "basicPubSub"
topic = "test/topica"

myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureEndpoint(host, port)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()


# Publish to the same topic in a loop forever
count = 0
while True:
	message ={}
	message['x'] = "127"
	message['y'] = "237"
	message['z'] = "1007"
	messageJson = json.dumps(message)
	myAWSIoTMQTTClient.publish(topic, messageJson, 1)
	print('Published topic %s: %s\n' % (topic, messageJson))
	count += 1
	if 2 < count:
		break 
	time.sleep(2)
# ------------------------------------------------------------------
```

## node.js https

```js:publish.cjs
#! /usr/local/bin/node
// ---------------------------------------------------------------
//	publish.cjs
//
//					Nov/13/2022
//
// ---------------------------------------------------------------
const https = require("https")
const fs = require('fs')

console.error ("*** 開始 ***")

const endpoint = 'b987ceh026tlxq-ats.iot.ap-northeast-1.amazonaws.com'
const topic = 'test/topica'

const KEY =  '../../certificate/5a6b*****-private.pem.key'
const CERT =  '../../certificate/5a6b*****-certificate.pem.crt'

const data = JSON.stringify({x: 124, y: 234, z: 1034})

const options = {
	method: "POST",
	cert: fs.readFileSync(CERT),
	key: fs.readFileSync(KEY),
	headers: {
		"Content-Type": "application/json",
		'Content-Length': data.length
		}
}

const url = 'https://' + endpoint + ':8443/topics/' + topic + '?qos=1'

const request = https.request(url, options, response => {
console.log(`statusCode: ${response.statusCode}`)
response.on('data', (dd) => {
	process.stdout.write(dd)
  })
})

request.write(data)
request.end()

// ---------------------------------------------------------------
```

次のバージョンで確認しました。

```text
$ node --version
v19.0.1
```