2525// 00000000 Unused
2626// ...x41 Unused Bytes
2727
28- use std:: collections:: HashMap ;
28+ use std:: { collections:: HashMap , thread :: sleep , time :: Duration } ;
2929
3030use {
3131 anyhow:: { Error , Result } ,
3232 hidapi:: { HidApi , HidDevice } ,
33- log:: trace,
33+ log:: { error , info , trace} ,
3434 serde:: Deserialize ,
3535 tokio:: sync:: mpsc:: Sender ,
3636} ;
@@ -40,6 +40,8 @@ use crate::{
4040 errors:: DeviceNotFound ,
4141} ;
4242
43+ const MAX_BACKOFF : u64 = 60 ;
44+
4345#[ derive( Debug ) ]
4446pub struct State { }
4547
@@ -143,11 +145,36 @@ impl XK68JS {
143145
144146impl Device for XK68JS {
145147 fn read_loop ( & mut self , tx : Sender < Event > ) {
146- let device = self . get_device ( ) . unwrap ( ) ;
148+ let mut device = None ;
149+ let mut backoff = 1 ;
147150
148151 loop {
149152 let mut buf: Vec < u8 > = vec ! [ 0 ; 64 ] ;
150- device. read ( & mut buf) . unwrap ( ) ;
153+
154+ let dev = match & device {
155+ Some ( device) => device,
156+ None => {
157+ backoff = ( backoff * 2 ) . min ( MAX_BACKOFF ) ;
158+ sleep ( Duration :: from_secs ( backoff) ) ;
159+ device = match self . get_device ( ) {
160+ Ok ( dev) => {
161+ info ! ( "Connection to device established" ) ;
162+ Some ( dev)
163+ }
164+ Err ( e) => {
165+ error ! ( "Error obtaining device: {}" , e) ;
166+ None
167+ }
168+ } ;
169+ continue ;
170+ }
171+ } ;
172+
173+ if let Err ( e) = dev. read ( & mut buf) {
174+ error ! ( "Couldn't read from device: {}" , e) ;
175+ device = None ;
176+ continue ;
177+ }
151178
152179 let events = self . process_buffer ( & buf) ;
153180
@@ -191,4 +218,3 @@ mod test {
191218 }
192219 }
193220}
194-
0 commit comments