wishbone-bridge 1.1.0

A library to control Wishbone devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::Duration;

use log::{debug, error, info};

use crate::{Bridge, BridgeConfig, BridgeError};

/// Connect to a target device via USB.
#[derive(Clone, Default)]
pub struct UsbBridge {
    /// If specified, indicate the USB product ID to match.
    pid: Option<u16>,

    /// If specified, indicate the USB vendor ID to match.
    vid: Option<u16>,

    /// If specified, indicate the USB bus number to look for.
    bus: Option<u8>,

    /// If specified, indicate the USB device number to look for.
    device: Option<u8>,
}

/// A builder to create a connection to a target via USB. You should
/// specify at least a USB VID or PID in order to avoid connecting
/// to any random device on your system.
///
/// ```no_run
/// use wishbone_bridge::UsbBridge;
/// let bridge = UsbBridge::new().pid(0x1234).create().unwrap();
/// ```
impl UsbBridge {
    /// Create a new `UsbBridge` object that will attempt to connect to
    /// any USB device on the system.
    pub fn new() -> UsbBridge {
        UsbBridge {
            pid: None,
            vid: None,
            bus: None,
            device: None,
        }
    }

    /// Specify a USB PID to connect to.
    pub fn pid(&mut self, pid: u16) -> &mut UsbBridge {
        self.pid = Some(pid);
        self
    }

    /// Specify a USB VID to connect to.
    pub fn vid(&mut self, vid: u16) -> &mut UsbBridge {
        self.vid = Some(vid);
        self
    }

    /// Limit connections to a specific USB bus number.
    pub fn bus(&mut self, bus: u8) -> &mut UsbBridge {
        self.bus = Some(bus);
        self
    }

    /// Limit connections to a specific USB device.
    pub fn device(&mut self, device: u8) -> &mut UsbBridge {
        self.device = Some(device);
        self
    }

    /// Create a bridge based on the current configuration.
    pub fn create(&self) -> Result<Bridge, BridgeError> {
        Bridge::new(BridgeConfig::UsbBridge(self.clone()))
    }
}

pub struct UsbBridgeInner {
    usb_pid: Option<u16>,
    usb_vid: Option<u16>,
    main_tx: Sender<ConnectThreadRequests>,
    main_rx: Arc<(Mutex<Option<ConnectThreadResponses>>, Condvar)>,
    mutex: Arc<Mutex<()>>,
    poll_thread: Option<thread::JoinHandle<()>>,
}

enum ConnectThreadRequests {
    StartPolling(Option<u16> /* vid */, Option<u16> /* pid */),
    Exit,
    Poke(u32 /* addr */, u32 /* val */),
    Peek(u32 /* addr */),
    BurstRead(u32 /* addr */, u32 /* len */),
    BurstWrite(u32 /* addr */, Vec<u8> /* write data */)
}

#[derive(Debug)]
enum ConnectThreadResponses {
    OpenedDevice,
    PeekResult(Result<u32, BridgeError>),
    BurstReadResult(Result<Vec<u8>, BridgeError>),
    BurstWriteResult(Result<(), BridgeError>),
    PokeResult(Result<(), BridgeError>),
    Exiting,
}

impl Clone for UsbBridgeInner {
    fn clone(&self) -> Self {
        UsbBridgeInner {
            usb_pid: self.usb_pid,
            usb_vid: self.usb_vid,
            main_tx: self.main_tx.clone(),
            main_rx: self.main_rx.clone(),
            mutex: self.mutex.clone(),
            poll_thread: None,
        }
    }
}

impl UsbBridgeInner {
    pub fn new(cfg: &UsbBridge) -> Result<Self, BridgeError> {
        let usb_ctx = libusb_wishbone_tool::Context::new()?;
        let (main_tx, thread_rx) = channel();
        let cv = Arc::new((Mutex::new(None), Condvar::new()));

        let thr_cfg = cfg.clone();
        let thr_cv = cv.clone();
        let poll_thread = Some(thread::spawn(move || {
            Self::usb_poll_thread(usb_ctx, thr_cv, thread_rx, thr_cfg, 0x43)
        }));

        Ok(UsbBridgeInner {
            usb_pid: cfg.pid,
            usb_vid: cfg.vid,
            main_tx,
            main_rx: cv,
            mutex: Arc::new(Mutex::new(())),
            poll_thread,
        })
    }

