1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Representations of all supported G-code instructions/commands for cnccoder.
//!
//! This is the lowest level of structs in the crate. Even if they are publicly exposed,
//! they are primarily intended to be used internally by the higher level [cuts](../cuts/index.html).

use std::fmt::Write as _;
use std::time::Duration;

use crate::utils::round_precision;

/// Rapid move
#[derive(Debug, Clone, PartialEq)]
pub struct G0 {
    /// X Coordinate
    pub x: Option<f64>,
    /// Y Coordinate
    pub y: Option<f64>,
    /// Z Coordinate
    pub z: Option<f64>,
}

impl G0 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        let mut command = "G0".to_string();

        if let Some(x) = self.x {
            let _ = write!(command, " X{}", round_precision(x));
        }

        if let Some(y) = self.y {
            let _ = write!(command, " Y{}", round_precision(y));
        }

        if let Some(z) = self.z {
            let _ = write!(command, " Z{}", round_precision(z));
        }

        command
    }
}

/// Linear Move
#[derive(Debug, Clone, PartialEq)]
pub struct G1 {
    /// X Coordinate
    pub x: Option<f64>,
    /// Y Coordinate
    pub y: Option<f64>,
    /// Z Coordinate
    pub z: Option<f64>,
    /// Feedrate
    pub f: Option<f64>,
}

impl G1 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        let mut command = "G1".to_string();

        if let Some(x) = self.x {
            let _ = write!(command, " X{}", round_precision(x));
        }

        if let Some(y) = self.y {
            let _ = write!(command, " Y{}", round_precision(y));
        }

        if let Some(z) = self.z {
            let _ = write!(command, " Z{}", round_precision(z));
        }

        if let Some(f) = self.f {
            let _ = write!(command, " F{}", round_precision(f));
        }

        command
    }
}

/// Arc Move (clockwise)
///
/// Use either R or I, J, mixing all three is not allowed
#[derive(Debug, Clone, PartialEq)]
pub struct G2 {
    /// X Coordinate
    pub x: Option<f64>,
    /// Y Coordinate
    pub y: Option<f64>,
    /// Z Coordinate
    pub z: Option<f64>,
    /// X Offset
    pub i: Option<f64>,
    /// Y Offset
    pub j: Option<f64>,
    /// Z Offset
    pub k: Option<f64>,
    /// Radius
    pub r: Option<f64>,
    ///  Number of complete circles
    pub p: Option<u32>,
    /// Feedrate
    pub f: Option<f64>,
}

impl G2 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        let mut command = "G2".to_string();

        if let Some(x) = self.x {
            let _ = write!(command, " X{}", round_precision(x));
        }

        if let Some(y) = self.y {
            let _ = write!(command, " Y{}", round_precision(y));
        }

        if let Some(z) = self.z {
            let _ = write!(command, " Z{}", round_precision(z));
        }

        if let Some(r) = self.r {
            let _ = write!(command, " R{}", round_precision(r));
        } else {
            if let Some(i) = self.i {
                let _ = write!(command, " I{}", round_precision(i));
            }

            if let Some(j) = self.j {
                let _ = write!(command, " J{}", round_precision(j));
            }

            if let Some(k) = self.k {
                let _ = write!(command, " K{}", round_precision(k));
            }
        }

        if let Some(p) = self.p {
            let _ = write!(command, " P{}", round_precision(p.into()));
        }

        if let Some(f) = self.f {
            let _ = write!(command, " F{}", round_precision(f));
        }

        command
    }
}

/// Arc Move (counterclockwise)
///
/// Use either R or I, J, mixing all three is not allowed
#[derive(Debug, Clone, PartialEq)]
pub struct G3 {
    /// X Coordinate
    pub x: Option<f64>,
    /// Y Coordinate
    pub y: Option<f64>,
    /// Z Coordinate
    pub z: Option<f64>,
    /// X Offset
    pub i: Option<f64>,
    /// Y Offset
    pub j: Option<f64>,
    /// Z Offset
    pub k: Option<f64>,
    /// Radius
    pub r: Option<f64>,
    ///  Number of complete circles
    pub p: Option<u32>,
    /// Feedrate
    pub f: Option<f64>,
}

