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
//! STM32 Serial Bootloader.
//!
//! Base on AN3155

use core::fmt::Debug;
use core::marker::PhantomData;

use log::{trace, debug, info, error};

use nb::block;
use thiserror::Error;

use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::serial::{Read, Write};

#[cfg(feature = "linux")]
extern crate linux_embedded_hal;
#[cfg(feature = "linux")]
pub mod linux;

pub mod protocol;
use protocol::*;


/// SerialPort trait wrapping embedded-hal with rts/dtr commands
pub trait SerialPort<E>: Write<u8, Error = E> + Read<u8, Error = E> {
    fn set_rts(&mut self, level: bool) -> Result<(), E>;
    fn set_dtr(&mut self, level: bool) -> Result<(), E>;
}

#[derive(Error, Clone, PartialEq, Debug)]
pub enum Error<SerialError: Debug> {
    #[error("Serial device error: {0:?}")]
    Serial(SerialError),
    #[error("Nack")]
    Nack,
    #[error("NoAck")]
    NoAck,
    #[error("Timeout")]
    Timeout,
    #[error("InvalidResponse")]
    InvalidResponse,
    #[error("BufferLength")]
    BufferLength,
    #[error("Io error: {0:?}")]
    Io(std::io::ErrorKind),
}

impl<SerialError: Debug> From<SerialError> for Error<SerialError> {
    fn from(e: SerialError) -> Self {
        Self::Serial(e)
    }
}

#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "structopt", derive(structopt::StructOpt))]
pub struct Options {
    /// Do not reset the device on connection
    #[cfg_attr(feature = "structopt", structopt(long))]
    pub no_reset: bool,

    /// Timeout to wait for bootloader responses
    #[cfg_attr(feature = "structopt", structopt(long, default_value = "100"))]
    pub response_timeout_ms: u32,

    /// Period to poll for bootloader responses
    #[cfg_attr(feature = "structopt", structopt(long, default_value = "10"))]
    pub poll_delay_ms: u32,

    /// Period to wait for bootloader init before sending init character
    #[cfg_attr(feature = "structopt", structopt(long, default_value = "100"))]
    pub init_delay_ms: u32,

    /// Disable progress bars during operations
    #[cfg_attr(feature = "structopt", structopt(long))]
    pub no_progress: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            no_reset: false,
            no_progress: false,
            response_timeout_ms: 100,
            poll_delay_ms: 10,
            init_delay_ms: 100,
        }
    }
}

pub struct Programmer<P, D, E> {
    options: Options,
    port: P,
    delay: D,
    _err: PhantomData<E>,
}

