Add address text sensor to WireGuard (#5576)

This commit is contained in:
Simone Rossetto 2023-10-23 21:05:57 +02:00 committed by GitHub
parent 7e27e98bff
commit e7d51f9c16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,28 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import text_sensor
from esphome.const import (
CONF_ADDRESS,
ENTITY_CATEGORY_DIAGNOSTIC,
)
from . import Wireguard
CONF_WIREGUARD_ID = "wireguard_id"
DEPENDENCIES = ["wireguard"]
CONFIG_SCHEMA = {
cv.GenerateID(CONF_WIREGUARD_ID): cv.use_id(Wireguard),
cv.Optional(CONF_ADDRESS): text_sensor.text_sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
async def to_code(config):
parent = await cg.get_variable(config[CONF_WIREGUARD_ID])
if address_config := config.get(CONF_ADDRESS):
sens = await text_sensor.new_text_sensor(address_config)
cg.add(parent.set_address_sensor(sens))

View File

@ -54,6 +54,12 @@ void Wireguard::setup() {
this->wg_peer_offline_time_ = millis();
this->srctime_->add_on_time_sync_callback(std::bind(&Wireguard::start_connection_, this));
this->defer(std::bind(&Wireguard::start_connection_, this)); // defer to avoid blocking setup
#ifdef USE_TEXT_SENSOR
if (this->address_sensor_ != nullptr) {
this->address_sensor_->publish_state(this->address_);
}
#endif
} else {
ESP_LOGE(TAG, "cannot initialize WireGuard, error code %d", this->wg_initialized_);
this->mark_failed();
@ -186,6 +192,10 @@ void Wireguard::set_status_sensor(binary_sensor::BinarySensor *sensor) { this->s
void Wireguard::set_handshake_sensor(sensor::Sensor *sensor) { this->handshake_sensor_ = sensor; }
#endif
#ifdef USE_TEXT_SENSOR
void Wireguard::set_address_sensor(text_sensor::TextSensor *sensor) { this->address_sensor_ = sensor; }
#endif
void Wireguard::disable_auto_proceed() { this->proceed_allowed_ = false; }
void Wireguard::start_connection_() {

View File

@ -17,6 +17,10 @@
#include "esphome/components/sensor/sensor.h"
#endif
#ifdef USE_TEXT_SENSOR
#include "esphome/components/text_sensor/text_sensor.h"
#endif
#include <esp_wireguard.h>
namespace esphome {
@ -55,6 +59,10 @@ class Wireguard : public PollingComponent {
void set_handshake_sensor(sensor::Sensor *sensor);
#endif
#ifdef USE_TEXT_SENSOR
void set_address_sensor(text_sensor::TextSensor *sensor);
#endif
/// Block the setup step until peer is connected.
void disable_auto_proceed();
@ -85,6 +93,10 @@ class Wireguard : public PollingComponent {
sensor::Sensor *handshake_sensor_ = nullptr;
#endif
#ifdef USE_TEXT_SENSOR
text_sensor::TextSensor *address_sensor_ = nullptr;
#endif
/// Set to false to block the setup step until peer is connected.
bool proceed_allowed_ = true;

View File

@ -49,3 +49,8 @@ sensor:
- platform: wireguard
latest_handshake:
name: 'WireGuard Latest Handshake'
text_sensor:
- platform: wireguard
address:
name: 'WireGuard Address'