scpi 1.0.1

SCPI/IEEE488.2 parser library
Documentation
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
mod util;

use scpi::cmd_qonly;
use scpi::{error::Result, tree::prelude::*};
use util::TestDevice;

use std::convert::TryFrom;
use std::marker::PhantomData;

extern crate std;

#[derive(Default)]
struct EchoCommand<T>(PhantomData<T>);

impl<T> EchoCommand<T> {
    const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T> Command<TestDevice> for EchoCommand<T>
where
    T: for<'a> TryFrom<Token<'a>, Error = Error> + ResponseData,
{
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: T = params.next_data()?;
        response.data(x).finish()
    }
}

struct StrEchoCommand;

impl Command<TestDevice> for StrEchoCommand {
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: &[u8] = params.next_data()?;
        response.data(x).finish()
    }
}

struct ArbEchoCommand;

impl Command<TestDevice> for ArbEchoCommand {
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: Arbitrary = params.next_data()?;
        response.data(x).finish()
    }
}

struct ChrEchoCommand;

impl Command<TestDevice> for ChrEchoCommand {
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: Character = params.next_data()?;
        response.data(x).finish()
    }
}

trait InfOrNan {
    fn is_t_inf(&self) -> bool;
    fn is_t_nan(&self) -> bool;
}

impl InfOrNan for f32 {
    fn is_t_inf(&self) -> bool {
        self.is_infinite()
    }

    fn is_t_nan(&self) -> bool {
        self.is_nan()
    }
}

impl InfOrNan for f64 {
    fn is_t_inf(&self) -> bool {
        self.is_infinite()
    }

    fn is_t_nan(&self) -> bool {
        self.is_nan()
    }
}

/// Used to test floating point number conversion for (N)INFINITY values
struct IsInf<T>(PhantomData<T>);

impl<T> IsInf<T> {
    const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T> Command<TestDevice> for IsInf<T>
where
    T: for<'a> TryFrom<Token<'a>, Error = Error> + ResponseData + InfOrNan,
{
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: T = params.next_data()?;
        response.data(x.is_t_inf()).finish()
    }
}

/// Used to test floating point number conversion for NAN values
struct IsNan<T>(PhantomData<T>);

impl<T> IsNan<T> {
    const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T> Command<TestDevice> for IsNan<T>
where
    T: for<'a> TryFrom<Token<'a>, Error = Error> + ResponseData + InfOrNan,
{
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: T = params.next_data()?;
        response.data(x.is_t_nan()).finish()
    }
}

#[cfg(feature = "alloc")]
struct VecData;

#[cfg(feature = "alloc")]
impl Command<TestDevice> for VecData {
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        _params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x = vec![1, 2, 3];
        response.data(x).finish()
    }
}

#[cfg(feature = "arrayvec")]
struct ArrayVecData;

#[cfg(feature = "arrayvec")]
impl Command<TestDevice> for ArrayVecData {
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        _params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        use arrayvec::ArrayVec;

        let x = ArrayVec::from([1, 2, 3]);
        response.data(x).finish()
    }
}

macro_rules! add_numeric_command {
    ($cmd:literal : $name:expr ) => {
        Leaf {
            name: $cmd,
            default: false,
            handler: $name,
        }
    };
}

macro_rules! test_integer {
    ($test:ident; $cmd:literal, $min:expr, $max:expr) => {
        mod $test {
            use super::*;
            #[test]
            fn test_integer() {
                let mut dev = TestDevice;
                let res = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} 42", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap();
                assert_eq!(res.as_slice(), b"42\n");
            }
            #[test]
            fn test_rounding() {
                let mut dev = TestDevice::new();
                let res = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} 0.4;{cmd} 0.6", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap();
                assert_eq!(res.as_slice(), b"0;1\n");
            }
            #[test]
            fn test_max_min() {
                let mut dev = TestDevice::new();
                let res = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} MAX;{cmd} MIN", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap();
                assert_eq!(
                    res.as_slice(),
                    format!("{max};{min}\n", max = $max, min = $min).as_bytes()
                );
            }
            #[test]
            fn test_hex() {
                let mut dev = TestDevice::new();
                let res = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} #H002A", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap();
                assert_eq!(res.as_slice(), b"42\n");
            }
            #[test]
            fn test_octal() {
                let mut dev = TestDevice::new();
                let res = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} #Q52", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap();
                assert_eq!(res.as_slice(), b"42\n");
            }
            #[test]
            fn test_binary() {
                let mut dev = TestDevice::new();
                let res = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} #B101010", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap();
                assert_eq!(res.as_slice(), b"42\n");
            }
            #[test]
            fn test_datatype_error() {
                let mut dev = TestDevice::new();
                let err = util::test_execute_str(
                    &TEST_TREE,
                    format!("{cmd} '42'", cmd = $cmd).as_bytes(),
                    &mut dev,
                )
                .unwrap_err();
                assert_eq!(err, Error::from(ErrorCode::DataTypeError));
            }
        }
    };
}

