one workspace for everything
This commit is contained in:
parent
0b28b24900
commit
01d1f1dad0
25 changed files with 461 additions and 1134 deletions
107
servicepoint2/src/bit_vec.rs
Normal file
107
servicepoint2/src/bit_vec.rs
Normal file
|
@ -0,0 +1,107 @@
|
|||
/// A vector of bits
|
||||
#[derive(Clone)]
|
||||
pub struct BitVec {
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
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 {
|
||||
data: vec![0; size / 8],
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
|
||||
let byte = self.data[byte_index];
|
||||
let old_value = byte & bit_mask != 0;
|
||||
|
||||
self.data[byte_index] = if value {
|
||||
byte | bit_mask
|
||||
} else {
|
||||
byte & (u8::MAX ^ bit_mask)
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.data.len() * 8
|
||||
}
|
||||
|
||||
fn get_indexes(&self, index: usize) -> (usize, u8) {
|
||||
let byte_index = index / 8;
|
||||
let bit_in_byte_index = 7 - index % 8;
|
||||
let bit_mask: u8 = 1 << bit_in_byte_index;
|
||||
return (byte_index, bit_mask);
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Vec<u8>> for BitVec {
|
||||
fn into(self) -> Vec<u8> {
|
||||
self.data
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
.field("len", &self.len())
|
||||
.field("data", &self.data)
|
||||
.finish()
|
||||
}
|
||||
}
|
59
servicepoint2/src/byte_grid.rs
Normal file
59
servicepoint2/src/byte_grid.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
/// A grid of bytes
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ByteGrid {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
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],
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
data: Vec::from(data),
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Vec<u8>> for ByteGrid {
|
||||
fn into(self) -> Vec<u8> {
|
||||
self.data
|
||||
}
|
||||
}
|
317
servicepoint2/src/command.rs
Normal file
317
servicepoint2/src/command.rs
Normal file
|
@ -0,0 +1,317 @@
|
|||
use crate::compression::{into_compressed, into_decompressed};
|
||||
use crate::{
|
||||
BitVec, ByteGrid, CommandCode, CompressionCode, Header, Packet, PixelGrid,
|
||||
TILE_SIZE,
|
||||
};
|
||||
|
||||
/// 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);
|
||||
|
||||
impl Origin {
|
||||
pub fn top_left() -> Self {
|
||||
Self(0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Size defines the width and height of a window
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Size(pub u16, pub u16);
|
||||
|
||||
type Offset = u16;
|
||||
|
||||
type Brightness = u8;
|
||||
|
||||
/// A command to send to the display.
|
||||
#[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),
|
||||
}
|
||||
|
||||
impl Into<Packet> for Command {
|
||||
fn into(self) -> Packet {
|
||||
match self {
|
||||
Command::Clear => command_code_only(CommandCode::Clear),
|
||||
Command::FadeOut => command_code_only(CommandCode::FadeOut),
|
||||
Command::HardReset => command_code_only(CommandCode::HardReset),
|
||||
#[allow(deprecated)]
|
||||
Command::BitmapLegacy => {
|
||||
command_code_only(CommandCode::BitmapLegacy)
|
||||
}
|
||||
Command::CharBrightness(origin, grid) => origin_size_payload(
|
||||
CommandCode::CharBrightness,
|
||||
origin,
|
||||
Size(grid.width as u16, grid.height as u16),
|
||||
grid.into(),
|
||||
),
|
||||
Command::Brightness(brightness) => Packet(
|
||||
Header(
|
||||
CommandCode::Brightness.into(),
|
||||
0x00000,
|
||||
0x0000,
|
||||
0x0000,
|
||||
0x0000,
|
||||
),
|
||||
vec![brightness],
|
||||
),
|
||||
Command::BitmapLinearWin(Origin(pixel_x, pixel_y), pixels) => {
|
||||
debug_assert_eq!(pixel_x % 8, 0);
|
||||
debug_assert_eq!(pixels.width % 8, 0);
|
||||
Packet(
|
||||
Header(
|
||||
CommandCode::BitmapLinearWin.into(),
|
||||
pixel_x / TILE_SIZE,
|
||||
pixel_y,
|
||||
pixels.width as u16 / TILE_SIZE,
|
||||
pixels.height as u16,
|
||||
),
|
||||
pixels.into(),
|
||||
)
|
||||
}
|
||||
Command::BitmapLinear(offset, bits, compression) => {
|
||||
bitmap_linear_into_packet(
|
||||
CommandCode::BitmapLinear,
|
||||
offset,
|
||||
compression,
|
||||
bits.into(),
|
||||
)
|
||||
}
|
||||
Command::BitmapLinearAnd(offset, bits, compression) => {
|
||||
bitmap_linear_into_packet(
|
||||
CommandCode::BitmapLinearAnd,
|
||||
offset,
|
||||
compression,
|
||||
bits.into(),
|
||||
)
|
||||
}
|
||||
Command::BitmapLinearOr(offset, bits, compression) => {
|
||||
bitmap_linear_into_packet(
|
||||
CommandCode::BitmapLinearOr,
|
||||
offset,
|
||||
compression,
|
||||
bits.into(),
|
||||
)
|
||||
}
|
||||
Command::BitmapLinearXor(offset, bits, compression) => {
|
||||
bitmap_linear_into_packet(
|
||||
CommandCode::BitmapLinearXor,
|
||||
offset,
|
||||
compression,
|
||||
bits.into(),
|
||||
)
|
||||
}
|
||||
Command::Cp437Data(origin, grid) => origin_size_payload(
|
||||
CommandCode::Cp437Data,
|
||||
origin,
|
||||
Size(grid.width as u16, grid.height as u16),
|
||||
grid.into(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl TryFrom<Packet> for Command {
|
||||
type Error = TryFromPacketError;
|
||||
|
||||
fn try_from(value: Packet) -> Result<Self, Self::Error> {
|
||||
let Packet(Header(command_u16, a, b, c, d), _) = value;
|
||||
let command_code = match CommandCode::try_from(command_u16) {
|
||||
Err(_) => {
|
||||
return Err(TryFromPacketError::InvalidCommand(command_u16));
|
||||
}
|
||||
Ok(value) => value,
|
||||
};
|
||||
|
||||
match command_code {
|
||||
CommandCode::Clear => match check_command_only(value) {
|
||||
Some(err) => Err(err),
|
||||
None => Ok(Command::Clear),
|
||||
},
|
||||
CommandCode::Brightness => {
|
||||
let Packet(header, payload) = value;
|
||||
if payload.len() != 1 {
|
||||
return Err(TryFromPacketError::UnexpectedPayloadSize(
|
||||
1,
|
||||
payload.len(),
|
||||
));
|
||||
}
|
||||
|
||||
match check_empty_header(header) {
|
||||
Some(err) => Err(err),
|
||||
None => Ok(Command::Brightness(payload[0])),
|
||||
}
|
||||
}
|
||||
CommandCode::HardReset => match check_command_only(value) {
|
||||
Some(err) => Err(err),
|
||||
None => Ok(Command::HardReset),
|
||||
},
|
||||
CommandCode::FadeOut => match check_command_only(value) {
|
||||
Some(err) => Err(err),
|
||||
None => Ok(Command::FadeOut),
|
||||
},
|
||||
CommandCode::Cp437Data => {
|
||||
let Packet(_, payload) = value;
|
||||
Ok(Command::Cp437Data(
|
||||
Origin(a, b),
|
||||
ByteGrid::load(c as usize, d as usize, &payload),
|
||||
))
|
||||
}
|
||||
CommandCode::CharBrightness => {
|
||||
let Packet(_, payload) = value;
|
||||
Ok(Command::CharBrightness(
|
||||
Origin(a, b),
|
||||
ByteGrid::load(c as usize, d as usize, &payload),
|
||||
))
|
||||
}
|
||||
#[allow(deprecated)]
|
||||
CommandCode::BitmapLegacy => Ok(Command::BitmapLegacy),
|
||||
CommandCode::BitmapLinearWin => {
|
||||
let Packet(_, payload) = value;
|
||||
Ok(Command::BitmapLinearWin(
|
||||
Origin(a * TILE_SIZE, b),
|
||||
PixelGrid::load(
|
||||
c as usize * TILE_SIZE as usize,
|
||||
d as usize,
|
||||
&payload,
|
||||
),
|
||||
))
|
||||
}
|
||||
CommandCode::BitmapLinear => {
|
||||
let (vec, compression) = packet_into_linear_bitmap(value)?;
|
||||
Ok(Command::BitmapLinear(a, vec, compression))
|
||||
}
|
||||
CommandCode::BitmapLinearAnd => {
|
||||
let (vec, compression) = packet_into_linear_bitmap(value)?;
|
||||
Ok(Command::BitmapLinearAnd(a, vec, compression))
|
||||
}
|
||||
CommandCode::BitmapLinearOr => {
|
||||
let (vec, compression) = packet_into_linear_bitmap(value)?;
|
||||
Ok(Command::BitmapLinearOr(a, vec, compression))
|
||||
}
|
||||
CommandCode::BitmapLinearXor => {
|
||||
let (vec, compression) = packet_into_linear_bitmap(value)?;
|
||||
Ok(Command::BitmapLinearXor(a, vec, compression))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bitmap_linear_into_packet(
|
||||
command: CommandCode,
|
||||
offset: Offset,
|
||||
compression: CompressionCode,
|
||||
payload: Vec<u8>,
|
||||
) -> Packet {
|
||||
let payload = into_compressed(compression, payload);
|
||||
Packet(
|
||||
Header(
|
||||
command.into(),
|
||||
offset,
|
||||
payload.len() as u16,
|
||||
compression.into(),
|
||||
0,
|
||||
),
|
||||
payload,
|
||||
)
|
||||
}
|
||||
|
||||
fn origin_size_payload(
|
||||
command: CommandCode,
|
||||
origin: Origin,
|
||||
size: Size,
|
||||
payload: Vec<u8>,
|
||||
) -> Packet {
|
||||
let Origin(x, y) = origin;
|
||||
let Size(w, h) = size;
|
||||
Packet(Header(command.into(), x, y, w, h), payload.into())
|
||||
}
|
||||
|
||||
fn command_code_only(code: CommandCode) -> Packet {
|
||||
Packet(Header(code.into(), 0x0000, 0x0000, 0x0000, 0x0000), vec![])
|
||||
}
|
||||
|
||||
fn check_empty_header(header: Header) -> Option<TryFromPacketError> {
|
||||
let Header(_, a, b, c, d) = header;
|
||||
if a != 0 || b != 0 || c != 0 || d != 0 {
|
||||
Some(TryFromPacketError::ExtraneousHeaderValues)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn check_command_only(packet: Packet) -> Option<TryFromPacketError> {
|
||||
let Packet(Header(_, a, b, c, d), payload) = packet;
|
||||
if payload.len() != 0 {
|
||||
Some(TryFromPacketError::UnexpectedPayloadSize(0, payload.len()))
|
||||
} else if a != 0 || b != 0 || c != 0 || d != 0 {
|
||||
Some(TryFromPacketError::ExtraneousHeaderValues)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn packet_into_linear_bitmap(
|
||||
packet: Packet,
|
||||
) -> Result<(BitVec, CompressionCode), TryFromPacketError> {
|
||||
let Packet(Header(_, _, length, sub, reserved), payload) = packet;
|
||||
if reserved != 0 {
|
||||
return Err(TryFromPacketError::ExtraneousHeaderValues);
|
||||
}
|
||||
if payload.len() != length as usize {
|
||||
return Err(TryFromPacketError::UnexpectedPayloadSize(
|
||||
length as usize,
|
||||
payload.len(),
|
||||
));
|
||||
}
|
||||
let sub = match CompressionCode::try_from(sub) {
|
||||
Err(_) => return Err(TryFromPacketError::InvalidCompressionCode(sub)),
|
||||
Ok(value) => value,
|
||||
};
|
||||
let payload = match into_decompressed(sub, payload) {
|
||||
None => return Err(TryFromPacketError::DecompressionFailed),
|
||||
Some(value) => value,
|
||||
};
|
||||
Ok((BitVec::from(&*payload), sub))
|
||||
}
|
49
servicepoint2/src/command_code.rs
Normal file
49
servicepoint2/src/command_code.rs
Normal file
|
@ -0,0 +1,49 @@
|
|||
use CommandCode::*;
|
||||
|
||||
/// The codes used for the commands. See the documentation on the corresponding commands.
|
||||
#[repr(u16)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum CommandCode {
|
||||
Clear = 0x0002,
|
||||
Cp437Data = 0x0003,
|
||||
CharBrightness = 0x0005,
|
||||
Brightness = 0x0007,
|
||||
HardReset = 0x000b,
|
||||
FadeOut = 0x000d,
|
||||
#[deprecated]
|
||||
BitmapLegacy = 0x0010,
|
||||
BitmapLinear = 0x0012,
|
||||
BitmapLinearWin = 0x0013,
|
||||
BitmapLinearAnd = 0x0014,
|
||||
BitmapLinearOr = 0x0015,
|
||||
BitmapLinearXor = 0x0016,
|
||||
}
|
||||
|
||||
impl Into<u16> for CommandCode {
|
||||
fn into(self) -> u16 {
|
||||
self as u16
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u16> for CommandCode {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u16) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
value if value == Clear as u16 => Ok(Clear),
|
||||
value if value == Cp437Data as u16 => Ok(Cp437Data),
|
||||
value if value == CharBrightness as u16 => Ok(CharBrightness),
|
||||
value if value == Brightness as u16 => Ok(Brightness),
|
||||
value if value == HardReset as u16 => Ok(HardReset),
|
||||
value if value == FadeOut as u16 => Ok(FadeOut),
|
||||
#[allow(deprecated)]
|
||||
value if value == BitmapLegacy as u16 => Ok(BitmapLegacy),
|
||||
value if value == BitmapLinear as u16 => Ok(BitmapLinear),
|
||||
value if value == BitmapLinearWin as u16 => Ok(BitmapLinearWin),
|
||||
value if value == BitmapLinearAnd as u16 => Ok(BitmapLinearAnd),
|
||||
value if value == BitmapLinearOr as u16 => Ok(BitmapLinearOr),
|
||||
value if value == BitmapLinearXor as u16 => Ok(BitmapLinearXor),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
111
servicepoint2/src/compression.rs
Normal file
111
servicepoint2/src/compression.rs
Normal file
|
@ -0,0 +1,111 @@
|
|||
#[cfg(feature = "compression-bz")]
|
||||
use bzip2::read::{BzDecoder, BzEncoder};
|
||||
#[cfg(feature = "compression-gz")]
|
||||
use flate2::read::{GzDecoder, GzEncoder};
|
||||
#[cfg(feature = "compression-lz")]
|
||||
use lz4::{Decoder as Lz4Decoder, EncoderBuilder as Lz4EncoderBuilder};
|
||||
#[cfg(feature = "compression")]
|
||||
use std::io::{Read, Write};
|
||||
#[cfg(feature = "compression-zs")]
|
||||
use zstd::{Decoder as ZstdDecoder, Encoder as ZstdEncoder};
|
||||
|
||||
use crate::{CompressionCode, Payload};
|
||||
|
||||
pub(crate) fn into_decompressed(
|
||||
kind: CompressionCode,
|
||||
payload: Payload,
|
||||
) -> Option<Payload> {
|
||||
match kind {
|
||||
CompressionCode::Uncompressed => Some(payload),
|
||||
#[cfg(feature = "compression-gz")]
|
||||
CompressionCode::Gz => {
|
||||
let mut decoder = GzDecoder::new(&*payload);
|
||||
let mut decompressed = vec![];
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Err(_) => None,
|
||||
Ok(_) => Some(decompressed),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "compression-bz")]
|
||||
CompressionCode::Bz => {
|
||||
let mut decoder = BzDecoder::new(&*payload);
|
||||
let mut decompressed = vec![];
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Err(_) => None,
|
||||
Ok(_) => Some(decompressed),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "compression-lz")]
|
||||
CompressionCode::Lz => {
|
||||
let mut decoder = match Lz4Decoder::new(&*payload) {
|
||||
Err(_) => return None,
|
||||
Ok(value) => value,
|
||||
};
|
||||
let mut decompressed = vec![];
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Err(_) => None,
|
||||
Ok(_) => Some(decompressed),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "compression-zs")]
|
||||
CompressionCode::Zs => {
|
||||
let mut decoder = match ZstdDecoder::new(&*payload) {
|
||||
Err(_) => return None,
|
||||
Ok(value) => value,
|
||||
};
|
||||
let mut decompressed = vec![];
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Err(_) => None,
|
||||
Ok(_) => Some(decompressed),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn into_compressed(
|
||||
kind: CompressionCode,
|
||||
payload: Payload,
|
||||
) -> Payload {
|
||||
match kind {
|
||||
CompressionCode::Uncompressed => payload,
|
||||
#[cfg(feature = "compression-gz")]
|
||||
CompressionCode::Gz => {
|
||||
let mut encoder =
|
||||
GzEncoder::new(&*payload, flate2::Compression::fast());
|
||||
let mut compressed = vec![];
|
||||
match encoder.read_to_end(&mut compressed) {
|
||||
Err(err) => panic!("could not compress payload: {}", err),
|
||||
Ok(_) => compressed,
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "compression-bz")]
|
||||
CompressionCode::Bz => {
|
||||
let mut encoder =
|
||||
BzEncoder::new(&*payload, bzip2::Compression::fast());
|
||||
let mut compressed = vec![];
|
||||
match encoder.read_to_end(&mut compressed) {
|
||||
Err(err) => panic!("could not compress payload: {}", err),
|
||||
Ok(_) => compressed,
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "compression-lz")]
|
||||
CompressionCode::Lz => {
|
||||
let mut encoder = Lz4EncoderBuilder::new()
|
||||
.build(vec![])
|
||||
.expect("could not create encoder");
|
||||
encoder.write(&*payload).expect("could not write payload");
|
||||
let (payload, _) = encoder.finish();
|
||||
payload
|
||||
}
|
||||
#[cfg(feature = "compression-zs")]
|
||||
CompressionCode::Zs => {
|
||||
let mut encoder =
|
||||
ZstdEncoder::new(vec![], zstd::DEFAULT_COMPRESSION_LEVEL)
|
||||
.expect("could not create encoder");
|
||||
encoder
|
||||
.write(&*payload)
|
||||
.expect("could not compress payload");
|
||||
encoder.finish().expect("could not finish encoding")
|
||||
}
|
||||
}
|
||||
}
|
41
servicepoint2/src/compression_code.rs
Normal file
41
servicepoint2/src/compression_code.rs
Normal file
|
@ -0,0 +1,41 @@
|
|||
use CompressionCode::*;
|
||||
|
||||
/// Specifies the kind of compression to use. Availability depends on features.
|
||||
#[repr(u16)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum CompressionCode {
|
||||
Uncompressed = 0x0,
|
||||
#[cfg(feature = "compression-gz")]
|
||||
Gz = 0x677a,
|
||||
#[cfg(feature = "compression-bz")]
|
||||
Bz = 0x627a,
|
||||
#[cfg(feature = "compression-lz")]
|
||||
Lz = 0x6c7a,
|
||||
#[cfg(feature = "compression-zs")]
|
||||
Zs = 0x7a73,
|
||||
}
|
||||
|
||||
impl Into<u16> for CompressionCode {
|
||||
fn into(self) -> u16 {
|
||||
self as u16
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u16> for CompressionCode {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u16) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
value if value == Uncompressed as u16 => Ok(Uncompressed),
|
||||
#[cfg(feature = "compression-gz")]
|
||||
value if value == Gz as u16 => Ok(Gz),
|
||||
#[cfg(feature = "compression-bz")]
|
||||
value if value == Bz as u16 => Ok(Bz),
|
||||
#[cfg(feature = "compression-lz")]
|
||||
value if value == Lz as u16 => Ok(Lz),
|
||||
#[cfg(feature = "compression-zs")]
|
||||
value if value == Zs as u16 => Ok(Zs),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
66
servicepoint2/src/connection.rs
Normal file
66
servicepoint2/src/connection.rs
Normal file
|
@ -0,0 +1,66 @@
|
|||
use std::fmt::Debug;
|
||||
use std::net::{ToSocketAddrs, UdpSocket};
|
||||
|
||||
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 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<Self> {
|
||||
info!("connecting to {addr:?}");
|
||||
let socket = UdpSocket::bind("0.0.0.0:0")?;
|
||||
socket.connect(addr)?;
|
||||
Ok(Self { socket })
|
||||
}
|
||||
|
||||
/// 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<Packet> + Debug,
|
||||
) -> Result<(), std::io::Error> {
|
||||
debug!("sending {packet:?}");
|
||||
let packet: Packet = packet.into();
|
||||
let data: Vec<u8> = packet.into();
|
||||
self.socket.send(&*data)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
31
servicepoint2/src/lib.rs
Normal file
31
servicepoint2/src/lib.rs
Normal file
|
@ -0,0 +1,31 @@
|
|||
pub use crate::bit_vec::BitVec;
|
||||
pub use crate::byte_grid::ByteGrid;
|
||||
pub use crate::command::{Command, Origin, Size};
|
||||
pub use crate::command_code::CommandCode;
|
||||
pub use crate::compression_code::CompressionCode;
|
||||
pub use crate::connection::Connection;
|
||||
pub use crate::packet::{Header, Packet, Payload};
|
||||
pub use crate::pixel_grid::PixelGrid;
|
||||
|
||||
mod bit_vec;
|
||||
mod byte_grid;
|
||||
mod command;
|
||||
mod command_code;
|
||||
mod compression;
|
||||
mod compression_code;
|
||||
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;
|
47
servicepoint2/src/packet.rs
Normal file
47
servicepoint2/src/packet.rs
Normal file
|
@ -0,0 +1,47 @@
|
|||
/// 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<u8>;
|
||||
|
||||
/// The raw packet. Should probably not be used directly.
|
||||
#[derive(Debug)]
|
||||
pub struct Packet(pub Header, pub Payload);
|
||||
|
||||
impl Into<Payload> for Packet {
|
||||
fn into(self) -> Vec<u8> {
|
||||
let Packet(Header(mode, a, b, c, d), payload) = self;
|
||||
|
||||
let mut packet = vec![0u8; 10 + payload.len()];
|
||||
packet[0..=1].copy_from_slice(&u16::to_be_bytes(mode));
|
||||
packet[2..=3].copy_from_slice(&u16::to_be_bytes(a));
|
||||
packet[4..=5].copy_from_slice(&u16::to_be_bytes(b));
|
||||
packet[6..=7].copy_from_slice(&u16::to_be_bytes(c));
|
||||
packet[8..=9].copy_from_slice(&u16::to_be_bytes(d));
|
||||
|
||||
packet[10..].copy_from_slice(&*payload);
|
||||
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
|
||||
fn u16_from_be_slice(slice: &[u8]) -> u16 {
|
||||
let mut bytes = [0u8; 2];
|
||||
bytes[0] = slice[0];
|
||||
bytes[1] = slice[1];
|
||||
u16::from_be_bytes(bytes)
|
||||
}
|
||||
|
||||
impl From<Payload> for Packet {
|
||||
fn from(value: Vec<u8>) -> Self {
|
||||
let mode = u16_from_be_slice(&value[0..=1]);
|
||||
let a = u16_from_be_slice(&value[2..=3]);
|
||||
let b = u16_from_be_slice(&value[4..=5]);
|
||||
let c = u16_from_be_slice(&value[6..=7]);
|
||||
let d = u16_from_be_slice(&value[8..=9]);
|
||||
let payload = value[10..].to_vec();
|
||||
|
||||
Packet(Header(mode, a, b, c, d), payload)
|
||||
}
|
||||
}
|
85
servicepoint2/src/pixel_grid.rs
Normal file
85
servicepoint2/src/pixel_grid.rs
Normal file
|
@ -0,0 +1,85 @@
|
|||
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);
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
bit_vec: BitVec::new(width * height),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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!(data.len(), height * width / 8);
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<Vec<u8>> for PixelGrid {
|
||||
fn into(self) -> Vec<u8> {
|
||||
self.bit_vec.into()
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue