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
#![doc = include_str!("../README.md")]
#![no_std]
#![forbid(unsafe_code)]

use device_driver::ll::register::RegisterInterface;
use device_driver::{create_low_level_device, implement_registers, Bit};
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::blocking::i2c::{Read, Write};
use num_enum::{IntoPrimitive, TryFromPrimitive};

/// Default I2C address of the sensor
pub const DEFAULT_ADDRESS: u8 = 0x15;

// Constants to make the register definitions more readable
const RA_FW: RegisterAddress = RegisterAddress {
    address: 0x1389,
    read_code: Some(ModbusFunctionCode::ReadInternalRegisters),
    write_code: None,
};
const RA_STATUS: RegisterAddress = RegisterAddress {
    address: 0x138A,
    read_code: Some(ModbusFunctionCode::ReadInternalRegisters),
    write_code: None,
};
const RA_GAS_PPM: RegisterAddress = RegisterAddress {
    address: 0x138B,
    read_code: Some(ModbusFunctionCode::ReadInternalRegisters),
    write_code: None,
};
const RA_RESET: RegisterAddress = RegisterAddress {
    address: 0x03E8,
    read_code: None,
    write_code: Some(ModbusFunctionCode::ForceSingleCoil),
};
const RA_SPC: RegisterAddress = RegisterAddress {
    address: 0x03EC,
    read_code: None,
    write_code: Some(ModbusFunctionCode::ForceSingleCoil),
};
const RA_SLAVE_ADDR: RegisterAddress = RegisterAddress {
    address: 0x0FA5,
    read_code: Some(ModbusFunctionCode::ReadHoldingRegisters),
    write_code: Some(ModbusFunctionCode::PresetSingleRegister),
};
const RA_ABC: RegisterAddress = RegisterAddress {
    address: 0x03EE,
    read_code: None, // Some(ModbusFunctionCode::ReadCoilStatus),
    write_code: Some(ModbusFunctionCode::ForceSingleCoil),
};

/// Modbus function codes
#[repr(u8)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum ModbusFunctionCode {
    /// Read output coils
    ReadCoilStatus = 0x01,
    /// Read holding registers
    ReadHoldingRegisters = 0x03,
    /// Read internal registers
    ReadInternalRegisters = 0x04,
    /// Write single coil
    ForceSingleCoil = 0x05,
    /// Write single register
    PresetSingleRegister = 0x06,
}

/// Encapsulates the address of the register as well as the function codes for reading and writing
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct RegisterAddress {
    /// Register address
    pub address: u16,
    /// Function code for reading
    pub read_code: Option<ModbusFunctionCode>,
    /// Function code for writing
    pub write_code: Option<ModbusFunctionCode>,
}

/// Valid values for ABC-Logic
#[repr(u16)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum AbcLogic {
    /// Enable
    Enabled = 0xFF00,
    /// Disable
    Disabled = 0x0000,
}

/// Valid values for single point calibration
#[repr(u16)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum SinglePointCalibration {
    /// Start
    Start = 0xFF00,
    /// Stop
    Stop = 0x0000,
}

/// Valid values for Reset
#[repr(u16)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
pub enum Reset {
    /// Reset
    Reset = 0xFF00,
}

/// The errors our hardware interface can return.
#[derive(Debug)]
pub enum InterfaceError {
    /// I2C error
    CommunicationError,
    /// Invalid command for reading/writing
    InvalidCommand,
    /// Error response from sensor
    ModbusError(u8),
}

/// Our full hardware interface with the chip
pub struct T67xxInterface<I2C: Read + Write, D: DelayMs<u8>> {
    /// The I2C interface we use to drive the sensor
    communication_interface: I2C,
    /// Some kind of delay provider
    delay: D,
    /// I2C address of the chip
    addr: u8,
}

impl<I2C: Read + Write, D: DelayMs<u8>> T67xxInterface<I2C, D> {
    /// Creates a new hardware interface
    ///
    /// If the address is `None` [DEFAULT_ADDRESS] is used.
    pub fn new(communication_interface: I2C, delay: D, address: Option<u8>) -> Self {
        T67xxInterface {
            communication_interface,
            delay,
            addr: address.unwrap_or(DEFAULT_ADDRESS),
        }
    }

    /// Frees the peripherals
    pub fn free(self) -> (I2C, D) {
        (self.communication_interface, self.delay)
    }
}

impl<I2C: Read + Write, D: DelayMs<u8>> RegisterInterface for T67xxInterface<I2C, D> {
    type Address = RegisterAddress;
    type InterfaceError = InterfaceError;

