def connect(self): if not self._running_event.wait(0.1): raise APIConnectionError("You need to call start() first!") if self._connected: self.disconnect(on_disconnect=False) try: ip = resolve_ip_address(self._address) except EsphomeError as err: _LOGGER.warning( "Error resolving IP address of %s. Is it connected to WiFi?", self._address, ) _LOGGER.warning( "(If this error persists, please set a static IP address: " "https://esphome.io/components/wifi.html#manual-ips)" ) raise APIConnectionError(err) from err _LOGGER.info("Connecting to %s:%s (%s)", self._address, self._port, ip) self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.settimeout(10.0) self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) try: self._socket.connect((ip, self._port)) except OSError as err: err = APIConnectionError(f"Error connecting to {ip}: {err}") self._fatal_error(err) raise err self._socket.settimeout(0.1) self._socket_open_event.set() hello = pb.HelloRequest() hello.client_info = f"ESPHome v{const.__version__}" try: resp = self._send_message_await_response(hello, pb.HelloResponse) except APIConnectionError as err: self._fatal_error(err) raise err _LOGGER.debug( "Successfully connected to %s ('%s' API=%s.%s)", self._address, resp.server_info, resp.api_version_major, resp.api_version_minor, ) self._connected = True self._refresh_ping() if self.on_connect is not None: self.on_connect()
def run_ota_impl_(remote_host, remote_port, password, filename): if is_ip_address(remote_host): _LOGGER.info("Connecting to %s", remote_host) ip = remote_host else: _LOGGER.info("Resolving IP address of %s", remote_host) try: ip = resolve_ip_address(remote_host) except EsphomeError as err: _LOGGER.error( "Error resolving IP address of %s. Is it connected to WiFi?", remote_host, ) _LOGGER.error( "(If this error persists, please set a static IP address: " "https://esphome.io/components/wifi.html#manual-ips)" ) raise OTAError(err) from err _LOGGER.info(" -> %s", ip) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10.0) try: sock.connect((ip, remote_port)) except OSError as err: sock.close() _LOGGER.error("Connecting to %s:%s failed: %s", remote_host, remote_port, err) return 1 file_handle = open(filename, "rb") try: perform_ota(sock, password, file_handle, filename) except OTAError as err: _LOGGER.error(str(err)) return 1 finally: sock.close() file_handle.close() return 0