Hey buddy, I got an error while compiling the code u mentioned in "how to store data using node mcu". And whatare the data need to be replaced threr

Home - Hey buddy, I got an error while compiling the code u mentioned in "how to store data using node mcu". And whatare the data need to be replaced threr

Chandupa Lasith asked 2 years ago

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = “tf”;
const char* password = “123456789”;
const char* mqtt_server = “api.mesosfer.com”;

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {

delay(10);
Serial.println();
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}

randomSeed(micros());
Serial.println(“”);
Serial.println(“WiFi connected”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
}

/// consumer
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(topic);
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
}

void reconnect() {
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
String clientId = “ESP8266Client-“;
clientId += String(random(0xffff), HEX);

// Attempt to connect broker
if (client.connect(clientId.c_str(), “3laM1pFmRAWZrG2TS-eEoQ”, “FxrmJC79kUMoTkDj”)) {
Serial.println(“connected”);
client.subscribe(“<span style=”color: #0000ff;”><strong>device/your_username/your_channel</strong></span>”);
client.publish(“<span style=”color: #0000ff;”><strong>device/ node/your_channel</strong></span>”, “{\”appId\”:\”test\”,\”schemaId\”:\”String\”,\”bucket\”:\”sensorRead\”,\”metadata\”:{5HGndLNDBI}}”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(” try again in 5 seconds”);
delay(5000);
}
}
}

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
if (!client.connected()) {
reconnect();
}
}

1 Answers
Badrullami Staff answered 2 years ago

Hi Chandupa,
Please change publisher and subscriber channel. It should be like code below :

client.subscribe("device/your_username/your_channel");
client.publish("device/your_username/your_channel", "{\"appId\":\"Your appId\",\"schemaId\":\"Your schemaId\",\"bucket\":\"Your bucet\",\"metadata\":{Your metadata}}");

And make sure that publisher and subscriber channel based on your device data in Mesosfer Dashboard.
Thanks.

Your Answer