    fn device_matches(
        device: &libusb_wishbone_tool::Device,
        device_desc: &libusb_wishbone_tool::DeviceDescriptor,
        cfg: &UsbBridge,
    ) -> bool {
        if let Some(pid) = cfg.pid {
            if pid != device_desc.product_id() {
                return false;
            }
        }
        if let Some(vid) = cfg.vid {
            if vid != device_desc.vendor_id() {
                return false;
            }
        }
        if let Some(bus) = cfg.bus {
            if bus != device.bus_number() {
                return false;
            }
        }
        if let Some(device_id) = cfg.device {
            if device_id != device.address() {
                return false;
            }
        }
        true
    }

    pub fn mutex(&self) -> &Arc<Mutex<()>> {
        &self.mutex
    }

    pub fn connect(&self) -> Result<(), BridgeError> {
        self.main_tx
            .send(ConnectThreadRequests::StartPolling(
                self.usb_pid,
                self.usb_vid,
            ))
            .unwrap();
        loop {
            let &(ref lock, ref cvar) = &*self.main_rx;
            let mut _mtx = lock.lock().unwrap();
            *_mtx = None;
            while _mtx.is_none() {
                _mtx = cvar.wait(_mtx).unwrap();
            }
            if let Some(ConnectThreadResponses::OpenedDevice) = _mtx.take() {
                return Ok(());
            }
        }
    }

    fn usb_poll_thread(
        usb_ctx: libusb_wishbone_tool::Context,
        tx: Arc<(Mutex<Option<ConnectThreadResponses>>, Condvar)>,
        rx: Receiver<ConnectThreadRequests>,
        mut cfg: UsbBridge,
        debug_byte: u8,
    ) {
        let mut print_waiting_message = true;
        let mut first_open = true;
        let &(ref response, ref cvar) = &*tx;
        loop {
            let devices = usb_ctx.devices().unwrap();
            for device in devices.iter() {
                let device_desc = device.device_descriptor().unwrap();
                if Self::device_matches(&device, &device_desc, &cfg) {
                    let usb = match device.open() {
                        Ok(o) => {
                            info!(
                                "opened USB device device {:03} on bus {:03}",
                                device.address(),
                                device.bus_number()
                            );
                            if first_open {
                                *response.lock().unwrap() =
                                    Some(ConnectThreadResponses::OpenedDevice);
                                cvar.notify_one();
                                first_open = false;
                            }
                            print_waiting_message = true;
                            o
                        }
                        Err(e) => {
                            error!("unable to open usb device: {:?}", e);
                            continue;
                        }
                    };
                    let mut keep_going = true;
                    while keep_going {
                        let var = rx.recv();
                        match var {
                            Err(e) => panic!("error in connect thread: {}", e),
                            Ok(o) => match o {
                                ConnectThreadRequests::Exit => {
                                    debug!("usb_poll_thread requested exit");
                                    *response.lock().unwrap() =
                                        Some(ConnectThreadResponses::Exiting);
                                    cvar.notify_one();
                                    return;
                                }
                                ConnectThreadRequests::StartPolling(p, v) => {
                                    cfg.pid = p;
                                    cfg.vid = v;
                                }
                                ConnectThreadRequests::Peek(addr) => {
                                    let result = Self::do_peek(&usb, addr, debug_byte);
                                    keep_going = result.is_ok();
                                    *response.lock().unwrap() =
                                        Some(ConnectThreadResponses::PeekResult(result));
                                    cvar.notify_one();
                                }
                                ConnectThreadRequests::Poke(addr, val) => {
                                    let result = Self::do_poke(&usb, addr, val, debug_byte);
                                    keep_going = result.is_ok();
                                    *response.lock().unwrap() =
                                        Some(ConnectThreadResponses::PokeResult(result));
                                    cvar.notify_one();
                                }
                                ConnectThreadRequests::BurstRead(addr, len) => {
                                    let result = Self::do_burst_read(&usb, addr, len, debug_byte);
                                    keep_going = result.is_ok();
                                    *response.lock().unwrap() =
                                        Some(ConnectThreadResponses::BurstReadResult(result));
                                    cvar.notify_one();
                                }
                                ConnectThreadRequests::BurstWrite(addr, data) => {
                                    let result = Self::do_burst_write(&usb, addr, data, debug_byte);
                                    keep_going = result.is_ok();
                                    *response.lock().unwrap() =
                                        Some(ConnectThreadResponses::BurstWriteResult(result));
                                    cvar.notify_one();
                                }
                            },
                        }
                    }
                }
            }

            // Only print out the message the first time.
            // This value gets re-set to `true` whenever there
            // is a successful USB connection.
            if print_waiting_message {
                info!("waiting for target device");
                print_waiting_message = false;
            }
            thread::park_timeout(Duration::from_millis(500));

            // Respond to any messages in the buffer with NotConnected.  As soon
            // as the channel is empty, loop back to the start of this function.
            loop {
                match rx.try_recv() {
                    Err(TryRecvError::Empty) => break,
                    Err(TryRecvError::Disconnected) => panic!("main thread disconnected"),
                    Ok(m) => match m {
                        ConnectThreadRequests::Exit => {
                            debug!("main thread requested exit");
                            *response.lock().unwrap() = Some(ConnectThreadResponses::Exiting);
                            cvar.notify_one();
                            return;
                        }
                        ConnectThreadRequests::Peek(_addr) => {
                            *response.lock().unwrap() = Some(ConnectThreadResponses::PeekResult(
                                Err(BridgeError::NotConnected),
                            ));
                            cvar.notify_one();
                        }
                        ConnectThreadRequests::Poke(_addr, _val) => {
                            *response.lock().unwrap() = Some(ConnectThreadResponses::PokeResult(
                                Err(BridgeError::NotConnected),
                            ));
                            cvar.notify_one();
                        }
                        ConnectThreadRequests::StartPolling(p, v) => {
                            cfg.pid = p;
                            cfg.vid = v;
                        }
                        ConnectThreadRequests::BurstRead(_addr, _len) => {
                            *response.lock().unwrap() = Some(ConnectThreadResponses::BurstReadResult(
                                Err(BridgeError::NotConnected),
                            ));
                            cvar.notify_one();
                        }
                        ConnectThreadRequests::BurstWrite(_addr, _data) => {
                            *response.lock().unwrap() = Some(ConnectThreadResponses::BurstWriteResult(
                                Err(BridgeError::NotConnected),
                            ));
                            cvar.notify_one();
                        }
                    },
                }
            }
        }
    }

