# MQTT ClientID デバイスIDの指定

**URL:** <https://forum.ficusonline.com/t/mqtt-clientid-id/166>\
**Category:** Automation\
**Created:** [2018 年 3 月 1 日午前 10:14 UTC](https://forum.ficusonline.com/t/mqtt-clientid-id/166 "2018-03-01T10:14:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)\
**Post date:** [2018 年 3 月 1 日午前 10:14 UTC](https://forum.ficusonline.com/t/mqtt-clientid-id/166/1 "2018-03-01T10:14:47Z")

</div>

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.conf man page](https://mosquitto.org/man/mosquitto-conf-5.html)**
>
> Name
> mosquitto.conf — the configuration file for mosquitto
> 
> 
> Synopsis
> mosquitto.conf 
> 
> 
> Description
> mosquitto.conf is the configuration file for
> mosquitto. This file can reside anywhere as long as m

**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**

[https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/](https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/)

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

> <https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst#macAddress>

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

[https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/tochararray/](https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/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);

```
