I've been having a discussion in another post about variable types. Forgive me, I'm a noob. The good news is that the forum helped me get this script functioning. It subscribes. It publishes. It does what it needs to do. The bad news, is that after two days, I could not get this to work using the variable type char.
Only String. Which everyone says is a bad idea. Can someone help me convert this so that lines 6,7, 8,9
String campus = "campus";
String building = "building";
String room = "office";
String subscription = campus+'/'+building+'/'+room+'/'+'#';
are variable type string and about half way down my function
client.subscribe(subscription.c_str());
Still works?
Here's my entire diagnostic script:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#define DEVICE "OfficeArduino"
#define DEVICEHELLO "OfficeArduino Connected"
String campus = "campus";
String building = "building";
String room = "office";
String subscription = campus+'/'+building+'/'+room+'/'+'#';
float setpoint = 45.00;
float actual = 44.44;
int state = 0;
int request = 0;
char *cstring;
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 221);
IPAddress server(192, 168, 0, 222);
void callback(char* topic, byte* payload, unsigned int length) {
for (int i=0;i<length;i++) {
payload[length] = '\0';
cstring = (char *) payload;
}
Serial.println(topic);
Serial.println(cstring);
setpoint = atof(cstring);
Serial.println("The setpoint is...");
}
EthernetClient ethClient;
PubSubClient client(ethClient);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(DEVICE)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic",DEVICEHELLO);
// ... and resubscribe
client.subscribe(subscription.c_str());
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
// disable SD card if one in the slot
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
Serial.begin(57600);
client.setServer(server, 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}