    fn do_poke(
        usb: &libusb_wishbone_tool::DeviceHandle,
        addr: u32,
        value: u32,
        debug_byte: u8,
    ) -> Result<(), BridgeError> {
        let mut data_val = [0; 4];
        data_val[0] = (value & 0xff) as u8;
        data_val[1] = ((value >> 8) & 0xff) as u8;
        data_val[2] = ((value >> 16) & 0xff) as u8;
        data_val[3] = ((value >> 24) & 0xff) as u8;
        match usb.write_control(
            debug_byte,
            0,
            (addr & 0xffff) as u16,
            ((addr >> 16) & 0xffff) as u16,
            &data_val,
            Duration::from_millis(100),
        ) {
            Err(e) => {
                debug!("POKE @ {:08x}: usb error {:?}", addr, e);
                Err(BridgeError::USBError(e))
            }
            Ok(len) => {
                if len != 4 {
                    debug!(
                        "POKE @ {:08x}: length error: expected 4 bytes, got {} bytes",
                        addr, len
                    );
                    Err(BridgeError::LengthError(4, len))
                } else {
                    debug!("POKE @ {:08x} -> {:08x}", addr, value);
                    Ok(())
                }
            }
        }
    }

    fn do_burst_write(
        usb: &libusb_wishbone_tool::DeviceHandle,
        addr: u32,
        data: Vec<u8>,
        debug_byte: u8,
    ) -> Result<(), BridgeError> {
        if data.len() == 0 {
            return Ok(());
        }

        let maxlen = 4096; // spec says...1023 max? but 4096 works.

        let packet_count = data.len() / maxlen + if (data.len() % maxlen) != 0 { 1 } else { 0 };
        for pkt_num in 0..packet_count {
            let cur_addr = addr as usize + pkt_num * maxlen;
            let bufsize = if pkt_num  == (packet_count - 1) {
                if data.len() % maxlen != 0 {
                    data.len() % maxlen
                } else {
                    maxlen
                }
            } else {
                maxlen
            };
            match usb.write_control(
                debug_byte,
                0,
                (cur_addr & 0xffff) as u16,
                ((cur_addr >> 16) & 0xffff) as u16,
                &data[pkt_num * maxlen..pkt_num * maxlen + bufsize],
                Duration::from_millis(500),
            ) {
                Err(e) => {
                    debug!("BURST_WRITE @ {:08x}: usb error {:?}", addr, e);
                    return Err(BridgeError::USBError(e));
                }
                Ok(retlen) => {
                    if retlen != bufsize as usize {
                        debug!(
                            "BURST_WRITE @ {:08x}: length error: expected {} bytes, got {} bytes",
                            addr, bufsize, retlen
                        );
                        return Err(BridgeError::LengthError(bufsize as usize, retlen));
                    }
                }
            }
        }
        Ok(())
    }

