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
#![no_std]

use embedded_hal_0_2_x::blocking::i2c::{AddressMode, Write, WriteIter};
use fugit::{Duration, NanosDurationU32};

pub struct One {}
pub struct Two {}

pub trait DisplayRows {
    fn value() -> u8;
}

impl DisplayRows for One {
    fn value() -> u8 {
        0b0000
    }
}

impl DisplayRows for Two {
    fn value() -> u8 {
        0b1000
    }
}

pub struct Single {}
pub struct Double {}

pub trait CharacterHeight {
    fn value() -> u8;
}

impl CharacterHeight for Single {
    fn value() -> u8 {
        0b0000
    }
}

impl CharacterHeight for Double {
    fn value() -> u8 {
        0b0100
    }
}

pub struct Normal {}
pub struct Extention {}
pub struct Unknown {}

pub trait InstructionSet {
    fn value() -> u8;
}

impl InstructionSet for Normal {
    fn value() -> u8 {
        0b0000_0000
    }
}

impl InstructionSet for Extention {
    fn value() -> u8 {
        0b0000_0001
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Character {
    Char(char),
    Cgram(u8),
}

pub const DDRAM_ADDRESS_LINE1: u8 = 0x00;
pub const DDRAM_ADDRESS_LINE2: u8 = 0x40;

pub struct ExecutionTime(NanosDurationU32);

impl<const NOM: u32, const DENOM: u32> From<ExecutionTime> for Duration<u32, NOM, DENOM> {
    fn from(v: ExecutionTime) -> Duration<u32, NOM, DENOM> {
        v.0.convert()
    }
}

impl<const NOM: u32, const DENOM: u32> From<ExecutionTime> for Duration<u64, NOM, DENOM> {
    fn from(v: ExecutionTime) -> Duration<u64, NOM, DENOM> {
        v.0.convert().into()
    }
}

pub const EXECUTION_TIME_SHORT: ExecutionTime = ExecutionTime(NanosDurationU32::nanos(26_300));
pub const EXECUTION_TIME_LONG: ExecutionTime = ExecutionTime(NanosDurationU32::micros(1_080));

pub struct St7032i<'a, I, W, A, D, N = Two, DH = Single>
where
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    dev: &'a mut W,
    addr: A,
    phantom: core::marker::PhantomData<(I, D, N, DH)>,
}

impl<'a, W, A, D, N, DH> St7032i<'a, Unknown, W, A, D, N, DH>
where
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    pub fn new(dev: &'a mut W, addr: A) -> Self {
        Self {
            dev,
            addr,
            phantom: core::marker::PhantomData,
        }
    }
}

impl<'a, I, W, A, D, N, DH> St7032i<'a, I, W, A, D, N, DH>
where
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    #[allow(clippy::type_complexity)]
    pub fn set_instruction_set<ITarget: InstructionSet>(
        mut self,
    ) -> Result<(St7032i<'a, ITarget, W, A, D, N, DH>, D), <W as Write<A>>::Error> {
        let value = 0b0011_0000 | N::value() | DH::value() | ITarget::value();
        self.write_raw(&[0b00_000000, value]).map(|_| {
            (
                St7032i::<ITarget, W, A, D, N, DH> {
                    dev: self.dev,
                    addr: self.addr,
                    phantom: core::marker::PhantomData,
                },
                EXECUTION_TIME_SHORT.into(),
            )
        })
    }

    pub fn write_raw(&mut self, data: &[u8]) -> Result<(), <W as Write<A>>::Error> {
        Write::write(self.dev, self.addr, data)
    }

    pub fn write_iter_raw<B>(&mut self, data: B) -> Result<(), <W as WriteIter<A>>::Error>
    where
        B: IntoIterator<Item = u8>,
    {
        WriteIter::write(self.dev, self.addr, data)
    }
}

