From 7ad593d674e488e3abbfb3208326e3cbcd404d24 Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 15:25:38 +0200 Subject: [PATCH 1/9] Add setup, loop as reserved IDs Fixes https://github.com/esphome/issues/issues/496 --- esphome/config_validation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/config_validation.py b/esphome/config_validation.py index b98a56c4b9..dfe05a7637 100644 --- a/esphome/config_validation.py +++ b/esphome/config_validation.py @@ -61,7 +61,7 @@ RESERVED_IDS = [ 'App', 'pinMode', 'delay', 'delayMicroseconds', 'digitalRead', 'digitalWrite', 'INPUT', 'OUTPUT', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'int8_t', 'int16_t', 'int32_t', 'int64_t', - 'close', 'pause', 'sleep', 'open', + 'close', 'pause', 'sleep', 'open', 'setup', 'loop', ] From 762f1b1fc9c109ae0ab6205c15c7b1ed2e4880eb Mon Sep 17 00:00:00 2001 From: Nikolay Vasilchuk Date: Wed, 3 Jul 2019 17:33:18 +0300 Subject: [PATCH 2/9] ZyAura CO2 / Temperature / Humidity Sensor (#656) * ZyAura sensors support * Validation * Small refactoring * Some checks * Small fix * Use floats, not double Co-Authored-By: Otto Winter * uint32_t now Co-Authored-By: Otto Winter * A constant for bits in a byte just over-complicates the source code Co-Authored-By: Otto Winter * Review fixes * Review fixes * Review fixes * Review fixes * Review fixes * Review fixes * Review fixes * Review fixes * Travis fixes * Travis fixes * Travis fixes --- esphome/components/zyaura/__init__.py | 0 esphome/components/zyaura/sensor.py | 43 ++++++++++ esphome/components/zyaura/zyaura.cpp | 117 ++++++++++++++++++++++++++ esphome/components/zyaura/zyaura.h | 86 +++++++++++++++++++ tests/test1.yaml | 9 ++ 5 files changed, 255 insertions(+) create mode 100644 esphome/components/zyaura/__init__.py create mode 100644 esphome/components/zyaura/sensor.py create mode 100644 esphome/components/zyaura/zyaura.cpp create mode 100644 esphome/components/zyaura/zyaura.h diff --git a/esphome/components/zyaura/__init__.py b/esphome/components/zyaura/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/zyaura/sensor.py b/esphome/components/zyaura/sensor.py new file mode 100644 index 0000000000..649b80b444 --- /dev/null +++ b/esphome/components/zyaura/sensor.py @@ -0,0 +1,43 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome import pins +from esphome.components import sensor +from esphome.const import CONF_ID, CONF_CLOCK_PIN, CONF_DATA_PIN, \ + CONF_CO2, CONF_TEMPERATURE, CONF_HUMIDITY, \ + UNIT_PARTS_PER_MILLION, UNIT_CELSIUS, UNIT_PERCENT, \ + ICON_PERIODIC_TABLE_CO2, ICON_THERMOMETER, ICON_WATER_PERCENT +from esphome.cpp_helpers import gpio_pin_expression + +zyaura_ns = cg.esphome_ns.namespace('zyaura') +ZyAuraSensor = zyaura_ns.class_('ZyAuraSensor', cg.PollingComponent) + +CONFIG_SCHEMA = cv.Schema({ + cv.GenerateID(): cv.declare_id(ZyAuraSensor), + cv.Required(CONF_CLOCK_PIN): cv.All(pins.internal_gpio_input_pin_schema, + pins.validate_has_interrupt), + cv.Required(CONF_DATA_PIN): cv.All(pins.internal_gpio_input_pin_schema, + pins.validate_has_interrupt), + cv.Optional(CONF_CO2): sensor.sensor_schema(UNIT_PARTS_PER_MILLION, ICON_PERIODIC_TABLE_CO2, 0), + cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 1), + cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(UNIT_PERCENT, ICON_WATER_PERCENT, 1), +}).extend(cv.polling_component_schema('60s')) + + +def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + yield cg.register_component(var, config) + + pin_clock = yield gpio_pin_expression(config[CONF_CLOCK_PIN]) + cg.add(var.set_pin_clock(pin_clock)) + pin_data = yield gpio_pin_expression(config[CONF_DATA_PIN]) + cg.add(var.set_pin_data(pin_data)) + + if CONF_CO2 in config: + sens = yield sensor.new_sensor(config[CONF_CO2]) + cg.add(var.set_co2_sensor(sens)) + if CONF_TEMPERATURE in config: + sens = yield sensor.new_sensor(config[CONF_TEMPERATURE]) + cg.add(var.set_temperature_sensor(sens)) + if CONF_HUMIDITY in config: + sens = yield sensor.new_sensor(config[CONF_HUMIDITY]) + cg.add(var.set_humidity_sensor(sens)) diff --git a/esphome/components/zyaura/zyaura.cpp b/esphome/components/zyaura/zyaura.cpp new file mode 100644 index 0000000000..3b1a2a5069 --- /dev/null +++ b/esphome/components/zyaura/zyaura.cpp @@ -0,0 +1,117 @@ +#include "zyaura.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace zyaura { + +static const char *TAG = "zyaura"; + +bool ICACHE_RAM_ATTR ZaDataProcessor::decode(unsigned long ms, bool data) { + // check if a new message has started, based on time since previous bit + if ((ms - this->prev_ms_) > ZA_MAX_MS) { + this->num_bits_ = 0; + } + this->prev_ms_ = ms; + + // number of bits received is basically the "state" + if (this->num_bits_ < ZA_FRAME_SIZE) { + // store it while it fits + int idx = this->num_bits_ / 8; + this->buffer_[idx] = (this->buffer_[idx] << 1) | (data ? 1 : 0); + this->num_bits_++; + + // are we done yet? + if (this->num_bits_ == ZA_FRAME_SIZE) { + // validate checksum + uint8_t checksum = this->buffer_[ZA_BYTE_TYPE] + this->buffer_[ZA_BYTE_HIGH] + this->buffer_[ZA_BYTE_LOW]; + if (checksum != this->buffer_[ZA_BYTE_SUM] || this->buffer_[ZA_BYTE_END] != ZA_MSG_DELIMETER) { + return false; + } + + this->message->type = (ZaDataType) this->buffer_[ZA_BYTE_TYPE]; + this->message->value = this->buffer_[ZA_BYTE_HIGH] << 8 | this->buffer_[ZA_BYTE_LOW]; + return true; + } + } + + return false; +} + +void ZaSensorStore::setup(GPIOPin *pin_clock, GPIOPin *pin_data) { + pin_clock->setup(); + pin_data->setup(); + this->pin_clock_ = pin_clock->to_isr(); + this->pin_data_ = pin_data->to_isr(); + pin_clock->attach_interrupt(ZaSensorStore::interrupt, this, FALLING); +} + +void ICACHE_RAM_ATTR ZaSensorStore::interrupt(ZaSensorStore *arg) { + uint32_t now = millis(); + bool data_bit = arg->pin_data_->digital_read(); + + if (arg->processor_.decode(now, data_bit)) { + arg->set_data_(arg->processor_.message); + } +} + +void ICACHE_RAM_ATTR ZaSensorStore::set_data_(ZaMessage *message) { + switch (message->type) { + case HUMIDITY: + this->humidity = (message->value > 10000) ? NAN : (message->value / 100.0f); + break; + + case TEMPERATURE: + this->temperature = (message->value > 5970) ? NAN : (message->value / 16.0f - 273.15f); + break; + + case CO2: + this->co2 = (message->value > 10000) ? NAN : message->value; + break; + + default: + break; + } +} + +bool ZyAuraSensor::publish_state_(sensor::Sensor *sensor, float *value) { + // Sensor doesn't added to configuration + if (sensor == nullptr) { + return true; + } + + sensor->publish_state(*value); + + // Sensor reported wrong value + if (isnan(*value)) { + ESP_LOGW(TAG, "Sensor reported invalid data. Is the update interval too small?"); + this->status_set_warning(); + return false; + } + + *value = NAN; + return true; +} + +void ZyAuraSensor::dump_config() { + ESP_LOGCONFIG(TAG, "ZyAuraSensor:"); + LOG_PIN(" Pin Clock: ", this->pin_clock_); + LOG_PIN(" Pin Data: ", this->pin_data_); + LOG_UPDATE_INTERVAL(this); + + LOG_SENSOR(" ", "CO2", this->co2_sensor_); + LOG_SENSOR(" ", "Temperature", this->temperature_sensor_); + LOG_SENSOR(" ", "Humidity", this->humidity_sensor_); +} + +void ZyAuraSensor::update() { + bool co2_result = this->publish_state_(this->co2_sensor_, &this->store_.co2); + bool temperature_result = this->publish_state_(this->temperature_sensor_, &this->store_.temperature); + bool humidity_result = this->publish_state_(this->humidity_sensor_, &this->store_.humidity); + + if (co2_result && temperature_result && humidity_result) { + this->status_clear_warning(); + } +} + +} // namespace zyaura +} // namespace esphome diff --git a/esphome/components/zyaura/zyaura.h b/esphome/components/zyaura/zyaura.h new file mode 100644 index 0000000000..fd26947e28 --- /dev/null +++ b/esphome/components/zyaura/zyaura.h @@ -0,0 +1,86 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/core/esphal.h" +#include "esphome/components/sensor/sensor.h" + +namespace esphome { +namespace zyaura { + +static const uint8_t ZA_MAX_MS = 2; +static const uint8_t ZA_MSG_LEN = 5; +static const uint8_t ZA_FRAME_SIZE = 40; +static const uint8_t ZA_MSG_DELIMETER = 0x0D; + +static const uint8_t ZA_BYTE_TYPE = 0; +static const uint8_t ZA_BYTE_HIGH = 1; +static const uint8_t ZA_BYTE_LOW = 2; +static const uint8_t ZA_BYTE_SUM = 3; +static const uint8_t ZA_BYTE_END = 4; + +enum ZaDataType { + HUMIDITY = 0x41, + TEMPERATURE = 0x42, + CO2 = 0x50, +}; + +struct ZaMessage { + ZaDataType type; + uint16_t value; +}; + +class ZaDataProcessor { + public: + bool decode(unsigned long ms, bool data); + ZaMessage *message = new ZaMessage; + + protected: + uint8_t buffer_[ZA_MSG_LEN]; + int num_bits_ = 0; + unsigned long prev_ms_; +}; + +class ZaSensorStore { + public: + float co2 = NAN; + float temperature = NAN; + float humidity = NAN; + + void setup(GPIOPin *pin_clock, GPIOPin *pin_data); + static void interrupt(ZaSensorStore *arg); + + protected: + ISRInternalGPIOPin *pin_clock_; + ISRInternalGPIOPin *pin_data_; + ZaDataProcessor processor_; + + void set_data_(ZaMessage *message); +}; + +/// Component for reading temperature/co2/humidity measurements from ZyAura sensors. +class ZyAuraSensor : public PollingComponent { + public: + void set_pin_clock(GPIOPin *pin) { pin_clock_ = pin; } + void set_pin_data(GPIOPin *pin) { pin_data_ = pin; } + void set_co2_sensor(sensor::Sensor *co2_sensor) { co2_sensor_ = co2_sensor; } + void set_temperature_sensor(sensor::Sensor *temperature_sensor) { temperature_sensor_ = temperature_sensor; } + void set_humidity_sensor(sensor::Sensor *humidity_sensor) { humidity_sensor_ = humidity_sensor; } + + void setup() override { this->store_.setup(this->pin_clock_, this->pin_data_); } + void dump_config() override; + void update() override; + float get_setup_priority() const override { return setup_priority::DATA; } + + protected: + ZaSensorStore store_; + GPIOPin *pin_clock_; + GPIOPin *pin_data_; + sensor::Sensor *co2_sensor_{nullptr}; + sensor::Sensor *temperature_sensor_{nullptr}; + sensor::Sensor *humidity_sensor_{nullptr}; + + bool publish_state_(sensor::Sensor *sensor, float *value); +}; + +} // namespace zyaura +} // namespace esphome diff --git a/tests/test1.yaml b/tests/test1.yaml index bfdc34fac1..4fa2f85cf6 100644 --- a/tests/test1.yaml +++ b/tests/test1.yaml @@ -564,6 +564,15 @@ sensor: name: CCS811 TVOC update_interval: 30s baseline: 0x4242 + - platform: zyaura + clock_pin: GPIO5 + data_pin: GPIO4 + co2: + name: "ZyAura CO2" + temperature: + name: "ZyAura Temperature" + humidity: + name: "ZyAura Humidity" esp32_touch: From 0ef1d178d29a5e7dc7c038d377432bb02375cfba Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 16:34:03 +0200 Subject: [PATCH 3/9] Fix deep sleep on_shutdown hooks (#660) Fixes https://github.com/esphome/feature-requests/issues/294 --- esphome/core/application.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/esphome/core/application.h b/esphome/core/application.h index 82f344bf1a..e2bf8c0ad9 100644 --- a/esphome/core/application.h +++ b/esphome/core/application.h @@ -119,8 +119,12 @@ class Application { void safe_reboot(); void run_safe_shutdown_hooks() { - for (auto *comp : this->components_) + for (auto *comp : this->components_) { comp->on_safe_shutdown(); + } + for (auto *comp : this->components_) { + comp->on_shutdown(); + } } uint32_t get_app_state() const { return this->app_state_; } From 81a070d03d04b83cff2e64c904cbc3e9daef5c01 Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 16:34:40 +0200 Subject: [PATCH 4/9] ESP32 Use NVS directly (#659) --- esphome/core/application.h | 2 +- esphome/core/preferences.cpp | 59 +++++++++++++++++++++++++++++------- esphome/core/preferences.h | 8 ++--- esphome/core_config.py | 1 - 4 files changed, 51 insertions(+), 19 deletions(-) diff --git a/esphome/core/application.h b/esphome/core/application.h index e2bf8c0ad9..2014b082e9 100644 --- a/esphome/core/application.h +++ b/esphome/core/application.h @@ -40,7 +40,7 @@ class Application { void pre_setup(const std::string &name, const char *compilation_time) { this->name_ = name; this->compilation_time_ = compilation_time; - global_preferences.begin(this->name_); + global_preferences.begin(); } #ifdef USE_BINARY_SENSOR diff --git a/esphome/core/preferences.cpp b/esphome/core/preferences.cpp index b975426181..f62a764b7e 100644 --- a/esphome/core/preferences.cpp +++ b/esphome/core/preferences.cpp @@ -1,12 +1,17 @@ #include "esphome/core/preferences.h" #include "esphome/core/log.h" #include "esphome/core/helpers.h" +#include "esphome/core/application.h" #ifdef ARDUINO_ARCH_ESP8266 extern "C" { #include "spi_flash.h" } #endif +#ifdef ARDUINO_ARCH_ESP32 +#include "nvs.h" +#include "nvs_flash.h" +#endif namespace esphome { @@ -165,7 +170,7 @@ ESPPreferences::ESPPreferences() // which will be reset each time OTA occurs : current_offset_(0) {} -void ESPPreferences::begin(const std::string &name) { +void ESPPreferences::begin() { this->flash_storage_ = new uint32_t[ESP8266_FLASH_STORAGE_SIZE]; ESP_LOGVV(TAG, "Loading preferences from flash..."); disable_interrupts(); @@ -219,32 +224,64 @@ bool ESPPreferences::is_prevent_write() { return this->prevent_write_; } #ifdef ARDUINO_ARCH_ESP32 bool ESPPreferenceObject::save_internal_() { + if (global_preferences.nvs_handle_ == 0) + return false; + char key[32]; sprintf(key, "%u", this->offset_); uint32_t len = (this->length_words_ + 1) * 4; - size_t ret = global_preferences.preferences_.putBytes(key, this->data_, len); - if (ret != len) { - ESP_LOGV(TAG, "putBytes failed!"); + esp_err_t err = nvs_set_blob(global_preferences.nvs_handle_, key, this->data_, len); + if (err) { + ESP_LOGV(TAG, "nvs_set_blob('%s', len=%u) failed: %s", key, len, esp_err_to_name(err)); + return false; + } + err = nvs_commit(global_preferences.nvs_handle_); + if (err) { + ESP_LOGV(TAG, "nvs_commit('%s', len=%u) failed: %s", key, len, esp_err_to_name(err)); return false; } return true; } bool ESPPreferenceObject::load_internal_() { + if (global_preferences.nvs_handle_ == 0) + return false; + char key[32]; sprintf(key, "%u", this->offset_); uint32_t len = (this->length_words_ + 1) * 4; - size_t ret = global_preferences.preferences_.getBytes(key, this->data_, len); - if (ret != len) { - ESP_LOGV(TAG, "getBytes failed!"); + + uint32_t actual_len; + esp_err_t err = nvs_get_blob(global_preferences.nvs_handle_, key, nullptr, &actual_len); + if (err) { + ESP_LOGV(TAG, "nvs_get_blob('%s'): %s - the key might not be set yet", key, esp_err_to_name(err)); + return false; + } + if (actual_len != len) { + ESP_LOGVV(TAG, "NVS length does not match. Assuming key changed (%u!=%u)", actual_len, len); + return false; + } + err = nvs_get_blob(global_preferences.nvs_handle_, key, this->data_, &len); + if (err) { + ESP_LOGV(TAG, "nvs_get_blob('%s') failed: %s", key, esp_err_to_name(err)); return false; } return true; } ESPPreferences::ESPPreferences() : current_offset_(0) {} -void ESPPreferences::begin(const std::string &name) { - const std::string key = truncate_string(name, 15); - ESP_LOGV(TAG, "Opening preferences with key '%s'", key.c_str()); - this->preferences_.begin(key.c_str()); +void ESPPreferences::begin() { + auto ns = truncate_string(App.get_name(), 15); + esp_err_t err = nvs_open(ns.c_str(), NVS_READWRITE, &this->nvs_handle_); + if (err) { + ESP_LOGW(TAG, "nvs_open failed: %s - erasing NVS...", esp_err_to_name(err)); + nvs_flash_deinit(); + nvs_flash_erase(); + nvs_flash_init(); + + err = nvs_open(ns.c_str(), NVS_READWRITE, &this->nvs_handle_); + if (err) { + this->nvs_handle_ = 0; + } + } } ESPPreferenceObject ESPPreferences::make_preference(size_t length, uint32_t type, bool in_flash) { diff --git a/esphome/core/preferences.h b/esphome/core/preferences.h index d1ec924af7..bfea4c2336 100644 --- a/esphome/core/preferences.h +++ b/esphome/core/preferences.h @@ -2,10 +2,6 @@ #include -#ifdef ARDUINO_ARCH_ESP32 -#include -#endif - #include "esphome/core/esphal.h" #include "esphome/core/defines.h" @@ -56,7 +52,7 @@ static bool DEFAULT_IN_FLASH = true; class ESPPreferences { public: ESPPreferences(); - void begin(const std::string &name); + void begin(); ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash = DEFAULT_IN_FLASH); template ESPPreferenceObject make_preference(uint32_t type, bool in_flash = DEFAULT_IN_FLASH); @@ -77,7 +73,7 @@ class ESPPreferences { uint32_t current_offset_; #ifdef ARDUINO_ARCH_ESP32 - Preferences preferences_; + uint32_t nvs_handle_; #endif #ifdef ARDUINO_ARCH_ESP8266 void save_esp8266_flash_(); diff --git a/esphome/core_config.py b/esphome/core_config.py index 051de896b5..573094db5c 100644 --- a/esphome/core_config.py +++ b/esphome/core_config.py @@ -239,7 +239,6 @@ def to_code(config): # Libraries if CORE.is_esp32: - cg.add_library('Preferences', None) cg.add_library('ESPmDNS', None) elif CORE.is_esp8266: cg.add_library('ESP8266WiFi', None) From c6512013bbf9defcd28a8618beb0f20eb31c3fe5 Mon Sep 17 00:00:00 2001 From: Thomas Eckerstorfer Date: Wed, 3 Jul 2019 16:42:32 +0200 Subject: [PATCH 5/9] added tx20 wind speed sensor (#275) * added tx20 wind speed sensor * added test * fixed lint errors * fixed more lint errors * updated tx20 * updated tx20 sensor * updated to new structure and removed static variables * removed content from __init__.py * fixing lint errors * resolved issues from review Co-authored-by: Thomas Co-authored-by: Otto Winter --- esphome/components/tx20/__init__.py | 0 esphome/components/tx20/sensor.py | 38 ++++++ esphome/components/tx20/tx20.cpp | 195 ++++++++++++++++++++++++++++ esphome/components/tx20/tx20.h | 51 ++++++++ esphome/const.py | 5 + tests/test1.yaml | 8 ++ 6 files changed, 297 insertions(+) create mode 100644 esphome/components/tx20/__init__.py create mode 100644 esphome/components/tx20/sensor.py create mode 100644 esphome/components/tx20/tx20.cpp create mode 100644 esphome/components/tx20/tx20.h diff --git a/esphome/components/tx20/__init__.py b/esphome/components/tx20/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/esphome/components/tx20/sensor.py b/esphome/components/tx20/sensor.py new file mode 100644 index 0000000000..daa6677196 --- /dev/null +++ b/esphome/components/tx20/sensor.py @@ -0,0 +1,38 @@ +import esphome.codegen as cg +import esphome.config_validation as cv +from esphome import pins +from esphome.components import sensor +from esphome.const import CONF_ID, CONF_WIND_SPEED, CONF_PIN, \ + CONF_WIND_DIRECTION_DEGREES, UNIT_KILOMETER_PER_HOUR, \ + UNIT_EMPTY, ICON_WEATHER_WINDY, ICON_SIGN_DIRECTION + +tx20_ns = cg.esphome_ns.namespace('tx20') +Tx20Component = tx20_ns.class_('Tx20Component', cg.Component) + +CONFIG_SCHEMA = cv.Schema({ + cv.GenerateID(): cv.declare_id(Tx20Component), + cv.Optional(CONF_WIND_SPEED): + sensor.sensor_schema(UNIT_KILOMETER_PER_HOUR, ICON_WEATHER_WINDY, 1), + cv.Optional(CONF_WIND_DIRECTION_DEGREES): + sensor.sensor_schema(UNIT_EMPTY, ICON_SIGN_DIRECTION, 1), + cv.Required(CONF_PIN): cv.All(pins.internal_gpio_input_pin_schema, + pins.validate_has_interrupt), +}).extend(cv.COMPONENT_SCHEMA) + + +def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + yield cg.register_component(var, config) + + if CONF_WIND_SPEED in config: + conf = config[CONF_WIND_SPEED] + sens = yield sensor.new_sensor(conf) + cg.add(var.set_wind_speed_sensor(sens)) + + if CONF_WIND_DIRECTION_DEGREES in config: + conf = config[CONF_WIND_DIRECTION_DEGREES] + sens = yield sensor.new_sensor(conf) + cg.add(var.set_wind_direction_degrees_sensor(sens)) + + pin = yield cg.gpio_pin_expression(config[CONF_PIN]) + cg.add(var.set_pin(pin)) diff --git a/esphome/components/tx20/tx20.cpp b/esphome/components/tx20/tx20.cpp new file mode 100644 index 0000000000..f3dafda288 --- /dev/null +++ b/esphome/components/tx20/tx20.cpp @@ -0,0 +1,195 @@ +#include "tx20.h" +#include "esphome/core/log.h" +#include "esphome/core/helpers.h" + +namespace esphome { +namespace tx20 { + +static const char *TAG = "tx20"; +static const uint8_t MAX_BUFFER_SIZE = 41; +static const uint16_t TX20_MAX_TIME = MAX_BUFFER_SIZE * 1200 + 5000; +static const uint16_t TX20_BIT_TIME = 1200; +static const char *DIRECTIONS[] = {"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", + "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"}; + +void Tx20Component::setup() { + ESP_LOGCONFIG(TAG, "Setting up Tx20"); + this->pin_->setup(); + + this->store_.buffer = new uint16_t[MAX_BUFFER_SIZE]; + this->store_.pin = this->pin_->to_isr(); + this->store_.reset(); + + this->pin_->attach_interrupt(Tx20ComponentStore::gpio_intr, &this->store_, CHANGE); +} +void Tx20Component::dump_config() { + ESP_LOGCONFIG(TAG, "Tx20:"); + + LOG_SENSOR(" ", "Wind speed:", this->wind_speed_sensor_); + LOG_SENSOR(" ", "Wind direction degrees:", this->wind_direction_degrees_sensor_); + + LOG_PIN(" Pin: ", this->pin_); +} +void Tx20Component::loop() { + if (this->store_.tx20_available) { + this->decode_and_publish_(); + this->store_.reset(); + } +} + +float Tx20Component::get_setup_priority() const { return setup_priority::DATA; } + +std::string Tx20Component::get_wind_cardinal_direction() const { return this->wind_cardinal_direction_; } + +void Tx20Component::decode_and_publish_() { + ESP_LOGVV(TAG, "Decode Tx20..."); + + std::string string_buffer; + std::string string_buffer_2; + std::vector bit_buffer; + bool current_bit = true; + + for (int i = 1; i <= this->store_.buffer_index; i++) { + string_buffer_2 += to_string(this->store_.buffer[i]) + ", "; + uint8_t repeat = this->store_.buffer[i] / TX20_BIT_TIME; + // ignore segments at the end that were too short + string_buffer.append(repeat, current_bit ? '1' : '0'); + bit_buffer.insert(bit_buffer.end(), repeat, current_bit); + current_bit = !current_bit; + } + current_bit = !current_bit; + if (string_buffer.length() < MAX_BUFFER_SIZE) { + uint8_t remain = MAX_BUFFER_SIZE - string_buffer.length(); + string_buffer_2 += to_string(remain) + ", "; + string_buffer.append(remain, current_bit ? '1' : '0'); + bit_buffer.insert(bit_buffer.end(), remain, current_bit); + } + + uint8_t tx20_sa = 0; + uint8_t tx20_sb = 0; + uint8_t tx20_sd = 0; + uint8_t tx20_se = 0; + uint16_t tx20_sc = 0; + uint16_t tx20_sf = 0; + uint8_t tx20_wind_direction = 0; + float tx20_wind_speed_kmh = 0; + uint8_t bit_count = 0; + + for (int i = 41; i > 0; i--) { + uint8_t bit = bit_buffer.at(bit_count); + bit_count++; + if (i > 41 - 5) { + // start, inverted + tx20_sa = (tx20_sa << 1) | (bit ^ 1); + } else if (i > 41 - 5 - 4) { + // wind dir, inverted + tx20_sb = tx20_sb >> 1 | ((bit ^ 1) << 3); + } else if (i > 41 - 5 - 4 - 12) { + // windspeed, inverted + tx20_sc = tx20_sc >> 1 | ((bit ^ 1) << 11); + } else if (i > 41 - 5 - 4 - 12 - 4) { + // checksum, inverted + tx20_sd = tx20_sd >> 1 | ((bit ^ 1) << 3); + } else if (i > 41 - 5 - 4 - 12 - 4 - 4) { + // wind dir + tx20_se = tx20_se >> 1 | (bit << 3); + } else { + // windspeed + tx20_sf = tx20_sf >> 1 | (bit << 11); + } + } + + uint8_t chk = (tx20_sb + (tx20_sc & 0xf) + ((tx20_sc >> 4) & 0xf) + ((tx20_sc >> 8) & 0xf)); + chk &= 0xf; + bool value_set = false; + // checks: + // 1. Check that the start frame is 00100 (0x04) + // 2. Check received checksum matches calculated checksum + // 3. Check that Wind Direction matches Wind Direction (Inverted) + // 4. Check that Wind Speed matches Wind Speed (Inverted) + ESP_LOGVV(TAG, "BUFFER %s", string_buffer_2.c_str()); + ESP_LOGVV(TAG, "Decoded bits %s", string_buffer.c_str()); + + if (tx20_sa == 4) { + if (chk == tx20_sd) { + if (tx20_sf == tx20_sc) { + tx20_wind_speed_kmh = float(tx20_sc) * 0.36; + ESP_LOGV(TAG, "WindSpeed %f", tx20_wind_speed_kmh); + if (this->wind_speed_sensor_ != nullptr) + this->wind_speed_sensor_->publish_state(tx20_wind_speed_kmh); + value_set = true; + } + if (tx20_se == tx20_sb) { + tx20_wind_direction = tx20_se; + if (tx20_wind_direction >= 0 && tx20_wind_direction < 16) { + wind_cardinal_direction_ = DIRECTIONS[tx20_wind_direction]; + } + ESP_LOGV(TAG, "WindDirection %d", tx20_wind_direction); + if (this->wind_direction_degrees_sensor_ != nullptr) + this->wind_direction_degrees_sensor_->publish_state(float(tx20_wind_direction) * 22.5f); + value_set = true; + } + if (!value_set) { + ESP_LOGW(TAG, "No value set!"); + } + } else { + ESP_LOGW(TAG, "Checksum wrong!"); + } + } else { + ESP_LOGW(TAG, "Start wrong!"); + } +} + +void ICACHE_RAM_ATTR Tx20ComponentStore::gpio_intr(Tx20ComponentStore *arg) { + arg->pin_state = arg->pin->digital_read(); + const uint32_t now = micros(); + if (!arg->start_time) { + // only detect a start if the bit is high + if (!arg->pin_state) { + return; + } + arg->buffer[arg->buffer_index] = 1; + arg->start_time = now; + arg->buffer_index++; + return; + } + const uint32_t delay = now - arg->start_time; + const uint8_t index = arg->buffer_index; + + // first delay has to be ~2400 + if (index == 1 && (delay > 3000 || delay < 2400)) { + arg->reset(); + return; + } + // second delay has to be ~1200 + if (index == 2 && (delay > 1500 || delay < 1200)) { + arg->reset(); + return; + } + // third delay has to be ~2400 + if (index == 3 && (delay > 3000 || delay < 2400)) { + arg->reset(); + return; + } + + if (arg->tx20_available || ((arg->spent_time + delay > TX20_MAX_TIME) && arg->start_time)) { + arg->tx20_available = true; + return; + } + if (index <= MAX_BUFFER_SIZE) { + arg->buffer[index] = delay; + } + arg->spent_time += delay; + arg->start_time = now; + arg->buffer_index++; +} +void ICACHE_RAM_ATTR Tx20ComponentStore::reset() { + tx20_available = false; + buffer_index = 0; + spent_time = 0; + // rearm it! + start_time = 0; +} + +} // namespace tx20 +} // namespace esphome diff --git a/esphome/components/tx20/tx20.h b/esphome/components/tx20/tx20.h new file mode 100644 index 0000000000..8b79deffbc --- /dev/null +++ b/esphome/components/tx20/tx20.h @@ -0,0 +1,51 @@ +#pragma once + +#include "esphome/core/component.h" +#include "esphome/components/sensor/sensor.h" + +namespace esphome { +namespace tx20 { + +/// Store data in a class that doesn't use multiple-inheritance (vtables in flash) +struct Tx20ComponentStore { + volatile uint16_t *buffer; + volatile uint32_t start_time; + volatile uint8_t buffer_index; + volatile uint32_t spent_time; + volatile bool tx20_available; + volatile bool pin_state; + ISRInternalGPIOPin *pin; + + void reset(); + static void gpio_intr(Tx20ComponentStore *arg); +}; + +/// This class implements support for the Tx20 Wind sensor. +class Tx20Component : public Component { + public: + /// Get the textual representation of the wind direction ('N', 'SSE', ..). + std::string get_wind_cardinal_direction() const; + + void set_pin(GPIOPin *pin) { pin_ = pin; } + void set_wind_speed_sensor(sensor::Sensor *wind_speed_sensor) { wind_speed_sensor_ = wind_speed_sensor; } + void set_wind_direction_degrees_sensor(sensor::Sensor *wind_direction_degrees_sensor) { + wind_direction_degrees_sensor_ = wind_direction_degrees_sensor; + } + + void setup() override; + void dump_config() override; + float get_setup_priority() const override; + void loop() override; + + protected: + void decode_and_publish_(); + + std::string wind_cardinal_direction_; + GPIOPin *pin_; + sensor::Sensor *wind_speed_sensor_; + sensor::Sensor *wind_direction_degrees_sensor_; + Tx20ComponentStore store_; +}; + +} // namespace tx20 +} // namespace esphome diff --git a/esphome/const.py b/esphome/const.py index 27c4b68799..3811d5b9cf 100644 --- a/esphome/const.py +++ b/esphome/const.py @@ -454,6 +454,8 @@ CONF_WHITE = 'white' CONF_WIDTH = 'width' CONF_WIFI = 'wifi' CONF_WILL_MESSAGE = 'will_message' +CONF_WIND_SPEED = 'wind_speed' +CONF_WIND_DIRECTION_DEGREES = 'wind_direction_degrees' CONF_WINDOW_SIZE = 'window_size' CONF_ZERO = 'zero' @@ -481,12 +483,14 @@ ICON_ROTATE_RIGHT = 'mdi:rotate-right' ICON_SCALE = 'mdi:scale' ICON_SCREEN_ROTATION = 'mdi:screen-rotation' ICON_SIGNAL = 'mdi:signal' +ICON_SIGN_DIRECTION = 'mdi:sign-direction' ICON_WEATHER_SUNSET = 'mdi:weather-sunset' ICON_WEATHER_SUNSET_DOWN = 'mdi:weather-sunset-down' ICON_WEATHER_SUNSET_UP = 'mdi:weather-sunset-up' ICON_THERMOMETER = 'mdi:thermometer' ICON_TIMER = 'mdi:timer' ICON_WATER_PERCENT = 'mdi:water-percent' +ICON_WEATHER_WINDY = 'mdi:weather-windy' ICON_WIFI = 'mdi:wifi' UNIT_AMPERE = 'A' @@ -498,6 +502,7 @@ UNIT_EMPTY = '' UNIT_HZ = 'hz' UNIT_HECTOPASCAL = 'hPa' UNIT_KELVIN = 'K' +UNIT_KILOMETER_PER_HOUR = 'km/h' UNIT_LUX = 'lx' UNIT_METER = 'm' UNIT_METER_PER_SECOND_SQUARED = u'm/s²' diff --git a/tests/test1.yaml b/tests/test1.yaml index 4fa2f85cf6..8fdcdd57ea 100644 --- a/tests/test1.yaml +++ b/tests/test1.yaml @@ -564,6 +564,14 @@ sensor: name: CCS811 TVOC update_interval: 30s baseline: 0x4242 + - platform: tx20 + wind_speed: + name: "Windspeed" + wind_direction_degrees: + name: "Winddirection Degrees" + pin: + number: GPIO04 + mode: INPUT - platform: zyaura clock_pin: GPIO5 data_pin: GPIO4 From 85195436c18d774805bb4436d92031709c5c6705 Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 17:13:40 +0200 Subject: [PATCH 6/9] Work around pytz tzname bug Fixes https://github.com/esphome/issues/issues/445 --- esphome/components/time/__init__.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/esphome/components/time/__init__.py b/esphome/components/time/__init__.py index 634de26f00..2097be3a26 100644 --- a/esphome/components/time/__init__.py +++ b/esphome/components/time/__init__.py @@ -2,6 +2,7 @@ import bisect import datetime import logging import math +import string import pytz import tzlocal @@ -52,8 +53,18 @@ def _tz_dst_str(dt): _tz_timedelta(td)) -def _non_dst_tz(tz, dt): +def _safe_tzname(tz, dt): tzname = tz.tzname(dt) + # pytz does not always return valid tznames + # For example: 'Europe/Saratov' returns '+04' + # Work around it by using a generic name for the timezone + if not all(c in string.ascii_letters for c in tzname): + return 'TZ' + return tzname + + +def _non_dst_tz(tz, dt): + tzname = _safe_tzname(tz, dt) utcoffset = tz.utcoffset(dt) _LOGGER.info("Detected timezone '%s' with UTC offset %s", tzname, _tz_timedelta(utcoffset)) From 6516a6ff7eb4b8e7ff8f1bf947ff5ac052d5aa9a Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 17:16:46 +0200 Subject: [PATCH 7/9] Fix LG nbits --- esphome/components/remote_base/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esphome/components/remote_base/__init__.py b/esphome/components/remote_base/__init__.py index 31d58c1cc0..f54fd1df9b 100644 --- a/esphome/components/remote_base/__init__.py +++ b/esphome/components/remote_base/__init__.py @@ -250,7 +250,7 @@ def lg_dumper(var, config): def lg_action(var, config, args): template_ = yield cg.templatable(config[CONF_DATA], args, cg.uint32) cg.add(var.set_data(template_)) - template_ = yield cg.templatable(config[CONF_DATA], args, cg.uint8) + template_ = yield cg.templatable(config[CONF_NBITS], args, cg.uint8) cg.add(var.set_nbits(template_)) From 1876c21e3e9a2c9c6c9121dc072ac71034eeaefc Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 20:42:46 +0200 Subject: [PATCH 8/9] WiFi networks priority (#658) * WiFi networks priority Fixes https://github.com/esphome/feature-requests/issues/136 * Print priority --- esphome/components/wifi/__init__.py | 5 ++- esphome/components/wifi/wifi_component.cpp | 20 ++++++++++++ esphome/components/wifi/wifi_component.h | 36 ++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index 545f6a7de7..4f9764f320 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -5,7 +5,7 @@ from esphome.automation import Condition from esphome.const import CONF_AP, CONF_BSSID, CONF_CHANNEL, CONF_DNS1, CONF_DNS2, CONF_DOMAIN, \ CONF_FAST_CONNECT, CONF_GATEWAY, CONF_HIDDEN, CONF_ID, CONF_MANUAL_IP, CONF_NETWORKS, \ CONF_PASSWORD, CONF_POWER_SAVE_MODE, CONF_REBOOT_TIMEOUT, CONF_SSID, CONF_STATIC_IP, \ - CONF_SUBNET, CONF_USE_ADDRESS + CONF_SUBNET, CONF_USE_ADDRESS, CONF_PRIORITY from esphome.core import CORE, HexInt, coroutine_with_priority AUTO_LOAD = ['network'] @@ -72,6 +72,7 @@ WIFI_NETWORK_AP = WIFI_NETWORK_BASE.extend({ WIFI_NETWORK_STA = WIFI_NETWORK_BASE.extend({ cv.Optional(CONF_BSSID): cv.mac_address, cv.Optional(CONF_HIDDEN): cv.boolean, + cv.Optional(CONF_PRIORITY, default=0.0): cv.float_, }) @@ -161,6 +162,8 @@ def wifi_network(config, static_ip): cg.add(ap.set_channel(config[CONF_CHANNEL])) if static_ip is not None: cg.add(ap.set_manual_ip(manual_ip(static_ip))) + if CONF_PRIORITY in config: + cg.add(ap.set_priority(config[CONF_PRIORITY])) return ap diff --git a/esphome/components/wifi/wifi_component.cpp b/esphome/components/wifi/wifi_component.cpp index 7af6176402..1f705e507f 100644 --- a/esphome/components/wifi/wifi_component.cpp +++ b/esphome/components/wifi/wifi_component.cpp @@ -273,6 +273,9 @@ void WiFiComponent::print_connect_params_() { int8_t rssi = WiFi.RSSI(); print_signal_bars(rssi, signal_bars); ESP_LOGCONFIG(TAG, " Signal strength: %d dB %s", rssi, signal_bars); + if (this->selected_ap_.get_bssid().has_value()) { + ESP_LOGV(TAG, " Priority: %.1f", this->get_sta_priority(*this->selected_ap_.get_bssid())); + } ESP_LOGCONFIG(TAG, " Channel: %d", WiFi.channel()); ESP_LOGCONFIG(TAG, " Subnet: %s", WiFi.subnetMask().toString().c_str()); ESP_LOGCONFIG(TAG, " Gateway: %s", WiFi.gatewayIP().toString().c_str()); @@ -308,6 +311,10 @@ void WiFiComponent::check_scanning_finished() { for (auto &ap : this->sta_) { if (res.matches(ap)) { res.set_matches(true); + if (!this->has_sta_priority(res.get_bssid())) { + this->set_sta_priority(res.get_bssid(), ap.get_priority()); + } + res.set_priority(this->get_sta_priority(res.get_bssid())); break; } } @@ -315,11 +322,18 @@ void WiFiComponent::check_scanning_finished() { std::stable_sort(this->scan_result_.begin(), this->scan_result_.end(), [](const WiFiScanResult &a, const WiFiScanResult &b) { + // return true if a is better than b if (a.get_matches() && !b.get_matches()) return true; if (!a.get_matches() && b.get_matches()) return false; + if (a.get_matches() && b.get_matches()) { + // if both match, check priority + if (a.get_priority() != b.get_priority()) + return a.get_priority() > b.get_priority(); + } + return a.get_rssi() > b.get_rssi(); }); @@ -443,6 +457,12 @@ void WiFiComponent::check_connecting_finished() { } void WiFiComponent::retry_connect() { + if (this->selected_ap_.get_bssid()) { + auto bssid = *this->selected_ap_.get_bssid(); + float priority = this->get_sta_priority(bssid); + this->set_sta_priority(bssid, priority - 1.0f); + } + delay(10); if (!this->is_captive_portal_active_() && (this->num_retried_ > 5 || this->error_from_callback_)) { // If retry failed for more than 5 times, let's restart STA diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index cbdde7245f..04866ef8e2 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -66,12 +66,14 @@ class WiFiAP { void set_bssid(optional bssid); void set_password(const std::string &password); void set_channel(optional channel); + void set_priority(float priority) { priority_ = priority; } void set_manual_ip(optional manual_ip); void set_hidden(bool hidden); const std::string &get_ssid() const; const optional &get_bssid() const; const std::string &get_password() const; const optional &get_channel() const; + float get_priority() const { return priority_; } const optional &get_manual_ip() const; bool get_hidden() const; @@ -80,6 +82,7 @@ class WiFiAP { optional bssid_; std::string password_; optional channel_; + float priority_{0}; optional manual_ip_; bool hidden_{false}; }; @@ -99,6 +102,8 @@ class WiFiScanResult { int8_t get_rssi() const; bool get_with_auth() const; bool get_is_hidden() const; + float get_priority() const { return priority_; } + void set_priority(float priority) { priority_ = priority; } protected: bool matches_{false}; @@ -108,6 +113,12 @@ class WiFiScanResult { int8_t rssi_; bool with_auth_; bool is_hidden_; + float priority_{0.0f}; +}; + +struct WiFiSTAPriority { + bssid_t bssid; + float priority; }; enum WiFiPowerSaveMode { @@ -175,6 +186,30 @@ class WiFiComponent : public Component { IPAddress wifi_soft_ap_ip(); + bool has_sta_priority(const bssid_t &bssid) { + for (auto &it : this->sta_priorities_) + if (it.bssid == bssid) + return true; + return false; + } + float get_sta_priority(const bssid_t bssid) { + for (auto &it : this->sta_priorities_) + if (it.bssid == bssid) + return it.priority; + return 0.0f; + } + void set_sta_priority(const bssid_t bssid, float priority) { + for (auto &it : this->sta_priorities_) + if (it.bssid == bssid) { + it.priority = priority; + return; + } + this->sta_priorities_.push_back(WiFiSTAPriority{ + .bssid = bssid, + .priority = priority, + }); + } + protected: static std::string format_mac_addr(const uint8_t mac[6]); void setup_ap_config_(); @@ -209,6 +244,7 @@ class WiFiComponent : public Component { std::string use_address_; std::vector sta_; + std::vector sta_priorities_; WiFiAP selected_ap_; bool fast_connect_{false}; From 7210ad7ed9b1a00c69a5e19231e10923df508418 Mon Sep 17 00:00:00 2001 From: Otto Winter Date: Wed, 3 Jul 2019 20:42:55 +0200 Subject: [PATCH 9/9] Change ESP32 default power_save_mode to light (#661) --- esphome/components/wifi/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index 4f9764f320..93f2d59564 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -121,7 +121,8 @@ CONFIG_SCHEMA = cv.All(cv.Schema({ cv.Optional(CONF_AP): WIFI_NETWORK_AP, cv.Optional(CONF_DOMAIN, default='.local'): cv.domain_name, cv.Optional(CONF_REBOOT_TIMEOUT, default='15min'): cv.positive_time_period_milliseconds, - cv.Optional(CONF_POWER_SAVE_MODE, default='NONE'): cv.enum(WIFI_POWER_SAVE_MODES, upper=True), + cv.SplitDefault(CONF_POWER_SAVE_MODE, esp8266='none', esp32='light'): + cv.enum(WIFI_POWER_SAVE_MODES, upper=True), cv.Optional(CONF_FAST_CONNECT, default=False): cv.boolean, cv.Optional(CONF_USE_ADDRESS): cv.string_strict,