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
use std::{mem, ptr};
use std::os::windows::io::AsRawHandle;
use winapi::um::handleapi::*;
use winapi::um::setupapi::*;
use winapi::um::fileapi::*;
use winapi::um::winnt::*;
use winapi::um::winbase::*;
use winapi::um::errhandlingapi::*;
use winapi::shared::ntdef::HANDLE;
use crate::*;

/// The ViGEmBus client connection.
#[derive(Debug)]
pub struct Client {
	pub(crate) device: HANDLE,
}

impl Client {
	/// Connects to the ViGEmBus service.
	pub fn connect() -> Result<Client, Error> {
		unsafe {
			let mut error = Error::BusNotFound;

			let mut member_index = 0;
			let mut device_interface_data: SP_DEVICE_INTERFACE_DATA = mem::zeroed();
			device_interface_data.cbSize = mem::size_of_val(&device_interface_data) as u32;

			let mut detail_data_buffer = mem::MaybeUninit::<[u32; 0x300]>::uninit();

			let device_info_set = SetupDiGetClassDevsW(
				&bus::GUID_DEVINTERFACE,
				ptr::null(),
				ptr::null_mut(),
				DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

			if device_info_set == INVALID_HANDLE_VALUE {
				return Err(Error::WinError(GetLastError()));
			}

			// Enumerate device instances
			while SetupDiEnumDeviceInterfaces(
				device_info_set,
				ptr::null_mut(),
				&bus::GUID_DEVINTERFACE,
				member_index,
				&mut device_interface_data) != 0
			{
				member_index += 1;

				// Allocate target buffer
				// This is a fixed size stack buffer which should be big enough for everyone
				let detail_data_ptr = detail_data_buffer.as_mut_ptr() as PSP_DEVICE_INTERFACE_DETAIL_DATA_W;
				(*detail_data_ptr).cbSize = mem::size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;

				// Get detail buffer
				let mut required_size = 0;
				if SetupDiGetDeviceInterfaceDetailW(
					device_info_set,
					&mut device_interface_data,
					detail_data_ptr,
					mem::size_of_val(&detail_data_buffer) as u32,
					&mut required_size,
					ptr::null_mut()) == 0
				{
					error = Error::WinError(GetLastError());
					continue;
				}

				// bus found, open it
				let device_path = (*detail_data_ptr).DevicePath.as_ptr();
				let device = CreateFileW(
					device_path,
					GENERIC_READ | GENERIC_WRITE,
					FILE_SHARE_READ | FILE_SHARE_WRITE,
					ptr::null_mut(),
					OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH | FILE_FLAG_OVERLAPPED,
					ptr::null_mut());

				if device == INVALID_HANDLE_VALUE {
					error = Error::BusAccessFailed(GetLastError());
					continue;
				}

				let mut check_version = bus::CheckVersion::common();
				if check_version.ioctl(device) {
					SetupDiDestroyDeviceInfoList(device_info_set);
					return Ok(Client { device })
				}

				// version mismatch, look for another instance
				CloseHandle(device);
				error = Error::BusVersionMismatch;
			}

			SetupDiDestroyDeviceInfoList(device_info_set);
			Err(error)
		}
	}
}

unsafe impl Sync for Client {}
unsafe impl Send for Client {}

impl AsRawHandle for Client {
	fn as_raw_handle(&self) -> HANDLE {
		self.device
	}
}

impl Drop for Client {
	fn drop(&mut self) {
		unsafe {
			CloseHandle(self.device);
		}
	}
}