impl<'a, I, W, A, D, N, DH> St7032i<'a, I, W, A, D, N, DH>
where
    I: InstructionSet,
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    pub fn cmd_clear_display(&mut self) -> Result<D, <W as Write<A>>::Error> {
        self.write_raw(&[0b00_000000, 0b0000_0001])
            .map(|_| EXECUTION_TIME_LONG.into())
    }

    pub fn cmd_display_on_off(
        &mut self,
        display: bool,
        cursor: bool,
        cursor_blink: bool,
    ) -> Result<D, <W as Write<A>>::Error> {
        let mut value = 0b0000_1000;
        if display {
            value |= 0b100;
        }
        if cursor {
            value |= 0b010;
        }
        if cursor_blink {
            value |= 0b001;
        }
        self.write_raw(&[0b00_000000, value])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }

    pub fn cmd_set_ddram_address(&mut self, addr: u8) -> Result<D, <W as Write<A>>::Error> {
        let value = 0b1000_0000 | (addr & 0b0111_1111);
        self.write_raw(&[0b00_000000, value])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }

    pub fn cmd_write_chars<C>(&mut self, chars: C) -> Result<D, <W as WriteIter<A>>::Error>
    where
        C: IntoIterator<Item = Character>,
        C::IntoIter: Iterator<Item = C::Item> + Clone,
    {
        self.write_iter_raw(stuff_control_bytes(
            chars
                .into_iter()
                .map(|c| to_character_code(c).unwrap_or(0b0010_0000)),
        ))
        .map(|_| EXECUTION_TIME_SHORT.into())
    }

    pub fn cmd_write_bytes<C>(&mut self, bytes: C) -> Result<D, <W as WriteIter<A>>::Error>
    where
        C: IntoIterator<Item = u8>,
        C::IntoIter: Iterator<Item = C::Item> + Clone,
    {
        self.write_iter_raw(stuff_control_bytes(bytes))
            .map(|_| EXECUTION_TIME_SHORT.into())
    }
}

impl<'a, W, A, D, N, DH> St7032i<'a, Normal, W, A, D, N, DH>
where
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    pub fn cmd_set_cgram_address(&mut self, addr: u8) -> Result<D, <W as Write<A>>::Error> {
        let value = 0b0100_0000 | (addr & 0b011_1111);
        self.write_raw(&[0b00_000000, value])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }
}

impl<'a, W, A, D, N, DH> St7032i<'a, Extention, W, A, D, N, DH>
where
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    pub fn cmd_internal_osc_frequency(&mut self) -> Result<D, <W as Write<A>>::Error> {
        self.write_raw(&[0b00_000000, 0b0001_0100])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }

    pub fn cmd_power_icon_contrast_set(
        &mut self,
        icon: bool,
        booster: bool,
        contrast_hi2: u8,
    ) -> Result<D, <W as Write<A>>::Error> {
        let mut value = 0b0101_0000 | (contrast_hi2 & 0b0011);
        if icon {
            value |= 0b1000;
        }
        if booster {
            value |= 0b0100;
        }
        self.write_raw(&[0b00_000000, value])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }

    pub fn cmd_follower_control(
        &mut self,
        enable: bool,
        ratio: u8,
    ) -> Result<D, <W as Write<A>>::Error> {
        let mut value = 0b0110_0000 | (ratio & 0b0111);
        if enable {
            value |= 0b1000;
        }
        self.write_raw(&[0b00_000000, value])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }

    pub fn cmd_contrast_set(&mut self, contrast_low4: u8) -> Result<D, <W as Write<A>>::Error> {
        let value = 0b0111_0000 | (contrast_low4 & 0b0000_1111);
        self.write_raw(&[0b00_000000, value])
            .map(|_| EXECUTION_TIME_SHORT.into())
    }
}

impl<'a, W, A, D, N, DH> core::fmt::Write for St7032i<'a, Normal, W, A, D, N, DH>
where
    W: Write<A> + WriteIter<A>,
    A: AddressMode + Copy,
    D: From<ExecutionTime>,
    N: DisplayRows,
    DH: CharacterHeight,
{
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        match self.cmd_write_chars(s.chars().map(Character::from)) {
            Ok(_) => Ok(()),
            Err(_) => Err(core::fmt::Error),
        }
    }
}

