MQTT ClientID デバイスIDの指定

MQTTブローカに接続するデバイスに任意のクライアントIDを割り当てることで、IDによる接続デバイスの制限をします。エラーの発生したデバイスの特定にも役立ちます。ArduinoのMQTTライブラリではデフォルトで任意のIDがランダムに割り当てられるためデバイスの特定ができません。以下スケッチ例です。

//add mqtt clientid
String modelNum = "Client-";
String rndNum = String(random(0xffff), HEX);
String clientId = String(modelNum + rndNum);
const char* MQTT_CID = clientId.c_str();

Mosquittoの設定ファイルの以下の項目を指定します。 client-xxxx の記載のあるデバイスのみがブローカに接続できます。

clientid_prefixes client-

If defined, only clients that have a clientid with a prefix that matches clientid_prefixes will be allowed to connect to the broker. For example, setting “secure-” here would mean a client “secure-client” could connect but another with clientid “mqtt” couldn’t. By default, all client ids are valid.

Arduino Reference String

MAC AddressまたはhostnameをIDに反映させる場合

上記リファレンスからWiFi.macAddress()、WiFi.hostname()共にstring型です。
以下char型ポインターに受け渡すためchar型にコンバートする例です。 toCharArray() を使用します。

char mqtt_cid[40] = "mqtt client id";
const char* MQTT_CID = mqtt_cid;

String modelNum = "Client-";
String hostName = WiFi.hostname();
String clientId = String(modelNum + hostName);
clientId.toCharArray(mqtt_cid, 40);