diff --git a/src/radio.rs b/src/radio.rs index 40cddae..fd0711b 100644 --- a/src/radio.rs +++ b/src/radio.rs @@ -1,6 +1,7 @@ use std::ffi::{CStr, CString}; -use libc::{c_char, c_int}; +use libc::{c_char, c_int, c_uint}; use std::os::unix::io::AsRawFd; +use sys::process::exit; include!(concat!(env!("OUT_DIR"), "/bindings.rs")); @@ -24,19 +25,74 @@ extern { fn radio_parse_config(device: *const radio_device_t, filename: *const c_char); fn radio_write_csv(device: *const radio_device_t, filename: *const c_char); + fn dfu_init(vid: c_uint, pid: c_uint) -> *const c_char; fn dfu_reboot(); fn dfu_close(); + + fn hid_init(vid: c_int, pid: c_int) -> c_int; + fn hid_identify() -> *const c_char; fn hid_close(); + + fn serial_init(vid: c_int, pid: c_int) -> c_int; + fn serial_identify() -> *const c_char; fn serial_close(); fn get_radio_tab() -> *const radio_tab_t; } /// Connect to the radio via the serial port. -/// Identify the type of device. +/// and identify the type of device. pub fn connect() -> *const radio_device_t { unsafe { - radio_connect() + + let mut ident: *const c_char = std::ptr::null(); + // Try TYT MD family. + ident = dfu_init(0x0483, 0xdf11); + if ident.is_null() { + // Try RD-5R, DM-1801 and GD-77. + if (hid_init(0x15a2, 0x0073) >= 0) + ident = hid_identify(); + } + + if ident.is_null() { + // Try AT-D868UV. + if (serial_init(0x28e9, 0x018a) >= 0) + ident = serial_identify(); + } + + if ident.is_null() { + eprintln!("No radio detected."); + eprintln!("Check your USB cable!"); + exit(-1); + } + + let mut device: *const radio_device_t = std::ptr::null(); + + let mut ptr = get_radio_tab(); + let ident_str = CStr::from_ptr(ident).to_str().unwrap(); + loop { + let ident_ptr = (*ptr).ident; + if ident_ptr.is_null() { + break; + } + let name_ptr = (*(*ptr).device).name; + + let table_ident = CStr::from_ptr(ident_ptr).to_str().unwrap().to_string(); + if table_ident.eq_ignore_ascii_case(ident_str) { + device = ptr; + break; + } + + ptr = ptr.offset(1); + } + if device.is_null() { + eprintln!("Unrecognized radio '{}'.", ident_str); + exit(-1); + } + + //TODO need to reset device static + + } }