move examples into package (include them in published crate)

This commit is contained in:
Vinzenz Schroeter 2024-05-26 13:55:19 +02:00
parent 5514f60c28
commit c92493fad1
22 changed files with 26 additions and 165 deletions

View file

@ -26,3 +26,8 @@ compression_bzip2 = ["dep:bzip2"]
compression_lzma = ["dep:rust-lzma"]
compression_zstd = ["dep:zstd"]
all_compressions = ["compression_zlib", "compression_bzip2", "compression_lzma", "compression_zstd"]
[dev-dependencies]
# for examples
clap = { version = "4.5", features = ["derive"] }
rand = "0.8"

View file

@ -0,0 +1,43 @@
use clap::Parser;
use servicepoint::{ByteGrid, Command, Connection, Grid, Origin};
#[derive(Parser, Debug)]
struct Cli {
#[arg(short, long, default_value = "localhost:2342")]
destination: String,
#[arg(short, long, num_args = 1.., value_delimiter = '\n')]
text: Vec<String>,
#[arg(short, long, default_value_t = true)]
clear: bool,
}
/// example: `cargo run -- --text "Hallo,
/// CCCB"`
fn main() {
let mut cli = Cli::parse();
if cli.text.is_empty() {
cli.text.push("Hello, CCCB!".to_string());
}
let connection = Connection::open(&cli.destination).unwrap();
if cli.clear {
connection.send(Command::Clear).unwrap();
}
let max_width = cli.text.iter().map(|t| t.len()).max().unwrap();
let mut chars = ByteGrid::new(max_width, cli.text.len());
for y in 0..cli.text.len() {
let row = &cli.text[y];
for (x, char) in row.chars().enumerate() {
let char = char.try_into().expect("invalid input char");
chars.set(x, y, char);
}
}
connection
.send(Command::Cp437Data(Origin(0, 0), chars))
.unwrap();
}

View file

@ -0,0 +1,89 @@
use std::thread;
use clap::Parser;
use rand::{distributions, Rng};
use servicepoint::*;
#[derive(Parser, Debug)]
struct Cli {
#[arg(short, long, default_value = "localhost:2342")]
destination: String,
#[arg(short, long, default_value_t = 0.5f64)]
probability: f64,
}
fn main() {
let cli = Cli::parse();
let connection = Connection::open(&cli.destination).unwrap();
let mut field = make_random_field(cli.probability);
loop {
connection
.send(Command::BitmapLinearWin(
Origin(0, 0),
field.clone(),
CompressionCode::Lzma,
))
.expect("could not send");
thread::sleep(FRAME_PACING);
field = iteration(field);
}
}
fn iteration(field: PixelGrid) -> PixelGrid {
let mut next = field.clone();
for x in 0..field.width() {
for y in 0..field.height() {
let old_state = field.get(x, y);
let neighbors = count_neighbors(&field, x as i32, y as i32);
let new_state = matches!(
(old_state, neighbors),
(true, 2) | (true, 3) | (false, 3)
);
next.set(x, y, new_state);
}
}
next
}
fn count_neighbors(field: &PixelGrid, x: i32, y: i32) -> i32 {
let mut count = 0;
for nx in x - 1..=x + 1 {
for ny in y - 1..=y + 1 {
if nx == x && ny == y {
continue; // the cell itself does not count
}
if nx < 0
|| ny < 0
|| nx >= field.width() as i32
|| ny >= field.height() as i32
{
continue; // pixels outside the grid do not count
}
if !field.get(nx as usize, ny as usize) {
continue; // dead cells do not count
}
count += 1;
}
}
count
}
fn make_random_field(probability: f64) -> PixelGrid {
let mut field = PixelGrid::max_sized();
let mut rng = rand::thread_rng();
let d = distributions::Bernoulli::new(probability).unwrap();
for x in 0..field.width() {
for y in 0..field.height() {
field.set(x, y, rng.sample(d));
}
}
field
}

