Hey all,
So I'm trying to use variables to set up my PubSubClient connection. When the port is hard coded, it seems fine but when I use a variable then it fails to connect:
Below shows the 2 methods I'm trying. The first one uses (int)mqtt_port and fails to connect. The second has it hard coded and works fine.
char mqtt_ip[16] = "192.168.1.82";
char mqtt_port[7] = "1883";
//This one doesn't work. When I try to connect I get message:
// Attempting MQTT connection... Failed.
PubSubClient client(mqtt_ip, (int)mqtt_port, callback, wifiClient);
//This one works fine
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);
Can anyone tell me what's wrong here?
Thanks,
Cheese
Why are you trying to cast a constant string to an int ?
Have you tried printing (int)mqtt_port) ?
iow, how about char mqtt_port[7] = "1883\0";
and using atoi(mqqt_port) There must be a reason for wanting it as a c-string initially, i hope.
There must be a reason for wanting it as a c-string initially, i hope.
I await the reply with bated breath
char mqtt_port[7] = "1883\0";
No need for the explicit terminator as the compiler will add one anyway. Nor any need for the array size specifier either unless it is to be used to hold a longer string later
No need for the explicit terminator as the compiler will add one anyway.
I'm never really sure about that, i know it does for a char *, and won't hurt might help.
won't hurt might help.
Unless for some reason later in the code you need to know the actual length of the string
UKHeliBob:
I await the reply with bated breath
I don't know about the OP, but I frequently reuse code for my Home IOT projects, and if I forget to make the pubSub client name unique, one or both fail to work.
Deva_Rishi:
iow, how about
char mqtt_port[7] = "1883\0";
and using
atoi(mqqt_port)
There must be a reason for wanting it as a c-string initially, i hope.
Thankyou. This did the job. There was no need to terminate it though.
As for the reason to use a c-string, I really can't tell you why. I think I got the code snippet from the WIFIManager GitHub for adding additional parameters. I'm no expert so I just followed that guidance. May or may not be right but it sure was a painful way to do it. 
Thanks again.
char mqtt_ip[16] = "192.168.1.82";I sort of understand it for an IP address that you may want to show in the SM or on a page (i tend to keep a copy as a String as well) though there is a struct available called IPAddress theIP = IPAddress(192,168,4,1);