From 89f9e4565abc46c99064e6283e71a3ff381d8383 Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Sun, 21 Jan 2024 21:36:19 +1000 Subject: [PATCH] WIP --- src/lib.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f846950..f87f5e2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,8 @@ use std::io; use esphome_proto::api::HelloRequest; -use esphome_proto::protobuf::{CodedOutputStream, MessageFull}; -use smol::io::{AsyncWrite, AsyncWriteExt}; +use esphome_proto::protobuf::{CodedInputStream, CodedOutputStream, MessageFull}; +use smol::io::{AsyncAsSync, AsyncRead, AsyncWrite, AsyncWriteExt}; use smol::net::{AsyncToSocketAddrs, TcpStream}; struct Client { @@ -33,17 +33,22 @@ impl Connection { api_version_minor: 0, special_fields: Default::default(), }; + Self::send_message(hello, &mut stream).await?; + + // Read response + + // Login + read response Ok(Connection { stream }) } - async fn send_message( - message: M, - stream: &mut W, - ) -> Result<(), io::Error> { + async fn send_message(message: M, stream: &mut W) -> Result<(), io::Error> + where + M: MessageFull, + W: AsyncWrite + Unpin, + { let mut buf = Vec::new(); let mut out = CodedOutputStream::vec(&mut buf); - // let message_bytes = message.write_to_bytes()?; let id_option = esphome_proto::api_options::exts::id; let id = M::descriptor() .proto() @@ -62,4 +67,47 @@ impl Connection { drop(out); stream.write_all(&buf).await } + + /// Receive a specific message type + async fn receive_message(stream: &mut R) -> Result<(), io::Error> + where + M: MessageFull, + R: AsyncRead + { + let mut buf = Vec::new(); + + let reader = AsyncAsSync::new(context, stream); + let mut ins= CodedInputStream::new(reader); + + let id_option = esphome_proto::api_options::exts::id; + let id = M::descriptor() + .proto() + .options + .as_ref() + .and_then(|options| id_option.get(options)) + .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "message is missing id"))?; + // let len = u32::try_from(message.compute_size()) + // .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; + + let zero = ins.read_raw_byte()?; + // TODO: Handle WouldBlock + if zero != 0 { + return Err(io::Error::new(io::ErrorKind::Other, format!("expected zero got: {zero}"))); + } + // TODO: Handle WouldBlock + let len = ins.read_raw_varint32()?; + // TODO: Handle WouldBlock + let message_id = ins.read_raw_varint32()?; + if message_id != id { + return Err(io::Error::new(io::ErrorKind::Other, format!("expected message id {id} got {message_id}"))); + } + + let msg = ins.read_message()?; + Ok(msg) + + // message.write_to_with_cached_sizes(&mut out)?; + // out.flush()?; + // drop(out); + // stream.write_all(&buf).await + } }