servicepoint-binding-csharp/src/connection.rs

27 lines
658 B
Rust
Raw Normal View History

2024-05-09 23:30:18 +02:00
use std::net::{ToSocketAddrs, UdpSocket};
2024-05-10 00:53:12 +02:00
use crate::{Packet};
2024-05-09 23:30:18 +02:00
pub struct Connection {
socket: UdpSocket,
}
2024-05-10 00:53:12 +02:00
pub trait ToPacket {
fn to_packet(self) -> Packet;
}
2024-05-09 23:30:18 +02:00
impl Connection {
/// Open a new UDP socket and create a display instance
pub fn open(addr: impl ToSocketAddrs) -> std::io::Result<Self> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.connect(addr)?;
Ok(Self { socket })
}
/// Send a command to the display
2024-05-10 00:53:12 +02:00
pub fn send(&self, packet: impl ToPacket) -> std::io::Result<()> {
let packet = packet.to_packet();
self.socket.send(&*packet.to_bytes())?;
2024-05-09 23:30:18 +02:00
Ok(())
}
}