1
0
mirror of https://github.com/esphome/esphome.git synced 2025-11-02 08:01:50 +00:00

Compare commits

...

21 Commits

Author SHA1 Message Date
Jesse Hills
d238e06f86 Merge pull request #1509 from esphome/bump-1.16.0
1.16.0
2021-02-04 02:56:32 +13:00
Jesse Hills
2fc59ecc30 Bump version to v1.16.0 2021-02-03 21:19:42 +13:00
Jesse Hills
0047d24698 Merge pull request #1507 from esphome/bump-1.16.0b8
1.16.0b8
2021-02-03 13:17:40 +13:00
Jesse Hills
89a89e1785 Bump version to v1.16.0b8 2021-02-03 12:33:30 +13:00
Guillermo Ruffino
1952d275f7 RC522 increased retry loop count (#1506) 2021-02-03 12:33:29 +13:00
hcoohb
043095b605 fix esp8266 remote_transmitter using incorrect timings (#1465)
* replace delay by delayMicroseconds in delay_microseconds_accurate

* Use delay(0) to let wifi and os function run

* Linting

* Remove unneeded delayMicroseconds, keep it for low usec

* Avoid micros() overflow issue
2021-02-03 12:33:29 +13:00
Jesse Hills
431d3578a5 Merge pull request #1504 from esphome/bump-1.16.0b7
1.16.0b7
2021-02-01 18:42:33 +13:00
Jesse Hills
5f02d86841 Bump version to v1.16.0b7 2021-02-01 15:34:45 +13:00
Jesse Hills
a7ec57d4be Allow SCD30 sensors to be optional (#1502) 2021-02-01 15:34:44 +13:00
Jesse Hills
1ea5cc497f Merge pull request #1497 from esphome/bump-1.16.0b6
1.16.0b6
2021-01-27 23:19:17 +13:00
Jesse Hills
b601cf6bc6 Bump version to v1.16.0b6 2021-01-27 23:04:20 +13:00
nikito7
5057caa7fc Add support for MHO-C401 (#1486)
Committer: nikito7

Co-authored-by: vevsvevs <v-v@mail.ru>
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: nikito7 <root@vbox.lan>
2021-01-27 23:04:20 +13:00
Klarstein
95bef53d37 Add docker healthcheck (#1492) 2021-01-27 23:04:20 +13:00
Paul Nicholls
ea019a057b Add support for string-type Tuya datapoints (#1488) 2021-01-27 23:04:20 +13:00
Jesse Hills
b860a317b9 Merge pull request #1495 from esphome/bump-1.16.0b5
1.16.0b5
2021-01-26 14:45:53 +13:00
Jesse Hills
9591c903f7 Bump version to v1.16.0b5 2021-01-26 13:39:43 +13:00
SenexCrenshaw
65fbb8bc60 SPI wasnt being disabled after display update (#1493) 2021-01-26 13:39:42 +13:00
Philipp Tölke
97428f2ba2 Make fade_to*, lighten, and darken const (#1450) 2021-01-26 13:39:42 +13:00
Zixuan Wang
9ab6a7b7ff Improve ccs811 precision (#1428) 2021-01-26 13:39:42 +13:00
Florian Mösch
e2ad6fe3d8 rename read/write to read/time/write_time (#1468) 2021-01-26 13:39:42 +13:00
Florian Mösch
6781d08c9b time sync notification (#1442)
* add on_time_sync trigger

* cleanup lint

* fix review remark (sntp didn't trigger callbacks)
2021-01-26 13:39:42 +13:00
27 changed files with 260 additions and 39 deletions

View File

@@ -100,3 +100,4 @@ esphome/components/version/* @esphome/core
esphome/components/web_server_base/* @OttoWinter esphome/components/web_server_base/* @OttoWinter
esphome/components/whirlpool/* @glmnet esphome/components/whirlpool/* @glmnet
esphome/components/xiaomi_lywsd03mmc/* @ahpohl esphome/components/xiaomi_lywsd03mmc/* @ahpohl
esphome/components/xiaomi_mhoc401/* @vevsvevs

View File

@@ -15,6 +15,10 @@ ENV USERNAME="" PASSWORD=""
# Expose the dashboard to Docker # Expose the dashboard to Docker
EXPOSE 6052 EXPOSE 6052
# Run healthcheck (heartbeat)
HEALTHCHECK --interval=5m --timeout=3s \
CMD curl --fail http://localhost:6052 || exit 1
# The directory the user should mount their configuration files to # The directory the user should mount their configuration files to
WORKDIR /config WORKDIR /config
# Set entrypoint to esphome so that the user doesn't have to type 'esphome' # Set entrypoint to esphome so that the user doesn't have to type 'esphome'

View File

@@ -102,10 +102,14 @@ void CCS811Component::send_env_data_() {
// temperature has a 25° offset to allow negative temperatures // temperature has a 25° offset to allow negative temperatures
temperature += 25; temperature += 25;
// only 0.5 fractions are supported (application note) // At page 18 of:
auto hum_value = static_cast<uint8_t>(roundf(humidity * 2)); // https://cdn.sparkfun.com/datasheets/BreakoutBoards/CCS811_Programming_Guide.pdf
auto temp_value = static_cast<uint8_t>(roundf(temperature * 2)); // Reference code:
this->write_bytes(0x05, {hum_value, 0x00, temp_value, 0x00}); // https://github.com/adafruit/Adafruit_CCS811/blob/0990f5c620354d8bc087c4706bec091d8e6e5dfd/Adafruit_CCS811.cpp#L135-L142
uint16_t hum_conv = static_cast<uint16_t>(lroundf(humidity * 512.0f + 0.5f));
uint16_t temp_conv = static_cast<uint16_t>(lroundf(temperature * 512.0f + 0.5f));
this->write_bytes(0x05, {(uint8_t)((hum_conv >> 8) & 0xff), (uint8_t)((hum_conv & 0xff)),
(uint8_t)((temp_conv >> 8) & 0xff), (uint8_t)((temp_conv & 0xff))});
} }
void CCS811Component::dump_config() { void CCS811Component::dump_config() {
ESP_LOGCONFIG(TAG, "CCS811"); ESP_LOGCONFIG(TAG, "CCS811");

View File

@@ -16,7 +16,7 @@ void DS1307Component::setup() {
} }
} }
void DS1307Component::update() { this->read(); } void DS1307Component::update() { this->read_time(); }
void DS1307Component::dump_config() { void DS1307Component::dump_config() {
ESP_LOGCONFIG(TAG, "DS1307:"); ESP_LOGCONFIG(TAG, "DS1307:");
@@ -29,7 +29,7 @@ void DS1307Component::dump_config() {
float DS1307Component::get_setup_priority() const { return setup_priority::DATA; } float DS1307Component::get_setup_priority() const { return setup_priority::DATA; }
void DS1307Component::read() { void DS1307Component::read_time() {
if (!this->read_rtc_()) { if (!this->read_rtc_()) {
return; return;
} }
@@ -53,7 +53,7 @@ void DS1307Component::read() {
time::RealTimeClock::synchronize_epoch_(rtc_time.timestamp); time::RealTimeClock::synchronize_epoch_(rtc_time.timestamp);
} }
void DS1307Component::write() { void DS1307Component::write_time() {
auto now = time::RealTimeClock::utcnow(); auto now = time::RealTimeClock::utcnow();
if (!now.is_valid()) { if (!now.is_valid()) {
ESP_LOGE(TAG, "Invalid system time, not syncing to RTC."); ESP_LOGE(TAG, "Invalid system time, not syncing to RTC.");

View File

@@ -13,8 +13,8 @@ class DS1307Component : public time::RealTimeClock, public i2c::I2CDevice {
void update() override; void update() override;
void dump_config() override; void dump_config() override;
float get_setup_priority() const override; float get_setup_priority() const override;
void read(); void read_time();
void write(); void write_time();
protected: protected:
bool read_rtc_(); bool read_rtc_();
@@ -59,12 +59,12 @@ class DS1307Component : public time::RealTimeClock, public i2c::I2CDevice {
template<typename... Ts> class WriteAction : public Action<Ts...>, public Parented<DS1307Component> { template<typename... Ts> class WriteAction : public Action<Ts...>, public Parented<DS1307Component> {
public: public:
void play(Ts... x) override { this->parent_->write(); } void play(Ts... x) override { this->parent_->write_time(); }
}; };
template<typename... Ts> class ReadAction : public Action<Ts...>, public Parented<DS1307Component> { template<typename... Ts> class ReadAction : public Action<Ts...>, public Parented<DS1307Component> {
public: public:
void play(Ts... x) override { this->parent_->read(); } void play(Ts... x) override { this->parent_->read_time(); }
}; };
} // namespace ds1307 } // namespace ds1307
} // namespace esphome } // namespace esphome

View File

@@ -18,19 +18,19 @@ CONFIG_SCHEMA = time.TIME_SCHEMA.extend({
}).extend(i2c.i2c_device_schema(0x68)) }).extend(i2c.i2c_device_schema(0x68))
@automation.register_action('ds1307.write', WriteAction, cv.Schema({ @automation.register_action('ds1307.write_time', WriteAction, cv.Schema({
cv.GenerateID(): cv.use_id(DS1307Component), cv.GenerateID(): cv.use_id(DS1307Component),
})) }))
def ds1307_write_to_code(config, action_id, template_arg, args): def ds1307_write_time_to_code(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg) var = cg.new_Pvariable(action_id, template_arg)
yield cg.register_parented(var, config[CONF_ID]) yield cg.register_parented(var, config[CONF_ID])
yield var yield var
@automation.register_action('ds1307.read', ReadAction, automation.maybe_simple_id({ @automation.register_action('ds1307.read_time', ReadAction, automation.maybe_simple_id({
cv.GenerateID(): cv.use_id(DS1307Component), cv.GenerateID(): cv.use_id(DS1307Component),
})) }))
def ds1307_read_to_code(config, action_id, template_arg, args): def ds1307_read_time_to_code(config, action_id, template_arg, args):
var = cg.new_Pvariable(action_id, template_arg) var = cg.new_Pvariable(action_id, template_arg)
yield cg.register_parented(var, config[CONF_ID]) yield cg.register_parented(var, config[CONF_ID])
yield var yield var

View File

@@ -149,10 +149,10 @@ struct ESPColor {
return ESPColor(uint8_t((uint16_t(r) * 255U / max_rgb)), uint8_t((uint16_t(g) * 255U / max_rgb)), return ESPColor(uint8_t((uint16_t(r) * 255U / max_rgb)), uint8_t((uint16_t(g) * 255U / max_rgb)),
uint8_t((uint16_t(b) * 255U / max_rgb)), w); uint8_t((uint16_t(b) * 255U / max_rgb)), w);
} }
ESPColor fade_to_white(uint8_t amnt) { return ESPColor(255, 255, 255, 255) - (*this * amnt); } ESPColor fade_to_white(uint8_t amnt) const { return ESPColor(255, 255, 255, 255) - (*this * amnt); }
ESPColor fade_to_black(uint8_t amnt) { return *this * amnt; } ESPColor fade_to_black(uint8_t amnt) const { return *this * amnt; }
ESPColor lighten(uint8_t delta) { return *this + delta; } ESPColor lighten(uint8_t delta) const { return *this + delta; }
ESPColor darken(uint8_t delta) { return *this - delta; } ESPColor darken(uint8_t delta) const { return *this - delta; }
static const ESPColor BLACK; static const ESPColor BLACK;
static const ESPColor WHITE; static const ESPColor WHITE;

View File

@@ -349,7 +349,7 @@ RC522::StatusCode RC522::pcd_communicate_with_picc_(
// transmitting. Each iteration of the do-while-loop takes 17.86μs. // transmitting. Each iteration of the do-while-loop takes 17.86μs.
// TODO check/modify for other architectures than Arduino Uno 16bit // TODO check/modify for other architectures than Arduino Uno 16bit
uint16_t i; uint16_t i;
for (i = 4; i > 0; i--) { for (i = 2000; i > 0; i--) {
uint8_t n = pcd_read_register( uint8_t n = pcd_read_register(
COM_IRQ_REG); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq COM_IRQ_REG); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
if (n & wait_i_rq) { // One of the interrupts that signal success has been set. if (n & wait_i_rq) { // One of the interrupts that signal success has been set.

View File

@@ -23,10 +23,10 @@ def remove_altitude_suffix(value):
CONFIG_SCHEMA = cv.Schema({ CONFIG_SCHEMA = cv.Schema({
cv.GenerateID(): cv.declare_id(SCD30Component), cv.GenerateID(): cv.declare_id(SCD30Component),
cv.Required(CONF_CO2): sensor.sensor_schema(UNIT_PARTS_PER_MILLION, cv.Optional(CONF_CO2): sensor.sensor_schema(UNIT_PARTS_PER_MILLION,
ICON_MOLECULE_CO2, 0), ICON_MOLECULE_CO2, 0),
cv.Required(CONF_TEMPERATURE): sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 1), cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 1),
cv.Required(CONF_HUMIDITY): sensor.sensor_schema(UNIT_PERCENT, ICON_WATER_PERCENT, 1), cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(UNIT_PERCENT, ICON_WATER_PERCENT, 1),
cv.Optional(CONF_AUTOMATIC_SELF_CALIBRATION, default=True): cv.boolean, cv.Optional(CONF_AUTOMATIC_SELF_CALIBRATION, default=True): cv.boolean,
cv.Optional(CONF_ALTITUDE_COMPENSATION): cv.All(remove_altitude_suffix, cv.Optional(CONF_ALTITUDE_COMPENSATION): cv.All(remove_altitude_suffix,
cv.int_range(min=0, max=0xFFFF, cv.int_range(min=0, max=0xFFFF,

View File

@@ -54,6 +54,7 @@ void SNTPComponent::loop() {
char buf[128]; char buf[128];
time.strftime(buf, sizeof(buf), "%c"); time.strftime(buf, sizeof(buf), "%c");
ESP_LOGD(TAG, "Synchronized time: %s", buf); ESP_LOGD(TAG, "Synchronized time: %s", buf);
this->time_sync_callback_.call();
this->has_time_ = true; this->has_time_ = true;
} }

View File

@@ -454,6 +454,7 @@ void HOT ST7735::write_display_data_() {
} else { } else {
this->write_array(this->buffer_, this->get_buffer_length()); this->write_array(this->buffer_, this->get_buffer_length());
} }
this->disable();
} }
void ST7735::spi_master_write_addr_(uint16_t addr1, uint16_t addr2) { void ST7735::spi_master_write_addr_(uint16_t addr1, uint16_t addr2) {

View File

@@ -11,8 +11,8 @@ import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome import automation from esphome import automation
from esphome.const import CONF_ID, CONF_CRON, CONF_DAYS_OF_MONTH, CONF_DAYS_OF_WEEK, CONF_HOURS, \ from esphome.const import CONF_ID, CONF_CRON, CONF_DAYS_OF_MONTH, CONF_DAYS_OF_WEEK, CONF_HOURS, \
CONF_MINUTES, CONF_MONTHS, CONF_ON_TIME, CONF_SECONDS, CONF_TIMEZONE, CONF_TRIGGER_ID, \ CONF_MINUTES, CONF_MONTHS, CONF_ON_TIME, CONF_ON_TIME_SYNC, CONF_SECONDS, CONF_TIMEZONE, \
CONF_AT, CONF_SECOND, CONF_HOUR, CONF_MINUTE CONF_TRIGGER_ID, CONF_AT, CONF_SECOND, CONF_HOUR, CONF_MINUTE
from esphome.core import coroutine, coroutine_with_priority from esphome.core import coroutine, coroutine_with_priority
from esphome.automation import Condition from esphome.automation import Condition
@@ -24,6 +24,7 @@ IS_PLATFORM_COMPONENT = True
time_ns = cg.esphome_ns.namespace('time') time_ns = cg.esphome_ns.namespace('time')
RealTimeClock = time_ns.class_('RealTimeClock', cg.PollingComponent) RealTimeClock = time_ns.class_('RealTimeClock', cg.PollingComponent)
CronTrigger = time_ns.class_('CronTrigger', automation.Trigger.template(), cg.Component) CronTrigger = time_ns.class_('CronTrigger', automation.Trigger.template(), cg.Component)
SyncTrigger = time_ns.class_('SyncTrigger', automation.Trigger.template(), cg.Component)
ESPTime = time_ns.struct('ESPTime') ESPTime = time_ns.struct('ESPTime')
TimeHasTimeCondition = time_ns.class_('TimeHasTimeCondition', Condition) TimeHasTimeCondition = time_ns.class_('TimeHasTimeCondition', Condition)
@@ -294,6 +295,9 @@ TIME_SCHEMA = cv.Schema({
cv.Optional(CONF_CRON): validate_cron_raw, cv.Optional(CONF_CRON): validate_cron_raw,
cv.Optional(CONF_AT): validate_time_at, cv.Optional(CONF_AT): validate_time_at,
}, validate_cron_keys), }, validate_cron_keys),
cv.Optional(CONF_ON_TIME_SYNC): automation.validate_automation({
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SyncTrigger),
}),
}).extend(cv.polling_component_schema('15min')) }).extend(cv.polling_component_schema('15min'))
@@ -320,6 +324,12 @@ def setup_time_core_(time_var, config):
yield cg.register_component(trigger, conf) yield cg.register_component(trigger, conf)
yield automation.build_automation(trigger, [], conf) yield automation.build_automation(trigger, [], conf)
for conf in config.get(CONF_ON_TIME_SYNC, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], time_var)
yield cg.register_component(trigger, conf)
yield automation.build_automation(trigger, [], conf)
@coroutine @coroutine
def register_time(time_var, config): def register_time(time_var, config):

View File

@@ -75,5 +75,9 @@ void CronTrigger::add_days_of_week(const std::vector<uint8_t> &days_of_week) {
} }
float CronTrigger::get_setup_priority() const { return setup_priority::HARDWARE; } float CronTrigger::get_setup_priority() const { return setup_priority::HARDWARE; }
SyncTrigger::SyncTrigger(RealTimeClock *rtc) : rtc_(rtc) {
rtc->add_on_time_sync_callback([this]() { this->trigger(); });
}
} // namespace time } // namespace time
} // namespace esphome } // namespace esphome

View File

@@ -37,5 +37,12 @@ class CronTrigger : public Trigger<>, public Component {
optional<ESPTime> last_check_; optional<ESPTime> last_check_;
}; };
class SyncTrigger : public Trigger<>, public Component {
public:
explicit SyncTrigger(RealTimeClock *rtc);
protected:
RealTimeClock *rtc_;
};
} // namespace time } // namespace time
} // namespace esphome } // namespace esphome

View File

@@ -38,6 +38,8 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
char buf[128]; char buf[128];
time.strftime(buf, sizeof(buf), "%c"); time.strftime(buf, sizeof(buf), "%c");
ESP_LOGD(TAG, "Synchronized time: %s", buf); ESP_LOGD(TAG, "Synchronized time: %s", buf);
this->time_sync_callback_.call();
} }
size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) { size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) {

View File

@@ -127,11 +127,17 @@ class RealTimeClock : public PollingComponent {
void call_setup() override; void call_setup() override;
void add_on_time_sync_callback(std::function<void()> callback) {
this->time_sync_callback_.add(std::move(callback));
};
protected: protected:
/// Report a unix epoch as current time. /// Report a unix epoch as current time.
void synchronize_epoch_(uint32_t epoch); void synchronize_epoch_(uint32_t epoch);
std::string timezone_{}; std::string timezone_{};
CallbackManager<void()> time_sync_callback_;
}; };
template<typename... Ts> class TimeHasTimeCondition : public Condition<Ts...> { template<typename... Ts> class TimeHasTimeCondition : public Condition<Ts...> {

View File

@@ -42,6 +42,8 @@ void Tuya::dump_config() {
ESP_LOGCONFIG(TAG, " Datapoint %d: switch (value: %s)", info.id, ONOFF(info.value_bool)); ESP_LOGCONFIG(TAG, " Datapoint %d: switch (value: %s)", info.id, ONOFF(info.value_bool));
else if (info.type == TuyaDatapointType::INTEGER) else if (info.type == TuyaDatapointType::INTEGER)
ESP_LOGCONFIG(TAG, " Datapoint %d: int value (value: %d)", info.id, info.value_int); ESP_LOGCONFIG(TAG, " Datapoint %d: int value (value: %d)", info.id, info.value_int);
else if (info.type == TuyaDatapointType::STRING)
ESP_LOGCONFIG(TAG, " Datapoint %d: string value (value: %s)", info.id, info.value_string.c_str());
else if (info.type == TuyaDatapointType::ENUM) else if (info.type == TuyaDatapointType::ENUM)
ESP_LOGCONFIG(TAG, " Datapoint %d: enum (value: %d)", info.id, info.value_enum); ESP_LOGCONFIG(TAG, " Datapoint %d: enum (value: %d)", info.id, info.value_enum);
else if (info.type == TuyaDatapointType::BITMASK) else if (info.type == TuyaDatapointType::BITMASK)
@@ -283,6 +285,9 @@ void Tuya::handle_datapoint_(const uint8_t *buffer, size_t len) {
return; return;
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]); datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
break; break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_len);
break;
case TuyaDatapointType::ENUM: case TuyaDatapointType::ENUM:
if (data_len != 1) if (data_len != 1)
return; return;
@@ -339,7 +344,13 @@ void Tuya::set_datapoint_value(TuyaDatapoint datapoint) {
ESP_LOGV(TAG, "Datapoint %u set to %u", datapoint.id, datapoint.value_uint); ESP_LOGV(TAG, "Datapoint %u set to %u", datapoint.id, datapoint.value_uint);
for (auto &other : this->datapoints_) { for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) { if (other.id == datapoint.id) {
if (other.value_uint == datapoint.value_uint) { // String value is stored outside the union; must be checked separately.
if (datapoint.type == TuyaDatapointType::STRING) {
if (other.value_string == datapoint.value_string) {
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
} else if (other.value_uint == datapoint.value_uint) {
ESP_LOGV(TAG, "Not sending unchanged value"); ESP_LOGV(TAG, "Not sending unchanged value");
return; return;
} }
@@ -359,6 +370,11 @@ void Tuya::set_datapoint_value(TuyaDatapoint datapoint) {
data.push_back(datapoint.value_uint >> 8); data.push_back(datapoint.value_uint >> 8);
data.push_back(datapoint.value_uint >> 0); data.push_back(datapoint.value_uint >> 0);
break; break;
case TuyaDatapointType::STRING:
for (char const &c : datapoint.value_string) {
data.push_back(c);
}
break;
case TuyaDatapointType::ENUM: case TuyaDatapointType::ENUM:
data.push_back(datapoint.value_enum); data.push_back(datapoint.value_enum);
break; break;

View File

@@ -30,6 +30,7 @@ struct TuyaDatapoint {
uint8_t value_enum; uint8_t value_enum;
uint16_t value_bitmask; uint16_t value_bitmask;
}; };
std::string value_string;
}; };
struct TuyaDatapointListener { struct TuyaDatapointListener {

View File

@@ -194,6 +194,9 @@ optional<XiaomiParseResult> parse_xiaomi_header(const esp32_ble_tracker::Service
result.name = "MJYD02YLA"; result.name = "MJYD02YLA";
if (raw.size() == 19) if (raw.size() == 19)
result.raw_offset -= 6; result.raw_offset -= 6;
} else if ((raw[2] == 0x87) && (raw[3] == 0x03)) { // square body, e-ink display
result.type = XiaomiParseResult::TYPE_MHOC401;
result.name = "MHOC401";
} else { } else {
ESP_LOGVV(TAG, "parse_xiaomi_header(): unknown device, no magic bytes."); ESP_LOGVV(TAG, "parse_xiaomi_header(): unknown device, no magic bytes.");
return {}; return {};

View File

@@ -21,7 +21,8 @@ struct XiaomiParseResult {
TYPE_JQJCY01YM, TYPE_JQJCY01YM,
TYPE_MUE4094RT, TYPE_MUE4094RT,
TYPE_WX08ZM, TYPE_WX08ZM,
TYPE_MJYD02YLA TYPE_MJYD02YLA,
TYPE_MHOC401
} type; } type;
std::string name; std::string name;
optional<float> temperature; optional<float> temperature;

View File

@@ -0,0 +1,43 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import sensor, esp32_ble_tracker
from esphome.const import CONF_BATTERY_LEVEL, CONF_HUMIDITY, CONF_MAC_ADDRESS, CONF_TEMPERATURE, \
UNIT_CELSIUS, ICON_THERMOMETER, UNIT_PERCENT, ICON_WATER_PERCENT, ICON_BATTERY, CONF_ID, \
CONF_BINDKEY
CODEOWNERS = ['@vevsvevs']
DEPENDENCIES = ['esp32_ble_tracker']
AUTO_LOAD = ['xiaomi_ble']
xiaomi_mhoc401_ns = cg.esphome_ns.namespace('xiaomi_mhoc401')
XiaomiMHOC401 = xiaomi_mhoc401_ns.class_('XiaomiMHOC401',
esp32_ble_tracker.ESPBTDeviceListener,
cg.Component)
CONFIG_SCHEMA = cv.Schema({
cv.GenerateID(): cv.declare_id(XiaomiMHOC401),
cv.Required(CONF_BINDKEY): cv.bind_key,
cv.Required(CONF_MAC_ADDRESS): cv.mac_address,
cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 1),
cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(UNIT_PERCENT, ICON_WATER_PERCENT, 0),
cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema(UNIT_PERCENT, ICON_BATTERY, 0),
}).extend(esp32_ble_tracker.ESP_BLE_DEVICE_SCHEMA).extend(cv.COMPONENT_SCHEMA)
def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
yield cg.register_component(var, config)
yield esp32_ble_tracker.register_ble_device(var, config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
cg.add(var.set_bindkey(config[CONF_BINDKEY]))
if CONF_TEMPERATURE in config:
sens = yield sensor.new_sensor(config[CONF_TEMPERATURE])
cg.add(var.set_temperature(sens))
if CONF_HUMIDITY in config:
sens = yield sensor.new_sensor(config[CONF_HUMIDITY])
cg.add(var.set_humidity(sens))
if CONF_BATTERY_LEVEL in config:
sens = yield sensor.new_sensor(config[CONF_BATTERY_LEVEL])
cg.add(var.set_battery_level(sens))

View File

@@ -0,0 +1,81 @@
#include "xiaomi_mhoc401.h"
#include "esphome/core/log.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace xiaomi_mhoc401 {
static const char *TAG = "xiaomi_mhoc401";
void XiaomiMHOC401::dump_config() {
ESP_LOGCONFIG(TAG, "Xiaomi MHOC401");
ESP_LOGCONFIG(TAG, " Bindkey: %s", hexencode(this->bindkey_, 16).c_str());
LOG_SENSOR(" ", "Temperature", this->temperature_);
LOG_SENSOR(" ", "Humidity", this->humidity_);
LOG_SENSOR(" ", "Battery Level", this->battery_level_);
}
bool XiaomiMHOC401::parse_device(const esp32_ble_tracker::ESPBTDevice &device) {
if (device.address_uint64() != this->address_) {
ESP_LOGVV(TAG, "parse_device(): unknown MAC address.");
return false;
}
ESP_LOGVV(TAG, "parse_device(): MAC address %s found.", device.address_str().c_str());
bool success = false;
for (auto &service_data : device.get_service_datas()) {
auto res = xiaomi_ble::parse_xiaomi_header(service_data);
if (!res.has_value()) {
continue;
}
if (res->is_duplicate) {
continue;
}
if (res->has_encryption &&
(!(xiaomi_ble::decrypt_xiaomi_payload(const_cast<std::vector<uint8_t> &>(service_data.data), this->bindkey_,
this->address_)))) {
continue;
}
if (!(xiaomi_ble::parse_xiaomi_message(service_data.data, *res))) {
continue;
}
if (res->humidity.has_value() && this->humidity_ != nullptr) {
// see https://github.com/custom-components/sensor.mitemp_bt/issues/7#issuecomment-595948254
*res->humidity = trunc(*res->humidity);
}
if (!(xiaomi_ble::report_xiaomi_results(res, device.address_str()))) {
continue;
}
if (res->temperature.has_value() && this->temperature_ != nullptr)
this->temperature_->publish_state(*res->temperature);
if (res->humidity.has_value() && this->humidity_ != nullptr)
this->humidity_->publish_state(*res->humidity);
if (res->battery_level.has_value() && this->battery_level_ != nullptr)
this->battery_level_->publish_state(*res->battery_level);
success = true;
}
if (!success) {
return false;
}
return true;
}
void XiaomiMHOC401::set_bindkey(const std::string &bindkey) {
memset(bindkey_, 0, 16);
if (bindkey.size() != 32) {
return;
}
char temp[3] = {0};
for (int i = 0; i < 16; i++) {
strncpy(temp, &(bindkey.c_str()[i * 2]), 2);
bindkey_[i] = std::strtoul(temp, NULL, 16);
}
}
} // namespace xiaomi_mhoc401
} // namespace esphome
#endif

View File

@@ -0,0 +1,36 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
#include "esphome/components/xiaomi_ble/xiaomi_ble.h"
#ifdef ARDUINO_ARCH_ESP32
namespace esphome {
namespace xiaomi_mhoc401 {
class XiaomiMHOC401 : public Component, public esp32_ble_tracker::ESPBTDeviceListener {
public:
void set_address(uint64_t address) { address_ = address; };
void set_bindkey(const std::string &bindkey);
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::DATA; }
void set_temperature(sensor::Sensor *temperature) { temperature_ = temperature; }
void set_humidity(sensor::Sensor *humidity) { humidity_ = humidity; }
void set_battery_level(sensor::Sensor *battery_level) { battery_level_ = battery_level; }
protected:
uint64_t address_;
uint8_t bindkey_[16];
sensor::Sensor *temperature_{nullptr};
sensor::Sensor *humidity_{nullptr};
sensor::Sensor *battery_level_{nullptr};
};
} // namespace xiaomi_mhoc401
} // namespace esphome
#endif

View File

@@ -2,7 +2,7 @@
MAJOR_VERSION = 1 MAJOR_VERSION = 1
MINOR_VERSION = 16 MINOR_VERSION = 16
PATCH_VERSION = '0b4' PATCH_VERSION = '0'
__short_version__ = f'{MAJOR_VERSION}.{MINOR_VERSION}' __short_version__ = f'{MAJOR_VERSION}.{MINOR_VERSION}'
__version__ = f'{__short_version__}.{PATCH_VERSION}' __version__ = f'{__short_version__}.{PATCH_VERSION}'
@@ -350,6 +350,7 @@ CONF_ON_SHUTDOWN = 'on_shutdown'
CONF_ON_STATE = 'on_state' CONF_ON_STATE = 'on_state'
CONF_ON_TAG = 'on_tag' CONF_ON_TAG = 'on_tag'
CONF_ON_TIME = 'on_time' CONF_ON_TIME = 'on_time'
CONF_ON_TIME_SYNC = 'on_time_sync'
CONF_ON_TURN_OFF = 'on_turn_off' CONF_ON_TURN_OFF = 'on_turn_off'
CONF_ON_TURN_ON = 'on_turn_on' CONF_ON_TURN_ON = 'on_turn_on'
CONF_ON_VALUE = 'on_value' CONF_ON_VALUE = 'on_value'

View File

@@ -171,15 +171,17 @@ uint8_t crc8(uint8_t *data, uint8_t len) {
} }
return crc; return crc;
} }
void delay_microseconds_accurate(uint32_t usec) { void delay_microseconds_accurate(uint32_t usec) {
if (usec == 0) if (usec == 0)
return; return;
if (usec < 5000UL) {
if (usec <= 16383UL) {
delayMicroseconds(usec); delayMicroseconds(usec);
} else { return;
delay(usec / 1000UL); }
delayMicroseconds(usec % 1000UL); uint32_t start = micros();
while (micros() - start < usec) {
delay(0);
} }
} }

View File

@@ -1854,12 +1854,9 @@ time:
then: then:
- lambda: 'ESP_LOGD("main", "time");' - lambda: 'ESP_LOGD("main", "time");'
- platform: gps - platform: gps
update_interval: 1h on_time_sync:
on_time:
seconds: 0
minutes: /15
then: then:
ds1307.write: ds1307.write_time:
id: ds1307_time id: ds1307_time
- platform: ds1307 - platform: ds1307
id: ds1307_time id: ds1307_time
@@ -1867,7 +1864,7 @@ time:
on_time: on_time:
seconds: 0 seconds: 0
then: then:
ds1307.read ds1307.read_time
cover: cover:
- platform: template - platform: template