diff --git a/benches/b15f.rs b/benches/b15f.rs index a4c4060..91a63f3 100644 --- a/benches/b15f.rs +++ b/benches/b15f.rs @@ -11,4 +11,18 @@ mod tests { fn bench_create_instance(b: &mut Bencher) { b.iter(|| B15F::new()); } + + #[bench] + fn bench_digital_write(b: &mut Bencher) { + let mut drv = B15F::new().unwrap(); + + b.iter(move || drv.digital_write::<0>(0xAB).unwrap()); + } + + #[bench] + fn bench_digital_read(b: &mut Bencher) { + let mut drv = B15F::new().unwrap(); + + b.iter(move || drv.digital_read::<0>().unwrap()); + } } \ No newline at end of file diff --git a/doc/b15f/b15f/index.html b/doc/b15f/b15f/index.html index 00afab9..970e2d0 100644 --- a/doc/b15f/b15f/index.html +++ b/doc/b15f/b15f/index.html @@ -1,4 +1,4 @@ -b15f::b15f - Rust

Module b15f::b15f

source · []
Expand description

This module contains all the structures and functions related to +b15f::b15f - Rust

Module b15f::b15f

source · []
Expand description

This module contains all the structures and functions related to interacting with the B15 on a high level. If you are writing code for the B15, this is the module you want to use.

Structs

Structure representing the driver for the board 15
\ No newline at end of file diff --git a/doc/b15f/b15f/struct.B15F.html b/doc/b15f/b15f/struct.B15F.html index 9d095ad..895d93e 100644 --- a/doc/b15f/b15f/struct.B15F.html +++ b/doc/b15f/b15f/struct.B15F.html @@ -1,5 +1,5 @@ -B15F in b15f::b15f - Rust
pub struct B15F { /* private fields */ }
Expand description

Structure representing the driver for the board 15

-

Implementations

Creates a new instance of the B15

+B15F in b15f::b15f - Rust
pub struct B15F { /* private fields */ }
Expand description

Structure representing the driver for the board 15

+

Implementations

Creates a new instance of the B15

This function will establish a connection to a connected B15 and return a handle to interact with it. Only one such instance should exist per program; calling B15F::new() more than once might lead to unexpected @@ -14,21 +14,52 @@ established, or if testing of that connection fails.

use b15f::B15F;
  
 let drv = B15F::new().unwrap();
-

Sets the value of the specified port

+

Sets the value of the specified port

Errors
-

port can either be 0 or 1, other values will cause a compile-time +

PORT can either be 0 or 1, other values will cause a compile-time error. Otherwise an error::Error is generated if communication with the B15 fails.

-
Examples

Yields information about the installed firmware on the B15

+
Examples
+
use b15f::B15F;
+ 
+fn main() -> Result<(), String> {
+	let mut drv = B15F::new()?;
+ 
+	drv.digital_write::<0>(0xFF)?;		// Turn on all bits of port 0
+	drv.digital_write::<1>(0x0F)?;		// Turn on bits 0-4 of port 1
+ 
+	// drv.digital_write::<2>(0xFF);	// Compiler error
+ 
+	Ok(())
+}
+

Reads the value of the specified port

+
Errors
+

PORT can either be 0 or 1, other values will cause a compile-time +error. Otherwise an error::Error is generated if communication +with the B15 fails.

+
Examples
+
use b15f::B15F;
+ 
+fn main() -> Result<(), String> {
+	let mut drv = B15F::new()?;
+ 
+	let _ = drv.digital_read::<0>()?;		// Read inputs of port 0
+	let _ = drv.digital_read::<1>()?;		// Read inputs of port 1
+ 
+	// drv.digital_read::<2>();				// Compiler error
+ 
+	Ok(())
+}
+

Yields information about the installed firmware on the B15

Returns an array of strings, where each string contains a piece of information stored on the B15

Returns

A list of strings where each string contains a piece of information about the board. What string contains what information is determined, but not explicitly listed.

-
Errors
+
Errors

An error::Error is generated if the communication with the board fails.

-
Examples
+
Examples
use b15f::B15F;
  
 let mut drv = B15F::new().unwrap();
@@ -38,19 +69,19 @@ but not explicitly listed.

.unwrap() .iter() .for_each(|info| println!("{info}"));
-

Clears data in the USART buffers on this device and on the B15

-

Test the integer conversion of the USART connection

-
Errors
+

Clears data in the USART buffers on this device and on the B15

+

Test the integer conversion of the USART connection

+
Errors

If an error occurs in the conversion or the communication with the board, an error::Error will be returned.

-

Tests the connetion to the B15

+

Tests the connetion to the B15

To test the connection a Request::Test request will be sent to the board together with a randomly generated value. If the board returns that value the connection is working correctly.

-
Errors
+
Errors

An error::Error is returned if the test fails, or if the communication itself fails.

-
Examples
+
Examples
use b15f::B15F;
  
 fn main() {
@@ -60,7 +91,7 @@ communication itself fails.

panic!("Connection is not working: {err}"); } }
-

