Skip to content

Commit

Permalink
make it work with ESP8266 with Arduino
Browse files Browse the repository at this point in the history
esphome::socket::Socket does not support UDP with the ESP8266
  • Loading branch information
Links2004 committed Apr 26, 2024
1 parent 5c5382d commit 0a1e6e6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
23 changes: 22 additions & 1 deletion esphome/components/statsd/statsd.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ static const uint16_t SEND_THRESHOLD = 1024;
static const char *const TAG = "statsD";

void StatsdComponent::setup() {
#ifndef USE_ARDUINO
#ifdef ESP8266
#error ESP8266 does not Support UDP socket
#endif
this->sock_ = esphome::socket::socket(AF_INET, SOCK_DGRAM, 0);

struct sockaddr_in source;
Expand All @@ -23,13 +27,16 @@ void StatsdComponent::setup() {
this->destination_.sin_family = AF_INET;
this->destination_.sin_port = htons(this->port_);
this->destination_.sin_addr.s_addr = inet_addr(this->host_);
#endif
}

StatsdComponent::~StatsdComponent() {
#ifndef USE_ARDUINO
if (!this->sock_) {
return;
}
this->sock_->close();
#endif
}

void StatsdComponent::dump_config() {
Expand Down Expand Up @@ -124,14 +131,28 @@ void StatsdComponent::update() {
}

void StatsdComponent::send_(std::string *out) {
if (out->empty() || !this->sock_) {
if (out->empty()) {
return;
}
#ifdef USE_ARDUINO
IPAddress ip;
ip.fromString(this->host_);

this->sock_.beginPacket(ip, this->port_);
this->sock_.write((const uint8_t *) out->c_str(), out->length());
this->sock_.endPacket();

#else
if (!this->sock_) {
return;
}

int n_bytes = this->sock_->sendto(out->c_str(), out->length(), 0, reinterpret_cast<sockaddr *>(&this->destination_),
sizeof(this->destination_));
if (n_bytes != out->length()) {
ESP_LOGE(TAG, "Failed to send UDP packed (%d of %d)", n_bytes, out->length());
}
#endif
}

} // namespace statsd
Expand Down
14 changes: 12 additions & 2 deletions esphome/components/statsd/statsd.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
#include "esphome/components/logger/logger.h"
#endif

#ifdef USE_ARDUINO
#include "WiFiUdp.h"
#include "IPAddress.h"
#endif

namespace esphome {
namespace statsd {

Expand Down Expand Up @@ -62,14 +67,19 @@ class StatsdComponent : public PollingComponent {
#endif

private:
std::unique_ptr<esphome::socket::Socket> sock_;
const char *host_;
const char *prefix_;
uint16_t port_;
struct sockaddr_in destination_;

std::vector<sensors_t> sensors_;

#ifdef USE_ARDUINO
WiFiUDP sock_;
#else
std::unique_ptr<esphome::socket::Socket> sock_;
struct sockaddr_in destination_;
#endif

void send_(std::string *out);
};

Expand Down

0 comments on commit 0a1e6e6

Please sign in to comment.