From 963dc072c989bca7e98258c2e53ee2cc5dc80ba7 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Thu, 4 Mar 2021 19:07:51 -0800 Subject: [PATCH] Port more serial stuff to Rust --- src/radio.rs | 10 +++++----- src/serial.rs | 20 +++++++++++++------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/radio.rs b/src/radio.rs index 20425a0..5ef0ee2 100644 --- a/src/radio.rs +++ b/src/radio.rs @@ -45,7 +45,6 @@ extern { fn hid_identify() -> *const c_char; fn hid_close(); - fn serial_identify(s: *const c_char) -> *const c_char; fn serial_close(); } @@ -65,7 +64,7 @@ unsafe fn set_active_device(d: *const radio_device_t) { /// and identify the type of device. pub fn connect() -> Radio { - let ident_str = { + let ident_str = (|| { let mut ident: *const c_char; // Try TYT MD family. ident = unsafe { dfu_init(0x0483, 0xdf11) }; @@ -79,8 +78,9 @@ pub fn connect() -> Radio { // Try AT-D868UV. let trace_flag = false; //TODO fix if let Some(device_path) = crate::serial::serial_init(0x28e9, 0x018a, trace_flag) { - let ptr = device_path.as_ptr() as *mut c_char; - ident = unsafe { serial_identify(ptr) }; + if let Some(identifier) = crate::serial::identify(&device_path) { + return identifier; + } } } @@ -91,7 +91,7 @@ pub fn connect() -> Radio { } unsafe { CStr::from_ptr(ident).to_str().unwrap().to_string() } - }; + })(); unsafe { diff --git a/src/serial.rs b/src/serial.rs index 7162a76..5a3b47f 100644 --- a/src/serial.rs +++ b/src/serial.rs @@ -1,8 +1,9 @@ -use std::ffi::{CStr}; +use std::ffi::{CStr, CString}; use libc::{c_char}; extern { fn find_path(vid: libc::c_int, pid: libc::c_int) -> *const c_char; + fn serial_identify(s: *const c_char) -> *const c_char; } /// Connect to the specified device. @@ -22,12 +23,17 @@ pub fn serial_init(vid: u32, pid: u32, trace_flag: bool) -> Option { Some(dev_path) } -/* /// Query and return the device identification string. /// On error, return None. -// -pub fn serial_identify(dev_path: &str) -> Option { - - +pub fn identify(dev_path: &str) -> Option { + let dev_path_c = CString::new(dev_path).unwrap(); + let ptr = dev_path_c.as_ptr() as *mut c_char; + unsafe { + let output = serial_identify(ptr); + if output.is_null() { + None + } else { + Some(CStr::from_ptr(output).to_str().unwrap().to_string()) + } + } } -*/