-1

I'm trying to let my Arduino and esp8266 send data to thingsboard and then subscribe to thingsboard's mqtt channel and get a timestamp from it but for some unknown reason, it just doesn't work. Checked server-side and it was ok, tried postman to simulate request and also getting the correct response from the server. Also, I had read the documentation about esp8266 and it somehow did state that it only can have 1 connection simultaneously. But tried to let my Arduino to only subscribe to channel but it still doesn't work.

My code:(I'm using Arduino Mega for this)

#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <TimeLib.h>

#define WIFI_AP "CEC"
#define WIFI_PASSWORD "#CEC@2017@CEC#"

#define TOKEN "A1_TEST_TOKEN"

// DHT
#define DHTPIN 2
#define DHTTYPE DHT22

char thingsboardServer[] = "192.168.0.250";

// Initialize the Ethernet client object
WiFiEspClient espClient;

// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);

PubSubClient client(espClient);

int status = WL_IDLE_STATUS;
unsigned long lastSend;
unsigned long lastSync;

void setup() {
  // initialize serial for debugging
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);

  //serial pin
      pinMode(LED_RUN_pin, OUTPUT);

  //dht.begin();
  InitWiFi();
  lastSend = 0;
  lastSync = 0;
  //client subscribe thingsboard rpc PUBLISH msg
  client.setServer( thingsboardServer, 1883 );
   client.setCallback(on_message);
}

void loop() {
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    while ( status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(WIFI_AP);
      // Connect to WPA/WPA2 network
      status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
      delay(500);
    }
  }

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

  if ( millis() - lastSend > 30000 ) { // Update and send after 30 seconds
    getAndSendTemperatureAndHumidityData();
    lastSend = millis();
  }

  client.loop();
}

void getAndSendTemperatureAndHumidityData()
{
  Serial.println("Collecting temperature data.");

  // Reading temperature or humidity takes about 250 milliseconds!
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");

  String temperature = String(t);
  String humidity = String(h);

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"temperature\":"; payload += temperature; payload += ",";
  payload += "\"humidity\":"; payload += humidity;
  payload += "}";

  // Send payload
  char attributes[100];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/devices/me/rpc/request/1", attributes , 1);
  //Serial.println( attributes );
}


  // Prepare a JSON payload string
 String payload = "{method: getTime, params:{}}";

  // Send payload
  char attributes[100];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/A1_TEST_TOKEN/rpc", attributes );
  //Serial.println( attributes );
}

void InitWiFi()
{ 
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);
  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (false);
  }

  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    // Connect to WPA/WPA2 network
    status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
    delay(500);
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    //Serial.print("Connecting to Thingsboard node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("Arduino Uno Device", TOKEN, NULL) ) {
     Serial.println( "[DONE]" );
      delay(500);
     // Serial.println("Subscribing RPC");
     client.subscribe("v1/devices/me/rpc/request/+");
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 20  seconds]" );
      // Wait 20 seconds before retrying
      delay( 20000 );
    }
  }
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

// The callback for when a PUBLISH message is received from the server.
void on_message (char* topic, byte* payload, unsigned int length) {

  //Serial.println("On message");

  char json[length + 1];
  strncpy (json, (char*)payload, length);
  json[length] = '\23';

  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  Serial.println(json); 

  // Decode JSON request
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& data = jsonBuffer.parseObject((char*)json);

  if (!data.success())
  {
    Serial.println("parseObject() failed");
    return;
  }
}
Tenent Jason
  • 5
  • 1
  • 6

1 Answers1

0

Probably a stupid remark, but is your TOKEN a valid Thingsboard device token? I assume you entered the value A1_TEST_TOKEN to hide your real authentication token.

I also assume you are trying to send sensor data (telemetry) to Thingsboard. Why did you decide to use the RPC API for sending data? I think it might be easier to use the MQTT Device API instead.

I don't have any experience in developing for Arduino. I am using Thingsboard together with a Raspberry PI to write and display sensor data. Hope you find a solution for your problem!

KDW
  • 485
  • 3
  • 17