Hi, I hope this is the right category for this question…
I’m having some trouble getting messages published to an MQTT broker from an Argon.
I’m using mesh.publish/subscribe from a Xenon, which is working fine to get the data I need.
I’m using the mesh subsribe handler function to call the MQTT client, but it refuses to connect and I’m not sure why. I have tested my MQTT broker with a simple sketch and it looks to be fine.
This is my code, I’m probably missing something obvious…!
// This #include statement was automatically added by the Particle IDE.
#include <MQTT.h>
SYSTEM_THREAD(ENABLED);
int boardLed = D7; // This is the LED that is already on your device.
//Setup MQTT
void callback(char* topic, byte* payload, unsigned int length);
byte server[] = { 192,168,0,30 };
MQTT client(server, 1883, callback);
//MQTT client("192.168.0.30", 1883, callback);
void callback(char* topic, byte* payload, unsigned int length) {
char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
if (!strcmp(p, "RED"))
RGB.color(255, 0, 0);
else if (!strcmp(p, "GREEN"))
RGB.color(0, 255, 0);
else if (!strcmp(p, "BLUE"))
RGB.color(0, 0, 255);
else
RGB.color(255, 255, 255);
delay(1000);
}
void setup() {
Serial.begin(9600);
pinMode(boardLed, OUTPUT);
//Use External Antenna
selectExternalMeshAntenna();
//Subscribe to MESH events
Mesh.subscribe("xenon/voltage", receiver);
//Connect to MQTT
client.connect("sparkclient");
for( int i=0; i<3; i++) {
digitalWrite(boardLed,HIGH);
delay( 150 );
digitalWrite(boardLed,LOW);
delay( 200 );
}
}
void loop() {
}
//Event listener for events from Xenon
void receiver(const char *event, const char *data)
{
if (client.isConnected()) {
//Publish to MQTT
client.publish(event, data);
delay(2000);
}
else {
Serial.printf("MQTT Not Connected");
}
static int i = 0;
Serial.printf( "[%d] [%s]:[%s]\n", ++i, event, (data ? data : "") );
digitalWrite(boardLed,HIGH);
delay( 200 );
digitalWrite(boardLed,LOW);
//Publish to the cloud.
Particle.publish(event, data);
}
//External Mesh Antenna Code
void selectExternalMeshAntenna() {
#if (PLATFORM_ID == PLATFORM_ARGON)
digitalWrite(ANTSW1, 1);
digitalWrite(ANTSW2, 0);
#elif (PLATFORM_ID == PLATFORM_BORON)
digitalWrite(ANTSW1, 0);
#else
digitalWrite(ANTSW1, 0);
digitalWrite(ANTSW2, 1);
#endif
}