2024-05-11 14:41:09 +02:00
|
|
|
use std::fmt::Debug;
|
2024-05-09 23:30:18 +02:00
|
|
|
use std::net::{ToSocketAddrs, UdpSocket};
|
2024-05-11 23:28:08 +02:00
|
|
|
|
2024-05-11 14:41:09 +02:00
|
|
|
use log::{debug, info};
|
2024-05-11 23:28:08 +02:00
|
|
|
|
2024-05-10 19:55:18 +02:00
|
|
|
use crate::Packet;
|
2024-05-09 23:30:18 +02:00
|
|
|
|
2024-05-12 01:30:55 +02:00
|
|
|
/// A connection to the display.
|
2024-05-09 23:30:18 +02:00
|
|
|
pub struct Connection {
|
|
|
|
socket: UdpSocket,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Connection {
|
2024-05-12 01:30:55 +02:00
|
|
|
/// Open a new UDP socket and connect to the provided host.
|
|
|
|
///
|
|
|
|
/// Note that this is UDP, which means that the open call can succeed even if the display is unreachable.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```rust
|
|
|
|
/// let connection = servicepoint2::Connection::open("172.23.42.29:2342")
|
|
|
|
/// .expect("connection failed");
|
|
|
|
/// ```
|
2024-05-11 14:41:09 +02:00
|
|
|
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 })
|
|
|
|
}
|
|
|
|
|
2024-05-12 01:30:55 +02:00
|
|
|
/// Send something packet-like to the display. Usually this is in the form of a Command.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `packet`: the packet-like to send
|
|
|
|
///
|
|
|
|
/// returns: Ok if packet was sent, otherwise socket error
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// let connection = servicepoint2::Connection::open("172.23.42.29:2342")
|
|
|
|
/// .expect("connection failed");
|
|
|
|
///
|
|
|
|
/// // turn off all pixels
|
|
|
|
/// connection.send(servicepoint2::Command::Clear)
|
|
|
|
/// .expect("send failed");
|
|
|
|
///
|
|
|
|
/// // turn on all pixels
|
|
|
|
/// let mut pixels = servicepoint2::PixelGrid::max_sized();
|
|
|
|
/// pixels.fill(true);
|
|
|
|
///
|
|
|
|
/// // send pixels to display
|
|
|
|
/// connection.send(servicepoint2::Command::BitmapLinearWin(servicepoint2::Origin::top_left(), pixels))
|
|
|
|
/// .expect("send failed");
|
|
|
|
/// ```
|
2024-05-11 23:28:08 +02:00
|
|
|
pub fn send(
|
|
|
|
&self,
|
|
|
|
packet: impl Into<Packet> + Debug,
|
|
|
|
) -> Result<(), std::io::Error> {
|
2024-05-11 14:41:09 +02:00
|
|
|
debug!("sending {packet:?}");
|
2024-05-11 21:14:20 +02:00
|
|
|
let packet: Packet = packet.into();
|
2024-05-10 19:55:18 +02:00
|
|
|
let data: Vec<u8> = packet.into();
|
|
|
|
self.socket.send(&*data)?;
|
2024-05-09 23:30:18 +02:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|