impl<P, D, E> Programmer<P, D, E>
where
    P: SerialPort<E>,
    D: DelayMs<u32>,
    E: core::fmt::Debug,
{
    /// Create a new programmer instance and connect to the attached bootloader
    pub fn new(port: P, delay: D, options: Options) -> Result<Self, Error<E>> {
        let mut s = Self {
            options,
            port,
            delay,
            _err: PhantomData,
        };

        s.init()?;

        Ok(s)
    }

    // Initialise the programmer/bootloader
    fn init(&mut self) -> Result<(), Error<E>> {
        // First, reset device
        debug!("Resetting device");

        self.reset(true)?;

        debug!("Sending discovery character");

        // Then, send discovery character
        block!(self.port.write(UART_DISC)).unwrap();
        block!(self.port.flush()).unwrap();

        // Wait for a response
        debug!("Awaiting bootloader response");
        let _ = self.await_ack();

        // Wait for bootloader to think a little
        self.delay.delay_ms(100);

        // Read info
        debug!("Reading bootloader info");
        let version = self.info()?;
        debug!("Bootloader version: 0x{:02x}", version);

        self.delay.delay_ms(100);

        // Return ok
        Ok(())
    }

    /// Fetch bootloader info byte
    // TODO: there's more useful info than just this?
    pub fn info(&mut self) -> Result<u8, Error<E>> {
        let mut data = [0u8; 12];

        // Write command
        self.write_cmd(Command::Get)?;

        // Await ack
        self.await_ack()?;

        // Read comand length
        let n = self.read_char()? as usize + 1;

        debug!("Reading {} bytes", n);

        if data.len() < n {
            error!("RX buffer too short");
            return Err(Error::BufferLength);
        }

        // Read data
        for i in 0..n {
            data[i] = self.read_char()?;
        }

        // Await final ack
        self.await_ack()?;

        debug!("Received: 0x{:02x?}", &data[..n]);

        Ok(data[0])
    }

    /// Erase pages by page offset and count
    pub fn erase(&mut self, page_offset: u8, page_count: u8) -> Result<(), Error<E>> {

        debug!("Erasing {} pages from index {}", page_count, page_offset);
        let pages: Vec<u8> = (page_count..page_offset+page_count).collect();

        self.erase_pages(&pages)
    }

    /// Erase pages by page number
    pub fn erase_pages(&mut self, pages: &[u8]) -> Result<(), Error<E>> {
        // Write command
        self.write_cmd(Command::Erase)?;
        self.await_ack()?;

        // Write number of pages
        let len = (pages.len() - 1) as u8;
        block!(self.port.write(len))?;

        // Write page list
        self.write_bytes_csum(pages)?;

        self.await_ack()
    }

    /// Erase the entire flash
    pub fn erase_all(&mut self) -> Result<(), Error<E>> {
        // Write command
        self.write_cmd(Command::Erase)?;
        self.await_ack()?;

        self.write_bytes(&[0xFF, 0x00])?;
        self.await_ack()?;

        Ok(())
    }

    /// Read memory from the device
    pub fn read(&mut self, addr: u32, data: &mut [u8]) -> Result<(), Error<E>> {
        let mut index = 0;
        
        // Setup progress bar _if_ enabled
        #[cfg(feature="indicatif")]
        let mut p = match !self.options.no_progress {
            true => {
                let pb = indicatif::ProgressBar::new(data.len() as u64);

                pb.set_style(indicatif::ProgressStyle::default_bar()
                    .template("{spinner:.green} [{elapsed_precise}] [{bar:80.cyan/blue}] {bytes}/{total_bytes} ({eta})")
                    .progress_chars("#>-"));

                Some(pb)
            },
            _ => None,
        };

        for chunk in data.chunks_mut(MAX_CHUNK as usize) {
            debug!("Read chunk at 0x{:08x}, length: {}", addr + index as u32, chunk.len());

            self.read_mem_block(addr + index as u32, &mut chunk[..])?;

            index += chunk.len();

            // Update progress bar (if enabled)
            #[cfg(feature="indicatif")]
            if let Some(p) = &mut p {
                p.inc(chunk.len() as u64)
            }
        }

        Ok(())
    }

    fn read_mem_block(&mut self, addr: u32, data: &mut [u8]) -> Result<(), Error<E>> {
        assert!(data.len() <= 256, "block size must be less than 256 bytes");

        // Write read command and await ack
        self.write_cmd(Command::ReadMemory)?;
        self.await_ack()?;
        

        // Write start address + xor checksum and await ack
        let addr = [(addr >> 24) as u8, (addr >> 16) as u8, (addr >> 8) as u8, addr as u8];
        let addr_csum = addr[0] ^ addr[1] ^ addr[2] ^ addr[3];

        for a in &addr {
            block!(self.port.write(*a))?;
        }
        block!(self.port.write(addr_csum))?;
        block!(self.port.flush())?;

        self.await_ack()?;


        // Write read length and checksum and await ack
        let len = (data.len() - 1) as u8;
        self.write_bytes(&[len, !len])?;

        self.await_ack()?;

        // Read response data
        for i in 0..data.len() {
            data[i] = self.read_char()?;
        }

        Ok(())
    }

    /// Write memory to the device
    pub fn write(&mut self, addr: u32, data: &[u8]) -> Result<(), Error<E>> {
        let mut index = 0;

        // Setup progress bar _if_ enabled
        #[cfg(feature="indicatif")]
        let mut p = match !self.options.no_progress {
            true => {
                let pb = indicatif::ProgressBar::new(data.len() as u64);

                pb.set_style(indicatif::ProgressStyle::default_bar()
                    .template("{spinner:.green} [{elapsed_precise}] [{bar:80.cyan/blue}] {bytes}/{total_bytes} ({eta})")
                    .progress_chars("#>-"));

                Some(pb)
            },
            _ => None,
        };

        for chunk in data.chunks(MAX_CHUNK as usize) {
            debug!("Write chunk at 0x{:08x}, length: {}", addr + index as u32, chunk.len());

            self.write_mem_block(addr + index as u32, &chunk[..])?;

            index += chunk.len();

            // Update progress bar (if enabled)
            #[cfg(feature="indicatif")]
            if let Some(p) = &mut p {
                p.inc(chunk.len() as u64)
            }
        }

        Ok(())
    }

    fn write_mem_block(&mut self, addr: u32, data: &[u8]) -> Result<(), Error<E>> {
        assert!(data.len() <= 256, "block size must be less than 256 bytes");

        // Write read command and await ack
        self.write_cmd(Command::WriteMemory)?;
        self.await_ack()?;
        

        // Write start address + xor checksum and await ack
        let addr = [(addr >> 24) as u8, (addr >> 16) as u8, (addr >> 8) as u8, addr as u8];
        let addr_csum = addr[0] ^ addr[1] ^ addr[2] ^ addr[3];

        for a in &addr {
            block!(self.port.write(*a))?;
        }
        block!(self.port.write(addr_csum))?;
        block!(self.port.flush())?;

        self.await_ack()?;


        // Set write length and checksum and await ack
        let len = (data.len() - 1) as u8;
        let mut data_csum = len;

        block!(self.port.write(len))?;
        for d in data {
            data_csum ^= *d;
            block!(self.port.write(*d))?;
        }
        block!(self.port.write(data_csum))?;

        self.await_ack()?;


        Ok(())
    }

    /// Reset the device using RTS while asserting DTR entering the bootloading or application
    pub fn reset(&mut self, bootloader: bool) -> Result<(), Error<E>> {
        // Assert RTS to reset the device
        self.port.set_rts(true)?;

        // Wait a moment for the device to turn off
        self.delay.delay_ms(10u32);

        if bootloader {
            // DTR signals to use bootloader
            self.port.set_dtr(true)?;
        }

        // RTS re-enables device
        self.port.set_rts(false)?;

        // Wait for bootloader or app to start
        self.delay.delay_ms(self.options.init_delay_ms);

        if bootloader {
            // De-assert DTR
            self.port.set_dtr(false)?;
        }

        Ok(())
    }

    /// Fetch device chip ID (not-working)
    pub fn chip_id(&mut self) -> Result<u16, Error<E>> {
        // Write GetID command
        self.write_cmd(Command::GetId)?;
        
        // Await ACK
        self.await_ack()?;

        // Read N (static sized)
        let n = self.read_char()? as usize + 1;

        debug!("Reading {} byte chip ID", n);

        // Read chip ID
        let mut v: u16 = 0;
        for i in 0..n {
            let c = self.read_char()?;
            v |= (c as u16) << (i * 8);
        }

        // Await ACK
        self.await_ack()?;

        Ok(v)
    }

    /// Write a bootloader command to the device
    pub fn write_cmd(&mut self, command: Command) -> Result<(), Error<E>> {
        // Write command
        let c1 = command.clone() as u8;
        let c2 = !c1;

        debug!("Writing command {:?} [0x{:02x}, 0x{:02x}]", command, c1, c2);

        block!(self.port.write(c1))?;
        block!(self.port.write(c2))?;
        block!(self.port.flush())?;

        Ok(())
    }

    pub fn write_bytes(&mut self, data: &[u8]) -> Result<(), Error<E>> {

        debug!("Writing bytes: 0x{:02x?}", data);

        for d in data {
            block!(self.port.write(*d))?;
        }

        block!(self.port.flush())?;

        Ok(())
    }

    /// Write data with xor checksum
    pub fn write_bytes_csum(&mut self, data: &[u8]) -> Result<(), Error<E>> {
        let mut csum = 0x00;
        for d in data {
            csum ^= *d;
        }

        info!("Writing data with checksum: {:02x?} ({:02x})", data, csum);

        for d in data {
            block!(self.port.write(*d))?;
        }

        block!(self.port.write(csum))?;
        block!(self.port.flush())?;

        Ok(())
    }

    /// Read a single character from the device
    pub fn read_char(&mut self) -> Result<u8, Error<E>> {
        let mut t = 0;

        loop {
            // Attempt to read from serial port
            match self.port.read() {
                Err(nb::Error::WouldBlock) => (),
                Err(nb::Error::Other(e)) => return Err(e.into()),
                Ok(v) => return Ok(v)
            };

            // Wait for delay period
            self.delay.delay_ms(self.options.poll_delay_ms);
            t += self.options.poll_delay_ms;

            if t > self.options.response_timeout_ms {
                error!("Receive timeout");
                return Err(Error::Timeout);
            }
        }
    }

    /// Await an ack from the bootloader
    fn await_ack(&mut self) -> Result<(), Error<E>> {
        let v = self.read_char()?;
        match v {
            UART_ACK => {
                trace!("Received ACK!");
                Ok(())
            },
            UART_NACK => {
                trace!("Received NACK?!");
                Err(Error::Nack)
            },
            _ => {
                error!("Unexpected response: 0x{:02x}", v);
                Err(Error::InvalidResponse)
            }
        }
    }
}