serial2 0.1.0-alpha3

Cross platform serial ports
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
use std::ffi::OsString;
use std::io::{IoSlice, IoSliceMut};
use std::os::windows::io::AsRawHandle;
use std::path::{Path, PathBuf};
use std::time::Duration;

use winapi::um::{commapi, fileapi, winbase, winnt, winreg};
use winapi::shared::minwindef::{BOOL, HKEY};
use winapi::shared::winerror;

pub struct SerialPort {
	pub file: std::fs::File,
}

#[derive(Clone)]
pub struct Settings {
	dcb: winbase::DCB,
}

impl SerialPort {
	pub fn open(name: &Path) -> std::io::Result<Self> {
		// Use the win32 device namespace, otherwise we're limited to COM1-9.
		// This also works with higher numbers.
		// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#win32-device-namespaces
		let mut path = OsString::from("\\\\.\\");
		path.push(name.as_os_str());

		let file = std::fs::OpenOptions::new()
			.read(true)
			.write(true)
			.create(false)
			.open(path)?;
		Ok(Self::from_file(file))
	}

	pub fn from_file(file: std::fs::File) -> Self {
		Self { file }
	}

	pub fn get_configuration(&self) -> std::io::Result<Settings> {
		unsafe {
			let mut dcb: winbase::DCB = std::mem::zeroed();
			check_bool(commapi::GetCommState(self.file.as_raw_handle(), &mut dcb))?;
			Ok(Settings {
				dcb,
			})
		}
	}

	pub fn set_configuration(&mut self, settings: &Settings) -> std::io::Result<()> {
		unsafe {
			let mut settings = settings.clone();
			check_bool(commapi::SetCommState(self.file.as_raw_handle(), &mut settings.dcb))
		}
	}

	pub fn set_read_timeout(&mut self, timeout: Duration) -> std::io::Result<()> {
		unsafe {
			let mut timeouts = std::mem::zeroed();
			check_bool(commapi::GetCommTimeouts(self.file.as_raw_handle(), &mut timeouts))?;
			timeouts.ReadIntervalTimeout = 0;
			timeouts.ReadTotalTimeoutMultiplier = 0;
			timeouts.ReadTotalTimeoutConstant = timeout.as_millis().try_into().unwrap_or(u32::MAX);
			check_bool(commapi::SetCommTimeouts(self.file.as_raw_handle(), &mut timeouts))
		}
	}

	pub fn get_read_timeout(&self) -> std::io::Result<Duration> {
		unsafe {
			let mut timeouts = std::mem::zeroed();
			check_bool(commapi::GetCommTimeouts(self.file.as_raw_handle(), &mut timeouts))?;
			Ok(Duration::from_millis(timeouts.ReadTotalTimeoutConstant.into()))
		}
	}

	pub fn set_write_timeout(&mut self, timeout: Duration) -> std::io::Result<()> {
		unsafe {
			let mut timeouts = std::mem::zeroed();
			check_bool(commapi::GetCommTimeouts(self.file.as_raw_handle(), &mut timeouts))?;
			timeouts.WriteTotalTimeoutMultiplier = 0;
			timeouts.WriteTotalTimeoutConstant = timeout.as_millis().try_into().unwrap_or(u32::MAX);
			check_bool(commapi::SetCommTimeouts(self.file.as_raw_handle(), &mut timeouts))
		}
	}

	pub fn get_write_timeout(&self) -> std::io::Result<Duration> {
		unsafe {
			let mut timeouts = std::mem::zeroed();
			check_bool(commapi::GetCommTimeouts(self.file.as_raw_handle(), &mut timeouts))?;
			Ok(Duration::from_millis(timeouts.WriteTotalTimeoutConstant.into()))
		}
	}

	pub fn read(&self, buf: &mut [u8]) -> std::io::Result<usize> {
		unsafe {
			let mut read = 0;
			let len = buf.len().try_into().unwrap_or(u32::MAX);
			let ret = fileapi::ReadFile(
				self.file.as_raw_handle(),
				buf.as_mut_ptr().cast(),
				len,
				&mut read, std::ptr::null_mut(),
			);
			match check_bool(ret) {
				Ok(_) => Ok(read as usize),
				// BrokenPipe means EOF on Windows
				Err(ref e) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(0),
				Err(e) => Err(e),
			}
		}
	}

