From 4fe0c95ccbfabc74b4e4a3c3b13acd956eef1224 Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Fri, 7 Jun 2019 14:26:17 +0200 Subject: [PATCH] Allow id() syntax for custom code (#621) * Allow id() syntax for custom code * Lint --- esphome/components/globals/globals_component.h | 3 +++ esphome/core/helpers.h | 8 ++++++-- tests/custom.h | 7 ++++++- tests/test3.yaml | 5 +++++ 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/esphome/components/globals/globals_component.h b/esphome/components/globals/globals_component.h index c7d2a18d84..397c55f6c4 100644 --- a/esphome/components/globals/globals_component.h +++ b/esphome/components/globals/globals_component.h @@ -2,6 +2,7 @@ #include "esphome/core/component.h" #include "esphome/core/automation.h" +#include "esphome/core/helpers.h" namespace esphome { namespace globals { @@ -64,5 +65,7 @@ template class GlobalVarSetAction : public Action T &id(GlobalsComponent *value) { return value->value(); } + } // namespace globals } // namespace esphome diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index d21cb85b7d..01586a606f 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -4,6 +4,7 @@ #include #include #include +#include #include "esphome/core/optional.h" #include "esphome/core/esphal.h" @@ -160,6 +161,11 @@ template struct seq {}; // NOLINT template struct gens : gens {}; // NOLINT template struct gens<0, S...> { using type = seq; }; // NOLINT +template using enable_if_t = typename std::enable_if::type; + +template::value, int> = 0> T id(T value) { return value; } +template::value, int> = 0> T &id(T *value) { return *value; } + template class CallbackManager; /** Simple helper class to allow having multiple subscribers to a signal. @@ -192,8 +198,6 @@ struct is_callable // NOLINT static constexpr auto value = decltype(test(nullptr))::value; // NOLINT }; -template using enable_if_t = typename std::enable_if::type; - template class TemplatableValue { public: TemplatableValue() : type_(EMPTY) {} diff --git a/tests/custom.h b/tests/custom.h index b392819efb..2635084406 100644 --- a/tests/custom.h +++ b/tests/custom.h @@ -3,7 +3,12 @@ class CustomSensor : public Component, public Sensor { public: - void loop() override { publish_state(42.0); } + void loop() override { + // Test id() helper + float value = id(my_sensor).state; + id(my_global_string) = "Hello World"; + publish_state(42.0); + } }; class CustomTextSensor : public Component, public TextSensor { diff --git a/tests/test3.yaml b/tests/test3.yaml index 6b64af8981..8088b12d03 100644 --- a/tests/test3.yaml +++ b/tests/test3.yaml @@ -246,6 +246,11 @@ binary_sensor: - id: custom_binary_sensor name: Custom Binary Sensor +globals: + - id: my_global_string + type: std::string + initial_value: '""' + remote_receiver: pin: GPIO12 dump: []