Trait Implementations

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

+

Trait Implementations

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

diff --git a/doc/b15f/index.html b/doc/b15f/index.html index d764cff..cdd9c19 100644 --- a/doc/b15f/index.html +++ b/doc/b15f/index.html @@ -1,4 +1,4 @@ -b15f - Rust

Crate b15f

source · []
Expand description

Driver code for the board 15

+b15f - Rust

Crate b15f

source · []
Expand description

Driver code for the board 15

It aims to be syntactically similar to the original implementation. The original repository is no longer maintained, and this library doesn’t maintain it either, it simply provides the same functionality in another language.

diff --git a/doc/search-index.js b/doc/search-index.js index 0903a4e..f8ad1b4 100644 --- a/doc/search-index.js +++ b/doc/search-index.js @@ -1,5 +1,5 @@ var searchIndex = JSON.parse('{\ -"b15f":{"doc":"Driver code for the board 15","t":[2,0,14,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["B15F","b15f","build_request","B15F","borrow","borrow_mut","digital_write","discard","fmt","from","get_board_info","into","new","test_connection","test_int_conv","try_from","try_into","type_id","vzip"],"q":["b15f","","","b15f::b15f","","","","","","","","","","","","","","",""],"d":["","This module contains all the structures and functions …","Builds a new request buffer from the given data","Structure representing the driver for the board 15","","","Sets the value of the specified port","Clears data in the USART buffers on this device and on the …","","Returns the argument unchanged.","Yields information about the installed firmware on the B15","Calls U::from(self).","Creates a new instance of the B15","Tests the connetion to the B15","Test the integer conversion of the USART connection","","","",""],"i":[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],"f":[0,0,0,0,[[]],[[]],[[1,2],[[3,[0]]]],[1,[[3,[0]]]],[[1,4],5],[[]],[1,[[3,[[7,[6]],0]]]],[[]],[[],[[3,[1,0]]]],[1,[[3,[0]]]],[1,[[3,[0]]]],[[],3],[[],3],[[],8],[[]]],"p":[[3,"B15F"],[15,"u8"],[4,"Result"],[3,"Formatter"],[6,"Result"],[3,"String"],[3,"Vec"],[3,"TypeId"]]}\ +"b15f":{"doc":"Driver code for the board 15","t":[2,0,14,3,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11],"n":["B15F","b15f","build_request","B15F","borrow","borrow_mut","digital_read","digital_write","discard","fmt","from","get_board_info","into","new","test_connection","test_int_conv","try_from","try_into","type_id","vzip"],"q":["b15f","","","b15f::b15f","","","","","","","","","","","","","","","",""],"d":["","This module contains all the structures and functions …","Builds a new request buffer from the given data","Structure representing the driver for the board 15","","","Reads the value of the specified port","Sets the value of the specified port","Clears data in the USART buffers on this device and on the …","","Returns the argument unchanged.","Yields information about the installed firmware on the B15","Calls U::from(self).","Creates a new instance of the B15","Tests the connetion to the B15","Test the integer conversion of the USART connection","","","",""],"i":[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],"f":[0,0,0,0,[[]],[[]],[1,[[3,[2,0]]]],[[1,2],[[3,[0]]]],[1,[[3,[0]]]],[[1,4],5],[[]],[1,[[3,[[7,[6]],0]]]],[[]],[[],[[3,[1,0]]]],[1,[[3,[0]]]],[1,[[3,[0]]]],[[],3],[[],3],[[],8],[[]]],"p":[[3,"B15F"],[15,"u8"],[4,"Result"],[3,"Formatter"],[6,"Result"],[3,"String"],[3,"Vec"],[3,"TypeId"]]}\ }'); if (typeof window !== 'undefined' && window.initSearch) {window.initSearch(searchIndex)}; if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex}; diff --git a/doc/source-files.js b/doc/source-files.js index 5669024..b008575 100644 --- a/doc/source-files.js +++ b/doc/source-files.js @@ -1,4 +1,4 @@ var sourcesIndex = JSON.parse('{\ -"b15f":["",[],["b15f.rs","error.rs","lib.rs","request.rs"]]\ +"b15f":["",[],["assert.rs","b15f.rs","error.rs","lib.rs","request.rs"]]\ }'); createSourceSidebar(); diff --git a/doc/src/b15f/assert.rs.html b/doc/src/b15f/assert.rs.html new file mode 100644 index 0000000..d8dbe2c --- /dev/null +++ b/doc/src/b15f/assert.rs.html @@ -0,0 +1,19 @@ +assert.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+
struct AssertInRange<const VALUE: usize, const MIN: usize, const MAX: usize>;
+
+impl<const VALUE: usize, const MIN: usize, const MAX: usize> AssertInRange<VALUE, MIN, MAX> {
+	const OK: () = assert!(MIN <= VALUE && VALUE <= MAX);
+}
+
+pub fn assert_in_range<const VALUE: usize, const MIN: usize, const MAX: usize> () {
+	let () = AssertInRange::<VALUE, MIN, MAX>::OK;
+}
+
\ No newline at end of file diff --git a/doc/src/b15f/b15f.rs.html b/doc/src/b15f/b15f.rs.html index 004a9f0..173dca6 100644 --- a/doc/src/b15f/b15f.rs.html +++ b/doc/src/b15f/b15f.rs.html @@ -314,6 +314,64 @@ 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
//! This module contains all the structures and functions related to
 //! interacting with the B15 on a high level. If you are writing code
 //! for the B15, this is the module you want to use.
