This commit is contained in:
Wesley Moore 2024-01-21 21:36:19 +10:00
parent 92a91fedab
commit 89f9e4565a
No known key found for this signature in database

View file

@ -1,8 +1,8 @@
use std::io; use std::io;
use esphome_proto::api::HelloRequest; use esphome_proto::api::HelloRequest;
use esphome_proto::protobuf::{CodedOutputStream, MessageFull}; use esphome_proto::protobuf::{CodedInputStream, CodedOutputStream, MessageFull};
use smol::io::{AsyncWrite, AsyncWriteExt}; use smol::io::{AsyncAsSync, AsyncRead, AsyncWrite, AsyncWriteExt};
use smol::net::{AsyncToSocketAddrs, TcpStream}; use smol::net::{AsyncToSocketAddrs, TcpStream};
struct Client { struct Client {
@ -33,17 +33,22 @@ impl Connection {
api_version_minor: 0, api_version_minor: 0,
special_fields: Default::default(), special_fields: Default::default(),
}; };
Self::send_message(hello, &mut stream).await?;
// Read response
// Login + read response
Ok(Connection { stream }) Ok(Connection { stream })
} }
async fn send_message<M: MessageFull, W: AsyncWrite>( async fn send_message<M, W>(message: M, stream: &mut W) -> Result<(), io::Error>
message: M, where
stream: &mut W, M: MessageFull,
) -> Result<(), io::Error> { W: AsyncWrite + Unpin,
{
let mut buf = Vec::new(); let mut buf = Vec::new();
let mut out = CodedOutputStream::vec(&mut buf); 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_option = esphome_proto::api_options::exts::id;
let id = M::descriptor() let id = M::descriptor()
.proto() .proto()
@ -62,4 +67,47 @@ impl Connection {
drop(out); drop(out);
stream.write_all(&buf).await stream.write_all(&buf).await
} }
/// Receive a specific message type
async fn receive_message<M, R>(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
}
} }