Example #1
0
        /// <summary>
        /// Get joystick event
        /// </summary>
        /// <returns>The event.</returns>
        public JoystickEvent GetEvent()
        {
            JoystickEvent joystickEvent;

            if (this.shutdownEvent != null)
            {
                if (!this.eventQueue.TryDequeue(out joystickEvent))
                {
                    joystickEvent = null;
                }
            }
            else
            {
                byte[] eventData = new byte[8];
                var    dataRead  = this.joystickDeviceStream.Read(eventData, 0, eventData.Length);
                if (dataRead == 0)
                {
                    joystickEvent = null;
                }
                else
                {
                    if (dataRead != eventData.Length)
                    {
                        throw new ApplicationException("Failed to read joystick data");
                    }

                    joystickEvent = new JoystickEvent(eventData);
                }
            }

            return(joystickEvent);
        }
Example #2
0
        /// <summary>
        /// Data Reader worker thread
        /// </summary>
        private void DataReaderWorker()
        {
            var          waitHandles = new WaitHandle[] { this.shutdownEvent.WaitHandle, null };
            var          buffer      = new byte[EventBufferSize];
            IAsyncResult asyncResult = null;

            while (true)
            {
                try
                {
                    asyncResult = this.joystickDeviceStream.BeginRead(
                        buffer,
                        0,
                        EventBufferSize,
                        null,
                        null);
                    waitHandles[1] = asyncResult.AsyncWaitHandle;
                    if (WaitHandle.WaitAny(waitHandles) == 0)
                    {
                        break;
                    }

                    var dataRead = this.joystickDeviceStream.EndRead(asyncResult);
                    if (dataRead != EventBufferSize)
                    {
                        var errorMessage = string.Format(
                            CultureInfo.InvariantCulture,
                            "Expected to read {0} bytes from joystick device \"{1}\". However, only {2} bytes returned",
                            EventBufferSize,
                            this.joystickDeviceFullName,
                            dataRead);
                        throw new IOException(errorMessage);
                    }

                    var joystickEvent = new JoystickEvent(buffer);
                    this.eventQueue.Enqueue(joystickEvent);
                }
                catch (Exception exception)
                {
                    Trace.TraceError("Joystick.DataReaderWorker: " + exception.ToString());
                    break;
                }
            }
        }