Hello everyone,
I am using an Arduino MKR 1400 board. Using GSM I am sending some data to the dashboard on Things Board. That is working fine for me. However, I want to integrate a switch on the dashboard and send a command like 0 and 1 that I want to receive on the Arduino so that I can turn on or off a relay. I have a written a callback function which is working on the MQTT server, for instance, if I send 0 or 1 I can receive it. However, this does not work for me on Things Board. Can someone please help me that how can I achieve it?
Code for sending the data to Things Dashboard:
#include <ArduinoJson.h>
#include <ArduinoMqttClient.h>
#include <PubSubClient.h>
#include <MKRGSM.h>
const char PINNUMBER[] = SECRET_PINNUMBER; // simcard PIN
const char GPRS_APN[] = SECRET_GPRS_APN; // simcard APN
const char GPRS_LOGIN[] = SECRET_GPRS_LOGIN; // simcard Login
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD; // simcard password
void callback(char* topic, byte* payload, unsigned int length) {
char response;
Serial.print("Messaged arrived [");
Serial.print(topic);
Serial.print("] ");
for (int d = 0; d < length; d++) {
Serial.print((char)payload[d]);
}
}
GSMClient client;
GPRS gprs;
GSM gsmAccess;
PubSubClient pubClient(client);
const char broker[] = "emiwa.info"; // address of the MQTT server "broker.emqx.io";
int port = 1883;
const char topic[] = "v1/devices/me/telemetry"; // topic to publish message to
void setup() {
bool connected = false;
while (!connected) {
if ((gsmAccess.begin() == GSM_READY) &&
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
connected = true;
} else {
Serial.println("Not connected to network...");
delay(1000);
}
}
Serial.println("Connected to network.");
pubClient.setServer(broker, port);
pubClient.setCallback(callback);
while (!pubClient.connected()) {
Serial.print("Attempting to connect to the broker: ");
Serial.println(broker);
if (pubClient.connect("EMIWA", "aHRYfkpmvCftq9mLlLWy", "")) { // Client, username, password
Serial.println("Connected to the broker!");
Serial.println();
pubClient.subscribe(topic);
} else {
Serial.print("Failed with state ");
Serial.print(pubClient.state());
delay(2000);
}
}
}
void loop () {
pubClient.loop();
dataToServer();
}
void dataToServer() {
StaticJsonBuffer<300> JSONbuffer;
JsonObject& JSONencoder = JSONbuffer.createObject();
JSONencoder["Battery_SOC"] = "80 %";
JSONencoder["Battery_Voltage"] = "50 V";
JSONencoder["Switch"] = "1";
char JSONmessageBuffer[100];
JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
if (pubClient.publish(topic, JSONmessageBuffer) == true) {
Serial.println("Message sent successfully...");
} else {
Serial.println("Error sending message...");
}
Serial.println();
Serial.println(JSONmessageBuffer);
}