ESP8266 connect fixes (#605)

* ESP8266 Connection Fixes

* Update client.py

* Update mqtt_client.cpp

* Update mqtt_client.cpp

* Fix ping

* Async dump config

* Update base image to 1.7.0

* Update helpers.py

* Updates

* Update Dockerfile.lint
This commit is contained in:
Otto Winter 2019-06-03 15:21:36 +02:00 committed by GitHub
parent fe24745815
commit c53483a3b2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 66 additions and 64 deletions

View file

@ -3,7 +3,7 @@
variables: variables:
DOCKER_DRIVER: overlay2 DOCKER_DRIVER: overlay2
DOCKER_HOST: tcp://docker:2375/ DOCKER_HOST: tcp://docker:2375/
BASE_VERSION: '1.5.1' BASE_VERSION: '1.7.0'
TZ: UTC TZ: UTC
stages: stages:

View file

@ -1,4 +1,4 @@
ARG BUILD_FROM=esphome/esphome-base-amd64:1.5.1 ARG BUILD_FROM=esphome/esphome-base-amd64:1.7.0
FROM ${BUILD_FROM} FROM ${BUILD_FROM}
COPY . . COPY . .

View file

@ -1,4 +1,4 @@
FROM esphome/esphome-base-amd64:1.5.1 FROM esphome/esphome-base-amd64:1.7.0
RUN \ RUN \
apt-get update \ apt-get update \
@ -12,7 +12,7 @@ RUN \
/var/lib/apt/lists/* /var/lib/apt/lists/*
COPY requirements_test.txt /requirements_test.txt COPY requirements_test.txt /requirements_test.txt
RUN pip2 install -r /requirements_test.txt RUN pip2 install --no-cache-dir wheel && pip2 install --no-cache-dir -r /requirements_test.txt
VOLUME ["/esphome"] VOLUME ["/esphome"]
WORKDIR /esphome WORKDIR /esphome

View file

@ -108,7 +108,6 @@ class APIClient(threading.Thread):
self._message_handlers = [] self._message_handlers = []
self._keepalive = 5 self._keepalive = 5
self._ping_timer = None self._ping_timer = None
self._refresh_ping()
self.on_disconnect = None self.on_disconnect = None
self.on_connect = None self.on_connect = None
@ -132,8 +131,8 @@ class APIClient(threading.Thread):
if self._connected: if self._connected:
try: try:
self.ping() self.ping()
except APIConnectionError: except APIConnectionError as err:
self._fatal_error() self._fatal_error(err)
else: else:
self._refresh_ping() self._refresh_ping()
@ -175,7 +174,7 @@ class APIClient(threading.Thread):
raise APIConnectionError("You need to call start() first!") raise APIConnectionError("You need to call start() first!")
if self._connected: if self._connected:
raise APIConnectionError("Already connected!") self.disconnect(on_disconnect=False)
try: try:
ip = resolve_ip_address(self._address) ip = resolve_ip_address(self._address)
@ -193,8 +192,9 @@ class APIClient(threading.Thread):
try: try:
self._socket.connect((ip, self._port)) self._socket.connect((ip, self._port))
except socket.error as err: except socket.error as err:
self._fatal_error() err = APIConnectionError("Error connecting to {}: {}".format(ip, err))
raise APIConnectionError("Error connecting to {}: {}".format(ip, err)) self._fatal_error(err)
raise err
self._socket.settimeout(0.1) self._socket.settimeout(0.1)
self._socket_open_event.set() self._socket_open_event.set()
@ -204,18 +204,20 @@ class APIClient(threading.Thread):
try: try:
resp = self._send_message_await_response(hello, pb.HelloResponse) resp = self._send_message_await_response(hello, pb.HelloResponse)
except APIConnectionError as err: except APIConnectionError as err:
self._fatal_error() self._fatal_error(err)
raise err raise err
_LOGGER.debug("Successfully connected to %s ('%s' API=%s.%s)", self._address, _LOGGER.debug("Successfully connected to %s ('%s' API=%s.%s)", self._address,
resp.server_info, resp.api_version_major, resp.api_version_minor) resp.server_info, resp.api_version_major, resp.api_version_minor)
self._connected = True self._connected = True
self._refresh_ping()
if self.on_connect is not None: if self.on_connect is not None:
self.on_connect() self.on_connect()
def _check_connected(self): def _check_connected(self):
if not self._connected: if not self._connected:
self._fatal_error() err = APIConnectionError("Must be connected!")
raise APIConnectionError("Must be connected!") self._fatal_error(err)
raise err
def login(self): def login(self):
self._check_connected() self._check_connected()
@ -233,13 +235,13 @@ class APIClient(threading.Thread):
if self.on_login is not None: if self.on_login is not None:
self.on_login() self.on_login()
def _fatal_error(self): def _fatal_error(self, err):
was_connected = self._connected was_connected = self._connected
self._close_socket() self._close_socket()
if was_connected and self.on_disconnect is not None: if was_connected and self.on_disconnect is not None:
self.on_disconnect() self.on_disconnect(err)
def _write(self, data): # type: (bytes) -> None def _write(self, data): # type: (bytes) -> None
if self._socket is None: if self._socket is None:
@ -250,8 +252,9 @@ class APIClient(threading.Thread):
try: try:
self._socket.sendall(data) self._socket.sendall(data)
except socket.error as err: except socket.error as err:
self._fatal_error() err = APIConnectionError("Error while writing data: {}".format(err))
raise APIConnectionError("Error while writing data: {}".format(err)) self._fatal_error(err)
raise err
def _send_message(self, msg): def _send_message(self, msg):
# type: (message.Message) -> None # type: (message.Message) -> None
@ -271,7 +274,6 @@ class APIClient(threading.Thread):
req += _varuint_to_bytes(message_type) req += _varuint_to_bytes(message_type)
req += encoded req += encoded
self._write(req) self._write(req)
self._refresh_ping()
def _send_message_await_response_complex(self, send_msg, do_append, do_stop, timeout=1): def _send_message_await_response_complex(self, send_msg, do_append, do_stop, timeout=1):
event = threading.Event() event = threading.Event()
@ -309,7 +311,7 @@ class APIClient(threading.Thread):
self._check_connected() self._check_connected()
return self._send_message_await_response(pb.PingRequest(), pb.PingResponse) return self._send_message_await_response(pb.PingRequest(), pb.PingResponse)
def disconnect(self): def disconnect(self, on_disconnect=True):
self._check_connected() self._check_connected()
try: try:
@ -318,7 +320,7 @@ class APIClient(threading.Thread):
pass pass
self._close_socket() self._close_socket()
if self.on_disconnect is not None: if self.on_disconnect is not None and on_disconnect:
self.on_disconnect() self.on_disconnect()
def _check_authenticated(self): def _check_authenticated(self):
@ -387,7 +389,6 @@ class APIClient(threading.Thread):
for msg_handler in self._message_handlers[:]: for msg_handler in self._message_handlers[:]:
msg_handler(msg) msg_handler(msg)
self._handle_internal_messages(msg) self._handle_internal_messages(msg)
self._refresh_ping()
def run(self): def run(self):
self._running_event.set() self._running_event.set()
@ -399,7 +400,7 @@ class APIClient(threading.Thread):
break break
if self._connected: if self._connected:
_LOGGER.error("Error while reading incoming messages: %s", err) _LOGGER.error("Error while reading incoming messages: %s", err)
self._fatal_error() self._fatal_error(err)
self._running_event.clear() self._running_event.clear()
def _handle_internal_messages(self, msg): def _handle_internal_messages(self, msg):
@ -431,12 +432,12 @@ def run_logs(config, address):
has_connects = [] has_connects = []
def try_connect(tries=0, is_disconnect=True): def try_connect(err, tries=0):
if stopping: if stopping:
return return
if is_disconnect: if err:
_LOGGER.warning(u"Disconnected from API.") _LOGGER.warning(u"Disconnected from API: %s", err)
while retry_timer: while retry_timer:
retry_timer.pop(0).cancel() retry_timer.pop(0).cancel()
@ -445,8 +446,8 @@ def run_logs(config, address):
try: try:
cli.connect() cli.connect()
cli.login() cli.login()
except APIConnectionError as err: # noqa except APIConnectionError as err2: # noqa
error = err error = err2
if error is None: if error is None:
_LOGGER.info("Successfully connected to %s", address) _LOGGER.info("Successfully connected to %s", address)
@ -460,7 +461,7 @@ def run_logs(config, address):
else: else:
_LOGGER.warning(u"Couldn't connect to API (%s). Trying to reconnect in %s seconds", _LOGGER.warning(u"Couldn't connect to API (%s). Trying to reconnect in %s seconds",
error, wait_time) error, wait_time)
timer = threading.Timer(wait_time, functools.partial(try_connect, tries + 1, is_disconnect)) timer = threading.Timer(wait_time, functools.partial(try_connect, None, tries + 1))
timer.start() timer.start()
retry_timer.append(timer) retry_timer.append(timer)
@ -484,7 +485,7 @@ def run_logs(config, address):
cli.start() cli.start()
try: try:
try_connect(is_disconnect=False) try_connect(None)
while True: while True:
time.sleep(1) time.sleep(1)
except KeyboardInterrupt: except KeyboardInterrupt:

View file

@ -712,12 +712,12 @@ bool APIConnection::send_buffer(APIMessageType type) {
size_t needed_space = this->send_buffer_.size() + header_len; size_t needed_space = this->send_buffer_.size() + header_len;
if (needed_space > this->client_->space()) { if (needed_space > this->client_->space()) {
delay(5); delay(0);
if (needed_space > this->client_->space()) { if (needed_space > this->client_->space()) {
if (type != APIMessageType::SUBSCRIBE_LOGS_RESPONSE) { if (type != APIMessageType::SUBSCRIBE_LOGS_RESPONSE) {
ESP_LOGV(TAG, "Cannot send message because of TCP buffer space"); ESP_LOGV(TAG, "Cannot send message because of TCP buffer space");
} }
delay(5); delay(0);
return false; return false;
} }
} }

View file

@ -360,18 +360,19 @@ bool MQTTClientComponent::publish(const std::string &topic, const char *payload,
} }
bool logging_topic = topic == this->log_message_.topic; bool logging_topic = topic == this->log_message_.topic;
uint16_t ret = this->mqtt_client_.publish(topic.c_str(), qos, retain, payload, payload_length); uint16_t ret = this->mqtt_client_.publish(topic.c_str(), qos, retain, payload, payload_length);
yield(); delay(0);
if (ret == 0 && !logging_topic && this->is_connected()) { if (ret == 0 && !logging_topic && this->is_connected()) {
delay(5); delay(0);
ret = this->mqtt_client_.publish(topic.c_str(), qos, retain, payload, payload_length); ret = this->mqtt_client_.publish(topic.c_str(), qos, retain, payload, payload_length);
yield(); delay(0);
} }
if (!logging_topic) { if (!logging_topic) {
if (ret != 0) { if (ret != 0) {
ESP_LOGV(TAG, "Publish(topic='%s' payload='%s' retain=%d)", topic.c_str(), payload, retain); ESP_LOGV(TAG, "Publish(topic='%s' payload='%s' retain=%d)", topic.c_str(), payload, retain);
} else { } else {
ESP_LOGW(TAG, "Publish failed for topic='%s' will retry later..", topic.c_str()); ESP_LOGV(TAG, "Publish failed for topic='%s' (len=%u). will retry later..", topic.c_str(),
payload_length); // NOLINT
this->status_momentary_warning("publish", 1000); this->status_momentary_warning("publish", 1000);
} }
} }

View file

@ -421,6 +421,7 @@ void WiFiComponent::check_connecting_finished() {
} }
void WiFiComponent::retry_connect() { void WiFiComponent::retry_connect() {
delay(10);
if (this->num_retried_ > 5 || this->error_from_callback_) { if (this->num_retried_ > 5 || this->error_from_callback_) {
// If retry failed for more than 5 times, let's restart STA // If retry failed for more than 5 times, let's restart STA
ESP_LOGW(TAG, "Restarting WiFi adapter..."); ESP_LOGW(TAG, "Restarting WiFi adapter...");

View file

@ -330,7 +330,6 @@ const char *get_disconnect_reason_str(uint8_t reason) {
} }
void WiFiComponent::wifi_event_callback(System_Event_t *event) { void WiFiComponent::wifi_event_callback(System_Event_t *event) {
#ifdef ESPHOME_LOG_HAS_VERBOSE
// TODO: this callback is called while in cont context, so delay will fail // TODO: this callback is called while in cont context, so delay will fail
// We need to defer the log messages until we're out of this context // We need to defer the log messages until we're out of this context
// only affects verbose log level // only affects verbose log level
@ -351,7 +350,7 @@ void WiFiComponent::wifi_event_callback(System_Event_t *event) {
char buf[33]; char buf[33];
memcpy(buf, it.ssid, it.ssid_len); memcpy(buf, it.ssid, it.ssid_len);
buf[it.ssid_len] = '\0'; buf[it.ssid_len] = '\0';
ESP_LOGV(TAG, "Event: Disconnected ssid='%s' bssid=%s reason='%s'", buf, format_mac_addr(it.bssid).c_str(), ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=%s reason='%s'", buf, format_mac_addr(it.bssid).c_str(),
get_disconnect_reason_str(it.reason)); get_disconnect_reason_str(it.reason));
break; break;
} }
@ -403,7 +402,6 @@ void WiFiComponent::wifi_event_callback(System_Event_t *event) {
default: default:
break; break;
} }
#endif
if (event->event == EVENT_STAMODE_DISCONNECTED) { if (event->event == EVENT_STAMODE_DISCONNECTED) {
global_wifi_component->error_from_callback_ = true; global_wifi_component->error_from_callback_ = true;

View file

@ -57,14 +57,7 @@ void Application::setup() {
} }
ESP_LOGI(TAG, "setup() finished successfully!"); ESP_LOGI(TAG, "setup() finished successfully!");
this->dump_config(); this->schedule_dump_config();
}
void Application::dump_config() {
ESP_LOGI(TAG, "esphome version " ESPHOME_VERSION " compiled on %s", this->compilation_time_.c_str());
for (auto component : this->components_) {
component->dump_config();
}
} }
void Application::loop() { void Application::loop() {
uint32_t new_app_state = 0; uint32_t new_app_state = 0;
@ -97,9 +90,13 @@ void Application::loop() {
} }
this->last_loop_ = now; this->last_loop_ = now;
if (this->dump_config_scheduled_) { if (this->dump_config_at_ >= 0 && this->dump_config_at_ < this->components_.size()) {
this->dump_config(); if (this->dump_config_at_ == 0) {
this->dump_config_scheduled_ = false; ESP_LOGI(TAG, "esphome version " ESPHOME_VERSION " compiled on %s", this->compilation_time_.c_str());
}
this->components_[this->dump_config_at_]->dump_config();
this->dump_config_at_++;
} }
} }

View file

@ -109,8 +109,7 @@ class Application {
*/ */
void set_loop_interval(uint32_t loop_interval) { this->loop_interval_ = loop_interval; } void set_loop_interval(uint32_t loop_interval) { this->loop_interval_ = loop_interval; }
void dump_config(); void schedule_dump_config() { this->dump_config_at_ = 0; }
void schedule_dump_config() { this->dump_config_scheduled_ = true; }
void feed_wdt(); void feed_wdt();
@ -234,7 +233,7 @@ class Application {
std::string compilation_time_; std::string compilation_time_;
uint32_t last_loop_{0}; uint32_t last_loop_{0};
uint32_t loop_interval_{16}; uint32_t loop_interval_{16};
bool dump_config_scheduled_{false}; int dump_config_at_{-1};
uint32_t app_state_{0}; uint32_t app_state_{0};
}; };

