Ubidots Community

[SOLVED] problem sending JSON object with pubsubclient library

Hello, I am new using the platform, my problem: I need to send text variables, and change them at will, for this I understand that I must use the “context” section, and for this I use a JSON work, but I do not get the message to reach The platform would greatly appreciate your help and patience.
I enclose the code I am using

#include "ArduinoJson.h"
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>    // incluye libreria para interfaz I2C
#include <RTClib.h>   // incluye libreria para el manejo del modulo RTC
RTC_DS3231 rtc;     // crea objeto del tipo RTC_DS3231
bool alarma = false;   // variable de control con valor verdadero
bool alarma2 =false;   // variable de control con valor verdadero

#define WIFISSID "********************" // Put your WifiSSID here
#define PASSWORD "***************************" // Put your wifi password here
#define TOKEN "***************" // Put your Ubidots' TOKEN
#define MQTT_CLIENT_NAME "Put_your_MQTT_client_name_here" // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string; 
                                           //it should be a random and unique ascii string and different from all other devices

/****************************************
 * Include Libraries
 ****************************************/

#define VARIABLE_LABEL "a1" // Assing the variable label
#define DEVICE_LABEL "ESP32" // Assig the device label

#define SENSOR 12 // Set the GPIO12 as SENSOR

char mqttBroker[]  = "industrial.api.ubidots.com";
char payload[100];
char topic[150];
// Space to store values to send
char str_sensor[10];
char str_lat[6];
char str_lng[6];

/****************************************
 * Auxiliar Functions
 ****************************************/
WiFiClient ubidots;
PubSubClient client(ubidots);

void callback(char* topic, byte* payload, unsigned int length) {
  char p[length + 1];
  memcpy(p, payload, length);
  p[length] = NULL;
  String message(p);
  Serial.write(payload, length);
  Serial.println(topic);
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    
    // Attemp to connect
    if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
      Serial.println("Connected");
    } else {
      Serial.print("Failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 2 seconds");
      // Wait 2 seconds before retrying
      delay(2000);
    }
  }
}

/****************************************
 * Main Functions
 ****************************************/
void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFISSID, PASSWORD);
  // Assign the pin as INPUT 
  pinMode(SENSOR, INPUT);

  Serial.println();
  Serial.print("Wait for WiFi...");
  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  
  Serial.println("");
  Serial.println("WiFi Connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  client.setServer(mqttBroker, 1883);
  client.setCallback(callback); 

}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  
  StaticJsonBuffer<300> JSONBuffer;
  JsonObject& root = JSONBuffer.createObject();
  root["%s value"] = "4000";
  //root["context"] = "gps";
  
  char json[256];
  root.printTo(json, sizeof(json));
  Serial.println();
  //JsonObject& parsed = JSONBuffer.parseObject(json);
  //const char * valor = parsed["\"value\""];
  //const char * valor2 = json;
  Serial.print("json =");Serial.println(json);
  root.printTo(Serial);

  sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
  sprintf(payload, "%s", ""); // Cleans the payload
  sprintf(payload, "{\"%s\":", VARIABLE_LABEL); // Adds the variable label
  
  float sensor = analogRead(SENSOR); 
  float lat = 6.101;
  float lng= -1.293;

  /* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
  dtostrf(sensor, 4, 2, str_sensor);
  dtostrf(lat, 4, 2, str_lat);
  dtostrf(lng, 4, 2, str_lng); 
  //sprintf(payload, "%s {\"value\": 10}}", payload);
  //sprintf(payload, "%s {\"value\": 10", payload, str_sensor); // Adds the value
  //sprintf(payload, "%s, \"context\":{\"lat\": %s, \"lng\": %s}", payload, str_lat, str_lng); // Adds coordinates
  //sprintf(payload, "%s } }", payload); // Closes the dictionary brackets
  Serial.println("Publishing data to Ubidots Cloud");

  client.publish(json,topic);
  client.loop();
  delay(1000);
}

Hi there, the script below will give you a way to create properly context keys accepted by our REST API, feel free to adapt it to your needs

  // Cloud chars
  char payload[700];
  char topic[150];

  // Space to store values to send
  char str_val[6];

  // Values to send
  float temperature = random(0, 50);

  /* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/
  dtostrf(temperature, 4, 2, str_val);

  char* str_status = (char *) malloc(sizeof(char) * 20);
  sprintf(str_status, "");
  if (temperature < 12) {
    sprintf(str_status, "\"cold\"");
  } else {
    sprintf(str_status, "\"sunny\"");
  }

  sprintf(topic, "%s", ""); // Cleans the topic content
  sprintf(topic, "%s%s", "/v1.6/devices/", "weather-station");

  sprintf(payload, "%s", ""); // Cleans the payload content
  sprintf(payload, "{\"%s\":", "temperature"); // Adds the variable label   
  sprintf(payload, "%s {\"value\": %s", payload, str_val); // Adds the value
  sprintf(payload, "%s, \"context\":{\"status\": %s}", payload, str_status); // Adds context
  sprintf(payload, "%s } }", payload); // Closes the dictionary brackets

  free(str_status);
  client.publish(topic, payload);
  client.loop();
  delay(1000);

You may reference additional examples at our docs.