impl G3 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        let mut command = "G3".to_string();

        if let Some(x) = self.x {
            let _ = write!(command, " X{}", round_precision(x));
        }

        if let Some(y) = self.y {
            let _ = write!(command, " Y{}", round_precision(y));
        }

        if let Some(z) = self.z {
            let _ = write!(command, " Z{}", round_precision(z));
        }

        if let Some(r) = self.r {
            let _ = write!(command, " R{}", round_precision(r));
        } else {
            if let Some(i) = self.i {
                let _ = write!(command, " I{}", round_precision(i));
            }

            if let Some(j) = self.j {
                let _ = write!(command, " J{}", round_precision(j));
            }

            if let Some(k) = self.k {
                let _ = write!(command, " K{}", round_precision(k));
            }
        }

        if let Some(p) = self.p {
            let _ = write!(command, " P{}", round_precision(p.into()));
        }

        if let Some(f) = self.f {
            let _ = write!(command, " F{}", round_precision(f));
        }

        command
    }
}

/// Dwell (pause duration)
#[derive(Debug, Clone, PartialEq)]
pub struct G4 {
    /// Duration to pause (serializedto seconds)
    pub p: Duration,
}

impl G4 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        format!("G4 P{}", round_precision(self.p.as_secs_f64()))
    }
}

/// Select Plane XY
#[derive(Debug, Clone, PartialEq)]
pub struct G17 {}

impl G17 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "G17".to_string()
    }
}

/// Select Plane ZX
#[derive(Debug, Clone, PartialEq)]
pub struct G18 {}

impl G18 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "G18".to_string()
    }
}

/// Select Plane YZ
#[derive(Debug, Clone, PartialEq)]
pub struct G19 {}

impl G19 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "G19".to_string()
    }
}

/// Inch Units
#[derive(Debug, Clone, PartialEq)]
pub struct G20 {}

impl G20 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "G20".to_string()
    }
}

/// Millimeter Units
#[derive(Debug, Clone, PartialEq)]
pub struct G21 {}

impl G21 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "G21".to_string()
    }
}

/// Tool Length Offset (applies offset to all coordinates)
#[derive(Debug, Clone, PartialEq)]
pub struct G43 {
    /// Tool number (offset will be looked up in the tool table)
    pub h: u32,
}

impl G43 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        format!("G43 H{}", self.h)
    }
}

/// Set Feed Rate
#[derive(Debug, Clone, PartialEq)]
pub struct F {
    /// Feed rate (units per minute)
    pub x: f64,
}

impl F {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        format!("F{}", round_precision(self.x))
    }
}

/// Set Spindle Speed
#[derive(Debug, Clone, PartialEq)]
pub struct S {
    /// Feed rate (rpm)
    pub x: f64,
}

impl S {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        format!("S{}", round_precision(self.x))
    }
}

/// Program Pause (user must resume)
#[derive(Debug, Clone, PartialEq)]
pub struct M0 {}

impl M0 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "M0".to_string()
    }
}

/// Program End (stop spindle and reset all offsets)
#[derive(Debug, Clone, PartialEq)]
pub struct M2 {}

impl M2 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "M2".to_string()
    }
}

/// Start Spindle (clockwise)
#[derive(Debug, Clone, PartialEq)]
pub struct M3 {}

impl M3 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "M3".to_string()
    }
}

/// Start Spindle (counterclockwise)
#[derive(Debug, Clone, PartialEq)]
pub struct M4 {}

impl M4 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "M4".to_string()
    }
}

/// Stop Spindle
#[derive(Debug, Clone, PartialEq)]
pub struct M5 {}

impl M5 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "M5".to_string()
    }
}

