yapu 0.1.0-alpha.2

AN3155-compliant programmer
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
//! # YAPU: Yet Another Programmer via USART
//!
//! AN3155-compliant programmer
//!
//! [![license][license badge]][repo]
//! [![crates.io version][crates.io version badge]][crate]
//!
//! The library implements the protocols used by AN3155-compliant bootloaders
//! and offers device discovery. Check [repo README][repo] for more details.
//!
//! A binary `yapu` is also shipped in the [crate][crate] for common use.
//!
//! [repo]: https://github.com/yapu-rs/yapu
//! [crate]: https://crates.io/crates/yapu
//!
//! [license badge]: https://img.shields.io/github/license/yapu-rs/yapu?style=flat
//! [crates.io version badge]: https://img.shields.io/crates/v/yapu?style=flat

mod probe;
mod protocol;

pub use probe::{Baudrate, Identify};
pub use probe::{Probe, ProbeBuilder, Signal, SignalScheme, SignalSchemeBuilder};

// Common requests and responses in the protocol
pub use protocol::{Address, Command, Opcode, Reply, Size};
pub use protocol::{Bootloader, Id, Version};
pub use protocol::{Erase, ExtendedErase};

// Slice and slice items defined in the protocol
pub use protocol::{
    Byte, Data, ExtendedPageNo, ExtendedPageNos, PageNo, PageNos, SectorNo, SectorNos,
};
pub use protocol::{Slice, SliceItem};

use binrw::io::NoSeek;
use binrw::meta::{ReadEndian, WriteEndian};
use binrw::{BinRead, BinWrite};
use log::trace;
use serialport::ClearBuffer;
pub use serialport::SerialPort;
use serialport::{DataBits, FlowControl, Parity, StopBits};

/// Error
#[derive(Debug)]
pub enum Error {
    NAck,
    Unidentified,
    Protocol(protocol::Error),
    Io(std::io::Error),
    Serial(serialport::Error),
    Frame(binrw::Error),
}

impl Error {
    pub fn is_nack(&self) -> bool {
        matches!(self, Self::NAck)
    }
    pub fn is_unidentified(&self) -> bool {
        matches!(self, Self::Unidentified)
    }

    pub fn is_protocol_conversion(&self) -> bool {
        matches!(self, Self::Protocol(..))
    }
    pub fn as_protocol_conversion(&self) -> Option<&protocol::Error> {
        match self {
            Self::Protocol(e) => Some(e),
            _ => None,
        }
    }
    pub fn into_protocol_conversion(self) -> Option<protocol::Error> {
        match self {
            Self::Protocol(e) => Some(e),
            _ => None,
        }
    }

    pub fn is_io_error(&self) -> bool {
        matches!(self, Self::Io(..))
    }
    pub fn as_io_error(&self) -> Option<&std::io::Error> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
    pub fn into_io_error(self) -> Option<std::io::Error> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }

    pub fn is_serial_error(&self) -> bool {
        matches!(self, Self::Serial(..))
    }
    pub fn as_serial_error(&self) -> Option<&serialport::Error> {
        match self {
            Self::Serial(e) => Some(e),
            _ => None,
        }
    }
    pub fn into_serial_error(self) -> Option<serialport::Error> {
        match self {
            Self::Serial(e) => Some(e),
            _ => None,
        }
    }

    pub fn is_frame_error(&self) -> bool {
        matches!(self, Self::Frame(..))
    }
    pub fn as_frame_error(&self) -> Option<&binrw::Error> {
        match self {
            Self::Frame(e) => Some(e),
            _ => None,
        }
    }
    pub fn into_frame_error(self) -> Option<binrw::Error> {
        match self {
            Self::Frame(e) => Some(e),
            _ => None,
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NAck => write!(f, "negative ack"),
            Self::Unidentified => write!(f, "cannot identify device"),
            Self::Protocol(e) => write!(f, "protocol conversion error: {}", e),
            Self::Io(e) => write!(f, "io error: {}", e),
            Self::Serial(e) => write!(f, "serial error: {}", e),
            Self::Frame(e) => write!(f, "frame error: {}", e),
        }
    }
}

