1
0
mirror of https://github.com/esphome/esphome.git synced 2025-03-13 22:28:14 +00:00

Merge pull request #21 from esphome/dev

update from dev
This commit is contained in:
Michiel van Turnhout 2019-08-12 21:09:21 +02:00 committed by GitHub
commit 70da91f378
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 686 additions and 29 deletions

View File

@ -5,10 +5,6 @@ install: script/setup
cache:
directories:
- "~/.platformio"
- "$TRAVIS_BUILD_DIR/.piolibdeps"
- "$TRAVIS_BUILD_DIR/tests/build/test1/.piolibdeps"
- "$TRAVIS_BUILD_DIR/tests/build/test2/.piolibdeps"
- "$TRAVIS_BUILD_DIR/tests/build/test3/.piolibdeps"
matrix:
fast_finish: true

View File

@ -318,6 +318,7 @@ bool APIConnection::send_light_info(light::LightState *light) {
msg.max_mireds = traits.get_max_mireds();
}
if (light->supports_effects()) {
msg.effects.emplace_back("None");
for (auto *effect : light->get_effects())
msg.effects.push_back(effect->get_name());
}

View File

@ -122,6 +122,7 @@ template<typename... Ts> class AddressableSet : public Action<Ts...> {
range.set_blue(this->blue_.value(x...));
if (this->white_.has_value())
range.set_white(this->white_.value(x...));
out->schedule_show();
}
protected:

View File

@ -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_))

View File

@ -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))

View File

View File

@ -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))

View File

@ -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<bool> 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

View File

@ -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

View File

@ -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_,
})
@ -120,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,
@ -161,6 +163,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

View File

@ -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

View File

@ -66,12 +66,14 @@ class WiFiAP {
void set_bssid(optional<bssid_t> bssid);
void set_password(const std::string &password);
void set_channel(optional<uint8_t> channel);
void set_priority(float priority) { priority_ = priority; }
void set_manual_ip(optional<ManualIP> manual_ip);
void set_hidden(bool hidden);
const std::string &get_ssid() const;
const optional<bssid_t> &get_bssid() const;
const std::string &get_password() const;
const optional<uint8_t> &get_channel() const;
float get_priority() const { return priority_; }
const optional<ManualIP> &get_manual_ip() const;
bool get_hidden() const;
@ -80,6 +82,7 @@ class WiFiAP {
optional<bssid_t> bssid_;
std::string password_;
optional<uint8_t> channel_;
float priority_{0};
optional<ManualIP> 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<WiFiAP> sta_;
std::vector<WiFiSTAPriority> sta_priorities_;
WiFiAP selected_ap_;
bool fast_connect_{false};

View File

View File

@ -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))

View File

@ -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

View File

@ -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

View File

@ -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',
]

View File

@ -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²'

View File

@ -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
@ -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_; }

View File

@ -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) {

View File

@ -2,10 +2,6 @@
#include <string>
#ifdef ARDUINO_ARCH_ESP32
#include <Preferences.h>
#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<typename T> 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_();

View File

@ -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)

View File

@ -564,6 +564,23 @@ 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
co2:
name: "ZyAura CO2"
temperature:
name: "ZyAura Temperature"
humidity:
name: "ZyAura Humidity"
esp32_touch: