ch347_rs 0.2.1

ch347 for rust
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
use super::*;
use std::{error::Error, fmt, ops::Range};

pub enum SpiFlashCmd {
    JedecId,
    WriteEnable,
    WriteDisable,
    // status
    ReadStatus,
    // erase
    ChipErase,
    Erase4K,
    Erase32K,
    Erase64K,
    // write
    PageProgram,
    // read
    ReadData,
}

impl Into<u8> for SpiFlashCmd {
    fn into(self) -> u8 {
        match self {
            SpiFlashCmd::JedecId => 0x9F,
            SpiFlashCmd::WriteEnable => 0x06,
            SpiFlashCmd::WriteDisable => 0x04,
            // status
            SpiFlashCmd::ReadStatus => 0x05,
            // erase
            SpiFlashCmd::ChipErase => 0xC7,
            SpiFlashCmd::Erase4K => 0x20,
            SpiFlashCmd::Erase32K => 0x52,
            SpiFlashCmd::Erase64K => 0xD8,
            // write
            SpiFlashCmd::PageProgram => 0x02,
            // read
            SpiFlashCmd::ReadData => 0x03,
        }
    }
}

pub enum WriteEvent {
    Block(usize, usize),
    Finish(usize),
}

pub type WriteEventFn = fn(e: WriteEvent);

#[derive(Debug)]
pub struct StatusRes {
    pub busy: bool,
    pub wtite_enable: bool,
}

impl From<u8> for StatusRes {
    fn from(data: u8) -> StatusRes {
        let s = StatusRes {
            busy: (data & 0x01) != 0,
            wtite_enable: (data & 0x02) != 0,
        };
        return s;
    }
}

pub struct SpiFlash<T: SpiDrive + ?Sized> {
    pub drive: T,
}

#[derive(Debug)]
pub enum DetectErr {
    UnknowManufacturerID([u8; 3]),
    Other(String),
}

impl fmt::Display for DetectErr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DetectErr::UnknowManufacturerID(buf) => write!(f, "Unknow JedecID {:02X?}", buf),
            DetectErr::Other(s) => write!(f, "{}", s),
        }
    }
}

impl Into<Box<dyn Error>> for DetectErr {
    fn into(self) -> Box<dyn Error> {
        self.to_string().into()
    }
}

impl<T: SpiDrive + 'static> SpiFlash<T> {
    pub fn new(drive: T) -> SpiFlash<T> {
        SpiFlash { drive }
    }

    pub fn detect(&self) -> Result<Chip, DetectErr> {
        let mut wbuf: [u8; 4] = [SpiFlashCmd::JedecId.into(), 0x00, 0x00, 0x00];

        if let Err(e) = self.drive.transfer(&mut wbuf) {
            return Err(DetectErr::Other(format!("{}", e)));
        }

        let jedec_id = &wbuf[1..4];
        // println!("JEDEC_ID: {:02X?} ", jedec_id);

        // let manufacturer_id = jedec_id[0];

        let chip_info = match parse_jedec_id(jedec_id) {
            None => {
                return Err(DetectErr::UnknowManufacturerID(
                    jedec_id.try_into().unwrap(),
                ));
                // return Err(DetectErr::Other(format!(
                //     "Unknow JedecID: {:02X?}",
                //     jedec_id
                // )));
            }
            Some(chip_info) => chip_info,
        };

        return Ok(chip_info);
    }

    pub fn read_uuid(&self, vendor: &Vendor) -> Result<Vec<u8>, &'static str> {
        return vendor.read_uid(self);
    }

    pub fn read_status_register(
        &self,
        _vendor: &Vendor,
    ) -> Result<Box<dyn StatusRegister>, &'static str> {
        return Err("Not supported");
    }

    pub fn detect_and_print(&self) -> Result<Chip, DetectErr> {
        let chip_info = self.detect()?;

        println!("ChipInfo:");
        println!("  Manufacturer: {}", chip_info.vendor.name);
        println!("          Name: {}", chip_info.name);
        println!("      Capacity: {}", chip_info.capacity);

        return Ok(chip_info);
    }

    pub fn read(&self, addr: u32, buf: &mut [u8]) {
        buf[0] = SpiFlashCmd::ReadData.into();
        buf[1] = (addr >> 16) as u8;
        buf[2] = (addr >> 8) as u8;
        buf[3] = (addr) as u8;

        if let Err(_) = self.drive.write_after_read(4, buf.len() as u32, buf) {
            return;
        }
    }

    pub fn read_status(&self) -> Result<StatusRes, &'static str> {
        let mut buf: [u8; 2] = [SpiFlashCmd::ReadStatus.into(), 0x00];

        if let Err(_) = self.drive.transfer(&mut buf) {
            return Err("transfer fail");
        }

        Ok(StatusRes::from(buf[1]))
    }

    pub fn wait_not_busy(&self) -> Result<StatusRes, &'static str> {
        loop {
            let status = match self.read_status() {
                Err(e) => {
                    println!("{:X?}", e);
                    return Err("read_status fail");
                }
                Ok(s) => s,
            };

            if status.busy {
                continue;
            }

            return Ok(status);
        }
    }

    pub fn erase_full(&self) -> Result<(), &'static str> {
        self.wait_not_busy()?;

        let mut buf: [u8; 1] = [SpiFlashCmd::WriteEnable.into()];
        self.drive.transfer(&mut buf)?;

        let mut buf: [u8; 1] = [SpiFlashCmd::ChipErase.into()];
        self.drive.transfer(&mut buf)?;

        self.wait_not_busy()?;

        return Ok(());
    }

    pub fn write(&self, addr: u32, buf: &[u8]) -> Result<(), &'static str> {
        self.write_with_callback(|_| true, addr, buf)
    }

    pub fn write_with_callback<F>(
        &self,
        mut cbk: F,
        addr: u32,
        buf: &[u8],
    ) -> Result<(), &'static str>
    where
        F: FnMut(WriteEvent) -> bool,
    {
        self.wait_not_busy()?;

        const BLOCK_SIZE: usize = 0x100;

        for i in (0..buf.len()).step_by(BLOCK_SIZE) {
            // write enable
            let mut wbuf: [u8; 1] = [SpiFlashCmd::WriteEnable.into()];
            self.drive.transfer(&mut wbuf)?;

            let addr_offset = addr + i as u32;

            if (buf.len() - i) >= BLOCK_SIZE {
                let mut wbuf: [u8; 4 + BLOCK_SIZE] = [0; 4 + BLOCK_SIZE];

                wbuf[0] = SpiFlashCmd::PageProgram.into();
                wbuf[1] = (addr_offset >> 16) as u8;
                wbuf[2] = (addr_offset >> 8) as u8;
                wbuf[3] = addr_offset as u8;
                wbuf[4..(4 + BLOCK_SIZE)].copy_from_slice(&buf[i..(i + BLOCK_SIZE)]);
                self.drive.transfer(&mut wbuf)?;
                self.wait_not_busy()?;

                if !cbk(WriteEvent::Block(i, BLOCK_SIZE)) {
                    return Ok(());
                }
            } else {
                let mut wbuf: Vec<u8> = Vec::new();
                wbuf.extend_from_slice(&[
                    SpiFlashCmd::PageProgram.into(),
                    (addr_offset >> 16) as u8,
                    (addr_offset >> 8) as u8,
                    addr_offset as u8,
                ]);
                wbuf.extend_from_slice(&buf[i..buf.len()]);
                self.drive.transfer(&mut wbuf)?;
                self.wait_not_busy()?;

                if cbk(WriteEvent::Block(i, buf.len() - i)) {
                    return Ok(());
                }
            }
        }

        cbk(WriteEvent::Finish(buf.len()));
        return Ok(());
    }
}

pub type RegReader = fn(spi_flash: &SpiFlash<dyn SpiDrive>) -> Result<RegReadRet, &'static str>;
pub type RegWriter =
    fn(spi_flash: &SpiFlash<dyn SpiDrive>, buf: &[u8]) -> Result<(), Box<dyn Error>>;

pub enum RegLen {
    One,
    Muti(usize),
}

#[derive(Debug)]
pub enum RegReadRet {
    One(u8),
    Muti(Vec<u8>),
}

impl fmt::Display for RegReadRet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RegReadRet::One(a) => write!(f, "0x{:02X}({:04b}_{:04b})", a, a >> 4, a & 0x0F),
            RegReadRet::Muti(a) => write!(f, "{:02X?}", a),
        }
    }
}

pub struct Register {
    // pub bits: Range<usize>,
    pub name: &'static str,
    pub addr: u8,
    pub items: Option<&'static [RegisterItem]>,
    pub reader: RegReader,
    pub writer: Option<RegWriter>,
}

pub struct RegisterItem {
    pub name: &'static str,
    pub alias: &'static [&'static str],
    pub describe: &'static str,
    pub offset: u8,
    pub width: u8,
    pub access: RegisterAccess,
}

#[derive(Debug)]
pub enum RegisterAccess {
    ReadOnly,
    ReadWrite,
    ReadWriteOTP,
}

impl fmt::Display for RegisterAccess {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                RegisterAccess::ReadOnly => "Volatile, read only",
                RegisterAccess::ReadWrite => "Non-volatile writable",
                RegisterAccess::ReadWriteOTP => "Non-volatile writable (OTP)",
            }
        )
    }
}

// impl Register {
//     pub fn new(bits: Range<usize>) -> Register {
//         Register { bits }
//     }

//     pub fn new_bit(bit: usize) -> Register {
//         Register { bits: bit..bit + 1 }
//     }

//     pub fn read(self, buf: &[u8]) -> u32 {
//         read_reg_bits(buf, self.bits)
//     }

//     pub fn bit_width(&self) -> usize {
//         self.bits.len()
//     }
// }

pub struct RegisterRead<'a> {
    buf: &'a [u8],
}

impl<'a> RegisterRead<'_> {
    pub fn new(buf: &'a [u8]) -> RegisterRead {
        RegisterRead { buf }
    }

    pub fn read_bit(&self, bit: usize) -> Result<bool, &'static str> {
        let buf_index = bit / 8;
        let bit_index = bit % 8;

        let ret = if self.buf[buf_index] & (1 << bit_index) != 0 {
            true
        } else {
            false
        };

        return Ok(ret);
    }

    pub fn read_bits(&self, bits: Range<usize>) -> Result<Vec<bool>, &'static str> {
        let mut ret = Vec::new();

        for i in bits {
            let buf_index = i / 8;
            let bit_index = i % 8;

            let b = if self.buf[buf_index] & (1 << bit_index) != 0 {
                true
            } else {
                false
            };

            ret.push(b);
        }

        Ok(ret)
    }

    pub fn read_bytes(&self, bits: Range<usize>) -> Result<Vec<u8>, &'static str> {
        let mut ret = Vec::new();
        let mut b: u8 = 0;

        let bit_width = if bits.start > bits.end {
            bits.start - bits.end
        } else {
            bits.end - bits.start
        };

        for (k, i) in bits.enumerate() {
            let buf_index = i / 8;
            let bit_index = i % 8;

            b <<= 1;
            if self.buf[buf_index] & (1 << bit_index) != 0 {
                b |= 1;
            }

            if (k != 0) && (k % 8 == 0) {
                ret.push(b);
                b = 0;
            }
        }

        if (bit_width % 8) != 0 {
            ret.push(b);
        }

        Ok(ret)
    }
}