impl From<protocol::Error> for Error {
    fn from(value: protocol::Error) -> Self {
        Self::Protocol(value)
    }
}

impl From<std::io::Error> for Error {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

impl From<serialport::Error> for Error {
    fn from(value: serialport::Error) -> Self {
        Self::Serial(value)
    }
}

impl From<binrw::Error> for Error {
    fn from(value: binrw::Error) -> Self {
        Self::Frame(value)
    }
}

impl std::error::Error for Error {}

type Result<T> = std::result::Result<T, Error>;

/// AN3155-compliant programmer
#[derive(Debug)]
pub struct Programmer {
    port: Box<dyn SerialPort>,
    probe: Probe,
}

impl Programmer {
    /// Reads all contents from the device.
    ///
    /// Not recommended to use.
    pub fn read_all(&mut self) -> Result<Vec<u8>> {
        let mut buf = Vec::new();
        let result = self.port.read_to_end(&mut buf);
        match result {
            Ok(_) => Ok(buf),
            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok(buf),
            Err(e) => Err(e.into()),
        }
    }

    /// Opens a serial port by its name and configures it according to a probe.
    pub fn port(path: impl AsRef<str>, probe: &Probe) -> Result<Box<dyn SerialPort>> {
        let port = serialport::new(path.as_ref(), probe.baudrate())
            .data_bits(DataBits::Eight)
            .parity(Parity::Even)
            .stop_bits(StopBits::One)
            .flow_control(FlowControl::None)
            .timeout(probe.timeout())
            .open()?;
        Ok(port)
    }

    /// Creates a programmer from an existing serial port without handshaking.
    pub fn attach(port: Box<dyn SerialPort>, probe: &Probe) -> Self {
        Self {
            port,
            probe: probe.clone(),
        }
    }

    /// Creates a programmer from a port name and tries to identify.
    pub fn open(path: impl AsRef<str>, probe: &Probe) -> Result<Self> {
        let port = Self::port(path.as_ref(), probe)?;
        let mut programmer = Self {
            port,
            probe: probe.clone(),
        };
        match probe.identify() {
            Identify::Handshake => {
                programmer.identify()?;
            }
            Identify::Get => {
                programmer.send_command(Command::Get())?;
            }
        }
        Ok(programmer)
    }

    /// Sends serializable [`BinWrite`] data to the underlying port.
    pub fn send<T: for<'b> BinWrite<Args<'b> = ()> + WriteEndian>(
        &mut self,
        data: T,
    ) -> Result<()> {
        let mut wrapper = NoSeek::new(&mut self.port);
        data.write(&mut wrapper)?;
        Ok(())
    }

    /// Sends serializable [`BinWrite`] data through reliable channels.
    ///
    /// Unlike [`Self::send`], the sender expects a reply from the controller.
    pub fn send_reliable<T: for<'b> BinWrite<Args<'b> = ()> + WriteEndian>(
        &mut self,
        data: T,
    ) -> Result<()> {
        let mut wrapper = NoSeek::new(&mut self.port);
        data.write(&mut wrapper)?;
        let reply: Reply = Reply::read(&mut wrapper)?;
        trace!("received reliable reply: {:?}", reply);
        match reply {
            Reply::NAck => Err(Error::NAck),
            Reply::Ack => Ok(()),
        }
    }

    /// Receives serializable [`BinRead`] data from the underlying port.
    pub fn recv<T: for<'b> BinRead<Args<'b> = ()> + ReadEndian>(&mut self) -> Result<T> {
        let mut wrapper = NoSeek::new(&mut self.port);
        let data = T::read(&mut wrapper)?;
        Ok(data)
    }

    /// Receives serializable [`BinRead`] data through reliable channels.
    pub fn recv_reliable<T: for<'b> BinRead<Args<'b> = ()> + ReadEndian>(&mut self) -> Result<T> {
        let mut wrapper = NoSeek::new(&mut self.port);
        let data = T::read(&mut wrapper)?;
        self.send_reliable(())?;
        Ok(data)
    }