	pub fn read_vectored(&self, buf: &mut [IoSliceMut<'_>]) -> std::io::Result<usize> {
		if buf.is_empty() {
			self.read(&mut [])
		} else {
			self.read(&mut buf[0])
		}
	}

	pub fn write(&self, buf: &[u8]) -> std::io::Result<usize> {
		unsafe {
			let mut written = 0;
			let len = buf.len().try_into().unwrap_or(u32::MAX);
			check_bool(fileapi::WriteFile(
				self.file.as_raw_handle(),
				buf.as_ptr().cast(),
				len,
				&mut written,
				std::ptr::null_mut(),
			))?;
			Ok(written as usize)
		}
	}

	pub fn write_vectored(&self, buf: &[IoSlice<'_>]) -> std::io::Result<usize> {
		if buf.is_empty() {
			self.write(&[])
		} else {
			self.write(&buf[0])
		}
	}

	pub fn flush_output(&self) -> std::io::Result<()> {
		unsafe {
			check_bool(winapi::um::fileapi::FlushFileBuffers(self.file.as_raw_handle()))
		}
	}

	pub fn discard_buffers(&self, discard_input: bool, discard_output: bool) -> std::io::Result<()> {
		unsafe {
			let mut flags = 0;
			if discard_input {
				flags |= winbase::PURGE_RXCLEAR;
			}
			if discard_output {
				flags |= winbase::PURGE_TXCLEAR;
			}
			check_bool(commapi::PurgeComm(self.file.as_raw_handle(), flags))
		}
	}


	pub fn set_rts(&self, state: bool) -> std::io::Result<()> {
		if state {
			escape_comm_function(&self.file, winbase::SETRTS)
		} else {
			escape_comm_function(&self.file, winbase::CLRRTS)
		}
	}

	pub fn read_cts(&self) -> std::io::Result<bool> {
		read_pin(&self.file, winbase::MS_CTS_ON)
	}

	pub fn set_dtr(&self, state: bool) -> std::io::Result<()> {
		if state {
			escape_comm_function(&self.file, winbase::SETDTR)
		} else {
			escape_comm_function(&self.file, winbase::CLRDTR)
		}
	}

	pub fn read_dsr(&self) -> std::io::Result<bool> {
		read_pin(&self.file, winbase::MS_DSR_ON)
	}

	pub fn read_ri(&self) -> std::io::Result<bool> {
		read_pin(&self.file, winbase::MS_RING_ON)
	}

	pub fn read_cd(&self) -> std::io::Result<bool> {
		// RLSD or Receive Line Signal Detect is the same as Carrier Detect.
		//
		// I think.
		read_pin(&self.file, winbase::MS_RLSD_ON)
	}
}

fn escape_comm_function(file: &std::fs::File, function: u32) -> std::io::Result<()> {
	unsafe {
		check_bool(commapi::EscapeCommFunction(file.as_raw_handle(), function))
	}
}

fn read_pin(file: &std::fs::File, pin: u32) -> std::io::Result<bool> {
	unsafe {
		let mut bits: u32 = 0;
		check_bool(commapi::GetCommModemStatus(file.as_raw_handle(), &mut bits))?;
		Ok(bits & pin != 0)
	}
}

/// Check the return value of a syscall for errors.
fn check_bool(ret: BOOL) -> std::io::Result<()> {
	if ret == 0 {
		Err(std::io::Error::last_os_error())
	} else {
		Ok(())
	}
}

/// Create an std::io::Error with custom message.
fn other_error<E>(msg: E) -> std::io::Error
where
	E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
	std::io::Error::new(std::io::ErrorKind::Other, msg)
}

impl Settings {
	pub fn set_baud_rate(&mut self, baud_rate: u32) -> std::io::Result<()> {
		self.dcb.BaudRate = baud_rate;
		Ok(())
	}

	pub fn get_baud_rate(&self) -> std::io::Result<u32> {
		Ok(self.dcb.BaudRate)
	}

