Beispiel #1
0
        /// <summary>
        /// Writes the data.
        /// </summary>
        /// <returns><c>true</c>, if data was written, <c>false</c> otherwise.</returns>
        /// <param name="bytesToSend">Bytes to send.</param>
        public bool WriteData(byte[] bytesToSend)
        {
            ErrorCode   ecWrite;
            int         transferredOut;
            UsbTransfer usbWriteTransfer = null;

            if (myUsbDevice != null)
            {
                ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 1000, out usbWriteTransfer);
                if (ecWrite != ErrorCode.None)
                {
                    throw new Exception("Submit Async Write Failed.");
                }

                WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle }, 1000);//, false);

                if (!usbWriteTransfer.IsCompleted)
                {
                    usbWriteTransfer.Cancel();
                }
                ecWrite = usbWriteTransfer.Wait(out transferredOut);
                usbWriteTransfer.Dispose();
                // TODO: should check if (transferredOut != bytesToSend.Length), and eventually resend?
                return(true);
            }
            return(false);
        }
        private ErrorCode WriteReadBytesCommand(UsbEndpointBase endpoint)
        {
            UsbPacket   usbPacket = CreateReadBytesCommandPacket();
            UsbTransfer transfer  = null;

            try
            {
                ErrorCode errorCode = endpoint.SubmitAsyncTransfer(usbPacket, 0, (int)(_usbPacketSizeWithoutData + usbPacket.uiDataLen), _transferTimeoutInMilliseconds, out transfer);

                if (errorCode != ErrorCode.None)
                {
                    return(errorCode);
                }

                WaitHandle.WaitAll(new[] { transfer.AsyncWaitHandle }, _waitTimeout, false);

                if (!transfer.IsCompleted)
                {
                    transfer.Cancel();
                }

                int bytesTransferred;

                return(transfer.Wait(out bytesTransferred));
            }
            finally
            {
                transfer?.Dispose();
            }
        }
Beispiel #3
0
 private void OnApplicationQuit()
 {
     if (usbReaderTransfer != null)
     {
         usbReaderTransfer.Dispose();
     }
     UsbDevice.Exit();
     GCNAdapter = null;
 }
Beispiel #4
0
 private void OnApplicationQuit()
 {
     usbReaderTransfer.Cancel();
     if (usbReaderTransfer != null)
     {
         usbReaderTransfer.Dispose();
     }
     UsbDevice.Exit();
     GCNAdapter = null;
     gcThread.Abort();
     gcThread = null;
 }
Beispiel #5
0
        /// <summary>
        /// Reads the data.
        /// </summary>
        /// <returns>The data.</returns>
        public byte[] ReadData()
        {
            ErrorCode   ecRead;
            int         transferredIn;
            UsbTransfer usbReadTransfer = null;

            byte[] readBuffer;
            //
            readBuffer = new byte[16];
            ecRead     = reader.SubmitAsyncTransfer(readBuffer, 0, 8, 1000, out usbReadTransfer);
            if (ecRead != ErrorCode.None)
            {
                throw new Exception("Submit Async Read Failed.");
            }
            WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, 1000);//, false);
            ecRead = usbReadTransfer.Wait(out transferredIn);

            if (!usbReadTransfer.IsCompleted)
            {
                ecRead = reader.SubmitAsyncTransfer(readBuffer, 8, 8, 1000, out usbReadTransfer);
                if (ecRead != ErrorCode.None)
                {
                    throw new Exception("Submit Async Read Failed.");
                }
                WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, 1000);//, false);
            }

            if (!usbReadTransfer.IsCompleted)
            {
                usbReadTransfer.Cancel();
            }
            try
            {
                ecRead = usbReadTransfer.Wait(out transferredIn);
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
            usbReadTransfer.Dispose();

            byte[] readdata = new byte[transferredIn];
            Array.Copy(readBuffer, readdata, transferredIn);

            return(readdata);
        }