    /// Sends a [`Command`] defined in the protocol.
    pub fn send_command(&mut self, command: Command) -> Result<()> {
        match command {
            Command::Read { address, size } => {
                self.send_reliable(Opcode::READ)?;
                self.send_reliable(address)?;
                self.send_reliable(size)
            }
            Command::Write { address, data } => {
                self.send_reliable(Opcode::WRITE)?;
                self.send_reliable(address)?;
                self.send_reliable(data)
            }
            Command::Erase(erase) => {
                self.send_reliable(Opcode::ERASE)?;
                self.send_reliable(erase)
            }
            Command::ExtendedErase(erase) => {
                self.send_reliable(Opcode::EXTENDED_ERASE)?;
                self.send_reliable(erase)
            }
            other => self.send_reliable(other),
        }
    }

    /// Changes a signal value of the underlying port.
    pub fn set_signal(&mut self, signal: Signal, active: bool) -> Result<()> {
        let raw = signal.raw_level(active);
        match signal {
            Signal::Rts { .. } => self.port.write_request_to_send(raw)?,
            Signal::Dtr { .. } => self.port.write_data_terminal_ready(raw)?,
        }
        Ok(())
    }

    /// Changes boot signal value of the underlying port.
    pub fn set_boot(&mut self, active: bool) -> Result<()> {
        if let Some(signal) = self.probe.signal_boot() {
            self.set_signal(signal, active)?;
        }
        Ok(())
    }

    /// Changes reset signal value of the underlying port.
    pub fn set_reset(&mut self, active: bool) -> Result<()> {
        if let Some(signal) = self.probe.signal_reset() {
            self.set_signal(signal, active)?;
        }
        Ok(())
    }

    /// Resets the device.
    pub fn reset(&mut self) -> Result<()> {
        if self.probe.signal_reset().is_some() {
            self.set_reset(false)?;
            self.set_reset(true)?;
            std::thread::sleep(self.probe.reset_for());
            self.set_reset(false)?;
        }
        Ok(())
    }

    fn identify(&mut self) -> Result<()> {
        let mut retries = 0;
        self.set_boot(true)?;
        while retries < self.probe.max_attempts() {
            self.reset()?;
            self.port.clear(ClearBuffer::All)?;
            match self.send_reliable(Command::Synchronize) {
                Ok(_) => {
                    self.set_boot(false)?;
                    self.port.clear(ClearBuffer::All)?;
                    return Ok(());
                }
                _ => {}
            }
            retries += 1;
        }
        Err(Error::Unidentified)
    }

    /// Discovers compliant devices using a probe.
    pub fn discover(probe: &Probe) -> Result<Vec<Self>> {
        let ports = serialport::available_ports()?
            .into_iter()
            .filter_map(|s| Self::open(s.port_name, probe).ok())
            .collect();
        Ok(ports)
    }

    /// Reads bootloader information.
    pub fn read_bootloader(&mut self) -> Result<Bootloader> {
        self.send_command(Command::Get())?;
        let bootloader: Bootloader = self.recv_reliable()?;
        Ok(bootloader)
    }

    /// Reads version.
    pub fn read_version(&mut self) -> Result<Version> {
        self.send_command(Command::Version())?;
        let version: Version = self.recv_reliable()?;
        Ok(version)
    }

    /// Reads chip ID.
    pub fn read_id(&mut self) -> Result<Id> {
        self.send_command(Command::Id())?;
        let id: Id = self.recv_reliable()?;
        Ok(id)
    }

    /// Reads memory at specific region.
    pub fn read_memory(&mut self, address: impl Into<Address>, size: Size) -> Result<Data> {
        self.send_command(Command::Read {
            address: address.into(),
            size,
        })?;
        let mut data = vec![0u8; size.into()];
        self.port.read_exact(&mut data)?;
        Ok(data.try_into().unwrap())
    }

    /// Writes memory at specific region.
    pub fn write_memory<'a, D>(&mut self, address: impl Into<Address>, data: Data) -> Result<()> {
        self.send_reliable(Command::Write {
            address: address.into(),
            data,
        })?;
        Ok(())
    }

    /// Gets the underlying serial port.
    pub fn inner(&self) -> &Box<dyn SerialPort> {
        &self.port
    }

    /// Gets the underlying serial port and drops the programmer.
    pub fn into_inner(self) -> Box<dyn SerialPort> {
        self.port
    }
}