    fn read_register(
        &mut self,
        address: Self::Address,
        value: &mut [u8],
    ) -> Result<(), Self::InterfaceError> {
        if value.len() != 2 {
            return Err(InterfaceError::InvalidCommand);
        }
        let mut buf: [u8; 4] = [0; 4];
        self.communication_interface
            .write(
                self.addr,
                &[
                    address.read_code.ok_or(InterfaceError::InvalidCommand)? as u8,
                    (address.address >> 8) as u8,
                    (address.address & 0xff) as u8,
                    0x00,
                    0x01,
                ],
            )
            .map_err(|_| InterfaceError::CommunicationError)?;
        // Delay according to datasheet
        self.delay.delay_ms(10);
        // Read response and check function code
        self.communication_interface
            .read(self.addr, &mut buf[..])
            .map_err(|_| InterfaceError::CommunicationError)?;
        if buf[0] != address.read_code.unwrap() as u8 {
            return Err(InterfaceError::ModbusError(buf[0]));
        }
        value.copy_from_slice(&buf[2..]);
        Ok(())
    }

    fn write_register(
        &mut self,
        address: Self::Address,
        value: &[u8],
    ) -> Result<(), Self::InterfaceError> {
        if value.len() != 2 {
            return Err(InterfaceError::InvalidCommand);
        }
        let mut buf = [
            address.write_code.ok_or(InterfaceError::InvalidCommand)? as u8,
            (address.address >> 8) as u8,
            (address.address & 0xff) as u8,
            0,
            0,
        ];
        buf[3..].copy_from_slice(value);
        self.communication_interface
            .write(self.addr, &buf)
            .map_err(|_| InterfaceError::CommunicationError)?;
        // Delay according to datasheet
        self.delay.delay_ms(10);
        if address != RA_RESET {
            // Read response and check function code
            self.communication_interface
                .read(self.addr, &mut buf[..])
                .map_err(|_| InterfaceError::CommunicationError)?;
            if buf[0] != address.write_code.unwrap() as u8 {
                return Err(InterfaceError::ModbusError(buf[0]));
            }
        }
        Ok(())
    }
}

impl<I2C: Read + Write, D: DelayMs<u8>> HardwareInterface for T67xxInterface<I2C, D> {}

// Create our low level device. This holds all the hardware communication definitions
create_low_level_device!(
    /// Low level access to the T67xx chip
    T67xxLL {
        // The types of errors our low level error enum must contain
        errors: [InterfaceError],
        hardware_interface_requirements: { RegisterInterface<Address = RegisterAddress, InterfaceError = InterfaceError> },
        hardware_interface_capabilities: {}
    }
);

// Create a register set for the device
implement_registers!(
    /// The global register set
    T67xxLL.registers<RegisterAddress> = {
        /// Returns the firmware revision from the sensor
        #[generate(Debug)]
        firmware_revision(RO, RA_FW, 2) = {
            /// Firmware revision
            firmware_revision: u16:BE = RO 0..16,
        },
        /// Returns a status register from the sensor
        #[generate(Debug)]
        status(RO, RA_STATUS, 2) = MSB {
            /// Error condition
            error_condition: u8 as Bit = RO 15..=15,
            /// Flash error
            flash_error: u8 as Bit = RO 14..=14,
            /// Calibration error
            calibration_error: u8 as Bit = RO 13..=13,
            /// RS-232
            rs232: u8 as Bit = RO 7..=7,
            /// RS-485
            rs485: u8 as Bit = RO 6..=6,
            /// I2C
            i2c: u8 as Bit = RO 5..=5,
            /// Warm-up mode
            warm_up_mode: u8 as Bit = RO 4..=4,
            /// Single point calibration
            single_point_calibration: u8 as Bit = RO 0..=0,
        },
        /// The current gas ppm calculation
        #[generate(Debug)]
        gas_ppm(RO, RA_GAS_PPM, 2) = {
            /// Gas ppm
            gas_ppm: u16:BE = RO 0..16,
        },
        /// Reset the sensor over the Modbus network
        reset_device(WO, RA_RESET, 2) = {
            /// Reset code
            reset_device: u16:BE as Reset = WO 0..16,
        },
        /// Single-point calibration
        start_single_point_cal(WO, RA_SPC, 2) = {
            /// Enable/disable single-point calibration
            start_single_point_cal: u16:BE as SinglePointCalibration = WO 0..16,
        },
        /// Change of sensor address (default address is 0x15)
        #[generate(Debug)]
        slave_address(RW, RA_SLAVE_ADDR, 2) = {
            /// Sensor address
            slave_address: u8 = RW 8..16,
        },
        /// Enable or disable ABC Logic™
        abc_logic(WO, RA_ABC, 2) = {
            /// Enable/disable ABC Logic™
            abc_logic: u16:BE as AbcLogic = WO 0..16,
        },
    }
);