View file

@ -0,0 +1,32 @@
use std::thread;
use clap::Parser;
use servicepoint::*;
#[derive(Parser, Debug)]
struct Cli {
#[arg(short, long, default_value = "localhost:2342")]
destination: String,
}
fn main() {
let connection = Connection::open(Cli::parse().destination).unwrap();
let mut pixels = PixelGrid::max_sized();
for x_offset in 0..usize::MAX {
pixels.fill(false);
for y in 0..PIXEL_HEIGHT {
pixels.set((y + x_offset) % PIXEL_WIDTH, y, true);
}
connection
.send(Command::BitmapLinearWin(
Origin(0, 0),
pixels.clone(),
CompressionCode::Lzma,
))
.unwrap();
thread::sleep(FRAME_PACING);
}
}

View file

@ -0,0 +1,60 @@
use std::time::Duration;
use clap::Parser;
use rand::Rng;
use servicepoint::Command::{BitmapLinearWin, Brightness, CharBrightness};
use servicepoint::*;
#[derive(Parser, Debug)]
struct Cli {
#[arg(short, long, default_value = "localhost:2342")]
destination: String,
#[arg(short, long, default_value_t = true)]
enable_all: bool,
#[arg(short, long, default_value_t = 100, allow_negative_numbers = false)]
wait_ms: u64,
}
fn main() {
let cli = Cli::parse();
let connection = Connection::open(cli.destination).unwrap();
let wait_duration = Duration::from_millis(cli.wait_ms);
// put all pixels in on state
if cli.enable_all {
let mut filled_grid = PixelGrid::max_sized();
filled_grid.fill(true);
let command =
BitmapLinearWin(Origin(0, 0), filled_grid, CompressionCode::Lzma);
connection.send(command).expect("send failed");
}
// set all pixels to the same random brightness
let mut rng = rand::thread_rng();
connection.send(Brightness(rng.gen())).unwrap();
// continuously update random windows to new random brightness
loop {
let min_size = 1;
let x = rng.gen_range(0..TILE_WIDTH - min_size);
let y = rng.gen_range(0..TILE_HEIGHT - min_size);
let w = rng.gen_range(min_size..=TILE_WIDTH - x);
let h = rng.gen_range(min_size..=TILE_HEIGHT - y);
let origin = Origin(x, y);
let mut luma = ByteGrid::new(w, h);
for y in 0..h {
for x in 0..w {
luma.set(x, y, rng.gen());
}
}
connection.send(CharBrightness(origin, luma)).unwrap();
std::thread::sleep(wait_duration);
}
}

View file

@ -0,0 +1,43 @@
use std::thread;
use std::time::Duration;
use clap::Parser;
use servicepoint::*;
#[derive(Parser, Debug)]
struct Cli {
#[arg(short, long, default_value = "localhost:2342")]
destination: String,
#[arg(short, long = "duration-ms", default_value_t = 5000)]
time: u64,
}
fn main() {
let cli = Cli::parse();
let sleep_duration = Duration::max(
FRAME_PACING,
Duration::from_millis(cli.time / PIXEL_WIDTH as u64),
);
let connection = Connection::open(cli.destination).unwrap();
let mut enabled_pixels = PixelGrid::new(PIXEL_WIDTH, PIXEL_HEIGHT);
enabled_pixels.fill(true);
for x_offset in 0..PIXEL_WIDTH {
for y in 0..PIXEL_HEIGHT {
enabled_pixels.set(x_offset % PIXEL_WIDTH, y, false);
}
// this works because the pixel grid has max size
let pixel_data: Vec<u8> = enabled_pixels.clone().into();
let bit_vec = BitVec::from(&*pixel_data);
connection
.send(Command::BitmapLinearAnd(0, bit_vec, CompressionCode::Lzma))
.unwrap();
thread::sleep(sleep_duration);
}
}

View file

