pack_unpack/
pack_unpack.rs

1use std::process;
2
3use meatpack::{MEATPACK_HEADER, MeatPackResult, Packer, Unpacker};
4
5fn main() {
6    let gcode = "M73 P0 R3
7M73 Q0 S3 ; Hello
8M201 X4000 Y4000 Z200 E2500
9M203 X300 Y300 Z40 E100
10M204 P4000 R1200 T4000
11";
12
13    println!("## IN ##");
14    println!("{}", gcode);
15    println!("####");
16
17    // Initiliase the packer with buffer size depending
18    // on your application
19    let mut packer = Packer::<64>::default();
20    let mut out: Vec<u8> = vec![];
21
22    // This will store the entire packed version of the gcode.
23    // Don't forget the header.
24    out.extend(&MEATPACK_HEADER);
25
26    // Feed in the bytes as you receive them and
27    // the packer will return completed lines of
28    // meatpacked gcode.
29    for byte in gcode.as_bytes() {
30        let packed = packer.pack(byte);
31        match packed {
32            Ok(MeatPackResult::Line(line)) => {
33                println!("{:?}", line);
34                out.extend(line);
35            }
36            Ok(MeatPackResult::WaitingForNextByte) => {}
37            Err(e) => println!("{:?}", e),
38        }
39    }
40
41    println!("{:?}", out);
42
43    println!("## OUT ##");
44
45    // Now we create an unpacker to unpack the meatpacked data.
46    let mut unpacker = Unpacker::<64>::default();
47
48    // Imagine receiving the bytes from some I/O and we want
49    // to construct gcode lines and deal with them as we form them.
50    for byte in out.iter() {
51        let res = unpacker.unpack(byte);
52        match res {
53            Ok(MeatPackResult::WaitingForNextByte) => {}
54            Ok(MeatPackResult::Line(line)) => {
55                // If in std.
56                for byte in line {
57                    let c = char::from(*byte);
58                    print!("{}", c);
59                }
60            }
61            Err(e) => {
62                println!("{:?}", e);
63                process::exit(0)
64            }
65        }
66    }
67
68    println!("####");
69}