macro_rules! test_real {
    ($test:ident; $cmd:literal, $inf:literal, $nan:literal, $min:expr, $max:expr) => {
        mod $test {
            use super::*;
            #[test]
            fn test_decimal() {
                let mut dev = TestDevice::new();

                let valid = [
                    ("1.0", "1.0\n"),
                    ("+1", "1.0\n"),
                    ("-1", "-1.0\n"),
                    ("1e10", "1.0e10\n"),
                    ("+1.3E-1", "0.13\n"),
                ];
                for s in &valid {
                    let cmd = format!("{cmd} {value}", cmd = $cmd, value = s.0);
                    let res = util::test_execute_str(&TEST_TREE, cmd.as_bytes(), &mut dev).unwrap();
                    println!("{}=>{}", s.0, std::str::from_utf8(res.as_slice()).unwrap());
                    assert_eq!(res.as_slice(), s.1.as_bytes());
                }
            }

            #[test]
            fn test_inf() {
                let mut dev = TestDevice::new();

                let infinite = ["inf", "ninf", "INFINITY", "NINFINITY"];
                for s in &infinite {
                    let cmd = format!("{cmd} {value}", cmd = $inf, value = s);
                    let res = util::test_execute_str(&TEST_TREE, cmd.as_bytes(), &mut dev).unwrap();
                    assert_eq!(res.as_slice(), b"1\n");
                }

                let cmd = format!("{cmd} 1.0", cmd = $nan);
                let res = util::test_execute_str(&TEST_TREE, cmd.as_bytes(), &mut dev).unwrap();
                assert_eq!(res.as_slice(), b"0\n");
            }

            #[test]
            fn test_nan() {
                let mut dev = TestDevice::new();

                let cmd = format!("{cmd} NAN;{cmd} 1.0", cmd = $nan);
                let res = util::test_execute_str(&TEST_TREE, cmd.as_bytes(), &mut dev).unwrap();
                assert_eq!(res.as_slice(), b"1;0\n");
            }

            #[test]
            fn test_datatype_error() {
                let mut dev = TestDevice::new();

                let cmd1 = format!("{cmd} 'STRING'", cmd = $nan);
                let res =
                    util::test_execute_str(&TEST_TREE, cmd1.as_bytes(), &mut dev).unwrap_err();
                assert_eq!(res, Error::from(ErrorCode::DataTypeError));

                let cmd2 = format!("{cmd} INVALID", cmd = $nan);
                let res =
                    util::test_execute_str(&TEST_TREE, cmd2.as_bytes(), &mut dev).unwrap_err();
                assert_eq!(res, Error::from(ErrorCode::DataTypeError));
            }
        }
    };
}

const TEST_TREE: &Node<TestDevice> = &Branch {
    name: b"",
    default: false,
    sub: &[
        add_numeric_command!(b"*STR": &StrEchoCommand),
        add_numeric_command!(b"*ARB": &ArbEchoCommand),
        add_numeric_command!(b"*CHR": &ChrEchoCommand),
        add_numeric_command!(b"*UTF8": &Utf8Command::new()),
        add_numeric_command!(b"*F64": &EchoCommand::<f64>::new()),
        add_numeric_command!(b"*F64ISINF": &IsInf::<f64>::new()),
        add_numeric_command!(b"*F64ISNAN": &IsNan::<f64>::new()),
        add_numeric_command!(b"*F32": &EchoCommand::<f32>::new()),
        add_numeric_command!(b"*F32ISINF": &IsInf::<f32>::new()),
        add_numeric_command!(b"*F32ISNAN": &IsNan::<f32>::new()),
        add_numeric_command!(b"*BOOL": &EchoCommand::<bool>::new()),
        add_numeric_command!(b"*U64": &EchoCommand::<u64>::new()),
        add_numeric_command!(b"*I64": &EchoCommand::<i64>::new()),
        add_numeric_command!(b"*U32": &EchoCommand::<u32>::new()),
        add_numeric_command!(b"*I32": &EchoCommand::<i32>::new()),
        add_numeric_command!(b"*U16": &EchoCommand::<u16>::new()),
        add_numeric_command!(b"*I16": &EchoCommand::<i16>::new()),
        add_numeric_command!(b"*U8": &EchoCommand::<u8>::new()),
        add_numeric_command!(b"*I8": &EchoCommand::<i8>::new()),
        add_numeric_command!(b"*USIZE": &EchoCommand::<usize>::new()),
        add_numeric_command!(b"*ISIZE": &EchoCommand::<isize>::new()),
        #[cfg(feature = "alloc")]
        add_numeric_command!(b"*VEC": &VecData),
        #[cfg(feature = "arrayvec")]
        add_numeric_command!(b"*ARRAYVEC": &ArrayVecData),
    ],
};

test_real!(real_f32; "*F32?", "*F32ISINF?", "*F32ISNAN?", f32::MIN, f32::MAX);

test_real!(real_f64; "*F64?", "*F64ISINF?", "*F64ISNAN?", f64::MIN, f64::MAX);

test_integer!(integer_u64; "*U64?", u64::MIN, u64::MAX);