Beispiel #6
0
        public byte[] GetMessage(int timeout = 1000)
        {
            byte[]      data        = null;
            UsbTransfer usbTransfer = null;

            try
            {
                int    bytesRead;
                byte[] readBuffer = new byte[EndPointLength];

                ErrorCode errorCode = _endpointReader.SubmitAsyncTransfer(readBuffer, 0, readBuffer.Length, timeout, out usbTransfer);
                if (errorCode != ErrorCode.None)
                {
                    //throw new Exception(UsbDevice.LastErrorString);
                    return(null);
                }

                errorCode = usbTransfer.Wait(out bytesRead);
                if (errorCode != ErrorCode.None)
                {
                    if (errorCode == ErrorCode.IoTimedOut)
                    {
                        resetWhenDisconnected = true;
                    }
                    //throw new Exception(UsbDevice.LastErrorString);
                    return(null);
                }

                data = new byte[bytesRead];
                Array.Copy(readBuffer, data, bytesRead);
            }
            finally
            {
                if (usbTransfer != null)
                {
                    if (!usbTransfer.IsCancelled || !usbTransfer.IsCompleted)
                    {
                        usbTransfer.Cancel();
                    }

                    usbTransfer.Dispose();
                }
            }

            return(data);
        }
Beispiel #7
0
        public byte[] SendMessage(byte[] message, int timeout = 1000)
        {
            UsbTransfer usbTransfer = null;

            try
            {
                int bytesWritten;

                ErrorCode errorCode = _endpointWriter.SubmitAsyncTransfer(message, 0, message.Length, timeout, out usbTransfer);
                if (errorCode != ErrorCode.None)
                {
                    //throw new Exception(UsbDevice.LastErrorString);
                    return(null);
                }

                errorCode = usbTransfer.Wait(out bytesWritten);
                if (errorCode != ErrorCode.None)
                {
                    if (errorCode == ErrorCode.IoTimedOut)
                    {
                        resetWhenDisconnected = true;
                    }
                    //throw new Exception(UsbDevice.LastErrorString);
                    return(null);
                }
            }
            finally
            {
                if (usbTransfer != null)
                {
                    if (!usbTransfer.IsCancelled || !usbTransfer.IsCompleted)
                    {
                        usbTransfer.Cancel();
                    }

                    usbTransfer.Dispose();
                }
            }

            return(GetMessage(timeout));
        }
Beispiel #8
0
        public void WriteData(byte[] bytesToSend)
        {
            ErrorCode   ecWrite;
            int         transferredOut;
            UsbTransfer usbWriteTransfer = null;

            //
            ecWrite = writer.SubmitAsyncTransfer(bytesToSend, 0, bytesToSend.Length, 1000, out usbWriteTransfer);
            if (ecWrite != ErrorCode.None)
            {
                throw new Exception("Submit Async Write Failed.");
            }
            //
            WaitHandle.WaitAll(new WaitHandle[] { usbWriteTransfer.AsyncWaitHandle }, 1000, false);
            //
            if (!usbWriteTransfer.IsCompleted)
            {
                usbWriteTransfer.Cancel();
            }
            ecWrite = usbWriteTransfer.Wait(out transferredOut);
            // TODO: should check if transferredOut != bytesToSend.length, and eventually resend?
            usbWriteTransfer.Dispose();
        }
        private unsafe ReadUsbPacketResult ReadUsbPacket(UsbEndpointBase endpoint)
        {
            UsbTransfer transfer = null;

            try
            {
                var       usbPacketBuffer = new byte[_usbPacketSize];
                ErrorCode errorCode       = endpoint.SubmitAsyncTransfer(usbPacketBuffer, 0, usbPacketBuffer.Length, _transferTimeoutInMilliseconds, out transfer);

                if (errorCode != ErrorCode.None)
                {
                    _error.OnNext(errorCode);

                    return(new ReadUsbPacketResult(errorCode));
                }

                WaitHandle.WaitAll(new[] { transfer.AsyncWaitHandle }, _waitTimeout, false);

                if (!transfer.IsCompleted)
                {
                    transfer.Cancel();
                }

                int bytesTransferred;

                errorCode = transfer.Wait(out bytesTransferred);

                if (bytesTransferred == 0)
                {
                    return(new ReadUsbPacketResult(errorCode));
                }

                GCHandle gcHandle  = GCHandle.Alloc(usbPacketBuffer, GCHandleType.Pinned);
                var      usbPacket = Marshal.PtrToStructure <UsbPacket>(gcHandle.AddrOfPinnedObject());

                if (usbPacket.uiSeqNum != _sequenceNumber)
                {
                    _incorrectSequenceNumberReceived.OnNext(new IncorrectSequenceNumberReceivedArgs(_sequenceNumber, usbPacket.uiSeqNum));

                    return(new ReadUsbPacketResult(errorCode));
                }

                _sequenceNumber++;

                if (bytesTransferred < _usbPacketSizeWithoutData)
                {
                    _incorrectNumberOfBytesReceived.OnNext(bytesTransferred);

                    return(new ReadUsbPacketResult(errorCode));
                }
                if (errorCode != ErrorCode.None)
                {
                    return(new ReadUsbPacketResult(errorCode));
                }
                if (usbPacket.uiDataLen == 0)
                {
                    _noData.OnNext(Unit.Default);

                    return(new ReadUsbPacketResult(errorCode));
                }

                _fileOffset += usbPacket.uiDataLen;

                var strokes    = new List <Stroke>();
                var dataBuffer = new byte[usbPacket.uiDataLen];
                Marshal.Copy(new IntPtr(usbPacket.pData), dataBuffer, 0, dataBuffer.Length);

                for (var i = 0; i < dataBuffer.Length; i += 8)
                {
                    strokes.Add(new Stroke(dataBuffer[i], dataBuffer[i + 1], dataBuffer[i + 2], dataBuffer[i + 3]));
                }

                return(new ReadUsbPacketResult(errorCode, strokes));
            }
            finally
            {
                transfer?.Dispose();
            }
        }
