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
//! *Midi driver on top of embedded hal serial communications*
//!
#![no_std]
#[warn(missing_debug_implementations, missing_docs)]
mod parser;

use core::fmt::Debug;
use embedded_hal::serial;
pub use midi_types::{Channel, Control, MidiMessage, Note, Program};
use nb::block;
pub use parser::MidiParser;

pub struct MidiIn<RX> {
    rx: RX,
    parser: MidiParser,
}

impl<RX, E> MidiIn<RX>
where
    RX: serial::Read<u8, Error = E>,
    E: Debug,
{
    pub fn new(rx: RX) -> Self {
        MidiIn {
            rx,
            parser: MidiParser::new(),
        }
    }

    pub fn read(&mut self) -> nb::Result<MidiMessage, E> {
        let byte = self.rx.read()?;

        match self.parser.parse_byte(byte) {
            Some(event) => Ok(event),
            None => Err(nb::Error::WouldBlock),
        }
    }
}

pub struct MidiOut<TX> {
    tx: TX,
    last_status: Option<u8>,
}

impl<TX, E> MidiOut<TX>
where
    TX: serial::Write<u8, Error = E>,
    E: Debug,
{
    pub fn new(tx: TX) -> Self {
        MidiOut {
            tx,
            last_status: None,
        }
    }

    pub fn release(self) -> TX {
        self.tx
    }

    pub fn write(&mut self, message: &MidiMessage) -> Result<(), E> {
        match message {
            &MidiMessage::NoteOn(channel, note, velocity) => {
                self.write_channel_message(0x90, channel.into(), &[note.into(), velocity.into()])?;
            }
            &MidiMessage::NoteOff(channel, note, velocity) => {
                self.write_channel_message(0x80, channel.into(), &[note.into(), velocity.into()])?;
            }
            &MidiMessage::KeyPressure(channel, note, value) => {
                self.write_channel_message(0xA0, channel.into(), &[note.into(), value.into()])?;
            }
            &MidiMessage::ControlChange(channel, control, value) => {
                self.write_channel_message(0xB0, channel.into(), &[control.into(), value.into()])?;
            }
            &MidiMessage::ProgramChange(channel, program) => {
                self.write_channel_message(0xC0, channel.into(), &[program.into()])?;
            }
            &MidiMessage::ChannelPressure(channel, value) => {
                self.write_channel_message(0xD0, channel.into(), &[value.into()])?;
            }
            &MidiMessage::PitchBendChange(channel, value) => {
                let (value_lsb, value_msb) = value.into();
                self.write_channel_message(0xE0, channel.into(), &[value_lsb, value_msb])?;
            }
            &MidiMessage::QuarterFrame(value) => {
                block!(self.tx.write(0xF1))?;
                block!(self.tx.write(value.into()))?;
                self.last_status = None;
            }
            &MidiMessage::SongPositionPointer(value) => {
                let (value_lsb, value_msb) = value.into();
                block!(self.tx.write(0xF2))?;
                block!(self.tx.write(value_lsb))?;
                block!(self.tx.write(value_msb))?;
                self.last_status = None;
            }
            &MidiMessage::SongSelect(value) => {
                block!(self.tx.write(0xF3))?;
                block!(self.tx.write(value.into()))?;
                self.last_status = None;
            }
            &MidiMessage::TuneRequest => {
                block!(self.tx.write(0xF6))?;
                self.last_status = None;
            }
            &MidiMessage::TimingClock => {
                block!(self.tx.write(0xF8))?;
            }
            &MidiMessage::Start => {
                block!(self.tx.write(0xFA))?;
            }
            &MidiMessage::Continue => {
                block!(self.tx.write(0xFB))?;
            }
            &MidiMessage::Stop => {
                block!(self.tx.write(0xFC))?;
            }
            &MidiMessage::ActiveSensing => {
                block!(self.tx.write(0xFE))?;
            }
            &MidiMessage::Reset => {
                block!(self.tx.write(0xFF))?;
            }
        }

        Ok(())
    }

    fn write_channel_message(&mut self, status_msb: u8, channel: u8, data: &[u8]) -> Result<(), E> {
        let status = status_msb + channel;
        // If the last command written had the same status/channel, the MIDI protocol allows us to
        // omit sending the status byte again.
        if self.last_status != Some(status) {
            block!(self.tx.write(status))?;
        }
        for byte in data {
            block!(self.tx.write(*byte))?;
        }
        self.last_status = Some(status);

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use embedded_hal_mock::serial;
    use std::vec::Vec;

    fn verify_writes(messages: &[MidiMessage], bytes: &[u8]) {
        let expectations: Vec<serial::Transaction<u8>> = bytes
            .into_iter()
            .map(|byte| serial::Transaction::write(*byte))
            .collect();
        let serial = serial::Mock::new(&expectations);
        let mut midi_out = MidiOut::new(serial);
        for message in messages {
            midi_out.write(&message).unwrap();
        }
        let mut serial = midi_out.release();
        serial.done();
    }

    #[test]
    fn note_on_should_write_successfully() {
        verify_writes(
            &[MidiMessage::NoteOn(0x02.into(), 0x76.into(), 0x34.into())],
            &[0x92, 0x76, 0x34],
        );
    }

    #[test]
    fn note_on_second_note_should_skip_status() {
        verify_writes(
            &[
                MidiMessage::NoteOn(0x02.into(), 0x76.into(), 0x34.into()),
                MidiMessage::NoteOn(0x02.into(), 0x33.into(), 0x65.into()),
            ],
            &[0x92, 0x76, 0x34, 0x33, 0x65],
        );
    }
    #[test]
    fn note_on_second_note_different_channel_should_not_skip_status() {
        verify_writes(
            &[
                MidiMessage::NoteOn(0x02.into(), 0x76.into(), 0x34.into()),
                MidiMessage::NoteOn(0x03.into(), 0x33.into(), 0x65.into()),
            ],
            &[0x92, 0x76, 0x34, 0x93, 0x33, 0x65],
        );
    }
    #[test]
    fn note_on_note_off_should_not_skip_status() {
        verify_writes(
            &[
                MidiMessage::NoteOn(0x02.into(), 0x76.into(), 0x34.into()),
                MidiMessage::NoteOff(0x02.into(), 0x33.into(), 0x65.into()),
            ],
            &[0x92, 0x76, 0x34, 0x82, 0x33, 0x65],
        );
    }
    #[test]
    fn note_off_should_write_successfully() {
        verify_writes(
            &[MidiMessage::NoteOff(0x02.into(), 0x76.into(), 0x34.into())],
            &[0x82, 0x76, 0x34],
        );
    }
    #[test]
    fn key_pressure_should_write_successfully() {
        verify_writes(
            &[MidiMessage::KeyPressure(
                0x02.into(),
                0x76.into(),
                0x34.into(),
            )],
            &[0xA2, 0x76, 0x34],
        );
    }
    #[test]
    fn control_change_should_write_successfully() {
        verify_writes(
            &[MidiMessage::ControlChange(
                0x02.into(),
                0x76.into(),
                0x34.into(),
            )],
            &[0xB2, 0x76, 0x34],
        );
    }
    #[test]
    fn program_change_should_write_successfully() {
        verify_writes(
            &[MidiMessage::ProgramChange(0x02.into(), 0x76.into())],
            &[0xC2, 0x76],
        );
    }
    #[test]
    fn channel_pressure_should_write_successfully() {
        verify_writes(
            &[MidiMessage::ChannelPressure(0x02.into(), 0x76.into())],
            &[0xD2, 0x76],
        );
    }
    #[test]
    fn pitch_bend_should_write_successfully() {
        verify_writes(
            &[MidiMessage::PitchBendChange(
                0x02.into(),
                (0x76, 0x34).into(),
            )],
            &[0xE2, 0x76, 0x34],
        );
    }
    #[test]
    fn quarter_frame_should_write_successfully() {
        verify_writes(&[MidiMessage::QuarterFrame(0x76.into())], &[0xF1, 0x76]);
    }
    #[test]
    fn song_position_pointer_should_write_successfully() {
        verify_writes(
            &[MidiMessage::SongPositionPointer((0x76, 0x34).into())],
            &[0xF2, 0x76, 0x34],
        );
    }
    #[test]
    fn song_select_should_write_successfully() {
        verify_writes(&[MidiMessage::SongSelect(0x76.into())], &[0xF3, 0x76]);
    }
    #[test]
    fn tune_request_should_write_successfully() {
        verify_writes(&[MidiMessage::TuneRequest], &[0xF6]);
    }
    #[test]
    fn timing_clock_should_write_successfully() {
        verify_writes(&[MidiMessage::TimingClock], &[0xF8]);
    }
    #[test]
    fn start_should_write_successfully() {
        verify_writes(&[MidiMessage::Start], &[0xFA]);
    }
    #[test]
    fn continue_should_write_successfully() {
        verify_writes(&[MidiMessage::Continue], &[0xFB]);
    }
    #[test]
    fn stop_should_write_successfully() {
        verify_writes(&[MidiMessage::Stop], &[0xFC]);
    }
    #[test]
    fn active_sensing_should_write_successfully() {
        verify_writes(&[MidiMessage::ActiveSensing], &[0xFE]);
    }
    #[test]
    fn reset_should_write_successfully() {
        verify_writes(&[MidiMessage::Reset], &[0xFF]);
    }
}