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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! # uFire Isolated EC Probe Interface
//!
//! * measure EC
//! * measure salinity
//! * temperature in Celsius

use std::f32;
use std::thread;
use std::time::Duration;
use std::mem;

extern crate byteorder;
use byteorder::{ByteOrder, LittleEndian};

extern crate i2cdev;
use self::i2cdev::core::*;
use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};

const EC_MEASURE_EC: u8 = 80;
const EC_MEASURE_TEMP: u8 = 40;
const EC_CALIBRATE_PROBE: u8 = 20;
const EC_CALIBRATE_LOW: u8 = 10;
const EC_CALIBRATE_HIGH: u8 = 8;
const EC_I2C: u8 = 4;
const EC_READ: u8 = 2;
const EC_WRITE: u8 = 1;

const EC_VERSION_REGISTER: u8 = 0;
const EC_MS_REGISTER: u8 = 1;
const EC_TEMP_REGISTER: u8 = 5;
const EC_SOLUTION_REGISTER: u8 = 9;
const EC_TEMPCOEF_REGISTER: u8 = 13;
const EC_CALIBRATE_REFHIGH_REGISTER: u8 = 17;
const EC_CALIBRATE_REFLOW_REGISTER: u8 = 21;
const EC_CALIBRATE_READHIGH_REGISTER: u8 = 25;
const EC_CALIBRATE_READLOW_REGISTER: u8 = 29;
const EC_CALIBRATE_OFFSET_REGISTER: u8 = 33;
const EC_PSU_REGISTER: u8 = 37;
const EC_RAW_REGISTER: u8 = 41;
const EC_TEMP_COMPENSATION_REGISTER: u8 = 45;
const EC_BUFFER_REGISTER: u8 = 49;
const EC_FW_VERSION_REGISTER: u8 = 53;
const EC_CONFIG_REGISTER: u8 = 54;
const EC_TASK_REGISTER: u8 = 55;    

const EC_TEMP_COMPENSATION_CONFIG_BIT: u8 = 1;

const EC_EC_MEASUREMENT_TIME: u64 = 750;
const EC_TEMP_MEASURE_TIME: u64 = 750;

pub struct EcProbe {
    dev: Box<LinuxI2CDevice>,
}

impl EcProbe {
    /// Create a new EcProbe object
    ///
    /// Pass the i2c port to use, it must be a software overlay device, and I2C address.
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ```
    pub fn new(filename: &'static str, address: u16) -> Result<Self, Box<LinuxI2CError>> {
        let dev = LinuxI2CDevice::new(filename, address)?;
        Ok(EcProbe { dev: Box::new(dev) })
    }

    /// Start a temperature measurement
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.measure_temp();
    /// ```
    pub fn measure_temp(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_MEASURE_TEMP)?;
        thread::sleep(Duration::from_millis(EC_TEMP_MEASURE_TIME));