Beispiel #10
0
        public static string WriteAndRead(int vid, int pid, byte[] byteArrayWritten)
        {
            ErrorCode       ec          = ErrorCode.None;
            UsbDevice       MyUsbDevice = null;
            UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(vid, pid);

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null)
                {
                    throw new Exception("Device Not Found. vid=" + vid + ", pid=" + pid);
                }

                // If this is a "whole" usb device (libusb-win32, linux libusb)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                using (UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02))
                {
                    reader.Reset();
                    // open write endpoint 1.
                    using (UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01))
                    {
                        UsbTransfer usbTransfer = null;

                        try
                        {
                            writer.Reset();
                            // Remove the exepath/startup filename text from the begining of the CommandLine.

                            if (byteArrayWritten.Length > 0)
                            {
                                int bytesWritten;

                                ec = writer.Write(byteArrayWritten, 2000, out bytesWritten);
                                if (ec != ErrorCode.None)
                                {
                                    throw new Exception(UsbDevice.LastErrorString);
                                }

                                byte[] readBuffer = new byte[256];
                                string retString  = "";
                                while (ec == ErrorCode.None)
                                {
                                    Thread.Sleep(1000);

                                    int bytesRead;

                                    // If the device hasn't sent data in the last 100 milliseconds,
                                    // a timeout error (ec = IoTimedOut) will occur.
                                    ec = reader.Read(readBuffer, 1000, out bytesRead);
                                    if (ec != ErrorCode.None)
                                    {
                                        throw new Exception(UsbDevice.LastErrorString);
                                    }

                                    if (bytesRead == 0)
                                    {
                                        return(retString);
                                        //throw new Exception("No more bytes!");
                                    }

                                    // Write that output to the console.
                                    //Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));

                                    retString += Encoding.Default.GetString(readBuffer, 0, bytesRead);
                                }

                                //Console.WriteLine("\r\nDone!\r\n");
                            }
                            else
                            {
                                throw new Exception("Nothing to do.");
                            }
                        }
                        finally
                        {
                            if (usbTransfer != null)
                            {
                                // **** Start of code added to fix ObjectDisposedException
                                if (!usbTransfer.IsCancelled || !usbTransfer.IsCompleted)
                                {
                                    usbTransfer.Cancel();
                                }
                                // **** End of code added to fix ObjectDisposedException
                                usbTransfer.Dispose();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new RMSAppException("WriteAndRead failed. " + ex.Message, ex, true);
                //Console.WriteLine();
                //Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                try
                {
                    if (MyUsbDevice != null)
                    {
                        if (MyUsbDevice.IsOpen)
                        {
                            // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                            // it exposes an IUsbDevice interface. If not (WinUSB) the
                            // 'wholeUsbDevice' variable will be null indicating this is
                            // an interface of a device; it does not require or support
                            // configuration and interface selection.
                            IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                            if (!ReferenceEquals(wholeUsbDevice, null))
                            {
                                // Release interface #0.
                                wholeUsbDevice.ReleaseInterface(0);
                                //wholeUsbDevice.ResetDevice();
                            }

                            MyUsbDevice.Close();
                        }
                        MyUsbDevice = null;

                        // Free usb resources
                        UsbDevice.Exit();
                    }
                    System.Threading.Thread.Sleep(750);
                }
                catch (Exception ex)
                {
                    new RMSAppException("WriteAndReadUSB - Closing USB failed. " + ex.Message, ex, true);
                }
            }
            return(null);
        }