	pub fn set_char_size(&mut self, char_size: crate::CharSize) {
		self.dcb.ByteSize = match char_size {
			crate::CharSize::Bits5 => 5,
			crate::CharSize::Bits6 => 6,
			crate::CharSize::Bits7 => 7,
			crate::CharSize::Bits8 => 8,
		};
	}

	pub fn get_char_size(&self) -> std::io::Result<crate::CharSize> {
		match self.dcb.ByteSize {
			5 => Ok(crate::CharSize::Bits5),
			6 => Ok(crate::CharSize::Bits6),
			7 => Ok(crate::CharSize::Bits7),
			8 => Ok(crate::CharSize::Bits8),
			_ => Err(other_error("unsupported char size")),
		}
	}

	pub fn set_stop_bits(&mut self, stop_bits: crate::StopBits) {
		self.dcb.StopBits = match stop_bits {
			crate::StopBits::One => winbase::ONESTOPBIT,
			crate::StopBits::Two => winbase::TWOSTOPBITS,
		};
	}

	pub fn get_stop_bits(&self) -> std::io::Result<crate::StopBits> {
		match self.dcb.StopBits {
			winbase::ONESTOPBIT => Ok(crate::StopBits::One),
			winbase::TWOSTOPBITS => Ok(crate::StopBits::Two),
			_ => Err(other_error("unsupported stop bits")),
		}
	}

	pub fn set_parity(&mut self, parity: crate::Parity) {
		match parity {
			crate::Parity::None => {
				self.dcb.set_fParity(0);
				self.dcb.Parity = winbase::NOPARITY;
			},
			crate::Parity::Odd => {
				self.dcb.set_fParity(1);
				self.dcb.Parity = winbase::ODDPARITY;
			},
			crate::Parity::Even => {
				self.dcb.set_fParity(1);
				self.dcb.Parity = winbase::EVENPARITY;
			},
		}
	}

	pub fn get_parity(&self) -> std::io::Result<crate::Parity> {
		let parity_enabled = self.dcb.fParity() != 0;
		match self.dcb.Parity {
			winbase::NOPARITY => Ok(crate::Parity::None),
			winbase::ODDPARITY if parity_enabled => Ok(crate::Parity::Odd),
			winbase::EVENPARITY if parity_enabled => Ok(crate::Parity::Even),
			_ => Err(other_error("unsupported parity configuration")),
		}
	}

	pub fn set_flow_control(&mut self, flow_control: crate::FlowControl) {
		match flow_control {
			crate::FlowControl::None => {
				self.dcb.set_fInX(0);
				self.dcb.set_fOutX(0);
				self.dcb.set_fDtrControl(winbase::DTR_CONTROL_DISABLE);
				self.dcb.set_fRtsControl(winbase::RTS_CONTROL_DISABLE);
				self.dcb.set_fOutxCtsFlow(0);
				self.dcb.set_fOutxDsrFlow(0);
			},
			crate::FlowControl::XonXoff => {
				self.dcb.set_fInX(1);
				self.dcb.set_fOutX(1);
				self.dcb.set_fDtrControl(winbase::DTR_CONTROL_DISABLE);
				self.dcb.set_fRtsControl(winbase::RTS_CONTROL_DISABLE);
				self.dcb.set_fOutxCtsFlow(0);
				self.dcb.set_fOutxDsrFlow(0);
			},
			crate::FlowControl::RtsCts => {
				self.dcb.set_fInX(0);
				self.dcb.set_fOutX(0);
				self.dcb.set_fDtrControl(winbase::DTR_CONTROL_DISABLE);
				self.dcb.set_fRtsControl(winbase::RTS_CONTROL_TOGGLE);
				self.dcb.set_fOutxCtsFlow(1);
				self.dcb.set_fOutxDsrFlow(0);
			},
		}
	}

