@@ -49,7 +49,6 @@ extern crate futures;
49
49
#[ cfg( feature = "mio-evented" ) ]
50
50
extern crate mio;
51
51
extern crate nix;
52
- extern crate regex;
53
52
#[ cfg( feature = "tokio" ) ]
54
53
extern crate tokio_core;
55
54
@@ -78,6 +77,8 @@ use tokio_core::reactor::{Handle, PollEvented};
78
77
mod error;
79
78
pub use error:: Error ;
80
79
80
+ const GPIO_PATH_PREFIX : & ' static str = "/sys/class/gpio/gpio" ;
81
+
81
82
#[ derive( Clone , Copy , Debug , PartialEq , Eq ) ]
82
83
pub struct Pin {
83
84
pin_num : u64 ,
@@ -176,26 +177,23 @@ impl Pin {
176
177
a directory"
177
178
. to_owned ( ) ) ) ;
178
179
}
179
-
180
- let re = regex:: Regex :: new ( r"^/sys/.*?/gpio/gpio(\d+)$" ) . unwrap ( ) ;
181
- let caps = match re. captures ( pb. to_str ( ) . unwrap_or ( "" ) ) {
182
- Some ( cap) => cap,
183
- None => return Err ( Error :: InvalidPath ( format ! ( "{:?}" , pb) ) ) ,
184
- } ;
185
-
186
- let num: u64 = match caps. at ( 1 ) {
187
- Some ( num) => {
188
- match num. parse ( ) {
189
- Ok ( unum) => unum,
190
- Err ( _) => return Err ( Error :: InvalidPath ( format ! ( "{:?}" , pb) ) ) ,
191
- }
192
- }
193
- None => return Err ( Error :: InvalidPath ( format ! ( "{:?}" , pb) ) ) ,
194
- } ;
195
-
180
+ let num = Pin :: extract_pin_from_path ( & pb. to_str ( ) . unwrap_or ( "" ) ) ?;
196
181
Ok ( Pin :: new ( num) )
197
182
}
198
183
184
+ /// Extract pin number from paths like /sys/class/gpio/gpioXXX
185
+ fn extract_pin_from_path ( path : & str ) -> Result < u64 > {
186
+ if path. starts_with ( GPIO_PATH_PREFIX ) {
187
+ path. split_at ( GPIO_PATH_PREFIX . len ( ) ) . 1 . parse :: < u64 > ( ) . or (
188
+ Err (
189
+ Error :: InvalidPath ( format ! ( "{:?}" , path) ) ,
190
+ ) ,
191
+ )
192
+ } else {
193
+ Err ( Error :: InvalidPath ( format ! ( "{:?}" , path) ) )
194
+ }
195
+ }
196
+
199
197
/// Get the pin number
200
198
pub fn get_pin_num ( & self ) -> u64 {
201
199
self . pin_num
@@ -483,6 +481,18 @@ impl Pin {
483
481
}
484
482
}
485
483
484
+ #[ test]
485
+ fn extract_pin_fom_path_test ( ) {
486
+ let tok = Pin :: extract_pin_from_path ( & "/sys/class/gpio/gpio951" ) ;
487
+ assert_eq ! ( 951 , tok. unwrap( ) ) ;
488
+ let err1 = Pin :: extract_pin_from_path ( & "/sys/is/error/gpio/gpio111" ) ;
489
+ assert_eq ! ( true , err1. is_err( ) ) ;
490
+ let err2 = Pin :: extract_pin_from_path ( & "/sys/CLASS/gpio/gpio" ) ;
491
+ assert_eq ! ( true , err2. is_err( ) ) ;
492
+ let err3 = Pin :: extract_pin_from_path ( & "/sys/class/gpio/gpioSDS" ) ;
493
+ assert_eq ! ( true , err3. is_err( ) ) ;
494
+ }
495
+
486
496
#[ derive( Debug ) ]
487
497
pub struct PinPoller {
488
498
pin_num : u64 ,
0 commit comments