Need help to understand how to connect esp8266 to thingsboard such that when my sensor on thingsboard receive and display data on thingsboard and the data on the latest telemetry will be forwarded to my esp32 on arduino ide? I really need the help thanks in advance
Please describe the entire system (esp8266 and an esp32 somewhere?) and the sensors used.
hi, sorry for the late reply. I am just using a D1 mini esp8266 and it is connected to a D1-Relay(Relay shield)-> and it is connected to a output which is a 2 wire fan.
For the software part I am not sure why i cannot use esp8266wifi library.
Okay; I personally never use a relay to drive a modest DC load like a fan; I'd go for a MOSFET solution instead. But a relay will work, so if that's your preference, stick with it.
One question though:
Where is all this in your system?
Anyway, I'll assume that the ESP8266-based system you've sketched above will receive its commands from the outside world in a way that you understand and don't have any trouble with. This leaves the question what exactly goes wrong; can you elaborate on this also new piece of information:
Can you post the code you're trying to run on the D1/ESP8266 and any errors or faulty behavior you're getting?
Actually i have had some success so far but not quite what i needed. I used a documentation online they showed me a code i copied and pasted.
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#define THINGSBOARD_ENABLE_PROGMEM 0
#elif defined(ESP32) || defined(RASPBERRYPI_PICO) || defined(RASPBERRYPI_PICO_W)
#include <WiFi.h>
#endif
#ifndef LED_BUILTIN
#define LED_BUILTIN 99
#endif
#include <Arduino_MQTT_Client.h>
#include <ThingsBoard.h>
constexpr char WIFI_SSID[] = "wifi";
constexpr char WIFI_PASSWORD[] = "password";
// See Getting Started with ThingsBoard | ThingsBoard Community Edition
// to understand how to obtain an access token
constexpr char TOKEN[] = "access_token_thingsboard";
// Thingsboard we want to establish a connection too
constexpr char THINGSBOARD_SERVER[] = "the server i am using";
// MQTT port used to communicate with the server, 1883 is the default unencrypted MQTT port.
constexpr uint16_t THINGSBOARD_PORT = 1883U;
// Maximum size packets will ever be sent or received by the underlying MQTT client,
// if the size is to small messages might not be sent or received messages will be discarded
constexpr uint32_t MAX_MESSAGE_SIZE = 1024U;
// Baud rate for the debugging serial connection.
// If the Serial output is mangled, ensure to change the monitor speed accordingly to this variable
constexpr uint32_t SERIAL_DEBUG_BAUD = 115200U;
// Initialize underlying client, used to establish a connection
WiFiClient wifiClient;
// Initalize the Mqtt client instance
Arduino_MQTT_Client mqttClient(wifiClient);
// Initialize ThingsBoard instance with the maximum needed buffer size
ThingsBoard tb(mqttClient, MAX_MESSAGE_SIZE);
// Attribute names for attribute request and attribute updates functionality
constexpr char BLINKING_INTERVAL_ATTR[] = "blinkingInterval";
constexpr char LED_MODE_ATTR[] = "ledMode";
constexpr char LED_STATE_ATTR[] = "ledState";
// handle led state and mode changes
volatile bool attributesChanged = false;
// LED modes: 0 - continious state, 1 - blinking
volatile int ledMode = 0;
// Current led state
volatile bool ledState = false;
// Settings for interval in blinking mode
constexpr uint16_t BLINKING_INTERVAL_MS_MIN = 10U;
constexpr uint16_t BLINKING_INTERVAL_MS_MAX = 60000U;
volatile uint16_t blinkingInterval = 1000U;
uint32_t previousStateChange;
// For telemetry
constexpr int16_t telemetrySendInterval = 2000U;
uint32_t previousDataSend;
// List of shared attributes for subscribing to their updates
constexpr std::array<const char *, 2U> SHARED_ATTRIBUTES_LIST = {
LED_STATE_ATTR,
BLINKING_INTERVAL_ATTR
};
// List of client attributes for requesting them (Using to initialize device states)
constexpr std::array<const char *, 1U> CLIENT_ATTRIBUTES_LIST = {
LED_MODE_ATTR
};
/// @brief Initalizes WiFi connection,
// will endlessly delay until a connection has been successfully established
void InitWiFi() {
Serial.println("Connecting to AP ...");
// Attempting to establish a connection to the given WiFi network
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
// Delay 500ms until a connection has been succesfully established
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
/// @brief Reconnects the WiFi uses InitWiFi if the connection has been removed
/// @return Returns true as soon as a connection has been established again
const bool reconnect() {
// Check to ensure we aren't connected yet
const wl_status_t status = WiFi.status();
if (status == WL_CONNECTED) {
return true;
}
// If we aren't establish a new connection to the given WiFi network
InitWiFi();
return true;
}
/// @brief Processes function for RPC call "setLedMode"
/// RPC_Data is a JSON variant, that can be queried using operator[]
/// See JsonVariant::operator[] | ArduinoJson 5 for more details
/// @param data Data containing the rpc data that was called and its current value
/// @return Response that should be sent to the cloud. Useful for getMethods
RPC_Response processSetLedMode(const RPC_Data &data) {
Serial.println("Received the set led state RPC method");
// Process data
int new_mode = data;
Serial.print("Mode to change: ");
Serial.println(new_mode);
if (new_mode != 0 && new_mode != 1) {
return RPC_Response("error", "Unknown mode!");
}
ledMode = new_mode;
attributesChanged = true;
// Returning current mode
return RPC_Response("newMode", (int)ledMode);
}
// Optional, keep subscribed shared attributes empty instead,
// and the callback will be called for every shared attribute changed on the device,
// instead of only the one that were entered instead
const std::array<RPC_Callback, 1U> callbacks = {
RPC_Callback{ "setLedMode", processSetLedMode }
};
/// @brief Update callback that will be called as soon as one of the provided shared attributes changes value,
/// if none are provided we subscribe to any shared attribute change instead
/// @param data Data containing the shared attributes that were changed and their current value
void processSharedAttributes(const Shared_Attribute_Data &data) {
for (auto it = data.begin(); it != data.end(); ++it) {
if (strcmp(it->key().c_str(), BLINKING_INTERVAL_ATTR) == 0) {
const uint16_t new_interval = it->value().as<uint16_t>();
if (new_interval >= BLINKING_INTERVAL_MS_MIN && new_interval <= BLINKING_INTERVAL_MS_MAX) {
blinkingInterval = new_interval;
Serial.print("Blinking interval is set to: ");
Serial.println(new_interval);
}
} else if (strcmp(it->key().c_str(), LED_STATE_ATTR) == 0) {
ledState = it->value().as();
if (LED_BUILTIN != 99) {
digitalWrite(LED_BUILTIN, ledState);
}
Serial.print("LED state is set to: ");
Serial.println(ledState);
}
}
attributesChanged = true;
}
void processClientAttributes(const Shared_Attribute_Data &data) {
for (auto it = data.begin(); it != data.end(); ++it) {
if (strcmp(it->key().c_str(), LED_MODE_ATTR) == 0) {
const uint16_t new_mode = it->value().as<uint16_t>();
ledMode = new_mode;
}
}
}
const Shared_Attribute_Callback attributes_callback(&processSharedAttributes, SHARED_ATTRIBUTES_LIST.cbegin(), SHARED_ATTRIBUTES_LIST.cend());
const Attribute_Request_Callback attribute_shared_request_callback(&processSharedAttributes, SHARED_ATTRIBUTES_LIST.cbegin(), SHARED_ATTRIBUTES_LIST.cend());
const Attribute_Request_Callback attribute_client_request_callback(&processClientAttributes, CLIENT_ATTRIBUTES_LIST.cbegin(), CLIENT_ATTRIBUTES_LIST.cend());
void setup() {
// Initalize serial connection for debugging
Serial.begin(SERIAL_DEBUG_BAUD);
if (LED_BUILTIN != 99) {
pinMode(LED_BUILTIN, OUTPUT);
}
delay(1000);
InitWiFi();
}
void loop() {
delay(10);
if (!reconnect()) {
return;
}
if (!tb.connected()) {
// Connect to the ThingsBoard
Serial.print("Connecting to: ");
Serial.print(THINGSBOARD_SERVER);
Serial.print(" with token ");
Serial.println(TOKEN);
if (!tb.connect(THINGSBOARD_SERVER, TOKEN, THINGSBOARD_PORT)) {
Serial.println("Failed to connect");
return;
}
// Sending a MAC address as an attribute
tb.sendAttributeData("macAddress", WiFi.macAddress().c_str());
Serial.println("Subscribing for RPC...");
// Perform a subscription. All consequent data processing will happen in
// processSetLedState() and processSetLedMode() functions,
// as denoted by callbacks array.
if (!tb.RPC_Subscribe(callbacks.cbegin(), callbacks.cend())) {
Serial.println("Failed to subscribe for RPC");
return;
}
if (!tb.Shared_Attributes_Subscribe(attributes_callback)) {
Serial.println("Failed to subscribe for shared attribute updates");
return;
}
Serial.println("Subscribe done");
// Request current states of shared attributes
if (!tb.Shared_Attributes_Request(attribute_shared_request_callback)) {
Serial.println("Failed to request for shared attributes");
return;
}
// Request current states of client attributes
if (!tb.Client_Attributes_Request(attribute_client_request_callback)) {
Serial.println("Failed to request for client attributes");
return;
}
}
if (attributesChanged) {
attributesChanged = false;
if (ledMode == 0) {
previousStateChange = millis();
}
tb.sendTelemetryData(LED_MODE_ATTR, ledMode);
tb.sendTelemetryData(LED_STATE_ATTR, ledState);
tb.sendAttributeData(LED_MODE_ATTR, ledMode);
tb.sendAttributeData(LED_STATE_ATTR, ledState);
}
if (ledMode == 1 && millis() - previousStateChange > blinkingInterval) {
previousStateChange = millis();
ledState = !ledState;
tb.sendTelemetryData(LED_STATE_ATTR, ledState);
tb.sendAttributeData(LED_STATE_ATTR, ledState);
if (LED_BUILTIN == 99) {
Serial.print("LED state changed to: ");
Serial.println(ledState);
} else {
digitalWrite(LED_BUILTIN, ledState);
}
}
// Sending telemetry every telemetrySendInterval time
if (millis() - previousDataSend > telemetrySendInterval) {
previousDataSend = millis();
tb.sendTelemetryData("temperature", random(10, 20));
tb.sendAttributeData("rssi", WiFi.RSSI());
tb.sendAttributeData("channel", WiFi.channel());
tb.sendAttributeData("bssid", WiFi.BSSIDstr().c_str());
tb.sendAttributeData("localIp", WiFi.localIP().toString().c_str());
tb.sendAttributeData("ssid", WiFi.SSID().c_str());
Serial.println("it worked");
}
tb.loop();
}
So it can send data but I want to do the reverse and receieve the data instead. but I am not sure how to write a program/ add codes to work. is it possible for you to help me.
This is my co2 sensor data that is being sent to thingsboard every 5 minutes.
The esp32 on top i type wrongly it should be esp8266 my bad @rsmls
so the error i had before disappeared but now im just not sure how to receive telemetry data
OK, that seems to be a very specific question about ThingsBoard. Have you tried their support forum: https://groups.google.com/g/thingsboard
There's also their own online documentation including examples/how-to's: ThingsBoard Community Edition | ThingsBoard Community Edition
ther isnt any documentation on it but I will try the forum
Really? This seems to be exactly what you're trying to do: ESP8266 GPIO control over MQTT using ThingsBoard | ThingsBoard Community Edition
I tried it didnt really work out how i wanted it to. in this code it sends data from thingsboard to arduino if you press something on the dashboard but how can i use it such that it connects to the v1/devices/me /telemetry?
You'll have to dig into the documentation of ThingsBoard for that.
In general, you'll have to rely on examples and at the same time learn about how the system works and can be programmed. The examples can be used for inspiration, but the actual solution tends to be the result of perspiration - i.e. doing the work by yourself mostly.
Embedded systems programming may seem like a matter of patching together bits of found code sometimes, but that approach nearly always gets you stuck. See if you can become a little more self-reliant, with the help of documentation, tutorials, YouTube videos and asking questions on forums.
As to the question you're asking now, I think you have a better chance of getting an answer on the ThingsBoard forum.
I see, thanks for the reply, I will do that.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.