From df8c1249c411c9055597de0bfaf38ed088ca09eb Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sun, 12 May 2024 01:30:55 +0200 Subject: [PATCH] renames, add documentation headers --- examples/wiping_clear/src/main.rs | 2 +- src/bit_vec.rs | 46 +++++++++++++++++++++++++++---- src/byte_grid.rs | 16 +++++++++++ src/command.rs | 30 ++++++++++++++++---- src/command_codes.rs | 16 ++++++++--- src/connection.rs | 38 +++++++++++++++++++++++-- src/lib.rs | 6 ++++ src/packet.rs | 3 ++ src/pixel_grid.rs | 39 ++++++++++++++++++++++++-- 9 files changed, 175 insertions(+), 21 deletions(-) diff --git a/examples/wiping_clear/src/main.rs b/examples/wiping_clear/src/main.rs index 069f06d..5837541 100644 --- a/examples/wiping_clear/src/main.rs +++ b/examples/wiping_clear/src/main.rs @@ -34,7 +34,7 @@ fn main() { // this works because the pixel grid has max size let pixel_data: Vec = enabled_pixels.clone().into(); - let bit_vec = BitVec::load(&*pixel_data); + let bit_vec = BitVec::from(&*pixel_data); connection .send(BitmapLinearAnd(0, bit_vec, CompressionCode::Gz)) diff --git a/src/bit_vec.rs b/src/bit_vec.rs index 4637de9..a6fa9ab 100644 --- a/src/bit_vec.rs +++ b/src/bit_vec.rs @@ -5,6 +5,13 @@ pub struct BitVec { } impl BitVec { + /// Create a new bit vector. + /// + /// # Arguments + /// + /// * `size`: size in bits. Must be dividable by 8. + /// + /// returns: bit vector with all bits set to false. pub fn new(size: usize) -> BitVec { assert_eq!(size % 8, 0); Self { @@ -12,12 +19,14 @@ impl BitVec { } } - pub fn load(data: &[u8]) -> BitVec { - Self { - data: Vec::from(data), - } - } - + /// Sets the value of a bit. + /// + /// # Arguments + /// + /// * `index`: the bit index to edit + /// * `value`: the value to set the bit to + /// + /// returns: old value of the bit pub fn set(&mut self, index: usize, value: bool) -> bool { let (byte_index, bit_mask) = self.get_indexes(index); @@ -33,11 +42,30 @@ impl BitVec { return old_value; } + /// Gets the value of a bit. + /// + /// # Arguments + /// + /// * `index`: the bit index to read + /// + /// returns: value of the bit pub fn get(&self, index: usize) -> bool { let (byte_index, bit_mask) = self.get_indexes(index); return self.data[byte_index] & bit_mask != 0; } + /// Sets all bits to the specified value + /// + /// # Arguments + /// + /// * `value`: the value to set all bits to + /// + /// # Examples + /// ``` + /// use servicepoint2::BitVec; + /// let mut vec = BitVec::new(8); + /// vec.fill(true); + /// ``` pub fn fill(&mut self, value: bool) { let byte: u8 = if value { 0xFF } else { 0x00 }; self.data.fill(byte); @@ -61,6 +89,12 @@ impl Into> for BitVec { } } +impl From<&[u8]> for BitVec { + fn from(value: &[u8]) -> Self { + Self { data: Vec::from(value) } + } +} + impl std::fmt::Debug for BitVec { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fmt.debug_struct("BitVec") diff --git a/src/byte_grid.rs b/src/byte_grid.rs index 61301ff..38c118c 100644 --- a/src/byte_grid.rs +++ b/src/byte_grid.rs @@ -1,3 +1,4 @@ +/// A grid of bytes #[derive(Debug, Clone)] pub struct ByteGrid { pub width: usize, @@ -6,6 +7,9 @@ pub struct ByteGrid { } impl ByteGrid { + /// Creates a new byte grid with the specified dimensions. + /// + /// returns: ByteGrid initialized to 0. pub fn new(width: usize, height: usize) -> Self { Self { data: vec![0; width * height], @@ -14,6 +18,13 @@ impl ByteGrid { } } + /// Loads a byte grid with the specified dimensions from the provided data. + /// + /// returns: ByteGrid that contains a copy of the provided data + /// + /// # Panics + /// + /// - when the dimensions and data size do not match exactly. pub fn load(width: usize, height: usize, data: &[u8]) -> Self { assert_eq!(width * height, data.len()); Self { @@ -23,14 +34,19 @@ impl ByteGrid { } } + /// Get the current value at the specified position + /// + /// returns: current byte value pub fn get(&self, x: usize, y: usize) -> u8 { self.data[x + y * self.width] } + /// Sets the byte value at the specified position pub fn set(&mut self, x: usize, y: usize, value: u8) { self.data[x + y * self.width] = value; } + /// Sets all bytes in the grid to the specified value pub fn fill(&mut self, value: u8) { self.data.fill(value) } diff --git a/src/command.rs b/src/command.rs index 6ed8b76..db06116 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,9 +1,8 @@ +use crate::{BitVec, ByteGrid, Header, Packet, PixelGrid, TILE_SIZE}; use crate::command_codes::{CommandCode, CompressionCode}; use crate::compression::{into_compressed, into_decompressed}; -use crate::{BitVec, ByteGrid, Header, Packet, PixelGrid, TILE_SIZE}; -/// An origin marks the top left position of the -/// data sent to the display. +/// An origin marks the top left position of a window sent to the display. #[derive(Debug, Clone, Copy)] pub struct Origin(pub u16, pub u16); @@ -23,18 +22,32 @@ type Brightness = u8; #[derive(Debug)] pub enum Command { + /// Set all pixels to the off state Clear, + /// Kills the udp daemon, usually results in a reboot of the display. HardReset, FadeOut, + /// Set the brightness of tiles CharBrightness(Origin, ByteGrid), + /// Set the brightness of all tiles Brightness(Brightness), #[deprecated] BitmapLegacy, + /// Set pixel data starting at the offset. + /// The contained BitVec is always uncompressed. BitmapLinear(Offset, BitVec, CompressionCode), + /// Set pixel data according to an and-mask starting at the offset. + /// The contained BitVec is always uncompressed. BitmapLinearAnd(Offset, BitVec, CompressionCode), + /// Set pixel data according to an or-mask starting at the offset. + /// The contained BitVec is always uncompressed. BitmapLinearOr(Offset, BitVec, CompressionCode), + /// Set pixel data according to an xor-mask starting at the offset. + /// The contained BitVec is always uncompressed. BitmapLinearXor(Offset, BitVec, CompressionCode), + /// Show text on the screen. Note that the byte data has to be CP437 encoded. Cp437Data(Origin, ByteGrid), + /// Sets a window of pixels to the specified values BitmapLinearWin(Origin, PixelGrid), } @@ -122,10 +135,17 @@ impl Into for Command { #[derive(Debug)] pub enum TryFromPacketError { + /// the contained command code does not correspond to a known command InvalidCommand(u16), + /// the expected payload size was n, but size m was found UnexpectedPayloadSize(usize, usize), + /// Header fields not needed for the command have been used. + /// + /// Note that these commands would usually still work on the actual display. ExtraneousHeaderValues, + /// The contained compression code is not known. This could be of disabled features. InvalidCompressionCode(u16), + /// Decompression of the payload failed. This can be caused by corrupted packets. DecompressionFailed, } @@ -136,7 +156,7 @@ impl TryFrom for Command { let Packet(Header(command_u16, a, b, c, d), _) = value; let command_code = match CommandCode::from_primitive(command_u16) { None => { - return Err(TryFromPacketError::InvalidCommand(command_u16)) + return Err(TryFromPacketError::InvalidCommand(command_u16)); } Some(value) => value, }; @@ -294,5 +314,5 @@ fn packet_into_linear_bitmap( None => return Err(TryFromPacketError::DecompressionFailed), Some(value) => value, }; - Ok((BitVec::load(&payload), sub)) + Ok((BitVec::from(&*payload), sub)) } diff --git a/src/command_codes.rs b/src/command_codes.rs index 7048348..5b371fb 100644 --- a/src/command_codes.rs +++ b/src/command_codes.rs @@ -1,6 +1,7 @@ use num::{FromPrimitive, ToPrimitive}; use num_derive::{FromPrimitive, ToPrimitive}; +/// The codes used for the commands. See the documentation on the corresponding commands. #[repr(u16)] #[derive(Debug, FromPrimitive, ToPrimitive, Copy, Clone)] pub enum CommandCode { @@ -20,15 +21,18 @@ pub enum CommandCode { } impl CommandCode { + /// convert u16 to CommandCode enum pub fn from_primitive(value: u16) -> Option { FromPrimitive::from_u16(value) } + /// convert CommandCode enum to u16 pub fn to_primitive(&self) -> u16 { ToPrimitive::to_u16(self).unwrap() } } +/// Specifies the kind of compression to use. Availability depends on features. #[repr(u16)] #[derive(Debug, FromPrimitive, ToPrimitive, Clone, Copy)] pub enum CompressionCode { @@ -44,11 +48,15 @@ pub enum CompressionCode { } impl CompressionCode { - pub fn from_primitive(value: u16) -> Option { - FromPrimitive::from_u16(value) - } - + /// convert CompressionCode enum to u16 pub fn to_primitive(&self) -> u16 { ToPrimitive::to_u16(self).unwrap() } + + /// Convert u16 to CommandCode enum. + /// + /// returns: None if the provided value is not one of the valid enum values. + pub fn from_primitive(value: u16) -> Option { + FromPrimitive::from_u16(value) + } } diff --git a/src/connection.rs b/src/connection.rs index e3728e4..e296939 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -5,12 +5,21 @@ use log::{debug, info}; use crate::Packet; +/// A connection to the display. pub struct Connection { socket: UdpSocket, } impl Connection { - /// Open a new UDP socket and create a display instance + /// 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"); + /// ``` pub fn open(addr: impl ToSocketAddrs + Debug) -> std::io::Result { info!("connecting to {addr:?}"); let socket = UdpSocket::bind("0.0.0.0:0")?; @@ -18,7 +27,32 @@ impl Connection { Ok(Self { socket }) } - /// Send a command to the display + /// 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"); + /// ``` pub fn send( &self, packet: impl Into + Debug, diff --git a/src/lib.rs b/src/lib.rs index c843249..12b3e9b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,9 +15,15 @@ mod connection; mod packet; mod pixel_grid; +/// size of a single tile in one dimension pub const TILE_SIZE: u16 = 8; +/// tile count in the x-direction pub const TILE_WIDTH: u16 = 56; +/// tile count in the y-direction pub const TILE_HEIGHT: u16 = 20; +/// screen width in pixels pub const PIXEL_WIDTH: u16 = TILE_WIDTH * TILE_SIZE; +/// screen height in pixels pub const PIXEL_HEIGHT: u16 = TILE_HEIGHT * TILE_SIZE; +/// pixel count on whole screen pub const PIXEL_COUNT: usize = PIXEL_WIDTH as usize * PIXEL_HEIGHT as usize; diff --git a/src/packet.rs b/src/packet.rs index 3e88f6f..07039b1 100644 --- a/src/packet.rs +++ b/src/packet.rs @@ -1,8 +1,11 @@ +/// A raw header. Should probably not be used directly. #[derive(Debug)] pub struct Header(pub u16, pub u16, pub u16, pub u16, pub u16); +/// The raw payload. Should probably not be used directly. pub type Payload = Vec; +/// The raw packet. Should probably not be used directly. #[derive(Debug)] pub struct Packet(pub Header, pub Payload); diff --git a/src/pixel_grid.rs b/src/pixel_grid.rs index 8138595..e81a3a2 100644 --- a/src/pixel_grid.rs +++ b/src/pixel_grid.rs @@ -1,16 +1,31 @@ use crate::{BitVec, PIXEL_HEIGHT, PIXEL_WIDTH}; +/// A grid of pixels stored in packed bytes. #[derive(Debug, Clone)] pub struct PixelGrid { + /// the width in pixels pub width: usize, + /// the height in pixels pub height: usize, bit_vec: BitVec, } impl PixelGrid { + + /// Creates a new pixel grid with the specified dimensions. + /// + /// # Arguments + /// + /// * `width`: size in pixels in x-direction + /// * `height`: size in pixels in y-direction + /// + /// returns: PixelGrid initialized to all pixels off + /// + /// # Panics + /// + /// - when the width is not dividable by 8 pub fn new(width: usize, height: usize) -> Self { assert_eq!(width % 8, 0); - assert_eq!(height % 8, 0); Self { width, height, @@ -18,29 +33,47 @@ impl PixelGrid { } } + /// Creates a new pixel grid with the size of the whole screen. pub fn max_sized() -> Self { Self::new(PIXEL_WIDTH as usize, PIXEL_HEIGHT as usize) } + /// Loads a pixel grid with the specified dimensions from the provided data. + /// + /// # Arguments + /// + /// * `width`: size in pixels in x-direction + /// * `height`: size in pixels in y-direction + /// + /// returns: PixelGrid that contains a copy of the provided data + /// + /// # Panics + /// + /// - when the dimensions and data size do not match exactly. + /// - when the width is not dividable by 8 pub fn load(width: usize, height: usize, data: &[u8]) -> Self { assert_eq!(width % 8, 0); - assert_eq!(height % 8, 0); assert_eq!(data.len(), height * width / 8); Self { width, height, - bit_vec: BitVec::load(data), + bit_vec: BitVec::from(data), } } + /// Sets the byte value at the specified position pub fn set(&mut self, x: usize, y: usize, value: bool) -> bool { self.bit_vec.set(x + y * self.width, value) } + /// Get the current value at the specified position + /// + /// returns: current pixel value pub fn get(&self, x: usize, y: usize) -> bool { self.bit_vec.get(x + y * self.width) } + /// Sets all pixels in the grid to the specified value pub fn fill(&mut self, value: bool) { self.bit_vec.fill(value); }