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
use crate::get_irp_protocols;

#[cfg(target_os = "linux")]
use super::keymap::{open_lirc, Purpose};
use cir::{
    keymap::{Keymap, LinuxProtocol},
    lircd_conf,
};
use irp::{Irp, Message, Pronto, Vartable};
use log::{error, info, warn};
use std::{fs, path::Path};
use terminal_size::{terminal_size, Width};

pub fn transmit(args: &crate::App, transmit: &crate::Transmit) {
    let message = encode_args(&args.irp_protocols, transmit);

    if let Some(carrier) = &message.carrier {
        if *carrier == 0 {
            info!("carrier: unmodulated (no carrier)");
        } else {
            info!("carrier: {}Hz", carrier);
        }
    }
    if let Some(duty_cycle) = &message.duty_cycle {
        info!("duty cycle: {}%", duty_cycle);
    }
    info!("rawir: {}", message.print_rawir());

    #[cfg(target_os = "linux")]
    if !transmit.dry_run {
        let mut lircdev = open_lirc(&transmit.device, Purpose::Transmit);

        if !transmit.transmitters.is_empty() {
            if !lircdev.can_set_send_transmitter_mask() {
                eprintln!("error: {lircdev}: device does not support setting transmitters");

                std::process::exit(1);
            }

            let transmitter_count = match lircdev.num_transmitters() {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("error: {lircdev}: failed to get transmitter count: {e}");

                    std::process::exit(1);
                }
            };

            if let Some(t) = transmit
                .transmitters
                .iter()
                .find(|t| **t == 0 || **t > transmitter_count)
            {
                eprintln!(
                    "error: transmitter {t} not valid, device has {transmitter_count} transmitters"
                );

                std::process::exit(1);
            }

            let mask: u32 = transmit
                .transmitters
                .iter()
                .fold(0, |acc, t| acc | (1 << (t - 1)));

            info!("debug: setting transmitter mask {:#b}", mask);

            match lircdev.set_transmitter_mask(mask) {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("error: {lircdev}: failed to set transmitter mask: {e}");

                    std::process::exit(1);
                }
            }
        }

        if let Some(duty_cycle) = message.duty_cycle {
            if lircdev.can_set_send_duty_cycle() {
                log::debug!("setting {} duty cycle {}", lircdev, duty_cycle);

                if let Err(s) = lircdev.set_send_duty_cycle(duty_cycle as u32) {
                    eprintln!("error: {lircdev}: {s}");

                    std::process::exit(1);
                }
            } else {
                warn!(
                    "warning: {}: device does not support setting send duty cycle",
                    lircdev
                );
            }
        }

        if let Some(carrier) = message.carrier {
            if lircdev.can_set_send_carrier() {
                log::debug!("setting {} send carrier {}", lircdev, carrier);

                if let Err(s) = lircdev.set_send_carrier(carrier as u32) {
                    eprintln!("error: {lircdev}: {s}");

                    if carrier == 0 {
                        eprintln!("info: not all lirc devices can send unmodulated");
                    }
                    std::process::exit(1);
                }
            } else {
                eprintln!("warning: {lircdev}: device does not support setting carrier");
            }
        }

        log::debug!("transmitting {} data {}", lircdev, message.print_rawir());

        if let Err(s) = lircdev.send(&message.raw) {
            eprintln!("error: {lircdev}: {s}");
            std::process::exit(1);
        }
    }
}

