PubSubClient connect() String nesnelerinden istemci kimliği oluşturduğumda rc=2 hatasıyla başarısız oluyor
Yapay zekâ tarafından English dilinden çevrildi ·
Garip bir durum. ESP32, Arduino core 2.0.14, PubSubClient 2.8. Bu her seferinde sorunsuz bağlanıyor:
mqtt.connect("barn-01", "my_access_token", "");
Ama istemci kimliğinin MAC adresinden gelmesini istiyorum, böylece aynı taslağı beş karta yükleyebileceğim ve token bir ayar yapısından geliyor. Bu yüzden şunu yaptım:
const char* clientId = (String("barn-") + WiFi.macAddress()).c_str();
const char* token = settings.token.c_str();
mqtt.setServer(host.c_str(), 8883);
if (!mqtt.connect(clientId, token, "")) {
Serial.println(mqtt.state());
}
Şimdi sürekli 2 yazdırıyor. Aynı token, aynı sunucu. Biraz çıldıracağım. MAC adresindeki iki noktalar mı sorun?
Weird one. ESP32, Arduino core 2.0.14, PubSubClient 2.8. This connects fine every time:
mqtt.connect("barn-01", "my_access_token", "");
But I want the client ID to come from the MAC so I can flash the same sketch to five boards, and the token comes from a settings struct. So I did this:
const char* clientId = (String("barn-") + WiFi.macAddress()).c_str();
const char* token = settings.token.c_str();
mqtt.setServer(host.c_str(), 8883);
if (!mqtt.connect(clientId, token, "")) {
Serial.println(mqtt.state());
}
Now it prints 2 forever. Same token, same host. I’m going slightly mad. Is it the colons in the MAC address?
Yapay zekâ tarafından English dilinden çevrildi ·
Buna benzer bir şey yapmıştım, connect öncesine delay(500) ekledim ve sorun ortadan kalktı.
I had something like this, added a delay(500) before connect and it went away.
Yapay zekâ tarafından English dilinden çevrildi ·
connect() çağrısından hemen önce clientId’nin gerçekte neyi içerdiğini yazdırabilir misiniz?
Can you print what clientId actually contains right before connect?
Yapay zekâ tarafından English dilinden çevrildi ·
rc=2, “client ID rejected” (istemci kimliği reddedildi) anlamına gelir. Hermetry client ID’lerinde iki nokta üst üste (:) karakterine izin verilir (harfler, rakamlar ve . _ : -, 1 ile 64 karakter), dolayısıyla sorun MAC formatı değil. Kimliğe başka bir şey karışıyor.
rc=2 is “client ID rejected”. Colons are allowed in Hermetry client IDs (letters, digits and . _ : -, 1 to 64 chars), so it’s not the MAC format. Something else is getting into the ID.
Yapay zekâ tarafından English dilinden çevrildi ·
Yazdırdım, ve çöp çıktı:
clientId=[□□?□barn-]
bazen boş, bazen bozuk veriler. Gecikme hiçbir şeyi değiştirmedi.
Printed it, and it’s garbage:
clientId=[□□?□barn-]
sometimes empty, sometimes junk. The delay didn’t change anything.
Yapay zekâ tarafından English dilinden çevrildi ·
String, kullanmadan önce yok oluyor. (String("barn-") + WiFi.macAddress()) o satır sonunda yok edilen geçici bir nesne oluşturur, bu yüzden clientId serbest bırakılmış belleğe işaret eder. Yığın bundan sonra ne yaparsa müşteri kimliğinize yansır. Yıllar önce bir sensör kartında başıma geldi, bir gün boşa harcadım.Aynı tuzak setServer(host.c_str(), ...) için de geçerli: PubSubClient kopya değil işaretçiyi saklar, dolayısıyla host setup() içinde yerel bir String ise daha sonra garip yeniden bağlanma hataları alırsınız.İstemci yaşadığı sürece yaşayan tamponlar kullanın:
static char clientId[32];
static char brokerHost[64];
void setupMqtt() {
uint8_t mac[6];
WiFi.macAddress(mac);
snprintf(clientId, sizeof(clientId), "barn-%02x%02x%02x", mac[3], mac[4], mac[5]);
strlcpy(brokerHost, settings.host.c_str(), sizeof(brokerHost));
mqtt.setServer(brokerHost, 8883);
}
// later
mqtt.connect(clientId, settings.token.c_str(), "");
settings global olduğu sürece settings.token.c_str() çağrının içinde sorunsuzdur.
The String is gone before you use it. (String("barn-") + WiFi.macAddress()) makes a temporary that’s destroyed at the end of that line, so clientId points into freed memory. Whatever the heap does next ends up in your client ID. Bit me on a sensor board years ago and I wasted a day too.
Same trap with setServer(host.c_str(), ...): PubSubClient keeps the pointer, not a copy, so if host is a local String in setup() you’ll get odd reconnect failures later.
Use buffers that live as long as the client:
static char clientId[32];
static char brokerHost[64];
void setupMqtt() {
uint8_t mac[6];
WiFi.macAddress(mac);
snprintf(clientId, sizeof(clientId), "barn-%02x%02x%02x", mac[3], mac[4], mac[5]);
strlcpy(brokerHost, settings.host.c_str(), sizeof(brokerHost));
mqtt.setServer(brokerHost, 8883);
}
// later
mqtt.connect(clientId, settings.token.c_str(), "");
settings.token.c_str() is fine inside the call as long as settings lives globally.
Yapay zekâ tarafından English dilinden çevrildi ·
Sorun buydu. Statik tamponlar kullanınca beş kartın hepsinde ilk denemede bağlanıyor. Ayrıca sizin dediğiniz gibi host’u setup() içinde oluşturuyormuşum; bu da Wi-Fi’ma suçlayıp durduğum rastgele yeniden bağlantı hatalarını açıklıyor. Teşekkürler Laura.
That was it. Static buffers and it connects first time on all five boards. I’d also been building the host in setup() exactly like you said, which explains the random reconnect failures I’d been blaming on my Wi-Fi. Thanks Laura.
- Bu konuyu yanıtlamak için giriş yapmış olmalısınız.
Sohbete katılın
Soru sormak ve yanıtlamak, yararlı gönderileri beğenmek ve sorununuzu çözen yanıtı işaretlemek için oturum açın. Her katkı puan ve seviye kazandırır.

