ESP32: AWS IOT の MQTT 送信

Ubuntu 22.10 上の Arduino IDE 1.8.18 を使いました。
ボードは、
ESP32 Dev Module
とします。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/eda3ec9b-4f2a-47df-4c47-6e319acb27b5.png)

## プログラム

フォルダー構造

```text
$ tree aws_publish/
aws_publish/
├── aws_publish.ino
├── config.h
└── mqtt_send.ino
```


```text:aws_publish.ino
// ---------------------------------------------------------------------
//	aws_publish.ino
//
//					Nov/17/2022
// ---------------------------------------------------------------------
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

#include "config.h"

WiFiClientSecure httpsClient;
PubSubClient mqttClient(httpsClient);

int count = 0;
// ---------------------------------------------------------------------
void setup() {
	Serial.begin(115200);
	Serial.println("*** setup start ***");

	httpsClient.setCACert(AWS_IOT_ROOT_CA);
	httpsClient.setCertificate(AWS_IOT_DEVICE_CERT);
	httpsClient.setPrivateKey(AWS_IOT_DEVICE_PRIVATE_KEY);
	mqttClient.setServer(AWS_IOT_ENDPOINT.c_str(), AWS_IOT_PORT);

	connectWiFi();
	Serial.println("*** setup aaa ***");

	mqtt_connect_wait_proc();
	Serial.println("*** ccc ***");
}

// ---------------------------------------------------------------------
void loop()
{
	mqtt_send_proc(count);

	Serial.println("*** loop ***" + String(count));
	Serial.println(WiFi.localIP());
	delay(3000);
	count++;

	if ( WiFi.status() == WL_DISCONNECTED ) {
		connectWiFi(); 
	}

	if ( ! mqttClient.connected() ) {
		mqtt_connect_wait_proc();
	}
	mqttClient.loop();  
}

// ---------------------------------------------------------------------
void connectWiFi()
{
	WiFi.begin(ssid, password);
	Serial.print("WiFi connecting...");
	while(WiFi.status() != WL_CONNECTED) {
		Serial.print(".");
		delay(100);
	}
	Serial.print(" connected. ");
	Serial.println(WiFi.localIP());
}

// ---------------------------------------------------------------------
void mqtt_connect_wait_proc()
{
	Serial.println("*** mqtt_connect_wait_proc ***");
	Serial.println("[AWS IoT]");
	while (!mqttClient.connected())
	{
		if (!mqttClient.connect(AWS_IOT_DEVICE_NAME.c_str()))
		{
			Serial.print("Connect Failed. Error state=");
			Serial.print(mqttClient.state());
			Serial.println("");
			delay(10000);
		}
	}
}

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

```text:mqtt_send.ino
// ---------------------------------------------------------------------
//	mqtt_send.ino
//
//					Nov/17/2022
// ---------------------------------------------------------------------
void mqtt_send_proc(int count)
{
	DynamicJsonDocument doc(256);
	char data_json[256];
	data_json[0] = '\0';

	char *chx = (char *)malloc(256);
	chx[0] = '\0';

	char qq[51] = "01234567890123456789";

	strcat(chx,qq);

	doc["count"] = count;
	doc["xx"] = 302;
	doc["yy"] = 402;
	doc["zz"] = 1303;

	doc["llx"] = String(strlen(chx));
	doc["chx"] = chx;
	doc["version"] = "2022-11-17 20:17";

	serializeJson(doc, data_json);

	Serial.println(data_json);
	Serial.println(strlen(data_json));
	Serial.println("MQTT_MAX_PACKET_SIZE = " + String(MQTT_MAX_PACKET_SIZE));
	boolean flag = mqttClient.publish(OUT_TOPIC, data_json);
	Serial.println(flag);

	free(chx);
}

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


```text:config.h
// ---------------------------------------------------------------
/*
	config.h

						Oct/02/2021
*/
// ---------------------------------------------------------------
const String SSID = "CHANGEME";
const String WIFI_PASSWORD = "CHANGEME";

const String AWS_IOT_ENDPOINT = "CHANGEME-ats.iot.ap-northeast-1.amazonaws.com";
const int AWS_IOT_PORT = 8883;
const String AWS_IOT_DEVICE_NAME = "CHANGEME";

#define OUT_TOPIC "CHANGEME";

// AmazonRootCA1.cer
static const char AWS_IOT_ROOT_CA[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
...CHANGEME...
-----END CERTIFICATE-----
)EOF";

// XXXXXXXXXX-certificate.pem.crt
static const char AWS_IOT_DEVICE_CERT[] PROGMEM = R"KEY(
-----BEGIN CERTIFICATE-----
...CHANGEME...
-----END CERTIFICATE-----
)KEY";

// XXXXXXXXXX-private.pem.key
static const char AWS_IOT_DEVICE_PRIVATE_KEY[] PROGMEM = R"KEY(
-----BEGIN RSA PRIVATE KEY-----
...CHANGEME...
-----END RSA PRIVATE KEY-----
)KEY";

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

## 送信結果の確認方法

AwsIOT -> テスト -> MQTT テストクライアント
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/179446/ba789664-2eb9-6974-65f5-2ce24e0a07f0.png)

スクリプトで確認

```bash:go_subscribe.sh
mosquitto_sub --cafile AmazonRootCA1.pem \
        --cert ****-certificate.pem.crt \
    --key ****-private.pem.key \
    -h "****-ats.iot.ap-northeast-1.amazonaws.com" \
    -p 8883 -q 1 -d -t sample/aaa
```