fn encode_args(irp_protocols: &Path, args: &crate::Transmit) -> Message {
    let mut vars = irp::Vartable::new();

    for field in &args.arguments {
        let list: Vec<&str> = field.trim().split('=').collect();

        if list.len() != 2 {
            eprintln!("argument to --field must be X=1");
            std::process::exit(2);
        }

        let value = match if list[1].starts_with("0x") {
            i64::from_str_radix(&list[1][2..], 16)
        } else if list[1].starts_with("0o") {
            i64::from_str_radix(&list[1][2..], 8)
        } else if list[1].starts_with("0b") {
            i64::from_str_radix(&list[1][2..], 2)
        } else {
            list[1].parse()
        } {
            Ok(v) => v,
            Err(_) => {
                eprintln!("‘{}’ is not a valid number", list[1]);
                std::process::exit(2);
            }
        };

        vars.set(list[0].to_string(), value);
    }

    let (lircd_conf, keymap) = if let Some(path) = &args.keymap {
        if path.to_string_lossy().ends_with(".lircd.conf") {
            match lircd_conf::parse(path) {
                Ok(r) => {
                    if args.list_codes {
                        list_lircd_remotes(path, &r, args.remote.as_deref());

                        std::process::exit(0);
                    }

                    (Some(r), None)
                }
                Err(_) => std::process::exit(2),
            }
        } else {
            match Keymap::parse_file(path) {
                Ok(r) => {
                    if args.list_codes {
                        list_keymap_remotes(path, &r, args.remote.as_deref());

                        std::process::exit(0);
                    }

                    (None, Some(r))
                }
                Err(e) => {
                    log::error!("{e}");
                    std::process::exit(2);
                }
            }
        }
    } else {
        (None, None)
    };

    enum Part {
        Raw(Message),
        Gap(u32),
    }

    let mut part = Vec::new();

    for tx in &args.transmitables {
        match tx {
            crate::Transmitables::File(filename) => {
                let input = match fs::read_to_string(filename) {
                    Ok(s) => s,
                    Err(s) => {
                        error!("{}: {}", Path::new(filename).display(), s);
                        std::process::exit(2);
                    }
                };

                match Message::parse(&input) {
                    Ok(m) => {
                        part.push(Part::Raw(m));
                    }
                    Err(msg) => match Message::parse_mode2(&input) {
                        Ok(m) => {
                            part.push(Part::Raw(m));
                        }
                        Err((line_no, error)) => {
                            error!("{}: parse as rawir: {}", Path::new(filename).display(), msg);
                            error!(
                                "{}:{}: parse as mode2: {}",
                                Path::new(filename).display(),
                                line_no,
                                error
                            );
                            std::process::exit(2);
                        }
                    },
                }
            }
            crate::Transmitables::RawIR(rawir) => match Message::parse(rawir) {
                Ok(m) => {
                    part.push(Part::Raw(m));
                }
                Err(msg) => {
                    error!("{}", msg);
                    std::process::exit(2);
                }
            },
            crate::Transmitables::Scancode((protocol, scancode)) => {
                match encode_scancode(protocol, *scancode, args.repeats) {
                    Ok(m) => {
                        part.push(Part::Raw(m));
                    }
                    Err(msg) => {
                        error!("{}", msg);
                        std::process::exit(2);
                    }
                }
            }
            crate::Transmitables::Gap(gap) => {
                part.push(Part::Gap(*gap));
            }
            crate::Transmitables::Pronto(pronto) => {
                let p = match Pronto::parse(pronto) {
                    Ok(pronto) => pronto,
                    Err(err) => {
                        eprintln!("error: {err}");
                        std::process::exit(2);
                    }
                };

                let m = p.encode(args.repeats as usize);

                part.push(Part::Raw(m));
            }
            crate::Transmitables::Irp(irp_notation) => {
                let mut protocols = &Vec::new();

                match get_irp_protocols(irp_protocols) {
                    Ok(res) => {
                        protocols = res;
                    }
                    Err(e) => {
                        log::error!("{}: {e}", irp_protocols.display());
                    }
                };

                let irp_notation = match protocols.iter().find(|e| {
                    !e.decode_only && (&e.name == irp_notation || e.alt_name.contains(irp_notation))
                }) {
                    Some(e) => &e.irp,
                    None => irp_notation,
                };

                log::debug!("transmit IRP: {irp_notation}");

                let irp = match Irp::parse(irp_notation) {
                    Ok(m) => m,
                    Err(s) => {
                        eprintln!("unable to parse irp ‘{}’: {s}", irp_notation);
                        std::process::exit(2);
                    }
                };
                match irp.encode_raw(vars.clone(), args.repeats) {
                    Ok(m) => {
                        part.push(Part::Raw(m));
                    }
                    Err(s) => {
                        eprintln!("error: {s}");
                        std::process::exit(2);
                    }
                }
            }
            crate::Transmitables::Code(code) => {
                if let Some(lircd_conf) = &lircd_conf {
                    match lircd_conf::encode(lircd_conf, args.remote.as_deref(), code, args.repeats)
                    {
                        Ok(m) => {
                            part.push(Part::Raw(m));
                        }
                        Err(s) => {
                            eprintln!("error: {s}");
                            std::process::exit(2);
                        }
                    }
                } else if let Some(keymap) = &keymap {
                    match cir::keymap::encode(keymap, args.remote.as_deref(), code, args.repeats) {
                        Ok(m) => {
                            part.push(Part::Raw(m));
                        }
                        Err(s) => {
                            eprintln!("error: {s}");
                            std::process::exit(2);
                        }
                    }
                } else {
                    eprintln!("error: missing --keymap argument for --keycode");
                    std::process::exit(2);
                }
            }
        }
    }

    let mut message = Message::new();
    let mut gap = 125000;

    for part in part {
        match part {
            Part::Gap(v) => {
                gap = v;
            }
            Part::Raw(raw) => {
                if !message.raw.is_empty() && !message.has_trailing_gap() {
                    message.raw.push(gap);
                }

                message.extend(&raw);
            }
        }
    }

    if message.raw.is_empty() {
        error!("nothing to send");
        std::process::exit(2);
    }

    if !message.has_trailing_gap() {
        message.raw.push(gap);
    }

    message
}