@ -0,0 +1,14 @@
[package]
name = "lang_c"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
test = false
[build-dependencies]
cc = "1.0"
[dependencies]
servicepoint_binding_c = { path = "../.." }

View file

@ -0,0 +1,33 @@
CC := gcc
THIS_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
REPO_ROOT := $(THIS_DIR)/../..
build: out/lang_c
clean:
rm -r out
rm include/servicepoint.h
run: out/lang_c
out/lang_c
PHONY: build clean dependencies run
out/lang_c: dependencies src/main.c
mkdir -p out || true
${CC} src/main.c \
-I include \
-L $(REPO_ROOT)/target/release \
-Wl,-Bstatic -lservicepoint_binding_c \
-Wl,-Bdynamic -llzma \
-o out/lang_c
dependencies: FORCE
mkdir -p include || true
# generate servicepoint header and binary to link against
SERVICEPOINT_HEADER_OUT=$(THIS_DIR)/include cargo build \
--manifest-path=$(REPO_ROOT)/crates/servicepoint_binding_c/Cargo.toml \
--release
FORCE: ;

View file

@ -0,0 +1,16 @@
const SP_INCLUDE: &str = "DEP_SERVICEPOINT_INCLUDE";
fn main() {
println!("cargo:rerun-if-changed=src/main.c");
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed={SP_INCLUDE}");
let sp_include =
std::env::var_os(SP_INCLUDE).unwrap().into_string().unwrap();
// this builds a lib, this is only to check that the example compiles
let mut cc = cc::Build::new();
cc.file("src/main.c");
cc.include(&sp_include);
cc.compile("lang_c");
}

View file

