diff --git a/.clang-format b/.clang-format index bda3fd99..a7c337f8 100644 --- a/.clang-format +++ b/.clang-format @@ -1,16 +1,137 @@ -BasedOnStyle: Google -Language: Cpp -ColumnLimit: 120 +Language: Cpp AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: DontAlign +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false -AllowShortFunctionsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +DisableFormat: false +ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^' + Priority: 2 + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 2000 PointerAlignment: Right -SortIncludes: false -TabWidth: 2 -UseTab: Never +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + CanonicalDelimiter: '' + BasedOnStyle: google +ReflowComments: true +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: true SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 2 -IndentPPDirectives: None +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 2 +UseTab: Never diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000..ed14a38b --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,65 @@ +--- +Checks: >- + *, + -android-*,-boost-*,-clang-analyzer-osx.*,-objc-*,-zircon-*,-mpi-*,-llvm-header-guard,-llvm-include-order,-fuchsia-default-arguments,-fuchsia-overloaded-operator,-fuchsia-statically-constructed-objects,-fuchsia-multiple-inheritance,-google-runtime-int,-google-explicit-constructor,-google-readability-braces-around-statements,-google-runtime-references,-google-readability-casting,-cppcoreguidelines-pro-type-varar,-cppcoreguidelines-pro-type-vararg,-cppcoreguidelines-pro-type-union-access,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-pro-type-cstyle-cast,-cppcoreguidelines-pro-type-reinterpret-cast,-cppcoreguidelines-owning-memory,-cppcoreguidelines-pro-bounds-constant-array-index,-cppcoreguidelines-c-copy-assignment-signature,-cppcoreguidelines-special-member-functions,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-readability-named-parameter,-readability-braces-around-statements,-readability-implicit-bool-conversion,-readability-else-after-return,-hicpp-*,-abseil-*,-fuchsia-*,-cert-err58-cpp,-cppcoreguidelines-pro-type-member-init,-cert-dcl50-cpp,-modernize-use-equals-default,-modernize-deprecated-headers,-modernize-use-auto,-modernize-pass-by-value,-bugprone-macro-parentheses,-misc-unused-parameters,-misc-unconventional-assign-operator,-performance-unnecessary-value-param,-modernize-pass-by-value,-modernize-return-braced-init-list,-cppcoreguidelines-pro-type-const-cast,-clang-analyzer-security.*,-google-readability-todo,-readability-redundant-member-init,-modernize-use-default-member-init,-cppcoreguidelines-pro-type-static-cast-downcast,-warnings-as-errors,-google-build-using-namespace,-clang-analyzer-core.CallAndMessage +WarningsAsErrors: '*' +HeaderFilterRegex: '^.*/src/esphome/.*' +AnalyzeTemporaryDtors: false +FormatStyle: google +CheckOptions: + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: readability-identifier-naming.LocalVariableCase + value: 'lower_case' + - key: readability-identifier-naming.ClassCase + value: 'CamelCase' + - key: readability-identifier-naming.StructCase + value: 'CamelCase' + - key: readability-identifier-naming.EnumCase + value: 'CamelCase' + - key: readability-identifier-naming.EnumConstantCase + value: 'UPPER_CASE' + - key: readability-identifier-naming.StaticConstantCase + value: 'UPPER_CASE' + - key: readability-identifier-naming.StaticVariableCase + value: 'UPPER_CASE' + - key: readability-identifier-naming.GlobalConstantCase + value: 'UPPER_CASE' + - key: readability-identifier-naming.ParameterCase + value: 'lower_case' + - key: readability-identifier-naming.PrivateMemberPrefix + value: 'NO_PRIVATE_MEMBERS_ALWAYS_USE_PROTECTED' + - key: readability-identifier-naming.PrivateMethodPrefix + value: 'NO_PRIVATE_METHODS_ALWAYS_USE_PROTECTED' + - key: readability-identifier-naming.ClassMemberCase + value: 'lower_case' + - key: readability-identifier-naming.ProtectedMemberSuffix + value: '_' + - key: readability-identifier-naming.FunctionCase + value: 'lower_case' + - key: readability-identifier-naming.ClassMethodCase + value: 'lower_case' + - key: readability-identifier-naming.ProtectedMethodSuffix + value: '_' + - key: readability-identifier-naming.VirtualMethodCase + value: 'lower_case' + - key: readability-identifier-naming.VirtualMethodSuffix + value: '' diff --git a/.gitignore b/.gitignore index 57d40bd5..215c8d3c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .piolibdeps .vscode CMakeListsPrivate.txt +CMakeLists.txt # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 @@ -36,3 +37,4 @@ cmake_install.cmake install_manifest.txt compile_commands.json CTestTestfile.cmake +/*.cbp diff --git a/.travis.yml b/.travis.yml index 604b8d1f..94f5c2cd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,15 +8,44 @@ cache: - "~/.platformio" - "$TRAVIS_BUILD_DIR/.piolibdeps" -script: - - python travis.py - - platformio run -e $BUILD_TARGET - matrix: fast_finish: true include: - - env: BUILD_TARGET=livingroom - - env: BUILD_TARGET=livingroom8266 - - env: BUILD_TARGET=custombmp180 - - env: BUILD_TARGET=fastled + - env: TARGET=lint + dist: trusty + sudo: required + addons: + apt: + sources: + - ubuntu-toolchain-r-test + - llvm-toolchain-trusty-7 + packages: + - cmake + - clang-tidy-7 + - clang-format-7 + before_script: + - pio init --ide clion + - | + if ! patch -R -p0 -s -f --dry-run decode_32bit(field_id, val)) { ESP_LOGV(TAG, "Cannot decode 32-bit field %u with value %u!", field_id, val); } @@ -98,8 +88,8 @@ void APIMessage::decode(const uint8_t *buffer, size_t length) { } } -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/api_message.h b/src/esphome/api/api_message.h index 702d0eef..8ce496dd 100644 --- a/src/esphome/api/api_message.h +++ b/src/esphome/api/api_message.h @@ -32,7 +32,7 @@ enum class APIMessageType { LIST_ENTITIES_SENSOR_RESPONSE = 16, LIST_ENTITIES_SWITCH_RESPONSE = 17, LIST_ENTITIES_TEXT_SENSOR_RESPONSE = 18, - LIST_SERVICES_SERVICE_RESPONSE = 41, + LIST_ENTITIES_SERVICE_RESPONSE = 41, LIST_ENTITIES_DONE_RESPONSE = 19, SUBSCRIBE_STATES_REQUEST = 20, @@ -75,10 +75,10 @@ class APIMessage { virtual void encode(APIBuffer &buffer); }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_API_API_MESSAGE_H +#endif // ESPHOME_API_API_MESSAGE_H diff --git a/src/esphome/api/api_server.cpp b/src/esphome/api/api_server.cpp index ff04d933..0dd88421 100644 --- a/src/esphome/api/api_server.cpp +++ b/src/esphome/api/api_server.cpp @@ -24,15 +24,17 @@ void APIServer::setup() { this->server_ = AsyncServer(this->port_); this->server_.setNoDelay(false); this->server_.begin(); - this->server_.onClient([](void *s, AsyncClient *client) { - if (client == nullptr) - return; - - // can't print here because in lwIP thread - // ESP_LOGD(TAG, "New client connected from %s", client->remoteIP().toString().c_str()); - auto *this_ = (APIServer *) s; - this_->clients_.push_back(new APIConnection(client, this_)); - }, this); + this->server_.onClient( + [](void *s, AsyncClient *client) { + if (client == nullptr) + return; + + // can't print here because in lwIP thread + // ESP_LOGD(TAG, "New client connected from %s", client->remoteIP().toString().c_str()); + auto *a_this = (APIServer *) s; + a_this->clients_.push_back(new APIConnection(client, a_this)); + }, + this); if (global_log_component != nullptr) { global_log_component->add_on_log_callback([this](int level, const char *tag, const char *message) { for (auto *c : this->clients_) { @@ -42,7 +44,7 @@ void APIServer::setup() { }); } - add_shutdown_hook([this] (const char *reason) { + add_shutdown_hook([this](const char *reason) { for (auto *c : this->clients_) { c->send_disconnect_request(reason); } @@ -54,10 +56,8 @@ void APIServer::setup() { } void APIServer::loop() { // Partition clients into remove and active - auto new_end = std::partition(this->clients_.begin(), this->clients_.end(), - [](APIConnection *conn) { - return !conn->remove_; - }); + auto new_end = + std::partition(this->clients_.begin(), this->clients_.end(), [](APIConnection *conn) { return !conn->remove_; }); // print disconnection messages for (auto it = new_end; it != this->clients_.end(); ++it) { ESP_LOGD(TAG, "Disconnecting %s", (*it)->client_info_.c_str()); @@ -89,9 +89,7 @@ void APIServer::dump_config() { ESP_LOGCONFIG(TAG, "API Server:"); ESP_LOGCONFIG(TAG, " Address: %s:%u", network_get_address().c_str(), this->port_); } -bool APIServer::uses_password() const { - return !this->password_.empty(); -} +bool APIServer::uses_password() const { return !this->password_.empty(); } bool APIServer::check_password(const std::string &password) const { // depend only on input password length const char *a = this->password_.c_str(); @@ -115,17 +113,16 @@ bool APIServer::check_password(const std::string &password) const { } for (size_t i = 0; i < length; i++) { - result |= *left++ ^ *right++; + result |= *left++ ^ *right++; // NOLINT } return result == 0; } -void APIServer::handle_disconnect(APIConnection *conn) { - -} +void APIServer::handle_disconnect(APIConnection *conn) {} #ifdef USE_BINARY_SENSOR void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool state) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_binary_sensor_state(obj, state); } @@ -133,7 +130,8 @@ void APIServer::on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool s #ifdef USE_COVER void APIServer::on_cover_update(cover::Cover *obj) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_cover_state(obj); } @@ -141,7 +139,8 @@ void APIServer::on_cover_update(cover::Cover *obj) { #ifdef USE_FAN void APIServer::on_fan_update(fan::FanState *obj) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_fan_state(obj); } @@ -149,7 +148,8 @@ void APIServer::on_fan_update(fan::FanState *obj) { #ifdef USE_LIGHT void APIServer::on_light_update(light::LightState *obj) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_light_state(obj); } @@ -157,7 +157,8 @@ void APIServer::on_light_update(light::LightState *obj) { #ifdef USE_SENSOR void APIServer::on_sensor_update(sensor::Sensor *obj, float state) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_sensor_state(obj, state); } @@ -165,7 +166,8 @@ void APIServer::on_sensor_update(sensor::Sensor *obj, float state) { #ifdef USE_SWITCH void APIServer::on_switch_update(switch_::Switch *obj, bool state) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_switch_state(obj, state); } @@ -173,30 +175,23 @@ void APIServer::on_switch_update(switch_::Switch *obj, bool state) { #ifdef USE_TEXT_SENSOR void APIServer::on_text_sensor_update(text_sensor::TextSensor *obj, std::string state) { - if (obj->is_internal()) return; + if (obj->is_internal()) + return; for (auto *c : this->clients_) c->send_text_sensor_state(obj, state); } #endif -float APIServer::get_setup_priority() const { - return setup_priority::WIFI - 1.0f; -} -void APIServer::set_port(uint16_t port) { - this->port_ = port; -} +float APIServer::get_setup_priority() const { return setup_priority::WIFI - 1.0f; } +void APIServer::set_port(uint16_t port) { this->port_ = port; } APIServer *global_api_server = nullptr; -void APIServer::set_password(const std::string &password) { - this->password_ = password; -} +void APIServer::set_password(const std::string &password) { this->password_ = password; } void APIServer::send_service_call(ServiceCallResponse &call) { for (auto *client : this->clients_) { client->send_service_call(call); } } -APIServer::APIServer() { - global_api_server = this; -} +APIServer::APIServer() { global_api_server = this; } void APIServer::subscribe_home_assistant_state(std::string entity_id, std::function f) { this->state_subs_.push_back(HomeAssistantStateSubscription{ .entity_id = entity_id, @@ -206,12 +201,8 @@ void APIServer::subscribe_home_assistant_state(std::string entity_id, std::funct const std::vector &APIServer::get_state_subs() const { return this->state_subs_; } -uint16_t APIServer::get_port() const { - return this->port_; -} -void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { - this->reboot_timeout_ = reboot_timeout; -} +uint16_t APIServer::get_port() const { return this->port_; } +void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; } #ifdef USE_HOMEASSISTANT_TIME void APIServer::request_time() { for (auto *client : this->clients_) { @@ -223,29 +214,21 @@ void APIServer::request_time() { // APIConnection APIConnection::APIConnection(AsyncClient *client, APIServer *parent) - : client_(client), parent_(parent), initial_state_iterator_(parent, this), - list_entities_iterator_(parent, this) { - this->client_->onError([](void *s, AsyncClient *c, int8_t error) { - ((APIConnection *) s)->on_error_(error); - }, this); - this->client_->onDisconnect([](void *s, AsyncClient *c) { - ((APIConnection *) s)->on_disconnect_(); - }, this); - this->client_->onTimeout([](void *s, AsyncClient *c, uint32_t time) { - ((APIConnection *) s)->on_timeout_(time); - }, this); - this->client_->onData([](void *s, AsyncClient *c, void *buf, size_t len) { - ((APIConnection *) s)->on_data_(reinterpret_cast(buf), len); - }, this); + : client_(client), parent_(parent), initial_state_iterator_(parent, this), list_entities_iterator_(parent, this) { + this->client_->onError([](void *s, AsyncClient *c, int8_t error) { ((APIConnection *) s)->on_error_(error); }, this); + this->client_->onDisconnect([](void *s, AsyncClient *c) { ((APIConnection *) s)->on_disconnect_(); }, this); + this->client_->onTimeout([](void *s, AsyncClient *c, uint32_t time) { ((APIConnection *) s)->on_timeout_(time); }, + this); + this->client_->onData([](void *s, AsyncClient *c, void *buf, + size_t len) { ((APIConnection *) s)->on_data_(reinterpret_cast(buf), len); }, + this); this->send_buffer_.reserve(64); this->recv_buffer_.reserve(32); this->client_info_ = this->client_->remoteIP().toString().c_str(); this->last_traffic_ = millis(); } -APIConnection::~APIConnection() { - delete this->client_; -} +APIConnection::~APIConnection() { delete this->client_; } void APIConnection::on_error_(int8_t error) { ESP_LOGD(TAG, "Error from client '%s': %d", this->client_info_.c_str(), error); // disconnect will also be called, nothing to do here @@ -255,9 +238,7 @@ void APIConnection::on_disconnect_() { // delete self, generally unsafe but not in this case. this->remove_ = true; } -void APIConnection::on_timeout_(uint32_t time) { - this->disconnect_client_(); -} +void APIConnection::on_timeout_(uint32_t time) { this->disconnect_client(); } void APIConnection::on_data_(uint8_t *buf, size_t len) { if (len == 0 || buf == nullptr) return; @@ -402,6 +383,7 @@ void APIConnection::read_message_(uint32_t size, uint32_t type, uint8_t *msg) { case APIMessageType::LIST_ENTITIES_SENSOR_RESPONSE: case APIMessageType::LIST_ENTITIES_SWITCH_RESPONSE: case APIMessageType::LIST_ENTITIES_TEXT_SENSOR_RESPONSE: + case APIMessageType::LIST_ENTITIES_SERVICE_RESPONSE: case APIMessageType::LIST_ENTITIES_DONE_RESPONSE: // Invalid break; @@ -464,7 +446,7 @@ void APIConnection::read_message_(uint32_t size, uint32_t type, uint8_t *msg) { case APIMessageType::SUBSCRIBE_SERVICE_CALLS_REQUEST: { SubscribeServiceCallsRequest req; req.decode(msg, size); - this->on_subscribe_service_calls_request(req); + this->on_subscribe_service_calls_request_(req); break; } case APIMessageType::SERVICE_CALL_RESPONSE: @@ -483,7 +465,7 @@ void APIConnection::read_message_(uint32_t size, uint32_t type, uint8_t *msg) { case APIMessageType::SUBSCRIBE_HOME_ASSISTANT_STATES_REQUEST: { SubscribeHomeAssistantStatesRequest req; req.decode(msg, size); - this->on_subscribe_home_assistant_states_request(req); + this->on_subscribe_home_assistant_states_request_(req); break; } case APIMessageType::SUBSCRIBE_HOME_ASSISTANT_STATE_RESPONSE: @@ -492,13 +474,13 @@ void APIConnection::read_message_(uint32_t size, uint32_t type, uint8_t *msg) { case APIMessageType::HOME_ASSISTANT_STATE_RESPONSE: { HomeAssistantStateResponse req; req.decode(msg, size); - this->on_home_assistant_state_response(req); + this->on_home_assistant_state_response_(req); break; } case APIMessageType::EXECUTE_SERVICE_REQUEST: { ExecuteServiceRequest req; req.decode(msg, size); - this->on_execute_service(req); + this->on_execute_service_(req); break; } } @@ -550,17 +532,17 @@ void APIConnection::on_connect_request_(const ConnectRequest &req) { } void APIConnection::on_disconnect_request_(const DisconnectRequest &req) { ESP_LOGVV(TAG, "on_disconnect_request_"); - // remote initiated disconnect_client_ + // remote initiated disconnect_client if (!this->send_empty_message(APIMessageType::DISCONNECT_RESPONSE)) { this->fatal_error_(); return; } - this->disconnect_client_(); + this->disconnect_client(); } void APIConnection::on_disconnect_response_(const DisconnectResponse &req) { ESP_LOGVV(TAG, "on_disconnect_response_"); - // we initiated disconnect_client_ - this->disconnect_client_(); + // we initiated disconnect_client + this->disconnect_client(); } void APIConnection::on_ping_request_(const PingRequest &req) { ESP_LOGVV(TAG, "on_ping_request_"); @@ -647,7 +629,7 @@ bool APIConnection::send_empty_message(APIMessageType type) { return this->send_buffer(type); } -void APIConnection::disconnect_client_() { +void APIConnection::disconnect_client() { this->client_->close(); this->remove_ = true; } @@ -691,19 +673,19 @@ bool APIConnection::send_buffer(APIMessageType type) { } } -// char buffer[512]; -// uint32_t offset = 0; -// for (int j = 0; j < header_len; j++) { -// offset += snprintf(buffer + offset, 512 - offset, "0x%02X ", header[j]); -// } -// offset += snprintf(buffer + offset, 512 - offset, "| "); -// for (auto &it : this->send_buffer_) { -// int i = snprintf(buffer + offset, 512 - offset, "0x%02X ", it); -// if (i <= 0) -// break; -// offset += i; -// } -// ESP_LOGVV(TAG, "SEND %s", buffer); + // char buffer[512]; + // uint32_t offset = 0; + // for (int j = 0; j < header_len; j++) { + // offset += snprintf(buffer + offset, 512 - offset, "0x%02X ", header[j]); + // } + // offset += snprintf(buffer + offset, 512 - offset, "| "); + // for (auto &it : this->send_buffer_) { + // int i = snprintf(buffer + offset, 512 - offset, "0x%02X ", it); + // if (i <= 0) + // break; + // offset += i; + // } + // ESP_LOGVV(TAG, "SEND %s", buffer); this->client_->add(reinterpret_cast(header), header_len); this->client_->add(reinterpret_cast(this->send_buffer_.data()), this->send_buffer_.size()); @@ -724,9 +706,8 @@ void APIConnection::loop() { const uint32_t keepalive = 60000; if (this->sent_ping_) { if (millis() - this->last_traffic_ > (keepalive * 3) / 2) { - ESP_LOGW(TAG, "'%s' didn't respond to ping request in time. Disconnecting...", - this->client_info_.c_str()); - this->disconnect_client_(); + ESP_LOGW(TAG, "'%s' didn't respond to ping request in time. Disconnecting...", this->client_info_.c_str()); + this->disconnect_client(); } } else if (millis() - this->last_traffic_ > keepalive) { this->sent_ping_ = true; @@ -850,13 +831,13 @@ bool APIConnection::send_sensor_state(sensor::Sensor *sensor, float state) { #endif #ifdef USE_SWITCH -bool APIConnection::send_switch_state(switch_::Switch *switch_, bool state) { +bool APIConnection::send_switch_state(switch_::Switch *a_switch, bool state) { if (!this->state_subscription_) return false; auto buffer = this->get_buffer(); // fixed32 key = 1; - buffer.encode_fixed32(1, switch_->get_object_id_hash()); + buffer.encode_fixed32(1, a_switch->get_object_id_hash()); // bool state = 2; buffer.encode_bool(2, state); return this->send_buffer(APIMessageType::SWITCH_STATE_RESPONSE); @@ -877,9 +858,7 @@ bool APIConnection::send_text_sensor_state(text_sensor::TextSensor *text_sensor, } #endif -bool APIConnection::send_log_message(int level, - const char *tag, - const char *line) { +bool APIConnection::send_log_message(int level, const char *tag, const char *line) { if (this->log_subscription_ < level) return false; @@ -977,19 +956,19 @@ void APIConnection::on_light_command_request_(const LightCommandRequest &req) { #ifdef USE_SWITCH void APIConnection::on_switch_command_request_(const SwitchCommandRequest &req) { ESP_LOGVV(TAG, "on_switch_command_request_"); - switch_::Switch *switch_ = this->parent_->get_switch_by_key(req.get_key()); - if (switch_ == nullptr) + switch_::Switch *a_switch = this->parent_->get_switch_by_key(req.get_key()); + if (a_switch == nullptr) return; if (req.get_state()) { - switch_->turn_on(); + a_switch->turn_on(); } else { - switch_->turn_off(); + a_switch->turn_off(); } } #endif -void APIConnection::on_subscribe_service_calls_request(const SubscribeServiceCallsRequest &req) { +void APIConnection::on_subscribe_service_calls_request_(const SubscribeServiceCallsRequest &req) { this->service_call_subscription_ = true; } void APIConnection::send_service_call(ServiceCallResponse &call) { @@ -998,7 +977,7 @@ void APIConnection::send_service_call(ServiceCallResponse &call) { this->send_message(call); } -void APIConnection::on_subscribe_home_assistant_states_request(const SubscribeHomeAssistantStatesRequest &req) { +void APIConnection::on_subscribe_home_assistant_states_request_(const SubscribeHomeAssistantStatesRequest &req) { for (auto &it : this->parent_->get_state_subs()) { auto buffer = this->get_buffer(); // string entity_id = 1; @@ -1006,15 +985,15 @@ void APIConnection::on_subscribe_home_assistant_states_request(const SubscribeHo this->send_buffer(APIMessageType::SUBSCRIBE_HOME_ASSISTANT_STATE_RESPONSE); } } -void APIConnection::on_home_assistant_state_response(const HomeAssistantStateResponse &req) { +void APIConnection::on_home_assistant_state_response_(const HomeAssistantStateResponse &req) { for (auto &it : this->parent_->get_state_subs()) { if (it.entity_id == req.get_entity_id()) { it.callback(req.get_state()); } } } -void APIConnection::on_execute_service(const ExecuteServiceRequest &req) { - ESP_LOGVV(TAG, "on_execute_service"); +void APIConnection::on_execute_service_(const ExecuteServiceRequest &req) { + ESP_LOGVV(TAG, "on_execute_service_"); bool found = false; for (auto *service : this->parent_->get_user_services()) { if (service->execute_service(req)) { @@ -1031,13 +1010,11 @@ APIBuffer APIConnection::get_buffer() { return APIBuffer(&this->send_buffer_); } #ifdef USE_HOMEASSISTANT_TIME -void APIConnection::send_time_request() { - this->send_empty_message(APIMessageType::GET_TIME_REQUEST); -} +void APIConnection::send_time_request() { this->send_empty_message(APIMessageType::GET_TIME_REQUEST); } #endif -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/api_server.h b/src/esphome/api/api_server.h index 0b9a9736..46bda462 100644 --- a/src/esphome/api/api_server.h +++ b/src/esphome/api/api_server.h @@ -19,10 +19,10 @@ #include "esphome/log.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #ifdef ARDUINO_ARCH_ESP8266 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -36,7 +36,7 @@ class APIConnection { APIConnection(AsyncClient *client, APIServer *parent); ~APIConnection(); - void disconnect_client_(); + void disconnect_client(); APIBuffer get_buffer(); bool send_buffer(APIMessageType type); bool send_message(APIMessage &msg); @@ -59,7 +59,7 @@ class APIConnection { bool send_sensor_state(sensor::Sensor *sensor, float state); #endif #ifdef USE_SWITCH - bool send_switch_state(switch_::Switch *switch_, bool state); + bool send_switch_state(switch_::Switch *a_switch, bool state); #endif #ifdef USE_TEXT_SENSOR bool send_text_sensor_state(text_sensor::TextSensor *text_sensor, std::string state); @@ -107,10 +107,10 @@ class APIConnection { #ifdef USE_SWITCH void on_switch_command_request_(const SwitchCommandRequest &req); #endif - void on_subscribe_service_calls_request(const SubscribeServiceCallsRequest &req); - void on_subscribe_home_assistant_states_request(const SubscribeHomeAssistantStatesRequest &req); - void on_home_assistant_state_response(const HomeAssistantStateResponse &req); - void on_execute_service(const ExecuteServiceRequest &req); + void on_subscribe_service_calls_request_(const SubscribeServiceCallsRequest &req); + void on_subscribe_home_assistant_states_request_(const SubscribeHomeAssistantStatesRequest &req); + void on_home_assistant_state_response_(const HomeAssistantStateResponse &req); + void on_execute_service_(const ExecuteServiceRequest &req); enum class ConnectionState { WAITING_FOR_HELLO, @@ -136,8 +136,7 @@ class APIConnection { bool service_call_subscription_{false}; }; -template -class HomeAssistantServiceCallAction; +template class HomeAssistantServiceCallAction; class APIServer : public Component, public StoringUpdateListenerController { public: @@ -175,10 +174,10 @@ class APIServer : public Component, public StoringUpdateListenerController { void on_text_sensor_update(text_sensor::TextSensor *obj, std::string state) override; #endif void send_service_call(ServiceCallResponse &call); + template HomeAssistantServiceCallAction *make_home_assistant_service_call_action(); template - HomeAssistantServiceCallAction *make_home_assistant_service_call_action(); - template - UserService *make_user_service_trigger(const std::string &name, const std::array &args); + UserService *make_user_service_trigger(const std::string &name, + const std::array &args); #ifdef USE_HOMEASSISTANT_TIME void request_time(); #endif @@ -205,8 +204,7 @@ class APIServer : public Component, public StoringUpdateListenerController { extern APIServer *global_api_server; -template -class HomeAssistantServiceCallAction : public Action { +template class HomeAssistantServiceCallAction : public Action { public: HomeAssistantServiceCallAction(APIServer *parent) : parent_(parent) {} void set_service(const std::string &service); @@ -214,22 +212,20 @@ class HomeAssistantServiceCallAction : public Action { void set_data_template(const std::vector &data_template); void set_variables(const std::vector &variables); void play(Ts... x) override; + protected: APIServer *parent_; ServiceCallResponse resp_; }; -template -HomeAssistantServiceCallAction *APIServer::make_home_assistant_service_call_action() { +template HomeAssistantServiceCallAction *APIServer::make_home_assistant_service_call_action() { return new HomeAssistantServiceCallAction(this); } -template -void HomeAssistantServiceCallAction::set_service(const std::string &service) { +template void HomeAssistantServiceCallAction::set_service(const std::string &service) { this->resp_.set_service(service); } -template -void HomeAssistantServiceCallAction::set_data(const std::vector &data) { +template void HomeAssistantServiceCallAction::set_data(const std::vector &data) { this->resp_.set_data(data); } template @@ -240,8 +236,7 @@ template void HomeAssistantServiceCallAction::set_variables(const std::vector &variables) { this->resp_.set_variables(variables); } -template -void HomeAssistantServiceCallAction::play(Ts... x) { +template void HomeAssistantServiceCallAction::play(Ts... x) { this->parent_->send_service_call(this->resp_); this->play_next(x...); } @@ -253,10 +248,10 @@ UserService *APIServer::make_user_service_trigger(const std::string &name return service; } -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_HOMEASSISTANT_API_SERVER_H +#endif // ESPHOME_HOMEASSISTANT_API_SERVER_H diff --git a/src/esphome/api/basic_messages.cpp b/src/esphome/api/basic_messages.cpp index 589abed7..5bf6275a 100644 --- a/src/esphome/api/basic_messages.cpp +++ b/src/esphome/api/basic_messages.cpp @@ -14,79 +14,53 @@ static const char *TAG = "api.message"; // Hello bool HelloRequest::decode_length_delimited(uint32_t field_id, const uint8_t *value, size_t len) { switch (field_id) { - case 1: // string client_info = 1; + case 1: // string client_info = 1; this->client_info_ = as_string(value, len); return true; default: return false; } } -const std::string &HelloRequest::get_client_info() const { - return this->client_info_; -} -void HelloRequest::set_client_info(const std::string &client_info) { - this->client_info_ = client_info; -} -APIMessageType HelloRequest::message_type() const { - return APIMessageType::HELLO_REQUEST; -} +const std::string &HelloRequest::get_client_info() const { return this->client_info_; } +void HelloRequest::set_client_info(const std::string &client_info) { this->client_info_ = client_info; } +APIMessageType HelloRequest::message_type() const { return APIMessageType::HELLO_REQUEST; } // Connect bool ConnectRequest::decode_length_delimited(uint32_t field_id, const uint8_t *value, size_t len) { switch (field_id) { - case 1: // string password = 1; + case 1: // string password = 1; this->password_ = as_string(value, len); return true; default: return false; } } -const std::string &ConnectRequest::get_password() const { - return this->password_; -} -void ConnectRequest::set_password(const std::string &password) { - this->password_ = password; -} -APIMessageType ConnectRequest::message_type() const { - return APIMessageType::CONNECT_REQUEST; -} +const std::string &ConnectRequest::get_password() const { return this->password_; } +void ConnectRequest::set_password(const std::string &password) { this->password_ = password; } +APIMessageType ConnectRequest::message_type() const { return APIMessageType::CONNECT_REQUEST; } -APIMessageType DeviceInfoRequest::message_type() const { - return APIMessageType::DEVICE_INFO_REQUEST; -} -APIMessageType DisconnectRequest::message_type() const { - return APIMessageType::DISCONNECT_REQUEST; -} +APIMessageType DeviceInfoRequest::message_type() const { return APIMessageType::DEVICE_INFO_REQUEST; } +APIMessageType DisconnectRequest::message_type() const { return APIMessageType::DISCONNECT_REQUEST; } bool DisconnectRequest::decode_length_delimited(uint32_t field_id, const uint8_t *value, size_t len) { switch (field_id) { - case 1: // string reason = 1; + case 1: // string reason = 1; this->reason_ = as_string(value, len); return true; default: return false; } } -const std::string &DisconnectRequest::get_reason() const { - return this->reason_; -} -void DisconnectRequest::set_reason(const std::string &reason) { - this->reason_ = reason; -} +const std::string &DisconnectRequest::get_reason() const { return this->reason_; } +void DisconnectRequest::set_reason(const std::string &reason) { this->reason_ = reason; } void DisconnectRequest::encode(APIBuffer &buffer) { // string reason = 1; buffer.encode_string(1, this->reason_); } -APIMessageType DisconnectResponse::message_type() const { - return APIMessageType::DISCONNECT_RESPONSE; -} -APIMessageType PingRequest::message_type() const { - return APIMessageType::PING_REQUEST; -} -APIMessageType PingResponse::message_type() const { - return APIMessageType::PING_RESPONSE; -} -} // namespace api +APIMessageType DisconnectResponse::message_type() const { return APIMessageType::DISCONNECT_RESPONSE; } +APIMessageType PingRequest::message_type() const { return APIMessageType::PING_REQUEST; } +APIMessageType PingResponse::message_type() const { return APIMessageType::PING_RESPONSE; } +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/basic_messages.h b/src/esphome/api/basic_messages.h index 9dda5cec..5f484e33 100644 --- a/src/esphome/api/basic_messages.h +++ b/src/esphome/api/basic_messages.h @@ -17,6 +17,7 @@ class HelloRequest : public APIMessage { const std::string &get_client_info() const; void set_client_info(const std::string &client_info); APIMessageType message_type() const override; + protected: std::string client_info_; }; @@ -27,6 +28,7 @@ class ConnectRequest : public APIMessage { const std::string &get_password() const; void set_password(const std::string &password); APIMessageType message_type() const override; + protected: std::string password_; }; @@ -43,6 +45,7 @@ class DisconnectRequest : public APIMessage { APIMessageType message_type() const override; const std::string &get_reason() const; void set_reason(const std::string &reason); + protected: std::string reason_; }; @@ -62,10 +65,10 @@ class PingResponse : public APIMessage { APIMessageType message_type() const override; }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_API_BASIC_MESSAGES_H +#endif // ESPHOME_API_BASIC_MESSAGES_H diff --git a/src/esphome/api/command_messages.cpp b/src/esphome/api/command_messages.cpp index ce964206..fe61ad4b 100644 --- a/src/esphome/api/command_messages.cpp +++ b/src/esphome/api/command_messages.cpp @@ -9,7 +9,6 @@ ESPHOME_NAMESPACE_BEGIN namespace api { - #ifdef USE_COVER bool CoverCommandRequest::decode_varint(uint32_t field_id, uint32_t value) { switch (field_id) { @@ -40,12 +39,8 @@ bool CoverCommandRequest::decode_32bit(uint32_t field_id, uint32_t value) { return false; } } -APIMessageType CoverCommandRequest::message_type() const { - return APIMessageType ::COVER_COMMAND_REQUEST; -} -uint32_t CoverCommandRequest::get_key() const { - return this->key_; -} +APIMessageType CoverCommandRequest::message_type() const { return APIMessageType ::COVER_COMMAND_REQUEST; } +uint32_t CoverCommandRequest::get_key() const { return this->key_; } optional CoverCommandRequest::get_command() const { if (!this->has_state_) return {}; @@ -94,12 +89,8 @@ bool FanCommandRequest::decode_32bit(uint32_t field_id, uint32_t value) { return false; } } -APIMessageType FanCommandRequest::message_type() const { - return APIMessageType::FAN_COMMAND_REQUEST; -} -uint32_t FanCommandRequest::get_key() const { - return this->key_; -} +APIMessageType FanCommandRequest::message_type() const { return APIMessageType::FAN_COMMAND_REQUEST; } +uint32_t FanCommandRequest::get_key() const { return this->key_; } optional FanCommandRequest::get_state() const { if (!this->has_state_) return {}; @@ -212,12 +203,8 @@ bool LightCommandRequest::decode_32bit(uint32_t field_id, uint32_t value) { return false; } } -APIMessageType LightCommandRequest::message_type() const { - return APIMessageType::LIGHT_COMMAND_REQUEST; -} -uint32_t LightCommandRequest::get_key() const { - return this->key_; -} +APIMessageType LightCommandRequest::message_type() const { return APIMessageType::LIGHT_COMMAND_REQUEST; } +uint32_t LightCommandRequest::get_key() const { return this->key_; } optional LightCommandRequest::get_state() const { if (!this->has_state_) return {}; @@ -291,19 +278,13 @@ bool SwitchCommandRequest::decode_32bit(uint32_t field_id, uint32_t value) { return false; } } -APIMessageType SwitchCommandRequest::message_type() const { - return APIMessageType::SWITCH_COMMAND_REQUEST; -} -uint32_t SwitchCommandRequest::get_key() const { - return this->key_; -} -bool SwitchCommandRequest::get_state() const { - return this->state_; -} +APIMessageType SwitchCommandRequest::message_type() const { return APIMessageType::SWITCH_COMMAND_REQUEST; } +uint32_t SwitchCommandRequest::get_key() const { return this->key_; } +bool SwitchCommandRequest::get_state() const { return this->state_; } #endif -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/command_messages.h b/src/esphome/api/command_messages.h index 5b4bb698..1b434d4e 100644 --- a/src/esphome/api/command_messages.h +++ b/src/esphome/api/command_messages.h @@ -20,6 +20,7 @@ class CoverCommandRequest : public APIMessage { APIMessageType message_type() const override; uint32_t get_key() const; optional get_command() const; + protected: uint32_t key_{0}; bool has_state_{false}; @@ -99,16 +100,17 @@ class SwitchCommandRequest : public APIMessage { APIMessageType message_type() const override; uint32_t get_key() const; bool get_state() const; + protected: uint32_t key_{0}; bool state_{false}; }; #endif -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_API_COMMAND_MESSAGES_H +#endif // ESPHOME_API_COMMAND_MESSAGES_H diff --git a/src/esphome/api/list_entities.cpp b/src/esphome/api/list_entities.cpp index c08c1257..afccad23 100644 --- a/src/esphome/api/list_entities.cpp +++ b/src/esphome/api/list_entities.cpp @@ -98,15 +98,15 @@ bool ListEntitiesIterator::on_sensor(sensor::Sensor *sensor) { } #endif #ifdef USE_SWITCH -bool ListEntitiesIterator::on_switch(switch_::Switch *switch_) { +bool ListEntitiesIterator::on_switch(switch_::Switch *a_switch) { auto buffer = this->client_->get_buffer(); - buffer.encode_nameable(switch_); + buffer.encode_nameable(a_switch); // string unique_id = 4; - buffer.encode_string(4, get_default_unique_id("switch", switch_)); + buffer.encode_string(4, get_default_unique_id("switch", a_switch)); // string icon = 5; - buffer.encode_string(5, switch_->get_icon()); + buffer.encode_string(5, a_switch->get_icon()); // bool assumed_state = 6; - buffer.encode_bool(6, switch_->assumed_state()); + buffer.encode_bool(6, a_switch->assumed_state()); return this->client_->send_buffer(APIMessageType::LIST_ENTITIES_SWITCH_RESPONSE); } #endif @@ -129,21 +129,17 @@ bool ListEntitiesIterator::on_end() { return this->client_->send_empty_message(APIMessageType::LIST_ENTITIES_DONE_RESPONSE); } ListEntitiesIterator::ListEntitiesIterator(APIServer *server, APIConnection *client) - : ComponentIterator(server), client_(client) { - -} + : ComponentIterator(server), client_(client) {} bool ListEntitiesIterator::on_service(UserServiceDescriptor *service) { auto buffer = this->client_->get_buffer(); service->encode_list_service_response(buffer); - return this->client_->send_buffer(APIMessageType::LIST_SERVICES_SERVICE_RESPONSE); + return this->client_->send_buffer(APIMessageType::LIST_ENTITIES_SERVICE_RESPONSE); } -APIMessageType ListEntitiesRequest::message_type() const { - return APIMessageType::LIST_ENTITIES_REQUEST; -} +APIMessageType ListEntitiesRequest::message_type() const { return APIMessageType::LIST_ENTITIES_REQUEST; } -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/list_entities.h b/src/esphome/api/list_entities.h index 799bdba9..2a1b38d6 100644 --- a/src/esphome/api/list_entities.h +++ b/src/esphome/api/list_entities.h @@ -38,23 +38,24 @@ class ListEntitiesIterator : public ComponentIterator { bool on_sensor(sensor::Sensor *sensor) override; #endif #ifdef USE_SWITCH - bool on_switch(switch_::Switch *switch_) override; + bool on_switch(switch_::Switch *a_switch) override; #endif #ifdef USE_TEXT_SENSOR bool on_text_sensor(text_sensor::TextSensor *text_sensor) override; #endif bool on_service(UserServiceDescriptor *service) override; bool on_end() override; + protected: APIConnection *client_; }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END #include "esphome/api/api_server.h" -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_LIST_ENTITIES_H +#endif // ESPHOME_LIST_ENTITIES_H diff --git a/src/esphome/api/service_call_message.cpp b/src/esphome/api/service_call_message.cpp index 9671c4ea..900e68ab 100644 --- a/src/esphome/api/service_call_message.cpp +++ b/src/esphome/api/service_call_message.cpp @@ -13,9 +13,7 @@ APIMessageType SubscribeServiceCallsRequest::message_type() const { return APIMessageType::SUBSCRIBE_SERVICE_CALLS_REQUEST; } -APIMessageType ServiceCallResponse::message_type() const { - return APIMessageType::SERVICE_CALL_RESPONSE; -} +APIMessageType ServiceCallResponse::message_type() const { return APIMessageType::SERVICE_CALL_RESPONSE; } void ServiceCallResponse::encode(APIBuffer &buffer) { // string service = 1; buffer.encode_string(1, this->service_); @@ -41,12 +39,8 @@ void ServiceCallResponse::encode(APIBuffer &buffer) { buffer.end_nested(nested); } } -void ServiceCallResponse::set_service(const std::string &service) { - this->service_ = service; -} -void ServiceCallResponse::set_data(const std::vector &data) { - this->data_ = data; -} +void ServiceCallResponse::set_service(const std::string &service) { this->service_ = service; } +void ServiceCallResponse::set_data(const std::vector &data) { this->data_ = data; } void ServiceCallResponse::set_data_template(const std::vector &data_template) { this->data_template_ = data_template; } @@ -54,11 +48,9 @@ void ServiceCallResponse::set_variables(const std::vectorvariables_ = variables; } -KeyValuePair::KeyValuePair(const std::string &key, const std::string &value) : key(key), value(value) { - -} -} // namespace api +KeyValuePair::KeyValuePair(const std::string &key, const std::string &value) : key(key), value(value) {} +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/service_call_message.h b/src/esphome/api/service_call_message.h index c1aaad78..2c014c09 100644 --- a/src/esphome/api/service_call_message.h +++ b/src/esphome/api/service_call_message.h @@ -28,17 +28,13 @@ class KeyValuePair { class TemplatableKeyValuePair { public: - template - TemplatableKeyValuePair(std::string key, T func); + template TemplatableKeyValuePair(std::string key, T func); std::string key; std::function value; }; -template -TemplatableKeyValuePair::TemplatableKeyValuePair(std::string key, T func) : key(key) { - this->value = [func]() -> std::string { - return to_string(func()); - }; +template TemplatableKeyValuePair::TemplatableKeyValuePair(std::string key, T func) : key(key) { + this->value = [func]() -> std::string { return to_string(func()); }; } class ServiceCallResponse : public APIMessage { @@ -59,10 +55,10 @@ class ServiceCallResponse : public APIMessage { std::vector variables_; }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_API_SERVICE_CALL_MESSAGE_H +#endif // ESPHOME_API_SERVICE_CALL_MESSAGE_H diff --git a/src/esphome/api/subscribe_logs.cpp b/src/esphome/api/subscribe_logs.cpp index dc40c6d2..b3c7e524 100644 --- a/src/esphome/api/subscribe_logs.cpp +++ b/src/esphome/api/subscribe_logs.cpp @@ -9,35 +9,25 @@ ESPHOME_NAMESPACE_BEGIN namespace api { -APIMessageType SubscribeLogsRequest::message_type() const { - return APIMessageType::SUBSCRIBE_LOGS_REQUEST; -} +APIMessageType SubscribeLogsRequest::message_type() const { return APIMessageType::SUBSCRIBE_LOGS_REQUEST; } bool SubscribeLogsRequest::decode_varint(uint32_t field_id, uint32_t value) { switch (field_id) { - case 1: // LogLevel level = 1; + case 1: // LogLevel level = 1; this->level_ = value; return true; - case 2: // bool dump_config = 2; + case 2: // bool dump_config = 2; this->dump_config_ = value; return true; default: return false; } } -uint32_t SubscribeLogsRequest::get_level() const { - return this->level_; -} -void SubscribeLogsRequest::set_level(uint32_t level) { - this->level_ = level; -} -bool SubscribeLogsRequest::get_dump_config() const { - return this->dump_config_; -} -void SubscribeLogsRequest::set_dump_config(bool dump_config) { - this->dump_config_ = dump_config; -} -} // namespace api +uint32_t SubscribeLogsRequest::get_level() const { return this->level_; } +void SubscribeLogsRequest::set_level(uint32_t level) { this->level_ = level; } +bool SubscribeLogsRequest::get_dump_config() const { return this->dump_config_; } +void SubscribeLogsRequest::set_dump_config(bool dump_config) { this->dump_config_ = dump_config; } +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/subscribe_logs.h b/src/esphome/api/subscribe_logs.h index 6b0609e0..4e2d54a6 100644 --- a/src/esphome/api/subscribe_logs.h +++ b/src/esphome/api/subscribe_logs.h @@ -20,15 +20,16 @@ class SubscribeLogsRequest : public APIMessage { void set_level(uint32_t level); bool get_dump_config() const; void set_dump_config(bool dump_config); + protected: uint32_t level_{6}; bool dump_config_{false}; }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_API_SUBSCRIBE_LOGS_H +#endif // ESPHOME_API_SUBSCRIBE_LOGS_H diff --git a/src/esphome/api/subscribe_state.cpp b/src/esphome/api/subscribe_state.cpp index f24e4579..49cfdf34 100644 --- a/src/esphome/api/subscribe_state.cpp +++ b/src/esphome/api/subscribe_state.cpp @@ -26,14 +26,10 @@ bool InitialStateIterator::on_cover(cover::Cover *cover) { } #endif #ifdef USE_FAN -bool InitialStateIterator::on_fan(fan::FanState *fan) { - return this->client_->send_fan_state(fan); -} +bool InitialStateIterator::on_fan(fan::FanState *fan) { return this->client_->send_fan_state(fan); } #endif #ifdef USE_LIGHT -bool InitialStateIterator::on_light(light::LightState *light) { - return this->client_->send_light_state(light); -} +bool InitialStateIterator::on_light(light::LightState *light) { return this->client_->send_light_state(light); } #endif #ifdef USE_SENSOR bool InitialStateIterator::on_sensor(sensor::Sensor *sensor) { @@ -44,8 +40,8 @@ bool InitialStateIterator::on_sensor(sensor::Sensor *sensor) { } #endif #ifdef USE_SWITCH -bool InitialStateIterator::on_switch(switch_::Switch *switch_) { - return this->client_->send_switch_state(switch_, switch_->state); +bool InitialStateIterator::on_switch(switch_::Switch *a_switch) { + return this->client_->send_switch_state(a_switch, a_switch->state); } #endif #ifdef USE_TEXT_SENSOR @@ -57,13 +53,9 @@ bool InitialStateIterator::on_text_sensor(text_sensor::TextSensor *text_sensor) } #endif InitialStateIterator::InitialStateIterator(APIServer *server, APIConnection *client) - : ComponentIterator(server), client_(client) { + : ComponentIterator(server), client_(client) {} -} - -APIMessageType SubscribeStatesRequest::message_type() const { - return APIMessageType::SUBSCRIBE_STATES_REQUEST; -} +APIMessageType SubscribeStatesRequest::message_type() const { return APIMessageType::SUBSCRIBE_STATES_REQUEST; } bool HomeAssistantStateResponse::decode_length_delimited(uint32_t field_id, const uint8_t *value, size_t len) { switch (field_id) { @@ -82,18 +74,14 @@ bool HomeAssistantStateResponse::decode_length_delimited(uint32_t field_id, cons APIMessageType HomeAssistantStateResponse::message_type() const { return APIMessageType::HOME_ASSISTANT_STATE_RESPONSE; } -const std::string &HomeAssistantStateResponse::get_entity_id() const { - return this->entity_id_; -} -const std::string &HomeAssistantStateResponse::get_state() const { - return this->state_; -} +const std::string &HomeAssistantStateResponse::get_entity_id() const { return this->entity_id_; } +const std::string &HomeAssistantStateResponse::get_state() const { return this->state_; } APIMessageType SubscribeHomeAssistantStatesRequest::message_type() const { return APIMessageType::SUBSCRIBE_HOME_ASSISTANT_STATES_REQUEST; } -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/subscribe_state.h b/src/esphome/api/subscribe_state.h index 5ba3d998..c0dabb57 100644 --- a/src/esphome/api/subscribe_state.h +++ b/src/esphome/api/subscribe_state.h @@ -40,7 +40,7 @@ class InitialStateIterator : public ComponentIterator { bool on_sensor(sensor::Sensor *sensor) override; #endif #ifdef USE_SWITCH - bool on_switch(switch_::Switch *switch_) override; + bool on_switch(switch_::Switch *a_switch) override; #endif #ifdef USE_TEXT_SENSOR bool on_text_sensor(text_sensor::TextSensor *text_sensor) override; @@ -60,17 +60,18 @@ class HomeAssistantStateResponse : public APIMessage { APIMessageType message_type() const override; const std::string &get_entity_id() const; const std::string &get_state() const; + protected: std::string entity_id_; std::string state_; }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END #include "esphome/api/api_server.h" -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_SUBSCRIBE_STATE_H +#endif // ESPHOME_SUBSCRIBE_STATE_H diff --git a/src/esphome/api/user_services.cpp b/src/esphome/api/user_services.cpp index 44d1d390..ce52775c 100644 --- a/src/esphome/api/user_services.cpp +++ b/src/esphome/api/user_services.cpp @@ -11,24 +11,18 @@ namespace api { static const char *TAG = "api.UserServices"; -template<> -bool ExecuteServiceArgument::get_value() { return this->value_bool_; } -template<> -int ExecuteServiceArgument::get_value() { return this->value_int_; } -template<> -float ExecuteServiceArgument::get_value() { return this->value_float_; } -template<> -std::string ExecuteServiceArgument::get_value() { return this->value_string_; } +template<> bool ExecuteServiceArgument::get_value() { return this->value_bool_; } +template<> int ExecuteServiceArgument::get_value() { return this->value_int_; } +template<> float ExecuteServiceArgument::get_value() { return this->value_float_; } +template<> std::string ExecuteServiceArgument::get_value() { return this->value_string_; } -APIMessageType ExecuteServiceArgument::message_type() const { - return APIMessageType::EXECUTE_SERVICE_REQUEST; -} +APIMessageType ExecuteServiceArgument::message_type() const { return APIMessageType::EXECUTE_SERVICE_REQUEST; } bool ExecuteServiceArgument::decode_varint(uint32_t field_id, uint32_t value) { switch (field_id) { - case 1: // bool bool_ = 1; + case 1: // bool bool_ = 1; this->value_bool_ = value; return true; - case 2: // int32 int_ = 2; + case 2: // int32 int_ = 2; this->value_int_ = value; return true; default: @@ -37,7 +31,7 @@ bool ExecuteServiceArgument::decode_varint(uint32_t field_id, uint32_t value) { } bool ExecuteServiceArgument::decode_32bit(uint32_t field_id, uint32_t value) { switch (field_id) { - case 3: // float float_ = 3; + case 3: // float float_ = 3; this->value_float_ = as_float(value); return true; default: @@ -46,7 +40,7 @@ bool ExecuteServiceArgument::decode_32bit(uint32_t field_id, uint32_t value) { } bool ExecuteServiceArgument::decode_length_delimited(uint32_t field_id, const uint8_t *value, size_t len) { switch (field_id) { - case 4: // string string_ = 4; + case 4: // string string_ = 4; this->value_string_ = as_string(value, len); return true; default: @@ -56,7 +50,7 @@ bool ExecuteServiceArgument::decode_length_delimited(uint32_t field_id, const ui bool ExecuteServiceRequest::decode_32bit(uint32_t field_id, uint32_t value) { switch (field_id) { - case 1: // fixed32 key = 1; + case 1: // fixed32 key = 1; this->key_ = value; return true; default: @@ -65,7 +59,7 @@ bool ExecuteServiceRequest::decode_32bit(uint32_t field_id, uint32_t value) { } bool ExecuteServiceRequest::decode_length_delimited(uint32_t field_id, const uint8_t *value, size_t len) { switch (field_id) { - case 2: { // repeated ExecuteServiceArgument args = 2; + case 2: { // repeated ExecuteServiceArgument args = 2; ExecuteServiceArgument arg; arg.decode(value, len); this->args_.push_back(arg); @@ -75,22 +69,16 @@ bool ExecuteServiceRequest::decode_length_delimited(uint32_t field_id, const uin return false; } } -APIMessageType ExecuteServiceRequest::message_type() const { - return APIMessageType::EXECUTE_SERVICE_REQUEST; -} -const std::vector &ExecuteServiceRequest::get_args() const { - return this->args_; -} -uint32_t ExecuteServiceRequest::get_key() const { - return this->key_; -} +APIMessageType ExecuteServiceRequest::message_type() const { return APIMessageType::EXECUTE_SERVICE_REQUEST; } +const std::vector &ExecuteServiceRequest::get_args() const { return this->args_; } +uint32_t ExecuteServiceRequest::get_key() const { return this->key_; } ServiceTypeArgument::ServiceTypeArgument(const std::string &name, ServiceArgType type) : name_(name), type_(type) {} const std::string &ServiceTypeArgument::get_name() const { return this->name_; } ServiceArgType ServiceTypeArgument::get_type() const { return this->type_; } -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/user_services.h b/src/esphome/api/user_services.h index c2408c47..c8a43330 100644 --- a/src/esphome/api/user_services.h +++ b/src/esphome/api/user_services.h @@ -67,8 +67,7 @@ class UserServiceDescriptor { virtual bool execute_service(const ExecuteServiceRequest &req) = 0; }; -template -class UserService : public UserServiceDescriptor, public Trigger { +template class UserService : public UserServiceDescriptor, public Trigger { public: UserService(const std::string &name, const std::array &args); @@ -77,11 +76,10 @@ class UserService : public UserServiceDescriptor, public Trigger { bool execute_service(const ExecuteServiceRequest &req) override; protected: - template - void execute_(std::vector args, seq); + template void execute_(std::vector args, seq); std::string name_; - uint32_t key_; + uint32_t key_{0}; std::array args_; }; @@ -90,8 +88,7 @@ template void UserService::execute_(std::vector args, seq) { this->trigger((args[S].get_value())...); } -template -void UserService::encode_list_service_response(APIBuffer &buffer) { +template void UserService::encode_list_service_response(APIBuffer &buffer) { // string name = 1; buffer.encode_string(1, this->name_); // fixed32 key = 2; @@ -107,8 +104,7 @@ void UserService::encode_list_service_response(APIBuffer &buffer) { buffer.end_nested(nested); } } -template -bool UserService::execute_service(const ExecuteServiceRequest &req) { +template bool UserService::execute_service(const ExecuteServiceRequest &req) { if (req.get_key() != this->key_) return false; @@ -130,10 +126,10 @@ template<> int ExecuteServiceArgument::get_value(); template<> float ExecuteServiceArgument::get_value(); template<> std::string ExecuteServiceArgument::get_value(); -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_CORE_API_USER_SERVICES_H +#endif // ESPHOME_CORE_API_USER_SERVICES_H diff --git a/src/esphome/api/util.cpp b/src/esphome/api/util.cpp index 1717e23d..cddf04eb 100644 --- a/src/esphome/api/util.cpp +++ b/src/esphome/api/util.cpp @@ -11,22 +11,15 @@ ESPHOME_NAMESPACE_BEGIN namespace api { -APIBuffer::APIBuffer(std::vector *buffer) - : buffer_(buffer) { - -} -size_t APIBuffer::get_length() const { - return this->buffer_->size(); -} -void APIBuffer::write(uint8_t value) { - this->buffer_->push_back(value); -} +APIBuffer::APIBuffer(std::vector *buffer) : buffer_(buffer) {} +size_t APIBuffer::get_length() const { return this->buffer_->size(); } +void APIBuffer::write(uint8_t value) { this->buffer_->push_back(value); } void APIBuffer::encode_uint32(uint32_t field, uint32_t value) { if (value == 0) return; - this->encode_field_(field, 0); - this->encode_varint_(value); + this->encode_field_raw(field, 0); + this->encode_varint_raw(value); } void APIBuffer::encode_int32(uint32_t field, int32_t value) { this->encode_uint32(field, static_cast(value)); @@ -35,7 +28,7 @@ void APIBuffer::encode_bool(uint32_t field, bool value) { if (!value) return; - this->encode_field_(field, 0); + this->encode_field_raw(field, 0); this->write(0x01); } void APIBuffer::encode_string(uint32_t field, const std::string &value) { @@ -45,8 +38,8 @@ void APIBuffer::encode_string(uint32_t field, const char *string, size_t len) { if (len == 0) return; - this->encode_field_(field, 2); - this->encode_varint_(len); + this->encode_field_raw(field, 2); + this->encode_varint_raw(len); const uint8_t *data = reinterpret_cast(string); for (size_t i = 0; i < len; i++) { this->write(data[i]); @@ -56,7 +49,7 @@ void APIBuffer::encode_fixed32(uint32_t field, uint32_t value) { if (value == 0) return; - this->encode_field_(field, 5); + this->encode_field_raw(field, 5); this->write((value >> 0) & 0xFF); this->write((value >> 8) & 0xFF); this->write((value >> 16) & 0xFF); @@ -73,11 +66,11 @@ void APIBuffer::encode_float(uint32_t field, float value) { val.value_f = value; this->encode_fixed32(field, val.value_raw); } -void APIBuffer::encode_field_(uint32_t field, uint32_t type) { +void APIBuffer::encode_field_raw(uint32_t field, uint32_t type) { uint32_t val = (field << 3) | (type & 0b111); - this->encode_varint_(val); + this->encode_varint_raw(val); } -void APIBuffer::encode_varint_(uint32_t value) { +void APIBuffer::encode_varint_raw(uint32_t value) { if (value <= 0x7F) { this->write(value); return; @@ -107,21 +100,8 @@ void APIBuffer::encode_nameable(Nameable *nameable) { // string name = 3; this->encode_string(3, nameable->get_name()); } -uint32_t APIBuffer::varint_length_(uint32_t value) { - if (value <= 0x7F) { - return 1; - } - - uint32_t bytes = 0; - while (value) { - value >>= 7; - bytes++; - } - - return bytes; -} size_t APIBuffer::begin_nested(uint32_t field) { - this->encode_field_(field, 2); + this->encode_field_raw(field, 2); return this->buffer_->size(); } void APIBuffer::end_nested(size_t begin_index) { @@ -187,9 +167,7 @@ float as_float(uint32_t val) { return x.value; } -ComponentIterator::ComponentIterator(APIServer *server) : server_(server) { - -} +ComponentIterator::ComponentIterator(APIServer *server) : server_(server) {} void ComponentIterator::begin() { this->state_ = IteratorState::BEGIN; this->at_ = 0; @@ -288,12 +266,12 @@ void ComponentIterator::advance() { if (this->at_ >= this->server_->switches_.size()) { advance_platform = true; } else { - auto *switch_ = this->server_->switches_[this->at_]; - if (switch_->is_internal()) { + auto *a_switch = this->server_->switches_[this->at_]; + if (a_switch->is_internal()) { success = true; break; } else { - success = this->on_switch(switch_); + success = this->on_switch(a_switch); } } break; @@ -335,18 +313,12 @@ void ComponentIterator::advance() { this->at_++; } } -bool ComponentIterator::on_end() { - return true; -} -bool ComponentIterator::on_begin() { - return true; -} -bool ComponentIterator::on_service(UserServiceDescriptor *service) { - -} +bool ComponentIterator::on_end() { return true; } +bool ComponentIterator::on_begin() { return true; } +bool ComponentIterator::on_service(UserServiceDescriptor *service) { return true; } -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API diff --git a/src/esphome/api/util.h b/src/esphome/api/util.h index b9c6a81c..02008f30 100644 --- a/src/esphome/api/util.h +++ b/src/esphome/api/util.h @@ -33,9 +33,8 @@ class APIBuffer { size_t begin_nested(uint32_t field); void end_nested(size_t begin_index); - void encode_field_(uint32_t field, uint32_t type); - void encode_varint_(uint32_t value); - uint32_t varint_length_(uint32_t value); + void encode_field_raw(uint32_t field, uint32_t type); + void encode_varint_raw(uint32_t value); protected: std::vector *buffer_; @@ -73,7 +72,7 @@ class ComponentIterator { virtual bool on_sensor(sensor::Sensor *sensor) = 0; #endif #ifdef USE_SWITCH - virtual bool on_switch(switch_::Switch *switch_) = 0; + virtual bool on_switch(switch_::Switch *a_switch) = 0; #endif #ifdef USE_TEXT_SENSOR virtual bool on_text_sensor(text_sensor::TextSensor *text_sensor) = 0; @@ -114,10 +113,10 @@ class ComponentIterator { APIServer *server_; }; -} // namespace api +} // namespace api ESPHOME_NAMESPACE_END -#endif //USE_API +#endif // USE_API -#endif //ESPHOME_API_UTIL_H +#endif // ESPHOME_API_UTIL_H diff --git a/src/esphome/application.cpp b/src/esphome/application.cpp index cc6c3e22..291c1ac5 100644 --- a/src/esphome/application.cpp +++ b/src/esphome/application.cpp @@ -63,19 +63,18 @@ void Application::setup() { if (component->is_failed()) continue; - component->setup_(); + component->call_setup(); if (component->can_proceed()) continue; - std::stable_sort(this->components_.begin(), this->components_.begin() + i + 1, [](Component *a, Component *b) { - return a->get_loop_priority() > b->get_loop_priority(); - }); + std::stable_sort(this->components_.begin(), this->components_.begin() + i + 1, + [](Component *a, Component *b) { return a->get_loop_priority() > b->get_loop_priority(); }); do { uint32_t new_global_state = STATUS_LED_WARNING; for (uint32_t j = 0; j <= i; j++) { if (!this->components_[j]->is_failed()) { - this->components_[j]->loop_(); + this->components_[j]->call_loop(); } new_global_state |= this->components_[j]->get_component_state(); global_state |= new_global_state; @@ -98,14 +97,11 @@ void Application::dump_config() { ESP_LOGI(TAG, "esphome-core version " ESPHOME_VERSION " compiled on %s", this->compilation_time_.c_str()); } - for (uint32_t i = 0; i < this->components_.size(); i++) { - Component *component = this->components_[i]; + for (auto component : this->components_) { component->dump_config(); } } -void Application::schedule_dump_config() { - this->dump_config_scheduled_ = true; -} +void Application::schedule_dump_config() { this->dump_config_scheduled_ = true; } void HOT Application::loop() { bool first_loop = this->application_state_ == COMPONENT_STATE_SETUP; @@ -117,7 +113,7 @@ void HOT Application::loop() { uint32_t new_global_state = 0; for (Component *component : this->components_) { if (!component->is_failed()) { - component->loop_(); + component->call_loop(); } new_global_state |= component->get_component_state(); global_state |= new_global_state; @@ -167,22 +163,20 @@ void Application::set_name(const std::string &name) { global_preferences.begin(name); } -void Application::set_compilation_datetime(const char *str) { - this->compilation_time_ = str; -} -const std::string &Application::get_compilation_time() const { - return this->compilation_time_; -} +void Application::set_compilation_datetime(const char *str) { this->compilation_time_ = str; } +const std::string &Application::get_compilation_time() const { return this->compilation_time_; } #ifdef USE_MQTT -MQTTClientComponent *Application::init_mqtt(const std::string &address, uint16_t port, - const std::string &username, const std::string &password) { - MQTTClientComponent *component = new MQTTClientComponent(MQTTCredentials{ - .address = address, - .port = port, - .username = username, - .password = password, - }, this->get_name()); +MQTTClientComponent *Application::init_mqtt(const std::string &address, uint16_t port, const std::string &username, + const std::string &password) { + MQTTClientComponent *component = new MQTTClientComponent( + MQTTCredentials{ + .address = address, + .port = port, + .username = username, + .password = password, + }, + this->get_name()); this->mqtt_client_ = component; return this->register_component(component); @@ -190,23 +184,20 @@ MQTTClientComponent *Application::init_mqtt(const std::string &address, uint16_t #endif #ifdef USE_MQTT -MQTTClientComponent *Application::init_mqtt(const std::string &address, - const std::string &username, const std::string &password) { +MQTTClientComponent *Application::init_mqtt(const std::string &address, const std::string &username, + const std::string &password) { return this->init_mqtt(address, 1883, username, password); } #endif -LogComponent *Application::init_log(uint32_t baud_rate, - size_t tx_buffer_size, - UARTSelection uart) { +LogComponent *Application::init_log(uint32_t baud_rate, size_t tx_buffer_size, UARTSelection uart) { auto *log = new LogComponent(baud_rate, tx_buffer_size, uart); log->pre_setup(); return this->register_component(log); } #ifdef USE_OUTPUT -PowerSupplyComponent *Application::make_power_supply(const GPIOOutputPin &pin, - uint32_t enable_time, +PowerSupplyComponent *Application::make_power_supply(const GPIOOutputPin &pin, uint32_t enable_time, uint32_t keep_on_time) { auto *atx = new PowerSupplyComponent(pin.copy(), enable_time, keep_on_time); return this->register_component(atx); @@ -238,8 +229,7 @@ GPIOBinarySensorComponent *Application::make_gpio_binary_sensor(const std::strin #ifdef USE_DHT_SENSOR DHTComponent *Application::make_dht_sensor(const std::string &temperature_friendly_name, - const std::string &humidity_friendly_name, - const GPIOOutputPin &pin, + const std::string &humidity_friendly_name, const GPIOOutputPin &pin, uint32_t check_interval) { auto *dht = new DHTComponent(temperature_friendly_name, humidity_friendly_name, pin.copy(), check_interval); this->register_component(dht); @@ -276,26 +266,23 @@ PCA9685OutputComponent *Application::make_pca9685_component(float frequency) { #endif #ifdef USE_MY9231_OUTPUT -MY9231OutputComponent *Application::make_my9231_component(const GPIOOutputPin &pin_di, - const GPIOOutputPin &pin_dcki) { +MY9231OutputComponent *Application::make_my9231_component(const GPIOOutputPin &pin_di, const GPIOOutputPin &pin_dcki) { auto *my9231 = new MY9231OutputComponent(pin_di.copy(), pin_dcki.copy()); return this->register_component(my9231); } #endif #ifdef USE_LIGHT -Application::MakeLight Application::make_rgb_light(const std::string &friendly_name, - FloatOutput *red, FloatOutput *green, FloatOutput *blue) { +Application::MakeLight Application::make_rgb_light(const std::string &friendly_name, FloatOutput *red, + FloatOutput *green, FloatOutput *blue) { auto *out = new RGBLightOutput(red, green, blue); return this->make_light_for_light_output(friendly_name, out); } #endif #ifdef USE_LIGHT -Application::MakeLight Application::make_rgbw_light(const std::string &friendly_name, - output::FloatOutput *red, - output::FloatOutput *green, - output::FloatOutput *blue, +Application::MakeLight Application::make_rgbw_light(const std::string &friendly_name, output::FloatOutput *red, + output::FloatOutput *green, output::FloatOutput *blue, output::FloatOutput *white) { auto *out = new RGBWLightOutput(red, green, blue, white); return this->make_light_for_light_output(friendly_name, out); @@ -303,25 +290,18 @@ Application::MakeLight Application::make_rgbw_light(const std::string &friendly_ #endif #ifdef USE_LIGHT -Application::MakeLight Application::make_rgbww_light(const std::string &friendly_name, - float cold_white_mireds, - float warm_white_mireds, - output::FloatOutput *red, - output::FloatOutput *green, - output::FloatOutput *blue, - output::FloatOutput *cold_white, - output::FloatOutput *warm_white) { - auto *out = new RGBWWLightOutput(cold_white_mireds, warm_white_mireds, - red, green, blue, cold_white, warm_white); +Application::MakeLight Application::make_rgbww_light(const std::string &friendly_name, float cold_white_mireds, + float warm_white_mireds, output::FloatOutput *red, + output::FloatOutput *green, output::FloatOutput *blue, + output::FloatOutput *cold_white, output::FloatOutput *warm_white) { + auto *out = new RGBWWLightOutput(cold_white_mireds, warm_white_mireds, red, green, blue, cold_white, warm_white); return this->make_light_for_light_output(friendly_name, out); } #endif #ifdef USE_LIGHT -Application::MakeLight Application::make_cwww_light(const std::string &friendly_name, - float cold_white_mireds, - float warm_white_mireds, - output::FloatOutput *cold_white, +Application::MakeLight Application::make_cwww_light(const std::string &friendly_name, float cold_white_mireds, + float warm_white_mireds, output::FloatOutput *cold_white, output::FloatOutput *warm_white) { auto *out = new CWWWLightOutput(cold_white_mireds, warm_white_mireds, cold_white, warm_white); return this->make_light_for_light_output(friendly_name, out); @@ -340,14 +320,10 @@ void Application::register_light(LightState *state) { } #endif -WiFiComponent *Application::get_wifi() const { - return this->wifi_; -} +WiFiComponent *Application::get_wifi() const { return this->wifi_; } #ifdef USE_OTA -OTAComponent *Application::init_ota() { - return this->register_component(new OTAComponent()); -} +OTAComponent *Application::init_ota() { return this->register_component(new OTAComponent()); } #endif #ifdef USE_LIGHT @@ -359,8 +335,7 @@ Application::MakeLight Application::make_monochromatic_light(const std::string & #endif #ifdef USE_LIGHT -Application::MakeLight Application::make_binary_light(const std::string &friendly_name, - output::BinaryOutput *binary) { +Application::MakeLight Application::make_binary_light(const std::string &friendly_name, output::BinaryOutput *binary) { auto *out = new BinaryLightOutput(binary); return this->make_light_for_light_output(friendly_name, out); } @@ -379,18 +354,16 @@ Application::MakeLight Application::make_light_for_light_output(const std::strin #endif #ifdef USE_MQTT -MQTTClientComponent *Application::get_mqtt_client() const { - return this->mqtt_client_; -} +MQTTClientComponent *Application::get_mqtt_client() const { return this->mqtt_client_; } #endif #ifdef USE_SWITCH -void Application::register_switch(switch_::Switch *switch_) { +void Application::register_switch(switch_::Switch *a_switch) { for (auto *controller : this->controllers_) - controller->register_switch(switch_); + controller->register_switch(a_switch); #ifdef USE_MQTT_SWITCH if (this->mqtt_client_ != nullptr) { - switch_->set_mqtt(this->register_component(new MQTTSwitchComponent(switch_))); + a_switch->set_mqtt(this->register_component(new MQTTSwitchComponent(a_switch))); } #endif } @@ -406,17 +379,14 @@ DallasComponent *Application::make_dallas_component(const GPIOOutputPin &pin, ui #endif #ifdef USE_GPIO_SWITCH -switch_::GPIOSwitch *Application::make_gpio_switch(const std::string &friendly_name, - const GPIOOutputPin &pin) { +switch_::GPIOSwitch *Application::make_gpio_switch(const std::string &friendly_name, const GPIOOutputPin &pin) { auto gpio_switch = this->register_component(new GPIOSwitch(friendly_name, pin.copy())); this->register_switch(gpio_switch); return gpio_switch; } #endif -const std::string &Application::get_name() const { - return this->name_; -} +const std::string &Application::get_name() const { return this->name_; } #ifdef USE_FAN Application::MakeFan Application::make_fan(const std::string &friendly_name) { @@ -446,8 +416,7 @@ sensor::PulseCounterSensorComponent *Application::make_pulse_counter_sensor(cons #endif #ifdef USE_ADC_SENSOR -sensor::ADCSensorComponent *Application::make_adc_sensor(const std::string &friendly_name, - uint8_t pin, +sensor::ADCSensorComponent *Application::make_adc_sensor(const std::string &friendly_name, uint8_t pin, uint32_t update_interval) { auto *adc = this->register_component(new ADCSensorComponent(friendly_name, pin, update_interval)); this->register_sensor(adc); @@ -461,16 +430,14 @@ sensor::UltrasonicSensorComponent *Application::make_ultrasonic_sensor(const std const GPIOInputPin &echo_pin, uint32_t update_interval) { auto *ultrasonic = this->register_component( - new UltrasonicSensorComponent(friendly_name, trigger_pin.copy(), echo_pin.copy(), update_interval) - ); + new UltrasonicSensorComponent(friendly_name, trigger_pin.copy(), echo_pin.copy(), update_interval)); this->register_sensor(ultrasonic); return ultrasonic; } #endif #ifdef USE_WIFI_SIGNAL_SENSOR -sensor::WiFiSignalSensor *Application::make_wifi_signal_sensor(const std::string &name, - uint32_t update_interval) { +sensor::WiFiSignalSensor *Application::make_wifi_signal_sensor(const std::string &name, uint32_t update_interval) { auto *wifi = this->register_component(new WiFiSignalSensor(name, update_interval)); this->register_sensor(wifi); return wifi; @@ -488,10 +455,7 @@ sensor::BMP085Component *Application::make_bmp085_sensor(const std::string &temp const std::string &pressure_friendly_name, uint32_t update_interval) { auto *bmp = this->register_component( - new BMP085Component(this->i2c_, - temperature_friendly_name, pressure_friendly_name, - update_interval) - ); + new BMP085Component(this->i2c_, temperature_friendly_name, pressure_friendly_name, update_interval)); this->register_sensor(bmp->get_temperature_sensor()); this->register_sensor(bmp->get_pressure_sensor()); return bmp; @@ -503,9 +467,7 @@ sensor::HTU21DComponent *Application::make_htu21d_sensor(const std::string &temp const std::string &humidity_friendly_name, uint32_t update_interval) { auto *htu21d = this->register_component( - new HTU21DComponent(this->i2c_, temperature_friendly_name, humidity_friendly_name, - update_interval) - ); + new HTU21DComponent(this->i2c_, temperature_friendly_name, humidity_friendly_name, update_interval)); this->register_sensor(htu21d->get_temperature_sensor()); this->register_sensor(htu21d->get_humidity_sensor()); return htu21d; @@ -539,23 +501,23 @@ StatusBinarySensor *Application::make_status_binary_sensor(const std::string &fr #ifdef USE_RESTART_SWITCH switch_::RestartSwitch *Application::make_restart_switch(const std::string &friendly_name) { - auto *switch_ = this->register_component(new RestartSwitch(friendly_name)); - this->register_switch(switch_); - return switch_; + auto *a_switch = this->register_component(new RestartSwitch(friendly_name)); + this->register_switch(a_switch); + return a_switch; } #endif #ifdef USE_SHUTDOWN_SWITCH switch_::ShutdownSwitch *Application::make_shutdown_switch(const std::string &friendly_name) { - auto *switch_ = this->register_component(new ShutdownSwitch(friendly_name)); - this->register_switch(switch_); - return switch_; + auto *a_switch = this->register_component(new ShutdownSwitch(friendly_name)); + this->register_switch(a_switch); + return a_switch; } #endif #ifdef USE_ESP8266_PWM_OUTPUT -ESP8266PWMOutput *Application::make_esp8266_pwm_output(GPIOOutputPin pin_) { - return this->register_component(new ESP8266PWMOutput(pin_)); +ESP8266PWMOutput *Application::make_esp8266_pwm_output(GPIOOutputPin pin) { + return this->register_component(new ESP8266PWMOutput(pin)); } #endif @@ -564,10 +526,7 @@ sensor::HDC1080Component *Application::make_hdc1080_sensor(const std::string &te const std::string &humidity_friendly_name, uint32_t update_interval) { auto *hdc1080 = this->register_component( - new HDC1080Component(this->i2c_, - temperature_friendly_name, humidity_friendly_name, - update_interval) - ); + new HDC1080Component(this->i2c_, temperature_friendly_name, humidity_friendly_name, update_interval)); this->register_sensor(hdc1080->get_temperature_sensor()); this->register_sensor(hdc1080->get_humidity_sensor()); return hdc1080; @@ -575,9 +534,7 @@ sensor::HDC1080Component *Application::make_hdc1080_sensor(const std::string &te #endif #ifdef USE_DEBUG_COMPONENT -DebugComponent *Application::make_debug_component() { - return this->register_component(new DebugComponent()); -} +DebugComponent *Application::make_debug_component() { return this->register_component(new DebugComponent()); } #endif #ifdef USE_FAN @@ -633,8 +590,7 @@ switch_::OutputSwitch *Application::make_output_switch(const std::string &friend #endif #ifdef USE_TSL2561 -sensor::TSL2561Sensor *Application::make_tsl2561_sensor(const std::string &name, - uint8_t address, +sensor::TSL2561Sensor *Application::make_tsl2561_sensor(const std::string &name, uint8_t address, uint32_t update_interval) { auto *tsl = this->register_component(new TSL2561Sensor(this->i2c_, name, address, update_interval)); this->register_sensor(tsl); @@ -643,8 +599,7 @@ sensor::TSL2561Sensor *Application::make_tsl2561_sensor(const std::string &name, #endif #ifdef USE_BH1750 -sensor::BH1750Sensor *Application::make_bh1750_sensor(const std::string &name, - uint8_t address, +sensor::BH1750Sensor *Application::make_bh1750_sensor(const std::string &name, uint8_t address, uint32_t update_interval) { auto *bh1750 = this->register_component(new BH1750Sensor(this->i2c_, name, address, update_interval)); this->register_sensor(bh1750); @@ -655,14 +610,10 @@ sensor::BH1750Sensor *Application::make_bh1750_sensor(const std::string &name, #ifdef USE_BME280 sensor::BME280Component *Application::make_bme280_sensor(const std::string &temperature_name, const std::string &pressure_name, - const std::string &humidity_name, - uint8_t address, + const std::string &humidity_name, uint8_t address, uint32_t update_interval) { auto *bme280 = this->register_component( - new BME280Component(this->i2c_, - temperature_name, pressure_name, humidity_name, - address, update_interval) - ); + new BME280Component(this->i2c_, temperature_name, pressure_name, humidity_name, address, update_interval)); this->register_sensor(bme280->get_temperature_sensor()); this->register_sensor(bme280->get_pressure_sensor()); this->register_sensor(bme280->get_humidity_sensor()); @@ -672,14 +623,10 @@ sensor::BME280Component *Application::make_bme280_sensor(const std::string &temp #ifdef USE_BMP280 sensor::BMP280Component *Application::make_bmp280_sensor(const std::string &temperature_name, - const std::string &pressure_name, - uint8_t address, + const std::string &pressure_name, uint8_t address, uint32_t update_interval) { auto *bmp280 = this->register_component( - new BMP280Component(this->i2c_, - temperature_name, pressure_name, - address, update_interval) - ); + new BMP280Component(this->i2c_, temperature_name, pressure_name, address, update_interval)); this->register_sensor(bmp280->get_temperature_sensor()); this->register_sensor(bmp280->get_pressure_sensor()); return bmp280; @@ -690,14 +637,10 @@ sensor::BMP280Component *Application::make_bmp280_sensor(const std::string &temp sensor::BME680Component *Application::make_bme680_sensor(const std::string &temperature_name, const std::string &pressure_name, const std::string &humidity_name, - const std::string &gas_resistance_name, - uint8_t address, + const std::string &gas_resistance_name, uint8_t address, uint32_t update_interval) { - auto *bme680 = this->register_component( - new BME680Component(this->i2c_, - temperature_name, pressure_name, humidity_name, gas_resistance_name, - address, update_interval) - ); + auto *bme680 = this->register_component(new BME680Component( + this->i2c_, temperature_name, pressure_name, humidity_name, gas_resistance_name, address, update_interval)); this->register_sensor(bme680->get_temperature_sensor()); this->register_sensor(bme680->get_pressure_sensor()); this->register_sensor(bme680->get_humidity_sensor()); @@ -708,14 +651,10 @@ sensor::BME680Component *Application::make_bme680_sensor(const std::string &temp #ifdef USE_SHT3XD sensor::SHT3XDComponent *Application::make_sht3xd_sensor(const std::string &temperature_name, - const std::string &humidity_name, - uint8_t address, + const std::string &humidity_name, uint8_t address, uint32_t update_interval) { auto *sht3xd = this->register_component( - new SHT3XDComponent(this->i2c_, - temperature_name, humidity_name, - address, update_interval) - ); + new SHT3XDComponent(this->i2c_, temperature_name, humidity_name, address, update_interval)); this->register_sensor(sht3xd->get_temperature_sensor()); this->register_sensor(sht3xd->get_humidity_sensor()); return sht3xd; @@ -729,9 +668,7 @@ ESP32TouchComponent *Application::make_esp32_touch_component() { #endif #ifdef USE_ESP32_BLE_TRACKER -ESP32BLETracker *Application::make_esp32_ble_tracker() { - return this->register_component(new ESP32BLETracker()); -} +ESP32BLETracker *Application::make_esp32_ble_tracker() { return this->register_component(new ESP32BLETracker()); } #endif #ifdef USE_FAST_LED_LIGHT @@ -748,11 +685,9 @@ Application::MakeFastLEDLight Application::make_fast_led_light(const std::string #ifdef USE_DHT12_SENSOR sensor::DHT12Component *Application::make_dht12_sensor(const std::string &temperature_name, - const std::string &humidity_name, - uint32_t update_interval) { - auto *dht12 = this->register_component( - new DHT12Component(this->i2c_, temperature_name, humidity_name, update_interval) - ); + const std::string &humidity_name, uint32_t update_interval) { + auto *dht12 = + this->register_component(new DHT12Component(this->i2c_, temperature_name, humidity_name, update_interval)); this->register_sensor(dht12->get_temperature_sensor()); this->register_sensor(dht12->get_humidity_sensor()); return dht12; @@ -760,8 +695,7 @@ sensor::DHT12Component *Application::make_dht12_sensor(const std::string &temper #endif #ifdef USE_ROTARY_ENCODER_SENSOR -sensor::RotaryEncoderSensor *Application::make_rotary_encoder_sensor(const std::string &name, - const GPIOInputPin &pin_a, +sensor::RotaryEncoderSensor *Application::make_rotary_encoder_sensor(const std::string &name, const GPIOInputPin &pin_a, const GPIOInputPin &pin_b) { auto *encoder = this->register_component(new RotaryEncoderSensor(name, pin_a.copy(), pin_b.copy())); this->register_sensor(encoder); @@ -769,44 +703,31 @@ sensor::RotaryEncoderSensor *Application::make_rotary_encoder_sensor(const std:: } #endif -StartupTrigger *Application::make_startup_trigger() { - return this->register_component(new StartupTrigger()); -} +StartupTrigger *Application::make_startup_trigger() { return this->register_component(new StartupTrigger()); } -ShutdownTrigger *Application::make_shutdown_trigger() { - return new ShutdownTrigger(); -} +ShutdownTrigger *Application::make_shutdown_trigger() { return new ShutdownTrigger(); } #ifdef USE_TEMPLATE_SENSOR -sensor::TemplateSensor *Application::make_template_sensor(const std::string &name, - uint32_t update_interval) { - auto *template_ = this->register_component(new TemplateSensor(name, update_interval)); - this->register_sensor(template_); - return template_; +sensor::TemplateSensor *Application::make_template_sensor(const std::string &name, uint32_t update_interval) { + auto *a_template = this->register_component(new TemplateSensor(name, update_interval)); + this->register_sensor(a_template); + return a_template; } #endif #ifdef USE_MAX31855_SENSOR -sensor::MAX31855Sensor *Application::make_max31855_sensor(const std::string &name, - SPIComponent *spi_bus, - const GPIOOutputPin &cs, - uint32_t update_interval) { - auto *sensor = this->register_component( - new MAX31855Sensor(name, spi_bus, cs.copy(), update_interval) - ); +sensor::MAX31855Sensor *Application::make_max31855_sensor(const std::string &name, SPIComponent *spi_bus, + const GPIOOutputPin &cs, uint32_t update_interval) { + auto *sensor = this->register_component(new MAX31855Sensor(name, spi_bus, cs.copy(), update_interval)); this->register_sensor(sensor); return sensor; } #endif #ifdef USE_MAX6675_SENSOR -sensor::MAX6675Sensor *Application::make_max6675_sensor(const std::string &name, - SPIComponent *spi_bus, - const GPIOOutputPin &cs, - uint32_t update_interval) { - auto *sensor = this->register_component( - new MAX6675Sensor(name, spi_bus, cs.copy(), update_interval) - ); +sensor::MAX6675Sensor *Application::make_max6675_sensor(const std::string &name, SPIComponent *spi_bus, + const GPIOOutputPin &cs, uint32_t update_interval) { + auto *sensor = this->register_component(new MAX6675Sensor(name, spi_bus, cs.copy(), update_interval)); this->register_sensor(sensor); return sensor; } @@ -814,17 +735,17 @@ sensor::MAX6675Sensor *Application::make_max6675_sensor(const std::string &name, #ifdef USE_TEMPLATE_BINARY_SENSOR binary_sensor::TemplateBinarySensor *Application::make_template_binary_sensor(const std::string &name) { - auto *template_ = this->register_component(new TemplateBinarySensor(name)); - this->register_binary_sensor(template_); - return template_; + auto *a_template = this->register_component(new TemplateBinarySensor(name)); + this->register_binary_sensor(a_template); + return a_template; } #endif #ifdef USE_TEMPLATE_SWITCH switch_::TemplateSwitch *Application::make_template_switch(const std::string &name) { - auto *template_ = this->register_component(new TemplateSwitch(name)); - this->register_switch(template_); - return template_; + auto *a_template = this->register_component(new TemplateSwitch(name)); + this->register_switch(a_template); + return a_template; } #endif @@ -861,8 +782,7 @@ remote::RemoteReceiverComponent *Application::make_remote_receiver_component(con #endif #ifdef USE_DUTY_CYCLE_SENSOR -sensor::DutyCycleSensor *Application::make_duty_cycle_sensor(const std::string &name, - const GPIOInputPin &pin, +sensor::DutyCycleSensor *Application::make_duty_cycle_sensor(const std::string &name, const GPIOInputPin &pin, uint32_t update_interval) { auto *duty = this->register_component(new DutyCycleSensor(name, pin.copy(), update_interval)); this->register_sensor(duty); @@ -871,8 +791,7 @@ sensor::DutyCycleSensor *Application::make_duty_cycle_sensor(const std::string & #endif #ifdef USE_ESP32_HALL_SENSOR -sensor::ESP32HallSensor *Application::make_esp32_hall_sensor(const std::string &name, - uint32_t update_interval) { +sensor::ESP32HallSensor *Application::make_esp32_hall_sensor(const std::string &name, uint32_t update_interval) { auto *hall = this->register_component(new ESP32HallSensor(name, update_interval)); this->register_sensor(hall); return hall; @@ -892,8 +811,7 @@ StatusLEDComponent *Application::make_status_led(const GPIOOutputPin &pin) { #endif #ifdef USE_MHZ19 -sensor::MHZ19Component *Application::make_mhz19_sensor(UARTComponent *parent, - const std::string &co2_name, +sensor::MHZ19Component *Application::make_mhz19_sensor(UARTComponent *parent, const std::string &co2_name, uint32_t update_interval) { auto *mhz19 = this->register_component(new MHZ19Component(parent, co2_name, update_interval)); this->register_sensor(mhz19->get_co2_sensor()); @@ -917,16 +835,14 @@ SPIComponent *Application::init_spi(const GPIOOutputPin &clk) { #endif #ifdef USE_PN532 -PN532Component *Application::make_pn532_component(SPIComponent *parent, - const GPIOOutputPin &cs, +PN532Component *Application::make_pn532_component(SPIComponent *parent, const GPIOOutputPin &cs, uint32_t update_interval) { return this->register_component(new PN532Component(parent, cs.copy(), update_interval)); } #endif #ifdef USE_UART_SWITCH -switch_::UARTSwitch *Application::make_uart_switch(UARTComponent *parent, - const std::string &name, +switch_::UARTSwitch *Application::make_uart_switch(UARTComponent *parent, const std::string &name, const std::vector &data) { auto *uart = new UARTSwitch(parent, name, data); this->register_switch(uart); @@ -943,17 +859,10 @@ sensor::UptimeSensor *Application::make_uptime_sensor(const std::string &name, u #endif #ifdef USE_INA219 -sensor::INA219Component *Application::make_ina219(float shunt_resistance_ohm, - float max_current_a, - float max_voltage_v, - uint8_t address, - uint32_t update_interval) { - return this->register_component(new INA219Component(this->i2c_, - shunt_resistance_ohm, - max_current_a, - max_voltage_v, - address, - update_interval)); +sensor::INA219Component *Application::make_ina219(float shunt_resistance_ohm, float max_current_a, float max_voltage_v, + uint8_t address, uint32_t update_interval) { + return this->register_component( + new INA219Component(this->i2c_, shunt_resistance_ohm, max_current_a, max_voltage_v, address, update_interval)); } #endif @@ -970,10 +879,8 @@ sensor::HMC5883LComponent *Application::make_hmc5883l(uint32_t update_interval) #endif #ifdef USE_HX711 -sensor::HX711Sensor *Application::make_hx711_sensor(const std::string &name, - const GPIOInputPin &dout, - const GPIOOutputPin &sck, - uint32_t update_interval) { +sensor::HX711Sensor *Application::make_hx711_sensor(const std::string &name, const GPIOInputPin &dout, + const GPIOOutputPin &sck, uint32_t update_interval) { auto *hx711 = this->register_component(new HX711Sensor(name, dout.copy(), sck.copy(), update_interval)); this->register_sensor(hx711); return hx711; @@ -982,11 +889,9 @@ sensor::HX711Sensor *Application::make_hx711_sensor(const std::string &name, #ifdef USE_MS5611 sensor::MS5611Component *Application::make_ms5611_sensor(const std::string &temperature_name, - const std::string &pressure_name, - uint32_t update_interval) { - auto *ms5611 = this->register_component( - new MS5611Component(this->i2c_, temperature_name, pressure_name, update_interval) - ); + const std::string &pressure_name, uint32_t update_interval) { + auto *ms5611 = + this->register_component(new MS5611Component(this->i2c_, temperature_name, pressure_name, update_interval)); this->register_sensor(ms5611->get_temperature_sensor()); this->register_sensor(ms5611->get_pressure_sensor()); return ms5611; @@ -1009,17 +914,14 @@ sensor::TCS34725Component *Application::make_tcs34725(uint32_t update_interval) #endif #ifdef USE_MAX7219 -display::MAX7219Component *Application::make_max7219(SPIComponent *parent, - const GPIOOutputPin &cs, +display::MAX7219Component *Application::make_max7219(SPIComponent *parent, const GPIOOutputPin &cs, uint32_t update_interval) { return this->register_component(new display::MAX7219Component(parent, cs.copy(), update_interval)); } #endif #ifdef USE_LCD_DISPLAY_PCF8574 -display::PCF8574LCDDisplay *Application::make_pcf8574_lcd_display(uint8_t columns, - uint8_t rows, - uint8_t address, +display::PCF8574LCDDisplay *Application::make_pcf8574_lcd_display(uint8_t columns, uint8_t rows, uint8_t address, uint32_t update_interval) { return this->register_component(new display::PCF8574LCDDisplay(this->i2c_, columns, rows, address, update_interval)); } @@ -1027,10 +929,8 @@ display::PCF8574LCDDisplay *Application::make_pcf8574_lcd_display(uint8_t column #ifdef USE_SSD1306 #ifdef USE_SPI -display::SPISSD1306 *Application::make_spi_ssd1306(SPIComponent *parent, - const GPIOOutputPin &cs, - const GPIOOutputPin &dc, - uint32_t update_interval) { +display::SPISSD1306 *Application::make_spi_ssd1306(SPIComponent *parent, const GPIOOutputPin &cs, + const GPIOOutputPin &dc, uint32_t update_interval) { return this->register_component(new display::SPISSD1306(parent, cs.copy(), dc.copy(), update_interval)); } #endif @@ -1043,18 +943,15 @@ display::I2CSSD1306 *Application::make_i2c_ssd1306(uint32_t update_interval) { #endif #ifdef USE_WAVESHARE_EPAPER -display::WaveshareEPaperTypeA *Application::make_waveshare_epaper_type_a(SPIComponent *parent, - const GPIOOutputPin &cs, +display::WaveshareEPaperTypeA *Application::make_waveshare_epaper_type_a(SPIComponent *parent, const GPIOOutputPin &cs, const GPIOOutputPin &dc_pin, display::WaveshareEPaperTypeAModel model, uint32_t update_interval) { return this->register_component( - new display::WaveshareEPaperTypeA(parent, cs.copy(), dc_pin.copy(), model, update_interval) - ); + new display::WaveshareEPaperTypeA(parent, cs.copy(), dc_pin.copy(), model, update_interval)); } -display::WaveshareEPaper *Application::make_waveshare_epaper_type_b(SPIComponent *parent, - const GPIOOutputPin &cs, +display::WaveshareEPaper *Application::make_waveshare_epaper_type_b(SPIComponent *parent, const GPIOOutputPin &cs, const GPIOOutputPin &dc_pin, display::WaveshareEPaperTypeBModel model, uint32_t update_interval) { @@ -1090,9 +987,7 @@ display::GPIOLCDDisplay *Application::make_gpio_lcd_display(uint8_t columns, uin #endif #ifdef USE_SNTP_COMPONENT -SNTPComponent *Application::make_sntp_component() { - return this->register_component(new SNTPComponent()); -} +SNTPComponent *Application::make_sntp_component() { return this->register_component(new SNTPComponent()); } #endif #ifdef USE_HOMEASSISTANT_TIME @@ -1102,9 +997,7 @@ HomeAssistantTime *Application::make_homeassistant_time_component() { #endif #ifdef USE_HLW8012 -sensor::HLW8012Component *Application::make_hlw8012(const GPIOOutputPin &sel_pin, - uint8_t cf_pin, - uint8_t cf1_pin, +sensor::HLW8012Component *Application::make_hlw8012(const GPIOOutputPin &sel_pin, uint8_t cf_pin, uint8_t cf1_pin, uint32_t update_interval) { return this->register_component(new HLW8012Component(sel_pin.copy(), cf_pin, cf1_pin, update_interval)); } @@ -1139,8 +1032,8 @@ text_sensor::MQTTSubscribeTextSensor *Application::make_mqtt_subscribe_text_sens #ifdef USE_HOMEASSISTANT_TEXT_SENSOR text_sensor::HomeassistantTextSensor *Application::make_homeassistant_text_sensor(const std::string &name, - std::string entity_id) { - auto *sensor = this->register_component(new HomeassistantTextSensor(name, std::move(entity_id))); + std::string entity_id) { + auto *sensor = this->register_component(new HomeassistantTextSensor(name, entity_id)); this->register_text_sensor(sensor); return sensor; } @@ -1163,18 +1056,17 @@ sensor::MQTTSubscribeSensor *Application::make_mqtt_subscribe_sensor(const std:: #endif #ifdef USE_HOMEASSISTANT_SENSOR -sensor::HomeassistantSensor *Application::make_homeassistant_sensor(const std::string &name, - std::string entity_id) { - auto *sensor = this->register_component(new HomeassistantSensor(name, std::move(entity_id))); +sensor::HomeassistantSensor *Application::make_homeassistant_sensor(const std::string &name, std::string entity_id) { + auto *sensor = this->register_component(new HomeassistantSensor(name, entity_id)); this->register_sensor(sensor); return sensor; } #endif #ifdef USE_HOMEASSISTANT_BINARY_SENSOR -binary_sensor::HomeassistantBinarySensor *Application::make_homeassistant_binary_sensor( - const std::string &name, std::string entity_id) { - auto *sensor = this->register_component(new HomeassistantBinarySensor(name, std::move(entity_id))); +binary_sensor::HomeassistantBinarySensor *Application::make_homeassistant_binary_sensor(const std::string &name, + std::string entity_id) { + auto *sensor = this->register_component(new HomeassistantBinarySensor(name, entity_id)); this->register_binary_sensor(sensor); return sensor; } @@ -1182,10 +1074,10 @@ binary_sensor::HomeassistantBinarySensor *Application::make_homeassistant_binary #ifdef USE_TEMPLATE_TEXT_SENSOR text_sensor::TemplateTextSensor *Application::make_template_text_sensor(const std::string &name, - uint32_t update_interval) { - auto *template_ = this->register_component(new TemplateTextSensor(name, update_interval)); - this->register_text_sensor(template_); - return template_; + uint32_t update_interval) { + auto *a_template = this->register_component(new TemplateTextSensor(name, update_interval)); + this->register_text_sensor(a_template); + return a_template; } #endif @@ -1217,9 +1109,7 @@ sensor::TotalDailyEnergy *Application::make_total_daily_energy_sensor(const std: } #endif -void Application::set_loop_interval(uint32_t loop_interval) { - this->loop_interval_ = loop_interval; -} +void Application::set_loop_interval(uint32_t loop_interval) { this->loop_interval_ = loop_interval; } void Application::register_component_(Component *comp) { if (comp == nullptr) { @@ -1246,8 +1136,8 @@ api::APIServer *Application::init_api_server() { #endif #ifdef USE_CUSTOM_BINARY_SENSOR -binary_sensor::CustomBinarySensorConstructor *Application::make_custom_binary_sensor(const std::function()> &init) { +binary_sensor::CustomBinarySensorConstructor *Application::make_custom_binary_sensor( + const std::function()> &init) { return this->register_component(new CustomBinarySensorConstructor(init)); } #endif @@ -1297,6 +1187,6 @@ Application::MakePartitionLight Application::make_partition_light( } #endif -Application App; // NOLINT +Application App; // NOLINT ESPHOME_NAMESPACE_END diff --git a/src/esphome/application.h b/src/esphome/application.h index e7e3ae37..b74cdfb1 100644 --- a/src/esphome/application.h +++ b/src/esphome/application.h @@ -167,8 +167,7 @@ class Application { * @param hw_serial The hardware serial UART used for logging. * @return The created and initialized LogComponent. */ - LogComponent *init_log(uint32_t baud_rate = 115200, - size_t tx_buffer_size = 512, + LogComponent *init_log(uint32_t baud_rate = 115200, size_t tx_buffer_size = 512, UARTSelection uart = UART_SELECTION_UART0); /** Initialize the WiFi engine in client mode. @@ -205,8 +204,8 @@ class Application { * @param password The password. Empty for no password. * @return The MQTTClient. Use this to set advanced settings. */ - mqtt::MQTTClientComponent *init_mqtt(const std::string &address, uint16_t port, - const std::string &username, const std::string &password); + mqtt::MQTTClientComponent *init_mqtt(const std::string &address, uint16_t port, const std::string &username, + const std::string &password); /** Initialize the MQTT client. * @@ -215,8 +214,8 @@ class Application { * @param password The password. Empty for no password. * @return The MQTTClient. Use this to set advanced settings. */ - mqtt::MQTTClientComponent *init_mqtt(const std::string &address, - const std::string &username, const std::string &password); + mqtt::MQTTClientComponent *init_mqtt(const std::string &address, const std::string &username, + const std::string &password); #endif #ifdef USE_I2C @@ -288,15 +287,12 @@ class Application { #endif #ifdef USE_MAX7219 - display::MAX7219Component *make_max7219(SPIComponent *parent, - const GPIOOutputPin &cs, + display::MAX7219Component *make_max7219(SPIComponent *parent, const GPIOOutputPin &cs, uint32_t update_interval = 1000); #endif #ifdef USE_LCD_DISPLAY_PCF8574 - display::PCF8574LCDDisplay *make_pcf8574_lcd_display(uint8_t columns, - uint8_t rows, - uint8_t address = 0x3F, + display::PCF8574LCDDisplay *make_pcf8574_lcd_display(uint8_t columns, uint8_t rows, uint8_t address = 0x3F, uint32_t update_interval = 1000); #endif @@ -306,9 +302,7 @@ class Application { #ifdef USE_SSD1306 #ifdef USE_SPI - display::SPISSD1306 *make_spi_ssd1306(SPIComponent *parent, - const GPIOOutputPin &cs, - const GPIOOutputPin &dc, + display::SPISSD1306 *make_spi_ssd1306(SPIComponent *parent, const GPIOOutputPin &cs, const GPIOOutputPin &dc, uint32_t update_interval = 5000); #endif #ifdef USE_I2C @@ -317,14 +311,12 @@ class Application { #endif #ifdef USE_WAVESHARE_EPAPER - display::WaveshareEPaperTypeA *make_waveshare_epaper_type_a(SPIComponent *parent, - const GPIOOutputPin &cs, + display::WaveshareEPaperTypeA *make_waveshare_epaper_type_a(SPIComponent *parent, const GPIOOutputPin &cs, const GPIOOutputPin &dc_pin, display::WaveshareEPaperTypeAModel model, uint32_t update_interval = 10000); - display::WaveshareEPaper *make_waveshare_epaper_type_b(SPIComponent *parent, - const GPIOOutputPin &cs, + display::WaveshareEPaper *make_waveshare_epaper_type_b(SPIComponent *parent, const GPIOOutputPin &cs, const GPIOOutputPin &dc_pin, display::WaveshareEPaperTypeBModel model, uint32_t update_interval = 10000); @@ -334,18 +326,9 @@ class Application { display::Nextion *make_nextion(UARTComponent *parent, uint32_t update_interval = 5000); #endif - template - GlobalVariableComponent *make_global_variable(); - - template - GlobalVariableComponent *make_global_variable(T initial_value); - - - - - - + template GlobalVariableComponent *make_global_variable(); + template GlobalVariableComponent *make_global_variable(T initial_value); /* _ _ _______ ____ __ __ _______ _____ ____ _ _ * /\ | | | |__ __/ __ \| \/ | /\|__ __|_ _/ __ \| \ | | @@ -355,19 +338,12 @@ class Application { * /_/ \_\____/ |_| \____/|_| |_/_/ \_\_| |_____\____/|_| \_| */ - template - Automation *make_automation(Trigger *trigger); + template Automation *make_automation(Trigger *trigger); StartupTrigger *make_startup_trigger(); ShutdownTrigger *make_shutdown_trigger(); - - - - - - /* ____ ___ _ _ _ ______ __ ____ _____ _ _ ____ ___ ____ * | __ |_ _| \ | | / \ | _ \ \ / / / ___|| ____| \ | / ___| / _ \| _ \ * | _ \| || \| | / _ \ | |_) \ V / \___ \| _| | \| \___ \| | | | |_) | @@ -386,7 +362,8 @@ class Application { * * @param friendly_name The friendly name that should be advertised. Leave empty for no automatic discovery. * @param pin The GPIO pin. - * @param device_class The Home Assistant device_class. + * @param device_class The Home Assistant device_class. */ binary_sensor::GPIOBinarySensorComponent *make_gpio_binary_sensor(const std::string &friendly_name, const GPIOInputPin &pin, @@ -433,21 +410,14 @@ class Application { #endif #ifdef USE_CUSTOM_BINARY_SENSOR - binary_sensor::CustomBinarySensorConstructor *make_custom_binary_sensor(const std::function()> &init); + binary_sensor::CustomBinarySensorConstructor *make_custom_binary_sensor( + const std::function()> &init); #endif #ifdef USE_MPR121 binary_sensor::MPR121Component *make_mpr121(uint8_t address = 0x5A); #endif - - - - - - - - /* ____ _____ _ _ ____ ___ ____ * / ___|| ____| \ | / ___| / _ \| _ \ * \___ \| _| | \| \___ \| | | | |_) | @@ -478,9 +448,8 @@ class Application { * @return The components. Use this for advanced settings. */ sensor::DHTComponent *make_dht_sensor(const std::string &temperature_friendly_name, - const std::string &humidity_friendly_name, - const GPIOOutputPin &pin, - uint32_t update_interval = 60000); + const std::string &humidity_friendly_name, const GPIOOutputPin &pin, + uint32_t check_interval = 60000); #endif #ifdef USE_DALLAS_SENSOR @@ -518,8 +487,7 @@ class Application { * @param update_interval The interval in ms the sensor should be checked. * @return The components. Use this for advanced settings. */ - sensor::ADCSensorComponent *make_adc_sensor(const std::string &friendly_name, - uint8_t pin, + sensor::ADCSensorComponent *make_adc_sensor(const std::string &friendly_name, uint8_t pin, uint32_t update_interval = 60000); #endif @@ -672,8 +640,8 @@ class Application { * @param update_interval The interval in ms to update the sensor values. */ sensor::BME280Component *make_bme280_sensor(const std::string &temperature_name, const std::string &pressure_name, - const std::string &humidity_name, - uint8_t address = 0x77, uint32_t update_interval = 60000); + const std::string &humidity_name, uint8_t address = 0x77, + uint32_t update_interval = 60000); #endif #ifdef USE_BMP280 @@ -724,8 +692,7 @@ class Application { * @param pin_a The first pin of the sensor. * @param pin_b The second pin of the sensor. */ - sensor::RotaryEncoderSensor *make_rotary_encoder_sensor(const std::string &name, - const GPIOInputPin &pin_a, + sensor::RotaryEncoderSensor *make_rotary_encoder_sensor(const std::string &name, const GPIOInputPin &pin_a, const GPIOInputPin &pin_b); #endif @@ -797,7 +764,8 @@ class Application { #endif #ifdef USE_HLW8012 - sensor::HLW8012Component *make_hlw8012(const GPIOOutputPin &sel_pin, uint8_t cf_pin, uint8_t cf1_pin, uint32_t update_interval = 60000); + sensor::HLW8012Component *make_hlw8012(const GPIOOutputPin &sel_pin, uint8_t cf_pin, uint8_t cf1_pin, + uint32_t update_interval = 60000); #endif #ifdef USE_MQTT_SUBSCRIBE_SENSOR @@ -809,14 +777,14 @@ class Application { #endif #ifdef USE_HOMEASSISTANT_BINARY_SENSOR - binary_sensor::HomeassistantBinarySensor *make_homeassistant_binary_sensor(const std::string &name, std::string entity_id); + binary_sensor::HomeassistantBinarySensor *make_homeassistant_binary_sensor(const std::string &name, + std::string entity_id); #endif #ifdef USE_CSE7766 sensor::CSE7766Component *make_cse7766(UARTComponent *parent, uint32_t update_interval = 60000); #endif - #ifdef USE_MQTT_SUBSCRIBE_TEXT_SENSOR text_sensor::MQTTSubscribeTextSensor *make_mqtt_subscribe_text_sensor(const std::string &name, std::string topic); #endif @@ -850,10 +818,6 @@ class Application { sensor::CustomSensorConstructor *make_custom_sensor(const std::function()> &init); #endif - - - - /* ___ _ _ _____ ____ _ _ _____ * / _ \| | | |_ _| _ \| | | |_ _| * | | | | | | | | | | |_) | | | | | | @@ -913,7 +877,7 @@ class Application { * @param pin The pin for this PWM output, supported pins are 0-16. * @return The PWM output channel, use this for advanced settings and using it with lights. */ - output::ESP8266PWMOutput *make_esp8266_pwm_output(GPIOOutputPin pin_); + output::ESP8266PWMOutput *make_esp8266_pwm_output(GPIOOutputPin pin); #endif #ifdef USE_MY9231_OUTPUT @@ -923,15 +887,9 @@ class Application { * @param pin_dcki The pin which DCKI is connected to. * @return The MY9231 component. Use this for advanced settings. */ - output::MY9231OutputComponent *make_my9231_component(const GPIOOutputPin &pin_di, - const GPIOOutputPin &pin_dcki); + output::MY9231OutputComponent *make_my9231_component(const GPIOOutputPin &pin_di, const GPIOOutputPin &pin_dcki); #endif - - - - - /* _ ___ ____ _ _ _____ * | | |_ _/ ___| | | |_ _| * | | | | | _| |_| | | | @@ -973,8 +931,8 @@ class Application { * @param blue The blue output channel. * @return The components for this light. Use this for advanced settings. */ - MakeLight make_rgb_light(const std::string &friendly_name, - output::FloatOutput *red, output::FloatOutput *green, output::FloatOutput *blue); + MakeLight make_rgb_light(const std::string &friendly_name, output::FloatOutput *red, output::FloatOutput *green, + output::FloatOutput *blue); /** Create a RGBW light. * @@ -985,24 +943,15 @@ class Application { * @param white The white output channel. * @return The components for this light. Use this for advanced settings. */ - MakeLight make_rgbw_light(const std::string &friendly_name, - output::FloatOutput *red, output::FloatOutput *green, output::FloatOutput *blue, - output::FloatOutput *white); - - MakeLight make_rgbww_light(const std::string &friendly_name, - float cold_white_mireds, - float warm_white_mireds, - output::FloatOutput *red, - output::FloatOutput *green, - output::FloatOutput *blue, - output::FloatOutput *cold_white, - output::FloatOutput *warm_white); - - MakeLight make_cwww_light(const std::string &friendly_name, - float cold_white_mireds, - float warm_white_mireds, - output::FloatOutput *cold_white, - output::FloatOutput *warm_white); + MakeLight make_rgbw_light(const std::string &friendly_name, output::FloatOutput *red, output::FloatOutput *green, + output::FloatOutput *blue, output::FloatOutput *white); + + MakeLight make_rgbww_light(const std::string &friendly_name, float cold_white_mireds, float warm_white_mireds, + output::FloatOutput *red, output::FloatOutput *green, output::FloatOutput *blue, + output::FloatOutput *cold_white, output::FloatOutput *warm_white); + + MakeLight make_cwww_light(const std::string &friendly_name, float cold_white_mireds, float warm_white_mireds, + output::FloatOutput *cold_white, output::FloatOutput *warm_white); #endif #ifdef USE_FAST_LED_LIGHT @@ -1016,8 +965,7 @@ class Application { #endif #ifdef USE_NEO_PIXEL_BUS_LIGHT - template - struct MakeNeoPixelBusLight { + template struct MakeNeoPixelBusLight { light::NeoPixelBusLightOutputBase *output; light::LightState *state; }; @@ -1040,10 +988,6 @@ class Application { const std::vector &segments); #endif - - - - /* ______ _____ _____ ____ _ _ * / ___\ \ / |_ _|_ _/ ___| | | | * \___ \\ \ /\ / / | | | || | | |_| | @@ -1052,7 +996,7 @@ class Application { */ #ifdef USE_SWITCH /// Register a Switch internally, creating a MQTT Switch if the MQTT client is set up - void register_switch(switch_::Switch *switch_); + void register_switch(switch_::Switch *a_switch); #endif #ifdef USE_GPIO_SWITCH @@ -1088,18 +1032,14 @@ class Application { #endif #ifdef USE_UART_SWITCH - switch_::UARTSwitch *make_uart_switch(UARTComponent *parent, const std::string &name, const std::vector &data); + switch_::UARTSwitch *make_uart_switch(UARTComponent *parent, const std::string &name, + const std::vector &data); #endif #ifdef USE_CUSTOM_SWITCH switch_::CustomSwitchConstructor *make_custom_switch(const std::function()> &init); #endif - - - - - /* _____ _ _ _ * | ___/ \ | \ | | * | |_ / _ \ | \| | @@ -1123,11 +1063,6 @@ class Application { MakeFan make_fan(const std::string &friendly_name); #endif - - - - - /* _____ ______ ________ _____ * / ____/ __ \ \ / / ____| __ \ * | | | | | \ \ / /| |__ | |__) | @@ -1143,22 +1078,15 @@ class Application { cover::TemplateCover *make_template_cover(const std::string &name); #endif - #ifdef USE_A4988 stepper::A4988 *make_a4988(const GPIOOutputPin &step_pin, const GPIOOutputPin &dir_pin); #endif #ifdef USE_ULN2003 - stepper::ULN2003 *make_uln2003(const GPIOOutputPin &pin_a, const GPIOOutputPin &pin_b, - const GPIOOutputPin &pin_c, const GPIOOutputPin &pin_d); + stepper::ULN2003 *make_uln2003(const GPIOOutputPin &pin_a, const GPIOOutputPin &pin_b, const GPIOOutputPin &pin_c, + const GPIOOutputPin &pin_d); #endif - - - - - - /* _ _ _____ _ ____ _____ ____ ____ * | | | | ____| | | _ \| ____| _ \/ ___| * | |_| | _| | | | |_) | _| | |_) \___ \ @@ -1191,11 +1119,9 @@ class Application { #endif /// Register the component in this Application instance. - template - C *register_component(C *c); + template C *register_component(C *c); - template - C *register_controller(C *c); + template C *register_controller(C *c); /// Set up all the registered components. Call this at the end of your setup() function. void setup(); @@ -1270,53 +1196,50 @@ class Application { /// Global storage of Application pointer - only one Application can exist. extern Application App; -template -C *Application::register_component(C *c) { +template C *Application::register_component(C *c) { static_assert(std::is_base_of::value, "Only Component subclasses can be registered"); this->register_component_((Component *) c); return c; } -template -C *Application::register_controller(C *c) { +template C *Application::register_controller(C *c) { static_assert(std::is_base_of::value, "Only Controller subclasses can be registered"); Controller *controller = c; this->controllers_.push_back(controller); return c; } -template -Automation *Application::make_automation(Trigger *trigger) { +template Automation *Application::make_automation(Trigger *trigger) { return new Automation(trigger); } -template -GlobalVariableComponent *Application::make_global_variable() { +template GlobalVariableComponent *Application::make_global_variable() { return this->register_component(new GlobalVariableComponent()); } -template -GlobalVariableComponent *Application::make_global_variable(T initial_value) { +template GlobalVariableComponent *Application::make_global_variable(T initial_value) { return this->register_component(new GlobalVariableComponent(initial_value)); } #ifdef USE_NEO_PIXEL_BUS_LIGHT template -Application::MakeNeoPixelBusLight Application::make_neo_pixel_bus_rgb_light(const std::string &name) { +Application::MakeNeoPixelBusLight Application::make_neo_pixel_bus_rgb_light( + const std::string &name) { auto *neo_pixel = this->register_component(new light::NeoPixelRGBLightOutput()); auto make = this->make_light_for_light_output(name, neo_pixel); - return MakeNeoPixelBusLight { + return MakeNeoPixelBusLight{ .output = neo_pixel, .state = make.state, }; } template -Application::MakeNeoPixelBusLight Application::make_neo_pixel_bus_rgbw_light(const std::string &name) { +Application::MakeNeoPixelBusLight Application::make_neo_pixel_bus_rgbw_light( + const std::string &name) { auto *neo_pixel = this->register_component(new light::NeoPixelRGBWLightOutput()); auto make = this->make_light_for_light_output(name, neo_pixel); - return MakeNeoPixelBusLight { + return MakeNeoPixelBusLight{ .output = neo_pixel, .state = make.state, }; @@ -1328,4 +1251,4 @@ ESPHOME_NAMESPACE_END /// namespace alias for backwards-compatability namespace esphomelib = esphome; -#endif //ESPHOME_APPLICATION_H +#endif // ESPHOME_APPLICATION_H diff --git a/src/esphome/automation.cpp b/src/esphome/automation.cpp index 7d404a56..74346669 100644 --- a/src/esphome/automation.cpp +++ b/src/esphome/automation.cpp @@ -3,37 +3,22 @@ ESPHOME_NAMESPACE_BEGIN -void StartupTrigger::setup() { - this->trigger(); -} +void StartupTrigger::setup() { this->trigger(); } float StartupTrigger::get_setup_priority() const { // Run after everything is set up return this->setup_priority_; } -StartupTrigger::StartupTrigger(float setup_priority) - : setup_priority_(setup_priority) { - -} +StartupTrigger::StartupTrigger(float setup_priority) : setup_priority_(setup_priority) {} ShutdownTrigger::ShutdownTrigger() { - add_shutdown_hook([this](const char *cause){ - this->trigger(cause); - }); + add_shutdown_hook([this](const char *cause) { this->trigger(cause); }); } -void LoopTrigger::loop() { - this->trigger(); -} -float LoopTrigger::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +void LoopTrigger::loop() { this->trigger(); } +float LoopTrigger::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -void IntervalTrigger::update() { - this->trigger(); -} -float IntervalTrigger::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +void IntervalTrigger::update() { this->trigger(); } +float IntervalTrigger::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } IntervalTrigger::IntervalTrigger(uint32_t update_interval) : PollingComponent(update_interval) {} @@ -51,12 +36,7 @@ bool RangeCondition::check(float x) { } } -void Script::execute() { - this->trigger(); -} -void Script::stop() { - this->parent_->stop(); -} +void Script::execute() { this->trigger(); } +void Script::stop() { this->parent_->stop(); } ESPHOME_NAMESPACE_END - diff --git a/src/esphome/automation.h b/src/esphome/automation.h index f6af131e..bc3c4b28 100644 --- a/src/esphome/automation.h +++ b/src/esphome/automation.h @@ -10,41 +10,39 @@ ESPHOME_NAMESPACE_BEGIN -template -class Condition { +template class Condition { public: virtual bool check(Ts... x) = 0; bool check_tuple(const std::tuple &tuple); protected: - template - bool check_tuple(const std::tuple &tuple, seq); + template bool check_tuple_(const std::tuple &tuple, seq); }; -template -class AndCondition : public Condition { +template class AndCondition : public Condition { public: explicit AndCondition(const std::vector *> &conditions); bool check(Ts... x) override; + protected: std::vector *> conditions_; }; -template -class OrCondition : public Condition { +template class OrCondition : public Condition { public: explicit OrCondition(const std::vector *> &conditions); bool check(Ts... x) override; + protected: std::vector *> conditions_; }; -template -class LambdaCondition : public Condition { +template class LambdaCondition : public Condition { public: explicit LambdaCondition(std::function &&f); bool check(Ts... x) override; + protected: std::function f_; }; @@ -54,25 +52,22 @@ class RangeCondition : public Condition { explicit RangeCondition(); bool check(float x) override; - template - void set_min(V value) { this->min_ = value; } - template - void set_max(V value) { this->max_ = value; } + template void set_min(V value) { this->min_ = value; } + template void set_max(V value) { this->max_ = value; } protected: TemplatableValue min_{NAN}; TemplatableValue max_{NAN}; }; -template -class Automation; +template class Automation; -template -class Trigger { +template class Trigger { public: void trigger(Ts... x); void set_parent(Automation *parent); void stop(); + protected: Automation *parent_{nullptr}; }; @@ -105,13 +100,10 @@ class IntervalTrigger : public Trigger<>, public PollingComponent { float get_setup_priority() const override; }; -template -class ScriptExecuteAction; -template -class ScriptStopAction; +template class ScriptExecuteAction; +template class ScriptStopAction; -template -class ScriptStopAction; +template class ScriptStopAction; class Script : public Trigger<> { public: @@ -119,18 +111,14 @@ class Script : public Trigger<> { void stop(); - template - ScriptExecuteAction *make_execute_action(); + template ScriptExecuteAction *make_execute_action(); - template - ScriptStopAction *make_stop_action(); + template ScriptStopAction *make_stop_action(); }; -template -class ActionList; +template class ActionList; -template -class Action { +template class Action { public: virtual void play(Ts... x) = 0; void play_next(Ts... x); @@ -142,38 +130,35 @@ class Action { protected: friend ActionList; - template - void play_next_tuple(const std::tuple &tuple, seq); + template void play_next_tuple_(const std::tuple &tuple, seq); Action *next_ = nullptr; }; -template -class DelayAction : public Action, public Component { +template class DelayAction : public Action, public Component { public: explicit DelayAction(); - template - void set_delay(V value) { this->delay_ = value; } + template void set_delay(V value) { this->delay_ = value; } void stop() override; void play(Ts... x) override; float get_setup_priority() const override; + protected: TemplatableValue delay_{0}; }; -template -class LambdaAction : public Action { +template class LambdaAction : public Action { public: explicit LambdaAction(std::function &&f); void play(Ts... x) override; + protected: std::function f_; }; -template -class IfAction : public Action { +template class IfAction : public Action { public: explicit IfAction(std::vector *> conditions); @@ -191,8 +176,7 @@ class IfAction : public Action { ActionList else_; }; -template -class WhileAction : public Action { +template class WhileAction : public Action { public: WhileAction(const std::vector *> &conditions); @@ -208,8 +192,7 @@ class WhileAction : public Action { bool is_running_{false}; }; -template -class WaitUntilAction : public Action, public Component { +template class WaitUntilAction : public Action, public Component { public: WaitUntilAction(const std::vector *> &conditions); @@ -227,37 +210,36 @@ class WaitUntilAction : public Action, public Component { std::tuple var_{}; }; -template -class UpdateComponentAction : public Action { +template class UpdateComponentAction : public Action { public: UpdateComponentAction(PollingComponent *component); void play(Ts... x) override; + protected: PollingComponent *component_; }; -template -class ScriptExecuteAction : public Action { +template class ScriptExecuteAction : public Action { public: ScriptExecuteAction(Script *script); void play(Ts... x) override; + protected: Script *script_; }; -template -class ScriptStopAction : public Action { +template class ScriptStopAction : public Action { public: ScriptStopAction(Script *script); void play(Ts... x) override; + protected: Script *script_; }; -template -class ActionList { +template class ActionList { public: Action *add_action(Action *action); void add_actions(const std::vector *> &actions); @@ -270,8 +252,7 @@ class ActionList { Action *actions_end_{nullptr}; }; -template -class Automation { +template class Automation { public: explicit Automation(Trigger *trigger); @@ -281,18 +262,17 @@ class Automation { Action *add_action(Action *action); void add_actions(const std::vector *> &actions); - void process_trigger_(Ts... x); - void stop(); + void trigger(Ts... x); + protected: Trigger *trigger_; std::vector *> conditions_; ActionList actions_; }; -template -class GlobalVariableComponent : public Component { +template class GlobalVariableComponent : public Component { public: explicit GlobalVariableComponent(); explicit GlobalVariableComponent(T initial_value); @@ -319,4 +299,4 @@ ESPHOME_NAMESPACE_END #include "esphome/automation.tcc" -#endif //ESPHOME_AUTOMATION_H +#endif // ESPHOME_AUTOMATION_H diff --git a/src/esphome/automation.tcc b/src/esphome/automation.tcc index 9a0d9c32..c0e0f40c 100644 --- a/src/esphome/automation.tcc +++ b/src/esphome/automation.tcc @@ -2,18 +2,16 @@ ESPHOME_NAMESPACE_BEGIN -template -bool Condition::check_tuple(const std::tuple &tuple) { - return this->check_tuple(tuple, typename gens::type()); +template bool Condition::check_tuple(const std::tuple &tuple) { + return this->check_tuple_(tuple, typename gens::type()); } template template -bool Condition::check_tuple(const std::tuple &tuple, seq) { - return this->check(std::get(tuple) ...); +bool Condition::check_tuple_(const std::tuple &tuple, seq) { + return this->check(std::get(tuple)...); } -template -bool AndCondition::check(Ts... x) { +template bool AndCondition::check(Ts... x) { for (auto *condition : this->conditions_) { if (!condition->check(x...)) return false; @@ -23,13 +21,9 @@ bool AndCondition::check(Ts... x) { } template -AndCondition::AndCondition(const std::vector *> &conditions) -: conditions_(conditions) { - -} +AndCondition::AndCondition(const std::vector *> &conditions) : conditions_(conditions) {} -template -bool OrCondition::check(Ts... x) { +template bool OrCondition::check(Ts... x) { for (auto *condition : this->conditions_) { if (condition->check(x...)) return true; @@ -39,97 +33,71 @@ bool OrCondition::check(Ts... x) { } template -OrCondition::OrCondition(const std::vector *> &conditions) -: conditions_(conditions) { +OrCondition::OrCondition(const std::vector *> &conditions) : conditions_(conditions) {} +template void Trigger::set_parent(Automation *parent) { this->parent_ = parent; } -} -template -void Trigger::set_parent(Automation *parent) { - this->parent_ = parent; -} - -template -void Trigger::trigger(Ts... x) { +template void Trigger::trigger(Ts... x) { if (this->parent_ == nullptr) return; - this->parent_->process_trigger_(x...); + this->parent_->trigger(x...); } -template -void Trigger::stop() { +template void Trigger::stop() { if (this->parent_ == nullptr) return; this->parent_->stop(); } -template -void Action::play_next(Ts... x) { +template void Action::play_next(Ts... x) { if (this->next_ != nullptr) { this->next_->play(x...); } } -template -void Action::stop() { - this->stop_next(); -} -template -void Action::stop_next() { +template void Action::stop() { this->stop_next(); } +template void Action::stop_next() { if (this->next_ != nullptr) { this->next_->stop(); } } -template -void Action::play_next_tuple(const std::tuple &tuple) { - this->play_next_tuple(tuple, typename gens::type()); +template void Action::play_next_tuple(const std::tuple &tuple) { + this->play_next_tuple_(tuple, typename gens::type()); } template template -void Action::play_next_tuple(const std::tuple &tuple, seq) { - this->play_next(std::get(tuple) ...); +void Action::play_next_tuple_(const std::tuple &tuple, seq) { + this->play_next(std::get(tuple)...); } -template -DelayAction::DelayAction() = default; +template DelayAction::DelayAction() = default; -template -void DelayAction::play(Ts... x) { +template void DelayAction::play(Ts... x) { auto f = std::bind(&DelayAction::play_next, this, x...); this->set_timeout(this->delay_.value(x...), f); } -template -float DelayAction::get_setup_priority() const { - return setup_priority::HARDWARE; -} -template -void DelayAction::stop() { +template float DelayAction::get_setup_priority() const { return setup_priority::HARDWARE; } +template void DelayAction::stop() { this->cancel_timeout(""); this->stop_next(); } -template -Condition *Automation::add_condition(Condition *condition) { +template Condition *Automation::add_condition(Condition *condition) { this->conditions_.push_back(condition); return condition; } -template -void Automation::add_conditions(const std::vector *> &conditions) { +template void Automation::add_conditions(const std::vector *> &conditions) { for (auto *condition : conditions) { this->add_condition(condition); } } -template -Automation::Automation(Trigger *trigger) : trigger_(trigger) { +template Automation::Automation(Trigger *trigger) : trigger_(trigger) { this->trigger_->set_parent(this); } -template -Action *Automation::add_action(Action *action) { +template Action *Automation::add_action(Action *action) { this->actions_.add_action(action); } -template -void Automation::add_actions(const std::vector *> &actions) { +template void Automation::add_actions(const std::vector *> &actions) { this->actions_.add_actions(actions); } -template -void Automation::process_trigger_(Ts... x) { +template void Automation::trigger(Ts... x) { for (auto *condition : this->conditions_) { if (!condition->check(x...)) return; @@ -137,30 +105,17 @@ void Automation::process_trigger_(Ts... x) { this->actions_.play(x...); } -template -void Automation::stop() { - this->actions_.stop(); -} -template -LambdaCondition::LambdaCondition(std::function &&f) - : f_(std::move(f)) { +template void Automation::stop() { this->actions_.stop(); } +template LambdaCondition::LambdaCondition(std::function &&f) : f_(std::move(f)) {} +template bool LambdaCondition::check(Ts... x) { return this->f_(x...); } -} -template -bool LambdaCondition::check(Ts... x) { - return this->f_(x...); -} - -template -LambdaAction::LambdaAction(std::function &&f) : f_(std::move(f)) {} -template -void LambdaAction::play(Ts... x) { +template LambdaAction::LambdaAction(std::function &&f) : f_(std::move(f)) {} +template void LambdaAction::play(Ts... x) { this->f_(x...); this->play_next(x...); } -template -Action *ActionList::add_action(Action *action) { +template Action *ActionList::add_action(Action *action) { if (this->actions_end_ == nullptr) { this->actions_begin_ = action; } else { @@ -168,32 +123,23 @@ Action *ActionList::add_action(Action *action) { } return this->actions_end_ = action; } -template -void ActionList::add_actions(const std::vector *> &actions) { +template void ActionList::add_actions(const std::vector *> &actions) { for (auto *action : actions) { this->add_action(action); } } -template -void ActionList::play(Ts... x) { +template void ActionList::play(Ts... x) { if (this->actions_begin_ != nullptr) this->actions_begin_->play(x...); } -template -void ActionList::stop() { +template void ActionList::stop() { if (this->actions_begin_ != nullptr) this->actions_begin_->stop(); } +template bool ActionList::empty() const { return this->actions_begin_ == nullptr; } template -bool ActionList::empty() const { - return this->actions_begin_ == nullptr; -} -template -IfAction::IfAction(const std::vector *> conditions) : conditions_(conditions) { - -} -template -void IfAction::play(Ts... x) { +IfAction::IfAction(const std::vector *> conditions) : conditions_(conditions) {} +template void IfAction::play(Ts... x) { bool res = true; for (auto *condition : this->conditions_) { if (!condition->check(x...)) { @@ -215,100 +161,62 @@ void IfAction::play(Ts... x) { } } } -template -void IfAction::add_then(const std::vector *> &actions) { +template void IfAction::add_then(const std::vector *> &actions) { this->then_.add_actions(actions); - this->then_.add_action(new LambdaAction([this](Ts... x) { - this->play_next(x...); - })); + this->then_.add_action(new LambdaAction([this](Ts... x) { this->play_next(x...); })); } -template -void IfAction::add_else(const std::vector *> &actions) { +template void IfAction::add_else(const std::vector *> &actions) { this->else_.add_actions(actions); - this->else_.add_action(new LambdaAction([this](Ts... x) { - this->play_next(x...); - })); + this->else_.add_action(new LambdaAction([this](Ts... x) { this->play_next(x...); })); } -template -void IfAction::stop() { +template void IfAction::stop() { this->then_.stop(); this->else_.stop(); this->stop_next(); } -template -void UpdateComponentAction::play(Ts... x) { +template void UpdateComponentAction::play(Ts... x) { this->component_->update(); this->play_next(x...); } template -UpdateComponentAction::UpdateComponentAction(PollingComponent *component) - : component_(component) { +UpdateComponentAction::UpdateComponentAction(PollingComponent *component) : component_(component) {} -} - -template -ScriptExecuteAction::ScriptExecuteAction(Script *script) - : script_(script) { - -} +template ScriptExecuteAction::ScriptExecuteAction(Script *script) : script_(script) {} -template -void ScriptExecuteAction::play(Ts... x) { +template void ScriptExecuteAction::play(Ts... x) { this->script_->trigger(); this->play_next(x...); } -template -ScriptExecuteAction *Script::make_execute_action() { +template ScriptExecuteAction *Script::make_execute_action() { return new ScriptExecuteAction(this); } -template -ScriptStopAction::ScriptStopAction(Script *script) - : script_(script) { - -} +template ScriptStopAction::ScriptStopAction(Script *script) : script_(script) {} -template -void ScriptStopAction::play(Ts... x) { +template void ScriptStopAction::play(Ts... x) { this->script_->stop(); this->play_next(x...); } -template -ScriptStopAction *Script::make_stop_action() { +template ScriptStopAction *Script::make_stop_action() { return new ScriptStopAction(this); } -template -GlobalVariableComponent::GlobalVariableComponent() { - -} -template -GlobalVariableComponent::GlobalVariableComponent(T initial_value) - : value_(initial_value) { - -} -template -T &GlobalVariableComponent::value() { - return this->value_; -} -template -void GlobalVariableComponent::setup() { +template GlobalVariableComponent::GlobalVariableComponent() {} +template GlobalVariableComponent::GlobalVariableComponent(T initial_value) : value_(initial_value) {} +template T &GlobalVariableComponent::value() { return this->value_; } +template void GlobalVariableComponent::setup() { if (this->restore_value_) { this->rtc_ = global_preferences.make_preference(1944399030U ^ this->name_hash_); this->rtc_.load(&this->value_); } memcpy(&this->prev_value_, &this->value_, sizeof(T)); } -template -float GlobalVariableComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} -template -void GlobalVariableComponent::loop() { +template float GlobalVariableComponent::get_setup_priority() const { return setup_priority::HARDWARE; } +template void GlobalVariableComponent::loop() { if (this->restore_value_) { int diff = memcmp(&this->value_, &this->prev_value_, sizeof(T)); if (diff != 0) { @@ -317,25 +225,20 @@ void GlobalVariableComponent::loop() { } } } -template -void GlobalVariableComponent::set_restore_value(uint32_t name_hash) { +template void GlobalVariableComponent::set_restore_value(uint32_t name_hash) { this->restore_value_ = true; this->name_hash_ = name_hash; } template -WhileAction::WhileAction(const std::vector *> &conditions) : conditions_(conditions) { - -} -template -void WhileAction::add_then(const std::vector *> &actions) { +WhileAction::WhileAction(const std::vector *> &conditions) : conditions_(conditions) {} +template void WhileAction::add_then(const std::vector *> &actions) { this->then_.add_actions(actions); this->then_.add_action(new LambdaAction([this](Ts... x) { this->is_running_ = false; this->play(x...); })); } -template -void WhileAction::play(Ts... x) { +template void WhileAction::play(Ts... x) { if (this->is_running_) return; @@ -348,32 +251,24 @@ void WhileAction::play(Ts... x) { this->is_running_ = true; this->then_.play(x...); } -template -void WhileAction::stop() { +template void WhileAction::stop() { this->then_.stop(); this->is_running_ = false; this->stop_next(); } - -template -WaitUntilAction::WaitUntilAction(const std::vector *> &conditions) - : conditions_(conditions) { - -} template -void WaitUntilAction::play(Ts... x) { +WaitUntilAction::WaitUntilAction(const std::vector *> &conditions) : conditions_(conditions) {} +template void WaitUntilAction::play(Ts... x) { this->var_ = std::make_tuple(x...); this->triggered_ = true; this->loop(); } -template -void WaitUntilAction::stop() { +template void WaitUntilAction::stop() { this->triggered_ = false; this->stop_next(); } -template -void WaitUntilAction::loop() { +template void WaitUntilAction::loop() { if (!this->triggered_) return; @@ -386,8 +281,7 @@ void WaitUntilAction::loop() { this->triggered_ = false; this->play_next_tuple(this->var_); } -template -float WaitUntilAction::get_setup_priority() const { +template float WaitUntilAction::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } diff --git a/src/esphome/binary_sensor/binary_sensor.cpp b/src/esphome/binary_sensor/binary_sensor.cpp index b7b3c7c2..fec734c7 100644 --- a/src/esphome/binary_sensor/binary_sensor.cpp +++ b/src/esphome/binary_sensor/binary_sensor.cpp @@ -19,7 +19,7 @@ void BinarySensor::publish_state(bool state) { if (!this->publish_dedup_.next(state)) return; if (this->filter_list_ == nullptr) { - this->send_state_internal_(state, false); + this->send_state_internal(state, false); } else { this->filter_list_->input(state, false); } @@ -28,12 +28,12 @@ void BinarySensor::publish_initial_state(bool state) { if (!this->publish_dedup_.next(state)) return; if (this->filter_list_ == nullptr) { - this->send_state_internal_(state, true); + this->send_state_internal(state, true); } else { this->filter_list_->input(state, true); } } -void BinarySensor::send_state_internal_(bool state, bool is_initial) { +void BinarySensor::send_state_internal(bool state, bool is_initial) { ESP_LOGD(TAG, "'%s': Sending state %s", this->get_name().c_str(), state ? "ON" : "OFF"); this->has_state_ = true; this->state = state; @@ -41,31 +41,17 @@ void BinarySensor::send_state_internal_(bool state, bool is_initial) { this->state_callback_.call(state); } } -std::string BinarySensor::device_class() { - return ""; -} -BinarySensor::BinarySensor(const std::string &name) - : Nameable(name), state(false) { - -} -BinarySensor::BinarySensor() - : BinarySensor("") { - -} -void BinarySensor::set_device_class(const std::string &device_class) { - this->device_class_ = device_class; -} +std::string BinarySensor::device_class() { return ""; } +BinarySensor::BinarySensor(const std::string &name) : Nameable(name), state(false) {} +BinarySensor::BinarySensor() : BinarySensor("") {} +void BinarySensor::set_device_class(const std::string &device_class) { this->device_class_ = device_class; } std::string BinarySensor::get_device_class() { if (this->device_class_.has_value()) return *this->device_class_; return this->device_class(); } -PressTrigger *BinarySensor::make_press_trigger() { - return new PressTrigger(this); -} -ReleaseTrigger *BinarySensor::make_release_trigger() { - return new ReleaseTrigger(this); -} +PressTrigger *BinarySensor::make_press_trigger() { return new PressTrigger(this); } +ReleaseTrigger *BinarySensor::make_release_trigger() { return new ReleaseTrigger(this); } ClickTrigger *BinarySensor::make_click_trigger(uint32_t min_length, uint32_t max_length) { return new ClickTrigger(this, min_length, max_length); } @@ -88,9 +74,7 @@ void BinarySensor::add_filters(std::vector filters) { this->add_filter(filter); } } -bool BinarySensor::has_state() const { - return this->has_state_; -} +bool BinarySensor::has_state() const { return this->has_state_; } PressTrigger::PressTrigger(BinarySensor *parent) { parent->add_on_state_callback([this](bool state) { if (state) @@ -149,36 +133,22 @@ DoubleClickTrigger::DoubleClickTrigger(BinarySensor *parent, uint32_t min_length MultiClickTrigger *BinarySensor::make_multi_click_trigger(const std::vector &timing) { return new MultiClickTrigger(this, timing); } -uint32_t BinarySensor::hash_base_() { - return 1210250844UL; -} -StateTrigger *BinarySensor::make_state_trigger() { - return new StateTrigger(this); -} -bool BinarySensor::is_status_binary_sensor() const { - return false; -} +uint32_t BinarySensor::hash_base() { return 1210250844UL; } +StateTrigger *BinarySensor::make_state_trigger() { return new StateTrigger(this); } +bool BinarySensor::is_status_binary_sensor() const { return false; } #ifdef USE_MQTT_BINARY_SENSOR -MQTTBinarySensorComponent *BinarySensor::get_mqtt() const { - return this->mqtt_; -} -void BinarySensor::set_mqtt(MQTTBinarySensorComponent *mqtt) { - this->mqtt_ = mqtt; -} +MQTTBinarySensorComponent *BinarySensor::get_mqtt() const { return this->mqtt_; } +void BinarySensor::set_mqtt(MQTTBinarySensorComponent *mqtt) { this->mqtt_ = mqtt; } #endif MultiClickTrigger::MultiClickTrigger(BinarySensor *parent, const std::vector &timing) - : parent_(parent), timing_(timing) { - -} + : parent_(parent), timing_(timing) {} void MultiClickTrigger::setup() { this->last_state_ = this->parent_->state; auto f = std::bind(&MultiClickTrigger::on_state_, this, std::placeholders::_1); this->parent_->add_on_state_callback(f); } -float MultiClickTrigger::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float MultiClickTrigger::get_setup_priority() const { return setup_priority::HARDWARE; } void MultiClickTrigger::on_state_(bool state) { // Handle duplicate events if (state == this->last_state_) { @@ -199,9 +169,7 @@ void MultiClickTrigger::on_state_(bool state) { ESP_LOGV(TAG, "Multi Click: Starting multi click action!"); this->at_index_ = 1; if (this->timing_.size() == 1 && evt.max_length == 4294967294UL) { - this->set_timeout("trigger", evt.min_length, [this]() { - this->trigger_(); - }); + this->set_timeout("trigger", evt.min_length, [this]() { this->trigger_(); }); } else { this->schedule_is_valid_(evt.min_length); this->schedule_is_not_valid_(evt.max_length); @@ -237,16 +205,12 @@ void MultiClickTrigger::on_state_(bool state) { ESP_LOGV(TAG, "C i=%u min=%u", *this->at_index_, evt.min_length); this->is_valid_ = false; this->cancel_timeout("is_not_valid"); - this->set_timeout("trigger", evt.min_length, [this]() { - this->trigger_(); - }); + this->set_timeout("trigger", evt.min_length, [this]() { this->trigger_(); }); } *this->at_index_ = *this->at_index_ + 1; } -void MultiClickTrigger::set_invalid_cooldown(uint32_t invalid_cooldown) { - this->invalid_cooldown_ = invalid_cooldown; -} +void MultiClickTrigger::set_invalid_cooldown(uint32_t invalid_cooldown) { this->invalid_cooldown_ = invalid_cooldown; } void MultiClickTrigger::schedule_cooldown_() { ESP_LOGV(TAG, "Multi Click: Invalid length of press, starting cooldown of %u ms...", this->invalid_cooldown_); this->is_in_cooldown_ = true; @@ -283,13 +247,11 @@ void MultiClickTrigger::trigger_() { } StateTrigger::StateTrigger(BinarySensor *parent) { - parent->add_on_state_callback([this](bool state) { - this->trigger(state); - }); + parent->add_on_state_callback([this](bool state) { this->trigger(state); }); } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_BINARY_SENSOR +#endif // USE_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/binary_sensor.h b/src/esphome/binary_sensor/binary_sensor.h index 8a09a1f9..f9e98e07 100644 --- a/src/esphome/binary_sensor/binary_sensor.h +++ b/src/esphome/binary_sensor/binary_sensor.h @@ -22,11 +22,9 @@ class ClickTrigger; class DoubleClickTrigger; class MultiClickTrigger; class StateTrigger; -template -class BinarySensorCondition; +template class BinarySensorCondition; class Filter; -template -class BinarySensorPublishAction; +template class BinarySensorPublishAction; struct MultiClickTriggerEvent { bool state; @@ -35,12 +33,12 @@ struct MultiClickTriggerEvent { }; #define LOG_BINARY_SENSOR(prefix, type, obj) \ - if (obj != nullptr) { \ - ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ - if (!obj->get_device_class().empty()) { \ - ESP_LOGCONFIG(TAG, prefix " Device Class: '%s'", obj->get_device_class().c_str()); \ - } \ - } + if (obj != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ + if (!obj->get_device_class().empty()) { \ + ESP_LOGCONFIG(TAG, prefix " Device Class: '%s'", obj->get_device_class().c_str()); \ + } \ + } #ifdef USE_MQTT_BINARY_SENSOR class MQTTBinarySensorComponent; @@ -98,19 +96,16 @@ class BinarySensor : public Nameable { DoubleClickTrigger *make_double_click_trigger(uint32_t min_length, uint32_t max_length); MultiClickTrigger *make_multi_click_trigger(const std::vector &timing); StateTrigger *make_state_trigger(); - template - BinarySensorCondition *make_binary_sensor_is_on_condition(); - template - BinarySensorCondition *make_binary_sensor_is_off_condition(); - template - BinarySensorPublishAction *make_binary_sensor_publish_action(); + template BinarySensorCondition *make_binary_sensor_is_on_condition(); + template BinarySensorCondition *make_binary_sensor_is_off_condition(); + template BinarySensorPublishAction *make_binary_sensor_publish_action(); void add_filter(Filter *filter); void add_filters(std::vector filters); // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) - void send_state_internal_(bool state, bool is_initial); + void send_state_internal(bool state, bool is_initial); /// Return whether this binary sensor has outputted a state. bool has_state() const; @@ -122,16 +117,16 @@ class BinarySensor : public Nameable { void set_mqtt(MQTTBinarySensorComponent *mqtt); #endif - protected: // ========== OVERRIDE METHODS ========== // (You'll only need this when creating your own custom binary sensor) /// Get the default device class for this sensor, or empty string for no default. virtual std::string device_class(); - uint32_t hash_base_() override; + protected: + uint32_t hash_base() override; CallbackManager state_callback_{}; - optional device_class_{}; ///< Stores the override of the device class + optional device_class_{}; ///< Stores the override of the device class Filter *filter_list_{nullptr}; bool has_state_{false}; Deduplicator publish_dedup_; @@ -156,9 +151,9 @@ class ClickTrigger : public Trigger<> { explicit ClickTrigger(BinarySensor *parent, uint32_t min_length, uint32_t max_length); protected: - uint32_t start_time_{0}; /// The millis() time when the click started. - uint32_t min_length_; /// Minimum length of click. 0 means no minimum. - uint32_t max_length_; /// Maximum length of click. 0 means no maximum. + uint32_t start_time_{0}; /// The millis() time when the click started. + uint32_t min_length_; /// Minimum length of click. 0 means no minimum. + uint32_t max_length_; /// Maximum length of click. 0 means no maximum. }; class DoubleClickTrigger : public Trigger<> { @@ -168,8 +163,8 @@ class DoubleClickTrigger : public Trigger<> { protected: uint32_t start_time_{0}; uint32_t end_time_{0}; - uint32_t min_length_; /// Minimum length of click. 0 means no minimum. - uint32_t max_length_; /// Maximum length of click. 0 means no maximum. + uint32_t min_length_; /// Minimum length of click. 0 means no minimum. + uint32_t max_length_; /// Maximum length of click. 0 means no maximum. }; class MultiClickTrigger : public Trigger<>, public Component { @@ -203,64 +198,57 @@ class StateTrigger : public Trigger { explicit StateTrigger(BinarySensor *parent); }; -template -class BinarySensorCondition : public Condition { +template class BinarySensorCondition : public Condition { public: BinarySensorCondition(BinarySensor *parent, bool state); bool check(Ts... x) override; + protected: BinarySensor *parent_; bool state_; }; -template -class BinarySensorPublishAction : public Action { +template class BinarySensorPublishAction : public Action { public: BinarySensorPublishAction(BinarySensor *sensor); - template - void set_state(V value) { this->state_ = value; } + template void set_state(V value) { this->state_ = value; } void play(Ts... x) override; + protected: BinarySensor *sensor_; TemplatableValue state_; }; template -BinarySensorCondition::BinarySensorCondition(BinarySensor *parent, bool state) : parent_(parent), state_(state) { - -} -template -bool BinarySensorCondition::check(Ts... x) { +BinarySensorCondition::BinarySensorCondition(BinarySensor *parent, bool state) + : parent_(parent), state_(state) {} +template bool BinarySensorCondition::check(Ts... x) { return this->parent_->state == this->state_; } -template -BinarySensorCondition *BinarySensor::make_binary_sensor_is_on_condition() { +template BinarySensorCondition *BinarySensor::make_binary_sensor_is_on_condition() { return new BinarySensorCondition(this, true); } -template -BinarySensorCondition *BinarySensor::make_binary_sensor_is_off_condition() { +template BinarySensorCondition *BinarySensor::make_binary_sensor_is_off_condition() { return new BinarySensorCondition(this, false); } template BinarySensorPublishAction::BinarySensorPublishAction(BinarySensor *sensor) : sensor_(sensor) {} -template -void BinarySensorPublishAction::play(Ts... x) { +template void BinarySensorPublishAction::play(Ts... x) { auto val = this->state_.value(x...); this->sensor_->publish_state(val); this->play_next(x...); } -template -BinarySensorPublishAction *BinarySensor::make_binary_sensor_publish_action() { +template BinarySensorPublishAction *BinarySensor::make_binary_sensor_publish_action() { return new BinarySensorPublishAction(this); } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END #include "esphome/binary_sensor/mqtt_binary_sensor_component.h" -#endif //USE_BINARY_SENSOR +#endif // USE_BINARY_SENSOR -#endif //ESPHOME_BINARY_SENSOR_BINARY_SENSOR_H +#endif // ESPHOME_BINARY_SENSOR_BINARY_SENSOR_H diff --git a/src/esphome/binary_sensor/custom_binary_sensor.cpp b/src/esphome/binary_sensor/custom_binary_sensor.cpp index 64620fef..3c5b4847 100644 --- a/src/esphome/binary_sensor/custom_binary_sensor.cpp +++ b/src/esphome/binary_sensor/custom_binary_sensor.cpp @@ -14,17 +14,15 @@ static const char *TAG = "binary_sensor.custom"; CustomBinarySensorConstructor::CustomBinarySensorConstructor(const std::function()> &init) { this->binary_sensors_ = init(); } -BinarySensor *CustomBinarySensorConstructor::get_binary_sensor(int i) { - return this->binary_sensors_[i]; -} +BinarySensor *CustomBinarySensorConstructor::get_binary_sensor(int i) { return this->binary_sensors_[i]; } void CustomBinarySensorConstructor::dump_config() { for (auto *child : this->binary_sensors_) { LOG_BINARY_SENSOR("", "Custom Binary Sensor", child); } } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_BINARY_SENSOR +#endif // USE_CUSTOM_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/custom_binary_sensor.h b/src/esphome/binary_sensor/custom_binary_sensor.h index 91989f5f..7f62c807 100644 --- a/src/esphome/binary_sensor/custom_binary_sensor.h +++ b/src/esphome/binary_sensor/custom_binary_sensor.h @@ -24,10 +24,10 @@ class CustomBinarySensorConstructor : public Component { std::vector binary_sensors_; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_BINARY_SENSOR +#endif // USE_CUSTOM_BINARY_SENSOR -#endif //ESPHOME_BINARY_SENSOR_CUSTOM_BINARY_SENSOR_H +#endif // ESPHOME_BINARY_SENSOR_CUSTOM_BINARY_SENSOR_H diff --git a/src/esphome/binary_sensor/esp32_touch_binary_sensor.cpp b/src/esphome/binary_sensor/esp32_touch_binary_sensor.cpp index 5460cd32..d9c7c87e 100644 --- a/src/esphome/binary_sensor/esp32_touch_binary_sensor.cpp +++ b/src/esphome/binary_sensor/esp32_touch_binary_sensor.cpp @@ -20,8 +20,7 @@ void ESP32TouchComponent::setup() { } touch_pad_set_meas_time(this->sleep_cycle_, this->meas_cycle_); - touch_pad_set_voltage(this->high_voltage_reference_, this->low_voltage_reference_, - this->voltage_attenuation_); + touch_pad_set_voltage(this->high_voltage_reference_, this->low_voltage_reference_, this->voltage_attenuation_); for (auto *child : this->children_) { // Disable interrupt threshold @@ -44,35 +43,64 @@ void ESP32TouchComponent::dump_config() { const char *lv_s; switch (this->low_voltage_reference_) { - case TOUCH_LVOLT_0V5: lv_s = "0.5V"; break; - case TOUCH_LVOLT_0V6: lv_s = "0.6V"; break; - case TOUCH_LVOLT_0V7: lv_s = "0.7V"; break; - case TOUCH_LVOLT_0V8: lv_s = "0.8V"; break; - default: lv_s = "UNKNOWN"; break; + case TOUCH_LVOLT_0V5: + lv_s = "0.5V"; + break; + case TOUCH_LVOLT_0V6: + lv_s = "0.6V"; + break; + case TOUCH_LVOLT_0V7: + lv_s = "0.7V"; + break; + case TOUCH_LVOLT_0V8: + lv_s = "0.8V"; + break; + default: + lv_s = "UNKNOWN"; + break; } ESP_LOGCONFIG(TAG, " Low Voltage Reference: %s", lv_s); const char *hv_s; switch (this->high_voltage_reference_) { - case TOUCH_HVOLT_2V4: hv_s = "2.4V"; break; - case TOUCH_HVOLT_2V5: hv_s = "2.5V"; break; - case TOUCH_HVOLT_2V6: hv_s = "2.6V"; break; - case TOUCH_HVOLT_2V7: hv_s = "2.7V"; break; - default: hv_s = "UNKNOWN"; break; + case TOUCH_HVOLT_2V4: + hv_s = "2.4V"; + break; + case TOUCH_HVOLT_2V5: + hv_s = "2.5V"; + break; + case TOUCH_HVOLT_2V6: + hv_s = "2.6V"; + break; + case TOUCH_HVOLT_2V7: + hv_s = "2.7V"; + break; + default: + hv_s = "UNKNOWN"; + break; } ESP_LOGCONFIG(TAG, " High Voltage Reference: %s", hv_s); const char *atten_s; switch (this->voltage_attenuation_) { - case TOUCH_HVOLT_ATTEN_1V5: atten_s = "1.5V"; break; - case TOUCH_HVOLT_ATTEN_1V: atten_s = "1V"; break; - case TOUCH_HVOLT_ATTEN_0V5: atten_s = "0.5V"; break; - case TOUCH_HVOLT_ATTEN_0V: atten_s = "0V"; break; - default: atten_s = "UNKNOWN"; break; + case TOUCH_HVOLT_ATTEN_1V5: + atten_s = "1.5V"; + break; + case TOUCH_HVOLT_ATTEN_1V: + atten_s = "1V"; + break; + case TOUCH_HVOLT_ATTEN_0V5: + atten_s = "0.5V"; + break; + case TOUCH_HVOLT_ATTEN_0V: + atten_s = "0V"; + break; + default: + atten_s = "UNKNOWN"; + break; } ESP_LOGCONFIG(TAG, " Voltage Attenuation: %s", atten_s); - if (this->iir_filter_enabled_()) { ESP_LOGCONFIG(TAG, " IIR Filter: %ums", this->iir_filter_); touch_pad_filter_start(this->iir_filter_); @@ -111,30 +139,19 @@ void ESP32TouchComponent::loop() { delay(250); } } -ESP32TouchBinarySensor *ESP32TouchComponent::make_touch_pad(const std::string &name, - touch_pad_t touch_pad, +ESP32TouchBinarySensor *ESP32TouchComponent::make_touch_pad(const std::string &name, touch_pad_t touch_pad, uint16_t threshold) { auto *sensor = new ESP32TouchBinarySensor(name, touch_pad, threshold); this->children_.push_back(sensor); return sensor; } -void ESP32TouchComponent::set_setup_mode(bool setup_mode) { - this->setup_mode_ = setup_mode; -} +void ESP32TouchComponent::set_setup_mode(bool setup_mode) { this->setup_mode_ = setup_mode; } bool ESP32TouchComponent::iir_filter_enabled_() const { return this->iir_filter_ > 0; } -void ESP32TouchComponent::set_iir_filter(uint32_t iir_filter) { - this->iir_filter_ = iir_filter; -} -float ESP32TouchComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -void ESP32TouchComponent::set_sleep_duration(uint16_t sleep_duration) { - this->sleep_cycle_ = sleep_duration; -} -void ESP32TouchComponent::set_measurement_duration(uint16_t meas_cycle) { - this->meas_cycle_ = meas_cycle; -} +void ESP32TouchComponent::set_iir_filter(uint32_t iir_filter) { this->iir_filter_ = iir_filter; } +float ESP32TouchComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +void ESP32TouchComponent::set_sleep_duration(uint16_t sleep_duration) { this->sleep_cycle_ = sleep_duration; } +void ESP32TouchComponent::set_measurement_duration(uint16_t meas_cycle) { this->meas_cycle_ = meas_cycle; } void ESP32TouchComponent::set_low_voltage_reference(touch_low_volt_t low_voltage_reference) { this->low_voltage_reference_ = low_voltage_reference; } @@ -146,18 +163,12 @@ void ESP32TouchComponent::set_voltage_attenuation(touch_volt_atten_t voltage_att } ESP32TouchBinarySensor::ESP32TouchBinarySensor(const std::string &name, touch_pad_t touch_pad, uint16_t threshold) - : BinarySensor(name), touch_pad_(touch_pad), threshold_(threshold) { - -} -touch_pad_t ESP32TouchBinarySensor::get_touch_pad() const { - return this->touch_pad_; -} -uint16_t ESP32TouchBinarySensor::get_threshold() const { - return this->threshold_; -} + : BinarySensor(name), touch_pad_(touch_pad), threshold_(threshold) {} +touch_pad_t ESP32TouchBinarySensor::get_touch_pad() const { return this->touch_pad_; } +uint16_t ESP32TouchBinarySensor::get_threshold() const { return this->threshold_; } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_ESP32_TOUCH_BINARY_SENSOR +#endif // USE_ESP32_TOUCH_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/esp32_touch_binary_sensor.h b/src/esphome/binary_sensor/esp32_touch_binary_sensor.h index d7bbc9df..df5d933a 100644 --- a/src/esphome/binary_sensor/esp32_touch_binary_sensor.h +++ b/src/esphome/binary_sensor/esp32_touch_binary_sensor.h @@ -85,7 +85,8 @@ class ESP32TouchComponent : public Component { /** Setup an infinite impulse response filter to improve accuracy of the touch readings. * - * See [Filtering Pulses](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/touch_pad.html#filtering-of-measurements + * See [Filtering + * Pulses](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/touch_pad.html#filtering-of-measurements * for more information). Good values for this can be 20ms or so, but often the default of no filter works * just fine. * @@ -199,10 +200,10 @@ class ESP32TouchBinarySensor : public BinarySensor { uint16_t threshold_; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_ESP32_TOUCH_BINARY_SENSOR +#endif // USE_ESP32_TOUCH_BINARY_SENSOR -#endif //ESPHOME_BINARY_SENSOR_ESP32_TOUCH_BINARY_SENSOR_H +#endif // ESPHOME_BINARY_SENSOR_ESP32_TOUCH_BINARY_SENSOR_H diff --git a/src/esphome/binary_sensor/filter.cpp b/src/esphome/binary_sensor/filter.cpp index 4af294d6..cb274c9f 100644 --- a/src/esphome/binary_sensor/filter.cpp +++ b/src/esphome/binary_sensor/filter.cpp @@ -13,7 +13,7 @@ void Filter::output(bool value, bool is_initial) { return; if (this->next_ == nullptr) { - this->parent_->send_state_internal_(value, is_initial); + this->parent_->send_state_internal(value, is_initial); } else { this->next_->input(value, is_initial); } @@ -24,14 +24,10 @@ void Filter::input(bool value, bool is_initial) { this->output(*b, is_initial); } } -DelayedOnFilter::DelayedOnFilter(uint32_t delay) : delay_(delay) { - -} +DelayedOnFilter::DelayedOnFilter(uint32_t delay) : delay_(delay) {} optional DelayedOnFilter::new_value(bool value, bool is_initial) { if (value) { - this->set_timeout("ON", this->delay_, [this, is_initial](){ - this->output(true, is_initial); - }); + this->set_timeout("ON", this->delay_, [this, is_initial]() { this->output(true, is_initial); }); return {}; } else { this->cancel_timeout("ON"); @@ -39,37 +35,25 @@ optional DelayedOnFilter::new_value(bool value, bool is_initial) { } } -float DelayedOnFilter::get_setup_priority() const { - return setup_priority::HARDWARE; -} - -DelayedOffFilter::DelayedOffFilter(uint32_t delay) : delay_(delay) { +float DelayedOnFilter::get_setup_priority() const { return setup_priority::HARDWARE; } -} +DelayedOffFilter::DelayedOffFilter(uint32_t delay) : delay_(delay) {} optional DelayedOffFilter::new_value(bool value, bool is_initial) { if (!value) { - this->set_timeout("OFF", this->delay_, [this, is_initial](){ - this->output(false, is_initial); - }); + this->set_timeout("OFF", this->delay_, [this, is_initial]() { this->output(false, is_initial); }); return {}; } else { this->cancel_timeout("OFF"); return true; } } -float DelayedOffFilter::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float DelayedOffFilter::get_setup_priority() const { return setup_priority::HARDWARE; } -optional InvertFilter::new_value(bool value, bool is_initial) { - return !value; -} +optional InvertFilter::new_value(bool value, bool is_initial) { return !value; } LambdaFilter::LambdaFilter(const std::function(bool)> &f) : f_(f) {} -optional LambdaFilter::new_value(bool value, bool is_initial) { - return this->f_(value); -} +optional LambdaFilter::new_value(bool value, bool is_initial) { return this->f_(value); } optional UniqueFilter::new_value(bool value, bool is_initial) { if (this->last_value_.has_value() && *this->last_value_ == value) { @@ -79,8 +63,8 @@ optional UniqueFilter::new_value(bool value, bool is_initial) { return value; } } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_BINARY_SENSOR +#endif // USE_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/filter.h b/src/esphome/binary_sensor/filter.h index bdc7e394..27c0cb21 100644 --- a/src/esphome/binary_sensor/filter.h +++ b/src/esphome/binary_sensor/filter.h @@ -76,10 +76,10 @@ class UniqueFilter : public Filter { optional last_value_{}; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_BINARY_SENSOR +#endif // USE_BINARY_SENSOR -#endif //ESPHOME_FILTER_H +#endif // ESPHOME_FILTER_H diff --git a/src/esphome/binary_sensor/gpio_binary_sensor_component.cpp b/src/esphome/binary_sensor/gpio_binary_sensor_component.cpp index ec564107..07c812aa 100644 --- a/src/esphome/binary_sensor/gpio_binary_sensor_component.cpp +++ b/src/esphome/binary_sensor/gpio_binary_sensor_component.cpp @@ -23,20 +23,14 @@ void GPIOBinarySensorComponent::dump_config() { LOG_PIN(" Pin: ", this->pin_); } -void GPIOBinarySensorComponent::loop() { - this->publish_state(this->pin_->digital_read()); -} +void GPIOBinarySensorComponent::loop() { this->publish_state(this->pin_->digital_read()); } -float GPIOBinarySensorComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float GPIOBinarySensorComponent::get_setup_priority() const { return setup_priority::HARDWARE; } GPIOBinarySensorComponent::GPIOBinarySensorComponent(const std::string &name, GPIOPin *pin) - : BinarySensor(name), pin_(pin) { - -} + : BinarySensor(name), pin_(pin) {} -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_GPIO_BINARY_SENSOR +#endif // USE_GPIO_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/gpio_binary_sensor_component.h b/src/esphome/binary_sensor/gpio_binary_sensor_component.h index 0b7b32ac..746ac5ab 100644 --- a/src/esphome/binary_sensor/gpio_binary_sensor_component.h +++ b/src/esphome/binary_sensor/gpio_binary_sensor_component.h @@ -39,10 +39,10 @@ class GPIOBinarySensorComponent : public BinarySensor, public Component { GPIOPin *pin_; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_GPIO_BINARY_SENSOR +#endif // USE_GPIO_BINARY_SENSOR -#endif //ESPHOME_BINARY_SENSOR_GPIO_BINARY_SENSOR_COMPONENT_H +#endif // ESPHOME_BINARY_SENSOR_GPIO_BINARY_SENSOR_COMPONENT_H diff --git a/src/esphome/binary_sensor/homeassistant_binary_sensor.cpp b/src/esphome/binary_sensor/homeassistant_binary_sensor.cpp index b3b1fae9..111edcc9 100644 --- a/src/esphome/binary_sensor/homeassistant_binary_sensor.cpp +++ b/src/esphome/binary_sensor/homeassistant_binary_sensor.cpp @@ -35,14 +35,12 @@ void HomeassistantBinarySensor::dump_config() { LOG_BINARY_SENSOR("", "Homeassistant Binary Sensor", this); ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str()); } -float HomeassistantBinarySensor::get_setup_priority() const { - return setup_priority::WIFI; -} +float HomeassistantBinarySensor::get_setup_priority() const { return setup_priority::WIFI; } HomeassistantBinarySensor::HomeassistantBinarySensor(const std::string &name, const std::string &entity_id) : BinarySensor(name), entity_id_(entity_id) {} -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_BINARY_SENSOR +#endif // USE_HOMEASSISTANT_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/homeassistant_binary_sensor.h b/src/esphome/binary_sensor/homeassistant_binary_sensor.h index bbe12ef4..d81401dd 100644 --- a/src/esphome/binary_sensor/homeassistant_binary_sensor.h +++ b/src/esphome/binary_sensor/homeassistant_binary_sensor.h @@ -18,14 +18,15 @@ class HomeassistantBinarySensor : public BinarySensor, public Component { void setup() override; void dump_config() override; float get_setup_priority() const override; + protected: std::string entity_id_; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_BINARY_SENSOR +#endif // USE_HOMEASSISTANT_BINARY_SENSOR -#endif //ESPHOME_HOMEASSISTANT_BINARY_SENSOR_H +#endif // ESPHOME_HOMEASSISTANT_BINARY_SENSOR_H diff --git a/src/esphome/binary_sensor/mpr121_sensor.cpp b/src/esphome/binary_sensor/mpr121_sensor.cpp index aa5e531a..ef06cf57 100644 --- a/src/esphome/binary_sensor/mpr121_sensor.cpp +++ b/src/esphome/binary_sensor/mpr121_sensor.cpp @@ -10,11 +10,9 @@ namespace binary_sensor { static const char *TAG = "binary_sensor.mpr121"; -MPR121Channel::MPR121Channel(const std::string &name, int channel_num) : BinarySensor(name) { - channel_ = channel_num; -} +MPR121Channel::MPR121Channel(const std::string &name, int channel_num) : BinarySensor(name) { channel_ = channel_num; } -void MPR121Channel::process(uint16_t *data, uint16_t *last_data) { +void MPR121Channel::process(const uint16_t *data, const uint16_t *last_data) { if ((*data & (1 << this->channel_)) && !(*last_data & (1 << this->channel_))) { this->publish_state(true); } @@ -23,8 +21,7 @@ void MPR121Channel::process(uint16_t *data, uint16_t *last_data) { } } -MPR121Component::MPR121Component(I2CComponent *parent, uint8_t address) : I2CDevice(parent, address) { -} +MPR121Component::MPR121Component(I2CComponent *parent, uint8_t address) : I2CDevice(parent, address) {} void MPR121Component::setup() { ESP_LOGCONFIG(TAG, "Setting up MPR121..."); @@ -61,7 +58,7 @@ void MPR121Component::setup() { this->write_byte(MPR121_CONFIG1, 0x10); // 0.5uS encoding, 1ms period this->write_byte(MPR121_CONFIG2, 0x20); - // start with first 5 bits of baseline tracking + // start with first 5 bits of baseline tracking this->write_byte(MPR121_ECR, 0x8F); } @@ -81,9 +78,7 @@ void MPR121Component::dump_config() { } } -float MPR121Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float MPR121Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } MPR121Channel *MPR121Component::add_channel(binary_sensor::MPR121Channel *channel) { this->channels_.push_back(channel); @@ -101,7 +96,7 @@ uint16_t MPR121Component::read_mpr121_channels_() { this->read_byte_16(MPR121_TOUCHSTATUS_L, &val); uint8_t lsb = val >> 8; uint8_t msb = val; - val = ((uint16_t)msb) << 8; + val = ((uint16_t) msb) << 8; val |= lsb; return val; } diff --git a/src/esphome/binary_sensor/mpr121_sensor.h b/src/esphome/binary_sensor/mpr121_sensor.h index 76ae987a..51b0a3be 100644 --- a/src/esphome/binary_sensor/mpr121_sensor.h +++ b/src/esphome/binary_sensor/mpr121_sensor.h @@ -54,7 +54,7 @@ enum { class MPR121Channel : public binary_sensor::BinarySensor { public: MPR121Channel(const std::string &name, int channel_num = 0); - void process(uint16_t *data, uint16_t *last_data); + void process(const uint16_t *data, const uint16_t *last_data); protected: int channel_ = 0; diff --git a/src/esphome/binary_sensor/mqtt_binary_sensor_component.cpp b/src/esphome/binary_sensor/mqtt_binary_sensor_component.cpp index 9dfcd33f..698ba980 100644 --- a/src/esphome/binary_sensor/mqtt_binary_sensor_component.cpp +++ b/src/esphome/binary_sensor/mqtt_binary_sensor_component.cpp @@ -11,14 +11,10 @@ namespace binary_sensor { static const char *TAG = "binary_sensor.mqtt"; -std::string MQTTBinarySensorComponent::component_type() const { - return "binary_sensor"; -} +std::string MQTTBinarySensorComponent::component_type() const { return "binary_sensor"; } void MQTTBinarySensorComponent::setup() { - this->binary_sensor_->add_on_state_callback([this](bool state) { - this->publish_state(state); - }); + this->binary_sensor_->add_on_state_callback([this](bool state) { this->publish_state(state); }); } void MQTTBinarySensorComponent::dump_config() { @@ -26,12 +22,8 @@ void MQTTBinarySensorComponent::dump_config() { LOG_MQTT_COMPONENT(true, false) } MQTTBinarySensorComponent::MQTTBinarySensorComponent(BinarySensor *binary_sensor) - : MQTTComponent(), binary_sensor_(binary_sensor) { - -} -std::string MQTTBinarySensorComponent::friendly_name() const { - return this->binary_sensor_->get_name(); -} + : MQTTComponent(), binary_sensor_(binary_sensor) {} +std::string MQTTBinarySensorComponent::friendly_name() const { return this->binary_sensor_->get_name(); } void MQTTBinarySensorComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (!this->binary_sensor_->get_device_class().empty()) @@ -49,22 +41,18 @@ bool MQTTBinarySensorComponent::send_initial_state() { return true; } } -bool MQTTBinarySensorComponent::is_internal() { - return this->binary_sensor_->is_internal(); -} +bool MQTTBinarySensorComponent::is_internal() { return this->binary_sensor_->is_internal(); } bool MQTTBinarySensorComponent::publish_state(bool state) { if (this->is_status_) return true; const char *state_s = state ? "ON" : "OFF"; - return this->publish(this->get_state_topic(), state_s); -} -void MQTTBinarySensorComponent::set_is_status(bool status) { - this->is_status_ = status; + return this->publish(this->get_state_topic_(), state_s); } +void MQTTBinarySensorComponent::set_is_status(bool status) { this->is_status_ = status; } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_BINARY_SENSOR +#endif // USE_MQTT_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/mqtt_binary_sensor_component.h b/src/esphome/binary_sensor/mqtt_binary_sensor_component.h index 6fdde977..40dd2dee 100644 --- a/src/esphome/binary_sensor/mqtt_binary_sensor_component.h +++ b/src/esphome/binary_sensor/mqtt_binary_sensor_component.h @@ -33,7 +33,7 @@ class MQTTBinarySensorComponent : public mqtt::MQTTComponent { void dump_config() override; /// Send Home Assistant discovery info - void send_discovery(JsonObject &obj, mqtt::SendDiscoveryConfig &config) override; + void send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) override; void set_is_status(bool status); @@ -51,10 +51,10 @@ class MQTTBinarySensorComponent : public mqtt::MQTTComponent { bool is_status_{false}; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_BINARY_SENSOR +#endif // USE_MQTT_BINARY_SENSOR -#endif //ESPHOME_BINARY_SENSOR_MQTT_BINARY_SENSOR_COMPONENT_H +#endif // ESPHOME_BINARY_SENSOR_MQTT_BINARY_SENSOR_COMPONENT_H diff --git a/src/esphome/binary_sensor/pn532_component.cpp b/src/esphome/binary_sensor/pn532_component.cpp index 26d94472..a56d9620 100644 --- a/src/esphome/binary_sensor/pn532_component.cpp +++ b/src/esphome/binary_sensor/pn532_component.cpp @@ -34,15 +34,15 @@ void PN532Component::setup() { delay(10); // Send dummy command to sync up with PN532 but ignore result - this->buffer_[0] = 0x02; // GET_FIRMWARE_VERSION + this->buffer_[0] = 0x02; // GET_FIRMWARE_VERSION this->pn532_write_command_check_ack_(1, true); // setup secure access module this->buffer_[0] = 0x14; - this->buffer_[1] = 0x01; // normal mode + this->buffer_[1] = 0x01; // normal mode // The length of a scan as a multiple of 50ms this->buffer_[2] = std::min(255u, this->update_interval_ / 50); - this->buffer_[3] = 0x01; // use IRQ pin, actually we don't need it but can't hurt either + this->buffer_[3] = 0x01; // use IRQ pin, actually we don't need it but can't hurt either if (!this->pn532_write_command_check_ack_(4)) { this->error_code_ = WRITING_SAM_COMMAND_FAILED; @@ -59,9 +59,9 @@ void PN532Component::setup() { } void PN532Component::update() { - this->buffer_[0] = 0x4A; // INLISTPASSIVETARGET - this->buffer_[1] = 0x01; // max 1 cards at once - this->buffer_[2] = 0x00; // Baud rate ISO14443A + this->buffer_[0] = 0x4A; // INLISTPASSIVETARGET + this->buffer_[1] = 0x01; // max 1 cards at once + this->buffer_[2] = 0x00; // Baud rate ISO14443A if (!this->pn532_write_command_check_ack_(3)) { ESP_LOGW(TAG, "Requesting TAG read failed!"); this->status_set_warning(); @@ -71,7 +71,7 @@ void PN532Component::update() { this->requested_read_ = true; } void PN532Component::loop() { - if (!this->requested_read_ || !this->is_ready()) + if (!this->requested_read_ || !this->is_ready_()) return; this->pn532_read_data_(20); @@ -117,7 +117,7 @@ void PN532Component::loop() { } } -bool PN532BinarySensor::process(uint8_t *data, uint8_t len) { +bool PN532BinarySensor::process(const uint8_t *data, uint8_t len) { if (len != this->uid_.size()) return false; @@ -131,9 +131,7 @@ bool PN532BinarySensor::process(uint8_t *data, uint8_t len) { this->publish_state(false); return true; } -float PN532Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float PN532Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void PN532Component::pn532_write_command_(uint8_t len) { this->enable(); @@ -170,7 +168,7 @@ bool PN532Component::pn532_write_command_check_ack_(uint8_t len, bool ignore) { this->pn532_write_command_(len); uint32_t start_time = millis(); - while (!this->is_ready()) { + while (!this->is_ready_()) { if (millis() - start_time > 100) { if (!ignore) { ESP_LOGE(TAG, "Timed out waiting for ACK from PN532!"); @@ -180,7 +178,7 @@ bool PN532Component::pn532_write_command_check_ack_(uint8_t len, bool ignore) { yield(); } - if (!this->read_ack()) { + if (!this->read_ack_()) { if (!ignore) { ESP_LOGE(TAG, "Invalid ACK frame received from PN532!"); } @@ -214,7 +212,7 @@ PN532Trigger *PN532Component::make_trigger() { this->triggers_.push_back(trigger); return trigger; } -bool PN532Component::is_ready() { +bool PN532Component::is_ready_() { this->enable(); // Mark we're reading state this->write_byte(0x02); @@ -225,7 +223,7 @@ bool PN532Component::is_ready() { } return ret; } -bool PN532Component::read_ack() { +bool PN532Component::read_ack_() { ESP_LOGVV(TAG, "Reading ACK..."); this->enable(); // Mark we're reading @@ -242,17 +240,14 @@ bool PN532Component::read_ack() { return matches; } PN532Component::PN532Component(SPIComponent *parent, GPIOPin *cs, uint32_t update_interval) - : PollingComponent(update_interval), SPIDevice(parent, cs) { - -} + : PollingComponent(update_interval), SPIDevice(parent, cs) {} -bool PN532Component::msb_first() { - return false; -} +bool PN532Component::is_device_msb_first() { return false; } void PN532Component::dump_config() { ESP_LOGCONFIG(TAG, "PN532:"); switch (this->error_code_) { - case NONE:break; + case NONE: + break; case WRITING_SAM_COMMAND_FAILED: ESP_LOGE(TAG, "Writing SAM command failed!"); break; @@ -281,8 +276,8 @@ void PN532Trigger::process(uint8_t *uid, uint8_t uid_length) { this->trigger(std::string(buf)); } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_PN532 +#endif // USE_PN532 diff --git a/src/esphome/binary_sensor/pn532_component.h b/src/esphome/binary_sensor/pn532_component.h index cb7e7af0..c356cc3b 100644 --- a/src/esphome/binary_sensor/pn532_component.h +++ b/src/esphome/binary_sensor/pn532_component.h @@ -34,16 +34,16 @@ class PN532Component : public PollingComponent, public SPIDevice { PN532Trigger *make_trigger(); protected: - bool msb_first() override; + bool is_device_msb_first() override; void pn532_write_command_(uint8_t len); bool pn532_write_command_check_ack_(uint8_t len, bool ignore = false); void pn532_read_data_(uint8_t len); - bool is_ready(); + bool is_ready_(); - bool read_ack(); + bool read_ack_(); uint8_t buffer_[32]; bool requested_read_{false}; @@ -61,7 +61,8 @@ class PN532BinarySensor : public binary_sensor::BinarySensor { public: PN532BinarySensor(const std::string &name, const std::vector &uid, uint32_t update_interval); - bool process(uint8_t *data, uint8_t len); + bool process(const uint8_t *data, uint8_t len); + protected: std::vector uid_; }; @@ -71,10 +72,10 @@ class PN532Trigger : public Trigger { void process(uint8_t *uid, uint8_t uid_length); }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_PN532 +#endif // USE_PN532 -#endif //ESPHOME_PN_532_COMPONENT_H +#endif // ESPHOME_PN_532_COMPONENT_H diff --git a/src/esphome/binary_sensor/rdm6300.cpp b/src/esphome/binary_sensor/rdm6300.cpp index 93bc10f1..c3af39cd 100644 --- a/src/esphome/binary_sensor/rdm6300.cpp +++ b/src/esphome/binary_sensor/rdm6300.cpp @@ -15,7 +15,6 @@ static const uint8_t RDM6300_START_BYTE = 0x02; static const uint8_t RDM6300_END_BYTE = 0x03; static const int8_t RDM6300_STATE_WAITING_FOR_START = -1; - void RDM6300Component::loop() { while (this->available() > 0) { uint8_t data; @@ -52,11 +51,8 @@ void RDM6300Component::loop() { } else { // Valid data this->status_clear_warning(); - const uint32_t result = - (uint32_t(this->buffer_[1]) << 24) - | (uint32_t(this->buffer_[2]) << 16) - | (uint32_t(this->buffer_[3]) << 8) - | this->buffer_[4]; + const uint32_t result = (uint32_t(this->buffer_[1]) << 24) | (uint32_t(this->buffer_[2]) << 16) | + (uint32_t(this->buffer_[3]) << 8) | this->buffer_[4]; bool report = result != last_id_; for (auto *card : this->cards_) { if (card->process(result)) { @@ -76,18 +72,10 @@ RDM6300BinarySensor *RDM6300Component::make_card(const std::string &name, uint32 this->cards_.push_back(card); return card; } -float RDM6300Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -RDM6300Component::RDM6300Component(UARTComponent *parent) - : Component(), UARTDevice(parent) { - -} - -RDM6300BinarySensor::RDM6300BinarySensor(const std::string &name, uint32_t id) - : BinarySensor(name), id_(id) { +float RDM6300Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +RDM6300Component::RDM6300Component(UARTComponent *parent) : Component(), UARTDevice(parent) {} -} +RDM6300BinarySensor::RDM6300BinarySensor(const std::string &name, uint32_t id) : BinarySensor(name), id_(id) {} bool RDM6300BinarySensor::process(uint32_t id) { if (this->id_ == id) { this->publish_state(true); @@ -98,8 +86,8 @@ bool RDM6300BinarySensor::process(uint32_t id) { return false; } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_RDM6300 +#endif // USE_RDM6300 diff --git a/src/esphome/binary_sensor/rdm6300.h b/src/esphome/binary_sensor/rdm6300.h index 2a70e533..1bd1b1b3 100644 --- a/src/esphome/binary_sensor/rdm6300.h +++ b/src/esphome/binary_sensor/rdm6300.h @@ -36,14 +36,15 @@ class RDM6300BinarySensor : public BinarySensor { RDM6300BinarySensor(const std::string &name, uint32_t id); bool process(uint32_t id); + protected: uint32_t id_; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_RDM6300 +#endif // USE_RDM6300 -#endif //ESPHOME_RDM_6300_H +#endif // ESPHOME_RDM_6300_H diff --git a/src/esphome/binary_sensor/status_binary_sensor.cpp b/src/esphome/binary_sensor/status_binary_sensor.cpp index 10add189..f0e67e7e 100644 --- a/src/esphome/binary_sensor/status_binary_sensor.cpp +++ b/src/esphome/binary_sensor/status_binary_sensor.cpp @@ -14,13 +14,8 @@ namespace binary_sensor { static const char *TAG = "binary_sensor.status"; -std::string StatusBinarySensor::device_class() { - return "connectivity"; -} -StatusBinarySensor::StatusBinarySensor(const std::string &name) - : BinarySensor(name) { - -} +std::string StatusBinarySensor::device_class() { return "connectivity"; } +StatusBinarySensor::StatusBinarySensor(const std::string &name) : BinarySensor(name) {} void StatusBinarySensor::loop() { bool status = network_is_connected(); #ifdef USE_MQTT @@ -34,21 +29,13 @@ void StatusBinarySensor::loop() { this->last_status_ = status; } } -void StatusBinarySensor::setup() { - this->publish_state(false); -} -float StatusBinarySensor::get_setup_priority() const { - return setup_priority::HARDWARE; -} -bool StatusBinarySensor::is_status_binary_sensor() const { - return true; -} -void StatusBinarySensor::dump_config() { - LOG_BINARY_SENSOR("", "Status Binary Sensor", this); -} +void StatusBinarySensor::setup() { this->publish_state(false); } +float StatusBinarySensor::get_setup_priority() const { return setup_priority::HARDWARE; } +bool StatusBinarySensor::is_status_binary_sensor() const { return true; } +void StatusBinarySensor::dump_config() { LOG_BINARY_SENSOR("", "Status Binary Sensor", this); } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_STATUS_BINARY_SENSOR +#endif // USE_STATUS_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/status_binary_sensor.h b/src/esphome/binary_sensor/status_binary_sensor.h index dad08967..af5c5acf 100644 --- a/src/esphome/binary_sensor/status_binary_sensor.h +++ b/src/esphome/binary_sensor/status_binary_sensor.h @@ -35,10 +35,10 @@ class StatusBinarySensor : public BinarySensor, public Component { bool last_status_{false}; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_STATUS_BINARY_SENSOR +#endif // USE_STATUS_BINARY_SENSOR -#endif //ESPHOME_STATUS_BINARY_SENSOR_H +#endif // ESPHOME_STATUS_BINARY_SENSOR_H diff --git a/src/esphome/binary_sensor/template_binary_sensor.cpp b/src/esphome/binary_sensor/template_binary_sensor.cpp index e962b76b..52a542e5 100644 --- a/src/esphome/binary_sensor/template_binary_sensor.cpp +++ b/src/esphome/binary_sensor/template_binary_sensor.cpp @@ -11,10 +11,7 @@ namespace binary_sensor { static const char *TAG = "binary_sensor.template"; -TemplateBinarySensor::TemplateBinarySensor(const std::string &name) - : BinarySensor(name) { - -} +TemplateBinarySensor::TemplateBinarySensor(const std::string &name) : BinarySensor(name) {} void TemplateBinarySensor::loop() { if (!this->f_.has_value()) return; @@ -24,19 +21,12 @@ void TemplateBinarySensor::loop() { this->publish_state(*s); } } -float TemplateBinarySensor::get_setup_priority() const { - return setup_priority::HARDWARE; -} -void TemplateBinarySensor::set_template(std::function()> &&f) { - this->f_ = std::move(f); -} -void TemplateBinarySensor::dump_config() { - LOG_BINARY_SENSOR("", "Template Binary Sensor", this); -} +float TemplateBinarySensor::get_setup_priority() const { return setup_priority::HARDWARE; } +void TemplateBinarySensor::set_template(std::function()> &&f) { this->f_ = f; } +void TemplateBinarySensor::dump_config() { LOG_BINARY_SENSOR("", "Template Binary Sensor", this); } -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_BINARY_SENSOR - +#endif // USE_TEMPLATE_BINARY_SENSOR diff --git a/src/esphome/binary_sensor/template_binary_sensor.h b/src/esphome/binary_sensor/template_binary_sensor.h index fe89ade5..a5ef8c64 100644 --- a/src/esphome/binary_sensor/template_binary_sensor.h +++ b/src/esphome/binary_sensor/template_binary_sensor.h @@ -27,10 +27,10 @@ class TemplateBinarySensor : public Component, public BinarySensor { optional()>> f_; }; -} // namespace binary_sensor +} // namespace binary_sensor ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_BINARY_SENSOR +#endif // USE_TEMPLATE_BINARY_SENSOR -#endif //ESPHOME_BINARY_SENSOR_TEMPLATE_BINARY_SENSOR_H +#endif // ESPHOME_BINARY_SENSOR_TEMPLATE_BINARY_SENSOR_H diff --git a/src/esphome/component.cpp b/src/esphome/component.cpp index ece742f2..f20ca8eb 100644 --- a/src/esphome/component.cpp +++ b/src/esphome/component.cpp @@ -20,7 +20,7 @@ const float MQTT_CLIENT = 7.5f; const float MQTT_COMPONENT = -5.0f; const float LATE = -10.0f; -} // namespace setup_priority +} // namespace setup_priority const uint32_t COMPONENT_STATE_MASK = 0xFF; const uint32_t COMPONENT_STATE_CONSTRUCTION = 0x00; @@ -34,23 +34,15 @@ const uint32_t STATUS_LED_ERROR = 0x0200; uint32_t global_state = 0; -float Component::get_loop_priority() const { - return 0.0f; -} - -float Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float Component::get_loop_priority() const { return 0.0f; } -void Component::setup() { +float Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -} +void Component::setup() {} -void Component::loop() { +void Component::loop() {} -} - -void Component::set_interval(const std::string &name, uint32_t interval, std::function &&f) { +void Component::set_interval(const std::string &name, uint32_t interval, std::function &&f) { // NOLINT const uint32_t now = millis(); // only put offset in lower half uint32_t offset = 0; @@ -72,11 +64,11 @@ void Component::set_interval(const std::string &name, uint32_t interval, std::fu this->time_functions_.push_back(function); } -bool Component::cancel_interval(const std::string &name) { - return this->cancel_time_function(name, TimeFunction::INTERVAL); +bool Component::cancel_interval(const std::string &name) { // NOLINT + return this->cancel_time_function_(name, TimeFunction::INTERVAL); } -void Component::set_timeout(const std::string &name, uint32_t timeout, std::function &&f) { +void Component::set_timeout(const std::string &name, uint32_t timeout, std::function &&f) { // NOLINT const uint32_t now = millis(); ESP_LOGVV(TAG, "set_timeout(name='%s', timeout=%u)", name.c_str(), timeout); @@ -94,16 +86,17 @@ void Component::set_timeout(const std::string &name, uint32_t timeout, std::func this->time_functions_.push_back(function); } -bool Component::cancel_timeout(const std::string &name) { - return this->cancel_time_function(name, TimeFunction::TIMEOUT); +bool Component::cancel_timeout(const std::string &name) { // NOLINT + return this->cancel_time_function_(name, TimeFunction::TIMEOUT); } -void Component::loop_() { - this->loop_internal(); +void Component::call_loop() { + this->loop_internal_(); this->loop(); } -bool Component::cancel_time_function(const std::string &name, TimeFunction::Type type) { +bool Component::cancel_time_function_(const std::string &name, TimeFunction::Type type) { + // NOLINTNEXTLINE for (auto iter = this->time_functions_.begin(); iter != this->time_functions_.end(); iter++) { if (!iter->remove && iter->name == name && iter->type == type) { ESP_LOGVV(TAG, "Removing old time function %s.", iter->name.c_str()); @@ -113,25 +106,24 @@ bool Component::cancel_time_function(const std::string &name, TimeFunction::Type } return false; } -void Component::setup_() { - this->setup_internal(); +void Component::call_setup() { + this->setup_internal_(); this->setup(); } -uint32_t Component::get_component_state() const { - return this->component_state_; -} -void Component::loop_internal() { +uint32_t Component::get_component_state() const { return this->component_state_; } +void Component::loop_internal_() { this->component_state_ &= ~COMPONENT_STATE_MASK; this->component_state_ |= COMPONENT_STATE_LOOP; - for (unsigned int i = 0; i < this->time_functions_.size(); i++) { // NOLINT + for (unsigned int i = 0; i < this->time_functions_.size(); i++) { // NOLINT const uint32_t now = millis(); TimeFunction *tf = &this->time_functions_[i]; if (tf->should_run(now)) { #ifdef ESPHOME_LOG_HAS_VERY_VERBOSE - const char *type = tf->type == TimeFunction::INTERVAL ? "interval" : (tf->type == TimeFunction::TIMEOUT ? "timeout" : "defer"); - ESP_LOGVV(TAG, "Running %s '%s':%u with interval=%u last_execution=%u (now=%u)", - type, tf->name.c_str(), i, tf->interval, tf->last_execution, now); + const char *type = + tf->type == TimeFunction::INTERVAL ? "interval" : (tf->type == TimeFunction::TIMEOUT ? "timeout" : "defer"); + ESP_LOGVV(TAG, "Running %s '%s':%u with interval=%u last_execution=%u (now=%u)", type, tf->name.c_str(), i, + tf->interval, tf->last_execution, now); #endif tf->f(); @@ -147,15 +139,11 @@ void Component::loop_internal() { } } - this->time_functions_.erase( - std::remove_if(this->time_functions_.begin(), this->time_functions_.end(), - [](const TimeFunction &tf) -> bool { - return tf.remove; - }), - this->time_functions_.end() - ); + this->time_functions_.erase(std::remove_if(this->time_functions_.begin(), this->time_functions_.end(), + [](const TimeFunction &tf) -> bool { return tf.remove; }), + this->time_functions_.end()); } -void Component::setup_internal() { +void Component::setup_internal_() { this->component_state_ &= ~COMPONENT_STATE_MASK; this->component_state_ |= COMPONENT_STATE_SETUP; } @@ -165,13 +153,11 @@ void Component::mark_failed() { this->component_state_ |= COMPONENT_STATE_FAILED; this->status_set_error(); } -void Component::defer(std::function &&f) { - this->defer("", std::move(f)); +void Component::defer(std::function &&f) { this->defer("", std::move(f)); } // NOLINT +bool Component::cancel_defer(const std::string &name) { // NOLINT + return this->cancel_time_function_(name, TimeFunction::DEFER); } -bool Component::cancel_defer(const std::string &name) { - return this->cancel_time_function(name, TimeFunction::DEFER); -} -void Component::defer(const std::string &name, std::function &&f) { +void Component::defer(const std::string &name, std::function &&f) { // NOLINT if (!name.empty()) { this->cancel_defer(name); } @@ -185,64 +171,39 @@ void Component::defer(const std::string &name, std::function &&f) { }; this->time_functions_.push_back(function); } -void Component::set_timeout(uint32_t timeout, std::function &&f) { +void Component::set_timeout(uint32_t timeout, std::function &&f) { // NOLINT this->set_timeout("", timeout, std::move(f)); } -void Component::set_interval(uint32_t interval, std::function &&f) { +void Component::set_interval(uint32_t interval, std::function &&f) { // NOLINT this->set_interval("", interval, std::move(f)); } -bool Component::is_failed() { - return (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_FAILED; -} -bool Component::can_proceed() { - return true; -} -bool Component::status_has_warning() { - return this->component_state_ & STATUS_LED_WARNING; -} -bool Component::status_has_error() { - return this->component_state_ & STATUS_LED_ERROR; -} -void Component::status_set_warning() { - this->component_state_ |= STATUS_LED_WARNING; -} -void Component::status_set_error() { - this->component_state_ |= STATUS_LED_ERROR; -} -void Component::status_clear_warning() { - this->component_state_ &= ~STATUS_LED_WARNING; -} -void Component::status_clear_error() { - this->component_state_ &= ~STATUS_LED_ERROR; -} +bool Component::is_failed() { return (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_FAILED; } +bool Component::can_proceed() { return true; } +bool Component::status_has_warning() { return this->component_state_ & STATUS_LED_WARNING; } +bool Component::status_has_error() { return this->component_state_ & STATUS_LED_ERROR; } +void Component::status_set_warning() { this->component_state_ |= STATUS_LED_WARNING; } +void Component::status_set_error() { this->component_state_ |= STATUS_LED_ERROR; } +void Component::status_clear_warning() { this->component_state_ &= ~STATUS_LED_WARNING; } +void Component::status_clear_error() { this->component_state_ &= ~STATUS_LED_ERROR; } void Component::status_momentary_warning(const std::string &name, uint32_t length) { this->status_set_warning(); - this->set_timeout(name, length, [this]() { - this->status_clear_warning(); - }); + this->set_timeout(name, length, [this]() { this->status_clear_warning(); }); } void Component::status_momentary_error(const std::string &name, uint32_t length) { this->status_set_error(); - this->set_timeout(name, length, [this]() { - this->status_clear_error(); - }); -} -void Component::dump_config() { - + this->set_timeout(name, length, [this]() { this->status_clear_error(); }); } +void Component::dump_config() {} float Component::get_actual_setup_priority() const { return this->setup_priority_override_.value_or(this->get_setup_priority()); } -void Component::set_setup_priority(float priority) { - this->setup_priority_override_ = priority; -} +void Component::set_setup_priority(float priority) { this->setup_priority_override_ = priority; } -PollingComponent::PollingComponent(uint32_t update_interval) - : Component(), update_interval_(update_interval) {} +PollingComponent::PollingComponent(uint32_t update_interval) : Component(), update_interval_(update_interval) {} -void PollingComponent::setup_() { +void PollingComponent::call_setup() { // Call component internal setup. - this->setup_internal(); + this->setup_internal_(); // Let the polling component subclass setup their HW. this->setup(); @@ -251,42 +212,25 @@ void PollingComponent::setup_() { this->set_interval("update", this->get_update_interval(), [this]() { this->update(); }); } -uint32_t PollingComponent::get_update_interval() const { - return this->update_interval_; -} -void PollingComponent::set_update_interval(uint32_t update_interval) { - this->update_interval_ = update_interval; -} +uint32_t PollingComponent::get_update_interval() const { return this->update_interval_; } +void PollingComponent::set_update_interval(uint32_t update_interval) { this->update_interval_ = update_interval; } -const std::string &Nameable::get_name() const { - return this->name_; -} +const std::string &Nameable::get_name() const { return this->name_; } void Nameable::set_name(const std::string &name) { this->name_ = name; this->calc_object_id_(); } -Nameable::Nameable(const std::string &name) - : name_(name) { - this->calc_object_id_(); -} +Nameable::Nameable(const std::string &name) : name_(name) { this->calc_object_id_(); } -const std::string &Nameable::get_object_id() { - return this->object_id_; -} -bool Nameable::is_internal() const { - return this->internal_; -} -void Nameable::set_internal(bool internal) { - this->internal_ = internal; -} +const std::string &Nameable::get_object_id() { return this->object_id_; } +bool Nameable::is_internal() const { return this->internal_; } +void Nameable::set_internal(bool internal) { this->internal_ = internal; } void Nameable::calc_object_id_() { this->object_id_ = sanitize_string_whitelist(to_lowercase_underscore(this->name_), HOSTNAME_CHARACTER_WHITELIST); // FNV-1 hash this->object_id_hash_ = fnv1_hash(this->object_id_); } -uint32_t Nameable::get_object_id_hash() { - return this->object_id_hash_; -} +uint32_t Nameable::get_object_id_hash() { return this->object_id_hash_; } bool Component::TimeFunction::should_run(uint32_t now) const { if (this->remove) diff --git a/src/esphome/component.h b/src/esphome/component.h index f33d170a..68bb3b8e 100644 --- a/src/esphome/component.h +++ b/src/esphome/component.h @@ -11,16 +11,17 @@ ESPHOME_NAMESPACE_BEGIN /// default setup priorities for components of different types. namespace setup_priority { -extern const float PRE_HARDWARE; ///< only for internal components that are necessary for hardware component initialization (like i2c bus) -extern const float HARDWARE; ///< for hardware initialization, but only where it's really necessary (like outputs) +extern const float PRE_HARDWARE; ///< only for internal components that are necessary for hardware component + ///< initialization (like i2c bus) +extern const float HARDWARE; ///< for hardware initialization, but only where it's really necessary (like outputs) extern const float POST_HARDWARE; extern const float HARDWARE_LATE; -extern const float WIFI; ///< for WiFi initialization -extern const float MQTT_CLIENT; ///< for the MQTT client initialization -extern const float MQTT_COMPONENT; ///< for MQTT component initialization +extern const float WIFI; ///< for WiFi initialization +extern const float MQTT_CLIENT; ///< for the MQTT client initialization +extern const float MQTT_COMPONENT; ///< for MQTT component initialization extern const float LATE; -} // namespace setup_priority +} // namespace setup_priority extern const uint32_t COMPONENT_STATE_MASK; extern const uint32_t COMPONENT_STATE_CONSTRUCTION; @@ -101,8 +102,8 @@ class Component { * * Basically, it handles stuff like interval/timeout functions and eventually calls loop(). */ - virtual void loop_(); - virtual void setup_(); + virtual void call_loop(); + virtual void call_setup(); uint32_t get_component_state() const; @@ -135,11 +136,6 @@ class Component { void status_momentary_error(const std::string &name, uint32_t length = 5000); protected: - void loop_internal(); - void setup_internal(); - - void set_interval(uint32_t interval, std::function &&f); - /** Set an interval function with a unique name. Empty name means no cancelling possible. * * This will call f every interval ms. Can be cancelled via CancelInterval(). @@ -155,16 +151,18 @@ class Component { * * @see cancel_interval() */ - void set_interval(const std::string &name, uint32_t interval, std::function &&f); + void set_interval(const std::string &name, uint32_t interval, std::function &&f); // NOLINT + + void set_interval(uint32_t interval, std::function &&f); // NOLINT /** Cancel an interval function. * * @param name The identifier for this interval function. * @return Whether an interval functions was deleted. */ - bool cancel_interval(const std::string &name); + bool cancel_interval(const std::string &name); // NOLINT - void set_timeout(uint32_t timeout, std::function &&f); + void set_timeout(uint32_t timeout, std::function &&f); // NOLINT /** Set a timeout function with a unique name. * @@ -180,14 +178,14 @@ class Component { * * @see cancel_timeout() */ - void set_timeout(const std::string &name, uint32_t timeout, std::function &&f); + void set_timeout(const std::string &name, uint32_t timeout, std::function &&f); // NOLINT /** Cancel a timeout function. * * @param name The identifier for this timeout function. * @return Whether a timeout functions was deleted. */ - bool cancel_timeout(const std::string &name); + bool cancel_timeout(const std::string &name); // NOLINT /** Defer a callback to the next loop() call. * @@ -196,29 +194,32 @@ class Component { * @param name The name of the defer function. * @param f The callback. */ - void defer(const std::string &name, std::function &&f); + void defer(const std::string &name, std::function &&f); // NOLINT /// Defer a callback to the next loop() call. - void defer(std::function &&f); + void defer(std::function &&f); // NOLINT /// Cancel a defer callback using the specified name, name must not be empty. - bool cancel_defer(const std::string &name); + bool cancel_defer(const std::string &name); // NOLINT + + void loop_internal_(); + void setup_internal_(); /// Internal struct for storing timeout/interval functions. struct TimeFunction { - std::string name; ///< The name/id of this TimeFunction. - enum Type { TIMEOUT, INTERVAL, DEFER } type; ///< The type of this TimeFunction. Either TIMEOUT, INTERVAL or DEFER. - uint32_t interval; ///< The interval/timeout of this function. + std::string name; ///< The name/id of this TimeFunction. + enum Type { TIMEOUT, INTERVAL, DEFER } type; ///< The type of this TimeFunction. Either TIMEOUT, INTERVAL or DEFER. + uint32_t interval; ///< The interval/timeout of this function. /// The last execution for interval functions and the time, SetInterval was called, for timeout functions. uint32_t last_execution; - std::function f; ///< The function (or callback) itself. + std::function f; ///< The function (or callback) itself. bool remove; bool should_run(uint32_t now) const; }; /// Cancel an only time function. If name is empty, won't do anything. - bool cancel_time_function(const std::string &name, TimeFunction::Type type); + bool cancel_time_function_(const std::string &name, TimeFunction::Type type); /** Storage for interval/timeout functions. * @@ -227,7 +228,7 @@ class Component { */ std::vector time_functions_; - uint32_t component_state_{0x0000}; ///< State of this component. + uint32_t component_state_{0x0000}; ///< State of this component. optional setup_priority_override_; }; @@ -259,10 +260,11 @@ class PollingComponent : public Component { // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) - void setup_() override; + void call_setup() override; /// Get the update interval in ms of this sensor virtual uint32_t get_update_interval() const; + protected: uint32_t update_interval_; }; @@ -281,7 +283,7 @@ class Nameable { void set_internal(bool internal); protected: - virtual uint32_t hash_base_() = 0; + virtual uint32_t hash_base() = 0; void calc_object_id_(); @@ -293,4 +295,4 @@ class Nameable { ESPHOME_NAMESPACE_END -#endif //ESPHOME_COMPONENT_H +#endif // ESPHOME_COMPONENT_H diff --git a/src/esphome/controller.cpp b/src/esphome/controller.cpp index e7849b17..a52502aa 100644 --- a/src/esphome/controller.cpp +++ b/src/esphome/controller.cpp @@ -3,9 +3,7 @@ ESPHOME_NAMESPACE_BEGIN #ifdef USE_BINARY_SENSOR -void Controller::register_binary_sensor(binary_sensor::BinarySensor *obj) { - -} +void Controller::register_binary_sensor(binary_sensor::BinarySensor *obj) {} void StoringController::register_binary_sensor(binary_sensor::BinarySensor *obj) { this->binary_sensors_.push_back(obj); @@ -20,19 +18,13 @@ binary_sensor::BinarySensor *StoringController::get_binary_sensor_by_key(uint32_ } void StoringUpdateListenerController::register_binary_sensor(binary_sensor::BinarySensor *obj) { StoringController::register_binary_sensor(obj); - obj->add_on_state_callback([this, obj](bool state) { - this->on_binary_sensor_update(obj, state); - }); + obj->add_on_state_callback([this, obj](bool state) { this->on_binary_sensor_update(obj, state); }); } #endif #ifdef USE_FAN -void Controller::register_fan(fan::FanState *obj) { - -} -void StoringController::register_fan(fan::FanState *obj) { - this->fans_.push_back(obj); -} +void Controller::register_fan(fan::FanState *obj) {} +void StoringController::register_fan(fan::FanState *obj) { this->fans_.push_back(obj); } fan::FanState *StoringController::get_fan_by_key(uint32_t key) { for (auto *c : this->fans_) { if (c->get_object_id_hash() == key && !c->is_internal()) @@ -42,19 +34,13 @@ fan::FanState *StoringController::get_fan_by_key(uint32_t key) { } void StoringUpdateListenerController::register_fan(fan::FanState *obj) { StoringController::register_fan(obj); - obj->add_on_state_callback([this, obj]() { - this->on_fan_update(obj); - }); + obj->add_on_state_callback([this, obj]() { this->on_fan_update(obj); }); } #endif #ifdef USE_LIGHT -void Controller::register_light(light::LightState *obj) { - -} -void StoringController::register_light(light::LightState *obj) { - this->lights_.push_back(obj); -} +void Controller::register_light(light::LightState *obj) {} +void StoringController::register_light(light::LightState *obj) { this->lights_.push_back(obj); } light::LightState *StoringController::get_light_by_key(uint32_t key) { for (auto *c : this->lights_) { if (c->get_object_id_hash() == key && !c->is_internal()) @@ -64,19 +50,13 @@ light::LightState *StoringController::get_light_by_key(uint32_t key) { } void StoringUpdateListenerController::register_light(light::LightState *obj) { StoringController::register_light(obj); - obj->add_new_remote_values_callback([this, obj]() { - this->on_light_update(obj); - }); + obj->add_new_remote_values_callback([this, obj]() { this->on_light_update(obj); }); } #endif #ifdef USE_SENSOR -void Controller::register_sensor(sensor::Sensor *obj) { - -} -void StoringController::register_sensor(sensor::Sensor *obj) { - this->sensors_.push_back(obj); -} +void Controller::register_sensor(sensor::Sensor *obj) {} +void StoringController::register_sensor(sensor::Sensor *obj) { this->sensors_.push_back(obj); } sensor::Sensor *StoringController::get_sensor_by_key(uint32_t key) { for (auto *c : this->sensors_) { if (c->get_object_id_hash() == key && !c->is_internal()) @@ -86,19 +66,13 @@ sensor::Sensor *StoringController::get_sensor_by_key(uint32_t key) { } void StoringUpdateListenerController::register_sensor(sensor::Sensor *obj) { StoringController::register_sensor(obj); - obj->add_on_state_callback([this, obj](float state) { - this->on_sensor_update(obj, state); - }); + obj->add_on_state_callback([this, obj](float state) { this->on_sensor_update(obj, state); }); } #endif #ifdef USE_SWITCH -void Controller::register_switch(switch_::Switch *obj) { - -} -void StoringController::register_switch(switch_::Switch *obj) { - this->switches_.push_back(obj); -} +void Controller::register_switch(switch_::Switch *obj) {} +void StoringController::register_switch(switch_::Switch *obj) { this->switches_.push_back(obj); } switch_::Switch *StoringController::get_switch_by_key(uint32_t key) { for (auto *c : this->switches_) { if (c->get_object_id_hash() == key && !c->is_internal()) @@ -108,19 +82,13 @@ switch_::Switch *StoringController::get_switch_by_key(uint32_t key) { } void StoringUpdateListenerController::register_switch(switch_::Switch *obj) { StoringController::register_switch(obj); - obj->add_on_state_callback([this, obj](bool state) { - this->on_switch_update(obj, state); - }); + obj->add_on_state_callback([this, obj](bool state) { this->on_switch_update(obj, state); }); } #endif #ifdef USE_COVER -void Controller::register_cover(cover::Cover *cover) { - -} -void StoringController::register_cover(cover::Cover *cover) { - this->covers_.push_back(cover); -} +void Controller::register_cover(cover::Cover *cover) {} +void StoringController::register_cover(cover::Cover *cover) { this->covers_.push_back(cover); } cover::Cover *StoringController::get_cover_by_key(uint32_t key) { for (auto *c : this->covers_) { if (c->get_object_id_hash() == key && !c->is_internal()) @@ -130,22 +98,14 @@ cover::Cover *StoringController::get_cover_by_key(uint32_t key) { } void StoringUpdateListenerController::register_cover(cover::Cover *obj) { StoringController::register_cover(obj); - obj->add_on_publish_state_callback([this, obj](bool state) { - this->on_cover_update(obj); - }); -} -void StoringUpdateListenerController::on_cover_update(cover::Cover *obj) { - + obj->add_on_publish_state_callback([this, obj](bool state) { this->on_cover_update(obj); }); } +void StoringUpdateListenerController::on_cover_update(cover::Cover *obj) {} #endif #ifdef USE_TEXT_SENSOR -void Controller::register_text_sensor(text_sensor::TextSensor *obj) { - -} -void StoringController::register_text_sensor(text_sensor::TextSensor *obj) { - this->text_sensors_.push_back(obj); -} +void Controller::register_text_sensor(text_sensor::TextSensor *obj) {} +void StoringController::register_text_sensor(text_sensor::TextSensor *obj) { this->text_sensors_.push_back(obj); } text_sensor::TextSensor *StoringController::get_text_sensor_by_key(uint32_t key) { for (auto *c : this->text_sensors_) { if (c->get_object_id_hash() == key && !c->is_internal()) @@ -155,9 +115,7 @@ text_sensor::TextSensor *StoringController::get_text_sensor_by_key(uint32_t key) } void StoringUpdateListenerController::register_text_sensor(text_sensor::TextSensor *obj) { StoringController::register_text_sensor(obj); - obj->add_on_state_callback([this, obj](std::string state) { - this->on_text_sensor_update(obj, state); - }); + obj->add_on_state_callback([this, obj](std::string state) { this->on_text_sensor_update(obj, state); }); } #endif diff --git a/src/esphome/controller.h b/src/esphome/controller.h index 95806c74..312f7ca2 100644 --- a/src/esphome/controller.h +++ b/src/esphome/controller.h @@ -36,7 +36,7 @@ class Controller { #endif #ifdef USE_COVER - virtual void register_cover(cover::Cover *cover); + virtual void register_cover(cover::Cover *cover); #endif #ifdef USE_TEXT_SENSOR @@ -164,4 +164,4 @@ class StoringUpdateListenerController : public StoringController { ESPHOME_NAMESPACE_END -#endif //ESPHOME_CONTROLLER_H +#endif // ESPHOME_CONTROLLER_H diff --git a/src/esphome/cover/cover.cpp b/src/esphome/cover/cover.cpp index 01f92f5b..78e4cf55 100644 --- a/src/esphome/cover/cover.cpp +++ b/src/esphome/cover/cover.cpp @@ -8,9 +8,7 @@ ESPHOME_NAMESPACE_BEGIN namespace cover { -Cover::Cover(const std::string &name) : Nameable(name) { - -} +Cover::Cover(const std::string &name) : Nameable(name) {} void Cover::add_on_publish_state_callback(std::function &&f) { this->state_callback_.add(std::move(f)); @@ -21,36 +19,20 @@ void Cover::publish_state(CoverState state) { this->state = state; this->state_callback_.call(state); } -bool Cover::assumed_state() { - return false; -} -bool Cover::has_state() const { - return this->dedup_.has_value(); -} +bool Cover::assumed_state() { return false; } +bool Cover::has_state() const { return this->dedup_.has_value(); } -void Cover::open() { - this->write_command(COVER_COMMAND_OPEN); -} -void Cover::close() { - this->write_command(COVER_COMMAND_CLOSE); -} -void Cover::stop() { - this->write_command(COVER_COMMAND_STOP); -} -uint32_t Cover::hash_base_() { - return 1727367479UL; -} +void Cover::open() { this->write_command(COVER_COMMAND_OPEN); } +void Cover::close() { this->write_command(COVER_COMMAND_CLOSE); } +void Cover::stop() { this->write_command(COVER_COMMAND_STOP); } +uint32_t Cover::hash_base() { return 1727367479UL; } #ifdef USE_MQTT_COVER -MQTTCoverComponent *Cover::get_mqtt() const { - return this->mqtt_; -} -void Cover::set_mqtt(MQTTCoverComponent *mqtt) { - this->mqtt_ = mqtt; -} +MQTTCoverComponent *Cover::get_mqtt() const { return this->mqtt_; } +void Cover::set_mqtt(MQTTCoverComponent *mqtt) { this->mqtt_ = mqtt; } #endif -} // namespace cover +} // namespace cover ESPHOME_NAMESPACE_END -#endif //USE_COVER +#endif // USE_COVER diff --git a/src/esphome/cover/cover.h b/src/esphome/cover/cover.h index 3000b10e..6a5d7a67 100644 --- a/src/esphome/cover/cover.h +++ b/src/esphome/cover/cover.h @@ -24,22 +24,18 @@ enum CoverCommand { COVER_COMMAND_STOP, }; -template -class OpenAction; -template -class CloseAction; -template -class StopAction; -template -class CoverPublishAction; +template class OpenAction; +template class CloseAction; +template class StopAction; +template class CoverPublishAction; #define LOG_COVER(prefix, type, obj) \ - if (obj != nullptr) { \ - ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ - if (obj->assumed_state()) { \ - ESP_LOGCONFIG(TAG, prefix " Assumed State: YES"); \ - } \ - } + if (obj != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ + if (obj->assumed_state()) { \ + ESP_LOGCONFIG(TAG, prefix " Assumed State: YES"); \ + } \ + } #ifdef USE_MQTT_COVER class MQTTCoverComponent; @@ -57,14 +53,10 @@ class Cover : public Nameable { void publish_state(CoverState state); - template - OpenAction *make_open_action(); - template - CloseAction *make_close_action(); - template - StopAction *make_stop_action(); - template - CoverPublishAction *make_cover_publish_action(); + template OpenAction *make_open_action(); + template CloseAction *make_close_action(); + template StopAction *make_stop_action(); + template CoverPublishAction *make_cover_publish_action(); /** Return whether this cover is optimistic - i.e. if both the OPEN/CLOSE actions should be displayed in * Home Assistant because the real state is unknown. @@ -85,7 +77,7 @@ class Cover : public Nameable { protected: virtual void write_command(CoverCommand command) = 0; - uint32_t hash_base_() override; + uint32_t hash_base() override; CallbackManager state_callback_{}; Deduplicator dedup_; @@ -95,8 +87,7 @@ class Cover : public Nameable { #endif }; -template -class OpenAction : public Action { +template class OpenAction : public Action { public: explicit OpenAction(Cover *cover); @@ -106,8 +97,7 @@ class OpenAction : public Action { Cover *cover_; }; -template -class CloseAction : public Action { +template class CloseAction : public Action { public: explicit CloseAction(Cover *cover); @@ -117,8 +107,7 @@ class CloseAction : public Action { Cover *cover_; }; -template -class StopAction : public Action { +template class StopAction : public Action { public: explicit StopAction(Cover *cover); @@ -128,13 +117,12 @@ class StopAction : public Action { Cover *cover_; }; -template -class CoverPublishAction : public Action { +template class CoverPublishAction : public Action { public: CoverPublishAction(Cover *cover); - template - void set_state(V value) { this->state_ = value; } + template void set_state(V value) { this->state_ = value; } void play(Ts... x) override; + protected: Cover *cover_; TemplatableValue state_; @@ -142,71 +130,46 @@ class CoverPublishAction : public Action { // =============== TEMPLATE DEFINITIONS =============== -template -OpenAction::OpenAction(Cover *cover) - : cover_(cover) { - -} -template -void OpenAction::play(Ts... x) { +template OpenAction::OpenAction(Cover *cover) : cover_(cover) {} +template void OpenAction::play(Ts... x) { this->cover_->open(); this->play_next(x...); } -template -CloseAction::CloseAction(Cover *cover) - : cover_(cover) { - -} -template -void CloseAction::play(Ts... x) { +template CloseAction::CloseAction(Cover *cover) : cover_(cover) {} +template void CloseAction::play(Ts... x) { this->cover_->close(); this->play_next(x...); } -template -StopAction::StopAction(Cover *cover) - : cover_(cover) { } +template StopAction::StopAction(Cover *cover) : cover_(cover) {} -template -void StopAction::play(Ts... x) { +template void StopAction::play(Ts... x) { this->cover_->stop(); this->play_next(x...); } -template -OpenAction *Cover::make_open_action() { - return new OpenAction(this); -} +template OpenAction *Cover::make_open_action() { return new OpenAction(this); } -template -CloseAction *Cover::make_close_action() { - return new CloseAction(this); -} -template -StopAction *Cover::make_stop_action() { - return new StopAction(this); -} +template CloseAction *Cover::make_close_action() { return new CloseAction(this); } +template StopAction *Cover::make_stop_action() { return new StopAction(this); } -template -CoverPublishAction::CoverPublishAction(Cover *cover) : cover_(cover) {} -template -void CoverPublishAction::play(Ts... x) { +template CoverPublishAction::CoverPublishAction(Cover *cover) : cover_(cover) {} +template void CoverPublishAction::play(Ts... x) { auto val = this->state_.value(x...); this->cover_->publish_state(val); this->play_next(x...); } -template -CoverPublishAction *Cover::make_cover_publish_action() { +template CoverPublishAction *Cover::make_cover_publish_action() { return new CoverPublishAction(this); } -} // namespace cover +} // namespace cover ESPHOME_NAMESPACE_END #include "esphome/cover/mqtt_cover_component.h" -#endif //USE_COVER +#endif // USE_COVER -#endif //ESPHOME_COVER_COVER_H +#endif // ESPHOME_COVER_COVER_H diff --git a/src/esphome/cover/mqtt_cover_component.cpp b/src/esphome/cover/mqtt_cover_component.cpp index da6447bb..614db1bd 100644 --- a/src/esphome/cover/mqtt_cover_component.cpp +++ b/src/esphome/cover/mqtt_cover_component.cpp @@ -13,10 +13,8 @@ static const char *TAG = "cover.mqtt"; MQTTCoverComponent::MQTTCoverComponent(Cover *cover) : cover_(cover) {} void MQTTCoverComponent::setup() { - this->cover_->add_on_publish_state_callback([this](CoverState state) { - this->publish_state(state); - }); - this->subscribe(this->get_command_topic(), [this](const std::string &topic, const std::string &payload) { + this->cover_->add_on_publish_state_callback([this](CoverState state) { this->publish_state(state); }); + this->subscribe(this->get_command_topic_(), [this](const std::string &topic, const std::string &payload) { if (strcasecmp(payload.c_str(), "OPEN") == 0) { ESP_LOGD(TAG, "'%s': Opening cover...", this->friendly_name().c_str()); this->cover_->open(); @@ -41,12 +39,8 @@ void MQTTCoverComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryCon root["optimistic"] = true; } -std::string MQTTCoverComponent::component_type() const { - return "cover"; -} -std::string MQTTCoverComponent::friendly_name() const { - return this->cover_->get_name(); -} +std::string MQTTCoverComponent::component_type() const { return "cover"; } +std::string MQTTCoverComponent::friendly_name() const { return this->cover_->get_name(); } bool MQTTCoverComponent::send_initial_state() { if (this->cover_->has_state()) { return this->publish_state(this->cover_->state); @@ -54,25 +48,27 @@ bool MQTTCoverComponent::send_initial_state() { return true; } } -bool MQTTCoverComponent::is_internal() { - return this->cover_->is_internal(); -} +bool MQTTCoverComponent::is_internal() { return this->cover_->is_internal(); } bool MQTTCoverComponent::publish_state(cover::CoverState state) { const char *state_s; switch (state) { - case COVER_OPEN: state_s = "open"; break; - case COVER_CLOSED: state_s = "closed"; break; + case COVER_OPEN: + state_s = "open"; + break; + case COVER_CLOSED: + state_s = "closed"; + break; default: { ESP_LOGW(TAG, "Unknown cover state."); return true; } } ESP_LOGD(TAG, "'%s': Sending state %s", this->friendly_name().c_str(), state_s); - return this->publish(this->get_state_topic(), state_s); + return this->publish(this->get_state_topic_(), state_s); } -} // namespace cover +} // namespace cover ESPHOME_NAMESPACE_END -#endif //USE_MQTT_COVER +#endif // USE_MQTT_COVER diff --git a/src/esphome/cover/mqtt_cover_component.h b/src/esphome/cover/mqtt_cover_component.h index 42306a97..c0c8c70a 100644 --- a/src/esphome/cover/mqtt_cover_component.h +++ b/src/esphome/cover/mqtt_cover_component.h @@ -33,10 +33,10 @@ class MQTTCoverComponent : public mqtt::MQTTComponent { Cover *cover_; }; -} // namespace cover +} // namespace cover ESPHOME_NAMESPACE_END -#endif //USE_MQTT_COVER +#endif // USE_MQTT_COVER -#endif //ESPHOME_COVER_MQTT_COVER_COMPONENT_H +#endif // ESPHOME_COVER_MQTT_COVER_COMPONENT_H diff --git a/src/esphome/cover/template_cover.cpp b/src/esphome/cover/template_cover.cpp index a6eb7316..9680b2de 100644 --- a/src/esphome/cover/template_cover.cpp +++ b/src/esphome/cover/template_cover.cpp @@ -12,10 +12,7 @@ namespace cover { static const char *TAG = "cover.template"; TemplateCover::TemplateCover(const std::string &name) - : Cover(name), open_trigger_(new Trigger<>()), close_trigger_(new Trigger<>), - stop_trigger_(new Trigger<>()) { - -} + : Cover(name), open_trigger_(new Trigger<>()), close_trigger_(new Trigger<>), stop_trigger_(new Trigger<>()) {} void TemplateCover::loop() { if (!this->f_.has_value()) return; @@ -25,30 +22,14 @@ void TemplateCover::loop() { this->publish_state(*s); } -void TemplateCover::set_optimistic(bool optimistic) { - this->optimistic_ = optimistic; -} -void TemplateCover::set_assumed_state(bool assumed_state) { - this->assumed_state_ = assumed_state; -} -bool TemplateCover::assumed_state() { - return this->assumed_state_; -} -void TemplateCover::set_state_lambda(std::function()> &&f) { - this->f_ = f; -} -float TemplateCover::get_setup_priority() const { - return setup_priority::HARDWARE; -} -Trigger<> *TemplateCover::get_open_trigger() const { - return this->open_trigger_; -} -Trigger<> *TemplateCover::get_close_trigger() const { - return this->close_trigger_; -} -Trigger<> *TemplateCover::get_stop_trigger() const { - return this->stop_trigger_; -} +void TemplateCover::set_optimistic(bool optimistic) { this->optimistic_ = optimistic; } +void TemplateCover::set_assumed_state(bool assumed_state) { this->assumed_state_ = assumed_state; } +bool TemplateCover::assumed_state() { return this->assumed_state_; } +void TemplateCover::set_state_lambda(std::function()> &&f) { this->f_ = f; } +float TemplateCover::get_setup_priority() const { return setup_priority::HARDWARE; } +Trigger<> *TemplateCover::get_open_trigger() const { return this->open_trigger_; } +Trigger<> *TemplateCover::get_close_trigger() const { return this->close_trigger_; } +Trigger<> *TemplateCover::get_stop_trigger() const { return this->stop_trigger_; } void TemplateCover::write_command(CoverCommand command) { if (this->prev_trigger_ != nullptr) { this->prev_trigger_->stop(); @@ -75,12 +56,10 @@ void TemplateCover::write_command(CoverCommand command) { } } } -void TemplateCover::dump_config() { - LOG_COVER("", "Template Cover", this); -} +void TemplateCover::dump_config() { LOG_COVER("", "Template Cover", this); } -} // namespace cover +} // namespace cover ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_COVER +#endif // USE_TEMPLATE_COVER diff --git a/src/esphome/cover/template_cover.h b/src/esphome/cover/template_cover.h index 91aeb10f..1eba9a98 100644 --- a/src/esphome/cover/template_cover.h +++ b/src/esphome/cover/template_cover.h @@ -41,10 +41,10 @@ class TemplateCover : public Cover, public Component { Trigger<> *prev_trigger_{nullptr}; }; -} // namespace cover +} // namespace cover ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_COVER +#endif // USE_TEMPLATE_COVER -#endif //ESPHOME_COVER_TEMPLATE_COVER_H +#endif // ESPHOME_COVER_TEMPLATE_COVER_H diff --git a/src/esphome/custom_component.cpp b/src/esphome/custom_component.cpp index 5122262c..77d76bf6 100644 --- a/src/esphome/custom_component.cpp +++ b/src/esphome/custom_component.cpp @@ -15,11 +15,8 @@ CustomComponentConstructor::CustomComponentConstructor(const std::functioncomponents_[i]; -} +Component *CustomComponentConstructor::get_component(int i) { return this->components_[i]; } ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_COMPONENT - +#endif // USE_CUSTOM_COMPONENT diff --git a/src/esphome/custom_component.h b/src/esphome/custom_component.h index f951d1e2..6fb1d88d 100644 --- a/src/esphome/custom_component.h +++ b/src/esphome/custom_component.h @@ -21,6 +21,6 @@ class CustomComponentConstructor { ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_COMPONENT +#endif // USE_CUSTOM_COMPONENT -#endif //ESPHOME_CUSTOM_COMPONENT_H +#endif // ESPHOME_CUSTOM_COMPONENT_H diff --git a/src/esphome/debug_component.cpp b/src/esphome/debug_component.cpp index a5273281..aa2ddae7 100644 --- a/src/esphome/debug_component.cpp +++ b/src/esphome/debug_component.cpp @@ -8,7 +8,7 @@ #include #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -17,9 +17,9 @@ static const char *TAG = "debug"; void DebugComponent::setup() { #ifndef ESPHOME_LOG_HAS_DEBUG - ESP_LOGE(TAG, "Debug Component requires debug log level!"); - this->status_set_error(); - return; + ESP_LOGE(TAG, "Debug Component requires debug log level!"); + this->status_set_error(); + return; #endif ESP_LOGD(TAG, "ESPHome Core version %s", ESPHOME_VERSION); @@ -28,28 +28,42 @@ void DebugComponent::setup() { const char *flash_mode; switch (ESP.getFlashChipMode()) { - case FM_QIO: flash_mode = "QIO"; break; - case FM_QOUT: flash_mode = "QOUT"; break; - case FM_DIO: flash_mode = "DIO"; break; - case FM_DOUT: flash_mode = "DOUT"; break; + case FM_QIO: + flash_mode = "QIO"; + break; + case FM_QOUT: + flash_mode = "QOUT"; + break; + case FM_DIO: + flash_mode = "DIO"; + break; + case FM_DOUT: + flash_mode = "DOUT"; + break; #ifdef ARDUINO_ARCH_ESP32 - case FM_FAST_READ: flash_mode = "FAST_READ"; break; - case FM_SLOW_READ: flash_mode = "SLOW_READ"; break; + case FM_FAST_READ: + flash_mode = "FAST_READ"; + break; + case FM_SLOW_READ: + flash_mode = "SLOW_READ"; + break; #endif - default: flash_mode = "UNKNOWN"; + default: + flash_mode = "UNKNOWN"; } - ESP_LOGD(TAG, "Flash Chip: Size=%ukB Speed=%uMHz Mode=%s", - ESP.getFlashChipSize() / 1024, - ESP.getFlashChipSpeed() / 1000000, - flash_mode); + ESP_LOGD(TAG, "Flash Chip: Size=%ukB Speed=%uMHz Mode=%s", ESP.getFlashChipSize() / 1024, + ESP.getFlashChipSpeed() / 1000000, flash_mode); #ifdef ARDUINO_ARCH_ESP32 esp_chip_info_t info; esp_chip_info(&info); const char *model; switch (info.model) { - case CHIP_ESP32: model = "ESP32"; break; - default: model = "UNKNOWN"; + case CHIP_ESP32: + model = "ESP32"; + break; + default: + model = "UNKNOWN"; } std::string features; if (info.features & CHIP_FEATURE_EMB_FLASH) { @@ -70,8 +84,8 @@ void DebugComponent::setup() { } if (info.features) features += "Other:" + uint64_to_string(info.features); - ESP_LOGD(TAG, "Chip: Model=%s, Features=%s Cores=%u, Revision=%u", - model, features.c_str(), info.cores, info.revision); + ESP_LOGD(TAG, "Chip: Model=%s, Features=%s Cores=%u, Revision=%u", model, features.c_str(), info.cores, + info.revision); ESP_LOGD(TAG, "ESP-IDF Version: %s", esp_get_idf_version()); @@ -80,40 +94,96 @@ void DebugComponent::setup() { const char *reset_reason; switch (rtc_get_reset_reason(0)) { - case POWERON_RESET: reset_reason = "Power On Reset"; break; - case SW_RESET: reset_reason = "Software Reset Digital Core"; break; - case OWDT_RESET: reset_reason = "Watch Dog Reset Digital Core"; break; - case DEEPSLEEP_RESET: reset_reason = "Deep Sleep Reset Digital Core"; break; - case SDIO_RESET: reset_reason = "SLC Module Reset Digital Core"; break; - case TG0WDT_SYS_RESET: reset_reason = "Timer Group 0 Watch Dog Reset Digital Core"; break; - case TG1WDT_SYS_RESET: reset_reason = "Timer Group 1 Watch Dog Reset Digital Core"; break; - case RTCWDT_SYS_RESET: reset_reason = "RTC Watch Dog Reset Digital Core"; break; - case INTRUSION_RESET: reset_reason = "Intrusion Reset CPU"; break; - case TGWDT_CPU_RESET: reset_reason = "Timer Group Reset CPU"; break; - case SW_CPU_RESET: reset_reason = "Software Reset CPU"; break; - case RTCWDT_CPU_RESET: reset_reason = "RTC Watch Dog Reset CPU"; break; - case EXT_CPU_RESET: reset_reason = "External CPU Reset"; break; - case RTCWDT_BROWN_OUT_RESET: reset_reason = "Voltage Unstable Reset"; break; - case RTCWDT_RTC_RESET: reset_reason = "RTC Watch Dog Reset Digital Core And RTC Module"; break; - default: reset_reason = "Unknown Reset Reason"; + case POWERON_RESET: + reset_reason = "Power On Reset"; + break; + case SW_RESET: + reset_reason = "Software Reset Digital Core"; + break; + case OWDT_RESET: + reset_reason = "Watch Dog Reset Digital Core"; + break; + case DEEPSLEEP_RESET: + reset_reason = "Deep Sleep Reset Digital Core"; + break; + case SDIO_RESET: + reset_reason = "SLC Module Reset Digital Core"; + break; + case TG0WDT_SYS_RESET: + reset_reason = "Timer Group 0 Watch Dog Reset Digital Core"; + break; + case TG1WDT_SYS_RESET: + reset_reason = "Timer Group 1 Watch Dog Reset Digital Core"; + break; + case RTCWDT_SYS_RESET: + reset_reason = "RTC Watch Dog Reset Digital Core"; + break; + case INTRUSION_RESET: + reset_reason = "Intrusion Reset CPU"; + break; + case TGWDT_CPU_RESET: + reset_reason = "Timer Group Reset CPU"; + break; + case SW_CPU_RESET: + reset_reason = "Software Reset CPU"; + break; + case RTCWDT_CPU_RESET: + reset_reason = "RTC Watch Dog Reset CPU"; + break; + case EXT_CPU_RESET: + reset_reason = "External CPU Reset"; + break; + case RTCWDT_BROWN_OUT_RESET: + reset_reason = "Voltage Unstable Reset"; + break; + case RTCWDT_RTC_RESET: + reset_reason = "RTC Watch Dog Reset Digital Core And RTC Module"; + break; + default: + reset_reason = "Unknown Reset Reason"; } ESP_LOGD(TAG, "Reset Reason: %s", reset_reason); const char *wakeup_reason; switch (rtc_get_wakeup_cause()) { - case NO_SLEEP: wakeup_reason = "No Sleep"; break; - case EXT_EVENT0_TRIG: wakeup_reason = "External Event 0"; break; - case EXT_EVENT1_TRIG: wakeup_reason = "External Event 1"; break; - case GPIO_TRIG: wakeup_reason = "GPIO"; break; - case TIMER_EXPIRE: wakeup_reason = "Wakeup Timer"; break; - case SDIO_TRIG: wakeup_reason = "SDIO"; break; - case MAC_TRIG: wakeup_reason = "MAC"; break; - case UART0_TRIG: wakeup_reason = "UART0"; break; - case UART1_TRIG: wakeup_reason = "UART1"; break; - case TOUCH_TRIG: wakeup_reason = "Touch"; break; - case SAR_TRIG: wakeup_reason = "SAR"; break; - case BT_TRIG: wakeup_reason = "BT"; break; - default: wakeup_reason = "Unknown"; + case NO_SLEEP: + wakeup_reason = "No Sleep"; + break; + case EXT_EVENT0_TRIG: + wakeup_reason = "External Event 0"; + break; + case EXT_EVENT1_TRIG: + wakeup_reason = "External Event 1"; + break; + case GPIO_TRIG: + wakeup_reason = "GPIO"; + break; + case TIMER_EXPIRE: + wakeup_reason = "Wakeup Timer"; + break; + case SDIO_TRIG: + wakeup_reason = "SDIO"; + break; + case MAC_TRIG: + wakeup_reason = "MAC"; + break; + case UART0_TRIG: + wakeup_reason = "UART0"; + break; + case UART1_TRIG: + wakeup_reason = "UART1"; + break; + case TOUCH_TRIG: + wakeup_reason = "Touch"; + break; + case SAR_TRIG: + wakeup_reason = "SAR"; + break; + case BT_TRIG: + wakeup_reason = "BT"; + break; + default: + wakeup_reason = "Unknown"; } ESP_LOGD(TAG, "Wakeup Reason: %s", wakeup_reason); #endif @@ -138,9 +208,9 @@ void DebugComponent::loop() { } } float DebugComponent::get_setup_priority() const { - return setup_priority::LATE; // display debug info via MQTT + return setup_priority::LATE; // display debug info via MQTT } ESPHOME_NAMESPACE_END -#endif //USE_DEBUG_COMPONENT +#endif // USE_DEBUG_COMPONENT diff --git a/src/esphome/debug_component.h b/src/esphome/debug_component.h index 087c46d6..61adee1f 100644 --- a/src/esphome/debug_component.h +++ b/src/esphome/debug_component.h @@ -15,12 +15,13 @@ class DebugComponent : public Component { void setup() override; void loop() override; float get_setup_priority() const override; + protected: uint32_t free_heap_{}; }; ESPHOME_NAMESPACE_END -#endif //USE_DEBUG_COMPONENT +#endif // USE_DEBUG_COMPONENT -#endif //ESPHOME_DEBUG_COMPONENT_H +#endif // ESPHOME_DEBUG_COMPONENT_H diff --git a/src/esphome/deep_sleep_component.cpp b/src/esphome/deep_sleep_component.cpp index bfcff762..89c2f98a 100644 --- a/src/esphome/deep_sleep_component.cpp +++ b/src/esphome/deep_sleep_component.cpp @@ -19,9 +19,7 @@ void DeepSleepComponent::setup() { global_has_deep_sleep = true; if (this->run_duration_.has_value()) - this->set_timeout(*this->run_duration_, [this](){ - this->begin_sleep_(); - }); + this->set_timeout(*this->run_duration_, [this]() { this->begin_sleep(); }); } void DeepSleepComponent::dump_config() { ESP_LOGCONFIG(TAG, "Setting up Deep Sleep..."); @@ -39,36 +37,28 @@ void DeepSleepComponent::dump_config() { } void DeepSleepComponent::loop() { if (this->next_enter_deep_sleep_) - this->begin_sleep_(); + this->begin_sleep(); } float DeepSleepComponent::get_loop_priority() const { - return -100.0f; // run after everything else is ready -} -void DeepSleepComponent::set_sleep_duration(uint32_t time_ms) { - this->sleep_duration_ = uint64_t(time_ms) * 1000; + return -100.0f; // run after everything else is ready } +void DeepSleepComponent::set_sleep_duration(uint32_t time_ms) { this->sleep_duration_ = uint64_t(time_ms) * 1000; } #ifdef ARDUINO_ARCH_ESP32 -void DeepSleepComponent::set_wakeup_pin(const GPIOInputPin &pin) { - this->wakeup_pin_ = pin.copy(); -} +void DeepSleepComponent::set_wakeup_pin(const GPIOInputPin &pin) { this->wakeup_pin_ = pin.copy(); } void DeepSleepComponent::set_wakeup_pin_mode(WakeupPinMode wakeup_pin_mode) { this->wakeup_pin_mode_ = wakeup_pin_mode; } -void DeepSleepComponent::set_ext1_wakeup(Ext1Wakeup ext1_wakeup) { - this->ext1_wakeup_ = ext1_wakeup; -} +void DeepSleepComponent::set_ext1_wakeup(Ext1Wakeup ext1_wakeup) { this->ext1_wakeup_ = ext1_wakeup; } #endif -void DeepSleepComponent::set_run_duration(uint32_t time_ms) { - this->run_duration_ = time_ms; -} -void DeepSleepComponent::begin_sleep_(bool manual) { +void DeepSleepComponent::set_run_duration(uint32_t time_ms) { this->run_duration_ = time_ms; } +void DeepSleepComponent::begin_sleep(bool manual) { if (this->prevent_ && !manual) { this->next_enter_deep_sleep_ = true; return; } #ifdef ARDUINO_ARCH_ESP32 - if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_KEEP_AWAKE && - this->wakeup_pin_.has_value() && !this->sleep_duration_.has_value() && (*this->wakeup_pin_)->digital_read()) { + if (this->wakeup_pin_mode_ == WAKEUP_PIN_MODE_KEEP_AWAKE && this->wakeup_pin_.has_value() && + !this->sleep_duration_.has_value() && (*this->wakeup_pin_)->digital_read()) { // Defer deep sleep until inactive if (!this->next_enter_deep_sleep_) { this->status_set_warning(); @@ -102,13 +92,9 @@ void DeepSleepComponent::begin_sleep_(bool manual) { ESP.deepSleep(*this->sleep_duration_); #endif } -float DeepSleepComponent::get_setup_priority() const { - return -100.0f; -} -void DeepSleepComponent::prevent_deep_sleep() { - this->prevent_ = true; -} +float DeepSleepComponent::get_setup_priority() const { return -100.0f; } +void DeepSleepComponent::prevent_deep_sleep() { this->prevent_ = true; } ESPHOME_NAMESPACE_END -#endif //USE_DEEP_SLEEP +#endif // USE_DEEP_SLEEP diff --git a/src/esphome/deep_sleep_component.h b/src/esphome/deep_sleep_component.h index 95ecb8df..02a6b691 100644 --- a/src/esphome/deep_sleep_component.h +++ b/src/esphome/deep_sleep_component.h @@ -17,8 +17,8 @@ ESPHOME_NAMESPACE_BEGIN * and the scenario occurs that the wakeup pin is already in the wakeup state. */ enum WakeupPinMode { - WAKEUP_PIN_MODE_IGNORE = 0, ///< Ignore the fact that we will wake up when going into deep sleep. - WAKEUP_PIN_MODE_KEEP_AWAKE, ///< As long as the wakeup pin is still in the wakeup state, keep awake. + WAKEUP_PIN_MODE_IGNORE = 0, ///< Ignore the fact that we will wake up when going into deep sleep. + WAKEUP_PIN_MODE_KEEP_AWAKE, ///< As long as the wakeup pin is still in the wakeup state, keep awake. /** Automatically invert the wakeup level. For example if we were set up to wake up on HIGH, but the pin * is already high when attempting to enter deep sleep, re-configure deep sleep to wake up on LOW level. @@ -33,11 +33,9 @@ struct Ext1Wakeup { #endif -template -class EnterDeepSleepAction; +template class EnterDeepSleepAction; -template -class PreventDeepSleepAction; +template class PreventDeepSleepAction; /** This component allows setting up the node to go into deep sleep mode to conserve battery. * @@ -69,13 +67,11 @@ class DeepSleepComponent : public Component { float get_setup_priority() const override; /// Helper to enter deep sleep mode - void begin_sleep_(bool manual = false); + void begin_sleep(bool manual = false); - template - EnterDeepSleepAction *make_enter_deep_sleep_action(); + template EnterDeepSleepAction *make_enter_deep_sleep_action(); - template - PreventDeepSleepAction *make_prevent_deep_sleep_action(); + template PreventDeepSleepAction *make_prevent_deep_sleep_action(); void prevent_deep_sleep(); @@ -83,7 +79,7 @@ class DeepSleepComponent : public Component { optional sleep_duration_; #ifdef ARDUINO_ARCH_ESP32 optional wakeup_pin_; - WakeupPinMode wakeup_pin_mode_{WAKEUP_PIN_MODE_IGNORE}; + WakeupPinMode wakeup_pin_mode_{WAKEUP_PIN_MODE_IGNORE}; optional ext1_wakeup_; #endif optional run_duration_; @@ -93,22 +89,22 @@ class DeepSleepComponent : public Component { extern bool global_has_deep_sleep; -template -class EnterDeepSleepAction : public Action { +template class EnterDeepSleepAction : public Action { public: EnterDeepSleepAction(DeepSleepComponent *deep_sleep); void play(Ts... x) override; + protected: DeepSleepComponent *deep_sleep_; }; -template -class PreventDeepSleepAction : public Action { +template class PreventDeepSleepAction : public Action { public: PreventDeepSleepAction(DeepSleepComponent *deep_sleep); void play(Ts... x) override; + protected: DeepSleepComponent *deep_sleep_; }; @@ -116,35 +112,28 @@ class PreventDeepSleepAction : public Action { template EnterDeepSleepAction::EnterDeepSleepAction(DeepSleepComponent *deep_sleep) : deep_sleep_(deep_sleep) {} -template -void EnterDeepSleepAction::play(Ts... x) { - this->deep_sleep_->begin_sleep_(true); +template void EnterDeepSleepAction::play(Ts... x) { + this->deep_sleep_->begin_sleep(true); // no need to call play_next. We should be done with execution by now. } -template -EnterDeepSleepAction *DeepSleepComponent::make_enter_deep_sleep_action() { +template EnterDeepSleepAction *DeepSleepComponent::make_enter_deep_sleep_action() { return new EnterDeepSleepAction(this); } template -PreventDeepSleepAction::PreventDeepSleepAction(DeepSleepComponent *deep_sleep) - : deep_sleep_(deep_sleep) { - -} -template -void PreventDeepSleepAction::play(Ts... x) { +PreventDeepSleepAction::PreventDeepSleepAction(DeepSleepComponent *deep_sleep) : deep_sleep_(deep_sleep) {} +template void PreventDeepSleepAction::play(Ts... x) { this->deep_sleep_->prevent_deep_sleep(); this->play_next(x...); } -template -PreventDeepSleepAction *DeepSleepComponent::make_prevent_deep_sleep_action() { +template PreventDeepSleepAction *DeepSleepComponent::make_prevent_deep_sleep_action() { return new PreventDeepSleepAction(this); } ESPHOME_NAMESPACE_END -#endif //USE_DEEP_SLEEP +#endif // USE_DEEP_SLEEP -#endif //ESPHOME_DEEP_SLEEP_COMPONENT_H +#endif // ESPHOME_DEEP_SLEEP_COMPONENT_H diff --git a/src/esphome/defines.h b/src/esphome/defines.h index 2a5b9986..853f9b74 100644 --- a/src/esphome/defines.h +++ b/src/esphome/defines.h @@ -3,276 +3,276 @@ #define ESPHOME_VERSION "1.12.0-dev" -#define HOT __attribute__ ((hot)) +#define HOT __attribute__((hot)) #define ESPDEPRECATED(msg) __attribute__((deprecated(msg))) #define ALWAYS_INLINE __attribute__((always_inline)) #ifndef DOXYGEN - #define ESPHOME_NAMESPACE_BEGIN namespace esphome { - #define ESPHOME_NAMESPACE_END } - #define ESPHOME_NAMESPACE esphome +#define ESPHOME_NAMESPACE_BEGIN namespace esphome { +#define ESPHOME_NAMESPACE_END } +#define ESPHOME_NAMESPACE esphome #else - #define ESPHOME_NAMESPACE_BEGIN /##/ - #define ESPHOME_NAMESPACE_END /##/ - #define ESPHOME_NAMESPACE +#define ESPHOME_NAMESPACE_BEGIN / ## / +#define ESPHOME_NAMESPACE_END / ## / +#define ESPHOME_NAMESPACE #endif #ifndef ESPHOME_USE - #define USE_OTA - #define USE_I2C - #define USE_BINARY_SENSOR - #define USE_GPIO_BINARY_SENSOR - #define USE_STATUS_BINARY_SENSOR - #define USE_SENSOR - #define USE_DHT_SENSOR - #define USE_DHT12_SENSOR - #define USE_DALLAS_SENSOR - #define USE_PULSE_COUNTER_SENSOR - #define USE_ADC_SENSOR - #define USE_ADS1115_SENSOR - #define USE_BMP085_SENSOR - #define USE_HTU21D_SENSOR - #define USE_HDC1080_SENSOR - #define USE_ULTRASONIC_SENSOR - #define USE_WIFI_SIGNAL_SENSOR - #define USE_OUTPUT - #ifdef ARDUINO_ARCH_ESP32 - #define USE_LEDC_OUTPUT - #endif - #define USE_PCA9685_OUTPUT - #define USE_GPIO_OUTPUT - #ifdef ARDUINO_ARCH_ESP8266 - #define USE_ESP8266_PWM_OUTPUT - #endif - #define USE_LIGHT - #define USE_SWITCH - #define USE_OUTPUT_SWITCH - #define USE_REMOTE - #define USE_REMOTE_RECEIVER - #define USE_REMOTE_TRANSMITTER - #define USE_GPIO_SWITCH - #define USE_RESTART_SWITCH - #define USE_SHUTDOWN_SWITCH - #define USE_FAN - #define USE_DEBUG_COMPONENT - #define USE_DEEP_SLEEP - #define USE_PCF8574 - #define USE_IO - #define USE_MPU6050 - #define USE_TSL2561 - #define USE_BH1750 - #define USE_BME280 - #define USE_BMP280 - #define USE_BME680 - #define USE_SHT3XD - #define USE_TEMPLATE_SENSOR - #ifdef ARDUINO_ARCH_ESP32 - #define USE_ESP32_TOUCH_BINARY_SENSOR - #endif - #ifdef ARDUINO_ARCH_ESP32 - #define USE_ESP32_BLE_TRACKER - #define USE_ESP32_BLE_BEACON - #endif - #define USE_ROTARY_ENCODER_SENSOR - #define USE_MAX31855_SENSOR - #define USE_MAX6675_SENSOR - #define USE_TEMPLATE_BINARY_SENSOR - #define USE_TEMPLATE_SWITCH - #define USE_COVER - #define USE_TEMPLATE_COVER - #ifdef ARDUINO_ARCH_ESP32 - #define USE_ESP32_HALL_SENSOR - #endif - #define USE_DUTY_CYCLE_SENSOR - #define USE_STATUS_LED - #define USE_SPI - #define USE_PN532 - #define USE_UART - #define USE_MHZ19 - #define USE_UART_SWITCH - #define USE_UPTIME_SENSOR - #define USE_INA219 - #define USE_INA3221 - #define USE_HMC5883L - #define USE_RDM6300 - #define USE_MS5611 - #define USE_HX711 - #define USE_TCS34725 - #define USE_MAX7219 - #define USE_LCD_DISPLAY - #define USE_LCD_DISPLAY_PCF8574 - #define USE_SSD1306 - #define USE_WAVESHARE_EPAPER - #define USE_DISPLAY - #define USE_TIME - #define USE_SNTP_COMPONENT - #define USE_NEXTION - #define USE_HLW8012 - #define USE_TEXT_SENSOR - #define USE_MQTT_SUBSCRIBE_TEXT_SENSOR - #define USE_VERSION_TEXT_SENSOR - #define USE_TEMPLATE_TEXT_SENSOR - #define USE_MQTT_SUBSCRIBE_SENSOR - #define USE_CSE7766 - #define USE_PMSX003 - #define USE_STEPPER - #define USE_A4988 - #define USE_ULN2003 - #define USE_TOTAL_DAILY_ENERGY_SENSOR - #define USE_MY9231_OUTPUT - #define USE_CUSTOM_SENSOR - #define USE_CUSTOM_BINARY_SENSOR - #define USE_CUSTOM_OUTPUT - #define USE_CUSTOM_SWITCH - #define USE_CUSTOM_TEXT_SENSOR - #define USE_CUSTOM_COMPONENT - #define USE_API - #define USE_HOMEASSISTANT_TIME - #define USE_HOMEASSISTANT_SENSOR - #define USE_HOMEASSISTANT_TEXT_SENSOR - #define USE_HOMEASSISTANT_BINARY_SENSOR - #define USE_APDS9960 - #define USE_MPR121 - #define USE_MQTT +#define USE_OTA +#define USE_I2C +#define USE_BINARY_SENSOR +#define USE_GPIO_BINARY_SENSOR +#define USE_STATUS_BINARY_SENSOR +#define USE_SENSOR +#define USE_DHT_SENSOR +#define USE_DHT12_SENSOR +#define USE_DALLAS_SENSOR +#define USE_PULSE_COUNTER_SENSOR +#define USE_ADC_SENSOR +#define USE_ADS1115_SENSOR +#define USE_BMP085_SENSOR +#define USE_HTU21D_SENSOR +#define USE_HDC1080_SENSOR +#define USE_ULTRASONIC_SENSOR +#define USE_WIFI_SIGNAL_SENSOR +#define USE_OUTPUT +#ifdef ARDUINO_ARCH_ESP32 +#define USE_LEDC_OUTPUT +#endif +#define USE_PCA9685_OUTPUT +#define USE_GPIO_OUTPUT +#ifdef ARDUINO_ARCH_ESP8266 +#define USE_ESP8266_PWM_OUTPUT +#endif +#define USE_LIGHT +#define USE_SWITCH +#define USE_OUTPUT_SWITCH +#define USE_REMOTE +#define USE_REMOTE_RECEIVER +#define USE_REMOTE_TRANSMITTER +#define USE_GPIO_SWITCH +#define USE_RESTART_SWITCH +#define USE_SHUTDOWN_SWITCH +#define USE_FAN +#define USE_DEBUG_COMPONENT +#define USE_DEEP_SLEEP +#define USE_PCF8574 +#define USE_IO +#define USE_MPU6050 +#define USE_TSL2561 +#define USE_BH1750 +#define USE_BME280 +#define USE_BMP280 +#define USE_BME680 +#define USE_SHT3XD +#define USE_TEMPLATE_SENSOR +#ifdef ARDUINO_ARCH_ESP32 +#define USE_ESP32_TOUCH_BINARY_SENSOR +#endif +#ifdef ARDUINO_ARCH_ESP32 +#define USE_ESP32_BLE_TRACKER +#define USE_ESP32_BLE_BEACON +#endif +#define USE_ROTARY_ENCODER_SENSOR +#define USE_MAX31855_SENSOR +#define USE_MAX6675_SENSOR +#define USE_TEMPLATE_BINARY_SENSOR +#define USE_TEMPLATE_SWITCH +#define USE_COVER +#define USE_TEMPLATE_COVER +#ifdef ARDUINO_ARCH_ESP32 +#define USE_ESP32_HALL_SENSOR +#endif +#define USE_DUTY_CYCLE_SENSOR +#define USE_STATUS_LED +#define USE_SPI +#define USE_PN532 +#define USE_UART +#define USE_MHZ19 +#define USE_UART_SWITCH +#define USE_UPTIME_SENSOR +#define USE_INA219 +#define USE_INA3221 +#define USE_HMC5883L +#define USE_RDM6300 +#define USE_MS5611 +#define USE_HX711 +#define USE_TCS34725 +#define USE_MAX7219 +#define USE_LCD_DISPLAY +#define USE_LCD_DISPLAY_PCF8574 +#define USE_SSD1306 +#define USE_WAVESHARE_EPAPER +#define USE_DISPLAY +#define USE_TIME +#define USE_SNTP_COMPONENT +#define USE_NEXTION +#define USE_HLW8012 +#define USE_TEXT_SENSOR +#define USE_MQTT_SUBSCRIBE_TEXT_SENSOR +#define USE_VERSION_TEXT_SENSOR +#define USE_TEMPLATE_TEXT_SENSOR +#define USE_MQTT_SUBSCRIBE_SENSOR +#define USE_CSE7766 +#define USE_PMSX003 +#define USE_STEPPER +#define USE_A4988 +#define USE_ULN2003 +#define USE_TOTAL_DAILY_ENERGY_SENSOR +#define USE_MY9231_OUTPUT +#define USE_CUSTOM_SENSOR +#define USE_CUSTOM_BINARY_SENSOR +#define USE_CUSTOM_OUTPUT +#define USE_CUSTOM_SWITCH +#define USE_CUSTOM_TEXT_SENSOR +#define USE_CUSTOM_COMPONENT +#define USE_API +#define USE_HOMEASSISTANT_TIME +#define USE_HOMEASSISTANT_SENSOR +#define USE_HOMEASSISTANT_TEXT_SENSOR +#define USE_HOMEASSISTANT_BINARY_SENSOR +#define USE_APDS9960 +#define USE_MPR121 +#define USE_MQTT #endif #ifdef USE_REMOTE_RECEIVER - #ifndef USE_REMOTE - #define USE_REMOTE - #endif - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif +#ifndef USE_REMOTE +#define USE_REMOTE +#endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif #endif #ifdef USE_REMOTE_TRANSMITTER - #ifndef USE_REMOTE - #define USE_REMOTE - #endif - #ifndef USE_SWITCH - #define USE_SWITCH - #endif +#ifndef USE_REMOTE +#define USE_REMOTE +#endif +#ifndef USE_SWITCH +#define USE_SWITCH +#endif #endif #ifdef USE_ESP32_TOUCH_BINARY_SENSOR - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif #endif #ifdef USE_ESP32_BLE_TRACKER - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif - #ifndef USE_SENSOR - #define USE_SENSOR - #endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif +#ifndef USE_SENSOR +#define USE_SENSOR +#endif #endif #ifdef USE_PN532 - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif #endif #ifdef USE_RDM6300 - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif #endif #ifdef USE_DALLAS_SENSOR - #ifndef USE_ONE_WIRE - #define USE_ONE_WIRE - #endif +#ifndef USE_ONE_WIRE +#define USE_ONE_WIRE +#endif #endif #ifdef USE_LIGHT - #ifndef USE_OUTPUT - #define USE_OUTPUT - #endif +#ifndef USE_OUTPUT +#define USE_OUTPUT +#endif #endif #ifdef USE_PCF8574 - #ifndef USE_IO - #define USE_IO - #endif +#ifndef USE_IO +#define USE_IO +#endif #endif #ifdef USE_LCD_DISPLAY_PCF8574 - #ifndef USE_LCD_DISPLAY - #define USE_LCD_DISPLAY - #endif +#ifndef USE_LCD_DISPLAY +#define USE_LCD_DISPLAY +#endif #endif #ifdef USE_HLW8012 - #ifndef USE_PULSE_COUNTER_SENSOR - #define USE_PULSE_COUNTER_SENSOR - #endif +#ifndef USE_PULSE_COUNTER_SENSOR +#define USE_PULSE_COUNTER_SENSOR +#endif #endif #ifdef USE_MY9231_OUTPUT - #ifndef USE_OUTPUT - #define USE_OUTPUT - #endif +#ifndef USE_OUTPUT +#define USE_OUTPUT +#endif #endif #ifdef USE_APDS9960 - #ifndef USE_SENSOR - #define USE_SENSOR - #endif - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif +#ifndef USE_SENSOR +#define USE_SENSOR +#endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif #endif #ifdef USE_MPR121 - #ifndef USE_BINARY_SENSOR - #define USE_BINARY_SENSOR - #endif +#ifndef USE_BINARY_SENSOR +#define USE_BINARY_SENSOR +#endif #endif #if defined(USE_MQTT) && defined(USE_BINARY_SENSOR) - #ifndef USE_MQTT_BINARY_SENSOR - #define USE_MQTT_BINARY_SENSOR - #endif +#ifndef USE_MQTT_BINARY_SENSOR +#define USE_MQTT_BINARY_SENSOR +#endif #endif #if defined(USE_MQTT) && defined(USE_COVER) - #ifndef USE_MQTT_COVER - #define USE_MQTT_COVER - #endif +#ifndef USE_MQTT_COVER +#define USE_MQTT_COVER +#endif #endif #if defined(USE_MQTT) && defined(USE_FAN) - #ifndef USE_MQTT_FAN - #define USE_MQTT_FAN - #endif +#ifndef USE_MQTT_FAN +#define USE_MQTT_FAN +#endif #endif #if defined(USE_MQTT) && defined(USE_LIGHT) - #ifndef USE_MQTT_LIGHT - #define USE_MQTT_LIGHT - #endif +#ifndef USE_MQTT_LIGHT +#define USE_MQTT_LIGHT +#endif #endif #if defined(USE_MQTT) && defined(USE_CUSTOM_COMPONENT) - #ifndef USE_MQTT_CUSTOM_COMPONENT - #define USE_MQTT_CUSTOM_COMPONENT - #endif +#ifndef USE_MQTT_CUSTOM_COMPONENT +#define USE_MQTT_CUSTOM_COMPONENT +#endif #endif #if defined(USE_MQTT) && defined(USE_SENSOR) - #ifndef USE_MQTT_SENSOR - #define USE_MQTT_SENSOR - #endif +#ifndef USE_MQTT_SENSOR +#define USE_MQTT_SENSOR +#endif #endif #if defined(USE_MQTT) && defined(USE_SWITCH) - #ifndef USE_MQTT_SWITCH - #define USE_MQTT_SWITCH - #endif +#ifndef USE_MQTT_SWITCH +#define USE_MQTT_SWITCH +#endif #endif #if defined(USE_MQTT) && defined(USE_TEXT_SENSOR) - #ifndef USE_MQTT_TEXT_SENSOR - #define USE_MQTT_TEXT_SENSOR - #endif +#ifndef USE_MQTT_TEXT_SENSOR +#define USE_MQTT_TEXT_SENSOR +#endif #endif #if !defined(DONT_STORE_LOG_STR_IN_FLASH) && defined(ARDUINO_ARCH_ESP8266) - #ifndef USE_STORE_LOG_STR_IN_FLASH - #define USE_STORE_LOG_STR_IN_FLASH - #endif +#ifndef USE_STORE_LOG_STR_IN_FLASH +#define USE_STORE_LOG_STR_IN_FLASH +#endif #endif -#endif //ESPHOME_DEFINES_H +#endif // ESPHOME_DEFINES_H diff --git a/src/esphome/display/display.cpp b/src/esphome/display/display.cpp index 85692a47..dc957f4b 100644 --- a/src/esphome/display/display.cpp +++ b/src/esphome/display/display.cpp @@ -25,54 +25,49 @@ void DisplayBuffer::init_internal_(uint32_t buffer_length) { } this->clear(); } -void DisplayBuffer::fill(int color) { - this->filled_rectangle(0, 0, this->get_width(), this->get_height(), color); -} -void DisplayBuffer::clear() { - this->fill(COLOR_OFF); -} +void DisplayBuffer::fill(int color) { this->filled_rectangle(0, 0, this->get_width(), this->get_height(), color); } +void DisplayBuffer::clear() { this->fill(COLOR_OFF); } int DisplayBuffer::get_width() { switch (this->rotation_) { case DISPLAY_ROTATION_90_DEGREES: case DISPLAY_ROTATION_270_DEGREES: - return this->get_height_internal_(); + return this->get_height_internal(); case DISPLAY_ROTATION_0_DEGREES: case DISPLAY_ROTATION_180_DEGREES: default: - return this->get_width_internal_(); + return this->get_width_internal(); } } int DisplayBuffer::get_height() { switch (this->rotation_) { case DISPLAY_ROTATION_0_DEGREES: case DISPLAY_ROTATION_180_DEGREES: - return this->get_height_internal_(); + return this->get_height_internal(); case DISPLAY_ROTATION_90_DEGREES: case DISPLAY_ROTATION_270_DEGREES: default: - return this->get_width_internal_(); + return this->get_width_internal(); } } -void DisplayBuffer::set_rotation(DisplayRotation rotation) { - this->rotation_ = rotation; -} +void DisplayBuffer::set_rotation(DisplayRotation rotation) { this->rotation_ = rotation; } void HOT DisplayBuffer::draw_pixel_at(int x, int y, int color) { switch (this->rotation_) { - case DISPLAY_ROTATION_0_DEGREES:break; + case DISPLAY_ROTATION_0_DEGREES: + break; case DISPLAY_ROTATION_90_DEGREES: std::swap(x, y); - x = this->get_width_internal_() - x - 1; + x = this->get_width_internal() - x - 1; break; case DISPLAY_ROTATION_180_DEGREES: - x = this->get_width_internal_() - x - 1; - y = this->get_height_internal_() - y - 1; + x = this->get_width_internal() - x - 1; + y = this->get_height_internal() - y - 1; break; case DISPLAY_ROTATION_270_DEGREES: std::swap(x, y); - y = this->get_height_internal_() - y - 1; + y = this->get_height_internal() - y - 1; break; } - this->draw_absolute_pixel_internal_(x, y, color); + this->draw_absolute_pixel_internal(x, y, color); feed_wdt(); } void HOT DisplayBuffer::line(int x1, int y1, int x2, int y2, int color) { @@ -181,11 +176,11 @@ void DisplayBuffer::print(int x, int y, Font *font, int color, TextAlign align, // Unknown char, skip ESP_LOGW(TAG, "Encountered character without representation in font: '%c'", text[i]); if (!font->get_glyphs().empty()) { - uint8_t width_ = font->get_glyphs()[0].width_; - for (int x_ = 0; x_ < width_; x_++) - for (int y_ = 0; y_ < height; y_++) - this->draw_pixel_at(x_ + x_at, y_ + y_start, color); - x_at += width_; + uint8_t glyph_width = font->get_glyphs()[0].width_; + for (int glyph_x = 0; glyph_x < glyph_width; glyph_x++) + for (int glyph_y = 0; glyph_y < height; glyph_y++) + this->draw_pixel_at(glyph_x + x_at, glyph_y + y_start, color); + x_at += glyph_width; } i++; @@ -196,15 +191,15 @@ void DisplayBuffer::print(int x, int y, Font *font, int color, TextAlign align, int scan_x1, scan_y1, scan_width, scan_height; glyph.scan_area(&scan_x1, &scan_y1, &scan_width, &scan_height); - for (int x_ = scan_x1; x_ < scan_x1 + scan_width; x_++) { - for (int y_ = scan_y1; y_ < scan_y1 + scan_height; y_++) { - if (glyph.get_pixel(x_, y_)) { - this->draw_pixel_at(x_ + x_at, y_ + y_start, color); + for (int glyph_x = scan_x1; glyph_x < scan_x1 + scan_width; glyph_x++) { + for (int glyph_y = scan_y1; glyph_y < scan_y1 + scan_height; glyph_y++) { + if (glyph.get_pixel(glyph_x, glyph_y)) { + this->draw_pixel_at(glyph_x + x_at, glyph_y + y_start, color); } } } - x_at += glyph.width_ + glyph.offset_x; + x_at += glyph.width_ + glyph.offset_x_; i += match_length; } @@ -216,15 +211,14 @@ void DisplayBuffer::vprintf_(int x, int y, Font *font, int color, TextAlign alig this->print(x, y, font, color, align, buffer); } void DisplayBuffer::image(int x, int y, Image *image) { - for (int x_ = 0; x_ < image->get_width(); x_++) { - for (int y_ = 0; y_ < image->get_height(); y_++) { - this->draw_pixel_at(x + x_, y + y_, image->get_pixel(x_, y_) ? COLOR_ON : COLOR_OFF); + for (int img_x = 0; img_x < image->get_width(); img_x++) { + for (int img_y = 0; img_y < image->get_height(); img_y++) { + this->draw_pixel_at(x + img_x, y + img_y, image->get_pixel(img_x, img_y) ? COLOR_ON : COLOR_OFF); } } } -void DisplayBuffer::get_text_bounds(int x, int y, - const char *text, Font *font, TextAlign align, - int *x1, int *y1, int *width, int *height) { +void DisplayBuffer::get_text_bounds(int x, int y, const char *text, Font *font, TextAlign align, int *x1, int *y1, + int *width, int *height) { int x_offset, baseline; font->measure(text, width, &x_offset, &baseline, height); @@ -236,7 +230,7 @@ void DisplayBuffer::get_text_bounds(int x, int y, *x1 = x - *width; break; case TextAlign::CENTER_HORIZONTAL: - *x1 = x - (*width)/2; + *x1 = x - (*width) / 2; break; case TextAlign::LEFT: default: @@ -253,7 +247,7 @@ void DisplayBuffer::get_text_bounds(int x, int y, *y1 = y - baseline; break; case TextAlign::CENTER_VERTICAL: - *y1 = y - (*height)/2; + *y1 = y - (*height) / 2; break; case TextAlign::TOP: default: @@ -294,9 +288,7 @@ void DisplayBuffer::printf(int x, int y, Font *font, const char *format, ...) { this->vprintf_(x, y, font, COLOR_ON, TextAlign::CENTER_LEFT, format, arg); va_end(arg); } -void DisplayBuffer::set_writer(display_writer_t &&writer) { - this->writer_ = std::move(writer); -} +void DisplayBuffer::set_writer(display_writer_t &&writer) { this->writer_ = writer; } void DisplayBuffer::set_pages(std::vector pages) { for (auto *page : pages) page->set_parent(this); @@ -309,16 +301,10 @@ void DisplayBuffer::set_pages(std::vector pages) { pages[pages.size() - 1]->set_next(pages[0]); this->show_page(pages[0]); } -void DisplayBuffer::show_page(DisplayPage *page) { - this->page_ = page; -} -void DisplayBuffer::show_next_page() { - this->page_->show_next(); -} -void DisplayBuffer::show_prev_page() { - this->page_->show_prev(); -} -void DisplayBuffer::do_update() { +void DisplayBuffer::show_page(DisplayPage *page) { this->page_ = page; } +void DisplayBuffer::show_next_page() { this->page_->show_next(); } +void DisplayBuffer::show_prev_page() { this->page_->show_prev(); } +void DisplayBuffer::do_update_() { this->clear(); if (this->page_ != nullptr) { this->page_->get_writer()(*this); @@ -345,22 +331,24 @@ void DisplayBuffer::strftime(int x, int y, Font *font, const char *format, time: } #endif -Glyph::Glyph(const char *aChar, const uint8_t *data_start, uint32_t offset, int offset_x, int offset_y, int width, int height) - : char_(aChar), data_(data_start + offset), offset_x(offset_x), offset_y(offset_y), width_(width), height_(height) { - -} +Glyph::Glyph(const char *a_char, const uint8_t *data_start, uint32_t offset, int offset_x, int offset_y, int width, + int height) + : char_(a_char), + data_(data_start + offset), + offset_x_(offset_x), + offset_y_(offset_y), + width_(width), + height_(height) {} bool Glyph::get_pixel(int x, int y) const { - const int x_data = x - this->offset_x; - const int y_data = y - this->offset_y; + const int x_data = x - this->offset_x_; + const int y_data = y - this->offset_y_; if (x_data < 0 || x_data >= this->width_ || y_data < 0 || y_data >= this->height_) return false; const uint32_t width_8 = ((this->width_ + 7u) / 8u) * 8u; const uint32_t pos = x_data + y_data * width_8; return pgm_read_byte(this->data_ + (pos / 8u)) & (0x80 >> (pos % 8u)); } -const char *Glyph::get_char() const { - return this->char_; -} +const char *Glyph::get_char() const { return this->char_; } bool Glyph::compare_to(const char *str) const { // 1 -> this->char_ // 2 -> str @@ -388,8 +376,8 @@ int Glyph::match_length(const char *str) const { return 0; } void Glyph::scan_area(int *x1, int *y1, int *width, int *height) const { - *x1 = this->offset_x; - *y1 = this->offset_y; + *x1 = this->offset_x_; + *y1 = this->offset_y_; *width = this->width_; *height = this->height_; } @@ -428,10 +416,10 @@ void Font::measure(const char *str, int *width, int *x_offset, int *baseline, in const Glyph &glyph = this->glyphs_[glyph_n]; if (!has_char) - min_x = glyph.offset_x; + min_x = glyph.offset_x_; else - min_x = std::min(min_x, x + glyph.offset_x); - x += glyph.width_ + glyph.offset_x; + min_x = std::min(min_x, x + glyph.offset_x_); + x += glyph.width_ + glyph.offset_x_; i += match_length; has_char = true; @@ -439,9 +427,7 @@ void Font::measure(const char *str, int *width, int *x_offset, int *baseline, in *x_offset = min_x; *width = x - min_x; } -const std::vector &Font::get_glyphs() const { - return this->glyphs_; -} +const std::vector &Font::get_glyphs() const { return this->glyphs_; } Font::Font(std::vector &&glyphs, int baseline, int bottom) : glyphs_(std::move(glyphs)), baseline_(baseline), bottom_(bottom) {} @@ -452,12 +438,8 @@ bool Image::get_pixel(int x, int y) const { const uint32_t pos = x + y * width_8; return pgm_read_byte(this->data_start_ + (pos / 8u)) & (0x80 >> (pos % 8u)); } -int Image::get_width() const { - return this->width_; -} -int Image::get_height() const { - return this->height_; -} +int Image::get_width() const { return this->width_; } +int Image::get_height() const { return this->height_; } Image::Image(const uint8_t *data_start, int width, int height) : width_(width), height_(height), data_start_(data_start) {} @@ -470,8 +452,8 @@ void DisplayPage::set_prev(DisplayPage *prev) { this->prev_ = prev; } void DisplayPage::set_next(DisplayPage *next) { this->next_ = next; } const display_writer_t &DisplayPage::get_writer() const { return this->writer_; } -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_DISPLAY +#endif // USE_DISPLAY diff --git a/src/esphome/display/display.h b/src/esphome/display/display.h index 9f045b45..697f90eb 100644 --- a/src/esphome/display/display.h +++ b/src/esphome/display/display.h @@ -87,11 +87,11 @@ class DisplayPage; using display_writer_t = std::function; #define LOG_DISPLAY(prefix, type, obj) \ - if (obj != nullptr) { \ - ESP_LOGCONFIG(TAG, prefix type); \ - ESP_LOGCONFIG(TAG, prefix " Rotations: %d °", obj->rotation_); \ - ESP_LOGCONFIG(TAG, prefix " Dimensions: %dpx x %dpx", obj->get_width(), obj->get_height()); \ - } + if (obj != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix type); \ + ESP_LOGCONFIG(TAG, prefix " Rotations: %d °", obj->rotation_); \ + ESP_LOGCONFIG(TAG, prefix " Dimensions: %dpx x %dpx", obj->get_width(), obj->get_height()); \ + } class DisplayBuffer { public: @@ -116,7 +116,8 @@ class DisplayBuffer { /// Draw a vertical line from the point [x,y] to [x,y+width] with the given color. void vertical_line(int x, int y, int height, int color = COLOR_ON); - /// Draw the outline of a rectangle with the top left point at [x1,y1] and the bottom right point at [x1+width,y1+height]. + /// Draw the outline of a rectangle with the top left point at [x1,y1] and the bottom right point at + /// [x1+width,y1+height]. void rectangle(int x1, int y1, int width, int height, int color = COLOR_ON); /// Fill a rectangle with the top left point at [x1,y1] and the bottom right point at [x1+width,y1+height]. @@ -159,7 +160,6 @@ class DisplayBuffer { */ void print(int x, int y, Font *font, TextAlign align, const char *text); - /** Print `text` with the top left at [x,y] with `font`. * * @param x The x coordinate of the upper left corner. @@ -179,7 +179,8 @@ class DisplayBuffer { * @param format The format to use. * @param ... The arguments to use for the text formatting. */ - void printf(int x, int y, Font *font, int color, TextAlign align, const char *format, ...) __attribute__ ((format (printf, 7, 8))); + void printf(int x, int y, Font *font, int color, TextAlign align, const char *format, ...) + __attribute__((format(printf, 7, 8))); /** Evaluate the printf-format `format` and print the result with the top left at [x,y] with `font`. * @@ -190,7 +191,7 @@ class DisplayBuffer { * @param format The format to use. * @param ... The arguments to use for the text formatting. */ - void printf(int x, int y, Font *font, int color, const char *format, ...) __attribute__ ((format (printf, 6, 7))); + void printf(int x, int y, Font *font, int color, const char *format, ...) __attribute__((format(printf, 6, 7))); /** Evaluate the printf-format `format` and print the result with the anchor point at [x,y] with `font`. * @@ -201,7 +202,7 @@ class DisplayBuffer { * @param format The format to use. * @param ... The arguments to use for the text formatting. */ - void printf(int x, int y, Font *font, TextAlign align, const char *format, ...) __attribute__ ((format (printf, 6, 7))); + void printf(int x, int y, Font *font, TextAlign align, const char *format, ...) __attribute__((format(printf, 6, 7))); /** Evaluate the printf-format `format` and print the result with the top left at [x,y] with `font`. * @@ -211,7 +212,7 @@ class DisplayBuffer { * @param format The format to use. * @param ... The arguments to use for the text formatting. */ - void printf(int x, int y, Font *font, const char *format, ...) __attribute__ ((format (printf, 5, 6))); + void printf(int x, int y, Font *font, const char *format, ...) __attribute__((format(printf, 5, 6))); #ifdef USE_TIME @@ -225,7 +226,8 @@ class DisplayBuffer { * @param format The strftime format to use. * @param time The time to format. */ - void strftime(int x, int y, Font *font, int color, TextAlign align, const char *format, time::ESPTime time) __attribute__ ((format (strftime, 7, 0))); + void strftime(int x, int y, Font *font, int color, TextAlign align, const char *format, time::ESPTime time) + __attribute__((format(strftime, 7, 0))); /** Evaluate the strftime-format `format` and print the result with the top left at [x,y] with `font`. * @@ -236,7 +238,8 @@ class DisplayBuffer { * @param format The strftime format to use. * @param time The time to format. */ - void strftime(int x, int y, Font *font, int color, const char *format, time::ESPTime time) __attribute__ ((format (strftime, 6, 0))); + void strftime(int x, int y, Font *font, int color, const char *format, time::ESPTime time) + __attribute__((format(strftime, 6, 0))); /** Evaluate the strftime-format `format` and print the result with the anchor point at [x,y] with `font`. * @@ -247,7 +250,8 @@ class DisplayBuffer { * @param format The strftime format to use. * @param time The time to format. */ - void strftime(int x, int y, Font *font, TextAlign align, const char *format, time::ESPTime time) __attribute__ ((format (strftime, 6, 0))); + void strftime(int x, int y, Font *font, TextAlign align, const char *format, time::ESPTime time) + __attribute__((format(strftime, 6, 0))); /** Evaluate the strftime-format `format` and print the result with the top left at [x,y] with `font`. * @@ -257,7 +261,8 @@ class DisplayBuffer { * @param format The strftime format to use. * @param time The time to format. */ - void strftime(int x, int y, Font *font, const char *format, time::ESPTime time) __attribute__ ((format (strftime, 5, 0))); + void strftime(int x, int y, Font *font, const char *format, time::ESPTime time) + __attribute__((format(strftime, 5, 0))); #endif /// Draw the `image` with the top-left corner at [x,y] to the screen. @@ -275,7 +280,8 @@ class DisplayBuffer { * @param width A pointer to store the returned text width in. * @param height A pointer to store the returned text height in. */ - void get_text_bounds(int x, int y, const char *text, Font *font, TextAlign align, int *x1, int *y1, int *width, int *height); + void get_text_bounds(int x, int y, const char *text, Font *font, TextAlign align, int *x1, int *y1, int *width, + int *height); /// Internal method to set the display writer lambda. void set_writer(display_writer_t &&writer); @@ -292,15 +298,15 @@ class DisplayBuffer { protected: void vprintf_(int x, int y, Font *font, int color, TextAlign align, const char *format, va_list arg); - virtual void draw_absolute_pixel_internal_(int x, int y, int color) = 0; + virtual void draw_absolute_pixel_internal(int x, int y, int color) = 0; - virtual int get_height_internal_() = 0; + virtual int get_height_internal() = 0; - virtual int get_width_internal_() = 0; + virtual int get_width_internal() = 0; void init_internal_(uint32_t buffer_length); - void do_update(); + void do_update_(); uint8_t *buffer_{nullptr}; DisplayRotation rotation_{DISPLAY_ROTATION_0_DEGREES}; @@ -318,6 +324,7 @@ class DisplayPage { void set_prev(DisplayPage *prev); void set_next(DisplayPage *next); const display_writer_t &get_writer() const; + protected: DisplayBuffer *parent_; display_writer_t writer_; @@ -327,7 +334,8 @@ class DisplayPage { class Glyph { public: - Glyph(const char *aChar, const uint8_t *data_start, uint32_t offset, int offset_x, int offset_y, int width, int height); + Glyph(const char *a_char, const uint8_t *data_start, uint32_t offset, int offset_x, int offset_y, int width, + int height); bool get_pixel(int x, int y) const; @@ -345,8 +353,8 @@ class Glyph { const char *char_; const uint8_t *data_; - int offset_x; - int offset_y; + int offset_x_; + int offset_y_; int width_; int height_; }; @@ -386,51 +394,43 @@ class Image { const uint8_t *data_start_; }; -template -class DisplayPageShowAction : public Action { +template class DisplayPageShowAction : public Action { public: DisplayPageShowAction(); - template - void set_page(V page) { this->page_ = page; } + template void set_page(V page) { this->page_ = page; } void play(Ts... x) override; + protected: TemplatableValue page_; }; -template -class DisplayPageShowNextAction : public Action { +template class DisplayPageShowNextAction : public Action { public: DisplayPageShowNextAction(DisplayBuffer *buffer); void play(Ts... x) override; + protected: DisplayBuffer *buffer_; }; -template -class DisplayPageShowPrevAction : public Action { +template class DisplayPageShowPrevAction : public Action { public: DisplayPageShowPrevAction(DisplayBuffer *buffer); - DisplayPageShowPrevAction(); void play(Ts... x) override; + protected: DisplayBuffer *buffer_; }; - -template -DisplayPageShowPrevAction::DisplayPageShowPrevAction() {} template DisplayPageShowPrevAction::DisplayPageShowPrevAction(DisplayBuffer *buffer) : buffer_(buffer) {} -template -void DisplayPageShowPrevAction::play(Ts... x) { +template void DisplayPageShowPrevAction::play(Ts... x) { this->buffer_->show_prev_page(); this->play_next(x...); } -template -DisplayPageShowAction::DisplayPageShowAction() {} -template -void DisplayPageShowAction::play(Ts... x) { +template DisplayPageShowAction::DisplayPageShowAction() {} +template void DisplayPageShowAction::play(Ts... x) { auto *page = this->page_.value(x...); if (page != nullptr) { page->show(); @@ -439,16 +439,15 @@ void DisplayPageShowAction::play(Ts... x) { } template DisplayPageShowNextAction::DisplayPageShowNextAction(DisplayBuffer *buffer) : buffer_(buffer) {} -template -void DisplayPageShowNextAction::play(Ts... x) { +template void DisplayPageShowNextAction::play(Ts... x) { this->buffer_->show_next_page(); this->play_next(x...); } -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_DISPLAY +#endif // USE_DISPLAY -#endif //ESPHOME_DISPLAY_H +#endif // ESPHOME_DISPLAY_H diff --git a/src/esphome/display/lcd_display.cpp b/src/esphome/display/lcd_display.cpp index 12e3d456..7383f230 100644 --- a/src/esphome/display/lcd_display.cpp +++ b/src/esphome/display/lcd_display.cpp @@ -30,7 +30,7 @@ static const uint8_t LCD_DISPLAY_DISPLAY_ON = 0x04; static const uint8_t LCD_DISPLAY_FUNCTION_8_BIT_MODE = 0x10; static const uint8_t LCD_DISPLAY_FUNCTION_2_LINE = 0x08; -static const uint8_t LCD_DISPLAY_FUNCTION_5x10_DOTS = 0x04; +static const uint8_t LCD_DISPLAY_FUNCTION_5X10_DOTS = 0x04; void LCDDisplay::setup() { this->buffer_ = new uint8_t[this->rows_ * this->columns_]; @@ -39,7 +39,7 @@ void LCDDisplay::setup() { uint8_t display_function = 0; - if (!this->is_four_bit_mode_()) + if (!this->is_four_bit_mode()) display_function |= LCD_DISPLAY_FUNCTION_8_BIT_MODE; if (this->rows_ > 1) @@ -49,44 +49,43 @@ void LCDDisplay::setup() { // Commands can only be sent 40ms after boot-up, so let's wait if we're close const uint8_t now = millis(); - if (now < 40) delay(40u - now); + if (now < 40) + delay(40u - now); - if (this->is_four_bit_mode_()) { + if (this->is_four_bit_mode()) { this->write_n_bits(0x03, 4); - delay(5); // 4.1ms + delay(5); // 4.1ms this->write_n_bits(0x03, 4); delay(5); this->write_n_bits(0x03, 4); delayMicroseconds(150); this->write_n_bits(0x02, 4); } else { - this->command(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); - delay(5); // 4.1ms - this->command(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); + this->command_(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); + delay(5); // 4.1ms + this->command_(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); delayMicroseconds(150); - this->command(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); + this->command_(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); } - this->command(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); + this->command_(LCD_DISPLAY_COMMAND_FUNCTION_SET | display_function); uint8_t display_control = LCD_DISPLAY_DISPLAY_ON; - this->command(LCD_DISPLAY_COMMAND_DISPLAY_CONTROL | display_control); + this->command_(LCD_DISPLAY_COMMAND_DISPLAY_CONTROL | display_control); // clear display, also sets DDRAM address to 0 (home) - this->command(LCD_DISPLAY_COMMAND_CLEAR_DISPLAY); - delay(2); // 1.52ms + this->command_(LCD_DISPLAY_COMMAND_CLEAR_DISPLAY); + delay(2); // 1.52ms uint8_t entry_mode = LCD_DISPLAY_ENTRY_LEFT; - this->command(LCD_DISPLAY_COMMAND_ENTRY_MODE_SET | entry_mode); // 37µs + this->command_(LCD_DISPLAY_COMMAND_ENTRY_MODE_SET | entry_mode); // 37µs - this->command(LCD_DISPLAY_COMMAND_RETURN_HOME); - delay(2); // 1.52ms + this->command_(LCD_DISPLAY_COMMAND_RETURN_HOME); + delay(2); // 1.52ms } -float LCDDisplay::get_setup_priority() const { - return setup_priority::POST_HARDWARE; -} +float LCDDisplay::get_setup_priority() const { return setup_priority::POST_HARDWARE; } void HOT LCDDisplay::display() { - this->command(LCD_DISPLAY_COMMAND_SET_DDRAM_ADDR | 0); + this->command_(LCD_DISPLAY_COMMAND_SET_DDRAM_ADDR | 0); for (uint8_t i = 0; i < this->columns_; i++) this->send(this->buffer_[i], true); @@ -97,7 +96,7 @@ void HOT LCDDisplay::display() { } if (this->rows_ >= 1) { - this->command(LCD_DISPLAY_COMMAND_SET_DDRAM_ADDR | 0x40); + this->command_(LCD_DISPLAY_COMMAND_SET_DDRAM_ADDR | 0x40); for (uint8_t i = 0; i < this->columns_; i++) this->send(this->buffer_[this->columns_ + i], true); @@ -115,9 +114,7 @@ void LCDDisplay::update() { this->writer_(*this); this->display(); } -void LCDDisplay::command(uint8_t value) { - this->send(value, false); -} +void LCDDisplay::command_(uint8_t value) { this->send(value, false); } void LCDDisplay::print(uint8_t column, uint8_t row, const char *str) { uint8_t pos = column + row * this->columns_; for (; *str != '\0'; str++) { @@ -134,15 +131,9 @@ void LCDDisplay::print(uint8_t column, uint8_t row, const char *str) { pos++; } } -void LCDDisplay::print(uint8_t column, uint8_t row, const std::string &str) { - this->print(column, row, str.c_str()); -} -void LCDDisplay::print(const char *str) { - this->print(0, 0, str); -} -void LCDDisplay::print(const std::string &str) { - this->print(0, 0, str.c_str()); -} +void LCDDisplay::print(uint8_t column, uint8_t row, const std::string &str) { this->print(column, row, str.c_str()); } +void LCDDisplay::print(const char *str) { this->print(0, 0, str); } +void LCDDisplay::print(const std::string &str) { this->print(0, 0, str.c_str()); } void LCDDisplay::printf(uint8_t column, uint8_t row, const char *format, ...) { va_list arg; va_start(arg, format); @@ -163,9 +154,7 @@ void LCDDisplay::printf(const char *format, ...) { } LCDDisplay::LCDDisplay(uint8_t columns, uint8_t rows, uint32_t update_interval) : PollingComponent(update_interval), columns_(columns), rows_(rows) {} -void LCDDisplay::set_writer(lcd_writer_t &&writer) { - this->writer_ = std::move(writer); -} +void LCDDisplay::set_writer(lcd_writer_t &&writer) { this->writer_ = std::move(writer); } #ifdef USE_TIME void LCDDisplay::strftime(uint8_t column, uint8_t row, const char *format, time::ESPTime time) { char buffer[64]; @@ -173,24 +162,22 @@ void LCDDisplay::strftime(uint8_t column, uint8_t row, const char *format, time: if (ret > 0) this->print(column, row, buffer); } -void LCDDisplay::strftime(const char *format, time::ESPTime time) { - this->strftime(0, 0, format, time); -} +void LCDDisplay::strftime(const char *format, time::ESPTime time) { this->strftime(0, 0, format, time); } #endif void GPIOLCDDisplay::setup() { ESP_LOGCONFIG(TAG, "Setting up GPIO LCD Display..."); - this->rs_pin_->setup(); // OUTPUT + this->rs_pin_->setup(); // OUTPUT this->rs_pin_->digital_write(false); if (this->rw_pin_ != nullptr) { - this->rw_pin_->setup(); // OUTPUT + this->rw_pin_->setup(); // OUTPUT this->rw_pin_->digital_write(false); } - this->enable_pin_->setup(); // OUTPUT + this->enable_pin_->setup(); // OUTPUT this->enable_pin_->digital_write(false); - for (uint8_t i = 0; i < (this->is_four_bit_mode_() ? 4 : 8); i++) { - this->data_pins_[i]->setup(); // OUTPUT + for (uint8_t i = 0; i < (this->is_four_bit_mode() ? 4 : 8); i++) { + this->data_pins_[i]->setup(); // OUTPUT this->data_pins_[i]->digital_write(false); } LCDDisplay::setup(); @@ -202,29 +189,22 @@ void GPIOLCDDisplay::dump_config() { LOG_PIN(" RW Pin: ", this->rw_pin_); LOG_PIN(" Enable Pin: ", this->enable_pin_); - for (uint8_t i = 0; i < (this->is_four_bit_mode_() ? 4 : 8); i++) { + for (uint8_t i = 0; i < (this->is_four_bit_mode() ? 4 : 8); i++) { ESP_LOGCONFIG(TAG, " Data Pin %u" LOG_PIN_PATTERN, i, LOG_PIN_ARGS(this->data_pins_[i])); } LOG_UPDATE_INTERVAL(this); } -void GPIOLCDDisplay::set_data_pins(const GPIOOutputPin &d0, - const GPIOOutputPin &d1, - const GPIOOutputPin &d2, +void GPIOLCDDisplay::set_data_pins(const GPIOOutputPin &d0, const GPIOOutputPin &d1, const GPIOOutputPin &d2, const GPIOOutputPin &d3) { this->data_pins_[0] = d0.copy(); this->data_pins_[1] = d1.copy(); this->data_pins_[2] = d2.copy(); this->data_pins_[3] = d3.copy(); } -void GPIOLCDDisplay::set_data_pins(const GPIOOutputPin &d0, - const GPIOOutputPin &d1, - const GPIOOutputPin &d2, - const GPIOOutputPin &d3, - const GPIOOutputPin &d4, - const GPIOOutputPin &d5, - const GPIOOutputPin &d6, - const GPIOOutputPin &d7) { +void GPIOLCDDisplay::set_data_pins(const GPIOOutputPin &d0, const GPIOOutputPin &d1, const GPIOOutputPin &d2, + const GPIOOutputPin &d3, const GPIOOutputPin &d4, const GPIOOutputPin &d5, + const GPIOOutputPin &d6, const GPIOOutputPin &d7) { this->data_pins_[0] = d0.copy(); this->data_pins_[1] = d1.copy(); this->data_pins_[2] = d2.copy(); @@ -234,40 +214,31 @@ void GPIOLCDDisplay::set_data_pins(const GPIOOutputPin &d0, this->data_pins_[6] = d6.copy(); this->data_pins_[7] = d7.copy(); } -void GPIOLCDDisplay::set_enable_pin(const GPIOOutputPin &enable) { - this->enable_pin_ = enable.copy(); -} -void GPIOLCDDisplay::set_rs_pin(const GPIOOutputPin &rs) { - this->rs_pin_ = rs.copy(); -} -void GPIOLCDDisplay::set_rw_pin(const GPIOOutputPin &rw) { - this->rw_pin_ = rw.copy(); -} -bool GPIOLCDDisplay::is_four_bit_mode_() { - return this->data_pins_[4] == nullptr; -} +void GPIOLCDDisplay::set_enable_pin(const GPIOOutputPin &enable) { this->enable_pin_ = enable.copy(); } +void GPIOLCDDisplay::set_rs_pin(const GPIOOutputPin &rs) { this->rs_pin_ = rs.copy(); } +void GPIOLCDDisplay::set_rw_pin(const GPIOOutputPin &rw) { this->rw_pin_ = rw.copy(); } +bool GPIOLCDDisplay::is_four_bit_mode() { return this->data_pins_[4] == nullptr; } void GPIOLCDDisplay::write_n_bits(uint8_t value, uint8_t n) { for (uint8_t i = 0; i < n; i++) this->data_pins_[i]->digital_write(value & (1 << i)); this->enable_pin_->digital_write(true); - delayMicroseconds(1); // >450ns + delayMicroseconds(1); // >450ns this->enable_pin_->digital_write(false); - delayMicroseconds(40); // >37us + delayMicroseconds(40); // >37us } void GPIOLCDDisplay::send(uint8_t value, bool rs) { this->rs_pin_->digital_write(rs); - if (this->is_four_bit_mode_()) { + if (this->is_four_bit_mode()) { this->write_n_bits(value >> 4, 4); this->write_n_bits(value, 4); } else { this->write_n_bits(value, 8); } } -GPIOLCDDisplay::GPIOLCDDisplay(uint8_t columns, uint8_t rows, uint32_t update_interval) : LCDDisplay(columns, - rows, - update_interval) {} +GPIOLCDDisplay::GPIOLCDDisplay(uint8_t columns, uint8_t rows, uint32_t update_interval) + : LCDDisplay(columns, rows, update_interval) {} #ifdef USE_LCD_DISPLAY_PCF8574 void PCF8574LCDDisplay::setup() { @@ -288,35 +259,31 @@ void PCF8574LCDDisplay::dump_config() { ESP_LOGE(TAG, "Communication with LCD Display failed!"); } } -bool PCF8574LCDDisplay::is_four_bit_mode_() { - return true; -} +bool PCF8574LCDDisplay::is_four_bit_mode() { return true; } void PCF8574LCDDisplay::write_n_bits(uint8_t value, uint8_t n) { if (n == 4) { // Ugly fix: in the super setup() with n == 4 value needs to be shifted left value <<= 4; } - uint8_t data = value | 0x08; // Enable backlight + uint8_t data = value | 0x08; // Enable backlight this->write_bytes(data, nullptr, 0); // Pulse ENABLE this->write_bytes(data | 0x04, nullptr, 0); - delayMicroseconds(1); // >450ns + delayMicroseconds(1); // >450ns this->write_bytes(data, nullptr, 0); - delayMicroseconds(100); // >37us + delayMicroseconds(100); // >37us } void PCF8574LCDDisplay::send(uint8_t value, bool rs) { this->write_n_bits((value & 0xF0) | rs, 0); this->write_n_bits(((value << 4) & 0xF0) | rs, 0); } PCF8574LCDDisplay::PCF8574LCDDisplay(I2CComponent *parent, uint8_t columns, uint8_t rows, uint8_t address, - uint32_t update_interval) : LCDDisplay(columns, rows, update_interval), - I2CDevice(parent, address) { - -} -#endif //USE_LCD_DISPLAY_PCF8574 + uint32_t update_interval) + : LCDDisplay(columns, rows, update_interval), I2CDevice(parent, address) {} +#endif // USE_LCD_DISPLAY_PCF8574 -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_LCD_DISPLAY +#endif // USE_LCD_DISPLAY diff --git a/src/esphome/display/lcd_display.h b/src/esphome/display/lcd_display.h index 19d46412..9788fab5 100644 --- a/src/esphome/display/lcd_display.h +++ b/src/esphome/display/lcd_display.h @@ -38,23 +38,24 @@ class LCDDisplay : public PollingComponent { /// Print the given string at column=0 and row=0. void print(const std::string &str); /// Evaluate the printf-format and print the text at the specified column and row. - void printf(uint8_t column, uint8_t row, const char *format, ...) __attribute__ ((format (printf, 4, 5))); + void printf(uint8_t column, uint8_t row, const char *format, ...) __attribute__((format(printf, 4, 5))); /// Evaluate the printf-format and print the text at column=0 and row=0. - void printf(const char *format, ...) __attribute__ ((format (printf, 2, 3))); + void printf(const char *format, ...) __attribute__((format(printf, 2, 3))); #ifdef USE_TIME /// Evaluate the strftime-format and print the text at the specified column and row. - void strftime(uint8_t column, uint8_t row, const char *format, time::ESPTime time) __attribute__ ((format (strftime, 4, 0))); + void strftime(uint8_t column, uint8_t row, const char *format, time::ESPTime time) + __attribute__((format(strftime, 4, 0))); /// Evaluate the strftime-format and print the text at column=0 and row=0. - void strftime(const char *format, time::ESPTime time) __attribute__ ((format (strftime, 2, 0))); + void strftime(const char *format, time::ESPTime time) __attribute__((format(strftime, 2, 0))); #endif protected: - virtual bool is_four_bit_mode_() = 0; + virtual bool is_four_bit_mode() = 0; virtual void write_n_bits(uint8_t value, uint8_t n) = 0; virtual void send(uint8_t value, bool rs) = 0; - void command(uint8_t value); + void command_(uint8_t value); uint8_t columns_; uint8_t rows_; @@ -66,21 +67,18 @@ class GPIOLCDDisplay : public LCDDisplay { public: GPIOLCDDisplay(uint8_t columns, uint8_t rows, uint32_t update_interval = 1000); void setup() override; - void set_data_pins(const GPIOOutputPin &d0, const GPIOOutputPin &d1, const GPIOOutputPin &d2, const GPIOOutputPin &d3); - void set_data_pins(const GPIOOutputPin &d0, - const GPIOOutputPin &d1, - const GPIOOutputPin &d2, - const GPIOOutputPin &d3, - const GPIOOutputPin &d4, - const GPIOOutputPin &d5, - const GPIOOutputPin &d6, + void set_data_pins(const GPIOOutputPin &d0, const GPIOOutputPin &d1, const GPIOOutputPin &d2, + const GPIOOutputPin &d3); + void set_data_pins(const GPIOOutputPin &d0, const GPIOOutputPin &d1, const GPIOOutputPin &d2, const GPIOOutputPin &d3, + const GPIOOutputPin &d4, const GPIOOutputPin &d5, const GPIOOutputPin &d6, const GPIOOutputPin &d7); void set_enable_pin(const GPIOOutputPin &enable); void set_rs_pin(const GPIOOutputPin &rs); void set_rw_pin(const GPIOOutputPin &rw); void dump_config() override; + protected: - bool is_four_bit_mode_() override; + bool is_four_bit_mode() override; void write_n_bits(uint8_t value, uint8_t n) override; void send(uint8_t value, bool rs) override; GPIOPin *rs_pin_{nullptr}; @@ -92,20 +90,22 @@ class GPIOLCDDisplay : public LCDDisplay { #ifdef USE_LCD_DISPLAY_PCF8574 class PCF8574LCDDisplay : public LCDDisplay, public I2CDevice { public: - PCF8574LCDDisplay(I2CComponent *parent, uint8_t columns, uint8_t rows, uint8_t address = 0x3F, uint32_t update_interval = 1000); + PCF8574LCDDisplay(I2CComponent *parent, uint8_t columns, uint8_t rows, uint8_t address = 0x3F, + uint32_t update_interval = 1000); void setup() override; void dump_config() override; + protected: - bool is_four_bit_mode_() override; + bool is_four_bit_mode() override; void write_n_bits(uint8_t value, uint8_t n) override; void send(uint8_t value, bool rs) override; }; #endif -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_LCD_DISPLAY +#endif // USE_LCD_DISPLAY -#endif //ESPHOME_LCD_DISPLAY_H +#endif // ESPHOME_LCD_DISPLAY_H diff --git a/src/esphome/display/max7219.cpp b/src/esphome/display/max7219.cpp index 336af086..1e9d56f1 100644 --- a/src/esphome/display/max7219.cpp +++ b/src/esphome/display/max7219.cpp @@ -18,108 +18,106 @@ static const uint8_t MAX7219_REGISTER_SHUTDOWN = 0x0C; static const uint8_t MAX7219_UNKNOWN_CHAR = 0b11111111; const uint8_t MAX7219_ASCII_TO_RAW[94] PROGMEM = { - 0b00000000, // ' ', ord 0x20 - 0b10110000, // '!', ord 0x21 - 0b00100010, // '"', ord 0x22 - MAX7219_UNKNOWN_CHAR, // '#', ord 0x23 - MAX7219_UNKNOWN_CHAR, // '$', ord 0x24 - 0b01001001, // '%', ord 0x25 - MAX7219_UNKNOWN_CHAR, // '&', ord 0x26 - 0b00000010, // ''', ord 0x27 - 0b01001110, // '(', ord 0x28 - 0b01111000, // ')', ord 0x29 - 0b01000000, // '*', ord 0x2A - MAX7219_UNKNOWN_CHAR, // '+', ord 0x2B - 0b00010000, // ',', ord 0x2C - 0b00000001, // '-', ord 0x2D - 0b10000000, // '.', ord 0x2E - MAX7219_UNKNOWN_CHAR, // '/', ord 0x2F - 0b01111110, // '0', ord 0x30 - 0b00110000, // '1', ord 0x31 - 0b01101101, // '2', ord 0x32 - 0b01111001, // '3', ord 0x33 - 0b00110011, // '4', ord 0x34 - 0b01011011, // '5', ord 0x35 - 0b01011111, // '6', ord 0x36 - 0b01110000, // '7', ord 0x37 - 0b01111111, // '8', ord 0x38 - 0b01110011, // '9', ord 0x39 - 0b01001000, // ':', ord 0x3A - 0b01011000, // ';', ord 0x3B - MAX7219_UNKNOWN_CHAR, // '<', ord 0x3C - MAX7219_UNKNOWN_CHAR, // '=', ord 0x3D - MAX7219_UNKNOWN_CHAR, // '>', ord 0x3E - 0b01100101, // '?', ord 0x3F - 0b01101111, // '@', ord 0x40 - 0b01110111, // 'A', ord 0x41 - 0b00011111, // 'B', ord 0x42 - 0b01001110, // 'C', ord 0x43 - 0b00111101, // 'D', ord 0x44 - 0b01001111, // 'E', ord 0x45 - 0b01000111, // 'F', ord 0x46 - 0b01011110, // 'G', ord 0x47 - 0b00110111, // 'H', ord 0x48 - 0b00110000, // 'I', ord 0x49 - 0b00111100, // 'J', ord 0x4A - MAX7219_UNKNOWN_CHAR, // 'K', ord 0x4B - 0b00001110, // 'L', ord 0x4C - MAX7219_UNKNOWN_CHAR, // 'M', ord 0x4D - 0b00010101, // 'N', ord 0x4E - 0b01111110, // 'O', ord 0x4F - 0b01100111, // 'P', ord 0x50 - 0b11111110, // 'Q', ord 0x51 - 0b00000101, // 'R', ord 0x52 - 0b01011011, // 'S', ord 0x53 - 0b00000111, // 'T', ord 0x54 - 0b00111110, // 'U', ord 0x55 - 0b00111110, // 'V', ord 0x56 - 0b00111111, // 'W', ord 0x57 - MAX7219_UNKNOWN_CHAR, // 'X', ord 0x58 - 0b00100111, // 'Y', ord 0x59 - 0b01101101, // 'Z', ord 0x5A - 0b01001110, // '[', ord 0x5B - MAX7219_UNKNOWN_CHAR, // '\', ord 0x5C - 0b01111000, // ']', ord 0x5D - MAX7219_UNKNOWN_CHAR, // '^', ord 0x5E - 0b00001000, // '_', ord 0x5F - 0b00100000, // '`', ord 0x60 - 0b01110111, // 'a', ord 0x61 - 0b00011111, // 'b', ord 0x62 - 0b00001101, // 'c', ord 0x63 - 0b00111101, // 'd', ord 0x64 - 0b01001111, // 'e', ord 0x65 - 0b01000111, // 'f', ord 0x66 - 0b01011110, // 'g', ord 0x67 - 0b00010111, // 'h', ord 0x68 - 0b00010000, // 'i', ord 0x69 - 0b00111100, // 'j', ord 0x6A - MAX7219_UNKNOWN_CHAR, // 'k', ord 0x6B - 0b00001110, // 'l', ord 0x6C - MAX7219_UNKNOWN_CHAR, // 'm', ord 0x6D - 0b00010101, // 'n', ord 0x6E - 0b00011101, // 'o', ord 0x6F - 0b01100111, // 'p', ord 0x70 - MAX7219_UNKNOWN_CHAR, // 'q', ord 0x71 - 0b00000101, // 'r', ord 0x72 - 0b01011011, // 's', ord 0x73 - 0b00000111, // 't', ord 0x74 - 0b00011100, // 'u', ord 0x75 - 0b00011100, // 'v', ord 0x76 - MAX7219_UNKNOWN_CHAR, // 'w', ord 0x77 - MAX7219_UNKNOWN_CHAR, // 'x', ord 0x78 - 0b00100111, // 'y', ord 0x79 - MAX7219_UNKNOWN_CHAR, // 'z', ord 0x7A - 0b00110001, // '{', ord 0x7B - 0b00000110, // '|', ord 0x7C - 0b00000111, // '}', ord 0x7D + 0b00000000, // ' ', ord 0x20 + 0b10110000, // '!', ord 0x21 + 0b00100010, // '"', ord 0x22 + MAX7219_UNKNOWN_CHAR, // '#', ord 0x23 + MAX7219_UNKNOWN_CHAR, // '$', ord 0x24 + 0b01001001, // '%', ord 0x25 + MAX7219_UNKNOWN_CHAR, // '&', ord 0x26 + 0b00000010, // ''', ord 0x27 + 0b01001110, // '(', ord 0x28 + 0b01111000, // ')', ord 0x29 + 0b01000000, // '*', ord 0x2A + MAX7219_UNKNOWN_CHAR, // '+', ord 0x2B + 0b00010000, // ',', ord 0x2C + 0b00000001, // '-', ord 0x2D + 0b10000000, // '.', ord 0x2E + MAX7219_UNKNOWN_CHAR, // '/', ord 0x2F + 0b01111110, // '0', ord 0x30 + 0b00110000, // '1', ord 0x31 + 0b01101101, // '2', ord 0x32 + 0b01111001, // '3', ord 0x33 + 0b00110011, // '4', ord 0x34 + 0b01011011, // '5', ord 0x35 + 0b01011111, // '6', ord 0x36 + 0b01110000, // '7', ord 0x37 + 0b01111111, // '8', ord 0x38 + 0b01110011, // '9', ord 0x39 + 0b01001000, // ':', ord 0x3A + 0b01011000, // ';', ord 0x3B + MAX7219_UNKNOWN_CHAR, // '<', ord 0x3C + MAX7219_UNKNOWN_CHAR, // '=', ord 0x3D + MAX7219_UNKNOWN_CHAR, // '>', ord 0x3E + 0b01100101, // '?', ord 0x3F + 0b01101111, // '@', ord 0x40 + 0b01110111, // 'A', ord 0x41 + 0b00011111, // 'B', ord 0x42 + 0b01001110, // 'C', ord 0x43 + 0b00111101, // 'D', ord 0x44 + 0b01001111, // 'E', ord 0x45 + 0b01000111, // 'F', ord 0x46 + 0b01011110, // 'G', ord 0x47 + 0b00110111, // 'H', ord 0x48 + 0b00110000, // 'I', ord 0x49 + 0b00111100, // 'J', ord 0x4A + MAX7219_UNKNOWN_CHAR, // 'K', ord 0x4B + 0b00001110, // 'L', ord 0x4C + MAX7219_UNKNOWN_CHAR, // 'M', ord 0x4D + 0b00010101, // 'N', ord 0x4E + 0b01111110, // 'O', ord 0x4F + 0b01100111, // 'P', ord 0x50 + 0b11111110, // 'Q', ord 0x51 + 0b00000101, // 'R', ord 0x52 + 0b01011011, // 'S', ord 0x53 + 0b00000111, // 'T', ord 0x54 + 0b00111110, // 'U', ord 0x55 + 0b00111110, // 'V', ord 0x56 + 0b00111111, // 'W', ord 0x57 + MAX7219_UNKNOWN_CHAR, // 'X', ord 0x58 + 0b00100111, // 'Y', ord 0x59 + 0b01101101, // 'Z', ord 0x5A + 0b01001110, // '[', ord 0x5B + MAX7219_UNKNOWN_CHAR, // '\', ord 0x5C + 0b01111000, // ']', ord 0x5D + MAX7219_UNKNOWN_CHAR, // '^', ord 0x5E + 0b00001000, // '_', ord 0x5F + 0b00100000, // '`', ord 0x60 + 0b01110111, // 'a', ord 0x61 + 0b00011111, // 'b', ord 0x62 + 0b00001101, // 'c', ord 0x63 + 0b00111101, // 'd', ord 0x64 + 0b01001111, // 'e', ord 0x65 + 0b01000111, // 'f', ord 0x66 + 0b01011110, // 'g', ord 0x67 + 0b00010111, // 'h', ord 0x68 + 0b00010000, // 'i', ord 0x69 + 0b00111100, // 'j', ord 0x6A + MAX7219_UNKNOWN_CHAR, // 'k', ord 0x6B + 0b00001110, // 'l', ord 0x6C + MAX7219_UNKNOWN_CHAR, // 'm', ord 0x6D + 0b00010101, // 'n', ord 0x6E + 0b00011101, // 'o', ord 0x6F + 0b01100111, // 'p', ord 0x70 + MAX7219_UNKNOWN_CHAR, // 'q', ord 0x71 + 0b00000101, // 'r', ord 0x72 + 0b01011011, // 's', ord 0x73 + 0b00000111, // 't', ord 0x74 + 0b00011100, // 'u', ord 0x75 + 0b00011100, // 'v', ord 0x76 + MAX7219_UNKNOWN_CHAR, // 'w', ord 0x77 + MAX7219_UNKNOWN_CHAR, // 'x', ord 0x78 + 0b00100111, // 'y', ord 0x79 + MAX7219_UNKNOWN_CHAR, // 'z', ord 0x7A + 0b00110001, // '{', ord 0x7B + 0b00000110, // '|', ord 0x7C + 0b00000111, // '}', ord 0x7D }; MAX7219Component::MAX7219Component(SPIComponent *parent, GPIOPin *cs, uint32_t update_interval) : PollingComponent(update_interval), SPIDevice(parent, cs) {} -float MAX7219Component::get_setup_priority() const { - return setup_priority::POST_HARDWARE; -} +float MAX7219Component::get_setup_priority() const { return setup_priority::POST_HARDWARE; } void MAX7219Component::setup() { ESP_LOGCONFIG(TAG, "Setting up MAX7219..."); this->spi_setup(); @@ -153,19 +151,17 @@ void MAX7219Component::display() { this->disable(); } } -void MAX7219Component::send_byte_(uint8_t register_, uint8_t data) { - this->write_byte(register_); +void MAX7219Component::send_byte_(uint8_t a_register, uint8_t data) { + this->write_byte(a_register); this->write_byte(data); } -void MAX7219Component::send_to_all_(uint8_t register_, uint8_t data) { +void MAX7219Component::send_to_all_(uint8_t a_register, uint8_t data) { this->enable(); for (uint8_t i = 0; i < this->num_chips_; i++) - this->send_byte_(register_, data); + this->send_byte_(a_register, data); this->disable(); } -bool MAX7219Component::msb_first() { - return true; -} +bool MAX7219Component::is_device_msb_first() { return true; } void MAX7219Component::update() { for (uint8_t i = 0; i < this->num_chips_ * 8; i++) this->buffer_[i] = 0; @@ -181,8 +177,7 @@ uint8_t MAX7219Component::print(uint8_t start_pos, const char *str) { data = pgm_read_byte(&MAX7219_ASCII_TO_RAW[*str - ' ']); if (data == MAX7219_UNKNOWN_CHAR) { - ESP_LOGW(TAG, "Encountered character '%c' with no MAX7219 representation while translating string!", - *str); + ESP_LOGW(TAG, "Encountered character '%c' with no MAX7219 representation while translating string!", *str); } if (*str == '.') { if (pos != start_pos) @@ -199,9 +194,7 @@ uint8_t MAX7219Component::print(uint8_t start_pos, const char *str) { } return pos - start_pos; } -uint8_t MAX7219Component::print(const char *str) { - return this->print(0, str); -} +uint8_t MAX7219Component::print(const char *str) { return this->print(0, str); } uint8_t MAX7219Component::printf(uint8_t pos, const char *format, ...) { va_list arg; va_start(arg, format); @@ -222,15 +215,9 @@ uint8_t MAX7219Component::printf(const char *format, ...) { return this->print(buffer); return 0; } -void MAX7219Component::set_writer(max7219_writer_t &&writer) { - this->writer_ = std::move(writer); -} -void MAX7219Component::set_intensity(uint8_t intensity) { - this->intensity_ = intensity; -} -void MAX7219Component::set_num_chips(uint8_t num_chips) { - this->num_chips_ = num_chips; -} +void MAX7219Component::set_writer(max7219_writer_t &&writer) { this->writer_ = writer; } +void MAX7219Component::set_intensity(uint8_t intensity) { this->intensity_ = intensity; } +void MAX7219Component::set_num_chips(uint8_t num_chips) { this->num_chips_ = num_chips; } #ifdef USE_TIME uint8_t MAX7219Component::strftime(uint8_t pos, const char *format, time::ESPTime time) { @@ -240,13 +227,11 @@ uint8_t MAX7219Component::strftime(uint8_t pos, const char *format, time::ESPTim return this->print(pos, buffer); return 0; } -uint8_t MAX7219Component::strftime(const char *format, time::ESPTime time) { - return this->strftime(0, format, time); -} +uint8_t MAX7219Component::strftime(const char *format, time::ESPTime time) { return this->strftime(0, format, time); } #endif -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_MAX7219 +#endif // USE_MAX7219 diff --git a/src/esphome/display/max7219.h b/src/esphome/display/max7219.h index ccf719d6..2233dfbd 100644 --- a/src/esphome/display/max7219.h +++ b/src/esphome/display/max7219.h @@ -39,9 +39,9 @@ class MAX7219Component : public PollingComponent, public SPIDevice { void set_num_chips(uint8_t num_chips); /// Evaluate the printf-format and print the result at the given position. - uint8_t printf(uint8_t pos, const char *format, ...) __attribute__ ((format (printf, 3, 4))); + uint8_t printf(uint8_t pos, const char *format, ...) __attribute__((format(printf, 3, 4))); /// Evaluate the printf-format and print the result at position 0. - uint8_t printf(const char *format, ...) __attribute__ ((format (printf, 2, 3))); + uint8_t printf(const char *format, ...) __attribute__((format(printf, 2, 3))); /// Print `str` at the given position. uint8_t print(uint8_t pos, const char *str); @@ -50,27 +50,27 @@ class MAX7219Component : public PollingComponent, public SPIDevice { #ifdef USE_TIME /// Evaluate the strftime-format and print the result at the given position. - uint8_t strftime(uint8_t pos, const char *format, time::ESPTime time) __attribute__ ((format (strftime, 3, 0))); + uint8_t strftime(uint8_t pos, const char *format, time::ESPTime time) __attribute__((format(strftime, 3, 0))); /// Evaluate the strftime-format and print the result at position 0. - uint8_t strftime(const char *format, time::ESPTime time) __attribute__ ((format (strftime, 2, 0))); + uint8_t strftime(const char *format, time::ESPTime time) __attribute__((format(strftime, 2, 0))); #endif protected: - void send_byte_(uint8_t register_, uint8_t data); - void send_to_all_(uint8_t register_, uint8_t data); - bool msb_first() override; + void send_byte_(uint8_t a_register, uint8_t data); + void send_to_all_(uint8_t a_register, uint8_t data); + bool is_device_msb_first() override; - uint8_t intensity_{15}; /// Intensity of the display from 0 to 15 (most) + uint8_t intensity_{15}; /// Intensity of the display from 0 to 15 (most) uint8_t num_chips_{1}; uint8_t *buffer_; optional writer_{}; }; -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_MAX7219 +#endif // USE_MAX7219 -#endif //ESPHOME_DISPLAY_MAX7219_H +#endif // ESPHOME_DISPLAY_MAX7219_H diff --git a/src/esphome/display/nextion.cpp b/src/esphome/display/nextion.cpp index ed039e43..01aa0fe7 100644 --- a/src/esphome/display/nextion.cpp +++ b/src/esphome/display/nextion.cpp @@ -12,20 +12,18 @@ namespace display { static const char *TAG = "display.nextion"; void Nextion::setup() { - this->send_command_(""); + this->send_command_no_ack(""); this->ack_(); this->goto_page("0"); - this->send_command_printf_("bkcmd=3"); -} -float Nextion::get_setup_priority() const { - return setup_priority::POST_HARDWARE; + this->send_command_printf("bkcmd=3"); } +float Nextion::get_setup_priority() const { return setup_priority::POST_HARDWARE; } void Nextion::update() { if (this->writer_.has_value()) { (*this->writer_)(*this); } } -void Nextion::send_command_(const char *command) { +void Nextion::send_command_no_ack(const char *command) { // Flush RX... this->loop(); @@ -35,7 +33,9 @@ void Nextion::send_command_(const char *command) { } bool Nextion::ack_() { - uint8_t bytes[4] = {0x00, }; + uint8_t bytes[4] = { + 0x00, + }; if (!this->read_array(bytes, 4)) { ESP_LOGW(TAG, "Nextion returned no ACK data!"); return false; @@ -47,60 +47,58 @@ bool Nextion::ack_() { } switch (bytes[0]) { - case 0x01: // successful execution of instruction + case 0x01: // successful execution of instruction return true; - case 0x00: // invalid instruction - case 0x02: // component ID invalid - case 0x03: // page ID invalid - case 0x04: // picture ID invalid - case 0x05: // font ID invalid - case 0x11: // baud rate setting invalid - case 0x12: // curve control ID number or channel number is invalid - case 0x1A: // variable name invalid - case 0x1B: // variable operation invalid - case 0x1C: // failed to assign - case 0x1D: // operate EEPROM failed - case 0x1E: // parameter quantity invalid - case 0x1F: // IO operation failed - case 0x20: // undefined escape characters - case 0x23: // too long variable name + case 0x00: // invalid instruction + case 0x02: // component ID invalid + case 0x03: // page ID invalid + case 0x04: // picture ID invalid + case 0x05: // font ID invalid + case 0x11: // baud rate setting invalid + case 0x12: // curve control ID number or channel number is invalid + case 0x1A: // variable name invalid + case 0x1B: // variable operation invalid + case 0x1C: // failed to assign + case 0x1D: // operate EEPROM failed + case 0x1E: // parameter quantity invalid + case 0x1F: // IO operation failed + case 0x20: // undefined escape characters + case 0x23: // too long variable name default: ESP_LOGW(TAG, "Nextion returned NACK with code 0x%02X", bytes[0]); return false; } } void Nextion::set_component_text(const char *component, const char *text) { - this->send_command_printf_("%s.txt=\"%s\"", component, text); + this->send_command_printf("%s.txt=\"%s\"", component, text); } void Nextion::set_component_value(const char *component, int value) { - this->send_command_printf_("%s.val=%d", component, value); + this->send_command_printf("%s.val=%d", component, value); } void Nextion::set_component_picture(const char *component, const char *picture) { - this->send_command_printf_("%s.pic=\"%s\"", component, picture); + this->send_command_printf("%s.pic=\"%s\"", component, picture); } void Nextion::set_component_background_color(const char *component, const char *color) { - this->send_command_printf_("%s.bco=\"%s\"", component, color); + this->send_command_printf("%s.bco=\"%s\"", component, color); } void Nextion::set_component_pressed_background_color(const char *component, const char *color) { - this->send_command_printf_("%s.bco2=\"%s\"", component, color); + this->send_command_printf("%s.bco2=\"%s\"", component, color); } void Nextion::set_component_font_color(const char *component, const char *color) { - this->send_command_printf_("%s.pco=\"%s\"", component, color); + this->send_command_printf("%s.pco=\"%s\"", component, color); } void Nextion::set_component_pressed_font_color(const char *component, const char *color) { - this->send_command_printf_("%s.pco2=\"%s\"", component, color); + this->send_command_printf("%s.pco2=\"%s\"", component, color); } void Nextion::set_component_coordinates(const char *component, int x, int y) { - this->send_command_printf_("%s.xcen=%d", component, x); - this->send_command_printf_("%s.ycen=%d", component, y); + this->send_command_printf("%s.xcen=%d", component, x); + this->send_command_printf("%s.ycen=%d", component, y); } void Nextion::set_component_font(const char *component, uint8_t font_id) { - this->send_command_printf_("%s.font=%d", component, font_id); -} -void Nextion::goto_page(const char *page) { - this->send_command_printf_("page %s", page); + this->send_command_printf("%s.font=%d", component, font_id); } -bool Nextion::send_command_printf_(const char *format, ...) { +void Nextion::goto_page(const char *page) { this->send_command_printf("page %s", page); } +bool Nextion::send_command_printf(const char *format, ...) { char buffer[256]; va_list arg; va_start(arg, format); @@ -110,7 +108,7 @@ bool Nextion::send_command_printf_(const char *format, ...) { ESP_LOGW(TAG, "Building command for format '%s' failed!", format); return false; } - this->send_command_(buffer); + this->send_command_no_ack(buffer); if (!this->ack_()) { ESP_LOGW(TAG, "Sending command '%s' failed because no ACK was received", buffer); return false; @@ -118,38 +116,30 @@ bool Nextion::send_command_printf_(const char *format, ...) { return true; } -void Nextion::hide_component(const char *component) { - this->send_command_printf_("vis %s,0", component); -} -void Nextion::show_component(const char *component) { - this->send_command_printf_("vis %s,1", component); -} -void Nextion::enable_component_touch(const char *component) { - this->send_command_printf_("tsw %s,1", component); -} -void Nextion::disable_component_touch(const char *component) { - this->send_command_printf_("tsw %s,0", component); -} +void Nextion::hide_component(const char *component) { this->send_command_printf("vis %s,0", component); } +void Nextion::show_component(const char *component) { this->send_command_printf("vis %s,1", component); } +void Nextion::enable_component_touch(const char *component) { this->send_command_printf("tsw %s,1", component); } +void Nextion::disable_component_touch(const char *component) { this->send_command_printf("tsw %s,0", component); } void Nextion::add_waveform_data(int component_id, uint8_t channel_number, uint8_t value) { - this->send_command_printf_("add %d,%u,%u", component_id, channel_number, value); + this->send_command_printf("add %d,%u,%u", component_id, channel_number, value); } void Nextion::display_picture(int picture_id, int x_start, int y_start) { - this->send_command_printf_("pic %d,%d,%d", x_start, y_start, picture_id); + this->send_command_printf("pic %d,%d,%d", x_start, y_start, picture_id); } void Nextion::fill_area(int x1, int y1, int width, int height, const char *color) { - this->send_command_printf_("fill %d,%d,%d,%d,%s", x1, y1, width, height, color); + this->send_command_printf("fill %d,%d,%d,%d,%s", x1, y1, width, height, color); } void Nextion::line(int x1, int y1, int x2, int y2, const char *color) { - this->send_command_printf_("line %d,%d,%d,%d,%s", x1, y1, x2, y2, color); + this->send_command_printf("line %d,%d,%d,%d,%s", x1, y1, x2, y2, color); } void Nextion::rectangle(int x1, int y1, int width, int height, const char *color) { - this->send_command_printf_("draw %d,%d,%d,%d,%s", x1, y1, x1 + width, y1 + height, color); + this->send_command_printf("draw %d,%d,%d,%d,%s", x1, y1, x1 + width, y1 + height, color); } void Nextion::circle(int center_x, int center_y, int radius, const char *color) { - this->send_command_printf_("cir %d,%d,%d,%s", center_x, center_y, radius, color); + this->send_command_printf("cir %d,%d,%d,%s", center_x, center_y, radius, color); } void Nextion::filled_circle(int center_x, int center_y, int radius, const char *color) { - this->send_command_printf_("cirs %d,%d,%d,%s", center_x, center_y, radius, color); + this->send_command_printf("cirs %d,%d,%d,%s", center_x, center_y, radius, color); } void Nextion::loop() { while (this->available() >= 4) { @@ -188,45 +178,46 @@ void Nextion::loop() { continue; } - data_length -= 3; // remove filler bytes + data_length -= 3; // remove filler bytes bool invalid_data_length = false; switch (event) { - case 0x65: { // touch event return data + case 0x65: { // touch event return data if (data_length != 3) { invalid_data_length = true; break; } uint8_t page_id = data[0]; uint8_t component_id = data[1]; - uint8_t touch_event = data[2]; // 0 -> release, 1 -> press - ESP_LOGD(TAG, "Got touch page=%u component=%u type=%s", page_id, component_id, touch_event ? "PRESS" : "RELEASE"); + uint8_t touch_event = data[2]; // 0 -> release, 1 -> press + ESP_LOGD(TAG, "Got touch page=%u component=%u type=%s", page_id, component_id, + touch_event ? "PRESS" : "RELEASE"); for (auto *touch : this->touch_) { touch->process(page_id, component_id, touch_event); } break; } case 0x67: - case 0x68: { // touch coordinate data + case 0x68: { // touch coordinate data if (data_length != 5) { invalid_data_length = true; break; } uint16_t x = (uint16_t(data[0]) << 8) | data[1]; uint16_t y = (uint16_t(data[2]) << 8) | data[3]; - uint8_t touch_event = data[4]; // 0 -> release, 1 -> press + uint8_t touch_event = data[4]; // 0 -> release, 1 -> press ESP_LOGD(TAG, "Got touch at x=%u y=%u type=%s", x, y, touch_event ? "PRESS" : "RELEASE"); break; } - case 0x66: // sendme page id - case 0x70: // string variable data return - case 0x71: // numeric variable data return - case 0x86: // device automatically enters into sleep mode - case 0x87: // device automatically wakes up - case 0x88: // system successful start up - case 0x89: // start SD card upgrade - case 0xFD: // data transparent transmit finished - case 0xFE: // data transparent transmit ready + case 0x66: // sendme page id + case 0x70: // string variable data return + case 0x71: // numeric variable data return + case 0x86: // device automatically enters into sleep mode + case 0x87: // device automatically wakes up + case 0x88: // system successful start up + case 0x89: // start SD card upgrade + case 0xFD: // data transparent transmit finished + case 0xFE: // data transparent transmit ready break; default: ESP_LOGW(TAG, "Received unknown event from nextion: 0x%02X", event); @@ -239,21 +230,17 @@ void Nextion::loop() { } #ifdef USE_TIME void Nextion::set_nextion_rtc_time(time::ESPTime time) { - this->send_command_printf_("rtc0=%u", time.year); - this->send_command_printf_("rtc1=%u", time.month); - this->send_command_printf_("rtc2=%u", time.day_of_month); - this->send_command_printf_("rtc3=%u", time.hour); - this->send_command_printf_("rtc4=%u", time.minute); - this->send_command_printf_("rtc5=%u", time.second); + this->send_command_printf("rtc0=%u", time.year); + this->send_command_printf("rtc1=%u", time.month); + this->send_command_printf("rtc2=%u", time.day_of_month); + this->send_command_printf("rtc3=%u", time.hour); + this->send_command_printf("rtc4=%u", time.minute); + this->send_command_printf("rtc5=%u", time.second); } #endif -void Nextion::set_backlight_brightness(uint8_t brightness) { - this->send_command_printf_("dim=%u", brightness); -} -void Nextion::set_touch_sleep_timeout(uint16_t timeout) { - this->send_command_printf_("thsp=%u", timeout); -} +void Nextion::set_backlight_brightness(uint8_t brightness) { this->send_command_printf("dim=%u", brightness); } +void Nextion::set_touch_sleep_timeout(uint16_t timeout) { this->send_command_printf("thsp=%u", timeout); } NextionTouchComponent *Nextion::make_touch_component(const std::string &name, uint8_t page_id, uint8_t component_id) { auto *ret = new NextionTouchComponent(name, page_id, component_id); @@ -261,12 +248,8 @@ NextionTouchComponent *Nextion::make_touch_component(const std::string &name, ui return ret; } Nextion::Nextion(UARTComponent *parent, uint32_t update_interval) - : PollingComponent(update_interval), UARTDevice(parent) { - -} -void Nextion::set_writer(const nextion_writer_t &writer) { - this->writer_ = writer; -} + : PollingComponent(update_interval), UARTDevice(parent) {} +void Nextion::set_writer(const nextion_writer_t &writer) { this->writer_ = writer; } void Nextion::set_component_text_printf(const char *component, const char *format, ...) { va_list arg; va_start(arg, format); @@ -285,8 +268,8 @@ void NextionTouchComponent::process(uint8_t page_id, uint8_t component_id, bool NextionTouchComponent::NextionTouchComponent(const std::string &name, uint8_t page_id, uint8_t component_id) : BinarySensor(name), page_id_(page_id), component_id_(component_id) {} -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_NEXTION +#endif // USE_NEXTION diff --git a/src/esphome/display/nextion.h b/src/esphome/display/nextion.h index 998b3b61..c9531450 100644 --- a/src/esphome/display/nextion.h +++ b/src/esphome/display/nextion.h @@ -33,7 +33,7 @@ class Nextion : public PollingComponent, public UARTDevice { * @param format The printf-style format string. * @param ... The arguments to the format. */ - void set_component_text_printf(const char *component, const char *format, ...) __attribute__ ((format (printf, 3, 4))); + void set_component_text_printf(const char *component, const char *format, ...) __attribute__((format(printf, 3, 4))); /** * Set the integer value of a component * @param component The component name. @@ -129,7 +129,7 @@ class Nextion : public PollingComponent, public UARTDevice { * @param x1 The x coordinate. * @param y1 The y coordniate. */ - void display_picture(int picture_id, int x1, int y1); + void display_picture(int picture_id, int x_start, int y_start); /** * Fill a rectangle with a color. * @param x1 The starting x coordinate. @@ -196,17 +196,17 @@ class Nextion : public PollingComponent, public UARTDevice { void set_writer(const nextion_writer_t &writer); /** - * Manually send a raw command to the display. + * Manually send a raw command to the display and don't wait for an acknolwedgement packet. * @param command The command to write, for example "vis b0,0". */ - void send_command_(const char *command); + void send_command_no_ack(const char *command); /** * Manually send a raw formatted command to the display. * @param format The printf-style command format, like "vis %s,0" * @param ... The format arguments * @return Whether the send was successful. */ - bool send_command_printf_(const char *format, ...) __attribute__ ((format (printf, 2, 3))); + bool send_command_printf(const char *format, ...) __attribute__((format(printf, 2, 3))); protected: bool ack_(); @@ -218,15 +218,16 @@ class NextionTouchComponent : public binary_sensor::BinarySensor { public: NextionTouchComponent(const std::string &name, uint8_t page_id, uint8_t component_id); void process(uint8_t page_id, uint8_t component_id, bool on); + protected: uint8_t page_id_; uint8_t component_id_; }; -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_NEXTION +#endif // USE_NEXTION -#endif //ESPHOME_DISPLAY_NEXTION_H +#endif // ESPHOME_DISPLAY_NEXTION_H diff --git a/src/esphome/display/ssd1306.cpp b/src/esphome/display/ssd1306.cpp index eb2cdb8f..dff07735 100644 --- a/src/esphome/display/ssd1306.cpp +++ b/src/esphome/display/ssd1306.cpp @@ -38,14 +38,14 @@ void SSD1306::setup() { this->command(SSD1306_COMMAND_DISPLAY_OFF); this->command(SSD1306_COMMAND_SET_DISPLAY_CLOCK_DIV); - this->command(0x80); // suggested ratio + this->command(0x80); // suggested ratio this->command(SSD1306_COMMAND_SET_MULTIPLEX); - this->command(this->get_height_internal_() - 1); + this->command(this->get_height_internal() - 1); this->command(SSD1306_COMMAND_SET_DISPLAY_OFFSET); - this->command(0x00); // no offset - this->command(SSD1306_COMMAND_SET_START_LINE | 0x00); // start at line 0 + this->command(0x00); // no offset + this->command(SSD1306_COMMAND_SET_START_LINE | 0x00); // start at line 0 this->command(SSD1306_COMMAND_CHARGE_PUMP); if (this->external_vcc_) this->command(0x10); @@ -123,11 +123,11 @@ void SSD1306::display() { switch (this->model_) { case SSD1306_MODEL_64_48: this->command(0x20); - this->command(0x20 + this->get_width_internal_() - 1); + this->command(0x20 + this->get_width_internal() - 1); break; default: - this->command(0); // Page start address, 0 - this->command(this->get_width_internal_() - 1); + this->command(0); // Page start address, 0 + this->command(this->get_width_internal() - 1); break; } @@ -135,27 +135,22 @@ void SSD1306::display() { // Page start address, 0 this->command(0); // Page end address: - this->command((this->get_height_internal_() / 8) - 1); + this->command((this->get_height_internal() / 8) - 1); this->write_display_data(); } bool SSD1306::is_sh1106_() const { - return this->model_ == SH1106_MODEL_96_16 || this->model_ == SH1106_MODEL_128_32 || this->model_ == SH1106_MODEL_128_64; + return this->model_ == SH1106_MODEL_96_16 || this->model_ == SH1106_MODEL_128_32 || + this->model_ == SH1106_MODEL_128_64; } void SSD1306::update() { - this->do_update(); + this->do_update_(); this->display(); } -void SSD1306::set_model(SSD1306Model model) { - this->model_ = model; -} -void SSD1306::set_reset_pin(const GPIOOutputPin &reset_pin) { - this->reset_pin_ = reset_pin.copy(); -} -void SSD1306::set_external_vcc(bool external_vcc) { - this->external_vcc_ = external_vcc; -} -int SSD1306::get_height_internal_() { +void SSD1306::set_model(SSD1306Model model) { this->model_ = model; } +void SSD1306::set_reset_pin(const GPIOOutputPin &reset_pin) { this->reset_pin_ = reset_pin.copy(); } +void SSD1306::set_external_vcc(bool external_vcc) { this->external_vcc_ = external_vcc; } +int SSD1306::get_height_internal() { switch (this->model_) { case SSD1306_MODEL_128_32: case SH1106_MODEL_128_32: @@ -169,10 +164,11 @@ int SSD1306::get_height_internal_() { case SSD1306_MODEL_64_48: case SH1106_MODEL_64_48: return 48; - default: return 0; + default: + return 0; } } -int SSD1306::get_width_internal_() { +int SSD1306::get_width_internal() { switch (this->model_) { case SSD1306_MODEL_128_32: case SH1106_MODEL_128_32: @@ -185,19 +181,20 @@ int SSD1306::get_width_internal_() { case SSD1306_MODEL_64_48: case SH1106_MODEL_64_48: return 64; - default: return 0; + default: + return 0; } } size_t SSD1306::get_buffer_length_() { - return size_t(this->get_width_internal_()) * size_t(this->get_height_internal_()) / 8u; + return size_t(this->get_width_internal()) * size_t(this->get_height_internal()) / 8u; } SSD1306::SSD1306(uint32_t update_interval) : PollingComponent(update_interval) {} -void HOT SSD1306::draw_absolute_pixel_internal_(int x, int y, int color) { - if (x >= this->get_width_internal_() || x < 0 || y >= this->get_height_internal_() || y < 0) +void HOT SSD1306::draw_absolute_pixel_internal(int x, int y, int color) { + if (x >= this->get_width_internal() || x < 0 || y >= this->get_height_internal() || y < 0) return; - uint16_t pos = x + (y / 8) * this->get_width_internal_(); + uint16_t pos = x + (y / 8) * this->get_width_internal(); uint8_t subpos = y & 0x07; if (color) { this->buffer_[pos] |= (1 << subpos); @@ -205,9 +202,7 @@ void HOT SSD1306::draw_absolute_pixel_internal_(int x, int y, int color) { this->buffer_[pos] &= ~(1 << subpos); } } -float SSD1306::get_setup_priority() const { - return setup_priority::POST_HARDWARE; -} +float SSD1306::get_setup_priority() const { return setup_priority::POST_HARDWARE; } void SSD1306::fill(int color) { uint8_t fill = color ? 0xFF : 0x00; for (uint32_t i = 0; i < this->get_buffer_length_(); i++) @@ -227,26 +222,33 @@ void SSD1306::init_reset_() { } const char *SSD1306::model_str_() { switch (this->model_) { - case SSD1306_MODEL_128_32: return "SSD1306 128x32"; - case SSD1306_MODEL_128_64: return "SSD1306 128x64"; - case SSD1306_MODEL_96_16: return "SSD1306 96x16"; - case SSD1306_MODEL_64_48: return "SSD1306 64x48"; - case SH1106_MODEL_128_32: return "SH1106 128x32"; - case SH1106_MODEL_128_64: return "SH1106 128x64"; - case SH1106_MODEL_96_16: return "SH1106 96x16"; - case SH1106_MODEL_64_48: return "SH1106 64x48"; - default: return "Unknown"; + case SSD1306_MODEL_128_32: + return "SSD1306 128x32"; + case SSD1306_MODEL_128_64: + return "SSD1306 128x64"; + case SSD1306_MODEL_96_16: + return "SSD1306 96x16"; + case SSD1306_MODEL_64_48: + return "SSD1306 64x48"; + case SH1106_MODEL_128_32: + return "SH1106 128x32"; + case SH1106_MODEL_128_64: + return "SH1106 128x64"; + case SH1106_MODEL_96_16: + return "SH1106 96x16"; + case SH1106_MODEL_64_48: + return "SH1106 64x48"; + default: + return "Unknown"; } } #ifdef USE_SPI -bool SPISSD1306::msb_first() { - return true; -} +bool SPISSD1306::is_device_msb_first() { return true; } void SPISSD1306::setup() { ESP_LOGCONFIG(TAG, "Setting up SPI SSD1306..."); this->spi_setup(); - this->dc_pin_->setup(); // OUTPUT + this->dc_pin_->setup(); // OUTPUT this->init_reset_(); SSD1306::setup(); @@ -268,14 +270,14 @@ void SPISSD1306::command(uint8_t value) { } void HOT SPISSD1306::write_display_data() { if (this->is_sh1106_()) { - for (uint8_t y = 0; y < this->get_height_internal_() / 8; y++) { + for (uint8_t y = 0; y < this->get_height_internal() / 8; y++) { this->command(0xB0 + y); this->command(0x02); this->command(0x10); this->dc_pin_->digital_write(true); - for (uint8_t x = 0; x < this->get_width_internal_(); x++) { + for (uint8_t x = 0; x < this->get_width_internal(); x++) { this->enable(); - this->write_byte(this->buffer_[x + y * this->get_width_internal_()]); + this->write_byte(this->buffer_[x + y * this->get_width_internal()]); this->disable(); feed_wdt(); } @@ -288,12 +290,8 @@ void HOT SPISSD1306::write_display_data() { } } SPISSD1306::SPISSD1306(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, uint32_t update_interval) - : SSD1306(update_interval), SPIDevice(parent, cs), dc_pin_(dc_pin) { - -} -bool SPISSD1306::high_speed() { - return true; -} + : SSD1306(update_interval), SPIDevice(parent, cs), dc_pin_(dc_pin) {} +bool SPISSD1306::is_device_high_speed() { return true; } #endif #ifdef USE_I2C @@ -301,8 +299,8 @@ void I2CSSD1306::setup() { ESP_LOGCONFIG(TAG, "Setting up I2C SSD1306..."); this->init_reset_(); - this->parent_->begin_transmission_(this->address_); - if (!this->parent_->end_transmission_(this->address_)) { + this->parent_->raw_begin_transmission(this->address_); + if (!this->parent_->raw_end_transmission(this->address_)) { this->error_code_ = COMMUNICATION_FAILED; this->mark_failed(); return; @@ -322,18 +320,16 @@ void I2CSSD1306::dump_config() { ESP_LOGE(TAG, "Communication with SSD1306 failed!"); } } -void I2CSSD1306::command(uint8_t value) { - this->write_byte(0x00, value); -} +void I2CSSD1306::command(uint8_t value) { this->write_byte(0x00, value); } void HOT I2CSSD1306::write_display_data() { if (this->is_sh1106_()) { uint32_t i = 0; - for (uint8_t page = 0; page < this->get_height_internal_() / 8; page++) { - this->command(0xB0 + page); // row - this->command(0x02); // lower column - this->command(0x10); // higher column + for (uint8_t page = 0; page < this->get_height_internal() / 8; page++) { + this->command(0xB0 + page); // row + this->command(0x02); // lower column + this->command(0x10); // higher column - for (uint8_t x = 0; x < this->get_width_internal_() / 16; x++) { + for (uint8_t x = 0; x < this->get_width_internal() / 16; x++) { uint8_t data[16]; for (uint8_t &j : data) j = this->buffer_[i++]; @@ -353,8 +349,8 @@ I2CSSD1306::I2CSSD1306(I2CComponent *parent, uint32_t update_interval) : I2CDevice(parent, 0x3C), SSD1306(update_interval) {} #endif -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_SSD1306 +#endif // USE_SSD1306 diff --git a/src/esphome/display/ssd1306.h b/src/esphome/display/ssd1306.h index ebc422f0..3844a928 100644 --- a/src/esphome/display/ssd1306.h +++ b/src/esphome/display/ssd1306.h @@ -48,10 +48,10 @@ class SSD1306 : public PollingComponent, public DisplayBuffer { bool is_sh1106_() const; - void draw_absolute_pixel_internal_(int x, int y, int color) override; + void draw_absolute_pixel_internal(int x, int y, int color) override; - int get_height_internal_() override; - int get_width_internal_() override; + int get_height_internal() override; + int get_width_internal() override; size_t get_buffer_length_(); const char *model_str_(); @@ -73,8 +73,8 @@ class SPISSD1306 : public SSD1306, public SPIDevice { void command(uint8_t value) override; void write_display_data() override; - bool msb_first() override; - bool high_speed() override; + bool is_device_msb_first() override; + bool is_device_high_speed() override; GPIOPin *dc_pin_; }; @@ -86,21 +86,19 @@ class I2CSSD1306 : public SSD1306, public I2CDevice { I2CSSD1306(I2CComponent *parent, uint32_t update_interval = 1000); void setup() override; void dump_config() override; + protected: void command(uint8_t value) override; void write_display_data() override; - enum ErrorCode { - NONE = 0, - COMMUNICATION_FAILED - } error_code_{NONE}; + enum ErrorCode { NONE = 0, COMMUNICATION_FAILED } error_code_{NONE}; }; #endif -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_SSD1306 +#endif // USE_SSD1306 -#endif //ESPHOME_SSD_1306_H +#endif // ESPHOME_SSD_1306_H diff --git a/src/esphome/display/waveshare_epaper.cpp b/src/esphome/display/waveshare_epaper.cpp index 1f46bcac..fb4be060 100644 --- a/src/esphome/display/waveshare_epaper.cpp +++ b/src/esphome/display/waveshare_epaper.cpp @@ -13,13 +13,13 @@ static const char *TAG = "display.waveshare_epaper"; static const uint8_t WAVESHARE_EPAPER_COMMAND_DRIVER_OUTPUT_CONTROL = 0x01; static const uint8_t WAVESHARE_EPAPER_COMMAND_BOOSTER_SOFT_START_CONTROL = 0x0C; -//static const uint8_t WAVESHARE_EPAPER_COMMAND_GATE_SCAN_START_POSITION = 0x0F; -//static const uint8_t WAVESHARE_EPAPER_COMMAND_DEEP_SLEEP_MODE = 0x10; +// static const uint8_t WAVESHARE_EPAPER_COMMAND_GATE_SCAN_START_POSITION = 0x0F; +// static const uint8_t WAVESHARE_EPAPER_COMMAND_DEEP_SLEEP_MODE = 0x10; static const uint8_t WAVESHARE_EPAPER_COMMAND_DATA_ENTRY_MODE_SETTING = 0x11; -//static const uint8_t WAVESHARE_EPAPER_COMMAND_SW_RESET = 0x12; -//static const uint8_t WAVESHARE_EPAPER_COMMAND_TEMPERATURE_SENSOR_CONTROL = 0x1A; +// static const uint8_t WAVESHARE_EPAPER_COMMAND_SW_RESET = 0x12; +// static const uint8_t WAVESHARE_EPAPER_COMMAND_TEMPERATURE_SENSOR_CONTROL = 0x1A; static const uint8_t WAVESHARE_EPAPER_COMMAND_MASTER_ACTIVATION = 0x20; -//static const uint8_t WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_1 = 0x21; +// static const uint8_t WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_1 = 0x21; static const uint8_t WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_2 = 0x22; static const uint8_t WAVESHARE_EPAPER_COMMAND_WRITE_RAM = 0x24; static const uint8_t WAVESHARE_EPAPER_COMMAND_WRITE_VCOM_REGISTER = 0x2C; @@ -34,30 +34,24 @@ static const uint8_t WAVESHARE_EPAPER_COMMAND_SET_RAM_Y_ADDRESS_COUNTER = 0x4F; static const uint8_t WAVESHARE_EPAPER_COMMAND_TERMINATE_FRAME_READ_WRITE = 0xFF; // not in .text section since only 30 bytes -static const uint8_t FULL_UPDATE_LUT[30] = { - 0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22, - 0x66, 0x69, 0x69, 0x59, 0x58, 0x99, 0x99, 0x88, - 0x00, 0x00, 0x00, 0x00, 0xF8, 0xB4, 0x13, 0x51, - 0x35, 0x51, 0x51, 0x19, 0x01, 0x00 -}; +static const uint8_t FULL_UPDATE_LUT[30] = {0x02, 0x02, 0x01, 0x11, 0x12, 0x12, 0x22, 0x22, 0x66, 0x69, + 0x69, 0x59, 0x58, 0x99, 0x99, 0x88, 0x00, 0x00, 0x00, 0x00, + 0xF8, 0xB4, 0x13, 0x51, 0x35, 0x51, 0x51, 0x19, 0x01, 0x00}; -static const uint8_t PARTIAL_UPDATE_LUT[30] = { - 0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x13, 0x14, 0x44, 0x12, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -}; +static const uint8_t PARTIAL_UPDATE_LUT[30] = {0x10, 0x18, 0x18, 0x08, 0x18, 0x18, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x13, 0x14, 0x44, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; -void WaveshareEPaper::setup_pins() { - this->init_internal_(this->get_buffer_length()); - this->dc_pin_->setup(); // OUTPUT +void WaveshareEPaper::setup_pins_() { + this->init_internal_(this->get_buffer_length_()); + this->dc_pin_->setup(); // OUTPUT this->dc_pin_->digital_write(false); if (this->reset_pin_ != nullptr) { - this->reset_pin_->setup(); // OUTPUT + this->reset_pin_->setup(); // OUTPUT this->reset_pin_->digital_write(true); } if (this->busy_pin_ != nullptr) { - this->busy_pin_->setup(); // INPUT + this->busy_pin_->setup(); // INPUT } this->spi_setup(); @@ -69,9 +63,7 @@ void WaveshareEPaper::setup_pins() { delay(200); } } -float WaveshareEPaper::get_setup_priority() const { - return setup_priority::POST_HARDWARE; -} +float WaveshareEPaper::get_setup_priority() const { return setup_priority::POST_HARDWARE; } void WaveshareEPaper::command(uint8_t value) { this->start_command_(); this->write_byte(value); @@ -82,9 +74,7 @@ void WaveshareEPaper::data(uint8_t value) { this->write_byte(value); this->end_data_(); } -bool WaveshareEPaper::msb_first() { - return true; -} +bool WaveshareEPaper::is_device_msb_first() { return true; } bool WaveshareEPaper::wait_until_idle_() { if (this->busy_pin_ == nullptr) { return true; @@ -100,27 +90,23 @@ bool WaveshareEPaper::wait_until_idle_() { } return true; } -void WaveshareEPaper::set_reset_pin(const GPIOOutputPin &reset) { - this->reset_pin_ = reset.copy(); -} -void WaveshareEPaper::set_busy_pin(const GPIOInputPin &busy) { - this->busy_pin_ = busy.copy(); -} +void WaveshareEPaper::set_reset_pin(const GPIOOutputPin &reset) { this->reset_pin_ = reset.copy(); } +void WaveshareEPaper::set_busy_pin(const GPIOInputPin &busy) { this->busy_pin_ = busy.copy(); } void WaveshareEPaper::update() { - this->do_update(); + this->do_update_(); this->display(); } void WaveshareEPaper::fill(int color) { // flip logic const uint8_t fill = color ? 0x00 : 0xFF; - for (uint32_t i = 0; i < this->get_buffer_length(); i++) + for (uint32_t i = 0; i < this->get_buffer_length_(); i++) this->buffer_[i] = fill; } -void HOT WaveshareEPaper::draw_absolute_pixel_internal_(int x, int y, int color) { - if (x >= this->get_width_internal_() || y >= this->get_height_internal_() || x < 0 || y < 0) +void HOT WaveshareEPaper::draw_absolute_pixel_internal(int x, int y, int color) { + if (x >= this->get_width_internal() || y >= this->get_height_internal() || x < 0 || y < 0) return; - const uint32_t pos = (x + y * this->get_width_internal_()) / 8u; + const uint32_t pos = (x + y * this->get_width_internal()) / 8u; const uint8_t subpos = x & 0x07; // flip logic if (!color) @@ -128,57 +114,49 @@ void HOT WaveshareEPaper::draw_absolute_pixel_internal_(int x, int y, int color) else this->buffer_[pos] &= ~(0x80 >> subpos); } -uint32_t WaveshareEPaper::get_buffer_length() { - return this->get_width_internal_() * this->get_height_internal_() / 8u; -} -WaveshareEPaper::WaveshareEPaper(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, uint32_t update_interval) : PollingComponent( - update_interval), SPIDevice(parent, cs), dc_pin_(dc_pin) {} -bool WaveshareEPaper::high_speed() { - return true; -} +uint32_t WaveshareEPaper::get_buffer_length_() { return this->get_width_internal() * this->get_height_internal() / 8u; } +WaveshareEPaper::WaveshareEPaper(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, uint32_t update_interval) + : PollingComponent(update_interval), SPIDevice(parent, cs), dc_pin_(dc_pin) {} +bool WaveshareEPaper::is_device_high_speed() { return true; } void WaveshareEPaper::start_command_() { this->dc_pin_->digital_write(false); this->enable(); } -void WaveshareEPaper::end_command_() { - this->disable(); -} +void WaveshareEPaper::end_command_() { this->disable(); } void WaveshareEPaper::start_data_() { this->dc_pin_->digital_write(true); this->enable(); } -void WaveshareEPaper::end_data_() { - this->disable(); -} +void WaveshareEPaper::end_data_() { this->disable(); } // ======================================================== // Type A // ======================================================== void WaveshareEPaperTypeA::setup() { - this->setup_pins(); + this->setup_pins_(); this->command(WAVESHARE_EPAPER_COMMAND_DRIVER_OUTPUT_CONTROL); - this->data(this->get_height_internal_() - 1); - this->data((this->get_height_internal_() - 1) >> 8); - this->data(0x00); // ? GD = 0, SM = 0, TB = 0 + this->data(this->get_height_internal() - 1); + this->data((this->get_height_internal() - 1) >> 8); + this->data(0x00); // ? GD = 0, SM = 0, TB = 0 - this->command(WAVESHARE_EPAPER_COMMAND_BOOSTER_SOFT_START_CONTROL); // ? + this->command(WAVESHARE_EPAPER_COMMAND_BOOSTER_SOFT_START_CONTROL); // ? this->data(0xD7); this->data(0xD6); this->data(0x9D); - this->command(WAVESHARE_EPAPER_COMMAND_WRITE_VCOM_REGISTER); // ? + this->command(WAVESHARE_EPAPER_COMMAND_WRITE_VCOM_REGISTER); // ? this->data(0xA8); - this->command(WAVESHARE_EPAPER_COMMAND_SET_DUMMY_LINE_PERIOD); // ? + this->command(WAVESHARE_EPAPER_COMMAND_SET_DUMMY_LINE_PERIOD); // ? this->data(0x1A); - this->command(WAVESHARE_EPAPER_COMMAND_SET_GATE_TIME); // 2µs per row + this->command(WAVESHARE_EPAPER_COMMAND_SET_GATE_TIME); // 2µs per row this->data(0x08); this->command(WAVESHARE_EPAPER_COMMAND_DATA_ENTRY_MODE_SETTING); - this->data(0x03); // from top left to bottom right + this->data(0x03); // from top left to bottom right } void WaveshareEPaperTypeA::dump_config() { LOG_DISPLAY("", "Waveshare E-Paper", this); @@ -217,12 +195,12 @@ void HOT WaveshareEPaperTypeA::display() { // Set x & y regions we want to write to (full) this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_X_ADDRESS_START_END_POSITION); this->data(0x00); - this->data((this->get_width_internal_() - 1) >> 3); + this->data((this->get_width_internal() - 1) >> 3); this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_Y_ADDRESS_START_END_POSITION); this->data(0x00); this->data(0x00); - this->data(this->get_height_internal_() - 1); - this->data((this->get_height_internal_() - 1) >> 8); + this->data(this->get_height_internal() - 1); + this->data((this->get_height_internal() - 1) >> 8); this->command(WAVESHARE_EPAPER_COMMAND_SET_RAM_X_ADDRESS_COUNTER); this->data(0x00); @@ -237,7 +215,7 @@ void HOT WaveshareEPaperTypeA::display() { this->command(WAVESHARE_EPAPER_COMMAND_WRITE_RAM); this->start_data_(); - this->write_array(this->buffer_, this->get_buffer_length()); + this->write_array(this->buffer_, this->get_buffer_length_()); this->end_data_(); this->command(WAVESHARE_EPAPER_COMMAND_DISPLAY_UPDATE_CONTROL_2); @@ -247,7 +225,7 @@ void HOT WaveshareEPaperTypeA::display() { this->status_clear_warning(); } -int WaveshareEPaperTypeA::get_width_internal_() { +int WaveshareEPaperTypeA::get_width_internal() { switch (this->model_) { case WAVESHARE_EPAPER_1_54_IN: return 200; @@ -258,7 +236,7 @@ int WaveshareEPaperTypeA::get_width_internal_() { } return 0; } -int WaveshareEPaperTypeA::get_height_internal_() { +int WaveshareEPaperTypeA::get_height_internal() { switch (this->model_) { case WAVESHARE_EPAPER_1_54_IN: return 200; @@ -287,18 +265,18 @@ void WaveshareEPaperTypeA::set_full_update_every(uint32_t full_update_every) { static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING = 0x00; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING = 0x01; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_OFF = 0x02; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_OFF_SEQUENCE_SETTING = 0x03; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_OFF = 0x02; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_OFF_SEQUENCE_SETTING = 0x03; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_ON = 0x04; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_MEASURE = 0x05; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_MEASURE = 0x05; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START = 0x06; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DEEP_SLEEP = 0x07; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DEEP_SLEEP = 0x07; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1 = 0x10; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_STOP = 0x11; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_STOP = 0x11; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH = 0x12; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_2 = 0x13; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DATA_START_TRANSMISSION_1 = 0x14; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DATA_START_TRANSMISSION_2 = 0x15; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DATA_START_TRANSMISSION_1 = 0x14; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DATA_START_TRANSMISSION_2 = 0x15; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_DISPLAY_REFRESH = 0x16; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_FOR_VCOM = 0x20; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_WHITE = 0x21; @@ -306,87 +284,66 @@ static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_WHITE = 0x22; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_BLACK = 0x23; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_BLACK = 0x24; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL = 0x30; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_COMMAND = 0x40; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_COMMAND = 0x40; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_CALIBRATION = 0x41; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_WRITE = 0x42; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_READ = 0x43; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_WRITE = 0x42; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TEMPERATURE_SENSOR_READ = 0x43; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCOM_AND_DATA_INTERVAL_SETTING = 0x50; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LOW_POWER_DETECTION = 0x51; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_LOW_POWER_DETECTION = 0x51; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_TCON_SETTING = 0x60; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_RESOLUTION_SETTING = 0x61; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_GET_STATUS = 0x71; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_AUTO_MEASURE_VCOM = 0x80; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCOM_VALUE = 0x81; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_GET_STATUS = 0x71; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_AUTO_MEASURE_VCOM = 0x80; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCOM_VALUE = 0x81; static const uint8_t WAVESHARE_EPAPER_B_COMMAND_VCM_DC_SETTING_REGISTER = 0x82; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_WINDOW = 0x90; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_IN = 0x91; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_OUT = 0x92; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PROGRAM_MODE = 0xA0; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_ACTIVE_PROGRAM = 0xA1; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_READ_OTP_DATA = 0xA2; -//static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_SAVING = 0xE3; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_WINDOW = 0x90; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_IN = 0x91; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PARTIAL_OUT = 0x92; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_PROGRAM_MODE = 0xA0; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_ACTIVE_PROGRAM = 0xA1; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_READ_OTP_DATA = 0xA2; +// static const uint8_t WAVESHARE_EPAPER_B_COMMAND_POWER_SAVING = 0xE3; static const uint8_t LUT_VCOM_DC_2_7[44] = { - 0x00, 0x00, - 0x00, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x00, 0x32, 0x32, 0x00, 0x00, 0x02, - 0x00, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x00, 0x32, 0x32, 0x00, 0x00, 0x02, 0x00, + 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const uint8_t LUT_WHITE_TO_WHITE_2_7[42] = { - 0x50, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, - 0xA0, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x50, 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, 0xA0, 0x0F, + 0x0F, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const uint8_t LUT_BLACK_TO_WHITE_2_7[42] = { - 0x50, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, - 0xA0, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x50, 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, 0xA0, 0x0F, + 0x0F, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const uint8_t LUT_WHITE_TO_BLACK_2_7[] = { - 0xA0, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, - 0x50, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xA0, 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, 0x50, 0x0F, + 0x0F, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const uint8_t LUT_BLACK_TO_BLACK_2_7[42] = { - 0xA0, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, - 0x50, 0x0F, 0x0F, 0x00, 0x00, 0x05, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xA0, 0x0F, 0x0F, 0x00, 0x00, 0x05, 0x60, 0x32, 0x32, 0x00, 0x00, 0x02, 0x50, 0x0F, + 0x0F, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; void WaveshareEPaper2P7In::setup() { - this->setup_pins(); + this->setup_pins_(); // this->buffer_.init(this->get_width_(), this->get_height_()); this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING); - this->data(0x03); // VDS_EN, VDG_EN - this->data(0x00); // VCOM_HV, VGHL_LV[1], VGHL_LV[0] - this->data(0x2B); // VDH - this->data(0x2B); // VDL - this->data(0x09); // VDHR + this->data(0x03); // VDS_EN, VDG_EN + this->data(0x00); // VCOM_HV, VGHL_LV[1], VGHL_LV[0] + this->data(0x2B); // VDH + this->data(0x2B); // VDL + this->data(0x09); // VDHR this->command(WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START); this->data(0x07); @@ -424,45 +381,46 @@ void WaveshareEPaper2P7In::setup() { delay(10); this->command(WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING); - this->data(0xAF); //KW-BF KWR-AF BWROTP 0f + this->data(0xAF); // KW-BF KWR-AF BWROTP 0f this->command(WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL); - this->data(0x3A); //3A 100HZ 29 150Hz 39 200HZ 31 171HZ + this->data(0x3A); // 3A 100HZ 29 150Hz 39 200HZ 31 171HZ this->command(WAVESHARE_EPAPER_B_COMMAND_VCM_DC_SETTING_REGISTER); this->data(0x12); delay(2); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_FOR_VCOM); - for (uint8_t i : LUT_VCOM_DC_2_7) this->data(i); + for (uint8_t i : LUT_VCOM_DC_2_7) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_WHITE); - for (uint8_t i : LUT_WHITE_TO_WHITE_2_7) this->data(i); + for (uint8_t i : LUT_WHITE_TO_WHITE_2_7) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_WHITE); - for (uint8_t i : LUT_BLACK_TO_WHITE_2_7) this->data(i); + for (uint8_t i : LUT_BLACK_TO_WHITE_2_7) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_BLACK); - for (uint8_t i : LUT_WHITE_TO_BLACK_2_7) this->data(i); + for (uint8_t i : LUT_WHITE_TO_BLACK_2_7) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_BLACK); - for (uint8_t i : LUT_BLACK_TO_BLACK_2_7) this->data(i); + for (uint8_t i : LUT_BLACK_TO_BLACK_2_7) + this->data(i); } void HOT WaveshareEPaper2P7In::display() { // TODO check active frame buffer to only transmit once / use partial transmits this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1); delay(2); this->start_data_(); - this->write_array(this->buffer_, this->get_buffer_length()); + this->write_array(this->buffer_, this->get_buffer_length_()); this->end_data_(); delay(2); this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_2); delay(2); this->start_data_(); - this->write_array(this->buffer_, this->get_buffer_length()); + this->write_array(this->buffer_, this->get_buffer_length_()); this->end_data_(); this->command(WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH); } -int WaveshareEPaper2P7In::get_width_internal_() { - return 176; -} -int WaveshareEPaper2P7In::get_height_internal_() { - return 264; -} +int WaveshareEPaper2P7In::get_width_internal() { return 176; } +int WaveshareEPaper2P7In::get_height_internal() { return 264; } WaveshareEPaper2P7In::WaveshareEPaper2P7In(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, uint32_t update_interval) : WaveshareEPaper(parent, cs, dc_pin, update_interval) {} void WaveshareEPaper2P7In::dump_config() { @@ -475,62 +433,42 @@ void WaveshareEPaper2P7In::dump_config() { } static const uint8_t LUT_VCOM_DC_4_2[] = { - 0x00, 0x17, 0x00, 0x00, 0x00, 0x02, - 0x00, 0x17, 0x17, 0x00, 0x00, 0x02, - 0x00, 0x0A, 0x01, 0x00, 0x00, 0x01, - 0x00, 0x0E, 0x0E, 0x00, 0x00, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x17, 0x00, 0x00, 0x00, 0x02, 0x00, 0x17, 0x17, 0x00, 0x00, 0x02, 0x00, 0x0A, 0x01, + 0x00, 0x00, 0x01, 0x00, 0x0E, 0x0E, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; -static const uint8_t LUT_WHITE_TO_WHITE_4_2[] ={ - 0x40, 0x17, 0x00, 0x00, 0x00, 0x02, - 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, - 0x40, 0x0A, 0x01, 0x00, 0x00, 0x01, - 0xA0, 0x0E, 0x0E, 0x00, 0x00, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +static const uint8_t LUT_WHITE_TO_WHITE_4_2[] = { + 0x40, 0x17, 0x00, 0x00, 0x00, 0x02, 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, 0x40, 0x0A, + 0x01, 0x00, 0x00, 0x01, 0xA0, 0x0E, 0x0E, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; -static const uint8_t LUT_BLACK_TO_WHITE_4_2[] ={ - 0x40, 0x17, 0x00, 0x00, 0x00, 0x02, - 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, - 0x40, 0x0A, 0x01, 0x00, 0x00, 0x01, - 0xA0, 0x0E, 0x0E, 0x00, 0x00, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +static const uint8_t LUT_BLACK_TO_WHITE_4_2[] = { + 0x40, 0x17, 0x00, 0x00, 0x00, 0x02, 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, 0x40, 0x0A, + 0x01, 0x00, 0x00, 0x01, 0xA0, 0x0E, 0x0E, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; -static const uint8_t LUT_BLACK_TO_BLACK_4_2[] ={ - 0x80, 0x17, 0x00, 0x00, 0x00, 0x02, - 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, - 0x80, 0x0A, 0x01, 0x00, 0x00, 0x01, - 0x50, 0x0E, 0x0E, 0x00, 0x00, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +static const uint8_t LUT_BLACK_TO_BLACK_4_2[] = { + 0x80, 0x17, 0x00, 0x00, 0x00, 0x02, 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, 0x80, 0x0A, + 0x01, 0x00, 0x00, 0x01, 0x50, 0x0E, 0x0E, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; -static const uint8_t LUT_WHITE_TO_BLACK_4_2[] ={ - 0x80, 0x17, 0x00, 0x00, 0x00, 0x02, - 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, - 0x80, 0x0A, 0x01, 0x00, 0x00, 0x01, - 0x50, 0x0E, 0x0E, 0x00, 0x00, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +static const uint8_t LUT_WHITE_TO_BLACK_4_2[] = { + 0x80, 0x17, 0x00, 0x00, 0x00, 0x02, 0x90, 0x17, 0x17, 0x00, 0x00, 0x02, 0x80, 0x0A, + 0x01, 0x00, 0x00, 0x01, 0x50, 0x0E, 0x0E, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; void WaveshareEPaper4P2In::setup() { - this->setup_pins(); + this->setup_pins_(); this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING); - this->data(0x03); // VDS_EN, VDG_EN - this->data(0x00); // VCOM_HV, VGHL_LV[1], VGHL_LV[0] - this->data(0x2B); // VDH - this->data(0x2B); // VDL - this->data(0xFF); // VDHR + this->data(0x03); // VDS_EN, VDG_EN + this->data(0x00); // VCOM_HV, VGHL_LV[1], VGHL_LV[0] + this->data(0x2B); // VDH + this->data(0x2B); // VDL + this->data(0xFF); // VDHR this->command(WAVESHARE_EPAPER_B_COMMAND_BOOSTER_SOFT_START); this->data(0x17); @@ -541,23 +479,27 @@ void WaveshareEPaper4P2In::setup() { this->wait_until_idle_(); delay(10); this->command(WAVESHARE_EPAPER_B_COMMAND_PANEL_SETTING); - this->data(0xBF); // KW-BF KWR-AF BWROTP 0f + this->data(0xBF); // KW-BF KWR-AF BWROTP 0f this->data(0x0B); this->command(WAVESHARE_EPAPER_B_COMMAND_PLL_CONTROL); - this->data(0x3C); // 3A 100HZ 29 150Hz 39 200HZ 31 171HZ + this->data(0x3C); // 3A 100HZ 29 150Hz 39 200HZ 31 171HZ delay(2); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_FOR_VCOM); - for (uint8_t i : LUT_VCOM_DC_4_2) this->data(i); + for (uint8_t i : LUT_VCOM_DC_4_2) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_WHITE); - for (uint8_t i : LUT_WHITE_TO_WHITE_4_2) this->data(i); + for (uint8_t i : LUT_WHITE_TO_WHITE_4_2) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_WHITE); - for (uint8_t i : LUT_BLACK_TO_WHITE_4_2) this->data(i); + for (uint8_t i : LUT_BLACK_TO_WHITE_4_2) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_WHITE_TO_BLACK); - for (uint8_t i : LUT_WHITE_TO_BLACK_4_2) this->data(i); + for (uint8_t i : LUT_WHITE_TO_BLACK_4_2) + this->data(i); this->command(WAVESHARE_EPAPER_B_COMMAND_LUT_BLACK_TO_BLACK); - for (uint8_t i : LUT_BLACK_TO_BLACK_4_2) this->data(i); - + for (uint8_t i : LUT_BLACK_TO_BLACK_4_2) + this->data(i); } void HOT WaveshareEPaper4P2In::display() { this->command(WAVESHARE_EPAPER_B_COMMAND_RESOLUTION_SETTING); @@ -572,27 +514,22 @@ void HOT WaveshareEPaper4P2In::display() { this->command(WAVESHARE_EPAPER_B_COMMAND_VCOM_AND_DATA_INTERVAL_SETTING); this->data(0x97); - // TODO check active frame buffer to only transmit once / use partial transmits this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1); delay(2); this->start_data_(); - this->write_array(this->buffer_, this->get_buffer_length()); + this->write_array(this->buffer_, this->get_buffer_length_()); this->end_data_(); delay(2); this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_2); delay(2); this->start_data_(); - this->write_array(this->buffer_, this->get_buffer_length()); + this->write_array(this->buffer_, this->get_buffer_length_()); this->end_data_(); this->command(WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH); } -int WaveshareEPaper4P2In::get_width_internal_() { - return 400; -} -int WaveshareEPaper4P2In::get_height_internal_() { - return 300; -} +int WaveshareEPaper4P2In::get_width_internal() { return 400; } +int WaveshareEPaper4P2In::get_height_internal() { return 300; } WaveshareEPaper4P2In::WaveshareEPaper4P2In(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, uint32_t update_interval) : WaveshareEPaper(parent, cs, dc_pin, update_interval) {} void WaveshareEPaper4P2In::dump_config() { @@ -605,7 +542,7 @@ void WaveshareEPaper4P2In::dump_config() { } void WaveshareEPaper7P5In::setup() { - this->setup_pins(); + this->setup_pins_(); this->command(WAVESHARE_EPAPER_B_COMMAND_POWER_SETTING); this->data(0x37); @@ -652,7 +589,7 @@ void HOT WaveshareEPaper7P5In::display() { this->command(WAVESHARE_EPAPER_B_COMMAND_DATA_START_TRANSMISSION_1); this->start_data_(); - for (size_t i = 0; i < this->get_buffer_length(); i++) { + for (size_t i = 0; i < this->get_buffer_length_(); i++) { uint8_t temp1 = this->buffer_[i]; for (uint8_t j = 0; j < 8; j++) { uint8_t temp2; @@ -678,12 +615,8 @@ void HOT WaveshareEPaper7P5In::display() { this->command(WAVESHARE_EPAPER_B_COMMAND_DISPLAY_REFRESH); } -int WaveshareEPaper7P5In::get_width_internal_() { - return 640; -} -int WaveshareEPaper7P5In::get_height_internal_() { - return 384; -} +int WaveshareEPaper7P5In::get_width_internal() { return 640; } +int WaveshareEPaper7P5In::get_height_internal() { return 384; } WaveshareEPaper7P5In::WaveshareEPaper7P5In(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, uint32_t update_interval) : WaveshareEPaper(parent, cs, dc_pin, update_interval) {} void WaveshareEPaper7P5In::dump_config() { @@ -695,8 +628,8 @@ void WaveshareEPaper7P5In::dump_config() { LOG_UPDATE_INTERVAL(this); } -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_WAVESHARE_EPAPER +#endif // USE_WAVESHARE_EPAPER diff --git a/src/esphome/display/waveshare_epaper.h b/src/esphome/display/waveshare_epaper.h index 0f68d305..033b2445 100644 --- a/src/esphome/display/waveshare_epaper.h +++ b/src/esphome/display/waveshare_epaper.h @@ -19,10 +19,9 @@ class WaveshareEPaper : public PollingComponent, public SPIDevice, public Displa void set_reset_pin(const GPIOOutputPin &reset); void set_busy_pin(const GPIOInputPin &busy); - bool msb_first() override; + bool is_device_msb_first() override; void command(uint8_t value); void data(uint8_t value); - bool wait_until_idle_(); virtual void display() = 0; @@ -31,13 +30,15 @@ class WaveshareEPaper : public PollingComponent, public SPIDevice, public Displa void fill(int color) override; protected: - void draw_absolute_pixel_internal_(int x, int y, int color) override; + void draw_absolute_pixel_internal(int x, int y, int color) override; + + bool wait_until_idle_(); - void setup_pins(); + void setup_pins_(); - uint32_t get_buffer_length(); + uint32_t get_buffer_length_(); - bool high_speed() override; + bool is_device_high_speed() override; void start_command_(); void end_command_(); @@ -57,8 +58,8 @@ enum WaveshareEPaperTypeAModel { class WaveshareEPaperTypeA : public WaveshareEPaper { public: - WaveshareEPaperTypeA(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, - WaveshareEPaperTypeAModel model, uint32_t update_interval); + WaveshareEPaperTypeA(SPIComponent *parent, GPIOPin *cs, GPIOPin *dc_pin, WaveshareEPaperTypeAModel model, + uint32_t update_interval); void setup() override; @@ -71,9 +72,9 @@ class WaveshareEPaperTypeA : public WaveshareEPaper { protected: void write_lut_(const uint8_t *lut); - int get_width_internal_() override; + int get_width_internal() override; - int get_height_internal_() override; + int get_height_internal() override; uint32_t full_update_every_{30}; uint32_t at_update_{0}; @@ -96,9 +97,9 @@ class WaveshareEPaper2P7In : public WaveshareEPaper { void dump_config() override; protected: - int get_width_internal_() override; + int get_width_internal() override; - int get_height_internal_() override; + int get_height_internal() override; }; class WaveshareEPaper4P2In : public WaveshareEPaper { @@ -111,9 +112,9 @@ class WaveshareEPaper4P2In : public WaveshareEPaper { void dump_config() override; protected: - int get_width_internal_() override; + int get_width_internal() override; - int get_height_internal_() override; + int get_height_internal() override; }; class WaveshareEPaper7P5In : public WaveshareEPaper { @@ -126,15 +127,15 @@ class WaveshareEPaper7P5In : public WaveshareEPaper { void dump_config() override; protected: - int get_width_internal_() override; + int get_width_internal() override; - int get_height_internal_() override; + int get_height_internal() override; }; -} // namespace display +} // namespace display ESPHOME_NAMESPACE_END -#endif //USE_WAVESHARE_EPAPER +#endif // USE_WAVESHARE_EPAPER -#endif //ESPHOME_WAVESHARE_E_PAPER_H +#endif // ESPHOME_WAVESHARE_E_PAPER_H diff --git a/src/esphome/esp32_ble_beacon.cpp b/src/esphome/esp32_ble_beacon.cpp index df4f0d99..d039292a 100644 --- a/src/esphome/esp32_ble_beacon.cpp +++ b/src/esphome/esp32_ble_beacon.cpp @@ -17,44 +17,36 @@ ESPHOME_NAMESPACE_BEGIN static const char *TAG = "esp32_ble_beacon"; static esp_ble_adv_params_t ble_adv_params = { - .adv_int_min = 0x20, - .adv_int_max = 0x40, - .adv_type = ADV_TYPE_NONCONN_IND, - .own_addr_type = BLE_ADDR_TYPE_PUBLIC, - .peer_addr = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - .peer_addr_type = BLE_ADDR_TYPE_PUBLIC, - .channel_map = ADV_CHNL_ALL, - .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, + .adv_int_min = 0x20, + .adv_int_max = 0x40, + .adv_type = ADV_TYPE_NONCONN_IND, + .own_addr_type = BLE_ADDR_TYPE_PUBLIC, + .peer_addr = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + .peer_addr_type = BLE_ADDR_TYPE_PUBLIC, + .channel_map = ADV_CHNL_ALL, + .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; -#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) +#define ENDIAN_CHANGE_U16(x) ((((x) &0xFF00) >> 8) + (((x) &0xFF) << 8)) static esp_ble_ibeacon_head_t ibeacon_common_head = { - .flags = {0x02, 0x01, 0x06}, - .length = 0x1A, - .type = 0xFF, - .company_id = 0x004C, - .beacon_type = 0x1502 -}; + .flags = {0x02, 0x01, 0x06}, .length = 0x1A, .type = 0xFF, .company_id = 0x004C, .beacon_type = 0x1502}; void ESP32BLEBeacon::setup() { ESP_LOGCONFIG(TAG, "Setting up ESP32 BLE beacon..."); global_esp32_ble_beacon = this; - xTaskCreatePinnedToCore( - ESP32BLEBeacon::ble_core_task, - "ble_task", // name - 10000, // stack size (in words) - nullptr, // input params - 1, // priority - nullptr, // Handle, not needed - 0 // core + xTaskCreatePinnedToCore(ESP32BLEBeacon::ble_core_task, + "ble_task", // name + 10000, // stack size (in words) + nullptr, // input params + 1, // priority + nullptr, // Handle, not needed + 0 // core ); } -float ESP32BLEBeacon::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float ESP32BLEBeacon::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void ESP32BLEBeacon::ble_core_task(void *params) { ble_setup(); @@ -130,21 +122,16 @@ void ESP32BLEBeacon::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap } break; } - default: break; + default: + break; } } -ESP32BLEBeacon::ESP32BLEBeacon(const std::array &uuid) : uuid(uuid) { - -} -void ESP32BLEBeacon::set_major(uint16_t major) { - this->major = major; -} -void ESP32BLEBeacon::set_minor(uint16_t minor) { - this->minor = minor; -} +ESP32BLEBeacon::ESP32BLEBeacon(const std::array &uuid) : uuid(uuid) {} +void ESP32BLEBeacon::set_major(uint16_t major) { this->major = major; } +void ESP32BLEBeacon::set_minor(uint16_t minor) { this->minor = minor; } ESP32BLEBeacon *global_esp32_ble_beacon = nullptr; ESPHOME_NAMESPACE_END -#endif //USE_ESP32_BLE_BEACON +#endif // USE_ESP32_BLE_BEACON diff --git a/src/esphome/esp32_ble_beacon.h b/src/esphome/esp32_ble_beacon.h index dd5fd8a3..515d4258 100644 --- a/src/esphome/esp32_ble_beacon.h +++ b/src/esphome/esp32_ble_beacon.h @@ -16,7 +16,7 @@ typedef struct { uint8_t type; uint16_t company_id; uint16_t beacon_type; -}__attribute__((packed)) esp_ble_ibeacon_head_t; +} __attribute__((packed)) esp_ble_ibeacon_head_t; typedef struct { uint8_t proximity_uuid[16]; @@ -25,7 +25,6 @@ typedef struct { uint8_t measured_power; } __attribute__((packed)) esp_ble_ibeacon_vendor_t; - typedef struct { esp_ble_ibeacon_head_t ibeacon_head; esp_ble_ibeacon_vendor_t ibeacon_vendor; @@ -55,6 +54,6 @@ extern ESP32BLEBeacon *global_esp32_ble_beacon; ESPHOME_NAMESPACE_END -#endif //USE_ESP32_BLE_BEACON +#endif // USE_ESP32_BLE_BEACON -#endif //ESPHOME_ESP_32_BLE_BEACON_H +#endif // ESPHOME_ESP_32_BLE_BEACON_H diff --git a/src/esphome/esp32_ble_tracker.cpp b/src/esphome/esp32_ble_tracker.cpp index 84793ab2..4ae4b164 100644 --- a/src/esphome/esp32_ble_tracker.cpp +++ b/src/esphome/esp32_ble_tracker.cpp @@ -252,7 +252,7 @@ enum XiaomiDataType { XiaomiDataType parse_xiaomi(uint8_t data_type, const uint8_t *data, uint8_t data_length, float *data1, float *data2) { switch (data_type) { - case 0x0D: { // temperature+humidity, 4 bytes, 16-bit signed integer (LE) each, 0.1 °C, 0.1 % + case 0x0D: { // temperature+humidity, 4 bytes, 16-bit signed integer (LE) each, 0.1 °C, 0.1 % if (data_length != 4) return XIAOMI_NO_DATA; const int16_t temperature = uint16_t(data[0]) | (uint16_t(data[1]) << 8); @@ -261,41 +261,41 @@ XiaomiDataType parse_xiaomi(uint8_t data_type, const uint8_t *data, uint8_t data *data2 = humidity / 10.0f; return XIAOMI_TEMPERATURE_HUMIDITY; } - case 0x0A: { // battery, 1 byte, 8-bit unsigned integer, 1 % + case 0x0A: { // battery, 1 byte, 8-bit unsigned integer, 1 % if (data_length != 1) return XIAOMI_NO_DATA; *data1 = data[0]; return XIAOMI_BATTERY_LEVEL; } - case 0x06: { // humidity, 2 bytes, 16-bit signed integer (LE), 0.1 % + case 0x06: { // humidity, 2 bytes, 16-bit signed integer (LE), 0.1 % if (data_length != 2) return XIAOMI_NO_DATA; const int16_t humidity = uint16_t(data[0]) | (uint16_t(data[1]) << 8); *data1 = humidity / 10.0f; return XIAOMI_HUMIDITY; } - case 0x04: { // temperature, 2 bytes, 16-bit signed integer (LE), 0.1 °C + case 0x04: { // temperature, 2 bytes, 16-bit signed integer (LE), 0.1 °C if (data_length != 2) return XIAOMI_NO_DATA; const int16_t temperature = uint16_t(data[0]) | (uint16_t(data[1]) << 8); *data1 = temperature / 10.0f; return XIAOMI_TEMPERATURE; } - case 0x09: { // conductivity, 2 bytes, 16-bit unsigned integer (LE), 1 µS/cm + case 0x09: { // conductivity, 2 bytes, 16-bit unsigned integer (LE), 1 µS/cm if (data_length != 2) return XIAOMI_NO_DATA; const uint16_t conductivity = uint16_t(data[0]) | (uint16_t(data[1]) << 8); *data1 = conductivity; return XIAOMI_CONDUCTIVITY; } - case 0x07: { // illuminance, 3 bytes, 24-bit unsigned integer (LE), 1 lx + case 0x07: { // illuminance, 3 bytes, 24-bit unsigned integer (LE), 1 lx if (data_length != 3) return XIAOMI_NO_DATA; const uint32_t illuminance = uint32_t(data[0]) | (uint32_t(data[1]) << 8) | (uint32_t(data[2]) << 16); *data1 = illuminance; return XIAOMI_ILLUMINANCE; } - case 0x08: { // soil moisture, 1 byte, 8-bit unsigned integer, 1 % + case 0x08: { // soil moisture, 1 byte, 8-bit unsigned integer, 1 % if (data_length != 1) return XIAOMI_NO_DATA; *data1 = data[0]; @@ -354,32 +354,25 @@ void ESP32BLETracker::parse_xiaomi_sensors_(const ESPBTDevice &device) { std::string address_str = device.address_str(); switch (data_type) { case XIAOMI_TEMPERATURE_HUMIDITY: - ESP_LOGD(TAG, "Xiaomi %s %s Got temperature=%.1f°C, humidity=%.1f%%", - type, address_str.c_str(), data1, data2); + ESP_LOGD(TAG, "Xiaomi %s %s Got temperature=%.1f°C, humidity=%.1f%%", type, address_str.c_str(), data1, data2); break; case XIAOMI_TEMPERATURE: - ESP_LOGD(TAG, "Xiaomi %s %s Got temperature=%.1f°C", - type, address_str.c_str(), data1); + ESP_LOGD(TAG, "Xiaomi %s %s Got temperature=%.1f°C", type, address_str.c_str(), data1); break; case XIAOMI_HUMIDITY: - ESP_LOGD(TAG, "Xiaomi %s %s Got humidity=%.1f%%", - type, address_str.c_str(), data1); + ESP_LOGD(TAG, "Xiaomi %s %s Got humidity=%.1f%%", type, address_str.c_str(), data1); break; case XIAOMI_BATTERY_LEVEL: - ESP_LOGD(TAG, "Xiaomi %s %s Got battery level=%.0f%%", - type, address_str.c_str(), data1); + ESP_LOGD(TAG, "Xiaomi %s %s Got battery level=%.0f%%", type, address_str.c_str(), data1); break; case XIAOMI_MOISTURE: - ESP_LOGD(TAG, "Xiaomi %s %s Got moisture=%.0f%%", - type, address_str.c_str(), data1); + ESP_LOGD(TAG, "Xiaomi %s %s Got moisture=%.0f%%", type, address_str.c_str(), data1); break; case XIAOMI_ILLUMINANCE: - ESP_LOGD(TAG, "Xiaomi %s %s Got illuminance=%.0flx", - type, address_str.c_str(), data1); + ESP_LOGD(TAG, "Xiaomi %s %s Got illuminance=%.0flx", type, address_str.c_str(), data1); break; case XIAOMI_CONDUCTIVITY: - ESP_LOGD(TAG, "Xiaomi %s %s Got soil conductivity=%.0fµS/cm", - type, address_str.c_str(), data1); + ESP_LOGD(TAG, "Xiaomi %s %s Got soil conductivity=%.0fµS/cm", type, address_str.c_str(), data1); break; default: break; @@ -520,8 +513,7 @@ std::string ESPBTUUID::to_string() { sprintf(sbuf, "%02X:%02X", this->uuid_.uuid.uuid16 >> 8, this->uuid_.uuid.uuid16); break; case ESP_UUID_LEN_32: - sprintf(sbuf, "%02X:%02X:%02X:%02X", - this->uuid_.uuid.uuid32 >> 24, this->uuid_.uuid.uuid32 >> 16, + sprintf(sbuf, "%02X:%02X:%02X:%02X", this->uuid_.uuid.uuid32 >> 24, this->uuid_.uuid.uuid32 >> 16, this->uuid_.uuid.uuid32 >> 8, this->uuid_.uuid.uuid32); break; default: @@ -545,24 +537,21 @@ void ESPBTDevice::parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_e ESP_LOGVV(TAG, "Parse Result:"); const char *address_type = ""; switch (this->address_type_) { - case BLE_ADDR_TYPE_PUBLIC:address_type = "PUBLIC"; + case BLE_ADDR_TYPE_PUBLIC: + address_type = "PUBLIC"; break; - case BLE_ADDR_TYPE_RANDOM:address_type = "RANDOM"; + case BLE_ADDR_TYPE_RANDOM: + address_type = "RANDOM"; break; - case BLE_ADDR_TYPE_RPA_PUBLIC:address_type = "RPA_PUBLIC"; + case BLE_ADDR_TYPE_RPA_PUBLIC: + address_type = "RPA_PUBLIC"; break; - case BLE_ADDR_TYPE_RPA_RANDOM:address_type = "RPA_RANDOM"; + case BLE_ADDR_TYPE_RPA_RANDOM: + address_type = "RPA_RANDOM"; break; } - ESP_LOGVV(TAG, - " Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", - this->address_[0], - this->address_[1], - this->address_[2], - this->address_[3], - this->address_[4], - this->address_[5], - address_type); + ESP_LOGVV(TAG, " Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1], + this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type); ESP_LOGVV(TAG, " RSSI: %d", this->rssi_); ESP_LOGVV(TAG, " Name: %s", this->name_.c_str()); @@ -603,7 +592,7 @@ void ESPBTDevice::parse_adv(const esp_ble_gap_cb_param_t::ble_scan_result_evt_pa uint8_t len = param.adv_data_len; while (offset + 2 < len) { - const uint8_t field_length = payload[offset++]; // First byte is length of adv record + const uint8_t field_length = payload[offset++]; // First byte is length of adv record if (field_length == 0) break; @@ -692,51 +681,24 @@ void ESPBTDevice::parse_adv(const esp_ble_gap_cb_param_t::ble_scan_result_evt_pa } std::string ESPBTDevice::address_str() const { char mac[24]; - snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X", - this->address_[0], this->address_[1], this->address_[2], + snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X", this->address_[0], this->address_[1], this->address_[2], this->address_[3], this->address_[4], this->address_[5]); return mac; } -uint64_t ESPBTDevice::address_uint64() const { - return ble_addr_to_uint64(this->address_); -} -esp_ble_addr_type_t ESPBTDevice::get_address_type() const { - return this->address_type_; -} -int ESPBTDevice::get_rssi() const { - return this->rssi_; -} -const std::string &ESPBTDevice::get_name() const { - return this->name_; -} -const optional &ESPBTDevice::get_tx_power() const { - return this->tx_power_; -} -const optional &ESPBTDevice::get_appearance() const { - return this->appearance_; -} -const optional &ESPBTDevice::get_ad_flag() const { - return this->ad_flag_; -} -const std::vector &ESPBTDevice::get_service_uuids() const { - return this->service_uuids_; -} -const std::string &ESPBTDevice::get_manufacturer_data() const { - return this->manufacturer_data_; -} -const std::string &ESPBTDevice::get_service_data() const { - return this->service_data_; -} -const optional &ESPBTDevice::get_service_data_uuid() const { - return this->service_data_uuid_; -} - -void ESP32BLETracker::set_scan_interval(uint32_t scan_interval) { - this->scan_interval_ = scan_interval; -} -uint32_t ESP32BLETracker::get_scan_interval() const { - return this->scan_interval_; -} +uint64_t ESPBTDevice::address_uint64() const { return ble_addr_to_uint64(this->address_); } +esp_ble_addr_type_t ESPBTDevice::get_address_type() const { return this->address_type_; } +int ESPBTDevice::get_rssi() const { return this->rssi_; } +const std::string &ESPBTDevice::get_name() const { return this->name_; } +const optional &ESPBTDevice::get_tx_power() const { return this->tx_power_; } +const optional &ESPBTDevice::get_appearance() const { return this->appearance_; } +const optional &ESPBTDevice::get_ad_flag() const { return this->ad_flag_; } +const std::vector &ESPBTDevice::get_service_uuids() const { return this->service_uuids_; } +const std::string &ESPBTDevice::get_manufacturer_data() const { return this->manufacturer_data_; } +const std::string &ESPBTDevice::get_service_data() const { return this->service_data_; } +const optional &ESPBTDevice::get_service_data_uuid() const { return this->service_data_uuid_; } + +void ESP32BLETracker::set_scan_interval(uint32_t scan_interval) { this->scan_interval_ = scan_interval; } +uint32_t ESP32BLETracker::get_scan_interval() const { return this->scan_interval_; } void ESP32BLETracker::dump_config() { ESP_LOGCONFIG(TAG, "BLE Tracker:"); ESP_LOGCONFIG(TAG, " Scan Interval: %u s", this->scan_interval_); @@ -757,43 +719,27 @@ void ESP32BLETracker::dump_config() { } } -std::string ESP32BLERSSISensor::unit_of_measurement() { - return "dB"; -} +std::string ESP32BLERSSISensor::unit_of_measurement() { return "dB"; } -std::string ESP32BLERSSISensor::icon() { - return "mdi:signal"; -} -int8_t ESP32BLERSSISensor::accuracy_decimals() { - return Sensor::accuracy_decimals(); -} +std::string ESP32BLERSSISensor::icon() { return "mdi:signal"; } +int8_t ESP32BLERSSISensor::accuracy_decimals() { return Sensor::accuracy_decimals(); } std::string ESP32BLERSSISensor::unique_id() { char buffer[32]; sprintf(buffer, "ble-%08X%08X-rssi", uint32_t(this->address_ >> 32), uint32_t(this->address_)); return buffer; } -uint32_t ESP32BLERSSISensor::update_interval() { - return this->parent_->get_scan_interval() * 1000u; -} +uint32_t ESP32BLERSSISensor::update_interval() { return this->parent_->get_scan_interval() * 1000u; } ESP32BLERSSISensor::ESP32BLERSSISensor(ESP32BLETracker *parent, const std::string &name, uint64_t address) - : Sensor(name), parent_(parent), address_(address) { - -} + : Sensor(name), parent_(parent), address_(address) {} uint32_t XiaomiDevice::update_interval() const { // Double the scan interval because Xiaomis don't send values too often. return this->parent_->get_scan_interval() * 2000; } -std::string XiaomiDevice::unique_id() const { - return uint64_to_string(this->address_); -} +std::string XiaomiDevice::unique_id() const { return uint64_to_string(this->address_); } ESP32BLEPresenceDevice::ESP32BLEPresenceDevice(const std::string &name, uint64_t address) - : BinarySensor(name), address_(address) { - -} -std::string ESP32BLEPresenceDevice::device_class() { - return "presence"; -} + : BinarySensor(name), address_(address) {} +std::string ESP32BLEPresenceDevice::device_class() { return "presence"; } std::string XiaomiSensor::unit_of_measurement() { switch (this->type_) { @@ -827,9 +773,7 @@ std::string XiaomiSensor::icon() { return ""; } -uint32_t XiaomiSensor::update_interval() { - return this->parent_->update_interval(); -} +uint32_t XiaomiSensor::update_interval() { return this->parent_->update_interval(); } int8_t XiaomiSensor::accuracy_decimals() { switch (this->type_) { case TYPE_TEMPERATURE: @@ -870,24 +814,12 @@ std::string XiaomiSensor::unique_id() { XiaomiSensor::XiaomiSensor(XiaomiDevice *parent, XiaomiSensor::Type type, const std::string &name) : Sensor(name), parent_(parent), type_(type) {} -XiaomiSensor *XiaomiDevice::get_temperature_sensor() const { - return this->temperature_sensor_; -} -XiaomiSensor *XiaomiDevice::get_humidity_sensor() const { - return this->humidity_sensor_; -} -XiaomiSensor *XiaomiDevice::get_moisture_sensor() const { - return this->moisture_sensor_; -} -XiaomiSensor *XiaomiDevice::get_illuminance_sensor() const { - return this->illuminance_sensor_; -} -XiaomiSensor *XiaomiDevice::get_conductivity_sensor() const { - return this->conductivity_sensor_; -} -XiaomiSensor *XiaomiDevice::get_battery_level_sensor() const { - return this->battery_level_sensor_; -} +XiaomiSensor *XiaomiDevice::get_temperature_sensor() const { return this->temperature_sensor_; } +XiaomiSensor *XiaomiDevice::get_humidity_sensor() const { return this->humidity_sensor_; } +XiaomiSensor *XiaomiDevice::get_moisture_sensor() const { return this->moisture_sensor_; } +XiaomiSensor *XiaomiDevice::get_illuminance_sensor() const { return this->illuminance_sensor_; } +XiaomiSensor *XiaomiDevice::get_conductivity_sensor() const { return this->conductivity_sensor_; } +XiaomiSensor *XiaomiDevice::get_battery_level_sensor() const { return this->battery_level_sensor_; } XiaomiSensor *XiaomiDevice::make_temperature_sensor(const std::string &name) { return this->temperature_sensor_ = new XiaomiSensor(this, XiaomiSensor::TYPE_TEMPERATURE, name); } @@ -910,4 +842,4 @@ XiaomiDevice::XiaomiDevice(ESP32BLETracker *parent, uint64_t address) : parent_( ESPHOME_NAMESPACE_END -#endif //USE_ESP32_BLE_TRACKER +#endif // USE_ESP32_BLE_TRACKER diff --git a/src/esphome/esp32_ble_tracker.h b/src/esphome/esp32_ble_tracker.h index f7c496fc..1d86e671 100644 --- a/src/esphome/esp32_ble_tracker.h +++ b/src/esphome/esp32_ble_tracker.h @@ -179,6 +179,7 @@ class XiaomiSensor : public sensor::Sensor { uint32_t update_interval() override; int8_t accuracy_decimals() override; std::string unique_id() override; + protected: XiaomiDevice *parent_; Type type_; @@ -258,7 +259,9 @@ class ESPBTDevice { const optional &get_service_data_uuid() const; protected: - esp_bd_addr_t address_{0, }; + esp_bd_addr_t address_{ + 0, + }; esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC}; int rssi_{0}; std::string name_{}; @@ -275,6 +278,6 @@ extern ESP32BLETracker *global_esp32_ble_tracker; ESPHOME_NAMESPACE_END -#endif //USE_ESP32_BLE_TRACKER +#endif // USE_ESP32_BLE_TRACKER -#endif //ESPHOME_ESP32_BLE_TRACKER_H +#endif // ESPHOME_ESP32_BLE_TRACKER_H diff --git a/src/esphome/esp_one_wire.cpp b/src/esphome/esp_one_wire.cpp index 12e0df48..1bc2b6f3 100644 --- a/src/esphome/esp_one_wire.cpp +++ b/src/esphome/esp_one_wire.cpp @@ -110,7 +110,7 @@ void ESPOneWire::reset_search() { this->last_discrepancy_ = 0; this->last_device_flag_ = false; this->last_family_discrepancy_ = 0; - this->rom_number = 0; + this->rom_number_ = 0; } uint64_t HOT ESPOneWire::search() { if (this->last_device_flag_) { @@ -178,7 +178,7 @@ uint64_t HOT ESPOneWire::search() { rom_byte_number++; rom_byte_mask = 1; } - } while (rom_byte_number < 8); // loop through all bytes + } while (rom_byte_number < 8); // loop through all bytes if (id_bit_number >= 65) { this->last_discrepancy_ = last_zero; @@ -194,7 +194,7 @@ uint64_t HOT ESPOneWire::search() { return 0u; } - return this->rom_number; + return this->rom_number_; } std::vector ESPOneWire::search_vec() { std::vector res; @@ -207,12 +207,12 @@ std::vector ESPOneWire::search_vec() { return res; } void ESPOneWire::skip() { - this->write8(0xCC); // skip ROM -} -GPIOPin *ESPOneWire::get_pin() { - return this->pin_; + this->write8(0xCC); // skip ROM } +GPIOPin *ESPOneWire::get_pin() { return this->pin_; } + +uint8_t *ESPOneWire::rom_number8_() { return reinterpret_cast(&this->rom_number_); } ESPHOME_NAMESPACE_END -#endif //USE_ONE_WIRE +#endif // USE_ONE_WIRE diff --git a/src/esphome/esp_one_wire.h b/src/esphome/esp_one_wire.h index 2d8ca3b6..9211c21e 100644 --- a/src/esphome/esp_one_wire.h +++ b/src/esphome/esp_one_wire.h @@ -68,18 +68,17 @@ class ESPOneWire { protected: /// Helper to get the internal 64-bit unsigned rom number as a 8-bit integer pointer. - inline uint8_t *rom_number8_() { return reinterpret_cast(&this->rom_number); } + inline uint8_t *rom_number8_(); GPIOPin *pin_; uint8_t last_discrepancy_{0}; uint8_t last_family_discrepancy_{0}; bool last_device_flag_{false}; - uint64_t rom_number{0}; - + uint64_t rom_number_{0}; }; ESPHOME_NAMESPACE_END -#endif //USE_ONE_WIRE +#endif // USE_ONE_WIRE -#endif //ESPHOME_ONE_WIRE_H +#endif // ESPHOME_ONE_WIRE_H diff --git a/src/esphome/esphal.cpp b/src/esphome/esphal.cpp index ba1c1bbb..5fcc67b8 100644 --- a/src/esphome/esphal.cpp +++ b/src/esphome/esphal.cpp @@ -4,77 +4,113 @@ #ifdef ARDUINO_ARCH_ESP8266 #include "FunctionalInterrupt.h" -extern "C" void ICACHE_RAM_ATTR __attachInterruptArg(uint8_t pin, void (*userFunc)(void*), void*fp , int mode); +extern "C" void ICACHE_RAM_ATTR __attachInterruptArg(uint8_t pin, void (*)(void*), void* fp, // NOLINT + int mode); #endif ESPHOME_NAMESPACE_BEGIN -static const char *TAG = "esphal"; +static const char* TAG = "esphal"; GPIOPin::GPIOPin(uint8_t pin, uint8_t mode, bool inverted) - : pin_(pin), mode_(mode), inverted_(inverted), + : pin_(pin), + mode_(mode), + inverted_(inverted), #ifdef ARDUINO_ARCH_ESP8266 - gpio_read_(pin < 16 ? &GPI : &GP16I), - gpio_mask_(pin < 16 ? (1UL << pin) : 1) + gpio_read_(pin < 16 ? &GPI : &GP16I), + gpio_mask_(pin < 16 ? (1UL << pin) : 1) #endif #ifdef ARDUINO_ARCH_ESP32 - gpio_set_(pin < 32 ? &GPIO.out_w1ts : &GPIO.out1_w1ts.val), - gpio_clear_(pin < 32 ? &GPIO.out_w1tc : &GPIO.out1_w1tc.val), - gpio_read_(pin < 32 ? &GPIO.in : &GPIO.in1.val), - gpio_mask_(pin < 32 ? (1UL << pin) : (1UL << (pin - 32))) + gpio_set_(pin < 32 ? &GPIO.out_w1ts : &GPIO.out1_w1ts.val), + gpio_clear_(pin < 32 ? &GPIO.out_w1tc : &GPIO.out1_w1tc.val), + gpio_read_(pin < 32 ? &GPIO.in : &GPIO.in1.val), + gpio_mask_(pin < 32 ? (1UL << pin) : (1UL << (pin - 32))) #endif - { - +{ } -const char *GPIOPin::get_pin_mode_name() const { - const char *mode_s; +const char* GPIOPin::get_pin_mode_name() const { + const char* mode_s; switch (this->mode_) { - case INPUT: mode_s = "INPUT"; break; - case OUTPUT: mode_s = "OUTPUT"; break; - case INPUT_PULLUP: mode_s = "INPUT_PULLUP"; break; - case OUTPUT_OPEN_DRAIN: mode_s = "OUTPUT_OPEN_DRAIN"; break; - case SPECIAL: mode_s = "SPECIAL"; break; - case FUNCTION_1: mode_s = "FUNCTION_1"; break; - case FUNCTION_2: mode_s = "FUNCTION_2"; break; - case FUNCTION_3: mode_s = "FUNCTION_3"; break; - case FUNCTION_4: mode_s = "FUNCTION_4"; break; + case INPUT: + mode_s = "INPUT"; + break; + case OUTPUT: + mode_s = "OUTPUT"; + break; + case INPUT_PULLUP: + mode_s = "INPUT_PULLUP"; + break; + case OUTPUT_OPEN_DRAIN: + mode_s = "OUTPUT_OPEN_DRAIN"; + break; + case SPECIAL: + mode_s = "SPECIAL"; + break; + case FUNCTION_1: + mode_s = "FUNCTION_1"; + break; + case FUNCTION_2: + mode_s = "FUNCTION_2"; + break; + case FUNCTION_3: + mode_s = "FUNCTION_3"; + break; + case FUNCTION_4: + mode_s = "FUNCTION_4"; + break; #ifdef ARDUINO_ARCH_ESP32 - case PULLUP: mode_s = "PULLUP"; break; - case PULLDOWN: mode_s = "PULLDOWN"; break; - case INPUT_PULLDOWN: mode_s = "INPUT_PULLDOWN"; break; - case OPEN_DRAIN: mode_s = "OPEN_DRAIN"; break; - case FUNCTION_5: mode_s = "FUNCTION_5"; break; - case FUNCTION_6: mode_s = "FUNCTION_6"; break; - case ANALOG: mode_s = "ANALOG"; break; + case PULLUP: + mode_s = "PULLUP"; + break; + case PULLDOWN: + mode_s = "PULLDOWN"; + break; + case INPUT_PULLDOWN: + mode_s = "INPUT_PULLDOWN"; + break; + case OPEN_DRAIN: + mode_s = "OPEN_DRAIN"; + break; + case FUNCTION_5: + mode_s = "FUNCTION_5"; + break; + case FUNCTION_6: + mode_s = "FUNCTION_6"; + break; + case ANALOG: + mode_s = "ANALOG"; + break; #endif #ifdef ARDUINO_ARCH_ESP8266 - case FUNCTION_0: mode_s = "FUNCTION_0"; break; - case WAKEUP_PULLUP: mode_s = "WAKEUP_PULLUP"; break; - case WAKEUP_PULLDOWN: mode_s = "WAKEUP_PULLDOWN"; break; - case INPUT_PULLDOWN_16: mode_s = "INPUT_PULLDOWN_16"; break; + case FUNCTION_0: + mode_s = "FUNCTION_0"; + break; + case WAKEUP_PULLUP: + mode_s = "WAKEUP_PULLUP"; + break; + case WAKEUP_PULLDOWN: + mode_s = "WAKEUP_PULLDOWN"; + break; + case INPUT_PULLDOWN_16: + mode_s = "INPUT_PULLDOWN_16"; + break; #endif - default: mode_s = "UNKNOWN"; break; + default: + mode_s = "UNKNOWN"; + break; } return mode_s; } -unsigned char GPIOPin::get_pin() const { - return this->pin_; -} -unsigned char GPIOPin::get_mode() const { - return this->mode_; -} +unsigned char GPIOPin::get_pin() const { return this->pin_; } +unsigned char GPIOPin::get_mode() const { return this->mode_; } -bool GPIOPin::is_inverted() const { - return this->inverted_; -} -void GPIOPin::setup() { - this->pin_mode(this->mode_); -} +bool GPIOPin::is_inverted() const { return this->inverted_; } +void GPIOPin::setup() { this->pin_mode(this->mode_); } bool ICACHE_RAM_ATTR HOT GPIOPin::digital_read() { return bool((*this->gpio_read_) & this->gpio_mask_) != this->inverted_; } @@ -102,23 +138,19 @@ void ICACHE_RAM_ATTR HOT GPIOPin::digital_write(bool value) { } #endif } -GPIOPin *GPIOPin::copy() const { return new GPIOPin(*this); } +GPIOPin* GPIOPin::copy() const { return new GPIOPin(*this); } -void ICACHE_RAM_ATTR HOT GPIOPin::pin_mode(uint8_t mode) { - pinMode(this->pin_, mode); -} +void ICACHE_RAM_ATTR HOT GPIOPin::pin_mode(uint8_t mode) { pinMode(this->pin_, mode); } -GPIOOutputPin::GPIOOutputPin(uint8_t pin, uint8_t mode, bool inverted) - : GPIOPin(pin, mode, inverted) {} +GPIOOutputPin::GPIOOutputPin(uint8_t pin, uint8_t mode, bool inverted) : GPIOPin(pin, mode, inverted) {} -GPIOInputPin::GPIOInputPin(uint8_t pin, uint8_t mode, bool inverted) - : GPIOPin(pin, mode, inverted) {} +GPIOInputPin::GPIOInputPin(uint8_t pin, uint8_t mode, bool inverted) : GPIOPin(pin, mode, inverted) {} #ifdef ARDUINO_ARCH_ESP8266 void ICACHE_RAM_ATTR custom_interrupt_functional(void* arg) { - ArgStructure* localArg = (ArgStructure*)arg; - if (localArg->functionInfo->reqFunction) { - localArg->functionInfo->reqFunction(); + ArgStructure* local_arg = (ArgStructure*) arg; + if (local_arg->functionInfo->reqFunction) { + local_arg->functionInfo->reqFunction(); } } diff --git a/src/esphome/esphal.h b/src/esphome/esphal.h index 184af2c6..e95e6f7c 100644 --- a/src/esphome/esphal.h +++ b/src/esphome/esphal.h @@ -2,27 +2,30 @@ #define ESPHOME_ESPHAL_H #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #ifdef ARDUINO_ARCH_ESP8266 - #include "Arduino.h" +#include "Arduino.h" #endif #include "esphome/espmath.h" #include "esphome/defines.h" #ifdef bool - #undef bool +#undef bool #endif #ifdef true - #undef true +#undef true #endif #ifdef false - #undef false +#undef false #endif ESPHOME_NAMESPACE_BEGIN -#define LOG_PIN(prefix, pin) if (pin != nullptr) {ESP_LOGCONFIG(TAG, prefix LOG_PIN_PATTERN, LOG_PIN_ARGS(pin));} +#define LOG_PIN(prefix, pin) \ + if ((pin) != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix LOG_PIN_PATTERN, LOG_PIN_ARGS(pin)); \ + } #define LOG_PIN_PATTERN "GPIO%u (Mode: %s%s)" #define LOG_PIN_ARGS(pin) (pin)->get_pin(), (pin)->get_pin_mode_name(), ((pin)->is_inverted() ? ", INVERTED" : "") @@ -86,7 +89,7 @@ void attach_functional_interrupt(uint8_t pin, std::function func, int mo */ class GPIOOutputPin : public GPIOPin { public: - GPIOOutputPin(uint8_t pin, uint8_t mode = OUTPUT, bool inverted = false); // NOLINT + GPIOOutputPin(uint8_t pin, uint8_t mode = OUTPUT, bool inverted = false); // NOLINT }; /** Basically just a GPIOPin, but defaults to INPUT pinMode. @@ -97,9 +100,9 @@ class GPIOOutputPin : public GPIOPin { */ class GPIOInputPin : public GPIOPin { public: - GPIOInputPin(uint8_t pin, uint8_t mode = INPUT, bool inverted = false); // NOLINT + GPIOInputPin(uint8_t pin, uint8_t mode = INPUT, bool inverted = false); // NOLINT }; ESPHOME_NAMESPACE_END -#endif //ESPHOME_ESPHAL_H +#endif // ESPHOME_ESPHAL_H diff --git a/src/esphome/espmath.h b/src/esphome/espmath.h index 8a208833..3f5590c2 100644 --- a/src/esphome/espmath.h +++ b/src/esphome/espmath.h @@ -19,6 +19,6 @@ #undef max #endif -#include "math.h" +#include "math.h" // NOLINT -#endif //ESPHOME_ESPMATH_H +#endif // ESPHOME_ESPMATH_H diff --git a/src/esphome/esppreferences.cpp b/src/esphome/esppreferences.cpp index 4873fe8e..9b75d434 100644 --- a/src/esphome/esppreferences.cpp +++ b/src/esphome/esppreferences.cpp @@ -7,7 +7,7 @@ #ifdef USE_ESP8266_PREFERENCES_FLASH extern "C" { - #include "spi_flash.h" +#include "spi_flash.h" } #endif @@ -15,10 +15,7 @@ ESPHOME_NAMESPACE_BEGIN static const char *TAG = "preferences"; -ESPPreferenceObject::ESPPreferenceObject() - : rtc_offset_(0), length_words_(0), type_(0), data_(nullptr) { - -} +ESPPreferenceObject::ESPPreferenceObject() : rtc_offset_(0), length_words_(0), type_(0), data_(nullptr) {} ESPPreferenceObject::ESPPreferenceObject(size_t rtc_offset, size_t length, uint32_t type) : rtc_offset_(rtc_offset), length_words_(length), type_(type) { this->data_ = new uint32_t[this->length_words_ + 1]; @@ -35,9 +32,8 @@ bool ESPPreferenceObject::load_() { bool valid = this->data_[this->length_words_] == this->calculate_crc_(); - ESP_LOGVV(TAG, "LOAD %u: valid=%s, 0=0x%08X 1=0x%08X (Type=%u, CRC=0x%08X)", - this->rtc_offset_, YESNO(valid), this->data_[0], this->data_[1], - this->type_, this->calculate_crc_()); + ESP_LOGVV(TAG, "LOAD %u: valid=%s, 0=0x%08X 1=0x%08X (Type=%u, CRC=0x%08X)", this->rtc_offset_, YESNO(valid), + this->data_[0], this->data_[1], this->type_, this->calculate_crc_()); return valid; } bool ESPPreferenceObject::save_() { @@ -49,8 +45,7 @@ bool ESPPreferenceObject::save_() { this->data_[this->length_words_] = this->calculate_crc_(); if (!this->save_internal_()) return false; - ESP_LOGVV(TAG, "SAVE %u: 0=0x%08X 1=0x%08X (Type=%u, CRC=0x%08X)", - this->rtc_offset_, this->data_[0], this->data_[1], + ESP_LOGVV(TAG, "SAVE %u: 0=0x%08X 1=0x%08X (Type=%u, CRC=0x%08X)", this->rtc_offset_, this->data_[0], this->data_[1], this->type_, this->calculate_crc_()); return true; } @@ -96,9 +91,7 @@ static inline bool esp_rtc_user_mem_write(uint32_t index, uint32_t value) { #ifdef USE_ESP8266_PREFERENCES_FLASH extern "C" uint32_t _SPIFFS_end; -static const uint32_t get_esp8266_flash_sector() { - return (uint32_t(&_SPIFFS_end) - 0x40200000) / SPI_FLASH_SEC_SIZE; -} +static const uint32_t get_esp8266_flash_sector() { return (uint32_t(&_SPIFFS_end) - 0x40200000) / SPI_FLASH_SEC_SIZE; } static const uint32_t get_esp8266_flash_address() { return get_esp8266_flash_sector() * SPI_FLASH_SEC_SIZE; } static void load_esp8266_flash() { @@ -150,12 +143,10 @@ bool ESPPreferenceObject::load_internal_() { return true; } ESPPreferences::ESPPreferences() - // offset starts from start of user RTC mem (64 words before that are reserved for system), - // an additional 32 words at the start of user RTC are for eboot (OTA, see eboot_command.h), - // which will be reset each time OTA occurs - : current_offset_(0) { - -} + // offset starts from start of user RTC mem (64 words before that are reserved for system), + // an additional 32 words at the start of user RTC are for eboot (OTA, see eboot_command.h), + // which will be reset each time OTA occurs + : current_offset_(0) {} void ESPPreferences::begin(const std::string &name) { #ifdef USE_ESP8266_PREFERENCES_FLASH @@ -192,12 +183,8 @@ ESPPreferenceObject ESPPreferences::make_preference(size_t length, uint32_t type this->current_offset_ += length + 1; return pref; } -void ESPPreferences::prevent_write(bool prevent) { - this->prevent_write_ = prevent; -} -bool ESPPreferences::is_prevent_write() { - return this->prevent_write_; -} +void ESPPreferences::prevent_write(bool prevent) { this->prevent_write_ = prevent; } +bool ESPPreferences::is_prevent_write() { return this->prevent_write_; } #endif #ifdef ARDUINO_ARCH_ESP32 @@ -223,10 +210,7 @@ bool ESPPreferenceObject::load_internal_() { } return true; } -ESPPreferences::ESPPreferences() - : current_offset_(0) { - -} +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()); @@ -246,9 +230,7 @@ uint32_t ESPPreferenceObject::calculate_crc_() const { } return crc; } -bool ESPPreferenceObject::is_initialized() const { - return this->data_ != nullptr; -} +bool ESPPreferenceObject::is_initialized() const { return this->data_ != nullptr; } ESPPreferences global_preferences; diff --git a/src/esphome/esppreferences.h b/src/esphome/esppreferences.h index 0cb3e7ea..a4ad4762 100644 --- a/src/esphome/esppreferences.h +++ b/src/esphome/esppreferences.h @@ -4,7 +4,7 @@ #include #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #include "esphome/espmath.h" @@ -17,11 +17,9 @@ class ESPPreferenceObject { ESPPreferenceObject(); ESPPreferenceObject(size_t rtc_offset, size_t length, uint32_t type); - template - bool save(T *src); + template bool save(T *src); - template - bool load(T *dest); + template bool load(T *dest); bool is_initialized() const; @@ -44,8 +42,7 @@ class ESPPreferences { ESPPreferences(); void begin(const std::string &name); ESPPreferenceObject make_preference(size_t length, uint32_t type); - template - ESPPreferenceObject make_preference(uint32_t type); + template ESPPreferenceObject make_preference(uint32_t type); #ifdef ARDUINO_ARCH_ESP8266 /** On the ESP8266, we can't override the first 128 bytes during OTA uploads @@ -73,13 +70,11 @@ class ESPPreferences { extern ESPPreferences global_preferences; -template -ESPPreferenceObject ESPPreferences::make_preference(uint32_t type) { +template ESPPreferenceObject ESPPreferences::make_preference(uint32_t type) { return this->make_preference((sizeof(T) + 3) / 4, type); } -template -bool ESPPreferenceObject::save(T *src) { +template bool ESPPreferenceObject::save(T *src) { if (!this->is_initialized()) return false; memset(this->data_, 0, this->length_words_ * 4); @@ -87,8 +82,7 @@ bool ESPPreferenceObject::save(T *src) { return this->save_(); } -template -bool ESPPreferenceObject::load(T *dest) { +template bool ESPPreferenceObject::load(T *dest) { memset(this->data_, 0, this->length_words_ * 4); if (!this->load_()) return false; @@ -99,4 +93,4 @@ bool ESPPreferenceObject::load(T *dest) { ESPHOME_NAMESPACE_END -#endif //ESPHOME_ESPPREFERENCES_H +#endif // ESPHOME_ESPPREFERENCES_H diff --git a/src/esphome/ethernet_component.cpp b/src/esphome/ethernet_component.cpp index 4052aa9a..f45cbf5b 100644 --- a/src/esphome/ethernet_component.cpp +++ b/src/esphome/ethernet_component.cpp @@ -21,9 +21,7 @@ static const char *TAG = "ethernet"; EthernetComponent *global_eth_component; -EthernetComponent::EthernetComponent() { - global_eth_component = this; -} +EthernetComponent::EthernetComponent() { global_eth_component = this; } void EthernetComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up Ethernet..."); @@ -73,12 +71,8 @@ void EthernetComponent::dump_config() { ESP_LOGCONFIG(TAG, " MDIO Pin: %u", this->mdio_pin_); ESP_LOGCONFIG(TAG, " Type: %s", this->type_ == ETHERNET_TYPE_LAN8720 ? "LAN8720" : "TLK110"); } -float EthernetComponent::get_setup_priority() const { - return setup_priority::WIFI; -} -bool EthernetComponent::can_proceed() { - return this->is_connected(); -} +float EthernetComponent::get_setup_priority() const { return setup_priority::WIFI; } +bool EthernetComponent::can_proceed() { return this->is_connected(); } IPAddress EthernetComponent::get_ip_address() { tcpip_adapter_ip_info_t ip; tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_ETH, &ip); @@ -115,11 +109,11 @@ void EthernetComponent::on_wifi_event_(system_event_id_t event, system_event_inf } #define ESPHL_ERROR_CHECK(err, message) \ - if (err != ESP_OK) { \ - ESP_LOGE(TAG, message ": %d", err); \ - this->mark_failed(); \ - return; \ - } + if (err != ESP_OK) { \ + ESP_LOGE(TAG, message ": %d", err); \ + this->mark_failed(); \ + return; \ + } void EthernetComponent::start_connect_() { this->connect_begin_ = millis(); @@ -220,9 +214,7 @@ void EthernetComponent::eth_phy_power_enable_(bool enable) { delay(1); global_eth_component->orig_power_enable_fun_(enable); } -bool EthernetComponent::is_connected() { - return this->connected_ && this->last_connected_; -} +bool EthernetComponent::is_connected() { return this->connected_ && this->last_connected_; } void EthernetComponent::dump_connect_params_() { tcpip_adapter_ip_info_t ip; tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_ETH, &ip); @@ -237,43 +229,26 @@ void EthernetComponent::dump_connect_params_() { ESP_LOGCONFIG(TAG, " DNS2: %s", IPAddress(dns_ip.u_addr.ip4.addr).toString().c_str()); uint8_t mac[6]; esp_eth_get_mac(mac); - ESP_LOGCONFIG(TAG, " MAC Address: %02X:%02X:%02X:%02X:%02X:%02X", - mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + ESP_LOGCONFIG(TAG, " MAC Address: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); ESP_LOGCONFIG(TAG, " Is Full Duplex: %s", YESNO(this->eth_config.phy_get_duplex_mode())); ESP_LOGCONFIG(TAG, " Link Up: %s", YESNO(this->eth_config.phy_check_link())); ESP_LOGCONFIG(TAG, " Link Speed: %u", this->eth_config.phy_get_speed_mode() ? 100 : 10); } -void EthernetComponent::set_phy_addr(uint8_t phy_addr) { - this->phy_addr_ = phy_addr; -} -void EthernetComponent::set_power_pin(const GPIOOutputPin &power_pin) { - this->power_pin_ = power_pin.copy(); -} -void EthernetComponent::set_mdc_pin(uint8_t mdc_pin) { - this->mdc_pin_ = mdc_pin; -} -void EthernetComponent::set_mdio_pin(uint8_t mdio_pin) { - this->mdio_pin_ = mdio_pin; -} -void EthernetComponent::set_type(EthernetType type) { - this->type_ = type; -} -void EthernetComponent::set_clk_mode(eth_clock_mode_t clk_mode) { - this->clk_mode_ = clk_mode; -} -void EthernetComponent::set_manual_ip(ManualIP manual_ip) { - this->manual_ip_ = manual_ip; -} +void EthernetComponent::set_phy_addr(uint8_t phy_addr) { this->phy_addr_ = phy_addr; } +void EthernetComponent::set_power_pin(const GPIOOutputPin &power_pin) { this->power_pin_ = power_pin.copy(); } +void EthernetComponent::set_mdc_pin(uint8_t mdc_pin) { this->mdc_pin_ = mdc_pin; } +void EthernetComponent::set_mdio_pin(uint8_t mdio_pin) { this->mdio_pin_ = mdio_pin; } +void EthernetComponent::set_type(EthernetType type) { this->type_ = type; } +void EthernetComponent::set_clk_mode(eth_clock_mode_t clk_mode) { this->clk_mode_ = clk_mode; } +void EthernetComponent::set_manual_ip(ManualIP manual_ip) { this->manual_ip_ = manual_ip; } std::string EthernetComponent::get_use_address() const { if (this->use_address_.empty()) { return get_app_name() + ".local"; } return this->use_address_; } -void EthernetComponent::set_use_address(const std::string &use_address) { - this->use_address_ = use_address; -} +void EthernetComponent::set_use_address(const std::string &use_address) { this->use_address_ = use_address; } ESPHOME_NAMESPACE_END -#endif //USE_ETHERNET +#endif // USE_ETHERNET diff --git a/src/esphome/ethernet_component.h b/src/esphome/ethernet_component.h index 36b4ca15..6861dd6f 100644 --- a/src/esphome/ethernet_component.h +++ b/src/esphome/ethernet_component.h @@ -67,6 +67,6 @@ extern EthernetComponent *global_eth_component; ESPHOME_NAMESPACE_END -#endif //USE_ETHERNET +#endif // USE_ETHERNET -#endif //ESPHOME_ETHERNET_COMPONENT_H +#endif // ESPHOME_ETHERNET_COMPONENT_H diff --git a/src/esphome/fan/basic_fan_component.cpp b/src/esphome/fan/basic_fan_component.cpp index b16b0127..c067deab 100644 --- a/src/esphome/fan/basic_fan_component.cpp +++ b/src/esphome/fan/basic_fan_component.cpp @@ -11,9 +11,7 @@ namespace fan { static const char *TAG = "fan.basic_fan"; -void BasicFanComponent::set_binary(output::BinaryOutput *output) { - this->binary_output_ = output; -} +void BasicFanComponent::set_binary(output::BinaryOutput *output) { this->binary_output_ = output; } void BasicFanComponent::set_speed(output::FloatOutput *output, float low_speed, float medium_speed, float high_speed) { FanTraits traits = this->state_->get_traits(); traits.set_speed(true); @@ -31,12 +29,8 @@ void BasicFanComponent::set_oscillation(output::BinaryOutput *oscillating_output this->oscillating_output_ = oscillating_output; } -FanState *BasicFanComponent::get_state() const { - return this->state_; -} -void BasicFanComponent::set_state(FanState *state) { - this->state_ = state; -} +FanState *BasicFanComponent::get_state() const { return this->state_; } +void BasicFanComponent::set_state(FanState *state) { this->state_ = state; } void BasicFanComponent::setup() { this->state_->add_on_state_callback([this]() { this->next_update_ = true; }); } @@ -47,8 +41,8 @@ void BasicFanComponent::dump_config() { } if (this->state_->get_traits().supports_speed()) { ESP_LOGCONFIG(TAG, " Mode: Speed"); - ESP_LOGCONFIG(TAG, " Speeds: Low=%.0f%% Medium=%.0f%% High=%.0f%%", - this->low_speed_ * 100.0f, this->medium_speed_ * 100.0f, this->high_speed_ * 100.0f); + ESP_LOGCONFIG(TAG, " Speeds: Low=%.0f%% Medium=%.0f%% High=%.0f%%", this->low_speed_ * 100.0f, + this->medium_speed_ * 100.0f, this->high_speed_ * 100.0f); } else { ESP_LOGCONFIG(TAG, " Mode: Binary"); } @@ -91,12 +85,10 @@ void BasicFanComponent::loop() { ESP_LOGD(TAG, "Setting oscillation: %d", int(enable)); } } -float BasicFanComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float BasicFanComponent::get_setup_priority() const { return setup_priority::HARDWARE; } -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_FAN +#endif // USE_FAN diff --git a/src/esphome/fan/basic_fan_component.h b/src/esphome/fan/basic_fan_component.h index 582aa2aa..e112f401 100644 --- a/src/esphome/fan/basic_fan_component.h +++ b/src/esphome/fan/basic_fan_component.h @@ -30,7 +30,8 @@ class BasicFanComponent : public Component { * @param medium_speed The speed that should be sent to the output if the fan is in MEDIUM speed mode. * @param high_speed The speed that should be sent to the output if the fan is in HIGH speed mode. */ - void set_speed(output::FloatOutput *output, float low_speed = 0.33, float medium_speed = 0.66, float high_speed = 1.0); + void set_speed(output::FloatOutput *output, float low_speed = 0.33, float medium_speed = 0.66, + float high_speed = 1.0); /** Set an oscillation output for this fan. * @@ -59,10 +60,10 @@ class BasicFanComponent : public Component { bool next_update_{true}; }; -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_FAN +#endif // USE_FAN -#endif //ESPHOME_FAN_BASIC_FAN_COMPONENT_H +#endif // ESPHOME_FAN_BASIC_FAN_COMPONENT_H diff --git a/src/esphome/fan/fan_state.cpp b/src/esphome/fan/fan_state.cpp index 980ac7eb..c0c9fa89 100644 --- a/src/esphome/fan/fan_state.cpp +++ b/src/esphome/fan/fan_state.cpp @@ -12,29 +12,17 @@ namespace fan { static const char *TAG = "fan.state"; -const FanTraits &FanState::get_traits() const { - return this->traits_; -} -void FanState::set_traits(const FanTraits &traits) { - this->traits_ = traits; -} +const FanTraits &FanState::get_traits() const { return this->traits_; } +void FanState::set_traits(const FanTraits &traits) { this->traits_ = traits; } void FanState::add_on_state_callback(std::function &&callback) { this->state_callback_.add(std::move(callback)); } FanState::FanState(const std::string &name) : Nameable(name) {} -FanState::StateCall FanState::turn_on() { - return this->make_call().set_state(true); -} -FanState::StateCall FanState::turn_off() { - return this->make_call().set_state(false); -} -FanState::StateCall FanState::toggle() { - return this->make_call().set_state(!this->state); -} -FanState::StateCall FanState::make_call() { - return FanState::StateCall(this); -} +FanState::StateCall FanState::turn_on() { return this->make_call().set_state(true); } +FanState::StateCall FanState::turn_off() { return this->make_call().set_state(false); } +FanState::StateCall FanState::toggle() { return this->make_call().set_state(!this->state); } +FanState::StateCall FanState::make_call() { return FanState::StateCall(this); } struct FanStateRTCState { bool state; @@ -54,25 +42,14 @@ void FanState::setup() { call.set_oscillating(recovered.oscillating); call.perform(); } -float FanState::get_setup_priority() const { - return setup_priority::HARDWARE - 1.0f; -} -uint32_t FanState::hash_base_() { - return 418001110UL; -} +float FanState::get_setup_priority() const { return setup_priority::HARDWARE - 1.0f; } +uint32_t FanState::hash_base() { return 418001110UL; } #ifdef USE_MQTT_FAN -MQTTFanComponent *FanState::get_mqtt() const { - return this->mqtt_; -} -void FanState::set_mqtt(MQTTFanComponent *mqtt) { - this->mqtt_ = mqtt; -} +MQTTFanComponent *FanState::get_mqtt() const { return this->mqtt_; } +void FanState::set_mqtt(MQTTFanComponent *mqtt) { this->mqtt_ = mqtt; } #endif -FanState::StateCall::StateCall(FanState *state) - : state_(state) { - -} +FanState::StateCall::StateCall(FanState *state) : state_(state) {} FanState::StateCall &FanState::StateCall::set_state(bool state) { this->binary_state_ = state; return *this; @@ -115,7 +92,6 @@ void FanState::StateCall::perform() const { // protect from invalid input break; } - } FanStateRTCState saved; @@ -137,8 +113,8 @@ FanState::StateCall &FanState::StateCall::set_speed(const char *speed) { return *this; } -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_FAN +#endif // USE_FAN diff --git a/src/esphome/fan/fan_state.h b/src/esphome/fan/fan_state.h index 8ebcfd64..ace5c6b3 100644 --- a/src/esphome/fan/fan_state.h +++ b/src/esphome/fan/fan_state.h @@ -16,17 +16,14 @@ namespace fan { /// Simple enum to represent the speed of a fan. enum FanSpeed { - FAN_SPEED_LOW = 0, ///< The fan is running on low speed. - FAN_SPEED_MEDIUM = 1, ///< The fan is running on medium speed. - FAN_SPEED_HIGH = 2 ///< The fan is running on high/full speed. + FAN_SPEED_LOW = 0, ///< The fan is running on low speed. + FAN_SPEED_MEDIUM = 1, ///< The fan is running on medium speed. + FAN_SPEED_HIGH = 2 ///< The fan is running on high/full speed. }; -template -class TurnOnAction; -template -class TurnOffAction; -template -class ToggleAction; +template class TurnOnAction; +template class TurnOffAction; +template class ToggleAction; #ifdef USE_MQTT_FAN class MQTTFanComponent; @@ -52,12 +49,9 @@ class FanState : public Nameable, public Component { /// Set the traits of this fan (i.e. what features it supports). void set_traits(const FanTraits &traits); - template - TurnOnAction *make_turn_on_action(); - template - TurnOffAction *make_turn_off_action(); - template - ToggleAction *make_toggle_action(); + template TurnOnAction *make_turn_on_action(); + template TurnOffAction *make_turn_off_action(); + template ToggleAction *make_toggle_action(); /// The current ON/OFF state of the fan. bool state{false}; @@ -101,7 +95,7 @@ class FanState : public Nameable, public Component { #endif protected: - uint32_t hash_base_() override; + uint32_t hash_base() override; FanTraits traits_{}; CallbackManager state_callback_{}; @@ -111,56 +105,49 @@ class FanState : public Nameable, public Component { #endif }; -template -class TurnOnAction : public Action { +template class TurnOnAction : public Action { public: explicit TurnOnAction(FanState *state); - template - void set_oscillating(V value) { this->oscillating_ = value; } - template - void set_speed(V value) { this->speed_ = value; } + template void set_oscillating(V value) { this->oscillating_ = value; } + template void set_speed(V value) { this->speed_ = value; } void play(Ts... x) override; protected: FanState *state_; TemplatableValue oscillating_; - TemplatableValue speed_; + TemplatableValue speed_; }; -template -class TurnOffAction : public Action { +template class TurnOffAction : public Action { public: explicit TurnOffAction(FanState *state); void play(Ts... x) override; + protected: FanState *state_; }; -template -class ToggleAction : public Action { +template class ToggleAction : public Action { public: explicit ToggleAction(FanState *state); void play(Ts... x) override; + protected: FanState *state_; }; -template -ToggleAction::ToggleAction(FanState *state) : state_(state) { } -template -void ToggleAction::play(Ts... x) { +template ToggleAction::ToggleAction(FanState *state) : state_(state) {} +template void ToggleAction::play(Ts... x) { this->state_->toggle().perform(); this->play_next(x...); } -template -TurnOnAction::TurnOnAction(FanState *state) : state_(state) { } -template -void TurnOnAction::play(Ts... x) { +template TurnOnAction::TurnOnAction(FanState *state) : state_(state) {} +template void TurnOnAction::play(Ts... x) { auto call = this->state_->turn_on(); if (this->oscillating_.has_value()) { call.set_oscillating(this->oscillating_.value(x...)); @@ -172,35 +159,24 @@ void TurnOnAction::play(Ts... x) { this->play_next(x...); } -template -TurnOffAction::TurnOffAction(FanState *state) : state_(state) { - -} -template -void TurnOffAction::play(Ts... x) { +template TurnOffAction::TurnOffAction(FanState *state) : state_(state) {} +template void TurnOffAction::play(Ts... x) { this->state_->turn_off().perform(); this->play_next(x...); } -template -TurnOnAction *FanState::make_turn_on_action() { - return new TurnOnAction(this); -} -template -TurnOffAction *FanState::make_turn_off_action() { +template TurnOnAction *FanState::make_turn_on_action() { return new TurnOnAction(this); } +template TurnOffAction *FanState::make_turn_off_action() { return new TurnOffAction(this); } -template -ToggleAction *FanState::make_toggle_action() { - return new ToggleAction(this); -} +template ToggleAction *FanState::make_toggle_action() { return new ToggleAction(this); } -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END #include "esphome/fan/mqtt_fan_component.h" -#endif //USE_FAN +#endif // USE_FAN -#endif //ESPHOME_FAN_FAN_STATE_H +#endif // ESPHOME_FAN_FAN_STATE_H diff --git a/src/esphome/fan/fan_traits.cpp b/src/esphome/fan/fan_traits.cpp index 0448b55c..3b704cb1 100644 --- a/src/esphome/fan/fan_traits.cpp +++ b/src/esphome/fan/fan_traits.cpp @@ -8,26 +8,16 @@ ESPHOME_NAMESPACE_BEGIN namespace fan { -FanTraits::FanTraits() - : oscillation_(false), speed_(false) {} - -FanTraits::FanTraits(bool oscillation, bool speed) - : oscillation_(oscillation), speed_(speed) {} -bool FanTraits::supports_oscillation() const { - return this->oscillation_; -} -bool FanTraits::supports_speed() const { - return this->speed_; -} -void FanTraits::set_oscillation(bool oscillation) { - this->oscillation_ = oscillation; -} -void FanTraits::set_speed(bool speed) { - this->speed_ = speed; -} - -} // namespace fan +FanTraits::FanTraits() : oscillation_(false), speed_(false) {} + +FanTraits::FanTraits(bool oscillation, bool speed) : oscillation_(oscillation), speed_(speed) {} +bool FanTraits::supports_oscillation() const { return this->oscillation_; } +bool FanTraits::supports_speed() const { return this->speed_; } +void FanTraits::set_oscillation(bool oscillation) { this->oscillation_ = oscillation; } +void FanTraits::set_speed(bool speed) { this->speed_ = speed; } + +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_FAN +#endif // USE_FAN diff --git a/src/esphome/fan/fan_traits.h b/src/esphome/fan/fan_traits.h index 87484b92..a7669e57 100644 --- a/src/esphome/fan/fan_traits.h +++ b/src/esphome/fan/fan_traits.h @@ -31,10 +31,10 @@ class FanTraits { bool speed_; }; -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_FAN +#endif // USE_FAN -#endif //ESPHOME_FAN_FAN_TRAITS_H +#endif // ESPHOME_FAN_FAN_TRAITS_H diff --git a/src/esphome/fan/mqtt_fan_component.cpp b/src/esphome/fan/mqtt_fan_component.cpp index c26cbb48..049d2cc0 100644 --- a/src/esphome/fan/mqtt_fan_component.cpp +++ b/src/esphome/fan/mqtt_fan_component.cpp @@ -11,19 +11,12 @@ namespace fan { static const char *TAG = "fan.mqtt"; -MQTTFanComponent::MQTTFanComponent(FanState *state) - : MQTTComponent(), state_(state) { +MQTTFanComponent::MQTTFanComponent(FanState *state) : MQTTComponent(), state_(state) {} -} - -FanState *MQTTFanComponent::get_state() const { - return this->state_; -} -std::string MQTTFanComponent::component_type() const { - return "fan"; -} +FanState *MQTTFanComponent::get_state() const { return this->state_; } +std::string MQTTFanComponent::component_type() const { return "fan"; } void MQTTFanComponent::setup() { - this->subscribe(this->get_command_topic(), [this](const std::string &topic, const std::string &payload) { + this->subscribe(this->get_command_topic_(), [this](const std::string &topic, const std::string &payload) { auto val = parse_on_off(payload.c_str()); switch (val) { case PARSE_ON: @@ -47,26 +40,27 @@ void MQTTFanComponent::setup() { }); if (this->state_->get_traits().supports_oscillation()) { - this->subscribe(this->get_oscillation_command_topic(), [this](const std::string &topic, const std::string &payload) { - auto val = parse_on_off(payload.c_str(), "oscillate_on", "oscillate_off"); - switch (val) { - case PARSE_ON: - ESP_LOGD(TAG, "'%s': Setting oscillating ON", this->friendly_name().c_str()); - this->state_->make_call().set_oscillating(true).perform(); - break; - case PARSE_OFF: - ESP_LOGD(TAG, "'%s': Setting oscillating OFF", this->friendly_name().c_str()); - this->state_->make_call().set_oscillating(false).perform(); - break; - case PARSE_TOGGLE: - this->state_->make_call().set_oscillating(!this->state_->oscillating).perform(); - break; - case PARSE_NONE: - ESP_LOGW(TAG, "Unknown Oscillation Payload %s", payload.c_str()); - this->status_momentary_warning("oscillation", 5000); - break; - } - }); + this->subscribe(this->get_oscillation_command_topic(), + [this](const std::string &topic, const std::string &payload) { + auto val = parse_on_off(payload.c_str(), "oscillate_on", "oscillate_off"); + switch (val) { + case PARSE_ON: + ESP_LOGD(TAG, "'%s': Setting oscillating ON", this->friendly_name().c_str()); + this->state_->make_call().set_oscillating(true).perform(); + break; + case PARSE_OFF: + ESP_LOGD(TAG, "'%s': Setting oscillating OFF", this->friendly_name().c_str()); + this->state_->make_call().set_oscillating(false).perform(); + break; + case PARSE_TOGGLE: + this->state_->make_call().set_oscillating(!this->state_->oscillating).perform(); + break; + case PARSE_NONE: + ESP_LOGW(TAG, "Unknown Oscillation Payload %s", payload.c_str()); + this->status_momentary_warning("oscillation", 5000); + break; + } + }); } if (this->state_->get_traits().supports_speed()) { @@ -76,9 +70,7 @@ void MQTTFanComponent::setup() { } auto f = std::bind(&MQTTFanComponent::publish_state, this); - this->state_->add_on_state_callback([this, f]() { - this->defer("send", f); - }); + this->state_->add_on_state_callback([this, f]() { this->defer("send", f); }); } void MQTTFanComponent::set_custom_oscillation_command_topic(const std::string &topic) { this->custom_oscillation_command_topic_ = topic; @@ -94,30 +86,26 @@ void MQTTFanComponent::set_custom_speed_state_topic(const std::string &topic) { } const std::string MQTTFanComponent::get_oscillation_command_topic() const { if (this->custom_oscillation_command_topic_.empty()) - return this->get_default_topic_for("oscillation/command"); + return this->get_default_topic_for_("oscillation/command"); return this->custom_oscillation_command_topic_; } const std::string MQTTFanComponent::get_oscillation_state_topic() const { if (this->custom_oscillation_state_topic_.empty()) - return this->get_default_topic_for("oscillation/state"); + return this->get_default_topic_for_("oscillation/state"); return this->custom_oscillation_state_topic_; } const std::string MQTTFanComponent::get_speed_command_topic() const { if (this->custom_speed_command_topic_.empty()) - return this->get_default_topic_for("speed/command"); + return this->get_default_topic_for_("speed/command"); return this->custom_speed_command_topic_; } const std::string MQTTFanComponent::get_speed_state_topic() const { if (this->custom_speed_state_topic_.empty()) - return this->get_default_topic_for("speed/state"); + return this->get_default_topic_for_("speed/state"); return this->custom_speed_state_topic_; } -bool MQTTFanComponent::send_initial_state() { - return this->publish_state(); -} -std::string MQTTFanComponent::friendly_name() const { - return this->state_->get_name(); -} +bool MQTTFanComponent::send_initial_state() { return this->publish_state(); } +std::string MQTTFanComponent::friendly_name() const { return this->state_->get_name(); } void MQTTFanComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (this->state_->get_traits().supports_oscillation()) { root["oscillation_command_topic"] = this->get_oscillation_command_topic(); @@ -128,13 +116,11 @@ void MQTTFanComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfi root["speed_state_topic"] = this->get_speed_state_topic(); } } -bool MQTTFanComponent::is_internal() { - return this->state_->is_internal(); -} +bool MQTTFanComponent::is_internal() { return this->state_->is_internal(); } bool MQTTFanComponent::publish_state() { const char *state_s = this->state_->state ? "ON" : "OFF"; ESP_LOGD(TAG, "'%s' Sending state %s.", this->state_->get_name().c_str(), state_s); - this->publish(this->get_state_topic(), state_s); + this->publish(this->get_state_topic_(), state_s); bool failed = false; if (this->state_->get_traits().supports_oscillation()) { bool success = this->publish(this->get_oscillation_state_topic(), @@ -165,8 +151,8 @@ bool MQTTFanComponent::publish_state() { return !failed; } -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_MQTT_FAN +#endif // USE_MQTT_FAN diff --git a/src/esphome/fan/mqtt_fan_component.h b/src/esphome/fan/mqtt_fan_component.h index 86aeaf17..c1287045 100644 --- a/src/esphome/fan/mqtt_fan_component.h +++ b/src/esphome/fan/mqtt_fan_component.h @@ -56,10 +56,10 @@ class MQTTFanComponent : public mqtt::MQTTComponent { FanState *state_; }; -} // namespace fan +} // namespace fan ESPHOME_NAMESPACE_END -#endif //USE_MQTT_FAN +#endif // USE_MQTT_FAN -#endif //ESPHOME_FAN_MQTT_FAN_COMPONENT_H +#endif // ESPHOME_FAN_MQTT_FAN_COMPONENT_H diff --git a/src/esphome/helpers.cpp b/src/esphome/helpers.cpp index 9766135a..185b7f7d 100644 --- a/src/esphome/helpers.cpp +++ b/src/esphome/helpers.cpp @@ -2,9 +2,9 @@ #include #ifdef ARDUINO_ARCH_ESP8266 - #include +#include #else - #include +#include #endif #include "esphome/espmath.h" @@ -44,13 +44,9 @@ std::string get_mac_address_pretty() { return std::string(tmp); } -bool is_empty(const IPAddress &address) { - return address == IPAddress(0, 0, 0, 0); -} +bool is_empty(const IPAddress &address) { return address == IPAddress(0, 0, 0, 0); } -std::string generate_hostname(const std::string &base) { - return base + std::string("-") + get_mac_address(); -} +std::string generate_hostname(const std::string &base) { return base + std::string("-") + get_mac_address(); } uint32_t random_uint32() { #ifdef ARDUINO_ARCH_ESP32 @@ -60,19 +56,13 @@ uint32_t random_uint32() { #endif } -double random_double() { - return random_uint32() / double(UINT32_MAX); -} +double random_double() { return random_uint32() / double(UINT32_MAX); } -float random_float() { - return float(random_double()); -} +float random_float() { return float(random_double()); } static uint32_t fast_random_seed = 0; -void fast_random_set_seed(uint32_t seed) { - fast_random_seed = seed; -} +void fast_random_set_seed(uint32_t seed) { fast_random_seed = seed; } uint32_t fast_random_32() { fast_random_seed = (fast_random_seed * 2654435769ULL) + 40503ULL; return fast_random_seed; @@ -102,9 +92,9 @@ std::string to_lowercase_underscore(std::string s) { std::string sanitize_string_whitelist(const std::string &s, const std::string &whitelist) { std::string out(s); - out.erase(std::remove_if(out.begin(), out.end(), [&out, &whitelist](const char &c) { - return whitelist.find(c) == std::string::npos; - }), out.end()); + out.erase(std::remove_if(out.begin(), out.end(), + [&out, &whitelist](const char &c) { return whitelist.find(c) == std::string::npos; }), + out.end()); return out; } @@ -121,17 +111,11 @@ std::string truncate_string(const std::string &s, size_t length) { ExponentialMovingAverage::ExponentialMovingAverage(float alpha) : alpha_(alpha), accumulator_(0) {} -float ExponentialMovingAverage::get_alpha() const { - return this->alpha_; -} +float ExponentialMovingAverage::get_alpha() const { return this->alpha_; } -void ExponentialMovingAverage::set_alpha(float alpha) { - this->alpha_ = alpha; -} +void ExponentialMovingAverage::set_alpha(float alpha) { this->alpha_ = alpha; } -float ExponentialMovingAverage::calculate_average() { - return this->accumulator_; -} +float ExponentialMovingAverage::calculate_average() { return this->accumulator_; } float ExponentialMovingAverage::next_value(float value) { if (std::isnan(value)) { @@ -147,9 +131,7 @@ float ExponentialMovingAverage::next_value(float value) { return this->calculate_average(); } -SlidingWindowMovingAverage::SlidingWindowMovingAverage(size_t max_size) : max_size_(max_size), sum_(0) { - -} +SlidingWindowMovingAverage::SlidingWindowMovingAverage(size_t max_size) : max_size_(max_size), sum_(0) {} float SlidingWindowMovingAverage::next_value(float value) { if (std::isnan(value)) @@ -165,15 +147,13 @@ float SlidingWindowMovingAverage::next_value(float value) { } float SlidingWindowMovingAverage::calculate_average() { - if (this->queue_.size() == 0) + if (this->queue_.empty()) return 0; else return this->sum_ / this->queue_.size(); } -size_t SlidingWindowMovingAverage::get_max_size() const { - return this->max_size_; -} +size_t SlidingWindowMovingAverage::get_max_size() const { return this->max_size_; } void SlidingWindowMovingAverage::set_max_size(size_t max_size) { this->max_size_ = max_size; @@ -187,15 +167,14 @@ void SlidingWindowMovingAverage::set_max_size(size_t max_size) { std::string value_accuracy_to_string(float value, int8_t accuracy_decimals) { auto multiplier = float(pow10(accuracy_decimals)); float value_rounded = roundf(value * multiplier) / multiplier; - char tmp[32]; // should be enough, but we should maybe improve this at some point. + char tmp[32]; // should be enough, but we should maybe improve this at some point. dtostrf(value_rounded, 0, uint8_t(std::max(0, int(accuracy_decimals))), tmp); return std::string(tmp); } std::string uint64_to_string(uint64_t num) { char buffer[17]; auto *address16 = reinterpret_cast(&num); - snprintf(buffer, sizeof(buffer), "%04X%04X%04X%04X", - address16[3], address16[2], address16[1], address16[0]); + snprintf(buffer, sizeof(buffer), "%04X%04X%04X%04X", address16[3], address16[2], address16[1], address16[0]); return std::string(buffer); } std::string uint32_to_string(uint32_t num) { @@ -209,7 +188,7 @@ static size_t global_json_build_buffer_size = 0; void reserve_global_json_build_buffer(size_t required_size) { if (global_json_build_buffer_size == 0 || global_json_build_buffer_size < required_size) { - delete [] global_json_build_buffer; + delete[] global_json_build_buffer; global_json_build_buffer_size = std::max(required_size, global_json_build_buffer_size * 2); size_t remainder = global_json_build_buffer_size % 16U; @@ -282,9 +261,7 @@ void reboot(const char *cause) { yield(); } } -void add_shutdown_hook(std::function &&f) { - shutdown_hooks.add(std::move(f)); -} +void add_shutdown_hook(std::function &&f) { shutdown_hooks.add(std::move(f)); } void safe_reboot(const char *cause) { ESP_LOGI(TAG, "Rebooting safely... Reason: '%s'", cause); run_safe_shutdown_hooks(cause); @@ -294,13 +271,9 @@ void safe_reboot(const char *cause) { yield(); } } -void add_safe_shutdown_hook(std::function &&f) { - safe_shutdown_hooks.add(std::move(f)); -} +void add_safe_shutdown_hook(std::function &&f) { safe_shutdown_hooks.add(std::move(f)); } -void run_shutdown_hooks(const char *cause) { - shutdown_hooks.call(cause); -} +void run_shutdown_hooks(const char *cause) { shutdown_hooks.call(cause); } void run_safe_shutdown_hooks(const char *cause) { safe_shutdown_hooks.call(cause); @@ -356,7 +329,7 @@ rmt_channel_t next_rmt_channel = RMT_CHANNEL_0; rmt_channel_t select_next_rmt_channel() { rmt_channel_t value = next_rmt_channel; - next_rmt_channel = rmt_channel_t(int(next_rmt_channel) + 1); // NOLINT + next_rmt_channel = rmt_channel_t(int(next_rmt_channel) + 1); // NOLINT return value; } #endif @@ -374,21 +347,21 @@ uint16_t reverse_bits_16(uint16_t x) { void tick_status_led() { #ifdef USE_STATUS_LED if (global_status_led != nullptr) { - global_status_led->loop_(); + global_status_led->call_loop(); } #endif } void ICACHE_RAM_ATTR HOT feed_wdt() { - static uint32_t last_feed = 0; + static uint32_t LAST_FEED = 0; uint32_t now = millis(); - if (now - last_feed > 3) { + if (now - LAST_FEED > 3) { #ifdef ARDUINO_ARCH_ESP8266 ESP.wdtFeed(); #endif #ifdef ARDUINO_ARCH_ESP32 yield(); #endif - last_feed = now; + LAST_FEED = now; } } std::string build_json(const json_build_t &f) { @@ -396,12 +369,8 @@ std::string build_json(const json_build_t &f) { const char *c_str = build_json(f, &len); return std::string(c_str, len); } -std::string to_string(std::string val) { - return val; -} -std::string to_string(String val) { - return val.c_str(); -} +std::string to_string(std::string val) { return val; } +std::string to_string(String val) { return val.c_str(); } std::string to_string(int val) { char buf[64]; sprintf(buf, "%d", val); @@ -463,17 +432,13 @@ uint32_t fnv1_hash(const std::string &str) { return hash; } -template -uint32_t reverse_bits(uint32_t x) { +template uint32_t reverse_bits(uint32_t x) { return uint32_t(reverse_bits_16(x & 0xFFFF) << 16) | uint32_t(reverse_bits_16(x >> 16)); } -VectorJsonBuffer::String::String(VectorJsonBuffer *parent) - : parent_(parent), start_(parent->size_) { - -} +VectorJsonBuffer::String::String(VectorJsonBuffer *parent) : parent_(parent), start_(parent->size_) {} void VectorJsonBuffer::String::append(char c) const { - char* last = static_cast(this->parent_->do_alloc(1)); + char *last = static_cast(this->parent_->do_alloc(1)); *last = c; } const char *VectorJsonBuffer::String::c_str() const { @@ -482,26 +447,24 @@ const char *VectorJsonBuffer::String::c_str() const { } void VectorJsonBuffer::clear() { for (char *block : this->free_blocks_) - free(block); + free(block); // NOLINT this->size_ = 0; this->free_blocks_.clear(); } -VectorJsonBuffer::String VectorJsonBuffer::startString() { - return {this}; -} +VectorJsonBuffer::String VectorJsonBuffer::startString() { return {this}; } // NOLINT void *VectorJsonBuffer::alloc(size_t bytes) { // Make sure memory addresses are aligned uint32_t new_size = round_size_up(this->size_); this->resize(new_size); return this->do_alloc(bytes); } -void *VectorJsonBuffer::do_alloc(size_t bytes) { +void *VectorJsonBuffer::do_alloc(size_t bytes) { // NOLINT const uint32_t begin = this->size_; this->resize(begin + bytes); return &this->buffer_[begin]; } -void VectorJsonBuffer::resize(size_t size) { +void VectorJsonBuffer::resize(size_t size) { // NOLINT if (size <= this->size_) { this->size_ = size; return; @@ -510,7 +473,7 @@ void VectorJsonBuffer::resize(size_t size) { this->reserve(size); this->size_ = size; } -void VectorJsonBuffer::reserve(size_t size) { +void VectorJsonBuffer::reserve(size_t size) { // NOLINT if (size <= this->capacity_) return; @@ -531,9 +494,7 @@ void VectorJsonBuffer::reserve(size_t size) { this->capacity_ = target_capacity; } -size_t VectorJsonBuffer::size() const { - return this->size_; -} +size_t VectorJsonBuffer::size() const { return this->size_; } VectorJsonBuffer global_json_buffer; @@ -551,8 +512,6 @@ void HighFrequencyLoopRequester::stop() { high_freq_num_requests--; this->started_ = false; } -bool HighFrequencyLoopRequester::is_high_frequency() { - return high_freq_num_requests > 0; -} +bool HighFrequencyLoopRequester::is_high_frequency() { return high_freq_num_requests > 0; } ESPHOME_NAMESPACE_END diff --git a/src/esphome/helpers.h b/src/esphome/helpers.h index b33966c9..4fdcd6cd 100644 --- a/src/esphome/helpers.h +++ b/src/esphome/helpers.h @@ -13,11 +13,18 @@ #include "esphome/optional.h" #ifndef JSON_BUFFER_SIZE - #define JSON_BUFFER_SIZE (JSON_OBJECT_SIZE(16)) +#define JSON_BUFFER_SIZE (JSON_OBJECT_SIZE(16)) #endif #ifdef ARDUINO_ARCH_ESP32 - #include +#include +#endif + +#ifdef CLANG_TIDY +#undef ICACHE_RAM_ATTR +#define ICACHE_RAM_ATTR +#undef ICACHE_RODATA_ATTR +#define ICACHE_RODATA_ATTR #endif ESPHOME_NAMESPACE_BEGIN @@ -66,13 +73,13 @@ std::string truncate_string(const std::string &s, size_t length); bool is_empty(const IPAddress &address); /// Force a shutdown (and reboot) of the ESP, calling any registered shutdown hooks. -void reboot(const char *cause) __attribute__ ((noreturn)); +void reboot(const char *cause) __attribute__((noreturn)); /// Add a shutdown callback. void add_shutdown_hook(std::function &&f); /// Create a safe shutdown (and reboot) of the ESP, calling any registered shutdown and safe shutdown hooks. -void safe_reboot(const char *cause) __attribute__ ((noreturn)); +void safe_reboot(const char *cause) __attribute__((noreturn)); /// Run shutdown hooks. void run_shutdown_hooks(const char *cause); @@ -100,6 +107,7 @@ class HighFrequencyLoopRequester { void stop(); static bool is_high_frequency(); + protected: bool started_{false}; }; @@ -112,8 +120,7 @@ class HighFrequencyLoopRequester { * @param val The value. * @return val clamped in between min and max. */ -template -T clamp(T min, T max, T val); +template T clamp(T min, T max, T val); /** Linearly interpolate between end start and end by completion. * @@ -123,12 +130,10 @@ T clamp(T min, T max, T val); * @param completion The completion. 0 is start value, 1 is end value. * @return The linearly interpolated value. */ -template -T lerp(T start, T end, T completion); +template T lerp(T start, T end, T completion); /// std::make_unique -template -std::unique_ptr make_unique(Args &&...args); +template std::unique_ptr make_unique(Args &&... args); /// Return a random 32 bit unsigned integer. uint32_t random_uint32(); @@ -236,20 +241,17 @@ class ExponentialMovingAverage { }; // https://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer/7858971#7858971 -template struct seq {}; -template struct gens : gens {}; -template struct gens<0, S...>{ typedef seq type; }; - +template struct seq {}; // NOLINT +template struct gens : gens {}; // NOLINT +template struct gens<0, S...> { using type = seq; }; // NOLINT template class CallbackManager; - /** Simple helper class to allow having multiple subscribers to a signal. * * @tparam Ts The arguments for the callback, wrapped in void(). */ -template -class CallbackManager { +template class CallbackManager { public: /// Add a callback to the internal callback list. void add(std::function &&callback); @@ -262,49 +264,36 @@ class CallbackManager { }; // https://stackoverflow.com/a/37161919/8924614 -template -struct is_callable +template +struct is_callable // NOLINT { - template static auto test(U*p) -> decltype((*p)(std::declval()...), void(), std::true_type()); + template static auto test(U *p) -> decltype((*p)(std::declval()...), void(), std::true_type()); template static auto test(...) -> decltype(std::false_type()); - static constexpr auto value = decltype(test(nullptr))::value; + static constexpr auto value = decltype(test(nullptr))::value; // NOLINT }; -template -using enable_if_t = typename std::enable_if::type; +template using enable_if_t = typename std::enable_if::type; -template -class TemplatableValue { +template class TemplatableValue { public: - TemplatableValue() : type_(EMPTY) { - - } + TemplatableValue() : type_(EMPTY) {} - template ::value, int> = 0> - TemplatableValue(F value) : type_(VALUE), value_(value) { + template::value, int> = 0> + TemplatableValue(F value) : type_(VALUE), value_(value) {} - } + template::value, int> = 0> + TemplatableValue(F f) : type_(LAMBDA), f_(f) {} - template ::value, int> = 0> - TemplatableValue(F f) : type_(LAMBDA), f_(f) { - - } - - bool has_value() { - return this->type_ != EMPTY; - } + bool has_value() { return this->type_ != EMPTY; } T value(X... x) { if (this->type_ == LAMBDA) { return this->f_(x...); - } else { - // return value also when empty - return this->value_; } + // return value also when empty + return this->value_; } protected: @@ -322,9 +311,9 @@ extern CallbackManager shutdown_hooks; extern CallbackManager safe_shutdown_hooks; #ifdef ARDUINO_ARCH_ESP32 - extern rmt_channel_t next_rmt_channel; +extern rmt_channel_t next_rmt_channel; - rmt_channel_t select_next_rmt_channel(); +rmt_channel_t select_next_rmt_channel(); #endif void delay_microseconds_accurate(uint32_t usec); @@ -333,31 +322,31 @@ class VectorJsonBuffer : public ArduinoJson::Internals::JsonBufferBase -class Deduplicator { +template class Deduplicator { public: bool next(T value); bool has_value() const; + protected: bool has_value_{false}; T last_value_{}; @@ -383,36 +372,31 @@ uint32_t fnv1_hash(const std::string &str); // Definitions // ================================================ -template -T clamp(T min, T max, T val) { - if (min > max) std::swap(min, max); - if (val < min) return min; - if (val > max) return max; +template T clamp(T min, T max, T val) { + if (min > max) + std::swap(min, max); + if (val < min) + return min; + if (val > max) + return max; return val; } -template -T lerp(T start, T end, T completion) { - return start + (end - start) * completion; -} +template T lerp(T start, T end, T completion) { return start + (end - start) * completion; } -template -std::unique_ptr make_unique(Args &&...args) { +template std::unique_ptr make_unique(Args &&... args) { return std::unique_ptr(new T(std::forward(args)...)); } -template -void CallbackManager::add(std::function &&callback) { +template void CallbackManager::add(std::function &&callback) { this->callbacks_.push_back(std::move(callback)); } -template -void CallbackManager::call(Ts... args) { +template void CallbackManager::call(Ts... args) { for (auto &cb : this->callbacks_) cb(args...); } -template -bool Deduplicator::next(T value) { +template bool Deduplicator::next(T value) { if (this->has_value_) { if (this->last_value_ == value) return false; @@ -421,11 +405,8 @@ bool Deduplicator::next(T value) { this->last_value_ = value; return true; } -template -bool Deduplicator::has_value() const { - return this->has_value_; -} +template bool Deduplicator::has_value() const { return this->has_value_; } ESPHOME_NAMESPACE_END -#endif //ESPHOME_HELPERS_H +#endif // ESPHOME_HELPERS_H diff --git a/src/esphome/i2c_component.cpp b/src/esphome/i2c_component.cpp index e956dee3..65c81cbd 100644 --- a/src/esphome/i2c_component.cpp +++ b/src/esphome/i2c_component.cpp @@ -22,18 +22,10 @@ I2CComponent::I2CComponent(uint8_t sda_pin, uint8_t scl_pin, bool scan) #endif } -void I2CComponent::set_sda_pin(uint8_t sda_pin) { - this->sda_pin_ = sda_pin; -} -void I2CComponent::set_scl_pin(uint8_t scl_pin) { - this->scl_pin_ = scl_pin; -} -void I2CComponent::set_scan(bool scan) { - this->scan_ = scan; -} -void I2CComponent::set_frequency(uint32_t frequency) { - this->frequency_ = frequency; -} +void I2CComponent::set_sda_pin(uint8_t sda_pin) { this->sda_pin_ = sda_pin; } +void I2CComponent::set_scl_pin(uint8_t scl_pin) { this->scl_pin_ = scl_pin; } +void I2CComponent::set_scan(bool scan) { this->scan_ = scan; } +void I2CComponent::set_frequency(uint32_t frequency) { this->frequency_ = frequency; } void I2CComponent::setup() { this->wire_->begin(this->sda_pin_, this->scl_pin_); @@ -65,15 +57,13 @@ void I2CComponent::dump_config() { } } } -float I2CComponent::get_setup_priority() const { - return setup_priority::PRE_HARDWARE; -} +float I2CComponent::get_setup_priority() const { return setup_priority::PRE_HARDWARE; } -void I2CComponent::begin_transmission_(uint8_t address) { +void I2CComponent::raw_begin_transmission(uint8_t address) { ESP_LOGVV(TAG, "Beginning Transmission to 0x%02X:", address); this->wire_->beginTransmission(address); } -bool I2CComponent::end_transmission_(uint8_t address) { +bool I2CComponent::raw_end_transmission(uint8_t address) { uint8_t status = this->wire_->endTransmission(); ESP_LOGVV(TAG, " Transmission ended. Status code: 0x%02X", status); @@ -96,7 +86,7 @@ bool I2CComponent::end_transmission_(uint8_t address) { return status == 0; } -bool I2CComponent::request_from_(uint8_t address, uint8_t len) { +bool I2CComponent::raw_request_from(uint8_t address, uint8_t len) { ESP_LOGVV(TAG, "Requesting %u bytes from 0x%02X:", len, address); uint8_t ret = this->wire_->requestFrom(address, len); if (ret != len) { @@ -105,15 +95,14 @@ bool I2CComponent::request_from_(uint8_t address, uint8_t len) { } return true; } -void HOT I2CComponent::write_(uint8_t address, const uint8_t *data, uint8_t len) { +void HOT I2CComponent::raw_write(uint8_t address, const uint8_t *data, uint8_t len) { for (size_t i = 0; i < len; i++) { - ESP_LOGVV(TAG, " Writing 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", - BYTE_TO_BINARY(data[i]), data[i]); + ESP_LOGVV(TAG, " Writing 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", BYTE_TO_BINARY(data[i]), data[i]); this->wire_->write(data[i]); feed_wdt(); } } -void HOT I2CComponent::write_16_(uint8_t address, const uint16_t *data, uint8_t len) { +void HOT I2CComponent::raw_write_16(uint8_t address, const uint16_t *data, uint8_t len) { for (size_t i = 0; i < len; i++) { ESP_LOGVV(TAG, " Writing 0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN " (0x%04X)", BYTE_TO_BINARY(data[i] >> 8), BYTE_TO_BINARY(data[i]), data[i]); @@ -123,19 +112,18 @@ void HOT I2CComponent::write_16_(uint8_t address, const uint16_t *data, uint8_t } } -bool I2CComponent::receive_(uint8_t address, uint8_t *data, uint8_t len) { - if (!this->request_from_(address, len)) +bool I2CComponent::raw_receive(uint8_t address, uint8_t *data, uint8_t len) { + if (!this->raw_request_from(address, len)) return false; for (uint8_t i = 0; i < len; i++) { data[i] = this->wire_->read(); - ESP_LOGVV(TAG, " Received 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", - BYTE_TO_BINARY(data[i]), data[i]); + ESP_LOGVV(TAG, " Received 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", BYTE_TO_BINARY(data[i]), data[i]); feed_wdt(); } return true; } -bool I2CComponent::receive_16_(uint8_t address, uint16_t *data, uint8_t len) { - if (!this->request_from_(address, len * 2)) +bool I2CComponent::raw_receive_16(uint8_t address, uint16_t *data, uint8_t len) { + if (!this->raw_request_from(address, len * 2)) return false; auto *data_8 = reinterpret_cast(data); for (uint8_t i = 0; i < len; i++) { @@ -146,87 +134,81 @@ bool I2CComponent::receive_16_(uint8_t address, uint16_t *data, uint8_t len) { } return true; } -bool I2CComponent::read_bytes(uint8_t address, uint8_t register_, uint8_t *data, uint8_t len, uint32_t conversion) { - if (!this->write_bytes(address, register_, nullptr, 0)) +bool I2CComponent::read_bytes(uint8_t address, uint8_t a_register, uint8_t *data, uint8_t len, uint32_t conversion) { + if (!this->write_bytes(address, a_register, nullptr, 0)) return false; if (conversion > 0) delay(conversion); - return this->receive_(address, data, len); + return this->raw_receive(address, data, len); } -bool I2CComponent::read_bytes_16(uint8_t address, uint8_t register_, uint16_t *data, uint8_t len, uint32_t conversion) { - if (!this->write_bytes(address, register_, nullptr, 0)) +bool I2CComponent::read_bytes_16(uint8_t address, uint8_t a_register, uint16_t *data, uint8_t len, + uint32_t conversion) { + if (!this->write_bytes(address, a_register, nullptr, 0)) return false; if (conversion > 0) delay(conversion); - return this->receive_16_(address, data, len); + return this->raw_receive_16(address, data, len); } -bool I2CComponent::read_byte(uint8_t address, uint8_t register_, uint8_t *data, uint32_t conversion) { - return this->read_bytes(address, register_, data, 1, conversion); +bool I2CComponent::read_byte(uint8_t address, uint8_t a_register, uint8_t *data, uint32_t conversion) { + return this->read_bytes(address, a_register, data, 1, conversion); } -bool I2CComponent::read_byte_16(uint8_t address, uint8_t register_, uint16_t *data, uint32_t conversion) { - return this->read_bytes_16(address, register_, data, 1, conversion); +bool I2CComponent::read_byte_16(uint8_t address, uint8_t a_register, uint16_t *data, uint32_t conversion) { + return this->read_bytes_16(address, a_register, data, 1, conversion); } -bool I2CComponent::write_bytes(uint8_t address, uint8_t register_, const uint8_t *data, uint8_t len) { - this->begin_transmission_(address); - this->write_(address, ®ister_, 1); - this->write_(address, data, len); - return this->end_transmission_(address); +bool I2CComponent::write_bytes(uint8_t address, uint8_t a_register, const uint8_t *data, uint8_t len) { + this->raw_begin_transmission(address); + this->raw_write(address, &a_register, 1); + this->raw_write(address, data, len); + return this->raw_end_transmission(address); } -bool I2CComponent::write_bytes_16(uint8_t address, uint8_t register_, const uint16_t *data, uint8_t len) { - - this->begin_transmission_(address); - this->write_(address, ®ister_, 1); - this->write_16_(address, data, len); - return this->end_transmission_(address); +bool I2CComponent::write_bytes_16(uint8_t address, uint8_t a_register, const uint16_t *data, uint8_t len) { + this->raw_begin_transmission(address); + this->raw_write(address, &a_register, 1); + this->raw_write_16(address, data, len); + return this->raw_end_transmission(address); } -bool I2CComponent::write_byte(uint8_t address, uint8_t register_, uint8_t data) { - return this->write_bytes(address, register_, &data, 1); +bool I2CComponent::write_byte(uint8_t address, uint8_t a_register, uint8_t data) { + return this->write_bytes(address, a_register, &data, 1); } -bool I2CComponent::write_byte_16(uint8_t address, uint8_t register_, uint16_t data) { - return this->write_bytes_16(address, register_, &data, 1); +bool I2CComponent::write_byte_16(uint8_t address, uint8_t a_register, uint16_t data) { + return this->write_bytes_16(address, a_register, &data, 1); } -I2CDevice::I2CDevice(I2CComponent *parent, uint8_t address) : address_(address), parent_(parent) { - -} +I2CDevice::I2CDevice(I2CComponent *parent, uint8_t address) : address_(address), parent_(parent) {} -void I2CDevice::set_address(uint8_t address) { - this->address_ = address; -} -bool I2CDevice::read_bytes(uint8_t register_, uint8_t *data, uint8_t len, uint32_t conversion) { - return this->parent_->read_bytes(this->address_, register_, data, len, conversion); -} -bool I2CDevice::read_byte(uint8_t register_, uint8_t *data, uint32_t conversion) { - return this->parent_->read_byte(this->address_, register_, data, conversion); +void I2CDevice::set_address(uint8_t address) { this->address_ = address; } +bool I2CDevice::read_bytes(uint8_t a_register, uint8_t *data, uint8_t len, uint32_t conversion) { // NOLINT + return this->parent_->read_bytes(this->address_, a_register, data, len, conversion); } -bool I2CDevice::write_bytes(uint8_t register_, const uint8_t *data, uint8_t len) { - return this->parent_->write_bytes(this->address_, register_, data, len); +bool I2CDevice::read_byte(uint8_t a_register, uint8_t *data, uint32_t conversion) { // NOLINT + return this->parent_->read_byte(this->address_, a_register, data, conversion); } -bool I2CDevice::write_byte(uint8_t register_, uint8_t data) { - return this->parent_->write_byte(this->address_, register_, data); +bool I2CDevice::write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) { // NOLINT + return this->parent_->write_bytes(this->address_, a_register, data, len); } -bool I2CDevice::read_bytes_16(uint8_t register_, uint16_t *data, uint8_t len, uint32_t conversion) { - return this->parent_->read_bytes_16(this->address_, register_, data, len, conversion); +bool I2CDevice::write_byte(uint8_t a_register, uint8_t data) { // NOLINT + return this->parent_->write_byte(this->address_, a_register, data); } -bool I2CDevice::read_byte_16(uint8_t register_, uint16_t *data, uint32_t conversion) { - return this->parent_->read_byte_16(this->address_, register_, data, conversion); +bool I2CDevice::read_bytes_16(uint8_t a_register, uint16_t *data, uint8_t len, uint32_t conversion) { // NOLINT + return this->parent_->read_bytes_16(this->address_, a_register, data, len, conversion); } -bool I2CDevice::write_bytes_16(uint8_t register_, const uint16_t *data, uint8_t len) { - return this->parent_->write_bytes_16(this->address_, register_, data, len); +bool I2CDevice::read_byte_16(uint8_t a_register, uint16_t *data, uint32_t conversion) { // NOLINT + return this->parent_->read_byte_16(this->address_, a_register, data, conversion); } -bool I2CDevice::write_byte_16(uint8_t register_, uint16_t data) { - return this->parent_->write_byte_16(this->address_, register_, data); +bool I2CDevice::write_bytes_16(uint8_t a_register, const uint16_t *data, uint8_t len) { // NOLINT + return this->parent_->write_bytes_16(this->address_, a_register, data, len); } -void I2CDevice::set_parent(I2CComponent *parent) { - this->parent_ = parent; +bool I2CDevice::write_byte_16(uint8_t a_register, uint16_t data) { // NOLINT + return this->parent_->write_byte_16(this->address_, a_register, data); } +void I2CDevice::set_parent(I2CComponent *parent) { this->parent_ = parent; } #ifdef ARDUINO_ARCH_ESP32 - uint8_t next_i2c_bus_num_ = 0; +uint8_t next_i2c_bus_num_ = 0; #endif ESPHOME_NAMESPACE_END -#endif //USE_I2C +#endif // USE_I2C diff --git a/src/esphome/i2c_component.h b/src/esphome/i2c_component.h index 2fb9bc23..310f43d0 100644 --- a/src/esphome/i2c_component.h +++ b/src/esphome/i2c_component.h @@ -43,64 +43,64 @@ class I2CComponent : public Component { * writing the register value to the bus. * * @param address The address to send the request to. - * @param register_ The register number to write to the bus before reading. + * @param a_register The register number to write to the bus before reading. * @param data An array to store len amount of 8-bit bytes into. * @param len The amount of bytes to request and write into data. * @param conversion The time in ms between writing the register value and reading out the value. * @return If the operation was successful. */ - bool read_bytes(uint8_t address, uint8_t register_, uint8_t *data, uint8_t len, uint32_t conversion = 0); + bool read_bytes(uint8_t address, uint8_t a_register, uint8_t *data, uint8_t len, uint32_t conversion = 0); /** Read len amount of 16-bit words (MSB first) from a register into data. * * @param address The address to send the request to. - * @param register_ The register number to write to the bus before reading. + * @param a_register The register number to write to the bus before reading. * @param data An array to store len amount of 16-bit words into. * @param len The amount of 16-bit words to request and write into data. * @param conversion The time in ms between writing the register value and reading out the value. * @return If the operation was successful. */ - bool read_bytes_16(uint8_t address, uint8_t register_, uint16_t *data, uint8_t len, uint32_t conversion = 0); + bool read_bytes_16(uint8_t address, uint8_t a_register, uint16_t *data, uint8_t len, uint32_t conversion = 0); /// Read a single byte from a register into the data variable. Return true if successful. - bool read_byte(uint8_t address, uint8_t register_, uint8_t *data, uint32_t conversion = 0); + bool read_byte(uint8_t address, uint8_t a_register, uint8_t *data, uint32_t conversion = 0); /// Read a single 16-bit words (MSB first) from a register into the data variable. Return true if successful. - bool read_byte_16(uint8_t address, uint8_t register_, uint16_t *data, uint32_t conversion = 0); + bool read_byte_16(uint8_t address, uint8_t a_register, uint16_t *data, uint32_t conversion = 0); /** Write len amount of 8-bit bytes to the specified register for address. * * @param address The address to use for the transmission. - * @param register_ The register to write the values to. + * @param a_register The register to write the values to. * @param data An array from which len bytes of data will be written to the bus. * @param len The amount of bytes to write to the bus. * @return If the operation was successful. */ - bool write_bytes(uint8_t address, uint8_t register_, const uint8_t *data, uint8_t len); + bool write_bytes(uint8_t address, uint8_t a_register, const uint8_t *data, uint8_t len); /** Write len amount of 16-bit words (MSB first) to the specified register for address. * * @param address The address to use for the transmission. - * @param register_ The register to write the values to. + * @param a_register The register to write the values to. * @param data An array from which len 16-bit words of data will be written to the bus. * @param len The amount of bytes to write to the bus. * @return If the operation was successful. */ - bool write_bytes_16(uint8_t address, uint8_t register_, const uint16_t *data, uint8_t len); + bool write_bytes_16(uint8_t address, uint8_t a_register, const uint16_t *data, uint8_t len); /// Write a single byte of data into the specified register of address. Return true if successful. - bool write_byte(uint8_t address, uint8_t register_, uint8_t data); + bool write_byte(uint8_t address, uint8_t a_register, uint8_t data); /// Write a single 16-bit word of data into the specified register of address. Return true if successful. - bool write_byte_16(uint8_t address, uint8_t register_, uint16_t data); + bool write_byte_16(uint8_t address, uint8_t a_register, uint16_t data); // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) /// Begin a write transmission to an address. - void begin_transmission_(uint8_t address); + void raw_begin_transmission(uint8_t address); /// End a write transmission to an address, return true if successful. - bool end_transmission_(uint8_t address); + bool raw_end_transmission(uint8_t address); /** Request data from an address with a number of (8-bit) bytes. * @@ -108,19 +108,19 @@ class I2CComponent : public Component { * @param len The number of bytes to receive, must not be 0. * @return True if all requested bytes were read, false otherwise. */ - bool request_from_(uint8_t address, uint8_t len); + bool raw_request_from(uint8_t address, uint8_t len); /// Write len amount of bytes from data to address. begin_transmission_ must be called before this. - void write_(uint8_t address, const uint8_t *data, uint8_t len); + void raw_write(uint8_t address, const uint8_t *data, uint8_t len); /// Write len amount of 16-bit words from data to address. begin_transmission_ must be called before this. - void write_16_(uint8_t address, const uint16_t *data, uint8_t len); + void raw_write_16(uint8_t address, const uint16_t *data, uint8_t len); /// Request len amount of bytes from address and write the result it into data. Returns true iff was successful. - bool receive_(uint8_t address, uint8_t *data, uint8_t len); + bool raw_receive(uint8_t address, uint8_t *data, uint8_t len); /// Request len amount of 16-bit words from address and write the result into data. Returns true iff was successful. - bool receive_16_(uint8_t address, uint16_t *data, uint8_t len); + bool raw_receive_16(uint8_t address, uint16_t *data, uint8_t len); /// Setup the i2c. bus void setup() override; @@ -137,7 +137,7 @@ class I2CComponent : public Component { }; #ifdef ARDUINO_ARCH_ESP32 - extern uint8_t next_i2c_bus_num_; +extern uint8_t next_i2c_bus_num_; #endif /** All components doing communication on the I2C bus should subclass I2CDevice. @@ -162,53 +162,53 @@ class I2CDevice { /** Read len amount of bytes from a register into data. Optionally with a conversion time after * writing the register value to the bus. * - * @param register_ The register number to write to the bus before reading. + * @param a_register The register number to write to the bus before reading. * @param data An array to store len amount of 8-bit bytes into. * @param len The amount of bytes to request and write into data. * @param conversion The time in ms between writing the register value and reading out the value. * @return If the operation was successful. */ - bool read_bytes(uint8_t register_, uint8_t *data, uint8_t len, uint32_t conversion = 0); + bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len, uint32_t conversion = 0); // NOLINT /** Read len amount of 16-bit words (MSB first) from a register into data. * - * @param register_ The register number to write to the bus before reading. + * @param a_register The register number to write to the bus before reading. * @param data An array to store len amount of 16-bit words into. * @param len The amount of 16-bit words to request and write into data. * @param conversion The time in ms between writing the register value and reading out the value. * @return If the operation was successful. */ - bool read_bytes_16(uint8_t register_, uint16_t *data, uint8_t len, uint32_t conversion = 0); + bool read_bytes_16(uint8_t a_register, uint16_t *data, uint8_t len, uint32_t conversion = 0); // NOLINT /// Read a single byte from a register into the data variable. Return true if successful. - bool read_byte(uint8_t register_, uint8_t *data, uint32_t conversion = 0); + bool read_byte(uint8_t a_register, uint8_t *data, uint32_t conversion = 0); // NOLINT /// Read a single 16-bit words (MSB first) from a register into the data variable. Return true if successful. - bool read_byte_16(uint8_t register_, uint16_t *data, uint32_t conversion = 0); + bool read_byte_16(uint8_t a_register, uint16_t *data, uint32_t conversion = 0); // NOLINT /** Write len amount of 8-bit bytes to the specified register. * - * @param register_ The register to write the values to. + * @param a_register The register to write the values to. * @param data An array from which len bytes of data will be written to the bus. * @param len The amount of bytes to write to the bus. * @return If the operation was successful. */ - bool write_bytes(uint8_t register_, const uint8_t *data, uint8_t len); + bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len); // NOLINT /** Write len amount of 16-bit words (MSB first) to the specified register. * - * @param register_ The register to write the values to. + * @param a_register The register to write the values to. * @param data An array from which len 16-bit words of data will be written to the bus. * @param len The amount of bytes to write to the bus. * @return If the operation was successful. */ - bool write_bytes_16(uint8_t register_, const uint16_t *data, uint8_t len); + bool write_bytes_16(uint8_t a_register, const uint16_t *data, uint8_t len); // NOLINT /// Write a single byte of data into the specified register. Return true if successful. - bool write_byte(uint8_t register_, uint8_t data); + bool write_byte(uint8_t a_register, uint8_t data); // NOLINT /// Write a single 16-bit word of data into the specified register. Return true if successful. - bool write_byte_16(uint8_t register_, uint16_t data); + bool write_byte_16(uint8_t a_register, uint16_t data); // NOLINT uint8_t address_; I2CComponent *parent_; @@ -216,6 +216,6 @@ class I2CDevice { ESPHOME_NAMESPACE_END -#endif //USE_I2C +#endif // USE_I2C -#endif //ESPHOME_I2C_COMPONENT_H +#endif // ESPHOME_I2C_COMPONENT_H diff --git a/src/esphome/io/pcf8574_component.cpp b/src/esphome/io/pcf8574_component.cpp index 6cf95427..77ac1cb0 100644 --- a/src/esphome/io/pcf8574_component.cpp +++ b/src/esphome/io/pcf8574_component.cpp @@ -39,11 +39,11 @@ void PCF8574Component::dump_config() { ESP_LOGE(TAG, "Communication with PCF8574 failed!"); } } -bool PCF8574Component::digital_read_(uint8_t pin) { +bool PCF8574Component::digital_read(uint8_t pin) { this->read_gpio_(); return this->input_mask_ & (1 << pin); } -void PCF8574Component::digital_write_(uint8_t pin, bool value) { +void PCF8574Component::digital_write(uint8_t pin, bool value) { if (value) { this->port_mask_ |= (1 << pin); } else { @@ -52,7 +52,7 @@ void PCF8574Component::digital_write_(uint8_t pin, bool value) { this->write_gpio_(); } -void PCF8574Component::pin_mode_(uint8_t pin, uint8_t mode) { +void PCF8574Component::pin_mode(uint8_t pin, uint8_t mode) { switch (mode) { case PCF8574_INPUT: this->ddr_mask_ &= ~(1 << pin); @@ -77,13 +77,13 @@ bool PCF8574Component::read_gpio_() { return false; if (this->pcf8575_) { - if (!this->parent_->receive_16_(this->address_, &this->input_mask_, 1)) { + if (!this->parent_->raw_receive_16(this->address_, &this->input_mask_, 1)) { this->status_set_warning(); return false; } } else { uint8_t data; - if (!this->parent_->receive_(this->address_, &data, 1)) { + if (!this->parent_->raw_receive(this->address_, &data, 1)) { this->status_set_warning(); return false; } @@ -99,15 +99,15 @@ bool PCF8574Component::write_gpio_() { uint16_t value = (this->input_mask_ & ~this->ddr_mask_) | this->port_mask_; - this->parent_->begin_transmission_(this->address_); + this->parent_->raw_begin_transmission(this->address_); uint8_t data = value & 0xFF; - this->parent_->write_(this->address_, &data, 1); + this->parent_->raw_write(this->address_, &data, 1); if (this->pcf8575_) { data = (value >> 8) & 0xFF; - this->parent_->write_(this->address_, &data, 1); + this->parent_->raw_write(this->address_, &data, 1); } - if (!this->parent_->end_transmission_(this->address_)) { + if (!this->parent_->raw_end_transmission(this->address_)) { this->status_set_warning(); return false; } @@ -120,48 +120,30 @@ PCF8574GPIOInputPin PCF8574Component::make_input_pin(uint8_t pin, uint8_t mode, PCF8574GPIOOutputPin PCF8574Component::make_output_pin(uint8_t pin, bool inverted) { return {this, pin, PCF8574_OUTPUT, inverted}; } -float PCF8574Component::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float PCF8574Component::get_setup_priority() const { return setup_priority::HARDWARE; } -void PCF8574GPIOInputPin::setup() { - this->pin_mode(this->mode_); -} -bool PCF8574GPIOInputPin::digital_read() { - return this->parent_->digital_read_(this->pin_) != this->inverted_; -} +void PCF8574GPIOInputPin::setup() { this->pin_mode(this->mode_); } +bool PCF8574GPIOInputPin::digital_read() { return this->parent_->digital_read(this->pin_) != this->inverted_; } void PCF8574GPIOInputPin::digital_write(bool value) { - this->parent_->digital_write_(this->pin_, value != this->inverted_); + this->parent_->digital_write(this->pin_, value != this->inverted_); } PCF8574GPIOInputPin::PCF8574GPIOInputPin(PCF8574Component *parent, uint8_t pin, uint8_t mode, bool inverted) : GPIOInputPin(pin, mode, inverted), parent_(parent) {} -GPIOPin *PCF8574GPIOInputPin::copy() const { - return new PCF8574GPIOInputPin(*this); -} -void PCF8574GPIOInputPin::pin_mode(uint8_t mode) { - this->parent_->pin_mode_(this->pin_, mode); -} +GPIOPin *PCF8574GPIOInputPin::copy() const { return new PCF8574GPIOInputPin(*this); } +void PCF8574GPIOInputPin::pin_mode(uint8_t mode) { this->parent_->pin_mode(this->pin_, mode); } -void PCF8574GPIOOutputPin::setup() { - this->pin_mode(this->mode_); -} -bool PCF8574GPIOOutputPin::digital_read() { - return this->parent_->digital_read_(this->pin_) != this->inverted_; -} +void PCF8574GPIOOutputPin::setup() { this->pin_mode(this->mode_); } +bool PCF8574GPIOOutputPin::digital_read() { return this->parent_->digital_read(this->pin_) != this->inverted_; } void PCF8574GPIOOutputPin::digital_write(bool value) { - this->parent_->digital_write_(this->pin_, value != this->inverted_); + this->parent_->digital_write(this->pin_, value != this->inverted_); } PCF8574GPIOOutputPin::PCF8574GPIOOutputPin(PCF8574Component *parent, uint8_t pin, uint8_t mode, bool inverted) : GPIOOutputPin(pin, mode, inverted), parent_(parent) {} -GPIOPin *PCF8574GPIOOutputPin::copy() const { - return new PCF8574GPIOOutputPin(*this); -} -void PCF8574GPIOOutputPin::pin_mode(uint8_t mode) { - this->parent_->pin_mode_(this->pin_, mode); -} +GPIOPin *PCF8574GPIOOutputPin::copy() const { return new PCF8574GPIOOutputPin(*this); } +void PCF8574GPIOOutputPin::pin_mode(uint8_t mode) { this->parent_->pin_mode(this->pin_, mode); } -} // namespace io +} // namespace io ESPHOME_NAMESPACE_END -#endif //USE_PCF8574 +#endif // USE_PCF8574 diff --git a/src/esphome/io/pcf8574_component.h b/src/esphome/io/pcf8574_component.h index 02d6f2c8..133eb2c1 100644 --- a/src/esphome/io/pcf8574_component.h +++ b/src/esphome/io/pcf8574_component.h @@ -57,11 +57,11 @@ class PCF8574Component : public Component, public I2CDevice { /// Check i2c availability and setup masks void setup() override; /// Helper function to read the value of a pin. - bool digital_read_(uint8_t pin); + bool digital_read(uint8_t pin); /// Helper function to write the value of a pin. - void digital_write_(uint8_t pin, bool value); + void digital_write(uint8_t pin, bool value); /// Helper function to set the pin mode of a pin. - void pin_mode_(uint8_t pin, uint8_t mode); + void pin_mode(uint8_t pin, uint8_t mode); float get_setup_priority() const override; @@ -75,7 +75,7 @@ class PCF8574Component : public Component, public I2CDevice { uint16_t ddr_mask_{0x00}; uint16_t input_mask_{0x00}; uint16_t port_mask_{0x00}; - bool pcf8575_; ///< TRUE->16-channel PCF8575, FALSE->8-channel PCF8574 + bool pcf8575_; ///< TRUE->16-channel PCF8575, FALSE->8-channel PCF8574 }; /// Helper class to expose a PCF8574 pin as an internal input GPIO pin. @@ -110,10 +110,10 @@ class PCF8574GPIOOutputPin : public GPIOOutputPin { PCF8574Component *parent_; }; -} // namespace io +} // namespace io ESPHOME_NAMESPACE_END -#endif //USE_PCF8574 +#endif // USE_PCF8574 -#endif //ESPHOME_PCF_8574_COMPONENT_H +#endif // ESPHOME_PCF_8574_COMPONENT_H diff --git a/src/esphome/light/addressable_light.cpp b/src/esphome/light/addressable_light.cpp index eaadbfba..cf86c6bf 100644 --- a/src/esphome/light/addressable_light.cpp +++ b/src/esphome/light/addressable_light.cpp @@ -16,13 +16,9 @@ ESPColor HOT ESPColor::random_color() { uint8_t r = rand >> 16; uint8_t g = rand >> 8; uint8_t b = rand >> 0; - const uint16_t max_ = std::max(r, std::max(g, b)); - return ESPColor( - uint8_t((uint16_t(r) * 255U / max_)), - uint8_t((uint16_t(g) * 255U / max_)), - uint8_t((uint16_t(b) * 255U / max_)), - w - ); + const uint16_t max_rgb = std::max(r, std::max(g, b)); + 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); } // based on FastLED's hsv rainbow to rgb @@ -31,7 +27,7 @@ ESPColor HOT ESPHSVColor::to_rgb() const { const uint8_t sat = this->saturation; const uint8_t val = this->value; // upper 3 hue bits are for branch selection, lower 5 are for values - const uint8_t offset8 = (hue & 0x1F) << 3; // 0..248 + const uint8_t offset8 = (hue & 0x1F) << 3; // 0..248 // third of the offset, 255/3 = 85 (actually only up to 82; 164) const uint8_t third = esp_scale8(offset8, 85); const uint8_t two_thirds = esp_scale8(offset8, 170); @@ -92,22 +88,16 @@ ESPColor HOT ESPHSVColor::to_rgb() const { return rgb; } -ESPColorCorrection::ESPColorCorrection() - : max_brightness_(255, 255, 255, 255) { -} +ESPColorCorrection::ESPColorCorrection() : max_brightness_(255, 255, 255, 255) {} -void ESPColorCorrection::set_local_brightness(uint8_t local_brightness) { - this->local_brightness_ = local_brightness; -} +void ESPColorCorrection::set_local_brightness(uint8_t local_brightness) { this->local_brightness_ = local_brightness; } -void ESPColorCorrection::set_max_brightness(const ESPColor &max_brightness) { - this->max_brightness_ = max_brightness; -} +void ESPColorCorrection::set_max_brightness(const ESPColor &max_brightness) { this->max_brightness_ = max_brightness; } void ESPColorCorrection::calculate_gamma_table(float gamma) { for (uint16_t i = 0; i < 256; i++) { // corrected = val ^ gamma - uint8_t corrected = roundf(255.0f * gamma_correct(i / 255.0f, gamma)); + auto corrected = static_cast(roundf(255.0f * gamma_correct(i / 255.0f, gamma))); this->gamma_table_[i] = corrected; } if (gamma == 0.0f) { @@ -117,23 +107,19 @@ void ESPColorCorrection::calculate_gamma_table(float gamma) { } for (uint16_t i = 0; i < 256; i++) { // val = corrected ^ (1/gamma) - uint8_t uncorrected = roundf(255.0f * powf(i / 255.0f, 1.0f / gamma)); + auto uncorrected = static_cast(roundf(255.0f * powf(i / 255.0f, 1.0f / gamma))); this->gamma_reverse_table_[i] = uncorrected; } } AddressableLight::AddressableLight() = default; -bool AddressableLight::is_effect_active() const { - return this->effect_active_; -} +bool AddressableLight::is_effect_active() const { return this->effect_active_; } -void AddressableLight::set_effect_active(bool effect_active) { - this->effect_active_ = effect_active; -} +void AddressableLight::set_effect_active(bool effect_active) { this->effect_active_ = effect_active; } void AddressableLight::write_state(LightState *state) { LightColorValues value = state->get_current_values(); - uint8_t max_brightness = roundf(value.get_brightness() * value.get_state() * 255.0f); + auto max_brightness = static_cast(roundf(value.get_brightness() * value.get_state() * 255.0f)); this->correction_.set_local_brightness(max_brightness); if (this->is_effect_active()) @@ -141,12 +127,8 @@ void AddressableLight::write_state(LightState *state) { auto val = state->get_current_values(); // don't use LightState helper, gamma correction+brightness is handled by ESPColorView - ESPColor color = ESPColor( - uint8_t(roundf(val.get_red() * 255.0f)), - uint8_t(roundf(val.get_green() * 255.0f)), - uint8_t(roundf(val.get_blue() * 255.0f)), - uint8_t(roundf(val.get_white() * 255.0f)) - ); + ESPColor color = ESPColor(uint8_t(roundf(val.get_red() * 255.0f)), uint8_t(roundf(val.get_green() * 255.0f)), + uint8_t(roundf(val.get_blue() * 255.0f)), uint8_t(roundf(val.get_white() * 255.0f))); for (int i = 0; i < this->size(); i++) { (*this)[i] = color; @@ -155,25 +137,15 @@ void AddressableLight::write_state(LightState *state) { this->schedule_show(); } void AddressableLight::set_correction(float red, float green, float blue, float white) { - this->correction_.set_max_brightness(ESPColor( - uint8_t(roundf(red * 255.0f)), - uint8_t(roundf(green * 255.0f)), - uint8_t(roundf(blue * 255.0f)), - uint8_t(roundf(white * 255.0f)) - )); + this->correction_.set_max_brightness(ESPColor(uint8_t(roundf(red * 255.0f)), uint8_t(roundf(green * 255.0f)), + uint8_t(roundf(blue * 255.0f)), uint8_t(roundf(white * 255.0f)))); } void AddressableLight::setup_state(LightState *state) { this->correction_.calculate_gamma_table(state->get_gamma_correct()); } -void AddressableLight::schedule_show() { - this->next_show_ = true; -} -bool AddressableLight::should_show_() const { - return this->effect_active_ || this->next_show_; -} -void AddressableLight::mark_shown_() { - this->next_show_ = false; -} +void AddressableLight::schedule_show() { this->next_show_ = true; } +bool AddressableLight::should_show_() const { return this->effect_active_ || this->next_show_; } +void AddressableLight::mark_shown_() { this->next_show_ = false; } int32_t PartitionLightOutput::size() const { auto &last_seg = this->segments_[this->segments_.size() - 1]; @@ -200,7 +172,7 @@ ESPColorView PartitionLightOutput::operator[](int32_t index) const { // offset within the src int32_t src_off = seg.get_src_offset() + seg_off; auto view = (*seg.get_src())[src_off]; - view.set_color_correction_(&this->correction_); + view.raw_set_color_correction(&this->correction_); return view; } void PartitionLightOutput::clear_effect_data() { @@ -208,9 +180,7 @@ void PartitionLightOutput::clear_effect_data() { seg.get_src()->clear_effect_data(); } } -LightTraits PartitionLightOutput::get_traits() { - return this->segments_[0].get_src()->get_traits(); -} +LightTraits PartitionLightOutput::get_traits() { return this->segments_[0].get_src()->get_traits(); } PartitionLightOutput::PartitionLightOutput(const std::vector &segments) : segments_(segments) { int32_t off = 0; for (auto &seg : this->segments_) { @@ -228,17 +198,15 @@ void PartitionLightOutput::loop() { } AddressableSegment::AddressableSegment(LightState *src, int32_t src_offset, int32_t size) - : src_(static_cast(src->get_output())), src_offset_(src_offset), size_(size) { - -} + : src_(static_cast(src->get_output())), src_offset_(src_offset), size_(size) {} AddressableLight *AddressableSegment::get_src() const { return this->src_; } int32_t AddressableSegment::get_src_offset() const { return this->src_offset_; } int32_t AddressableSegment::get_size() const { return this->size_; } int32_t AddressableSegment::get_dst_offset() const { return this->dst_offset_; } void AddressableSegment::set_dst_offset(int32_t dst_offset) { this->dst_offset_ = dst_offset; } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/addressable_light.h b/src/esphome/light/addressable_light.h index 92d6968f..947bbdb3 100644 --- a/src/esphome/light/addressable_light.h +++ b/src/esphome/light/addressable_light.h @@ -40,23 +40,23 @@ struct ESPColor { inline ESPColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t white) ALWAYS_INLINE; inline ESPColor(uint8_t red, uint8_t green, uint8_t blue) ALWAYS_INLINE; inline ESPColor(uint32_t colorcode) ALWAYS_INLINE; - inline ESPColor(const ESPColor& rhs) ALWAYS_INLINE; + inline ESPColor(const ESPColor &rhs) ALWAYS_INLINE; inline bool is_on() ALWAYS_INLINE; - inline ESPColor& operator= (const ESPColor& rhs) ALWAYS_INLINE; - inline ESPColor& operator= (const uint32_t colorcode) ALWAYS_INLINE; - inline uint8_t &operator[] (uint8_t x) ALWAYS_INLINE; - inline ESPColor operator* (uint8_t scale) const ALWAYS_INLINE; - inline ESPColor &operator*= (uint8_t scale) ALWAYS_INLINE; - inline ESPColor operator* (const ESPColor &scale) const ALWAYS_INLINE; - inline ESPColor &operator*= (const ESPColor &scale) ALWAYS_INLINE; - inline ESPColor operator+ (const ESPColor &add) const ALWAYS_INLINE; - inline ESPColor &operator+= (const ESPColor &add) ALWAYS_INLINE; - inline ESPColor operator+ (uint8_t add) const ALWAYS_INLINE; - inline ESPColor &operator+= (uint8_t add) ALWAYS_INLINE; - inline ESPColor operator- (const ESPColor &subtract) const ALWAYS_INLINE; - inline ESPColor &operator-= (const ESPColor &subtract) ALWAYS_INLINE; - inline ESPColor operator- (uint8_t subtract) const ALWAYS_INLINE; - inline ESPColor &operator-= (uint8_t subtract) ALWAYS_INLINE; + inline ESPColor &operator=(const ESPColor &rhs) ALWAYS_INLINE; + inline ESPColor &operator=(uint32_t colorcode) ALWAYS_INLINE; + inline uint8_t &operator[](uint8_t x) ALWAYS_INLINE; + inline ESPColor operator*(uint8_t scale) const ALWAYS_INLINE; + inline ESPColor &operator*=(uint8_t scale) ALWAYS_INLINE; + inline ESPColor operator*(const ESPColor &scale) const ALWAYS_INLINE; + inline ESPColor &operator*=(const ESPColor &scale) ALWAYS_INLINE; + inline ESPColor operator+(const ESPColor &add) const ALWAYS_INLINE; + inline ESPColor &operator+=(const ESPColor &add) ALWAYS_INLINE; + inline ESPColor operator+(uint8_t add) const ALWAYS_INLINE; + inline ESPColor &operator+=(uint8_t add) ALWAYS_INLINE; + inline ESPColor operator-(const ESPColor &subtract) const ALWAYS_INLINE; + inline ESPColor &operator-=(const ESPColor &subtract) ALWAYS_INLINE; + inline ESPColor operator-(uint8_t subtract) const ALWAYS_INLINE; + inline ESPColor &operator-=(uint8_t subtract) ALWAYS_INLINE; static ESPColor random_color(); }; @@ -99,6 +99,7 @@ class ESPColorCorrection { inline uint8_t color_uncorrect_green(uint8_t green) const ALWAYS_INLINE; inline uint8_t color_uncorrect_blue(uint8_t blue) const ALWAYS_INLINE; inline uint8_t color_uncorrect_white(uint8_t white) const ALWAYS_INLINE; + protected: uint8_t gamma_table_[256]; uint8_t gamma_reverse_table_[256]; @@ -108,10 +109,10 @@ class ESPColorCorrection { class ESPColorView { public: - inline ESPColorView(uint8_t *red, uint8_t *green, uint8_t *blue, uint8_t *white, - uint8_t *effect_data, const ESPColorCorrection *color_correction) ALWAYS_INLINE; - inline const ESPColorView &operator= (const ESPColor &rhs) const ALWAYS_INLINE; - inline const ESPColorView &operator= (const ESPHSVColor &rhs) const ALWAYS_INLINE; + inline ESPColorView(uint8_t *red, uint8_t *green, uint8_t *blue, uint8_t *white, uint8_t *effect_data, + const ESPColorCorrection *color_correction) ALWAYS_INLINE; + inline const ESPColorView &operator=(const ESPColor &rhs) const ALWAYS_INLINE; + inline const ESPColorView &operator=(const ESPHSVColor &rhs) const ALWAYS_INLINE; inline void set(const ESPColor &color) const ALWAYS_INLINE; inline void set(const ESPHSVColor &color) const ALWAYS_INLINE; inline void set_red(uint8_t red) const ALWAYS_INLINE; @@ -127,7 +128,8 @@ class ESPColorView { inline uint8_t get_blue() const ALWAYS_INLINE; inline uint8_t get_white() const ALWAYS_INLINE; inline uint8_t get_effect_data() const ALWAYS_INLINE; - inline void set_color_correction_(const ESPColorCorrection *color_correction) ALWAYS_INLINE; + inline void raw_set_color_correction(const ESPColorCorrection *color_correction) ALWAYS_INLINE; + protected: uint8_t *const red_; uint8_t *const green_; @@ -141,7 +143,7 @@ class AddressableLight : public LightOutput { public: AddressableLight(); virtual int32_t size() const = 0; - virtual ESPColorView operator [](int32_t index) const = 0; + virtual ESPColorView operator[](int32_t index) const = 0; virtual void clear_effect_data() = 0; bool is_effect_active() const; void set_effect_active(bool effect_active); @@ -149,10 +151,11 @@ class AddressableLight : public LightOutput { void set_correction(float red, float green, float blue, float white = 1.0f); void setup_state(LightState *state) override; void schedule_show(); + protected: bool should_show_() const; void mark_shown_(); - + bool effect_active_{false}; bool next_show_{true}; ESPColorCorrection correction_{}; @@ -188,12 +191,12 @@ class PartitionLightOutput : public AddressableLight, public Component { std::vector segments_; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END #include "esphome/light/addressable_light.tcc" -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_ADDRESSABLE_LIGHT_H +#endif // ESPHOME_LIGHT_ADDRESSABLE_LIGHT_H diff --git a/src/esphome/light/addressable_light.tcc b/src/esphome/light/addressable_light.tcc index d651e864..3fab7d79 100644 --- a/src/esphome/light/addressable_light.tcc +++ b/src/esphome/light/addressable_light.tcc @@ -9,26 +9,24 @@ ESPHOME_NAMESPACE_BEGIN namespace light { -inline static uint8_t esp_scale8(uint8_t i, uint8_t scale) { - return (uint16_t(i) * (1 + uint16_t(scale))) / 256; -} +inline static uint8_t esp_scale8(uint8_t i, uint8_t scale) { return (uint16_t(i) * (1 + uint16_t(scale))) / 256; } -ESPColor::ESPColor() { +ESPColor::ESPColor() : r(0), g(0), b(0), w(0) { // NOLINT } -ESPColor::ESPColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t white) - : r(red), g(green), b(blue), w(white) { -} +ESPColor::ESPColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t white) // NOLINT + : r(red), g(green), b(blue), w(white) {} -ESPColor::ESPColor(uint8_t red, uint8_t green, uint8_t blue) - : r(red), g(green), b(blue), w(0) { -} +ESPColor::ESPColor(uint8_t red, uint8_t green, uint8_t blue) // NOLINT + : r(red), g(green), b(blue), w(0) {} -ESPColor::ESPColor(uint32_t colorcode) - : r((colorcode >> 16) & 0xFF), g((colorcode >> 8) & 0xFF), b((colorcode >> 0) & 0xFF), w((colorcode >> 24) & 0xFF) { -} +ESPColor::ESPColor(uint32_t colorcode) // NOLINT + : r((colorcode >> 16) & 0xFF), + g((colorcode >> 8) & 0xFF), + b((colorcode >> 0) & 0xFF), + w((colorcode >> 24) & 0xFF) {} -ESPColor::ESPColor(const ESPColor &rhs) { +ESPColor::ESPColor(const ESPColor &rhs) { // NOLINT this->r = rhs.r; this->g = rhs.g; this->b = rhs.b; @@ -43,7 +41,7 @@ ESPColor &ESPColor::operator=(const ESPColor &rhs) { return *this; } -ESPColor &ESPColor::operator=(const uint32_t colorcode) { +ESPColor &ESPColor::operator=(uint32_t colorcode) { this->w = (colorcode >> 24) & 0xFF; this->r = (colorcode >> 16) & 0xFF; this->g = (colorcode >> 8) & 0xFF; @@ -52,12 +50,8 @@ ESPColor &ESPColor::operator=(const uint32_t colorcode) { } ESPColor ESPColor::operator*(const uint8_t scale) const { - return ESPColor( - esp_scale8(this->red, scale), - esp_scale8(this->green, scale), - esp_scale8(this->blue, scale), - esp_scale8(this->white, scale) - ); + return ESPColor(esp_scale8(this->red, scale), esp_scale8(this->green, scale), esp_scale8(this->blue, scale), + esp_scale8(this->white, scale)); } ESPColor &ESPColor::operator*=(uint8_t scale) { @@ -70,53 +64,59 @@ ESPColor &ESPColor::operator*=(uint8_t scale) { ESPColor ESPColor::operator+(const ESPColor &add) const { ESPColor ret; - if (uint8_t(add.r + this->r) < this->r) ret.r = 255; - else ret.r = this->r + add.r; - if (uint8_t(add.g + this->g) < this->g) ret.g = 255; - else ret.g = this->g + add.g; - if (uint8_t(add.b + this->b) < this->b) ret.b = 255; - else ret.b = this->b + add.b; - if (uint8_t(add.w + this->w) < this->w) ret.w = 255; - else ret.w = this->w + add.w; + if (uint8_t(add.r + this->r) < this->r) + ret.r = 255; + else + ret.r = this->r + add.r; + if (uint8_t(add.g + this->g) < this->g) + ret.g = 255; + else + ret.g = this->g + add.g; + if (uint8_t(add.b + this->b) < this->b) + ret.b = 255; + else + ret.b = this->b + add.b; + if (uint8_t(add.w + this->w) < this->w) + ret.w = 255; + else + ret.w = this->w + add.w; return ret; } -ESPColor &ESPColor::operator+=(const ESPColor &add) { - return *this = (*this) + add; -} +ESPColor &ESPColor::operator+=(const ESPColor &add) { return *this = (*this) + add; } -ESPColor ESPColor::operator+(uint8_t add) const { - return (*this) + ESPColor(add, add, add, add); -} +ESPColor ESPColor::operator+(uint8_t add) const { return (*this) + ESPColor(add, add, add, add); } -ESPColor &ESPColor::operator+=(uint8_t add) { - return *this = (*this) + add; -} +ESPColor &ESPColor::operator+=(uint8_t add) { return *this = (*this) + add; } ESPColor ESPColor::operator-(const ESPColor &subtract) const { ESPColor ret; - if (subtract.r > this->r) ret.r = 0; - else ret.r = this->r - subtract.r; - if (subtract.g > this->g) ret.g = 0; - else ret.g = this->g - subtract.g; - if (subtract.b > this->b) ret.b = 0; - else ret.b = this->b - subtract.b; - if (subtract.w > this->w) ret.w = 0; - else ret.w = this->w - subtract.w; + if (subtract.r > this->r) + ret.r = 0; + else + ret.r = this->r - subtract.r; + if (subtract.g > this->g) + ret.g = 0; + else + ret.g = this->g - subtract.g; + if (subtract.b > this->b) + ret.b = 0; + else + ret.b = this->b - subtract.b; + if (subtract.w > this->w) + ret.w = 0; + else + ret.w = this->w - subtract.w; return ret; } -ESPColor &ESPColor::operator-=(const ESPColor &subtract) { - return *this = (*this) - subtract; -} +ESPColor &ESPColor::operator-=(const ESPColor &subtract) { return *this = (*this) - subtract; } ESPColor ESPColor::operator-(uint8_t subtract) const { return (*this) - ESPColor(subtract, subtract, subtract, subtract); } -ESPColor &ESPColor::operator-=(uint8_t subtract) { - return *this = (*this) - subtract; -} +ESPColor &ESPColor::operator-=(uint8_t subtract) { return *this = (*this) - subtract; } ESPColor &ESPColor::operator*=(const ESPColor &scale) { this->red = esp_scale8(this->red, scale.red); @@ -127,48 +127,37 @@ ESPColor &ESPColor::operator*=(const ESPColor &scale) { } ESPColor ESPColor::operator*(const ESPColor &scale) const { - return ESPColor( - esp_scale8(this->red, scale.red), - esp_scale8(this->green, scale.green), - esp_scale8(this->blue, scale.blue), - esp_scale8(this->white, scale.white) - ); + return ESPColor(esp_scale8(this->red, scale.red), esp_scale8(this->green, scale.green), + esp_scale8(this->blue, scale.blue), esp_scale8(this->white, scale.white)); } -uint8_t &ESPColor::operator[](uint8_t x) { - return this->raw[x]; -} +uint8_t &ESPColor::operator[](uint8_t x) { return this->raw[x]; } -bool ESPColor::is_on() { - return this->r != 0 || this->g != 0 || this->b != 0 || this->w != 0; -} +bool ESPColor::is_on() { return this->r != 0 || this->g != 0 || this->b != 0 || this->w != 0; } ESPColorView::ESPColorView(uint8_t *red, uint8_t *green, uint8_t *blue, uint8_t *white, uint8_t *effect_data, const ESPColorCorrection *color_correction) - : red_(red), green_(green), blue_(blue), white_(white), effect_data_(effect_data), - color_correction_(color_correction) { -} + : red_(red), + green_(green), + blue_(blue), + white_(white), + effect_data_(effect_data), + color_correction_(color_correction) {} const ESPColorView &ESPColorView::operator=(const ESPColor &rhs) const { this->set(rhs); return *this; } -void ESPColorView::set(const ESPColor &color) const { - this->set_rgbw(color.r, color.g, color.b, color.w); -} +void ESPColorView::set(const ESPColor &color) const { this->set_rgbw(color.r, color.g, color.b, color.w); } -void ESPColorView::set_red(uint8_t red) const { - *this->red_ = this->color_correction_->color_correct_red(red); -} +void ESPColorView::set_red(uint8_t red) const { *this->red_ = this->color_correction_->color_correct_red(red); } void ESPColorView::set_green(uint8_t green) const { *this->green_ = this->color_correction_->color_correct_green(green); } -void ESPColorView::set_blue(uint8_t blue) const { - *this->blue_ = this->color_correction_->color_correct_blue(blue); -} +void ESPColorView::set_blue(uint8_t blue) const { *this->blue_ = this->color_correction_->color_correct_blue(blue); } void ESPColorView::set_white(uint8_t white) const { if (this->white_ == nullptr) @@ -191,17 +180,11 @@ ESPColor ESPColorView::get() const { return ESPColor(this->get_red(), this->get_green(), this->get_blue(), this->get_white()); } -uint8_t ESPColorView::get_red() const { - return this->color_correction_->color_uncorrect_red(*this->red_); -} +uint8_t ESPColorView::get_red() const { return this->color_correction_->color_uncorrect_red(*this->red_); } -uint8_t ESPColorView::get_green() const { - return this->color_correction_->color_uncorrect_green(*this->green_); -} +uint8_t ESPColorView::get_green() const { return this->color_correction_->color_uncorrect_green(*this->green_); } -uint8_t ESPColorView::get_blue() const { - return this->color_correction_->color_uncorrect_blue(*this->blue_); -} +uint8_t ESPColorView::get_blue() const { return this->color_correction_->color_uncorrect_blue(*this->blue_); } uint8_t ESPColorView::get_white() const { if (this->white_ == nullptr) @@ -230,18 +213,14 @@ const ESPColorView &ESPColorView::operator=(const ESPHSVColor &rhs) const { this->set(rhs); return *this; } -void ESPColorView::set_color_correction_(const ESPColorCorrection *color_correction) { +void ESPColorView::raw_set_color_correction(const ESPColorCorrection *color_correction) { this->color_correction_ = color_correction; } ESPColor ESPColorCorrection::color_correct(ESPColor color) const { // corrected = (uncorrected * max_brightness * local_brightness) ^ gamma - return ESPColor( - this->color_correct_red(color.red), - this->color_correct_green(color.green), - this->color_correct_blue(color.blue), - this->color_correct_white(color.white) - ); + return ESPColor(this->color_correct_red(color.red), this->color_correct_green(color.green), + this->color_correct_blue(color.blue), this->color_correct_white(color.white)); } uint8_t ESPColorCorrection::color_correct_red(uint8_t red) const { @@ -267,12 +246,8 @@ uint8_t ESPColorCorrection::color_correct_white(uint8_t white) const { ESPColor ESPColorCorrection::color_uncorrect(ESPColor color) const { // uncorrected = corrected^(1/gamma) / (max_brightness * local_brightness) - return ESPColor( - this->color_uncorrect_red(color.red), - this->color_uncorrect_green(color.green), - this->color_uncorrect_blue(color.blue), - this->color_uncorrect_white(color.white) - ); + return ESPColor(this->color_uncorrect_red(color.red), this->color_uncorrect_green(color.green), + this->color_uncorrect_blue(color.blue), this->color_uncorrect_white(color.white)); } uint8_t ESPColorCorrection::color_uncorrect_red(uint8_t red) const { @@ -307,15 +282,14 @@ uint8_t ESPColorCorrection::color_uncorrect_white(uint8_t white) const { return res; } -ESPHSVColor::ESPHSVColor() { +ESPHSVColor::ESPHSVColor() : h(0), s(0), v(0) { // NOLINT } -ESPHSVColor::ESPHSVColor(uint8_t hue, uint8_t saturation, uint8_t value) - : hue(hue), saturation(saturation), value(value) { -} +ESPHSVColor::ESPHSVColor(uint8_t hue, uint8_t saturation, uint8_t value) // NOLINT + : hue(hue), saturation(saturation), value(value) {} -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/addressable_light_effect.cpp b/src/esphome/light/addressable_light_effect.cpp index 16f3e0bb..f44a3171 100644 --- a/src/esphome/light/addressable_light_effect.cpp +++ b/src/esphome/light/addressable_light_effect.cpp @@ -8,7 +8,7 @@ ESPHOME_NAMESPACE_BEGIN namespace light { -void AddressableLightEffect::start_() { +void AddressableLightEffect::start_internal() { this->get_addressable_()->set_effect_active(true); this->get_addressable_()->clear_effect_data(); this->high_freq_.start(); @@ -24,30 +24,26 @@ AddressableLight *AddressableLightEffect::get_addressable_() const { return (AddressableLight *) this->state_->get_output(); } -AddressableLightEffect::AddressableLightEffect(const std::string &name) : LightEffect(name) { -} +AddressableLightEffect::AddressableLightEffect(const std::string &name) : LightEffect(name) {} void AddressableLightEffect::apply() { LightColorValues color = this->state_->get_remote_values(); // not using any color correction etc. that will be handled by the addressable layer - ESPColor current_color = ESPColor( - color.get_red() * 255, - color.get_green() * 255, - color.get_blue() * 255, - color.get_white() * 255 - ); + ESPColor current_color = + ESPColor(static_cast(color.get_red() * 255), static_cast(color.get_green() * 255), + static_cast(color.get_blue() * 255), static_cast(color.get_white() * 255)); this->apply(*this->get_addressable_(), current_color); } -inline static int16_t sin16_C(uint16_t theta) { - static const uint16_t base[] = {0, 6393, 12539, 18204, 23170, 27245, 30273, 32137}; - static const uint8_t slope[] = {49, 48, 44, 38, 31, 23, 14, 4}; - uint16_t offset = (theta & 0x3FFF) >> 3; // 0..2047 +inline static int16_t sin16_c(uint16_t theta) { + static const uint16_t BASE[] = {0, 6393, 12539, 18204, 23170, 27245, 30273, 32137}; + static const uint8_t SLOPE[] = {49, 48, 44, 38, 31, 23, 14, 4}; + uint16_t offset = (theta & 0x3FFF) >> 3; // 0..2047 if (theta & 0x4000) offset = 2047 - offset; - uint8_t section = offset / 256; // 0..7 - uint16_t b = base[section]; - uint8_t m = slope[section]; + uint8_t section = offset / 256; // 0..7 + uint16_t b = BASE[section]; + uint8_t m = SLOPE[section]; uint8_t secoffset8 = uint8_t(offset) / 2; uint16_t mx = m * secoffset8; int16_t y = mx + b; @@ -56,15 +52,12 @@ inline static int16_t sin16_C(uint16_t theta) { return y; } -inline static uint8_t half_sin8(uint8_t v) { - return sin16_C(uint16_t(v) * 128u) >> 8; -} +inline static uint8_t half_sin8(uint8_t v) { return sin16_c(uint16_t(v) * 128u) >> 8; } AddressableLambdaLightEffect::AddressableLambdaLightEffect(const std::string &name, const std::function &f, uint32_t update_interval) - : AddressableLightEffect(name), f_(f), update_interval_(update_interval) { -} + : AddressableLightEffect(name), f_(f), update_interval_(update_interval) {} void AddressableLambdaLightEffect::apply(AddressableLight &it, const ESPColor ¤t_color) { const uint32_t now = millis(); @@ -74,9 +67,7 @@ void AddressableLambdaLightEffect::apply(AddressableLight &it, const ESPColor &c } } -AddressableRainbowLightEffect::AddressableRainbowLightEffect(const std::string &name) - : AddressableLightEffect(name) { -} +AddressableRainbowLightEffect::AddressableRainbowLightEffect(const std::string &name) : AddressableLightEffect(name) {} void AddressableRainbowLightEffect::apply(AddressableLight &it, const ESPColor ¤t_color) { ESPHSVColor hsv; @@ -91,23 +82,13 @@ void AddressableRainbowLightEffect::apply(AddressableLight &it, const ESPColor & } } -void AddressableRainbowLightEffect::set_speed(uint32_t speed) { - this->speed_ = speed; -} +void AddressableRainbowLightEffect::set_speed(uint32_t speed) { this->speed_ = speed; } -void AddressableRainbowLightEffect::set_width(uint32_t width) { - this->width_ = width; -} +void AddressableRainbowLightEffect::set_width(uint32_t width) { this->width_ = width; } AddressableColorWipeEffect::AddressableColorWipeEffect(const std::string &name) : AddressableLightEffect(name) { - this->colors_.push_back(AddressableColorWipeEffectColor { - .r = 255, - .g = 255, - .b = 255, - .w = 255, - .random = true, - .num_leds = 1 - }); + this->colors_.push_back( + AddressableColorWipeEffectColor{.r = 255, .g = 255, .b = 255, .w = 255, .random = true, .num_leds = 1}); } void AddressableColorWipeEffect::set_colors(const std::vector &colors) { @@ -118,9 +99,7 @@ void AddressableColorWipeEffect::set_add_led_interval(uint32_t add_led_interval) this->add_led_interval_ = add_led_interval; } -void AddressableColorWipeEffect::set_reverse(bool reverse) { - this->reverse_ = reverse; -} +void AddressableColorWipeEffect::set_reverse(bool reverse) { this->reverse_ = reverse; } void AddressableColorWipeEffect::apply(AddressableLight &it, const ESPColor ¤t_color) { const uint32_t now = millis(); @@ -156,13 +135,9 @@ void AddressableColorWipeEffect::apply(AddressableLight &it, const ESPColor &cur } } -AddressableScanEffect::AddressableScanEffect(const std::string &name) - : AddressableLightEffect(name) { -} +AddressableScanEffect::AddressableScanEffect(const std::string &name) : AddressableLightEffect(name) {} -void AddressableScanEffect::set_move_interval(uint32_t move_interval) { - this->move_interval_ = move_interval; -} +void AddressableScanEffect::set_move_interval(uint32_t move_interval) { this->move_interval_ = move_interval; } void AddressableScanEffect::apply(AddressableLight &addressable, const ESPColor ¤t_color) { for (int i = 0; i < addressable.size(); i++) { @@ -216,9 +191,7 @@ void AddressableTwinkleEffect::apply(AddressableLight &addressable, const ESPCol } } -AddressableTwinkleEffect::AddressableTwinkleEffect(const std::string &name) - : AddressableLightEffect(name) { -} +AddressableTwinkleEffect::AddressableTwinkleEffect(const std::string &name) : AddressableLightEffect(name) {} void AddressableTwinkleEffect::set_twinkle_probability(float twinkle_probability) { this->twinkle_probability_ = twinkle_probability; @@ -229,8 +202,7 @@ void AddressableTwinkleEffect::set_progress_interval(uint32_t progress_interval) } AddressableRandomTwinkleEffect::AddressableRandomTwinkleEffect(const std::string &name) - : AddressableLightEffect(name) { -} + : AddressableLightEffect(name) {} void AddressableRandomTwinkleEffect::apply(AddressableLight &it, const ESPColor ¤t_color) { const uint32_t now = millis(); @@ -249,11 +221,7 @@ void AddressableRandomTwinkleEffect::apply(AddressableLight &it, const ESPColor if (color == 0) { view = current_color * sine; } else { - view = ESPColor( - ((color >> 2) & 1) * sine, - ((color >> 1) & 1) * sine, - ((color >> 0) & 1) * sine - ); + view = ESPColor(((color >> 2) & 1) * sine, ((color >> 1) & 1) * sine, ((color >> 0) & 1) * sine); } const uint8_t new_x = x + pos_add; if (new_x > 0b11111) @@ -281,9 +249,7 @@ void AddressableRandomTwinkleEffect::set_progress_interval(uint32_t progress_int this->progress_interval_ = progress_interval; } -AddressableFireworksEffect::AddressableFireworksEffect(const std::string &name) - : AddressableLightEffect(name) { -} +AddressableFireworksEffect::AddressableFireworksEffect(const std::string &name) : AddressableLightEffect(name) {} void AddressableFireworksEffect::start() { const auto &it = *this->get_addressable_(); @@ -328,17 +294,11 @@ void AddressableFireworksEffect::set_spark_probability(float spark_probability) this->spark_probability_ = spark_probability; } -void AddressableFireworksEffect::set_use_random_color(bool random_color) { - this->use_random_color_= random_color; -} +void AddressableFireworksEffect::set_use_random_color(bool random_color) { this->use_random_color_ = random_color; } -void AddressableFireworksEffect::set_fade_out_rate(uint8_t fade_out_rate) { - this->fade_out_rate_ = fade_out_rate; -} +void AddressableFireworksEffect::set_fade_out_rate(uint8_t fade_out_rate) { this->fade_out_rate_ = fade_out_rate; } -AddressableFlickerEffect::AddressableFlickerEffect(const std::string &name) - : AddressableLightEffect(name) { -} +AddressableFlickerEffect::AddressableFlickerEffect(const std::string &name) : AddressableLightEffect(name) {} void AddressableFlickerEffect::apply(AddressableLight &it, const ESPColor ¤t_color) { const uint32_t now = millis(); @@ -358,11 +318,11 @@ void AddressableFlickerEffect::set_update_interval(uint32_t update_interval) { } void AddressableFlickerEffect::set_intensity(float intensity) { - this->intensity_ = roundf(intensity * 255.0f); + this->intensity_ = static_cast(roundf(intensity * 255.0f)); } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/addressable_light_effect.h b/src/esphome/light/addressable_light_effect.h index f3f2a008..4ad85521 100644 --- a/src/esphome/light/addressable_light_effect.h +++ b/src/esphome/light/addressable_light_effect.h @@ -15,10 +15,11 @@ namespace light { class AddressableLightEffect : public LightEffect { public: explicit AddressableLightEffect(const std::string &name); - void start_() override; + void start_internal() override; void stop() override; virtual void apply(AddressableLight &it, const ESPColor ¤t_color) = 0; void apply() override; + protected: AddressableLight *get_addressable_() const; @@ -27,10 +28,10 @@ class AddressableLightEffect : public LightEffect { class AddressableLambdaLightEffect : public AddressableLightEffect { public: - AddressableLambdaLightEffect(const std::string &name, - const std::function &f, + AddressableLambdaLightEffect(const std::string &name, const std::function &f, uint32_t update_interval); void apply(AddressableLight &it, const ESPColor ¤t_color) override; + protected: std::function f_; uint32_t update_interval_; @@ -43,6 +44,7 @@ class AddressableRainbowLightEffect : public AddressableLightEffect { void apply(AddressableLight &it, const ESPColor ¤t_color) override; void set_speed(uint32_t speed); void set_width(uint32_t width); + protected: uint32_t speed_{10}; uint16_t width_{50}; @@ -61,6 +63,7 @@ class AddressableColorWipeEffect : public AddressableLightEffect { void set_add_led_interval(uint32_t add_led_interval); void set_reverse(bool reverse); void apply(AddressableLight &it, const ESPColor ¤t_color) override; + protected: std::vector colors_; size_t at_color_{0}; @@ -75,6 +78,7 @@ class AddressableScanEffect : public AddressableLightEffect { explicit AddressableScanEffect(const std::string &name); void set_move_interval(uint32_t move_interval); void apply(AddressableLight &addressable, const ESPColor ¤t_color) override; + protected: uint32_t move_interval_{100}; uint32_t last_move_{0}; @@ -88,6 +92,7 @@ class AddressableTwinkleEffect : public AddressableLightEffect { void apply(AddressableLight &addressable, const ESPColor ¤t_color) override; void set_twinkle_probability(float twinkle_probability); void set_progress_interval(uint32_t progress_interval); + protected: float twinkle_probability_{0.05f}; uint32_t progress_interval_{4}; @@ -100,6 +105,7 @@ class AddressableRandomTwinkleEffect : public AddressableLightEffect { void apply(AddressableLight &it, const ESPColor ¤t_color) override; void set_twinkle_probability(float twinkle_probability); void set_progress_interval(uint32_t progress_interval); + protected: float twinkle_probability_{0.05f}; uint32_t progress_interval_{32}; @@ -115,6 +121,7 @@ class AddressableFireworksEffect : public AddressableLightEffect { void set_spark_probability(float spark_probability); void set_use_random_color(bool random_color); void set_fade_out_rate(uint8_t fade_out_rate); + protected: uint8_t fade_out_rate_{120}; uint32_t update_interval_{32}; @@ -129,16 +136,17 @@ class AddressableFlickerEffect : public AddressableLightEffect { void apply(AddressableLight &it, const ESPColor ¤t_color) override; void set_update_interval(uint32_t update_interval); void set_intensity(float intensity); + protected: uint32_t update_interval_{16}; uint32_t last_update_{0}; uint8_t intensity_{13}; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_ADDRESSABLE_LIGHT_EFFECT_H +#endif // ESPHOME_LIGHT_ADDRESSABLE_LIGHT_EFFECT_H diff --git a/src/esphome/light/fast_led_light_output.cpp b/src/esphome/light/fast_led_light_output.cpp index 30dda0b0..b3a06b1a 100644 --- a/src/esphome/light/fast_led_light_output.cpp +++ b/src/esphome/light/fast_led_light_output.cpp @@ -11,9 +11,7 @@ namespace light { static const char *TAG = "light.fast_led"; -LightTraits FastLEDLightOutputComponent::get_traits() { - return {true, true, false, false}; -} +LightTraits FastLEDLightOutputComponent::get_traits() { return {true, true, false, false}; } void FastLEDLightOutputComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up FastLED light..."); this->controller_->init(); @@ -74,15 +72,9 @@ CLEDController &FastLEDLightOutputComponent::add_leds(CLEDController *controller return *this->controller_; } -CLEDController *FastLEDLightOutputComponent::get_controller() const { - return this->controller_; -} -void FastLEDLightOutputComponent::set_max_refresh_rate(uint32_t interval_us) { - this->max_refresh_rate_ = interval_us; -} -float FastLEDLightOutputComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} +CLEDController *FastLEDLightOutputComponent::get_controller() const { return this->controller_; } +void FastLEDLightOutputComponent::set_max_refresh_rate(uint32_t interval_us) { this->max_refresh_rate_ = interval_us; } +float FastLEDLightOutputComponent::get_setup_priority() const { return setup_priority::HARDWARE; } #ifdef USE_OUTPUT void FastLEDLightOutputComponent::set_power_supply(PowerSupplyComponent *power_supply) { this->power_supply_ = power_supply; @@ -93,17 +85,14 @@ ESPColorView FastLEDLightOutputComponent::operator[](int32_t index) const { return ESPColorView(&this->leds_[index].r, &this->leds_[index].g, &this->leds_[index].b, nullptr, &this->effect_data_[index], &this->correction_); } -int32_t FastLEDLightOutputComponent::size() const { - return this->num_leds_; -} +int32_t FastLEDLightOutputComponent::size() const { return this->num_leds_; } void FastLEDLightOutputComponent::clear_effect_data() { for (int i = 0; i < this->size(); i++) this->effect_data_[i] = 0; } - -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_FAST_LED_LIGHT +#endif // USE_FAST_LED_LIGHT diff --git a/src/esphome/light/fast_led_light_output.h b/src/esphome/light/fast_led_light_output.h index 06cf33d0..577fbac0 100644 --- a/src/esphome/light/fast_led_light_output.h +++ b/src/esphome/light/fast_led_light_output.h @@ -57,68 +57,67 @@ class FastLEDLightOutputComponent : public Component, public AddressableLight { CLEDController &add_leds(int num_leds) { switch (CHIPSET) { case LPD8806: { - static LPD8806Controller c; - return add_leds(&c, num_leds); + static LPD8806Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case WS2801: { - static WS2801Controller c; - return add_leds(&c, num_leds); + static WS2801Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case WS2803: { - static WS2803Controller c; - return add_leds(&c, num_leds); + static WS2803Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case SM16716: { - static SM16716Controller c; - return add_leds(&c, num_leds); + static SM16716Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case P9813: { - static P9813Controller c; - return add_leds(&c, num_leds); + static P9813Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case DOTSTAR: case APA102: { - static APA102Controller c; - return add_leds(&c, num_leds); + static APA102Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case SK9822: { - static SK9822Controller c; - return add_leds(&c, num_leds); + static SK9822Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } } } - template - CLEDController &add_leds(int num_leds) { + template CLEDController &add_leds(int num_leds) { switch (CHIPSET) { case LPD8806: { - static LPD8806Controller c; - return add_leds(&c, num_leds); + static LPD8806Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case WS2801: { - static WS2801Controller c; - return add_leds(&c, num_leds); + static WS2801Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case WS2803: { - static WS2803Controller c; - return add_leds(&c, num_leds); + static WS2803Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case SM16716: { - static SM16716Controller c; - return add_leds(&c, num_leds); + static SM16716Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case P9813: { - static P9813Controller c; - return add_leds(&c, num_leds); + static P9813Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case DOTSTAR: case APA102: { - static APA102Controller c; - return add_leds(&c, num_leds); + static APA102Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case SK9822: { - static SK9822Controller c; - return add_leds(&c, num_leds); + static SK9822Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } } } @@ -127,50 +126,47 @@ class FastLEDLightOutputComponent : public Component, public AddressableLight { CLEDController &add_leds(int num_leds) { switch (CHIPSET) { case LPD8806: { - static LPD8806Controller c; - return add_leds(&c, num_leds); + static LPD8806Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case WS2801: { - static WS2801Controller c; - return add_leds(&c, num_leds); + static WS2801Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case WS2803: { - static WS2803Controller c; - return add_leds(&c, num_leds); + static WS2803Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case SM16716: { - static SM16716Controller c; - return add_leds(&c, num_leds); + static SM16716Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case P9813: { - static P9813Controller c; - return add_leds(&c, num_leds); + static P9813Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case DOTSTAR: case APA102: { - static APA102Controller c; - return add_leds(&c, num_leds); + static APA102Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } case SK9822: { - static SK9822Controller c; - return add_leds(&c, num_leds); + static SK9822Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } } } #ifdef SPI_DATA - template - CLEDController &add_leds(int num_leds) { + template CLEDController &add_leds(int num_leds) { return add_leds(num_leds); } - template - CLEDController &add_leds(int num_leds) { + template CLEDController &add_leds(int num_leds) { return add_leds(num_leds); } - template - CLEDController &add_leds(int num_leds) { + template CLEDController &add_leds(int num_leds) { return add_leds(num_leds); } #endif @@ -178,143 +174,187 @@ class FastLEDLightOutputComponent : public Component, public AddressableLight { #ifdef FASTLED_HAS_CLOCKLESS template class CHIPSET, uint8_t DATA_PIN, EOrder RGB_ORDER> CLEDController &add_leds(int num_leds) { - static CHIPSET c; - return add_leds(&c, num_leds); + static CHIPSET CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } template class CHIPSET, uint8_t DATA_PIN> CLEDController &add_leds(int num_leds) { - static CHIPSET c; - return add_leds(&c, num_leds); + static CHIPSET CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } - template class CHIPSET, uint8_t DATA_PIN> - CLEDController &add_leds(int num_leds) { - static CHIPSET c; - return add_leds(&c, num_leds); + template class CHIPSET, uint8_t DATA_PIN> CLEDController &add_leds(int num_leds) { + static CHIPSET CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } #endif - template class CHIPSET, EOrder RGB_ORDER> - CLEDController &add_leds(int num_leds) { - static CHIPSET c; - return add_leds(&c, num_leds); + template class CHIPSET, EOrder RGB_ORDER> CLEDController &add_leds(int num_leds) { + static CHIPSET CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } - template class CHIPSET> - CLEDController &add_leds(int num_leds) { - static CHIPSET c; - return add_leds(&c, num_leds); + template class CHIPSET> CLEDController &add_leds(int num_leds) { + static CHIPSET CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } #ifdef USE_OCTOWS2811 - template - CLEDController &add_leds(int num_leds) { - switch(CHIPSET) { - case OCTOWS2811: { static COctoWS2811Controller controller; return add_leds(&controller, num_leds); } - case OCTOWS2811_400: { static COctoWS2811Controller controller; return add_leds(&controller, num_leds); } + template CLEDController &add_leds(int num_leds) { + switch (CHIPSET) { + case OCTOWS2811: { + static COctoWS2811Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); + } + case OCTOWS2811_400: { + static COctoWS2811Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); + } #ifdef WS2813_800kHz - case OCTOWS2813: { static COctoWS2811Controller controller; return add_leds(&controller, num_leds); } + case OCTOWS2813: { + static COctoWS2811Controller CONTROLLER; + return add_leds(&CONTROLLER, num_leds); + } #endif } } - template - CLEDController &add_leds(int num_leds) { - return add_leds(num_leds); - } + template CLEDController &add_leds(int num_leds) { return add_leds(num_leds); } #endif #ifdef USE_WS2812SERIAL - template - CLEDController &add_leds(int num_leds) { - static CWS2812SerialController controller; - return add_leds(&controller, num_leds); + template CLEDController &add_leds(int num_leds) { + static CWS2812SerialController CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } #endif #ifdef SmartMatrix_h - template - CLEDController &add_leds(int num_leds) { + template CLEDController &add_leds(int num_leds) { switch (CHIPSET) { case SMART_MATRIX: { - static CSmartMatrixController controller; - return add_leds(&controller, num_leds); + static CSmartMatrixController CONTROLLER; + return add_leds(&CONTROLLER, num_leds); } } } #endif #ifdef FASTLED_HAS_BLOCKLESS - template - CLEDController &add_leds(int num_leds) { - switch(CHIPSET) { + template CLEDController &add_leds(int num_leds) { + switch (CHIPSET) { #ifdef PORTA_FIRST_PIN - case WS2811_PORTA: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2811_400_PORTA: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2813_PORTA: - return add_leds(new InlineBlockClocklessController(), num_leds); - case TM1803_PORTA: - return add_leds(new InlineBlockClocklessController(), num_leds); - case UCS1903_PORTA: - return add_leds(new InlineBlockClocklessController(), num_leds); + case WS2811_PORTA: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2811_400_PORTA: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2813_PORTA: + return add_leds(new InlineBlockClocklessController(), + num_leds); + case TM1803_PORTA: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case UCS1903_PORTA: + return add_leds( + new InlineBlockClocklessController(), + num_leds); #endif #ifdef PORTB_FIRST_PIN - case WS2811_PORTB: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2811_400_PORTB: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2813_PORTB: - return add_leds(new InlineBlockClocklessController(), num_leds); - case TM1803_PORTB: - return add_leds(new InlineBlockClocklessController(), num_leds); - case UCS1903_PORTB: - return add_leds(new InlineBlockClocklessController(), num_leds); + case WS2811_PORTB: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2811_400_PORTB: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2813_PORTB: + return add_leds(new InlineBlockClocklessController(), + num_leds); + case TM1803_PORTB: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case UCS1903_PORTB: + return add_leds( + new InlineBlockClocklessController(), + num_leds); #endif #ifdef PORTC_FIRST_PIN - case WS2811_PORTC: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2811_400_PORTC: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2813_PORTC: - return add_leds(new InlineBlockClocklessController(), num_leds); - case TM1803_PORTC: - return add_leds(new InlineBlockClocklessController(), num_leds); - case UCS1903_PORTC: - return add_leds(new InlineBlockClocklessController(), num_leds); + case WS2811_PORTC: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2811_400_PORTC: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2813_PORTC: + return add_leds(new InlineBlockClocklessController(), + num_leds); + case TM1803_PORTC: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case UCS1903_PORTC: + return add_leds( + new InlineBlockClocklessController(), + num_leds); #endif #ifdef PORTD_FIRST_PIN - case WS2811_PORTD: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2811_400_PORTD: - return add_leds(new InlineBlockClocklessController(), num_leds); - case WS2813_PORTD: - return add_leds(new InlineBlockClocklessController(), num_leds); - case TM1803_PORTD: - return add_leds(new InlineBlockClocklessController(), num_leds); - case UCS1903_PORTD: - return add_leds(new InlineBlockClocklessController(), num_leds); + case WS2811_PORTD: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2811_400_PORTD: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case WS2813_PORTD: + return add_leds(new InlineBlockClocklessController(), + num_leds); + case TM1803_PORTD: + return add_leds( + new InlineBlockClocklessController(), + num_leds); + case UCS1903_PORTD: + return add_leds( + new InlineBlockClocklessController(), + num_leds); #endif #ifdef HAS_PORTDC - case WS2811_PORTDC: - return add_leds(new SixteenWayInlineBlockClocklessController(), num_leds); - case WS2811_400_PORTDC: - return add_leds(new SixteenWayInlineBlockClocklessController(), num_leds); - case WS2813_PORTDC: - return add_leds(new SixteenWayInlineBlockClocklessController(), num_leds); - case TM1803_PORTDC: - return add_leds(new SixteenWayInlineBlockClocklessController(), num_leds); - case UCS1903_PORTDC: - return add_leds(new SixteenWayInlineBlockClocklessController(), num_leds); + case WS2811_PORTDC: + return add_leds(new SixteenWayInlineBlockClocklessController(), + num_leds); + case WS2811_400_PORTDC: + return add_leds(new SixteenWayInlineBlockClocklessController(), + num_leds); + case WS2813_PORTDC: + return add_leds(new SixteenWayInlineBlockClocklessController(), + num_leds); + case TM1803_PORTDC: + return add_leds( + new SixteenWayInlineBlockClocklessController(), num_leds); + case UCS1903_PORTDC: + return add_leds( + new SixteenWayInlineBlockClocklessController(), num_leds); #endif - } + } } - template - CLEDController &add_leds(int num_leds) { - return add_leds(num_leds); + template CLEDController &add_leds(int num_leds) { + return add_leds(num_leds); } #endif @@ -343,10 +383,10 @@ class FastLEDLightOutputComponent : public Component, public AddressableLight { #endif }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_FAST_LED_LIGHT +#endif // USE_FAST_LED_LIGHT -#endif //ESPHOME_LIGHT_FAST_LED_LIGHT_OUTPUT_H +#endif // ESPHOME_LIGHT_FAST_LED_LIGHT_OUTPUT_H diff --git a/src/esphome/light/light_color_values.cpp b/src/esphome/light/light_color_values.cpp index 6ab2ade5..60ecae70 100644 --- a/src/esphome/light/light_color_values.cpp +++ b/src/esphome/light/light_color_values.cpp @@ -21,64 +21,35 @@ namespace light { static const char *TAG = "light.light_color_values"; #endif -float LightColorValues::get_state() const { - return this->state_; -} +float LightColorValues::get_state() const { return this->state_; } -void LightColorValues::set_state(float state) { - this->state_ = clamp(0.0f, 1.0f, state); -} -void LightColorValues::set_state(bool state) { - this->state_ = state ? 1.0f : 0.0f; -} +void LightColorValues::set_state(float state) { this->state_ = clamp(0.0f, 1.0f, state); } +void LightColorValues::set_state(bool state) { this->state_ = state ? 1.0f : 0.0f; } -float LightColorValues::get_brightness() const { - return this->brightness_; -} +float LightColorValues::get_brightness() const { return this->brightness_; } -void LightColorValues::set_brightness(float brightness) { - this->brightness_ = clamp(0.0f, 1.0f, brightness); -} +void LightColorValues::set_brightness(float brightness) { this->brightness_ = clamp(0.0f, 1.0f, brightness); } -float LightColorValues::get_red() const { - return this->red_; -} +float LightColorValues::get_red() const { return this->red_; } -void LightColorValues::set_red(float red) { - this->red_ = clamp(0.0f, 1.0f, red); -} +void LightColorValues::set_red(float red) { this->red_ = clamp(0.0f, 1.0f, red); } -float LightColorValues::get_green() const { - return this->green_; -} +float LightColorValues::get_green() const { return this->green_; } -void LightColorValues::set_green(float green) { - this->green_ = clamp(0.0f, 1.0f, green); -} +void LightColorValues::set_green(float green) { this->green_ = clamp(0.0f, 1.0f, green); } -float LightColorValues::get_blue() const { - return this->blue_; -} +float LightColorValues::get_blue() const { return this->blue_; } -void LightColorValues::set_blue(float blue) { - this->blue_ = clamp(0.0f, 1.0f, blue); -} +void LightColorValues::set_blue(float blue) { this->blue_ = clamp(0.0f, 1.0f, blue); } -float LightColorValues::get_white() const { - return white_; -} +float LightColorValues::get_white() const { return white_; } -void LightColorValues::set_white(float white) { - this->white_ = clamp(0.0f, 1.0f, white); -} +void LightColorValues::set_white(float white) { this->white_ = clamp(0.0f, 1.0f, white); } LightColorValues::LightColorValues() - : state_(0.0f), brightness_(1.0f), red_(1.0f), green_(1.0f), blue_(1.0f), white_(1.0f), color_temperature_{1.0f} { - -} + : state_(0.0f), brightness_(1.0f), red_(1.0f), green_(1.0f), blue_(1.0f), white_(1.0f), color_temperature_{1.0f} {} -LightColorValues LightColorValues::lerp(const LightColorValues &start, const LightColorValues &end, - float completion) { +LightColorValues LightColorValues::lerp(const LightColorValues &start, const LightColorValues &end, float completion) { LightColorValues v; v.set_state(esphome::lerp(start.get_state(), end.get_state(), completion)); v.set_brightness(esphome::lerp(start.get_brightness(), end.get_brightness(), completion)); @@ -91,8 +62,8 @@ LightColorValues LightColorValues::lerp(const LightColorValues &start, const Lig return v; } -LightColorValues::LightColorValues(float state, float brightness, float red, float green, float blue, - float white, float color_temperature) { +LightColorValues::LightColorValues(float state, float brightness, float red, float green, float blue, float white, + float color_temperature) { this->set_state(state); this->set_brightness(brightness); this->set_red(red); @@ -102,11 +73,9 @@ LightColorValues::LightColorValues(float state, float brightness, float red, flo this->set_color_temperature(color_temperature); } -LightColorValues::LightColorValues(bool state, float brightness, float red, float green, float blue, - float white, float color_temperature) - : LightColorValues(state ? 1.0f : 0.0f, brightness, red, green, blue, white, color_temperature) { - -} +LightColorValues::LightColorValues(bool state, float brightness, float red, float green, float blue, float white, + float color_temperature) + : LightColorValues(state ? 1.0f : 0.0f, brightness, red, green, blue, white, color_temperature) {} void LightColorValues::normalize_color(const LightTraits &traits) { if (traits.has_rgb()) { @@ -145,63 +114,43 @@ void LightColorValues::dump_json(JsonObject &root, const LightTraits &traits) co } bool LightColorValues::operator==(const LightColorValues &rhs) const { - return state_ == rhs.state_ && - brightness_ == rhs.brightness_ && - red_ == rhs.red_ && - green_ == rhs.green_ && - blue_ == rhs.blue_ && - white_ == rhs.white_ && - color_temperature_ == rhs.color_temperature_; + return state_ == rhs.state_ && brightness_ == rhs.brightness_ && red_ == rhs.red_ && green_ == rhs.green_ && + blue_ == rhs.blue_ && white_ == rhs.white_ && color_temperature_ == rhs.color_temperature_; } -bool LightColorValues::operator!=(const LightColorValues &rhs) const { - return !(rhs == *this); -} +bool LightColorValues::operator!=(const LightColorValues &rhs) const { return !(rhs == *this); } void LightColorValues::as_rgbw(float *red, float *green, float *blue, float *white) const { this->as_rgb(red, green, blue); *white = this->state_ * this->white_; } -void LightColorValues::as_rgbww(float color_temperature_cw, - float color_temperature_ww, - float *red, - float *green, - float *blue, - float *cold_white, - float *warm_white) const { +void LightColorValues::as_rgbww(float color_temperature_cw, float color_temperature_ww, float *red, float *green, + float *blue, float *cold_white, float *warm_white) const { this->as_rgb(red, green, blue); const float color_temp = clamp(color_temperature_cw, color_temperature_ww, this->color_temperature_); const float ww_fraction = (color_temp - color_temperature_cw) / (color_temperature_ww - color_temperature_cw); const float cw_fraction = 1.0f - ww_fraction; - const float max_ = std::max(ww_fraction, cw_fraction); - *cold_white = this->state_ * this->white_ * (cw_fraction / max_); - *warm_white = this->state_ * this->white_ * (ww_fraction / max_); + const float max_cw_ww = std::max(ww_fraction, cw_fraction); + *cold_white = this->state_ * this->white_ * (cw_fraction / max_cw_ww); + *warm_white = this->state_ * this->white_ * (ww_fraction / max_cw_ww); } -void LightColorValues::as_cwww(float color_temperature_cw, - float color_temperature_ww, - float *cold_white, +void LightColorValues::as_cwww(float color_temperature_cw, float color_temperature_ww, float *cold_white, float *warm_white) const { const float color_temp = clamp(color_temperature_cw, color_temperature_ww, this->color_temperature_); const float ww_fraction = (color_temp - color_temperature_cw) / (color_temperature_ww - color_temperature_cw); const float cw_fraction = 1.0f - ww_fraction; - const float max_ = std::max(ww_fraction, cw_fraction); - *cold_white = this->state_ * this->brightness_ * (cw_fraction / max_); - *warm_white = this->state_ * this->brightness_ * (ww_fraction / max_); + const float max_cw_ww = std::max(ww_fraction, cw_fraction); + *cold_white = this->state_ * this->brightness_ * (cw_fraction / max_cw_ww); + *warm_white = this->state_ * this->brightness_ * (ww_fraction / max_cw_ww); } void LightColorValues::as_rgb(float *red, float *green, float *blue) const { *red = this->state_ * this->brightness_ * this->red_; *green = this->state_ * this->brightness_ * this->green_; *blue = this->state_ * this->brightness_ * this->blue_; } -void LightColorValues::as_brightness(float *brightness) const { - *brightness = this->state_ * this->brightness_; -} -void LightColorValues::as_binary(bool *binary) const { - *binary = this->state_ == 1.0f; -} -LightColorValues LightColorValues::from_binary(bool state) { - return {state, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}; -} +void LightColorValues::as_brightness(float *brightness) const { *brightness = this->state_ * this->brightness_; } +void LightColorValues::as_binary(bool *binary) const { *binary = this->state_ == 1.0f; } +LightColorValues LightColorValues::from_binary(bool state) { return {state, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}; } LightColorValues LightColorValues::from_monochromatic(float brightness) { if (brightness == 0.0f) return {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}; @@ -224,18 +173,14 @@ LightColorValues LightColorValues::from_rgbw(float r, float g, float b, float w) return {1.0f, brightness, r / brightness, g / brightness, b / brightness, w / brightness}; } } -float LightColorValues::get_color_temperature() const { - return this->color_temperature_; -} +float LightColorValues::get_color_temperature() const { return this->color_temperature_; } void LightColorValues::set_color_temperature(float color_temperature) { this->color_temperature_ = std::max(0.000001f, color_temperature); } -bool LightColorValues::is_on() const { - return this->get_state() != 0.0f; -} +bool LightColorValues::is_on() const { return this->get_state() != 0.0f; } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/light_color_values.h b/src/esphome/light/light_color_values.h index 964191b2..f3a0805c 100644 --- a/src/esphome/light/light_color_values.h +++ b/src/esphome/light/light_color_values.h @@ -31,9 +31,11 @@ class LightColorValues { /// Construct the LightColorValues with all attributes enabled, but state set to 0.0 LightColorValues(); - LightColorValues(float state, float brightness, float red, float green, float blue, float white, float color_temperature = 1.0f); + LightColorValues(float state, float brightness, float red, float green, float blue, float white, + float color_temperature = 1.0f); - LightColorValues(bool state, float brightness, float red, float green, float blue, float white, float color_temperature = 1.0f); + LightColorValues(bool state, float brightness, float red, float green, float blue, float white, + float color_temperature = 1.0f); static LightColorValues from_binary(bool state); @@ -79,7 +81,8 @@ class LightColorValues { void as_rgbw(float *red, float *green, float *blue, float *white) const; - void as_rgbww(float color_temperature_cw, float color_temperature_ww, float *red, float *green, float *blue, float *cold_white, float *warm_white) const; + void as_rgbww(float color_temperature_cw, float color_temperature_ww, float *red, float *green, float *blue, + float *cold_white, float *warm_white) const; void as_cwww(float color_temperature_cw, float color_temperature_ww, float *cold_white, float *warm_white) const; @@ -111,19 +114,19 @@ class LightColorValues { void set_color_temperature(float color_temperature); protected: - float state_; ///< ON / OFF, float for transition + float state_; ///< ON / OFF, float for transition float brightness_; float red_; float green_; float blue_; float white_; - float color_temperature_; ///< Color Temperature in Mired + float color_temperature_; ///< Color Temperature in Mired }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_LIGHT_COLOR_VALUES_H +#endif // ESPHOME_LIGHT_LIGHT_COLOR_VALUES_H diff --git a/src/esphome/light/light_effect.cpp b/src/esphome/light/light_effect.cpp index cab2c9b2..03bbf5e4 100644 --- a/src/esphome/light/light_effect.cpp +++ b/src/esphome/light/light_effect.cpp @@ -33,36 +33,22 @@ RandomLightEffect::RandomLightEffect(const std::string &name) : LightEffect(name void RandomLightEffect::set_transition_length(uint32_t transition_length) { this->transition_length_ = transition_length; } -void RandomLightEffect::set_update_interval(uint32_t update_interval) { - this->update_interval_ = update_interval; -} +void RandomLightEffect::set_update_interval(uint32_t update_interval) { this->update_interval_ = update_interval; } LightEffect::LightEffect(const std::string &name) : name_(name) {} -void LightEffect::start() { - -} -void LightEffect::start_() { - this->start(); -} -void LightEffect::stop() { - -} -const std::string &LightEffect::get_name() { - return this->name_; -} -void LightEffect::init() { - -} -void LightEffect::init_(LightState *state) { +void LightEffect::start() {} +void LightEffect::start_internal() { this->start(); } +void LightEffect::stop() {} +const std::string &LightEffect::get_name() { return this->name_; } +void LightEffect::init() {} +void LightEffect::init_internal(LightState *state) { this->state_ = state; this->init(); } LambdaLightEffect::LambdaLightEffect(const std::string &name, const std::function &f, uint32_t update_interval) - : LightEffect(name), f_(f), update_interval_(update_interval) { - -} + : LightEffect(name), f_(f), update_interval_(update_interval) {} void LambdaLightEffect::apply() { const uint32_t now = millis(); @@ -83,23 +69,17 @@ void StrobeLightEffect::apply() { } StrobeLightEffect::StrobeLightEffect(const std::string &name) : LightEffect(name) { this->colors_.reserve(2); - this->colors_.push_back(StrobeLightEffectColor{ - .color = LightColorValues(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f), - .duration = 500 - }); - this->colors_.push_back(StrobeLightEffectColor{ - .color = LightColorValues(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), - .duration = 500 - }); + this->colors_.push_back( + StrobeLightEffectColor{.color = LightColorValues(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f), .duration = 500}); + this->colors_.push_back( + StrobeLightEffectColor{.color = LightColorValues(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), .duration = 500}); } -void StrobeLightEffect::set_colors(const std::vector &colors) { - this->colors_ = colors; -} +void StrobeLightEffect::set_colors(const std::vector &colors) { this->colors_ = colors; } inline float random_cubic_float() { const float r = random_float() * 2.0f - 1.0f; - return r*r*r; + return r * r * r; } void FlickerLightEffect::apply() { @@ -109,7 +89,8 @@ void FlickerLightEffect::apply() { const float alpha = this->alpha_; const float beta = 1.0f - alpha; out.set_state(remote.get_state()); - out.set_brightness(remote.get_brightness() * beta + current.get_brightness() * alpha + (random_cubic_float() * this->intensity_)); + out.set_brightness(remote.get_brightness() * beta + current.get_brightness() * alpha + + (random_cubic_float() * this->intensity_)); out.set_red(remote.get_red() * beta + current.get_red() * alpha + (random_cubic_float() * this->intensity_)); out.set_green(remote.get_green() * beta + current.get_green() * alpha + (random_cubic_float() * this->intensity_)); out.set_blue(remote.get_blue() * beta + current.get_blue() * alpha + (random_cubic_float() * this->intensity_)); @@ -117,16 +98,12 @@ void FlickerLightEffect::apply() { this->state_->set_immediately_without_sending(out); } -void FlickerLightEffect::set_alpha(float alpha) { - this->alpha_ = alpha; -} -void FlickerLightEffect::set_intensity(float intensity) { - this->intensity_ = intensity; -} +void FlickerLightEffect::set_alpha(float alpha) { this->alpha_ = alpha; } +void FlickerLightEffect::set_intensity(float intensity) { this->intensity_ = intensity; } FlickerLightEffect::FlickerLightEffect(const std::string &name) : LightEffect(name) {} -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/light_effect.h b/src/esphome/light/light_effect.h index ad4ebcab..a27a98fb 100644 --- a/src/esphome/light/light_effect.h +++ b/src/esphome/light/light_effect.h @@ -22,7 +22,7 @@ class LightEffect { /// Initialize this LightEffect. Will be called once after creation. virtual void start(); - virtual void start_(); + virtual void start_internal(); /// Called when this effect is about to be removed virtual void stop(); @@ -35,7 +35,7 @@ class LightEffect { /// Internal method called by the LightState when this light effect is registered in it. virtual void init(); - void init_(LightState *state); + void init_internal(LightState *state); protected: LightState *state_{nullptr}; @@ -97,15 +97,16 @@ class FlickerLightEffect : public LightEffect { void set_alpha(float alpha); void set_intensity(float intensity); + protected: float intensity_{0.015f}; float alpha_{0.95f}; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_LIGHT_EFFECT_H +#endif // ESPHOME_LIGHT_LIGHT_EFFECT_H diff --git a/src/esphome/light/light_output_component.cpp b/src/esphome/light/light_output_component.cpp index a9f15a4b..cf320fe5 100644 --- a/src/esphome/light/light_output_component.cpp +++ b/src/esphome/light/light_output_component.cpp @@ -13,32 +13,24 @@ namespace light { using output::FloatOutput; -LightTraits BinaryLightOutput::get_traits() { - return {false, false, false, false}; -} +LightTraits BinaryLightOutput::get_traits() { return {false, false, false, false}; } void BinaryLightOutput::write_state(LightState *state) { bool value; state->current_values_as_binary(&value); - if (value) this->output_->turn_on(); - else this->output_->turn_off(); -} -BinaryLightOutput::BinaryLightOutput(output::BinaryOutput *output) - : LightOutput(), output_(output) { - + if (value) + this->output_->turn_on(); + else + this->output_->turn_off(); } +BinaryLightOutput::BinaryLightOutput(output::BinaryOutput *output) : LightOutput(), output_(output) {} -LightTraits MonochromaticLightOutput::get_traits() { - return {true, false, false, false}; -} +LightTraits MonochromaticLightOutput::get_traits() { return {true, false, false, false}; } void MonochromaticLightOutput::write_state(LightState *state) { float value; state->current_values_as_brightness(&value); this->output_->set_level(value); } -MonochromaticLightOutput::MonochromaticLightOutput(FloatOutput *output) - : output_(output) { - -} +MonochromaticLightOutput::MonochromaticLightOutput(FloatOutput *output) : output_(output) {} LightTraits CWWWLightOutput::get_traits() { LightTraits traits{true, false, false, true}; @@ -48,23 +40,18 @@ LightTraits CWWWLightOutput::get_traits() { } void CWWWLightOutput::write_state(LightState *state) { float cold_white, warm_white; - state->current_values_as_cwww(this->cold_white_mireds_, this->warm_white_mireds_, - &cold_white, &warm_white); + state->current_values_as_cwww(this->cold_white_mireds_, this->warm_white_mireds_, &cold_white, &warm_white); this->cold_white_->set_level(cold_white); this->warm_white_->set_level(warm_white); } -CWWWLightOutput::CWWWLightOutput(float cold_white_mireds, - float warm_white_mireds, - FloatOutput *cold_white, +CWWWLightOutput::CWWWLightOutput(float cold_white_mireds, float warm_white_mireds, FloatOutput *cold_white, FloatOutput *warm_white) - : cold_white_mireds_(cold_white_mireds), warm_white_mireds_(warm_white_mireds), - cold_white_(cold_white), warm_white_(warm_white) { - -} + : cold_white_mireds_(cold_white_mireds), + warm_white_mireds_(warm_white_mireds), + cold_white_(cold_white), + warm_white_(warm_white) {} -LightTraits RGBLightOutput::get_traits() { - return {true, true, false, false}; -} +LightTraits RGBLightOutput::get_traits() { return {true, true, false, false}; } void RGBLightOutput::write_state(LightState *state) { float red, green, blue; state->current_values_as_rgb(&red, &green, &blue); @@ -73,13 +60,9 @@ void RGBLightOutput::write_state(LightState *state) { this->blue_->set_level(blue); } RGBLightOutput::RGBLightOutput(FloatOutput *red, FloatOutput *green, FloatOutput *blue) - : red_(red), green_(green), blue_(blue) { - -} + : red_(red), green_(green), blue_(blue) {} -LightTraits RGBWLightOutput::get_traits() { - return {true, true, true, false}; -} +LightTraits RGBWLightOutput::get_traits() { return {true, true, true, false}; } void RGBWLightOutput::write_state(LightState *state) { float red, green, blue, white; state->current_values_as_rgbw(&red, &green, &blue, &white); @@ -89,9 +72,7 @@ void RGBWLightOutput::write_state(LightState *state) { this->white_->set_level(white); } RGBWLightOutput::RGBWLightOutput(FloatOutput *red, FloatOutput *green, FloatOutput *blue, FloatOutput *white) - : red_(red), green_(green), blue_(blue), white_(white) { - -} + : red_(red), green_(green), blue_(blue), white_(white) {} LightTraits RGBWWLightOutput::get_traits() { LightTraits traits{true, true, true, true}; @@ -101,29 +82,27 @@ LightTraits RGBWWLightOutput::get_traits() { } void RGBWWLightOutput::write_state(LightState *state) { float red, green, blue, cold_white, warm_white; - state->current_values_as_rgbww(this->cold_white_mireds_, this->warm_white_mireds_, - &red, &green, &blue, &cold_white, &warm_white); + state->current_values_as_rgbww(this->cold_white_mireds_, this->warm_white_mireds_, &red, &green, &blue, &cold_white, + &warm_white); this->red_->set_level(red); this->green_->set_level(green); this->blue_->set_level(blue); this->cold_white_->set_level(cold_white); this->warm_white_->set_level(warm_white); } -RGBWWLightOutput::RGBWWLightOutput(float cold_white_mireds, - float warm_white_mireds, - FloatOutput *red, - FloatOutput *green, - FloatOutput *blue, - FloatOutput *cold_white, +RGBWWLightOutput::RGBWWLightOutput(float cold_white_mireds, float warm_white_mireds, FloatOutput *red, + FloatOutput *green, FloatOutput *blue, FloatOutput *cold_white, FloatOutput *warm_white) - : cold_white_mireds_(cold_white_mireds), warm_white_mireds_(warm_white_mireds), - red_(red), green_(green), blue_(blue), - cold_white_(cold_white), warm_white_(warm_white) { - -} + : cold_white_mireds_(cold_white_mireds), + warm_white_mireds_(warm_white_mireds), + red_(red), + green_(green), + blue_(blue), + cold_white_(cold_white), + warm_white_(warm_white) {} -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/light_output_component.h b/src/esphome/light/light_output_component.h index 111365e0..fd8b7444 100644 --- a/src/esphome/light/light_output_component.h +++ b/src/esphome/light/light_output_component.h @@ -35,9 +35,7 @@ class MonochromaticLightOutput : public LightOutput { class CWWWLightOutput : public LightOutput { public: - CWWWLightOutput(float cold_white_mireds, - float warm_white_mireds, - output::FloatOutput *cold_white, + CWWWLightOutput(float cold_white_mireds, float warm_white_mireds, output::FloatOutput *cold_white, output::FloatOutput *warm_white); LightTraits get_traits() override; @@ -64,9 +62,7 @@ class RGBLightOutput : public LightOutput { class RGBWLightOutput : public LightOutput { public: - RGBWLightOutput(output::FloatOutput *red, - output::FloatOutput *green, - output::FloatOutput *blue, + RGBWLightOutput(output::FloatOutput *red, output::FloatOutput *green, output::FloatOutput *blue, output::FloatOutput *white); LightTraits get_traits() override; void write_state(LightState *state) override; @@ -80,12 +76,8 @@ class RGBWLightOutput : public LightOutput { class RGBWWLightOutput : public LightOutput { public: - RGBWWLightOutput(float cold_white_mireds, - float warm_white_mireds, - output::FloatOutput *red, - output::FloatOutput *green, - output::FloatOutput *blue, - output::FloatOutput *cold_white, + RGBWWLightOutput(float cold_white_mireds, float warm_white_mireds, output::FloatOutput *red, + output::FloatOutput *green, output::FloatOutput *blue, output::FloatOutput *cold_white, output::FloatOutput *warm_white); LightTraits get_traits() override; @@ -101,10 +93,10 @@ class RGBWWLightOutput : public LightOutput { output::FloatOutput *warm_white_; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_LIGHT_OUTPUT_COMPONENT_H +#endif // ESPHOME_LIGHT_LIGHT_OUTPUT_COMPONENT_H diff --git a/src/esphome/light/light_state.cpp b/src/esphome/light/light_state.cpp index 1e976d71..6bacd19d 100644 --- a/src/esphome/light/light_state.cpp +++ b/src/esphome/light/light_state.cpp @@ -18,11 +18,9 @@ namespace light { static const char *TAG = "light.state"; void LightState::start_transition(const LightColorValues &target, uint32_t length) { - if (this->get_traits().has_brightness()) { - this->transformer_ = make_unique(millis(), length, - this->get_current_values_lazy(), - target); + this->transformer_ = + make_unique(millis(), length, this->get_current_values_lazy(), target); this->remote_values_ = this->transformer_->get_remote_values(); } else { this->set_immediately(target); @@ -46,10 +44,7 @@ void LightState::start_flash(const LightColorValues &target, uint32_t length) { this->transformer_ = make_unique(millis(), length, end_colors, target); } -LightState::LightState(const std::string &name, LightOutput *output) - : Nameable(name), output_(output) { - -} +LightState::LightState(const std::string &name, LightOutput *output) : Nameable(name), output_(output) {} void LightState::set_immediately_without_sending(const LightColorValues &target) { this->transformer_ = nullptr; @@ -88,9 +83,7 @@ LightColorValues LightState::get_remote_values() { return out; } -const LightColorValues &LightState::get_current_values_lazy() { - return this->values_; -} +const LightColorValues &LightState::get_current_values_lazy() { return this->values_; } std::string LightState::get_effect_name() { if (this->active_effect_ != nullptr) @@ -106,12 +99,10 @@ void LightState::start_effect(uint32_t effect_index) { this->active_effect_ = this->effects_[effect_index - 1]; this->active_effect_index_ = effect_index; - this->active_effect_->start_(); + this->active_effect_->start_internal(); } -bool LightState::supports_effects() { - return !this->effects_.empty(); -} +bool LightState::supports_effects() { return !this->effects_.empty(); } void LightState::set_transformer(std::unique_ptr transformer) { this->transformer_ = std::move(transformer); } @@ -125,9 +116,7 @@ void LightState::stop_effect() { void LightState::set_default_transition_length(uint32_t default_transition_length) { this->default_transition_length_ = default_transition_length; } -uint32_t LightState::get_default_transition_length() const { - return this->default_transition_length_; -} +uint32_t LightState::get_default_transition_length() const { return this->default_transition_length_; } void LightState::dump_json(JsonObject &root) { if (this->supports_effects()) root["effect"] = this->get_effect_name(); @@ -150,7 +139,7 @@ void LightState::setup() { this->output_->setup_state(this); for (auto *effect : this->effects_) { - effect->init_(this); + effect->init_internal(this); } this->rtc_ = global_preferences.make_preference(this->get_object_id_hash()); @@ -169,21 +158,11 @@ void LightState::setup() { call.set_effect(recovered.effect); call.perform(); } -float LightState::get_setup_priority() const { - return setup_priority::HARDWARE - 1.0f; -} -LightOutput *LightState::get_output() const { - return this->output_; -} -float LightState::get_gamma_correct() const { - return this->gamma_correct_; -} -void LightState::set_gamma_correct(float gamma_correct) { - this->gamma_correct_ = gamma_correct; -} -void LightState::current_values_as_binary(bool *binary) { - this->get_current_values().as_binary(binary); -} +float LightState::get_setup_priority() const { return setup_priority::HARDWARE - 1.0f; } +LightOutput *LightState::get_output() const { return this->output_; } +float LightState::get_gamma_correct() const { return this->gamma_correct_; } +void LightState::set_gamma_correct(float gamma_correct) { this->gamma_correct_ = gamma_correct; } +void LightState::current_values_as_binary(bool *binary) { this->get_current_values().as_binary(binary); } void LightState::current_values_as_brightness(float *brightness) { this->get_current_values().as_brightness(brightness); *brightness = gamma_correct(*brightness, this->gamma_correct_); @@ -201,27 +180,19 @@ void LightState::current_values_as_rgbw(float *red, float *green, float *blue, f *blue = gamma_correct(*blue, this->gamma_correct_); *white = gamma_correct(*white, this->gamma_correct_); } -void LightState::current_values_as_rgbww(float color_temperature_cw, - float color_temperature_ww, - float *red, - float *green, - float *blue, - float *cold_white, - float *warm_white) { - this->get_current_values().as_rgbww(color_temperature_cw, color_temperature_ww, - red, green, blue, cold_white, warm_white); +void LightState::current_values_as_rgbww(float color_temperature_cw, float color_temperature_ww, float *red, + float *green, float *blue, float *cold_white, float *warm_white) { + this->get_current_values().as_rgbww(color_temperature_cw, color_temperature_ww, red, green, blue, cold_white, + warm_white); *red = gamma_correct(*red, this->gamma_correct_); *green = gamma_correct(*green, this->gamma_correct_); *blue = gamma_correct(*blue, this->gamma_correct_); *cold_white = gamma_correct(*cold_white, this->gamma_correct_); *warm_white = gamma_correct(*warm_white, this->gamma_correct_); } -void LightState::current_values_as_cwww(float color_temperature_cw, - float color_temperature_ww, - float *cold_white, +void LightState::current_values_as_cwww(float color_temperature_cw, float color_temperature_ww, float *cold_white, float *warm_white) { - this->get_current_values().as_cwww(color_temperature_cw, color_temperature_ww, - cold_white, warm_white); + this->get_current_values().as_cwww(color_temperature_cw, color_temperature_ww, cold_white, warm_white); *cold_white = gamma_correct(*cold_white, this->gamma_correct_); *warm_white = gamma_correct(*warm_white, this->gamma_correct_); } @@ -235,33 +206,21 @@ void LightState::loop() { this->next_write_ = false; } } -LightTraits LightState::get_traits() { - return this->output_->get_traits(); -} -const std::vector &LightState::get_effects() const { - return this->effects_; -} +LightTraits LightState::get_traits() { return this->output_->get_traits(); } +const std::vector &LightState::get_effects() const { return this->effects_; } void LightState::add_effects(const std::vector effects) { this->effects_.reserve(this->effects_.size() + effects.size()); for (auto *effect : effects) { this->effects_.push_back(effect); } } -LightState::StateCall LightState::turn_on() { - return this->make_call().set_state(true); -} -LightState::StateCall LightState::turn_off() { - return this->make_call().set_state(false); -} +LightState::StateCall LightState::turn_on() { return this->make_call().set_state(true); } +LightState::StateCall LightState::turn_off() { return this->make_call().set_state(false); } LightState::StateCall LightState::toggle() { return this->make_call().set_state(this->get_remote_values().get_state() == 0.0f); } -LightState::StateCall LightState::make_call() { - return LightState::StateCall(this); -} -uint32_t LightState::hash_base_() { - return 1114400283; -} +LightState::StateCall LightState::make_call() { return LightState::StateCall(this); } +uint32_t LightState::hash_base() { return 1114400283; } void LightState::dump_config() { ESP_LOGCONFIG(TAG, "Light '%s'", this->get_name().c_str()); if (this->get_traits().has_brightness()) { @@ -274,12 +233,8 @@ void LightState::dump_config() { } } #ifdef USE_MQTT_LIGHT -MQTTJSONLightComponent *LightState::get_mqtt() const { - return this->mqtt_; -} -void LightState::set_mqtt(MQTTJSONLightComponent *mqtt) { - this->mqtt_ = mqtt; -} +MQTTJSONLightComponent *LightState::get_mqtt() const { return this->mqtt_; } +void LightState::set_mqtt(MQTTJSONLightComponent *mqtt) { this->mqtt_ = mqtt; } #endif LightState::StateCall &LightState::StateCall::set_state(bool state) { @@ -381,7 +336,7 @@ LightState::StateCall &LightState::StateCall::set_effect(const std::string &effe } return *this; } -LightState::StateCall &LightState::StateCall::set_effect(optional effect) { +LightState::StateCall &LightState::StateCall::set_effect(optional effect) { if (effect.has_value()) { this->set_effect(*effect); } @@ -404,7 +359,8 @@ LightState::StateCall &LightState::StateCall::parse_color_json(JsonObject &root) case PARSE_TOGGLE: this->set_state(this->state_->get_remote_values().get_state() == 0.0f); break; - case PARSE_NONE:break; + case PARSE_NONE: + break; } } @@ -479,19 +435,18 @@ void LightState::StateCall::perform() const { if (traits.has_color_temperature() && this->color_temperature_.has_value()) { v.set_color_temperature(*this->color_temperature_); - ESP_LOGD(TAG, " Color Temperature: %.1f mireds", - v.get_color_temperature()); + ESP_LOGD(TAG, " Color Temperature: %.1f mireds", v.get_color_temperature()); } v.normalize_color(this->state_->output_->get_traits()); if (traits.has_rgb() && (this->red_.has_value() || this->green_.has_value() || this->blue_.has_value())) { if (traits.has_rgb_white_value() && this->white_.has_value()) { - ESP_LOGD(TAG, " Red=%.0f%%, Green=%.0f%%, Blue=%.0f%%, White=%.0f%%", - v.get_red() * 100.0f, v.get_green() * 100.0f, v.get_blue() * 100.0f, v.get_white() * 100.0f); + ESP_LOGD(TAG, " Red=%.0f%%, Green=%.0f%%, Blue=%.0f%%, White=%.0f%%", v.get_red() * 100.0f, + v.get_green() * 100.0f, v.get_blue() * 100.0f, v.get_white() * 100.0f); } else { - ESP_LOGD(TAG, " Red=%.0f%%, Green=%.0f%%, Blue=%.0f%%", - v.get_red() * 100.0f, v.get_green() * 100.0f, v.get_blue() * 100.0f); + ESP_LOGD(TAG, " Red=%.0f%%, Green=%.0f%%, Blue=%.0f%%", v.get_red() * 100.0f, v.get_green() * 100.0f, + v.get_blue() * 100.0f); } } @@ -525,17 +480,12 @@ void LightState::StateCall::perform() const { this->state_->rtc_.save(&saved); this->state_->send_values(); } -LightState::StateCall::StateCall(LightState *state) - : state_(state) { - -} - -void LightOutput::setup_state(LightState *state) { +LightState::StateCall::StateCall(LightState *state) : state_(state) {} -} +void LightOutput::setup_state(LightState *state) {} -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/light_state.h b/src/esphome/light/light_state.h index 3b33e869..6afc3ce3 100644 --- a/src/esphome/light/light_state.h +++ b/src/esphome/light/light_state.h @@ -24,12 +24,9 @@ using light_send_callback_t = std::function; class LightEffect; class LightOutput; -template -class ToggleAction; -template -class TurnOffAction; -template -class TurnOnAction; +template class ToggleAction; +template class TurnOffAction; +template class TurnOnAction; #ifdef USE_MQTT_LIGHT class MQTTJSONLightComponent; @@ -81,27 +78,17 @@ class LightState : public Nameable, public Component { void current_values_as_rgbw(float *red, float *green, float *blue, float *white); - void current_values_as_rgbww(float color_temperature_cw, - float color_temperature_ww, - float *red, - float *green, - float *blue, - float *cold_white, - float *warm_white); - - void current_values_as_cwww(float color_temperature_cw, - float color_temperature_ww, - float *cold_white, + void current_values_as_rgbww(float color_temperature_cw, float color_temperature_ww, float *red, float *green, + float *blue, float *cold_white, float *warm_white); + + void current_values_as_cwww(float color_temperature_cw, float color_temperature_ww, float *cold_white, float *warm_white); LightTraits get_traits(); - template - ToggleAction *make_toggle_action(); - template - TurnOffAction *make_turn_off_action(); - template - TurnOnAction *make_turn_on_action(); + template ToggleAction *make_toggle_action(); + template TurnOffAction *make_turn_off_action(); + template TurnOnAction *make_turn_on_action(); class StateCall { public: @@ -220,7 +207,7 @@ class LightState : public Nameable, public Component { #endif protected: - uint32_t hash_base_() override; + uint32_t hash_base() override; ESPPreferenceObject rtc_; uint32_t default_transition_length_{1000}; @@ -230,7 +217,7 @@ class LightState : public Nameable, public Component { LightColorValues values_{}; LightColorValues remote_values_{}; CallbackManager remote_values_callback_{}; - LightOutput *output_; ///< Store the output to allow effects to have more access. + LightOutput *output_; ///< Store the output to allow effects to have more access. bool next_write_{true}; float gamma_correct_{2.8f}; std::vector effects_; @@ -250,13 +237,11 @@ class LightOutput { virtual void write_state(LightState *state) = 0; }; -template -class ToggleAction : public Action { +template class ToggleAction : public Action { public: explicit ToggleAction(LightState *state); - template - void set_transition_length(V value) { this->transition_length_ = value; } + template void set_transition_length(V value) { this->transition_length_ = value; } void play(Ts... x) override; @@ -265,13 +250,11 @@ class ToggleAction : public Action { TemplatableValue transition_length_; }; -template -class TurnOffAction : public Action { +template class TurnOffAction : public Action { public: explicit TurnOffAction(LightState *state); - template - void set_transition_length(V value) { this->transition_length_ = value; } + template void set_transition_length(V value) { this->transition_length_ = value; } void play(Ts... x) override; @@ -280,29 +263,19 @@ class TurnOffAction : public Action { TemplatableValue transition_length_; }; -template -class TurnOnAction : public Action { +template class TurnOnAction : public Action { public: explicit TurnOnAction(LightState *state) : state_(state) {} - template - void set_transition_length(V value) { this->transition_length_ = value; } - template - void set_flash_length(V value) { this->flash_length_ = value; } - template - void set_brightness(V value) { this->brightness_ = value; } - template - void set_red(V value) { this->red_ = value; } - template - void set_green(V value) { this->green_ = value; } - template - void set_blue(V value) { this->blue_ = value; } - template - void set_white(V value) { this->white_ = value; } - template - void set_color_temperature(V value) { this->color_temperature_ = value; } - template - void set_effect(V value) { this->effect_ = value; } + template void set_transition_length(V value) { this->transition_length_ = value; } + template void set_flash_length(V value) { this->flash_length_ = value; } + template void set_brightness(V value) { this->brightness_ = value; } + template void set_red(V value) { this->red_ = value; } + template void set_green(V value) { this->green_ = value; } + template void set_blue(V value) { this->blue_ = value; } + template void set_white(V value) { this->white_ = value; } + template void set_color_temperature(V value) { this->color_temperature_ = value; } + template void set_effect(V value) { this->effect_ = value; } void play(Ts... x) override; @@ -320,24 +293,17 @@ class TurnOnAction : public Action { }; // =============== TEMPLATE DEFINITIONS =============== -template -ToggleAction *LightState::make_toggle_action() { - return new ToggleAction(this); -} -template -TurnOffAction *LightState::make_turn_off_action() { +template ToggleAction *LightState::make_toggle_action() { return new ToggleAction(this); } +template TurnOffAction *LightState::make_turn_off_action() { return new TurnOffAction(this); } -template -TurnOnAction *LightState::make_turn_on_action() { +template TurnOnAction *LightState::make_turn_on_action() { return new TurnOnAction(this); } -template -ToggleAction::ToggleAction(LightState *state) : state_(state) {} +template ToggleAction::ToggleAction(LightState *state) : state_(state) {} -template -void ToggleAction::play(Ts... x) { +template void ToggleAction::play(Ts... x) { auto call = this->state_->toggle(); if (this->transition_length_.has_value()) { call.set_transition_length(this->transition_length_.value(x...)); @@ -345,10 +311,8 @@ void ToggleAction::play(Ts... x) { call.perform(); this->play_next(x...); } -template -TurnOffAction::TurnOffAction(LightState *state) : state_(state) {} -template -void TurnOffAction::play(Ts... x) { +template TurnOffAction::TurnOffAction(LightState *state) : state_(state) {} +template void TurnOffAction::play(Ts... x) { auto call = this->state_->turn_off(); if (this->transition_length_.has_value()) { call.set_transition_length(this->transition_length_.value(x...)); @@ -356,8 +320,7 @@ void TurnOffAction::play(Ts... x) { call.perform(); this->play_next(x...); } -template -void TurnOnAction::play(Ts... x) { +template void TurnOnAction::play(Ts... x) { auto call = this->state_->turn_on(); if (this->brightness_.has_value()) { call.set_brightness(this->brightness_.value(x...)); @@ -390,12 +353,12 @@ void TurnOnAction::play(Ts... x) { this->play_next(x...); } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END #include "esphome/light/mqtt_json_light_component.h" -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_LIGHT_STATE_H +#endif // ESPHOME_LIGHT_LIGHT_STATE_H diff --git a/src/esphome/light/light_traits.cpp b/src/esphome/light/light_traits.cpp index f11c5dff..607f8dd7 100644 --- a/src/esphome/light/light_traits.cpp +++ b/src/esphome/light/light_traits.cpp @@ -8,42 +8,22 @@ ESPHOME_NAMESPACE_BEGIN namespace light { -LightTraits::LightTraits() - : brightness_(false), rgb_(false), rgb_white_value_(false), color_temperature_(false) { - -} +LightTraits::LightTraits() : brightness_(false), rgb_(false), rgb_white_value_(false), color_temperature_(false) {} LightTraits::LightTraits(bool brightness, bool rgb, bool rgb_white_value, bool color_temperature) - : brightness_(brightness), rgb_(rgb), rgb_white_value_(rgb_white_value), - color_temperature_(color_temperature) {} - -bool LightTraits::has_brightness() const { - return this->brightness_; -} -bool LightTraits::has_rgb() const { - return this->rgb_; -} -bool LightTraits::has_rgb_white_value() const { - return this->rgb_white_value_; -} -bool LightTraits::has_color_temperature() const { - return this->color_temperature_; -} -float LightTraits::get_min_mireds() const { - return this->min_mireds_; -} -float LightTraits::get_max_mireds() const { - return this->max_mireds_; -} -void LightTraits::set_min_mireds(float min_mireds) { - this->min_mireds_ = min_mireds; -} -void LightTraits::set_max_mireds(float max_mireds) { - this->max_mireds_ = max_mireds; -} - -} // namespace light + : brightness_(brightness), rgb_(rgb), rgb_white_value_(rgb_white_value), color_temperature_(color_temperature) {} + +bool LightTraits::has_brightness() const { return this->brightness_; } +bool LightTraits::has_rgb() const { return this->rgb_; } +bool LightTraits::has_rgb_white_value() const { return this->rgb_white_value_; } +bool LightTraits::has_color_temperature() const { return this->color_temperature_; } +float LightTraits::get_min_mireds() const { return this->min_mireds_; } +float LightTraits::get_max_mireds() const { return this->max_mireds_; } +void LightTraits::set_min_mireds(float min_mireds) { this->min_mireds_ = min_mireds; } +void LightTraits::set_max_mireds(float max_mireds) { this->max_mireds_ = max_mireds; } + +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/light_traits.h b/src/esphome/light/light_traits.h index c6268ce8..67e70209 100644 --- a/src/esphome/light/light_traits.h +++ b/src/esphome/light/light_traits.h @@ -34,10 +34,10 @@ class LightTraits { float max_mireds_{0}; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_LIGHT_TRAITS_H +#endif // ESPHOME_LIGHT_LIGHT_TRAITS_H diff --git a/src/esphome/light/light_transformer.cpp b/src/esphome/light/light_transformer.cpp index 45dd8196..dbc1e64e 100644 --- a/src/esphome/light/light_transformer.cpp +++ b/src/esphome/light/light_transformer.cpp @@ -13,47 +13,33 @@ ESPHOME_NAMESPACE_BEGIN namespace light { -const LightColorValues &LightTransformer::get_start_values() const { - return start_values_; -} - -const LightColorValues &LightTransformer::get_target_values() const { - return target_values_; -} +const LightColorValues &LightTransformer::get_start_values_() const { return start_values_; } -LightTransformer::LightTransformer(uint32_t start_time, uint32_t length, - const LightColorValues &start_values, - const LightColorValues &target_values) : start_time_( - start_time), length_(length), start_values_(start_values), target_values_(target_values) { +const LightColorValues &LightTransformer::get_target_values_() const { return target_values_; } -} +LightTransformer::LightTransformer(uint32_t start_time, uint32_t length, const LightColorValues &start_values, + const LightColorValues &target_values) + : start_time_(start_time), length_(length), start_values_(start_values), target_values_(target_values) {} -bool LightTransformer::is_finished() { - return this->get_progress() >= 1.0f; -} +bool LightTransformer::is_finished() { return this->get_progress_() >= 1.0f; } -float LightTransformer::get_progress() { +float LightTransformer::get_progress_() { return clamp(0.0f, 1.0f, (millis() - this->start_time_) / float(this->length_)); } -LightColorValues LightTransformer::get_remote_values() { - return this->get_target_values(); -} +LightColorValues LightTransformer::get_remote_values() { return this->get_target_values_(); } -LightColorValues LightTransformer::get_end_values() { - return this->get_target_values(); -} +LightColorValues LightTransformer::get_end_values() { return this->get_target_values_(); } LightColorValues LightTransitionTransformer::get_values() { - float x = this->get_progress(); + float x = this->get_progress_(); float v = x * x * x * (x * (x * 6.0f - 15.0f) + 10.0f); - return LightColorValues::lerp(this->get_start_values(), this->get_target_values(), v); + return LightColorValues::lerp(this->get_start_values_(), this->get_target_values_(), v); } -LightTransitionTransformer::LightTransitionTransformer(uint32_t start_time, - uint32_t length, +LightTransitionTransformer::LightTransitionTransformer(uint32_t start_time, uint32_t length, const LightColorValues &start_values, - const LightColorValues &target_values) : - LightTransformer(start_time, length, start_values, target_values) { + const LightColorValues &target_values) + : LightTransformer(start_time, length, start_values, target_values) { // When turning light on from off state, use colors from new. if (!this->start_values_.is_on() && this->target_values_.is_on()) { this->start_values_.set_brightness(0.0f); @@ -64,28 +50,19 @@ LightTransitionTransformer::LightTransitionTransformer(uint32_t start_time, this->start_values_.set_color_temperature(target_values.get_color_temperature()); } } -bool LightTransitionTransformer::is_continuous() { - return true; -} +bool LightTransitionTransformer::is_continuous() { return true; } -LightColorValues LightFlashTransformer::get_values() { - return this->get_target_values(); -} +LightColorValues LightFlashTransformer::get_values() { return this->get_target_values_(); } -LightColorValues LightFlashTransformer::get_end_values() { - return this->get_start_values(); -} +LightColorValues LightFlashTransformer::get_end_values() { return this->get_start_values_(); } -LightFlashTransformer::LightFlashTransformer(uint32_t start_time, uint32_t length, - const LightColorValues &start_values, +LightFlashTransformer::LightFlashTransformer(uint32_t start_time, uint32_t length, const LightColorValues &start_values, const LightColorValues &target_values) : LightTransformer(start_time, length, start_values, target_values) {} -bool LightFlashTransformer::is_continuous() { - return false; -} +bool LightFlashTransformer::is_continuous() { return false; } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT diff --git a/src/esphome/light/light_transformer.h b/src/esphome/light/light_transformer.h index 1b45105a..54b8e44f 100644 --- a/src/esphome/light/light_transformer.h +++ b/src/esphome/light/light_transformer.h @@ -36,11 +36,11 @@ class LightTransformer { protected: /// Get the completion of this transformer, 0 to 1. - float get_progress(); + float get_progress_(); - const LightColorValues &get_start_values() const; + const LightColorValues &get_start_values_() const; - const LightColorValues &get_target_values() const; + const LightColorValues &get_target_values_() const; uint32_t start_time_; uint32_t length_; @@ -50,9 +50,7 @@ class LightTransformer { class LightTransitionTransformer : public LightTransformer { public: - LightTransitionTransformer(uint32_t start_time, - uint32_t length, - const LightColorValues &start_values, + LightTransitionTransformer(uint32_t start_time, uint32_t length, const LightColorValues &start_values, const LightColorValues &target_values); LightColorValues get_values() override; @@ -72,10 +70,10 @@ class LightFlashTransformer : public LightTransformer { bool is_continuous() override; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_LIGHT +#endif // USE_LIGHT -#endif //ESPHOME_LIGHT_LIGHT_TRANSFORMER_H +#endif // ESPHOME_LIGHT_LIGHT_TRANSFORMER_H diff --git a/src/esphome/light/mqtt_json_light_component.cpp b/src/esphome/light/mqtt_json_light_component.cpp index 5ddfd78a..9283ac2c 100644 --- a/src/esphome/light/mqtt_json_light_component.cpp +++ b/src/esphome/light/mqtt_json_light_component.cpp @@ -12,37 +12,24 @@ namespace light { static const char *TAG = "light.mqtt_json"; -std::string MQTTJSONLightComponent::component_type() const { - return "light"; -} +std::string MQTTJSONLightComponent::component_type() const { return "light"; } void MQTTJSONLightComponent::setup() { - this->subscribe_json(this->get_command_topic(), [this](const std::string &topic, JsonObject &root) { + this->subscribe_json(this->get_command_topic_(), [this](const std::string &topic, JsonObject &root) { this->state_->make_call().parse_json(root).perform(); }); - auto f = std::bind(&MQTTJSONLightComponent::publish_state, this); - this->state_->add_new_remote_values_callback([this, f]() { - this->defer("send", f); - }); + auto f = std::bind(&MQTTJSONLightComponent::publish_state_, this); + this->state_->add_new_remote_values_callback([this, f]() { this->defer("send", f); }); } -MQTTJSONLightComponent::MQTTJSONLightComponent(LightState *state) - : MQTTComponent(), state_(state) { +MQTTJSONLightComponent::MQTTJSONLightComponent(LightState *state) : MQTTComponent(), state_(state) {} +bool MQTTJSONLightComponent::publish_state_() { + return this->publish_json(this->get_state_topic_(), [this](JsonObject &root) { this->state_->dump_json(root); }); } - -bool MQTTJSONLightComponent::publish_state() { - return this->publish_json(this->get_state_topic(), [this](JsonObject &root) { - this->state_->dump_json(root); - }); -} -LightState *MQTTJSONLightComponent::get_state() const { - return this->state_; -} -std::string MQTTJSONLightComponent::friendly_name() const { - return this->state_->get_name(); -} +LightState *MQTTJSONLightComponent::get_state() const { return this->state_; } +std::string MQTTJSONLightComponent::friendly_name() const { return this->state_->get_name(); } void MQTTJSONLightComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (this->state_->get_traits().has_brightness()) root["brightness"] = true; @@ -61,19 +48,15 @@ void MQTTJSONLightComponent::send_discovery(JsonObject &root, mqtt::SendDiscover } config.platform = "mqtt_json"; } -bool MQTTJSONLightComponent::send_initial_state() { - return this->publish_state(); -} -bool MQTTJSONLightComponent::is_internal() { - return this->state_->is_internal(); -} +bool MQTTJSONLightComponent::send_initial_state() { return this->publish_state_(); } +bool MQTTJSONLightComponent::is_internal() { return this->state_->is_internal(); } void MQTTJSONLightComponent::dump_config() { ESP_LOGCONFIG(TAG, "MQTT Light '%s':", this->state_->get_name().c_str()); LOG_MQTT_COMPONENT(true, true) } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_MQTT_LIGHT +#endif // USE_MQTT_LIGHT diff --git a/src/esphome/light/mqtt_json_light_component.h b/src/esphome/light/mqtt_json_light_component.h index cfcf1e0f..a57b4214 100644 --- a/src/esphome/light/mqtt_json_light_component.h +++ b/src/esphome/light/mqtt_json_light_component.h @@ -32,15 +32,15 @@ class MQTTJSONLightComponent : public mqtt::MQTTComponent { std::string friendly_name() const override; std::string component_type() const override; - bool publish_state(); + bool publish_state_(); LightState *state_; }; -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_MQTT_LIGHT +#endif // USE_MQTT_LIGHT -#endif //ESPHOME_LIGHT_MQTT_JSON_LIGHT_COMPONENT +#endif // ESPHOME_LIGHT_MQTT_JSON_LIGHT_COMPONENT diff --git a/src/esphome/light/neo_pixel_bus_light_output.h b/src/esphome/light/neo_pixel_bus_light_output.h index 1259ecd0..97d9bcea 100644 --- a/src/esphome/light/neo_pixel_bus_light_output.h +++ b/src/esphome/light/neo_pixel_bus_light_output.h @@ -17,21 +17,27 @@ namespace light { enum class ESPNeoPixelOrder { GBWR = 0b11000110, - GBRW = 0b10000111, GBR = 0b10000111, + GBRW = 0b10000111, + GBR = 0b10000111, GWBR = 0b11001001, - GRBW = 0b01001011, GRB = 0b01001011, + GRBW = 0b01001011, + GRB = 0b01001011, GWRB = 0b10001101, GRWB = 0b01001110, BGWR = 0b11010010, - BGRW = 0b10010011, BGR = 0b10010011, + BGRW = 0b10010011, + BGR = 0b10010011, WGBR = 0b11011000, - RGBW = 0b00011011, RGB = 0b00011011, + RGBW = 0b00011011, + RGB = 0b00011011, WGRB = 0b10011100, RGWB = 0b00011110, BWGR = 0b11100001, - BRGW = 0b01100011, BRG = 0b01100011, + BRGW = 0b01100011, + BRG = 0b01100011, WBGR = 0b11100100, - RBGW = 0b00100111, RBG = 0b00100111, + RBGW = 0b00100111, + RBG = 0b00100111, WRGB = 0b01101100, RWGB = 0b00101101, BWRG = 0b10110001, @@ -84,13 +90,13 @@ class NeoPixelBusLightOutputBase : public Component, public AddressableLight { protected: NeoPixelBus *controller_{nullptr}; uint8_t *effect_data_{nullptr}; - uint8_t rgb_offsets_[4]; + uint8_t rgb_offsets_[4]{0, 1, 2, 3}; #ifdef USE_OUTPUT PowerSupplyComponent *power_supply_{nullptr}; bool has_requested_high_power_{false}; #endif - static const char* TAG; + static const char *TAG; // NOLINT }; template @@ -115,6 +121,6 @@ ESPHOME_NAMESPACE_END #include "esphome/light/neo_pixel_bus_light_output.tcc" -#endif //USE_NEO_PIXEL_BUS_LIGHT +#endif // USE_NEO_PIXEL_BUS_LIGHT -#endif //ESPHOME_LIGHT_NEO_PIXEL_BUS_LIGHT_OUTPUT_H +#endif // ESPHOME_LIGHT_NEO_PIXEL_BUS_LIGHT_OUTPUT_H diff --git a/src/esphome/light/neo_pixel_bus_light_output.tcc b/src/esphome/light/neo_pixel_bus_light_output.tcc index bf907144..45846abc 100644 --- a/src/esphome/light/neo_pixel_bus_light_output.tcc +++ b/src/esphome/light/neo_pixel_bus_light_output.tcc @@ -11,7 +11,7 @@ ESPHOME_NAMESPACE_BEGIN namespace light { template -const char* NeoPixelBusLightOutputBase::TAG = "light.neo_pixel_bus"; +const char *NeoPixelBusLightOutputBase::TAG = "light.neo_pixel_bus"; // NOLINT #ifdef USE_OUTPUT template @@ -34,8 +34,7 @@ void NeoPixelBusLightOutputBase::add_leds(uint16_t co this->add_leds(new NeoPixelBus(count_pixels, pin)); } template -void NeoPixelBusLightOutputBase::add_leds(uint16_t count_pixels, - uint8_t pin_clock, +void NeoPixelBusLightOutputBase::add_leds(uint16_t count_pixels, uint8_t pin_clock, uint8_t pin_data) { this->add_leds(new NeoPixelBus(count_pixels, pin_clock, pin_data)); } @@ -44,7 +43,8 @@ void NeoPixelBusLightOutputBase::add_leds(uint16_t co this->add_leds(new NeoPixelBus(count_pixels)); } template -void NeoPixelBusLightOutputBase::add_leds(NeoPixelBus *controller) { +void NeoPixelBusLightOutputBase::add_leds( + NeoPixelBus *controller) { this->controller_ = controller; this->controller_->Begin(); } @@ -106,37 +106,25 @@ int32_t NeoPixelBusLightOutputBase::size() const { template void NeoPixelBusLightOutputBase::set_pixel_order(ESPNeoPixelOrder order) { - uint8_t order_ = static_cast(order); - this->rgb_offsets_[0] = (order_ >> 6) & 0b11; - this->rgb_offsets_[1] = (order_ >> 4) & 0b11; - this->rgb_offsets_[2] = (order_ >> 2) & 0b11; - this->rgb_offsets_[3] = (order_ >> 0) & 0b11; + uint8_t u_order = static_cast(order); + this->rgb_offsets_[0] = (u_order >> 6) & 0b11; + this->rgb_offsets_[1] = (u_order >> 4) & 0b11; + this->rgb_offsets_[2] = (u_order >> 2) & 0b11; + this->rgb_offsets_[3] = (u_order >> 0) & 0b11; } template ESPColorView NeoPixelRGBLightOutput::operator[](int32_t index) const { uint8_t *base = this->controller_->Pixels() + 3ULL * index; - return ESPColorView( - base + this->rgb_offsets_[0], - base + this->rgb_offsets_[1], - base + this->rgb_offsets_[2], - nullptr, - this->effect_data_ + index, - &this->correction_ - ); + return ESPColorView(base + this->rgb_offsets_[0], base + this->rgb_offsets_[1], base + this->rgb_offsets_[2], nullptr, + this->effect_data_ + index, &this->correction_); } template ESPColorView NeoPixelRGBWLightOutput::operator[](int32_t index) const { uint8_t *base = this->controller_->Pixels() + 4ULL * index; - return ESPColorView( - base + this->rgb_offsets_[0], - base + this->rgb_offsets_[1], - base + this->rgb_offsets_[2], - base + this->rgb_offsets_[3], - this->effect_data_ + index, - &this->correction_ - ); + return ESPColorView(base + this->rgb_offsets_[0], base + this->rgb_offsets_[1], base + this->rgb_offsets_[2], + base + this->rgb_offsets_[3], this->effect_data_ + index, &this->correction_); } template @@ -149,8 +137,8 @@ LightTraits NeoPixelRGBWLightOutput::get_traits() { return {true, true, true, false}; } -} // namespace light +} // namespace light ESPHOME_NAMESPACE_END -#endif //USE_NEO_PIXEL_BUS_LIGHT +#endif // USE_NEO_PIXEL_BUS_LIGHT diff --git a/src/esphome/log.cpp b/src/esphome/log.cpp index e1e9a252..f6aede42 100644 --- a/src/esphome/log.cpp +++ b/src/esphome/log.cpp @@ -2,7 +2,7 @@ #include "esphome/log_component.h" -int HOT esp_log_printf_(int level, const char *tag, const char *format, ...) { +int HOT esp_log_printf_(int level, const char *tag, const char *format, ...) { // NOLINT va_list arg; va_start(arg, format); int ret = esp_log_vprintf_(level, tag, format, arg); @@ -19,7 +19,7 @@ int HOT esp_log_printf_(int level, const char *tag, const __FlashStringHelper *f } #endif -int HOT esp_log_vprintf_(int level, const char *tag, const char *format, va_list args) { +int HOT esp_log_vprintf_(int level, const char *tag, const char *format, va_list args) { // NOLINT auto *log = esphome::global_log_component; if (log == nullptr) return 0; @@ -28,7 +28,7 @@ int HOT esp_log_vprintf_(int level, const char *tag, const char *format, va_list } #ifdef USE_STORE_LOG_STR_IN_FLASH -int HOT esp_log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args) { +int HOT esp_log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args) { // NOLINT auto *log = esphome::global_log_component; if (log == nullptr) return 0; @@ -37,7 +37,7 @@ int HOT esp_log_vprintf_(int level, const char *tag, const __FlashStringHelper * } #endif -int HOT esp_idf_log_vprintf_(const char *format, va_list args) { +int HOT esp_idf_log_vprintf_(const char *format, va_list args) { // NOLINT auto *log = esphome::global_log_component; if (log == nullptr) return 0; diff --git a/src/esphome/log.h b/src/esphome/log.h index 6cf6dc57..2b8078f4 100644 --- a/src/esphome/log.h +++ b/src/esphome/log.h @@ -6,14 +6,14 @@ #include #include "esphome/defines.h" #ifdef USE_STORE_LOG_STR_IN_FLASH - #include "WString.h" +#include "WString.h" #endif // avoid esp-idf redefining our macros #include "esphome/esphal.h" #ifdef ARDUINO_ARCH_ESP32 - #include "esp_err.h" +#include "esp_err.h" #endif #define ESPHOME_LOG_LEVEL_NONE 0 @@ -25,156 +25,160 @@ #define ESPHOME_LOG_LEVEL_VERY_VERBOSE 6 #ifndef ESPHOME_LOG_LEVEL - #define ESPHOME_LOG_LEVEL ESPHOME_LOG_LEVEL_DEBUG -#endif - -#define ESPHOME_LOG_COLOR_BLACK "30" -#define ESPHOME_LOG_COLOR_RED "31" //ERROR -#define ESPHOME_LOG_COLOR_GREEN "32" //INFO -#define ESPHOME_LOG_COLOR_YELLOW "33" //WARNING -#define ESPHOME_LOG_COLOR_BLUE "34" -#define ESPHOME_LOG_COLOR_MAGENTA "35" //CONFIG -#define ESPHOME_LOG_COLOR_CYAN "36" //DEBUG -#define ESPHOME_LOG_COLOR_GRAY "37" //VERBOSE -#define ESPHOME_LOG_COLOR_WHITE "38" -#define ESPHOME_LOG_SECRET_BEGIN "\033[5m" -#define ESPHOME_LOG_SECRET_END "\033[6m" +#define ESPHOME_LOG_LEVEL ESPHOME_LOG_LEVEL_DEBUG +#endif + +#define ESPHOME_LOG_COLOR_BLACK "30" +#define ESPHOME_LOG_COLOR_RED "31" // ERROR +#define ESPHOME_LOG_COLOR_GREEN "32" // INFO +#define ESPHOME_LOG_COLOR_YELLOW "33" // WARNING +#define ESPHOME_LOG_COLOR_BLUE "34" +#define ESPHOME_LOG_COLOR_MAGENTA "35" // CONFIG +#define ESPHOME_LOG_COLOR_CYAN "36" // DEBUG +#define ESPHOME_LOG_COLOR_GRAY "37" // VERBOSE +#define ESPHOME_LOG_COLOR_WHITE "38" +#define ESPHOME_LOG_SECRET_BEGIN "\033[5m" +#define ESPHOME_LOG_SECRET_END "\033[6m" #define LOG_SECRET(x) ESPHOME_LOG_SECRET_BEGIN x ESPHOME_LOG_SECRET_END -#define ESPHOME_LOG_COLOR(COLOR) "\033[0;" COLOR "m" -#define ESPHOME_LOG_BOLD(COLOR) "\033[1;" COLOR "m" +#define ESPHOME_LOG_COLOR(COLOR) "\033[0;" COLOR "m" +#define ESPHOME_LOG_BOLD(COLOR) "\033[1;" COLOR "m" #ifndef ESPHOME_LOG_NO_COLORS - #define ESPHOME_LOG_COLOR_E ESPHOME_LOG_BOLD(ESPHOME_LOG_COLOR_RED) - #define ESPHOME_LOG_COLOR_W ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_YELLOW) - #define ESPHOME_LOG_COLOR_I ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_GREEN) - #define ESPHOME_LOG_COLOR_C ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_MAGENTA) - #define ESPHOME_LOG_COLOR_D ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_CYAN) - #define ESPHOME_LOG_COLOR_V ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_GRAY) - #define ESPHOME_LOG_COLOR_VV ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_WHITE) - #define ESPHOME_LOG_RESET_COLOR "\033[0m" +#define ESPHOME_LOG_COLOR_E ESPHOME_LOG_BOLD(ESPHOME_LOG_COLOR_RED) +#define ESPHOME_LOG_COLOR_W ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_YELLOW) +#define ESPHOME_LOG_COLOR_I ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_GREEN) +#define ESPHOME_LOG_COLOR_C ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_MAGENTA) +#define ESPHOME_LOG_COLOR_D ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_CYAN) +#define ESPHOME_LOG_COLOR_V ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_GRAY) +#define ESPHOME_LOG_COLOR_VV ESPHOME_LOG_COLOR(ESPHOME_LOG_COLOR_WHITE) +#define ESPHOME_LOG_RESET_COLOR "\033[0m" #else - #define ESPHOME_LOG_COLOR_E - #define ESPHOME_LOG_COLOR_W - #define ESPHOME_LOG_COLOR_I - #define ESPHOME_LOG_COLOR_C - #define ESPHOME_LOG_COLOR_D - #define ESPHOME_LOG_COLOR_V - #define ESPHOME_LOG_COLOR_VV - #define ESPHOME_LOG_RESET_COLOR -#endif - -int esp_log_printf_(int level, const char *tag, const char *format, ...) __attribute__ ((format (printf, 3, 4))); +#define ESPHOME_LOG_COLOR_E +#define ESPHOME_LOG_COLOR_W +#define ESPHOME_LOG_COLOR_I +#define ESPHOME_LOG_COLOR_C +#define ESPHOME_LOG_COLOR_D +#define ESPHOME_LOG_COLOR_V +#define ESPHOME_LOG_COLOR_VV +#define ESPHOME_LOG_RESET_COLOR +#endif + +int esp_log_printf_(int level, const char *tag, const char *format, ...) // NOLINT + __attribute__((format(printf, 3, 4))); #ifdef USE_STORE_LOG_STR_IN_FLASH - int esp_log_printf_(int level, const char *tag, const __FlashStringHelper *format, ...); +int esp_log_printf_(int level, const char *tag, const __FlashStringHelper *format, ...); #endif -int esp_log_vprintf_(int level, const char *tag, const char *format, va_list args); +int esp_log_vprintf_(int level, const char *tag, const char *format, va_list args); // NOLINT #ifdef USE_STORE_LOG_STR_IN_FLASH - int esp_log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args); +int esp_log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args); #endif -int esp_idf_log_vprintf_(const char *format, va_list args); +int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT #ifdef USE_STORE_LOG_STR_IN_FLASH - #define ESPHOME_LOG_FORMAT(tag, letter, format) F(ESPHOME_LOG_COLOR_ ## letter "[" #letter "][%s:%03u]: " format ESPHOME_LOG_RESET_COLOR), tag, __LINE__ +#define ESPHOME_LOG_FORMAT(tag, letter, format) \ + F(ESPHOME_LOG_COLOR_##letter "[" #letter "][%s:%03u]: " format ESPHOME_LOG_RESET_COLOR), tag, __LINE__ #else - #define ESPHOME_LOG_FORMAT(tag, letter, format) ESPHOME_LOG_COLOR_ ## letter "[" #letter "][%s:%03u]: " format ESPHOME_LOG_RESET_COLOR, tag, __LINE__ +#define ESPHOME_LOG_FORMAT(tag, letter, format) \ + ESPHOME_LOG_COLOR_##letter "[" #letter "][%s:%03u]: " format ESPHOME_LOG_RESET_COLOR, tag, __LINE__ #endif #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE - #define esph_log_vv(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_VERY_VERBOSE, tag, ESPHOME_LOG_FORMAT(tag, VV, format), ##__VA_ARGS__) +#define esph_log_vv(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_VERY_VERBOSE, tag, ESPHOME_LOG_FORMAT(tag, VV, format), ##__VA_ARGS__) - #define ESPHOME_LOG_HAS_VERY_VERBOSE +#define ESPHOME_LOG_HAS_VERY_VERBOSE #else - #define esph_log_vv(tag, format, ...) +#define esph_log_vv(tag, format, ...) #endif #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE - #define esph_log_v(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_VERBOSE, tag, ESPHOME_LOG_FORMAT(tag, V, format), ##__VA_ARGS__) +#define esph_log_v(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_VERBOSE, tag, ESPHOME_LOG_FORMAT(tag, V, format), ##__VA_ARGS__) - #define ESPHOME_LOG_HAS_VERBOSE +#define ESPHOME_LOG_HAS_VERBOSE #else - #define esph_log_v(tag, format, ...) +#define esph_log_v(tag, format, ...) #endif #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG - #define esph_log_d(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_DEBUG, tag, ESPHOME_LOG_FORMAT(tag, D, format), ##__VA_ARGS__) +#define esph_log_d(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_DEBUG, tag, ESPHOME_LOG_FORMAT(tag, D, format), ##__VA_ARGS__) - #define esph_log_config(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_DEBUG, tag, ESPHOME_LOG_FORMAT(tag, C, format), ##__VA_ARGS__) +#define esph_log_config(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_DEBUG, tag, ESPHOME_LOG_FORMAT(tag, C, format), ##__VA_ARGS__) - #define ESPHOME_LOG_HAS_DEBUG - #define ESPHOME_LOG_HAS_CONFIG +#define ESPHOME_LOG_HAS_DEBUG +#define ESPHOME_LOG_HAS_CONFIG #else - #define esph_log_d(tag, format, ...) +#define esph_log_d(tag, format, ...) - #define esph_log_config(tag, format, ...) +#define esph_log_config(tag, format, ...) #endif #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO - #define esph_log_i(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, tag, ESPHOME_LOG_FORMAT(tag, I, format), ##__VA_ARGS__) +#define esph_log_i(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, tag, ESPHOME_LOG_FORMAT(tag, I, format), ##__VA_ARGS__) - #define ESPHOME_LOG_HAS_INFO +#define ESPHOME_LOG_HAS_INFO #else - #define esph_log_i(tag, format, ...) +#define esph_log_i(tag, format, ...) #endif #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_WARN - #define esph_log_w(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_WARN, tag, ESPHOME_LOG_FORMAT(tag, W, format), ##__VA_ARGS__) +#define esph_log_w(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_WARN, tag, ESPHOME_LOG_FORMAT(tag, W, format), ##__VA_ARGS__) - #define ESPHOME_LOG_HAS_WARN +#define ESPHOME_LOG_HAS_WARN #else - #define esph_log_w(tag, format, ...) +#define esph_log_w(tag, format, ...) #endif #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR - #define esph_log_e(tag, format, ...) esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, tag, ESPHOME_LOG_FORMAT(tag, E, format), ##__VA_ARGS__) +#define esph_log_e(tag, format, ...) \ + esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, tag, ESPHOME_LOG_FORMAT(tag, E, format), ##__VA_ARGS__) - #define ESPHOME_LOG_HAS_ERROR +#define ESPHOME_LOG_HAS_ERROR #else - #define esph_log_e(tag, format, ...) +#define esph_log_e(tag, format, ...) #endif #ifdef ESP_LOGE - #undef ESP_LOGE +#undef ESP_LOGE #endif #ifdef ESP_LOGW - #undef ESP_LOGW +#undef ESP_LOGW #endif #ifdef ESP_LOGI - #undef ESP_LOGI +#undef ESP_LOGI #endif #ifdef ESP_LOGD - #undef ESP_LOGD +#undef ESP_LOGD #endif #ifdef ESP_LOGV - #undef ESP_LOGV +#undef ESP_LOGV #endif -#define ESP_LOGE(tag, ...) esph_log_e(tag, __VA_ARGS__) +#define ESP_LOGE(tag, ...) esph_log_e(tag, __VA_ARGS__) #define LOG_E(tag, ...) ESP_LOGE(tag, __VA__ARGS__) -#define ESP_LOGW(tag, ...) esph_log_w(tag, __VA_ARGS__) +#define ESP_LOGW(tag, ...) esph_log_w(tag, __VA_ARGS__) #define LOG_W(tag, ...) ESP_LOGW(tag, __VA__ARGS__) -#define ESP_LOGI(tag, ...) esph_log_i(tag, __VA_ARGS__) +#define ESP_LOGI(tag, ...) esph_log_i(tag, __VA_ARGS__) #define LOG_I(tag, ...) ESP_LOGI(tag, __VA__ARGS__) -#define ESP_LOGD(tag, ...) esph_log_d(tag, __VA_ARGS__) +#define ESP_LOGD(tag, ...) esph_log_d(tag, __VA_ARGS__) #define LOG_D(tag, ...) ESP_LOGD(tag, __VA__ARGS__) -#define ESP_LOGCONFIG(tag, ...) esph_log_config(tag, __VA_ARGS__) +#define ESP_LOGCONFIG(tag, ...) esph_log_config(tag, __VA_ARGS__) #define LOG_CONFIG(tag, ...) ESP_LOGCONFIG(tag, __VA__ARGS__) -#define ESP_LOGV(tag, ...) esph_log_v(tag, __VA_ARGS__) +#define ESP_LOGV(tag, ...) esph_log_v(tag, __VA_ARGS__) #define LOG_V(tag, ...) ESP_LOGV(tag, __VA__ARGS__) -#define ESP_LOGVV(tag, ...) esph_log_vv(tag, __VA_ARGS__) +#define ESP_LOGVV(tag, ...) esph_log_vv(tag, __VA_ARGS__) #define LOG_VV(tag, ...) ESP_LOGVV(tag, __VA__ARGS__) #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" -#define BYTE_TO_BINARY(byte) \ - ((byte) & 0x80 ? '1' : '0'), \ - ((byte) & 0x40 ? '1' : '0'), \ - ((byte) & 0x20 ? '1' : '0'), \ - ((byte) & 0x10 ? '1' : '0'), \ - ((byte) & 0x08 ? '1' : '0'), \ - ((byte) & 0x04 ? '1' : '0'), \ - ((byte) & 0x02 ? '1' : '0'), \ - ((byte) & 0x01 ? '1' : '0') +#define BYTE_TO_BINARY(byte) \ + ((byte) &0x80 ? '1' : '0'), ((byte) &0x40 ? '1' : '0'), ((byte) &0x20 ? '1' : '0'), ((byte) &0x10 ? '1' : '0'), \ + ((byte) &0x08 ? '1' : '0'), ((byte) &0x04 ? '1' : '0'), ((byte) &0x02 ? '1' : '0'), ((byte) &0x01 ? '1' : '0') #define YESNO(b) ((b) ? "YES" : "NO") #define ONOFF(b) ((b) ? "ON" : "OFF") -#endif //ESPHOME_LOG_H +#endif // ESPHOME_LOG_H diff --git a/src/esphome/log_component.cpp b/src/esphome/log_component.cpp index 15943eae..e62d2ad0 100644 --- a/src/esphome/log_component.cpp +++ b/src/esphome/log_component.cpp @@ -1,7 +1,7 @@ #include "esphome/log_component.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #include @@ -12,25 +12,23 @@ ESPHOME_NAMESPACE_BEGIN static const char *TAG = "logger"; -int HOT LogComponent::log_vprintf_(int level, const char *tag, - const char *format, va_list args) { - if (level > this->level_for_(tag)) +int HOT LogComponent::log_vprintf_(int level, const char *tag, const char *format, va_list args) { // NOLINT + if (level > this->level_for(tag)) return 0; - int ret = vsnprintf(this->tx_buffer_.data(), this->tx_buffer_.capacity(), - format, args); + int ret = vsnprintf(this->tx_buffer_.data(), this->tx_buffer_.capacity(), format, args); this->log_message_(level, tag, this->tx_buffer_.data(), ret); return ret; } #ifdef USE_STORE_LOG_STR_IN_FLASH -int LogComponent::log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args) { +int LogComponent::log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args) { // NOLINT if (level > this->level_for_(tag)) return 0; // copy format string - const char* format_pgm_p = (PGM_P) format; + const char *format_pgm_p = (PGM_P) format; size_t len = 0; - char* write = this->tx_buffer_.data(); + char *write = this->tx_buffer_.data(); char ch = '.'; while (len < this->tx_buffer_.capacity() && ch != '\0') { *write++ = ch = pgm_read_byte(format_pgm_p++); @@ -49,7 +47,7 @@ int LogComponent::log_vprintf_(int level, const char *tag, const __FlashStringHe } #endif -int HOT LogComponent::level_for_(const char *tag) { +int HOT LogComponent::level_for(const char *tag) { // Uses std::vector<> for low memory footprint, though the vector // could be sorted to minimize lookup times. This feature isn't used that // much anyway so it doesn't matter too much. @@ -73,8 +71,7 @@ void HOT LogComponent::log_message_(int level, const char *tag, char *msg, int r } LogComponent::LogComponent(uint32_t baud_rate, size_t tx_buffer_size, UARTSelection uart) - : baud_rate_(baud_rate) - , uart_(uart) { + : baud_rate_(baud_rate), uart_(uart) { this->set_tx_buffer_size(tx_buffer_size); } @@ -83,7 +80,7 @@ void LogComponent::pre_setup() { switch (this->uart_) { case UART_SELECTION_UART0: #ifdef ARDUINO_ARCH_ESP8266 - case UART_SELECTION_UART0_SWAP: + case UART_SELECTION_UART0_SWAP: #endif this->hw_serial_ = &Serial; break; @@ -121,33 +118,19 @@ void LogComponent::pre_setup() { ESP_LOGI(TAG, "Log initialized"); } -uint32_t LogComponent::get_baud_rate() const { - return this->baud_rate_; -} -void LogComponent::set_baud_rate(uint32_t baud_rate) { - this->baud_rate_ = baud_rate; -} -void LogComponent::set_global_log_level(int log_level) { - this->global_log_level_ = log_level; -} +uint32_t LogComponent::get_baud_rate() const { return this->baud_rate_; } +void LogComponent::set_baud_rate(uint32_t baud_rate) { this->baud_rate_ = baud_rate; } +void LogComponent::set_global_log_level(int log_level) { this->global_log_level_ = log_level; } void LogComponent::set_log_level(const std::string &tag, int log_level) { this->log_levels_.push_back(LogLevelOverride{tag, log_level}); } -size_t LogComponent::get_tx_buffer_size() const { - return this->tx_buffer_.capacity(); -} -void LogComponent::set_tx_buffer_size(size_t tx_buffer_size) { - this->tx_buffer_.reserve(tx_buffer_size); -} -UARTSelection LogComponent::get_uart() const { - return this->uart_; -} +size_t LogComponent::get_tx_buffer_size() const { return this->tx_buffer_.capacity(); } +void LogComponent::set_tx_buffer_size(size_t tx_buffer_size) { this->tx_buffer_.reserve(tx_buffer_size); } +UARTSelection LogComponent::get_uart() const { return this->uart_; } void LogComponent::add_on_log_callback(std::function &&callback) { this->log_callback_.add(std::move(callback)); } -float LogComponent::get_setup_priority() const { - return setup_priority::HARDWARE - 1.0f; -} +float LogComponent::get_setup_priority() const { return setup_priority::HARDWARE - 1.0f; } const char *LOG_LEVELS[] = {"NONE", "ERROR", "WARN", "INFO", "DEBUG", "VERBOSE", "VERY_VERBOSE"}; #ifdef ARDUINO_ARCH_ESP32 const char *UART_SELECTIONS[] = {"UART0", "UART1", "UART2"}; @@ -164,9 +147,7 @@ void LogComponent::dump_config() { ESP_LOGCONFIG(TAG, " Level for '%s': %s", it.tag.c_str(), LOG_LEVELS[it.level]); } } -int LogComponent::get_global_log_level() const { - return this->global_log_level_; -} +int LogComponent::get_global_log_level() const { return this->global_log_level_; } LogComponent *global_log_component = nullptr; diff --git a/src/esphome/log_component.h b/src/esphome/log_component.h index 3f3975df..53208c94 100644 --- a/src/esphome/log_component.h +++ b/src/esphome/log_component.h @@ -28,11 +28,10 @@ enum UARTSelection { UART_SELECTION_UART2 #endif #ifdef ARDUINO_ARCH_ESP8266 - UART_SELECTION_UART0_SWAP + UART_SELECTION_UART0_SWAP #endif }; - /** A simple component that enables logging to Serial via the ESP_LOG* macros. * * This component should optimally be setup very early because only after its setup log messages are actually sent. @@ -45,7 +44,8 @@ class LogComponent : public Component { * @param baud_rate The baud_rate for the serial interface. 0 to disable UART logging. * @param tx_buffer_size The buffer size (in bytes) used for constructing log messages. */ - explicit LogComponent(uint32_t baud_rate = 115200, size_t tx_buffer_size = 512, UARTSelection uart = UART_SELECTION_UART0); + explicit LogComponent(uint32_t baud_rate = 115200, size_t tx_buffer_size = 512, + UARTSelection uart = UART_SELECTION_UART0); /// Manually set the baud rate for serial, set to 0 to disable. void set_baud_rate(uint32_t baud_rate); @@ -72,19 +72,21 @@ class LogComponent : public Component { size_t get_tx_buffer_size() const; - int log_vprintf_(int level, const char *tag, const char *format, va_list args); -#ifdef USE_STORE_LOG_STR_IN_FLASH - int log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args); -#endif - int level_for_(const char *tag); - void log_message_(int level, const char *tag, char *msg, int ret); + int level_for(const char *tag); /// Register a callback that will be called for every log message sent void add_on_log_callback(std::function &&callback); float get_setup_priority() const override; + int log_vprintf_(int level, const char *tag, const char *format, va_list args); // NOLINT +#ifdef USE_STORE_LOG_STR_IN_FLASH + int log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args); // NOLINT +#endif + protected: + void log_message_(int level, const char *tag, char *msg, int ret); + uint32_t baud_rate_; std::vector tx_buffer_; int global_log_level_{ESPHOME_LOG_LEVEL}; @@ -102,4 +104,4 @@ extern LogComponent *global_log_component; ESPHOME_NAMESPACE_END -#endif //ESPHOME_LOG_COMPONENT_H +#endif // ESPHOME_LOG_COMPONENT_H diff --git a/src/esphome/mqtt/custom_mqtt_device.cpp b/src/esphome/mqtt/custom_mqtt_device.cpp index 3166124b..e1831ba7 100644 --- a/src/esphome/mqtt/custom_mqtt_device.cpp +++ b/src/esphome/mqtt/custom_mqtt_device.cpp @@ -26,12 +26,10 @@ bool CustomMQTTDevice::publish_json(const std::string &topic, const json_build_t bool CustomMQTTDevice::publish_json(const std::string &topic, const json_build_t &f) { return this->publish_json(topic, f, 0, false); } -bool CustomMQTTDevice::is_connected() { - return global_mqtt_client != nullptr && global_mqtt_client->is_connected(); -} +bool CustomMQTTDevice::is_connected() { return global_mqtt_client != nullptr && global_mqtt_client->is_connected(); } -} // namespace mqtt +} // namespace mqtt ESPHOME_NAMESPACE_END -#endif //USE_MQTT_CUSTOM_COMPONENT +#endif // USE_MQTT_CUSTOM_COMPONENT diff --git a/src/esphome/mqtt/custom_mqtt_device.h b/src/esphome/mqtt/custom_mqtt_device.h index b78e4504..75e159b0 100644 --- a/src/esphome/mqtt/custom_mqtt_device.h +++ b/src/esphome/mqtt/custom_mqtt_device.h @@ -55,14 +55,13 @@ class CustomMQTTDevice { * @param qos The Quality of Service to subscribe with. Defaults to 0. */ template - void subscribe(const std::string &topic, void(T::*callback)(const std::string &, const std::string &), uint8_t qos = 0); + void subscribe(const std::string &topic, void (T::*callback)(const std::string &, const std::string &), + uint8_t qos = 0); template - void subscribe(const std::string &topic, void(T::*callback)(const std::string &), uint8_t qos = 0); - - template - void subscribe(const std::string &topic, void(T::*callback)(), uint8_t qos = 0); + void subscribe(const std::string &topic, void (T::*callback)(const std::string &), uint8_t qos = 0); + template void subscribe(const std::string &topic, void (T::*callback)(), uint8_t qos = 0); /** Subscribe to an MQTT topic and call the callback if the payload can be decoded * as JSON with the given Quality of Service. @@ -97,10 +96,11 @@ class CustomMQTTDevice { * @param qos The Quality of Service to subscribe with. Defaults to 0. */ template - void subscribe_json(const std::string &topic, void(T::*callback)(const std::string &, JsonObject &), uint8_t qos = 0); + void subscribe_json(const std::string &topic, void (T::*callback)(const std::string &, JsonObject &), + uint8_t qos = 0); template - void subscribe_json(const std::string &topic, void(T::*callback)(JsonObject &), uint8_t qos = 0); + void subscribe_json(const std::string &topic, void (T::*callback)(JsonObject &), uint8_t qos = 0); /** Publish an MQTT message with the given payload and QoS and retain settings. * @@ -193,35 +193,36 @@ class CustomMQTTDevice { }; template -void CustomMQTTDevice::subscribe(const std::string &topic, void(T::*callback)(const std::string &, const std::string &), uint8_t qos) { +void CustomMQTTDevice::subscribe(const std::string &topic, + void (T::*callback)(const std::string &, const std::string &), uint8_t qos) { auto f = std::bind(callback, (T *) this, std::placeholders::_1, std::placeholders::_2); global_mqtt_client->subscribe(topic, f, qos); } template -void CustomMQTTDevice::subscribe(const std::string &topic, void(T::*callback)(const std::string &), uint8_t qos) { +void CustomMQTTDevice::subscribe(const std::string &topic, void (T::*callback)(const std::string &), uint8_t qos) { auto f = std::bind(callback, (T *) this, std::placeholders::_2); global_mqtt_client->subscribe(topic, f, qos); } -template -void CustomMQTTDevice::subscribe(const std::string &topic, void(T::*callback)(), uint8_t qos) { +template void CustomMQTTDevice::subscribe(const std::string &topic, void (T::*callback)(), uint8_t qos) { auto f = std::bind(callback, (T *) this); global_mqtt_client->subscribe(topic, f, qos); } template -void CustomMQTTDevice::subscribe_json(const std::string &topic, void(T::*callback)(const std::string &, JsonObject &), uint8_t qos) { +void CustomMQTTDevice::subscribe_json(const std::string &topic, void (T::*callback)(const std::string &, JsonObject &), + uint8_t qos) { auto f = std::bind(callback, (T *) this, std::placeholders::_1, std::placeholders::_2); global_mqtt_client->subscribe_json(topic, f, qos); } template -void CustomMQTTDevice::subscribe_json(const std::string &topic, void(T::*callback)(JsonObject &), uint8_t qos) { +void CustomMQTTDevice::subscribe_json(const std::string &topic, void (T::*callback)(JsonObject &), uint8_t qos) { auto f = std::bind(callback, (T *) this, std::placeholders::_2); global_mqtt_client->subscribe_json(topic, f, qos); } -} // namespace mqtt +} // namespace mqtt ESPHOME_NAMESPACE_END -#endif //USE_MQTT_CUSTOM_COMPONENT +#endif // USE_MQTT_CUSTOM_COMPONENT -#endif //ESPHOME_MQTT_CUSTOM_MQTT_DEVICE_H +#endif // ESPHOME_MQTT_CUSTOM_MQTT_DEVICE_H diff --git a/src/esphome/mqtt/mqtt_client_component.cpp b/src/esphome/mqtt/mqtt_client_component.cpp index 3e94d415..0ab1cebe 100644 --- a/src/esphome/mqtt/mqtt_client_component.cpp +++ b/src/esphome/mqtt/mqtt_client_component.cpp @@ -27,7 +27,8 @@ void MQTTClientComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up MQTT..."); if (this->credentials_.client_id.empty()) this->credentials_.client_id = generate_hostname(get_app_name()); - this->mqtt_client_.onMessage([this](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total){ + this->mqtt_client_.onMessage([this](char *topic, char *payload, AsyncMqttClientMessageProperties properties, + size_t len, size_t index, size_t total) { std::string payload_s(payload, len); std::string topic_s(topic); this->on_message(topic_s, payload_s); @@ -39,13 +40,13 @@ void MQTTClientComponent::setup() { if (this->is_log_message_enabled() && global_log_component != nullptr) { global_log_component->add_on_log_callback([this](int level, const char *tag, const char *message) { if (level <= this->log_level_ && this->is_connected()) { - this->publish(this->log_message_.topic, message, strlen(message), - this->log_message_.qos, this->log_message_.retain); + this->publish(this->log_message_.topic, message, strlen(message), this->log_message_.qos, + this->log_message_.retain); } }); } - add_shutdown_hook([this](const char *cause){ + add_shutdown_hook([this](const char *cause) { if (!this->shutdown_message_.topic.empty()) { yield(); this->publish(this->shutdown_message_); @@ -55,12 +56,12 @@ void MQTTClientComponent::setup() { }); this->last_connected_ = millis(); - this->start_dnslookup(); + this->start_dnslookup_(); } void MQTTClientComponent::dump_config() { ESP_LOGCONFIG(TAG, "MQTT:"); - ESP_LOGCONFIG(TAG, " Server Address: %s:%u (%s)", - this->credentials_.address.c_str(), this->credentials_.port, this->ip_.toString().c_str()); + ESP_LOGCONFIG(TAG, " Server Address: %s:%u (%s)", this->credentials_.address.c_str(), this->credentials_.port, + this->ip_.toString().c_str()); ESP_LOGCONFIG(TAG, " Username: " LOG_SECRET("'%s'"), this->credentials_.username.c_str()); ESP_LOGCONFIG(TAG, " Client ID: " LOG_SECRET("'%s'"), this->credentials_.client_id.c_str()); if (!this->discovery_info_.prefix.empty()) { @@ -75,14 +76,12 @@ void MQTTClientComponent::dump_config() { ESP_LOGCONFIG(TAG, " Availability: '%s'", this->availability_.topic.c_str()); } } -bool MQTTClientComponent::can_proceed() { - return this->is_connected(); -} +bool MQTTClientComponent::can_proceed() { return this->is_connected(); } -void MQTTClientComponent::start_dnslookup() { - for (size_t i = 0; i < this->subscriptions_.size(); i++) { - this->subscriptions_[i].subscribed = false; - this->subscriptions_[i].resubscribe_timeout = 0; +void MQTTClientComponent::start_dnslookup_() { + for (auto &subscription : this->subscriptions_) { + subscription.subscribed = false; + subscription.resubscribe_timeout = 0; } this->status_set_warning(); @@ -90,11 +89,12 @@ void MQTTClientComponent::start_dnslookup() { this->dns_resolved_ = false; ip_addr_t addr; #ifdef ARDUINO_ARCH_ESP32 - err_t err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, this->dns_found_callback_, this, + err_t err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, this->dns_found_callback, this, LWIP_DNS_ADDRTYPE_IPV4); #endif #ifdef ARDUINO_ARCH_ESP8266 - err_t err = dns_gethostbyname(this->credentials_.address.c_str(), &addr, this->dns_found_callback_, this); + err_t err = dns_gethostbyname(this->credentials_.address.c_str(), &addr, + esphome::mqtt::MQTTClientComponent::dns_found_callback, this); #endif switch (err) { case ERR_OK: { @@ -106,7 +106,7 @@ void MQTTClientComponent::start_dnslookup() { #ifdef ARDUINO_ARCH_ESP8266 this->ip_ = IPAddress(addr.addr); #endif - this->start_connect(); + this->start_connect_(); return; } case ERR_INPROGRESS: { @@ -129,7 +129,7 @@ void MQTTClientComponent::start_dnslookup() { this->state_ = MQTT_CLIENT_RESOLVING_ADDRESS; this->connect_begin_ = millis(); } -void MQTTClientComponent::check_dnslookup() { +void MQTTClientComponent::check_dnslookup_() { if (!this->dns_resolved_ && millis() - this->connect_begin_ > 20000) { this->dns_resolve_error_ = true; } @@ -145,28 +145,28 @@ void MQTTClientComponent::check_dnslookup() { } ESP_LOGD(TAG, "Resolved broker IP address to %s", this->ip_.toString().c_str()); - this->start_connect(); + this->start_connect_(); } #if defined(ARDUINO_ARCH_ESP8266) && LWIP_VERSION_MAJOR == 1 -void MQTTClientComponent::dns_found_callback_(const char *name, ip_addr_t *ipaddr, void *callback_arg) { +void MQTTClientComponent::dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg) { #else -void MQTTClientComponent::dns_found_callback_(const char *name, const ip_addr_t *ipaddr, void *callback_arg) { +void MQTTClientComponent::dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) { #endif - auto *this_ = (MQTTClientComponent *) callback_arg; + auto *a_this = (MQTTClientComponent *) callback_arg; if (ipaddr == nullptr) { - this_->dns_resolve_error_ = true; + a_this->dns_resolve_error_ = true; } else { #ifdef ARDUINO_ARCH_ESP32 - this_->ip_ = IPAddress(ipaddr->u_addr.ip4.addr); + a_this->ip_ = IPAddress(ipaddr->u_addr.ip4.addr); #endif #ifdef ARDUINO_ARCH_ESP8266 - this_->ip_ = IPAddress(ipaddr->addr); + a_this->ip_ = IPAddress(ipaddr->addr); #endif - this_->dns_resolved_ = true; + a_this->dns_resolved_ = true; } } -void MQTTClientComponent::start_connect() { +void MQTTClientComponent::start_connect_() { if (!network_is_connected()) return; @@ -202,7 +202,7 @@ void MQTTClientComponent::check_connected() { if (!this->mqtt_client_.connected()) { if (millis() - this->connect_begin_ > 60000) { this->state_ = MQTT_CLIENT_DISCONNECTED; - this->start_dnslookup(); + this->start_dnslookup_(); } return; } @@ -264,11 +264,11 @@ void MQTTClientComponent::loop() { switch (this->state_) { case MQTT_CLIENT_DISCONNECTED: if (now - this->connect_begin_ > 5000) { - this->start_dnslookup(); + this->start_dnslookup_(); } break; case MQTT_CLIENT_RESOLVING_ADDRESS: - this->check_dnslookup(); + this->check_dnslookup_(); break; case MQTT_CLIENT_CONNECTING: this->check_connected(); @@ -277,7 +277,7 @@ void MQTTClientComponent::loop() { if (!this->mqtt_client_.connected()) { this->state_ = MQTT_CLIENT_DISCONNECTED; ESP_LOGW(TAG, "Lost MQTT Client connection!"); - this->start_dnslookup(); + this->start_dnslookup_(); } else { if (!this->birth_message_.topic.empty() && !this->sent_birth_message_) { this->sent_birth_message_ = this->publish(this->birth_message_); @@ -294,9 +294,7 @@ void MQTTClientComponent::loop() { reboot("mqtt"); } } -float MQTTClientComponent::get_setup_priority() const { - return setup_priority::MQTT_CLIENT; -} +float MQTTClientComponent::get_setup_priority() const { return setup_priority::MQTT_CLIENT; } // Subscribe bool MQTTClientComponent::subscribe_(const char *topic, uint8_t qos) { @@ -328,8 +326,8 @@ void MQTTClientComponent::resubscribe_subscription_(MQTTSubscription *sub) { } } void MQTTClientComponent::resubscribe_subscriptions_() { - for (size_t i = 0; i < this->subscriptions_.size(); i++) { - this->resubscribe_subscription_(&this->subscriptions_[i]); + for (auto &subscription : this->subscriptions_) { + this->resubscribe_subscription_(&subscription); } } @@ -347,9 +345,7 @@ void MQTTClientComponent::subscribe(const std::string &topic, mqtt_callback_t ca void MQTTClientComponent::subscribe_json(const std::string &topic, mqtt_json_callback_t callback, uint8_t qos) { auto f = [callback](const std::string &topic, const std::string &payload) { - parse_json(payload, [topic, callback](JsonObject &root) { - callback(topic, root); - }); + parse_json(payload, [topic, callback](JsonObject &root) { callback(topic, root); }); }; MQTTSubscription subscription{ .topic = topic, @@ -367,8 +363,8 @@ bool MQTTClientComponent::publish(const std::string &topic, const std::string &p return this->publish(topic, payload.data(), payload.size(), qos, retain); } -bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, - uint8_t qos, bool retain) { +bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos, + bool retain) { if (!this->is_connected()) { // critical components will re-transmit their messages return false; @@ -413,7 +409,7 @@ bool MQTTClientComponent::publish_json(const std::string &topic, const json_buil * @param past_separator Are we past the first '/' topic separator. * @return true if the subscription topic matches the message topic, false otherwise. */ -static bool topic_match_(const char *message, const char *subscription, bool is_normal, bool past_separator) { +static bool topic_match(const char *message, const char *subscription, bool is_normal, bool past_separator) { // Reached end of both strings at the same time, this means we have a successful match if (*message == '\0' && *subscription == '\0') return true; @@ -434,7 +430,7 @@ static bool topic_match_(const char *message, const char *subscription, bool is_ } // after this, both pointers will point to a '/' or to the end of the string - return topic_match_(message, subscription, is_normal, true); + return topic_match(message, subscription, is_normal, true); } if (*subscription == '#' && do_wildcards) { @@ -452,11 +448,11 @@ static bool topic_match_(const char *message, const char *subscription, bool is_ subscription++; message++; - return topic_match_(message, subscription, is_normal, past_separator); + return topic_match(message, subscription, is_normal, past_separator); } static bool topic_match(const char *message, const char *subscription) { - return topic_match_(message, subscription, *message != '\0' && *message != '$', false); + return topic_match(message, subscription, *message != '\0' && *message != '$', false); } void MQTTClientComponent::on_message(const std::string &topic, const std::string &payload) { @@ -474,36 +470,20 @@ void MQTTClientComponent::on_message(const std::string &topic, const std::string } // Setters -void MQTTClientComponent::disable_log_message() { - this->log_message_.topic = ""; -} -bool MQTTClientComponent::is_log_message_enabled() const { - return !this->log_message_.topic.empty(); -} +void MQTTClientComponent::disable_log_message() { this->log_message_.topic = ""; } +bool MQTTClientComponent::is_log_message_enabled() const { return !this->log_message_.topic.empty(); } MQTTMessageTrigger *MQTTClientComponent::make_message_trigger(const std::string &topic) { return new MQTTMessageTrigger(topic); } MQTTJsonMessageTrigger *MQTTClientComponent::make_json_message_trigger(const std::string &topic, uint8_t qos) { return new MQTTJsonMessageTrigger(topic, qos); } -void MQTTClientComponent::set_reboot_timeout(uint32_t reboot_timeout) { - this->reboot_timeout_ = reboot_timeout; -} -void MQTTClientComponent::register_mqtt_component(MQTTComponent *component) { - this->children_.push_back(component); -} -void MQTTClientComponent::set_log_level(int level) { - this->log_level_ = level; -} -void MQTTClientComponent::set_keep_alive(uint16_t keep_alive_s) { - this->mqtt_client_.setKeepAlive(keep_alive_s); -} -void MQTTClientComponent::set_log_message_template(MQTTMessage &&message) { - this->log_message_ = std::move(message); -} -const MQTTDiscoveryInfo &MQTTClientComponent::get_discovery_info() const { - return this->discovery_info_; -} +void MQTTClientComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; } +void MQTTClientComponent::register_mqtt_component(MQTTComponent *component) { this->children_.push_back(component); } +void MQTTClientComponent::set_log_level(int level) { this->log_level_ = level; } +void MQTTClientComponent::set_keep_alive(uint16_t keep_alive_s) { this->mqtt_client_.setKeepAlive(keep_alive_s); } +void MQTTClientComponent::set_log_message_template(MQTTMessage &&message) { this->log_message_ = std::move(message); } +const MQTTDiscoveryInfo &MQTTClientComponent::get_discovery_info() const { return this->discovery_info_; } void MQTTClientComponent::set_topic_prefix(std::string topic_prefix) { this->topic_prefix_ = std::move(topic_prefix); this->set_birth_message(MQTTMessage{ @@ -525,27 +505,19 @@ void MQTTClientComponent::set_topic_prefix(std::string topic_prefix) { .retain = false, }); } -const std::string &MQTTClientComponent::get_topic_prefix() const { - return this->topic_prefix_; -} +const std::string &MQTTClientComponent::get_topic_prefix() const { return this->topic_prefix_; } void MQTTClientComponent::disable_birth_message() { this->birth_message_.topic = ""; - this->recalculate_availability(); + this->recalculate_availability_(); } void MQTTClientComponent::disable_shutdown_message() { this->shutdown_message_.topic = ""; - this->recalculate_availability(); -} -bool MQTTClientComponent::is_discovery_enabled() const { - return !this->discovery_info_.prefix.empty(); + this->recalculate_availability_(); } -void MQTTClientComponent::set_client_id(std::string client_id) { - this->credentials_.client_id = std::move(client_id); -} -const Availability &MQTTClientComponent::get_availability() { - return this->availability_; -} -void MQTTClientComponent::recalculate_availability() { +bool MQTTClientComponent::is_discovery_enabled() const { return !this->discovery_info_.prefix.empty(); } +void MQTTClientComponent::set_client_id(std::string client_id) { this->credentials_.client_id = std::move(client_id); } +const Availability &MQTTClientComponent::get_availability() { return this->availability_; } +void MQTTClientComponent::recalculate_availability_() { if (this->birth_message_.topic.empty() || this->birth_message_.topic != this->last_will_.topic) { this->availability_.topic = ""; return; @@ -557,17 +529,15 @@ void MQTTClientComponent::recalculate_availability() { void MQTTClientComponent::set_last_will(MQTTMessage &&message) { this->last_will_ = std::move(message); - this->recalculate_availability(); + this->recalculate_availability_(); } void MQTTClientComponent::set_birth_message(MQTTMessage &&message) { this->birth_message_ = std::move(message); - this->recalculate_availability(); + this->recalculate_availability_(); } -void MQTTClientComponent::set_shutdown_message(MQTTMessage &&message) { - this->shutdown_message_ = std::move(message); -} +void MQTTClientComponent::set_shutdown_message(MQTTMessage &&message) { this->shutdown_message_ = std::move(message); } void MQTTClientComponent::set_discovery_info(std::string &&prefix, bool retain, bool clean) { this->discovery_info_.prefix = std::move(prefix); @@ -575,15 +545,10 @@ void MQTTClientComponent::set_discovery_info(std::string &&prefix, bool retain, this->discovery_info_.clean = clean; } -void MQTTClientComponent::disable_last_will() { - this->last_will_.topic = ""; -} +void MQTTClientComponent::disable_last_will() { this->last_will_.topic = ""; } void MQTTClientComponent::disable_discovery() { - this->discovery_info_ = MQTTDiscoveryInfo{ - .prefix = "", - .retain = false - }; + this->discovery_info_ = MQTTDiscoveryInfo{.prefix = "", .retain = false}; } #if ASYNC_TCP_SSL_ENABLED @@ -597,42 +562,34 @@ MQTTClientComponent *global_mqtt_client = nullptr; // MQTTJsonMessageTrigger MQTTJsonMessageTrigger::MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos) { - global_mqtt_client->subscribe_json(topic, [this](const std::string &topic, JsonObject &root) { - this->trigger(root); - }, qos); + global_mqtt_client->subscribe_json(topic, [this](const std::string &topic, JsonObject &root) { this->trigger(root); }, + qos); } // MQTTMessageTrigger -MQTTMessageTrigger::MQTTMessageTrigger(const std::string &topic) - : topic_(topic) { - -} -void MQTTMessageTrigger::set_qos(uint8_t qos) { - this->qos_ = qos; -} -void MQTTMessageTrigger::set_payload(const std::string &payload) { - this->payload_ = payload; -} +MQTTMessageTrigger::MQTTMessageTrigger(const std::string &topic) : topic_(topic) {} +void MQTTMessageTrigger::set_qos(uint8_t qos) { this->qos_ = qos; } +void MQTTMessageTrigger::set_payload(const std::string &payload) { this->payload_ = payload; } void MQTTMessageTrigger::setup() { - global_mqtt_client->subscribe(this->topic_, [this](const std::string &topic, const std::string &payload) { - if (this->payload_.has_value() && payload != *this->payload_) { - return; - } + global_mqtt_client->subscribe(this->topic_, + [this](const std::string &topic, const std::string &payload) { + if (this->payload_.has_value() && payload != *this->payload_) { + return; + } - this->trigger(payload); - }, this->qos_); + this->trigger(payload); + }, + this->qos_); } void MQTTMessageTrigger::dump_config() { ESP_LOGCONFIG(TAG, "MQTT Message Trigger:"); ESP_LOGCONFIG(TAG, " Topic: '%s'", this->topic_.c_str()); ESP_LOGCONFIG(TAG, " QoS: %u", this->qos_); } -float MQTTMessageTrigger::get_setup_priority() const { - return setup_priority::MQTT_CLIENT; -} +float MQTTMessageTrigger::get_setup_priority() const { return setup_priority::MQTT_CLIENT; } -} // namespace mqtt +} // namespace mqtt ESPHOME_NAMESPACE_END -#endif //USE_MQTT +#endif // USE_MQTT diff --git a/src/esphome/mqtt/mqtt_client_component.h b/src/esphome/mqtt/mqtt_client_component.h index 508f79e0..b47a7e24 100644 --- a/src/esphome/mqtt/mqtt_client_component.h +++ b/src/esphome/mqtt/mqtt_client_component.h @@ -32,7 +32,7 @@ using mqtt_json_callback_t = std::function -class MQTTPublishAction; +template class MQTTPublishAction; -template -class MQTTPublishJsonAction; +template class MQTTPublishJsonAction; /** Internal struct for MQTT Home Assistant discovery * * See MQTT Discovery. */ struct MQTTDiscoveryInfo { - std::string prefix; ///< The Home Assistant discovery prefix. Empty means disabled. - bool retain; ///< Whether to retain discovery messages. + std::string prefix; ///< The Home Assistant discovery prefix. Empty means disabled. + bool retain; ///< Whether to retain discovery messages. bool clean; }; @@ -175,7 +173,8 @@ class MQTTClientComponent : public Component { * If an invalid JSON payload is received, the callback will not be called. * * @param topic The topic. Wildcards are currently not supported. - * @param callback The callback with a parsed JsonObject that will be called when a message with matching topic is received. + * @param callback The callback with a parsed JsonObject that will be called when a message with matching topic is + * received. * @param qos The QoS of this subscription. */ void subscribe_json(const std::string &topic, mqtt_json_callback_t callback, uint8_t qos = 0); @@ -194,8 +193,8 @@ class MQTTClientComponent : public Component { */ bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false); - bool publish(const std::string &topic, const char *payload, size_t payload_length, - uint8_t qos = 0, bool retain = false); + bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0, + bool retain = false); /** Construct and send a JSON MQTT message. * @@ -219,11 +218,9 @@ class MQTTClientComponent : public Component { MQTTJsonMessageTrigger *make_json_message_trigger(const std::string &topic, uint8_t qos = 0); - template - MQTTPublishAction *make_publish_action(); + template MQTTPublishAction *make_publish_action(); - template - MQTTPublishJsonAction *make_publish_json_action(); + template MQTTPublishJsonAction *make_publish_json_action(); bool can_proceed() override; @@ -237,19 +234,19 @@ class MQTTClientComponent : public Component { protected: /// Reconnect to the MQTT broker if not already connected. - void start_connect(); - void start_dnslookup(); - void check_dnslookup(); + void start_connect_(); + void start_dnslookup_(); + void check_dnslookup_(); #if defined(ARDUINO_ARCH_ESP8266) && LWIP_VERSION_MAJOR == 1 - static void dns_found_callback_(const char *name, ip_addr_t *ipaddr, void *callback_arg); + static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg); #else - static void dns_found_callback_(const char *name, const ip_addr_t *ipaddr, void *callback_arg); + static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg); #endif /// Re-calculate the availability property. - void recalculate_availability(); + void recalculate_availability_(); - bool subscribe_(const char* topic, uint8_t qos); + bool subscribe_(const char *topic, uint8_t qos); void resubscribe_subscription_(MQTTSubscription *sub); void resubscribe_subscriptions_(); @@ -311,19 +308,14 @@ class MQTTJsonMessageTrigger : public Trigger { explicit MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos = 0); }; -template -class MQTTPublishAction : public Action { +template class MQTTPublishAction : public Action { public: MQTTPublishAction(); - template - void set_topic(V topic) { this->topic_ = topic; } - template - void set_payload(V payload) { this->payload_ = payload; } - template - void set_qos(V qos) { this->qos_ = qos; } - template - void set_retain(V retain) { this->retain_ = retain; } + template void set_topic(V topic) { this->topic_ = topic; } + template void set_payload(V payload) { this->payload_ = payload; } + template void set_qos(V qos) { this->qos_ = qos; } + template void set_retain(V retain) { this->retain_ = retain; } void play(Ts... x) override; @@ -334,13 +326,11 @@ class MQTTPublishAction : public Action { TemplatableValue retain_{false}; }; -template -class MQTTPublishJsonAction : public Action { +template class MQTTPublishJsonAction : public Action { public: MQTTPublishJsonAction(); - template - void set_topic(V topic) { this->topic_ = topic; } + template void set_topic(V topic) { this->topic_ = topic; } void set_payload(std::function payload); void set_qos(uint8_t qos); void set_retain(bool retain); @@ -361,50 +351,37 @@ template void MQTTPublishJsonAction::set_payload(std::function payload) { this->payload_ = std::move(payload); } -template -void MQTTPublishJsonAction::set_qos(uint8_t qos) { - this->qos_ = qos; -} -template -void MQTTPublishJsonAction::set_retain(bool retain) { - this->retain_ = retain; -} -template -void MQTTPublishJsonAction::play(Ts... x) { +template void MQTTPublishJsonAction::set_qos(uint8_t qos) { this->qos_ = qos; } +template void MQTTPublishJsonAction::set_retain(bool retain) { this->retain_ = retain; } +template void MQTTPublishJsonAction::play(Ts... x) { auto f = std::bind(&MQTTPublishJsonAction::encode_, this, x..., std::placeholders::_1); global_mqtt_client->publish_json(this->topic_.value(x...), f, this->qos_, this->retain_); this->play_next(x...); } -template -void MQTTPublishJsonAction::encode_(Ts... x, JsonObject &root) { +template void MQTTPublishJsonAction::encode_(Ts... x, JsonObject &root) { this->payload_(x..., root); } -template -MQTTPublishJsonAction::MQTTPublishJsonAction() = default; +template MQTTPublishJsonAction::MQTTPublishJsonAction() = default; -template -MQTTPublishJsonAction *MQTTClientComponent::make_publish_json_action() { +template MQTTPublishJsonAction *MQTTClientComponent::make_publish_json_action() { return new MQTTPublishJsonAction(); } -template -void MQTTPublishAction::play(Ts... x) { - global_mqtt_client->publish(this->topic_.value(x...), this->payload_.value(x...), - this->qos_.value(x...), this->retain_.value(x...)); +template void MQTTPublishAction::play(Ts... x) { + global_mqtt_client->publish(this->topic_.value(x...), this->payload_.value(x...), this->qos_.value(x...), + this->retain_.value(x...)); this->play_next(x...); } -template -MQTTPublishAction::MQTTPublishAction() = default; +template MQTTPublishAction::MQTTPublishAction() = default; -template -MQTTPublishAction *MQTTClientComponent::make_publish_action() { +template MQTTPublishAction *MQTTClientComponent::make_publish_action() { return new MQTTPublishAction(); } -} // namespace mqtt +} // namespace mqtt ESPHOME_NAMESPACE_END -#endif //USE_MQTT +#endif // USE_MQTT -#endif //ESPHOME_MQTT_MQTT_CLIENT_COMPONENT_H +#endif // ESPHOME_MQTT_MQTT_CLIENT_COMPONENT_H diff --git a/src/esphome/mqtt/mqtt_component.cpp b/src/esphome/mqtt/mqtt_component.cpp index 7d0ad9d9..d2dd6dac 100644 --- a/src/esphome/mqtt/mqtt_component.cpp +++ b/src/esphome/mqtt/mqtt_component.cpp @@ -20,30 +20,28 @@ namespace mqtt { static const char *TAG = "mqtt.component"; #endif -void MQTTComponent::set_retain(bool retain) { - this->retain_ = retain; -} +void MQTTComponent::set_retain(bool retain) { this->retain_ = retain; } -std::string MQTTComponent::get_discovery_topic(const MQTTDiscoveryInfo &discovery_info) const { +std::string MQTTComponent::get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const { std::string sanitized_name = sanitize_string_whitelist(get_app_name(), HOSTNAME_CHARACTER_WHITELIST); return discovery_info.prefix + "/" + this->component_type() + "/" + sanitized_name + "/" + - this->get_default_object_id() + "/config"; + this->get_default_object_id_() + "/config"; } -std::string MQTTComponent::get_default_topic_for(const std::string &suffix) const { - return global_mqtt_client->get_topic_prefix() + "/" + this->component_type() + "/" + this->get_default_object_id() - + "/" + suffix; +std::string MQTTComponent::get_default_topic_for_(const std::string &suffix) const { + return global_mqtt_client->get_topic_prefix() + "/" + this->component_type() + "/" + this->get_default_object_id_() + + "/" + suffix; } -const std::string MQTTComponent::get_state_topic() const { +const std::string MQTTComponent::get_state_topic_() const { if (this->custom_state_topic_.empty()) - return this->get_default_topic_for("state"); + return this->get_default_topic_for_("state"); return this->custom_state_topic_; } -const std::string MQTTComponent::get_command_topic() const { +const std::string MQTTComponent::get_command_topic_() const { if (this->custom_command_topic_.empty()) - return this->get_default_topic_for("command"); + return this->get_default_topic_for_("command"); return this->custom_command_topic_; } @@ -64,76 +62,77 @@ bool MQTTComponent::send_discovery_() { if (discovery_info.clean) { ESP_LOGV(TAG, "'%s': Cleaning discovery...", this->friendly_name().c_str()); - return global_mqtt_client->publish(this->get_discovery_topic(discovery_info), "", 0, 0, true); + return global_mqtt_client->publish(this->get_discovery_topic_(discovery_info), "", 0, 0, true); } ESP_LOGV(TAG, "'%s': Sending discovery...", this->friendly_name().c_str()); - return global_mqtt_client->publish_json(this->get_discovery_topic(discovery_info), [this](JsonObject &root) { - SendDiscoveryConfig config; - config.state_topic = true; - config.command_topic = true; - config.platform = "mqtt"; - - this->send_discovery(root, config); - - std::string name = this->friendly_name(); - root["name"] = name; - if (strcmp(config.platform, "mqtt") != 0) - root["platform"] = config.platform; - if (config.state_topic) - root["state_topic"] = this->get_state_topic(); - if (config.command_topic) - root["command_topic"] = this->get_command_topic(); - - if (this->availability_ == nullptr) { - root["availability_topic"] = global_mqtt_client->get_availability().topic; - if (global_mqtt_client->get_availability().payload_available != "online") - root["payload_available"] = global_mqtt_client->get_availability().payload_available; - if (global_mqtt_client->get_availability().payload_not_available != "offline") - root["payload_not_available"] = global_mqtt_client->get_availability().payload_not_available; - } else if (!this->availability_->topic.empty()) { - root["availability_topic"] = this->availability_->topic; - if (this->availability_->payload_available != "online") - root["payload_available"] = this->availability_->payload_available; - if (this->availability_->payload_not_available != "offline") - root["payload_not_available"] = this->availability_->payload_not_available; - } - - const std::string &node_name = get_app_name(); - std::string unique_id = this->unique_id(); - if (!unique_id.empty()) { - root["unique_id"] = unique_id; - } else { - // default to almost-unique ID. It's a hack but the only way to get that - // gorgeous device registry view. - root["unique_id"] = "ESP" + this->component_type() + this->get_default_object_id(); - } - - JsonObject &device_info = root.createNestedObject("device"); - device_info["identifiers"] = get_mac_address(); - device_info["name"] = node_name; - if (get_app_compilation_time().empty()) { - device_info["sw_version"] = "esphome v" ESPHOME_VERSION; - } else { - device_info["sw_version"] = "esphome v" ESPHOME_VERSION " " + get_app_compilation_time(); - } + return global_mqtt_client->publish_json( + this->get_discovery_topic_(discovery_info), + [this](JsonObject &root) { + SendDiscoveryConfig config; + config.state_topic = true; + config.command_topic = true; + config.platform = "mqtt"; + + this->send_discovery(root, config); + + std::string name = this->friendly_name(); + root["name"] = name; + if (strcmp(config.platform, "mqtt") != 0) + root["platform"] = config.platform; + if (config.state_topic) + root["state_topic"] = this->get_state_topic_(); + if (config.command_topic) + root["command_topic"] = this->get_command_topic_(); + + if (this->availability_ == nullptr) { + root["availability_topic"] = global_mqtt_client->get_availability().topic; + if (global_mqtt_client->get_availability().payload_available != "online") + root["payload_available"] = global_mqtt_client->get_availability().payload_available; + if (global_mqtt_client->get_availability().payload_not_available != "offline") + root["payload_not_available"] = global_mqtt_client->get_availability().payload_not_available; + } else if (!this->availability_->topic.empty()) { + root["availability_topic"] = this->availability_->topic; + if (this->availability_->payload_available != "online") + root["payload_available"] = this->availability_->payload_available; + if (this->availability_->payload_not_available != "offline") + root["payload_not_available"] = this->availability_->payload_not_available; + } + + const std::string &node_name = get_app_name(); + std::string unique_id = this->unique_id(); + if (!unique_id.empty()) { + root["unique_id"] = unique_id; + } else { + // default to almost-unique ID. It's a hack but the only way to get that + // gorgeous device registry view. + root["unique_id"] = "ESP" + this->component_type() + this->get_default_object_id_(); + } + + JsonObject &device_info = root.createNestedObject("device"); + device_info["identifiers"] = get_mac_address(); + device_info["name"] = node_name; + if (get_app_compilation_time().empty()) { + device_info["sw_version"] = "esphome v" ESPHOME_VERSION; + } else { + device_info["sw_version"] = "esphome v" ESPHOME_VERSION " " + get_app_compilation_time(); + } #ifdef ARDUINO_BOARD - device_info["model"] = ARDUINO_BOARD; + device_info["model"] = ARDUINO_BOARD; #endif - device_info["manufacturer"] = "espressif"; - }, 0, discovery_info.retain); + device_info["manufacturer"] = "espressif"; + }, + 0, discovery_info.retain); } -bool MQTTComponent::get_retain() const { - return this->retain_; -} +bool MQTTComponent::get_retain() const { return this->retain_; } bool MQTTComponent::is_discovery_enabled() const { return this->discovery_enabled_ && global_mqtt_client->is_discovery_enabled(); } -std::string MQTTComponent::get_default_object_id() const { +std::string MQTTComponent::get_default_object_id_() const { return sanitize_string_whitelist(to_lowercase_underscore(this->friendly_name()), HOSTNAME_CHARACTER_WHITELIST); } @@ -147,12 +146,8 @@ void MQTTComponent::subscribe_json(const std::string &topic, mqtt_json_callback_ MQTTComponent::MQTTComponent() = default; -float MQTTComponent::get_setup_priority() const { - return setup_priority::MQTT_COMPONENT; -} -void MQTTComponent::disable_discovery() { - this->discovery_enabled_ = false; -} +float MQTTComponent::get_setup_priority() const { return setup_priority::MQTT_COMPONENT; } +void MQTTComponent::disable_discovery() { this->discovery_enabled_ = false; } void MQTTComponent::set_custom_state_topic(const std::string &custom_state_topic) { this->custom_state_topic_ = custom_state_topic; } @@ -160,8 +155,7 @@ void MQTTComponent::set_custom_command_topic(const std::string &custom_command_t this->custom_command_topic_ = custom_command_topic; } -void MQTTComponent::set_availability(std::string topic, - std::string payload_available, +void MQTTComponent::set_availability(std::string topic, std::string payload_available, std::string payload_not_available) { delete this->availability_; this->availability_ = new Availability(); @@ -169,12 +163,10 @@ void MQTTComponent::set_availability(std::string topic, this->availability_->payload_available = std::move(payload_available); this->availability_->payload_not_available = std::move(payload_not_available); } -void MQTTComponent::disable_availability() { - this->set_availability("", "", ""); -} -void MQTTComponent::setup_() { +void MQTTComponent::disable_availability() { this->set_availability("", "", ""); } +void MQTTComponent::call_setup() { // Call component internal setup. - this->setup_internal(); + this->setup_internal_(); if (this->is_internal()) return; @@ -183,7 +175,7 @@ void MQTTComponent::setup_() { global_mqtt_client->register_mqtt_component(this); - if (!this->is_connected()) + if (!this->is_connected_()) return; if (this->is_discovery_enabled()) { @@ -196,15 +188,15 @@ void MQTTComponent::setup_() { } } -void MQTTComponent::loop_() { - this->loop_internal(); +void MQTTComponent::call_loop() { + this->loop_internal_(); if (this->is_internal()) return; this->loop(); - if (!this->resend_state_ || !this->is_connected()) { + if (!this->resend_state_ || !this->is_connected_()) { return; } @@ -218,18 +210,12 @@ void MQTTComponent::loop_() { this->schedule_resend_state(); } } -void MQTTComponent::schedule_resend_state() { - this->resend_state_ = true; -} -std::string MQTTComponent::unique_id() { - return ""; -} -bool MQTTComponent::is_connected() const { - return global_mqtt_client->is_connected(); -} +void MQTTComponent::schedule_resend_state() { this->resend_state_ = true; } +std::string MQTTComponent::unique_id() { return ""; } +bool MQTTComponent::is_connected_() const { return global_mqtt_client->is_connected(); } -} // namespace mqtt +} // namespace mqtt ESPHOME_NAMESPACE_END -#endif //USE_MQTT +#endif // USE_MQTT diff --git a/src/esphome/mqtt/mqtt_component.h b/src/esphome/mqtt/mqtt_component.h index 5cb5e27c..0eb3a802 100644 --- a/src/esphome/mqtt/mqtt_component.h +++ b/src/esphome/mqtt/mqtt_component.h @@ -14,15 +14,18 @@ namespace mqtt { /// Simple Helper struct used for Home Assistant MQTT send_discovery(). struct SendDiscoveryConfig { - bool state_topic{true}; ///< If the state topic should be included. Defaults to true. - bool command_topic{true}; ///< If the command topic should be included. Default to true. - const char *platform{"mqtt"}; ///< The platform of this component. Defaults to "mqtt". + bool state_topic{true}; ///< If the state topic should be included. Defaults to true. + bool command_topic{true}; ///< If the command topic should be included. Default to true. + const char *platform{"mqtt"}; ///< The platform of this component. Defaults to "mqtt". }; #define LOG_MQTT_COMPONENT(state_topic, command_topic) \ - if (state_topic) { ESP_LOGCONFIG(TAG, " State Topic: '%s'", this->get_state_topic().c_str()); } \ - if (command_topic) { ESP_LOGCONFIG(TAG, " Command Topic: '%s'", this->get_command_topic().c_str()); } \ - + if (state_topic) { \ + ESP_LOGCONFIG(TAG, " State Topic: '%s'", this->get_state_topic_().c_str()); \ + } \ + if (command_topic) { \ + ESP_LOGCONFIG(TAG, " Command Topic: '%s'", this->get_command_topic_().c_str()); \ + } /** MQTTComponent is the base class for all components that interact with MQTT to expose * certain functionality or data from actuators or sensors to clients. @@ -46,9 +49,9 @@ class MQTTComponent : public Component { explicit MQTTComponent(); /// Override setup_ so that we can call send_discovery() when needed. - void setup_() override; + void call_setup() override; - void loop_() override; + void call_loop() override; /// Send discovery info the Home Assistant, override this. virtual void send_discovery(JsonObject &root, SendDiscoveryConfig &config) = 0; @@ -85,38 +88,6 @@ class MQTTComponent : public Component { /// Internal method for the MQTT client base to schedule a resend of the state on reconnect. void schedule_resend_state(); - - protected: - /// Helper method to get the discovery topic for this component. - virtual std::string get_discovery_topic(const MQTTDiscoveryInfo &discovery_info) const; - - /** Get this components state/command/... topic. - * - * @param suffix The suffix/key such as "state" or "command". - * @return The full topic. - */ - virtual std::string get_default_topic_for(const std::string &suffix) const; - - /// Get the friendly name of this MQTT component. - virtual std::string friendly_name() const = 0; - - /** A unique ID for this MQTT component, empty for no unique id. See unique ID requirements: - * https://developers.home-assistant.io/docs/en/entity_registry_index.html#unique-id-requirements - * - * @return The unique id as a string. - */ - virtual std::string unique_id(); - - /// Get the MQTT topic that new states will be shared to. - const std::string get_state_topic() const; - - /// Get the MQTT topic for listening to commands. - const std::string get_command_topic() const; - - bool is_connected() const; - - /// Internal method to start sending discovery info, this will call send_discovery(). - bool send_discovery_(); /** Send a MQTT message. * @@ -145,15 +116,48 @@ class MQTTComponent : public Component { * If an invalid JSON payload is received, the callback will not be called. * * @param topic The topic. Wildcards are currently not supported. - * @param callback The callback with a parsed JsonObject that will be called when a message with matching topic is received. + * @param callback The callback with a parsed JsonObject that will be called when a message with matching topic is + * received. * @param qos The MQTT quality of service. Defaults to 0. */ void subscribe_json(const std::string &topic, mqtt_json_callback_t callback, uint8_t qos = 0); + protected: + /// Helper method to get the discovery topic for this component. + std::string get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const; + + /** Get this components state/command/... topic. + * + * @param suffix The suffix/key such as "state" or "command". + * @return The full topic. + */ + std::string get_default_topic_for_(const std::string &suffix) const; + + /// Get the friendly name of this MQTT component. + virtual std::string friendly_name() const = 0; + + /** A unique ID for this MQTT component, empty for no unique id. See unique ID requirements: + * https://developers.home-assistant.io/docs/en/entity_registry_index.html#unique-id-requirements + * + * @return The unique id as a string. + */ + virtual std::string unique_id(); + + /// Get the MQTT topic that new states will be shared to. + const std::string get_state_topic_() const; + + /// Get the MQTT topic for listening to commands. + const std::string get_command_topic_() const; + + bool is_connected_() const; + + /// Internal method to start sending discovery info, this will call send_discovery(). + bool send_discovery_(); + // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) /// Generate the Home Assistant MQTT discovery object id by automatically transforming the friendly name. - std::string get_default_object_id() const; + std::string get_default_object_id_() const; protected: std::string custom_state_topic_{}; @@ -164,10 +168,10 @@ class MQTTComponent : public Component { bool resend_state_{false}; }; -} // namespace mqtt +} // namespace mqtt ESPHOME_NAMESPACE_END -#endif //USE_MQTT +#endif // USE_MQTT -#endif //ESPHOME_MQTT_MQTT_COMPONENT_H +#endif // ESPHOME_MQTT_MQTT_COMPONENT_H diff --git a/src/esphome/optional.h b/src/esphome/optional.h index e498d29f..b1e9f205 100644 --- a/src/esphome/optional.h +++ b/src/esphome/optional.h @@ -24,46 +24,38 @@ ESPHOME_NAMESPACE_BEGIN // type for nullopt -struct nullopt_t { - struct init {}; +struct nullopt_t { // NOLINT + struct init {}; // NOLINT nullopt_t(init) {} }; // extra parenthesis to prevent the most vexing parse: -const nullopt_t nullopt((nullopt_t::init())); - +const nullopt_t nullopt((nullopt_t::init())); // NOLINT // Simplistic optional: requires T to be default constructible, copyable. -template -class optional { +template class optional { // NOLINT private: - typedef void (optional::*safe_bool)() const; + using safe_bool = void (optional::*)() const; public: - typedef T value_type; + using value_type = T; - optional() - : has_value_(false) {} + optional() {} - optional(nullopt_t) - : has_value_(false) {} + optional(nullopt_t) {} - optional(T const &arg) - : has_value_(true), value_(arg) {} + optional(T const &arg) : has_value_(true), value_(arg) {} - template - optional(optional const &other) - : has_value_(other.has_value()), value_(other.value()) {} + template optional(optional const &other) : has_value_(other.has_value()), value_(other.value()) {} optional &operator=(nullopt_t) { reset(); return *this; } - template - optional &operator=(optional const &other) { + template optional &operator=(optional const &other) { has_value_ = other.has_value(); value_ = other.value(); return *this; @@ -71,12 +63,12 @@ class optional { void swap(optional &rhs) { using std::swap; - if (has_value() == true && rhs.has_value() == true) { swap(**this, *rhs); } - else if (has_value() == false && rhs.has_value() == true) { + if (has_value() && rhs.has_value()) { + swap(**this, *rhs); + } else if (!has_value() && rhs.has_value()) { initialize(*rhs); rhs.reset(); - } - else if (has_value() == true && rhs.has_value() == false) { + } else if (has_value() && !rhs.has_value()) { rhs.initialize(**this); reset(); } @@ -84,233 +76,145 @@ class optional { // observers - value_type const *operator->() const { - return &value_; - } + value_type const *operator->() const { return &value_; } - value_type *operator->() { - return &value_; - } + value_type *operator->() { return &value_; } - value_type const &operator*() const { - return value_; - } + value_type const &operator*() const { return value_; } - value_type &operator*() { - return value_; - } + value_type &operator*() { return value_; } - operator safe_bool() const { - return has_value() ? &optional::this_type_does_not_support_comparisons : 0; - } + operator safe_bool() const { return has_value() ? &optional::this_type_does_not_support_comparisons : 0; } - bool has_value() const { - return has_value_; - } + bool has_value() const { return has_value_; } - value_type const &value() const { - return value_; - } + value_type const &value() const { return value_; } - value_type &value() { - return value_; - } + value_type &value() { return value_; } - template - value_type value_or(U const &v) const { - return has_value() ? value() : static_cast( v ); - } + template value_type value_or(U const &v) const { return has_value() ? value() : static_cast(v); } // modifiers - void reset() { - has_value_ = false; - } + void reset() { has_value_ = false; } private: - void this_type_does_not_support_comparisons() const {} + void this_type_does_not_support_comparisons() const {} // NOLINT - template - void initialize(V const &value) { + template void initialize(V const &value) { // NOLINT value_ = value; has_value_ = true; } private: - bool has_value_; - value_type value_; + bool has_value_{false}; // NOLINT + value_type value_; // NOLINT }; // Relational operators -template -inline bool operator==(optional const &x, optional const &y) { - return bool(x) != bool(y) ? false : bool(x) == false ? true : *x == *y; +template inline bool operator==(optional const &x, optional const &y) { + return bool(x) != bool(y) ? false : !bool(x) ? true : *x == *y; } -template -inline bool operator!=(optional const &x, optional const &y) { +template inline bool operator!=(optional const &x, optional const &y) { return !(x == y); } -template -inline bool operator<(optional const &x, optional const &y) { +template inline bool operator<(optional const &x, optional const &y) { return (!y) ? false : (!x) ? true : *x < *y; } -template -inline bool operator>(optional const &x, optional const &y) { - return (y < x); -} +template inline bool operator>(optional const &x, optional const &y) { return (y < x); } -template -inline bool operator<=(optional const &x, optional const &y) { - return !(y < x); -} +template inline bool operator<=(optional const &x, optional const &y) { return !(y < x); } -template -inline bool operator>=(optional const &x, optional const &y) { - return !(x < y); -} +template inline bool operator>=(optional const &x, optional const &y) { return !(x < y); } // Comparison with nullopt -template -inline bool operator==(optional const &x, nullopt_t) { - return (!x); -} +template inline bool operator==(optional const &x, nullopt_t) { return (!x); } -template -inline bool operator==(nullopt_t, optional const &x) { - return (!x); -} +template inline bool operator==(nullopt_t, optional const &x) { return (!x); } -template -inline bool operator!=(optional const &x, nullopt_t) { - return bool(x); -} +template inline bool operator!=(optional const &x, nullopt_t) { return bool(x); } -template -inline bool operator!=(nullopt_t, optional const &x) { - return bool(x); -} +template inline bool operator!=(nullopt_t, optional const &x) { return bool(x); } -template -inline bool operator<(optional const &, nullopt_t) { - return false; -} +template inline bool operator<(optional const &, nullopt_t) { return false; } -template -inline bool operator<(nullopt_t, optional const &x) { - return bool(x); -} +template inline bool operator<(nullopt_t, optional const &x) { return bool(x); } -template -inline bool operator<=(optional const &x, nullopt_t) { - return (!x); -} +template inline bool operator<=(optional const &x, nullopt_t) { return (!x); } -template -inline bool operator<=(nullopt_t, optional const &) { - return true; -} +template inline bool operator<=(nullopt_t, optional const &) { return true; } -template -inline bool operator>(optional const &x, nullopt_t) { - return bool(x); -} +template inline bool operator>(optional const &x, nullopt_t) { return bool(x); } -template -inline bool operator>(nullopt_t, optional const &) { - return false; -} +template inline bool operator>(nullopt_t, optional const &) { return false; } -template -inline bool operator>=(optional const &, nullopt_t) { - return true; -} +template inline bool operator>=(optional const &, nullopt_t) { return true; } -template -inline bool operator>=(nullopt_t, optional const &x) { - return (!x); -} +template inline bool operator>=(nullopt_t, optional const &x) { return (!x); } // Comparison with T -template -inline bool operator==(optional const &x, U const &v) { +template inline bool operator==(optional const &x, U const &v) { return bool(x) ? *x == v : false; } -template -inline bool operator==(U const &v, optional const &x) { +template inline bool operator==(U const &v, optional const &x) { return bool(x) ? v == *x : false; } -template -inline bool operator!=(optional const &x, U const &v) { +template inline bool operator!=(optional const &x, U const &v) { return bool(x) ? *x != v : true; } -template -inline bool operator!=(U const &v, optional const &x) { +template inline bool operator!=(U const &v, optional const &x) { return bool(x) ? v != *x : true; } -template -inline bool operator<(optional const &x, U const &v) { +template inline bool operator<(optional const &x, U const &v) { return bool(x) ? *x < v : true; } -template -inline bool operator<(U const &v, optional const &x) { +template inline bool operator<(U const &v, optional const &x) { return bool(x) ? v < *x : false; } -template -inline bool operator<=(optional const &x, U const &v) { +template inline bool operator<=(optional const &x, U const &v) { return bool(x) ? *x <= v : true; } -template -inline bool operator<=(U const &v, optional const &x) { +template inline bool operator<=(U const &v, optional const &x) { return bool(x) ? v <= *x : false; } -template -inline bool operator>(optional const &x, U const &v) { +template inline bool operator>(optional const &x, U const &v) { return bool(x) ? *x > v : false; } -template -inline bool operator>(U const &v, optional const &x) { +template inline bool operator>(U const &v, optional const &x) { return bool(x) ? v > *x : true; } -template -inline bool operator>=(optional const &x, U const &v) { +template inline bool operator>=(optional const &x, U const &v) { return bool(x) ? *x >= v : false; } -template -inline bool operator>=(U const &v, optional const &x) { +template inline bool operator>=(U const &v, optional const &x) { return bool(x) ? v >= *x : true; } // Specialized algorithms -template -void swap(optional &x, optional &y) { - x.swap(y); -} +template void swap(optional &x, optional &y) { x.swap(y); } // Convenience function to create an optional. -template -inline optional make_optional(T const &v) { - return optional(v); -} +template inline optional make_optional(T const &v) { return optional(v); } ESPHOME_NAMESPACE_END -#endif //ESPHOME_OPTIONAL_H +#endif // ESPHOME_OPTIONAL_H diff --git a/src/esphome/ota_component.cpp b/src/esphome/ota_component.cpp index f1c45492..92414542 100644 --- a/src/esphome/ota_component.cpp +++ b/src/esphome/ota_component.cpp @@ -11,11 +11,11 @@ #include #ifndef USE_NEW_OTA - #include +#include #else #include #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #endif #include @@ -34,9 +34,7 @@ void OTAComponent::setup() { #ifdef USE_NEW_OTA #ifdef ARDUINO_ARCH_ESP32 - add_shutdown_hook([this](const char *cause) { - this->server_->close(); - }); + add_shutdown_hook([this](const char *cause) { this->server_->close(); }); #endif #else ArduinoOTA.setHostname(get_app_name().c_str()); @@ -52,8 +50,10 @@ void OTAComponent::setup() { break; } #endif - case OPEN: {} - default: break; + case OPEN: { + } + default: + break; } ArduinoOTA.onStart([this]() { @@ -77,7 +77,7 @@ void OTAComponent::setup() { ArduinoOTA.onProgress([this](uint progress, uint total) { tick_status_led(); if (this->at_ota_progress_message_++ % 8 != 0) - return; // only print every 8th message + return; // only print every 8th message float percentage = float(progress) * 100 / float(total); ESP_LOGD(TAG, "OTA in progress: %0.1f%%", percentage); }); @@ -104,7 +104,8 @@ void OTAComponent::setup() { ESP_LOGE(TAG, " End Failed"); break; } - default:ESP_LOGE(TAG, " Unknown Error"); + default: + ESP_LOGE(TAG, " Unknown Error"); } this->ota_triggered_ = false; this->status_clear_warning(); @@ -116,11 +117,8 @@ void OTAComponent::setup() { ArduinoOTA.begin(); #endif - if (this->has_safe_mode_) { - add_safe_shutdown_hook([this](const char *cause) { - this->clean_rtc(); - }); + add_safe_shutdown_hook([this](const char *cause) { this->clean_rtc(); }); } this->dump_config(); @@ -190,8 +188,8 @@ void OTAComponent::handle_() { } // 0x6C, 0x26, 0xF7, 0x5C, 0x45 if (buf[0] != 0x6C || buf[1] != 0x26 || buf[2] != 0xF7 || buf[3] != 0x5C || buf[4] != 0x45) { - ESP_LOGW(TAG, "Magic bytes do not match! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", - buf[0], buf[1], buf[2], buf[3], buf[4]); + ESP_LOGW(TAG, "Magic bytes do not match! 0x%02X-0x%02X-0x%02X-0x%02X-0x%02X", buf[0], buf[1], buf[2], buf[3], + buf[4]); error_code = OTA_RESPONSE_ERROR_MAGIC; goto error; } @@ -381,7 +379,7 @@ void OTAComponent::handle_() { delay(100); safe_reboot("ota"); - error: +error: if (update_started) { StreamString ss; Update.printError(ss); @@ -440,15 +438,10 @@ size_t OTAComponent::wait_receive_(uint8_t *buf, size_t bytes, bool check_discon } #endif -OTAComponent::OTAComponent(uint16_t port) - : port_(port) { - -} +OTAComponent::OTAComponent(uint16_t port) : port_(port) {} #ifdef USE_NEW_OTA -void OTAComponent::set_auth_password(const std::string &password) { - this->password_ = password; -} +void OTAComponent::set_auth_password(const std::string &password) { this->password_ = password; } #else void OTAComponent::set_auth_plaintext_password(const std::string &password) { this->auth_type_ = PLAINTEXT; @@ -460,15 +453,9 @@ void OTAComponent::set_auth_password_hash(const std::string &hash) { } #endif -float OTAComponent::get_setup_priority() const { - return setup_priority::MQTT_CLIENT + 1.0f; -} -uint16_t OTAComponent::get_port() const { - return this->port_; -} -void OTAComponent::set_port(uint16_t port) { - this->port_ = port; -} +float OTAComponent::get_setup_priority() const { return setup_priority::MQTT_CLIENT + 1.0f; } +uint16_t OTAComponent::get_port() const { return this->port_; } +void OTAComponent::set_port(uint16_t port) { this->port_ = port; } void OTAComponent::start_safe_mode(uint8_t num_attempts, uint32_t enable_time) { this->has_safe_mode_ = true; this->safe_mode_start_time_ = millis(); @@ -486,17 +473,17 @@ void OTAComponent::start_safe_mode(uint8_t num_attempts, uint32_t enable_time) { #ifdef USE_STATUS_LED if (global_status_led != nullptr) { - global_status_led->setup_(); + global_status_led->call_setup(); } #endif global_state = STATUS_LED_ERROR; network_setup(); - this->setup_(); + this->call_setup(); ESP_LOGI(TAG, "Waiting for OTA attempt."); uint32_t begin = millis(); while ((millis() - begin) < enable_time) { - this->loop_(); + this->call_loop(); network_tick(); tick_status_led(); yield(); @@ -508,19 +495,15 @@ void OTAComponent::start_safe_mode(uint8_t num_attempts, uint32_t enable_time) { this->write_rtc_(this->safe_mode_rtc_value_ + 1); } } -void OTAComponent::write_rtc_(uint32_t val) { - this->rtc_.save(&val); -} +void OTAComponent::write_rtc_(uint32_t val) { this->rtc_.save(&val); } uint32_t OTAComponent::read_rtc_() { uint32_t val; if (!this->rtc_.load(&val)) return 0; return val; } -void OTAComponent::clean_rtc() { - this->write_rtc_(0); -} +void OTAComponent::clean_rtc() { this->write_rtc_(0); } ESPHOME_NAMESPACE_END -#endif //USE_OTA +#endif // USE_OTA diff --git a/src/esphome/ota_component.h b/src/esphome/ota_component.h index 4be79200..10876242 100644 --- a/src/esphome/ota_component.h +++ b/src/esphome/ota_component.h @@ -11,10 +11,10 @@ #include #ifdef ARDUINO_ARCH_ESP32 - #define OTA_DEFAULT_PORT 3232 +#define OTA_DEFAULT_PORT 3232 #endif #ifdef ARDUINO_ARCH_ESP8266 - #define OTA_DEFAULT_PORT 8266 +#define OTA_DEFAULT_PORT 8266 #endif ESPHOME_NAMESPACE_BEGIN @@ -129,17 +129,17 @@ class OTAComponent : public Component { bool ota_triggered_{false}; #endif - bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled. - uint32_t safe_mode_start_time_; ///inverted_; -} -void BinaryOutput::set_inverted(bool inverted) { - this->inverted_ = inverted; -} -PowerSupplyComponent *BinaryOutput::get_power_supply() const { - return this->power_supply_; -} -void BinaryOutput::set_power_supply(PowerSupplyComponent *power_supply) { - this->power_supply_ = power_supply; -} +bool BinaryOutput::is_inverted() const { return this->inverted_; } +void BinaryOutput::set_inverted(bool inverted) { this->inverted_ = inverted; } +PowerSupplyComponent *BinaryOutput::get_power_supply() const { return this->power_supply_; } +void BinaryOutput::set_power_supply(PowerSupplyComponent *power_supply) { this->power_supply_ = power_supply; } void BinaryOutput::turn_on() { if (this->power_supply_ != nullptr && !this->has_requested_high_power_) { this->power_supply_->request_high_power(); @@ -35,8 +27,8 @@ void BinaryOutput::turn_off() { this->write_state(this->inverted_); } -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT +#endif // USE_OUTPUT diff --git a/src/esphome/output/binary_output.h b/src/esphome/output/binary_output.h index e94914e5..3fe8a241 100644 --- a/src/esphome/output/binary_output.h +++ b/src/esphome/output/binary_output.h @@ -12,13 +12,13 @@ ESPHOME_NAMESPACE_BEGIN namespace output { -template -class TurnOffAction; -template -class TurnOnAction; +template class TurnOffAction; +template class TurnOnAction; #define LOG_BINARY_OUTPUT(this) \ - if (this->inverted_) { ESP_LOGCONFIG(TAG, " Inverted: YES"); } \ + if (this->inverted_) { \ + ESP_LOGCONFIG(TAG, " Inverted: YES"); \ + } /** The base class for all binary outputs i.e. outputs that can only be switched on/off. * @@ -60,10 +60,8 @@ class BinaryOutput { /// Return the power supply assigned to this binary output. PowerSupplyComponent *get_power_supply() const; - template - TurnOffAction *make_turn_off_action(); - template - TurnOnAction *make_turn_on_action(); + template TurnOffAction *make_turn_off_action(); + template TurnOnAction *make_turn_on_action(); protected: virtual void write_state(bool state) = 0; @@ -73,52 +71,46 @@ class BinaryOutput { bool has_requested_high_power_{false}; }; -template -class TurnOffAction : public Action { +template class TurnOffAction : public Action { public: TurnOffAction(BinaryOutput *output); void play(Ts... x) override; + protected: BinaryOutput *output_; }; -template -class TurnOnAction : public Action { +template class TurnOnAction : public Action { public: TurnOnAction(BinaryOutput *output); void play(Ts... x) override; + protected: BinaryOutput *output_; }; -template -TurnOffAction::TurnOffAction(BinaryOutput *output) : output_(output) {} -template -void TurnOffAction::play(Ts... x) { +template TurnOffAction::TurnOffAction(BinaryOutput *output) : output_(output) {} +template void TurnOffAction::play(Ts... x) { this->output_->turn_off(); this->play_next(x...); } -template -TurnOnAction::TurnOnAction(BinaryOutput *output) : output_(output) {} -template -void TurnOnAction::play(Ts... x) { +template TurnOnAction::TurnOnAction(BinaryOutput *output) : output_(output) {} +template void TurnOnAction::play(Ts... x) { this->output_->turn_on(); this->play_next(x...); } -template -TurnOffAction *BinaryOutput::make_turn_off_action() { +template TurnOffAction *BinaryOutput::make_turn_off_action() { return new TurnOffAction(this); } -template -TurnOnAction *BinaryOutput::make_turn_on_action() { +template TurnOnAction *BinaryOutput::make_turn_on_action() { return new TurnOnAction(this); } -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT +#endif // USE_OUTPUT -#endif //ESPHOME_OUTPUT_BINARY_OUTPUT_H +#endif // ESPHOME_OUTPUT_BINARY_OUTPUT_H diff --git a/src/esphome/output/custom_output.cpp b/src/esphome/output/custom_output.cpp index e80fb6a4..4039b96a 100644 --- a/src/esphome/output/custom_output.cpp +++ b/src/esphome/output/custom_output.cpp @@ -12,17 +12,13 @@ namespace output { CustomBinaryOutputConstructor::CustomBinaryOutputConstructor(std::function()> init) { this->outputs_ = init(); } -BinaryOutput *CustomBinaryOutputConstructor::get_output(int i) { - return this->outputs_[i]; -} +BinaryOutput *CustomBinaryOutputConstructor::get_output(int i) { return this->outputs_[i]; } CustomFloatOutputConstructor::CustomFloatOutputConstructor(std::function()> init) { this->outputs_ = init(); } -FloatOutput *CustomFloatOutputConstructor::get_output(int i) { - return this->outputs_[i]; -} -} // namespace output +FloatOutput *CustomFloatOutputConstructor::get_output(int i) { return this->outputs_[i]; } +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_OUTPUT +#endif // USE_CUSTOM_OUTPUT diff --git a/src/esphome/output/custom_output.h b/src/esphome/output/custom_output.h index cd88e631..7279476b 100644 --- a/src/esphome/output/custom_output.h +++ b/src/esphome/output/custom_output.h @@ -32,10 +32,10 @@ class CustomFloatOutputConstructor { std::vector outputs_; }; -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_OUTPUT +#endif // USE_CUSTOM_OUTPUT -#endif //ESPHOME_OUTPUT_CUSTOM_OUTPUT_H +#endif // ESPHOME_OUTPUT_CUSTOM_OUTPUT_H diff --git a/src/esphome/output/esp8266_pwm_output.cpp b/src/esphome/output/esp8266_pwm_output.cpp index c17da7e6..c6d39def 100644 --- a/src/esphome/output/esp8266_pwm_output.cpp +++ b/src/esphome/output/esp8266_pwm_output.cpp @@ -14,10 +14,7 @@ namespace output { static const char *TAG = "output.esp8266_pwm"; -ESP8266PWMOutput::ESP8266PWMOutput(const GPIOOutputPin &pin) - : pin_(pin) { - -} +ESP8266PWMOutput::ESP8266PWMOutput(const GPIOOutputPin &pin) : pin_(pin) {} void ESP8266PWMOutput::setup() { ESP_LOGCONFIG(TAG, "Setting up ESP8266 PWM Output..."); @@ -50,15 +47,11 @@ void HOT ESP8266PWMOutput::write_state(float state) { startWaveform(this->pin_.get_pin(), duty_on, duty_off, 0); } } -float ESP8266PWMOutput::get_setup_priority() const { - return setup_priority::HARDWARE; -} -void ESP8266PWMOutput::set_frequency(float frequency) { - this->frequency_ = frequency; -} +float ESP8266PWMOutput::get_setup_priority() const { return setup_priority::HARDWARE; } +void ESP8266PWMOutput::set_frequency(float frequency) { this->frequency_ = frequency; } -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_ESP8266_PWM_OUTPUT +#endif // USE_ESP8266_PWM_OUTPUT diff --git a/src/esphome/output/esp8266_pwm_output.h b/src/esphome/output/esp8266_pwm_output.h index f748b3b4..d59f59be 100644 --- a/src/esphome/output/esp8266_pwm_output.h +++ b/src/esphome/output/esp8266_pwm_output.h @@ -41,17 +41,18 @@ class ESP8266PWMOutput : public FloatOutput, public Component { /// HARDWARE setup_priority float get_setup_priority() const override; /// Override FloatOutput's write_state for analogWrite - void write_state(float state) override; protected: + void write_state(float state) override; + GPIOOutputPin pin_; float frequency_{1000.0}; }; -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_ESP8266_PWM_OUTPUT +#endif // USE_ESP8266_PWM_OUTPUT -#endif //ESPHOME_ESP_8266_PWM_OUTPUT_H +#endif // ESPHOME_ESP_8266_PWM_OUTPUT_H diff --git a/src/esphome/output/float_output.cpp b/src/esphome/output/float_output.cpp index 2b96e68f..dc8847d3 100644 --- a/src/esphome/output/float_output.cpp +++ b/src/esphome/output/float_output.cpp @@ -12,49 +12,43 @@ ESPHOME_NAMESPACE_BEGIN namespace output { void FloatOutput::set_max_power(float max_power) { - this->max_power_ = clamp(this->min_power_, 1.0f, max_power); // Clamp to MIN>=MAX>=1.0 + this->max_power_ = clamp(this->min_power_, 1.0f, max_power); // Clamp to MIN>=MAX>=1.0 } -float FloatOutput::get_max_power() const { - return this->max_power_; -} +float FloatOutput::get_max_power() const { return this->max_power_; } void FloatOutput::set_min_power(float min_power) { - this->min_power_ = clamp(0.0f, this->max_power_, min_power); // Clamp to 0.0>=MIN>=MAX + this->min_power_ = clamp(0.0f, this->max_power_, min_power); // Clamp to 0.0>=MIN>=MAX } -float FloatOutput::get_min_power() const { - return this->min_power_; -} +float FloatOutput::get_min_power() const { return this->min_power_; } void FloatOutput::set_level(float state) { state = clamp(0.0f, 1.0f, state); - if (state > 0.0f) { // ON + if (state > 0.0f) { // ON // maybe refactor this if (this->power_supply_ != nullptr && !this->has_requested_high_power_) { this->power_supply_->request_high_power(); this->has_requested_high_power_ = true; } - } else { // OFF + } else { // OFF if (this->power_supply_ != nullptr && this->has_requested_high_power_) { this->power_supply_->unrequest_high_power(); this->has_requested_high_power_ = false; } } - float adjusted_value = (state * (this->max_power_ - this->min_power_)) + this->min_power_; + float adjusted_value = (state * (this->max_power_ - this->min_power_)) + this->min_power_; if (this->is_inverted()) adjusted_value = 1.0f - adjusted_value; this->write_state(adjusted_value); } -void FloatOutput::write_state(bool state) { - this->set_level(state != this->inverted_ ? 1.0f : 0.0f); -} +void FloatOutput::write_state(bool state) { this->set_level(state != this->inverted_ ? 1.0f : 0.0f); } -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT +#endif // USE_OUTPUT diff --git a/src/esphome/output/float_output.h b/src/esphome/output/float_output.h index a44bb386..77b354ed 100644 --- a/src/esphome/output/float_output.h +++ b/src/esphome/output/float_output.h @@ -12,13 +12,16 @@ ESPHOME_NAMESPACE_BEGIN namespace output { -template -class SetLevelAction; +template class SetLevelAction; #define LOG_FLOAT_OUTPUT(this) \ LOG_BINARY_OUTPUT(this) \ - if (this->max_power_ != 1.0f) { ESP_LOGCONFIG(TAG, " Max Power: %.1f%%", this->max_power_ * 100.0f); } \ - if (this->min_power_ != 0.0f) { ESP_LOGCONFIG(TAG, " Min Power: %.1f%%", this->min_power_ * 100.0f); } + if (this->max_power_ != 1.0f) { \ + ESP_LOGCONFIG(TAG, " Max Power: %.1f%%", this->max_power_ * 100.0f); \ + } \ + if (this->min_power_ != 0.0f) { \ + ESP_LOGCONFIG(TAG, " Min Power: %.1f%%", this->min_power_ * 100.0f); \ + } /** Base class for all output components that can output a variable level, like PWM. * @@ -63,26 +66,22 @@ class FloatOutput : public BinaryOutput { /// Get the minimum power output. float get_min_power() const; - /// Implement BinarySensor's write_enabled; this should never be called. - void write_state(bool value) override; - - template - SetLevelAction *make_set_level_action(); + template SetLevelAction *make_set_level_action(); protected: + /// Implement BinarySensor's write_enabled; this should never be called. + void write_state(bool state) override; virtual void write_state(float state) = 0; float max_power_{1.0f}; float min_power_{0.0f}; }; -template -class SetLevelAction : public Action { +template class SetLevelAction : public Action { public: SetLevelAction(FloatOutput *output); - template - void set_level(V level) { this->level_ = level; } + template void set_level(V level) { this->level_ = level; } void play(Ts... x) override; protected: @@ -90,24 +89,21 @@ class SetLevelAction : public Action { TemplatableValue level_; }; -template -SetLevelAction::SetLevelAction(FloatOutput *output) : output_(output) {} +template SetLevelAction::SetLevelAction(FloatOutput *output) : output_(output) {} -template -void SetLevelAction::play(Ts... x) { +template void SetLevelAction::play(Ts... x) { this->output_->set_level(this->level_.value(x...)); this->play_next(x...); } -template -SetLevelAction *FloatOutput::make_set_level_action() { +template SetLevelAction *FloatOutput::make_set_level_action() { return new SetLevelAction(this); } -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT +#endif // USE_OUTPUT -#endif //ESPHOME_OUTPUT_FLOAT_OUTPUT_H +#endif // ESPHOME_OUTPUT_FLOAT_OUTPUT_H diff --git a/src/esphome/output/gpio_binary_output_component.cpp b/src/esphome/output/gpio_binary_output_component.cpp index c485026e..b513b9f2 100644 --- a/src/esphome/output/gpio_binary_output_component.cpp +++ b/src/esphome/output/gpio_binary_output_component.cpp @@ -13,9 +13,7 @@ namespace output { static const char *TAG = "output.gpio"; -void GPIOBinaryOutputComponent::write_state(bool state) { - this->pin_->digital_write(state); -} +void GPIOBinaryOutputComponent::write_state(bool state) { this->pin_->digital_write(state); } void GPIOBinaryOutputComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up GPIO Binary Output..."); @@ -29,16 +27,11 @@ void GPIOBinaryOutputComponent::dump_config() { LOG_BINARY_OUTPUT(this); } -float GPIOBinaryOutputComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} -GPIOBinaryOutputComponent::GPIOBinaryOutputComponent(GPIOPin *pin) - : pin_(pin) { - -} +float GPIOBinaryOutputComponent::get_setup_priority() const { return setup_priority::HARDWARE; } +GPIOBinaryOutputComponent::GPIOBinaryOutputComponent(GPIOPin *pin) : pin_(pin) {} -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_GPIO_OUTPUT +#endif // USE_GPIO_OUTPUT diff --git a/src/esphome/output/gpio_binary_output_component.h b/src/esphome/output/gpio_binary_output_component.h index 07ac1349..c5cc49b5 100644 --- a/src/esphome/output/gpio_binary_output_component.h +++ b/src/esphome/output/gpio_binary_output_component.h @@ -39,17 +39,17 @@ class GPIOBinaryOutputComponent : public BinaryOutput, public Component { /// Hardware setup priority. float get_setup_priority() const override; + protected: /// Override the BinaryOutput method for writing values to HW. void write_state(bool state) override; - protected: GPIOPin *pin_; }; -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_GPIO_OUTPUT +#endif // USE_GPIO_OUTPUT -#endif //ESPHOME_OUTPUT_GPIO_BINARY_OUTPUT_COMPONENT_H +#endif // ESPHOME_OUTPUT_GPIO_BINARY_OUTPUT_COMPONENT_H diff --git a/src/esphome/output/ledc_output_component.cpp b/src/esphome/output/ledc_output_component.cpp index 05889698..a40475b2 100644 --- a/src/esphome/output/ledc_output_component.cpp +++ b/src/esphome/output/ledc_output_component.cpp @@ -25,7 +25,7 @@ void LEDCOutputComponent::setup() { ledcSetup(this->channel_, this->frequency_, this->bit_depth_); ledcAttachPin(this->pin_, this->channel_); - this->turn_off(); // initialize off + this->turn_off(); // initialize off } void LEDCOutputComponent::dump_config() { @@ -36,49 +36,28 @@ void LEDCOutputComponent::dump_config() { ESP_LOGCONFIG(TAG, " Bit Depth: %u", this->bit_depth_); } -float LEDCOutputComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float LEDCOutputComponent::get_setup_priority() const { return setup_priority::HARDWARE; } -LEDCOutputComponent::LEDCOutputComponent(uint8_t pin, - float frequency, - uint8_t bit_depth) - : Component(), FloatOutput() { +LEDCOutputComponent::LEDCOutputComponent(uint8_t pin, float frequency, uint8_t bit_depth) : Component(), FloatOutput() { this->set_channel(next_ledc_channel++); this->set_frequency(frequency); this->set_pin(pin); this->set_channel(next_ledc_channel); this->set_bit_depth(bit_depth); } -uint8_t LEDCOutputComponent::get_pin() const { - return this->pin_; -} -void LEDCOutputComponent::set_pin(uint8_t pin) { - this->pin_ = pin; -} -uint8_t LEDCOutputComponent::get_channel() const { - return this->channel_; -} -void LEDCOutputComponent::set_channel(uint8_t channel) { - this->channel_ = channel; -} -uint8_t LEDCOutputComponent::get_bit_depth() const { - return this->bit_depth_; -} -void LEDCOutputComponent::set_bit_depth(uint8_t bit_depth) { - this->bit_depth_ = bit_depth; -} -float LEDCOutputComponent::get_frequency() const { - return this->frequency_; -} -void LEDCOutputComponent::set_frequency(float frequency) { - this->frequency_ = frequency; -} +uint8_t LEDCOutputComponent::get_pin() const { return this->pin_; } +void LEDCOutputComponent::set_pin(uint8_t pin) { this->pin_ = pin; } +uint8_t LEDCOutputComponent::get_channel() const { return this->channel_; } +void LEDCOutputComponent::set_channel(uint8_t channel) { this->channel_ = channel; } +uint8_t LEDCOutputComponent::get_bit_depth() const { return this->bit_depth_; } +void LEDCOutputComponent::set_bit_depth(uint8_t bit_depth) { this->bit_depth_ = bit_depth; } +float LEDCOutputComponent::get_frequency() const { return this->frequency_; } +void LEDCOutputComponent::set_frequency(float frequency) { this->frequency_ = frequency; } uint8_t next_ledc_channel = 0; -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_LEDC_OUTPUT +#endif // USE_LEDC_OUTPUT diff --git a/src/esphome/output/ledc_output_component.h b/src/esphome/output/ledc_output_component.h index d3c3ac16..c6c71498 100644 --- a/src/esphome/output/ledc_output_component.h +++ b/src/esphome/output/ledc_output_component.h @@ -58,10 +58,10 @@ class LEDCOutputComponent : public FloatOutput, public Component { extern uint8_t next_ledc_channel; -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_LEDC_OUTPUT +#endif // USE_LEDC_OUTPUT -#endif //ESPHOME_OUTPUT_LEDC_OUTPUT_COMPONENT_H +#endif // ESPHOME_OUTPUT_LEDC_OUTPUT_COMPONENT_H diff --git a/src/esphome/output/my9231_output_component.cpp b/src/esphome/output/my9231_output_component.cpp index 3dc201a1..7b64bdb9 100644 --- a/src/esphome/output/my9231_output_component.cpp +++ b/src/esphome/output/my9231_output_component.cpp @@ -34,10 +34,8 @@ static const uint8_t MY9231_CMD_FREQUENCY_DIVIDE_64 = 0x3 << 1; static const uint8_t MY9231_CMD_SCATTER_APDM = 0x0 << 0; static const uint8_t MY9231_CMD_SCATTER_PWM = 0x1 << 0; -MY9231OutputComponent::MY9231OutputComponent(GPIOPin *pin_di, GPIOPin *pin_dcki, - uint16_t num_channels, - uint8_t num_chips, - uint8_t bit_depth, bool update) +MY9231OutputComponent::MY9231OutputComponent(GPIOPin *pin_di, GPIOPin *pin_dcki, uint16_t num_channels, + uint8_t num_chips, uint8_t bit_depth, bool update) : pin_di_(pin_di), pin_dcki_(pin_dcki), num_channels_(num_channels), @@ -66,11 +64,11 @@ void MY9231OutputComponent::setup() { this->bit_depth_ = 16; command |= MY9231_CMD_BIT_WIDTH_16; } - command |= MY9231_CMD_SCATTER_APDM | MY9231_CMD_FREQUENCY_DIVIDE_1 | - MY9231_CMD_REACTION_FAST | MY9231_CMD_ONE_SHOT_DISABLE; + command |= + MY9231_CMD_SCATTER_APDM | MY9231_CMD_FREQUENCY_DIVIDE_1 | MY9231_CMD_REACTION_FAST | MY9231_CMD_ONE_SHOT_DISABLE; ESP_LOGV(TAG, " Command: 0x%02X", command); - this->init_chips(command); + this->init_chips_(command); ESP_LOGV(TAG, " Chips initialized."); this->loop(); } @@ -89,15 +87,16 @@ void MY9231OutputComponent::loop() { } for (auto pwm_amount : this->pwm_amounts_) { - this->write_word(pwm_amount, this->bit_depth_); + this->write_word_(pwm_amount, this->bit_depth_); } // Send 8 DI pulses. After 8 falling edges, the duty data are store. - this->send_di_pulses(8); + this->send_di_pulses_(8); this->update_ = false; } -MY9231OutputComponent::Channel *MY9231OutputComponent::create_channel( - uint8_t channel, PowerSupplyComponent *power_supply, float max_power) { +MY9231OutputComponent::Channel *MY9231OutputComponent::create_channel(uint8_t channel, + PowerSupplyComponent *power_supply, + float max_power) { ESP_LOGV(TAG, "Getting channel %d...", channel); auto *c = new Channel(this, channel); c->set_power_supply(power_supply); @@ -105,11 +104,9 @@ MY9231OutputComponent::Channel *MY9231OutputComponent::create_channel( return c; } -float MY9231OutputComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float MY9231OutputComponent::get_setup_priority() const { return setup_priority::HARDWARE; } -void MY9231OutputComponent::set_channel_value(uint8_t channel, uint16_t value) { +void MY9231OutputComponent::set_channel_value_(uint8_t channel, uint16_t value) { ESP_LOGV(TAG, "set channels %u to %u", channel, value); uint8_t index = this->num_channels_ - channel - 1; if (this->pwm_amounts_[index] != value) { @@ -118,57 +115,43 @@ void MY9231OutputComponent::set_channel_value(uint8_t channel, uint16_t value) { this->pwm_amounts_[index] = value; } -void MY9231OutputComponent::set_num_channels(uint16_t num_channels) { - this->num_channels_ = num_channels; -} +void MY9231OutputComponent::set_num_channels(uint16_t num_channels) { this->num_channels_ = num_channels; } -uint16_t MY9231OutputComponent::get_num_channels() const { - return this->num_channels_; -} +uint16_t MY9231OutputComponent::get_num_channels() const { return this->num_channels_; } -void MY9231OutputComponent::set_num_chips(uint8_t num_chips) { - this->num_chips_ = num_chips; -} +void MY9231OutputComponent::set_num_chips(uint8_t num_chips) { this->num_chips_ = num_chips; } -uint8_t MY9231OutputComponent::get_num_chips() const { - return this->num_chips_; -} +uint8_t MY9231OutputComponent::get_num_chips() const { return this->num_chips_; } -void MY9231OutputComponent::set_bit_depth(uint8_t bit_depth) { - this->bit_depth_ = bit_depth; -} +void MY9231OutputComponent::set_bit_depth(uint8_t bit_depth) { this->bit_depth_ = bit_depth; } -uint8_t MY9231OutputComponent::get_bit_depth() const { - return this->bit_depth_; -} +uint8_t MY9231OutputComponent::get_bit_depth() const { return this->bit_depth_; } void MY9231OutputComponent::set_update(bool update) { this->update_ = update; } -uint16_t MY9231OutputComponent::get_max_amount() const { - return (uint32_t(1) << this->bit_depth_) - 1; -} +uint16_t MY9231OutputComponent::get_max_amount() const { return (uint32_t(1) << this->bit_depth_) - 1; } -void MY9231OutputComponent::init_chips(uint8_t command) { +void MY9231OutputComponent::init_chips_(uint8_t command) { // Send 12 DI pulse. After 6 falling edges, the duty data are stored // and after 12 rising edges the command mode is activated. - this->send_di_pulses(12); + this->send_di_pulses_(12); delayMicroseconds(12); for (uint8_t i = 0; i < this->num_chips_; i++) { - this->write_word(command, 8); + this->write_word_(command, 8); } // Send 16 DI pulse. After 14 falling edges, the command data are // stored and after 16 falling edges the duty mode is activated. - this->send_di_pulses(16); + this->send_di_pulses_(16); } -void MY9231OutputComponent::write_word(uint16_t value, uint8_t bits) { +void MY9231OutputComponent::write_word_(uint16_t value, uint8_t bits) { for (uint8_t i = bits; i > 0; i--) { this->pin_di_->digital_write(value & (1 << (i - 1))); this->pin_dcki_->digital_write(!this->pin_dcki_->digital_read()); } } -void MY9231OutputComponent::send_di_pulses(uint8_t count) { +void MY9231OutputComponent::send_di_pulses_(uint8_t count) { delayMicroseconds(12); for (uint8_t i = 0; i < count; i++) { this->pin_di_->digital_write(true); @@ -176,13 +159,12 @@ void MY9231OutputComponent::send_di_pulses(uint8_t count) { } } -MY9231OutputComponent::Channel::Channel(MY9231OutputComponent *parent, - uint8_t channel) +MY9231OutputComponent::Channel::Channel(MY9231OutputComponent *parent, uint8_t channel) : FloatOutput(), parent_(parent), channel_(channel) {} void MY9231OutputComponent::Channel::write_state(float state) { auto amount = uint16_t(state * this->parent_->get_max_amount()); - this->parent_->set_channel_value(this->channel_, amount); + this->parent_->set_channel_value_(this->channel_, amount); } } // namespace output diff --git a/src/esphome/output/my9231_output_component.h b/src/esphome/output/my9231_output_component.h index 65e8d07b..2481d3c9 100644 --- a/src/esphome/output/my9231_output_component.h +++ b/src/esphome/output/my9231_output_component.h @@ -25,8 +25,7 @@ class MY9231OutputComponent : public Component { * @param update Update/reset duty data at boot (driver will keep * configuration after powercycle) */ - MY9231OutputComponent(GPIOPin *pin_di, GPIOPin *pin_dcki, - uint16_t num_channels = 6, uint8_t num_chips = 2, + MY9231OutputComponent(GPIOPin *pin_di, GPIOPin *pin_dcki, uint16_t num_channels = 6, uint8_t num_chips = 2, uint8_t bit_depth = 16, bool update = true); /** Get a MY9231 output channel. @@ -38,9 +37,7 @@ class MY9231OutputComponent : public Component { * be multiplied by this. * @return The new channel output component. */ - Channel *create_channel(uint8_t channel, - PowerSupplyComponent *power_supply = nullptr, - float max_power = 1.0f); + Channel *create_channel(uint8_t channel, PowerSupplyComponent *power_supply = nullptr, float max_power = 1.0f); /// Manually set the total number of channels. Defaults to 6. void set_num_channels(uint16_t num_channels); @@ -70,18 +67,18 @@ class MY9231OutputComponent : public Component { public: Channel(MY9231OutputComponent *parent, uint8_t channel); + protected: void write_state(float state) override; - protected: MY9231OutputComponent *parent_; uint8_t channel_; }; protected: - void set_channel_value(uint8_t channel, uint16_t value); - void init_chips(uint8_t cmd); - void write_word(uint16_t value, uint8_t bits); - void send_di_pulses(uint8_t count); + void set_channel_value_(uint8_t channel, uint16_t value); + void init_chips_(uint8_t command); + void write_word_(uint16_t value, uint8_t bits); + void send_di_pulses_(uint8_t count); GPIOPin *pin_di_; GPIOPin *pin_dcki_; diff --git a/src/esphome/output/pca9685_output_component.cpp b/src/esphome/output/pca9685_output_component.cpp index d74fbf87..9870256c 100644 --- a/src/esphome/output/pca9685_output_component.cpp +++ b/src/esphome/output/pca9685_output_component.cpp @@ -36,10 +36,13 @@ static const uint16_t PCA9685_PWM_FULL = 4096; static const uint8_t PCA9685_ADDRESS = 0x40; -PCA9685OutputComponent::PCA9685OutputComponent(I2CComponent *parent, float frequency, - uint8_t mode) - : I2CDevice(parent, PCA9685_ADDRESS), frequency_(frequency), - mode_(mode), min_channel_(0xFF), max_channel_(0x00), update_(true) { +PCA9685OutputComponent::PCA9685OutputComponent(I2CComponent *parent, float frequency, uint8_t mode) + : I2CDevice(parent, PCA9685_ADDRESS), + frequency_(frequency), + mode_(mode), + min_channel_(0xFF), + max_channel_(0x00), + update_(true) { for (uint16_t &pwm_amount : this->pwm_amounts_) pwm_amount = 0; } @@ -62,9 +65,11 @@ void PCA9685OutputComponent::setup() { return; } - int pre_scaler = (25000000 / (4096 * this->frequency_)) - 1; - if (pre_scaler > 255) pre_scaler = 255; - if (pre_scaler < 3) pre_scaler = 3; + int pre_scaler = static_cast((25000000 / (4096 * this->frequency_)) - 1); + if (pre_scaler > 255) + pre_scaler = 255; + if (pre_scaler < 3) + pre_scaler = 3; ESP_LOGV(TAG, " -> Prescaler: %d", pre_scaler); @@ -108,7 +113,7 @@ void PCA9685OutputComponent::loop() { const uint16_t num_channels = this->max_channel_ - this->min_channel_ + 1; for (uint8_t channel = this->min_channel_; channel <= this->max_channel_; channel++) { - uint16_t phase_begin = uint16_t(channel - this->min_channel_) / num_channels * 4096 ; + uint16_t phase_begin = uint16_t(channel - this->min_channel_) / num_channels * 4096; uint16_t phase_end; uint16_t amount = this->pwm_amounts_[channel]; if (amount == 0) { @@ -122,7 +127,8 @@ void PCA9685OutputComponent::loop() { phase_end -= 4096; } - ESP_LOGVV(TAG, "Channel %02u: amount=%04u phase_begin=%04u phase_end=%04u", channel, amount, phase_begin, phase_end); + ESP_LOGVV(TAG, "Channel %02u: amount=%04u phase_begin=%04u phase_end=%04u", channel, amount, phase_begin, + phase_end); uint8_t data[4]; data[0] = phase_begin & 0xFF; @@ -141,11 +147,9 @@ void PCA9685OutputComponent::loop() { this->update_ = false; } -float PCA9685OutputComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float PCA9685OutputComponent::get_setup_priority() const { return setup_priority::HARDWARE; } -void PCA9685OutputComponent::set_channel_value(uint8_t channel, uint16_t value) { +void PCA9685OutputComponent::set_channel_value_(uint8_t channel, uint16_t value) { if (this->pwm_amounts_[channel] != value) this->update_ = true; this->pwm_amounts_[channel] = value; @@ -162,18 +166,10 @@ PCA9685OutputComponent::Channel *PCA9685OutputComponent::create_channel(uint8_t return c; } -float PCA9685OutputComponent::get_frequency() const { - return this->frequency_; -} -void PCA9685OutputComponent::set_frequency(float frequency) { - this->frequency_ = frequency; -} -uint8_t PCA9685OutputComponent::get_mode() const { - return this->mode_; -} -void PCA9685OutputComponent::set_mode(uint8_t mode) { - this->mode_ = mode; -} +float PCA9685OutputComponent::get_frequency() const { return this->frequency_; } +void PCA9685OutputComponent::set_frequency(float frequency) { this->frequency_ = frequency; } +uint8_t PCA9685OutputComponent::get_mode() const { return this->mode_; } +void PCA9685OutputComponent::set_mode(uint8_t mode) { this->mode_ = mode; } PCA9685OutputComponent::Channel::Channel(PCA9685OutputComponent *parent, uint8_t channel) : FloatOutput(), parent_(parent), channel_(channel) {} @@ -182,11 +178,11 @@ void PCA9685OutputComponent::Channel::write_state(float state) { const uint16_t max_duty = 4096; const float duty_rounded = roundf(state * max_duty); auto duty = static_cast(duty_rounded); - this->parent_->set_channel_value(this->channel_, duty); + this->parent_->set_channel_value_(this->channel_, duty); } -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_PCA9685_OUTPUT +#endif // USE_PCA9685_OUTPUT diff --git a/src/esphome/output/pca9685_output_component.h b/src/esphome/output/pca9685_output_component.h index 9e7c697e..26fe53f6 100644 --- a/src/esphome/output/pca9685_output_component.h +++ b/src/esphome/output/pca9685_output_component.h @@ -12,11 +12,15 @@ ESPHOME_NAMESPACE_BEGIN namespace output { -extern const uint8_t PCA9685_MODE_INVERTED; // Inverts polarity of channel output signal -extern const uint8_t PCA9685_MODE_OUTPUT_ONACK; // Channel update happens upon ACK (post-set) rather than on STOP (endTransmission) -extern const uint8_t PCA9685_MODE_OUTPUT_TOTEM_POLE; // Use a totem-pole (push-pull) style output rather than an open-drain structure. -extern const uint8_t PCA9685_MODE_OUTNE_HIGHZ; // For active low output enable, sets channel output to high-impedance state -extern const uint8_t PCA9685_MODE_OUTNE_LOW; // Similarly, sets channel output to high if in totem-pole mode, otherwise high-impedance state +extern const uint8_t PCA9685_MODE_INVERTED; // Inverts polarity of channel output signal +extern const uint8_t + PCA9685_MODE_OUTPUT_ONACK; // Channel update happens upon ACK (post-set) rather than on STOP (endTransmission) +extern const uint8_t + PCA9685_MODE_OUTPUT_TOTEM_POLE; // Use a totem-pole (push-pull) style output rather than an open-drain structure. +extern const uint8_t + PCA9685_MODE_OUTNE_HIGHZ; // For active low output enable, sets channel output to high-impedance state +extern const uint8_t PCA9685_MODE_OUTNE_LOW; // Similarly, sets channel output to high if in totem-pole mode, otherwise + // high-impedance state /// PCA9685 float output component. class PCA9685OutputComponent : public Component, public I2CDevice { @@ -62,15 +66,15 @@ class PCA9685OutputComponent : public Component, public I2CDevice { public: Channel(PCA9685OutputComponent *parent, uint8_t channel); + protected: void write_state(float state) override; - protected: PCA9685OutputComponent *parent_; uint8_t channel_; }; protected: - void set_channel_value(uint8_t channel, uint16_t value); + void set_channel_value_(uint8_t channel, uint16_t value); float frequency_; uint8_t mode_; @@ -81,10 +85,10 @@ class PCA9685OutputComponent : public Component, public I2CDevice { bool update_; }; -} // namespace output +} // namespace output ESPHOME_NAMESPACE_END -#endif //USE_PCA9685_OUTPUT +#endif // USE_PCA9685_OUTPUT -#endif //ESPHOME_OUTPUT_PCA9685_OUTPUT_COMPONENT_H +#endif // ESPHOME_OUTPUT_PCA9685_OUTPUT_COMPONENT_H diff --git a/src/esphome/power_supply_component.cpp b/src/esphome/power_supply_component.cpp index 71156443..e921eba6 100644 --- a/src/esphome/power_supply_component.cpp +++ b/src/esphome/power_supply_component.cpp @@ -31,28 +31,16 @@ void PowerSupplyComponent::dump_config() { ESP_LOGCONFIG(TAG, " Keep on time: %.1f s", this->keep_on_time_ / 1000.0f); } -float PowerSupplyComponent::get_setup_priority() const { - return setup_priority::PRE_HARDWARE; -} +float PowerSupplyComponent::get_setup_priority() const { return setup_priority::PRE_HARDWARE; } PowerSupplyComponent::PowerSupplyComponent(GPIOPin *pin, uint32_t enable_time, uint32_t keep_on_time) : pin_(pin), enable_time_(enable_time), keep_on_time_(keep_on_time) {} -bool PowerSupplyComponent::is_enabled() const { - return this->enabled_; -} -uint32_t PowerSupplyComponent::get_enable_time() const { - return this->enable_time_; -} -void PowerSupplyComponent::set_enable_time(uint32_t enable_time) { - this->enable_time_ = enable_time; -} -uint32_t PowerSupplyComponent::get_keep_on_time() const { - return this->keep_on_time_; -} -void PowerSupplyComponent::set_keep_on_time(uint32_t keep_on_time) { - this->keep_on_time_ = keep_on_time; -} +bool PowerSupplyComponent::is_enabled() const { return this->enabled_; } +uint32_t PowerSupplyComponent::get_enable_time() const { return this->enable_time_; } +void PowerSupplyComponent::set_enable_time(uint32_t enable_time) { this->enable_time_ = enable_time; } +uint32_t PowerSupplyComponent::get_keep_on_time() const { return this->keep_on_time_; } +void PowerSupplyComponent::set_keep_on_time(uint32_t keep_on_time) { this->keep_on_time_ = keep_on_time; } void PowerSupplyComponent::request_high_power() { this->cancel_timeout("power-supply-off"); @@ -67,7 +55,6 @@ void PowerSupplyComponent::request_high_power() { this->enabled_ = true; // increase active requests this->active_requests_++; - } void PowerSupplyComponent::unrequest_high_power() { @@ -79,7 +66,7 @@ void PowerSupplyComponent::unrequest_high_power() { if (this->active_requests_ == 0) { // set timeout for power supply off - this->set_timeout("power-supply-off", this->keep_on_time_, [this](){ + this->set_timeout("power-supply-off", this->keep_on_time_, [this]() { ESP_LOGD(TAG, "Disabling power supply."); this->pin_->digital_write(false); this->enabled_ = false; @@ -89,4 +76,4 @@ void PowerSupplyComponent::unrequest_high_power() { ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT +#endif // USE_OUTPUT diff --git a/src/esphome/power_supply_component.h b/src/esphome/power_supply_component.h index 9dd2af6e..437bc3a8 100644 --- a/src/esphome/power_supply_component.h +++ b/src/esphome/power_supply_component.h @@ -70,7 +70,6 @@ class PowerSupplyComponent : public Component { uint32_t get_enable_time() const; protected: - GPIOPin *pin_; bool enabled_{false}; uint32_t enable_time_; @@ -80,6 +79,6 @@ class PowerSupplyComponent : public Component { ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT +#endif // USE_OUTPUT -#endif //ESPHOME_POWER_SUPPLY_COMPONENT_H +#endif // ESPHOME_POWER_SUPPLY_COMPONENT_H diff --git a/src/esphome/remote/jvc.cpp b/src/esphome/remote/jvc.cpp index e63677f4..79421ece 100644 --- a/src/esphome/remote/jvc.cpp +++ b/src/esphome/remote/jvc.cpp @@ -19,21 +19,18 @@ static const uint32_t BIT_ZERO_LOW_US = 525; static const uint32_t BIT_HIGH_US = 525; #ifdef USE_REMOTE_TRANSMITTER -JVCTransmitter::JVCTransmitter(const std::string &name, uint32_t data) - : RemoteTransmitter(name), data_(data) {} +JVCTransmitter::JVCTransmitter(const std::string &name, uint32_t data) : RemoteTransmitter(name), data_(data) {} -void JVCTransmitter::to_data(RemoteTransmitData *data) { - encode_jvc(data, this->data_); -} +void JVCTransmitter::to_data(RemoteTransmitData *data) { encode_jvc(data, this->data_); } -void encode_jvc(RemoteTransmitData *data, uint32_t data_) { +void encode_jvc(RemoteTransmitData *data, uint32_t jvc_data) { data->set_carrier_frequency(38000); data->reserve(2 + NBITS * 2u); data->item(HEADER_HIGH_US, HEADER_LOW_US); for (uint32_t mask = 1UL << (NBITS - 1); mask != 0; mask >>= 1) { - if (data_ & mask) + if (jvc_data & mask) data->item(BIT_HIGH_US, BIT_ONE_LOW_US); else data->item(BIT_HIGH_US, BIT_ZERO_LOW_US); @@ -51,7 +48,6 @@ JVCDecodeData decode_jvc(RemoteReceiveData *data) { if (!data->expect_item(HEADER_HIGH_US, HEADER_LOW_US)) return out; - for (uint8_t i = 0; i < NBITS; i++) { out.data <<= 1UL; if (data->expect_item(BIT_HIGH_US, BIT_ONE_LOW_US)) { @@ -67,12 +63,11 @@ JVCDecodeData decode_jvc(RemoteReceiveData *data) { return out; } -JVCReceiver::JVCReceiver(const std::string &name, uint32_t data) - : RemoteReceiver(name), data_(data) {} +JVCReceiver::JVCReceiver(const std::string &name, uint32_t data) : RemoteReceiver(name), data_(data) {} bool JVCReceiver::matches(RemoteReceiveData *data) { auto decode = decode_jvc(data); - if(!decode.valid) + if (!decode.valid) return false; return this->data_ == decode.data; @@ -88,8 +83,8 @@ bool JVCDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/jvc.h b/src/esphome/remote/jvc.h index 7a10c4bf..3368373a 100644 --- a/src/esphome/remote/jvc.h +++ b/src/esphome/remote/jvc.h @@ -23,7 +23,7 @@ class JVCTransmitter : public RemoteTransmitter { uint32_t data_; }; -void encode_jvc(RemoteTransmitData *data, uint32_t data_); +void encode_jvc(RemoteTransmitData *data, uint32_t jvc_data); #endif #ifdef USE_REMOTE_RECEIVER @@ -36,7 +36,6 @@ class JVCReceiver : public RemoteReceiver { protected: bool matches(RemoteReceiveData *data) override; - protected: uint32_t data_; }; @@ -46,10 +45,10 @@ class JVCDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_JVC_H +#endif // ESPHOME_REMOTE_JVC_H diff --git a/src/esphome/remote/lg.cpp b/src/esphome/remote/lg.cpp index 582150e5..3e3d3b85 100644 --- a/src/esphome/remote/lg.cpp +++ b/src/esphome/remote/lg.cpp @@ -39,14 +39,14 @@ void LGTransmitter::to_data(RemoteTransmitData *data) { data->mark(BIT_HIGH_US); } -void encode_lg(RemoteTransmitData *data, uint32_t data_, uint8_t nbits) { +void encode_lg(RemoteTransmitData *data, uint32_t lg_data, uint8_t nbits) { data->set_carrier_frequency(38000); data->reserve(2 + nbits * 2u); data->item(HEADER_HIGH_US, HEADER_LOW_US); for (uint32_t mask = 1UL << (nbits - 1); mask != 0; mask >>= 1) { - if (data_ & mask) + if (lg_data & mask) data->item(BIT_HIGH_US, BIT_ONE_LOW_US); else data->item(BIT_HIGH_US, BIT_ZERO_LOW_US); @@ -102,8 +102,8 @@ bool LGDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/lg.h b/src/esphome/remote/lg.h index 5761e145..7d139fca 100644 --- a/src/esphome/remote/lg.h +++ b/src/esphome/remote/lg.h @@ -24,7 +24,7 @@ class LGTransmitter : public RemoteTransmitter { uint8_t nbits_; }; -void encode_lg(RemoteTransmitData *data, uint32_t data_, uint8_t nbits); +void encode_lg(RemoteTransmitData *data, uint32_t lg_data, uint8_t nbits); #endif #ifdef USE_REMOTE_RECEIVER @@ -47,10 +47,10 @@ class LGDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_LG_H +#endif // ESPHOME_REMOTE_LG_H diff --git a/src/esphome/remote/nec.cpp b/src/esphome/remote/nec.cpp index 603d16cb..0081e324 100644 --- a/src/esphome/remote/nec.cpp +++ b/src/esphome/remote/nec.cpp @@ -41,15 +41,9 @@ void encode_nec(RemoteTransmitData *data, uint16_t address, uint16_t command) { data->mark(BIT_HIGH_US); } -NECTransmitter::NECTransmitter(const std::string &name, - uint16_t address, - uint16_t command) - : RemoteTransmitter(name), address_(address), command_(command) { - -} -void NECTransmitter::to_data(RemoteTransmitData *data) { - encode_nec(data, this->address_, this->command_); -} +NECTransmitter::NECTransmitter(const std::string &name, uint16_t address, uint16_t command) + : RemoteTransmitter(name), address_(address), command_(command) {} +void NECTransmitter::to_data(RemoteTransmitData *data) { encode_nec(data, this->address_, this->command_); } #endif #ifdef USE_REMOTE_RECEIVER @@ -87,9 +81,7 @@ NECDecodeData decode_nec(RemoteReceiveData *data) { } NECReceiver::NECReceiver(const std::string &name, uint16_t address, uint16_t command) - : RemoteReceiver(name), address_(address), command_(command) { - -} + : RemoteReceiver(name), address_(address), command_(command) {} bool NECReceiver::matches(RemoteReceiveData *data) { auto decode = decode_nec(data); if (!decode.valid) @@ -107,8 +99,8 @@ bool NECDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/nec.h b/src/esphome/remote/nec.h index 094c4325..12a7c740 100644 --- a/src/esphome/remote/nec.h +++ b/src/esphome/remote/nec.h @@ -34,9 +34,9 @@ class NECReceiver : public RemoteReceiver { public: NECReceiver(const std::string &name, uint16_t address, uint16_t command); + protected: bool matches(RemoteReceiveData *data) override; - protected: uint16_t address_; uint16_t command_; }; @@ -47,10 +47,10 @@ class NECDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_NEC_H +#endif // ESPHOME_REMOTE_NEC_H diff --git a/src/esphome/remote/panasonic.cpp b/src/esphome/remote/panasonic.cpp index 4b9583a0..4f23831d 100644 --- a/src/esphome/remote/panasonic.cpp +++ b/src/esphome/remote/panasonic.cpp @@ -20,16 +20,10 @@ static const uint32_t BIT_ZERO_LOW_US = 400; static const uint32_t BIT_ONE_LOW_US = 1244; #ifdef USE_REMOTE_TRANSMITTER -void PanasonicTransmitter::to_data(RemoteTransmitData *data) { - encode_panasonic(data, this->address_, this->command_); -} - -PanasonicTransmitter::PanasonicTransmitter(const std::string &name, - uint16_t address, - uint32_t command) - : RemoteTransmitter(name), address_(address), command_(command) { +void PanasonicTransmitter::to_data(RemoteTransmitData *data) { encode_panasonic(data, this->address_, this->command_); } -} +PanasonicTransmitter::PanasonicTransmitter(const std::string &name, uint16_t address, uint32_t command) + : RemoteTransmitter(name), address_(address), command_(command) {} void encode_panasonic(RemoteTransmitData *data, uint16_t address, uint32_t command) { data->reserve(100); @@ -72,7 +66,6 @@ PanasonicDecodeData decode_panasonic(RemoteReceiveData *data) { } else { return out; } - } for (mask = 1UL << 31; mask != 0; mask >>= 1) { @@ -95,9 +88,7 @@ bool PanasonicReceiver::matches(RemoteReceiveData *data) { return decode.valid && this->address_ == decode.address && this->command_ == decode.command; } PanasonicReceiver::PanasonicReceiver(const std::string &name, uint16_t address, uint32_t command) - : RemoteReceiver(name), address_(address), command_(command) { - -} + : RemoteReceiver(name), address_(address), command_(command) {} bool PanasonicDumper::dump(RemoteReceiveData *data) { auto decode = decode_panasonic(data); @@ -109,8 +100,8 @@ bool PanasonicDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/panasonic.h b/src/esphome/remote/panasonic.h index bbeeef1e..dc73d10a 100644 --- a/src/esphome/remote/panasonic.h +++ b/src/esphome/remote/panasonic.h @@ -34,9 +34,9 @@ class PanasonicReceiver : public RemoteReceiver { public: PanasonicReceiver(const std::string &name, uint16_t address, uint32_t command); + protected: bool matches(RemoteReceiveData *data) override; - protected: uint16_t address_; uint32_t command_; }; @@ -47,10 +47,10 @@ class PanasonicDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_PANASONIC_H +#endif // ESPHOME_REMOTE_PANASONIC_H diff --git a/src/esphome/remote/raw.cpp b/src/esphome/remote/raw.cpp index 69356c0f..a71137d8 100644 --- a/src/esphome/remote/raw.cpp +++ b/src/esphome/remote/raw.cpp @@ -27,12 +27,8 @@ void RawTransmitter::to_data(RemoteTransmitData *data) { } data->set_carrier_frequency(this->carrier_frequency_); } -RawTransmitter::RawTransmitter(const std::string &name, - const int32_t *data, size_t len, - uint32_t carrier_frequency) - : RemoteTransmitter(name), data_(data), len_(len), carrier_frequency_(carrier_frequency) { - -} +RawTransmitter::RawTransmitter(const std::string &name, const int32_t *data, size_t len, uint32_t carrier_frequency) + : RemoteTransmitter(name), data_(data), len_(len), carrier_frequency_(carrier_frequency) {} #endif #ifdef USE_REMOTE_RECEIVER @@ -73,9 +69,7 @@ bool RawDumper::dump(RemoteReceiveData *data) { return true; } -bool RawDumper::secondary_() { - return true; -} +bool RawDumper::is_secondary() { return true; } bool RawReceiver::matches(RemoteReceiveData *data) { for (size_t i = 0; i < this->len_; i++) { auto val = this->data_[i]; @@ -91,13 +85,11 @@ bool RawReceiver::matches(RemoteReceiveData *data) { } RawReceiver::RawReceiver(const std::string &name, const int32_t *data, size_t len) - : RemoteReceiver(name), data_(data), len_(len) { - -} + : RemoteReceiver(name), data_(data), len_(len) {} #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/raw.h b/src/esphome/remote/raw.h index 416ee8d2..329bedf8 100644 --- a/src/esphome/remote/raw.h +++ b/src/esphome/remote/raw.h @@ -15,8 +15,7 @@ namespace remote { #ifdef USE_REMOTE_TRANSMITTER class RawTransmitter : public RemoteTransmitter { public: - RawTransmitter(const std::string &name, const int32_t *data, size_t len, - uint32_t carrier_frequency = 0); + RawTransmitter(const std::string &name, const int32_t *data, size_t len, uint32_t carrier_frequency = 0); void to_data(RemoteTransmitData *data) override; @@ -32,9 +31,9 @@ class RawReceiver : public RemoteReceiver { public: RawReceiver(const std::string &name, const int32_t *data, size_t len); + protected: bool matches(RemoteReceiveData *data) override; - protected: const int32_t *data_; size_t len_; }; @@ -43,14 +42,14 @@ class RawDumper : public RemoteReceiveDumper { public: bool dump(RemoteReceiveData *data) override; - bool secondary_() override; + bool is_secondary() override; }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_RAW_H +#endif // ESPHOME_REMOTE_RAW_H diff --git a/src/esphome/remote/rc5.cpp b/src/esphome/remote/rc5.cpp index 6c6da8a2..acb6da27 100644 --- a/src/esphome/remote/rc5.cpp +++ b/src/esphome/remote/rc5.cpp @@ -28,14 +28,14 @@ void RC5Transmitter::to_data(RemoteTransmitData *data) { void encode_rc5(RemoteTransmitData *data, uint8_t address, uint8_t command, bool toggle) { data->set_carrier_frequency(36000); - uint64_t data_ = 0; - data_ |= 0b11 << 12; - data_ |= toggle << 11; - data_ |= address << 6; - data_ |= command; + uint64_t out_data = 0; + out_data |= 0b11 << 12; + out_data |= toggle << 11; + out_data |= address << 6; + out_data |= command; for (uint64_t mask = 1UL << (NBITS - 1); mask != 0; mask >>= 1) { - if (data_ & mask) { + if (out_data & mask) { data->space(BIT_TIME_US); data->mark(BIT_TIME_US); } else { @@ -53,26 +53,24 @@ RC5DecodeData decode_rc5(RemoteReceiveData *data) { out.address = 0; out.command = 0; data->expect_space(BIT_TIME_US); - if (!data->expect_mark(BIT_TIME_US) || - !data->expect_space(BIT_TIME_US) || - !data->expect_mark(BIT_TIME_US)) { + if (!data->expect_mark(BIT_TIME_US) || !data->expect_space(BIT_TIME_US) || !data->expect_mark(BIT_TIME_US)) { return out; } - uint64_t data_ = 0; + uint64_t out_data = 0; for (int bit = NBITS - 3; bit >= 0; bit--) { if (data->expect_space(BIT_TIME_US) && data->expect_mark(BIT_TIME_US)) { - data_ |= 1 << bit; + out_data |= 1 << bit; } else if (data->expect_mark(BIT_TIME_US) && data->expect_space(BIT_TIME_US)) { - data_ |= 0 << bit; + out_data |= 0 << bit; } else { out.valid = false; return out; } } - out.command = data_ & 0x3F; - out.address = (data_ >> 6) & 0x1F; + out.command = out_data & 0x3F; + out.address = (out_data >> 6) & 0x1F; out.valid = true; return out; } @@ -93,13 +91,13 @@ bool RC5Dumper::dump(RemoteReceiveData *data) { if (!res.valid) return false; - ESP_LOGD(TAG, "Received RC5: address=0x02X, command=0x%02X", res.address, res.command); + ESP_LOGD(TAG, "Received RC5: address=0x%02X, command=0x%02X", res.address, res.command); return true; } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/rc5.h b/src/esphome/remote/rc5.h index 97298be2..af45f17f 100644 --- a/src/esphome/remote/rc5.h +++ b/src/esphome/remote/rc5.h @@ -25,7 +25,7 @@ class RC5Transmitter : public RemoteTransmitter { bool toggle_{false}; }; -void encode_rc5(RemoteTransmitData *data, uint8_t data_, uint8_t command, bool toggle); +void encode_rc5(RemoteTransmitData *data, uint8_t address, uint8_t command, bool toggle); #endif #ifdef USE_REMOTE_RECEIVER @@ -48,10 +48,10 @@ class RC5Dumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_RC5_H +#endif // ESPHOME_REMOTE_RC5_H diff --git a/src/esphome/remote/rc_switch.cpp b/src/esphome/remote/rc_switch.cpp index 777ea815..ba4fce70 100644 --- a/src/esphome/remote/rc_switch.cpp +++ b/src/esphome/remote/rc_switch.cpp @@ -14,11 +14,9 @@ static const char *TAG = "remote.rc_switch"; #endif #ifdef USE_REMOTE_TRANSMITTER -RCSwitchRawTransmitter::RCSwitchRawTransmitter(const std::string &name, - RCSwitchProtocol aProtocol, - uint32_t code, +RCSwitchRawTransmitter::RCSwitchRawTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint32_t code, uint8_t nbits) - : RemoteTransmitter(name), protocol_(aProtocol), code_(code), nbits_(nbits) {} + : RemoteTransmitter(name), protocol_(a_protocol), code_(code), nbits_(nbits) {} void RCSwitchRawTransmitter::to_data(RemoteTransmitData *data) { this->protocol_.transmit(data, this->code_, this->nbits_); } @@ -27,49 +25,43 @@ void encode_rc_switch_raw(RemoteTransmitData *data, uint32_t code, uint8_t nbits protocol.transmit(data, code, nbits); } void encode_rc_switch_raw(RemoteTransmitData *data, const char *code, RCSwitchProtocol protocol) { - uint32_t code_ = 0; + uint32_t the_code = 0; uint8_t nbits = 0; for (; code[nbits] != '\0'; nbits++) { - code_ <<= 1UL; - code_ |= (code[nbits] != '0'); + the_code <<= 1UL; + the_code |= (code[nbits] != '0'); } - protocol.transmit(data, code_, nbits); + protocol.transmit(data, the_code, nbits); } void encode_rc_switch_raw_tristate(RemoteTransmitData *data, const char *code, RCSwitchProtocol protocol) { - uint32_t code_ = 0; + uint32_t the_code = 0; uint8_t nbits = 0; for (; code[nbits] != '\0'; nbits++) { - code_ <<= 2UL; + the_code <<= 2UL; switch (code[nbits]) { case 'F': - code_ |= 0b01UL; + the_code |= 0b01UL; break; case '1': - code_ |= 0b11UL; + the_code |= 0b11UL; break; case '0': default: - code_ |= 0b00UL; + the_code |= 0b00UL; break; } } - protocol.transmit(data, code_, nbits += 2); + protocol.transmit(data, the_code, nbits * 2); } -RCSwitchTypeATransmitter::RCSwitchTypeATransmitter(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t switch_group, - uint8_t switch_device, - bool state) - : RCSwitchRawTransmitter(name, aProtocol, 0, 0) { +RCSwitchTypeATransmitter::RCSwitchTypeATransmitter(const std::string &name, RCSwitchProtocol a_protocol, + uint8_t switch_group, uint8_t switch_device, bool state) + : RCSwitchRawTransmitter(name, a_protocol, 0, 0) { RCSwitchProtocol::type_a_code(switch_group, switch_device, state, &this->code_, &this->nbits_); } -void encode_rc_switch_type_a(RemoteTransmitData *data, - uint8_t switch_group, - uint8_t switch_device, - bool state, +void encode_rc_switch_type_a(RemoteTransmitData *data, uint8_t switch_group, uint8_t switch_device, bool state, RCSwitchProtocol protocol) { uint32_t code; uint8_t nbits; @@ -86,98 +78,66 @@ uint32_t decode_string(const char *str, uint8_t len) { return ret; } -void encode_rc_switch_type_a(RemoteTransmitData *data, - const char *switch_group, - const char *switch_device, - bool state, +void encode_rc_switch_type_a(RemoteTransmitData *data, const char *switch_group, const char *switch_device, bool state, RCSwitchProtocol protocol) { - uint8_t switch_group_ = decode_string(switch_group, 5); - uint8_t switch_device_ = decode_string(switch_device, 5); + uint8_t u_switch_group = decode_string(switch_group, 5); + uint8_t u_switch_device = decode_string(switch_device, 5); - encode_rc_switch_type_a(data, switch_group_, switch_device_, state, protocol); + encode_rc_switch_type_a(data, u_switch_group, u_switch_device, state, protocol); } -RCSwitchTypeBTransmitter::RCSwitchTypeBTransmitter(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t address_code, - uint8_t channel_code, - bool state) - : RCSwitchRawTransmitter(name, aProtocol, 0, 0) { +RCSwitchTypeBTransmitter::RCSwitchTypeBTransmitter(const std::string &name, RCSwitchProtocol a_protocol, + uint8_t address_code, uint8_t channel_code, bool state) + : RCSwitchRawTransmitter(name, a_protocol, 0, 0) { RCSwitchProtocol::type_b_code(address_code, channel_code, state, &this->code_, &this->nbits_); } -void encode_rc_switch_type_b(RemoteTransmitData *data, - uint8_t address, - uint8_t channel, - bool state, +void encode_rc_switch_type_b(RemoteTransmitData *data, uint8_t address, uint8_t channel, bool state, RCSwitchProtocol protocol) { uint32_t code; uint8_t nbits; RCSwitchProtocol::type_b_code(address, channel, state, &code, &nbits); protocol.transmit(data, code, nbits); } -RCSwitchTypeCTransmitter::RCSwitchTypeCTransmitter(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t family, - uint8_t group, - uint8_t device, - bool state) - : RCSwitchRawTransmitter(name, aProtocol, 0, 0) { +RCSwitchTypeCTransmitter::RCSwitchTypeCTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint8_t family, + uint8_t group, uint8_t device, bool state) + : RCSwitchRawTransmitter(name, a_protocol, 0, 0) { RCSwitchProtocol::type_c_code(family, group, device, state, &this->code_, &this->nbits_); } -void encode_rc_switch_type_c(RemoteTransmitData *data, - uint8_t family, - uint8_t group, - uint8_t device, - bool state, +void encode_rc_switch_type_c(RemoteTransmitData *data, uint8_t family, uint8_t group, uint8_t device, bool state, RCSwitchProtocol protocol) { uint32_t code; uint8_t nbits; RCSwitchProtocol::type_c_code(family, group, device, state, &code, &nbits); protocol.transmit(data, code, nbits); } -void encode_rc_switch_type_c(RemoteTransmitData *data, - char family, - uint8_t group, - uint8_t device, - bool state, - RCSwitchProtocol protocol) { - uint8_t family_ = static_cast(family - 'a'); - encode_rc_switch_type_c(data, family_, group, device, state, protocol); -} -RCSwitchTypeDTransmitter::RCSwitchTypeDTransmitter(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t group, - uint8_t device, - bool state) - : RCSwitchRawTransmitter(name, aProtocol, 0, 0) { +void encode_rc_switch_type_c(RemoteTransmitData *data, char family, uint8_t group, uint8_t device, bool state, + RCSwitchProtocol protocol) { + uint8_t u_family = static_cast(family - 'a'); + encode_rc_switch_type_c(data, u_family, group, device, state, protocol); +} +RCSwitchTypeDTransmitter::RCSwitchTypeDTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint8_t group, + uint8_t device, bool state) + : RCSwitchRawTransmitter(name, a_protocol, 0, 0) { RCSwitchProtocol::type_d_code(group, device, state, &this->code_, &this->nbits_); } -void encode_rc_switch_type_d(RemoteTransmitData *data, - uint8_t group, - uint8_t device, - bool state, +void encode_rc_switch_type_d(RemoteTransmitData *data, uint8_t group, uint8_t device, bool state, RCSwitchProtocol protocol) { uint32_t code; uint8_t nbits; RCSwitchProtocol::type_d_code(group, device, state, &code, &nbits); protocol.transmit(data, code, nbits); } -void encode_rc_switch_type_d(RemoteTransmitData *data, - char group, - uint8_t device, - bool state, +void encode_rc_switch_type_d(RemoteTransmitData *data, char group, uint8_t device, bool state, RCSwitchProtocol protocol) { - uint8_t group_ = static_cast(group - 'a'); - encode_rc_switch_type_d(data, group_, device, state, protocol); + uint8_t u_group = static_cast(group - 'a'); + encode_rc_switch_type_d(data, u_group, device, state, protocol); } #endif #ifdef USE_REMOTE_RECEIVER -RCSwitchRawReceiver::RCSwitchRawReceiver(const std::string &name, - RCSwitchProtocol aProtocol, - uint32_t code, +RCSwitchRawReceiver::RCSwitchRawReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint32_t code, uint8_t nbits) - : RemoteReceiver(name), protocol_(aProtocol), code_(code), nbits_(nbits) {} + : RemoteReceiver(name), protocol_(a_protocol), code_(code), nbits_(nbits) {} bool RCSwitchRawReceiver::matches(RemoteReceiveData *data) { uint32_t decoded_code; uint8_t decoded_nbits; @@ -186,37 +146,24 @@ bool RCSwitchRawReceiver::matches(RemoteReceiveData *data) { return decoded_nbits == this->nbits_ && decoded_code == this->code_; } -RCSwitchTypeAReceiver::RCSwitchTypeAReceiver(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t switch_group, - uint8_t switch_device, - bool state) - : RCSwitchRawReceiver(name, aProtocol, 0, 0) { +RCSwitchTypeAReceiver::RCSwitchTypeAReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t switch_group, + uint8_t switch_device, bool state) + : RCSwitchRawReceiver(name, a_protocol, 0, 0) { RCSwitchProtocol::type_a_code(switch_group, switch_device, state, &this->code_, &this->nbits_); } -RCSwitchTypeBReceiver::RCSwitchTypeBReceiver(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t address_code, - uint8_t channel_code, - bool state) - : RCSwitchRawReceiver(name, aProtocol, 0, 0) { +RCSwitchTypeBReceiver::RCSwitchTypeBReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t address_code, + uint8_t channel_code, bool state) + : RCSwitchRawReceiver(name, a_protocol, 0, 0) { RCSwitchProtocol::type_b_code(address_code, channel_code, state, &this->code_, &this->nbits_); } -RCSwitchTypeCReceiver::RCSwitchTypeCReceiver(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t family, - uint8_t group, - uint8_t device, - bool state) - : RCSwitchRawReceiver(name, aProtocol, 0, 0) { +RCSwitchTypeCReceiver::RCSwitchTypeCReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t family, + uint8_t group, uint8_t device, bool state) + : RCSwitchRawReceiver(name, a_protocol, 0, 0) { RCSwitchProtocol::type_c_code(family, group, device, state, &this->code_, &this->nbits_); } -RCSwitchTypeDReceiver::RCSwitchTypeDReceiver(const std::string &name, - RCSwitchProtocol aProtocol, - uint8_t group, - uint8_t device, - bool state) - : RCSwitchRawReceiver(name, aProtocol, 0, 0) { +RCSwitchTypeDReceiver::RCSwitchTypeDReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t group, + uint8_t device, bool state) + : RCSwitchRawReceiver(name, a_protocol, 0, 0) { RCSwitchProtocol::type_d_code(group, device, state, &this->code_, &this->nbits_); } @@ -242,8 +189,8 @@ bool RCSwitchDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/rc_switch.h b/src/esphome/remote/rc_switch.h index 7aedd776..25118c33 100644 --- a/src/esphome/remote/rc_switch.h +++ b/src/esphome/remote/rc_switch.h @@ -16,9 +16,10 @@ namespace remote { #ifdef USE_REMOTE_TRANSMITTER class RCSwitchRawTransmitter : public RemoteTransmitter { public: - RCSwitchRawTransmitter(const std::string &name, RCSwitchProtocol aProtocol, uint32_t code, uint8_t nbits); + RCSwitchRawTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint32_t code, uint8_t nbits); void to_data(RemoteTransmitData *data) override; + protected: RCSwitchProtocol protocol_; uint32_t code_; @@ -36,7 +37,8 @@ void encode_rc_switch_raw_tristate(RemoteTransmitData *data, const char *code, class RCSwitchTypeATransmitter : public RCSwitchRawTransmitter { public: - RCSwitchTypeATransmitter(const std::string &name, RCSwitchProtocol aProtocol, uint8_t switch_group, uint8_t switch_device, bool state); + RCSwitchTypeATransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint8_t switch_group, + uint8_t switch_device, bool state); }; void encode_rc_switch_type_a(RemoteTransmitData *data, uint8_t switch_group, uint8_t switch_device, bool state, @@ -47,7 +49,8 @@ void encode_rc_switch_type_a(RemoteTransmitData *data, const char *switch_group, class RCSwitchTypeBTransmitter : public RCSwitchRawTransmitter { public: - RCSwitchTypeBTransmitter(const std::string &name, RCSwitchProtocol aProtocol, uint8_t address_code, uint8_t channel_code, bool state); + RCSwitchTypeBTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint8_t address_code, + uint8_t channel_code, bool state); }; void encode_rc_switch_type_b(RemoteTransmitData *data, uint8_t address, uint8_t channel, bool state, @@ -55,7 +58,8 @@ void encode_rc_switch_type_b(RemoteTransmitData *data, uint8_t address, uint8_t class RCSwitchTypeCTransmitter : public RCSwitchRawTransmitter { public: - RCSwitchTypeCTransmitter(const std::string &name, RCSwitchProtocol aProtocol, uint8_t family, uint8_t group, uint8_t device, bool state); + RCSwitchTypeCTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint8_t family, uint8_t group, + uint8_t device, bool state); }; void encode_rc_switch_type_c(RemoteTransmitData *data, uint8_t family, uint8_t group, uint8_t device, bool state, @@ -66,7 +70,8 @@ void encode_rc_switch_type_c(RemoteTransmitData *data, char family, uint8_t grou class RCSwitchTypeDTransmitter : public RCSwitchRawTransmitter { public: - RCSwitchTypeDTransmitter(const std::string &name, RCSwitchProtocol aProtocol, uint8_t group, uint8_t device, bool state); + RCSwitchTypeDTransmitter(const std::string &name, RCSwitchProtocol a_protocol, uint8_t group, uint8_t device, + bool state); }; void encode_rc_switch_type_d(RemoteTransmitData *data, uint8_t group, uint8_t device, bool state, @@ -80,11 +85,11 @@ void encode_rc_switch_type_d(RemoteTransmitData *data, char group, uint8_t devic #ifdef USE_REMOTE_RECEIVER class RCSwitchRawReceiver : public RemoteReceiver { public: - RCSwitchRawReceiver(const std::string &name, RCSwitchProtocol aProtocol, uint32_t code, uint8_t nbits); + RCSwitchRawReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint32_t code, uint8_t nbits); + protected: bool matches(RemoteReceiveData *data) override; - protected: RCSwitchProtocol protocol_; uint32_t code_; uint8_t nbits_; @@ -92,22 +97,26 @@ class RCSwitchRawReceiver : public RemoteReceiver { class RCSwitchTypeAReceiver : public RCSwitchRawReceiver { public: - RCSwitchTypeAReceiver(const std::string &name, RCSwitchProtocol aProtocol, uint8_t switch_group, uint8_t switch_device, bool state); + RCSwitchTypeAReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t switch_group, + uint8_t switch_device, bool state); }; class RCSwitchTypeBReceiver : public RCSwitchRawReceiver { public: - RCSwitchTypeBReceiver(const std::string &name, RCSwitchProtocol aProtocol, uint8_t address_code, uint8_t channel_code, bool state); + RCSwitchTypeBReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t address_code, + uint8_t channel_code, bool state); }; class RCSwitchTypeCReceiver : public RCSwitchRawReceiver { public: - RCSwitchTypeCReceiver(const std::string &name, RCSwitchProtocol aProtocol, uint8_t family, uint8_t group, uint8_t device, bool state); + RCSwitchTypeCReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t family, uint8_t group, + uint8_t device, bool state); }; class RCSwitchTypeDReceiver : public RCSwitchRawReceiver { public: - RCSwitchTypeDReceiver(const std::string &name, RCSwitchProtocol aProtocol, uint8_t group, uint8_t device, bool state); + RCSwitchTypeDReceiver(const std::string &name, RCSwitchProtocol a_protocol, uint8_t group, uint8_t device, + bool state); }; class RCSwitchDumper : public RemoteReceiveDumper { @@ -116,10 +125,10 @@ class RCSwitchDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_ +#endif // USE_ -#endif //ESPHOME_REMOTE_RC_SWITCH_H +#endif // ESPHOME_REMOTE_RC_SWITCH_H diff --git a/src/esphome/remote/rc_switch_protocol.cpp b/src/esphome/remote/rc_switch_protocol.cpp index bb37314d..165a2152 100644 --- a/src/esphome/remote/rc_switch_protocol.cpp +++ b/src/esphome/remote/rc_switch_protocol.cpp @@ -9,33 +9,24 @@ ESPHOME_NAMESPACE_BEGIN namespace remote { -RCSwitchProtocol rc_switch_protocols[8] = { - RCSwitchProtocol(0, 0, 0, 0, 0, 0, false), - RCSwitchProtocol(350, 10850, 350, 1050, 1050, 350, false), - RCSwitchProtocol(650, 6500, 650, 1300, 1300, 650, false), - RCSwitchProtocol(3000, 7100, 400, 1100, 900, 600, false), - RCSwitchProtocol(380, 2280, 380, 1140, 1140, 380, false), - RCSwitchProtocol(3000, 7000, 500, 1000, 1000, 500, false), - RCSwitchProtocol(10350, 450, 450, 900, 900, 450, true), - RCSwitchProtocol(300, 9300, 150, 900, 900, 150, false) -}; +RCSwitchProtocol rc_switch_protocols[8] = {RCSwitchProtocol(0, 0, 0, 0, 0, 0, false), + RCSwitchProtocol(350, 10850, 350, 1050, 1050, 350, false), + RCSwitchProtocol(650, 6500, 650, 1300, 1300, 650, false), + RCSwitchProtocol(3000, 7100, 400, 1100, 900, 600, false), + RCSwitchProtocol(380, 2280, 380, 1140, 1140, 380, false), + RCSwitchProtocol(3000, 7000, 500, 1000, 1000, 500, false), + RCSwitchProtocol(10350, 450, 450, 900, 900, 450, true), + RCSwitchProtocol(300, 9300, 150, 900, 900, 150, false)}; -RCSwitchProtocol::RCSwitchProtocol(uint32_t sync_high, - uint32_t sync_low, - uint32_t zero_high, - uint32_t zero_low, - uint32_t one_high, - uint32_t one_low, - bool inverted) +RCSwitchProtocol::RCSwitchProtocol(uint32_t sync_high, uint32_t sync_low, uint32_t zero_high, uint32_t zero_low, + uint32_t one_high, uint32_t one_low, bool inverted) : sync_high_(sync_high), sync_low_(sync_low), zero_high_(zero_high), zero_low_(zero_low), one_high_(one_high), one_low_(one_low), - inverted_(inverted) { - -} + inverted_(inverted) {} #ifdef USE_REMOTE_TRANSMITTER void RCSwitchProtocol::one(RemoteTransmitData *data) const { @@ -153,10 +144,7 @@ void RCSwitchProtocol::simple_code_to_tristate(uint16_t code, uint8_t nbits, uin *out_code |= 0b00; } } -void RCSwitchProtocol::type_a_code(uint8_t switch_group, - uint8_t switch_device, - bool state, - uint32_t *out_code, +void RCSwitchProtocol::type_a_code(uint8_t switch_group, uint8_t switch_device, bool state, uint32_t *out_code, uint8_t *out_nbits) { uint16_t code = 0; code |= (switch_group & 0b0001) ? 0 : 0b1000; @@ -173,10 +161,7 @@ void RCSwitchProtocol::type_a_code(uint8_t switch_group, simple_code_to_tristate(code, 10, out_code); *out_nbits = 20; } -void RCSwitchProtocol::type_b_code(uint8_t address_code, - uint8_t channel_code, - bool state, - uint32_t *out_code, +void RCSwitchProtocol::type_b_code(uint8_t address_code, uint8_t channel_code, bool state, uint32_t *out_code, uint8_t *out_nbits) { uint16_t code = 0; code |= (address_code == 1) ? 0 : 0b1000; @@ -194,11 +179,7 @@ void RCSwitchProtocol::type_b_code(uint8_t address_code, simple_code_to_tristate(code, 12, out_code); *out_nbits = 24; } -void RCSwitchProtocol::type_c_code(uint8_t family, - uint8_t group, - uint8_t device, - bool state, - uint32_t *out_code, +void RCSwitchProtocol::type_c_code(uint8_t family, uint8_t group, uint8_t device, bool state, uint32_t *out_code, uint8_t *out_nbits) { uint16_t code = 0; code |= (family & 0b0001) ? 0b1000 : 0; @@ -208,8 +189,8 @@ void RCSwitchProtocol::type_c_code(uint8_t family, code <<= 4; code |= ((device - 1) & 0b01) ? 0b1000 : 0; code |= ((device - 1) & 0b10) ? 0b0100 : 0; - code |= ((group - 1) & 0b01) ? 0b0010 : 0; - code |= ((group - 1) & 0b10) ? 0b0001 : 0; + code |= ((group - 1) & 0b01) ? 0b0010 : 0; + code |= ((group - 1) & 0b10) ? 0b0001 : 0; code <<= 4; code |= 0b0110; code |= state ? 0b1 : 0b0; @@ -233,8 +214,8 @@ void RCSwitchProtocol::type_d_code(uint8_t group, uint8_t device, bool state, ui *out_nbits = 24; } -} // namespace something +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/rc_switch_protocol.h b/src/esphome/remote/rc_switch_protocol.h index 2518b10b..5cbe38e5 100644 --- a/src/esphome/remote/rc_switch_protocol.h +++ b/src/esphome/remote/rc_switch_protocol.h @@ -16,13 +16,8 @@ class RemoteReceiveData; class RCSwitchProtocol { public: - RCSwitchProtocol(uint32_t sync_high, - uint32_t sync_low, - uint32_t zero_high, - uint32_t zero_low, - uint32_t one_high, - uint32_t one_low, - bool inverted); + RCSwitchProtocol(uint32_t sync_high, uint32_t sync_low, uint32_t zero_high, uint32_t zero_low, uint32_t one_high, + uint32_t one_low, bool inverted); #ifdef USE_REMOTE_TRANSMITTER void one(RemoteTransmitData *data) const; @@ -46,11 +41,14 @@ class RCSwitchProtocol { static void simple_code_to_tristate(uint16_t code, uint8_t nbits, uint32_t *out_code); - static void type_a_code(uint8_t switch_group, uint8_t switch_device, bool state, uint32_t *out_code, uint8_t *out_nbits); + static void type_a_code(uint8_t switch_group, uint8_t switch_device, bool state, uint32_t *out_code, + uint8_t *out_nbits); - static void type_b_code(uint8_t address_code, uint8_t channel_code, bool state, uint32_t *out_code, uint8_t *out_nbits); + static void type_b_code(uint8_t address_code, uint8_t channel_code, bool state, uint32_t *out_code, + uint8_t *out_nbits); - static void type_c_code(uint8_t family, uint8_t group, uint8_t device, bool state, uint32_t *out_code, uint8_t *out_nbits); + static void type_c_code(uint8_t family, uint8_t group, uint8_t device, bool state, uint32_t *out_code, + uint8_t *out_nbits); static void type_d_code(uint8_t group, uint8_t device, bool state, uint32_t *out_code, uint8_t *out_nbits); @@ -66,13 +64,13 @@ class RCSwitchProtocol { extern RCSwitchProtocol rc_switch_protocols[8]; -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END #include "esphome/remote/remote_receiver.h" #include "esphome/remote/remote_transmitter.h" -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_RC_SWITCH_PROTOCOL_H +#endif // ESPHOME_RC_SWITCH_PROTOCOL_H diff --git a/src/esphome/remote/remote_protocol.cpp b/src/esphome/remote/remote_protocol.cpp index 9a045d20..e91717b0 100644 --- a/src/esphome/remote/remote_protocol.cpp +++ b/src/esphome/remote/remote_protocol.cpp @@ -11,8 +11,7 @@ ESPHOME_NAMESPACE_BEGIN namespace remote { -RemoteControlComponentBase::RemoteControlComponentBase(GPIOPin *pin) - : pin_(pin) { +RemoteControlComponentBase::RemoteControlComponentBase(GPIOPin *pin) : pin_(pin) { #ifdef ARDUINO_ARCH_ESP32 this->channel_ = select_next_rmt_channel(); #endif @@ -26,16 +25,12 @@ uint32_t RemoteControlComponentBase::to_microseconds(uint32_t ticks) { const uint32_t ticks_per_ten_us = 80000000u / this->clock_divider_ / 100000u; return (ticks * 10) / ticks_per_ten_us; } -void RemoteControlComponentBase::set_channel(rmt_channel_t channel) { - this->channel_ = channel; -} -void RemoteControlComponentBase::set_clock_divider(uint8_t clock_divider) { - this->clock_divider_ = clock_divider; -} +void RemoteControlComponentBase::set_channel(rmt_channel_t channel) { this->channel_ = channel; } +void RemoteControlComponentBase::set_clock_divider(uint8_t clock_divider) { this->clock_divider_ = clock_divider; } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/remote_protocol.h b/src/esphome/remote/remote_protocol.h index 44eb5d80..ba9f5e32 100644 --- a/src/esphome/remote/remote_protocol.h +++ b/src/esphome/remote/remote_protocol.h @@ -10,7 +10,7 @@ #include "esphome/esphal.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -40,10 +40,10 @@ class RemoteControlComponentBase { #endif }; -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_REMOTE_PROTOCOL_H +#endif // ESPHOME_REMOTE_REMOTE_PROTOCOL_H diff --git a/src/esphome/remote/remote_receiver.cpp b/src/esphome/remote/remote_receiver.cpp index c41cf75e..5d16d5be 100644 --- a/src/esphome/remote/remote_receiver.cpp +++ b/src/esphome/remote/remote_receiver.cpp @@ -14,7 +14,7 @@ #include "esphome/remote/sony.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -51,9 +51,7 @@ bool RemoteReceiveData::peek_space(uint32_t length, uint32_t offset) { bool RemoteReceiveData::peek_item(uint32_t mark, uint32_t space, uint32_t offset) { return this->peek_mark(mark, offset) && this->peek_space(space, offset + 1); } -void RemoteReceiveData::advance(uint32_t amount) { - this->index_ += amount; -} +void RemoteReceiveData::advance(uint32_t amount) { this->index_ += amount; } bool RemoteReceiveData::expect_mark(uint32_t length) { if (this->peek_mark(length)) { this->advance(); @@ -75,12 +73,8 @@ bool RemoteReceiveData::expect_item(uint32_t mark, uint32_t space) { } return false; } -void RemoteReceiveData::reset_index() { - this->index_ = 0; -} -int32_t RemoteReceiveData::peek(uint32_t offset) { - return (*this)[this->index_ + offset]; -} +void RemoteReceiveData::reset_index() { this->index_ = 0; } +int32_t RemoteReceiveData::peek(uint32_t offset) { return (*this)[this->index_ + offset]; } bool RemoteReceiveData::peek_space_at_least(uint32_t length, uint32_t offset) { if (int32_t(this->index_ + offset) >= this->size()) return false; @@ -88,43 +82,20 @@ bool RemoteReceiveData::peek_space_at_least(uint32_t length, uint32_t offset) { const int32_t lo = this->lower_bound_(length); return value <= 0 && lo <= -value; } -int32_t RemoteReceiveData::operator[](uint32_t index) const { - return this->pos(index); -} -int32_t RemoteReceiveData::pos(uint32_t index) const { - return (*this->data_)[index]; -} - -int32_t RemoteReceiveData::size() const { - return this->data_->size(); -} -JVCDecodeData RemoteReceiveData::decode_jvc() { - return remote::decode_jvc(this); -} -LGDecodeData RemoteReceiveData::decode_lg() { - return remote::decode_lg(this); -} -NECDecodeData RemoteReceiveData::decode_nec() { - return remote::decode_nec(this); -} -PanasonicDecodeData RemoteReceiveData::decode_panasonic() { - return remote::decode_panasonic(this); -} -SamsungDecodeData RemoteReceiveData::decode_samsung() { - return remote::decode_samsung(this); -} -SonyDecodeData RemoteReceiveData::decode_sony() { - return remote::decode_sony(this); -} +int32_t RemoteReceiveData::operator[](uint32_t index) const { return this->pos(index); } +int32_t RemoteReceiveData::pos(uint32_t index) const { return (*this->data_)[index]; } -RemoteReceiverComponent::RemoteReceiverComponent(GPIOPin *pin) - : RemoteControlComponentBase(pin) { +int32_t RemoteReceiveData::size() const { return this->data_->size(); } +JVCDecodeData RemoteReceiveData::decode_jvc() { return remote::decode_jvc(this); } +LGDecodeData RemoteReceiveData::decode_lg() { return remote::decode_lg(this); } +NECDecodeData RemoteReceiveData::decode_nec() { return remote::decode_nec(this); } +PanasonicDecodeData RemoteReceiveData::decode_panasonic() { return remote::decode_panasonic(this); } +SamsungDecodeData RemoteReceiveData::decode_samsung() { return remote::decode_samsung(this); } +SonyDecodeData RemoteReceiveData::decode_sony() { return remote::decode_sony(this); } -} +RemoteReceiverComponent::RemoteReceiverComponent(GPIOPin *pin) : RemoteControlComponentBase(pin) {} -float RemoteReceiverComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float RemoteReceiverComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } #ifdef ARDUINO_ARCH_ESP32 void RemoteReceiverComponent::setup() { @@ -200,7 +171,7 @@ void RemoteReceiverComponent::loop() { this->process_(&data); } } -void RemoteReceiverComponent::decode_rmt_(rmt_item32_t *item, size_t len) { +void RemoteReceiverComponent::decode_rmt_(rmt_item32_t *item, size_t len) { bool prev_level = false; uint32_t prev_length = 0; this->temp_.clear(); @@ -275,7 +246,7 @@ void RemoteReceiverComponent::decode_rmt_(rmt_item32_t *item, size_t len) { #ifdef ARDUINO_ARCH_ESP8266 -void ICACHE_RAM_ATTR HOT RemoteReceiverComponent::gpio_intr() { +void ICACHE_RAM_ATTR HOT RemoteReceiverComponent::gpio_intr_() { const uint32_t now = micros(); // If the lhs is 1 (rising edge) we should write to an uneven index and vice versa const uint32_t next = (this->buffer_write_at_ + 1) % this->buffer_size_; @@ -310,9 +281,7 @@ void RemoteReceiverComponent::setup() { this->buffer_write_at_ = this->buffer_read_at_ = 0; this->buffer_[0] = 0; } - attach_functional_interrupt(this->pin_->get_pin(), [this]() ICACHE_RAM_ATTR { - this->gpio_intr(); - }, CHANGE); + attach_functional_interrupt(this->pin_->get_pin(), [this]() ICACHE_RAM_ATTR { this->gpio_intr_(); }, CHANGE); } void RemoteReceiverComponent::dump_config() { ESP_LOGCONFIG(TAG, "Remote Receiver:"); @@ -351,8 +320,8 @@ void RemoteReceiverComponent::loop() { // TODO: Handle case when loop() is not called quickly enough to catch idle return; - ESP_LOGVV(TAG, "read_at=%u write_at=%u dist=%u now=%u end=%u", - this->buffer_read_at_, write_at, dist, now, this->buffer_[write_at]); + ESP_LOGVV(TAG, "read_at=%u write_at=%u dist=%u now=%u end=%u", this->buffer_read_at_, write_at, dist, now, + this->buffer_[write_at]); // Skip first value, it's from the previous idle level this->buffer_read_at_ = (this->buffer_read_at_ + 1) % this->buffer_size_; @@ -364,14 +333,14 @@ void RemoteReceiverComponent::loop() { int32_t multiplier = this->buffer_read_at_ % 2 == 0 ? 1 : -1; for (uint32_t i = 0; prev != write_at; i++) { - int32_t delta = this->buffer_[this->buffer_read_at_] - this->buffer_[prev]; + int32_t delta = this->buffer_[this->buffer_read_at_] - this->buffer_[prev]; if (uint32_t(delta) >= this->idle_us_) { // already found a space longer than idle. There must have been two pulses break; } - ESP_LOGVV(TAG, " i=%u buffer[%u]=%u - buffer[%u]=%u -> %d", - i, this->buffer_read_at_, this->buffer_[this->buffer_read_at_], prev, this->buffer_[prev], multiplier * delta); + ESP_LOGVV(TAG, " i=%u buffer[%u]=%u - buffer[%u]=%u -> %d", i, this->buffer_read_at_, + this->buffer_[this->buffer_read_at_], prev, this->buffer_[prev], multiplier * delta); this->temp_.push_back(multiplier * delta); prev = this->buffer_read_at_; this->buffer_read_at_ = (this->buffer_read_at_ + 1) % this->buffer_size_; @@ -389,25 +358,15 @@ RemoteReceiver *RemoteReceiverComponent::add_decoder(RemoteReceiver *decoder) { this->decoders_.push_back(decoder); return decoder; } -void RemoteReceiverComponent::add_dumper(RemoteReceiveDumper *dumper) { - this->dumpers_.push_back(dumper); -} -void RemoteReceiverComponent::set_buffer_size(uint32_t buffer_size) { - this->buffer_size_ = buffer_size; -} -void RemoteReceiverComponent::set_tolerance(uint8_t tolerance) { - this->tolerance_ = tolerance; -} -void RemoteReceiverComponent::set_filter_us(uint8_t filter_us) { - this->filter_us_ = filter_us; -} -void RemoteReceiverComponent::set_idle_us(uint32_t idle_us) { - this->idle_us_ = idle_us; -} +void RemoteReceiverComponent::add_dumper(RemoteReceiveDumper *dumper) { this->dumpers_.push_back(dumper); } +void RemoteReceiverComponent::set_buffer_size(uint32_t buffer_size) { this->buffer_size_ = buffer_size; } +void RemoteReceiverComponent::set_tolerance(uint8_t tolerance) { this->tolerance_ = tolerance; } +void RemoteReceiverComponent::set_filter_us(uint8_t filter_us) { this->filter_us_ = filter_us; } +void RemoteReceiverComponent::set_idle_us(uint32_t idle_us) { this->idle_us_ = idle_us; } void RemoteReceiverComponent::process_(RemoteReceiveData *data) { bool found_decoder = false; for (auto *decoder : this->decoders_) { - if (decoder->process_(data)) + if (decoder->process(data)) found_decoder = true; } @@ -415,27 +374,24 @@ void RemoteReceiverComponent::process_(RemoteReceiveData *data) { bool found = false; for (auto *dumper : this->dumpers_) { - if (!dumper->secondary_()) { - if (dumper->process_(data)) { + if (!dumper->is_secondary()) { + if (dumper->process(data)) { found = true; } } } for (auto *dumper : this->dumpers_) { - if (!found && dumper->secondary_()) { - dumper->process_(data); + if (!found && dumper->is_secondary()) { + dumper->process(data); } } } } -RemoteReceiver::RemoteReceiver(const std::string &name) - : BinarySensor(name) { - -} +RemoteReceiver::RemoteReceiver(const std::string &name) : BinarySensor(name) {} -bool RemoteReceiver::process_(RemoteReceiveData *data) { +bool RemoteReceiver::process(RemoteReceiveData *data) { data->reset_index(); if (this->matches(data)) { this->publish_state(true); @@ -445,17 +401,15 @@ bool RemoteReceiver::process_(RemoteReceiveData *data) { } return false; } -bool RemoteReceiveDumper::secondary_() { - return false; -} +bool RemoteReceiveDumper::is_secondary() { return false; } -bool RemoteReceiveDumper::process_(RemoteReceiveData *data) { +bool RemoteReceiveDumper::process(RemoteReceiveData *data) { data->reset_index(); return this->dump(data); } -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE_RECEIVER +#endif // USE_REMOTE_RECEIVER diff --git a/src/esphome/remote/remote_receiver.h b/src/esphome/remote/remote_receiver.h index d0c5db5a..598c7a53 100644 --- a/src/esphome/remote/remote_receiver.h +++ b/src/esphome/remote/remote_receiver.h @@ -82,7 +82,7 @@ class RemoteReceiveData { int32_t pos(uint32_t index) const; - int32_t operator [](uint32_t index) const; + int32_t operator[](uint32_t index) const; int32_t size() const; @@ -106,7 +106,7 @@ class RemoteReceiver : public binary_sensor::BinarySensor { public: explicit RemoteReceiver(const std::string &name); - bool process_(RemoteReceiveData *data); + bool process(RemoteReceiveData *data); protected: virtual bool matches(RemoteReceiveData *data) = 0; @@ -116,9 +116,9 @@ class RemoteReceiveDumper { public: virtual bool dump(RemoteReceiveData *data) = 0; - bool process_(RemoteReceiveData *data); + bool process(RemoteReceiveData *data); - virtual bool secondary_(); + virtual bool is_secondary(); }; class RemoteReceiverComponent : public RemoteControlComponentBase, public Component { @@ -138,11 +138,11 @@ class RemoteReceiverComponent : public RemoteControlComponentBase, public Compon void set_filter_us(uint8_t filter_us); void set_idle_us(uint32_t idle_us); - void process_(RemoteReceiveData *data); - protected: friend RemoteReceiveData; + void process_(RemoteReceiveData *data); + #ifdef ARDUINO_ARCH_ESP32 void decode_rmt_(rmt_item32_t *item, size_t len); #endif @@ -160,7 +160,7 @@ class RemoteReceiverComponent : public RemoteControlComponentBase, public Compon /// The position last read from uint32_t buffer_read_at_{0}; bool overflow_{false}; - void gpio_intr(); + void gpio_intr_(); #endif #ifdef ARDUINO_ARCH_ESP32 @@ -178,10 +178,10 @@ class RemoteReceiverComponent : public RemoteControlComponentBase, public Compon std::vector temp_; }; -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE_RECEIVER +#endif // USE_REMOTE_RECEIVER -#endif //ESPHOME_REMOTE_REMOTE_RECEIVER_H +#endif // ESPHOME_REMOTE_REMOTE_RECEIVER_H diff --git a/src/esphome/remote/remote_transmitter.cpp b/src/esphome/remote/remote_transmitter.cpp index cf0965da..e94999bc 100644 --- a/src/esphome/remote/remote_transmitter.cpp +++ b/src/esphome/remote/remote_transmitter.cpp @@ -15,7 +15,7 @@ #include "esphome/remote/sony.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -24,19 +24,13 @@ namespace remote { static const char *TAG = "remote.transmitter"; -void RemoteTransmitData::mark(uint32_t length) { - this->data_.push_back(length); -} -void RemoteTransmitData::space(uint32_t length) { - this->data_.push_back(-length); -} +void RemoteTransmitData::mark(uint32_t length) { this->data_.push_back(length); } +void RemoteTransmitData::space(uint32_t length) { this->data_.push_back(-length); } void RemoteTransmitData::item(uint32_t mark, uint32_t space) { this->mark(mark); this->space(space); } -void RemoteTransmitData::reserve(uint32_t len) { - this->data_.reserve(len); -} +void RemoteTransmitData::reserve(uint32_t len) { this->data_.reserve(len); } void RemoteTransmitData::set_data(std::vector data) { this->data_.clear(); this->data_.reserve(data.size()); @@ -46,29 +40,14 @@ void RemoteTransmitData::set_data(std::vector data) { void RemoteTransmitData::set_carrier_frequency(uint32_t carrier_frequency) { this->carrier_frequency_ = carrier_frequency; } -uint32_t RemoteTransmitData::get_carrier_frequency() const { - return this->carrier_frequency_; -} -const std::vector &RemoteTransmitData::get_data() const { - return this->data_; -} -std::vector::iterator RemoteTransmitData::begin() { - return this->data_.begin(); -} -std::vector::iterator RemoteTransmitData::end() { - return this->data_.end(); -} -void RemoteTransmitData::reset() { - this->data_.clear(); -} - -RemoteTransmitter::RemoteTransmitter(const std::string &name) - : Switch(name) { +uint32_t RemoteTransmitData::get_carrier_frequency() const { return this->carrier_frequency_; } +const std::vector &RemoteTransmitData::get_data() const { return this->data_; } +std::vector::iterator RemoteTransmitData::begin() { return this->data_.begin(); } +std::vector::iterator RemoteTransmitData::end() { return this->data_.end(); } +void RemoteTransmitData::reset() { this->data_.clear(); } -} -void RemoteTransmitter::set_parent(RemoteTransmitterComponent *parent) { - this->parent_ = parent; -} +RemoteTransmitter::RemoteTransmitter(const std::string &name) : Switch(name) {} +void RemoteTransmitter::set_parent(RemoteTransmitterComponent *parent) { this->parent_ = parent; } void RemoteTransmitter::set_repeat(uint32_t send_times, uint32_t send_wait) { this->send_times_ = send_times; this->send_wait_ = send_wait; @@ -83,24 +62,13 @@ void RemoteTransmitter::write_state(bool state) { // we must defer sending until next loop execution this->parent_->deferred_send(this); } -uint32_t RemoteTransmitter::get_send_times() const { - return this->send_times_; -} -uint32_t RemoteTransmitter::get_send_wait() const { - return this->send_wait_; -} - -RemoteTransmitterComponent::RemoteTransmitterComponent(GPIOPin *pin) - : RemoteControlComponentBase(pin) { +uint32_t RemoteTransmitter::get_send_times() const { return this->send_times_; } +uint32_t RemoteTransmitter::get_send_wait() const { return this->send_wait_; } -} -float RemoteTransmitterComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +RemoteTransmitterComponent::RemoteTransmitterComponent(GPIOPin *pin) : RemoteControlComponentBase(pin) {} +float RemoteTransmitterComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } #ifdef ARDUINO_ARCH_ESP32 -void RemoteTransmitterComponent::setup() { - -} +void RemoteTransmitterComponent::setup() {} void RemoteTransmitterComponent::dump_config() { ESP_LOGCONFIG(TAG, "Remote Transmitter..."); @@ -222,7 +190,7 @@ void RemoteTransmitterComponent::send_(RemoteTransmitData *data, uint32_t send_t } } } -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 void RemoteTransmitterComponent::setup() { @@ -240,15 +208,14 @@ void RemoteTransmitterComponent::dump_config() { } } -void RemoteTransmitterComponent::calculate_on_off_time_(uint32_t carrier_frequency, - uint32_t *on_time_period, +void RemoteTransmitterComponent::calculate_on_off_time_(uint32_t carrier_frequency, uint32_t *on_time_period, uint32_t *off_time_period) { if (carrier_frequency == 0) { *on_time_period = 0; *off_time_period = 0; return; } - uint32_t period = (1000000UL + carrier_frequency / 2) / carrier_frequency; // round(1000000/freq) + uint32_t period = (1000000UL + carrier_frequency / 2) / carrier_frequency; // round(1000000/freq) period = std::max(uint32_t(1), period); *on_time_period = (period * this->carrier_duty_percent_) / 100; *off_time_period = period - *on_time_period; @@ -309,7 +276,7 @@ void RemoteTransmitterComponent::space_(uint32_t usec) { this->pin_->digital_write(false); delay_microseconds_accurate(usec); } -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 RemoteTransmitter *RemoteTransmitterComponent::add_transmitter(RemoteTransmitter *transmitter) { transmitter->set_parent(this); @@ -319,32 +286,25 @@ RemoteTransmitter *RemoteTransmitterComponent::add_transmitter(RemoteTransmitter void RemoteTransmitterComponent::set_carrier_duty_percent(uint8_t carrier_duty_percent) { this->carrier_duty_percent_ = carrier_duty_percent; } -RemoteTransmitterComponent::TransmitCall RemoteTransmitterComponent::transmit() { - return TransmitCall(this); -} -void RemoteTransmitterComponent::deferred_send(RemoteTransmitter *switch_) { - this->defer([this, switch_]() { - switch_->publish_state(true); +RemoteTransmitterComponent::TransmitCall RemoteTransmitterComponent::transmit() { return TransmitCall(this); } +void RemoteTransmitterComponent::deferred_send(RemoteTransmitter *a_switch) { + this->defer([this, a_switch]() { + a_switch->publish_state(true); this->temp_.reset(); - switch_->to_data(&this->temp_); - this->send_(&this->temp_, switch_->get_send_times(), switch_->get_send_wait()); - switch_->publish_state(false); + a_switch->to_data(&this->temp_); + this->send_(&this->temp_, a_switch->get_send_times(), a_switch->get_send_wait()); + a_switch->publish_state(false); }); } void RemoteTransmitterComponent::TransmitCall::perform() { this->parent_->send_(&this->parent_->temp_, this->send_times_, this->send_wait_); } -RemoteTransmitterComponent::TransmitCall::TransmitCall(RemoteTransmitterComponent *parent) - : parent_(parent) { +RemoteTransmitterComponent::TransmitCall::TransmitCall(RemoteTransmitterComponent *parent) : parent_(parent) { this->get_data()->reset(); } -RemoteTransmitData *RemoteTransmitterComponent::TransmitCall::get_data() { - return &this->parent_->temp_; -} -void RemoteTransmitterComponent::TransmitCall::set_jvc(uint32_t data) { - encode_jvc(this->get_data(), data); -} +RemoteTransmitData *RemoteTransmitterComponent::TransmitCall::get_data() { return &this->parent_->temp_; } +void RemoteTransmitterComponent::TransmitCall::set_jvc(uint32_t data) { encode_jvc(this->get_data(), data); } void RemoteTransmitterComponent::TransmitCall::set_lg(uint32_t data, uint8_t nbits) { encode_lg(this->get_data(), data, nbits); } @@ -354,14 +314,11 @@ void RemoteTransmitterComponent::TransmitCall::set_nec(uint16_t address, uint16_ void RemoteTransmitterComponent::TransmitCall::set_panasonic(uint16_t address, uint32_t command) { encode_panasonic(this->get_data(), address, command); } -void RemoteTransmitterComponent::TransmitCall::set_raw(std::vector data) { - this->get_data()->set_data(data); -} +void RemoteTransmitterComponent::TransmitCall::set_raw(std::vector data) { this->get_data()->set_data(data); } void RemoteTransmitterComponent::TransmitCall::set_rc5(uint8_t address, uint8_t command, bool toggle) { encode_rc5(this->get_data(), address, command, toggle); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_raw(uint32_t code, - uint8_t nbits, +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_raw(uint32_t code, uint8_t nbits, RCSwitchProtocol protocol) { encode_rc_switch_raw(this->get_data(), code, nbits, protocol); } @@ -371,59 +328,41 @@ void RemoteTransmitterComponent::TransmitCall::set_rc_switch_raw(const char *cod void RemoteTransmitterComponent::TransmitCall::set_rc_switch_raw_tristate(const char *code, RCSwitchProtocol protocol) { encode_rc_switch_raw_tristate(this->get_data(), code, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_a(uint8_t switch_group, - uint8_t switch_device, - bool state, - RCSwitchProtocol protocol) { +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_a(uint8_t switch_group, uint8_t switch_device, + bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_a(this->get_data(), switch_group, switch_device, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_a(const char *switch_group, - const char *switch_device, - bool state, - RCSwitchProtocol protocol) { +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_a(const char *switch_group, const char *switch_device, + bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_a(this->get_data(), switch_group, switch_device, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_b(uint8_t address, - uint8_t channel, - bool state, +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_b(uint8_t address, uint8_t channel, bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_b(this->get_data(), address, channel, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_c(uint8_t family, - uint8_t group, - uint8_t device, - bool state, - RCSwitchProtocol protocol) { +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_c(uint8_t family, uint8_t group, uint8_t device, + bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_c(this->get_data(), family, group, device, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_c(char family, - uint8_t group, - uint8_t device, - bool state, - RCSwitchProtocol protocol) { +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_c(char family, uint8_t group, uint8_t device, + bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_c(this->get_data(), family, group, device, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_d(uint8_t group, - uint8_t device, - bool state, +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_d(uint8_t group, uint8_t device, bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_d(this->get_data(), group, device, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_d(char group, - uint8_t device, - bool state, +void RemoteTransmitterComponent::TransmitCall::set_rc_switch_type_d(char group, uint8_t device, bool state, RCSwitchProtocol protocol) { encode_rc_switch_type_d(this->get_data(), group, device, state, protocol); } -void RemoteTransmitterComponent::TransmitCall::set_samsung(uint32_t data) { - encode_samsung(this->get_data(), data); -} +void RemoteTransmitterComponent::TransmitCall::set_samsung(uint32_t data) { encode_samsung(this->get_data(), data); } void RemoteTransmitterComponent::TransmitCall::set_sony(uint32_t data, uint8_t nbits) { encode_sony(this->get_data(), data, nbits); } -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE_TRANSMITTER +#endif // USE_REMOTE_TRANSMITTER diff --git a/src/esphome/remote/remote_transmitter.h b/src/esphome/remote/remote_transmitter.h index 2909002f..c64be914 100644 --- a/src/esphome/remote/remote_transmitter.h +++ b/src/esphome/remote/remote_transmitter.h @@ -61,8 +61,8 @@ class RemoteTransmitter : public switch_::Switch { void write_state(bool state) override; RemoteTransmitterComponent *parent_; - uint32_t send_times_{1}; ///< How many times to send the data - uint32_t send_wait_{0}; ///< How many microseconds to wait between repeats. + uint32_t send_times_{1}; ///< How many times to send the data + uint32_t send_wait_{0}; ///< How many microseconds to wait between repeats. }; class RemoteTransmitterComponent : public RemoteControlComponentBase, public Component { @@ -80,7 +80,7 @@ class RemoteTransmitterComponent : public RemoteControlComponentBase, public Com void set_carrier_duty_percent(uint8_t carrier_duty_percent); /// Defer send of the switches remote code until next loop(). - void deferred_send(RemoteTransmitter *switch_); + void deferred_send(RemoteTransmitter *a_switch); class TransmitCall { public: @@ -91,12 +91,9 @@ class RemoteTransmitterComponent : public RemoteControlComponentBase, public Com void set_panasonic(uint16_t address, uint32_t command); void set_raw(std::vector data); void set_rc5(uint8_t address, uint8_t command, bool toggle); - void set_rc_switch_raw(uint32_t code, uint8_t nbits, - RCSwitchProtocol protocol = rc_switch_protocols[1]); - void set_rc_switch_raw(const char *code, - RCSwitchProtocol protocol = rc_switch_protocols[1]); - void set_rc_switch_raw_tristate(const char *code, - RCSwitchProtocol protocol = rc_switch_protocols[1]); + void set_rc_switch_raw(uint32_t code, uint8_t nbits, RCSwitchProtocol protocol = rc_switch_protocols[1]); + void set_rc_switch_raw(const char *code, RCSwitchProtocol protocol = rc_switch_protocols[1]); + void set_rc_switch_raw_tristate(const char *code, RCSwitchProtocol protocol = rc_switch_protocols[1]); void set_rc_switch_type_a(uint8_t switch_group, uint8_t switch_device, bool state, RCSwitchProtocol protocol = rc_switch_protocols[1]); void set_rc_switch_type_a(const char *switch_group, const char *switch_device, bool state, @@ -117,6 +114,7 @@ class RemoteTransmitterComponent : public RemoteControlComponentBase, public Com void perform(); RemoteTransmitData *get_data(); + protected: RemoteTransmitterComponent *parent_; uint32_t send_times_{1}; @@ -131,9 +129,7 @@ class RemoteTransmitterComponent : public RemoteControlComponentBase, public Com void send_(RemoteTransmitData *data, uint32_t send_times, uint32_t send_wait); #ifdef ARDUINO_ARCH_ESP8266 - void calculate_on_off_time_(uint32_t carrier_frequency, - uint32_t *on_time_period, - uint32_t *off_time_period); + void calculate_on_off_time_(uint32_t carrier_frequency, uint32_t *on_time_period, uint32_t *off_time_period); void mark_(uint32_t on_time, uint32_t off_time, uint32_t usec); @@ -151,10 +147,10 @@ class RemoteTransmitterComponent : public RemoteControlComponentBase, public Com RemoteTransmitData temp_; }; -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE_TRANSMITTER +#endif // USE_REMOTE_TRANSMITTER -#endif //ESPHOME_REMOTE_TRANSMITTER_H +#endif // ESPHOME_REMOTE_TRANSMITTER_H diff --git a/src/esphome/remote/samsung.cpp b/src/esphome/remote/samsung.cpp index ee6fee46..acbd4254 100644 --- a/src/esphome/remote/samsung.cpp +++ b/src/esphome/remote/samsung.cpp @@ -23,21 +23,18 @@ static const uint32_t FOOTER_HIGH_US = 560; static const uint32_t FOOTER_LOW_US = 560; #ifdef USE_REMOTE_TRANSMITTER -SamsungTransmitter::SamsungTransmitter(const std::string &name, uint32_t data) - : RemoteTransmitter(name), data_(data) {} +SamsungTransmitter::SamsungTransmitter(const std::string &name, uint32_t data) : RemoteTransmitter(name), data_(data) {} -void SamsungTransmitter::to_data(RemoteTransmitData *data) { - encode_samsung(data, this->data_); -} +void SamsungTransmitter::to_data(RemoteTransmitData *data) { encode_samsung(data, this->data_); } -void encode_samsung(RemoteTransmitData *data, uint32_t data_) { +void encode_samsung(RemoteTransmitData *data, uint32_t samsung_data) { data->set_carrier_frequency(38000); data->reserve(4 + NBITS * 2u); data->item(HEADER_HIGH_US, HEADER_LOW_US); for (uint32_t mask = 1UL << (NBITS - 1); mask != 0; mask >>= 1) { - if (data_ & mask) + if (samsung_data & mask) data->item(BIT_HIGH_US, BIT_ONE_LOW_US); else data->item(BIT_HIGH_US, BIT_ZERO_LOW_US); @@ -70,8 +67,7 @@ SamsungDecodeData decode_samsung(RemoteReceiveData *data) { return out; } -SamsungReceiver::SamsungReceiver(const std::string &name, uint32_t data) - : RemoteReceiver(name), data_(data) {} +SamsungReceiver::SamsungReceiver(const std::string &name, uint32_t data) : RemoteReceiver(name), data_(data) {} bool SamsungReceiver::matches(RemoteReceiveData *data) { auto decode = decode_samsung(data); @@ -91,8 +87,8 @@ bool SamsungDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/samsung.h b/src/esphome/remote/samsung.h index 90e492b6..c299aba4 100644 --- a/src/esphome/remote/samsung.h +++ b/src/esphome/remote/samsung.h @@ -23,7 +23,7 @@ class SamsungTransmitter : public RemoteTransmitter { uint32_t data_; }; -void encode_samsung(RemoteTransmitData *data, uint32_t data_); +void encode_samsung(RemoteTransmitData *data, uint32_t samsung_data); #endif #ifdef USE_REMOTE_RECEIVER @@ -45,10 +45,10 @@ class SamsungDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_SAMSUNG_H +#endif // ESPHOME_REMOTE_SAMSUNG_H diff --git a/src/esphome/remote/sony.cpp b/src/esphome/remote/sony.cpp index e94c7483..37d91f5e 100644 --- a/src/esphome/remote/sony.cpp +++ b/src/esphome/remote/sony.cpp @@ -18,24 +18,18 @@ static const uint32_t BIT_ZERO_HIGH_US = 600; static const uint32_t BIT_LOW_US = 600; #ifdef USE_REMOTE_TRANSMITTER -SonyTransmitter::SonyTransmitter(const std::string &name, - uint32_t data, - uint8_t nbits) - : RemoteTransmitter(name), data_(data), nbits_(nbits) { +SonyTransmitter::SonyTransmitter(const std::string &name, uint32_t data, uint8_t nbits) + : RemoteTransmitter(name), data_(data), nbits_(nbits) {} +void SonyTransmitter::to_data(RemoteTransmitData *data) { encode_sony(data, this->data_, this->nbits_); } -} -void SonyTransmitter::to_data(RemoteTransmitData *data) { - encode_sony(data, this->data_, this->nbits_); -} - -void encode_sony(RemoteTransmitData *data, uint32_t data_, uint8_t nbits) { +void encode_sony(RemoteTransmitData *data, uint32_t sony_data, uint8_t nbits) { data->set_carrier_frequency(40000); data->reserve(2 + nbits * 2u); data->item(HEADER_HIGH_US, HEADER_LOW_US); for (uint32_t mask = 1UL << (nbits - 1); mask != 0; mask >>= 1) { - if (data_ & mask) + if (sony_data & mask) data->item(BIT_ONE_HIGH_US, BIT_LOW_US); else data->item(BIT_ZERO_HIGH_US, BIT_LOW_US); @@ -97,8 +91,8 @@ bool SonyDumper::dump(RemoteReceiveData *data) { } #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE diff --git a/src/esphome/remote/sony.h b/src/esphome/remote/sony.h index 5c322416..bd774c76 100644 --- a/src/esphome/remote/sony.h +++ b/src/esphome/remote/sony.h @@ -24,7 +24,7 @@ class SonyTransmitter : public RemoteTransmitter { uint8_t nbits_; }; -void encode_sony(RemoteTransmitData *data, uint32_t data_, uint8_t nbits); +void encode_sony(RemoteTransmitData *data, uint32_t sony_data, uint8_t nbits); #endif #ifdef USE_REMOTE_RECEIVER @@ -37,7 +37,6 @@ class SonyReceiver : public RemoteReceiver { protected: bool matches(RemoteReceiveData *data) override; - protected: uint32_t data_; uint8_t nbits_; }; @@ -48,10 +47,10 @@ class SonyDumper : public RemoteReceiveDumper { }; #endif -} // namespace remote +} // namespace remote ESPHOME_NAMESPACE_END -#endif //USE_REMOTE +#endif // USE_REMOTE -#endif //ESPHOME_REMOTE_SONY_H +#endif // ESPHOME_REMOTE_SONY_H diff --git a/src/esphome/sensor/adc.cpp b/src/esphome/sensor/adc.cpp index 29b8456c..f67ae3de 100644 --- a/src/esphome/sensor/adc.cpp +++ b/src/esphome/sensor/adc.cpp @@ -13,15 +13,11 @@ namespace sensor { static const char *TAG = "sensor.adc"; ADCSensorComponent::ADCSensorComponent(const std::string &name, GPIOInputPin pin, uint32_t update_interval) - : PollingSensorComponent(name, update_interval), pin_(pin) { } + : PollingSensorComponent(name, update_interval), pin_(pin) {} #ifdef ARDUINO_ARCH_ESP32 -adc_attenuation_t ADCSensorComponent::get_attenuation() const { - return this->attenuation_; -} -void ADCSensorComponent::set_attenuation(adc_attenuation_t attenuation) { - this->attenuation_ = attenuation; -} +adc_attenuation_t ADCSensorComponent::get_attenuation() const { return this->attenuation_; } +void ADCSensorComponent::set_attenuation(adc_attenuation_t attenuation) { this->attenuation_ = attenuation; } #endif void ADCSensorComponent::setup() { @@ -35,11 +31,11 @@ void ADCSensorComponent::setup() { void ADCSensorComponent::dump_config() { LOG_SENSOR("", "ADC Sensor", this); #ifdef ARDUINO_ARCH_ESP8266 - #ifdef USE_ADC_SENSOR_VCC - ESP_LOGCONFIG(TAG, " Pin: VCC"); - #else - LOG_PIN(" Pin: ", &this->pin_); - #endif +#ifdef USE_ADC_SENSOR_VCC + ESP_LOGCONFIG(TAG, " Pin: VCC"); +#else + LOG_PIN(" Pin: ", &this->pin_); +#endif #endif #ifdef ARDUINO_ARCH_ESP32 LOG_PIN(" Pin: ", &this->pin_); @@ -60,9 +56,7 @@ void ADCSensorComponent::dump_config() { #endif LOG_UPDATE_INTERVAL(this); } -float ADCSensorComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float ADCSensorComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void ADCSensorComponent::update() { #ifdef ARDUINO_ARCH_ESP32 float value_v = analogRead(this->pin_.get_pin()) / 4095.0f; @@ -83,34 +77,26 @@ void ADCSensorComponent::update() { #endif #ifdef ARDUINO_ARCH_ESP8266 - #ifdef USE_ADC_SENSOR_VCC - float value_v = ESP.getVcc() / 1024.0f; - #else - float value_v = analogRead(this->pin_.get_pin()) / 1024.0f; - #endif +#ifdef USE_ADC_SENSOR_VCC + float value_v = ESP.getVcc() / 1024.0f; +#else + float value_v = analogRead(this->pin_.get_pin()) / 1024.0f; +#endif #endif ESP_LOGD(TAG, "'%s': Got voltage=%.2fV", this->get_name().c_str(), value_v); this->publish_state(value_v); } -std::string ADCSensorComponent::unit_of_measurement() { - return "V"; -} -std::string ADCSensorComponent::icon() { - return "mdi:flash"; -} -int8_t ADCSensorComponent::accuracy_decimals() { - return 2; -} +std::string ADCSensorComponent::unit_of_measurement() { return "V"; } +std::string ADCSensorComponent::icon() { return "mdi:flash"; } +int8_t ADCSensorComponent::accuracy_decimals() { return 2; } #ifdef ARDUINO_ARCH_ESP8266 -std::string ADCSensorComponent::unique_id() { - return get_mac_address() + "-adc"; -} +std::string ADCSensorComponent::unique_id() { return get_mac_address() + "-adc"; } #endif -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ADC_SENSOR +#endif // USE_ADC_SENSOR diff --git a/src/esphome/sensor/adc.h b/src/esphome/sensor/adc.h index 298af7b5..7dd5f7ae 100644 --- a/src/esphome/sensor/adc.h +++ b/src/esphome/sensor/adc.h @@ -67,10 +67,10 @@ class ADCSensorComponent : public PollingSensorComponent { #endif }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ADC_SENSOR +#endif // USE_ADC_SENSOR -#endif //ESPHOME_SENSOR_ADC_SENSOR_COMPONENT_H +#endif // ESPHOME_SENSOR_ADC_SENSOR_COMPONENT_H diff --git a/src/esphome/sensor/ads1115_component.cpp b/src/esphome/sensor/ads1115_component.cpp index dc018914..7144e5a2 100644 --- a/src/esphome/sensor/ads1115_component.cpp +++ b/src/esphome/sensor/ads1115_component.cpp @@ -63,9 +63,8 @@ void ADS1115Component::setup() { return; } for (auto *sensor : this->sensors_) { - this->set_interval(sensor->get_name(), sensor->update_interval(), [this, sensor]{ - this->request_measurement_(sensor); - }); + this->set_interval(sensor->get_name(), sensor->update_interval(), + [this, sensor] { this->request_measurement_(sensor); }); } } void ADS1115Component::dump_config() { @@ -81,9 +80,7 @@ void ADS1115Component::dump_config() { ESP_LOGCONFIG(TAG, " Gain: %u", sensor->get_gain()); } } -float ADS1115Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float ADS1115Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void ADS1115Component::request_measurement_(ADS1115Sensor *sensor) { uint16_t config; if (!this->read_byte_16(ADS1115_REGISTER_CONFIG, &config)) { @@ -129,13 +126,26 @@ void ADS1115Component::request_measurement_(ADS1115Sensor *sensor) { float millivolts; switch (sensor->get_gain()) { - case ADS1115_GAIN_6P144: millivolts = signed_conversion * 0.187500f; break; - case ADS1115_GAIN_4P096: millivolts = signed_conversion * 0.125000f; break; - case ADS1115_GAIN_2P048: millivolts = signed_conversion * 0.062500f; break; - case ADS1115_GAIN_1P024: millivolts = signed_conversion * 0.031250f; break; - case ADS1115_GAIN_0P512: millivolts = signed_conversion * 0.015625f; break; - case ADS1115_GAIN_0P256: millivolts = signed_conversion * 0.007813f; break; - default: millivolts = NAN; + case ADS1115_GAIN_6P144: + millivolts = signed_conversion * 0.187500f; + break; + case ADS1115_GAIN_4P096: + millivolts = signed_conversion * 0.125000f; + break; + case ADS1115_GAIN_2P048: + millivolts = signed_conversion * 0.062500f; + break; + case ADS1115_GAIN_1P024: + millivolts = signed_conversion * 0.031250f; + break; + case ADS1115_GAIN_0P512: + millivolts = signed_conversion * 0.015625f; + break; + case ADS1115_GAIN_0P256: + millivolts = signed_conversion * 0.007813f; + break; + default: + millivolts = NAN; } float v = millivolts / 1000.0f; @@ -152,27 +162,17 @@ ADS1115Sensor *ADS1115Component::get_sensor(const std::string &name, ADS1115Mult } ADS1115Component::ADS1115Component(I2CComponent *parent, uint8_t address) : I2CDevice(parent, address) {} -uint8_t ADS1115Sensor::get_multiplexer() const { - return this->multiplexer_; -} -void ADS1115Sensor::set_multiplexer(ADS1115Multiplexer multiplexer) { - this->multiplexer_ = multiplexer; -} -uint8_t ADS1115Sensor::get_gain() const { - return this->gain_; -} -void ADS1115Sensor::set_gain(ADS1115Gain gain) { - this->gain_ = gain; -} +uint8_t ADS1115Sensor::get_multiplexer() const { return this->multiplexer_; } +void ADS1115Sensor::set_multiplexer(ADS1115Multiplexer multiplexer) { this->multiplexer_ = multiplexer; } +uint8_t ADS1115Sensor::get_gain() const { return this->gain_; } +void ADS1115Sensor::set_gain(ADS1115Gain gain) { this->gain_ = gain; } ADS1115Sensor::ADS1115Sensor(const std::string &name, ADS1115Multiplexer multiplexer, ADS1115Gain gain, uint32_t update_interval) : EmptySensor(name), multiplexer_(multiplexer), gain_(gain), update_interval_(update_interval) {} -uint32_t ADS1115Sensor::update_interval() { - return this->update_interval_; -} +uint32_t ADS1115Sensor::update_interval() { return this->update_interval_; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ADS1115_SENSOR +#endif // USE_ADS1115_SENSOR diff --git a/src/esphome/sensor/ads1115_component.h b/src/esphome/sensor/ads1115_component.h index 3e4e484d..95007ebd 100644 --- a/src/esphome/sensor/ads1115_component.h +++ b/src/esphome/sensor/ads1115_component.h @@ -74,8 +74,7 @@ class ADS1115Component : public Component, public I2CDevice { /// Internal holder class that is in instance of Sensor so that the hub can create individual sensors. class ADS1115Sensor : public sensor::EmptySensor<3, ICON_FLASH, UNIT_V> { public: - ADS1115Sensor(const std::string &name, ADS1115Multiplexer multiplexer, ADS1115Gain gain, - uint32_t update_interval); + ADS1115Sensor(const std::string &name, ADS1115Multiplexer multiplexer, ADS1115Gain gain, uint32_t update_interval); void set_multiplexer(ADS1115Multiplexer multiplexer); void set_gain(ADS1115Gain gain); @@ -93,10 +92,10 @@ class ADS1115Sensor : public sensor::EmptySensor<3, ICON_FLASH, UNIT_V> { uint32_t update_interval_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ADS1115_SENSOR +#endif // USE_ADS1115_SENSOR -#endif //ESPHOME_INPUT_ADS1115_COMPONENT_H +#endif // ESPHOME_INPUT_ADS1115_COMPONENT_H diff --git a/src/esphome/sensor/apds9960.cpp b/src/esphome/sensor/apds9960.cpp index 86dbbd6d..b81b75ec 100644 --- a/src/esphome/sensor/apds9960.cpp +++ b/src/esphome/sensor/apds9960.cpp @@ -11,7 +11,11 @@ namespace sensor { static const char *TAG = "sensor.apds9960"; -#define APDS9960_ERROR_CHECK(func) if (!func) { this->mark_failed(); return; } +#define APDS9960_ERROR_CHECK(func) \ + if (!func) { \ + this->mark_failed(); \ + return; \ + } #define APDS9960_WRITE_BYTE(reg, value) APDS9960_ERROR_CHECK(this->write_byte(reg, value)); void APDS9960::setup() { @@ -23,7 +27,7 @@ void APDS9960::setup() { return; } - if (id != 0xAB && id != 0x9C) { // APDS9960 all should have one of these IDs + if (id != 0xAB && id != 0x9C) { // APDS9960 all should have one of these IDs this->error_code_ = WRONG_ID; this->mark_failed(); return; @@ -46,15 +50,15 @@ void APDS9960::setup() { uint8_t val = 0; APDS9960_ERROR_CHECK(this->read_byte(0x8F, &val)); val &= 0b00111111; - uint8_t led_drive = 0; // led drive, 0 -> 100mA, 1 -> 50mA, 2 -> 25mA, 3 -> 12.5mA + uint8_t led_drive = 0; // led drive, 0 -> 100mA, 1 -> 50mA, 2 -> 25mA, 3 -> 12.5mA val |= (led_drive & 0b11) << 6; val &= 0b11110011; - uint8_t proximity_gain = 2; // proximity gain, 0 -> 1x, 1 -> 2X, 2 -> 4X, 4 -> 8X + uint8_t proximity_gain = 2; // proximity gain, 0 -> 1x, 1 -> 2X, 2 -> 4X, 4 -> 8X val |= (proximity_gain & 0b11) << 2; val &= 0b11111100; - uint8_t ambient_gain = 1; // ambient light gain, 0 -> 1x, 1 -> 4x, 2 -> 16x, 3 -> 64x + uint8_t ambient_gain = 1; // ambient light gain, 0 -> 1x, 1 -> 4x, 2 -> 16x, 3 -> 64x val |= (ambient_gain & 0b11) << 0; APDS9960_WRITE_BYTE(0x8F, val); @@ -75,18 +79,18 @@ void APDS9960::setup() { // GConf 2 (0xA3, gesture config 2) -> APDS9960_ERROR_CHECK(this->read_byte(0xA3, &val)); val &= 0b10011111; - uint8_t gesture_gain = 2; // gesture gain, 0 -> 1x, 1 -> 2x, 2 -> 4x, 3 -> 8x + uint8_t gesture_gain = 2; // gesture gain, 0 -> 1x, 1 -> 2x, 2 -> 4x, 3 -> 8x val |= (gesture_gain & 0b11) << 5; val &= 0b11100111; - uint8_t gesture_led_drive = 0; // gesture led drive, 0 -> 100mA, 1 -> 50mA, 2 -> 25mA, 3 -> 12.5mA + uint8_t gesture_led_drive = 0; // gesture led drive, 0 -> 100mA, 1 -> 50mA, 2 -> 25mA, 3 -> 12.5mA val |= (gesture_led_drive & 0b11) << 3; val &= 0b11111000; // gesture wait time // 0 -> 0ms, 1 -> 2.8ms, 2 -> 5.6ms, 3 -> 8.4ms // 4 -> 14.0ms, 5 -> 22.4 ms, 6 -> 30.8ms, 7 -> 39.2 ms - uint8_t gesture_wait_time = 1; // gesture wait time + uint8_t gesture_wait_time = 1; // gesture wait time val |= (gesture_wait_time & 0b111) << 0; APDS9960_WRITE_BYTE(0xA3, val); @@ -107,20 +111,18 @@ void APDS9960::setup() { // Enable (0x80) -> val = 0; - val |= (0b1) << 0; // power on + val |= (0b1) << 0; // power on val |= (this->is_color_enabled_() & 0b1) << 1; val |= (this->is_proximity_enabled_() & 0b1) << 2; - val |= 0b0 << 3; // wait timer disabled - val |= 0b0 << 4; // color interrupt disabled - val |= 0b0 << 5; // proximity interrupt disabled + val |= 0b0 << 3; // wait timer disabled + val |= 0b0 << 4; // color interrupt disabled + val |= 0b0 << 5; // proximity interrupt disabled val |= (this->is_gesture_enabled_() & 0b1) << 6; // proximity is required for gestures APDS9960_WRITE_BYTE(0x80, val); } bool APDS9960::is_color_enabled_() const { - return this->red_channel_ != nullptr || - this->green_channel_ != nullptr || - this->blue_channel_ != nullptr || - this->clear_channel_ != nullptr; + return this->red_channel_ != nullptr || this->green_channel_ != nullptr || this->blue_channel_ != nullptr || + this->clear_channel_ != nullptr; } void APDS9960::dump_config() { @@ -144,11 +146,11 @@ void APDS9960::dump_config() { } #define APDS9960_WARNING_CHECK(func, warning) \ - if (!(func)) { \ - ESP_LOGW(TAG, warning); \ - this->status_set_warning(); \ - return; \ - } + if (!(func)) { \ + ESP_LOGW(TAG, warning); \ + this->status_set_warning(); \ + return; \ + } void APDS9960::update() { uint8_t status; @@ -159,9 +161,7 @@ void APDS9960::update() { this->read_proximity_data_(status); } -void APDS9960::loop() { - this->read_gesture_data_(); -} +void APDS9960::loop() { this->read_gesture_data_(); } void APDS9960::read_color_data_(uint8_t status) { if (!this->is_color_enabled_()) @@ -185,8 +185,7 @@ void APDS9960::read_color_data_(uint8_t status) { float green_perc = (uint_green / float(UINT16_MAX)) * 100.0f; float blue_perc = (uint_blue / float(UINT16_MAX)) * 100.0f; - ESP_LOGD(TAG, "Got clear=%.1f%% red=%.1f%% green=%.1f%% blue=%.1f%%", - clear_perc, red_perc, green_perc, blue_perc); + ESP_LOGD(TAG, "Got clear=%.1f%% red=%.1f%% green=%.1f%% blue=%.1f%%", clear_perc, red_perc, green_perc, blue_perc); if (this->clear_channel_ != nullptr) this->clear_channel_->publish_state(clear_perc); if (this->red_channel_ != nullptr) @@ -200,7 +199,7 @@ void APDS9960::read_proximity_data_(uint8_t status) { if (this->proximity_ == nullptr) return; - if ((status& 0b10) == 0x00) { + if ((status & 0b10) == 0x00) { // proximity data not ready yet. return; } @@ -253,7 +252,7 @@ void APDS9960::read_gesture_data_() { } for (uint32_t i = 0; i < fifo_level * 4; i += 4) { - const int up = buf[i + 0]; + const int up = buf[i + 0]; // NOLINT const int down = buf[i + 1]; const int left = buf[i + 2]; const int right = buf[i + 3]; @@ -329,7 +328,7 @@ void APDS9960::process_dataset_(int up, int down, int left, int right) { if (up_down_delta < 0) { if (this->gesture_up_started_) { // trailing edge of gesture up - this->report_gesture_(1); // UP + this->report_gesture_(1); // UP } else { // leading edge of gesture down this->gesture_down_started_ = true; @@ -338,7 +337,7 @@ void APDS9960::process_dataset_(int up, int down, int left, int right) { } else { if (this->gesture_down_started_) { // trailing edge of gesture down - this->report_gesture_(2); // DOWN + this->report_gesture_(2); // DOWN } else { // leading edge of gesture up this->gesture_up_started_ = true; @@ -351,7 +350,7 @@ void APDS9960::process_dataset_(int up, int down, int left, int right) { if (left_right_delta < 0) { if (this->gesture_left_started_) { // trailing edge of gesture left - this->report_gesture_(3); // LEFT + this->report_gesture_(3); // LEFT } else { // leading edge of gesture right this->gesture_right_started_ = true; @@ -360,7 +359,7 @@ void APDS9960::process_dataset_(int up, int down, int left, int right) { } else { if (this->gesture_right_started_) { // trailing edge of gesture right - this->report_gesture_(4); // RIGHT + this->report_gesture_(4); // RIGHT } else { // leading edge of gesture left this->gesture_left_started_ = true; @@ -369,22 +368,14 @@ void APDS9960::process_dataset_(int up, int down, int left, int right) { } } } -float APDS9960::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -bool APDS9960::is_proximity_enabled_() const { - return this->proximity_ != nullptr || this->is_gesture_enabled_(); -} +float APDS9960::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +bool APDS9960::is_proximity_enabled_() const { return this->proximity_ != nullptr || this->is_gesture_enabled_(); } bool APDS9960::is_gesture_enabled_() const { - return this->up_direction_ != nullptr || - this->left_direction_ != nullptr || - this->down_direction_ != nullptr || - this->right_direction_ != nullptr; + return this->up_direction_ != nullptr || this->left_direction_ != nullptr || this->down_direction_ != nullptr || + this->right_direction_ != nullptr; } APDS9960::APDS9960(I2CComponent *parent, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, 0x39) { - -} + : PollingComponent(update_interval), I2CDevice(parent, 0x39) {} APDS9960ColorChannelSensor *APDS9960::make_clear_channel(const std::string &name) { return this->clear_channel_ = new APDS9960ColorChannelSensor(name, this); } @@ -412,16 +403,12 @@ APDS9960GestureDirectionBinarySensor *APDS9960::make_left_direction(const std::s APDS9960GestureDirectionBinarySensor *APDS9960::make_right_direction(const std::string &name) { return this->right_direction_ = new APDS9960GestureDirectionBinarySensor(name); } -std::string APDS9960GestureDirectionBinarySensor::device_class() { - return "moving"; -} +std::string APDS9960GestureDirectionBinarySensor::device_class() { return "moving"; } APDS9960GestureDirectionBinarySensor::APDS9960GestureDirectionBinarySensor(const std::string &name) - : BinarySensor(name) { - -} + : BinarySensor(name) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_APDS9960 +#endif // USE_APDS9960 diff --git a/src/esphome/sensor/apds9960.h b/src/esphome/sensor/apds9960.h index f8ce9553..10d47ad7 100644 --- a/src/esphome/sensor/apds9960.h +++ b/src/esphome/sensor/apds9960.h @@ -71,14 +71,15 @@ class APDS9960 : public PollingComponent, public I2CDevice { class APDS9960GestureDirectionBinarySensor : public binary_sensor::BinarySensor { public: APDS9960GestureDirectionBinarySensor(const std::string &name); + protected: std::string device_class() override; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_APDS9960 +#endif // USE_APDS9960 -#endif //ESPHOME_SENSOR_APDS9960_H +#endif // ESPHOME_SENSOR_APDS9960_H diff --git a/src/esphome/sensor/bh1750_sensor.cpp b/src/esphome/sensor/bh1750_sensor.cpp index aae18353..2ec5ad92 100644 --- a/src/esphome/sensor/bh1750_sensor.cpp +++ b/src/esphome/sensor/bh1750_sensor.cpp @@ -18,8 +18,7 @@ static const char *TAG = "sensor.bh1750"; static const uint8_t BH1750_COMMAND_POWER_ON = 0b00000001; -BH1750Sensor::BH1750Sensor(I2CComponent *parent, const std::string &name, - uint8_t address, uint32_t update_interval) +BH1750Sensor::BH1750Sensor(I2CComponent *parent, const std::string &name, uint8_t address, uint32_t update_interval) : PollingSensorComponent(name, update_interval), I2CDevice(parent, address) {} void BH1750Sensor::setup() { @@ -38,10 +37,18 @@ void BH1750Sensor::dump_config() { const char *resolution_s; switch (this->resolution_) { - case BH1750_RESOLUTION_0P5_LX: resolution_s = "0.5"; break; - case BH1750_RESOLUTION_1P0_LX: resolution_s = "1"; break; - case BH1750_RESOLUTION_4P0_LX: resolution_s = "4"; break; - default: resolution_s = "Unknown"; break; + case BH1750_RESOLUTION_0P5_LX: + resolution_s = "0.5"; + break; + case BH1750_RESOLUTION_1P0_LX: + resolution_s = "1"; + break; + case BH1750_RESOLUTION_4P0_LX: + resolution_s = "4"; + break; + default: + resolution_s = "Unknown"; + break; } ESP_LOGCONFIG(TAG, " Resolution: %s", resolution_s); LOG_UPDATE_INTERVAL(this); @@ -63,25 +70,15 @@ void BH1750Sensor::update() { break; } - this->set_timeout("illuminance", wait, [this]() { - this->read_data_(); - }); -} -std::string BH1750Sensor::unit_of_measurement() { - return UNIT_LX; -} -std::string BH1750Sensor::icon() { - return ICON_BRIGHTNESS_5; -} -int8_t BH1750Sensor::accuracy_decimals() { - return 1; -} -float BH1750Sensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; + this->set_timeout("illuminance", wait, [this]() { this->read_data_(); }); } +std::string BH1750Sensor::unit_of_measurement() { return UNIT_LX; } +std::string BH1750Sensor::icon() { return ICON_BRIGHTNESS_5; } +int8_t BH1750Sensor::accuracy_decimals() { return 1; } +float BH1750Sensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void BH1750Sensor::read_data_() { uint16_t raw_value; - if (!this->parent_->receive_16_(this->address_, &raw_value, 1)) { + if (!this->parent_->raw_receive_16(this->address_, &raw_value, 1)) { this->status_set_warning(); return; } @@ -91,12 +88,10 @@ void BH1750Sensor::read_data_() { this->publish_state(lx); this->status_clear_warning(); } -void BH1750Sensor::set_resolution(BH1750Resolution resolution) { - this->resolution_ = resolution; -} +void BH1750Sensor::set_resolution(BH1750Resolution resolution) { this->resolution_ = resolution; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BH1750 +#endif // USE_BH1750 diff --git a/src/esphome/sensor/bh1750_sensor.h b/src/esphome/sensor/bh1750_sensor.h index a9f7fb84..0dd8dfd9 100644 --- a/src/esphome/sensor/bh1750_sensor.h +++ b/src/esphome/sensor/bh1750_sensor.h @@ -14,16 +14,15 @@ namespace sensor { /// Enum listing all resolutions that can be used with the BH1750 enum BH1750Resolution { - BH1750_RESOLUTION_4P0_LX = 0b00100011, // one-time low resolution mode - BH1750_RESOLUTION_1P0_LX = 0b00100000, // one-time high resolution mode 1 - BH1750_RESOLUTION_0P5_LX = 0b00100001, // one-time high resolution mode 2 + BH1750_RESOLUTION_4P0_LX = 0b00100011, // one-time low resolution mode + BH1750_RESOLUTION_1P0_LX = 0b00100000, // one-time high resolution mode 1 + BH1750_RESOLUTION_0P5_LX = 0b00100001, // one-time high resolution mode 2 }; /// This class implements support for the i2c-based BH1750 ambient light sensor. class BH1750Sensor : public PollingSensorComponent, public I2CDevice { public: - BH1750Sensor(I2CComponent *parent, const std::string &name, - uint8_t address = 0x23, uint32_t update_interval = 60000); + BH1750Sensor(I2CComponent *parent, const std::string &name, uint8_t address = 0x23, uint32_t update_interval = 60000); /** Set the resolution of this sensor. * @@ -53,10 +52,10 @@ class BH1750Sensor : public PollingSensorComponent, public I2CDevice { BH1750Resolution resolution_{BH1750_RESOLUTION_0P5_LX}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BH1750 +#endif // USE_BH1750 -#endif //ESPHOME_SENSOR_BH1750_SENSOR_H +#endif // ESPHOME_SENSOR_BH1750_SENSOR_H diff --git a/src/esphome/sensor/bme280_component.cpp b/src/esphome/sensor/bme280_component.cpp index 5a8da7ab..1901e59f 100644 --- a/src/esphome/sensor/bme280_component.cpp +++ b/src/esphome/sensor/bme280_component.cpp @@ -52,37 +52,48 @@ static const uint8_t BME280_MODE_FORCED = 0b01; inline uint16_t combine_bytes(uint8_t msb, uint8_t lsb) { return ((msb & 0xFF) << 8) | (lsb & 0xFF); } -BME280Component::BME280Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, - const std::string &humidity_name, - uint8_t address, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, address), +BME280Component::BME280Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &pressure_name, const std::string &humidity_name, uint8_t address, + uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, address), temperature_sensor_(new BME280TemperatureSensor(temperature_name, this)), pressure_sensor_(new BME280PressureSensor(pressure_name, this)), - humidity_sensor_(new BME280HumiditySensor(humidity_name, this)) { + humidity_sensor_(new BME280HumiditySensor(humidity_name, this)) {} -} - -static const char* oversampling_to_str(BME280Oversampling oversampling) { +static const char *oversampling_to_str(BME280Oversampling oversampling) { switch (oversampling) { - case BME280_OVERSAMPLING_NONE: return "None"; - case BME280_OVERSAMPLING_1X: return "1x"; - case BME280_OVERSAMPLING_2X: return "2x"; - case BME280_OVERSAMPLING_4X: return "4x"; - case BME280_OVERSAMPLING_8X: return "8x"; - case BME280_OVERSAMPLING_16X: return "16x"; - default: return "UNKNOWN"; + case BME280_OVERSAMPLING_NONE: + return "None"; + case BME280_OVERSAMPLING_1X: + return "1x"; + case BME280_OVERSAMPLING_2X: + return "2x"; + case BME280_OVERSAMPLING_4X: + return "4x"; + case BME280_OVERSAMPLING_8X: + return "8x"; + case BME280_OVERSAMPLING_16X: + return "16x"; + default: + return "UNKNOWN"; } } -static const char* iir_filter_to_str(BME280IIRFilter filter) { +static const char *iir_filter_to_str(BME280IIRFilter filter) { switch (filter) { - case BME280_IIR_FILTER_OFF: return "OFF"; - case BME280_IIR_FILTER_2X: return "2x"; - case BME280_IIR_FILTER_4X: return "4x"; - case BME280_IIR_FILTER_8X: return "8x"; - case BME280_IIR_FILTER_16X: return "16x"; - default: return "UNKNOWN"; + case BME280_IIR_FILTER_OFF: + return "OFF"; + case BME280_IIR_FILTER_2X: + return "2x"; + case BME280_IIR_FILTER_4X: + return "4x"; + case BME280_IIR_FILTER_8X: + return "8x"; + case BME280_IIR_FILTER_16X: + return "16x"; + default: + return "UNKNOWN"; } } @@ -101,26 +112,26 @@ void BME280Component::setup() { } // Read calibration - this->calibration_.t1 = read_u16_le(BME280_REGISTER_DIG_T1); - this->calibration_.t2 = read_s16_le(BME280_REGISTER_DIG_T2); - this->calibration_.t3 = read_s16_le(BME280_REGISTER_DIG_T3); - - this->calibration_.p1 = read_u16_le(BME280_REGISTER_DIG_P1); - this->calibration_.p2 = read_s16_le(BME280_REGISTER_DIG_P2); - this->calibration_.p3 = read_s16_le(BME280_REGISTER_DIG_P3); - this->calibration_.p4 = read_s16_le(BME280_REGISTER_DIG_P4); - this->calibration_.p5 = read_s16_le(BME280_REGISTER_DIG_P5); - this->calibration_.p6 = read_s16_le(BME280_REGISTER_DIG_P6); - this->calibration_.p7 = read_s16_le(BME280_REGISTER_DIG_P7); - this->calibration_.p8 = read_s16_le(BME280_REGISTER_DIG_P8); - this->calibration_.p9 = read_s16_le(BME280_REGISTER_DIG_P9); - - this->calibration_.h1 = read_u8(BME280_REGISTER_DIG_H1); - this->calibration_.h2 = read_s16_le(BME280_REGISTER_DIG_H2); - this->calibration_.h3 = read_u8(BME280_REGISTER_DIG_H3); - this->calibration_.h4 = read_u8(BME280_REGISTER_DIG_H4) << 4 | (read_u8(BME280_REGISTER_DIG_H4 + 1) & 0x0F); - this->calibration_.h5 = read_u8(BME280_REGISTER_DIG_H5 + 1) << 4 | (read_u8(BME280_REGISTER_DIG_H5) >> 4); - this->calibration_.h6 = read_u8(BME280_REGISTER_DIG_H6); + this->calibration_.t1 = read_u16_le_(BME280_REGISTER_DIG_T1); + this->calibration_.t2 = read_s16_le_(BME280_REGISTER_DIG_T2); + this->calibration_.t3 = read_s16_le_(BME280_REGISTER_DIG_T3); + + this->calibration_.p1 = read_u16_le_(BME280_REGISTER_DIG_P1); + this->calibration_.p2 = read_s16_le_(BME280_REGISTER_DIG_P2); + this->calibration_.p3 = read_s16_le_(BME280_REGISTER_DIG_P3); + this->calibration_.p4 = read_s16_le_(BME280_REGISTER_DIG_P4); + this->calibration_.p5 = read_s16_le_(BME280_REGISTER_DIG_P5); + this->calibration_.p6 = read_s16_le_(BME280_REGISTER_DIG_P6); + this->calibration_.p7 = read_s16_le_(BME280_REGISTER_DIG_P7); + this->calibration_.p8 = read_s16_le_(BME280_REGISTER_DIG_P8); + this->calibration_.p9 = read_s16_le_(BME280_REGISTER_DIG_P9); + + this->calibration_.h1 = read_u8_(BME280_REGISTER_DIG_H1); + this->calibration_.h2 = read_s16_le_(BME280_REGISTER_DIG_H2); + this->calibration_.h3 = read_u8_(BME280_REGISTER_DIG_H3); + this->calibration_.h4 = read_u8_(BME280_REGISTER_DIG_H4) << 4 | (read_u8_(BME280_REGISTER_DIG_H4 + 1) & 0x0F); + this->calibration_.h5 = read_u8_(BME280_REGISTER_DIG_H5 + 1) << 4 | (read_u8_(BME280_REGISTER_DIG_H5) >> 4); + this->calibration_.h6 = read_u8_(BME280_REGISTER_DIG_H6); uint8_t humid_register = 0; if (!this->read_byte(BME280_REGISTER_CONTROLHUMID, &humid_register)) { @@ -140,7 +151,7 @@ void BME280Component::setup() { return; } config_register &= ~0b11111100; - config_register |= 0b000 << 5; // 0.5 ms standby time + config_register |= 0b000 << 5; // 0.5 ms standby time config_register |= (this->iir_filter_ & 0b111) << 2; if (!this->write_byte(BME280_REGISTER_CONFIG, config_register)) { this->mark_failed(); @@ -171,13 +182,9 @@ void BME280Component::dump_config() { LOG_SENSOR(" ", "Humidity", this->humidity_sensor_); ESP_LOGCONFIG(TAG, " Oversampling: %s", oversampling_to_str(this->humidity_oversampling_)); } -float BME280Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float BME280Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -inline uint8_t oversampling_to_time(BME280Oversampling over_sampling) { - return (1 << uint8_t(over_sampling)) >> 1; -} +inline uint8_t oversampling_to_time(BME280Oversampling over_sampling) { return (1 << uint8_t(over_sampling)) >> 1; } void BME280Component::update() { // Enable sensor @@ -185,7 +192,7 @@ void BME280Component::update() { uint8_t meas_register = 0; meas_register |= (this->temperature_oversampling_ & 0b111) << 5; meas_register |= (this->pressure_oversampling_ & 0b111) << 2; - meas_register |= 0b01; // Forced mode + meas_register |= 0b01; // Forced mode if (!this->write_byte(BME280_REGISTER_CONTROL, meas_register)) { this->status_set_warning(); return; @@ -207,8 +214,7 @@ void BME280Component::update() { float pressure = this->read_pressure_(t_fine); float humidity = this->read_humidity_(t_fine); - ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa humidity=%.1f%%", - temperature, pressure, humidity); + ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa humidity=%.1f%%", temperature, pressure, humidity); this->temperature_sensor_->publish_state(temperature); this->pressure_sensor_->publish_state(pressure); this->humidity_sensor_->publish_state(humidity); @@ -292,9 +298,8 @@ float BME280Component::read_humidity_(int32_t t_fine) { int32_t v_x1_u32r = t_fine - 76800; - v_x1_u32r = ((((adc << 14) - (h4 << 20) - - (h5 * v_x1_u32r)) + 16384) >> 15) * - (((((((v_x1_u32r * h6) >> 10) * (((v_x1_u32r * h3) >> 11) + 32768)) >> 10) + 2097152) * h2 + 8192) >> 14); + v_x1_u32r = ((((adc << 14) - (h4 << 20) - (h5 * v_x1_u32r)) + 16384) >> 15) * + (((((((v_x1_u32r * h6) >> 10) * (((v_x1_u32r * h3) >> 11) + 32768)) >> 10) + 2097152) * h2 + 8192) >> 14); v_x1_u32r = v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * h1) >> 4); @@ -304,15 +309,9 @@ float BME280Component::read_humidity_(int32_t t_fine) { return h / 1024.0f; } -BME280TemperatureSensor *BME280Component::get_temperature_sensor() const { - return this->temperature_sensor_; -} -BME280PressureSensor *BME280Component::get_pressure_sensor() const { - return this->pressure_sensor_; -} -BME280HumiditySensor *BME280Component::get_humidity_sensor() const { - return this->humidity_sensor_; -} +BME280TemperatureSensor *BME280Component::get_temperature_sensor() const { return this->temperature_sensor_; } +BME280PressureSensor *BME280Component::get_pressure_sensor() const { return this->pressure_sensor_; } +BME280HumiditySensor *BME280Component::get_humidity_sensor() const { return this->humidity_sensor_; } void BME280Component::set_temperature_oversampling(BME280Oversampling temperature_over_sampling) { this->temperature_oversampling_ = temperature_over_sampling; } @@ -322,25 +321,21 @@ void BME280Component::set_pressure_oversampling(BME280Oversampling pressure_over void BME280Component::set_humidity_oversampling(BME280Oversampling humidity_over_sampling) { this->humidity_oversampling_ = humidity_over_sampling; } -void BME280Component::set_iir_filter(BME280IIRFilter iir_filter) { - this->iir_filter_ = iir_filter; -} -uint8_t BME280Component::read_u8(uint8_t register_) { +void BME280Component::set_iir_filter(BME280IIRFilter iir_filter) { this->iir_filter_ = iir_filter; } +uint8_t BME280Component::read_u8_(uint8_t a_register) { uint8_t data = 0; - this->read_byte(register_, &data); + this->read_byte(a_register, &data); return data; } -uint16_t BME280Component::read_u16_le(uint8_t register_) { +uint16_t BME280Component::read_u16_le_(uint8_t a_register) { uint16_t data = 0; - this->read_byte_16(register_, &data); + this->read_byte_16(a_register, &data); return (data >> 8) | (data << 8); } -int16_t BME280Component::read_s16_le(uint8_t register_) { - return this->read_u16_le(register_); -} +int16_t BME280Component::read_s16_le_(uint8_t a_register) { return this->read_u16_le_(a_register); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BME280 +#endif // USE_BME280 diff --git a/src/esphome/sensor/bme280_component.h b/src/esphome/sensor/bme280_component.h index 6db2903d..bbe38bad 100644 --- a/src/esphome/sensor/bme280_component.h +++ b/src/esphome/sensor/bme280_component.h @@ -14,19 +14,19 @@ namespace sensor { /// Internal struct storing the calibration values of an BME280. struct BME280CalibrationData { - uint16_t t1; // 0x88 - 0x89 - int16_t t2; // 0x8A - 0x8B - int16_t t3; // 0x8C - 0x8D - - uint16_t p1; // 0x8E - 0x8F - int16_t p2; // 0x90 - 0x91 - int16_t p3; // 0x92 - 0x93 - int16_t p4; // 0x94 - 0x95 - int16_t p5; // 0x96 - 0x97 - int16_t p6; // 0x98 - 0x99 - int16_t p7; // 0x9A - 0x9B - int16_t p8; // 0x9C - 0x9D - int16_t p9; // 0x9E - 0x9F + uint16_t t1; // 0x88 - 0x89 + int16_t t2; // 0x8A - 0x8B + int16_t t3; // 0x8C - 0x8D + + uint16_t p1; // 0x8E - 0x8F + int16_t p2; // 0x90 - 0x91 + int16_t p3; // 0x92 - 0x93 + int16_t p4; // 0x94 - 0x95 + int16_t p5; // 0x96 - 0x97 + int16_t p6; // 0x98 - 0x99 + int16_t p7; // 0x9A - 0x9B + int16_t p8; // 0x9C - 0x9D + int16_t p9; // 0x9E - 0x9F uint8_t h1; // 0xA1 int16_t h2; // 0xE1 - 0xE2 @@ -69,10 +69,8 @@ using BME280HumiditySensor = sensor::EmptyPollingParentSensor<1, ICON_WATER_PERC /// This class implements support for the BME280 Temperature+Pressure+Humidity i2c sensor. class BME280Component : public PollingComponent, public I2CDevice { public: - BME280Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, - const std::string &humidity_name, - uint8_t address = 0x77, uint32_t update_interval = 60000); + BME280Component(I2CComponent *parent, const std::string &temperature_name, const std::string &pressure_name, + const std::string &humidity_name, uint8_t address = 0x77, uint32_t update_interval = 60000); /// Set the oversampling value for the temperature sensor. Default is 16x. void set_temperature_oversampling(BME280Oversampling temperature_over_sampling); @@ -101,9 +99,9 @@ class BME280Component : public PollingComponent, public I2CDevice { float read_pressure_(int32_t t_fine); /// Read the humidity value in % using the provided t_fine value. float read_humidity_(int32_t t_fine); - uint8_t read_u8(uint8_t register_); - uint16_t read_u16_le(uint8_t register_); - int16_t read_s16_le(uint8_t register_); + uint8_t read_u8_(uint8_t a_register); + uint16_t read_u16_le_(uint8_t a_register); + int16_t read_s16_le_(uint8_t a_register); BME280CalibrationData calibration_; BME280Oversampling temperature_oversampling_{BME280_OVERSAMPLING_16X}; @@ -120,10 +118,10 @@ class BME280Component : public PollingComponent, public I2CDevice { } error_code_{NONE}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BME280 +#endif // USE_BME280 -#endif //ESPHOME_SENSOR_BME280_COMPONENT_H +#endif // ESPHOME_SENSOR_BME280_COMPONENT_H diff --git a/src/esphome/sensor/bme680_component.cpp b/src/esphome/sensor/bme680_component.cpp index c494d27b..7b64d2dc 100644 --- a/src/esphome/sensor/bme680_component.cpp +++ b/src/esphome/sensor/bme680_component.cpp @@ -33,39 +33,51 @@ static const uint8_t BME680_REGISTER_CHIPID = 0xD0; static const uint8_t BME680_REGISTER_FIELD0 = 0x1D; -const float BME680_GAS_LOOKUP_TABLE_1[16] PROGMEM = { - 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -0.8, - 0.0, 0.0, -0.2, -0.5, 0.0, -1.0, 0.0, 0.0 -}; +const float BME680_GAS_LOOKUP_TABLE_1[16] PROGMEM = {0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -0.8, + 0.0, 0.0, -0.2, -0.5, 0.0, -1.0, 0.0, 0.0}; -const float BME680_GAS_LOOKUP_TABLE_2[16] PROGMEM = { - 0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.0, -0.8, - -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 -}; +const float BME680_GAS_LOOKUP_TABLE_2[16] PROGMEM = {0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.0, -0.8, + -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; -static const char* oversampling_to_str(BME680Oversampling oversampling) { +static const char *oversampling_to_str(BME680Oversampling oversampling) { switch (oversampling) { - case BME680_OVERSAMPLING_NONE: return "None"; - case BME680_OVERSAMPLING_1X: return "1x"; - case BME680_OVERSAMPLING_2X: return "2x"; - case BME680_OVERSAMPLING_4X: return "4x"; - case BME680_OVERSAMPLING_8X: return "8x"; - case BME680_OVERSAMPLING_16X: return "16x"; - default: return "UNKNOWN"; + case BME680_OVERSAMPLING_NONE: + return "None"; + case BME680_OVERSAMPLING_1X: + return "1x"; + case BME680_OVERSAMPLING_2X: + return "2x"; + case BME680_OVERSAMPLING_4X: + return "4x"; + case BME680_OVERSAMPLING_8X: + return "8x"; + case BME680_OVERSAMPLING_16X: + return "16x"; + default: + return "UNKNOWN"; } } -static const char* iir_filter_to_str(BME680IIRFilter filter) { +static const char *iir_filter_to_str(BME680IIRFilter filter) { switch (filter) { - case BME680_IIR_FILTER_OFF: return "OFF"; - case BME680_IIR_FILTER_1X: return "1x"; - case BME680_IIR_FILTER_3X: return "3x"; - case BME680_IIR_FILTER_7X: return "7x"; - case BME680_IIR_FILTER_15X: return "15x"; - case BME680_IIR_FILTER_31X: return "31x"; - case BME680_IIR_FILTER_63X: return "63x"; - case BME680_IIR_FILTER_127X: return "127x"; - default: return "UNKNOWN"; + case BME680_IIR_FILTER_OFF: + return "OFF"; + case BME680_IIR_FILTER_1X: + return "1x"; + case BME680_IIR_FILTER_3X: + return "3x"; + case BME680_IIR_FILTER_7X: + return "7x"; + case BME680_IIR_FILTER_15X: + return "15x"; + case BME680_IIR_FILTER_31X: + return "31x"; + case BME680_IIR_FILTER_63X: + return "63x"; + case BME680_IIR_FILTER_127X: + return "127x"; + default: + return "UNKNOWN"; } } @@ -129,7 +141,7 @@ void BME680Component::setup() { return; } - this->calibration_.ambient_temperature = 25; // prime ambient temperature + this->calibration_.ambient_temperature = 25; // prime ambient temperature // Config register uint8_t config_register; @@ -165,7 +177,7 @@ void BME680Component::setup() { } gas1_control &= ~0b00011111; gas1_control |= 1 << 4; - gas1_control |= 0; // profile 0 + gas1_control |= 0; // profile 0 if (!this->write_byte(BME680_REGISTER_CONTROL_GAS1, gas1_control)) { this->mark_failed(); return; @@ -223,33 +235,30 @@ void BME680Component::dump_config() { if (this->heater_duration_ == 0 || this->heater_temperature_ == 0) { ESP_LOGCONFIG(TAG, " Heater OFF"); } else { - ESP_LOGCONFIG(TAG, " Heater temperature=%u°C duration=%ums", - this->heater_temperature_, this->heater_duration_); + ESP_LOGCONFIG(TAG, " Heater temperature=%u°C duration=%ums", this->heater_temperature_, this->heater_duration_); } } -float BME680Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float BME680Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void BME680Component::update() { - uint8_t meas_control = 0; // No need to fetch, we're setting all fields + uint8_t meas_control = 0; // No need to fetch, we're setting all fields meas_control |= (this->temperature_oversampling_ & 0b111) << 5; meas_control |= (this->pressure_oversampling_ & 0b111) << 5; - meas_control |= 0b01; // forced mode + meas_control |= 0b01; // forced mode if (!this->write_byte(BME680_REGISTER_CONTROL_MEAS, meas_control)) { this->status_set_warning(); return; } - this->set_timeout("data", this->calc_meas_duration_(), [this]() { - this->read_data_(); - }); + this->set_timeout("data", this->calc_meas_duration_(), [this]() { this->read_data_(); }); } uint8_t BME680Component::calc_heater_resistance_(uint16_t temperature) { - if (temperature < 200) temperature = 200; - if (temperature > 400) temperature = 400; + if (temperature < 200) + temperature = 200; + if (temperature > 400) + temperature = 400; const uint8_t ambient_temperature = this->calibration_.ambient_temperature; const int8_t gh1 = this->calibration_.gh1; @@ -271,8 +280,8 @@ uint8_t BME680Component::calc_heater_resistance_(uint16_t temperature) { var3 = var1 + (var2 / 2); var4 = (var3 / (res_heat_range + 4)); var5 = (131 * res_heat_val) + 65536; - heatr_res_x100 = (int32_t) (((var4 / var5) - 250) * 34); - heatr_res = (uint8_t) ((heatr_res_x100 + 50) / 100); + heatr_res_x100 = (int32_t)(((var4 / var5) - 250) * 34); + heatr_res = (uint8_t)((heatr_res_x100 + 50) / 100); return heatr_res; } @@ -313,8 +322,8 @@ void BME680Component::read_data_() { gas_resistance = this->calc_gas_resistance_(raw_gas, gas_range); } - ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa humidity=%.1f%% gas_resistance=%.1fΩ", - temperature, pressure, humidity, gas_resistance); + ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa humidity=%.1f%% gas_resistance=%.1fΩ", temperature, pressure, + humidity, gas_resistance); this->temperature_sensor_->publish_state(temperature); this->pressure_sensor_->publish_state(pressure); this->humidity_sensor_->publish_state(humidity); @@ -411,8 +420,8 @@ float BME680Component::calc_humidity_(uint16_t raw_humidity) { temp_comp = tfine / 5120.0f; var1 = float(raw_humidity) - (h1 * 16.0f + ((h3 / 2.0f) * temp_comp)); - var2 = var1 * (((h2 / 262144.0f) * (1.0f + ((h4 / 16384.0f) * temp_comp) + - ((h5 / 1048576.0f) * temp_comp * temp_comp)))); + var2 = var1 * + (((h2 / 262144.0f) * (1.0f + ((h4 / 16384.0f) * temp_comp) + ((h5 / 1048576.0f) * temp_comp * temp_comp)))); var3 = h6 / 16384.0f; var4 = h7 / 2097152.0f; @@ -438,10 +447,10 @@ uint32_t BME680Component::calc_gas_resistance_(uint16_t raw_gas, uint8_t range) calc_gas_res = 1.0f / (var3 * 0.000000125f * float(1 << range) * (((float(raw_gas) - 512.0f) / var2) + 1.0f)); - return calc_gas_res; + return static_cast(calc_gas_res); } uint32_t BME680Component::calc_meas_duration_() { - uint32_t tph_dur; // Calculate in us + uint32_t tph_dur; // Calculate in us uint32_t meas_cycles; const uint8_t os_to_meas_cycles[6] = {0, 1, 2, 4, 8, 16}; @@ -451,44 +460,31 @@ uint32_t BME680Component::calc_meas_duration_() { /* TPH measurement duration */ tph_dur = meas_cycles * 1963u; - tph_dur += 477 * 4; // TPH switching duration - tph_dur += 477 * 5; // Gas measurement duration - tph_dur += 500; // Get it to the closest whole number. - tph_dur /= 1000; // Convert to ms + tph_dur += 477 * 4; // TPH switching duration + tph_dur += 477 * 5; // Gas measurement duration + tph_dur += 500; // Get it to the closest whole number. + tph_dur /= 1000; // Convert to ms - tph_dur += 1; // Wake up duration of 1ms + tph_dur += 1; // Wake up duration of 1ms /* The remaining time should be used for heating */ tph_dur += this->heater_duration_; return tph_dur; } -BME680Component::BME680Component(I2CComponent *parent, - const std::string &temperature_name, - const std::string &pressure_name, - const std::string &humidity_name, - const std::string &gas_resistance_name, - uint8_t address, - uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, address), +BME680Component::BME680Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &pressure_name, const std::string &humidity_name, + const std::string &gas_resistance_name, uint8_t address, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, address), temperature_sensor_(new BME680TemperatureSensor(temperature_name, this)), pressure_sensor_(new BME680PressureSensor(pressure_name, this)), humidity_sensor_(new BME680HumiditySensor(humidity_name, this)), - gas_resistance_sensor_(new BME680GasResistanceSensor(gas_resistance_name, this)) { - -} -BME680TemperatureSensor *BME680Component::get_temperature_sensor() const { - return this->temperature_sensor_; -} -BME680PressureSensor *BME680Component::get_pressure_sensor() const { - return this->pressure_sensor_; -} -BME680HumiditySensor *BME680Component::get_humidity_sensor() const { - return this->humidity_sensor_; -} -BME680GasResistanceSensor *BME680Component::get_gas_resistance_sensor() const { - return this->gas_resistance_sensor_; -} + gas_resistance_sensor_(new BME680GasResistanceSensor(gas_resistance_name, this)) {} +BME680TemperatureSensor *BME680Component::get_temperature_sensor() const { return this->temperature_sensor_; } +BME680PressureSensor *BME680Component::get_pressure_sensor() const { return this->pressure_sensor_; } +BME680HumiditySensor *BME680Component::get_humidity_sensor() const { return this->humidity_sensor_; } +BME680GasResistanceSensor *BME680Component::get_gas_resistance_sensor() const { return this->gas_resistance_sensor_; } void BME680Component::set_temperature_oversampling(BME680Oversampling temperature_oversampling) { this->temperature_oversampling_ = temperature_oversampling; } @@ -498,16 +494,14 @@ void BME680Component::set_pressure_oversampling(BME680Oversampling pressure_over void BME680Component::set_humidity_oversampling(BME680Oversampling humidity_oversampling) { this->humidity_oversampling_ = humidity_oversampling; } -void BME680Component::set_iir_filter(BME680IIRFilter iir_filter) { - this->iir_filter_ = iir_filter; -} +void BME680Component::set_iir_filter(BME680IIRFilter iir_filter) { this->iir_filter_ = iir_filter; } void BME680Component::set_heater(uint16_t heater_temperature, uint16_t heater_duration) { this->heater_temperature_ = heater_temperature; this->heater_duration_ = heater_duration; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BME680 +#endif // USE_BME680 diff --git a/src/esphome/sensor/bme680_component.h b/src/esphome/sensor/bme680_component.h index e42df511..e6d1ec1a 100644 --- a/src/esphome/sensor/bme680_component.h +++ b/src/esphome/sensor/bme680_component.h @@ -81,10 +81,9 @@ using BME680GasResistanceSensor = sensor::EmptyPollingParentSensor<1, ICON_GAS_C class BME680Component : public PollingComponent, public I2CDevice { public: - BME680Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, - const std::string &humidity_name, const std::string &gas_resistance_name, - uint8_t address = 0x76, uint32_t update_interval = 60000); + BME680Component(I2CComponent *parent, const std::string &temperature_name, const std::string &pressure_name, + const std::string &humidity_name, const std::string &gas_resistance_name, uint8_t address = 0x76, + uint32_t update_interval = 60000); /// Set the temperature oversampling value. Defaults to 16X. void set_temperature_oversampling(BME680Oversampling temperature_oversampling); @@ -151,10 +150,10 @@ class BME680Component : public PollingComponent, public I2CDevice { BME680GasResistanceSensor *gas_resistance_sensor_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BME680 +#endif // USE_BME680 -#endif //ESPHOME_SENSOR_BME680_COMPONENT_H +#endif // ESPHOME_SENSOR_BME680_COMPONENT_H diff --git a/src/esphome/sensor/bmp085_component.cpp b/src/esphome/sensor/bmp085_component.cpp index de03a4ee..72f78bec 100644 --- a/src/esphome/sensor/bmp085_component.cpp +++ b/src/esphome/sensor/bmp085_component.cpp @@ -62,14 +62,12 @@ void BMP085Component::dump_config() { LOG_SENSOR(" ", "Temperature", this->temperature_); LOG_SENSOR(" ", "Pressure", this->pressure_); } -BMP085Component::BMP085Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, - uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, BMP085_ADDRESS), +BMP085Component::BMP085Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &pressure_name, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, BMP085_ADDRESS), temperature_(new BMP085TemperatureSensor(temperature_name, this)), - pressure_(new BMP085PressureSensor(pressure_name, this)) { - -} + pressure_(new BMP085PressureSensor(pressure_name, this)) {} void BMP085Component::read_temperature_() { uint8_t buffer[2]; @@ -145,22 +143,16 @@ void BMP085Component::read_pressure_() { this->pressure_->publish_state(pressure); this->status_clear_warning(); } -BMP085TemperatureSensor *BMP085Component::get_temperature_sensor() const { - return this->temperature_; -} -BMP085PressureSensor *BMP085Component::get_pressure_sensor() const { - return this->pressure_; -} +BMP085TemperatureSensor *BMP085Component::get_temperature_sensor() const { return this->temperature_; } +BMP085PressureSensor *BMP085Component::get_pressure_sensor() const { return this->pressure_; } bool BMP085Component::set_mode_(uint8_t mode) { ESP_LOGV(TAG, "Setting mode to 0x%02X...", mode); return this->write_byte(BMP085_REGISTER_CONTROL, mode); } -float BMP085Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float BMP085Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BMP085_SENSOR +#endif // USE_BMP085_SENSOR diff --git a/src/esphome/sensor/bmp085_component.h b/src/esphome/sensor/bmp085_component.h index caf6bf3c..367e72e9 100644 --- a/src/esphome/sensor/bmp085_component.h +++ b/src/esphome/sensor/bmp085_component.h @@ -23,8 +23,7 @@ using BMP085PressureSensor = sensor::EmptyPollingParentSensor<1, ICON_GAUGE, UNI class BMP085Component : public PollingComponent, public I2CDevice { public: /// Construct the BMP085Component using the provided address and update interval. - BMP085Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, + BMP085Component(I2CComponent *parent, const std::string &temperature_name, const std::string &pressure_name, uint32_t update_interval = 30000); // ========== INTERNAL METHODS ========== @@ -63,10 +62,10 @@ class BMP085Component : public PollingComponent, public I2CDevice { CalibrationData calibration_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BMP085_SENSOR +#endif // USE_BMP085_SENSOR -#endif //ESPHOME_SENSOR_BMP085_COMPONENT_H +#endif // ESPHOME_SENSOR_BMP085_COMPONENT_H diff --git a/src/esphome/sensor/bmp280_component.cpp b/src/esphome/sensor/bmp280_component.cpp index e0b7b6dd..c763da88 100644 --- a/src/esphome/sensor/bmp280_component.cpp +++ b/src/esphome/sensor/bmp280_component.cpp @@ -27,35 +27,46 @@ static const uint8_t BMP280_MODE_FORCED = 0b01; inline uint16_t combine_bytes(uint8_t msb, uint8_t lsb) { return ((msb & 0xFF) << 8) | (lsb & 0xFF); } -BMP280Component::BMP280Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, - uint8_t address, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, address), +BMP280Component::BMP280Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &pressure_name, uint8_t address, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, address), temperature_sensor_(new BMP280TemperatureSensor(temperature_name, this)), - pressure_sensor_(new BMP280PressureSensor(pressure_name, this)) { + pressure_sensor_(new BMP280PressureSensor(pressure_name, this)) {} -} - -static const char* oversampling_to_str(BMP280Oversampling oversampling) { +static const char *oversampling_to_str(BMP280Oversampling oversampling) { switch (oversampling) { - case BMP280_OVERSAMPLING_NONE: return "None"; - case BMP280_OVERSAMPLING_1X: return "1x"; - case BMP280_OVERSAMPLING_2X: return "2x"; - case BMP280_OVERSAMPLING_4X: return "4x"; - case BMP280_OVERSAMPLING_8X: return "8x"; - case BMP280_OVERSAMPLING_16X: return "16x"; - default: return "UNKNOWN"; + case BMP280_OVERSAMPLING_NONE: + return "None"; + case BMP280_OVERSAMPLING_1X: + return "1x"; + case BMP280_OVERSAMPLING_2X: + return "2x"; + case BMP280_OVERSAMPLING_4X: + return "4x"; + case BMP280_OVERSAMPLING_8X: + return "8x"; + case BMP280_OVERSAMPLING_16X: + return "16x"; + default: + return "UNKNOWN"; } } -static const char* iir_filter_to_str(BMP280IIRFilter filter) { +static const char *iir_filter_to_str(BMP280IIRFilter filter) { switch (filter) { - case BMP280_IIR_FILTER_OFF: return "OFF"; - case BMP280_IIR_FILTER_2X: return "2x"; - case BMP280_IIR_FILTER_4X: return "4x"; - case BMP280_IIR_FILTER_8X: return "8x"; - case BMP280_IIR_FILTER_16X: return "16x"; - default: return "UNKNOWN"; + case BMP280_IIR_FILTER_OFF: + return "OFF"; + case BMP280_IIR_FILTER_2X: + return "2x"; + case BMP280_IIR_FILTER_4X: + return "4x"; + case BMP280_IIR_FILTER_8X: + return "8x"; + case BMP280_IIR_FILTER_16X: + return "16x"; + default: + return "UNKNOWN"; } } @@ -74,19 +85,19 @@ void BMP280Component::setup() { } // Read calibration - this->calibration_.t1 = read_u16_le(0x88); - this->calibration_.t2 = read_s16_le(0x8A); - this->calibration_.t3 = read_s16_le(0x8C); - - this->calibration_.p1 = read_u16_le(0x8E); - this->calibration_.p2 = read_s16_le(0x90); - this->calibration_.p3 = read_s16_le(0x92); - this->calibration_.p4 = read_s16_le(0x94); - this->calibration_.p5 = read_s16_le(0x96); - this->calibration_.p6 = read_s16_le(0x98); - this->calibration_.p7 = read_s16_le(0x9A); - this->calibration_.p8 = read_s16_le(0x9C); - this->calibration_.p9 = read_s16_le(0x9E); + this->calibration_.t1 = this->read_u16_le_(0x88); + this->calibration_.t2 = this->read_s16_le_(0x8A); + this->calibration_.t3 = this->read_s16_le_(0x8C); + + this->calibration_.p1 = this->read_u16_le_(0x8E); + this->calibration_.p2 = this->read_s16_le_(0x90); + this->calibration_.p3 = this->read_s16_le_(0x92); + this->calibration_.p4 = this->read_s16_le_(0x94); + this->calibration_.p5 = this->read_s16_le_(0x96); + this->calibration_.p6 = this->read_s16_le_(0x98); + this->calibration_.p7 = this->read_s16_le_(0x9A); + this->calibration_.p8 = this->read_s16_le_(0x9C); + this->calibration_.p9 = this->read_s16_le_(0x9E); uint8_t config_register = 0; if (!this->read_byte(BMP280_REGISTER_CONFIG, &config_register)) { @@ -94,7 +105,7 @@ void BMP280Component::setup() { return; } config_register &= ~0b11111100; - config_register |= 0b000 << 5; // 0.5 ms standby time + config_register |= 0b000 << 5; // 0.5 ms standby time config_register |= (this->iir_filter_ & 0b111) << 2; if (!this->write_byte(BMP280_REGISTER_CONFIG, config_register)) { this->mark_failed(); @@ -123,13 +134,9 @@ void BMP280Component::dump_config() { LOG_SENSOR(" ", "Pressure", this->pressure_sensor_); ESP_LOGCONFIG(TAG, " Oversampling: %s", oversampling_to_str(this->pressure_oversampling_)); } -float BMP280Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float BMP280Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -inline uint8_t oversampling_to_time(BMP280Oversampling over_sampling) { - return (1 << uint8_t(over_sampling)) >> 1; -} +inline uint8_t oversampling_to_time(BMP280Oversampling over_sampling) { return (1 << uint8_t(over_sampling)) >> 1; } void BMP280Component::update() { // Enable sensor @@ -137,7 +144,7 @@ void BMP280Component::update() { uint8_t meas_register = 0; meas_register |= (this->temperature_oversampling_ & 0b111) << 5; meas_register |= (this->pressure_oversampling_ & 0b111) << 2; - meas_register |= 0b01; // Forced mode + meas_register |= 0b01; // Forced mode if (!this->write_byte(BMP280_REGISTER_CONTROL, meas_register)) { this->status_set_warning(); return; @@ -157,8 +164,7 @@ void BMP280Component::update() { } float pressure = this->read_pressure_(t_fine); - ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa", - temperature, pressure); + ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa", temperature, pressure); this->temperature_sensor_->publish_state(temperature); this->pressure_sensor_->publish_state(pressure); this->status_clear_warning(); @@ -225,37 +231,29 @@ float BMP280Component::read_pressure_(int32_t t_fine) { p = ((p + var1 + var2) >> 8) + (p7 << 4); return (p / 256.0f) / 100.0f; } -BMP280TemperatureSensor *BMP280Component::get_temperature_sensor() const { - return this->temperature_sensor_; -} -BMP280PressureSensor *BMP280Component::get_pressure_sensor() const { - return this->pressure_sensor_; -} +BMP280TemperatureSensor *BMP280Component::get_temperature_sensor() const { return this->temperature_sensor_; } +BMP280PressureSensor *BMP280Component::get_pressure_sensor() const { return this->pressure_sensor_; } void BMP280Component::set_temperature_oversampling(BMP280Oversampling temperature_over_sampling) { this->temperature_oversampling_ = temperature_over_sampling; } void BMP280Component::set_pressure_oversampling(BMP280Oversampling pressure_over_sampling) { this->pressure_oversampling_ = pressure_over_sampling; } -void BMP280Component::set_iir_filter(BMP280IIRFilter iir_filter) { - this->iir_filter_ = iir_filter; -} -uint8_t BMP280Component::read_u8(uint8_t register_) { +void BMP280Component::set_iir_filter(BMP280IIRFilter iir_filter) { this->iir_filter_ = iir_filter; } +uint8_t BMP280Component::read_u8_(uint8_t a_register) { uint8_t data = 0; - this->read_byte(register_, &data); + this->read_byte(a_register, &data); return data; } -uint16_t BMP280Component::read_u16_le(uint8_t register_) { +uint16_t BMP280Component::read_u16_le_(uint8_t a_register) { uint16_t data = 0; - this->read_byte_16(register_, &data); + this->read_byte_16(a_register, &data); return (data >> 8) | (data << 8); } -int16_t BMP280Component::read_s16_le(uint8_t register_) { - return this->read_u16_le(register_); -} +int16_t BMP280Component::read_s16_le_(uint8_t a_register) { return this->read_u16_le_(a_register); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BMP280 +#endif // USE_BMP280 diff --git a/src/esphome/sensor/bmp280_component.h b/src/esphome/sensor/bmp280_component.h index 8b8edddf..1c5856d3 100644 --- a/src/esphome/sensor/bmp280_component.h +++ b/src/esphome/sensor/bmp280_component.h @@ -14,19 +14,19 @@ namespace sensor { /// Internal struct storing the calibration values of an BMP280. struct BMP280CalibrationData { - uint16_t t1; // 0x88 - 0x89 - int16_t t2; // 0x8A - 0x8B - int16_t t3; // 0x8C - 0x8D - - uint16_t p1; // 0x8E - 0x8F - int16_t p2; // 0x90 - 0x91 - int16_t p3; // 0x92 - 0x93 - int16_t p4; // 0x94 - 0x95 - int16_t p5; // 0x96 - 0x97 - int16_t p6; // 0x98 - 0x99 - int16_t p7; // 0x9A - 0x9B - int16_t p8; // 0x9C - 0x9D - int16_t p9; // 0x9E - 0x9F + uint16_t t1; // 0x88 - 0x89 + int16_t t2; // 0x8A - 0x8B + int16_t t3; // 0x8C - 0x8D + + uint16_t p1; // 0x8E - 0x8F + int16_t p2; // 0x90 - 0x91 + int16_t p3; // 0x92 - 0x93 + int16_t p4; // 0x94 - 0x95 + int16_t p5; // 0x96 - 0x97 + int16_t p6; // 0x98 - 0x99 + int16_t p7; // 0x9A - 0x9B + int16_t p8; // 0x9C - 0x9D + int16_t p9; // 0x9E - 0x9F }; /** Enum listing all Oversampling values for the BMP280. @@ -61,8 +61,7 @@ using BMP280PressureSensor = sensor::EmptyPollingParentSensor<1, ICON_GAUGE, UNI /// This class implements support for the BMP280 Temperature+Pressure i2c sensor. class BMP280Component : public PollingComponent, public I2CDevice { public: - BMP280Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &pressure_name, + BMP280Component(I2CComponent *parent, const std::string &temperature_name, const std::string &pressure_name, uint8_t address = 0x77, uint32_t update_interval = 60000); /// Set the oversampling value for the temperature sensor. Default is 16x. @@ -87,9 +86,9 @@ class BMP280Component : public PollingComponent, public I2CDevice { float read_temperature_(int32_t *t_fine); /// Read the pressure value in hPa using the provided t_fine value. float read_pressure_(int32_t t_fine); - uint8_t read_u8(uint8_t register_); - uint16_t read_u16_le(uint8_t register_); - int16_t read_s16_le(uint8_t register_); + uint8_t read_u8_(uint8_t a_register); + uint16_t read_u16_le_(uint8_t a_register); + int16_t read_s16_le_(uint8_t a_register); BMP280CalibrationData calibration_; BMP280Oversampling temperature_oversampling_{BMP280_OVERSAMPLING_16X}; @@ -104,10 +103,10 @@ class BMP280Component : public PollingComponent, public I2CDevice { } error_code_{NONE}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_BMP280 +#endif // USE_BMP280 -#endif //ESPHOME_SENSOR_BMP280_COMPONENT_H +#endif // ESPHOME_SENSOR_BMP280_COMPONENT_H diff --git a/src/esphome/sensor/cse7766.cpp b/src/esphome/sensor/cse7766.cpp index e00fdec5..f8c6b3df 100644 --- a/src/esphome/sensor/cse7766.cpp +++ b/src/esphome/sensor/cse7766.cpp @@ -38,9 +38,7 @@ void CSE7766Component::loop() { this->raw_data_index_ = (this->raw_data_index_ + 1) % 24; } } -float CSE7766Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float CSE7766Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } bool CSE7766Component::check_byte_() { uint8_t index = this->raw_data_index_; uint8_t byte = this->raw_data_[index]; @@ -102,19 +100,19 @@ bool CSE7766Component::check_byte_() { void CSE7766Component::parse_data_() { ESP_LOGVV(TAG, "CSE7766 Data: "); for (uint8_t i = 0; i < 23; i++) { - ESP_LOGVV(TAG, " i=%u: 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", - i, BYTE_TO_BINARY(this->raw_data_[i]), this->raw_data_[i]); + ESP_LOGVV(TAG, " i=%u: 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", i, BYTE_TO_BINARY(this->raw_data_[i]), + this->raw_data_[i]); } const uint32_t now = micros(); const float d = (now - this->last_reading_) / 1000.0f; this->last_reading_ = now; - uint32_t voltage_calib = this->get_24_bit_uint(2); - uint32_t voltage_cycle = this->get_24_bit_uint(5); - uint32_t current_calib = this->get_24_bit_uint(8); - uint32_t current_cycle = this->get_24_bit_uint(11); - uint32_t power_calib = this->get_24_bit_uint(14); - uint32_t power_cycle = this->get_24_bit_uint(17); + uint32_t voltage_calib = this->get_24_bit_uint_(2); + uint32_t voltage_cycle = this->get_24_bit_uint_(5); + uint32_t current_calib = this->get_24_bit_uint_(8); + uint32_t current_cycle = this->get_24_bit_uint_(11); + uint32_t power_calib = this->get_24_bit_uint_(14); + uint32_t power_cycle = this->get_24_bit_uint_(17); uint8_t adj = this->raw_data_[20]; @@ -143,8 +141,7 @@ void CSE7766Component::update() { float voltage = this->voltage_acc_ / d; float current = this->current_acc_ / d; float power = this->power_acc_ / d; - ESP_LOGD(TAG, "Got voltage=%.1fV current=%.1fA power=%.1fW", - voltage, current, power); + ESP_LOGD(TAG, "Got voltage=%.1fV current=%.1fA power=%.1fW", voltage, current, power); if (this->voltage_ != nullptr) this->voltage_->publish_state(voltage); @@ -159,16 +156,13 @@ void CSE7766Component::setup() { this->last_reading_ = micros(); this->last_update_ = millis(); } -uint32_t CSE7766Component::get_24_bit_uint(uint8_t start_index) { - return (uint32_t(this->raw_data_[start_index]) << 16) | - (uint32_t(this->raw_data_[start_index + 1]) << 8) | - uint32_t(this->raw_data_[start_index + 2]); +uint32_t CSE7766Component::get_24_bit_uint_(uint8_t start_index) { + return (uint32_t(this->raw_data_[start_index]) << 16) | (uint32_t(this->raw_data_[start_index + 1]) << 8) | + uint32_t(this->raw_data_[start_index + 2]); } CSE7766Component::CSE7766Component(UARTComponent *parent, uint32_t update_interval) - : UARTDevice(parent), PollingComponent(update_interval) { - -} + : UARTDevice(parent), PollingComponent(update_interval) {} CSE7766VoltageSensor *CSE7766Component::make_voltage_sensor(const std::string &name) { return this->voltage_ = new CSE7766VoltageSensor(name); } @@ -186,8 +180,8 @@ void CSE7766Component::dump_config() { LOG_SENSOR(" ", "Power", this->power_); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_CSE7766 +#endif // USE_CSE7766 diff --git a/src/esphome/sensor/cse7766.h b/src/esphome/sensor/cse7766.h index d6063368..01d7d70f 100644 --- a/src/esphome/sensor/cse7766.h +++ b/src/esphome/sensor/cse7766.h @@ -37,7 +37,7 @@ class CSE7766Component : public PollingComponent, public UARTDevice { protected: bool check_byte_(); void parse_data_(); - uint32_t get_24_bit_uint(uint8_t start_index); + uint32_t get_24_bit_uint_(uint8_t start_index); uint8_t raw_data_[24]; uint8_t raw_data_index_{0}; @@ -52,10 +52,10 @@ class CSE7766Component : public PollingComponent, public UARTDevice { uint32_t last_update_{0}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_CSE7766 +#endif // USE_CSE7766 -#endif //ESPHOME_SENSOR_CSE7766_H +#endif // ESPHOME_SENSOR_CSE7766_H diff --git a/src/esphome/sensor/custom_sensor.cpp b/src/esphome/sensor/custom_sensor.cpp index 283f454c..60839aa7 100644 --- a/src/esphome/sensor/custom_sensor.cpp +++ b/src/esphome/sensor/custom_sensor.cpp @@ -14,17 +14,15 @@ static const char *TAG = "sensor.custom"; CustomSensorConstructor::CustomSensorConstructor(const std::function()> &init) { this->sensors_ = init(); } -Sensor *CustomSensorConstructor::get_sensor(int i) { - return this->sensors_[i]; -} +Sensor *CustomSensorConstructor::get_sensor(int i) { return this->sensors_[i]; } void CustomSensorConstructor::dump_config() { for (auto *child : this->sensors_) { LOG_SENSOR("", "Custom Sensor", child); } } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_SENSOR +#endif // USE_CUSTOM_SENSOR diff --git a/src/esphome/sensor/custom_sensor.h b/src/esphome/sensor/custom_sensor.h index 894004fd..be683e46 100644 --- a/src/esphome/sensor/custom_sensor.h +++ b/src/esphome/sensor/custom_sensor.h @@ -24,10 +24,10 @@ class CustomSensorConstructor : public Component { std::vector sensors_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_SENSOR +#endif // USE_CUSTOM_SENSOR -#endif //ESPHOME_SENSOR_CUSTOM_SENSOR_H +#endif // ESPHOME_SENSOR_CUSTOM_SENSOR_H diff --git a/src/esphome/sensor/dallas_component.cpp b/src/esphome/sensor/dallas_component.cpp index ac4ce338..f32b54e4 100644 --- a/src/esphome/sensor/dallas_component.cpp +++ b/src/esphome/sensor/dallas_component.cpp @@ -25,18 +25,20 @@ static const uint8_t DALLAS_COMMAND_START_CONVERSION = 0x44; static const uint8_t DALLAS_COMMAND_READ_SCRATCH_PAD = 0xBE; static const uint8_t DALLAS_COMMAND_WRITE_SCRATCH_PAD = 0x4E; -uint16_t DallasTemperatureSensor::millis_to_wait_for_conversion_() const { +uint16_t DallasTemperatureSensor::millis_to_wait_for_conversion() const { switch (this->resolution_) { - case 9:return 94; - case 10:return 188; - case 11:return 375; - default:return 750; + case 9: + return 94; + case 10: + return 188; + case 11: + return 375; + default: + return 750; } } -void DallasComponent::set_one_wire(ESPOneWire *one_wire) { - this->one_wire_ = one_wire; -} +void DallasComponent::set_one_wire(ESPOneWire *one_wire) { this->one_wire_ = one_wire; } void DallasComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up DallasComponent..."); @@ -70,7 +72,7 @@ void DallasComponent::setup() { sensor->set_address(this->found_sensors_[*sensor->get_index()]); } - if (!sensor->setup_sensor_()) { + if (!sensor->setup_sensor()) { this->status_set_error(); } } @@ -104,17 +106,15 @@ void DallasComponent::dump_config() { } } -DallasTemperatureSensor *DallasComponent::get_sensor_by_address(const std::string &name, - uint64_t address, uint8_t resolution) { +DallasTemperatureSensor *DallasComponent::get_sensor_by_address(const std::string &name, uint64_t address, + uint8_t resolution) { auto s = new DallasTemperatureSensor(name, address, resolution, this); this->sensors_.push_back(s); return s; } -float DallasComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -DallasTemperatureSensor *DallasComponent::get_sensor_by_index(const std::string &name, - uint8_t index, uint8_t resolution) { +float DallasComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +DallasTemperatureSensor *DallasComponent::get_sensor_by_index(const std::string &name, uint8_t index, + uint8_t resolution) { auto s = this->get_sensor_by_address(name, 0, resolution); s->set_index(index); return s; @@ -140,16 +140,16 @@ void DallasComponent::update() { } for (auto *sensor : this->sensors_) { - this->set_timeout(sensor->get_address_name(), sensor->millis_to_wait_for_conversion_(), [this, sensor] { + this->set_timeout(sensor->get_address_name(), sensor->millis_to_wait_for_conversion(), [this, sensor] { disable_interrupts(); - bool res = sensor->read_scratch_pad_(); + bool res = sensor->read_scratch_pad(); enable_interrupts(); if (!res) { this->status_set_warning(); return; } - if (!sensor->check_scratch_pad_()) { + if (!sensor->check_scratch_pad()) { this->status_set_warning(); return; } @@ -161,41 +161,22 @@ void DallasComponent::update() { } } DallasComponent::DallasComponent(ESPOneWire *one_wire, uint32_t update_interval) - : PollingComponent(update_interval), one_wire_(one_wire) { + : PollingComponent(update_interval), one_wire_(one_wire) {} +ESPOneWire *DallasComponent::get_one_wire() const { return this->one_wire_; } -} -ESPOneWire *DallasComponent::get_one_wire() const { - return this->one_wire_; -} - -DallasTemperatureSensor::DallasTemperatureSensor(const std::string &name, - uint64_t address, uint8_t resolution, +DallasTemperatureSensor::DallasTemperatureSensor(const std::string &name, uint64_t address, uint8_t resolution, DallasComponent *parent) : EmptyPollingParentSensor(name, parent) { this->set_address(address); this->set_resolution(resolution); } -uint64_t DallasTemperatureSensor::get_address() const { - return this->address_; -} -void DallasTemperatureSensor::set_address(uint64_t address) { - this->address_ = address; -} -uint8_t DallasTemperatureSensor::get_resolution() const { - return this->resolution_; -} -void DallasTemperatureSensor::set_resolution(uint8_t resolution) { - this->resolution_ = resolution; -} -optional DallasTemperatureSensor::get_index() const { - return this->index_; -} -void DallasTemperatureSensor::set_index(uint8_t index) { - this->index_ = index; -} -uint8_t *DallasTemperatureSensor::get_address8() { - return reinterpret_cast(&this->address_); -} +uint64_t DallasTemperatureSensor::get_address() const { return this->address_; } +void DallasTemperatureSensor::set_address(uint64_t address) { this->address_ = address; } +uint8_t DallasTemperatureSensor::get_resolution() const { return this->resolution_; } +void DallasTemperatureSensor::set_resolution(uint8_t resolution) { this->resolution_ = resolution; } +optional DallasTemperatureSensor::get_index() const { return this->index_; } +void DallasTemperatureSensor::set_index(uint8_t index) { this->index_ = index; } +uint8_t *DallasTemperatureSensor::get_address8() { return reinterpret_cast(&this->address_); } const std::string &DallasTemperatureSensor::get_address_name() { if (this->address_name_.empty()) { this->address_name_ = std::string("0x") + uint64_to_string(this->address_); @@ -203,7 +184,7 @@ const std::string &DallasTemperatureSensor::get_address_name() { return this->address_name_; } -bool DallasTemperatureSensor::read_scratch_pad_() { +bool DallasTemperatureSensor::read_scratch_pad() { ESPOneWire *wire = this->parent_->get_one_wire(); if (!wire->reset()) { return false; @@ -217,16 +198,16 @@ bool DallasTemperatureSensor::read_scratch_pad_() { } return true; } -bool DallasTemperatureSensor::setup_sensor_() { +bool DallasTemperatureSensor::setup_sensor() { disable_interrupts(); - bool r = this->read_scratch_pad_(); + bool r = this->read_scratch_pad(); enable_interrupts(); if (!r) { ESP_LOGE(TAG, "Reading scratchpad failed: reset"); return false; } - if (!this->check_scratch_pad_()) + if (!this->check_scratch_pad()) return false; if (this->scratch_pad_[4] == this->resolution_) @@ -239,14 +220,18 @@ bool DallasTemperatureSensor::setup_sensor_() { } switch (this->resolution_) { - case 12:this->scratch_pad_[4] = 0x7F; + case 12: + this->scratch_pad_[4] = 0x7F; break; - case 11:this->scratch_pad_[4] = 0x5F; + case 11: + this->scratch_pad_[4] = 0x5F; break; - case 10:this->scratch_pad_[4] = 0x3F; + case 10: + this->scratch_pad_[4] = 0x3F; break; case 9: - default:this->scratch_pad_[4] = 0x1F; + default: + this->scratch_pad_[4] = 0x1F; break; } @@ -255,9 +240,9 @@ bool DallasTemperatureSensor::setup_sensor_() { if (wire->reset()) { wire->select(this->address_); wire->write8(DALLAS_COMMAND_WRITE_SCRATCH_PAD); - wire->write8(this->scratch_pad_[2]); // high alarm temp - wire->write8(this->scratch_pad_[3]); // low alarm temp - wire->write8(this->scratch_pad_[4]); // resolution + wire->write8(this->scratch_pad_[2]); // high alarm temp + wire->write8(this->scratch_pad_[3]); // low alarm temp + wire->write8(this->scratch_pad_[4]); // resolution wire->reset(); // write value to EEPROM @@ -270,12 +255,11 @@ bool DallasTemperatureSensor::setup_sensor_() { wire->reset(); return true; } -bool DallasTemperatureSensor::check_scratch_pad_() { +bool DallasTemperatureSensor::check_scratch_pad() { #ifdef ESPHOME_LOG_LEVEL_VERY_VERBOSE - ESP_LOGVV(TAG, "Scratch pad: %02X.%02X.%02X.%02X.%02X.%02X.%02X.%02X.%02X (%02X)", - this->scratch_pad_[0], this->scratch_pad_[1], this->scratch_pad_[2], - this->scratch_pad_[3], this->scratch_pad_[4], this->scratch_pad_[5], - this->scratch_pad_[6], this->scratch_pad_[7], this->scratch_pad_[8], + ESP_LOGVV(TAG, "Scratch pad: %02X.%02X.%02X.%02X.%02X.%02X.%02X.%02X.%02X (%02X)", this->scratch_pad_[0], + this->scratch_pad_[1], this->scratch_pad_[2], this->scratch_pad_[3], this->scratch_pad_[4], + this->scratch_pad_[5], this->scratch_pad_[6], this->scratch_pad_[7], this->scratch_pad_[8], crc8(this->scratch_pad_, 8)); #endif if (crc8(this->scratch_pad_, 8) != this->scratch_pad_[8]) { @@ -293,12 +277,10 @@ float DallasTemperatureSensor::get_temp_c() { return temp / 128.0f; } -std::string DallasTemperatureSensor::unique_id() { - return "dallas-" + uint64_to_string(this->address_); -} +std::string DallasTemperatureSensor::unique_id() { return "dallas-" + uint64_to_string(this->address_); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DALLAS_SENSOR +#endif // USE_DALLAS_SENSOR diff --git a/src/esphome/sensor/dallas_component.h b/src/esphome/sensor/dallas_component.h index b2871f01..4497b496 100644 --- a/src/esphome/sensor/dallas_component.h +++ b/src/esphome/sensor/dallas_component.h @@ -29,8 +29,7 @@ class DallasComponent : public PollingComponent { * @param resolution The resolution for this sensor, 8-12. * @return A pointer to a DallasTemperatureSensor, use this to setup MQTT. */ - DallasTemperatureSensor *get_sensor_by_address(const std::string &name, uint64_t address, - uint8_t resolution = 12); + DallasTemperatureSensor *get_sensor_by_address(const std::string &name, uint64_t address, uint8_t resolution = 12); /** Get a DallasTemperatureSensor by index. * * Note: It is recommended to use sensors by address to avoid mixing up sensor values @@ -40,8 +39,7 @@ class DallasComponent : public PollingComponent { * @param resolution The resolution for this sensor, 8-12. * @return A pointer to a DallasTemperatureSensor, use this to setup MQTT. */ - DallasTemperatureSensor *get_sensor_by_index(const std::string &name, uint8_t index, - uint8_t resolution = 12); + DallasTemperatureSensor *get_sensor_by_index(const std::string &name, uint8_t index, uint8_t resolution = 12); // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) @@ -94,29 +92,32 @@ class DallasTemperatureSensor : public EmptyPollingParentSensor<1, ICON_EMPTY, U /// Set the resolution for this sensor. void set_resolution(uint8_t resolution); /// Get the number of milliseconds we have to wait for the conversion phase. - uint16_t millis_to_wait_for_conversion_() const; + uint16_t millis_to_wait_for_conversion() const; - bool setup_sensor_(); - bool read_scratch_pad_(); + bool setup_sensor(); + bool read_scratch_pad(); - bool check_scratch_pad_(); + bool check_scratch_pad(); float get_temp_c(); std::string unique_id() override; + protected: uint64_t address_; optional index_; uint8_t resolution_; std::string address_name_; - uint8_t scratch_pad_[9] = {0,}; + uint8_t scratch_pad_[9] = { + 0, + }; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DALLAS_SENSOR +#endif // USE_DALLAS_SENSOR -#endif //ESPHOME_SENSOR_DALLAS_COMPONENT_H +#endif // ESPHOME_SENSOR_DALLAS_COMPONENT_H diff --git a/src/esphome/sensor/dht12_component.cpp b/src/esphome/sensor/dht12_component.cpp index 0c6b3d88..2bf0a9a2 100644 --- a/src/esphome/sensor/dht12_component.cpp +++ b/src/esphome/sensor/dht12_component.cpp @@ -17,14 +17,12 @@ static const char *TAG = "sensor.dht12"; static const uint8_t DHT12_I2C_ADDRESS = 0x5C; -DHT12Component::DHT12Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, - uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, DHT12_I2C_ADDRESS), +DHT12Component::DHT12Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &humidity_name, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, DHT12_I2C_ADDRESS), temperature_sensor_(new DHT12TemperatureSensor(temperature_name, this)), - humidity_sensor_(new DHT12HumiditySensor(humidity_name, this)) { - -} + humidity_sensor_(new DHT12HumiditySensor(humidity_name, this)) {} void DHT12Component::update() { uint8_t data[5]; @@ -64,9 +62,7 @@ void DHT12Component::dump_config() { LOG_SENSOR(" ", "Temperature", this->temperature_sensor_); LOG_SENSOR(" ", "Humidity", this->humidity_sensor_); } -float DHT12Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float DHT12Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } bool DHT12Component::read_data_(uint8_t *data) { if (!this->read_bytes(0, data, 5)) { ESP_LOGW(TAG, "Updating DHT12 failed!"); @@ -81,15 +77,11 @@ bool DHT12Component::read_data_(uint8_t *data) { return true; } -DHT12TemperatureSensor *DHT12Component::get_temperature_sensor() const { - return this->temperature_sensor_; -} -DHT12HumiditySensor *DHT12Component::get_humidity_sensor() const { - return this->humidity_sensor_; -} +DHT12TemperatureSensor *DHT12Component::get_temperature_sensor() const { return this->temperature_sensor_; } +DHT12HumiditySensor *DHT12Component::get_humidity_sensor() const { return this->humidity_sensor_; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DHT12_SENSOR +#endif // USE_DHT12_SENSOR diff --git a/src/esphome/sensor/dht12_component.h b/src/esphome/sensor/dht12_component.h index 33b7c8bb..741fc0b4 100644 --- a/src/esphome/sensor/dht12_component.h +++ b/src/esphome/sensor/dht12_component.h @@ -17,8 +17,7 @@ using DHT12HumiditySensor = EmptyPollingParentSensor<0, ICON_WATER_PERCENT, UNIT class DHT12Component : public PollingComponent, public I2CDevice { public: - DHT12Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, + DHT12Component(I2CComponent *parent, const std::string &temperature_name, const std::string &humidity_name, uint32_t update_interval = 60000); // ========== INTERNAL METHODS ========== @@ -37,10 +36,10 @@ class DHT12Component : public PollingComponent, public I2CDevice { DHT12HumiditySensor *humidity_sensor_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DHT12_SENSOR +#endif // USE_DHT12_SENSOR -#endif //ESPHOME_SENSOR_DHT12_COMPONENT_H +#endif // ESPHOME_SENSOR_DHT12_COMPONENT_H diff --git a/src/esphome/sensor/dht_component.cpp b/src/esphome/sensor/dht_component.cpp index b2ee55d8..59759ae5 100644 --- a/src/esphome/sensor/dht_component.cpp +++ b/src/esphome/sensor/dht_component.cpp @@ -18,13 +18,12 @@ namespace sensor { static const char *TAG = "sensor.dht"; -DHTComponent::DHTComponent(const std::string &temperature_name, const std::string &humidity_name, - GPIOPin *pin, uint32_t update_interval) - : PollingComponent(update_interval), pin_(pin), +DHTComponent::DHTComponent(const std::string &temperature_name, const std::string &humidity_name, GPIOPin *pin, + uint32_t update_interval) + : PollingComponent(update_interval), + pin_(pin), temperature_sensor_(new DHTTemperatureSensor(temperature_name, this)), - humidity_sensor_(new DHTHumiditySensor(humidity_name, this)) { - -} + humidity_sensor_(new DHTHumiditySensor(humidity_name, this)) {} void DHTComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up DHT..."); @@ -79,19 +78,13 @@ void DHTComponent::update() { } } -float DHTComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float DHTComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void DHTComponent::set_dht_model(DHTModel model) { this->model_ = model; this->is_auto_detect_ = model == DHT_MODEL_AUTO_DETECT; } -DHTTemperatureSensor *DHTComponent::get_temperature_sensor() const { - return this->temperature_sensor_; -} -DHTHumiditySensor *DHTComponent::get_humidity_sensor() const { - return this->humidity_sensor_; -} +DHTTemperatureSensor *DHTComponent::get_temperature_sensor() const { return this->temperature_sensor_; } +DHTHumiditySensor *DHTComponent::get_humidity_sensor() const { return this->humidity_sensor_; } bool HOT DHTComponent::read_sensor_(float *temperature, float *humidity, bool report_errors) { *humidity = NAN; *temperature = NAN; @@ -162,14 +155,15 @@ bool HOT DHTComponent::read_sensor_(float *temperature, float *humidity, bool re if (bit == 0) { bit = 7; byte++; - } - else bit--; + } else + bit--; } enable_interrupts(); - ESP_LOGVV(TAG, "Data: Hum=0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN ", Temp=0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN ", Checksum=0b" BYTE_TO_BINARY_PATTERN, - BYTE_TO_BINARY(data[0]), BYTE_TO_BINARY(data[1]), - BYTE_TO_BINARY(data[2]), BYTE_TO_BINARY(data[3]), + ESP_LOGVV(TAG, + "Data: Hum=0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN + ", Temp=0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN ", Checksum=0b" BYTE_TO_BINARY_PATTERN, + BYTE_TO_BINARY(data[0]), BYTE_TO_BINARY(data[1]), BYTE_TO_BINARY(data[2]), BYTE_TO_BINARY(data[3]), BYTE_TO_BINARY(data[4])); uint8_t checksum_a = data[0] + data[1] + data[2] + data[3]; @@ -208,8 +202,8 @@ bool HOT DHTComponent::read_sensor_(float *temperature, float *humidity, bool re return true; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DHT_SENSOR +#endif // USE_DHT_SENSOR diff --git a/src/esphome/sensor/dht_component.h b/src/esphome/sensor/dht_component.h index 086e24e5..58203976 100644 --- a/src/esphome/sensor/dht_component.h +++ b/src/esphome/sensor/dht_component.h @@ -31,8 +31,8 @@ class DHTComponent : public PollingComponent { * @param pin The pin which DHT sensor is connected to. * @param update_interval The interval in ms the sensor should be checked. */ - DHTComponent(const std::string &temperature_name, const std::string &humidity_name, - GPIOPin *pin, uint32_t update_interval = 60000); + DHTComponent(const std::string &temperature_name, const std::string &humidity_name, GPIOPin *pin, + uint32_t update_interval = 60000); /** Manually select the DHT model. * @@ -72,10 +72,10 @@ class DHTComponent : public PollingComponent { DHTHumiditySensor *humidity_sensor_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DHT_SENSOR +#endif // USE_DHT_SENSOR -#endif //ESPHOME_SENSOR_DHT_COMPONENT_H +#endif // ESPHOME_SENSOR_DHT_COMPONENT_H diff --git a/src/esphome/sensor/duty_cycle_sensor.cpp b/src/esphome/sensor/duty_cycle_sensor.cpp index e695c665..7049ce07 100644 --- a/src/esphome/sensor/duty_cycle_sensor.cpp +++ b/src/esphome/sensor/duty_cycle_sensor.cpp @@ -12,9 +12,7 @@ namespace sensor { static const char *TAG = "sensor.duty_cycle"; DutyCycleSensor::DutyCycleSensor(const std::string &name, GPIOPin *pin, uint32_t update_interval) - : PollingSensorComponent(name, update_interval), pin_(pin) { - -} + : PollingSensorComponent(name, update_interval), pin_(pin) {} DutyCycleSensor *duty_cycle_sensors = nullptr; @@ -80,21 +78,13 @@ void DutyCycleSensor::update() { this->last_interrupt_ = now; } -std::string DutyCycleSensor::unit_of_measurement() { - return "%"; -} -std::string DutyCycleSensor::icon() { - return "mdi:percent"; -} -int8_t DutyCycleSensor::accuracy_decimals() { - return 1; -} -float DutyCycleSensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +std::string DutyCycleSensor::unit_of_measurement() { return "%"; } +std::string DutyCycleSensor::icon() { return "mdi:percent"; } +int8_t DutyCycleSensor::accuracy_decimals() { return 1; } +float DutyCycleSensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DUTY_CYCLE_SENSOR +#endif // USE_DUTY_CYCLE_SENSOR diff --git a/src/esphome/sensor/duty_cycle_sensor.h b/src/esphome/sensor/duty_cycle_sensor.h index f07e9dda..9b132ef1 100644 --- a/src/esphome/sensor/duty_cycle_sensor.h +++ b/src/esphome/sensor/duty_cycle_sensor.h @@ -37,10 +37,10 @@ class DutyCycleSensor : public PollingSensorComponent { extern DutyCycleSensor *duty_cycle_sensors; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_DUTY_CYCLE_SENSOR +#endif // USE_DUTY_CYCLE_SENSOR -#endif //ESPHOME_DUTY_CYCLE_SENSOR_H +#endif // ESPHOME_DUTY_CYCLE_SENSOR_H diff --git a/src/esphome/sensor/esp32_hall_sensor.cpp b/src/esphome/sensor/esp32_hall_sensor.cpp index 66d27ade..bd5b8421 100644 --- a/src/esphome/sensor/esp32_hall_sensor.cpp +++ b/src/esphome/sensor/esp32_hall_sensor.cpp @@ -13,32 +13,20 @@ namespace sensor { static const char *TAG = "sensor.esp32_hall"; ESP32HallSensor::ESP32HallSensor(const std::string &name, uint32_t update_interval) - : PollingSensorComponent(name, update_interval) { - -} + : PollingSensorComponent(name, update_interval) {} void ESP32HallSensor::update() { float value = (hallRead() / 4095.0f) * 10000.0f; ESP_LOGCONFIG(TAG, "'%s': Got reading %.0f µT", this->name_.c_str(), value); this->publish_state(value); } -std::string ESP32HallSensor::unit_of_measurement() { - return "µT"; -} -std::string ESP32HallSensor::icon() { - return "mdi:magnet"; -} -int8_t ESP32HallSensor::accuracy_decimals() { - return -1; -} -std::string ESP32HallSensor::unique_id() { - return get_mac_address() + "-hall"; -} -void ESP32HallSensor::dump_config() { - LOG_SENSOR("", "ESP32 Hall Sensor", this); -} +std::string ESP32HallSensor::unit_of_measurement() { return "µT"; } +std::string ESP32HallSensor::icon() { return "mdi:magnet"; } +int8_t ESP32HallSensor::accuracy_decimals() { return -1; } +std::string ESP32HallSensor::unique_id() { return get_mac_address() + "-hall"; } +void ESP32HallSensor::dump_config() { LOG_SENSOR("", "ESP32 Hall Sensor", this); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ESP32_HALL_SENSOR +#endif // USE_ESP32_HALL_SENSOR diff --git a/src/esphome/sensor/esp32_hall_sensor.h b/src/esphome/sensor/esp32_hall_sensor.h index 270c0ea9..0cc1ba14 100644 --- a/src/esphome/sensor/esp32_hall_sensor.h +++ b/src/esphome/sensor/esp32_hall_sensor.h @@ -25,10 +25,10 @@ class ESP32HallSensor : public PollingSensorComponent { std::string unique_id() override; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ESP32_HALL_SENSOR +#endif // USE_ESP32_HALL_SENSOR -#endif //ESPHOME_SENSOR_ESP32_HALL_SENSOR_H +#endif // ESPHOME_SENSOR_ESP32_HALL_SENSOR_H diff --git a/src/esphome/sensor/filter.cpp b/src/esphome/sensor/filter.cpp index c0e74668..2f3c4662 100644 --- a/src/esphome/sensor/filter.cpp +++ b/src/esphome/sensor/filter.cpp @@ -15,9 +15,7 @@ namespace sensor { static const char *TAG = "sensor.filter"; // Filter -uint32_t Filter::expected_interval(uint32_t input) { - return input; -} +uint32_t Filter::expected_interval(uint32_t input) { return input; } void Filter::input(float value) { ESP_LOGVV(TAG, "Filter(%p)::input(%f)", this, value); optional out = this->new_value(value); @@ -27,7 +25,7 @@ void Filter::input(float value) { void Filter::output(float value) { if (this->next_ == nullptr) { ESP_LOGVV(TAG, "Filter(%p)::output(%f) -> SENSOR", this, value); - this->parent_->send_state_to_frontend_internal_(value); + this->parent_->internal_send_state_to_frontend(value); } else { ESP_LOGVV(TAG, "Filter(%p)::output(%f) -> %p", this, value, this->next_); this->next_->input(value); @@ -49,23 +47,15 @@ uint32_t Filter::calculate_remaining_interval(uint32_t input) { } // SlidingWindowMovingAverageFilter -SlidingWindowMovingAverageFilter::SlidingWindowMovingAverageFilter(size_t window_size, size_t send_every, size_t send_first_at) - : send_every_(send_every), send_at_(send_every - send_first_at), - average_(SlidingWindowMovingAverage(window_size)) { - -} -size_t SlidingWindowMovingAverageFilter::get_send_every() const { - return this->send_every_; -} -void SlidingWindowMovingAverageFilter::set_send_every(size_t send_every) { - this->send_every_ = send_every; -} -size_t SlidingWindowMovingAverageFilter::get_window_size() const { - return this->average_.get_max_size(); -} -void SlidingWindowMovingAverageFilter::set_window_size(size_t window_size) { - this->average_.set_max_size(window_size); -} +SlidingWindowMovingAverageFilter::SlidingWindowMovingAverageFilter(size_t window_size, size_t send_every, + size_t send_first_at) + : send_every_(send_every), + send_at_(send_every - send_first_at), + average_(SlidingWindowMovingAverage(window_size)) {} +size_t SlidingWindowMovingAverageFilter::get_send_every() const { return this->send_every_; } +void SlidingWindowMovingAverageFilter::set_send_every(size_t send_every) { this->send_every_ = send_every; } +size_t SlidingWindowMovingAverageFilter::get_window_size() const { return this->average_.get_max_size(); } +void SlidingWindowMovingAverageFilter::set_window_size(size_t window_size) { this->average_.set_max_size(window_size); } optional SlidingWindowMovingAverageFilter::new_value(float value) { float average_value = this->average_.next_value(value); ESP_LOGVV(TAG, "SlidingWindowMovingAverageFilter(%p)::new_value(%f) -> %f", this, value, average_value); @@ -78,15 +68,11 @@ optional SlidingWindowMovingAverageFilter::new_value(float value) { return {}; } -uint32_t SlidingWindowMovingAverageFilter::expected_interval(uint32_t input) { - return input * this->send_every_; -} +uint32_t SlidingWindowMovingAverageFilter::expected_interval(uint32_t input) { return input * this->send_every_; } // ExponentialMovingAverageFilter ExponentialMovingAverageFilter::ExponentialMovingAverageFilter(float alpha, size_t send_every) - : send_every_(send_every), send_at_(send_every - 1), - average_(ExponentialMovingAverage(alpha)) { -} + : send_every_(send_every), send_at_(send_every - 1), average_(ExponentialMovingAverage(alpha)) {} optional ExponentialMovingAverageFilter::new_value(float value) { float average_value = this->average_.next_value(value); ESP_LOGVV(TAG, "ExponentialMovingAverageFilter(%p)::new_value(%f) -> %f", this, value, average_value); @@ -98,33 +84,16 @@ optional ExponentialMovingAverageFilter::new_value(float value) { } return {}; } -size_t ExponentialMovingAverageFilter::get_send_every() const { - return this->send_every_; -} -void ExponentialMovingAverageFilter::set_send_every(size_t send_every) { - this->send_every_ = send_every; -} -float ExponentialMovingAverageFilter::get_alpha() const { - return this->average_.get_alpha(); -} -void ExponentialMovingAverageFilter::set_alpha(float alpha) { - this->average_.set_alpha(alpha); -} -uint32_t ExponentialMovingAverageFilter::expected_interval(uint32_t input) { - return input * this->send_every_; -} +size_t ExponentialMovingAverageFilter::get_send_every() const { return this->send_every_; } +void ExponentialMovingAverageFilter::set_send_every(size_t send_every) { this->send_every_ = send_every; } +float ExponentialMovingAverageFilter::get_alpha() const { return this->average_.get_alpha(); } +void ExponentialMovingAverageFilter::set_alpha(float alpha) { this->average_.set_alpha(alpha); } +uint32_t ExponentialMovingAverageFilter::expected_interval(uint32_t input) { return input * this->send_every_; } // LambdaFilter -LambdaFilter::LambdaFilter(lambda_filter_t lambda_filter) - : lambda_filter_(std::move(lambda_filter)) { - -} -const lambda_filter_t &LambdaFilter::get_lambda_filter() const { - return this->lambda_filter_; -} -void LambdaFilter::set_lambda_filter(const lambda_filter_t &lambda_filter) { - this->lambda_filter_ = lambda_filter; -} +LambdaFilter::LambdaFilter(lambda_filter_t lambda_filter) : lambda_filter_(std::move(lambda_filter)) {} +const lambda_filter_t &LambdaFilter::get_lambda_filter() const { return this->lambda_filter_; } +void LambdaFilter::set_lambda_filter(const lambda_filter_t &lambda_filter) { this->lambda_filter_ = lambda_filter; } optional LambdaFilter::new_value(float value) { auto it = this->lambda_filter_(value); @@ -133,43 +102,35 @@ optional LambdaFilter::new_value(float value) { } // OffsetFilter -OffsetFilter::OffsetFilter(float offset) - : offset_(offset) { } +OffsetFilter::OffsetFilter(float offset) : offset_(offset) {} -optional OffsetFilter::new_value(float value) { - return value + this->offset_; -} +optional OffsetFilter::new_value(float value) { return value + this->offset_; } // MultiplyFilter -MultiplyFilter::MultiplyFilter(float multiplier) - : multiplier_(multiplier) { } +MultiplyFilter::MultiplyFilter(float multiplier) : multiplier_(multiplier) {} -optional MultiplyFilter::new_value(float value) { - return value * this->multiplier_; -} +optional MultiplyFilter::new_value(float value) { return value * this->multiplier_; } // FilterOutValueFilter -FilterOutValueFilter::FilterOutValueFilter(float value_to_filter_out) - : value_to_filter_out_(value_to_filter_out) { - -} +FilterOutValueFilter::FilterOutValueFilter(float value_to_filter_out) : value_to_filter_out_(value_to_filter_out) {} optional FilterOutValueFilter::new_value(float value) { if (isnan(this->value_to_filter_out_)) { - if (isnan(value)) return {}; - else return value; + if (isnan(value)) + return {}; + else + return value; } else { - if (value == this->value_to_filter_out_) return {}; - else return value; + if (value == this->value_to_filter_out_) + return {}; + else + return value; } } - // ThrottleFilter ThrottleFilter::ThrottleFilter(uint32_t min_time_between_inputs) - : min_time_between_inputs_(min_time_between_inputs), Filter() { - -} + : min_time_between_inputs_(min_time_between_inputs), Filter() {} optional ThrottleFilter::new_value(float value) { const uint32_t now = millis(); if (this->last_input_ == 0 || now - this->last_input_ >= min_time_between_inputs_) { @@ -180,10 +141,7 @@ optional ThrottleFilter::new_value(float value) { } // DeltaFilter -DeltaFilter::DeltaFilter(float min_delta) - : min_delta_(min_delta), last_value_(NAN) { - -} +DeltaFilter::DeltaFilter(float min_delta) : min_delta_(min_delta), last_value_(NAN) {} optional DeltaFilter::new_value(float value) { if (isnan(value)) return {}; @@ -197,10 +155,7 @@ optional DeltaFilter::new_value(float value) { } // OrFilter -OrFilter::OrFilter(std::vector filters) - : filters_(std::move(filters)), phi_(this) { - -} +OrFilter::OrFilter(std::vector filters) : filters_(std::move(filters)), phi_(this) {} OrFilter::PhiNode::PhiNode(OrFilter *parent) : parent_(parent) {} optional OrFilter::PhiNode::new_value(float value) { @@ -232,26 +187,16 @@ uint32_t OrFilter::expected_interval(uint32_t input) { } // DebounceFilter optional DebounceFilter::new_value(float value) { - this->set_timeout("debounce", this->time_period_, [this, value](){ - this->output(value); - }); + this->set_timeout("debounce", this->time_period_, [this, value]() { this->output(value); }); return {}; } -DebounceFilter::DebounceFilter(uint32_t time_period) - : time_period_(time_period) { - -} -float DebounceFilter::get_setup_priority() const { - return setup_priority::HARDWARE; -} +DebounceFilter::DebounceFilter(uint32_t time_period) : time_period_(time_period) {} +float DebounceFilter::get_setup_priority() const { return setup_priority::HARDWARE; } // HeartbeatFilter -HeartbeatFilter::HeartbeatFilter(uint32_t time_period) - : time_period_(time_period), last_input_(NAN) { - -} +HeartbeatFilter::HeartbeatFilter(uint32_t time_period) : time_period_(time_period), last_input_(NAN) {} optional HeartbeatFilter::new_value(float value) { ESP_LOGVV(TAG, "HeartbeatFilter(%p)::new_value(value=%f)", this, value); @@ -260,29 +205,24 @@ optional HeartbeatFilter::new_value(float value) { return {}; } -uint32_t HeartbeatFilter::expected_interval(uint32_t input) { - return this->time_period_; -} +uint32_t HeartbeatFilter::expected_interval(uint32_t input) { return this->time_period_; } void HeartbeatFilter::setup() { this->set_interval("heartbeat", this->time_period_, [this]() { - ESP_LOGVV(TAG, "HeartbeatFilter(%p)::interval(has_value=%s, last_input=%f)", this, YESNO(this->has_value_), this->last_input_); + ESP_LOGVV(TAG, "HeartbeatFilter(%p)::interval(has_value=%s, last_input=%f)", this, YESNO(this->has_value_), + this->last_input_); if (!this->has_value_) return; this->output(this->last_input_); }); } -float HeartbeatFilter::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float HeartbeatFilter::get_setup_priority() const { return setup_priority::HARDWARE; } -optional CalibrateLinearFilter::new_value(float value) { - return value * this->slope_ + this->bias_; -} +optional CalibrateLinearFilter::new_value(float value) { return value * this->slope_ + this->bias_; } CalibrateLinearFilter::CalibrateLinearFilter(float slope, float bias) : slope_(slope), bias_(bias) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_SENSOR +#endif // USE_SENSOR diff --git a/src/esphome/sensor/filter.h b/src/esphome/sensor/filter.h index 91a8f7d6..10a64744 100644 --- a/src/esphome/sensor/filter.h +++ b/src/esphome/sensor/filter.h @@ -71,7 +71,7 @@ class SlidingWindowMovingAverageFilter : public Filter { * on startup being published on the first *raw* value, so with no filter applied. Must be less than or equal to * send_every. */ - explicit SlidingWindowMovingAverageFilter(size_t window_size, size_t send_every, uint32_t send_first_at = 1); + explicit SlidingWindowMovingAverageFilter(size_t window_size, size_t send_every, size_t send_first_at = 1); optional new_value(float value) override; @@ -159,7 +159,7 @@ class MultiplyFilter : public Filter { /// A simple filter that only forwards the filter chain if it doesn't receive `value_to_filter_out`. class FilterOutValueFilter : public Filter { public: - explicit FilterOutValueFilter(float values_to_filter_out); + explicit FilterOutValueFilter(float value_to_filter_out); optional new_value(float value) override; @@ -234,6 +234,7 @@ class OrFilter : public Filter { public: PhiNode(OrFilter *parent); optional new_value(float value) override; + protected: OrFilter *parent_; }; @@ -246,15 +247,16 @@ class CalibrateLinearFilter : public Filter { public: CalibrateLinearFilter(float slope, float bias); optional new_value(float value) override; + protected: float slope_; float bias_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_SENSOR +#endif // USE_SENSOR -#endif //ESPHOME_SENSOR_FILTER_H +#endif // ESPHOME_SENSOR_FILTER_H diff --git a/src/esphome/sensor/hdc1080_component.cpp b/src/esphome/sensor/hdc1080_component.cpp index 74ba210a..45a33671 100644 --- a/src/esphome/sensor/hdc1080_component.cpp +++ b/src/esphome/sensor/hdc1080_component.cpp @@ -15,25 +15,23 @@ ESPHOME_NAMESPACE_BEGIN namespace sensor { static const char *TAG = "sensor.hdc1080"; -static const uint8_t HDC1080_ADDRESS = 0x40; // 0b1000000 from datasheet +static const uint8_t HDC1080_ADDRESS = 0x40; // 0b1000000 from datasheet static const uint8_t HDC1080_CMD_CONFIGURATION = 0x02; static const uint8_t HDC1080_CMD_TEMPERATURE = 0x00; static const uint8_t HDC1080_CMD_HUMIDITY = 0x01; -HDC1080Component::HDC1080Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, - uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, HDC1080_ADDRESS), +HDC1080Component::HDC1080Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &humidity_name, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, HDC1080_ADDRESS), temperature_(new HDC1080TemperatureSensor(temperature_name, this)), - humidity_(new HDC1080HumiditySensor(humidity_name, this)) { - -} + humidity_(new HDC1080HumiditySensor(humidity_name, this)) {} void HDC1080Component::setup() { ESP_LOGCONFIG(TAG, "Setting up HDC1080..."); const uint8_t data[2] = { - 0b00000000, // resolution 14bit for both humidity and temperature - 0b00000000 // reserved + 0b00000000, // resolution 14bit for both humidity and temperature + 0b00000000 // reserved }; if (this->write_bytes(HDC1080_CMD_CONFIGURATION, data, 2)) { @@ -57,7 +55,7 @@ void HDC1080Component::update() { this->status_set_warning(); return; } - float temp = raw_temp * 0.0025177f - 40.0f; // raw * 2^-16 * 165 - 40 + float temp = raw_temp * 0.0025177f - 40.0f; // raw * 2^-16 * 165 - 40 this->temperature_->publish_state(temp); uint16_t raw_humidity; @@ -65,24 +63,18 @@ void HDC1080Component::update() { this->status_set_warning(); return; } - float humidity = raw_humidity * 0.001525879f; // raw * 2^-16 * 100 + float humidity = raw_humidity * 0.001525879f; // raw * 2^-16 * 100 this->humidity_->publish_state(humidity); ESP_LOGD(TAG, "Got temperature=%.1f°C humidity=%.1f%%", temp, humidity); this->status_clear_warning(); } -HDC1080TemperatureSensor *HDC1080Component::get_temperature_sensor() const { - return this->temperature_; -} -HDC1080HumiditySensor *HDC1080Component::get_humidity_sensor() const { - return this->humidity_; -} -float HDC1080Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +HDC1080TemperatureSensor *HDC1080Component::get_temperature_sensor() const { return this->temperature_; } +HDC1080HumiditySensor *HDC1080Component::get_humidity_sensor() const { return this->humidity_; } +float HDC1080Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HDC1080_SENSOR +#endif // USE_HDC1080_SENSOR diff --git a/src/esphome/sensor/hdc1080_component.h b/src/esphome/sensor/hdc1080_component.h index 6ec0f0ab..96b61aaa 100644 --- a/src/esphome/sensor/hdc1080_component.h +++ b/src/esphome/sensor/hdc1080_component.h @@ -23,8 +23,7 @@ using HDC1080HumiditySensor = EmptyPollingParentSensor<0, ICON_WATER_PERCENT, UN class HDC1080Component : public PollingComponent, public I2CDevice { public: /// Initialize the component with the provided update interval. - explicit HDC1080Component(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, + explicit HDC1080Component(I2CComponent *parent, const std::string &temperature_name, const std::string &humidity_name, uint32_t update_interval); // ========== INTERNAL METHODS ========== @@ -47,10 +46,10 @@ class HDC1080Component : public PollingComponent, public I2CDevice { HDC1080HumiditySensor *humidity_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HDC1080_SENSOR +#endif // USE_HDC1080_SENSOR -#endif //ESPHOME_SENSOR_HDC1080_COMPONENT_H +#endif // ESPHOME_SENSOR_HDC1080_COMPONENT_H diff --git a/src/esphome/sensor/hlw8012.cpp b/src/esphome/sensor/hlw8012.cpp index 5e2b5170..d3ae1579 100644 --- a/src/esphome/sensor/hlw8012.cpp +++ b/src/esphome/sensor/hlw8012.cpp @@ -16,16 +16,16 @@ static const uint32_t HLW8012_CLOCK_FREQUENCY = 3579000; static const float HLW8012_REFERENCE_VOLTAGE = 2.43f; HLW8012Component::HLW8012Component(GPIOPin *sel_pin, uint8_t cf_pin, uint8_t cf1_pin, uint32_t update_interval) - : PollingComponent(update_interval), sel_pin_(sel_pin), - cf_(GPIOInputPin(cf_pin, INPUT_PULLUP).copy()), cf1_(GPIOInputPin(cf1_pin, INPUT_PULLUP).copy()) { - -} + : PollingComponent(update_interval), + sel_pin_(sel_pin), + cf_(GPIOInputPin(cf_pin, INPUT_PULLUP).copy()), + cf1_(GPIOInputPin(cf1_pin, INPUT_PULLUP).copy()) {} void HLW8012Component::setup() { ESP_LOGCONFIG(TAG, "Setting up HLW8012..."); this->sel_pin_->setup(); this->sel_pin_->digital_write(this->current_mode_); - if (!this->cf_.pulse_counter_setup_() || !this->cf1_.pulse_counter_setup_()) { + if (!this->cf_.pulse_counter_setup() || !this->cf1_.pulse_counter_setup()) { this->mark_failed(); return; } @@ -43,12 +43,10 @@ void HLW8012Component::dump_config() { LOG_SENSOR(" ", "Current", this->current_sensor_); LOG_SENSOR(" ", "Power", this->power_sensor_); } -float HLW8012Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float HLW8012Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void HLW8012Component::update() { - pulse_counter_t raw_cf = this->cf_.read_raw_value_(); - pulse_counter_t raw_cf1 = this->cf1_.read_raw_value_(); + pulse_counter_t raw_cf = this->cf_.read_raw_value(); + pulse_counter_t raw_cf1 = this->cf1_.read_raw_value(); float cf_hz = raw_cf / (this->get_update_interval() / 1000.0f); if (raw_cf <= 1) { // don't count single pulse as power @@ -65,7 +63,8 @@ void HLW8012Component::update() { } const float v_ref_squared = HLW8012_REFERENCE_VOLTAGE * HLW8012_REFERENCE_VOLTAGE; - const float power_multiplier_micros = 64000000.0f * v_ref_squared * this->voltage_divider_ / this->current_resistor_ / 24.0f / HLW8012_CLOCK_FREQUENCY; + const float power_multiplier_micros = + 64000000.0f * v_ref_squared * this->voltage_divider_ / this->current_resistor_ / 24.0f / HLW8012_CLOCK_FREQUENCY; float power = cf_hz * power_multiplier_micros / 1000000.0f; if (this->change_mode_at_ != 0) { @@ -112,12 +111,8 @@ HLW8012PowerSensor *HLW8012Component::make_power_sensor(const std::string &name) void HLW8012Component::set_change_mode_every(uint32_t change_mode_every) { this->change_mode_every_ = change_mode_every; } -void HLW8012Component::set_current_resistor(float current_resistor) { - this->current_resistor_ = current_resistor; -} -void HLW8012Component::set_voltage_divider(float voltage_divider) { - this->voltage_divider_ = voltage_divider; -} +void HLW8012Component::set_current_resistor(float current_resistor) { this->current_resistor_ = current_resistor; } +void HLW8012Component::set_voltage_divider(float voltage_divider) { this->voltage_divider_ = voltage_divider; } uint32_t HLW8012CurrentSensor::update_interval() { return this->parent_->get_update_interval() * this->parent_->change_mode_every_; @@ -131,8 +126,8 @@ uint32_t HLW8012VoltageSensor::update_interval() { HLW8012VoltageSensor::HLW8012VoltageSensor(const std::string &name, HLW8012Component *parent) : EmptySensor(name), parent_(parent) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HLW8012 +#endif // USE_HLW8012 diff --git a/src/esphome/sensor/hlw8012.h b/src/esphome/sensor/hlw8012.h index 24c40323..08190309 100644 --- a/src/esphome/sensor/hlw8012.h +++ b/src/esphome/sensor/hlw8012.h @@ -19,6 +19,7 @@ class HLW8012VoltageSensor : public EmptySensor<1, ICON_FLASH, UNIT_V> { public: HLW8012VoltageSensor(const std::string &name, HLW8012Component *parent); uint32_t update_interval() override; + protected: HLW8012Component *parent_; }; @@ -26,6 +27,7 @@ class HLW8012CurrentSensor : public EmptySensor<1, ICON_FLASH, UNIT_A> { public: HLW8012CurrentSensor(const std::string &name, HLW8012Component *parent); uint32_t update_interval() override; + protected: HLW8012Component *parent_; }; @@ -65,10 +67,10 @@ class HLW8012Component : public PollingComponent { HLW8012PowerSensor *power_sensor_{nullptr}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HLW8012 +#endif // USE_HLW8012 -#endif //ESPHOME_HLW_8012_H +#endif // ESPHOME_HLW_8012_H diff --git a/src/esphome/sensor/hmc5883l.cpp b/src/esphome/sensor/hmc5883l.cpp index 92a2b9a0..d811c4dc 100644 --- a/src/esphome/sensor/hmc5883l.cpp +++ b/src/esphome/sensor/hmc5883l.cpp @@ -88,9 +88,7 @@ void HMC5883LComponent::dump_config() { LOG_SENSOR(" ", "Z Axis", this->z_sensor_); LOG_SENSOR(" ", "Heading", this->heading_sensor_); } -float HMC5883LComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float HMC5883LComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void HMC5883LComponent::update() { uint16_t raw_x, raw_y, raw_z; if (!this->read_byte_16(HMC5883L_REGISTER_DATA_X_MSB, &raw_x) || @@ -102,15 +100,32 @@ void HMC5883LComponent::update() { float mg_per_bit; switch (this->range_) { - case HMC5883L_RANGE_88_UT: mg_per_bit = 0.073f; break; - case HMC5883L_RANGE_130_UT: mg_per_bit = 0.92f; break; - case HMC5883L_RANGE_190_UT: mg_per_bit = 1.22f; break; - case HMC5883L_RANGE_250_UT: mg_per_bit = 1.52f; break; - case HMC5883L_RANGE_400_UT: mg_per_bit = 2.27f; break; - case HMC5883L_RANGE_470_UT: mg_per_bit = 2.56f; break; - case HMC5883L_RANGE_560_UT: mg_per_bit = 3.03f; break; - case HMC5883L_RANGE_810_UT: mg_per_bit = 4.35f; break; - default: mg_per_bit = NAN; + case HMC5883L_RANGE_88_UT: + mg_per_bit = 0.073f; + break; + case HMC5883L_RANGE_130_UT: + mg_per_bit = 0.92f; + break; + case HMC5883L_RANGE_190_UT: + mg_per_bit = 1.22f; + break; + case HMC5883L_RANGE_250_UT: + mg_per_bit = 1.52f; + break; + case HMC5883L_RANGE_400_UT: + mg_per_bit = 2.27f; + break; + case HMC5883L_RANGE_470_UT: + mg_per_bit = 2.56f; + break; + case HMC5883L_RANGE_560_UT: + mg_per_bit = 3.03f; + break; + case HMC5883L_RANGE_810_UT: + mg_per_bit = 4.35f; + break; + default: + mg_per_bit = NAN; } // in µT @@ -119,8 +134,7 @@ void HMC5883LComponent::update() { const float z = int16_t(raw_z) * mg_per_bit * 0.1f; float heading = atan2f(0.0f - x, y) * 180.0f / M_PI; - ESP_LOGD(TAG, "Got x=%0.02fµT y=%0.02fµT z=%0.02fµT heading=%0.01f°", - x, y, z, heading); + ESP_LOGD(TAG, "Got x=%0.02fµT y=%0.02fµT z=%0.02fµT heading=%0.01f°", x, y, z, heading); if (this->x_sensor_ != nullptr) this->x_sensor_->publish_state(x); @@ -145,12 +159,10 @@ HMC5883LFieldStrengthSensor *HMC5883LComponent::make_z_sensor(const std::string HMC5883LHeadingSensor *HMC5883LComponent::make_heading_sensor(const std::string &name) { return this->heading_sensor_ = new HMC5883LHeadingSensor(name, this); } -void HMC5883LComponent::set_range(HMC5883LRange range) { - this->range_ = range; -} +void HMC5883LComponent::set_range(HMC5883LRange range) { this->range_ = range; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HMC5883L +#endif // USE_HMC5883L diff --git a/src/esphome/sensor/hmc5883l.h b/src/esphome/sensor/hmc5883l.h index e2e34e27..415f0fe8 100644 --- a/src/esphome/sensor/hmc5883l.h +++ b/src/esphome/sensor/hmc5883l.h @@ -55,10 +55,10 @@ class HMC5883LComponent : public PollingComponent, public I2CDevice { } error_code_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HMC5883L +#endif // USE_HMC5883L -#endif //ESPHOME_HMC_5883_L_H +#endif // ESPHOME_HMC_5883_L_H diff --git a/src/esphome/sensor/homeassistant_sensor.cpp b/src/esphome/sensor/homeassistant_sensor.cpp index 2f1f74ac..88032178 100644 --- a/src/esphome/sensor/homeassistant_sensor.cpp +++ b/src/esphome/sensor/homeassistant_sensor.cpp @@ -13,9 +13,7 @@ namespace sensor { static const char *TAG = "sensor.homeassistant"; HomeassistantSensor::HomeassistantSensor(const std::string &name, const std::string &entity_id) - : Sensor(name), entity_id_(entity_id) { - -} + : Sensor(name), entity_id_(entity_id) {} void HomeassistantSensor::setup() { api::global_api_server->subscribe_home_assistant_state(this->entity_id_, [this](std::string state) { auto val = parse_float(state); @@ -33,12 +31,10 @@ void HomeassistantSensor::dump_config() { LOG_SENSOR("", "Homeassistant Sensor", this); ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str()); } -float HomeassistantSensor::get_setup_priority() const { - return setup_priority::WIFI; -} +float HomeassistantSensor::get_setup_priority() const { return setup_priority::WIFI; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_SENSOR +#endif // USE_HOMEASSISTANT_SENSOR diff --git a/src/esphome/sensor/homeassistant_sensor.h b/src/esphome/sensor/homeassistant_sensor.h index f630e5f0..b9944848 100644 --- a/src/esphome/sensor/homeassistant_sensor.h +++ b/src/esphome/sensor/homeassistant_sensor.h @@ -18,14 +18,15 @@ class HomeassistantSensor : public Sensor, public Component { void setup() override; void dump_config() override; float get_setup_priority() const override; + protected: std::string entity_id_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_SENSOR +#endif // USE_HOMEASSISTANT_SENSOR -#endif //ESPHOME_HOMEASSISTANT_SENSOR_H +#endif // ESPHOME_HOMEASSISTANT_SENSOR_H diff --git a/src/esphome/sensor/htu21d_component.cpp b/src/esphome/sensor/htu21d_component.cpp index 622b4f2e..6f7962fd 100644 --- a/src/esphome/sensor/htu21d_component.cpp +++ b/src/esphome/sensor/htu21d_component.cpp @@ -1,5 +1,6 @@ // Based on: -// - http://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+Sheet%7FHPC199_6%7FA6%7Fpdf%7FEnglish%7FENG_DS_HPC199_6_A6.pdf%7FCAT-HSC0004 +// - +// http://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+Sheet%7FHPC199_6%7FA6%7Fpdf%7FEnglish%7FENG_DS_HPC199_6_A6.pdf%7FCAT-HSC0004 // - https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/HTU21D #include "esphome/defines.h" @@ -21,14 +22,12 @@ static const uint8_t HTU21D_REGISTER_TEMPERATURE = 0xE3; static const uint8_t HTU21D_REGISTER_HUMIDITY = 0xE5; static const uint8_t HTU21D_REGISTER_STATUS = 0xE7; -HTU21DComponent::HTU21DComponent(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, - uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, HTU21D_ADDRESS), +HTU21DComponent::HTU21DComponent(I2CComponent *parent, const std::string &temperature_name, + const std::string &humidity_name, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, HTU21D_ADDRESS), temperature_(new HTU21DTemperatureSensor(temperature_name, this)), - humidity_(new HTU21DHumiditySensor(humidity_name, this)) { - -} + humidity_(new HTU21DHumiditySensor(humidity_name, this)) {} void HTU21DComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up HTU21D..."); @@ -72,18 +71,12 @@ void HTU21DComponent::update() { this->humidity_->publish_state(humidity); this->status_clear_warning(); } -HTU21DTemperatureSensor *HTU21DComponent::get_temperature_sensor() const { - return this->temperature_; -} -HTU21DHumiditySensor *HTU21DComponent::get_humidity_sensor() const { - return this->humidity_; -} -float HTU21DComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +HTU21DTemperatureSensor *HTU21DComponent::get_temperature_sensor() const { return this->temperature_; } +HTU21DHumiditySensor *HTU21DComponent::get_humidity_sensor() const { return this->humidity_; } +float HTU21DComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HTU21D_SENSOR +#endif // USE_HTU21D_SENSOR diff --git a/src/esphome/sensor/htu21d_component.h b/src/esphome/sensor/htu21d_component.h index 4726c949..0787506b 100644 --- a/src/esphome/sensor/htu21d_component.h +++ b/src/esphome/sensor/htu21d_component.h @@ -19,8 +19,7 @@ using HTU21DHumiditySensor = EmptyPollingParentSensor<0, ICON_WATER_PERCENT, UNI class HTU21DComponent : public PollingComponent, public I2CDevice { public: /// Construct the HTU21D with the given update interval. - HTU21DComponent(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, + HTU21DComponent(I2CComponent *parent, const std::string &temperature_name, const std::string &humidity_name, uint32_t update_interval = 60000); // ========== INTERNAL METHODS ========== @@ -43,10 +42,10 @@ class HTU21DComponent : public PollingComponent, public I2CDevice { HTU21DHumiditySensor *humidity_{nullptr}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HTU21D_SENSOR +#endif // USE_HTU21D_SENSOR -#endif //ESPHOME_SENSOR_HTU21D_COMPONENT_H +#endif // ESPHOME_SENSOR_HTU21D_COMPONENT_H diff --git a/src/esphome/sensor/hx711.cpp b/src/esphome/sensor/hx711.cpp index 0033069b..b5c9f972 100644 --- a/src/esphome/sensor/hx711.cpp +++ b/src/esphome/sensor/hx711.cpp @@ -26,9 +26,7 @@ void HX711Sensor::dump_config() { LOG_PIN(" SCK Pin: ", this->sck_pin_); LOG_UPDATE_INTERVAL(this); } -float HX711Sensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float HX711Sensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void HX711Sensor::update() { uint32_t result; if (this->read_sensor_(&result)) { @@ -69,23 +67,15 @@ std::string HX711Sensor::unit_of_measurement() { // datasheet gives no unit return ""; } -std::string HX711Sensor::icon() { - return "mdi:scale"; -} -int8_t HX711Sensor::accuracy_decimals() { - return 0; -} +std::string HX711Sensor::icon() { return "mdi:scale"; } +int8_t HX711Sensor::accuracy_decimals() { return 0; } HX711Sensor::HX711Sensor(const std::string &name, GPIOPin *dout, GPIOPin *sck, uint32_t update_interval) -: PollingSensorComponent(name, update_interval), dout_pin_(dout), sck_pin_(sck) { + : PollingSensorComponent(name, update_interval), dout_pin_(dout), sck_pin_(sck) {} -} - -void HX711Sensor::set_gain(HX711Gain gain) { - this->gain_ = gain; -} +void HX711Sensor::set_gain(HX711Gain gain) { this->gain_ = gain; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HX711 +#endif // USE_HX711 diff --git a/src/esphome/sensor/hx711.h b/src/esphome/sensor/hx711.h index cbafad37..39c69c33 100644 --- a/src/esphome/sensor/hx711.h +++ b/src/esphome/sensor/hx711.h @@ -40,10 +40,10 @@ class HX711Sensor : public PollingSensorComponent { HX711Gain gain_{HX711_GAIN_128}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_HX711 +#endif // USE_HX711 -#endif //ESPHOME_SENSOR_HX711_H +#endif // ESPHOME_SENSOR_HX711_H diff --git a/src/esphome/sensor/ina219.cpp b/src/esphome/sensor/ina219.cpp index 0e114afb..937914f4 100644 --- a/src/esphome/sensor/ina219.cpp +++ b/src/esphome/sensor/ina219.cpp @@ -90,18 +90,19 @@ void INA219Component::setup() { // 0b000xx00000000000 << 11 Shunt Voltage Gain (0b00 -> 40mV, 0b01 -> 80mV, 0b10 -> 160mV, 0b11 -> 320mV) uint16_t shunt_gain; if (shunt_max_voltage * multiplier <= 0.02f) { - shunt_gain = 0b00; // 40mV + shunt_gain = 0b00; // 40mV } else if (shunt_max_voltage * multiplier <= 0.04f) { - shunt_gain = 0b01; // 80mV + shunt_gain = 0b01; // 80mV } else if (shunt_max_voltage * multiplier <= 0.08f) { - shunt_gain = 0b10; // 160mV + shunt_gain = 0b10; // 160mV } else { if (int(shunt_max_voltage * multiplier * 100) > 16) { - ESP_LOGW(TAG, " Max voltage across shunt resistor (resistance*current) exceeds %dmV. " - "This could damage the sensor!", + ESP_LOGW(TAG, + " Max voltage across shunt resistor (resistance*current) exceeds %dmV. " + "This could damage the sensor!", int(160 / multiplier)); } - shunt_gain = 0b11; // 320mV + shunt_gain = 0b11; // 320mV } config |= shunt_gain << 11; @@ -121,8 +122,7 @@ void INA219Component::setup() { } if (lsb > max_lsb) { lsb = max_lsb; - ESP_LOGW(TAG, " The requested current (%0.02fA) cannot be achieved without an overflow", - this->max_current_a_); + ESP_LOGW(TAG, " The requested current (%0.02fA) cannot be achieved without an overflow", this->max_current_a_); } this->calibration_lsb_ = lsb; @@ -151,9 +151,7 @@ void INA219Component::dump_config() { LOG_SENSOR(" ", "Power", this->power_sensor_); } -float INA219Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float INA219Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void INA219Component::update() { if (this->bus_voltage_sensor_ != nullptr) { @@ -198,13 +196,13 @@ void INA219Component::update() { this->status_clear_warning(); } -INA219Component::INA219Component(I2CComponent *parent, - float shunt_resistance_ohm, float max_current_a, float max_voltage_v, - uint8_t address, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, address), shunt_resistance_ohm_(shunt_resistance_ohm), - max_current_a_(max_current_a), max_voltage_v_(max_voltage_v) { - -} +INA219Component::INA219Component(I2CComponent *parent, float shunt_resistance_ohm, float max_current_a, + float max_voltage_v, uint8_t address, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, address), + shunt_resistance_ohm_(shunt_resistance_ohm), + max_current_a_(max_current_a), + max_voltage_v_(max_voltage_v) {} INA219VoltageSensor *INA219Component::make_bus_voltage_sensor(const std::string &name) { return this->bus_voltage_sensor_ = new INA219VoltageSensor(name, this); } @@ -218,8 +216,8 @@ INA219PowerSensor *INA219Component::make_power_sensor(const std::string &name) { return this->power_sensor_ = new INA219PowerSensor(name, this); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_INA219 +#endif // USE_INA219 diff --git a/src/esphome/sensor/ina219.h b/src/esphome/sensor/ina219.h index 477e9919..6a3adfc5 100644 --- a/src/esphome/sensor/ina219.h +++ b/src/esphome/sensor/ina219.h @@ -19,8 +19,7 @@ using INA219PowerSensor = EmptyPollingParentSensor<2, ICON_FLASH, UNIT_W>; class INA219Component : public PollingComponent, public I2CDevice { public: - INA219Component(I2CComponent *parent, - float shunt_resistance_ohm, float max_current_a, float max_voltage_v, + INA219Component(I2CComponent *parent, float shunt_resistance_ohm, float max_current_a, float max_voltage_v, uint8_t address = 0x40, uint32_t update_interval = 60000); void setup() override; void dump_config() override; @@ -30,7 +29,7 @@ class INA219Component : public PollingComponent, public I2CDevice { INA219VoltageSensor *make_bus_voltage_sensor(const std::string &name); INA219VoltageSensor *make_shunt_voltage_sensor(const std::string &name); INA219CurrentSensor *make_current_sensor(const std::string &name); - INA219PowerSensor *make_power_sensor(const std::string &name); + INA219PowerSensor *make_power_sensor(const std::string &name); protected: float shunt_resistance_ohm_; @@ -43,10 +42,10 @@ class INA219Component : public PollingComponent, public I2CDevice { INA219PowerSensor *power_sensor_{nullptr}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_INA219 +#endif // USE_INA219 -#endif //ESPHOME_INA_219_H +#endif // ESPHOME_INA_219_H diff --git a/src/esphome/sensor/ina3221.cpp b/src/esphome/sensor/ina3221.cpp index 0335cb8e..7f7a0cbd 100644 --- a/src/esphome/sensor/ina3221.cpp +++ b/src/esphome/sensor/ina3221.cpp @@ -37,13 +37,13 @@ void INA3221Component::setup() { uint16_t config = 0; // 0b0xxx000000000000 << 12 Channel Enables (1 -> ON) - if (this->channels[0].exists()) { + if (this->channels_[0].exists()) { config |= 0b0100000000000000; } - if (this->channels[1].exists()) { + if (this->channels_[1].exists()) { config |= 0b0010000000000000; } - if (this->channels[2].exists()) { + if (this->channels_[2].exists()) { config |= 0b0001000000000000; } // 0b0000xxx000000000 << 9 Averaging Mode (0 -> 1 sample, 111 -> 1024 samples) @@ -68,31 +68,27 @@ void INA3221Component::dump_config() { } LOG_UPDATE_INTERVAL(this); - LOG_SENSOR(" ", "Bus Voltage #1", this->channels[0].bus_voltage_sensor_); - LOG_SENSOR(" ", "Shunt Voltage #1", this->channels[0].shunt_voltage_sensor_); - LOG_SENSOR(" ", "Current #1", this->channels[0].current_sensor_); - LOG_SENSOR(" ", "Power #1", this->channels[0].power_sensor_); - LOG_SENSOR(" ", "Bus Voltage #2", this->channels[1].bus_voltage_sensor_); - LOG_SENSOR(" ", "Shunt Voltage #2", this->channels[1].shunt_voltage_sensor_); - LOG_SENSOR(" ", "Current #2", this->channels[1].current_sensor_); - LOG_SENSOR(" ", "Power #2", this->channels[1].power_sensor_); - LOG_SENSOR(" ", "Bus Voltage #3", this->channels[2].bus_voltage_sensor_); - LOG_SENSOR(" ", "Shunt Voltage #3", this->channels[2].shunt_voltage_sensor_); - LOG_SENSOR(" ", "Current #3", this->channels[2].current_sensor_); - LOG_SENSOR(" ", "Power #3", this->channels[2].power_sensor_); + LOG_SENSOR(" ", "Bus Voltage #1", this->channels_[0].bus_voltage_sensor_); + LOG_SENSOR(" ", "Shunt Voltage #1", this->channels_[0].shunt_voltage_sensor_); + LOG_SENSOR(" ", "Current #1", this->channels_[0].current_sensor_); + LOG_SENSOR(" ", "Power #1", this->channels_[0].power_sensor_); + LOG_SENSOR(" ", "Bus Voltage #2", this->channels_[1].bus_voltage_sensor_); + LOG_SENSOR(" ", "Shunt Voltage #2", this->channels_[1].shunt_voltage_sensor_); + LOG_SENSOR(" ", "Current #2", this->channels_[1].current_sensor_); + LOG_SENSOR(" ", "Power #2", this->channels_[1].power_sensor_); + LOG_SENSOR(" ", "Bus Voltage #3", this->channels_[2].bus_voltage_sensor_); + LOG_SENSOR(" ", "Shunt Voltage #3", this->channels_[2].shunt_voltage_sensor_); + LOG_SENSOR(" ", "Current #3", this->channels_[2].current_sensor_); + LOG_SENSOR(" ", "Power #3", this->channels_[2].power_sensor_); } -inline uint8_t ina3221_bus_voltage_register(int channel) { - return 0x02 + channel * 2; -} +inline uint8_t ina3221_bus_voltage_register(int channel) { return 0x02 + channel * 2; } -inline uint8_t ina3221_shunt_voltage_register(int channel) { - return 0x01 + channel * 2; -} +inline uint8_t ina3221_shunt_voltage_register(int channel) { return 0x01 + channel * 2; } void INA3221Component::update() { for (int i = 0; i < 3; i++) { - INA3221Channel &channel = this->channels[i]; + INA3221Channel &channel = this->channels_[i]; float bus_voltage_v = NAN, current_a = NAN; uint16_t raw; if (channel.should_measure_bus_voltage()) { @@ -122,29 +118,28 @@ void INA3221Component::update() { } } -float INA3221Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float INA3221Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void INA3221Component::set_shunt_resistance(int channel, float resistance_ohm) { - this->channels[channel].shunt_resistance_ = resistance_ohm; + this->channels_[channel].shunt_resistance_ = resistance_ohm; } INA3221PowerSensor *INA3221Component::make_power_sensor(int channel, const std::string &name) { - return this->channels[channel].power_sensor_ = new INA3221PowerSensor(name, this); + return this->channels_[channel].power_sensor_ = new INA3221PowerSensor(name, this); } INA3221CurrentSensor *INA3221Component::make_current_sensor(int channel, const std::string &name) { - return this->channels[channel].current_sensor_ = new INA3221CurrentSensor(name, this); + return this->channels_[channel].current_sensor_ = new INA3221CurrentSensor(name, this); } INA3221VoltageSensor *INA3221Component::make_shunt_voltage_sensor(int channel, const std::string &name) { - return this->channels[channel].shunt_voltage_sensor_ = new INA3221VoltageSensor(name, this); + return this->channels_[channel].shunt_voltage_sensor_ = new INA3221VoltageSensor(name, this); } INA3221VoltageSensor *INA3221Component::make_bus_voltage_sensor(int channel, const std::string &name) { - return this->channels[channel].bus_voltage_sensor_ = new INA3221VoltageSensor(name, this); + return this->channels_[channel].bus_voltage_sensor_ = new INA3221VoltageSensor(name, this); } INA3221Component::INA3221Component(I2CComponent *parent, uint8_t address, uint32_t update_interval) : PollingComponent(update_interval), I2CDevice(parent, address) {} bool INA3221Component::INA3221Channel::exists() { - return this->bus_voltage_sensor_ != nullptr || this->shunt_voltage_sensor_ != nullptr || this->current_sensor_ != nullptr || this->power_sensor_ != nullptr; + return this->bus_voltage_sensor_ != nullptr || this->shunt_voltage_sensor_ != nullptr || + this->current_sensor_ != nullptr || this->power_sensor_ != nullptr; } bool INA3221Component::INA3221Channel::should_measure_shunt_voltage() { return this->shunt_voltage_sensor_ != nullptr || this->current_sensor_ != nullptr || this->power_sensor_ != nullptr; @@ -152,8 +147,8 @@ bool INA3221Component::INA3221Channel::should_measure_shunt_voltage() { bool INA3221Component::INA3221Channel::should_measure_bus_voltage() { return this->bus_voltage_sensor_ != nullptr || this->power_sensor_ != nullptr; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_INA3221 +#endif // USE_INA3221 diff --git a/src/esphome/sensor/ina3221.h b/src/esphome/sensor/ina3221.h index 6b50bbe2..f2954593 100644 --- a/src/esphome/sensor/ina3221.h +++ b/src/esphome/sensor/ina3221.h @@ -41,13 +41,13 @@ class INA3221Component : public PollingComponent, public I2CDevice { bool exists(); bool should_measure_shunt_voltage(); bool should_measure_bus_voltage(); - } channels[3]; + } channels_[3]; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_INA3221 +#endif // USE_INA3221 -#endif //ESPHOME_INA3221_H +#endif // ESPHOME_INA3221_H diff --git a/src/esphome/sensor/max31855_sensor.cpp b/src/esphome/sensor/max31855_sensor.cpp index 8dfba7b5..e6c92566 100644 --- a/src/esphome/sensor/max31855_sensor.cpp +++ b/src/esphome/sensor/max31855_sensor.cpp @@ -1,4 +1,5 @@ -// Implementation based on https://github.com/adafruit/MAX31855-library/blob/master/max31855.cpp and https://github.com/adafruit/Adafruit_CircuitPython_MAX31855/blob/master/adafruit_max31855.py +// Implementation based on https://github.com/adafruit/MAX31855-library/blob/master/max31855.cpp and +// https://github.com/adafruit/Adafruit_CircuitPython_MAX31855/blob/master/adafruit_max31855.py #include "esphome/defines.h" @@ -33,18 +34,10 @@ void MAX31855Sensor::dump_config() { LOG_PIN(" CS Pin: ", this->cs_); LOG_UPDATE_INTERVAL(this); } -float MAX31855Sensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -std::string MAX31855Sensor::unit_of_measurement() { - return UNIT_C; -} -std::string MAX31855Sensor::icon() { - return ICON_EMPTY; -} -int8_t MAX31855Sensor::accuracy_decimals() { - return 1; -} +float MAX31855Sensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +std::string MAX31855Sensor::unit_of_measurement() { return UNIT_C; } +std::string MAX31855Sensor::icon() { return ICON_EMPTY; } +int8_t MAX31855Sensor::accuracy_decimals() { return 1; } void MAX31855Sensor::read_data_() { this->enable(); delay(1); @@ -66,22 +59,22 @@ void MAX31855Sensor::read_data_() { this->disable(); if ((data[3] & 0x01) != 0) { - ESP_LOGW(TAG, "Got thermocouple not connected from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] <<8); + ESP_LOGW(TAG, "Got thermocouple not connected from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] << 8); this->status_set_warning(); return; } if ((data[3] & 0x02) != 0) { - ESP_LOGW(TAG, "Got short circuit to ground from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] <<8); + ESP_LOGW(TAG, "Got short circuit to ground from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] << 8); this->status_set_warning(); return; } if ((data[3] & 0x04) != 0) { - ESP_LOGW(TAG, "Got short circuit to power from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] <<8); + ESP_LOGW(TAG, "Got short circuit to power from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] << 8); this->status_set_warning(); return; } if ((data[1] & 0x01) != 0) { - ESP_LOGW(TAG, "Got faulty reading from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] <<8); + ESP_LOGW(TAG, "Got faulty reading from MAX31855Sensor (0x%04X) (0x%04X)", val, data[3] | data[2] << 8); this->status_set_warning(); return; } @@ -103,12 +96,10 @@ void MAX31855Sensor::read_data_() { MAX31855Sensor::MAX31855Sensor(const std::string &name, SPIComponent *parent, GPIOPin *cs, uint32_t update_interval) : PollingSensorComponent(name, update_interval), SPIDevice(parent, cs) {} -bool MAX31855Sensor::msb_first() { - return true; -} +bool MAX31855Sensor::is_device_msb_first() { return true; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MAX31855_SENSOR +#endif // USE_MAX31855_SENSOR diff --git a/src/esphome/sensor/max31855_sensor.h b/src/esphome/sensor/max31855_sensor.h index 3479bb8e..fc11822f 100644 --- a/src/esphome/sensor/max31855_sensor.h +++ b/src/esphome/sensor/max31855_sensor.h @@ -27,15 +27,15 @@ class MAX31855Sensor : public PollingSensorComponent, public SPIDevice { int8_t accuracy_decimals() override; protected: - bool msb_first() override; + bool is_device_msb_first() override; void read_data_(); }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MAX31855_SENSOR +#endif // USE_MAX31855_SENSOR -#endif //ESPHOME_SENSOR_MAX31855_H +#endif // ESPHOME_SENSOR_MAX31855_H diff --git a/src/esphome/sensor/max6675_sensor.cpp b/src/esphome/sensor/max6675_sensor.cpp index da126bbb..96e9c135 100644 --- a/src/esphome/sensor/max6675_sensor.cpp +++ b/src/esphome/sensor/max6675_sensor.cpp @@ -33,18 +33,10 @@ void MAX6675Sensor::dump_config() { LOG_PIN(" CS Pin: ", this->cs_); LOG_UPDATE_INTERVAL(this); } -float MAX6675Sensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -std::string MAX6675Sensor::unit_of_measurement() { - return UNIT_C; -} -std::string MAX6675Sensor::icon() { - return ICON_EMPTY; -} -int8_t MAX6675Sensor::accuracy_decimals() { - return 1; -} +float MAX6675Sensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +std::string MAX6675Sensor::unit_of_measurement() { return UNIT_C; } +std::string MAX6675Sensor::icon() { return ICON_EMPTY; } +int8_t MAX6675Sensor::accuracy_decimals() { return 1; } void MAX6675Sensor::read_data_() { this->enable(); delay(1); @@ -69,12 +61,10 @@ void MAX6675Sensor::read_data_() { MAX6675Sensor::MAX6675Sensor(const std::string &name, SPIComponent *parent, GPIOPin *cs, uint32_t update_interval) : PollingSensorComponent(name, update_interval), SPIDevice(parent, cs) {} -bool MAX6675Sensor::msb_first() { - return true; -} +bool MAX6675Sensor::is_device_msb_first() { return true; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MAX6675_SENSOR +#endif // USE_MAX6675_SENSOR diff --git a/src/esphome/sensor/max6675_sensor.h b/src/esphome/sensor/max6675_sensor.h index f50773c5..6fc60747 100644 --- a/src/esphome/sensor/max6675_sensor.h +++ b/src/esphome/sensor/max6675_sensor.h @@ -27,15 +27,15 @@ class MAX6675Sensor : public PollingSensorComponent, public SPIDevice { int8_t accuracy_decimals() override; protected: - bool msb_first() override; + bool is_device_msb_first() override; void read_data_(); }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MAX6675_SENSOR +#endif // USE_MAX6675_SENSOR -#endif //ESPHOME_SENSOR_MAX6675_H +#endif // ESPHOME_SENSOR_MAX6675_H diff --git a/src/esphome/sensor/mhz19_component.cpp b/src/esphome/sensor/mhz19_component.cpp index 97048398..00f0c3e8 100644 --- a/src/esphome/sensor/mhz19_component.cpp +++ b/src/esphome/sensor/mhz19_component.cpp @@ -14,13 +14,9 @@ static const uint8_t MHZ19_REQUEST_LENGTH = 8; static const uint8_t MHZ19_RESPONSE_LENGTH = 9; static const uint8_t MHZ19_COMMAND_GET_PPM[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00}; -MHZ19Component::MHZ19Component(UARTComponent *parent, const std::string &co2_name, - uint32_t update_interval) - : PollingComponent(update_interval), UARTDevice(parent), - co2_sensor_(new MHZ19CO2Sensor(co2_name, this)) { - -} -uint8_t mhz19_checksum_(const uint8_t *command) { +MHZ19Component::MHZ19Component(UARTComponent *parent, const std::string &co2_name, uint32_t update_interval) + : PollingComponent(update_interval), UARTDevice(parent), co2_sensor_(new MHZ19CO2Sensor(co2_name, this)) {} +uint8_t mhz19_checksum(const uint8_t *command) { uint8_t sum = 0; for (uint8_t i = 1; i < MHZ19_REQUEST_LENGTH; i++) { sum += command[i]; @@ -42,7 +38,7 @@ void MHZ19Component::update() { return; } - uint8_t checksum = mhz19_checksum_(response); + uint8_t checksum = mhz19_checksum(response); if (response[8] != checksum) { ESP_LOGW(TAG, "MHZ19 Checksum doesn't match: 0x%02X!=0x%02X", response[8], checksum); this->status_set_warning(); @@ -63,7 +59,7 @@ void MHZ19Component::update() { bool MHZ19Component::mhz19_write_command_(const uint8_t *command, uint8_t *response) { this->flush(); this->write_array(command, MHZ19_REQUEST_LENGTH); - this->write_byte(mhz19_checksum_(command)); + this->write_byte(mhz19_checksum(command)); if (response == nullptr) return true; @@ -75,20 +71,16 @@ bool MHZ19Component::mhz19_write_command_(const uint8_t *command, uint8_t *respo MHZ19TemperatureSensor *MHZ19Component::make_temperature_sensor(const std::string &name) { return this->temperature_sensor_ = new MHZ19TemperatureSensor(name, this); } -MHZ19CO2Sensor *MHZ19Component::get_co2_sensor() const { - return this->co2_sensor_; -} -float MHZ19Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +MHZ19CO2Sensor *MHZ19Component::get_co2_sensor() const { return this->co2_sensor_; } +float MHZ19Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void MHZ19Component::dump_config() { ESP_LOGCONFIG(TAG, "MH-Z19:"); LOG_SENSOR(" ", "CO2", this->co2_sensor_); LOG_SENSOR(" ", "Temperature", this->temperature_sensor_); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MHZ19 +#endif // USE_MHZ19 diff --git a/src/esphome/sensor/mhz19_component.h b/src/esphome/sensor/mhz19_component.h index b4aa7a57..b3d49897 100644 --- a/src/esphome/sensor/mhz19_component.h +++ b/src/esphome/sensor/mhz19_component.h @@ -18,9 +18,8 @@ using MHZ19CO2Sensor = sensor::EmptyPollingParentSensor<0, ICON_PERIODIC_TABLE_C class MHZ19Component : public PollingComponent, public UARTDevice { public: - MHZ19Component(UARTComponent *parent, const std::string &name, - uint32_t update_interval = 60000); - + MHZ19Component(UARTComponent *parent, const std::string &name, uint32_t update_interval = 60000); + float get_setup_priority() const override; void update() override; @@ -36,10 +35,10 @@ class MHZ19Component : public PollingComponent, public UARTDevice { MHZ19CO2Sensor *co2_sensor_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MHZ19 +#endif // USE_MHZ19 -#endif //ESPHOME_MHZ_19_COMPONENT_H +#endif // ESPHOME_MHZ_19_COMPONENT_H diff --git a/src/esphome/sensor/mpu6050_component.cpp b/src/esphome/sensor/mpu6050_component.cpp index ee531d52..23dae030 100644 --- a/src/esphome/sensor/mpu6050_component.cpp +++ b/src/esphome/sensor/mpu6050_component.cpp @@ -31,9 +31,7 @@ const uint8_t MPU6050_BIT_TEMPERATURE_DISABLED = 3; const float GRAVITY_EARTH = 9.80665f; MPU6050Component::MPU6050Component(I2CComponent *parent, uint8_t address, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, address) { - -} + : PollingComponent(update_interval), I2CDevice(parent, address) {} void MPU6050Component::setup() { ESP_LOGCONFIG(TAG, "Setting up MPU6050..."); @@ -130,8 +128,9 @@ void MPU6050Component::update() { float gyro_y = data[5] * MPU6050_SCALE_DPS_PER_DIGIT_2000; float gyro_z = data[6] * MPU6050_SCALE_DPS_PER_DIGIT_2000; - ESP_LOGD(TAG, "Got accel={x=%.3f m/s², y=%.3f m/s², z=%.3f m/s²}, " - "gyro={x=%.3f °/s, y=%.3f °/s, z=%.3f °/s}, temp=%.3f°C", + ESP_LOGD(TAG, + "Got accel={x=%.3f m/s², y=%.3f m/s², z=%.3f m/s²}, " + "gyro={x=%.3f °/s, y=%.3f °/s, z=%.3f °/s}, temp=%.3f°C", accel_x, accel_y, accel_z, gyro_x, gyro_y, gyro_z, temperature); if (this->accel_x_sensor_ != nullptr) @@ -174,12 +173,10 @@ MPU6050GyroSensor *MPU6050Component::make_gyro_z_sensor(const std::string &name) MPU6050TemperatureSensor *MPU6050Component::make_temperature_sensor(const std::string &name) { return this->temperature_sensor_ = new MPU6050TemperatureSensor(name, this); } -float MPU6050Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float MPU6050Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MPUT6050 +#endif // USE_MPUT6050 diff --git a/src/esphome/sensor/mpu6050_component.h b/src/esphome/sensor/mpu6050_component.h index 9c5c12d6..924dc1d2 100644 --- a/src/esphome/sensor/mpu6050_component.h +++ b/src/esphome/sensor/mpu6050_component.h @@ -46,10 +46,10 @@ class MPU6050Component : public PollingComponent, public I2CDevice { MPU6050GyroSensor *gyro_z_sensor_{nullptr}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MPU6050 +#endif // USE_MPU6050 -#endif //ESPHOME_MPU_6050_COMPONENT_H +#endif // ESPHOME_MPU_6050_COMPONENT_H diff --git a/src/esphome/sensor/mqtt_sensor_component.cpp b/src/esphome/sensor/mqtt_sensor_component.cpp index 0f7ac558..a1dddd49 100644 --- a/src/esphome/sensor/mqtt_sensor_component.cpp +++ b/src/esphome/sensor/mqtt_sensor_component.cpp @@ -15,15 +15,10 @@ namespace sensor { static const char *TAG = "sensor.mqtt"; -MQTTSensorComponent::MQTTSensorComponent(Sensor *sensor) - : MQTTComponent(), sensor_(sensor) { - -} +MQTTSensorComponent::MQTTSensorComponent(Sensor *sensor) : MQTTComponent(), sensor_(sensor) {} void MQTTSensorComponent::setup() { - this->sensor_->add_on_state_callback([this](float state) { - this->publish_state(state); - }); + this->sensor_->add_on_state_callback([this](float state) { this->publish_state(state); }); } void MQTTSensorComponent::dump_config() { @@ -34,9 +29,7 @@ void MQTTSensorComponent::dump_config() { LOG_MQTT_COMPONENT(true, false) } -std::string MQTTSensorComponent::component_type() const { - return "sensor"; -} +std::string MQTTSensorComponent::component_type() const { return "sensor"; } uint32_t MQTTSensorComponent::get_expire_after() const { if (this->expire_after_.has_value()) { @@ -50,15 +43,9 @@ uint32_t MQTTSensorComponent::get_expire_after() const { return this->sensor_->calculate_expected_filter_update_interval() * 5; } } -void MQTTSensorComponent::set_expire_after(uint32_t expire_after) { - this->expire_after_ = expire_after; -} -void MQTTSensorComponent::disable_expire_after() { - this->expire_after_ = 0; -} -std::string MQTTSensorComponent::friendly_name() const { - return this->sensor_->get_name(); -} +void MQTTSensorComponent::set_expire_after(uint32_t expire_after) { this->expire_after_ = expire_after; } +void MQTTSensorComponent::disable_expire_after() { this->expire_after_ = 0; } +std::string MQTTSensorComponent::friendly_name() const { return this->sensor_->get_name(); } void MQTTSensorComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (!this->sensor_->get_unit_of_measurement().empty()) root["unit_of_measurement"] = this->sensor_->get_unit_of_measurement(); @@ -78,19 +65,15 @@ bool MQTTSensorComponent::send_initial_state() { return true; } } -bool MQTTSensorComponent::is_internal() { - return this->sensor_->is_internal(); -} +bool MQTTSensorComponent::is_internal() { return this->sensor_->is_internal(); } bool MQTTSensorComponent::publish_state(float value) { int8_t accuracy = this->sensor_->get_accuracy_decimals(); - return this->publish(this->get_state_topic(), value_accuracy_to_string(value, accuracy)); -} -std::string MQTTSensorComponent::unique_id() { - return this->sensor_->unique_id(); + return this->publish(this->get_state_topic_(), value_accuracy_to_string(value, accuracy)); } +std::string MQTTSensorComponent::unique_id() { return this->sensor_->unique_id(); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SENSOR +#endif // USE_MQTT_SENSOR diff --git a/src/esphome/sensor/mqtt_sensor_component.h b/src/esphome/sensor/mqtt_sensor_component.h index eef836bb..4861a0be 100644 --- a/src/esphome/sensor/mqtt_sensor_component.h +++ b/src/esphome/sensor/mqtt_sensor_component.h @@ -56,13 +56,13 @@ class MQTTSensorComponent : public mqtt::MQTTComponent { std::string unique_id() override; Sensor *sensor_; - optional expire_after_; // Override the expire after advertised to Home Assistant + optional expire_after_; // Override the expire after advertised to Home Assistant }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SENSOR +#endif // USE_MQTT_SENSOR -#endif //ESPHOME_SENSOR_MQTT_SENSOR_COMPONENT_H +#endif // ESPHOME_SENSOR_MQTT_SENSOR_COMPONENT_H diff --git a/src/esphome/sensor/mqtt_subscribe_sensor.cpp b/src/esphome/sensor/mqtt_subscribe_sensor.cpp index 778d300f..18f6cf75 100644 --- a/src/esphome/sensor/mqtt_subscribe_sensor.cpp +++ b/src/esphome/sensor/mqtt_subscribe_sensor.cpp @@ -15,35 +15,31 @@ namespace sensor { static const char *TAG = "sensor.mqtt_subscribe"; MQTTSubscribeSensor::MQTTSubscribeSensor(const std::string &name, std::string topic) - : Sensor(name), topic_(std::move(topic)) { - -} + : Sensor(name), topic_(std::move(topic)) {} void MQTTSubscribeSensor::setup() { - mqtt::global_mqtt_client->subscribe(this->topic_, [this](const std::string &topic, std::string payload) { - auto val = parse_float(payload); - if (!val.has_value()) { - ESP_LOGW(TAG, "Can't convert '%s' to number!", payload.c_str()); - this->publish_state(NAN); - return; - } - - this->publish_state(*val); - }, this->qos_); + mqtt::global_mqtt_client->subscribe(this->topic_, + [this](const std::string &topic, std::string payload) { + auto val = parse_float(payload); + if (!val.has_value()) { + ESP_LOGW(TAG, "Can't convert '%s' to number!", payload.c_str()); + this->publish_state(NAN); + return; + } + + this->publish_state(*val); + }, + this->qos_); } -float MQTTSubscribeSensor::get_setup_priority() const { - return setup_priority::MQTT_CLIENT - 1.0f; -} -void MQTTSubscribeSensor::set_qos(uint8_t qos) { - this->qos_ = qos; -} +float MQTTSubscribeSensor::get_setup_priority() const { return setup_priority::MQTT_CLIENT - 1.0f; } +void MQTTSubscribeSensor::set_qos(uint8_t qos) { this->qos_ = qos; } void MQTTSubscribeSensor::dump_config() { LOG_SENSOR("", "MQTT Subscribe", this); ESP_LOGCONFIG(TAG, " Topic: %s", this->topic_.c_str()); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SUBSCRIBE_SENSOR +#endif // USE_MQTT_SUBSCRIBE_SENSOR diff --git a/src/esphome/sensor/mqtt_subscribe_sensor.h b/src/esphome/sensor/mqtt_subscribe_sensor.h index f28b2892..59b23bba 100644 --- a/src/esphome/sensor/mqtt_subscribe_sensor.h +++ b/src/esphome/sensor/mqtt_subscribe_sensor.h @@ -27,10 +27,10 @@ class MQTTSubscribeSensor : public Sensor, public Component { uint8_t qos_{0}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SUBSCRIBE_SENSOR +#endif // USE_MQTT_SUBSCRIBE_SENSOR -#endif //ESPHOME_SENSOR_MQTT_SUBSCRIBE_SENSOR_H +#endif // ESPHOME_SENSOR_MQTT_SUBSCRIBE_SENSOR_H diff --git a/src/esphome/sensor/ms5611.cpp b/src/esphome/sensor/ms5611.cpp index 916d9b1f..8b3ceec2 100644 --- a/src/esphome/sensor/ms5611.cpp +++ b/src/esphome/sensor/ms5611.cpp @@ -26,7 +26,7 @@ void MS5611Component::setup() { } delay(100); for (uint8_t offset = 0; offset < 6; offset++) { - if (!this->read_byte_16(MS5611_CMD_READ_PROM + (offset * 2), &this->prom[offset])) { + if (!this->read_byte_16(MS5611_CMD_READ_PROM + (offset * 2), &this->prom_[offset])) { this->mark_failed(); return; } @@ -42,9 +42,7 @@ void MS5611Component::dump_config() { LOG_SENSOR(" ", "Temperature", this->temperature_sensor_); LOG_SENSOR(" ", "Pressure", this->pressure_sensor_); } -float MS5611Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float MS5611Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void MS5611Component::update() { // request temperature reading if (!this->write_bytes(MS5611_CMD_CONV_D2 + 0x08, nullptr, 0)) { @@ -79,17 +77,17 @@ void MS5611Component::read_pressure_(uint32_t raw_temperature) { return; } const uint32_t raw_pressure = (uint32_t(bytes[0]) << 16) | (uint32_t(bytes[1]) << 8) | (uint32_t(bytes[2])); - this->calculate_values(raw_temperature, raw_pressure); + this->calculate_values_(raw_temperature, raw_pressure); } -void MS5611Component::calculate_values(uint32_t raw_temperature, uint32_t raw_pressure) { - const int32_t dT = int32_t(raw_temperature) - (uint32_t(this->prom[4]) << 8); - float temperature = (2000 + (int64_t(dT) * this->prom[5]) / 8388608.0f) / 100.0f; +void MS5611Component::calculate_values_(uint32_t raw_temperature, uint32_t raw_pressure) { + const int32_t d_t = int32_t(raw_temperature) - (uint32_t(this->prom_[4]) << 8); + float temperature = (2000 + (int64_t(d_t) * this->prom_[5]) / 8388608.0f) / 100.0f; - float pressure_offset = (uint32_t(this->prom[1]) << 16) + ((this->prom[3] * dT) >> 7); - float pressure_sensitivity = (uint32_t(this->prom[0]) << 15) + ((this->prom[2] * dT) >> 8); + float pressure_offset = (uint32_t(this->prom_[1]) << 16) + ((this->prom_[3] * d_t) >> 7); + float pressure_sensitivity = (uint32_t(this->prom_[0]) << 15) + ((this->prom_[2] * d_t) >> 8); if (temperature < 20.0f) { - const float T2 = (dT*dT) / 2147483648.0f; + const float t2 = (d_t * d_t) / 2147483648.0f; const float temp20 = (temperature - 20.0f) * 100.0f; float pressure_offset_2 = 2.5f * temp20 * temp20; float pressure_sensitivity_2 = 1.25f * temp20 * temp20; @@ -98,7 +96,7 @@ void MS5611Component::calculate_values(uint32_t raw_temperature, uint32_t raw_pr pressure_offset_2 += 7.0f * temp15; pressure_sensitivity_2 += 5.5f * temp15; } - temperature -= T2; + temperature -= t2; pressure_offset -= pressure_offset_2; pressure_sensitivity -= pressure_sensitivity_2; } @@ -108,24 +106,20 @@ void MS5611Component::calculate_values(uint32_t raw_temperature, uint32_t raw_pr ESP_LOGD(TAG, "Got temperature=%0.02f°C pressure=%0.01fhPa", temperature, pressure); this->temperature_sensor_->publish_state(temperature); - this->pressure_sensor_->publish_state(pressure); // hPa + this->pressure_sensor_->publish_state(pressure); // hPa this->status_clear_warning(); } -MS5611TemperatureSensor *MS5611Component::get_temperature_sensor() const { - return this->temperature_sensor_; -} -MS5611PressureSensor *MS5611Component::get_pressure_sensor() const { - return this->pressure_sensor_; -} -MS5611Component::MS5611Component(I2CComponent *parent, const std::string &temperature_name, const std::string &pressure_name, - uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, MS5611_ADDRESS), - temperature_sensor_(new MS5611TemperatureSensor(temperature_name, this)), - pressure_sensor_(new MS5611PressureSensor(pressure_name, this)) { -} +MS5611TemperatureSensor *MS5611Component::get_temperature_sensor() const { return this->temperature_sensor_; } +MS5611PressureSensor *MS5611Component::get_pressure_sensor() const { return this->pressure_sensor_; } +MS5611Component::MS5611Component(I2CComponent *parent, const std::string &temperature_name, + const std::string &pressure_name, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, MS5611_ADDRESS), + temperature_sensor_(new MS5611TemperatureSensor(temperature_name, this)), + pressure_sensor_(new MS5611PressureSensor(pressure_name, this)) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MS5611 +#endif // USE_MS5611 diff --git a/src/esphome/sensor/ms5611.h b/src/esphome/sensor/ms5611.h index 03c20627..c48e2ff8 100644 --- a/src/esphome/sensor/ms5611.h +++ b/src/esphome/sensor/ms5611.h @@ -31,17 +31,17 @@ class MS5611Component : public PollingComponent, public I2CDevice { protected: void read_temperature_(); void read_pressure_(uint32_t raw_temperature); - void calculate_values(uint32_t raw_temperature, uint32_t raw_pressure); + void calculate_values_(uint32_t raw_temperature, uint32_t raw_pressure); MS5611TemperatureSensor *temperature_sensor_; MS5611PressureSensor *pressure_sensor_; - uint16_t prom[6]; + uint16_t prom_[6]; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_MS5611 +#endif // USE_MS5611 -#endif //ESPHOME_SENSOR_MS5611_H +#endif // ESPHOME_SENSOR_MS5611_H diff --git a/src/esphome/sensor/pmsx003.cpp b/src/esphome/sensor/pmsx003.cpp index 14fbed2f..00afa45b 100644 --- a/src/esphome/sensor/pmsx003.cpp +++ b/src/esphome/sensor/pmsx003.cpp @@ -38,9 +38,7 @@ void PMSX003Component::loop() { } } } -float PMSX003Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float PMSX003Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } optional PMSX003Component::check_byte_() { uint8_t index = this->data_index_; uint8_t byte = this->data_[index]; @@ -70,8 +68,7 @@ optional PMSX003Component::check_byte_() { } if (!length_matches) { - ESP_LOGW(TAG, "PMSX003 length %u doesn't match. Are you using the correct PMSX003 type?", - payload_length); + ESP_LOGW(TAG, "PMSX003 length %u doesn't match. Are you using the correct PMSX003 type?", payload_length); return false; } return true; @@ -103,8 +100,9 @@ void PMSX003Component::parse_data_() { uint16_t pm_1_0_concentration = this->get_16_bit_uint_(10); uint16_t pm_2_5_concentration = this->get_16_bit_uint_(12); uint16_t pm_10_0_concentration = this->get_16_bit_uint_(14); - ESP_LOGD(TAG, "Got PM1.0 Concentration: %u µg/m^3, PM2.5 Concentration %u µg/m^3, PM10.0 Concentration: %u µg/m^3", - pm_1_0_concentration, pm_2_5_concentration, pm_10_0_concentration); + ESP_LOGD(TAG, + "Got PM1.0 Concentration: %u µg/m^3, PM2.5 Concentration %u µg/m^3, PM10.0 Concentration: %u µg/m^3", + pm_1_0_concentration, pm_2_5_concentration, pm_10_0_concentration); if (this->pm_1_0_sensor_ != nullptr) this->pm_1_0_sensor_->publish_state(pm_1_0_concentration); if (this->pm_2_5_sensor_ != nullptr) @@ -117,8 +115,8 @@ void PMSX003Component::parse_data_() { uint16_t pm_2_5_concentration = this->get_16_bit_uint_(12); float temperature = this->get_16_bit_uint_(24) / 10.0f; float humidity = this->get_16_bit_uint_(26) / 10.0f; - ESP_LOGD(TAG, "Got PM2.5 Concentration: %u µg/m^3, Temperature: %.1f°C, Humidity: %.1f%%", - pm_2_5_concentration, temperature, humidity); + ESP_LOGD(TAG, "Got PM2.5 Concentration: %u µg/m^3, Temperature: %.1f°C, Humidity: %.1f%%", pm_2_5_concentration, + temperature, humidity); if (this->pm_2_5_sensor_ != nullptr) this->pm_2_5_sensor_->publish_state(pm_2_5_concentration); if (this->temperature_sensor_ != nullptr) @@ -169,9 +167,7 @@ PMSX003Sensor *PMSX003Component::make_humidity_sensor(const std::string &name) { PMSX003Sensor *PMSX003Component::make_formaldehyde_sensor(const std::string &name) { return this->formaldehyde_sensor_ = new PMSX003Sensor(name, PMSX003_SENSOR_TYPE_FORMALDEHYDE); } -PMSX003Component::PMSX003Component(UARTComponent *parent, PMSX003Type type) : UARTDevice(parent), type_(type) { - -} +PMSX003Component::PMSX003Component(UARTComponent *parent, PMSX003Type type) : UARTDevice(parent), type_(type) {} void PMSX003Component::dump_config() { ESP_LOGCONFIG(TAG, "PMSX003:"); LOG_SENSOR(" ", "PM1.0", this->pm_1_0_sensor_); @@ -225,13 +221,10 @@ int8_t PMSX003Sensor::accuracy_decimals() { return 0; } -PMSX003Sensor::PMSX003Sensor(const std::string &name, PMSX003SensorType type) - : Sensor(name), type_(type) { - -} +PMSX003Sensor::PMSX003Sensor(const std::string &name, PMSX003SensorType type) : Sensor(name), type_(type) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_PMSX003 +#endif // USE_PMSX003 diff --git a/src/esphome/sensor/pmsx003.h b/src/esphome/sensor/pmsx003.h index db097b72..6e44592e 100644 --- a/src/esphome/sensor/pmsx003.h +++ b/src/esphome/sensor/pmsx003.h @@ -79,10 +79,10 @@ class PMSX003Component : public UARTDevice, public Component { PMSX003Sensor *formaldehyde_sensor_{nullptr}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_PMSX003 +#endif // USE_PMSX003 -#endif //ESPHOME_SENSOR_PMSX003_H +#endif // ESPHOME_SENSOR_PMSX003_H diff --git a/src/esphome/sensor/pulse_counter.cpp b/src/esphome/sensor/pulse_counter.cpp index c4163478..21d8bf94 100644 --- a/src/esphome/sensor/pulse_counter.cpp +++ b/src/esphome/sensor/pulse_counter.cpp @@ -17,29 +17,25 @@ static const char *TAG = "sensor.pulse_counter"; PulseCounterBase::PulseCounterBase(GPIOPin *pin) : pin_(pin) { #ifdef ARDUINO_ARCH_ESP32 this->pcnt_unit_ = next_pcnt_unit; - next_pcnt_unit = pcnt_unit_t(int(next_pcnt_unit) + 1); // NOLINT + next_pcnt_unit = pcnt_unit_t(int(next_pcnt_unit) + 1); // NOLINT #endif } -PulseCounterSensorComponent::PulseCounterSensorComponent(const std::string &name, - GPIOPin *pin, +PulseCounterSensorComponent::PulseCounterSensorComponent(const std::string &name, GPIOPin *pin, uint32_t update_interval) - : PollingSensorComponent(name, update_interval), PulseCounterBase(pin) { - -} -void PulseCounterSensorComponent::set_edge_mode(PulseCounterCountMode rising_edge_mode, PulseCounterCountMode falling_edge_mode) { + : PollingSensorComponent(name, update_interval), PulseCounterBase(pin) {} +void PulseCounterSensorComponent::set_edge_mode(PulseCounterCountMode rising_edge_mode, + PulseCounterCountMode falling_edge_mode) { this->rising_edge_mode_ = rising_edge_mode; this->falling_edge_mode_ = falling_edge_mode; } const char *EDGE_MODE_TO_STRING[] = {"DISABLE", "INCREMENT", "DECREMENT"}; -GPIOPin *PulseCounterBase::get_pin() { - return this->pin_; -} +GPIOPin *PulseCounterBase::get_pin() { return this->pin_; } #ifdef ARDUINO_ARCH_ESP8266 -void ICACHE_RAM_ATTR HOT PulseCounterBase::gpio_intr() { +void ICACHE_RAM_ATTR HOT PulseCounterBase::gpio_intr_() { const uint32_t now = micros(); const bool discard = now - this->last_pulse_ < this->filter_us_; this->last_pulse_ = now; @@ -58,14 +54,12 @@ void ICACHE_RAM_ATTR HOT PulseCounterBase::gpio_intr() { break; } } -bool PulseCounterBase::pulse_counter_setup_() { +bool PulseCounterBase::pulse_counter_setup() { this->pin_->setup(); - attach_functional_interrupt(this->pin_->get_pin(), [this]() ICACHE_RAM_ATTR { - this->gpio_intr(); - }, CHANGE); + attach_functional_interrupt(this->pin_->get_pin(), [this]() ICACHE_RAM_ATTR { this->gpio_intr_(); }, CHANGE); return true; } -pulse_counter_t PulseCounterBase::read_raw_value_() { +pulse_counter_t PulseCounterBase::read_raw_value() { pulse_counter_t counter = this->counter_; pulse_counter_t ret = counter - this->last_value_; this->last_value_ = counter; @@ -74,19 +68,31 @@ pulse_counter_t PulseCounterBase::read_raw_value_() { #endif #ifdef ARDUINO_ARCH_ESP32 -bool PulseCounterBase::pulse_counter_setup_() { +bool PulseCounterBase::pulse_counter_setup() { ESP_LOGCONFIG(TAG, " PCNT Unit Number: %u", this->pcnt_unit_); pcnt_count_mode_t rising = PCNT_COUNT_DIS, falling = PCNT_COUNT_DIS; switch (this->rising_edge_mode_) { - case PULSE_COUNTER_DISABLE: rising = PCNT_COUNT_DIS; break; - case PULSE_COUNTER_INCREMENT: rising = PCNT_COUNT_INC; break; - case PULSE_COUNTER_DECREMENT: rising = PCNT_COUNT_DEC; break; + case PULSE_COUNTER_DISABLE: + rising = PCNT_COUNT_DIS; + break; + case PULSE_COUNTER_INCREMENT: + rising = PCNT_COUNT_INC; + break; + case PULSE_COUNTER_DECREMENT: + rising = PCNT_COUNT_DEC; + break; } switch (this->falling_edge_mode_) { - case PULSE_COUNTER_DISABLE: falling = PCNT_COUNT_DIS; break; - case PULSE_COUNTER_INCREMENT: falling = PCNT_COUNT_INC; break; - case PULSE_COUNTER_DECREMENT: falling = PCNT_COUNT_DEC; break; + case PULSE_COUNTER_DISABLE: + falling = PCNT_COUNT_DIS; + break; + case PULSE_COUNTER_INCREMENT: + falling = PCNT_COUNT_INC; + break; + case PULSE_COUNTER_DECREMENT: + falling = PCNT_COUNT_DEC; + break; } pcnt_config_t pcnt_config = { @@ -139,7 +145,7 @@ bool PulseCounterBase::pulse_counter_setup_() { } return true; } -pulse_counter_t PulseCounterBase::read_raw_value_() { +pulse_counter_t PulseCounterBase::read_raw_value() { pulse_counter_t counter; pcnt_get_counter_value(this->pcnt_unit_, &counter); pulse_counter_t ret = counter - this->last_value_; @@ -150,7 +156,7 @@ pulse_counter_t PulseCounterBase::read_raw_value_() { void PulseCounterSensorComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up pulse counter '%s'...", this->name_.c_str()); - if (!this->pulse_counter_setup_()) { + if (!this->pulse_counter_setup()) { this->mark_failed(); return; } @@ -165,35 +171,25 @@ void PulseCounterSensorComponent::dump_config() { } void PulseCounterSensorComponent::update() { - pulse_counter_t raw = this->read_raw_value_(); - float value = (60000.0f * raw) / float(this->get_update_interval()); // per minute + pulse_counter_t raw = this->read_raw_value(); + float value = (60000.0f * raw) / float(this->get_update_interval()); // per minute ESP_LOGD(TAG, "'%s': Retrieved counter: %0.2f pulses/min", this->get_name().c_str(), value); this->publish_state(value); } -float PulseCounterSensorComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -std::string PulseCounterSensorComponent::unit_of_measurement() { - return "pulses/min"; -} -std::string PulseCounterSensorComponent::icon() { - return "mdi:pulse"; -} -int8_t PulseCounterSensorComponent::accuracy_decimals() { - return 2; -} -void PulseCounterSensorComponent::set_filter_us(uint32_t filter_us) { - this->filter_us_ = filter_us; -} +float PulseCounterSensorComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +std::string PulseCounterSensorComponent::unit_of_measurement() { return "pulses/min"; } +std::string PulseCounterSensorComponent::icon() { return "mdi:pulse"; } +int8_t PulseCounterSensorComponent::accuracy_decimals() { return 2; } +void PulseCounterSensorComponent::set_filter_us(uint32_t filter_us) { this->filter_us_ = filter_us; } #ifdef ARDUINO_ARCH_ESP32 pcnt_unit_t next_pcnt_unit = PCNT_UNIT_0; #endif -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_PULSE_COUNTER_SENSOR +#endif // USE_PULSE_COUNTER_SENSOR diff --git a/src/esphome/sensor/pulse_counter.h b/src/esphome/sensor/pulse_counter.h index 3e5b1ac2..11200110 100644 --- a/src/esphome/sensor/pulse_counter.h +++ b/src/esphome/sensor/pulse_counter.h @@ -9,7 +9,7 @@ #include "esphome/esphal.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -32,14 +32,14 @@ using pulse_counter_t = int32_t; class PulseCounterBase { public: PulseCounterBase(GPIOPin *pin); - bool pulse_counter_setup_(); - pulse_counter_t read_raw_value_(); + bool pulse_counter_setup(); + pulse_counter_t read_raw_value(); GPIOPin *get_pin(); protected: #ifdef ARDUINO_ARCH_ESP8266 - void gpio_intr(); + void gpio_intr_(); volatile pulse_counter_t counter_{0}; volatile uint32_t last_pulse_{0}; #endif @@ -98,10 +98,10 @@ class PulseCounterSensorComponent : public PollingSensorComponent, public PulseC extern pcnt_unit_t next_pcnt_unit; #endif -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_PULSE_COUNTER_SENSOR +#endif // USE_PULSE_COUNTER_SENSOR -#endif //ESPHOME_SENSOR_PULSE_COUNTER_H +#endif // ESPHOME_SENSOR_PULSE_COUNTER_H diff --git a/src/esphome/sensor/rotary_encoder.cpp b/src/esphome/sensor/rotary_encoder.cpp index a7a52950..d0f42093 100644 --- a/src/esphome/sensor/rotary_encoder.cpp +++ b/src/esphome/sensor/rotary_encoder.cpp @@ -12,84 +12,65 @@ namespace sensor { static const char *TAG = "sensor.rotary_encoder"; // copied from https://github.com/jkDesignDE/MechInputs/blob/master/QEIx4.cpp -static const uint16_t QEIx4_MASK = 0x1C; -static const uint16_t QEIx4_1x_INC = 0x0100; -static const uint16_t QEIx4_2x_INC = 0x0200; -static const uint16_t QEIx4_4x_INC = 0x0400; -static const uint16_t QEIx4_1x_DEC = 0x1000; -static const uint16_t QEIx4_2x_DEC = 0x2000; -static const uint16_t QEIx4_4x_DEC = 0x4000; -static const uint16_t QEIx4_DIR = 0x20; -static const uint16_t QEIx4_A = 1; -static const uint16_t QEIx4_B = 2; -static const uint16_t QEIx4_AB = 3; -static const uint16_t QEIx4_S0 = 0x0; -static const uint16_t QEIx4_S1 = 0x4; -static const uint16_t QEIx4_S2 = 0x8; -static const uint16_t QEIx4_S3 = 0xC; -static const uint16_t QEIx4_CCW = 0; -static const uint16_t QEIx4_CW = 0x10; -static const uint16_t QEIx4_IS_CHG = 0x7700; -static const uint16_t QEIx4_IS_INC = 0x0700; -static const uint16_t QEIx4_IS_DEC = 0x7000; +static const uint16_t QE_IX4_MASK = 0x1C; +static const uint16_t QE_IX4_1X_INC = 0x0100; +static const uint16_t QE_IX4_2X_INC = 0x0200; +static const uint16_t QE_IX4_4X_INC = 0x0400; +static const uint16_t QE_IX4_1X_DEC = 0x1000; +static const uint16_t QE_IX4_2X_DEC = 0x2000; +static const uint16_t QE_IX4_4X_DEC = 0x4000; +static const uint16_t QE_IX4_DIR = 0x20; +static const uint16_t QE_IX4_A = 1; +static const uint16_t QE_IX4_B = 2; +static const uint16_t QE_IX4_AB = 3; +static const uint16_t QE_IX4_S0 = 0x0; +static const uint16_t QE_IX4_S1 = 0x4; +static const uint16_t QE_IX4_S2 = 0x8; +static const uint16_t QE_IX4_S3 = 0xC; +static const uint16_t QE_IX4_CCW = 0; +static const uint16_t QE_IX4_CW = 0x10; +static const uint16_t QE_IX4_IS_CHG = 0x7700; +static const uint16_t QE_IX4_IS_INC = 0x0700; +static const uint16_t QE_IX4_IS_DEC = 0x7000; static uint16_t state_lookup_table[32] = { // act state S0 in CCW direction - QEIx4_CCW | QEIx4_S0, - QEIx4_CW | QEIx4_S1 | QEIx4_A | QEIx4_4x_INC | QEIx4_DIR, - QEIx4_CCW | QEIx4_S0 | QEIx4_B, - QEIx4_CCW | QEIx4_S3 | QEIx4_AB | QEIx4_1x_DEC, + QE_IX4_CCW | QE_IX4_S0, QE_IX4_CW | QE_IX4_S1 | QE_IX4_A | QE_IX4_4X_INC | QE_IX4_DIR, + QE_IX4_CCW | QE_IX4_S0 | QE_IX4_B, QE_IX4_CCW | QE_IX4_S3 | QE_IX4_AB | QE_IX4_1X_DEC, // act state S1 in CCW direction - QEIx4_CCW | QEIx4_S1, - QEIx4_CCW | QEIx4_S1 | QEIx4_A, - QEIx4_CCW | QEIx4_S0 | QEIx4_B | QEIx4_4x_DEC, - QEIx4_CW | QEIx4_S2 | QEIx4_AB | QEIx4_1x_INC | QEIx4_DIR, + QE_IX4_CCW | QE_IX4_S1, QE_IX4_CCW | QE_IX4_S1 | QE_IX4_A, QE_IX4_CCW | QE_IX4_S0 | QE_IX4_B | QE_IX4_4X_DEC, + QE_IX4_CW | QE_IX4_S2 | QE_IX4_AB | QE_IX4_1X_INC | QE_IX4_DIR, // act state S2 in CCW direction - QEIx4_CCW | QEIx4_S1 | QEIx4_2x_DEC, - QEIx4_CCW | QEIx4_S2 | QEIx4_A, - QEIx4_CW | QEIx4_S3 | QEIx4_B | QEIx4_4x_INC | QEIx4_DIR, - QEIx4_CCW | QEIx4_S2 | QEIx4_AB, + QE_IX4_CCW | QE_IX4_S1 | QE_IX4_2X_DEC, QE_IX4_CCW | QE_IX4_S2 | QE_IX4_A, + QE_IX4_CW | QE_IX4_S3 | QE_IX4_B | QE_IX4_4X_INC | QE_IX4_DIR, QE_IX4_CCW | QE_IX4_S2 | QE_IX4_AB, // act state S3 in CCW direction - QEIx4_CW | QEIx4_S0 | QEIx4_2x_INC | QEIx4_DIR, - QEIx4_CCW | QEIx4_S2 | QEIx4_A | QEIx4_4x_DEC, - QEIx4_CCW | QEIx4_S3 | QEIx4_B, - QEIx4_CCW | QEIx4_S3 | QEIx4_AB, + QE_IX4_CW | QE_IX4_S0 | QE_IX4_2X_INC | QE_IX4_DIR, QE_IX4_CCW | QE_IX4_S2 | QE_IX4_A | QE_IX4_4X_DEC, + QE_IX4_CCW | QE_IX4_S3 | QE_IX4_B, QE_IX4_CCW | QE_IX4_S3 | QE_IX4_AB, // act state S0 in CW direction - QEIx4_CW | QEIx4_S0, - QEIx4_CW | QEIx4_S1 | QEIx4_A | QEIx4_4x_INC, - QEIx4_CW | QEIx4_S0 | QEIx4_B, - QEIx4_CCW | QEIx4_S3 | QEIx4_AB | QEIx4_1x_DEC | QEIx4_DIR, + QE_IX4_CW | QE_IX4_S0, QE_IX4_CW | QE_IX4_S1 | QE_IX4_A | QE_IX4_4X_INC, QE_IX4_CW | QE_IX4_S0 | QE_IX4_B, + QE_IX4_CCW | QE_IX4_S3 | QE_IX4_AB | QE_IX4_1X_DEC | QE_IX4_DIR, // act state S1 in CW direction - QEIx4_CW | QEIx4_S1, - QEIx4_CW | QEIx4_S1 | QEIx4_A, - QEIx4_CCW | QEIx4_S0 | QEIx4_B | QEIx4_4x_DEC | QEIx4_DIR, - QEIx4_CW | QEIx4_S2 | QEIx4_AB | QEIx4_1x_INC, + QE_IX4_CW | QE_IX4_S1, QE_IX4_CW | QE_IX4_S1 | QE_IX4_A, + QE_IX4_CCW | QE_IX4_S0 | QE_IX4_B | QE_IX4_4X_DEC | QE_IX4_DIR, QE_IX4_CW | QE_IX4_S2 | QE_IX4_AB | QE_IX4_1X_INC, // act state S2 in CW direction - QEIx4_CCW | QEIx4_S1 | QEIx4_2x_DEC | QEIx4_DIR, - QEIx4_CW | QEIx4_S2 | QEIx4_A, - QEIx4_CW | QEIx4_S3 | QEIx4_B | QEIx4_4x_INC, - QEIx4_CW | QEIx4_S2 | QEIx4_AB, + QE_IX4_CCW | QE_IX4_S1 | QE_IX4_2X_DEC | QE_IX4_DIR, QE_IX4_CW | QE_IX4_S2 | QE_IX4_A, + QE_IX4_CW | QE_IX4_S3 | QE_IX4_B | QE_IX4_4X_INC, QE_IX4_CW | QE_IX4_S2 | QE_IX4_AB, // act state S3 in CW direction - QEIx4_CW | QEIx4_S0 | QEIx4_2x_INC, - QEIx4_CCW | QEIx4_S2 | QEIx4_A | QEIx4_4x_DEC | QEIx4_DIR, - QEIx4_CW | QEIx4_S3 | QEIx4_B, - QEIx4_CW | QEIx4_S3 | QEIx4_AB -}; + QE_IX4_CW | QE_IX4_S0 | QE_IX4_2X_INC, QE_IX4_CCW | QE_IX4_S2 | QE_IX4_A | QE_IX4_4X_DEC | QE_IX4_DIR, + QE_IX4_CW | QE_IX4_S3 | QE_IX4_B, QE_IX4_CW | QE_IX4_S3 | QE_IX4_AB}; RotaryEncoderSensor::RotaryEncoderSensor(const std::string &name, GPIOPin *pin_a, GPIOPin *pin_b) - : Sensor(name), Component(), pin_a_(pin_a), pin_b_(pin_b) { - -} + : Sensor(name), Component(), pin_a_(pin_a), pin_b_(pin_b) {} void RotaryEncoderSensor::setup() { ESP_LOGCONFIG(TAG, "Setting up Rotary Encoder '%s'...", this->name_.c_str()); int interrupt_a = digitalPinToInterrupt(this->pin_a_->get_pin()); this->pin_a_->setup(); - attachInterrupt(interrupt_a, RotaryEncoderSensor::encoder_isr_, CHANGE); + attachInterrupt(interrupt_a, RotaryEncoderSensor::encoder_isr, CHANGE); int interrupt_b = digitalPinToInterrupt(this->pin_b_->get_pin()); this->pin_b_->setup(); - attachInterrupt(interrupt_b, RotaryEncoderSensor::encoder_isr_, CHANGE); + attachInterrupt(interrupt_b, RotaryEncoderSensor::encoder_isr, CHANGE); if (this->pin_i_ != nullptr) { this->pin_i_->setup(); @@ -103,29 +84,29 @@ void RotaryEncoderSensor::dump_config() { LOG_PIN(" Pin B: ", this->pin_b_); LOG_PIN(" Pin I: ", this->pin_i_); } -void ICACHE_RAM_ATTR RotaryEncoderSensor::encoder_isr_() { +void ICACHE_RAM_ATTR RotaryEncoderSensor::encoder_isr() { for (auto *encoder : global_rotary_encoders_) { encoder->process_state_machine_(); } } void ICACHE_RAM_ATTR RotaryEncoderSensor::process_state_machine_() { - this->state_ &= QEIx4_MASK; + this->state_ &= QE_IX4_MASK; if (this->pin_a_->digital_read()) - this->state_ |= QEIx4_A; + this->state_ |= QE_IX4_A; if (this->pin_b_->digital_read()) - this->state_ |= QEIx4_B; + this->state_ |= QE_IX4_B; this->state_ = state_lookup_table[this->state_]; this->state_ &= this->resolution_; - if ((this->state_ & QEIx4_IS_CHG) != 0) { + if ((this->state_ & QE_IX4_IS_CHG) != 0) { bool counter_change = false; - if ((this->state_ & QEIx4_IS_INC) != 0) { + if ((this->state_ & QE_IX4_IS_INC) != 0) { this->counter_ = std::min(this->counter_ + 1, this->max_value_); counter_change = true; } - if ((this->state_ & QEIx4_IS_DEC) != 0) { + if ((this->state_ & QE_IX4_IS_DEC) != 0) { this->counter_ = std::max(this->counter_ - 1, this->min_value_); counter_change = true; } @@ -143,32 +124,20 @@ void RotaryEncoderSensor::loop() { this->publish_state(this->counter_); } } -std::string RotaryEncoderSensor::unit_of_measurement() { - return "steps"; -} -std::string RotaryEncoderSensor::icon() { - return "mdi:rotate-right"; -} -int8_t RotaryEncoderSensor::accuracy_decimals() { - return 0; -} -void RotaryEncoderSensor::set_resolution(RotaryEncoderResolution mode) { - this->resolution_ = mode; -} -void RotaryEncoderSensor::set_reset_pin(const GPIOInputPin &pin_i) { - this->pin_i_ = pin_i.copy(); -} +std::string RotaryEncoderSensor::unit_of_measurement() { return "steps"; } +std::string RotaryEncoderSensor::icon() { return "mdi:rotate-right"; } +int8_t RotaryEncoderSensor::accuracy_decimals() { return 0; } +void RotaryEncoderSensor::set_resolution(RotaryEncoderResolution mode) { this->resolution_ = mode; } +void RotaryEncoderSensor::set_reset_pin(const GPIOInputPin &pin_i) { this->pin_i_ = pin_i.copy(); } std::vector global_rotary_encoders_; -float RotaryEncoderSensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float RotaryEncoderSensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void RotaryEncoderSensor::set_min_value(int32_t min_value) { this->min_value_ = min_value; } void RotaryEncoderSensor::set_max_value(int32_t max_value) { this->max_value_ = max_value; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ROTARY_ENCODER_SENSOR +#endif // USE_ROTARY_ENCODER_SENSOR diff --git a/src/esphome/sensor/rotary_encoder.h b/src/esphome/sensor/rotary_encoder.h index 327510cb..a81c1baf 100644 --- a/src/esphome/sensor/rotary_encoder.h +++ b/src/esphome/sensor/rotary_encoder.h @@ -16,9 +16,10 @@ namespace sensor { /// All possible resolutions for the rotary encoder enum RotaryEncoderResolution { - ROTARY_ENCODER_1_PULSE_PER_CYCLE = 0x11FF, /// increment counter by 1 with every A-B cycle, slow response but accurate - ROTARY_ENCODER_2_PULSES_PER_CYCLE = 0x33FF, /// increment counter by 2 with every A-B cycle - ROTARY_ENCODER_4_PULSES_PER_CYCLE = 0x77FF, /// increment counter by 4 with every A-B cycle, most inaccurate + ROTARY_ENCODER_1_PULSE_PER_CYCLE = + 0x11FF, /// increment counter by 1 with every A-B cycle, slow response but accurate + ROTARY_ENCODER_2_PULSES_PER_CYCLE = 0x33FF, /// increment counter by 2 with every A-B cycle + ROTARY_ENCODER_4_PULSES_PER_CYCLE = 0x77FF, /// increment counter by 4 with every A-B cycle, most inaccurate }; class RotaryEncoderSensor : public Sensor, public Component { @@ -51,16 +52,16 @@ class RotaryEncoderSensor : public Sensor, public Component { protected: /// The ISR that handles pushing all interrupts to process_state_machine_ of all rotary encoders. - static void encoder_isr_(); + static void encoder_isr(); /// Process the state machine state of this rotary encoder. Called from encoder_isr_ void process_state_machine_(); GPIOPin *pin_a_; GPIOPin *pin_b_; - GPIOPin *pin_i_{nullptr}; /// Index pin, if this is not nullptr, the counter will reset to 0 once this pin is HIGH. + GPIOPin *pin_i_{nullptr}; /// Index pin, if this is not nullptr, the counter will reset to 0 once this pin is HIGH. - volatile int32_t counter_{0}; /// The internal counter for steps + volatile int32_t counter_{0}; /// The internal counter for steps volatile bool has_changed_{true}; uint16_t state_{0}; RotaryEncoderResolution resolution_{ROTARY_ENCODER_1_PULSE_PER_CYCLE}; @@ -71,10 +72,10 @@ class RotaryEncoderSensor : public Sensor, public Component { /// Global storage for having multiple rotary encoders with a single ISR extern std::vector global_rotary_encoders_; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ROTARY_ENCODER_SENSOR +#endif // USE_ROTARY_ENCODER_SENSOR -#endif //ESPHOME_ROTARY_ENCODER_H +#endif // ESPHOME_ROTARY_ENCODER_H diff --git a/src/esphome/sensor/sensor.cpp b/src/esphome/sensor/sensor.cpp index 021ead70..b90da25c 100644 --- a/src/esphome/sensor/sensor.cpp +++ b/src/esphome/sensor/sensor.cpp @@ -20,47 +20,25 @@ void Sensor::publish_state(float state) { ESP_LOGV(TAG, "'%s': Received new state %f", this->name_.c_str(), state); if (this->filter_list_ == nullptr) { - this->send_state_to_frontend_internal_(state); + this->internal_send_state_to_frontend(state); } else { this->filter_list_->input(state); } } -void Sensor::push_new_value(float state) { - this->publish_state(state); -} -std::string Sensor::unit_of_measurement() { - return ""; -} -std::string Sensor::icon() { - return ""; -} -uint32_t Sensor::update_interval() { - return 0; -} -int8_t Sensor::accuracy_decimals() { - return 0; -} -Sensor::Sensor(const std::string &name) - : Nameable(name), state(NAN), raw_state(NAN) { - -} -Sensor::Sensor() - : Sensor("") { - -} +void Sensor::push_new_value(float state) { this->publish_state(state); } +std::string Sensor::unit_of_measurement() { return ""; } +std::string Sensor::icon() { return ""; } +uint32_t Sensor::update_interval() { return 0; } +int8_t Sensor::accuracy_decimals() { return 0; } +Sensor::Sensor(const std::string &name) : Nameable(name), state(NAN), raw_state(NAN) {} +Sensor::Sensor() : Sensor("") {} void Sensor::set_unit_of_measurement(const std::string &unit_of_measurement) { this->unit_of_measurement_ = unit_of_measurement; } -void Sensor::set_icon(const std::string &icon) { - this->icon_ = icon; -} -void Sensor::set_accuracy_decimals(int8_t accuracy_decimals) { - this->accuracy_decimals_ = accuracy_decimals; -} -void Sensor::add_on_state_callback(std::function &&callback) { - this->callback_.add(std::move(callback)); -} +void Sensor::set_icon(const std::string &icon) { this->icon_ = icon; } +void Sensor::set_accuracy_decimals(int8_t accuracy_decimals) { this->accuracy_decimals_ = accuracy_decimals; } +void Sensor::add_on_state_callback(std::function &&callback) { this->callback_.add(std::move(callback)); } void Sensor::add_on_raw_state_callback(std::function &&callback) { this->raw_callback_.add(std::move(callback)); } @@ -108,42 +86,25 @@ void Sensor::clear_filters() { } this->filter_list_ = nullptr; } -float Sensor::get_value() const { - return this->state; -} -float Sensor::get_state() const { - return this->state; -} -float Sensor::get_raw_value() const { - return this->raw_state; -} -float Sensor::get_raw_state() const { - return this->raw_state; -} +float Sensor::get_value() const { return this->state; } +float Sensor::get_state() const { return this->state; } +float Sensor::get_raw_value() const { return this->raw_state; } +float Sensor::get_raw_state() const { return this->raw_state; } std::string Sensor::unique_id() { return ""; } -void Sensor::send_state_to_frontend_internal_(float state) { +void Sensor::internal_send_state_to_frontend(float state) { this->has_state_ = true; this->state = state; if (this->filter_list_ != nullptr) { - ESP_LOGD(TAG, "'%s': Sending state %.5f %s with %d decimals of accuracy", - this->get_name().c_str(), state, this->get_unit_of_measurement().c_str(), - this->get_accuracy_decimals()); + ESP_LOGD(TAG, "'%s': Sending state %.5f %s with %d decimals of accuracy", this->get_name().c_str(), state, + this->get_unit_of_measurement().c_str(), this->get_accuracy_decimals()); } this->callback_.call(state); } -SensorStateTrigger *Sensor::make_state_trigger() { - return new SensorStateTrigger(this); -} -SensorRawStateTrigger *Sensor::make_raw_state_trigger() { - return new SensorRawStateTrigger(this); -} -ValueRangeTrigger *Sensor::make_value_range_trigger() { - return new ValueRangeTrigger(this); -} -bool Sensor::has_state() const { - return this->has_state_; -} +SensorStateTrigger *Sensor::make_state_trigger() { return new SensorStateTrigger(this); } +SensorRawStateTrigger *Sensor::make_raw_state_trigger() { return new SensorRawStateTrigger(this); } +ValueRangeTrigger *Sensor::make_value_range_trigger() { return new ValueRangeTrigger(this); } +bool Sensor::has_state() const { return this->has_state_; } uint32_t Sensor::calculate_expected_filter_update_interval() { uint32_t interval = this->update_interval(); if (interval == 4294967295UL) @@ -156,25 +117,17 @@ uint32_t Sensor::calculate_expected_filter_update_interval() { return this->filter_list_->calculate_remaining_interval(interval); } -uint32_t Sensor::hash_base_() { - return 2455723294UL; -} +uint32_t Sensor::hash_base() { return 2455723294UL; } #ifdef USE_MQTT_SENSOR -MQTTSensorComponent *Sensor::get_mqtt() const { - return this->mqtt_; -} -void Sensor::set_mqtt(MQTTSensorComponent *mqtt) { - this->mqtt_ = mqtt; -} +MQTTSensorComponent *Sensor::get_mqtt() const { return this->mqtt_; } +void Sensor::set_mqtt(MQTTSensorComponent *mqtt) { this->mqtt_ = mqtt; } #endif PollingSensorComponent::PollingSensorComponent(const std::string &name, uint32_t update_interval) : PollingComponent(update_interval), Sensor(name) {} -uint32_t PollingSensorComponent::update_interval() { - return this->get_update_interval(); -} +uint32_t PollingSensorComponent::update_interval() { return this->get_update_interval(); } const char ICON_FLASH[] = "mdi:flash"; const char UNIT_V[] = "V"; @@ -209,20 +162,14 @@ const char UNIT_MICROGRAMS_PER_CUBIC_METER[] = "µg/m^3"; const char ICON_CHEMICAL_WEAPON[] = "mdi:chemical-weapon"; SensorStateTrigger::SensorStateTrigger(Sensor *parent) { - parent->add_on_state_callback([this](float value) { - this->trigger(value); - }); + parent->add_on_state_callback([this](float value) { this->trigger(value); }); } SensorRawStateTrigger::SensorRawStateTrigger(Sensor *parent) { - parent->add_on_raw_state_callback([this](float value) { - this->trigger(value); - }); + parent->add_on_raw_state_callback([this](float value) { this->trigger(value); }); } -ValueRangeTrigger::ValueRangeTrigger(Sensor *parent) : parent_(parent) { - -} +ValueRangeTrigger::ValueRangeTrigger(Sensor *parent) : parent_(parent) {} void ValueRangeTrigger::on_state_(float state) { if (isnan(state)) return; @@ -255,16 +202,12 @@ void ValueRangeTrigger::setup() { this->previous_in_range_ = initial_state; } - this->parent_->add_on_state_callback([this](float state) { - this->on_state_(state); - }); -} -float ValueRangeTrigger::get_setup_priority() const { - return setup_priority::HARDWARE; + this->parent_->add_on_state_callback([this](float state) { this->on_state_(state); }); } +float ValueRangeTrigger::get_setup_priority() const { return setup_priority::HARDWARE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_SENSOR +#endif // USE_SENSOR diff --git a/src/esphome/sensor/sensor.h b/src/esphome/sensor/sensor.h index bba13bc7..1c61355a 100644 --- a/src/esphome/sensor/sensor.h +++ b/src/esphome/sensor/sensor.h @@ -21,23 +21,21 @@ class MQTTSensorComponent; class SensorStateTrigger; class SensorRawStateTrigger; class ValueRangeTrigger; -template -class SensorInRangeCondition; -template -class SensorPublishAction; +template class SensorInRangeCondition; +template class SensorPublishAction; #define LOG_SENSOR(prefix, type, obj) \ - if (obj != nullptr) { \ - ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ - ESP_LOGCONFIG(TAG, prefix " Unit of Measurement: '%s'", obj->get_unit_of_measurement().c_str()); \ - ESP_LOGCONFIG(TAG, prefix " Accuracy Decimals: %d", obj->get_accuracy_decimals()); \ - if (!obj->get_icon().empty()) { \ - ESP_LOGCONFIG(TAG, prefix " Icon: '%s'", obj->get_icon().c_str()); \ - } \ - if (!obj->unique_id().empty()) { \ - ESP_LOGV(TAG, prefix " Unique ID: '%s'", obj->unique_id().c_str()); \ - } \ - } + if (obj != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ + ESP_LOGCONFIG(TAG, prefix " Unit of Measurement: '%s'", obj->get_unit_of_measurement().c_str()); \ + ESP_LOGCONFIG(TAG, prefix " Accuracy Decimals: %d", obj->get_accuracy_decimals()); \ + if (!obj->get_icon().empty()) { \ + ESP_LOGCONFIG(TAG, prefix " Icon: '%s'", obj->get_icon().c_str()); \ + } \ + if (!obj->unique_id().empty()) { \ + ESP_LOGV(TAG, prefix " Unique ID: '%s'", obj->unique_id().c_str()); \ + } \ + } #ifdef USE_MQTT_SENSOR class MQTTSensorComponent; @@ -61,9 +59,9 @@ class Sensor : public Nameable { void set_unit_of_measurement(const std::string &unit_of_measurement); /** Manually set the icon of this sensor. By default the sensor's default defined by icon() is used. - * - * @param icon The icon, for example "mdi:flash". "" to disable. - */ + * + * @param icon The icon, for example "mdi:flash". "" to disable. + */ void set_icon(const std::string &icon); /** Manually set the accuracy in decimals for this sensor. By default, the sensor's default defined by @@ -86,10 +84,10 @@ class Sensor : public Nameable { * SlidingWindowMovingAverageFilter(15, 15), // average over last 15 values * }); */ - void add_filters(const std::vector & filters); + void add_filters(const std::vector &filters); /// Clear the filters and replace them by filters. - void set_filters(const std::vector & filters); + void set_filters(const std::vector &filters); /// Clear the entire filter chain. void clear_filters(); @@ -125,7 +123,7 @@ class Sensor : public Nameable { * * Note: deprecated, please use publish_state. */ - void push_new_value(float value) ESPDEPRECATED("push_new_value is deprecated. Please use .publish_state instead"); + void push_new_value(float state) ESPDEPRECATED("push_new_value is deprecated. Please use .publish_state instead"); // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) @@ -137,11 +135,8 @@ class Sensor : public Nameable { SensorStateTrigger *make_state_trigger(); SensorRawStateTrigger *make_raw_state_trigger(); ValueRangeTrigger *make_value_range_trigger(); - template - SensorInRangeCondition *make_sensor_in_range_condition(); - template - SensorPublishAction *make_sensor_publish_action(); - + template SensorInRangeCondition *make_sensor_in_range_condition(); + template SensorPublishAction *make_sensor_publish_action(); union { /** This member variable stores the last state that has passed through all filters. @@ -183,7 +178,7 @@ class Sensor : public Nameable { /// Calculate the expected update interval for values that pass through all filters. uint32_t calculate_expected_filter_update_interval(); - void send_state_to_frontend_internal_(float state); + void internal_send_state_to_frontend(float state); #ifdef USE_MQTT_SENSOR MQTTSensorComponent *get_mqtt() const; @@ -197,7 +192,7 @@ class Sensor : public Nameable { * * @return The icon of this sensor, for example "°C". */ - virtual std::string unit_of_measurement(); + virtual std::string unit_of_measurement(); // NOLINT /** Override this to set the Home Assistant icon for this sensor. * @@ -205,19 +200,21 @@ class Sensor : public Nameable { * * @return The icon of this sensor, for example "mdi:battery". */ - virtual std::string icon(); + virtual std::string icon(); // NOLINT /// Return the accuracy in decimals for this sensor. - virtual int8_t accuracy_decimals(); - - uint32_t hash_base_() override; - - CallbackManager raw_callback_; ///< Storage for raw state callbacks. - CallbackManager callback_; ///< Storage for filtered state callbacks. - optional unit_of_measurement_; ///< Override the unit of measurement - optional icon_; /// Override the icon advertised to Home Assistant, otherwise sensor's icon will be used. - optional accuracy_decimals_; ///< Override the accuracy in decimals, otherwise the sensor's values will be used. - Filter *filter_list_{nullptr}; ///< Store all active filters. + virtual int8_t accuracy_decimals(); // NOLINT + + uint32_t hash_base() override; + + CallbackManager raw_callback_; ///< Storage for raw state callbacks. + CallbackManager callback_; ///< Storage for filtered state callbacks. + optional unit_of_measurement_; ///< Override the unit of measurement + optional + icon_; /// Override the icon advertised to Home Assistant, otherwise sensor's icon will be used. + optional + accuracy_decimals_; ///< Override the accuracy in decimals, otherwise the sensor's values will be used. + Filter *filter_list_{nullptr}; ///< Store all active filters. bool has_state_{false}; #ifdef USE_MQTT_SENSOR @@ -238,39 +235,26 @@ class EmptySensor; template class EmptySensor : public Sensor { public: - explicit EmptySensor(const std::string &name) - : Sensor(name) { - - } + explicit EmptySensor(const std::string &name) : Sensor(name) {} - std::string unit_of_measurement() override { - return default_unit_of_measurement; - } - std::string icon() override { - return default_icon; - } - int8_t accuracy_decimals() override { - return default_accuracy_decimals; - } + std::string unit_of_measurement() override { return default_unit_of_measurement; } + std::string icon() override { return default_icon; } + int8_t accuracy_decimals() override { return default_accuracy_decimals; } }; template + class ParentType = PollingComponent> class EmptyPollingParentSensor; template + class ParentType> class EmptyPollingParentSensor : public EmptySensor { public: EmptyPollingParentSensor(const std::string &name, ParentType *parent) - : EmptySensor(name), parent_(parent) { + : EmptySensor(name), parent_(parent) {} - } - - uint32_t update_interval() override { - return parent_->get_update_interval(); - } + uint32_t update_interval() override { return parent_->get_update_interval(); } protected: ParentType *parent_; @@ -286,13 +270,12 @@ class SensorRawStateTrigger : public Trigger { explicit SensorRawStateTrigger(Sensor *parent); }; -template -class SensorPublishAction : public Action { +template class SensorPublishAction : public Action { public: SensorPublishAction(Sensor *sensor); - template - void set_state(V state) { this->state_ = state; } + template void set_state(V state) { this->state_ = state; } void play(Ts... x) override; + protected: Sensor *sensor_; TemplatableValue state_; @@ -302,10 +285,8 @@ class ValueRangeTrigger : public Trigger, public Component { public: explicit ValueRangeTrigger(Sensor *parent); - template - void set_min(V min) { this->min_ = min; } - template - void set_max(V max) { this->max_ = max; } + template void set_min(V min) { this->min_ = min; } + template void set_max(V max) { this->max_ = max; } void setup() override; float get_setup_priority() const override; @@ -320,14 +301,14 @@ class ValueRangeTrigger : public Trigger, public Component { TemplatableValue max_{NAN}; }; -template -class SensorInRangeCondition : public Condition { +template class SensorInRangeCondition : public Condition { public: SensorInRangeCondition(Sensor *parent); void set_min(float min); void set_max(float max); bool check(Ts... x) override; + protected: Sensor *parent_; float min_{NAN}; @@ -367,22 +348,13 @@ extern const char UNIT_K[]; extern const char UNIT_MICROSIEMENS_PER_CENTIMETER[]; extern const char UNIT_MICROGRAMS_PER_CUBIC_METER[]; -template -SensorInRangeCondition *Sensor::make_sensor_in_range_condition() { +template SensorInRangeCondition *Sensor::make_sensor_in_range_condition() { return new SensorInRangeCondition(this); } -template -SensorInRangeCondition::SensorInRangeCondition(Sensor *parent) : parent_(parent) {} -template -void SensorInRangeCondition::set_min(float min) { - this->min_ = min; -} -template -void SensorInRangeCondition::set_max(float max) { - this->max_ = max; -} -template -bool SensorInRangeCondition::check(Ts... x) { +template SensorInRangeCondition::SensorInRangeCondition(Sensor *parent) : parent_(parent) {} +template void SensorInRangeCondition::set_min(float min) { this->min_ = min; } +template void SensorInRangeCondition::set_max(float max) { this->max_ = max; } +template bool SensorInRangeCondition::check(Ts... x) { const float state = this->parent_->state; if (isnan(this->min_)) { return state <= this->max_; @@ -392,24 +364,21 @@ bool SensorInRangeCondition::check(Ts... x) { return this->min_ <= state && state <= this->max_; } } -template -SensorPublishAction::SensorPublishAction(Sensor *sensor) : sensor_(sensor) {} -template -void SensorPublishAction::play(Ts... x) { +template SensorPublishAction::SensorPublishAction(Sensor *sensor) : sensor_(sensor) {} +template void SensorPublishAction::play(Ts... x) { this->sensor_->publish_state(this->state_.value(x...)); this->play_next(x...); } -template -SensorPublishAction *Sensor::make_sensor_publish_action() { +template SensorPublishAction *Sensor::make_sensor_publish_action() { return new SensorPublishAction(this); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END #include "esphome/sensor/mqtt_sensor_component.h" -#endif //USE_SENSOR +#endif // USE_SENSOR -#endif //ESPHOME_SENSOR_SENSOR_H +#endif // ESPHOME_SENSOR_SENSOR_H diff --git a/src/esphome/sensor/sht3xd_component.cpp b/src/esphome/sensor/sht3xd_component.cpp index 9d03b6be..236b89da 100644 --- a/src/esphome/sensor/sht3xd_component.cpp +++ b/src/esphome/sensor/sht3xd_component.cpp @@ -25,24 +25,22 @@ static const uint16_t SHT3XD_COMMAND_SOFT_RESET = 0x30A2; static const uint16_t SHT3XD_COMMAND_POLLING_H = 0x2400; static const uint16_t SHT3XD_COMMAND_FETCH_DATA = 0xE000; -SHT3XDComponent::SHT3XDComponent(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, - uint8_t address, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, address), +SHT3XDComponent::SHT3XDComponent(I2CComponent *parent, const std::string &temperature_name, + const std::string &humidity_name, uint8_t address, uint32_t update_interval) + : PollingComponent(update_interval), + I2CDevice(parent, address), temperature_sensor_(new SHT3XDTemperatureSensor(temperature_name, this)), - humidity_sensor_(new SHT3XDHumiditySensor(humidity_name, this)) { - -} + humidity_sensor_(new SHT3XDHumiditySensor(humidity_name, this)) {} void SHT3XDComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up SHT3xD..."); - if (!this->write_command(SHT3XD_COMMAND_READ_SERIAL_NUMBER)) { + if (!this->write_command_(SHT3XD_COMMAND_READ_SERIAL_NUMBER)) { this->mark_failed(); return; } uint16_t raw_serial_number[2]; - if (!this->read_data(raw_serial_number, 2)) { + if (!this->read_data_(raw_serial_number, 2)) { this->mark_failed(); return; } @@ -63,16 +61,14 @@ void SHT3XDComponent::dump_config() { LOG_SENSOR(" ", "Temperature", this->temperature_sensor_); LOG_SENSOR(" ", "Humidity", this->humidity_sensor_); } -float SHT3XDComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float SHT3XDComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void SHT3XDComponent::update() { - if (!this->write_command(SHT3XD_COMMAND_POLLING_H)) + if (!this->write_command_(SHT3XD_COMMAND_POLLING_H)) return; - this->set_timeout(50, [this](){ + this->set_timeout(50, [this]() { uint16_t raw_data[2]; - if (!this->read_data(raw_data, 2)) { + if (!this->read_data_(raw_data, 2)) { this->status_set_warning(); return; } @@ -87,7 +83,7 @@ void SHT3XDComponent::update() { }); } -bool SHT3XDComponent::write_command(uint16_t command) { +bool SHT3XDComponent::write_command_(uint16_t command) { // Warning ugly, trick the I2Ccomponent base by setting register to the first 8 bit. return this->write_byte(command >> 8, command & 0xFF); } @@ -115,11 +111,11 @@ uint8_t sht_crc(uint8_t data1, uint8_t data2) { return crc; } -bool SHT3XDComponent::read_data(uint16_t *data, uint8_t len) { +bool SHT3XDComponent::read_data_(uint16_t *data, uint8_t len) { const uint8_t num_bytes = len * 3; auto *buf = new uint8_t[num_bytes]; - if (!this->parent_->receive_(this->address_, buf, num_bytes)) { + if (!this->parent_->raw_receive(this->address_, buf, num_bytes)) { delete[](buf); return false; } @@ -138,27 +134,19 @@ bool SHT3XDComponent::read_data(uint16_t *data, uint8_t len) { delete[](buf); return true; } -SHT3XDTemperatureSensor *SHT3XDComponent::get_temperature_sensor() const { - return this->temperature_sensor_; -} -SHT3XDHumiditySensor *SHT3XDComponent::get_humidity_sensor() const { - return this->humidity_sensor_; -} +SHT3XDTemperatureSensor *SHT3XDComponent::get_temperature_sensor() const { return this->temperature_sensor_; } +SHT3XDHumiditySensor *SHT3XDComponent::get_humidity_sensor() const { return this->humidity_sensor_; } SHT3XDTemperatureSensor::SHT3XDTemperatureSensor(const std::string &name, SHT3XDComponent *parent) : EmptyPollingParentSensor(name, parent) {} -std::string SHT3XDTemperatureSensor::unique_id() { - return this->unique_id_; -} +std::string SHT3XDTemperatureSensor::unique_id() { return this->unique_id_; } SHT3XDHumiditySensor::SHT3XDHumiditySensor(const std::string &name, SHT3XDComponent *parent) : EmptyPollingParentSensor(name, parent) {} -std::string SHT3XDHumiditySensor::unique_id() { - return this->unique_id_; -} +std::string SHT3XDHumiditySensor::unique_id() { return this->unique_id_; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_SHT3XD +#endif // USE_SHT3XD diff --git a/src/esphome/sensor/sht3xd_component.h b/src/esphome/sensor/sht3xd_component.h index d3be05a9..bb8a4bad 100644 --- a/src/esphome/sensor/sht3xd_component.h +++ b/src/esphome/sensor/sht3xd_component.h @@ -18,8 +18,7 @@ class SHT3XDHumiditySensor; /// This class implements support for the SHT3x-DIS family of temperature+humidity i2c sensors. class SHT3XDComponent : public PollingComponent, public I2CDevice { public: - SHT3XDComponent(I2CComponent *parent, - const std::string &temperature_name, const std::string &humidity_name, + SHT3XDComponent(I2CComponent *parent, const std::string &temperature_name, const std::string &humidity_name, uint8_t address = 0x44, uint32_t update_interval = 60000); // ========== INTERNAL METHODS ========== @@ -33,8 +32,8 @@ class SHT3XDComponent : public PollingComponent, public I2CDevice { void update() override; protected: - bool write_command(uint16_t command); - bool read_data(uint16_t *data, uint8_t len); + bool write_command_(uint16_t command); + bool read_data_(uint16_t *data, uint8_t len); SHT3XDTemperatureSensor *temperature_sensor_; SHT3XDHumiditySensor *humidity_sensor_; @@ -66,10 +65,10 @@ class SHT3XDHumiditySensor : public EmptyPollingParentSensor<1, ICON_WATER_PERCE std::string unique_id_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_SHT3XD +#endif // USE_SHT3XD -#endif //ESPHOME_SENSOR_SHT3XD_COMPONENT_H +#endif // ESPHOME_SENSOR_SHT3XD_COMPONENT_H diff --git a/src/esphome/sensor/tcs34725.cpp b/src/esphome/sensor/tcs34725.cpp index da1b2b10..6f59967e 100644 --- a/src/esphome/sensor/tcs34725.cpp +++ b/src/esphome/sensor/tcs34725.cpp @@ -17,11 +17,11 @@ static const uint8_t TCS34725_COMMAND_BIT = 0x80; static const uint8_t TCS34725_REGISTER_ID = TCS34725_COMMAND_BIT | 0x12; static const uint8_t TCS34725_REGISTER_ATIME = TCS34725_COMMAND_BIT | 0x01; static const uint8_t TCS34725_REGISTER_CONTROL = TCS34725_COMMAND_BIT | 0x0F; -static const uint8_t TCS34725_REGISTER_ENABLE = TCS34725_COMMAND_BIT | 0x00; -static const uint8_t TCS34725_REGISTER_CDATAL = TCS34725_COMMAND_BIT | 0x14; -static const uint8_t TCS34725_REGISTER_RDATAL = TCS34725_COMMAND_BIT | 0x16; -static const uint8_t TCS34725_REGISTER_GDATAL = TCS34725_COMMAND_BIT | 0x18; -static const uint8_t TCS34725_REGISTER_BDATAL = TCS34725_COMMAND_BIT | 0x1A; +static const uint8_t TCS34725_REGISTER_ENABLE = TCS34725_COMMAND_BIT | 0x00; +static const uint8_t TCS34725_REGISTER_CDATAL = TCS34725_COMMAND_BIT | 0x14; +static const uint8_t TCS34725_REGISTER_RDATAL = TCS34725_COMMAND_BIT | 0x16; +static const uint8_t TCS34725_REGISTER_GDATAL = TCS34725_COMMAND_BIT | 0x18; +static const uint8_t TCS34725_REGISTER_BDATAL = TCS34725_COMMAND_BIT | 0x1A; void TCS34725Component::setup() { ESP_LOGCONFIG(TAG, "Setting up TCS34725..."); @@ -39,12 +39,12 @@ void TCS34725Component::setup() { return; } - if (!this->write_byte(TCS34725_REGISTER_ENABLE, 0x01)) { // Power on (internal oscillator on) + if (!this->write_byte(TCS34725_REGISTER_ENABLE, 0x01)) { // Power on (internal oscillator on) this->mark_failed(); return; } delay(3); - if (!this->write_byte(TCS34725_REGISTER_ENABLE, 0x03)) { // Power on (internal oscillator on) + RGBC ADC Enable + if (!this->write_byte(TCS34725_REGISTER_ENABLE, 0x03)) { // Power on (internal oscillator on) + RGBC ADC Enable this->mark_failed(); return; } @@ -65,19 +65,15 @@ void TCS34725Component::dump_config() { LOG_SENSOR(" ", "Illuminance", this->illuminance_sensor_); LOG_SENSOR(" ", "Color Temperature", this->color_temperature_sensor_); } -float TCS34725Component::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float TCS34725Component::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void TCS34725Component::update() { uint16_t raw_c; uint16_t raw_r; uint16_t raw_g; uint16_t raw_b; - if (!this->read_byte_16(TCS34725_REGISTER_CDATAL, &raw_c) || - !this->read_byte_16(TCS34725_REGISTER_RDATAL, &raw_r) || - !this->read_byte_16(TCS34725_REGISTER_GDATAL, &raw_g) || - !this->read_byte_16(TCS34725_REGISTER_BDATAL, &raw_b)) { + if (!this->read_byte_16(TCS34725_REGISTER_CDATAL, &raw_c) || !this->read_byte_16(TCS34725_REGISTER_RDATAL, &raw_r) || + !this->read_byte_16(TCS34725_REGISTER_GDATAL, &raw_g) || !this->read_byte_16(TCS34725_REGISTER_BDATAL, &raw_b)) { ESP_LOGW(TAG, "Reading data from TCS34725 failed!"); this->status_set_warning(); return; @@ -87,20 +83,25 @@ void TCS34725Component::update() { const float channel_r = raw_r / 655.35f; const float channel_g = raw_g / 655.35f; const float channel_b = raw_b / 655.35f; - if (this->clear_sensor_ != nullptr) this->clear_sensor_->publish_state(channel_c); - if (this->red_sensor_ != nullptr) this->red_sensor_->publish_state(channel_r); - if (this->green_sensor_ != nullptr) this->green_sensor_->publish_state(channel_g); - if (this->blue_sensor_ != nullptr) this->blue_sensor_->publish_state(channel_b); + if (this->clear_sensor_ != nullptr) + this->clear_sensor_->publish_state(channel_c); + if (this->red_sensor_ != nullptr) + this->red_sensor_->publish_state(channel_r); + if (this->green_sensor_ != nullptr) + this->green_sensor_->publish_state(channel_g); + if (this->blue_sensor_ != nullptr) + this->blue_sensor_->publish_state(channel_b); // Formulae taken from Adafruit TCS35725 library float illuminance = (-0.32466f * channel_r) + (1.57837f * channel_g) + (-0.73191f * channel_b); - if (this->illuminance_sensor_ != nullptr) this->illuminance_sensor_->publish_state(illuminance); + if (this->illuminance_sensor_ != nullptr) + this->illuminance_sensor_->publish_state(illuminance); // Color temperature // 1. Convert RGB to XYZ color space const float x = (-0.14282f * raw_r) + (1.54924f * raw_g) + (-0.95641f * raw_b); const float y = (-0.32466f * raw_r) + (1.57837f * raw_g) + (-0.73191f * raw_b); - const float z = (-0.68202f * raw_r) + (0.77073f * raw_g) + ( 0.56332f * raw_b); + const float z = (-0.68202f * raw_r) + (0.77073f * raw_g) + (0.56332f * raw_b); // 2. Calculate chromacity coordinates const float xc = (x) / (x + y + z); @@ -111,19 +112,18 @@ void TCS34725Component::update() { // 4. final color temperature in Kelvin. const float color_temperature = (449.0f * powf(n, 3.0f)) + (3525.0f * powf(n, 2.0f)) + (6823.3f * n) + 5520.33f; - if (this->color_temperature_sensor_ != nullptr) this->color_temperature_sensor_->publish_state(color_temperature); + if (this->color_temperature_sensor_ != nullptr) + this->color_temperature_sensor_->publish_state(color_temperature); - ESP_LOGD(TAG, "Got R=%.1f%%,G=%.1f%%,B=%.1f%%,C=%.1f%% Illuminance=%.1flx Color Temperature=%.1fK", - channel_r, channel_g, channel_b, channel_c, illuminance, color_temperature); + ESP_LOGD(TAG, "Got R=%.1f%%,G=%.1f%%,B=%.1f%%,C=%.1f%% Illuminance=%.1flx Color Temperature=%.1fK", channel_r, + channel_g, channel_b, channel_c, illuminance, color_temperature); this->status_clear_warning(); } void TCS34725Component::set_integration_time(TCS34725IntegrationTime integration_time) { this->integration_time_ = integration_time; } -void TCS34725Component::set_gain(TCS34725Gain gain) { - this->gain_ = gain; -} +void TCS34725Component::set_gain(TCS34725Gain gain) { this->gain_ = gain; } TCS35725ColorChannelSensor *TCS34725Component::make_clear_sensor(const std::string &name) { return this->clear_sensor_ = new TCS35725ColorChannelSensor(name, this); } @@ -144,12 +144,10 @@ TCS35725ColorTemperatureSensor *TCS34725Component::make_color_temperature_sensor } TCS34725Component::TCS34725Component(I2CComponent *parent, uint32_t update_interval) - : PollingComponent(update_interval), I2CDevice(parent, TCS34725_ADDRESS) { - -} + : PollingComponent(update_interval), I2CDevice(parent, TCS34725_ADDRESS) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TCS34725 +#endif // USE_TCS34725 diff --git a/src/esphome/sensor/tcs34725.h b/src/esphome/sensor/tcs34725.h index 2c7efeb9..bfb11c20 100644 --- a/src/esphome/sensor/tcs34725.h +++ b/src/esphome/sensor/tcs34725.h @@ -62,10 +62,10 @@ class TCS34725Component : public PollingComponent, public I2CDevice { TCS34725Gain gain_{TCS34725_GAIN_1X}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TCS34725 +#endif // USE_TCS34725 -#endif //ESPHOME_SENSOR_TCS34725_H +#endif // ESPHOME_SENSOR_TCS34725_H diff --git a/src/esphome/sensor/template_sensor.cpp b/src/esphome/sensor/template_sensor.cpp index e11de7f0..dadbbdca 100644 --- a/src/esphome/sensor/template_sensor.cpp +++ b/src/esphome/sensor/template_sensor.cpp @@ -12,9 +12,7 @@ namespace sensor { static const char *TAG = "sensor.template"; TemplateSensor::TemplateSensor(const std::string &name, uint32_t update_interval) - : PollingSensorComponent(name, update_interval) { - -} + : PollingSensorComponent(name, update_interval) {} void TemplateSensor::update() { if (!this->f_.has_value()) return; @@ -24,19 +22,15 @@ void TemplateSensor::update() { this->publish_state(*val); } } -float TemplateSensor::get_setup_priority() const { - return setup_priority::HARDWARE; -} -void TemplateSensor::set_template(std::function()> &&f) { - this->f_ = std::move(f); -} +float TemplateSensor::get_setup_priority() const { return setup_priority::HARDWARE; } +void TemplateSensor::set_template(std::function()> &&f) { this->f_ = f; } void TemplateSensor::dump_config() { LOG_SENSOR("", "Template Sensor", this); LOG_UPDATE_INTERVAL(this); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_SENSOR +#endif // USE_TEMPLATE_SENSOR diff --git a/src/esphome/sensor/template_sensor.h b/src/esphome/sensor/template_sensor.h index faff753f..4eeac045 100644 --- a/src/esphome/sensor/template_sensor.h +++ b/src/esphome/sensor/template_sensor.h @@ -28,10 +28,10 @@ class TemplateSensor : public PollingSensorComponent { optional()>> f_; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_SENSOR +#endif // USE_TEMPLATE_SENSOR -#endif //ESPHOME_SENSOR_TEMPLATE_SENSOR_H +#endif // ESPHOME_SENSOR_TEMPLATE_SENSOR_H diff --git a/src/esphome/sensor/total_daily_energy.cpp b/src/esphome/sensor/total_daily_energy.cpp index 581cb0a1..31a043dd 100644 --- a/src/esphome/sensor/total_daily_energy.cpp +++ b/src/esphome/sensor/total_daily_energy.cpp @@ -16,40 +16,28 @@ void TotalDailyEnergy::setup() { float recovered; if (this->pref_.load(&recovered)) { - this->publish_state_and_save_(recovered); + this->publish_state_and_save(recovered); } else { - this->publish_state_and_save_(0); + this->publish_state_and_save(0); } this->last_update_ = millis(); auto f = std::bind(&TotalDailyEnergy::process_new_state_, this, std::placeholders::_1); this->parent_->add_on_state_callback(f); } -void TotalDailyEnergy::dump_config() { - LOG_SENSOR("", "Total Daily Energy", this); -} -float TotalDailyEnergy::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -uint32_t TotalDailyEnergy::update_interval() { - return this->parent_->update_interval(); -} -std::string TotalDailyEnergy::unit_of_measurement() { - return this->parent_->get_unit_of_measurement() + "h"; -} -std::string TotalDailyEnergy::icon() { - return this->parent_->get_icon(); -} -int8_t TotalDailyEnergy::accuracy_decimals() { - return this->parent_->get_accuracy_decimals() + 1; -} +void TotalDailyEnergy::dump_config() { LOG_SENSOR("", "Total Daily Energy", this); } +float TotalDailyEnergy::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +uint32_t TotalDailyEnergy::update_interval() { return this->parent_->update_interval(); } +std::string TotalDailyEnergy::unit_of_measurement() { return this->parent_->get_unit_of_measurement() + "h"; } +std::string TotalDailyEnergy::icon() { return this->parent_->get_icon(); } +int8_t TotalDailyEnergy::accuracy_decimals() { return this->parent_->get_accuracy_decimals() + 1; } void TotalDailyEnergy::process_new_state_(float state) { if (isnan(state)) return; const uint32_t now = millis(); float delta_hours = (now - this->last_update_) / 1000.0f / 60.0f / 60.0f; this->last_update_ = now; - this->publish_state_and_save_(this->total_energy_ + state * delta_hours); + this->publish_state_and_save(this->total_energy_ + state * delta_hours); } void TotalDailyEnergy::loop() { auto t = this->time_->now(); @@ -64,21 +52,19 @@ void TotalDailyEnergy::loop() { if (t.day_of_year != this->last_day_of_year_) { this->last_day_of_year_ = t.day_of_year; this->total_energy_ = 0; - this->publish_state_and_save_(0); + this->publish_state_and_save(0); } } -void TotalDailyEnergy::publish_state_and_save_(float state) { +void TotalDailyEnergy::publish_state_and_save(float state) { this->pref_.save(&state); this->total_energy_ = state; this->publish_state(state); } TotalDailyEnergy::TotalDailyEnergy(const std::string &name, time::RealTimeClockComponent *time, Sensor *parent) - : Sensor(name), time_(time), parent_(parent) { - -} + : Sensor(name), time_(time), parent_(parent) {} -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TOTAL_DAILY_ENERGY_SENSOR +#endif // USE_TOTAL_DAILY_ENERGY_SENSOR diff --git a/src/esphome/sensor/total_daily_energy.h b/src/esphome/sensor/total_daily_energy.h index 3e2af1b5..38b99486 100644 --- a/src/esphome/sensor/total_daily_energy.h +++ b/src/esphome/sensor/total_daily_energy.h @@ -26,7 +26,7 @@ class TotalDailyEnergy : public Sensor, public Component { int8_t accuracy_decimals() override; void loop() override; - void publish_state_and_save_(float state); + void publish_state_and_save(float state); protected: void process_new_state_(float state); @@ -39,10 +39,10 @@ class TotalDailyEnergy : public Sensor, public Component { float total_energy_{0.0f}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TOTAL_DAILY_ENERGY_SENSOR +#endif // USE_TOTAL_DAILY_ENERGY_SENSOR -#endif //ESPHOME_SENSOR_TOTAL_DAILY_ENERGY_H +#endif // ESPHOME_SENSOR_TOTAL_DAILY_ENERGY_H diff --git a/src/esphome/sensor/tsl2561_sensor.cpp b/src/esphome/sensor/tsl2561_sensor.cpp index 0a17d2d3..189da689 100644 --- a/src/esphome/sensor/tsl2561_sensor.cpp +++ b/src/esphome/sensor/tsl2561_sensor.cpp @@ -23,8 +23,7 @@ static const uint8_t TSL2561_REGISTER_ID = 0x0A; static const uint8_t TSL2561_REGISTER_DATA_0 = 0x0C; static const uint8_t TSL2561_REGISTER_DATA_1 = 0x0E; -TSL2561Sensor::TSL2561Sensor(I2CComponent *parent, const std::string &name, - uint8_t address, uint32_t update_interval) +TSL2561Sensor::TSL2561Sensor(I2CComponent *parent, const std::string &name, uint8_t address, uint32_t update_interval) : PollingSensorComponent(name, update_interval), I2CDevice(parent, address) {} void TSL2561Sensor::setup() { @@ -71,11 +70,9 @@ void TSL2561Sensor::update() { } // Make sure the data is there when we will read it. - uint32_t timeout = this->get_integration_time_ms_() + 20.0f; + auto timeout = static_cast(this->get_integration_time_ms_() + 20); - this->set_timeout("illuminance", timeout, [this]() { - this->read_data_(); - }); + this->set_timeout("illuminance", timeout, [this]() { this->read_data_(); }); } float TSL2561Sensor::calculate_lx_(uint16_t ch0, uint16_t ch1) { @@ -142,53 +139,44 @@ void TSL2561Sensor::read_data_() { this->publish_state(lx); this->status_clear_warning(); } -std::string TSL2561Sensor::unit_of_measurement() { - return UNIT_LX; -} -std::string TSL2561Sensor::icon() { - return ICON_BRIGHTNESS_5; -} -int8_t TSL2561Sensor::accuracy_decimals() { - return 1; -} +std::string TSL2561Sensor::unit_of_measurement() { return UNIT_LX; } +std::string TSL2561Sensor::icon() { return ICON_BRIGHTNESS_5; } +int8_t TSL2561Sensor::accuracy_decimals() { return 1; } float TSL2561Sensor::get_integration_time_ms_() { switch (this->integration_time_) { - case TSL2561_INTEGRATION_14MS: return 13.7f; - case TSL2561_INTEGRATION_101MS: return 100.0f; - case TSL2561_INTEGRATION_402MS: return 402.0f; + case TSL2561_INTEGRATION_14MS: + return 13.7f; + case TSL2561_INTEGRATION_101MS: + return 100.0f; + case TSL2561_INTEGRATION_402MS: + return 402.0f; } return 0.0f; } void TSL2561Sensor::set_integration_time(TSL2561IntegrationTime integration_time) { this->integration_time_ = integration_time; } -void TSL2561Sensor::set_gain(TSL2561Gain gain) { - this->gain_ = gain; -} -void TSL2561Sensor::set_is_cs_package(bool package_cs) { - this->package_cs_ = package_cs; -} -float TSL2561Sensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -bool TSL2561Sensor::tsl2561_write_byte(uint8_t register_, uint8_t value) { - return this->write_byte(register_ | TSL2561_COMMAND_BIT, value); +void TSL2561Sensor::set_gain(TSL2561Gain gain) { this->gain_ = gain; } +void TSL2561Sensor::set_is_cs_package(bool package_cs) { this->package_cs_ = package_cs; } +float TSL2561Sensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +bool TSL2561Sensor::tsl2561_write_byte(uint8_t a_register, uint8_t value) { + return this->write_byte(a_register | TSL2561_COMMAND_BIT, value); } -bool TSL2561Sensor::tsl2561_read_uint(uint8_t register_, uint16_t *value) { +bool TSL2561Sensor::tsl2561_read_uint(uint8_t a_register, uint16_t *value) { uint8_t data[2]; - if (!this->read_bytes(register_ | TSL2561_COMMAND_BIT, data, 2)) + if (!this->read_bytes(a_register | TSL2561_COMMAND_BIT, data, 2)) return false; const uint16_t hi = data[1]; const uint16_t lo = data[0]; *value = (hi << 8) | lo; return true; } -bool TSL2561Sensor::tsl2561_read_byte(uint8_t register_, uint8_t *value) { - return this->read_byte(register_ | TSL2561_COMMAND_BIT, value); +bool TSL2561Sensor::tsl2561_read_byte(uint8_t a_register, uint8_t *value) { + return this->read_byte(a_register | TSL2561_COMMAND_BIT, value); } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TSL2561 +#endif // USE_TSL2561 diff --git a/src/esphome/sensor/tsl2561_sensor.h b/src/esphome/sensor/tsl2561_sensor.h index 8f18e038..0041b8ca 100644 --- a/src/esphome/sensor/tsl2561_sensor.h +++ b/src/esphome/sensor/tsl2561_sensor.h @@ -80,9 +80,9 @@ class TSL2561Sensor : public PollingSensorComponent, public I2CDevice { int8_t accuracy_decimals() override; float get_setup_priority() const override; - bool tsl2561_read_byte(uint8_t register_, uint8_t *value); - bool tsl2561_read_uint(uint8_t register_, uint16_t *value); - bool tsl2561_write_byte(uint8_t register_, uint8_t value); + bool tsl2561_read_byte(uint8_t a_register, uint8_t *value); + bool tsl2561_read_uint(uint8_t a_register, uint16_t *value); + bool tsl2561_write_byte(uint8_t a_register, uint8_t value); protected: float get_integration_time_ms_(); @@ -94,10 +94,10 @@ class TSL2561Sensor : public PollingSensorComponent, public I2CDevice { bool package_cs_{false}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_TSL2561 +#endif // USE_TSL2561 -#endif //ESPHOME_SENSOR_TSL2561_SENSOR_H +#endif // ESPHOME_SENSOR_TSL2561_SENSOR_H diff --git a/src/esphome/sensor/ultrasonic_sensor.cpp b/src/esphome/sensor/ultrasonic_sensor.cpp index d42ce9eb..392cfcc3 100644 --- a/src/esphome/sensor/ultrasonic_sensor.cpp +++ b/src/esphome/sensor/ultrasonic_sensor.cpp @@ -13,13 +13,9 @@ namespace sensor { static const char *TAG = "sensor.ultrasonic"; -UltrasonicSensorComponent::UltrasonicSensorComponent(const std::string &name, - GPIOPin *trigger_pin, GPIOPin *echo_pin, +UltrasonicSensorComponent::UltrasonicSensorComponent(const std::string &name, GPIOPin *trigger_pin, GPIOPin *echo_pin, uint32_t update_interval) - : PollingSensorComponent(name, update_interval), - trigger_pin_(trigger_pin), echo_pin_(echo_pin) { - -} + : PollingSensorComponent(name, update_interval), trigger_pin_(trigger_pin), echo_pin_(echo_pin) {} void UltrasonicSensorComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up Ultrasonic Sensor..."); this->echo_pin_->setup(); @@ -39,9 +35,7 @@ void UltrasonicSensorComponent::update() { delayMicroseconds(this->pulse_time_us_); this->trigger_pin_->digital_write(false); disable_interrupts(); - uint32_t time = pulseIn(this->echo_pin_->get_pin(), - uint8_t(!this->echo_pin_->is_inverted()), - this->timeout_us_); + uint32_t time = pulseIn(this->echo_pin_->get_pin(), uint8_t(!this->echo_pin_->is_inverted()), this->timeout_us_); enable_interrupts(); float result = 0; @@ -54,47 +48,29 @@ void UltrasonicSensorComponent::update() { this->publish_state(result); } -uint32_t UltrasonicSensorComponent::get_timeout_us() const { - return this->timeout_us_; -} -void UltrasonicSensorComponent::set_timeout_us(uint32_t timeout_us) { - this->timeout_us_ = timeout_us; -} -void UltrasonicSensorComponent::set_timeout_m(float timeout_m) { - this->set_timeout_us(m_to_us(timeout_m)); -} +uint32_t UltrasonicSensorComponent::get_timeout_us() const { return this->timeout_us_; } +void UltrasonicSensorComponent::set_timeout_us(uint32_t timeout_us) { this->timeout_us_ = timeout_us; } +void UltrasonicSensorComponent::set_timeout_m(float timeout_m) { this->set_timeout_us(m_to_us(timeout_m)); } float UltrasonicSensorComponent::us_to_m(uint32_t us) { // The ultrasonic sound wave needs to travel both ways. - return (SPEED_OF_SOUND_M_PER_US/2.0f) * us; + return (SPEED_OF_SOUND_M_PER_US / 2.0f) * us; } uint32_t UltrasonicSensorComponent::m_to_us(float m) { // The ultrasonic sound wave needs to travel both ways. - return static_cast(m / (SPEED_OF_SOUND_M_PER_US/2.0f)); -} -float UltrasonicSensorComponent::get_timeout_m() const { - return us_to_m(this->get_timeout_us()); -} -float UltrasonicSensorComponent::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} -uint32_t UltrasonicSensorComponent::get_pulse_time_us() const { - return this->pulse_time_us_; -} -void UltrasonicSensorComponent::set_pulse_time_us(uint32_t pulse_time_us) { - this->pulse_time_us_ = pulse_time_us; -} -std::string UltrasonicSensorComponent::unit_of_measurement() { - return "m"; -} -std::string UltrasonicSensorComponent::icon() { - return "mdi:arrow-expand-vertical"; -} + return static_cast(m / (SPEED_OF_SOUND_M_PER_US / 2.0f)); +} +float UltrasonicSensorComponent::get_timeout_m() const { return us_to_m(this->get_timeout_us()); } +float UltrasonicSensorComponent::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } +uint32_t UltrasonicSensorComponent::get_pulse_time_us() const { return this->pulse_time_us_; } +void UltrasonicSensorComponent::set_pulse_time_us(uint32_t pulse_time_us) { this->pulse_time_us_ = pulse_time_us; } +std::string UltrasonicSensorComponent::unit_of_measurement() { return "m"; } +std::string UltrasonicSensorComponent::icon() { return "mdi:arrow-expand-vertical"; } int8_t UltrasonicSensorComponent::accuracy_decimals() { - return 2; // cm precision + return 2; // cm precision } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ULTRASONIC_SENSOR +#endif // USE_ULTRASONIC_SENSOR diff --git a/src/esphome/sensor/ultrasonic_sensor.h b/src/esphome/sensor/ultrasonic_sensor.h index 16d98ffd..7e986d86 100644 --- a/src/esphome/sensor/ultrasonic_sensor.h +++ b/src/esphome/sensor/ultrasonic_sensor.h @@ -40,8 +40,7 @@ class UltrasonicSensorComponent : public PollingSensorComponent { * @param echo_pin The echo pin where the echo is listened for. * @param update_interval The interval in ms the sensor should check for new values. */ - UltrasonicSensorComponent(const std::string &name, - GPIOPin *trigger_pin, GPIOPin *echo_pin, + UltrasonicSensorComponent(const std::string &name, GPIOPin *trigger_pin, GPIOPin *echo_pin, uint32_t update_interval = 5000); /// Set the timeout for waiting for the echo in µs. @@ -82,14 +81,14 @@ class UltrasonicSensorComponent : public PollingSensorComponent { GPIOPin *trigger_pin_; GPIOPin *echo_pin_; - uint32_t timeout_us_{11662}; /// 2 meters. + uint32_t timeout_us_{11662}; /// 2 meters. uint32_t pulse_time_us_{10}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_ULTRASONIC_SENSOR +#endif // USE_ULTRASONIC_SENSOR -#endif //ESPHOME_SENSOR_ULTRASONIC_SENSOR_H +#endif // ESPHOME_SENSOR_ULTRASONIC_SENSOR_H diff --git a/src/esphome/sensor/uptime_sensor.cpp b/src/esphome/sensor/uptime_sensor.cpp index 28b28ece..f04811fb 100644 --- a/src/esphome/sensor/uptime_sensor.cpp +++ b/src/esphome/sensor/uptime_sensor.cpp @@ -12,9 +12,7 @@ namespace sensor { static const char *TAG = "sensor.uptime"; UptimeSensor::UptimeSensor(const std::string &name, uint32_t update_interval) - : PollingSensorComponent(name, update_interval) { - -} + : PollingSensorComponent(name, update_interval) {} void UptimeSensor::update() { const uint32_t ms = millis(); const uint64_t ms_mask = (1ULL << 32) - 1ULL; @@ -33,24 +31,14 @@ void UptimeSensor::update() { const float seconds = float(seconds_int) + (this->uptime_ % 1000ULL) / 1000.0f; this->publish_state(seconds); } -std::string UptimeSensor::unit_of_measurement() { - return "s"; -} -std::string UptimeSensor::icon() { - return "mdi:timer"; -} -int8_t UptimeSensor::accuracy_decimals() { - return 0; -} -std::string UptimeSensor::unique_id() { - return get_mac_address() + "-uptime"; -} -float UptimeSensor::get_setup_priority() const { - return setup_priority::HARDWARE; -} +std::string UptimeSensor::unit_of_measurement() { return "s"; } +std::string UptimeSensor::icon() { return "mdi:timer"; } +int8_t UptimeSensor::accuracy_decimals() { return 0; } +std::string UptimeSensor::unique_id() { return get_mac_address() + "-uptime"; } +float UptimeSensor::get_setup_priority() const { return setup_priority::HARDWARE; } -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_UPTIME_SENSOR +#endif // USE_UPTIME_SENSOR diff --git a/src/esphome/sensor/uptime_sensor.h b/src/esphome/sensor/uptime_sensor.h index 43fae683..ba244cc3 100644 --- a/src/esphome/sensor/uptime_sensor.h +++ b/src/esphome/sensor/uptime_sensor.h @@ -28,10 +28,10 @@ class UptimeSensor : public PollingSensorComponent { uint64_t uptime_{0}; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_UPTIME_SENSOR +#endif // USE_UPTIME_SENSOR -#endif //ESPHOME_UPTIME_SENSOR_H +#endif // ESPHOME_UPTIME_SENSOR_H diff --git a/src/esphome/sensor/wifi_signal_sensor.cpp b/src/esphome/sensor/wifi_signal_sensor.cpp index fa5179fc..992018ed 100644 --- a/src/esphome/sensor/wifi_signal_sensor.cpp +++ b/src/esphome/sensor/wifi_signal_sensor.cpp @@ -4,9 +4,9 @@ #include "esphome/sensor/wifi_signal_sensor.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #else - #include +#include #endif #include "esphome/log.h" @@ -17,33 +17,17 @@ namespace sensor { static const char *TAG = "sensor.wifi_signal"; WiFiSignalSensor::WiFiSignalSensor(const std::string &name, uint32_t update_interval) - : PollingSensorComponent(name, update_interval) { - -} -void WiFiSignalSensor::update() { - this->publish_state(WiFi.RSSI()); -} -std::string WiFiSignalSensor::unit_of_measurement() { - return "dB"; -} -std::string WiFiSignalSensor::icon() { - return "mdi:wifi"; -} -int8_t WiFiSignalSensor::accuracy_decimals() { - return 0; -} -std::string WiFiSignalSensor::unique_id() { - return get_mac_address() + "-wifisignal"; -} -float WiFiSignalSensor::get_setup_priority() const { - return setup_priority::WIFI; -} -void WiFiSignalSensor::dump_config() { - LOG_SENSOR("", "WiFi Signal", this); -} - -} // namespace sensor + : PollingSensorComponent(name, update_interval) {} +void WiFiSignalSensor::update() { this->publish_state(WiFi.RSSI()); } +std::string WiFiSignalSensor::unit_of_measurement() { return "dB"; } +std::string WiFiSignalSensor::icon() { return "mdi:wifi"; } +int8_t WiFiSignalSensor::accuracy_decimals() { return 0; } +std::string WiFiSignalSensor::unique_id() { return get_mac_address() + "-wifisignal"; } +float WiFiSignalSensor::get_setup_priority() const { return setup_priority::WIFI; } +void WiFiSignalSensor::dump_config() { LOG_SENSOR("", "WiFi Signal", this); } + +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_WIFI_SIGNAL_SENSOR +#endif // USE_WIFI_SIGNAL_SENSOR diff --git a/src/esphome/sensor/wifi_signal_sensor.h b/src/esphome/sensor/wifi_signal_sensor.h index dfe1f250..fb29e95e 100644 --- a/src/esphome/sensor/wifi_signal_sensor.h +++ b/src/esphome/sensor/wifi_signal_sensor.h @@ -25,10 +25,10 @@ class WiFiSignalSensor : public PollingSensorComponent { float get_setup_priority() const override; }; -} // namespace sensor +} // namespace sensor ESPHOME_NAMESPACE_END -#endif //USE_WIFI_SIGNAL_SENSOR +#endif // USE_WIFI_SIGNAL_SENSOR -#endif //ESPHOME_SENSOR_WIFI_SIGNAL_SENSOR_H +#endif // ESPHOME_SENSOR_WIFI_SIGNAL_SENSOR_H diff --git a/src/esphome/spi_component.cpp b/src/esphome/spi_component.cpp index 44c188fd..b4c58d5e 100644 --- a/src/esphome/spi_component.cpp +++ b/src/esphome/spi_component.cpp @@ -10,10 +10,7 @@ ESPHOME_NAMESPACE_BEGIN static const char *TAG = "spi"; -SPIComponent::SPIComponent(GPIOPin *clk, GPIOPin *miso, GPIOPin *mosi) - : clk_(clk), miso_(miso), mosi_(mosi){ - -} +SPIComponent::SPIComponent(GPIOPin *clk, GPIOPin *miso, GPIOPin *mosi) : clk_(clk), miso_(miso), mosi_(mosi) {} void ICACHE_RAM_ATTR HOT SPIComponent::write_byte(uint8_t data) { uint8_t send_bits = data; @@ -36,8 +33,7 @@ void ICACHE_RAM_ATTR HOT SPIComponent::write_byte(uint8_t data) { this->clk_->digital_write(true); } - ESP_LOGVV(TAG, " Wrote 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", - BYTE_TO_BINARY(data), data); + ESP_LOGVV(TAG, " Wrote 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", BYTE_TO_BINARY(data), data); } uint8_t ICACHE_RAM_ATTR HOT SPIComponent::read_byte() { @@ -58,8 +54,7 @@ uint8_t ICACHE_RAM_ATTR HOT SPIComponent::read_byte() { data = reverse_bits_8(data); } - ESP_LOGVV(TAG, " Received 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", - BYTE_TO_BINARY(data), data); + ESP_LOGVV(TAG, " Received 0b" BYTE_TO_BINARY_PATTERN " (0x%02X)", BYTE_TO_BINARY(data), data); return data; } @@ -107,44 +102,25 @@ void SPIComponent::dump_config() { LOG_PIN(" MISO Pin: ", this->miso_); LOG_PIN(" MOSI Pin: ", this->mosi_); } -float SPIComponent::get_setup_priority() const { - return setup_priority::PRE_HARDWARE; -} -void SPIComponent::set_miso(const GPIOInputPin &miso) { - this->miso_ = miso.copy(); -} -void SPIComponent::set_mosi(const GPIOOutputPin &mosi) { - this->mosi_ = mosi.copy(); -} +float SPIComponent::get_setup_priority() const { return setup_priority::PRE_HARDWARE; } +void SPIComponent::set_miso(const GPIOInputPin &miso) { this->miso_ = miso.copy(); } +void SPIComponent::set_mosi(const GPIOOutputPin &mosi) { this->mosi_ = mosi.copy(); } -SPIDevice::SPIDevice(SPIComponent *parent, GPIOPin *cs) - : parent_(parent), cs_(cs) {} +SPIDevice::SPIDevice(SPIComponent *parent, GPIOPin *cs) : parent_(parent), cs_(cs) {} void HOT SPIDevice::enable() { - this->parent_->enable(this->cs_, this->msb_first(), this->high_speed()); -} -void HOT SPIDevice::disable() { - this->parent_->disable(); -} -uint8_t HOT SPIDevice::read_byte() { - return this->parent_->read_byte(); -} -void HOT SPIDevice::read_array(uint8_t *data, size_t length) { - return this->parent_->read_array(data, length); -} -void HOT SPIDevice::write_byte(uint8_t data) { - return this->parent_->write_byte(data); -} -void HOT SPIDevice::write_array(uint8_t *data, size_t length) { - this->parent_->write_array(data, length); + this->parent_->enable(this->cs_, this->is_device_msb_first(), this->is_device_high_speed()); } +void HOT SPIDevice::disable() { this->parent_->disable(); } +uint8_t HOT SPIDevice::read_byte() { return this->parent_->read_byte(); } +void HOT SPIDevice::read_array(uint8_t *data, size_t length) { return this->parent_->read_array(data, length); } +void HOT SPIDevice::write_byte(uint8_t data) { return this->parent_->write_byte(data); } +void HOT SPIDevice::write_array(uint8_t *data, size_t length) { this->parent_->write_array(data, length); } void SPIDevice::spi_setup() { this->cs_->setup(); this->cs_->digital_write(true); } -bool HOT SPIDevice::high_speed() { - return false; -} +bool HOT SPIDevice::is_device_high_speed() { return false; } ESPHOME_NAMESPACE_END -#endif //USE_SPI +#endif // USE_SPI diff --git a/src/esphome/spi_component.h b/src/esphome/spi_component.h index a810d779..7a2ece00 100644 --- a/src/esphome/spi_component.h +++ b/src/esphome/spi_component.h @@ -64,18 +64,16 @@ class SPIDevice { void write_array(uint8_t *data, size_t length); protected: - virtual bool msb_first() = 0; + virtual bool is_device_msb_first() = 0; - virtual bool high_speed(); + virtual bool is_device_high_speed(); SPIComponent *parent_; GPIOPin *cs_; }; - - ESPHOME_NAMESPACE_END -#endif //USE_SPI +#endif // USE_SPI -#endif //ESPHOME_SPI_COMPONENT_H +#endif // ESPHOME_SPI_COMPONENT_H diff --git a/src/esphome/status_led.cpp b/src/esphome/status_led.cpp index 550b460a..f7dc32b5 100644 --- a/src/esphome/status_led.cpp +++ b/src/esphome/status_led.cpp @@ -11,9 +11,7 @@ static const char *TAG = "status_led"; StatusLEDComponent *global_status_led = nullptr; -StatusLEDComponent::StatusLEDComponent(GPIOPin *pin) : pin_(pin) { - global_status_led = this; -} +StatusLEDComponent::StatusLEDComponent(GPIOPin *pin) : pin_(pin) { global_status_led = this; } void StatusLEDComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up Status LED..."); this->pin_->setup(); @@ -32,13 +30,9 @@ void StatusLEDComponent::loop() { this->pin_->digital_write(false); } } -float StatusLEDComponent::get_setup_priority() const { - return setup_priority::HARDWARE; -} -float StatusLEDComponent::get_loop_priority() const { - return 50.0f; -} +float StatusLEDComponent::get_setup_priority() const { return setup_priority::HARDWARE; } +float StatusLEDComponent::get_loop_priority() const { return 50.0f; } ESPHOME_NAMESPACE_END -#endif //USE_STATUS_LED +#endif // USE_STATUS_LED diff --git a/src/esphome/status_led.h b/src/esphome/status_led.h index 23f66996..bf68ef38 100644 --- a/src/esphome/status_led.h +++ b/src/esphome/status_led.h @@ -28,6 +28,6 @@ extern StatusLEDComponent *global_status_led; ESPHOME_NAMESPACE_END -#endif //USE_STATUS_LED +#endif // USE_STATUS_LED -#endif //ESPHOME_STATUS_LED_H +#endif // ESPHOME_STATUS_LED_H diff --git a/src/esphome/stepper/a4988.cpp b/src/esphome/stepper/a4988.cpp index 8a090fa2..0c8926cb 100644 --- a/src/esphome/stepper/a4988.cpp +++ b/src/esphome/stepper/a4988.cpp @@ -49,19 +49,12 @@ void A4988::loop() { delayMicroseconds(5); this->step_pin_->digital_write(false); } -float A4988::get_setup_priority() const { - return setup_priority::HARDWARE; -} -A4988::A4988(GPIOPin *step_pin, GPIOPin *dir_pin) - : step_pin_(step_pin), dir_pin_(dir_pin) { - -} -void A4988::set_sleep_pin(const GPIOOutputPin &sleep_pin) { - this->sleep_pin_ = sleep_pin.copy(); -} +float A4988::get_setup_priority() const { return setup_priority::HARDWARE; } +A4988::A4988(GPIOPin *step_pin, GPIOPin *dir_pin) : step_pin_(step_pin), dir_pin_(dir_pin) {} +void A4988::set_sleep_pin(const GPIOOutputPin &sleep_pin) { this->sleep_pin_ = sleep_pin.copy(); } -} // namespace stepper +} // namespace stepper ESPHOME_NAMESPACE_END -#endif //USE_A4988 +#endif // USE_A4988 diff --git a/src/esphome/stepper/a4988.h b/src/esphome/stepper/a4988.h index b89f502a..3a08f0cd 100644 --- a/src/esphome/stepper/a4988.h +++ b/src/esphome/stepper/a4988.h @@ -29,10 +29,10 @@ class A4988 : public Stepper, public Component { HighFrequencyLoopRequester high_freq_; }; -} // namespace stepper +} // namespace stepper ESPHOME_NAMESPACE_END -#endif //USE_A4988 +#endif // USE_A4988 -#endif //ESPHOME_STEPPER_A4988_H +#endif // ESPHOME_STEPPER_A4988_H diff --git a/src/esphome/stepper/stepper.cpp b/src/esphome/stepper/stepper.cpp index ac5bfd1a..a94621c4 100644 --- a/src/esphome/stepper/stepper.cpp +++ b/src/esphome/stepper/stepper.cpp @@ -25,7 +25,7 @@ void Stepper::calculate_speed_(uint32_t now) { int32_t num_steps = abs(int32_t(this->target_position) - int32_t(this->current_position)); // (v_0)^2 / 2*a float v_squared = this->current_speed_ * this->current_speed_; - int32_t steps_to_decelerate = v_squared / (2 * this->deceleration_); + auto steps_to_decelerate = static_cast(v_squared / (2 * this->deceleration_)); if (num_steps <= steps_to_decelerate) { // need to start decelerating this->current_speed_ -= this->deceleration_ * dt; @@ -52,27 +52,15 @@ int32_t Stepper::should_step_() { return 0; } -void Stepper::set_target(int32_t steps) { - this->target_position = steps; -} -void Stepper::report_position(int32_t steps) { - this->current_position = steps; -} -void Stepper::set_acceleration(float acceleration) { - this->acceleration_ = acceleration; -} -void Stepper::set_deceleration(float deceleration) { - this->deceleration_ = deceleration; -} -void Stepper::set_max_speed(float max_speed) { - this->max_speed_ = max_speed; -} -bool Stepper::has_reached_target() { - return this->current_position == this->target_position; -} +void Stepper::set_target(int32_t steps) { this->target_position = steps; } +void Stepper::report_position(int32_t steps) { this->current_position = steps; } +void Stepper::set_acceleration(float acceleration) { this->acceleration_ = acceleration; } +void Stepper::set_deceleration(float deceleration) { this->deceleration_ = deceleration; } +void Stepper::set_max_speed(float max_speed) { this->max_speed_ = max_speed; } +bool Stepper::has_reached_target() { return this->current_position == this->target_position; } -} // namespace stepper +} // namespace stepper ESPHOME_NAMESPACE_END -#endif //USE_STEPPER +#endif // USE_STEPPER diff --git a/src/esphome/stepper/stepper.h b/src/esphome/stepper/stepper.h index 806347c3..27a28b18 100644 --- a/src/esphome/stepper/stepper.h +++ b/src/esphome/stepper/stepper.h @@ -12,15 +12,13 @@ ESPHOME_NAMESPACE_BEGIN namespace stepper { -template -class SetTargetAction; -template -class ReportPositionAction; +template class SetTargetAction; +template class ReportPositionAction; #define LOG_STEPPER(this) \ - ESP_LOGCONFIG(TAG, " Acceleration: %.0f steps/s^2", this->acceleration_); \ - ESP_LOGCONFIG(TAG, " Deceleration: %.0f steps/s^2", this->deceleration_); \ - ESP_LOGCONFIG(TAG, " Max Speed: %.0f steps/s", this->max_speed_); + ESP_LOGCONFIG(TAG, " Acceleration: %.0f steps/s^2", this->acceleration_); \ + ESP_LOGCONFIG(TAG, " Deceleration: %.0f steps/s^2", this->deceleration_); \ + ESP_LOGCONFIG(TAG, " Max Speed: %.0f steps/s", this->max_speed_); class Stepper { public: @@ -31,10 +29,8 @@ class Stepper { void set_max_speed(float max_speed); bool has_reached_target(); - template - SetTargetAction *make_set_target_action(); - template - ReportPositionAction *make_report_position_action(); + template SetTargetAction *make_set_target_action(); + template ReportPositionAction *make_report_position_action(); int32_t current_position{0}; int32_t target_position{0}; @@ -51,13 +47,11 @@ class Stepper { uint32_t last_step_{0}; }; -template -class SetTargetAction : public Action { +template class SetTargetAction : public Action { public: explicit SetTargetAction(Stepper *parent); - template - void set_target(V target) { this->target_ = target; } + template void set_target(V target) { this->target_ = target; } void play(Ts... x) override; @@ -66,13 +60,11 @@ class SetTargetAction : public Action { TemplatableValue target_; }; -template -class ReportPositionAction : public Action { +template class ReportPositionAction : public Action { public: explicit ReportPositionAction(Stepper *parent); - template - void set_position(V position) { this->position_ = position; } + template void set_position(V position) { this->position_ = position; } void play(Ts... x) override; @@ -80,36 +72,28 @@ class ReportPositionAction : public Action { Stepper *parent_; TemplatableValue position_; }; -template -ReportPositionAction::ReportPositionAction(Stepper *parent) - : parent_(parent) { } -template -void ReportPositionAction::play(Ts... x) { +template ReportPositionAction::ReportPositionAction(Stepper *parent) : parent_(parent) {} +template void ReportPositionAction::play(Ts... x) { this->parent_->report_position(this->position_.value(x...)); this->play_next(x...); } -template -SetTargetAction *Stepper::make_set_target_action() { +template SetTargetAction *Stepper::make_set_target_action() { return new SetTargetAction(this); } -template -ReportPositionAction *Stepper::make_report_position_action() { +template ReportPositionAction *Stepper::make_report_position_action() { return new ReportPositionAction(this); } -template -SetTargetAction::SetTargetAction(Stepper *parent) - : parent_(parent) { } -template -void SetTargetAction::play(Ts... x) { +template SetTargetAction::SetTargetAction(Stepper *parent) : parent_(parent) {} +template void SetTargetAction::play(Ts... x) { this->parent_->set_target(this->target_.value(x...)); this->play_next(x...); } -} // namespace stepper +} // namespace stepper ESPHOME_NAMESPACE_END -#endif //USE_STEPPER +#endif // USE_STEPPER -#endif //ESPHOME_STEPPER_STEPPER_H +#endif // ESPHOME_STEPPER_STEPPER_H diff --git a/src/esphome/stepper/uln2003.cpp b/src/esphome/stepper/uln2003.cpp index 0bd99e7a..7414affa 100644 --- a/src/esphome/stepper/uln2003.cpp +++ b/src/esphome/stepper/uln2003.cpp @@ -11,10 +11,7 @@ namespace stepper { static const char *TAG = "stepper.uln2003"; -ULN2003::ULN2003(GPIOPin *a, GPIOPin *b, GPIOPin *c, GPIOPin *d) - : pin_a_(a), pin_b_(b), pin_c_(c), pin_d_(d) { - -} +ULN2003::ULN2003(GPIOPin *a, GPIOPin *b, GPIOPin *c, GPIOPin *d) : pin_a_(a), pin_b_(b), pin_c_(c), pin_d_(d) {} void ULN2003::setup() { this->pin_a_->setup(); this->pin_b_->setup(); @@ -65,9 +62,7 @@ void ULN2003::loop() { this->write_step_(this->current_uln_pos_); } -float ULN2003::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float ULN2003::get_setup_priority() const { return setup_priority::HARDWARE; } void ULN2003::write_step_(int32_t step) { int32_t n = this->step_mode_ == ULN2003_STEP_MODE_HALF_STEP ? 8 : 4; auto i = static_cast((step % n + n) % n); @@ -104,15 +99,11 @@ void ULN2003::write_step_(int32_t step) { this->pin_c_->digital_write((res >> 2) & 1); this->pin_d_->digital_write((res >> 3) & 1); } -void ULN2003::set_sleep_when_done(bool sleep_when_done) { - this->sleep_when_done_ = sleep_when_done; -} -void ULN2003::set_step_mode(ULN2003StepMode step_mode) { - this->step_mode_ = step_mode; -} +void ULN2003::set_sleep_when_done(bool sleep_when_done) { this->sleep_when_done_ = sleep_when_done; } +void ULN2003::set_step_mode(ULN2003StepMode step_mode) { this->step_mode_ = step_mode; } -} // namespace stepper +} // namespace stepper ESPHOME_NAMESPACE_END -#endif //USE_ULN2003 +#endif // USE_ULN2003 diff --git a/src/esphome/stepper/uln2003.h b/src/esphome/stepper/uln2003.h index 7b6848a2..02850da1 100644 --- a/src/esphome/stepper/uln2003.h +++ b/src/esphome/stepper/uln2003.h @@ -42,10 +42,10 @@ class ULN2003 : public Stepper, public Component { int32_t current_uln_pos_{0}; }; -} // namespace stepper +} // namespace stepper ESPHOME_NAMESPACE_END -#endif //USE_ULN2003 +#endif // USE_ULN2003 -#endif //ESPHOME_STEPPER_ULN2003_H +#endif // ESPHOME_STEPPER_ULN2003_H diff --git a/src/esphome/switch_/custom_switch.cpp b/src/esphome/switch_/custom_switch.cpp index b917ebd3..dfa80ada 100644 --- a/src/esphome/switch_/custom_switch.cpp +++ b/src/esphome/switch_/custom_switch.cpp @@ -14,17 +14,15 @@ static const char *TAG = "switch.custom"; CustomSwitchConstructor::CustomSwitchConstructor(std::function()> init) { this->switches_ = init(); } -Switch *CustomSwitchConstructor::get_switch(int i) { - return this->switches_[i]; -} +Switch *CustomSwitchConstructor::get_switch(int i) { return this->switches_[i]; } void CustomSwitchConstructor::dump_config() { for (auto *child : this->switches_) { LOG_SWITCH("", "Custom Switch", child); } } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_SWITCH +#endif // USE_CUSTOM_SWITCH diff --git a/src/esphome/switch_/custom_switch.h b/src/esphome/switch_/custom_switch.h index 590ed4b9..f9a97513 100644 --- a/src/esphome/switch_/custom_switch.h +++ b/src/esphome/switch_/custom_switch.h @@ -19,14 +19,15 @@ class CustomSwitchConstructor : public Component { Switch *get_switch(int i); void dump_config() override; + protected: std::vector switches_; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_SWITCH +#endif // USE_CUSTOM_SWITCH -#endif //ESPHOME_CUSTOM_SWITCH_H +#endif // ESPHOME_CUSTOM_SWITCH_H diff --git a/src/esphome/switch_/gpio_switch.cpp b/src/esphome/switch_/gpio_switch.cpp index 5843de36..92829781 100644 --- a/src/esphome/switch_/gpio_switch.cpp +++ b/src/esphome/switch_/gpio_switch.cpp @@ -11,14 +11,9 @@ namespace switch_ { static const char *TAG = "switch.gpio"; -GPIOSwitch::GPIOSwitch(const std::string &name, GPIOPin *pin) - : Switch(name), Component(), pin_(pin) { +GPIOSwitch::GPIOSwitch(const std::string &name, GPIOPin *pin) : Switch(name), Component(), pin_(pin) {} -} - -float GPIOSwitch::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float GPIOSwitch::get_setup_priority() const { return setup_priority::HARDWARE; } void GPIOSwitch::setup() { ESP_LOGCONFIG(TAG, "Setting up GPIO Switch '%s'...", this->name_.c_str()); @@ -39,10 +34,16 @@ void GPIOSwitch::setup() { } // write state before setup - if (initial_state) this->turn_on(); else this->turn_off(); + if (initial_state) + this->turn_on(); + else + this->turn_off(); this->pin_->setup(); // write after setup again for other IOs - if (initial_state) this->turn_on(); else this->turn_off(); + if (initial_state) + this->turn_on(); + else + this->turn_off(); } void GPIOSwitch::dump_config() { LOG_SWITCH("", "GPIO Switch", this); @@ -87,15 +88,11 @@ void GPIOSwitch::write_state(bool state) { this->pin_->digital_write(state); this->publish_state(state); } -void GPIOSwitch::set_restore_mode(GPIOSwitchRestoreMode restore_mode) { - this->restore_mode_ = restore_mode; -} -void GPIOSwitch::set_interlock(const std::vector &interlock) { - this->interlock_ = interlock; -} +void GPIOSwitch::set_restore_mode(GPIOSwitchRestoreMode restore_mode) { this->restore_mode_ = restore_mode; } +void GPIOSwitch::set_interlock(const std::vector &interlock) { this->interlock_ = interlock; } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_GPIO_SWITCH +#endif // USE_GPIO_SWITCH diff --git a/src/esphome/switch_/gpio_switch.h b/src/esphome/switch_/gpio_switch.h index 65da6860..f9d083cd 100644 --- a/src/esphome/switch_/gpio_switch.h +++ b/src/esphome/switch_/gpio_switch.h @@ -42,10 +42,10 @@ class GPIOSwitch : public Switch, public Component { std::vector interlock_; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_GPIO_SWITCH +#endif // USE_GPIO_SWITCH -#endif //ESPHOME_SWITCH_GPIO_SWITCH_H +#endif // ESPHOME_SWITCH_GPIO_SWITCH_H diff --git a/src/esphome/switch_/mqtt_switch_component.cpp b/src/esphome/switch_/mqtt_switch_component.cpp index 30e30268..ba309748 100644 --- a/src/esphome/switch_/mqtt_switch_component.cpp +++ b/src/esphome/switch_/mqtt_switch_component.cpp @@ -14,13 +14,10 @@ namespace switch_ { static const char *TAG = "switch.mqtt"; -MQTTSwitchComponent::MQTTSwitchComponent(switch_::Switch *switch_) - : MQTTComponent(), switch_(switch_) { - -} +MQTTSwitchComponent::MQTTSwitchComponent(switch_::Switch *a_switch) : MQTTComponent(), switch_(a_switch) {} void MQTTSwitchComponent::setup() { - this->subscribe(this->get_command_topic(), [this](const std::string &topic, const std::string &payload) { + this->subscribe(this->get_command_topic_(), [this](const std::string &topic, const std::string &payload) { switch (parse_on_off(payload.c_str())) { case PARSE_ON: this->switch_->turn_on(); @@ -38,42 +35,31 @@ void MQTTSwitchComponent::setup() { break; } }); - this->switch_->add_on_state_callback([this](bool enabled){ - this->defer("send", [this, enabled]() { - this->publish_state(enabled); - }); - }); + this->switch_->add_on_state_callback( + [this](bool enabled) { this->defer("send", [this, enabled]() { this->publish_state(enabled); }); }); } void MQTTSwitchComponent::dump_config() { ESP_LOGCONFIG(TAG, "MQTT Switch '%s': ", this->switch_->get_name().c_str()); LOG_MQTT_COMPONENT(true, true); } -std::string MQTTSwitchComponent::component_type() const { - return "switch"; -} +std::string MQTTSwitchComponent::component_type() const { return "switch"; } void MQTTSwitchComponent::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (!this->switch_->get_icon().empty()) root["icon"] = this->switch_->get_icon(); if (this->switch_->assumed_state()) root["optimistic"] = true; } -bool MQTTSwitchComponent::send_initial_state() { - return this->publish_state(this->switch_->state); -} -bool MQTTSwitchComponent::is_internal() { - return this->switch_->is_internal(); -} -std::string MQTTSwitchComponent::friendly_name() const { - return this->switch_->get_name(); -} +bool MQTTSwitchComponent::send_initial_state() { return this->publish_state(this->switch_->state); } +bool MQTTSwitchComponent::is_internal() { return this->switch_->is_internal(); } +std::string MQTTSwitchComponent::friendly_name() const { return this->switch_->get_name(); } bool MQTTSwitchComponent::publish_state(bool state) { const char *state_s = state ? "ON" : "OFF"; - return this->publish(this->get_state_topic(), state_s); + return this->publish(this->get_state_topic_(), state_s); } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SWITCH +#endif // USE_MQTT_SWITCH diff --git a/src/esphome/switch_/mqtt_switch_component.h b/src/esphome/switch_/mqtt_switch_component.h index 8e38dc3d..2274b673 100644 --- a/src/esphome/switch_/mqtt_switch_component.h +++ b/src/esphome/switch_/mqtt_switch_component.h @@ -19,7 +19,7 @@ namespace switch_ { */ class MQTTSwitchComponent : public mqtt::MQTTComponent { public: - explicit MQTTSwitchComponent(switch_::Switch *switch_); + explicit MQTTSwitchComponent(switch_::Switch *a_switch); // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) @@ -42,10 +42,10 @@ class MQTTSwitchComponent : public mqtt::MQTTComponent { Switch *switch_; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SWITCH +#endif // USE_MQTT_SWITCH -#endif //ESPHOME_SWITCH_MQTT_SWITCH_COMPONENT_H +#endif // ESPHOME_SWITCH_MQTT_SWITCH_COMPONENT_H diff --git a/src/esphome/switch_/output_switch.cpp b/src/esphome/switch_/output_switch.cpp index b40b2f37..7b0635f4 100644 --- a/src/esphome/switch_/output_switch.cpp +++ b/src/esphome/switch_/output_switch.cpp @@ -11,10 +11,7 @@ namespace switch_ { static const char *TAG = "switch.output"; -OutputSwitch::OutputSwitch(const std::string &name, output::BinaryOutput *output) - : Switch(name), output_(output) { - -} +OutputSwitch::OutputSwitch(const std::string &name, output::BinaryOutput *output) : Switch(name), output_(output) {} void OutputSwitch::write_state(bool state) { if (state) { this->output_->turn_on(); @@ -34,15 +31,11 @@ void OutputSwitch::setup() { this->turn_off(); } } -float OutputSwitch::get_setup_priority() const { - return setup_priority::HARDWARE; -} -void OutputSwitch::dump_config() { - LOG_SWITCH("", "Output Switch", this); -} +float OutputSwitch::get_setup_priority() const { return setup_priority::HARDWARE; } +void OutputSwitch::dump_config() { LOG_SWITCH("", "Output Switch", this); } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT_SWITCH +#endif // USE_OUTPUT_SWITCH diff --git a/src/esphome/switch_/output_switch.h b/src/esphome/switch_/output_switch.h index 3ee08339..51b2466e 100644 --- a/src/esphome/switch_/output_switch.h +++ b/src/esphome/switch_/output_switch.h @@ -24,16 +24,17 @@ class OutputSwitch : public Switch, public Component { void setup() override; float get_setup_priority() const override; void dump_config() override; + protected: void write_state(bool state) override; output::BinaryOutput *output_; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_OUTPUT_SWITCH +#endif // USE_OUTPUT_SWITCH -#endif //ESPHOME_SWITCH_OUTPUT_SWITCH +#endif // ESPHOME_SWITCH_OUTPUT_SWITCH diff --git a/src/esphome/switch_/restart_switch.cpp b/src/esphome/switch_/restart_switch.cpp index e011a06d..5d5a949f 100644 --- a/src/esphome/switch_/restart_switch.cpp +++ b/src/esphome/switch_/restart_switch.cpp @@ -12,13 +12,8 @@ namespace switch_ { static const char *TAG = "switch.restart"; -std::string RestartSwitch::icon() { - return "mdi:restart"; -} -RestartSwitch::RestartSwitch(const std::string &name) - : Switch(name) { - -} +std::string RestartSwitch::icon() { return "mdi:restart"; } +RestartSwitch::RestartSwitch(const std::string &name) : Switch(name) {} void RestartSwitch::write_state(bool state) { // Acknowledge this->publish_state(false); @@ -26,16 +21,14 @@ void RestartSwitch::write_state(bool state) { if (state) { ESP_LOGI(TAG, "Restarting device..."); // then execute - delay(100); // Let MQTT settle a bit + delay(100); // Let MQTT settle a bit safe_reboot("restart"); } } -void RestartSwitch::dump_config() { - LOG_SWITCH("", "Restart Switch", this); -} +void RestartSwitch::dump_config() { LOG_SWITCH("", "Restart Switch", this); } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_RESTART_SWITCH +#endif // USE_RESTART_SWITCH diff --git a/src/esphome/switch_/restart_switch.h b/src/esphome/switch_/restart_switch.h index 350ebe3b..4d3ab5ff 100644 --- a/src/esphome/switch_/restart_switch.h +++ b/src/esphome/switch_/restart_switch.h @@ -23,10 +23,10 @@ class RestartSwitch : public Switch, public Component { void write_state(bool state) override; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_RESTART_SWITCH +#endif // USE_RESTART_SWITCH -#endif //ESPHOME_RESTART_SWITCH_H +#endif // ESPHOME_RESTART_SWITCH_H diff --git a/src/esphome/switch_/shutdown_switch.cpp b/src/esphome/switch_/shutdown_switch.cpp index c334a8a3..3f366669 100644 --- a/src/esphome/switch_/shutdown_switch.cpp +++ b/src/esphome/switch_/shutdown_switch.cpp @@ -15,16 +15,14 @@ static const char *TAG = "switch.shutdown"; ShutdownSwitch::ShutdownSwitch(const std::string &name) : Switch(name) {} -std::string ShutdownSwitch::icon() { - return "mdi:power"; -} +std::string ShutdownSwitch::icon() { return "mdi:power"; } void ShutdownSwitch::write_state(bool state) { // Acknowledge this->publish_state(false); if (state) { ESP_LOGI(TAG, "Shutting down..."); - delay(100); // Let MQTT settle a bit + delay(100); // Let MQTT settle a bit run_safe_shutdown_hooks("shutdown"); #ifdef ARDUINO_ARCH_ESP8266 @@ -35,12 +33,10 @@ void ShutdownSwitch::write_state(bool state) { #endif } } -void ShutdownSwitch::dump_config() { - LOG_SWITCH("", "Shutdown Switch", this); -} +void ShutdownSwitch::dump_config() { LOG_SWITCH("", "Shutdown Switch", this); } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_SHUTDOWN_SWITCH +#endif // USE_SHUTDOWN_SWITCH diff --git a/src/esphome/switch_/shutdown_switch.h b/src/esphome/switch_/shutdown_switch.h index 6d6d7195..494b3059 100644 --- a/src/esphome/switch_/shutdown_switch.h +++ b/src/esphome/switch_/shutdown_switch.h @@ -18,15 +18,15 @@ class ShutdownSwitch : public Switch, public Component { std::string icon() override; void dump_config() override; + protected: void write_state(bool state) override; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_RESTART_SWITCH - +#endif // USE_RESTART_SWITCH -#endif //ESPHOME_SWITCH_SHUTDOWN_SWITCH_H +#endif // ESPHOME_SWITCH_SHUTDOWN_SWITCH_H diff --git a/src/esphome/switch_/switch.cpp b/src/esphome/switch_/switch.cpp index f66ff047..8e064ef7 100644 --- a/src/esphome/switch_/switch.cpp +++ b/src/esphome/switch_/switch.cpp @@ -12,9 +12,7 @@ namespace switch_ { static const char *TAG = "switch"; -std::string Switch::icon() { - return ""; -} +std::string Switch::icon() { return ""; } Switch::Switch(const std::string &name) : Nameable(name), state(false) {} Switch::Switch() : Switch("") {} @@ -24,9 +22,7 @@ std::string Switch::get_icon() { return this->icon(); } -void Switch::set_icon(const std::string &icon) { - this->icon_ = icon; -} +void Switch::set_icon(const std::string &icon) { this->icon_ = icon; } void Switch::turn_on() { ESP_LOGD(TAG, "'%s' Turning ON.", this->get_name().c_str()); this->write_state(!this->inverted_); @@ -55,53 +51,37 @@ void Switch::publish_state(bool state) { ESP_LOGD(TAG, "'%s': Sending state %s", this->name_.c_str(), ONOFF(state)); this->state_callback_.call(this->state); } -bool Switch::assumed_state() { - return false; -} +bool Switch::assumed_state() { return false; } void Switch::add_on_state_callback(std::function &&callback) { this->state_callback_.add(std::move(callback)); } -void Switch::set_inverted(bool inverted) { - this->inverted_ = inverted; -} -uint32_t Switch::hash_base_() { - return 3129890955UL; -} -bool Switch::is_inverted() const { - return this->inverted_; -} +void Switch::set_inverted(bool inverted) { this->inverted_ = inverted; } +uint32_t Switch::hash_base() { return 3129890955UL; } +bool Switch::is_inverted() const { return this->inverted_; } #ifdef USE_MQTT_SWITCH -MQTTSwitchComponent *Switch::get_mqtt() const { - return this->mqtt_; -} -void Switch::set_mqtt(MQTTSwitchComponent *mqtt) { - this->mqtt_ = mqtt; -} +MQTTSwitchComponent *Switch::get_mqtt() const { return this->mqtt_; } +void Switch::set_mqtt(MQTTSwitchComponent *mqtt) { this->mqtt_ = mqtt; } #endif -SwitchTurnOnTrigger *Switch::make_switch_turn_on_trigger() { - return new SwitchTurnOnTrigger(this); -} -SwitchTurnOffTrigger *Switch::make_switch_turn_off_trigger() { - return new SwitchTurnOffTrigger(this); -} +SwitchTurnOnTrigger *Switch::make_switch_turn_on_trigger() { return new SwitchTurnOnTrigger(this); } +SwitchTurnOffTrigger *Switch::make_switch_turn_off_trigger() { return new SwitchTurnOffTrigger(this); } -SwitchTurnOnTrigger::SwitchTurnOnTrigger(Switch *switch_) { - switch_->add_on_state_callback([this](bool state) { +SwitchTurnOnTrigger::SwitchTurnOnTrigger(Switch *a_switch) { + a_switch->add_on_state_callback([this](bool state) { if (state) { this->trigger(); } }); } -SwitchTurnOffTrigger::SwitchTurnOffTrigger(Switch *switch_) { - switch_->add_on_state_callback([this](bool state) { +SwitchTurnOffTrigger::SwitchTurnOffTrigger(Switch *a_switch) { + a_switch->add_on_state_callback([this](bool state) { if (!state) { this->trigger(); } }); } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_SWITCH +#endif // USE_SWITCH diff --git a/src/esphome/switch_/switch.h b/src/esphome/switch_/switch.h index 2de5a7a4..39bd98e3 100644 --- a/src/esphome/switch_/switch.h +++ b/src/esphome/switch_/switch.h @@ -13,32 +13,27 @@ ESPHOME_NAMESPACE_BEGIN namespace switch_ { -template -class ToggleAction; -template -class TurnOffAction; -template -class TurnOnAction; -template -class SwitchCondition; -template -class SwitchPublishAction; +template class ToggleAction; +template class TurnOffAction; +template class TurnOnAction; +template class SwitchCondition; +template class SwitchPublishAction; class SwitchTurnOnTrigger; class SwitchTurnOffTrigger; #define LOG_SWITCH(prefix, type, obj) \ - if (obj != nullptr) { \ - ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ - if (!obj->get_icon().empty()) { \ - ESP_LOGCONFIG(TAG, prefix " Icon: '%s'", obj->get_icon().c_str()); \ - } \ - if (obj->assumed_state()) { \ - ESP_LOGCONFIG(TAG, prefix " Assumed State: YES"); \ - } \ - if (obj->is_inverted()) { \ - ESP_LOGCONFIG(TAG, prefix " Inverted: YES"); \ - } \ - } + if (obj != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ + if (!obj->get_icon().empty()) { \ + ESP_LOGCONFIG(TAG, prefix " Icon: '%s'", obj->get_icon().c_str()); \ + } \ + if (obj->assumed_state()) { \ + ESP_LOGCONFIG(TAG, prefix " Assumed State: YES"); \ + } \ + if (obj->is_inverted()) { \ + ESP_LOGCONFIG(TAG, prefix " Inverted: YES"); \ + } \ + } #ifdef USE_MQTT_SWITCH class MQTTSwitchComponent; @@ -102,18 +97,12 @@ class Switch : public Nameable { /// Get the icon for this switch. Using icon() if not manually set std::string get_icon(); - template - ToggleAction *make_toggle_action(); - template - TurnOffAction *make_turn_off_action(); - template - TurnOnAction *make_turn_on_action(); - template - SwitchCondition *make_switch_is_on_condition(); - template - SwitchCondition *make_switch_is_off_condition(); - template - SwitchPublishAction *make_switch_publish_action(); + template ToggleAction *make_toggle_action(); + template TurnOffAction *make_turn_off_action(); + template TurnOnAction *make_turn_on_action(); + template SwitchCondition *make_switch_is_on_condition(); + template SwitchCondition *make_switch_is_off_condition(); + template SwitchPublishAction *make_switch_publish_action(); SwitchTurnOnTrigger *make_switch_turn_on_trigger(); SwitchTurnOffTrigger *make_switch_turn_off_trigger(); @@ -125,8 +114,8 @@ class Switch : public Nameable { optional get_initial_state(); - /** Return whether this switch uses an assumed state - i.e. if both the ON/OFF actions should be displayed in Home Assistant - * because the real state is unknown. + /** Return whether this switch uses an assumed state - i.e. if both the ON/OFF actions should be displayed in Home + * Assistant because the real state is unknown. * * Defaults to false. */ @@ -156,11 +145,11 @@ class Switch : public Nameable { * * @return The icon of this switch, for example "mdi:fan". */ - virtual std::string icon(); + virtual std::string icon(); // NOLINT - uint32_t hash_base_() override; + uint32_t hash_base() override; - optional icon_{}; ///< The icon shown here. Not set means use default from switch. Empty means no icon. + optional icon_{}; ///< The icon shown here. Not set means use default from switch. Empty means no icon. CallbackManager state_callback_{}; bool inverted_{false}; @@ -171,8 +160,7 @@ class Switch : public Nameable { #endif }; -template -class TurnOnAction : public Action { +template class TurnOnAction : public Action { public: explicit TurnOnAction(Switch *a_switch); @@ -182,8 +170,7 @@ class TurnOnAction : public Action { Switch *switch_; }; -template -class TurnOffAction : public Action { +template class TurnOffAction : public Action { public: explicit TurnOffAction(Switch *a_switch); @@ -193,8 +180,7 @@ class TurnOffAction : public Action { Switch *switch_; }; -template -class ToggleAction : public Action { +template class ToggleAction : public Action { public: explicit ToggleAction(Switch *a_switch); @@ -204,11 +190,11 @@ class ToggleAction : public Action { Switch *switch_; }; -template -class SwitchCondition : public Condition { +template class SwitchCondition : public Condition { public: SwitchCondition(Switch *parent, bool state); bool check(Ts... x) override; + protected: Switch *parent_; bool state_; @@ -216,21 +202,20 @@ class SwitchCondition : public Condition { class SwitchTurnOnTrigger : public Trigger<> { public: - SwitchTurnOnTrigger(Switch *switch_); + SwitchTurnOnTrigger(Switch *a_switch); }; class SwitchTurnOffTrigger : public Trigger<> { public: - SwitchTurnOffTrigger(Switch *switch_); + SwitchTurnOffTrigger(Switch *a_switch); }; -template -class SwitchPublishAction : public Action { +template class SwitchPublishAction : public Action { public: - SwitchPublishAction(Switch *sensor); - template - void set_state(V state) { this->state_ = state; } + SwitchPublishAction(Switch *a_switch); + template void set_state(V state) { this->state_ = state; } void play(Ts... x) override; + protected: Switch *switch_; TemplatableValue state_; @@ -238,68 +223,57 @@ class SwitchPublishAction : public Action { // =============== TEMPLATE DEFINITIONS =============== -template -TurnOnAction::TurnOnAction(Switch *a_switch) : switch_(a_switch) {} +template TurnOnAction::TurnOnAction(Switch *a_switch) : switch_(a_switch) {} -template -void TurnOnAction::play(Ts... x) { +template void TurnOnAction::play(Ts... x) { this->switch_->turn_on(); this->play_next(x...); } -template -TurnOffAction::TurnOffAction(Switch *a_switch) : switch_(a_switch) {} +template TurnOffAction::TurnOffAction(Switch *a_switch) : switch_(a_switch) {} -template -void TurnOffAction::play(Ts... x) { +template void TurnOffAction::play(Ts... x) { this->switch_->turn_off(); this->play_next(x...); } -template -ToggleAction::ToggleAction(Switch *a_switch) : switch_(a_switch) {} +template ToggleAction::ToggleAction(Switch *a_switch) : switch_(a_switch) {} -template -void ToggleAction::play(Ts... x) { +template void ToggleAction::play(Ts... x) { this->switch_->toggle(); this->play_next(x...); } -template -ToggleAction *Switch::make_toggle_action() { return new ToggleAction(this); } -template -TurnOffAction *Switch::make_turn_off_action() { return new TurnOffAction(this); } -template -TurnOnAction *Switch::make_turn_on_action() { return new TurnOnAction(this); } +template ToggleAction *Switch::make_toggle_action() { return new ToggleAction(this); } +template TurnOffAction *Switch::make_turn_off_action() { return new TurnOffAction(this); } +template TurnOnAction *Switch::make_turn_on_action() { return new TurnOnAction(this); } template -SwitchCondition::SwitchCondition(Switch *parent, bool state) : parent_(parent), state_(state) { } -template -bool SwitchCondition::check(Ts... x) { - return this->parent_->state == this->state_; -} +SwitchCondition::SwitchCondition(Switch *parent, bool state) : parent_(parent), state_(state) {} +template bool SwitchCondition::check(Ts... x) { return this->parent_->state == this->state_; } -template -SwitchCondition *Switch::make_switch_is_on_condition() { return new SwitchCondition(this, true); } -template -SwitchCondition *Switch::make_switch_is_off_condition() { return new SwitchCondition(this, false); } +template SwitchCondition *Switch::make_switch_is_on_condition() { + return new SwitchCondition(this, true); +} +template SwitchCondition *Switch::make_switch_is_off_condition() { + return new SwitchCondition(this, false); +} -template -SwitchPublishAction::SwitchPublishAction(Switch *switch_) : switch_(switch_) {} -template -void SwitchPublishAction::play(Ts... x) { +template SwitchPublishAction::SwitchPublishAction(Switch *a_switch) : switch_(a_switch) {} +template void SwitchPublishAction::play(Ts... x) { this->switch_->publish_state(this->state_.value(x...)); this->play_next(x...); } -template -SwitchPublishAction *Switch::make_switch_publish_action() { return new SwitchPublishAction(this); } +template SwitchPublishAction *Switch::make_switch_publish_action() { + return new SwitchPublishAction(this); +} -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END #include "esphome/switch_/mqtt_switch_component.h" -#endif //USE_SWITCH +#endif // USE_SWITCH -#endif //ESPHOME_SWITCH_SWITCH_H +#endif // ESPHOME_SWITCH_SWITCH_H diff --git a/src/esphome/switch_/template_switch.cpp b/src/esphome/switch_/template_switch.cpp index 6147625e..f818b987 100644 --- a/src/esphome/switch_/template_switch.cpp +++ b/src/esphome/switch_/template_switch.cpp @@ -12,9 +12,7 @@ namespace switch_ { static const char *TAG = "switch.template"; TemplateSwitch::TemplateSwitch(const std::string &name) - : Switch(name), Component(), turn_on_trigger_(new Trigger<>()), turn_off_trigger_(new Trigger<>()) { - -} + : Switch(name), Component(), turn_on_trigger_(new Trigger<>()), turn_off_trigger_(new Trigger<>()) {} void TemplateSwitch::loop() { if (!this->f_.has_value()) return; @@ -40,24 +38,12 @@ void TemplateSwitch::write_state(bool state) { if (this->optimistic_) this->publish_state(state); } -void TemplateSwitch::set_optimistic(bool optimistic) { - this->optimistic_ = optimistic; -} -bool TemplateSwitch::assumed_state() { - return this->assumed_state_; -} -void TemplateSwitch::set_state_lambda(std::function()> &&f) { - this->f_ = f; -} -float TemplateSwitch::get_setup_priority() const { - return setup_priority::HARDWARE; -} -Trigger<> *TemplateSwitch::get_turn_on_trigger() const { - return this->turn_on_trigger_; -} -Trigger<> *TemplateSwitch::get_turn_off_trigger() const { - return this->turn_off_trigger_; -} +void TemplateSwitch::set_optimistic(bool optimistic) { this->optimistic_ = optimistic; } +bool TemplateSwitch::assumed_state() { return this->assumed_state_; } +void TemplateSwitch::set_state_lambda(std::function()> &&f) { this->f_ = f; } +float TemplateSwitch::get_setup_priority() const { return setup_priority::HARDWARE; } +Trigger<> *TemplateSwitch::get_turn_on_trigger() const { return this->turn_on_trigger_; } +Trigger<> *TemplateSwitch::get_turn_off_trigger() const { return this->turn_off_trigger_; } void TemplateSwitch::setup() { if (!this->restore_state_) return; @@ -78,15 +64,11 @@ void TemplateSwitch::dump_config() { ESP_LOGCONFIG(TAG, " Restore State: %s", YESNO(this->restore_state_)); ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_)); } -void TemplateSwitch::set_restore_state(bool restore_state) { - this->restore_state_ = restore_state; -} -void TemplateSwitch::set_assumed_state(bool assumed_state) { - this->assumed_state_ = assumed_state; -} +void TemplateSwitch::set_restore_state(bool restore_state) { this->restore_state_ = restore_state; } +void TemplateSwitch::set_assumed_state(bool assumed_state) { this->assumed_state_ = assumed_state; } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_SWITCH +#endif // USE_TEMPLATE_SWITCH diff --git a/src/esphome/switch_/template_switch.h b/src/esphome/switch_/template_switch.h index bcaccd38..8d7d0dee 100644 --- a/src/esphome/switch_/template_switch.h +++ b/src/esphome/switch_/template_switch.h @@ -43,10 +43,10 @@ class TemplateSwitch : public Switch, public Component { bool restore_state_{false}; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_SWITCH +#endif // USE_TEMPLATE_SWITCH -#endif //ESPHOME_SWITCH_TEMPLATE_SWITCH_H +#endif // ESPHOME_SWITCH_TEMPLATE_SWITCH_H diff --git a/src/esphome/switch_/uart_switch.cpp b/src/esphome/switch_/uart_switch.cpp index 6df59c9e..564ee754 100644 --- a/src/esphome/switch_/uart_switch.cpp +++ b/src/esphome/switch_/uart_switch.cpp @@ -12,9 +12,7 @@ namespace switch_ { static const char *TAG = "switch.uart"; UARTSwitch::UARTSwitch(UARTComponent *parent, const std::string &name, const std::vector &data) - : Switch(name), UARTDevice(parent), data_(data) { - -} + : Switch(name), UARTDevice(parent), data_(data) {} void UARTSwitch::write_state(bool state) { if (!state) { @@ -27,12 +25,10 @@ void UARTSwitch::write_state(bool state) { this->write_array(this->data_.data(), this->data_.size()); this->publish_state(false); } -void UARTSwitch::dump_config() { - LOG_SWITCH("", "UART Switch", this); -} +void UARTSwitch::dump_config() { LOG_SWITCH("", "UART Switch", this); } -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_UART_SWITCH +#endif // USE_UART_SWITCH diff --git a/src/esphome/switch_/uart_switch.h b/src/esphome/switch_/uart_switch.h index 3bfad54a..98503ba6 100644 --- a/src/esphome/switch_/uart_switch.h +++ b/src/esphome/switch_/uart_switch.h @@ -23,10 +23,10 @@ class UARTSwitch : public Switch, public UARTDevice, public Component { std::vector data_; }; -} // namespace switch_ +} // namespace switch_ ESPHOME_NAMESPACE_END -#endif //USE_UART_SWITCH +#endif // USE_UART_SWITCH -#endif //ESPHOME_UART_SWITCH_H +#endif // ESPHOME_UART_SWITCH_H diff --git a/src/esphome/text_sensor/custom_text_sensor.cpp b/src/esphome/text_sensor/custom_text_sensor.cpp index f473e163..b2b17074 100644 --- a/src/esphome/text_sensor/custom_text_sensor.cpp +++ b/src/esphome/text_sensor/custom_text_sensor.cpp @@ -14,17 +14,15 @@ static const char *TAG = "text_sensor.custom"; CustomTextSensorConstructor::CustomTextSensorConstructor(std::function()> init) { this->text_sensors_ = init(); } -TextSensor *CustomTextSensorConstructor::get_text_sensor(int i) { - return this->text_sensors_[i]; -} +TextSensor *CustomTextSensorConstructor::get_text_sensor(int i) { return this->text_sensors_[i]; } void CustomTextSensorConstructor::dump_config() { for (auto *child : this->text_sensors_) { LOG_TEXT_SENSOR("", "Custom Text Sensor", child); } } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_TEXT_SENSOR +#endif // USE_CUSTOM_TEXT_SENSOR diff --git a/src/esphome/text_sensor/custom_text_sensor.h b/src/esphome/text_sensor/custom_text_sensor.h index 1a460407..2a263a3d 100644 --- a/src/esphome/text_sensor/custom_text_sensor.h +++ b/src/esphome/text_sensor/custom_text_sensor.h @@ -24,10 +24,10 @@ class CustomTextSensorConstructor : public Component { std::vector text_sensors_; }; -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_CUSTOM_TEXT_SENSOR +#endif // USE_CUSTOM_TEXT_SENSOR -#endif //ESPHOME_TEXT_SENSOR_CUSTOM_TEXT_SENSOR_H +#endif // ESPHOME_TEXT_SENSOR_CUSTOM_TEXT_SENSOR_H diff --git a/src/esphome/text_sensor/homeassistant_text_sensor.cpp b/src/esphome/text_sensor/homeassistant_text_sensor.cpp index f49b11a8..38b56959 100644 --- a/src/esphome/text_sensor/homeassistant_text_sensor.cpp +++ b/src/esphome/text_sensor/homeassistant_text_sensor.cpp @@ -13,9 +13,7 @@ namespace text_sensor { static const char *TAG = "text_sensor.homeassistant"; HomeassistantTextSensor::HomeassistantTextSensor(const std::string &name, const std::string &entity_id) - : TextSensor(name), entity_id_(entity_id) { - -} + : TextSensor(name), entity_id_(entity_id) {} void HomeassistantTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Homeassistant Text Sensor", this); ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_.c_str()); @@ -27,8 +25,8 @@ void HomeassistantTextSensor::setup() { }); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_TEXT_SENSOR +#endif // USE_HOMEASSISTANT_TEXT_SENSOR diff --git a/src/esphome/text_sensor/homeassistant_text_sensor.h b/src/esphome/text_sensor/homeassistant_text_sensor.h index 6a330ea3..7d89f736 100644 --- a/src/esphome/text_sensor/homeassistant_text_sensor.h +++ b/src/esphome/text_sensor/homeassistant_text_sensor.h @@ -17,14 +17,15 @@ class HomeassistantTextSensor : public TextSensor, public Component { HomeassistantTextSensor(const std::string &name, const std::string &entity_id); void dump_config() override; void setup() override; + protected: std::string entity_id_; }; -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_TEXT_SENSOR +#endif // USE_HOMEASSISTANT_TEXT_SENSOR -#endif //ESPHOME_HOMEASSISTANT_TEXT_SENSOR_H +#endif // ESPHOME_HOMEASSISTANT_TEXT_SENSOR_H diff --git a/src/esphome/text_sensor/mqtt_subscribe_text_sensor.cpp b/src/esphome/text_sensor/mqtt_subscribe_text_sensor.cpp index 8d485dfa..b7025ee4 100644 --- a/src/esphome/text_sensor/mqtt_subscribe_text_sensor.cpp +++ b/src/esphome/text_sensor/mqtt_subscribe_text_sensor.cpp @@ -12,27 +12,21 @@ namespace text_sensor { static const char *TAG = "text_sensor.mqtt_subscribe"; MQTTSubscribeTextSensor::MQTTSubscribeTextSensor(const std::string &name, std::string topic) - : TextSensor(name), topic_(std::move(topic)) { - -} + : TextSensor(name), topic_(std::move(topic)) {} void MQTTSubscribeTextSensor::setup() { - mqtt::global_mqtt_client->subscribe(this->topic_, [this](const std::string &topic, std::string payload) { - this->publish_state(payload); - }, this->qos_); -} -float MQTTSubscribeTextSensor::get_setup_priority() const { - return setup_priority::MQTT_CLIENT - 1.0f; -} -void MQTTSubscribeTextSensor::set_qos(uint8_t qos) { - this->qos_ = qos; + mqtt::global_mqtt_client->subscribe( + this->topic_, [this](const std::string &topic, std::string payload) { this->publish_state(payload); }, + this->qos_); } +float MQTTSubscribeTextSensor::get_setup_priority() const { return setup_priority::MQTT_CLIENT - 1.0f; } +void MQTTSubscribeTextSensor::set_qos(uint8_t qos) { this->qos_ = qos; } void MQTTSubscribeTextSensor::dump_config() { LOG_TEXT_SENSOR("", "MQTT Subscribe Text Sensor", this); ESP_LOGCONFIG(TAG, " Topic: %s", this->topic_.c_str()); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SUBSCRIBE_TEXT_SENSOR +#endif // USE_MQTT_SUBSCRIBE_TEXT_SENSOR diff --git a/src/esphome/text_sensor/mqtt_subscribe_text_sensor.h b/src/esphome/text_sensor/mqtt_subscribe_text_sensor.h index 99ffd800..65940dc5 100644 --- a/src/esphome/text_sensor/mqtt_subscribe_text_sensor.h +++ b/src/esphome/text_sensor/mqtt_subscribe_text_sensor.h @@ -27,10 +27,10 @@ class MQTTSubscribeTextSensor : public TextSensor, public Component { uint8_t qos_{0}; }; -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_SUBSCRIBE_TEXT_SENSOR +#endif // USE_MQTT_SUBSCRIBE_TEXT_SENSOR -#endif //ESPHOME_MQTT_SUBSCRIBE_TEXT_SENSOR_H +#endif // ESPHOME_MQTT_SUBSCRIBE_TEXT_SENSOR_H diff --git a/src/esphome/text_sensor/mqtt_text_sensor.cpp b/src/esphome/text_sensor/mqtt_text_sensor.cpp index f07f1a24..5c567817 100644 --- a/src/esphome/text_sensor/mqtt_text_sensor.cpp +++ b/src/esphome/text_sensor/mqtt_text_sensor.cpp @@ -11,10 +11,7 @@ namespace text_sensor { static const char *TAG = "text_sensor.mqtt"; -MQTTTextSensor::MQTTTextSensor(TextSensor *sensor) - : MQTTComponent(), sensor_(sensor) { - -} +MQTTTextSensor::MQTTTextSensor(TextSensor *sensor) : MQTTComponent(), sensor_(sensor) {} void MQTTTextSensor::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig &config) { if (!this->sensor_->get_icon().empty()) root["icon"] = this->sensor_->get_icon(); @@ -25,9 +22,7 @@ void MQTTTextSensor::send_discovery(JsonObject &root, mqtt::SendDiscoveryConfig config.command_topic = false; } void MQTTTextSensor::setup() { - this->sensor_->add_on_state_callback([this](const std::string &state) { - this->publish_state(state); - }); + this->sensor_->add_on_state_callback([this](const std::string &state) { this->publish_state(state); }); } void MQTTTextSensor::dump_config() { @@ -35,9 +30,7 @@ void MQTTTextSensor::dump_config() { LOG_MQTT_COMPONENT(true, false); } -bool MQTTTextSensor::publish_state(const std::string &value) { - return this->publish(this->get_state_topic(), value); -} +bool MQTTTextSensor::publish_state(const std::string &value) { return this->publish(this->get_state_topic_(), value); } bool MQTTTextSensor::send_initial_state() { if (this->sensor_->has_state()) { return this->publish_state(this->sensor_->state); @@ -45,18 +38,12 @@ bool MQTTTextSensor::send_initial_state() { return true; } } -bool MQTTTextSensor::is_internal() { - return this->sensor_->is_internal(); -} -std::string MQTTTextSensor::component_type() const { - return "sensor"; -} -std::string MQTTTextSensor::friendly_name() const { - return this->sensor_->get_name(); -} +bool MQTTTextSensor::is_internal() { return this->sensor_->is_internal(); } +std::string MQTTTextSensor::component_type() const { return "sensor"; } +std::string MQTTTextSensor::friendly_name() const { return this->sensor_->get_name(); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_TEXT_SENSOR +#endif // USE_MQTT_TEXT_SENSOR diff --git a/src/esphome/text_sensor/mqtt_text_sensor.h b/src/esphome/text_sensor/mqtt_text_sensor.h index 40cbd910..378be8e0 100644 --- a/src/esphome/text_sensor/mqtt_text_sensor.h +++ b/src/esphome/text_sensor/mqtt_text_sensor.h @@ -37,10 +37,10 @@ class MQTTTextSensor : public mqtt::MQTTComponent { TextSensor *sensor_; }; -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_MQTT_TEXT_SENSOR +#endif // USE_MQTT_TEXT_SENSOR -#endif //ESPHOME_MQTT_TEXT_SENSOR_H +#endif // ESPHOME_MQTT_TEXT_SENSOR_H diff --git a/src/esphome/text_sensor/template_text_sensor.cpp b/src/esphome/text_sensor/template_text_sensor.cpp index 2e24e1f6..b8ffd1ed 100644 --- a/src/esphome/text_sensor/template_text_sensor.cpp +++ b/src/esphome/text_sensor/template_text_sensor.cpp @@ -12,9 +12,7 @@ namespace text_sensor { static const char *TAG = "text_sensor.template"; TemplateTextSensor::TemplateTextSensor(const std::string &name, uint32_t update_interval) - : TextSensor(name), PollingComponent(update_interval) { - -} + : TextSensor(name), PollingComponent(update_interval) {} void TemplateTextSensor::update() { if (!this->f_.has_value()) return; @@ -24,18 +22,12 @@ void TemplateTextSensor::update() { this->publish_state(*val); } } -float TemplateTextSensor::get_setup_priority() const { - return setup_priority::HARDWARE; -} -void TemplateTextSensor::set_template(std::function()> &&f) { - this->f_ = std::move(f); -} -void TemplateTextSensor::dump_config() { - LOG_TEXT_SENSOR("", "Template Sensor", this); -} +float TemplateTextSensor::get_setup_priority() const { return setup_priority::HARDWARE; } +void TemplateTextSensor::set_template(std::function()> &&f) { this->f_ = f; } +void TemplateTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Template Sensor", this); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_TEXT_SENSOR +#endif // USE_TEMPLATE_TEXT_SENSOR diff --git a/src/esphome/text_sensor/template_text_sensor.h b/src/esphome/text_sensor/template_text_sensor.h index 8e505840..7d5ad3f8 100644 --- a/src/esphome/text_sensor/template_text_sensor.h +++ b/src/esphome/text_sensor/template_text_sensor.h @@ -28,10 +28,10 @@ class TemplateTextSensor : public TextSensor, public PollingComponent { optional()>> f_{}; }; -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_TEMPLATE_TEXT_SENSOR +#endif // USE_TEMPLATE_TEXT_SENSOR -#endif //ESPHOME_TEXT_SENSOR_TEMPLATE_TEXT_SENSOR_H +#endif // ESPHOME_TEXT_SENSOR_TEMPLATE_TEXT_SENSOR_H diff --git a/src/esphome/text_sensor/text_sensor.cpp b/src/esphome/text_sensor/text_sensor.cpp index bc24f2a1..1b40e25f 100644 --- a/src/esphome/text_sensor/text_sensor.cpp +++ b/src/esphome/text_sensor/text_sensor.cpp @@ -20,9 +20,7 @@ void TextSensor::publish_state(std::string state) { ESP_LOGD(TAG, "'%s': Sending state '%s'", this->name_.c_str(), state.c_str()); this->callback_.call(state); } -void TextSensor::set_icon(const std::string &icon) { - this->icon_ = icon; -} +void TextSensor::set_icon(const std::string &icon) { this->icon_ = icon; } void TextSensor::add_on_state_callback(std::function callback) { this->callback_.add(std::move(callback)); } @@ -31,38 +29,22 @@ std::string TextSensor::get_icon() { return *this->icon_; return this->icon(); } -std::string TextSensor::icon() { - return ""; -} -std::string TextSensor::unique_id() { - return ""; -} -TextSensorStateTrigger *TextSensor::make_state_trigger() { - return new TextSensorStateTrigger(this); -} -bool TextSensor::has_state() { - return this->has_state_; -} -uint32_t TextSensor::hash_base_() { - return 334300109UL; -} +std::string TextSensor::icon() { return ""; } +std::string TextSensor::unique_id() { return ""; } +TextSensorStateTrigger *TextSensor::make_state_trigger() { return new TextSensorStateTrigger(this); } +bool TextSensor::has_state() { return this->has_state_; } +uint32_t TextSensor::hash_base() { return 334300109UL; } #ifdef USE_MQTT_TEXT_SENSOR -MQTTTextSensor *TextSensor::get_mqtt() const { - return this->mqtt_; -} -void TextSensor::set_mqtt(MQTTTextSensor *mqtt) { - this->mqtt_ = mqtt; -} +MQTTTextSensor *TextSensor::get_mqtt() const { return this->mqtt_; } +void TextSensor::set_mqtt(MQTTTextSensor *mqtt) { this->mqtt_ = mqtt; } #endif TextSensorStateTrigger::TextSensorStateTrigger(TextSensor *parent) { - parent->add_on_state_callback([this](std::string value) { - this->trigger(value); - }); + parent->add_on_state_callback([this](std::string value) { this->trigger(value); }); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_TEXT_SENSOR +#endif // USE_TEXT_SENSOR diff --git a/src/esphome/text_sensor/text_sensor.h b/src/esphome/text_sensor/text_sensor.h index 1386346f..97940934 100644 --- a/src/esphome/text_sensor/text_sensor.h +++ b/src/esphome/text_sensor/text_sensor.h @@ -14,19 +14,18 @@ ESPHOME_NAMESPACE_BEGIN namespace text_sensor { class TextSensorStateTrigger; -template -class TextSensorPublishAction; +template class TextSensorPublishAction; #define LOG_TEXT_SENSOR(prefix, type, obj) \ - if (obj != nullptr) { \ - ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ - if (!obj->get_icon().empty()) { \ - ESP_LOGCONFIG(TAG, prefix " Icon: '%s'", obj->get_icon().c_str()); \ - } \ - if (!obj->unique_id().empty()) { \ - ESP_LOGV(TAG, prefix " Unique ID: '%s'", obj->unique_id().c_str()); \ - } \ - } + if (obj != nullptr) { \ + ESP_LOGCONFIG(TAG, prefix type " '%s'", obj->get_name().c_str()); \ + if (!obj->get_icon().empty()) { \ + ESP_LOGCONFIG(TAG, prefix " Icon: '%s'", obj->get_icon().c_str()); \ + } \ + if (!obj->unique_id().empty()) { \ + ESP_LOGV(TAG, prefix " Unique ID: '%s'", obj->unique_id().c_str()); \ + } \ + } #ifdef USE_MQTT_TEXT_SENSOR class MQTTTextSensor; @@ -54,8 +53,7 @@ class TextSensor : public Nameable { virtual std::string unique_id(); TextSensorStateTrigger *make_state_trigger(); - template - TextSensorPublishAction *make_text_sensor_publish_action(); + template TextSensorPublishAction *make_text_sensor_publish_action(); bool has_state(); @@ -65,7 +63,7 @@ class TextSensor : public Nameable { #endif protected: - uint32_t hash_base_() override; + uint32_t hash_base() override; CallbackManager callback_; optional icon_; @@ -80,13 +78,12 @@ class TextSensorStateTrigger : public Trigger { explicit TextSensorStateTrigger(TextSensor *parent); }; -template -class TextSensorPublishAction : public Action { +template class TextSensorPublishAction : public Action { public: TextSensorPublishAction(TextSensor *sensor); - template - void set_state(V state) { this->state_ = state; } + template void set_state(V state) { this->state_ = state; } void play(Ts... x) override; + protected: TextSensor *sensor_; TemplatableValue state_; @@ -94,22 +91,20 @@ class TextSensorPublishAction : public Action { template TextSensorPublishAction::TextSensorPublishAction(TextSensor *sensor) : sensor_(sensor) {} -template -void TextSensorPublishAction::play(Ts... x) { +template void TextSensorPublishAction::play(Ts... x) { this->sensor_->publish_state(this->state_.value(x...)); this->play_next(x...); } -template -TextSensorPublishAction *TextSensor::make_text_sensor_publish_action() { +template TextSensorPublishAction *TextSensor::make_text_sensor_publish_action() { return new TextSensorPublishAction(this); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END #include "esphome/text_sensor/mqtt_text_sensor.h" -#endif //USE_TEXT_SENSOR +#endif // USE_TEXT_SENSOR -#endif //ESPHOME_TEXT_SENSOR_TEXT_SENSOR_H +#endif // ESPHOME_TEXT_SENSOR_TEXT_SENSOR_H diff --git a/src/esphome/text_sensor/version_text_sensor.cpp b/src/esphome/text_sensor/version_text_sensor.cpp index 4f6937f2..bc7818be 100644 --- a/src/esphome/text_sensor/version_text_sensor.cpp +++ b/src/esphome/text_sensor/version_text_sensor.cpp @@ -19,23 +19,15 @@ void VersionTextSensor::setup() { this->publish_state(ESPHOME_VERSION " " + get_app_compilation_time()); } } -float VersionTextSensor::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float VersionTextSensor::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } VersionTextSensor::VersionTextSensor(const std::string &name) : TextSensor(name) {} -std::string VersionTextSensor::icon() { - return "mdi:new-box"; -} -std::string VersionTextSensor::unique_id() { - return get_mac_address() + "-version"; -} -void VersionTextSensor::dump_config() { - LOG_TEXT_SENSOR("", "Version Text Sensor", this); -} +std::string VersionTextSensor::icon() { return "mdi:new-box"; } +std::string VersionTextSensor::unique_id() { return get_mac_address() + "-version"; } +void VersionTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Version Text Sensor", this); } -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_VERSION_TEXT_SENSOR +#endif // USE_VERSION_TEXT_SENSOR diff --git a/src/esphome/text_sensor/version_text_sensor.h b/src/esphome/text_sensor/version_text_sensor.h index edecce89..50df881e 100644 --- a/src/esphome/text_sensor/version_text_sensor.h +++ b/src/esphome/text_sensor/version_text_sensor.h @@ -22,10 +22,10 @@ class VersionTextSensor : public TextSensor, public Component { std::string unique_id() override; }; -} // namespace text_sensor +} // namespace text_sensor ESPHOME_NAMESPACE_END -#endif //USE_VERSION_TEXT_SENSOR +#endif // USE_VERSION_TEXT_SENSOR -#endif //ESPHOME_VERSION_TEXT_SENSOR_H +#endif // ESPHOME_VERSION_TEXT_SENSOR_H diff --git a/src/esphome/time/homeassistant_time.cpp b/src/esphome/time/homeassistant_time.cpp index f29b254f..d487e714 100644 --- a/src/esphome/time/homeassistant_time.cpp +++ b/src/esphome/time/homeassistant_time.cpp @@ -7,7 +7,7 @@ #include "esphome/log.h" #include "lwip/opt.h" #ifdef ARDUINO_ARCH_ESP8266 - #include "sys/time.h" +#include "sys/time.h" #endif ESPHOME_NAMESPACE_BEGIN @@ -18,10 +18,9 @@ static const char *TAG = "time.homeassistant"; void HomeAssistantTime::set_epoch_time(uint32_t epoch) { struct timeval timev { - .tv_sec = static_cast(epoch), - .tv_usec = 0, + .tv_sec = static_cast(epoch), .tv_usec = 0, }; - timezone tz = { 0, 0 }; + timezone tz = {0, 0}; settimeofday(&timev, &tz); auto time = this->now(); @@ -33,9 +32,7 @@ void HomeAssistantTime::dump_config() { ESP_LOGCONFIG(TAG, "Home Assistant Time:"); ESP_LOGCONFIG(TAG, " Timezone: '%s'", this->timezone_.c_str()); } -float HomeAssistantTime::get_setup_priority() const { - return setup_priority::HARDWARE_LATE; -} +float HomeAssistantTime::get_setup_priority() const { return setup_priority::HARDWARE_LATE; } void HomeAssistantTime::setup() { global_homeassistant_time = this; @@ -59,12 +56,10 @@ bool GetTimeResponse::decode_32bit(uint32_t field_id, uint32_t value) { return false; } } -api::APIMessageType GetTimeResponse::message_type() const { - return api::APIMessageType::GET_TIME_RESPONSE; -} +api::APIMessageType GetTimeResponse::message_type() const { return api::APIMessageType::GET_TIME_RESPONSE; } -} // namespace time +} // namespace time ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_TIME +#endif // USE_HOMEASSISTANT_TIME diff --git a/src/esphome/time/homeassistant_time.h b/src/esphome/time/homeassistant_time.h index 7ae76dad..745eb67a 100644 --- a/src/esphome/time/homeassistant_time.h +++ b/src/esphome/time/homeassistant_time.h @@ -19,6 +19,7 @@ class HomeAssistantTime : public RealTimeClockComponent { void dump_config() override; void set_epoch_time(uint32_t epoch); float get_setup_priority() const override; + protected: }; @@ -30,10 +31,10 @@ class GetTimeResponse : public api::APIMessage { api::APIMessageType message_type() const override; }; -} // namespace time +} // namespace time ESPHOME_NAMESPACE_END -#endif //USE_HOMEASSISTANT_TIME +#endif // USE_HOMEASSISTANT_TIME -#endif //ESPHOME_HOMEASSISTANT_TIME_H +#endif // ESPHOME_HOMEASSISTANT_TIME_H diff --git a/src/esphome/time/rtc_component.cpp b/src/esphome/time/rtc_component.cpp index 7c06354a..9a929fdb 100644 --- a/src/esphome/time/rtc_component.cpp +++ b/src/esphome/time/rtc_component.cpp @@ -11,15 +11,9 @@ namespace time { static const char *TAG = "time.rtc"; -RealTimeClockComponent::RealTimeClockComponent() { - -} -void RealTimeClockComponent::set_timezone(const std::string &tz) { - this->timezone_ = tz; -} -std::string RealTimeClockComponent::get_timezone() { - return this->timezone_; -} +RealTimeClockComponent::RealTimeClockComponent() {} +void RealTimeClockComponent::set_timezone(const std::string &tz) { this->timezone_ = tz; } +std::string RealTimeClockComponent::get_timezone() { return this->timezone_; } ESPTime RealTimeClockComponent::now() { time_t t = ::time(nullptr); struct tm *c_tm = ::localtime(&t); @@ -30,11 +24,9 @@ ESPTime RealTimeClockComponent::utcnow() { struct tm *c_tm = ::gmtime(&t); return ESPTime::from_tm(c_tm, t); } -CronTrigger *RealTimeClockComponent::make_cron_trigger() { - return new CronTrigger(this); -} -void RealTimeClockComponent::setup_() { - this->setup_internal(); +CronTrigger *RealTimeClockComponent::make_cron_trigger() { return new CronTrigger(this); } +void RealTimeClockComponent::call_setup() { + this->setup_internal_(); setenv("TZ", this->timezone_.c_str(), 1); tzset(); this->setup(); @@ -45,31 +37,27 @@ size_t ESPTime::strftime(char *buffer, size_t buffer_len, const char *format) { return ::strftime(buffer, buffer_len, format, &c_tm); } ESPTime ESPTime::from_tm(struct tm *c_tm, time_t c_time) { - return ESPTime{ - .second = uint8_t(c_tm->tm_sec), - .minute = uint8_t(c_tm->tm_min), - .hour = uint8_t(c_tm->tm_hour), - .day_of_week = uint8_t(c_tm->tm_wday + 1), - .day_of_month = uint8_t(c_tm->tm_mday), - .day_of_year = uint16_t(c_tm->tm_yday + 1), - .month = uint8_t(c_tm->tm_mon + 1), - .year = uint16_t(c_tm->tm_year + 1900), - .is_dst = bool(c_tm->tm_isdst), - .time = c_time - }; + return ESPTime{.second = uint8_t(c_tm->tm_sec), + .minute = uint8_t(c_tm->tm_min), + .hour = uint8_t(c_tm->tm_hour), + .day_of_week = uint8_t(c_tm->tm_wday + 1), + .day_of_month = uint8_t(c_tm->tm_mday), + .day_of_year = uint16_t(c_tm->tm_yday + 1), + .month = uint8_t(c_tm->tm_mon + 1), + .year = uint16_t(c_tm->tm_year + 1900), + .is_dst = bool(c_tm->tm_isdst), + .time = c_time}; } struct tm ESPTime::to_c_tm() { - struct tm c_tm = tm{ - .tm_sec = this->second, - .tm_min = this->minute, - .tm_hour = this->hour, - .tm_mday = this->day_of_month, - .tm_mon = this->month - 1, - .tm_year = this->year - 1900, - .tm_wday = this->day_of_week - 1, - .tm_yday = this->day_of_year - 1, - .tm_isdst = this->is_dst - }; + struct tm c_tm = tm{.tm_sec = this->second, + .tm_min = this->minute, + .tm_hour = this->hour, + .tm_mday = this->day_of_month, + .tm_mon = this->month - 1, + .tm_year = this->year - 1900, + .tm_wday = this->day_of_week - 1, + .tm_yday = this->day_of_year - 1, + .tm_isdst = this->is_dst}; return c_tm; } std::string ESPTime::strftime(const std::string &format) { @@ -84,12 +72,9 @@ std::string ESPTime::strftime(const std::string &format) { timestr.resize(len); return timestr; } -bool ESPTime::is_valid() const { - return this->year >= 2018; -} +bool ESPTime::is_valid() const { return this->year >= 2018; } -template -bool increment_time_value(T ¤t, uint16_t begin, uint16_t end) { +template bool increment_time_value(T ¤t, uint16_t begin, uint16_t end) { current++; if (current >= end) { current = begin; @@ -130,51 +115,26 @@ void ESPTime::increment_second() { this->year++; } } -bool ESPTime::operator<(ESPTime other) { - return this->time < other.time; -} -bool ESPTime::operator<=(ESPTime other) { - return this->time <= other.time; -} -bool ESPTime::operator==(ESPTime other) { - return this->time == other.time; -} -bool ESPTime::operator>=(ESPTime other) { - return this->time >= other.time; -} -bool ESPTime::operator>(ESPTime other) { - return this->time > other.time; -} +bool ESPTime::operator<(ESPTime other) { return this->time < other.time; } +bool ESPTime::operator<=(ESPTime other) { return this->time <= other.time; } +bool ESPTime::operator==(ESPTime other) { return this->time == other.time; } +bool ESPTime::operator>=(ESPTime other) { return this->time >= other.time; } +bool ESPTime::operator>(ESPTime other) { return this->time > other.time; } bool ESPTime::in_range() const { - return this->second < 61 && this->minute < 60 && this->hour < 24 && - this->day_of_week > 0 && this->day_of_week < 8 && - this->day_of_month > 0 && this->day_of_month < 32 && - this->day_of_year > 0 && this->day_of_year < 367 && - this->month > 0 && this->month < 13; + return this->second < 61 && this->minute < 60 && this->hour < 24 && this->day_of_week > 0 && this->day_of_week < 8 && + this->day_of_month > 0 && this->day_of_month < 32 && this->day_of_year > 0 && this->day_of_year < 367 && + this->month > 0 && this->month < 13; } -void CronTrigger::add_second(uint8_t second) { - this->seconds_[second] = true; -} -void CronTrigger::add_minute(uint8_t minute) { - this->minutes_[minute] = true; -} -void CronTrigger::add_hour(uint8_t hour) { - this->hours_[hour] = true; -} -void CronTrigger::add_day_of_month(uint8_t day_of_month) { - this->days_of_month_[day_of_month] = true; -} -void CronTrigger::add_month(uint8_t month) { - this->months_[month] = true; -} -void CronTrigger::add_day_of_week(uint8_t day_of_week) { - this->days_of_week_[day_of_week] = true; -} +void CronTrigger::add_second(uint8_t second) { this->seconds_[second] = true; } +void CronTrigger::add_minute(uint8_t minute) { this->minutes_[minute] = true; } +void CronTrigger::add_hour(uint8_t hour) { this->hours_[hour] = true; } +void CronTrigger::add_day_of_month(uint8_t day_of_month) { this->days_of_month_[day_of_month] = true; } +void CronTrigger::add_month(uint8_t month) { this->months_[month] = true; } +void CronTrigger::add_day_of_week(uint8_t day_of_week) { this->days_of_week_[day_of_week] = true; } bool CronTrigger::matches(const ESPTime &time) { - return time.is_valid() && this->seconds_[time.second] && this->minutes_[time.minute] && - this->hours_[time.hour] && this->days_of_month_[time.day_of_month] && this->months_[time.month] && - this->days_of_week_[time.day_of_week]; + return time.is_valid() && this->seconds_[time.second] && this->minutes_[time.minute] && this->hours_[time.hour] && + this->days_of_month_[time.day_of_month] && this->months_[time.month] && this->days_of_week_[time.day_of_week]; } void CronTrigger::loop() { ESPTime time = this->rtc_->now(); @@ -201,17 +161,14 @@ void CronTrigger::loop() { if (!time.in_range()) { ESP_LOGW(TAG, "Time is out of range!"); ESP_LOGD(TAG, "Second=%02u Minute=%02u Hour=%02u DayOfWeek=%u DayOfMonth=%u DayOfYear=%u Month=%u time=%ld", - time.second, time.minute, time.hour, - time.day_of_week, time.day_of_month, time.day_of_year, - time.month, time.time); + time.second, time.minute, time.hour, time.day_of_week, time.day_of_month, time.day_of_year, time.month, + time.time); } if (this->matches(time)) this->trigger(); } -CronTrigger::CronTrigger(RealTimeClockComponent *rtc) : rtc_(rtc) { - -} +CronTrigger::CronTrigger(RealTimeClockComponent *rtc) : rtc_(rtc) {} void CronTrigger::add_seconds(const std::vector &seconds) { for (uint8_t it : seconds) this->add_second(it); @@ -236,12 +193,10 @@ void CronTrigger::add_days_of_week(const std::vector &days_of_week) { for (uint8_t it : days_of_week) this->add_day_of_week(it); } -float CronTrigger::get_setup_priority() const { - return setup_priority::HARDWARE; -} +float CronTrigger::get_setup_priority() const { return setup_priority::HARDWARE; } -} // namespace time +} // namespace time ESPHOME_NAMESPACE_END -#endif //USE_TIME +#endif // USE_TIME diff --git a/src/esphome/time/rtc_component.h b/src/esphome/time/rtc_component.h index fb308e38..78ebafce 100644 --- a/src/esphome/time/rtc_component.h +++ b/src/esphome/time/rtc_component.h @@ -129,15 +129,16 @@ class RealTimeClockComponent : public Component { CronTrigger *make_cron_trigger(); - void setup_() override; + void call_setup() override; + protected: std::string timezone_{}; }; -} // namespace time +} // namespace time ESPHOME_NAMESPACE_END -#endif //USE_TIME +#endif // USE_TIME -#endif //ESPHOME_TIME_RTC_COMPONENT_H +#endif // ESPHOME_TIME_RTC_COMPONENT_H diff --git a/src/esphome/time/sntp_component.cpp b/src/esphome/time/sntp_component.cpp index d06534b3..30005534 100644 --- a/src/esphome/time/sntp_component.cpp +++ b/src/esphome/time/sntp_component.cpp @@ -8,10 +8,10 @@ #include "esphome/time/sntp_component.h" #ifdef ARDUINO_ARCH_ESP32 - #include "apps/sntp/sntp.h" +#include "apps/sntp/sntp.h" #endif #ifdef ARDUINO_ARCH_ESP8266 - #include "sntp.h" +#include "sntp.h" #endif ESPHOME_NAMESPACE_BEGIN @@ -20,8 +20,7 @@ namespace time { static const char *TAG = "time.sntp"; -SNTPComponent::SNTPComponent() - : RealTimeClockComponent() { +SNTPComponent::SNTPComponent() : RealTimeClockComponent() { this->server_1_ = "0.pool.ntp.org"; this->server_2_ = "1.pool.ntp.org"; this->server_3_ = "2.pool.ntp.org"; @@ -59,16 +58,12 @@ void SNTPComponent::dump_config() { ESP_LOGCONFIG(TAG, " Server 3: '%s'", this->server_3_.c_str()); ESP_LOGCONFIG(TAG, " Timezone: '%s'", this->timezone_.c_str()); } -void SNTPComponent::set_servers(const std::string &server_1, - const std::string &server_2, - const std::string &server_3) { +void SNTPComponent::set_servers(const std::string &server_1, const std::string &server_2, const std::string &server_3) { this->server_1_ = server_1; this->server_2_ = server_2; this->server_3_ = server_3; } -float SNTPComponent::get_setup_priority() const { - return setup_priority::WIFI; -} +float SNTPComponent::get_setup_priority() const { return setup_priority::WIFI; } void SNTPComponent::loop() { if (this->has_time_) return; @@ -83,8 +78,8 @@ void SNTPComponent::loop() { this->has_time_ = true; } -} // namespace time +} // namespace time ESPHOME_NAMESPACE_END -#endif //USE_SNTP_COMPONENT +#endif // USE_SNTP_COMPONENT diff --git a/src/esphome/time/sntp_component.h b/src/esphome/time/sntp_component.h index 205f6d30..636942e4 100644 --- a/src/esphome/time/sntp_component.h +++ b/src/esphome/time/sntp_component.h @@ -25,9 +25,7 @@ class SNTPComponent : public RealTimeClockComponent { void setup() override; void dump_config() override; /// Change the servers used by SNTP for timekeeping - void set_servers(const std::string &server_1, - const std::string &server_2, - const std::string &server_3); + void set_servers(const std::string &server_1, const std::string &server_2, const std::string &server_3); float get_setup_priority() const override; void loop() override; @@ -39,10 +37,10 @@ class SNTPComponent : public RealTimeClockComponent { bool has_time_{false}; }; -} // namespace time +} // namespace time ESPHOME_NAMESPACE_END -#endif //USE_SNTP_COMPONENT +#endif // USE_SNTP_COMPONENT -#endif //ESPHOME_SNTP_COMPONENT_H +#endif // ESPHOME_SNTP_COMPONENT_H diff --git a/src/esphome/uart_component.cpp b/src/esphome/uart_component.cpp index 2786074f..4090b60b 100644 --- a/src/esphome/uart_component.cpp +++ b/src/esphome/uart_component.cpp @@ -14,14 +14,9 @@ static const char *TAG = "uart"; uint8_t next_uart_num = 1; #endif -UARTComponent::UARTComponent(uint32_t baud_rate) - : baud_rate_(baud_rate) { +UARTComponent::UARTComponent(uint32_t baud_rate) : baud_rate_(baud_rate) {} -} - -float UARTComponent::get_setup_priority() const { - return setup_priority::PRE_HARDWARE; -} +float UARTComponent::get_setup_priority() const { return setup_priority::PRE_HARDWARE; } #ifdef ARDUINO_ARCH_ESP32 void UARTComponent::setup() { @@ -104,14 +99,12 @@ bool UARTComponent::check_read_timeout_(size_t len) { } return true; } -int UARTComponent::available() { - return this->hw_serial_->available(); -} +int UARTComponent::available() { return this->hw_serial_->available(); } void UARTComponent::flush() { ESP_LOGVV(TAG, " Flushing..."); this->hw_serial_->flush(); } -#endif //ESP32 +#endif // ESP32 #ifdef ARDUINO_ARCH_ESP8266 void UARTComponent::setup() { @@ -259,14 +252,12 @@ void ESP8266SoftwareSerial::setup(int8_t tx_pin, int8_t rx_pin, uint32_t baud_ra this->rx_mask_ = (1U << rx_pin); pinMode(rx_pin, INPUT); this->rx_buffer_ = new uint8_t[this->rx_buffer_size_]; - attach_functional_interrupt(rx_pin, [this]() ICACHE_RAM_ATTR { - this->gpio_intr_(); - }, FALLING); + attach_functional_interrupt(rx_pin, [this]() ICACHE_RAM_ATTR { this->gpio_intr_(); }, FALLING); } } void ICACHE_RAM_ATTR HOT ESP8266SoftwareSerial::gpio_intr_() { - uint32_t wait = this->bit_time_ + this->bit_time_/3 - 500; + uint32_t wait = this->bit_time_ + this->bit_time_ / 3 - 500; const uint32_t start = ESP.getCycleCount(); uint8_t rec = 0; // Manually unroll the loop @@ -310,7 +301,8 @@ void ICACHE_RAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) { enable_interrupts(); } void ESP8266SoftwareSerial::wait_(uint32_t &wait, const uint32_t &start) { - while (ESP.getCycleCount() - start < wait); + while (ESP.getCycleCount() - start < wait) + ; wait += this->bit_time_; } uint8_t ESP8266SoftwareSerial::read_bit_(uint32_t &wait, const uint32_t &start) { @@ -325,12 +317,8 @@ void ESP8266SoftwareSerial::write_bit_(bool bit, uint32_t &wait, const uint32_t } this->wait_(wait, start); } -void ESP8266SoftwareSerial::tx_high_() { - GPOS = this->tx_mask_; -} -void ESP8266SoftwareSerial::tx_low_() { - GPOC = this->tx_mask_; -} +void ESP8266SoftwareSerial::tx_high_() { GPOS = this->tx_mask_; } +void ESP8266SoftwareSerial::tx_low_() { GPOC = this->tx_mask_; } uint8_t ESP8266SoftwareSerial::read_byte() { if (this->rx_in_pos_ == this->rx_out_pos_) return 0; @@ -343,16 +331,14 @@ uint8_t ESP8266SoftwareSerial::peek_byte() { return 0; return this->rx_buffer_[this->rx_out_pos_]; } -void ESP8266SoftwareSerial::flush() { - this->rx_in_pos_ = this->rx_out_pos_ = 0; -} +void ESP8266SoftwareSerial::flush() { this->rx_in_pos_ = this->rx_out_pos_ = 0; } int ESP8266SoftwareSerial::available() { int avail = int(this->rx_in_pos_) - int(this->rx_out_pos_); if (avail < 0) return avail + this->rx_buffer_size_; return avail; } -#endif //ESP8266 +#endif // ESP8266 size_t UARTComponent::write(uint8_t data) { this->write_byte(data); @@ -370,50 +356,22 @@ int UARTComponent::peek() { return -1; return data; } -void UARTComponent::set_tx_pin(uint8_t tx_pin) { - this->tx_pin_ = tx_pin; -} -void UARTComponent::set_rx_pin(uint8_t rx_pin) { - this->rx_pin_ = rx_pin; -} +void UARTComponent::set_tx_pin(uint8_t tx_pin) { this->tx_pin_ = tx_pin; } +void UARTComponent::set_rx_pin(uint8_t rx_pin) { this->rx_pin_ = rx_pin; } -void UARTDevice::write_byte(uint8_t data) { - this->parent_->write_byte(data); -} -void UARTDevice::write_array(const uint8_t *data, size_t len) { - this->parent_->write_array(data, len); -} -void UARTDevice::write_str(const char *str) { - this->parent_->write_str(str); -} -bool UARTDevice::read_byte(uint8_t *data) { - return this->parent_->read_byte(data); -} -bool UARTDevice::peek_byte(uint8_t *data) { - return this->parent_->peek_byte(data); -} -bool UARTDevice::read_array(uint8_t *data, size_t len) { - return this->parent_->read_array(data, len); -} -int UARTDevice::available() { - return this->parent_->available(); -} -void UARTDevice::flush() { - return this->parent_->flush(); -} -UARTDevice::UARTDevice(UARTComponent *parent) : parent_(parent) { - -} -size_t UARTDevice::write(uint8_t data) { - return this->parent_->write(data); -} -int UARTDevice::read() { - return this->parent_->read(); -} -int UARTDevice::peek() { - return this->parent_->peek(); -} +void UARTDevice::write_byte(uint8_t data) { this->parent_->write_byte(data); } +void UARTDevice::write_array(const uint8_t *data, size_t len) { this->parent_->write_array(data, len); } +void UARTDevice::write_str(const char *str) { this->parent_->write_str(str); } +bool UARTDevice::read_byte(uint8_t *data) { return this->parent_->read_byte(data); } +bool UARTDevice::peek_byte(uint8_t *data) { return this->parent_->peek_byte(data); } +bool UARTDevice::read_array(uint8_t *data, size_t len) { return this->parent_->read_array(data, len); } +int UARTDevice::available() { return this->parent_->available(); } +void UARTDevice::flush() { return this->parent_->flush(); } +UARTDevice::UARTDevice(UARTComponent *parent) : parent_(parent) {} +size_t UARTDevice::write(uint8_t data) { return this->parent_->write(data); } +int UARTDevice::read() { return this->parent_->read(); } +int UARTDevice::peek() { return this->parent_->peek(); } ESPHOME_NAMESPACE_END -#endif //USE_UART +#endif // USE_UART diff --git a/src/esphome/uart_component.h b/src/esphome/uart_component.h index 28dbad94..ec7f5135 100644 --- a/src/esphome/uart_component.h +++ b/src/esphome/uart_component.h @@ -121,6 +121,6 @@ class UARTDevice : public Stream { ESPHOME_NAMESPACE_END -#endif //USE_UART +#endif // USE_UART -#endif //ESPHOME_UART_COMPONENT_H +#endif // ESPHOME_UART_COMPONENT_H diff --git a/src/esphome/util.cpp b/src/esphome/util.cpp index be00fdf5..ef01e6d4 100644 --- a/src/esphome/util.cpp +++ b/src/esphome/util.cpp @@ -6,10 +6,10 @@ #include "esphome/application.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #ifdef ARDUINO_ARCH_ESP8266 - #include +#include #endif ESPHOME_NAMESPACE_BEGIN @@ -30,25 +30,25 @@ void network_setup() { bool ready = true; #ifdef USE_ETHERNET if (global_eth_component != nullptr) { - global_eth_component->setup_(); + global_eth_component->call_setup(); ready = false; } #endif if (global_wifi_component != nullptr) { - global_wifi_component->setup_(); + global_wifi_component->call_setup(); ready = false; } while (!ready) { #ifdef USE_ETHERNET if (global_eth_component != nullptr) { - global_eth_component->loop_(); + global_eth_component->call_loop(); ready = ready || global_eth_component->can_proceed(); } #endif if (global_wifi_component != nullptr) { - global_wifi_component->loop_(); + global_wifi_component->call_loop(); ready = ready || global_wifi_component->can_proceed(); } tick_status_led(); @@ -58,10 +58,10 @@ void network_setup() { void network_tick() { #ifdef USE_ETHERNET if (global_eth_component != nullptr) - global_eth_component->loop_(); + global_eth_component->call_loop(); #endif if (global_wifi_component != nullptr) - global_wifi_component->loop_(); + global_wifi_component->call_loop(); } void network_setup_mdns() { @@ -98,12 +98,8 @@ std::string network_get_address() { return ""; } -std::string get_app_name() { - return App.get_name(); -} +std::string get_app_name() { return App.get_name(); } -std::string get_app_compilation_time() { - return App.get_compilation_time(); -} +std::string get_app_compilation_time() { return App.get_compilation_time(); } ESPHOME_NAMESPACE_END diff --git a/src/esphome/util.h b/src/esphome/util.h index 824b8c45..27471039 100644 --- a/src/esphome/util.h +++ b/src/esphome/util.h @@ -23,4 +23,4 @@ std::string get_app_compilation_time(); ESPHOME_NAMESPACE_END -#endif //ESPHOME_UTIL_H +#endif // ESPHOME_UTIL_H diff --git a/src/esphome/web_server.cpp b/src/esphome/web_server.cpp index e215e9f6..582ac925 100644 --- a/src/esphome/web_server.cpp +++ b/src/esphome/web_server.cpp @@ -9,10 +9,10 @@ #include "StreamString.h" #ifdef ARDUINO_ARCH_ESP32 - #include +#include #endif #ifdef ARDUINO_ARCH_ESP8266 - #include +#include #endif #include @@ -21,8 +21,7 @@ ESPHOME_NAMESPACE_BEGIN static const char *TAG = "web_server"; -void write_row(AsyncResponseStream *stream, Nameable *obj, - const std::string &klass, const std::string &action) { +void write_row(AsyncResponseStream *stream, Nameable *obj, const std::string &klass, const std::string &action) { stream->print("print(klass.c_str()); stream->print("\" id=\""); @@ -62,20 +61,11 @@ UrlMatch match_url(const std::string &url, bool only_domain = false) { return match; } -WebServer::WebServer(uint16_t port) - : port_(port) { +WebServer::WebServer(uint16_t port) : port_(port) {} -} - -void WebServer::set_css_url(const char *css_url) { - this->css_url_ = css_url; -} -void WebServer::set_js_url(const char *js_url) { - this->js_url_ = js_url; -} -void WebServer::set_port(uint16_t port) { - this->port_ = port; -} +void WebServer::set_css_url(const char *css_url) { this->css_url_ = css_url; } +void WebServer::set_js_url(const char *js_url) { this->js_url_ = js_url; } +void WebServer::set_port(uint16_t port) { this->port_ = port; } void WebServer::setup() { ESP_LOGCONFIG(TAG, "Setting up web server..."); @@ -123,25 +113,20 @@ void WebServer::setup() { }); if (global_log_component != nullptr) - global_log_component->add_on_log_callback([this](int level, const char *tag, const char *message) { - this->events_.send(message, "log", millis()); - }); + global_log_component->add_on_log_callback( + [this](int level, const char *tag, const char *message) { this->events_.send(message, "log", millis()); }); this->server_->addHandler(this); this->server_->addHandler(&this->events_); this->server_->begin(); - this->set_interval(10000, [this]() { - this->events_.send("", "ping", millis(), 30000); - }); + this->set_interval(10000, [this]() { this->events_.send("", "ping", millis(), 30000); }); } void WebServer::dump_config() { ESP_LOGCONFIG(TAG, "Web Server:"); ESP_LOGCONFIG(TAG, " Address: %s:%u", network_get_address().c_str(), this->port_); } -float WebServer::get_setup_priority() const { - return setup_priority::WIFI - 1.0f; -} +float WebServer::get_setup_priority() const { return setup_priority::WIFI - 1.0f; } void WebServer::handle_update_request(AsyncWebServerRequest *request) { AsyncWebServerResponse *response; @@ -163,12 +148,8 @@ void report_ota_error() { ESP_LOGW(TAG, "OTA Update failed! Error: %s", ss.c_str()); } -void WebServer::handleUpload(AsyncWebServerRequest *request, - const String &filename, - size_t index, - uint8_t *data, - size_t len, - bool final) { +void WebServer::handleUpload(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, + size_t len, bool final) { bool success; if (index == 0) { ESP_LOGI(TAG, "OTA Update Start: %s", filename.c_str()); @@ -212,9 +193,7 @@ void WebServer::handleUpload(AsyncWebServerRequest *request, if (final) { if (Update.end(true)) { ESP_LOGI(TAG, "OTA update successful!"); - this->set_timeout(100, []() { - safe_reboot("ota"); - }); + this->set_timeout(100, []() { safe_reboot("ota"); }); } else { report_ota_error(); } @@ -272,12 +251,12 @@ void WebServer::handle_index_request(AsyncWebServerRequest *request) { write_row(stream, obj, "text_sensor", ""); #endif - stream->print( - F("

See ESPHome Web API for REST API documentation.

" - "

OTA Update

" - "

Debug Log

"
-        "