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
// The MIT License (MIT)
//
// Copyright (c) 2015 Johan Johansson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#![feature(collections)]
#![cfg_attr(test, feature(step_by))]

#[macro_use]
extern crate bitflags;
extern crate libc;
pub use ffi::*;

use libc::consts::os::extra::*;
use libc::funcs::extra::kernel32;
use libc::{ c_void, c_int, HANDLE };
use std::{ ptr, mem, io };
use std::io::{ Error, ErrorKind };
use std::cell::RefCell;

mod ffi;

fn system_to_io_err(operation: &'static str, error_code: c_int) -> io::Error {
	use std::io::ErrorKind::*;

	let (error_kind, message) = match error_code {
		ERROR_ACCESS_DENIED => (AlreadyExists, "Access denied. Resource might be busy"),
		ERROR_FILE_NOT_FOUND => (NotFound, "Serial port not found"),
		ERROR_INVALID_USER_BUFFER => (InvalidInput, "Supplied buffer is invalid"),
		ERROR_NOT_ENOUGH_MEMORY => (Other, "Too many I/O requests, not enough memory"),
		ERROR_OPERATION_ABORTED => (Interrupted, "Operation was canceled"),
		ERROR_INVALID_HANDLE => (InvalidInput, "Communications handle is invalid"),
		_ => (Other, "unmatched error"),
	};

	Error::new(error_kind,
		format!(r#"Operation `{}` failed with code 0x{:x} and message "{}""#,
			operation, error_code, message))
}

/// A serial connection
pub struct Connection {
	// Pointer to the serial connection
	comm_handle: RefCell<HANDLE>
}
impl Connection {
	/// Open a new connection via port `port` with baud rate `baud_rate`
	pub fn new(port: &str, baud_rate: u32) -> io::Result<Connection> {
		let (comm_handle, err) = unsafe {
			let mut port_u16: Vec<_> = port.utf16_units().collect();
			port_u16.push(0);
			(
				kernel32::CreateFileW(port_u16.as_ptr(),
					GENERIC_READ | GENERIC_WRITE,
					0,
					ptr::null_mut(),
					OPEN_EXISTING,
					libc::FILE_ATTRIBUTE_NORMAL,
					ptr::null_mut()),
				kernel32::GetLastError() as c_int
			)
		};

		if comm_handle == INVALID_HANDLE_VALUE {
			Err(system_to_io_err("Open port", err))
		} else {
			let mut conn = Connection{ comm_handle: RefCell::new(comm_handle) };

			conn.comm_state().map(|mut dcb| {
					dcb.set_dtr_control(DTR_CONTROL::ENABLE);
					dcb
				})
				.and_then(|dcb| conn.set_comm_state(dcb))
				.and_then(|_| conn.set_baud_rate(baud_rate))
				.and_then(|_| conn.set_byte_size(8))
				.and_then(|_| conn.set_stop_bits(StopBits::ONE))
				.and_then(|_| conn.set_parity(Parity::NO))
				.and_then(|_| {
					unsafe {
						PurgeComm(*conn.comm_handle.borrow_mut(), PURGE_RXCLEAR | PURGE_TXCLEAR);
					}
					conn.set_timeout(40)
				})
				.map(|_| conn)					
		}
	}

	/// Retrieve the current control settings for this communications device
	fn comm_state(&self) -> io::Result<DCB> {
		let mut dcb = unsafe { mem::zeroed() };
		let (succeded, err) = unsafe { (
			GetCommState(*self.comm_handle.borrow_mut(), &mut dcb) != 0,
			kernel32::GetLastError() as i32
		)};

		if succeded {
			Ok(dcb)
		} else {
			Err(system_to_io_err("GetCommState", err))
		}
	}

	/// Configures this communications device according to specifications in a device-control block,
	/// `dcb`.
	fn set_comm_state(&mut self, mut dcb: DCB) -> io::Result<()> {
		let (succeded, err) = unsafe { (
			SetCommState(*self.comm_handle.borrow_mut(), &mut dcb) != 0,
			kernel32::GetLastError() as i32
		)};

		if succeded {
			Ok(())
		} else {
			Err(system_to_io_err("SetCommState", err))
		}
	}

	/// Set interval and total timeouts to `timeout_ms`
	pub fn set_timeout(&mut self, timeout_ms: u32) -> io::Result<()> {
		let (succeded, err) = unsafe { (
			SetCommTimeouts(*self.comm_handle.borrow_mut(), &mut COMMTIMEOUTS{
				ReadIntervalTimeout: timeout_ms,
				ReadTotalTimeoutMultiplier: timeout_ms,
				ReadTotalTimeoutConstant: timeout_ms,
				WriteTotalTimeoutMultiplier: timeout_ms,
				WriteTotalTimeoutConstant: timeout_ms,
			}) != 0,
			kernel32::GetLastError() as i32
		)};

		if succeded {
			Ok(())
		} else {
			Err(system_to_io_err("SetCommTimeouts", err))
		}
	}