/// Manual Tool Change
#[derive(Debug, Clone, PartialEq)]
pub struct M6 {
    /// Tool number
    pub t: u8,
}

impl M6 {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        format!("T{} M6", self.t)
    }
}

/// Empty Line
#[derive(Debug, Clone, PartialEq)]
pub struct Empty {}

impl Empty {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        "".to_string()
    }
}

/// Comment
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Comment {
    /// Comment
    pub text: String,
}

impl Comment {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        if self.text.is_empty() {
            return String::new();
        }

        format!(";({})", self.text)
    }
}

/// Message to print
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
    /// Message
    pub text: String,
}

impl Message {
    /// Generate G-code string
    pub fn to_gcode(&self) -> String {
        format!("(MSG,{})", self.text)
    }
}

/// The Instruction enum is used to represent a single G-code command in a program.
/// See the
/// [Grbl reference](https://github.com/gnea/grbl/wiki/Grbl-v1.1-Commands#g---view-gcode-parser-state)
/// for more details.
#[derive(Debug, Clone, PartialEq)]
pub enum Instruction {
    /// Command G0, Rapid Move
    G0(G0),
    /// Command G1, Linear Move
    G1(G1),
    /// Command G2, Arc Move (clockwise)
    G2(G2),
    /// Command G3, Arc Move (counterclockwise)
    G3(G3),
    /// Command G4, Dwell
    G4(G4),
    /// Command G17, Select Plane XY
    G17(G17),
    /// Command G18, Select Plane XZ
    G18(G18),
    /// Command G19, Select Plane YZ
    G19(G19),
    /// Command G20, Inch Units
    G20(G20),
    /// Command G20, Millimeter Units
    G21(G21),
    /// Command G43, Tool Length Offset
    G43(G43),
    /// Command F, Set Feed Rate
    F(F),
    /// Command S, Set Spindle Speed
    S(S),
    /// Command M0, Program Pause
    M0(M0),
    /// Command M2, Program End
    M2(M2),
    /// Command M3, Start Spindle (clockwise)
    M3(M3),
    /// Command M4, Start Spindle (counterclockwise)
    M4(M4),
    /// Command M5, Stop Spindle
    M5(M5),
    /// Command M6, Manual Tool Change
    M6(M6),
    /// Command Empty, Empty Line
    Empty(Empty),
    /// Command Comment, Comment
    Comment(Comment),
    /// Command Message, Message to point
    Message(Message),
}

impl Instruction {
    /// Converts instruction to G-code
    pub fn to_gcode(&self) -> String {
        match self {
            Instruction::G0(instruction) => instruction.to_gcode(),
            Instruction::G1(instruction) => instruction.to_gcode(),
            Instruction::G2(instruction) => instruction.to_gcode(),
            Instruction::G3(instruction) => instruction.to_gcode(),
            Instruction::G4(instruction) => instruction.to_gcode(),
            Instruction::G17(instruction) => instruction.to_gcode(),
            Instruction::G18(instruction) => instruction.to_gcode(),
            Instruction::G19(instruction) => instruction.to_gcode(),
            Instruction::G20(instruction) => instruction.to_gcode(),
            Instruction::G21(instruction) => instruction.to_gcode(),
            Instruction::G43(instruction) => instruction.to_gcode(),
            Instruction::F(instruction) => instruction.to_gcode(),
            Instruction::S(instruction) => instruction.to_gcode(),
            Instruction::M0(instruction) => instruction.to_gcode(),
            Instruction::M2(instruction) => instruction.to_gcode(),
            Instruction::M3(instruction) => instruction.to_gcode(),
            Instruction::M4(instruction) => instruction.to_gcode(),
            Instruction::M5(instruction) => instruction.to_gcode(),
            Instruction::M6(instruction) => instruction.to_gcode(),
            Instruction::Empty(instruction) => instruction.to_gcode(),
            Instruction::Comment(instruction) => instruction.to_gcode(),
            Instruction::Message(instruction) => instruction.to_gcode(),
        }
    }
}