@@ -321,9 +379,8 @@
 use std::{process::Command, time::Duration, fmt::Debug, thread::sleep};
 use rand::Rng;
 use serialport::SerialPort;
-use crate::error::Error;
 
-use crate::{request::Request, build_request};
+use crate::{assert::assert_in_range, error::Error, request::Request, build_request};
 
 macro_rules! log {
 	($text: literal, $($arg:tt)*) => (println!(concat!("[B15F] ", $text), $($arg)*));
@@ -435,30 +492,89 @@
 	/// Sets the value of the specified port
 	///
 	/// # Errors 
-	/// `port` can either be 0 or 1, other values will cause a compile-time
+	/// `PORT` can either be 0 or 1, other values will cause a compile-time
 	/// error. Otherwise an `error::Error` is generated if communication
 	/// with the B15 fails.
 	/// 
 	/// # Examples
+	/// ```
+	/// use b15f::B15F;
 	/// 
-	pub fn digital_write<const port: u8> (&mut self, value: u8) -> Result<(), Error> {
-		assert!(port == 0 || port == 1);
+	/// fn main() -> Result<(), String> {
+	/// 	let mut drv = B15F::new()?;
+	/// 
+	/// 	drv.digital_write::<0>(0xFF)?;		// Turn on all bits of port 0
+	/// 	drv.digital_write::<1>(0x0F)?;		// Turn on bits 0-4 of port 1
+	/// 
+	/// 	// drv.digital_write::<2>(0xFF);	// Compiler error
+	/// 
+	/// 	Ok(())
+	/// }
+	/// ```
+	/// 
+	pub fn digital_write<const PORT: usize> (&mut self, value: u8) -> Result<(), Error> {
+		assert_in_range::<PORT, 0, 1>();
 
 		let reversed = value.reverse_bits();
-		let request = if port == 0 { Request::DigitalWrite0 } else { Request::DigitalWrite1 };
-
+		let request = match PORT { 
+			0 => Request::DigitalWrite0,
+			1 => Request::DigitalWrite1,
+			_ => panic!("Report this issue to someone, this should not ever be visible.")
+		};
+		
 		self.usart.write(build_request![request, reversed])?;
 
 		let mut aw: [u8; 1] = [0; 1];
 		self.usart.read(&mut aw)?;
 
 		if aw[0] != B15F::MSG_OK {
-			return Err(format!("Setting Port {} failed", port).into());
+			return Err(format!("Setting Port {} failed", PORT).into());
 		}
 
 		Ok(())
 	}
 
+	/// Reads the value of the specified port
+	///
+	/// # Errors 
+	/// `PORT` can either be 0 or 1, other values will cause a compile-time
+	/// error. Otherwise an `error::Error` is generated if communication
+	/// with the B15 fails.
+	/// 
+	/// # Examples
+	/// ```
+	/// use b15f::B15F;
+	/// 
+	/// fn main() -> Result<(), String> {
+	/// 	let mut drv = B15F::new()?;
+	/// 
+	/// 	let _ = drv.digital_read::<0>()?;		// Read inputs of port 0
+	/// 	let _ = drv.digital_read::<1>()?;		// Read inputs of port 1
+	/// 
+	/// 	// drv.digital_read::<2>();				// Compiler error
+	/// 
+	/// 	Ok(())
+	/// }
+	/// ```
+	///
+	pub fn digital_read<const PORT: usize> (&mut self) -> Result<u8, Error> {
+	 	assert_in_range::<PORT, 0, 1>();
+
+		let request = match PORT {
+			0 => Request::DigitalRead0,
+			1 => Request::DigitalRead1,
+			_ => panic!("Report this issue to someone, this should not ever be visible.")
+		};
+
+		self.usart.clear(serialport::ClearBuffer::Input)?;
+		self.usart.write(build_request![request])?;
+
+		let mut aw: [u8; 1] = [0; 1];
+		self.usart.read(&mut aw)?;
+
+		Ok(u8::reverse_bits(aw[0]))
+	}
+
 	/// Yields information about the installed firmware on the B15
 	/// 
 	/// Returns an array of strings, where each string contains a piece
diff --git a/doc/src/b15f/error.rs.html b/doc/src/b15f/error.rs.html
index 1310124..775510a 100644
--- a/doc/src/b15f/error.rs.html
+++ b/doc/src/b15f/error.rs.html
@@ -40,6 +40,12 @@
 40
 41
 42
+43
+44
+45
+46
+47
+48
 
use std::fmt::Display;
 
 #[derive(Debug)]
@@ -77,6 +83,12 @@
 	}
 }
 