	pub fn baud_rate(&self) -> io::Result<u32> {
		self.comm_state().map(|dcb| dcb.BaudRate)
	}

	pub fn set_baud_rate(&mut self, baud_rate: u32) -> io::Result<()> {
		self.comm_state().and_then(|dcb| self.set_comm_state(DCB{ BaudRate: baud_rate, ..dcb }))
	}

	pub fn byte_size(&self) -> io::Result<u8> {
		self.comm_state().map(|dcb| dcb.ByteSize)
	}

	pub fn set_byte_size(&mut self, byte_size: u8) -> io::Result<()> {
		self.comm_state().and_then(|dcb| self.set_comm_state(DCB{ ByteSize: byte_size, ..dcb }))
	}

	pub fn parity(&self) -> io::Result<Parity> {
		self.comm_state().map(|dcb| match dcb.Parity {
			0 => Parity::NO,
			1 => Parity::ODD,
			2 => Parity::EVEN,
			3 => Parity::MARK,
			4 => Parity::SPACE,
			x => panic!("No match for parity, dcb.Parity = {}", x)
		})
	}

	pub fn set_parity(&mut self, parity: Parity) -> io::Result<()> {
		self.comm_state().and_then(|dcb| self.set_comm_state(DCB{ Parity: parity as u8, ..dcb }))
	}

	pub fn stop_bits(&self) -> io::Result<StopBits> {
		self.comm_state().map(|dcb| match dcb.StopBits {
			0 => StopBits::ONE,
			1 => StopBits::ONE5,
			2 => StopBits::TWO,
			x => panic!("No match for stop bits, dcb.StopBits = {}", x)
		})
	}

	pub fn set_stop_bits(&mut self, stop_bits: StopBits) -> io::Result<()> {
		self.comm_state().and_then(|dcb|
			self.set_comm_state(DCB{ StopBits: stop_bits as u8, ..dcb })
		)
	}

	/// Read into `buf` until `delim` is encountered. Return n.o. bytes read on success,
	/// and an IO error on failure.
	pub fn read_until(&mut self, delim: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
		use std::io::Read;

		let mut byte = [0_u8];
		loop {
			match self.read(&mut byte) {
				Err(e) => return Err(e),
				Ok(0) => { println!("read 0 bytes"); break },
				Ok(_) => (),
			};

			let buf_len = buf.len();
			if byte[0] == delim {
				return Ok(buf_len);
			}

			if buf_len == buf.capacity() {
				buf.reserve(buf_len);
			}
			buf.push(byte[0])
		}

		// Delimiter was not found before end of stream or timeout
		Err(Error::new(ErrorKind::Other, "Delimiter was not found"))
	}

	/// Read until newline. Return n.o. bytes read on success
	pub fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
		self.read_until('\n' as u8, buf)
	}
}
impl io::Read for Connection {
	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
		if buf.len() == 0 {
			return Ok(0)
		}

		let mut n_bytes_read = 0;
		let (succeded, err) = unsafe { (
			kernel32::ReadFile(*self.comm_handle.borrow_mut(),
				buf.as_mut_ptr() as *mut c_void,
				buf.len() as u32,
				&mut n_bytes_read,
				ptr::null_mut()) != 0,
			kernel32::GetLastError() as c_int
		)};

		if succeded {
			if n_bytes_read == 0 {
				Err(Error::new(ErrorKind::TimedOut, "Operation timed out"))
			} else {
				Ok(n_bytes_read as usize)
			}
		} else {
			Err(system_to_io_err("read", err))
		}
	}
}
impl io::Write for Connection {
	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
		let mut n_bytes_written = 0;

		let (succeded, err) = unsafe { (
			kernel32::WriteFile(*self.comm_handle.borrow_mut(),
				mem::transmute(buf.as_ptr()),
				buf.len() as u32,
				&mut n_bytes_written,
				ptr::null_mut()) != 0,
			kernel32::GetLastError() as c_int
		) };

		if succeded {
			Ok(n_bytes_written as usize)
		} else {
			Err(system_to_io_err("write", err))
		}
	}

	fn flush(&mut self) -> io::Result<()> {
		let (succeded, err) = unsafe { (
			kernel32::FlushFileBuffers(*self.comm_handle.borrow_mut()) != 0,
			kernel32::GetLastError() as c_int
		)};

		if succeded {
			Ok(())
		} else {
			Err(system_to_io_err("flush", err))
		}
	}
}
impl Drop for Connection {
	fn drop(&mut self) {
		let e = unsafe { kernel32::CloseHandle(*self.comm_handle.borrow_mut()) };
		if e == 0 {
			panic!("Drop of Connection failed. CloseHandle gave error 0x{:x}", e)
		}
	}
}
unsafe impl Send for Connection { }