        Ok(self._read_register(EC_TEMP_REGISTER)?)
    }

    /// Sets the temperature used by the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_temp(20.2);
    /// ```
    pub fn set_temp(&mut self, temp_c: f32) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_TEMP_REGISTER, temp_c)?;

        Ok(())
    }

    /// Calibrates the probe using a single point using a mS value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.calibrate_single(1.413.0);
    /// ```
    pub fn calibrate_single(&mut self, solution_ec: f32) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_SOLUTION_REGISTER, solution_ec)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_CALIBRATE_PROBE)?;
        thread::sleep(Duration::from_millis(EC_EC_MEASUREMENT_TIME));
        Ok(())
    }
    
    /// Calibrates the dual-point values for the low reading, in mS, and saves them in the
    /// devices's EEPROM.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.calibrate_probe_low(1.413.0);
    /// ```
    pub fn calibrate_probe_low(&mut self, solution_ec: f32) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_SOLUTION_REGISTER, solution_ec)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_CALIBRATE_LOW)?;
        thread::sleep(Duration::from_millis(EC_EC_MEASUREMENT_TIME));
        Ok(())
    }

    /// Calibrates the dual-point values for the high reading, in mS, and saves them in the
    /// devices's EEPROM.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.calibrate_probe_high(12.88.0);
    /// ```
    pub fn calibrate_probe_high(&mut self, solution_ec: f32) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_SOLUTION_REGISTER, solution_ec)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_CALIBRATE_HIGH)?;
        thread::sleep(Duration::from_millis(EC_EC_MEASUREMENT_TIME));
        Ok(())
    }


    /// Starts an EC measurement, taking a new temp measurement if true passed
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.measure_ec(22.1);
    /// ```
    pub fn measure_ec(&mut self, temp_c: f32) -> Result<(f32), Box<LinuxI2CError>> {
	self.use_temperature_compensation(true)?;
        self._write_register(EC_TEMP_REGISTER, temp_c)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_MEASURE_EC)?;
        thread::sleep(Duration::from_millis(EC_EC_MEASUREMENT_TIME));

        Ok(self._read_register(EC_MS_REGISTER)?)
    }

    /// Starts an salinity measurement and returns the salinity in PSU.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.measure_salinity(22.1);
    /// ```
    pub fn measure_salinity(&mut self, temp_c: f32) -> Result<(f32), Box<LinuxI2CError>> {
        self._write_register(EC_TEMP_REGISTER, temp_c)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_MEASURE_EC)?;
        thread::sleep(Duration::from_millis(EC_EC_MEASUREMENT_TIME));
        Ok(self._read_register(EC_PSU_REGISTER)?)
    }

    /// Configures the device to use temperature compensation or not.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.use_temperature_compensation(true);
    /// assert_eq!(1, ec.using_temperature_compensation().unwrap());
    /// ```
    pub fn use_temperature_compensation(&mut self, b: bool) -> Result<(), Box<LinuxI2CError>> {
        self._change_register(EC_CONFIG_REGISTER)?;
        let mut config: u8 = self.dev.smbus_read_byte()?;
        thread::sleep(Duration::from_millis(10));
        if b {
            config |= 1 << EC_TEMP_COMPENSATION_CONFIG_BIT;
        } else {
            config &= !(1 << EC_TEMP_COMPENSATION_CONFIG_BIT);
        }
        self.dev.smbus_write_byte_data(EC_CONFIG_REGISTER, config)?;
        thread::sleep(Duration::from_millis(10));
        Ok(())
   }

    /// Starts a raw measurement.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.measure_raw(true);
    /// ```
    pub fn measure_raw(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_MEASURE_EC)?;
        thread::sleep(Duration::from_millis(EC_EC_MEASUREMENT_TIME));

        Ok(self._read_register(EC_RAW_REGISTER)?)
    }

    /// Sets the temperature constant to use for compensation and saves it in the devices's EEPROM.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_temp_constant(20);
    /// ```
    pub fn set_temp_constant(&mut self, temp_constant: f32) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_TEMP_COMPENSATION_REGISTER, temp_constant)?;

        Ok(())
    }

    /// Returns the temperature constant from the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.get_temp_constant();
    /// ```
    pub fn get_temp_constant(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_TEMP_COMPENSATION_REGISTER)?)
    }

    /// Sets the temperature coefficient to use for compensation and saves it in the devices's EEPROM.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_temp_coefficient(0.019);
    /// ```
    pub fn set_temp_coefficient(&mut self, temp_coef: f32) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_TEMPCOEF_REGISTER, temp_coef)?;

        Ok(())
    }

    /// Returns the temperature coefficient from the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.get_temp_coefficient();
    /// ```
    pub fn get_temp_coefficient(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_TEMPCOEF_REGISTER)?)
    }

    /// Returns the dual-point calibration low reference value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(50.0, 0.0, 0.0, 0.0);
    /// assert_eq!(50.0, ec.get_calibrate_low_reference().unwrap());
    /// ```
    pub fn read_eeprom(&mut self, address: f32) -> Result<(f32), Box<LinuxI2CError>> {
        self._write_register(EC_SOLUTION_REGISTER, address)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_READ)?;
        Ok(self._read_register(EC_BUFFER_REGISTER)?)
    }

    /// Returns the dual-point calibration low reference value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(50.0, 0.0, 0.0, 0.0);
    /// assert_eq!(50.0, ec.get_calibrate_low_reference().unwrap());
    /// ```
    pub fn write_eeprom(&mut self, address: f32, value: f32) -> Result<(f32), Box<LinuxI2CError>> {
        self._write_register(EC_SOLUTION_REGISTER, address)?;
        self._write_register(EC_BUFFER_REGISTER, value)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_WRITE)?;
        Ok(self._read_register(EC_BUFFER_REGISTER)?)
    }

    /// Returns the firmware version of the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// assert_eq!(0x1c, ec.get_version().unwrap());
    /// ```
    pub fn get_version(&mut self) -> Result<(u8), Box<LinuxI2CError>> {
        self._change_register(EC_VERSION_REGISTER)?;
        Ok(self.dev.smbus_read_byte()?)
    }

    /// Returns the firmware version of the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// assert_eq!(0x1, ec.get_version().unwrap());
    /// ```
    pub fn get_firmware(&mut self) -> Result<(u8), Box<LinuxI2CError>> {
        self._change_register(EC_FW_VERSION_REGISTER)?;
        Ok(self.dev.smbus_read_byte()?)
    }

    /// Resets all the stored calibration information.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.reset();
    /// assert_eq!(true, ec.get_calibrate_offset().unwrap().is_nan());
    /// assert_eq!(true, ec.get_calibrate_low_reading().unwrap().is_nan());
    /// assert_eq!(true, ec.get_calibrate_high_reading().unwrap().is_nan());
    /// assert_eq!(true, ec.get_calibrate_low_reference().unwrap().is_nan());
    /// assert_eq!(true, ec.get_calibrate_high_reference().unwrap().is_nan());
    /// ```
    pub fn reset(&mut self) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_CALIBRATE_REFLOW_REGISTER, f32::NAN)?;
        self._write_register(EC_CALIBRATE_REFHIGH_REGISTER, f32::NAN)?;
        self._write_register(EC_CALIBRATE_READLOW_REGISTER, f32::NAN)?;
        self._write_register(EC_CALIBRATE_READHIGH_REGISTER, f32::NAN)?;
        self._write_register(EC_CALIBRATE_OFFSET_REGISTER, f32::NAN)?;
        self._write_register(EC_TEMP_COMPENSATION_REGISTER, 25.0)?;
	    self.set_temp_coefficient(0.019)?;
        Ok(())
    }

    /// Sets the I2C address of the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// // ec.set_i2c_address(0x4f);
    /// ```
    pub fn set_i2c_address(&mut self, i2c_address: u16) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_SOLUTION_REGISTER, i2c_address as f32)?;
        self.dev.smbus_write_byte_data(EC_TASK_REGISTER, EC_I2C)?;

        Ok(())
    }

    /// Sets all the values, in mS, for dual point calibration and saves them in the devices's
    /// EEPROM.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(50.0, 58.0, 48.0, 56.0);
    /// ```
    pub fn set_dual_point_calibration(
        &mut self,
        ref_low: f32,
        ref_high: f32,
        read_low: f32,
        read_high: f32,
    ) -> Result<(), Box<LinuxI2CError>> {
        self._write_register(EC_CALIBRATE_REFLOW_REGISTER, ref_low)?;
        self._write_register(EC_CALIBRATE_REFHIGH_REGISTER, ref_high)?;
        self._write_register(EC_CALIBRATE_READLOW_REGISTER, read_low)?;
        self._write_register(EC_CALIBRATE_READHIGH_REGISTER, read_high)?;
        Ok(())
    }

    /// Returns the single-point offset from the device.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.get_calibrate_offset();
    /// ```
    pub fn get_calibrate_offset(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_CALIBRATE_OFFSET_REGISTER)?)
    }

    /// Returns the dual-point calibration high reference value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(0.0, 500.0, 0.0, 0.0);
    /// ```
    pub fn get_calibrate_high_reference(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_CALIBRATE_REFHIGH_REGISTER)?)
    }
    /// Returns the dual-point calibration high reading value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(0.0, 0.0, 0.0, 553.0);
    /// assert_eq!(553.0, ec.get_calibrate_high_reading().unwrap());
    /// ```
    pub fn get_calibrate_high_reading(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_CALIBRATE_READHIGH_REGISTER)?)
    }
    /// Returns the dual-point calibration low reference value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(50.0, 0.0, 0.0, 0.0);
    /// assert_eq!(50.0, ec.get_calibrate_low_reference().unwrap());
    /// ```
    pub fn get_calibrate_low_reference(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_CALIBRATE_REFLOW_REGISTER)?)
    }
    /// Returns the dual-point calibration low reading value.
    ///
    /// # Example
    /// ```
    /// let mut ec = ufire_ec::EcProbe::new("/dev/i2c-3", 0x3c).unwrap();
    /// ec.set_dual_point_calibration(0.0, 0.0, 34.0, 0.0);
    /// assert_eq!(34.0, ec.get_calibrate_low_reading().unwrap());
    /// ```
    pub fn get_calibrate_low_reading(&mut self) -> Result<(f32), Box<LinuxI2CError>> {
        Ok(self._read_register(EC_CALIBRATE_READLOW_REGISTER)?)
    }
    
    pub fn _write_register(&mut self, register: u8, f_val: f32) -> Result<(), Box<LinuxI2CError>> {
        unsafe {
            let buf: [u8; 4] = mem::transmute(f_val);
            self._change_register(register)?;
            self.dev.smbus_write_byte_data(register + 0, buf[0])?;
            thread::sleep(Duration::from_millis(10));
            self.dev.smbus_write_byte_data(register + 1, buf[1])?;
            thread::sleep(Duration::from_millis(10));
            self.dev.smbus_write_byte_data(register + 2, buf[2])?;
            thread::sleep(Duration::from_millis(10));
            self.dev.smbus_write_byte_data(register + 3, buf[3])?;
            thread::sleep(Duration::from_millis(10));
            Ok(())
        }
    }

    pub fn _read_register(&mut self, register: u8) -> Result<(f32), Box<LinuxI2CError>> {
        let mut buf: [u8; 4] = [0; 4];
        self._change_register(register)?;
        buf[0] = self.dev.smbus_read_byte()?;
        thread::sleep(Duration::from_millis(10));
        buf[1] = self.dev.smbus_read_byte()?;
        thread::sleep(Duration::from_millis(10));
        buf[2] = self.dev.smbus_read_byte()?;
        thread::sleep(Duration::from_millis(10));
        buf[3] = self.dev.smbus_read_byte()?;
        thread::sleep(Duration::from_millis(10));
        Ok(LittleEndian::read_f32(&buf))
    }

    pub fn _change_register(&mut self, register: u8) -> Result<(), Box<LinuxI2CError>> {
        self.dev.smbus_write_byte(register)?;
        thread::sleep(Duration::from_millis(10));
        Ok(())
    }
}