Skip to content

Commit c1d25f7

Browse files
authored
Merge pull request #53 from eldruin/refactoring
Refactoring + some simplifications
2 parents fb83826 + 6671e87 commit c1d25f7

File tree

8 files changed

+84
-93
lines changed

8 files changed

+84
-93
lines changed

examples/nunchuck.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ mod nunchuck {
5353
}
5454
}
5555

56-
fn cause(&self) -> Option<&Error> {
56+
fn cause(&self) -> Option<&dyn Error> {
5757
match *self {
5858
NunchuckError::Error(ref e) => Some(e),
5959
NunchuckError::ParseError => None,
@@ -82,9 +82,9 @@ mod nunchuck {
8282
Some(NunchuckReading {
8383
joystick_x: data[0],
8484
joystick_y: data[1],
85-
accel_x: (data[2] as u16) << 2 | ((data[5] as u16 >> 6) & 0b11),
86-
accel_y: (data[3] as u16) << 2 | ((data[5] as u16 >> 4) & 0b11),
87-
accel_z: (data[4] as u16) << 2 | ((data[5] as u16 >> 2) & 0b11),
85+
accel_x: (u16::from(data[2]) << 2) | ((u16::from(data[5]) >> 6) & 0b11),
86+
accel_y: (u16::from(data[3]) << 2) | ((u16::from(data[5]) >> 4) & 0b11),
87+
accel_z: (u16::from(data[4]) << 2) | ((u16::from(data[5]) >> 2) & 0b11),
8888
c_button_pressed: (data[5] & 0b10) == 0,
8989
z_button_pressed: (data[5] & 0b01) == 0,
9090
})
@@ -106,7 +106,7 @@ mod nunchuck {
106106
/// send the required init sequence in order to read data in
107107
/// the future.
108108
pub fn new(i2cdev: T) -> Result<Nunchuck<T>, T::Error> {
109-
let mut nunchuck = Nunchuck { i2cdev: i2cdev };
109+
let mut nunchuck = Nunchuck { i2cdev };
110110
nunchuck.init()?;
111111
Ok(nunchuck)
112112
}
@@ -122,8 +122,7 @@ mod nunchuck {
122122
// lacking but it appears this is some kind of handshake to
123123
// perform unencrypted data tranfers
124124
self.i2cdev.smbus_write_byte_data(0xF0, 0x55)?;
125-
self.i2cdev.smbus_write_byte_data(0xFB, 0x00)?;
126-
Ok(())
125+
self.i2cdev.smbus_write_byte_data(0xFB, 0x00)
127126
}
128127

129128
pub fn read(&mut self) -> Result<NunchuckReading, NunchuckError<T::Error>> {
@@ -198,7 +197,7 @@ use nunchuck::*;
198197
use docopt::Docopt;
199198
use std::env::args;
200199

201-
const USAGE: &'static str = "
200+
const USAGE: &str = "
202201
Reading Wii Nunchuck data via Linux i2cdev.
203202
204203
Usage:
@@ -217,7 +216,7 @@ fn main() {}
217216
#[cfg(any(target_os = "linux", target_os = "android"))]
218217
fn main() {
219218
let args = Docopt::new(USAGE)
220-
.and_then(|d| d.argv(args().into_iter()).parse())
219+
.and_then(|d| d.argv(args()).parse())
221220
.unwrap_or_else(|e| e.exit());
222221
let device = args.get_str("<device>");
223222
let i2cdev = LinuxI2CDevice::new(device, NUNCHUCK_SLAVE_ADDR).unwrap();

examples/pca9956b.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ Options:
3434

3535
const ADDR: u16 = 0x20;
3636

37+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
38+
fn main() {}
39+
3740
#[cfg(any(target_os = "linux", target_os = "android"))]
3841
fn main() {
3942
let args = Docopt::new(USAGE)

examples/sensors.rs

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ mod sensors {
183183
// put device in measurement mode
184184
i2cdev.smbus_write_byte_data(REGISTER_POWER_CTL, 0x08)?;
185185

186-
Ok(ADXL345Accelerometer { i2cdev: i2cdev })
186+
Ok(ADXL345Accelerometer { i2cdev })
187187
}
188188

189189
/// Get the device id
@@ -212,9 +212,9 @@ mod sensors {
212212
let y: i16 = LittleEndian::read_i16(&[buf[2], buf[3]]);
213213
let z: i16 = LittleEndian::read_i16(&[buf[4], buf[5]]);
214214
Ok(AccelerometerSample {
215-
x: (x as f32 / 1023.0) * (ACCEL_RANGE * 2.0),
216-
y: (y as f32 / 1023.0) * (ACCEL_RANGE * 2.0),
217-
z: (z as f32 / 1023.0) * (ACCEL_RANGE * 2.0),
215+
x: (f32::from(x) / 1023.0) * (ACCEL_RANGE * 2.0),
216+
y: (f32::from(y) / 1023.0) * (ACCEL_RANGE * 2.0),
217+
z: (f32::from(z) / 1023.0) * (ACCEL_RANGE * 2.0),
218218
})
219219
}
220220
}
@@ -285,7 +285,7 @@ mod sensors {
285285
// If values are less than 16 bytes, need to adjust
286286
let extrabits = 16 - integer_bits - fractional_bits - 1;
287287
let rawval: i16 = BigEndian::read_i16(&[msb, lsb]);
288-
let adj = (rawval as f32 / 2_f32.powi(fractional_bits + extrabits))
288+
let adj = (f32::from(rawval) / 2_f32.powi(fractional_bits + extrabits))
289289
/ 10_f32.powi(dec_pt_zero_pad);
290290
adj
291291
}
@@ -297,7 +297,7 @@ mod sensors {
297297
/// order. This gets the raw, unconverted value of each
298298
/// coefficient.
299299
pub fn new<E: Error>(
300-
i2cdev: &mut I2CDevice<Error = E>,
300+
i2cdev: &mut dyn I2CDevice<Error = E>,
301301
) -> Result<MPL115A2Coefficients, E> {
302302
let mut buf: [u8; 8] = [0; 8];
303303
i2cdev.write(&[REGISTER_ADDR_A0])?;
@@ -314,7 +314,7 @@ mod sensors {
314314
impl MPL115A2RawReading {
315315
/// Create a new reading from the provided I2C Device
316316
pub fn new<E: Error>(
317-
i2cdev: &mut I2CDevice<Error = E>,
317+
i2cdev: &mut dyn I2CDevice<Error = E>,
318318
) -> Result<MPL115A2RawReading, E> {
319319
// tell the chip to do an ADC read so we can get updated values
320320
i2cdev.smbus_write_byte_data(REGISTER_ADDR_START_CONVERSION, 0x00)?;
@@ -329,24 +329,21 @@ mod sensors {
329329
i2cdev.read(&mut buf)?;
330330
let padc: u16 = BigEndian::read_u16(&buf) >> 6;
331331
let tadc: u16 = BigEndian::read_u16(&buf[2..]) >> 6;
332-
Ok(MPL115A2RawReading {
333-
padc: padc,
334-
tadc: tadc,
335-
})
332+
Ok(MPL115A2RawReading { padc, tadc })
336333
}
337334

338335
/// Calculate the temperature in centrigrade for this reading
339336
pub fn temperature_celsius(&self) -> f32 {
340-
(self.tadc as f32 - 498.0) / -5.35 + 25.0
337+
(f32::from(self.tadc) - 498.0) / -5.35 + 25.0
341338
}
342339

343340
/// Calculate the pressure in pascals for this reading
344341
pub fn pressure_kpa(&self, coeff: &MPL115A2Coefficients) -> f32 {
345342
// Pcomp = a0 + (b1 + c12 * Tadc) * Padc + b2 * Tadc
346343
// Pkpa = Pcomp * ((115 - 50) / 1023) + 50
347344
let pcomp: f32 = coeff.a0
348-
+ (coeff.b1 + coeff.c12 * self.tadc as f32) * self.padc as f32
349-
+ (coeff.b2 * self.tadc as f32);
345+
+ (coeff.b1 + coeff.c12 * f32::from(self.tadc)) * f32::from(self.padc)
346+
+ (coeff.b2 * f32::from(self.tadc));
350347

351348
// scale has 1023 bits of range from 50 kPa to 115 kPa
352349
let pkpa: f32 = pcomp * ((115.0 - 50.0) / 1023.0) + 50.0;
@@ -361,10 +358,7 @@ mod sensors {
361358
/// Create sensor accessor for MPL115A2 on the provided i2c bus path
362359
pub fn new(mut i2cdev: T) -> Result<MPL115A2BarometerThermometer<T>, T::Error> {
363360
let coeff = MPL115A2Coefficients::new(&mut i2cdev)?;
364-
Ok(MPL115A2BarometerThermometer {
365-
i2cdev: i2cdev,
366-
coeff: coeff,
367-
})
361+
Ok(MPL115A2BarometerThermometer { i2cdev, coeff })
368362
}
369363
}
370364

@@ -457,7 +451,7 @@ mod sensors {
457451
}
458452
}
459453

460-
const USAGE: &'static str = "
454+
const USAGE: &str = "
461455
Reading sensor data from a variety of sensors
462456
463457
Usage:
@@ -476,7 +470,7 @@ fn main() {}
476470
#[cfg(any(target_os = "linux", target_os = "android"))]
477471
fn main() {
478472
let args = Docopt::new(USAGE)
479-
.and_then(|d| d.argv(args().into_iter()).parse())
473+
.and_then(|d| d.argv(args()).parse())
480474
.unwrap_or_else(|e| e.exit());
481475
let device = args.get_str("<device>");
482476
let mpl115a2_i2cdev = LinuxI2CDevice::new(device, MPL115A2_I2C_ADDR).unwrap();

src/core.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ pub trait I2CDevice {
4242
/// This is the opposite operation as smbus_read_byte. As with read_byte,
4343
/// no register is specified.
4444
fn smbus_write_byte(&mut self, value: u8) -> Result<(), Self::Error> {
45-
self.write(&mut [value])
45+
self.write(&[value])
4646
}
4747

4848
/// Read a single byte from a device, from a designated register
@@ -57,7 +57,7 @@ pub trait I2CDevice {
5757
///
5858
/// The register is specified through the Comm byte.
5959
fn smbus_write_byte_data(&mut self, register: u8, value: u8) -> Result<(), Self::Error> {
60-
self.write(&mut [register, value])
60+
self.write(&[register, value])
6161
}
6262

6363
/// Read 2 bytes from a given register on a device (lsb first)

src/ffi.rs

Lines changed: 45 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,8 @@
1010
#![allow(non_camel_case_types)]
1111

1212
use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt};
13-
use libc::c_int;
1413
use nix;
1514
use std::io::Cursor;
16-
use std::marker::PhantomData;
1715
use std::mem;
1816
use std::os::unix::prelude::*;
1917
use std::ptr;
@@ -34,24 +32,24 @@ pub struct i2c_msg {
3432

3533
bitflags! {
3634
struct I2CFunctions: u32 {
37-
const I2C_FUNC_I2C = 0x00000001;
38-
const I2C_FUNC_10BIT_ADDR = 0x00000002;
39-
const I2C_FUNC_PROTOCOL_MANGLING = 0x00000004; /* I2C_M_IGNORE_NAK etc. */
40-
const I2C_FUNC_SMBUS_PEC = 0x00000008;
41-
const I2C_FUNC_NOSTART = 0x00000010; /* I2C_M_NOSTART */
42-
const I2C_FUNC_SMBUS_BLOCK_PROC_CALL = 0x00008000; /* SMBus 2.0 */
43-
const I2C_FUNC_SMBUS_QUICK = 0x00010000;
44-
const I2C_FUNC_SMBUS_READ_BYTE = 0x00020000;
45-
const I2C_FUNC_SMBUS_WRITE_BYTE = 0x00040000;
46-
const I2C_FUNC_SMBUS_READ_BYTE_DATA = 0x00080000;
47-
const I2C_FUNC_SMBUS_WRITE_BYTE_DATA = 0x00100000;
48-
const I2C_FUNC_SMBUS_READ_WORD_DATA = 0x00200000;
49-
const I2C_FUNC_SMBUS_WRITE_WORD_DATA = 0x00400000;
50-
const I2C_FUNC_SMBUS_PROC_CALL = 0x00800000;
51-
const I2C_FUNC_SMBUS_READ_BLOCK_DATA = 0x01000000;
52-
const I2C_FUNC_SMBUS_WRITE_BLOCK_DATA = 0x02000000;
53-
const I2C_FUNC_SMBUS_READ_I2C_BLOCK = 0x04000000; /* I2C-like block xfer */
54-
const I2C_FUNC_SMBUS_WRITE_I2C_BLOCK = 0x08000000; /* w/ 1-byte reg. addr. */
35+
const I2C_FUNC_I2C = 0x0000_0001;
36+
const I2C_FUNC_10BIT_ADDR = 0x0000_0002;
37+
const I2C_FUNC_PROTOCOL_MANGLING = 0x0000_0004; /* I2C_M_IGNORE_NAK etc. */
38+
const I2C_FUNC_SMBUS_PEC = 0x0000_0008;
39+
const I2C_FUNC_NOSTART = 0x0000_0010; /* I2C_M_NOSTART */
40+
const I2C_FUNC_SMBUS_BLOCK_PROC_CALL = 0x0000_8000; /* SMBus 2.0 */
41+
const I2C_FUNC_SMBUS_QUICK = 0x0001_0000;
42+
const I2C_FUNC_SMBUS_READ_BYTE = 0x0002_0000;
43+
const I2C_FUNC_SMBUS_WRITE_BYTE = 0x0004_0000;
44+
const I2C_FUNC_SMBUS_READ_BYTE_DATA = 0x0008_0000;
45+
const I2C_FUNC_SMBUS_WRITE_BYTE_DATA = 0x0010_0000;
46+
const I2C_FUNC_SMBUS_READ_WORD_DATA = 0x0020_0000;
47+
const I2C_FUNC_SMBUS_WRITE_WORD_DATA = 0x0040_0000;
48+
const I2C_FUNC_SMBUS_PROC_CALL = 0x0080_0000;
49+
const I2C_FUNC_SMBUS_READ_BLOCK_DATA = 0x0100_0000;
50+
const I2C_FUNC_SMBUS_WRITE_BLOCK_DATA = 0x0200_0000;
51+
const I2C_FUNC_SMBUS_READ_I2C_BLOCK = 0x0400_0000; /* I2C-like block xfer */
52+
const I2C_FUNC_SMBUS_WRITE_I2C_BLOCK = 0x0800_0000; /* w/ 1-byte reg. addr. */
5553

5654
const I2C_FUNC_SMBUS_BYTE = (I2CFunctions::I2C_FUNC_SMBUS_READ_BYTE.bits |
5755
I2CFunctions::I2C_FUNC_SMBUS_WRITE_BYTE.bits);
@@ -164,7 +162,7 @@ mod ioctl {
164162

165163
pub fn i2c_set_slave_address(fd: RawFd, slave_address: u16) -> Result<(), nix::Error> {
166164
unsafe {
167-
ioctl::set_i2c_slave_address(fd, slave_address as i32)?;
165+
ioctl::set_i2c_slave_address(fd, i32::from(slave_address))?;
168166
}
169167
Ok(())
170168
}
@@ -178,9 +176,9 @@ unsafe fn i2c_smbus_access(
178176
) -> Result<(), I2CError> {
179177
let mut args = i2c_smbus_ioctl_data {
180178
read_write: read_write as u8,
181-
command: command,
179+
command,
182180
size: size as u32,
183-
data: data,
181+
data,
184182
};
185183

186184
// remove type information
@@ -189,9 +187,10 @@ unsafe fn i2c_smbus_access(
189187

190188
#[inline]
191189
pub fn i2c_smbus_write_quick(fd: RawFd, bit: bool) -> Result<(), I2CError> {
192-
let read_write = match bit {
193-
true => I2CSMBusReadWrite::I2C_SMBUS_READ,
194-
false => I2CSMBusReadWrite::I2C_SMBUS_WRITE,
190+
let read_write = if bit {
191+
I2CSMBusReadWrite::I2C_SMBUS_READ
192+
} else {
193+
I2CSMBusReadWrite::I2C_SMBUS_WRITE
195194
};
196195
unsafe {
197196
i2c_smbus_access(
@@ -258,9 +257,8 @@ pub fn i2c_smbus_write_byte_data(fd: RawFd, register: u8, value: u8) -> Result<(
258257
register,
259258
I2CSMBusSize::I2C_SMBUS_BYTE_DATA,
260259
&mut data,
261-
)?;
260+
)
262261
}
263-
Ok(())
264262
}
265263

266264
#[inline]
@@ -295,9 +293,8 @@ pub fn i2c_smbus_write_word_data(fd: RawFd, register: u8, value: u16) -> Result<
295293
register,
296294
I2CSMBusSize::I2C_SMBUS_WORD_DATA,
297295
&mut data,
298-
)?;
299-
};
300-
Ok(())
296+
)
297+
}
301298
}
302299

303300
#[inline]
@@ -364,23 +361,30 @@ pub fn i2c_smbus_read_i2c_block_data(
364361
}
365362

366363
#[inline]
367-
pub fn i2c_smbus_write_block_data(fd: RawFd, register: u8, values: &[u8]) -> Result<(), I2CError> {
364+
fn copy_to_i2c_block_data(values: &[u8], max_size: usize) -> i2c_smbus_data {
368365
let mut data = i2c_smbus_data::empty();
369-
let len: usize = if values.len() > 32 { 32 } else { values.len() };
366+
let len: usize = if values.len() > max_size {
367+
max_size
368+
} else {
369+
values.len()
370+
};
370371
data.block[0] = len as u8;
371-
for i in 1..(len + 1) {
372-
data.block[i] = values[i - 1];
373-
}
372+
data.block[1..=len].copy_from_slice(&values[..len]);
373+
data
374+
}
375+
376+
#[inline]
377+
pub fn i2c_smbus_write_block_data(fd: RawFd, register: u8, values: &[u8]) -> Result<(), I2CError> {
378+
let mut data = copy_to_i2c_block_data(&values, 32);
374379
unsafe {
375380
i2c_smbus_access(
376381
fd,
377382
I2CSMBusReadWrite::I2C_SMBUS_WRITE,
378383
register,
379384
I2CSMBusSize::I2C_SMBUS_BLOCK_DATA,
380385
&mut data,
381-
)?;
386+
)
382387
}
383-
Ok(())
384388
}
385389

386390
#[inline]
@@ -389,22 +393,16 @@ pub fn i2c_smbus_write_i2c_block_data(
389393
register: u8,
390394
values: &[u8],
391395
) -> Result<(), I2CError> {
392-
let mut data = i2c_smbus_data::empty();
393-
let len: usize = if values.len() > 32 { 32 } else { values.len() };
394-
data.block[0] = len as u8;
395-
for i in 1..(len + 1) {
396-
data.block[i] = values[i - 1];
397-
}
396+
let mut data = copy_to_i2c_block_data(&values, 32);
398397
unsafe {
399398
i2c_smbus_access(
400399
fd,
401400
I2CSMBusReadWrite::I2C_SMBUS_WRITE,
402401
register,
403402
I2CSMBusSize::I2C_SMBUS_I2C_BLOCK_DATA,
404403
&mut data,
405-
)?;
404+
)
406405
}
407-
Ok(())
408406
}
409407

410408
#[inline]
@@ -413,12 +411,7 @@ pub fn i2c_smbus_process_call_block(
413411
register: u8,
414412
values: &[u8],
415413
) -> Result<Vec<u8>, I2CError> {
416-
let mut data = i2c_smbus_data::empty();
417-
let len: usize = if values.len() > 31 { 31 } else { values.len() };
418-
data.block[0] = len as u8;
419-
for i in 1..(len + 1) {
420-
data.block[i] = values[i - 1];
421-
}
414+
let mut data = copy_to_i2c_block_data(&values, 31);
422415
unsafe {
423416
i2c_smbus_access(
424417
fd,

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,10 @@
9797
#![crate_name = "i2cdev"]
9898
#![crate_type = "lib"]
9999

100-
extern crate byteorder;
101-
extern crate libc;
102100
#[macro_use]
103101
extern crate bitflags;
102+
extern crate byteorder;
103+
extern crate libc;
104104
#[macro_use]
105105
extern crate nix;
106106

0 commit comments

Comments
 (0)