+impl From<Error> for String {
+	fn from(err: Error) -> Self {
+		err.message	
+	}
+}
+
 impl Display for Error {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "{}", self.message)
diff --git a/doc/src/b15f/lib.rs.html b/doc/src/b15f/lib.rs.html
index c99c952..7dc4593 100644
--- a/doc/src/b15f/lib.rs.html
+++ b/doc/src/b15f/lib.rs.html
@@ -18,6 +18,7 @@
 18
 19
 20
+21
 
#![deny(missing_docs,
     missing_debug_implementations,
     trivial_casts,
@@ -36,6 +37,7 @@
 pub mod b15f;
 mod request;
 mod error;
+mod assert;
 
 pub use crate::b15f::B15F;
\ No newline at end of file diff --git a/doc/src/b15f/request.rs.html b/doc/src/b15f/request.rs.html index 49544b3..cd90f5c 100644 --- a/doc/src/b15f/request.rs.html +++ b/doc/src/b15f/request.rs.html @@ -25,6 +25,8 @@ 25 26 27 +28 +29
//! This module contains the request data used to communicate
 //! with the B15 via USART. 
 //! 
@@ -51,5 +53,7 @@
 
 	DigitalWrite0 	= 5,
 	DigitalWrite1 	= 6,
-}
+ DigitalRead0 = 7, + DigitalRead1 = 8 +}
\ No newline at end of file diff --git a/examples/nightrider.rs b/examples/nightrider.rs index 8972314..df75f47 100644 --- a/examples/nightrider.rs +++ b/examples/nightrider.rs @@ -2,14 +2,14 @@ use std::{thread::sleep, time::Duration}; use b15f::b15f::B15F; -fn main() { - let mut drv = B15F::new().unwrap(); +fn main() -> Result<(), String> { + let mut drv = B15F::new()?; let mut position = 0; let mut direction = 1; loop { - drv.digital_write::<0>(1 << position); + drv.digital_write::<0>(1 << position)?; position += direction; if position >= 7 || position <= 0 { diff --git a/examples/read.rs b/examples/read.rs new file mode 100644 index 0000000..87e2434 --- /dev/null +++ b/examples/read.rs @@ -0,0 +1,8 @@ +use b15f::b15f::B15F; + +fn main() -> Result<(), String> { + let mut drv = B15F::new()?; + + println!("{}", drv.digital_read::<0>().unwrap()); + Ok(()) +} \ No newline at end of file diff --git a/src/b15f.rs b/src/b15f.rs index 1a1955c..e23f560 100644 --- a/src/b15f.rs +++ b/src/b15f.rs @@ -118,18 +118,36 @@ impl B15F { /// Sets the value of the specified port /// /// # Errors - /// `port` can either be 0 or 1, other values will cause a compile-time + /// `PORT` can either be 0 or 1, other values will cause a compile-time /// error. Otherwise an `error::Error` is generated if communication /// with the B15 fails. /// /// # Examples + /// ``` + /// use b15f::B15F; + /// + /// fn main() -> Result<(), String> { + /// let mut drv = B15F::new()?; + /// + /// drv.digital_write::<0>(0xFF)?; // Turn on all bits of port 0 + /// drv.digital_write::<1>(0x0F)?; // Turn on bits 0-4 of port 1 + /// + /// // drv.digital_write::<2>(0xFF); // Compiler error + /// + /// Ok(()) + /// } + /// ``` /// pub fn digital_write (&mut self, value: u8) -> Result<(), Error> { assert_in_range::(); let reversed = value.reverse_bits(); - let request = if PORT == 0 { Request::DigitalWrite0 } else { Request::DigitalWrite1 }; - + let request = match PORT { + 0 => Request::DigitalWrite0, + 1 => Request::DigitalWrite1, + _ => panic!("Report this issue to someone, this should not ever be visible.") + }; + self.usart.write(build_request![request, reversed])?; let mut aw: [u8; 1] = [0; 1]; @@ -142,6 +160,47 @@ impl B15F { Ok(()) } + /// Reads the value of the specified port + /// + /// # Errors + /// `PORT` can either be 0 or 1, other values will cause a compile-time + /// error. Otherwise an `error::Error` is generated if communication + /// with the B15 fails. + /// + /// # Examples + /// ``` + /// use b15f::B15F; + /// + /// fn main() -> Result<(), String> { + /// let mut drv = B15F::new()?; + /// + /// let _ = drv.digital_read::<0>()?; // Read inputs of port 0 + /// let _ = drv.digital_read::<1>()?; // Read inputs of port 1 + /// + /// // drv.digital_read::<2>(); // Compiler error + /// + /// Ok(()) + /// } + /// ``` + /// + pub fn digital_read (&mut self) -> Result { + assert_in_range::(); + + let request = match PORT { + 0 => Request::DigitalRead0, + 1 => Request::DigitalRead1, + _ => panic!("Report this issue to someone, this should not ever be visible.") + }; + + self.usart.clear(serialport::ClearBuffer::Input)?; + self.usart.write(build_request![request])?; + + let mut aw: [u8; 1] = [0; 1]; + self.usart.read(&mut aw)?; + + Ok(u8::reverse_bits(aw[0])) + } + /// Yields information about the installed firmware on the B15 /// /// Returns an array of strings, where each string contains a piece diff --git a/src/error.rs b/src/error.rs index 9efc9e3..8619d98 100644 --- a/src/error.rs +++ b/src/error.rs @@ -35,6 +35,12 @@ impl From for Error { } } +impl From for String { + fn from(err: Error) -> Self { + err.message + } +} + impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.message) diff --git a/src/request.rs b/src/request.rs index d268c91..dd66cf8 100644 --- a/src/request.rs +++ b/src/request.rs @@ -24,4 +24,6 @@ pub enum Request { DigitalWrite0 = 5, DigitalWrite1 = 6, + DigitalRead0 = 7, + DigitalRead1 = 8 } \ No newline at end of file