From 794286d2a8ec12e9406d8a5545343aaca2b45e83 Mon Sep 17 00:00:00 2001 From: Claas Date: Sat, 27 Jul 2024 01:10:14 +0200 Subject: [PATCH] Clean up --- debug-listener/src/main.rs | 13 +++-- fan-controller/src/main.rs | 49 +++++++---------- mqtt/src/main.rs | 106 +++++++++++++++++++++++++++---------- 3 files changed, 102 insertions(+), 66 deletions(-) diff --git a/debug-listener/src/main.rs b/debug-listener/src/main.rs index fb878d9..8d0e0cb 100644 --- a/debug-listener/src/main.rs +++ b/debug-listener/src/main.rs @@ -1,11 +1,9 @@ - -use std::time::Duration; use serialport::{DataBits, Parity, SerialPort, StopBits}; +use std::time::Duration; // This might change depending on your system. Could put this in an environment variable const PORT_NAME: &str = "/dev/cu.usbserial-2150"; - fn open_serial_port() -> serialport::Result> { serialport::new(PORT_NAME, 19_200) .timeout(Duration::from_secs(120)) @@ -24,7 +22,6 @@ async fn main() -> serialport::Result<()> { let mut count = 0u64; loop { - let mut buffer = [0u8; 32]; // We expect this length but this is a test, and it could not be guaranteed @@ -39,12 +36,14 @@ async fn main() -> serialport::Result<()> { let bytes_read = port.read(&mut buffer)?; // let mut buffer = Vec::with_capacity(7); // let bytes_read = port.read_to_end(&mut buffer)?; - println!("message {count} - bytes_read: ({:?}) {:?} {:#b} {:#b} ", bytes_read, buffer, buffer[0], buffer[1]); + println!( + "message {count} - bytes_read: ({:?}) {:?} {:#b} {:#b} ", + bytes_read, buffer, buffer[0], buffer[1] + ); // let inverse: Vec = buffer.iter().map(|byte| byte.to_be()).collect::>(); // println!("message {count} - inverse: {:?}", inverse); count += 1; - // tokio::time::sleep(std::time::Duration::from_secs(1)).await; } -} \ No newline at end of file +} diff --git a/fan-controller/src/main.rs b/fan-controller/src/main.rs index 77bf4dc..7d79585 100644 --- a/fan-controller/src/main.rs +++ b/fan-controller/src/main.rs @@ -17,17 +17,17 @@ use cyw43_pio::PioSpi; use defmt::*; use embassy_executor::Spawner; use embassy_futures::yield_now; -use embassy_net::{Config, Stack, StackResources}; use embassy_net::tcp::client::{TcpClient, TcpClientState}; +use embassy_net::{Config, Stack, StackResources}; +use embassy_rp::clocks::RoscRng; use embassy_rp::gpio::{Input, Level, Output, Pin, Pull}; use embassy_rp::peripherals::{ DMA_CH0, PIN_12, PIN_13, PIN_18, PIN_23, PIN_24, PIN_25, PIN_29, PIN_4, PIO0, UART0, }; use embassy_rp::pio::{InterruptHandler, Pio, PioPin}; -use embassy_rp::uart::Uart; -use embassy_rp::{bind_interrupts, uart, Peripherals, Peripheral, pio, dma}; -use embassy_rp::clocks::RoscRng; use embassy_rp::spi::ClkPin; +use embassy_rp::uart::Uart; +use embassy_rp::{bind_interrupts, dma, pio, uart, Peripheral, Peripherals}; use embassy_time::{Duration, Timer}; use mqttrust_core::bbqueue::BBBuffer; use reqwless::client::{TlsConfig, TlsVerify}; @@ -85,8 +85,8 @@ async fn gain_control( spawner: Spawner, pwr_pin: PIN_23, cs_pin: PIN_25, - pio: PIO0,//impl Peripheral, - dma: DMA_CH0,//impl Peripheral, + pio: PIO0, //impl Peripheral, + dma: DMA_CH0, //impl Peripheral, dio: impl PioPin, clk: impl PioPin, ) -> Control<'static> { @@ -105,15 +105,7 @@ async fn gain_control( let pwr = Output::new(pwr_pin, Level::Low); let cs = Output::new(cs_pin, Level::High); let mut pio = Pio::new(pio, Irqs); - let spi = PioSpi::new( - &mut pio.common, - pio.sm0, - pio.irq0, - cs, - dio, - clk, - dma, - ); + let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, dio, clk, dma); static STATE: StaticCell = StaticCell::new(); let state = STATE.init(cyw43::State::new()); @@ -155,8 +147,10 @@ async fn setup_tls(spawner: Spawner, net_device: NetDriver, mut control: Control static RESOURCES: StaticCell> = StaticCell::new(); let stack = &*STACK.init(Stack::new( net_device, - configuration, RESOURCES.init(StackResources::<5>::new()), seed)); - + configuration, + RESOURCES.init(StackResources::<5>::new()), + seed, + )); unwrap!(spawner.spawn(net_task(stack))); @@ -199,8 +193,12 @@ async fn setup_tls(spawner: Spawner, net_device: NetDriver, mut control: Control let dns_client = embassy_net::dns::DnsSocket::new(stack); //TODO consider increasing security by including a pre shared key otherwise this is // vulnerable to man in the middle attacks - let tls_configuration = TlsConfig::new(seed, &mut tls_read_buffer, &mut tls_write_buffer, TlsVerify::None); - + let tls_configuration = TlsConfig::new( + seed, + &mut tls_read_buffer, + &mut tls_write_buffer, + TlsVerify::None, + ); // MQTT stuff following the examples in the mqttrust repository static mut BUFFER: BBBuffer<{ 1024 * 6 }> = BBBuffer::new(); @@ -230,16 +228,7 @@ async fn main(spawner: Spawner) { .. } = embassy_rp::init(Default::default()); - let mut control = gain_control( - spawner, - pin_23, - pin_25, - pio0, - dma_ch0, - pin_24, - pin_29, - ) - .await; + let mut control = gain_control(spawner, pin_23, pin_25, pio0, dma_ch0, pin_24, pin_29).await; // UART things // PIN_4 seems to refer to GP4 on the Pico W pinout @@ -280,7 +269,7 @@ async fn main(spawner: Spawner) { // 50% fan::State::High => fan::MAX_SET_POINT / 2, } - .to_be_bytes(); + .to_be_bytes(); control.gpio_set(0, true).await; // Form message to fan 1 diff --git a/mqtt/src/main.rs b/mqtt/src/main.rs index c30f28e..7467443 100644 --- a/mqtt/src/main.rs +++ b/mqtt/src/main.rs @@ -1,9 +1,11 @@ use std::net::{AddrParseError, SocketAddr, ToSocketAddrs}; +use std::ops::{BitOrAssign, Rem}; use std::str::FromStr; use std::sync::Arc; +use std::{cmp, ops}; use tokio::net::TcpStream; -use tokio_rustls::rustls::{ClientConfig, RootCertStore}; use tokio_rustls::rustls::pki_types::{InvalidDnsNameError, ServerName}; +use tokio_rustls::rustls::{ClientConfig, RootCertStore}; use tokio_rustls::TlsConnector; const MQTT_BROKER_ADDRESS: &str = "91c57a00c93443dc90b40bfcaefa7aa3.s1.eu.hivemq.cloud"; @@ -19,31 +21,38 @@ enum AppError { } /// Encodes an integer as variable byte integer according to the MQTT specification -fn encode_variable_byte_integer(mut x: u32) -> Vec { +fn encode_variable_byte_integer(mut value: u32) -> Vec { // Each byte can hold 7 bits, so how many 7 bit "bytes" do we need for 32 bits? // 32 / 7 - let length = 32usize.div_ceil(7); + let length: usize = match value { + 0..=127 => 1, + 128..=16_383 => 2, + 16_384..=2_097_151 => 3, + 2_097_152..=268_435_455 => 4, + _ => 5, + }; let mut output = Vec::with_capacity(length); loop { // 128 = 0b1000_0000 // x = 128 = 0b1000_0000 // encoded_byte = 128 % 0b1000_0000 = 0 - let mut encoded_byte = (x % 0b1000_0000); - println!("Encoded byte (remainder): {encoded_byte:#010b} {encoded_byte} {x} {}", 0x00_00_80_01_u32); + let mut encoded_byte = (value % 0b1000_0000); + println!( + "Encoded byte (remainder): {encoded_byte:#010b} {encoded_byte} {value} {}", + 0x00_00_80_01_u32 + ); // x = 128 / 128 = 1 - x = x / 0b1000_0000; + value = value / 0b1000_0000; // If there is more data to encode, set the top bit of this byte - if x > 0 { + if value > 0 { encoded_byte |= 0b1000_0000; } output.push(encoded_byte as u8); - if x > 0 { - continue; - } else { + if value == 0 { break; } } @@ -62,15 +71,33 @@ fn can_encode_variable_byte_integer() { assert_eq!(encode_variable_byte_integer(1), [0b0000_0001]); assert_eq!(encode_variable_byte_integer(127), [0b0111_1111]); // Range two bytes - assert_eq!(encode_variable_byte_integer(128), [0b1000_0000, 0b0000_0001]); - assert_eq!(encode_variable_byte_integer(16_383), [0b1111_1111, 0b0111_1111]); + assert_eq!( + encode_variable_byte_integer(128), + [0b1000_0000, 0b0000_0001] + ); + assert_eq!( + encode_variable_byte_integer(16_383), + [0b1111_1111, 0b0111_1111] + ); // Range three bytes - assert_eq!(encode_variable_byte_integer(16_384), [0b1000_0000, 0b1000_0000, 0b0000_0001]); - assert_eq!(encode_variable_byte_integer(2_097_151), [0b1111_1111, 0b1111_1111, 0b0111_1111]); + assert_eq!( + encode_variable_byte_integer(16_384), + [0b1000_0000, 0b1000_0000, 0b0000_0001] + ); + assert_eq!( + encode_variable_byte_integer(2_097_151), + [0b1111_1111, 0b1111_1111, 0b0111_1111] + ); // Range four bytes - assert_eq!(encode_variable_byte_integer(2_097_152), [0b1000_0000, 0b1000_0000, 0b1000_0000, 0b0000_0001]); - assert_eq!(encode_variable_byte_integer(268_435_455), [0b1111_1111, 0b1111_1111, 0b1111_1111, 0b0111_1111]); + assert_eq!( + encode_variable_byte_integer(2_097_152), + [0b1000_0000, 0b1000_0000, 0b1000_0000, 0b0000_0001] + ); + assert_eq!( + encode_variable_byte_integer(268_435_455), + [0b1111_1111, 0b1111_1111, 0b1111_1111, 0b0111_1111] + ); } #[derive(Debug)] @@ -79,16 +106,17 @@ enum DecodeVariableByteIntegerError { UnexpectedEndOfInput, } - -fn decode_variable_byte_integer(bytes: impl IntoIterator + std::fmt::Debug) -> Result { - dbg!(&bytes); +fn decode_variable_byte_integer( + bytes: impl IntoIterator + std::fmt::Debug, +) -> Result { let mut multiplier = 1; let mut value: u32 = 0; let mut bytes = bytes.into_iter(); loop { - let encoded_byte = bytes.next().ok_or(DecodeVariableByteIntegerError::UnexpectedEndOfInput)?; - dbg!(encoded_byte); + let encoded_byte = bytes + .next() + .ok_or(DecodeVariableByteIntegerError::UnexpectedEndOfInput)?; value += (encoded_byte & 127) as u32 * multiplier; @@ -121,16 +149,34 @@ fn can_decode_variable_byte_integer() { assert_eq!(decode_variable_byte_integer([0b0111_1111]).unwrap(), 127); // Range two bytes - assert_eq!(decode_variable_byte_integer([0b1000_0000, 0b0000_0001]).unwrap(), 128); - assert_eq!(decode_variable_byte_integer([0b1111_1111, 0b0111_1111]).unwrap(), 16_383); + assert_eq!( + decode_variable_byte_integer([0b1000_0000, 0b0000_0001]).unwrap(), + 128 + ); + assert_eq!( + decode_variable_byte_integer([0b1111_1111, 0b0111_1111]).unwrap(), + 16_383 + ); // Range three bytes - assert_eq!(decode_variable_byte_integer([0b1000_0000, 0b1000_0000, 0b0000_0001]).unwrap(), 16_384); - assert_eq!(decode_variable_byte_integer([0b1111_1111, 0b1111_1111, 0b0111_1111]).unwrap(), 2_097_151); + assert_eq!( + decode_variable_byte_integer([0b1000_0000, 0b1000_0000, 0b0000_0001]).unwrap(), + 16_384 + ); + assert_eq!( + decode_variable_byte_integer([0b1111_1111, 0b1111_1111, 0b0111_1111]).unwrap(), + 2_097_151 + ); // Range four bytes - assert_eq!(decode_variable_byte_integer([0b1000_0000, 0b1000_0000, 0b1000_0000, 0b0000_0001]).unwrap(), 2_097_152); - assert_eq!(decode_variable_byte_integer([0b1111_1111, 0b1111_1111, 0b1111_1111, 0b0111_1111]).unwrap(), 268_435_455); + assert_eq!( + decode_variable_byte_integer([0b1000_0000, 0b1000_0000, 0b1000_0000, 0b0000_0001]).unwrap(), + 2_097_152 + ); + assert_eq!( + decode_variable_byte_integer([0b1111_1111, 0b1111_1111, 0b1111_1111, 0b0111_1111]).unwrap(), + 268_435_455 + ); } #[tokio::main] @@ -141,7 +187,10 @@ async fn main() -> Result<(), AppError> { .with_root_certificates(root_certificate_store) .with_no_client_auth(); let connector = TlsConnector::from(Arc::new(configuration)); - let address = (MQTT_BROKER_ADDRESS, 8883).to_socket_addrs()?.next().unwrap(); + let address = (MQTT_BROKER_ADDRESS, 8883) + .to_socket_addrs()? + .next() + .unwrap(); // let address = SocketAddr::from_str(MQTT_BROKER_ADDRESS)?; let server_name = ServerName::try_from("91c57a00c93443dc90b40bfcaefa7aa3.s1.eu.hivemq.cloud")?; @@ -152,7 +201,6 @@ async fn main() -> Result<(), AppError> { // Connection request let fixed_header = 0b001_0000_u8; - println!("Hello, world! {fixed_header}"); Ok(()) } -- 2.51.2