servicepoint-binding-csharp/src/connection.rs

28 lines
767 B
Rust
Raw Normal View History

use std::fmt::Debug;
2024-05-09 23:30:18 +02:00
use std::net::{ToSocketAddrs, UdpSocket};
use log::{debug, info};
2024-05-10 19:55:18 +02:00
use crate::Packet;
2024-05-09 23:30:18 +02:00
pub struct Connection {
socket: UdpSocket,
}
impl Connection {
/// Open a new UDP socket and create a display instance
pub fn open(addr: impl ToSocketAddrs + Debug) -> std::io::Result<Self> {
info!("connecting to {addr:?}");
2024-05-09 23:30:18 +02:00
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.connect(addr)?;
Ok(Self { socket })
}
/// Send a command to the display
pub fn send(&self, packet: impl Into<Packet> + Debug) -> std::io::Result<()> {
debug!("sending {packet:?}");
2024-05-10 19:55:18 +02:00
let packet = packet.into();
let data: Vec<u8> = packet.into();
self.socket.send(&*data)?;
2024-05-09 23:30:18 +02:00
Ok(())
}
}