	pub fn get_flow_control(&self) -> std::io::Result<crate::FlowControl> {
		let in_x = self.dcb.fInX() != 0;
		let out_x = self.dcb.fOutX() != 0;
		let out_cts = self.dcb.fOutxCtsFlow() != 0;
		let out_dsr = self.dcb.fOutxDsrFlow() != 0;

		match (in_x, out_x, out_cts, out_dsr, self.dcb.fDtrControl(), self.dcb.fRtsControl()) {
			(false, false, false, false, winbase::DTR_CONTROL_DISABLE, winbase::RTS_CONTROL_DISABLE) => Ok(crate::FlowControl::None),
			(true, true, false, false, winbase::DTR_CONTROL_DISABLE, winbase::RTS_CONTROL_DISABLE) => Ok(crate::FlowControl::XonXoff),
			(false, false, true, false, winbase::DTR_CONTROL_DISABLE, winbase::RTS_CONTROL_TOGGLE) => Ok(crate::FlowControl::RtsCts),
			_ => Err(other_error("unsupported flow control configuration")),
		}
	}
}

#[derive(Debug)]
struct RegKey {
	key: HKEY,
}

impl RegKey {
	fn open(parent: HKEY, subpath: &std::ffi::CStr, rights: winreg::REGSAM) -> std::io::Result<Self> {
		unsafe {
			let mut key: HKEY = std::ptr::null_mut();
			let status = winreg::RegOpenKeyExA(
				parent,
				subpath.as_ptr(),
				0,
				rights,
				&mut key,
			);
			if status != 0 {
				Err(std::io::Error::from_raw_os_error(status))
			} else {
				Ok(Self { key })
			}
		}
	}

	fn get_value_info(&self) -> std::io::Result<(u32, u32, u32)> {
		unsafe {
			let mut value_count: u32 = 0;
			let mut max_value_name_len: u32 = 0;
			let mut max_value_data_len: u32 = 0;
			let status = winreg::RegQueryInfoKeyA(
				self.key,
				std::ptr::null_mut(),
				std::ptr::null_mut(),
				std::ptr::null_mut(),
				std::ptr::null_mut(),
				std::ptr::null_mut(),
				std::ptr::null_mut(),
				&mut value_count,
				&mut max_value_name_len,
				&mut max_value_data_len,
				std::ptr::null_mut(),
				std::ptr::null_mut(),
			);
			if status != 0 {
				Err(std::io::Error::from_raw_os_error(status))
			} else {
				Ok((value_count, max_value_name_len, max_value_data_len))
			}
		}
	}

	fn get_string_value(&self, index: u32, max_name_len: u32, max_data_len: u32) -> std::io::Result<Option<(Vec<u8>, Vec<u8>)>> {
		unsafe {
			let mut name = vec![0u8; max_name_len as usize + 1];
			let mut data = vec![0u8; max_data_len as usize];
			let mut name_len = name.len() as u32;
			let mut data_len = data.len() as u32;
			let mut kind = 0;
			let status = winreg::RegEnumValueA(
				self.key,
				index,
				name.as_mut_ptr().cast(),
				&mut name_len,
				std::ptr::null_mut(),
				&mut kind,
				data.as_mut_ptr().cast(),
				&mut data_len,
			);
			if status == winerror::ERROR_NO_MORE_ITEMS as i32 {
				Ok(None)
			} else if status != 0 {
				Err(std::io::Error::from_raw_os_error(status))
			} else if kind != winnt::REG_SZ {
				Ok(None)
			} else {
				name.shrink_to(name_len as usize + 1);
				data.shrink_to(data_len as usize);
				Ok(Some((name, data)))
			}
		}
	}
}

impl Drop for RegKey {
	fn drop(&mut self) {
		unsafe {
			winreg::RegCloseKey(self.key);
		}
	}
}

pub fn enumerate() -> std::io::Result<Vec<PathBuf>> {
	let subkey = unsafe { std::ffi::CStr::from_bytes_with_nul_unchecked(b"Hardware\\DEVICEMAP\\SERIALCOMM\x00") };
	let device_map = RegKey::open(winreg::HKEY_LOCAL_MACHINE, subkey, winnt::KEY_READ)?;
	let (value_count, max_value_name_len, max_value_data_len) = device_map.get_value_info()?;

	let mut entries = Vec::with_capacity(16);
	for i in 0.. value_count {
		let name = match device_map.get_string_value(i, max_value_name_len, max_value_data_len) {
			Ok(Some((_name, data))) => data,
			Ok(None) => continue,
			Err(_) => continue,
		};
		if let Ok(name) = String::from_utf8(name) {
			entries.push(name.into());
		}
	}

	Ok(entries)
}