cir 0.1.4

Linux Infrared Tooling
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use super::{Code, Flags, ParseError, RawCode, Remote};
use log::{debug, error, warn};
use std::num::ParseIntError;
use std::str::Lines;
use std::{
    fs::OpenOptions,
    io::Read,
    path::{Path, PathBuf},
    str::{FromStr, SplitWhitespace},
};

pub struct LircParser<'a> {
    path: PathBuf,
    line_no: u32,
    lines: Lines<'a>,
}

/// We need a custom parser for lircd.conf files, because the parser in lircd itself
/// is custom and permits all sorts which a proper parser would not. For example,
/// garbage is permitted when 'begin remote' is expected, and most lines can have
/// trailing characters after the first two tokens.
impl LircParser<'_> {
    pub fn parse(path: &Path) -> Result<Vec<Remote>, ParseError> {
        let mut file = OpenOptions::new().read(true).open(path).map_err(|e| {
            error!("failed to open ‘{}’: {}", path.display(), e);
            ParseError::FileError(e)
        })?;

        let mut buf = Vec::new();
        file.read_to_end(&mut buf).map_err(|e| {
            error!("failed to read ‘{}’: {}", path.display(), e);
            ParseError::FileError(e)
        })?;

        let contents = String::from_utf8_lossy(&buf);

        // strip bom
        let contents = if let Some(contents) = contents.strip_prefix('\u{feff}') {
            contents
        } else {
            &contents
        };

        let lines = contents.lines();

        debug!("parsing ‘{}’ as lircd.conf file", path.display());

        let mut parser = LircParser {
            path: PathBuf::from(path),
            line_no: 0,
            lines,
        };

        parser.read()
    }

    fn read(&mut self) -> Result<Vec<Remote>, ParseError> {
        let mut remotes = Vec::new();

        loop {
            let line = self.next_line();

            if line.is_none() {
                return if remotes.is_empty() {
                    error!("{}: no remote definitions found", self.path.display());
                    Err(ParseError::SyntaxError(self.line_no))
                } else {
                    Ok(remotes)
                };
            }

            let line = line.unwrap();

            let mut words = line.split_whitespace();

            let first = words.next();
            let second = words.next();

            if let (Some("begin"), Some("remote")) = (first, second) {
                let mut remote = self.read_remote()?;

                if self.sanity_checks(&mut remote) {
                    remotes.push(remote);
                }
            } else if let Some(first) = first {
                if !first.starts_with('#') {
                    warn!(
                        "{}:{}: expected 'begin remote', got ‘{}’",
                        self.path.display(),
                        self.line_no,
                        line
                    );
                }
            }
        }
    }

    fn read_remote(&mut self) -> Result<Remote, ParseError> {
        let mut remote = Remote {
            frequency: 38000,
            ..Default::default()
        };

        loop {
            let line = self.next_line();

            if line.is_none() {
                error!(
                    "{}:{}: unexpected end of file",
                    self.path.display(),
                    self.line_no
                );
                return Err(ParseError::SyntaxError(self.line_no));
            }

            let line = line.unwrap();

            let mut words = line.split_whitespace();

            let first = words.next();
            let second = words.next();

            match first {
                Some("name") => {
                    if second.is_none() {
                        error!(
                            "{}:{}: missing name argument",
                            self.path.display(),
                            self.line_no
                        );
                        return Err(ParseError::SyntaxError(self.line_no));
                    }

                    second.unwrap().clone_into(&mut remote.name);
                }
                Some("driver") => {
                    if second.is_none() {
                        error!(
                            "{}:{}: missing driver argument",
                            self.path.display(),
                            self.line_no
                        );
                        return Err(ParseError::SyntaxError(self.line_no));
                    }

                    second.unwrap().clone_into(&mut remote.driver);
                }
                Some("serial_mode") => {
                    if second.is_none() {
                        error!(
                            "{}:{}: missing serial_mode argument",
                            self.path.display(),
                            self.line_no
                        );
                        return Err(ParseError::SyntaxError(self.line_no));
                    }

                    second.unwrap().clone_into(&mut remote.serial_mode);
                }
                Some(name @ "eps")
                | Some(name @ "aeps")
                | Some(name @ "bits")
                | Some(name @ "plead")
                | Some(name @ "ptrail")
                | Some(name @ "pre_data_bits")
                | Some(name @ "pre_data")
                | Some(name @ "post_data_bits")
                | Some(name @ "post_data")
                | Some(name @ "frequency")
                | Some(name @ "duty_cycle")
                | Some(name @ "min_repeat")
                | Some(name @ "toggle_bit")
                | Some(name @ "repeat_bit")
                | Some(name @ "toggle_bit_mask")
                | Some(name @ "toggle_mask")
                | Some(name @ "rc6_mask")
                | Some(name @ "baud")
                | Some(name @ "repeat_gap")
                | Some(name @ "repeat_mask")
                | Some(name @ "suppress_repeat")
                | Some(name @ "manual_sort")
                | Some(name @ "min_code_repeat")
                | Some(name @ "ignore_mask") => {
                    let val = self.parse_number_arg(name, second)?;
                    match name {
                        "eps" => remote.eps = val,
                        "aeps" => remote.aeps = val,
                        "bits" => remote.bits = val,
                        "plead" => remote.plead = val,
                        "ptrail" => remote.ptrail = val,
                        "pre_data_bits" => remote.pre_data_bits = val,
                        "pre_data" => remote.pre_data = val,
                        "post_data_bits" => remote.post_data_bits = val,
                        "post_data" => remote.post_data = val,
                        "frequency" => remote.frequency = val,
                        "duty_cycle" => remote.duty_cycle = val,
                        "min_repeat" => remote.min_repeat = val,
                        "toggle_bit_mask" => remote.toggle_bit_mask = val,
                        "toggle_bit" => remote.toggle_bit = val,
                        "repeat_bit" => remote.toggle_bit = val,
                        "toggle_mask" => remote.toggle_mask = val,
                        "rc6_mask" => remote.rc6_mask = val,
                        "baud" => remote.baud = val,
                        "repeat_gap" => remote.repeat_gap = val,
                        "repeat_mask" => remote.repeat_mask = val,
                        "suppress_repeat" => remote.suppress_repeat = val,
                        "manual_sort" => remote.manual_sort = val,
                        "min_code_repeat" => remote.min_code_repeat = val,
                        "ignore_mask" => remote.ignore_mask = val,
                        _ => unreachable!(),
                    }
                }
                Some(name @ "gap") => {
                    remote.gap = self.parse_number_arg(name, second)?;

                    let gap2 = words.next();
                    if gap2.is_some() {
                        remote.gap2 = self.parse_number_arg(name, gap2)?;
                    }
                }
                Some(name @ "header")
                | Some(name @ "three")
                | Some(name @ "two")
                | Some(name @ "one")
                | Some(name @ "zero")
                | Some(name @ "foot")
                | Some(name @ "repeat")
                | Some(name @ "pre")
                | Some(name @ "post") => {
                    let first = self.parse_number_arg(name, second)?;
                    let second = self.parse_number_arg(name, words.next())?;

                    match name {
                        "header" => remote.header = (first, second),
                        "three" => remote.bit[3] = (first, second),
                        "two" => remote.bit[2] = (first, second),
                        "one" => remote.bit[1] = (first, second),
                        "zero" => remote.bit[0] = (first, second),
                        "foot" => remote.foot = (first, second),
                        "repeat" => remote.repeat = (first, second),
                        "pre" => remote.pre = (first, second),
                        "post" => remote.post = (first, second),
                        _ => unreachable!(),
                    }
                }
                Some("flags") => match second {
                    Some(val) => {
                        let mut flags = Flags::empty();

                        for flag in val.split('|') {
                            match flag {
                                "RAW_CODES" => {
                                    flags |= Flags::RAW_CODES;
                                }
                                "RC5" => {
                                    flags |= Flags::RC5;
                                }
                                "SHIFT_ENC" => {
                                    flags |= Flags::SHIFT_ENC;
                                }
                                "RC6" => {
                                    flags |= Flags::RC6;
                                }
                                "RCMM" => {
                                    flags |= Flags::RCMM;
                                }
                                "SPACE_ENC" => {
                                    flags |= Flags::SPACE_ENC;
                                }
                                "SPACE_FIRST" => {
                                    flags |= Flags::SPACE_FIRST;
                                }
                                "GRUNDIG" => {
                                    flags |= Flags::GRUNDIG;
                                }
                                "BO" => {
                                    flags |= Flags::BO;
                                }
                                "SERIAL" => {
                                    flags |= Flags::SERIAL;
                                }
                                "XMP" => {
                                    flags |= Flags::XMP;
                                }
                                "REVERSE" => {
                                    flags |= Flags::REVERSE;
                                }
                                "NO_HEAD_REP" => {
                                    flags |= Flags::NO_HEAD_REP;
                                }
                                "NO_FOOT_REP" => {
                                    flags |= Flags::NO_FOOT_REP;
                                }
                                "CONST_LENGTH" => {
                                    flags |= Flags::CONST_LENGTH;
                                }
                                "REPEAT_HEADER" => {
                                    flags |= Flags::REPEAT_HEADER;
                                }
                                _ => {
                                    error!(
                                        "{}:{}: unknown flag {}",
                                        self.path.display(),
                                        self.line_no,
                                        flag
                                    );
                                    return Err(ParseError::SyntaxError(self.line_no));
                                }
                            }
                        }

                        remote.flags = flags;
                    }
                    None => {
                        error!(
                            "{}:{}: missing flags argument",
                            self.path.display(),
                            self.line_no
                        );
                        return Err(ParseError::SyntaxError(self.line_no));
                    }
                },
                Some("end") => {
                    if let Some("remote") = second {
                        return Ok(remote);
                    }

                    error!(
                        "{}:{}: expected 'end remote', got ‘{}’",
                        self.path.display(),
                        self.line_no,
                        line
                    );

                    return Err(ParseError::SyntaxError(self.line_no));
                }
                Some("begin") => match second {
                    Some("codes") => {
                        remote.codes = self.read_codes()?;
                    }
                    Some("raw_codes") => {
                        remote.raw_codes = self.read_raw_codes()?;
                    }
                    _ => {
                        error!(
                            "{}:{}: expected 'begin codes' or 'begin raw_codes', got ‘{}’",
                            self.path.display(),
                            self.line_no,
                            line
                        );

                        return Err(ParseError::SyntaxError(self.line_no));
                    }
                },
                Some(key) => {
                    error!(
                        "{}:{}: ‘{}’ unexpected",
                        self.path.display(),
                        self.line_no,
                        key
                    );
                }
                None => (),
            }
        }
    }

    fn parse_number_arg(&self, arg_name: &str, arg: Option<&str>) -> Result<u64, ParseError> {
        if let Some(val) = arg {
            if let Ok(val) = parse_number(val) {
                Ok(val)
            } else {
                error!(
                    "{}:{}: {} argument {} is not a number",
                    self.path.display(),
                    self.line_no,
                    arg_name,
                    val
                );
                Err(ParseError::SyntaxError(self.line_no))
            }
        } else {
            error!(
                "{}:{}: missing {} argument",
                self.path.display(),
                self.line_no,
                arg_name
            );
            Err(ParseError::SyntaxError(self.line_no))
        }
    }

    fn read_codes(&mut self) -> Result<Vec<Code>, ParseError> {
        let mut codes = Vec::new();

        loop {
            let line = self.next_line();

            if line.is_none() {
                error!(
                    "{}:{}: unexpected end of file",
                    self.path.display(),
                    self.line_no
                );
                return Err(ParseError::SyntaxError(self.line_no));
            }

            let line = line.unwrap();

            let mut words = line.split_whitespace();

            match words.next() {
                Some("end") => {
                    if let Some("codes") = words.next() {
                        return Ok(codes);
                    }

                    error!(
                        "{}:{}: expected 'end codes', got ‘{}’",
                        self.path.display(),
                        self.line_no,
                        line
                    );

                    return Err(ParseError::SyntaxError(self.line_no));
                }
                Some(name) => {
                    let mut values = Vec::new();

                    for code in words {
                        if code.starts_with('#') {
                            break;
                        }

                        match parse_number(code) {
                            Ok(code) => {
                                values.push(code);
                            }
                            Err(_) => {
                                error!(
                                    "{}:{}: code ‘{}’ is not valid",
                                    self.path.display(),
                                    self.line_no,
                                    code,
                                );
                                return Err(ParseError::SyntaxError(self.line_no));
                            }
                        }
                    }

                    if values.is_empty() {
                        error!("{}:{}: missing code", self.path.display(), self.line_no);
                        return Err(ParseError::SyntaxError(self.line_no));
                    }

                    let dup = codes.iter().any(|c| c.name == name);

                    codes.push(Code {
                        name: name.to_owned(),
                        dup,
                        code: values,
                        line_no: self.line_no,
                    });
                }
                None => (),
            }
        }
    }

    fn read_raw_codes(&mut self) -> Result<Vec<RawCode>, ParseError> {
        let mut raw_codes = Vec::new();
        let mut raw_code = None;

        loop {
            let line = self.next_line();

            if line.is_none() {
                error!(
                    "{}:{}: unexpected end of file",
                    self.path.display(),
                    self.line_no
                );
                return Err(ParseError::SyntaxError(self.line_no));
            }

            let line = line.unwrap();

            let mut words = line.split_whitespace();

            match words.next() {
                Some("end") => {
                    if let Some("raw_codes") = words.next() {
                        if let Some(raw_code) = raw_code {
                            raw_codes.push(raw_code);
                        }
                        return Ok(raw_codes);
                    }

                    error!(
                        "{}:{}: expected 'end raw_codes', got ‘{}’",
                        self.path.display(),
                        self.line_no,
                        line,
                    );

                    return Err(ParseError::SyntaxError(self.line_no));
                }
                Some("name") => {
                    if let Some(name) = words.next() {
                        if let Some(raw_code) = raw_code {
                            raw_codes.push(raw_code);
                        }

                        let dup = raw_codes.iter().any(|c| c.name == name);

                        raw_code = Some(RawCode {
                            name: name.to_owned(),
                            dup,
                            rawir: self.read_lengths(words)?,
                            line_no: self.line_no,
                        });
                    } else {
                        error!("{}:{}: missing name", self.path.display(), self.line_no);
                        return Err(ParseError::SyntaxError(self.line_no));
                    }
                }
                Some(v) => {
                    if let Some(raw_code) = &mut raw_code {
                        let codes = self.read_lengths(line.split_whitespace())?;

                        raw_code.rawir.extend(codes);
                    } else {
                        error!(
                            "{}:{}: ‘{}’ not expected",
                            self.path.display(),
                            self.line_no,
                            v
                        );
                        return Err(ParseError::SyntaxError(self.line_no));
                    }
                }
                None => (),
            }
        }
    }

    fn read_lengths(&self, words: SplitWhitespace) -> Result<Vec<u32>, ParseError> {
        let mut rawir = Vec::new();

        for no in words {
            if no.starts_with('#') {
                break;
            }

            match parse_number(no) {
                Ok(v) if v <= u32::MAX as u64 => rawir.push(v as u32),
                _ => {
                    error!(
                        "{}:{}: invalid duration ‘{}’",
                        self.path.display(),
                        self.line_no,
                        no
                    );
                    return Err(ParseError::SyntaxError(self.line_no));
                }
            }
        }

        Ok(rawir)
    }

    fn next_line(&mut self) -> Option<String> {
        loop {
            let line = self.lines.next()?;

            self.line_no += 1;

            let trimmed = line.trim();

            if !trimmed.is_empty() && !line.starts_with('#') {
                return Some(trimmed.to_owned());
            }
        }
    }

    /// Do some sanity checks and cleanups. Returns false for invalid
    fn sanity_checks(&self, remote: &mut Remote) -> bool {
        if remote.name.is_empty() {
            error!(
                "{}:{}: missing remote name",
                self.path.display(),
                self.line_no,
            );
            return false;
        }

        if remote.gap == 0 {
            warn!(
                "{}:{}: missing gap for remote {}",
                self.path.display(),
                self.line_no,
                remote.name
            );
        }

        if remote.duty_cycle > 99 {
            warn!(
                "{}:{}: duty_cycle {} is not valid for remote {}",
                self.path.display(),
                self.line_no,
                remote.duty_cycle,
                remote.name
            );
            remote.duty_cycle = 0;
        }

        if !remote.raw_codes.is_empty() {
            remote.flags.set(Flags::RAW_CODES, true);

            if !remote.codes.is_empty() {
                error!(
                    "{}:{}: non-raw codes specified for raw remote {}",
                    self.path.display(),
                    self.line_no,
                    remote.name
                );
                return false;
            }

            return true;
        }

        if remote.flags.contains(Flags::RAW_CODES) {
            error!(
                "{}:{}: missing raw codes for remote {}",
                self.path.display(),
                self.line_no,
                remote.name
            );
            return false;
        }

        if remote.codes.is_empty() {
            error!(
                "{}:{}: missing codes for remote {}",
                self.path.display(),
                self.line_no,
                remote.name
            );
            return false;
        }

        // Can we generate a sensible irp for this remote
        if (remote.bit[0].0 == 0 && remote.bit[0].1 == 0)
            || (remote.bit[1].0 == 0 && remote.bit[1].1 == 0)
        {
            error!(
                "{}:{}: no bit encoding provided",
                self.path.display(),
                self.line_no,
            );
            return false;
        }

        if (remote.pre_data & !gen_mask(remote.pre_data_bits)) != 0 {
            warn!("{}:{}: invalid pre_data", self.path.display(), self.line_no);
            remote.pre_data &= gen_mask(remote.pre_data_bits);
        }

        if (remote.post_data & !gen_mask(remote.post_data_bits)) != 0 {
            warn!(
                "{}:{}: invalid post_data",
                self.path.display(),
                self.line_no,
            );
            remote.post_data &= gen_mask(remote.post_data_bits);
        }

        for code in &mut remote.codes {
            for code in &mut code.code {
                if (*code & !gen_mask(remote.bits)) != 0 {
                    warn!(
                        "{}:{}: invalid code {:#x} truncated",
                        self.path.display(),
                        self.line_no,
                        code
                    );
                    *code &= gen_mask(remote.bits);
                }
            }
        }

        if remote.flags.contains(Flags::REVERSE) {
            if remote.pre_data_bits > 0 {
                remote.pre_data = reverse(remote.pre_data, remote.pre_data_bits);
            }

            if remote.post_data_bits > 0 {
                remote.post_data = reverse(remote.post_data, remote.post_data_bits);
            }

            for code in &mut remote.codes {
                for code in &mut code.code {
                    *code = reverse(*code, remote.bits)
                }
            }
        }

        if remote.flags.contains(Flags::RC6) && remote.rc6_mask == 0 && remote.toggle_bit > 0 {
            remote.rc6_mask = 1u64 << (remote.all_bits() - remote.toggle_bit);
        }

        if remote.toggle_bit > 0 {
            if remote.toggle_bit_mask > 0 {
                warn!(
                    "{}:{}: remote {} uses both toggle_bit and toggle_bit_mask",
                    self.path.display(),
                    self.line_no,
                    remote.name
                );
            } else {
                remote.toggle_bit_mask = 1u64 << (remote.all_bits() - remote.toggle_bit);
            }
            remote.toggle_bit = 0;
        }

        true
    }
}

fn gen_mask(v: u64) -> u64 {
    if v < 64 {
        (1u64 << v) - 1
    } else {
        u64::MAX
    }
}

fn reverse(val: u64, bits: u64) -> u64 {
    let val = val.reverse_bits();

    assert!(bits <= 64);

    if bits == 64 {
        val
    } else {
        val >> (64 - bits)
    }
}

/// Parse a number like strtoull in lirc daemon
fn parse_number(val: &str) -> Result<u64, ParseIntError> {
    if let Some(hex) = val.strip_prefix("0x") {
        u64::from_str_radix(hex, 16)
    } else if let Some(hex) = val.strip_prefix("0X") {
        u64::from_str_radix(hex, 16)
    } else if let Some(oct) = val.strip_prefix('0') {
        if oct.is_empty() {
            Ok(0)
        } else {
            u64::from_str_radix(oct, 8)
        }
    } else {
        u64::from_str(val)
    }
}