@ -0,0 +1,455 @@
/* Generated with cbindgen:0.26.0 */
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
/**
* pixel count on whole screen
*/
#define sp_PIXEL_COUNT (sp_PIXEL_WIDTH * sp_PIXEL_HEIGHT)
/**
* screen height in pixels
*/
#define sp_PIXEL_HEIGHT (sp_TILE_HEIGHT * sp_TILE_SIZE)
/**
* screen width in pixels
*/
#define sp_PIXEL_WIDTH (sp_TILE_WIDTH * sp_TILE_SIZE)
/**
* tile count in the y-direction
*/
#define sp_TILE_HEIGHT 20
/**
* size of a single tile in one dimension
*/
#define sp_TILE_SIZE 8
/**
* tile count in the x-direction
*/
#define sp_TILE_WIDTH 56
/**
* Specifies the kind of compression to use. Availability depends on features.
*/
enum sp_CompressionCode
#ifdef __cplusplus
: uint16_t
#endif // __cplusplus
{
Uncompressed = 0,
Zlib = 26490,
Bzip2 = 25210,
Lzma = 27770,
Zstd = 31347,
};
#ifndef __cplusplus
typedef uint16_t sp_CompressionCode;
#endif // __cplusplus
/**
* A vector of bits
*/
typedef struct sp_BitVec sp_BitVec;
/**
* A 2D grid of bytes
*/
typedef struct sp_ByteGrid sp_ByteGrid;
/**
* A command to send to the display.
*/
typedef struct sp_Command sp_Command;
/**
* A connection to the display.
*/
typedef struct sp_Connection sp_Connection;
/**
* The raw packet. Should probably not be used directly.
*/
typedef struct sp_Packet sp_Packet;
/**
* A grid of pixels stored in packed bytes.
*/
typedef struct sp_PixelGrid sp_PixelGrid;
/**
* Represents a span of memory (`&mut [u8]` ) as a struct usable by C code.
*
* Usage of this type is inherently unsafe.
*/
typedef struct sp_CByteSlice {
/**
* The start address of the memory
*/
uint8_t *start;
/**
* The amount of memory in bytes
*/
size_t length;
} sp_CByteSlice;
/**
* Type alias for documenting the meaning of the u16 in enum values
*/
typedef size_t sp_Offset;
/**
* Type alias for documenting the meaning of the u16 in enum values
*/
typedef uint8_t sp_Brightness;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Clones a `BitVec`.
* The returned instance has to be freed with `bit_vec_dealloc`.
*/
struct sp_BitVec *sp_bit_vec_clone(const struct sp_BitVec *this_);
/**
* Deallocates a `BitVec`.
*
* Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
*/
void sp_bit_vec_dealloc(struct sp_BitVec *this_);
/**
* Sets the value of all bits in the `BitVec`.
*/
void sp_bit_vec_fill(struct sp_BitVec *this_, bool value);
/**
* Gets the value of a bit from the `BitVec`.
*/
bool sp_bit_vec_get(const struct sp_BitVec *this_, size_t index);
/**
* Returns true if length is 0.
*/
bool sp_bit_vec_is_empty(const struct sp_BitVec *this_);
/**
* Gets the length of the `BitVec` in bits.
*/
size_t sp_bit_vec_len(const struct sp_BitVec *this_);
/**
* Loads a `BitVec` from the provided data.
* The returned instance has to be freed with `bit_vec_dealloc`.
*/
struct sp_BitVec *sp_bit_vec_load(const uint8_t *data, size_t data_length);
/**
* Creates a new `BitVec` instance.
* The returned instance has to be freed with `bit_vec_dealloc`.
*/
struct sp_BitVec *sp_bit_vec_new(size_t size);
/**
* Sets the value of a bit in the `BitVec`.
*/
bool sp_bit_vec_set(struct sp_BitVec *this_, size_t index, bool value);
/**
* Gets an unsafe reference to the data of the `BitVec` instance.
*
* ## Safety
*
* The caller has to make sure to never access the returned memory after the `BitVec`
* instance has been consumed or manually deallocated.
*
* Reading and writing concurrently to either the original instance or the returned data will
* result in undefined behavior.
*/
struct sp_CByteSlice sp_bit_vec_unsafe_data_ref(struct sp_BitVec *this_);
/**
* Clones a `ByteGrid`.
* The returned instance has to be freed with `byte_grid_dealloc`.
*/
struct sp_ByteGrid *sp_byte_grid_clone(const struct sp_ByteGrid *this_);
/**
* Deallocates a `ByteGrid`.
*
* Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
*/
void sp_byte_grid_dealloc(struct sp_ByteGrid *this_);
/**
* Fills the whole `ByteGrid` with the specified value
*/
void sp_byte_grid_fill(struct sp_ByteGrid *this_, uint8_t value);
/**
* Get the current value at the specified position
*/
uint8_t sp_byte_grid_get(const struct sp_ByteGrid *this_, size_t x, size_t y);
/**
* Gets the height in pixels of the `ByteGrid` instance.
*/
size_t sp_byte_grid_height(const struct sp_ByteGrid *this_);
/**
* Loads a `ByteGrid` with the specified dimensions from the provided data.
* The returned instance has to be freed with `byte_grid_dealloc`.
*/
struct sp_ByteGrid *sp_byte_grid_load(size_t width,
size_t height,
const uint8_t *data,
size_t data_length);
/**
* Creates a new `ByteGrid` instance.
* The returned instance has to be freed with `byte_grid_dealloc`.
*/
struct sp_ByteGrid *sp_byte_grid_new(size_t width, size_t height);
/**
* Sets the current value at the specified position
*/
void sp_byte_grid_set(struct sp_ByteGrid *this_,
size_t x,
size_t y,
uint8_t value);
/**
* Gets an unsafe reference to the data of the `ByteGrid` instance.
*
* ## Safety
*
* The caller has to make sure to never access the returned memory after the `ByteGrid`
* instance has been consumed or manually deallocated.
*
* Reading and writing concurrently to either the original instance or the returned data will
* result in undefined behavior.
*/
struct sp_CByteSlice sp_byte_grid_unsafe_data_ref(struct sp_ByteGrid *this_);
/**
* Gets the width in pixels of the `ByteGrid` instance.
*/
size_t sp_byte_grid_width(const struct sp_ByteGrid *this_);
/**
* Allocates a new `Command::BitmapLinear` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp_Command *sp_command_bitmap_linear(sp_Offset offset,
struct sp_BitVec *bit_vec,
sp_CompressionCode compression);
/**
* Allocates a new `Command::BitmapLinearAnd` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp_Command *sp_command_bitmap_linear_and(sp_Offset offset,
struct sp_BitVec *bit_vec,
sp_CompressionCode compression);
/**
* Allocates a new `Command::BitmapLinearOr` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp_Command *sp_command_bitmap_linear_or(sp_Offset offset,
struct sp_BitVec *bit_vec,
sp_CompressionCode compression);
/**
* Allocates a new `Command::BitmapLinearWin` instance.
* The passed `PixelGrid` gets deallocated in the process.
*/
struct sp_Command *sp_command_bitmap_linear_win(size_t x,
size_t y,
struct sp_PixelGrid *byte_grid,
sp_CompressionCode compression_code);
/**
* Allocates a new `Command::BitmapLinearXor` instance.
* The passed `BitVec` gets deallocated in the process.
*/
struct sp_Command *sp_command_bitmap_linear_xor(sp_Offset offset,
struct sp_BitVec *bit_vec,
sp_CompressionCode compression);
/**
* Allocates a new `Command::Brightness` instance
*/
struct sp_Command *sp_command_brightness(sp_Brightness brightness);
/**
* Allocates a new `Command::CharBrightness` instance.
* The passed `ByteGrid` gets deallocated in the process.
*/
struct sp_Command *sp_command_char_brightness(size_t x,
size_t y,
struct sp_ByteGrid *byte_grid);
/**
* Allocates a new `Command::Clear` instance
*/
struct sp_Command *sp_command_clear(void);
/**
* Clones a `Command` instance
*/
struct sp_Command *sp_command_clone(const struct sp_Command *original);
/**
* Allocates a new `Command::Cp437Data` instance.
* The passed `ByteGrid` gets deallocated in the process.
*/
struct sp_Command *sp_command_cp437_data(size_t x,
size_t y,
struct sp_ByteGrid *byte_grid);
/**
* Deallocates a `Command`. Note that connection_send does this implicitly, so you only need
* to do this if you use the library for parsing commands.
*/
void sp_command_dealloc(struct sp_Command *ptr);
/**
* Allocates a new `Command::FadeOut` instance
*/
struct sp_Command *sp_command_fade_out(void);
/**
* Allocates a new `Command::HardReset` instance
*/
struct sp_Command *sp_command_hard_reset(void);
/**
* Tries to turn a `Packet` into a `Command`. The packet is gets deallocated in the process.
*
* Returns: pointer to command or NULL
*/
struct sp_Command *sp_command_try_from_packet(struct sp_Packet *packet);
/**
* Closes and deallocates a connection instance
*/
void sp_connection_dealloc(struct sp_Connection *ptr);
/**
* Creates a new instance of Connection.
* The returned instance has to be deallocated with `connection_dealloc`.
*
* returns: NULL if connection fails or connected instance
*
* Panics: bad string encoding
*/
struct sp_Connection *sp_connection_open(const char *host);
/**
* Sends the command instance. The instance is consumed / destroyed and cannot be used after this call.
*/
bool sp_connection_send(const struct sp_Connection *connection,
struct sp_Packet *command_ptr);
/**
* Deallocates a `Packet`.
*
* Note: do not call this if the instance has been consumed in another way, e.g. by sending it.
*/
void sp_packet_dealloc(struct sp_Packet *this_);
/**
* Turns a `Command` into a `Packet`. The command gets deallocated in the process.
*/
struct sp_Packet *sp_packet_from_command(struct sp_Command *command);
/**
* Tries to load a `Packet` from the passed array with the specified length.
*
* returns: NULL in case of an error, pointer to the allocated packet otherwise
*/
struct sp_Packet *sp_packet_try_load(const uint8_t *data, size_t length);
/**
* Clones a `PixelGrid`.
* The returned instance has to be freed with `pixel_grid_dealloc`.
*/
struct sp_PixelGrid *sp_pixel_grid_clone(const struct sp_PixelGrid *this_);
/**
* Deallocates a `PixelGrid`.
*
* Note: do not call this if the grid has been consumed in another way, e.g. to create a command.
*/
void sp_pixel_grid_dealloc(struct sp_PixelGrid *this_);
/**
* Fills the whole `PixelGrid` with the specified value
*/
void sp_pixel_grid_fill(struct sp_PixelGrid *this_, bool value);
/**
* Get the current value at the specified position
*/
bool sp_pixel_grid_get(const struct sp_PixelGrid *this_, size_t x, size_t y);
/**
* Gets the height in pixels of the `PixelGrid` instance.
*/
size_t sp_pixel_grid_height(const struct sp_PixelGrid *this_);
/**
* Loads a `PixelGrid` with the specified dimensions from the provided data.
* The returned instance has to be freed with `pixel_grid_dealloc`.
*/
struct sp_PixelGrid *sp_pixel_grid_load(size_t width,
size_t height,
const uint8_t *data,
size_t data_length);
/**
* Creates a new `PixelGrid` instance.
* The returned instance has to be freed with `pixel_grid_dealloc`.
*/
struct sp_PixelGrid *sp_pixel_grid_new(size_t width, size_t height);
/**
* Sets the current value at the specified position
*/
void sp_pixel_grid_set(struct sp_PixelGrid *this_,
size_t x,
size_t y,
bool value);
/**
* Gets an unsafe reference to the data of the `PixelGrid` instance.
*
* ## Safety
*
* The caller has to make sure to never access the returned memory after the `PixelGrid`
* instance has been consumed or manually deallocated.
*
* Reading and writing concurrently to either the original instance or the returned data will
* result in undefined behavior.
*/
struct sp_CByteSlice sp_pixel_grid_unsafe_data_ref(struct sp_PixelGrid *this_);
/**
* Gets the width in pixels of the `PixelGrid` instance.
*/
size_t sp_pixel_grid_width(const struct sp_PixelGrid *this_);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus

