Reformat code

This commit is contained in:
FliegendeWurst 2022-04-24 16:11:54 +02:00
parent d8b6ffec7e
commit 106e4050b0
3 changed files with 287 additions and 247 deletions

3
rustfmt.toml Normal file
View File

@ -0,0 +1,3 @@
hard_tabs = true
match_block_trailing_comma = true
max_width = 120

View File

@ -1,12 +1,12 @@
use std::{thread::sleep, time::{self, Duration}};
use std::{
thread::sleep,
time::{self, Duration},
};
use gpio_cdev::{EventType, Line, LineRequestFlags};
fn read_events(line: &gpio_cdev::Line, timeout: std::time::Duration) -> Result<Vec<(u64, EventType)>, SensorError> {
let input = line.request(
LineRequestFlags::INPUT,
0,
"read-data")?;
let input = line.request(LineRequestFlags::INPUT, 0, "read-data")?;
let mut last_state = 1;
let start = time::Instant::now();
@ -43,9 +43,8 @@ fn events_to_data(events: Vec<(u64, EventType)>) -> Vec<u8> {
}
})
.filter(|&d| d.is_some())
.map(|elapsed| {
if elapsed.unwrap() > 35 { 1 } else { 0 }
}).collect()
.map(|elapsed| if elapsed.unwrap() > 35 { 1 } else { 0 })
.collect()
}
const MAX_HUMIDITY: u16 = 1000;
@ -58,12 +57,15 @@ fn process_data(mut bits: &[u8]) -> Result<(u16, u16), SensorError> {
}
let bytes: Vec<u8> = bits
.chunks(8)
.map(|chunk| chunk.iter()
.map(|chunk| {
chunk
.iter()
.enumerate()
// 8 bits, starting with the MSB
.map(|(bit_idx, &x)| x << (7 - bit_idx))
.sum()
).collect();
})
.collect();
let rh = (bytes[0] as u16) << 8 | bytes[1] as u16;
if rh > MAX_HUMIDITY {
return Err(SensorError::HumidityTooHigh);
@ -71,12 +73,12 @@ fn process_data(mut bits: &[u8]) -> Result<(u16, u16), SensorError> {
let celsius = (bytes[2] as u16) << 8 | bytes[3] as u16;
if bits.len() >= 40 {
let cksum: u8 = bits[32..40]
.iter()
.enumerate()
.map(|(idx, &x)| x << (7 - idx))
.sum();
let actual_sum = (bytes[0].wrapping_add(bytes[1]).wrapping_add(bytes[2]).wrapping_add(bytes[3])) & 0xff;
let cksum: u8 = bits[32..40].iter().enumerate().map(|(idx, &x)| x << (7 - idx)).sum();
let actual_sum = (bytes[0]
.wrapping_add(bytes[1])
.wrapping_add(bytes[2])
.wrapping_add(bytes[3]))
& 0xff;
if actual_sum != cksum {
return Err(SensorError::ChecksumMismatch);
}
@ -86,7 +88,11 @@ fn process_data(mut bits: &[u8]) -> Result<(u16, u16), SensorError> {
#[test]
fn test_process_data() {
let x = process_data(&[1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1]).unwrap();
let x = process_data(&[
1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0,
0, 1, 1,
])
.unwrap();
assert_eq!(471, x.0);
assert_eq!(268, x.1);
}
@ -96,7 +102,7 @@ pub enum SensorError {
Io(gpio_cdev::Error),
ChecksumMismatch,
HumidityTooHigh,
Timeout
Timeout,
}
impl From<gpio_cdev::Error> for SensorError {

View File

@ -14,18 +14,17 @@ use embedded_hal::prelude::_embedded_hal_blocking_i2c_Write;
use gpio_cdev::{Chip, EventRequestFlags, EventType, LineRequestFlags};
use linux_embedded_hal::i2cdev::core::I2CDevice;
use linux_embedded_hal::i2cdev::linux::LinuxI2CError;
use rusqlite::{Connection, params};
use ssd1306::{prelude::*, I2CDisplayInterface, Ssd1306};
use linux_embedded_hal::{Delay, I2cdev};
use machine_ip;
use rusqlite::{params, Connection};
use ssd1306::{prelude::*, I2CDisplayInterface, Ssd1306};
use std::intrinsics::transmute;
use std::{env, mem, time};
use std::thread::sleep;
use std::time::{Duration, SystemTime};
use std::{env, mem, time};
static IMG_DATA: &[u8; 512] = include_bytes!("../rust.raw");
const CCS811_ADDR: u8 = 0x5A; // or 0x5B
const CCS811_STATUS: u8 = 0x00;
@ -46,16 +45,13 @@ const CCS811_SW_RESET: u8 = 0xFF;
struct CCS811 {
i2c: I2cdev,
addr: u8
addr: u8,
}
impl CCS811 {
fn new(mut i2c: I2cdev, addr: u8) -> Self {
i2c.set_slave_address(addr as u16).unwrap();
Self {
i2c,
addr
}
Self { i2c, addr }
}
fn check_for_error(&mut self) -> Option<u8> {
@ -85,7 +81,9 @@ impl CCS811 {
let mut setting = self.i2c.smbus_read_byte_data(CCS811_MEAS_MODE).map_err(Some)?;
setting &= !(0b00000111 << 4);
setting |= (mode as u8) << 4;
self.i2c.smbus_write_byte_data(CCS811_MEAS_MODE, setting).map_err(Some)?;
self.i2c
.smbus_write_byte_data(CCS811_MEAS_MODE, setting)
.map_err(Some)?;
Ok(())
}
@ -97,7 +95,10 @@ impl CCS811 {
/// Returns (eCO2, tVOC)
fn get_reading(&mut self) -> (u16, u16) {
let x = self.i2c.smbus_read_i2c_block_data(CCS811_ALG_RESULT_DATA, 4).unwrap();
(((x[0] as u16) << 8) | (x[1] as u16), ((x[2] as u16) << 8) | (x[3] as u16))
(
((x[0] as u16) << 8) | (x[1] as u16),
((x[2] as u16) << 8) | (x[3] as u16),
)
}
}
@ -116,12 +117,17 @@ fn main() {
panic!("missing argument: database path");
}
let database = Connection::open(&args[1]).expect("failed to open database");
database.execute("
database
.execute(
"
CREATE TABLE IF NOT EXISTS sensor_readings(
time INTEGER PRIMARY KEY,
humidity INTEGER NOT NULL,
celsius INTEGER NOT NULL
)", []).unwrap();
)",
[],
)
.unwrap();
/*
let mut ccs = CCS811::new(i2c, CCS811_ADDR);
@ -135,10 +141,17 @@ fn main() {
let mut chip = Chip::new("/dev/gpiochip0").unwrap();
let line = chip.get_line(26).unwrap();
for _attempt in 0..5 {
let time = std::time::SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
let time = std::time::SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
if let Ok((rh, temp)) = raspi_oled::am2302_reading(&line) {
if rh > 0 && temp < 500 {
database.execute("INSERT INTO sensor_readings (time, humidity, celsius) VALUES (?1, ?2, ?3)", params![time.as_secs(), rh, temp]).unwrap();
database
.execute(
"INSERT INTO sensor_readings (time, humidity, celsius) VALUES (?1, ?2, ?3)",
params![time.as_secs(), rh, temp],
)
.unwrap();
display_on_ssd1306(rh, temp, time);
break;
}
@ -146,15 +159,10 @@ fn main() {
}
}
fn display_on_ssd1306(rh: u16, temp: u16, time: Duration) {
let i2c = I2cdev::new("/dev/i2c-1").unwrap();
let interface = I2CDisplayInterface::new(i2c);
let mut disp = Ssd1306::new(
interface,
DisplaySize128x64,
DisplayRotation::Rotate0,
).into_buffered_graphics_mode();
let mut disp = Ssd1306::new(interface, DisplaySize128x64, DisplayRotation::Rotate0).into_buffered_graphics_mode();
disp.init().unwrap();
@ -164,14 +172,10 @@ fn display_on_ssd1306(rh: u16, temp: u16, time: Duration) {
.build();
let text = format!("{}.{}% {}.{}°C", rh / 10, rh % 10, temp / 10, temp % 10);
Text::new(&text, Point::new(0, 10), text_style)
.draw(&mut disp)
.unwrap();
Text::new(&text, Point::new(0, 10), text_style).draw(&mut disp).unwrap();
let secs = time.as_secs();
let time = format!("{:02}:{:02} Uhr", (secs / 3600 + 2) % 24, secs / 60 % 60);
Text::new(&time, Point::new(0, 32), text_style)
.draw(&mut disp)
.unwrap();
Text::new(&time, Point::new(0, 32), text_style).draw(&mut disp).unwrap();
disp.flush().unwrap();
/*
sleep(Duration::from_secs(2));
@ -248,6 +252,7 @@ impl InputPin for LineWrapper {
}
impl OutputPin for LineWrapper {
<<<<<<< HEAD
type Error = gpio_cdev::Error;
fn set_low(&mut self) -> Result<(), Self::Error> {
@ -258,3 +263,29 @@ impl OutputPin for LineWrapper {
self.0.request(LineRequestFlags::OUTPUT, 1, "rust-line-wrapper")?.set_value(1)
}
}
||||||| parent of 683458d (Reformat code)
type Error = gpio_cdev::Error;
fn set_low(&mut self) -> Result<(), Self::Error> {
self.0.request(LineRequestFlags::OUTPUT, 1, "rust-line-wrapper")?.set_value(0)
}
fn set_high(&mut self) -> Result<(), Self::Error> {
self.0.request(LineRequestFlags::OUTPUT, 1, "rust-line-wrapper")?.set_value(1)
}
}
=======
type Error = gpio_cdev::Error;
fn set_low(&mut self) -> Result<(), Self::Error> {
self.0
.request(LineRequestFlags::OUTPUT, 1, "rust-line-wrapper")?
.set_value(0)
}
fn set_high(&mut self) -> Result<(), Self::Error> {
self.0
.request(LineRequestFlags::OUTPUT, 1, "rust-line-wrapper")?
.set_value(1)
}
}