diff --git a/homekit-controller/src/homekit_http.rs b/homekit-controller/src/homekit_http.rs index 80d8f7b..ba8363d 100644 --- a/homekit-controller/src/homekit_http.rs +++ b/homekit-controller/src/homekit_http.rs @@ -277,6 +277,12 @@ impl AccessorySocket { Ok(packet) } + async fn reconnect(&mut self) -> Result { + self.socket.flush().await?; + self.socket.shutdown().await?; + TcpStream::connect(format!("{}:{}", self.ip, self.port)).await + } + async fn get_next(&mut self) -> Result, HomekitError> { // max packet size + authtag size + associated data size let mut buf = [0; 1024 + 16 + 2]; @@ -286,19 +292,26 @@ impl AccessorySocket { while read_num == 0 { if tries > 20 { - log::error!("unsuccessfully tried to reconnect"); + log::error!("reconnect unsuccessful"); return Err(ConnectionError::Http.into()); } tries += 1; log::info!("read 0 bytes - about to reconnect"); std::thread::sleep(std::time::Duration::from_millis(200)); - self.socket.flush().await?; - log::warn!("reconnecting..."); - self.socket = TcpStream::connect(format!("{}:{}", self.ip, self.port)).await?; + match tokio::time::timeout(Duration::from_secs(5), self.reconnect()).await { + Ok(Ok(socket)) => self.socket = socket, + _ => continue, + } - read_num = self.socket.read(&mut buf).await?; + read_num = + match tokio::time::timeout(Duration::from_secs(5), self.socket.read(&mut buf)).await + { + Ok(Ok(val)) => val, + _ => continue, + } } + if let Some(encryption) = self.socket_encryption.as_mut() { let associated_data: [u8; 2] = buf[..2].try_into()?; let length = u16::from_le_bytes(associated_data);