View file

@ -0,0 +1 @@

View file

@ -0,0 +1,19 @@
#include <stdio.h>
#include "servicepoint.h"
int main(void) {
sp_Connection *connection = sp_connection_open("localhost:2342");
if (connection == NULL)
return 1;
sp_PixelGrid *pixels = sp_pixel_grid_new(sp_PIXEL_WIDTH, sp_PIXEL_HEIGHT);
sp_pixel_grid_fill(pixels, true);
sp_Command *command = sp_command_bitmap_linear_win(0, 0, pixels, Uncompressed);
sp_Packet *packet = sp_packet_from_command(command);
if (!sp_connection_send(connection, packet))
return 1;
sp_connection_dealloc(connection);
return 0;
}

View file

@ -0,0 +1,20 @@
using ServicePoint;
using CompressionCode = ServicePoint.BindGen.CompressionCode;
using var connection = Connection.Open("127.0.0.1:2342");
connection.Send(Command.Clear().IntoPacket());
connection.Send(Command.Brightness(128).IntoPacket());
using var pixels = PixelGrid.New(Constants.PixelWidth, Constants.PixelHeight);
for (var offset = 0; offset < int.MaxValue; offset++)
{
pixels.Fill(false);
for (var y = 0; y < pixels.Height; y++)
pixels[(y + offset) % Constants.PixelWidth, y] = true;
connection.Send(Command.BitmapLinearWin(0, 0, pixels.Clone(), CompressionCode.Lzma).IntoPacket());
Thread.Sleep(14);
}

View file

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>lang_cs</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../crates/servicepoint_binding_cs/ServicePoint/ServicePoint.csproj"/>
</ItemGroup>
</Project>