tmcl/modules/generic/
mod.rs

1//! Generic `TMCM` implementation - uses `TMCL` instructions without making assumptions about parameters.
2//!
3//! The types in module only provides a minimum of compile time guarantees.
4//! It is therefore preferable to use a less generic module that will fail to compile if
5//! it is attempted to write to a read only register and such.
6//! This module is only recommended to use if no such module exists.
7
8pub mod instructions;
9
10use lib::ops::Deref;
11use lib::marker::PhantomData;
12
13use interior_mut::InteriorMut;
14
15use Error;
16use Instruction;
17use instructions::DirectInstruction;
18use Interface;
19use Return;
20use Status;
21use Command;
22
23/// This type represents a generic TMCM module.
24#[derive(Debug)]
25pub struct GenericModule<'a, IF: Interface + 'a, Cell: InteriorMut<'a, IF>, T: Deref<Target=Cell> + 'a> {
26    /// The module address
27    address: u8,
28    interface: T,
29    pd1: PhantomData<&'a IF>,
30    pd2: PhantomData<&'a T>,
31}
32
33impl<'a, IF: Interface, Cell: InteriorMut<'a, IF>, T: Deref<Target=Cell>> GenericModule<'a, IF, Cell, T> {
34    /// Create a new module
35    pub fn new(interface: T, address: u8) -> Self {
36        GenericModule{
37            address,
38            interface,
39            pd1: PhantomData{},
40            pd2: PhantomData{},
41        }
42    }
43
44    /// Synchronously write a command and wait for the Reply
45    pub fn write_command<Inst: Instruction + DirectInstruction>(&'a self, instruction: Inst) -> Result<Inst::Return, Error<IF::Error>> {
46        let mut interface = self.interface.borrow_int_mut().or(Err(Error::InterfaceUnavailable))?;
47        interface.transmit_command(&Command::new(self.address, instruction)).map_err(|e| Error::InterfaceError(e))?;
48        let reply = interface.receive_reply().map_err(|e| Error::InterfaceError(e))?;
49        match reply.status() {
50            Status::Ok(_) => Ok(<Inst::Return as Return>::from_operand(reply.operand())),
51            Status::Err(e) => Err(e.into()),
52        }
53    }
54}