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
//! Ebyte module control.

#![doc = include_str!("../README.md")]

use crate::config::StopBits;
use crate::{cli::Mode, config::Config};
use anyhow::Context;
use anyhow::Result;
use cli::App;
use ebyte_e32::{parameters::Parameters, Ebyte};
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::digital::v2::InputPin;
use embedded_hal::digital::v2::OutputPin;
use embedded_hal::prelude::*;
use embedded_hal::serial;
use linux_embedded_hal::serial_core::BaudRate;
use linux_embedded_hal::serial_core::CharSize;
use linux_embedded_hal::serial_core::FlowControl;
use linux_embedded_hal::serial_core::PortSettings;
use linux_embedded_hal::serial_core::SerialPort;
use linux_embedded_hal::serial_unix::TTYPort;
use linux_embedded_hal::sysfs_gpio::Direction;
use linux_embedded_hal::sysfs_gpio::Pin;
use linux_embedded_hal::Delay;
use nb::block;
use rustyline::{error::ReadlineError, Editor};
use std::fmt::Debug;
use std::fs::read_to_string;
use std::io::{self, Write};

/// Configuration from `Config.toml`.
pub mod config;

/// Command line interface.
pub mod cli;

/// Load a configuration from `Config.toml`,
/// returning an error if something goes wrong.
///
/// # Errors
/// Opening "Config.toml" and parsing it may fail, returning error.
pub fn load_config() -> Result<Config> {
    let config = read_to_string("Config.toml").context("Failed to open Config.toml")?;
    toml::from_str(&config).context("Failed to parse config")
}

/// Setup the hardware, then load some parameters,
/// update them if needed, then listen, send, or read model data.
///
/// # Panics
/// Failed initialization of the module driver
/// or communicating with the module may cause a panic.
pub fn process(config: Config, args: App) -> anyhow::Result<()> {
    let baud_rate = BaudRate::from_speed(config.baudrate as usize);
    let stop_bits = StopBits::try_from(config.stop_bits)
        .context("Failed to parse stop bits")?
        .into();
    let settings: PortSettings = PortSettings {
        baud_rate,
        char_size: CharSize::Bits8,
        parity: config.parity.into(),
        stop_bits,
        flow_control: FlowControl::FlowNone,
    };
    let mut serial = TTYPort::open(&config.serial_path).unwrap();
    serial
        .configure(&settings)
        .context("Failed to set up serial port")?;
    let serial = linux_embedded_hal::Serial(serial);

    let aux = Pin::new(config.aux_pin);
    aux.set_direction(Direction::In)
        .context("Failed to open AUX pin")?;
    let aux = linux_embedded_hal::Pin(aux);

    let m0 = Pin::new(config.m0_pin);
    m0.set_direction(Direction::Out)
        .context("Failed to open m0 pin")?;
    let m0 = linux_embedded_hal::Pin(m0);

    let m1 = Pin::new(config.m1_pin);
    m1.set_direction(Direction::Out)
        .context("Failed to open m1 pin")?;
    let m1 = linux_embedded_hal::Pin(m1);

    let mut ebyte = Ebyte::new(serial, aux, m0, m1, Delay).expect("Failed to initialize driver");

    let old_params = ebyte
        .parameters()
        .expect("Failed to read current parameters");
    println!("Loaded parameters: {old_params:#?}");

    let new_params = Parameters::from(&args);

    if new_params == old_params {
        println!("Leaving parameters unchanged");
    } else {
        println!("Updating parameters (persistence: {:?})", args.persistence);
        ebyte
            .set_parameters(&new_params, args.persistence)
            .expect("Failed to set new parameters");
        let current_params = ebyte
            .parameters()
            .expect("Failed to read current parameters");
        if current_params != new_params {
            eprintln!("Error: parameters unchanged: {current_params:#?}");
        }
    }

    match args.mode {
        Mode::Send => {
            send(ebyte);
            Ok(())
        }
        Mode::ReadModelData => {
            println!("Reading model data");
            let model_data = ebyte.model_data().expect("Failed to read model data");
            println!("{model_data:#?}");
            Ok(())
        }
        Mode::Listen => loop {
            let b = block!(ebyte.read()).expect("Failed to read");
            print!("{}", b as char);
            io::stdout().flush().expect("Failed to flush");
        },
    }
}

fn send<S, Aux, M0, M1, D>(mut ebyte: Ebyte<S, Aux, M0, M1, D, ebyte_e32::mode::Normal>)
where
    S: serial::Read<u8> + serial::Write<u8>,
    <S as serial::Write<u8>>::Error: Debug,
    Aux: InputPin,
    M0: OutputPin,
    M1: OutputPin,
    D: DelayMs<u32>,
{
    let mut prompt = Editor::<()>::new().expect("Failed to set up prompt");
    loop {
        match prompt.readline("Enter message >> ") {
            Ok(line) => {
                if line == "exit" || line == "quit" {
                    break;
                }
                prompt.add_history_entry(&line);

                for b in line.as_bytes() {
                    block!(ebyte.write(*b)).expect("Failed to write");
                    print!("{}", *b as char);
                    io::stdout().flush().expect("Failed to flush");
                }
                block!(ebyte.write(b'\n')).expect("Failed to write");
                println!();
            }
            Err(ReadlineError::Interrupted) => {
                println!("CTRL-C");
                break;
            }
            Err(ReadlineError::Eof) => {
                println!("CTRL-D");
                break;
            }
            Err(err) => {
                println!("Error: {:?}", err);
                break;
            }
        }
    }
}