diff USBLib/Communication/UsbPipeStream.cs @ 67:2d16447eff12

Simplified USB communication code, added functions to abort pipe transfers
author Ivo Smits <Ivo@UCIS.nl>
date Wed, 16 Oct 2013 01:11:49 +0200
parents dcfec2be27c9
children
line wrap: on
line diff
--- a/USBLib/Communication/UsbPipeStream.cs	Tue Oct 15 16:22:54 2013 +0200
+++ b/USBLib/Communication/UsbPipeStream.cs	Wed Oct 16 01:11:49 2013 +0200
@@ -5,12 +5,10 @@
 	public class UsbPipeStream : Stream {
 		public IUsbInterface Device { get; private set; }
 		public Byte Endpoint { get; private set; }
-		public Boolean InterruptEndpoint { get; private set; }
 
-		public UsbPipeStream(IUsbInterface device, Byte endpoint, Boolean interrupt) {
+		public UsbPipeStream(IUsbInterface device, Byte endpoint) {
 			this.Device = device;
 			this.Endpoint = endpoint;
-			this.InterruptEndpoint = interrupt;
 		}
 
 		public override bool CanRead {
@@ -35,12 +33,17 @@
 			set { throw new NotImplementedException(); }
 		}
 
+		public void Abort() {
+			Device.PipeAbort(Endpoint);
+		}
+
+		public void ClearHalt() {
+			Device.PipeReset(Endpoint);
+		}
+
 		public override int Read(byte[] buffer, int offset, int count) {
-			if (InterruptEndpoint) {
-				return Device.InterruptRead(Endpoint, buffer, offset, count);
-			} else {
-				return Device.BulkRead(Endpoint, buffer, offset, count);
-			}
+			if (!CanRead) throw new InvalidOperationException("Can not read from an output endpoint");
+			return Device.PipeTransfer(Endpoint, buffer, offset, count);
 		}
 
 		public override long Seek(long offset, SeekOrigin origin) {
@@ -52,13 +55,14 @@
 		}
 
 		public override void Write(byte[] buffer, int offset, int count) {
-			int written;
-			if (InterruptEndpoint) {
-				written = Device.InterruptWrite(Endpoint, buffer, offset, count);
-			} else {
-				written = Device.BulkWrite(Endpoint, buffer, offset, count);
-			}
+			if (!CanWrite) throw new InvalidOperationException("Can not write to an input endpoint");
+			int written = Device.PipeTransfer(Endpoint, buffer, offset, count);
 			if (written != count) throw new EndOfStreamException("Could not write all data");
 		}
+
+		protected override void Dispose(bool disposing) {
+			if (disposing) try { Abort(); } catch { }
+			base.Dispose(disposing);
+		}
 	}
 }