// Some tests requires correct code to be running on connected serial device

// // Should work with any simple echo code on the arduino
// #[test]
// fn echo_test() {
// 	use std::io::Write;
// 	use std::thread;

// 	let port = "COM8";
// 	let baud_rate = 9600_u32;
// 	let mut connection = Connection::new(port, baud_rate).unwrap();
// 	thread::sleep_ms(2000);

// 	for i in 0..20 {
// 		let test_str = format!("One two {}\n", i);

// 		let n_bytes_written = connection.write(test_str.as_bytes());

// 		let mut buffer = Vec::with_capacity(20);

// 		let n_bytes_read = connection.read_line(&mut buffer);
// 		let read_string = String::from_utf8(buffer).unwrap();

// 		println!("Bytes written: {:?}, Bytes read: {:?}, String read: {}",
// 			n_bytes_written, n_bytes_read, read_string);
// 	}
// }

// Colorswirl. Works with arduino running LEDstream
#[test]
fn colorswirl_test() {
	use std::thread;
	use std::io::Write;

	let port = "COM8";
	let baud_rate = 115_200;
	let mut connection = Connection::new(port, baud_rate).unwrap();

	thread::sleep_ms(2000);

	let n_leds = 32;
	let pixel_size = 3;
	let header_size = 6;
	let mut buffer: Vec<u8> = (0..(header_size + n_leds * pixel_size)).map(|_| 0).collect();

	// A special header / magic word is expected by the corresponding LED streaming code 
	// running on the Arduino. This only needs to be initialized once because the number of  
	// LEDs remains constant:
	buffer[0] = 'A' as u8;                    // Magic word
	buffer[1] = 'd' as u8;
	buffer[2] = 'a' as u8;
	buffer[3] = ((n_leds - 1) >> 8) as u8;    // LED count high byte
	buffer[4] = ((n_leds - 1) & 0xff) as u8;  // LED count low byte
	buffer[5] = buffer[3] ^ buffer[4] ^ 0x55; // Checksum
	
	let mut main_sin = 0.0_f32;
	let mut main_hue = 0_u16;

	for _ in 0..1_000 {
		let mut internal_sin = main_sin;
		let mut internal_hue = main_hue;

		let (mut r, mut g, mut b): (u8, u8, u8);
		// Start at position 6, after the LED header/magic word
		for i in (6..buffer.len()).step_by(3) {
			// Fixed-point hue-to-RGB conversion.  'internal_hue' is an integer in the
			// range of 0 to 1535, where 0 = red, 256 = yellow, 512 = green, etc.
			// The high byte (0-5) corresponds to the sextant within the color
			// wheel, while the low byte (0-255) is the fractional part between
			// the primary/secondary colors.
			let pri_sec_frac = (internal_hue & 255) as u8;
			match (internal_hue >> 8) % 6 {
				0 => {
					r = 255;
					g = pri_sec_frac;
					b = 0;
				}, 1 => {
					r = 255 - pri_sec_frac;
					g = 255;
					b = 0;
				}, 2 => {
					r = 0;
					g = 255;
					b = pri_sec_frac;
				}, 3 => {
					r = 0;
					g = 255 - pri_sec_frac;
					b = 255;
				}, 4 => {
					r = pri_sec_frac;
					g = 0;
					b = 255;
				}, _ => {
					r = 255;
					g = 0;
					b = 255 - pri_sec_frac;
				}
			}

			// Resulting hue is multiplied by brightness in the range of 0 to 255
			// (0 = off, 255 = brightest).  Gamma corrrection (the 'powf' function
			// here) adjusts the brightness to be more perceptually linear.
			let brightness = (0.5 + internal_sin.sin() * 0.5).powf(2.8);
			buffer[i]     = (r as f32 * brightness) as u8;
			buffer[i + 1] = (g as f32 * brightness) as u8;
			buffer[i + 2] = (b as f32 * brightness) as u8;

			// Each pixel is slightly offset in both hue and brightness
			internal_hue += 40;
			internal_sin += 0.3;
		}

		// Slowly rotate hue and brightness in opposite directions
		main_hue = (main_hue + 4) % 1536;
		main_sin -= 0.03;

		// Issue color data to LEDs
		connection.write(&buffer[..]).unwrap();
		connection.flush().unwrap(); // Not necessary, just testing

		// The arduino can't handle it if we go too fast
		thread::sleep_ms(2);
	}
}