    fn do_peek(
        usb: &libusb_wishbone_tool::DeviceHandle,
        addr: u32,
        debug_byte: u8,
    ) -> Result<u32, BridgeError> {
        let mut data_val = [0; 4];
        match usb.read_control(
            0x80 | debug_byte,
            0,
            (addr & 0xffff) as u16,
            ((addr >> 16) & 0xffff) as u16,
            &mut data_val,
            Duration::from_millis(500),
        ) {
            Err(e) => {
                debug!("PEEK @ {:08x}: usb error {:?}", addr, e);
                Err(BridgeError::USBError(e))
            }
            Ok(len) => {
                if len != 4 {
                    debug!(
                        "PEEK @ {:08x}: length error: expected 4 bytes, got {} bytes",
                        addr, len
                    );
                    Err(BridgeError::LengthError(4, len))
                } else {
                    let value = ((data_val[3] as u32) << 24)
                        | ((data_val[2] as u32) << 16)
                        | ((data_val[1] as u32) << 8)
                        | (data_val[0] as u32);
                    debug!("PEEK @ {:08x} = {:08x}", addr, value);
                    Ok(value)
                }
            }
        }
    }

    fn do_burst_read(
        usb: &libusb_wishbone_tool::DeviceHandle,
        addr: u32,
        len: u32,
        debug_byte: u8,
    ) -> Result<Vec<u8>, BridgeError> {
        let mut data_val = vec![];

        if len == 0 {
            return Ok(data_val);
        }

        let maxlen = 4096; // spec says...1023 max? but 4096 works.

        let packet_count = len / maxlen + if (len % maxlen) != 0 { 1 } else { 0 };
        for pkt_num in 0..packet_count {
            let cur_addr = addr + pkt_num * maxlen;
            let bufsize = if pkt_num  == (packet_count - 1) {
                if len % maxlen != 0 {
                    len % maxlen
                } else {
                    maxlen
                }
            } else {
                maxlen
            };
            let mut buffer = vec![0; bufsize as usize];
            match usb.read_control(
                0x80 | debug_byte,
                0,
                (cur_addr & 0xffff) as u16,
                ((cur_addr >> 16) & 0xffff) as u16,
                &mut buffer,
                Duration::from_millis(500),
            ) {
                Err(e) => {
                    debug!("BURST_READ @ {:08x}: usb error {:?}", addr, e);
                    return Err(BridgeError::USBError(e));
                }
                Ok(retlen) => {
                    if retlen != bufsize as usize {
                        debug!(
                            "BURST_READ @ {:08x}: length error: expected {} bytes, got {} bytes",
                            addr, bufsize, retlen
                        );
                        return Err(BridgeError::LengthError(bufsize as usize, retlen));
                    } else {
                        for i in 0..data_val.len() {
                            if (i % 16) == 0 {
                               debug!("\nBURST_READ @ {:08x}: ", addr as usize + i);
                            }
                            debug!("{:02x} ", data_val[i]);
                        }
                        data_val.append(&mut buffer);
                    }
                }
            }
        }
        Ok(data_val)
    }