test_integer!(integer_i64; "*I64?", i64::MIN, i64::MAX);

test_integer!(integer_u32; "*U32?", u32::MIN, u32::MAX);

test_integer!(integer_i32; "*I32?", i32::MIN, i32::MAX);

test_integer!(integer_u16; "*U16?", u16::MIN, u16::MAX);

test_integer!(integer_i16; "*I16?", i16::MIN, i16::MAX);

test_integer!(integer_u8; "*u8?", u8::MIN, u8::MAX);

test_integer!(integer_i8; "*I8?", i8::MIN, i8::MAX);

test_integer!(integer_usize; "*USIZE?", usize::MIN, usize::MAX);

test_integer!(integer_isize; "*ISIZE?", isize::MIN, isize::MAX);

mod string {
    use super::*;
    #[test]
    fn test_str() {
        let mut dev = TestDevice::new();

        let res = util::test_execute_str(TEST_TREE, "*STR? 'STRING'".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"\"STRING\"\n");

        let res =
            util::test_execute_str(TEST_TREE, "*STR? CHRDATA".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));

        let res = util::test_execute_str(TEST_TREE, "*STR? 1.0".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));
    }
}

mod arbitrary {
    use super::*;
    #[test]
    fn test_arb() {
        let mut dev = TestDevice::new();

        let res = util::test_execute_str(TEST_TREE, "*ARB? #203ABC".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"#13ABC\n");

        let res =
            util::test_execute_str(TEST_TREE, "*ARB? CHRDATA".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));

        let res = util::test_execute_str(TEST_TREE, "*ARB? 1.0".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));
    }
}

mod character {
    use super::*;
    #[test]
    fn test_chr() {
        let mut dev = TestDevice::new();

        let res = util::test_execute_str(TEST_TREE, "*CHR? CHRDATA".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"CHRDATA\n");

        let res =
            util::test_execute_str(TEST_TREE, "*CHR? 'CHRDATA'".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));

        let res = util::test_execute_str(TEST_TREE, "*CHR? 1.0".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));
    }
}

struct Utf8Command {}

impl Utf8Command {
    const fn new() -> Self {
        Self {}
    }
}

impl Command<TestDevice> for Utf8Command {
    cmd_qonly!();

    fn query(
        &self,
        _device: &mut TestDevice,
        _context: &mut Context,
        mut params: Parameters,
        mut response: ResponseUnit,
    ) -> Result<()> {
        let x: &str = params.next_data()?;
        response.data(Arbitrary(x.as_bytes())).finish()
    }
}
mod utf8 {
    //! Test parsing of UTF8 str type
    //! Parser will accept either a IEEE488 string type or arbitray data and check if the data is valid Utf8

    use super::*;
    #[test]
    fn test_utf8() {
        let mut dev = TestDevice::new();

        let res =
            util::test_execute_str(TEST_TREE, "*UTF8? 'STRING'".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"#16STRING\n");

        let res =
            util::test_execute_str(TEST_TREE, "*UTF8? #206STRING".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"#16STRING\n");

        let res = util::test_execute_str(TEST_TREE, "*UTF8? 1.0".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));
    }
}

mod boolean {
    use super::*;
    #[test]
    fn test_bool_numeric() {
        let mut dev = TestDevice::new();

        let res = util::test_execute_str(
            TEST_TREE,
            "*BOOL? 0;*BOOL? 1;*BOOL? -1;*BOOL? 1.0".as_bytes(),
            &mut dev,
        )
        .unwrap();
        assert_eq!(res.as_slice(), b"0;1;1;1\n");
    }

    #[test]
    fn test_bool_character() {
        let mut dev = TestDevice::new();

        let res =
            util::test_execute_str(TEST_TREE, "*BOOL? ON;*BOOL? OFF".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"1;0\n");

        let res =
            util::test_execute_str(TEST_TREE, "*BOOL? POTATO".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::IllegalParameterValue));

        let res =
            util::test_execute_str(TEST_TREE, "*BOOL? (@1)".as_bytes(), &mut dev).unwrap_err();
        assert_eq!(res, Error::from(ErrorCode::DataTypeError));
    }
}

#[cfg(feature = "alloc")]
mod test_vec {
    //! Test parsing of UTF8 str type
    //! Parser will accept either a IEEE488 string type or arbitray data and check if the data is valid Utf8

    use super::*;
    #[test]
    fn test_vec() {
        let mut dev = TestDevice::new();

        let res = util::test_execute_str(TEST_TREE, "*VEC?".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"1,2,3\n");
    }
}

#[cfg(feature = "arrayvec")]
mod test_arrayvec {
    //! Test parsing of UTF8 str type
    //! Parser will accept either a IEEE488 string type or arbitray data and check if the data is valid Utf8

    use super::*;
    #[test]
    fn test_vec() {
        let mut dev = TestDevice::new();

        let res = util::test_execute_str(TEST_TREE, "*ARRAYVEC?".as_bytes(), &mut dev).unwrap();
        assert_eq!(res.as_slice(), b"1,2,3\n");
    }
}