fn list_keymap_remotes(filename: &Path, remotes: &[Keymap], needle: Option<&str>) {
    let size = terminal_size();

    if size.is_some() {
        println!("\nAvailable remotes and codes in {}:\n", filename.display());
    }

    let mut remote_found = false;

    for remote in remotes {
        if let Some(needle) = needle {
            if remote.name != needle {
                continue;
            }
        }
        remote_found = true;

        let mut codes: Vec<_> = remote
            .scancodes
            .values()
            .map(|code| code.as_str())
            .chain(remote.raw.iter().map(|code| code.keycode.as_str()))
            .collect();

        codes.sort();

        if let Some((Width(term_witdh), _)) = size {
            let mut pos = 2;
            let mut res = String::new();
            let mut first = true;

            for code in codes {
                if first {
                    first = false
                } else {
                    res.push_str(", ");
                }

                if pos + code.len() + 2 < term_witdh as usize {
                    res.push_str(code);
                    pos += code.len() + 2;
                } else {
                    res.push_str("\n  ");
                    res.push_str(code);
                    pos = code.len() + 4;
                }
            }

            println!("Remote:\n  {}\nCodes:\n  {}", remote.name, res);
        } else {
            for code in codes {
                println!("{code}");
            }
        }
    }

    if !remote_found {
        error!("not remote found");
    }
}

fn list_lircd_remotes(filename: &Path, remotes: &[lircd_conf::Remote], needle: Option<&str>) {
    let size = terminal_size();

    if size.is_some() {
        println!("\nAvailable remotes and codes in {}:\n", filename.display());
    }

    let mut remote_found = false;

    for remote in remotes {
        if let Some(needle) = needle {
            if remote.name != needle {
                continue;
            }
        }
        remote_found = true;

        let mut codes: Vec<_> = remote
            .codes
            .iter()
            .map(|code| code.name.as_str())
            .chain(remote.raw_codes.iter().map(|code| code.name.as_str()))
            .collect();

        codes.sort();

        if let Some((Width(term_witdh), _)) = size {
            let mut pos = 2;
            let mut res = String::new();
            let mut first = true;

            for code in codes {
                if first {
                    first = false
                } else {
                    res.push_str(", ");
                }

                if pos + code.len() + 2 < term_witdh as usize {
                    res.push_str(code);
                    pos += code.len() + 2;
                } else {
                    res.push_str("\n  ");
                    res.push_str(code);
                    pos = code.len() + 4;
                }
            }

            println!("Remote:\n  {}\nCodes:\n  {}", remote.name, res);
        } else {
            for code in codes {
                println!("{code}");
            }
        }
    }

    if !remote_found {
        error!("not remote found");
    }
}

fn encode_scancode(protocol: &str, mut scancode: u64, repeats: u64) -> Result<Message, String> {
    let Some(linux) = LinuxProtocol::find_like(protocol) else {
        return Err(format!("protocol {protocol} is not known"));
    };

    if linux.irp.is_none() {
        return Err(format!("protocol {protocol} is cannot be encoded"));
    }

    let masked = scancode & linux.scancode_mask as u64;

    if masked != scancode {
        warn!("scancode {scancode:#x} masked to {masked:#x}");
        scancode = masked;
    }

    log::debug!(
        "using irp {} for linux protocol {}",
        linux.irp.unwrap(),
        linux.name
    );

    let irp = Irp::parse(linux.irp.unwrap()).unwrap();

    let mut vars = Vartable::new();

    vars.set("CODE".into(), scancode as i64);

    irp.encode_raw(vars, repeats)
}