impl From<char> for Character {
    fn from(c: char) -> Self {
        Character::Char(c)
    }
}

fn to_character_code(c: Character) -> Option<u8> {
    match c {
        // 0b0010_0000 ~ 0b0111_1101
        Character::Char(c @ ' '..='}') => Some(c as u8),

        // 0b1010_0001 ~ 0b1101_1111
        Character::Char(c @ '。'..='゚') => Some((c as u16 - 0xfec0) as u8),

        Character::Cgram(c @ 0..=7) => Some(c),

        _ => None,
    }
}

fn stuff_control_bytes<C>(chars: C) -> impl Iterator<Item = u8>
where
    C: IntoIterator<Item = u8>,
    C::IntoIter: Iterator<Item = C::Item> + Clone,
{
    let chars = chars.into_iter();
    chars
        // chars と要素数が同じで 0b11_000000 だけの Iterator を作る
        //                          │└──── C0: 最終データのとき0、それ以外のとき1
        //                          └───── Rs: Data register の読み書きのとき1
        .clone()
        .map(|_| 0b11_000000)
        // 最後だけ 0b01_000000 にする
        .skip(1)
        .chain(core::iter::once(0b01_000000))
        // ↑ で作った control byte の Iterator と chars を zip
        // chars は ST7032 のコードに変換 未対応の文字はスペースに置換
        .zip(chars)
        // control byte, data byte の順で交互に出力
        .flat_map(|c| [c.0, c.1])
}

#[cfg(test)]
mod tests {
    extern crate std;
    use crate::*;

    #[test]
    fn test_to_character_code() {
        assert_eq!(to_character_code(' '.into()), Some(0b0010_0000));
        assert_eq!(to_character_code('!'.into()), Some(0b0010_0001));
        assert_eq!(to_character_code('0'.into()), Some(0b0011_0000));
        assert_eq!(to_character_code('@'.into()), Some(0b0100_0000));
        assert_eq!(to_character_code('A'.into()), Some(0b0100_0001));
        assert_eq!(to_character_code('`'.into()), Some(0b0110_0000));
        assert_eq!(to_character_code('a'.into()), Some(0b0110_0001));
        assert_eq!(to_character_code('}'.into()), Some(0b0111_1101));
        assert_eq!(to_character_code('~'.into()), None);
        assert_eq!(to_character_code('。'.into()), Some(0b1010_0001));
        assert_eq!(to_character_code('ア'.into()), Some(0b1011_0001));
        assert_eq!(to_character_code('゚'.into()), Some(0b1101_1111));

        assert_eq!(to_character_code(Character::Cgram(0)), Some(0b0000_0000));
        assert_eq!(to_character_code(Character::Cgram(7)), Some(0b0000_0111));
        assert_eq!(to_character_code(Character::Cgram(8)), None);
    }

    #[test]
    fn test_to_write_command() {
        {
            let mut iter = stuff_control_bytes([] as [u8; 0]);
            assert_eq!(iter.next(), None);
        }

        {
            let mut iter = stuff_control_bytes([0xa5]);
            assert_eq!(iter.next(), Some(0b01_000000));
            assert_eq!(iter.next(), Some(0xa5));
            assert_eq!(iter.next(), None);
        }

        {
            let mut iter = stuff_control_bytes([0xa5, 0x5a, 0xff]);
            assert_eq!(iter.next(), Some(0b11_000000));
            assert_eq!(iter.next(), Some(0xa5));
            assert_eq!(iter.next(), Some(0b11_000000));
            assert_eq!(iter.next(), Some(0x5a));
            assert_eq!(iter.next(), Some(0b01_000000));
            assert_eq!(iter.next(), Some(0xff));
            assert_eq!(iter.next(), None);
        }
    }
}