    pub fn poke(&self, addr: u32, value: u32) -> Result<(), BridgeError> {
        let &(ref lock, ref cvar) = &*self.main_rx;
        let mut _mtx = lock.lock().unwrap();
        self.main_tx
            .send(ConnectThreadRequests::Poke(addr, value))
            .expect("Unable to send poke to connect thread");
        *_mtx = None;
        while _mtx.is_none() {
            _mtx = cvar.wait(_mtx).unwrap();
        }
        match _mtx.take() {
            Some(ConnectThreadResponses::PokeResult(r)) => Ok(r?),
            e => {
                error!("unexpected bridge poke response: {:?}", e);
                Err(BridgeError::WrongResponse)
            }
        }
    }

    pub fn peek(&self, addr: u32) -> Result<u32, BridgeError> {
        let &(ref lock, ref cvar) = &*self.main_rx;
        let mut _mtx = lock.lock().unwrap();
        self.main_tx
            .send(ConnectThreadRequests::Peek(addr))
            .expect("Unable to send peek to connect thread");
        *_mtx = None;
        while _mtx.is_none() {
            _mtx = cvar.wait(_mtx).unwrap();
        }
        match _mtx.take() {
            Some(ConnectThreadResponses::PeekResult(r)) => Ok(r?),
            e => {
                error!("unexpected bridge peek response: {:?}", e);
                Err(BridgeError::WrongResponse)
            }
        }
    }

    pub fn burst_read(&self, addr: u32, len: u32) -> Result<Vec<u8>, BridgeError> {
        let &(ref lock, ref cvar) = &*self.main_rx;
        let mut _mtx = lock.lock().unwrap();
        self.main_tx
            .send(ConnectThreadRequests::BurstRead(addr, len))
            .expect("Unable to send burst read to connect thread");
        *_mtx = None;
        while _mtx.is_none() {
            _mtx = cvar.wait(_mtx).unwrap();
        }
        match _mtx.take() {
            Some(ConnectThreadResponses::BurstReadResult(r)) => Ok(r?),
            e => {
                error!("unexpected bridge burst reed response: {:?}", e);
                Err(BridgeError::WrongResponse)
            }
        }
    }

    pub fn burst_write(&self, addr: u32, data: &[u8]) -> Result<(), BridgeError> {
        let &(ref lock, ref cvar) = &*self.main_rx;
        let mut _mtx = lock.lock().unwrap();
        let local_data = data.to_vec();
        self.main_tx
            .send(ConnectThreadRequests::BurstWrite(addr, local_data))
            .expect("Unable to send burst write to connect thread");
        *_mtx = None;
        while _mtx.is_none() {
            _mtx = cvar.wait(_mtx).unwrap();
        }
        match _mtx.take() {
            Some(ConnectThreadResponses::BurstWriteResult(r)) => Ok(r?),
            e => {
                error!("unexpected bridge burst write response: {:?}", e);
                Err(BridgeError::WrongResponse)
            }
        }
    }
}

impl Drop for UsbBridgeInner {
    fn drop(&mut self) {
        // If this is the last reference to the bridge, tell the control thread
        // to exit.
        let sc = Arc::strong_count(&self.mutex);
        let wc = Arc::weak_count(&self.mutex);
        debug!("strong count: {}  weak count: {}", sc, wc);
        if (sc + wc) <= 1 {
            let &(ref lock, ref cvar) = &*self.main_rx;
            let mut mtx = lock.lock().unwrap();
            self.main_tx
                .send(ConnectThreadRequests::Exit)
                .expect("Unable to send Exit request to thread");

            // Get a response back from the poll thread
            while mtx.is_none() {
                mtx = cvar.wait(mtx).unwrap();
            }
            match mtx.take() {
                Some(ConnectThreadResponses::Exiting) => (),
                e => {
                    error!("unexpected bridge exit response: {:?}", e);
                }
            }
            if let Some(pt) = self.poll_thread.take() {
                pt.join().expect("Unable to join polling thread");
            }
        }
    }
}