View file

@ -61,7 +61,7 @@ PLATFORMIO_ESP32_LUT = {
'1.0.0': 'espressif32@1.4.0', '1.0.0': 'espressif32@1.4.0',
'1.0.1': 'espressif32@1.6.0', '1.0.1': 'espressif32@1.6.0',
'1.0.2': 'espressif32@1.8.0', '1.0.2': 'espressif32@1.8.0',
'RECOMMENDED': 'espressif32@1.6.0', 'RECOMMENDED': 'espressif32@1.8.0',
'LATEST': 'espressif32', 'LATEST': 'espressif32',
'DEV': ARDUINO_VERSION_ESP32_DEV, 'DEV': ARDUINO_VERSION_ESP32_DEV,
} }

View file

@ -127,15 +127,20 @@ def resolve_ip_address(host):
from esphome.core import EsphomeError from esphome.core import EsphomeError
import socket import socket
try: errs = []
ip = socket.gethostbyname(host)
except socket.error as err:
if host.endswith('.local'):
ip = _resolve_with_zeroconf(host)
else:
raise EsphomeError("Error resolving IP address: {}".format(err))
return ip if host.endswith('.local'):
try:
return _resolve_with_zeroconf(host)
except EsphomeError as err:
errs.append(str(err))
try:
return socket.gethostbyname(host)
except socket.error as err:
errs.append(str(err))
raise EsphomeError("Error resolving IP address: {}"
"".format(', '.join(errs)))
def get_bool_env(var, default=False): def get_bool_env(var, default=False):

View file

@ -56,7 +56,7 @@ def main():
print("Running flake8...") print("Running flake8...")
log = get_output(*cmd) log = get_output(*cmd)
for line in log.splitlines(): for line in log.splitlines():
line = line.split(':') line = line.split(':', 4)
if len(line) < 4: if len(line) < 4:
continue continue
file_ = line[0] file_ = line[0]
@ -69,12 +69,12 @@ def main():
print("Running pylint...") print("Running pylint...")
log = get_output(*cmd) log = get_output(*cmd)
for line in log.splitlines(): for line in log.splitlines():
line = line.split(':') line = line.split(':', 3)
if len(line) < 3: if len(line) < 3:
continue continue
file_ = line[0] file_ = line[0]
linno = line[1] linno = line[1]
msg = (u':'.join(line[3:])).strip() msg = (u':'.join(line[2:])).strip()
print_error(file_, linno, msg) print_error(file_, linno, msg)
errors += 1 errors += 1