I am not sure if this is possible but I have started with the basic blocks and not sure how to go from here.
The idea is to have a topic or part of it declared during the setup of the sketch and then be called later in the sketch. In the end, I will have a HTML setup page whereby the topic can be changed as the need arises.
// So it would be something in the line of
base topic = "cmnd/"
then get the main topic from EEMROM and send/receive a message to/from
main topic = "house"
client.publish(fulltopic, "ON")
I have been playing with the basic mqtt examples but I can't recall the variable that is set on setup, is it even possible?
here is what I have so far
/*
Basic MQTT example
This sketch demonstrates the basic capabilities of the library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 8, 7);
IPAddress server(192, 168, 8, 30);
String mqtttopic = "test";
String mqtttopic2 = "test/";
const char* outTopictest = "test/" ;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
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("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(outTopictest,"hello world");
// ... and resubscribe
client.subscribe("inTopic");
mqtttsetup () ;
} 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()
{
Serial.begin(57600);
String mqtttopic = "setup" ; // set new topic
client.setServer(server, 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
Serial.println(mqtttopic);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
void mqtttsetup (){
String mqtt1 = mqtttopic2 ;
String mqtt2 = mqtttopic;
String mqttf = mqtt1+mqtt2 ;
const char* outTopic = mqttf.c_str();
Serial.println("Send MQTT");
Serial.println(mqtttopic);
client.publish(outTopic,"MQTT Setup Works");
}