private static void HandleJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Debug.WriteLine("No Gamepad found.");
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Debug.WriteLine("Found Gamepad with GUID: {0}", joystickGuid);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick every 1 millisecond
            var timer = Observable.Interval(TimeSpan.FromMilliseconds(1));

            timer
                // Get all joystick input
                .SelectMany(_ => { joystick.Poll(); return joystick.GetBufferedData(); })
                // Filter only menu key button (xbox one controller)
                .Where(a => a.Offset == JoystickOffset.Buttons6)
                // Input will contain UP and Down button events
                .Buffer(2)
                // If button was pressed longer than a second
                .Where(t => (TimeSpan.FromMilliseconds(t.Last().Timestamp) - TimeSpan.FromMilliseconds(t.First().Timestamp)).TotalSeconds >= 1)
                // Press and hold F key for 1.5s
                .Subscribe(t =>
                {
                    SendKeyDown(KeyCode.KEY_F);
                    System.Threading.Thread.Sleep(1500);
                    SendKeyUp(KeyCode.KEY_F);
                });
        }
Пример #2
0
        static void MainForJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                    Console.WriteLine(state);
            }
        }
Пример #3
0
        /*
         * Start reading
         */
        private void HIDReadData()
        {
            // Poll events
            _HIDTransmitterInterface.Poll();
            var bufferedData = _HIDTransmitterInterface.GetBufferedData();

            if (bufferedData != null)
            {
                foreach (var state in bufferedData)
                {
                    switch (state.Offset)
                    {
                    case JoystickOffset.X:
                    {
                        _positions.Aileron = state.Value / CONTROL_RATES;
                        break;
                    }

                    case JoystickOffset.Y:
                    {
                        _positions.Elevator = state.Value / CONTROL_RATES;
                        break;
                    }

                    case JoystickOffset.RotationZ:
                    {
                        _positions.Rudder = state.Value / CONTROL_RATES;
                        break;
                    }

                    case JoystickOffset.Sliders0:
                    {
                        _positions.Throttle = state.Value / CONTROL_RATES;
                        break;
                    }

                    default:
                    {
                        Console.WriteLine("HID:: Unsupported control!");
                        break;
                    }
                    }
                }

                _protocolServices.OnPositionMessageModelChanged(_positions);
            }
        }
Пример #4
0
        public void getData()
        {
            joystick.Poll();
            var datas = joystick.GetBufferedData();

            foreach (var state in datas)
            {
                if (state.Offset == JoystickOffset.X)
                {
                    Console.WriteLine("X = " + state.Value);
                }
                if (state.Offset == JoystickOffset.RotationY)
                {
                    Console.WriteLine("RotationY = " + state.Value);
                }
            }
        }
Пример #5
0
        private void listen(DeviceInstance controller)
        {
            var directInput = new DirectInput();

            joystick = new Joystick(directInput, controller.InstanceGuid);
            joystick.Properties.BufferSize = 128;
            joystick.Acquire();
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    updateStatus(state.Offset.ToString(), state.Value);
                }
            }
        }
Пример #6
0
        public void send_joystick()
        {
            if (stick == null || stick.Poll().IsFailure)
            {
                StateData.send_joystick_enabled   = false;
                StateData.dashboard_state.enabled = false;
                StateData.mainwindow.Disable();
                MessageBox.Show("Joystick Disconnected");
                return;
            }
            stick.GetBufferedData();
            var state = stick.GetCurrentState();

            StateData.joystick_data.Load(state);

            send_key(StateData.joystick_data.Serialize());
        }
Пример #7
0
        public void Timer_tick(object obj)
        {
            try
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();


                foreach (var state in datas)
                {
                    //speed coef
                    if (Convert.ToString(state.Offset) == "Z")
                    {
                        coef = map((65535 - state.Value), 0, 65535, 0, 5);
                    }

                    // left/right
                    else if (Convert.ToString(state.Offset) == "Y")
                    {
                        Stabilization.StabData.EncoderVertData = (int)(map((65535 - state.Value), 0, 65535, -140, 140));
                        prevY = Stabilization.StabData.EncoderVertData;
                    }

                    //Up/down
                    else if (Convert.ToString(state.Offset) == "X")
                    {
                        Stabilization.StabData.EncoderHorData = (int)(map((65535 - state.Value), 0, 65535, -70, 70));
                        prevX = Stabilization.StabData.EncoderHorData;
                    }
                }
                Stabilization.StabData.EncoderHorData  *= (int)(coef);
                Stabilization.StabData.EncoderVertData *= (int)(coef);
                Console.WriteLine(Stabilization.StabData.EncoderHorData);
                Console.WriteLine(Stabilization.StabData.EncoderVertData);
                Stabilization.protocol.UpdateAndSendPacket(Stabilization.StabData);
                Stabilization.StabData.EncoderHorData  = prevX;
                Stabilization.StabData.EncoderVertData = prevY;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
Пример #8
0
        private void PollGamepads()
        {
            foreach (DeviceInstance device in AllGamepads)
            {
                //TODO: Do this in initialisation?
                Joystick gamepad = new Joystick(RawInput, device.InstanceGuid);
                gamepad.Properties.BufferSize = InputBufferSize;
                gamepad.Acquire();

                //Poll events from gamepad
                gamepad.Poll();
                JoystickState         state       = gamepad.GetCurrentState();
                List <JoystickUpdate> lastUpdates = gamepad.GetBufferedData().ToList();

                //Handle updates
                if (lastUpdates != null && lastUpdates.Count > 0)
                {
                    //TODO
                }

                //D-Pad events
                switch (state.PointOfViewControllers[0])
                {
                case 0:
                    //D-Pad Up
                    break;

                case 9000:
                    //D-Pad Right
                    break;

                case 18000:
                    //D-Pad Down
                    break;

                case 27000:
                    //D-Pad Left
                    break;
                }
            }
        }
        private void getJoystickData(object state)
        {
            try
            {
                joystick.Poll();
                JoystickUpdate[] datas = joystick.GetBufferedData();
                foreach (JoystickUpdate joyState in datas)
                {
                    if (joyState.Offset == JoystickOffset.X)
                    {
                        X = Math.Max(Math.Min(((double)joyState.Value - 32767.5) / 32767.5, +1), -1);
                    }
                    if (joyState.Offset == JoystickOffset.Y)
                    {
                        Y = Math.Max(Math.Min(((double)joyState.Value - 32767.5) / 32767.5, +1), -1);
                    }
                    if (OnUpdate != null)
                    {
                        OnUpdate(this, new joystickEventArgs(X, Y));
                    }
                }
            }
            catch (SharpDX.SharpDXException ex)
            {
                // Most likely connection was lost, so resume connection timer
                Debug.WriteLine("Joystick connection lost.");
                isDeviceAttached = false;
                if (pollTimer != null)
                {
                    pollTimer.Dispose();
                }

                connectTimer = new System.Threading.Timer(attemptJoystickConnect, null, 0, 1000);

                if (OnConnectionEvent != null)
                {
                    OnConnectionEvent(this, new joystickEventArgs(X, Y));
                }
            }
        }
Пример #10
0
        public JoystickUpdate[] GetData()
        {
            if (_controller == null)
            {
                return(null);
            }

            if (!_directInput.IsDeviceAttached(_controller.Information.InstanceGuid))
            {
                if (!Initialize())
                {
                    return(null);
                }
            }

            try
            {
                // Poll events from joystick
                _controller.Poll();
                var datas = _controller.GetBufferedData();
                foreach (var state in datas)
                {
                    Debug.WriteLine(state);
                }
                return(datas);
            }
            catch (SharpDXException e)
            {
                if (e.ResultCode.Code == ResultCode.InputLost.Code ||
                    e.ResultCode.Code == ResultCode.NotAcquired.Code)
                {
                    _controller.Acquire();
                }

                Debug.WriteLine(e.ToString());
            }

            return(null);
        }
Пример #11
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            joystick.Poll();

            joystick.GetCurrentState();

            var datas = joystick.GetBufferedData();

            if (datas.Length > 0 && !firstRun)
            {
                foreach (var item in datas)
                {
                    JoystickUpdate x;

                    if (joystick.Information.InstanceName.Contains("Xbox"))
                    {
                        //not sure why, but xbox controllers always put pressed buttons after axis manipulation data contrary to my PS2 adapter
                        x = datas[datas.Length - 1];
                    }
                    else
                    {
                        x = datas[0];
                    }

                    if ((x.Offset != JoystickOffset.Buttons4 && (toggle_ignore.IsChecked ?? false)) && x.Value > 0)
                    {
                        buttonColor = new JoystickButtonToColor()
                        {
                            Button = x.Offset, Color = new Color(), ControlType = controlType, PressedBrightness = 64, CenteredBrightness = 255
                        };
                        buttonColor.SetMinMaxValues(x.Value);
                        timer.Stop();
                        DialogHost.CloseDialogCommand.Execute(buttonColor, this);
                    }
                }
            }

            firstRun = false;
        }
 private void SpawnDirectInputListener(Joystick joystick, DeviceInstance deviceInstance)
 {
     _joystickCollection.Add(joystick);
     // Acquire the joystick
     try
     {
         while (!_stopListening)
         {
             joystick.Poll();
             var datas = joystick.GetBufferedData();
             foreach (var state in datas)
             {
                 SetTextBoxText(state, deviceInstance);
             }
             Thread.Sleep(10);
         }
     }
     catch (Exception)
     {
     }
     joystick.Unacquire();
 }
Пример #13
0
 private void joystickInputHandler(Joystick joystick)
 {
     try
     {
         RoverConsole.ArcEyeContentThreadSafe("Joystick ready to rock and roll.");
         joystick.Properties.BufferSize = 128;
         joystick.Acquire();
         while (true)
         {
             joystick.Poll();
             var datas = joystick.GetBufferedData();
             foreach (var state in datas)
             {
                 //RoverConsole.ArcEyeContentThreadSafe("Joystick data : " + state.ToString());
                 _RoverMovement.buttonHandlerAnalog(state);
                 _RoverMovement.buttonHandlerDigital(state);
             }
         }
     }
     catch (Exception ex)
     {
         RoverConsole.ArcEyeAiContentThreadSafe(ex.ToString());
         _RoverMovement.rvr_mvmnt_pnl.Dispatcher.Invoke((Action)(() =>
         {
             _RoverMovement.joystck_pnl.IsExpanded = false;
             _RoverMovement.rld_btn.IsEnabled = true;
             _RoverMovement.fst_initialize_btn.IsEnabled = true;
             if (_RoverMovement.roverMovement != RoverAndArmRoverMovement.Stop)
             {
                 RoverConsole.ArcEyeAiContentThreadSafe("Exciting safety procedure ...!!!");
                 _RoverMovement.roverMovement = RoverAndArmRoverMovement.Stop;
                 _RoverMovement.pwm = 0;
                 _RoverMovement.RoverMovementStatusUpdater();
             }
         }));
         RoverConsole.ArcEyeAiContentThreadSafe("Mouse And KeyBoard Panel Activated, Set As primary I/o Device");
     }
 }
Пример #14
0
        private List <JoystickUpdate> SetJoystickButton(Joystick joystick, string button)
        {
            //var ButtonAssignments = new Dictionary<string, JoystickUpdate[]>;

            List <JoystickUpdate> ButtonPressRelease = new List <JoystickUpdate>();

            // Poll events from joystick
            while (ButtonPressRelease.Count < 2)
            {
                if (Skip)
                {
                    Skip = false;
                    break;
                }
                else
                {
                    joystick.Poll();
                }
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.Offset == JoystickOffset.Z && !AnalogSet)
                    {
                        ZDetected = true;
                        return(null);
                    }
                    var acceptedState = state.Offset != JoystickOffset.X && state.Offset != JoystickOffset.Y && state.Offset != JoystickOffset.Z && state.Offset != JoystickOffset.RotationZ;
                    if (acceptedState)
                    {
                        ButtonPressRelease.Add(state);
                        Console.WriteLine(state);
                    }
                }
            }
            Console.WriteLine(ButtonPressRelease);
            return(ButtonPressRelease);
        }
Пример #15
0
        /// <summary>
        /// The method for the joystick polling thread. Gets all joystick values and sends them (along with each property updated flag) to the sender timer
        /// For more informatino on this method, see the sharpDX api documentation/samples
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void GetJoystickValues(object sender, DoWorkEventArgs e)
        {
            if (System.Threading.Thread.CurrentThread.Priority != System.Threading.ThreadPriority.BelowNormal)
            {
                System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal;
            }
            //https://stackoverflow.com/questions/3929764/taking-input-from-a-joystick-with-c-sharp-net
            //https://github.com/sharpdx/SharpDX-Samples/blob/master/Desktop/DirectInput/JoystickApp/Program.cs
            //http://sharpdx.org/wiki/class-library-api/directinput/

            Joystick = new Joystick(DirectInput, DeviceInstances[joystickIndex].InstanceGuid);
            Joystick.Properties.BufferSize = 128;
            Joystick.Properties.AxisMode   = DeviceAxisMode.Absolute;
            Joystick.Properties.DeadZone   = AXIS_DEADZONE;
            Joystick.Acquire();
            while (true)
            {
                if (joystickWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                if (Joystick != null && joystickDriveneable)
                {
                    //send values from joystick
                    Joystick.Poll();
                    JoystickUpdate[] updates    = Joystick.GetBufferedData();
                    float            xValue     = 0;
                    float            yValue     = 0;
                    bool             buttonTemp = false;
                    //reverse the list to get the latest version of each
                    //updates.Reverse();
                    bool xUpdated      = false;
                    bool yUpdated      = false;
                    bool buttonUpdated = false;
                    if (FirstJoystickMoveMent)
                    {
                        xUpdated              = true;
                        yUpdated              = true;
                        buttonUpdated         = true;
                        xValue                = 0.5F;
                        yValue                = 0.5F;
                        buttonTemp            = false;
                        FirstJoystickMoveMent = false;
                    }
                    foreach (JoystickUpdate update in updates)
                    {
                        //scale the x and y values to between 0 and 1
                        if (!xUpdated && update.Offset == JoystickOffset.X)
                        {
                            xValue   = update.Value / MAX_AXIS_VALUE;
                            xUpdated = true;
                        }
                        else if (!yUpdated && update.Offset == JoystickOffset.Y)
                        {
                            yValue   = update.Value / MAX_AXIS_VALUE;
                            yUpdated = true;
                        }
                        else if (!buttonUpdated && update.Offset == JoystickOffset.Buttons0)
                        {
                            buttonTemp    = update.Value == 128 ? true : false;
                            buttonUpdated = true;
                        }
                    }
                    //subtract to make the -0.5 to 0.5, 0 being center
                    if (xUpdated)
                    {
                        JoystickXValue = xValue - 0.5F;
                    }
                    if (yUpdated)
                    {
                        JoystickYValue = yValue - 0.5F;
                    }
                    if (buttonUpdated)
                    {
                        Motor = buttonTemp;
                    }
                    //round them as well to 3 decimal places
                    JoystickXValue = (float)Math.Round(JoystickXValue, 3);
                    JoystickYValue = (float)Math.Round(JoystickYValue, 3);
                }
            }
        }
Пример #16
0
        public override void ProcessInput()
        {
            Boolean[] updatedAxis   = new Boolean[AltDirectInputDevice.AxisList.GetLength(0)];
            Boolean[] updatedPov    = new Boolean[Pov.Length];
            Boolean[] updatedButton = new Boolean[Button.Length];
            uint      CurrentMode   = (uint)GameState.CurrentMode;

            Joystick.Poll();
            var data = Joystick.GetBufferedData();

            foreach (var state in data)
            {
                String OffsetName = Enum.GetName(typeof(JoystickOffset), state.Offset);
                if (OffsetName.StartsWith("Buttons"))
                {
                    // This call should always succeed
                    uint i = uint.Parse(OffsetName.Substring("Buttons".Length));
                    // DirectInput doc says a button is pressed if the MSB is set
                    GameState.UpdateButton(Button[i].Mapping[(uint)GameState.CurrentMode], (state.Value >= 0x80)? 1.0f : 0.0f);
                    updatedButton[i]    = true;
                    Button[i].LastValue = state.Value;
                }
                else if (OffsetName.StartsWith("PointOf"))
                {
                    uint i = uint.Parse(OffsetName.Substring("PointOfViewControllers".Length));
                    GameState.UpdatePov(Pov[i], state.Value, (uint)GameState.CurrentMode, false);
                    updatedPov[i]    = true;
                    Pov[i].LastValue = state.Value;
                }
                else
                {
                    for (var i = 0; i < AltDirectInputDevice.AxisList.GetLength(0); i++)
                    {
                        if ((!Axis[i].isAvailable) || (String.IsNullOrEmpty(Axis[i].Mapping1[CurrentMode].Action)))
                        {
                            continue;
                        }
                        if (OffsetName == AltDirectInputDevice.AxisList[i, 0])
                        {
                            float value = ((state.Value - Axis[i].Range.Minimum) /
                                           (0.5f * Axis[i].Range.FloatRange)) - 1.0f;
                            if (Axis[i].Control[CurrentMode].Inverted)
                            {
                                value = -value;
                            }
                            // Because we computed some stuff, we need to apply the dead zone ourselves.
                            // Also a slider's dead zone applies to the edges rather than the center.
                            if (OffsetName.StartsWith("Slider"))
                            {
                                if (value < (-1.0f + Axis[i].Control[CurrentMode].DeadZone))
                                {
                                    value = -1.0f;
                                }
                                if (value > (1.0f - Axis[i].Control[CurrentMode].DeadZone))
                                {
                                    value = 1.0f;
                                }
                            }
                            else
                            {
                                if (Math.Abs(value) < Axis[i].Control[CurrentMode].DeadZone)
                                {
                                    value = 0.0f;
                                }
                            }

                            switch (Axis[i].Control[CurrentMode].Type)
                            {
                            case ControlType.Axis:
                                GameState.UpdateAxis(Axis[i].Mapping1[CurrentMode], value, Axis[i].Control[CurrentMode].Factor);
                                break;

                            case ControlType.OneShot:
                                var MinThreshold = -1.0f * Axis[i].Control[CurrentMode].DeadZone;
                                var MaxThreshold = +1.0f * Axis[i].Control[CurrentMode].DeadZone;
                                // When an axis is used as OneShot, we detect transitions across the threshold(s)
                                if ((Axis[i].LastValue < MinThreshold) && (value >= MinThreshold))
                                {
                                    GameState.UpdateButton(Axis[i].Mapping1[CurrentMode], 0.0f);
                                }
                                else if ((Axis[i].LastValue > MinThreshold) && (value <= MinThreshold))
                                {
                                    GameState.UpdateButton(Axis[i].Mapping1[CurrentMode], 1.0f);
                                }
                                else if ((Axis[i].LastValue < MaxThreshold) && (value >= MaxThreshold))
                                {
                                    GameState.UpdateButton(Axis[i].Mapping2[CurrentMode], 1.0f);
                                }
                                else if ((Axis[i].LastValue > MaxThreshold) && (value <= MaxThreshold))
                                {
                                    GameState.UpdateButton(Axis[i].Mapping2[CurrentMode], 0.0f);
                                }
                                break;

                            case ControlType.Continuous:
                                GameState.UpdateButton((value < 0.0f) ? Axis[i].Mapping1[CurrentMode] :
                                                       Axis[i].Mapping2[CurrentMode], Math.Abs(value));
                                break;

                            default:
                                print("AltInput: DirectInputDevice.ProcessInput() - unhandled control type");
                                break;
                            }
                            updatedAxis[i]    = true;
                            Axis[i].LastValue = value;
                        }
                    }
                }
            }
            // Now update all controls that are in Continuous mode and that weren't previously updated
            for (var i = 0; i < AltDirectInputDevice.AxisList.GetLength(0); i++)
            {
                // Only update the axis if it's Continuous, nonzero and wasn't updated  from regular check
                if ((!Axis[i].isAvailable) || (Axis[i].Control[CurrentMode].Type != ControlType.Continuous) ||
                    (Axis[i].LastValue == 0.0f) || (updatedAxis[i]))
                {
                    continue;
                }
                GameState.UpdateButton((Axis[i].LastValue < 0.0f) ? Axis[i].Mapping1[CurrentMode] :
                                       Axis[i].Mapping2[CurrentMode], Math.Abs(Axis[i].LastValue));
            }
            for (uint i = 0; i < Button.Length; i++)
            {
                if ((!Button[i].Continuous[CurrentMode]) || (Button[i].LastValue < 0x80) || (updatedButton[i]))
                {
                    continue;
                }
                GameState.UpdateButton(Button[i].Mapping[CurrentMode], 1.0f);
            }
            for (uint i = 0; i < Pov.Length; i++)
            {
                if ((Pov[i].LastValue < 0) || (updatedPov[i]))
                {
                    continue;
                }
                GameState.UpdatePov(Pov[i], Pov[i].LastValue, CurrentMode, true);
            }
        }
        static void Main(string[] args)
        {
            TcpClient tcpclnt = new TcpClient();

            Console.WriteLine("Enter the IP address or hostname of the PC you wish to connect to:");
            string IPAddr = Console.ReadLine();

            Console.WriteLine("Enter the port:");
            string portString = Console.ReadLine();
            int    port       = Int32.Parse(portString);

            Console.WriteLine("Connecting.....");
            try
            {
                tcpclnt.Connect(IPAddr, port);
            }
            catch
            {
                Console.WriteLine("Connection failed. Hit enter to exit");
                Console.ReadLine();
                System.Environment.Exit(1);
            }

            //send test message on TCP connection
            //string message = "Hello thar TCP!";
            Stream TCPstream = tcpclnt.GetStream();
            //ASCIIEncoding asen = new ASCIIEncoding();
            //byte[] byteArray = asen.GetBytes(message);

            //TCPstream.Write(byteArray, 0, byteArray.Length);

            /*byte[] TempByteArray = new byte[100];
             * int k = TCPstream.Read(TempByteArray, 0, 100);
             *
             * for(int i = 0; i < k; i++)
             * {
             *  Console.Write(Convert.ToChar(TempByteArray[i]));
             * }*/


            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();

            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    //Console.WriteLine(state);
                    if (state.Offset == JoystickOffset.PointOfViewControllers0)
                    {
                        DpadState(state, TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons0)
                    {
                        ButtonState(state, '1', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons1)
                    {
                        ButtonState(state, '2', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons2)
                    {
                        ButtonState(state, '3', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons3)
                    {
                        ButtonState(state, '4', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons4)
                    {
                        ButtonState(state, '5', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons5)
                    {
                        ButtonState(state, '6', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons6)
                    {
                        ButtonState(state, '7', TCPstream);
                    }
                    else if (state.Offset == JoystickOffset.Buttons7)
                    {
                        ButtonState(state, '8', TCPstream);
                    }
                }
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            if (client == null)
            {
                // create client instance
                client = new MqttClient(MQTT_BROKER_ADDRESS);

                string clientId = Guid.NewGuid().ToString();
                client.Connect(clientId, "mifmasterz", "123qweasd");

                SubscribeMessage();
            }
            // Initialize DirectInput

            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                                                                  DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                                                                      DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();

            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
            const int stop = 32511;

            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.Offset.ToString() == "X" && state.Value > stop)
                    {
                        MoveRobot("MOVE", "R");
                        Console.WriteLine("Kanan");
                    }
                    else if (state.Offset.ToString() == "X" && state.Value < stop)
                    {
                        MoveRobot("MOVE", "L");

                        Console.WriteLine("Kiri");
                    }
                    else if (state.Offset.ToString() == "Y" && state.Value < stop)
                    {
                        MoveRobot("MOVE", "F");

                        Console.WriteLine("Maju");
                    }
                    else if (state.Offset.ToString() == "Y" && state.Value > stop)
                    {
                        MoveRobot("MOVE", "B");

                        Console.WriteLine("Mundur");
                    }
                    else
                    {
                        MoveRobot("MOVE", "S");

                        Console.WriteLine("Stop");
                    }
                }
            }
        }
Пример #19
0
        public static void _Joystic()
        {

            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;


            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                    DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
                _is_joysticConnect = true;

            }
            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
                _is_joysticConnect = true;
            }
            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                _is_joysticConnect = false;
            }

            if (_is_joysticConnect)
            {
                var joystick = new Joystick(directInput, joystickGuid);

                Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

                // Query all suported ForceFeedback effects
                var allEffects = joystick.GetEffects();
                foreach (var effectInfo in allEffects)
                    Console.WriteLine("Effect available {0}", effectInfo.Name);

                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;

                // Acquire the joystick
                joystick.Acquire();

                // Poll events from joystick
                var joystickState = new JoystickState();
                bool work;
                while (_continue )
                {
                    work = false;
                    joystick.Poll();
                    var data = joystick.GetBufferedData();
                    foreach (var state in data)
                    {

                        if (state.Offset == JoystickOffset.X)
                        {
                            yaw_curr = ((32767 - state.Value) / 4096);
                            if (Math.Abs(yaw_curr - yaw_prev) >3 )
                            {
                                string mes = Convert.ToString(yaw_curr);
                                while (mes.Length < 5)
                                {
                                    mes = ' ' + mes;
                                }
                                _serialPort.WriteLine('y' + mes);
                                yaw_prev = yaw_curr;

                            }
                            work = true;
                        }
                        if (state.Offset == JoystickOffset.Z)
                        {
                            pitch_curr = ((32767 - state.Value) / 20) + pitch0;
                            if(Math.Abs(pitch_curr - pitch_prev)>100)
                            {
                                string mes = Convert.ToString(pitch_curr);
                                while (mes.Length < 5)
                                {
                                    mes = ' ' + mes;
                                }
                                _serialPort.WriteLine('p'+mes);
                                pitch_prev = pitch_curr;
                                
                            }
                            work = true;
                        }
                        if (state.Offset == JoystickOffset.RotationZ)
                        {
                            roll_curr = ((state.Value - 32767) / 20) + roll0;
                            if (Math.Abs(roll_curr - roll_prev) > 100)
                            {
                                string mes = Convert.ToString(roll_curr);
                                while (mes.Length < 5)
                                {
                                    mes = ' ' + mes;
                                }
                                _serialPort.WriteLine('r' + mes);
                                roll_prev = roll_curr;
                                
                            }
                            work = true;
                        }
                        if (state.Offset == JoystickOffset.PointOfViewControllers0) // power
                        {
                            work = true;
                            var val = state.Value;
                            switch (val)
                            {
                                case 0:
                                    if(force < 970)
                                    {
                                        force += 20;
                                        string mes = Convert.ToString(force);
                                        while (mes.Length < 5)
                                        {
                                            mes =  ' ' + mes;
                                        }
                                        _serialPort.WriteLine('f'+mes);
                                    }
                                    break;
                                case 9000:
                                    force = 0;
                                    _serialPort.WriteLine("f00000\n");
                                    break;
                                case 18000:
                                    if (force >19)
                                    {
                                        force -= 20;
                                        string mes = Convert.ToString(force);
                                        while (mes.Length < 5)
                                        {
                                            mes = ' ' + mes;
                                        }
                                        _serialPort.WriteLine('f'+mes);
                                    }
                                    break;
                                case 27000:
                                    //NOP
                                    break;
                            }
                            
                        }
                        if(work == false)
                        {
                            Thread.Sleep(200);
                        }
                    }
                }
            }
        }
Пример #20
0
        static void Main(string[] args)
        {
            /** BLUETOOTH INIT **/
            // Replace this COM port by the appropriate one on your computer
            SerialPort arduino = new SerialPort("COM7");

            //Open Arduino connection
            while (!arduino.IsOpen)
            {
                Console.WriteLine("Attempting to connect to Arduino (COM 7)...");
                try
                {
                    arduino.Open();
                } catch (Exception)
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            Console.WriteLine("Connected to Arduino!");

            /** CONTROLLER INIT **/
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                                                                  DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                                                                      DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            JoystickControlUpdate joyL = new JoystickControlUpdate();
            JoystickControlUpdate joyR = new JoystickControlUpdate();

            int  direction  = 1; //direction switch
            bool lastYState = false;

            /** EVENT LOOP **/
            while (true)
            {
                try
                {
                    //Poll joystick
                    joystick.Poll();
                    var updates = joystick.GetBufferedData();
                    //JoystickState state = joystick.GetCurrentState();

                    foreach (JoystickUpdate update in updates)
                    {
                        ControllerUpdate result = parseUpdate(update, joyL, joyR, direction);
                        if (result.updateType == ControllerUpdateType.BUTTON)
                        {
                            ButtonUpdate btnUpdate = (ButtonUpdate)result;

                            Console.WriteLine(btnUpdate.ToString());

                            //We have nothing to do with buttons right now

                            if ((btnUpdate.btn == JoystickButtons.Y) && (btnUpdate.pressed == true) && (lastYState == false))
                            {
                                direction = -direction;
                            }
                            if (btnUpdate.btn == JoystickButtons.Y)
                            {
                                lastYState = btnUpdate.pressed;
                            }
                        }
                        else if (result.updateType == ControllerUpdateType.JOYSTICK)
                        {
                            //TODO put everything below in here
                            JoystickControlUpdate joyUpdate = (JoystickControlUpdate)result;

                            //Flush if previous bin is not equal to previous bin
                            bool flush = false;
                            if (joyUpdate.getJoystick() == JoystickType.LEFT)
                            {
                                flush = (joyL.getBinX() != joyUpdate.getBinX()) || (joyL.getBinY() != joyUpdate.getBinY());
                                joyL  = joyUpdate;
                            }
                            if (joyUpdate.getJoystick() == JoystickType.RIGHT)
                            {
                                flush = (joyR.getBinX() != joyUpdate.getBinX()) || (joyR.getBinY() != joyUpdate.getBinY());
                                joyR  = joyUpdate;
                            }

                            try
                            {
                                Console.WriteLine(joyUpdate.ToBinnedString(direction));
                                if (flush)
                                {
                                    arduino.WriteLine(joyUpdate.ToBinnedString(direction));
                                }
                            }
                            catch (Exception)
                            {
                                if (!arduino.IsOpen)
                                {
                                    do
                                    {
                                        Console.WriteLine("Reconnecting to Arduino (COM 7)...");
                                        try
                                        {
                                            arduino.Open();
                                        }
                                        catch (Exception)
                                        {
                                            System.Threading.Thread.Sleep(1000);
                                        }
                                    } while (!arduino.IsOpen);
                                    Console.WriteLine("Connected to Arduino!");
                                }
                                else
                                {
                                    Console.WriteLine("Unknown Bluetooth exception. Restart program.");
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Error reading from joystick.");
                    bool okay = false;
                    while (!okay)
                    {
                        try
                        {
                            joystick.Unacquire();
                            joystick.Acquire();
                            okay = true;
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }
Пример #21
0
        public void controllerPoller()
        {
            var dInput = new DirectInput();
            var guid   = Guid.Empty;

            foreach (var instance in dInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
            {
                var tempGuid     = instance.InstanceGuid;
                var tempJoystick = new Joystick(dInput, tempGuid);
                tempJoystick.Acquire();
                var vendorId    = tempJoystick.Properties.VendorId;
                var productId   = tempJoystick.Properties.ProductId;
                var productName = tempJoystick.Properties.ProductName;
                Console.WriteLine("Found Gamepad: {0} VendorID: {1} ProductID: {2} GUID: {3}", productName, vendorId, productId, tempGuid);
                tempJoystick.Unacquire();
                if (vendorId == 0x054c)
                {
                    if (productId == 0x1000 || productId == 0x0002)
                    {
                        //Found the right device!
                        guid = tempGuid;
                    }
                }
            }

            if (guid == Guid.Empty)
            {
                Console.WriteLine("Didn't find a correct device");
                //Console.ReadKey();
                //Environment.Exit(1);
                //this.Close();
            }
            else
            {
                //Joystick found, now for the meat of the thread.

                var joystick = new Joystick(dInput, guid);
                joystick.Properties.BufferSize = 128;
                joystick.Acquire();
                bool[] buttons    = new bool[20];
                bool[] lastInputs = new bool[20];
                //bool threadRunning = true;

                while (!endThreads)
                {
                    joystick.Poll();
                    var data = joystick.GetBufferedData();
                    foreach (var state in data)
                    {
                        JoystickOffset offset = state.Offset;
                        if (offset.ToString().StartsWith("Buttons"))
                        {
                            StringBuilder builder = new StringBuilder();
                            builder.Append(offset);
                            builder.Replace("Buttons", "");
                            int chosenButton = int.Parse(builder.ToString());
                            if (state.Value == 0x0)
                            {
                                buttons[chosenButton] = false;
                            }
                            else
                            {
                                buttons[chosenButton] = true;
                            }
                        }
                    }

                    for (int i = 0; i < buttons.Length; i++)
                    {
                        if (buttons[i] != lastInputs[i])
                        {
                            lastInputs[i] = buttons[i];
                            if (buttons[i])
                            {
                                //A button was pushed. Now process it correctly.
                                if (i % 5 == 0)
                                {
                                    //buzzer was pushed. Are buzzers locked out?
                                    if (!buzzerLockout)
                                    {
                                        //No, take the lock, light up the buzzers, and light the indicator.
                                        buzzerLockout     = true;
                                        buzzLights[i / 5] = true;
                                        buzzerPlayer      = i / 5;
                                        try
                                        {
                                            this.Dispatcher.Invoke(new Action(delegate()
                                            {
                                                indicators[i].Fill = Brushes.Red;
                                            }));
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine(e.ToString());
                                        }
                                        dispatchGet(false);
                                        if (buzzSoundActive)
                                        {
                                            buzzSound.Play();
                                        }
                                    }
                                }
                                else
                                {
                                    //a choice was pushed. Has this player already locked in?
                                    if (!choiceLockouts[i / 5])
                                    {
                                        //Nope, take the lock and light up the right choice
                                        choiceLockouts[i / 5] = true;

                                        choiceLights[i / 5] = true;

                                        Brush fillBrush = Brushes.White;
                                        if (i % 5 == 1)
                                        {
                                            fillBrush      = Brushes.Goldenrod;
                                            choices[i / 5] = 3;
                                        }
                                        else if (i % 5 == 2)
                                        {
                                            fillBrush      = Brushes.Green;
                                            choices[i / 5] = 2;
                                        }
                                        else if (i % 5 == 3)
                                        {
                                            fillBrush      = Brushes.Orange;
                                            choices[i / 5] = 1;
                                        }
                                        else if (i % 5 == 4)
                                        {
                                            fillBrush      = Brushes.Blue;
                                            choices[i / 5] = 0;
                                        }
                                        try
                                        {
                                            this.Dispatcher.Invoke(new Action(delegate()
                                            {
                                                indicators[i].Fill = fillBrush;
                                            }));
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine(e.ToString());
                                        }
                                        if (choiceSoundActive)
                                        {
                                            choiceSound.Play();
                                        }
                                        if (sendImmediately)
                                        {
                                            dispatchGetSingle(i / 5);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Thread.Sleep(1);
                }
            }
        }
Пример #22
0
        private static void ReceiveData()
        {
            while (true)
            {
                joystick.Poll();
                JoystickUpdate[] datas = null;

                try
                {
                    datas = joystick.GetBufferedData();
                }
                catch
                {
                    break;
                }

                if (datas.Length > 0)
                {
                    switch (datas[0].Offset)
                    {
                    case JoystickOffset.X:
                        NewData.x = datas[0].Value;
                        break;

                    case JoystickOffset.Y:
                        NewData.y = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons0:
                        NewData.button0 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons1:
                        NewData.button1 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons2:
                        NewData.button2 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons3:
                        NewData.button3 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons4:
                        NewData.button4 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons5:
                        NewData.button5 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons6:
                        NewData.button6 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons7:
                        NewData.button7 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons8:
                        NewData.button8 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons9:
                        NewData.button9 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons10:
                        NewData.button10 = datas[0].Value;
                        break;

                    case JoystickOffset.Buttons11:
                        NewData.button11 = datas[0].Value;
                        break;

                    default:
                        break;
                    }

                    Global.gamepadState = NewData;
                }
            }
        }
Пример #23
0
 public JoystickUpdate[] pollJoystick()
 {
     joystick.Poll();
     return(joystick.GetBufferedData());
 }
        private void pollJoystickLoop(Joystick joystick)
        {
            joystick.Properties.BufferSize = 128;
            joystick.Acquire();

            try
            {
                while (true)
                {
                    joystick.Poll();
                    var data = joystick.GetBufferedData();
                    foreach (var state in data)
                    {
                        FireJoystickInputEvent(state);
                    }
                }
            }
            catch(SharpDX.SharpDXException)
            {
                mLogger.Info("Gamepad disconnected");
            }
        }
Пример #25
0
        public void joyStatus()
        {
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                                                                  DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                                                                      DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                MessageBox.Show("");
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            //Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();

            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            //Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            //Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var data = joystick.GetBufferedData();
                //foreach (var state in datas)
                //    Console.WriteLine(state);
                foreach (var state in data)
                {
                    if (state.Offset == JoystickOffset.X)
                    {
                        X = (state.Value / 256);
                    }
                    else if (state.Offset == JoystickOffset.Y)
                    {
                        Y = (state.Value / 256);
                    }
                    else if (state.Offset == JoystickOffset.Z)
                    {
                        Z = (state.Value / 256);
                    }
                    else if (state.Offset == JoystickOffset.RotationZ)
                    {
                        RotZ = (state.Value / 256);
                    }
                }
            }
        }
Пример #26
0
 public JoystickUpdate[] GetBuffer() => joystick.GetBufferedData();
        public async Task StartGameControllerTask()
        {
            var progressHandler = new Progress <GameControllerProgressArgs>(value =>
            {
                if (value.Notification == GameControllerUpdateNotification.JoystickUpdate)
                {
                    ProcessUpdate(value.Update);
                }
                else if (value.Notification == GameControllerUpdateNotification.ConnectedChanged)
                {
                    ControllerConnected = GameControllerService.IsInstanceConnected(_OriginalController.Id);
                }
            });

            var progress = progressHandler as IProgress <GameControllerProgressArgs>;

            _cts = new CancellationTokenSource();
            var token = _cts.Token;

            try
            {
                await Task.Run(() =>
                {
                    System.Diagnostics.Debug.WriteLine("Game Controller Configuration task STARTED.");
                    bool notResponding = false;
                    // Initialize DirectInput
                    using (var directInput = new DirectInput())
                    {
                        while (true)
                        {
                            token.ThrowIfCancellationRequested();
                            try
                            {
                                // Instantiate the joystick
                                using (Joystick joystick = new Joystick(directInput, _OriginalController.Id))
                                {
                                    joystick.Properties.Range      = new InputRange(-500, 500);
                                    joystick.Properties.DeadZone   = 2000;
                                    joystick.Properties.Saturation = 8000;
                                    // Set BufferSize in order to use buffered data.
                                    joystick.Properties.BufferSize = 128;

                                    // If configuring populate the joystick objects.
                                    if (_Controller.JoystickObjects.Count == 0)
                                    {
                                        foreach (DeviceObjectInstance doi in joystick.GetObjects())
                                        {
                                            JoystickOffset offset;
                                            if (GameControllerService.USAGE_OFFSET.TryGetValue(doi.Usage, out offset))
                                            {
                                                if (((int)doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                                                {
                                                    _Controller.JoystickObjects.Add(offset, doi.Name);
                                                }
                                                else if (((int)doi.ObjectId & (int)DeviceObjectTypeFlags.Button) != 0)
                                                {
                                                    _Controller.JoystickObjects.Add(offset, doi.Name);
                                                }
                                                else if (((int)doi.ObjectId & (int)DeviceObjectTypeFlags.PointOfViewController) != 0)
                                                {
                                                    _Controller.JoystickObjects.Add(offset, doi.Name);
                                                }
                                            }
                                        }
                                    }


                                    // Acquire the joystick
                                    joystick.Acquire();


                                    while (true)
                                    {
                                        try
                                        {
                                            token.ThrowIfCancellationRequested();
                                            joystick.Poll();
                                            JoystickUpdate[] datas = joystick.GetBufferedData();
                                            // Check for POV as this needs special handling to take the first value
                                            JoystickUpdate povUpdate = datas.Where(s => s.Offset == JoystickOffset.PointOfViewControllers0).OrderBy(s => s.Sequence).FirstOrDefault();
                                            if (povUpdate.Timestamp > 0)
                                            {
                                                if (progress != null)
                                                {
                                                    progress.Report(new GameControllerProgressArgs(povUpdate));
                                                }
                                            }
                                            else
                                            {
                                                foreach (JoystickUpdate state in datas.Where(s => s.Value != -1)) // Just take the down clicks not the up.
                                                {
                                                    if (progress != null)
                                                    {
                                                        progress.Report(new GameControllerProgressArgs(state));
                                                    }
                                                }
                                            }
                                            if (notResponding)
                                            {
                                                notResponding = false;
                                                progress.Report(new GameControllerProgressArgs());
                                            }
                                        }
                                        catch (SharpDX.SharpDXException)
                                        {
                                            notResponding = true;
                                            progress.Report(new GameControllerProgressArgs());
                                            Thread.Sleep(2000);
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (SharpDX.SharpDXException)
                            {
                                notResponding = true;
                                progress.Report(new GameControllerProgressArgs());
                                Thread.Sleep(2000);
                            }
                        }
                    }
                });
            }
            catch (OperationCanceledException)
            {
                System.Diagnostics.Debug.WriteLine("Game Controller Configuration task CANCELLED.");
            }
        }
Пример #28
0
        public void CaptureJoystick()
        {
            while (true)
            {
                joystick.Poll();

                var data = joystick.GetBufferedData();

                foreach (var state in data)
                {
                    if (state.Offset == JoystickOffset.X)
                    {
                        SetText("" + state.Value, textBoxX);
                    }
                    if (state.Offset == JoystickOffset.Y)
                    {
                        SetText("" + state.Value, textBoxY);
                    }
                    if (state.Offset == JoystickOffset.Z)
                    {
                        SetText("" + state.Value, textBoxZ);
                    }
                    if (state.Offset == JoystickOffset.Buttons0)
                    {
                        checkBox1.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox1.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons1)
                    {
                        checkBox2.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox2.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons2)
                    {
                        checkBox3.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox3.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons3)
                    {
                        checkBox4.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox4.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons4)
                    {
                        checkBox5.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox5.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons5)
                    {
                        checkBox6.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox6.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons6)
                    {
                        checkBox7.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox7.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons7)
                    {
                        checkBox8.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox8.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons8)
                    {
                        checkBox9.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox9.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons9)
                    {
                        checkBox10.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox10.Checked = false;
                        }
                    }
                    if (state.Offset == JoystickOffset.Buttons10)
                    {
                        checkBox11.Checked = true;
                        if (state.Value.Equals(0))
                        {
                            checkBox11.Checked = false;
                        }
                    }
                }
            }
        }
        private void pollJoystick(Guid joystickGuid)
        {
            Joystick joystick;

            // Instantiate the joystick
            joystick = new Joystick(directInput, joystickGuid);
            joystick.Properties.BufferSize = 128;

            Console.WriteLine("Joystick {0}", joystick.Properties.ProductName.ToString());
            Console.WriteLine("GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            // TODO - maybe look into vibration effects on gamepads?
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var data = joystick.GetBufferedData();
                foreach (var state in data)
                {
                    //Null characters in the device name clogs up the write buffer when not run as a Console app. Replace all \0 with empty string to fix this.
                    Console.WriteLine("{0} - {1} - {2}", joystick.Properties.InstanceName.Replace("\0", ""), state.Offset, state.Value);

                    if (state.Offset.ToString().StartsWith("Button"))
                    {

                        buttonPressed(state.Offset, state.Value);
                        Console.WriteLine("Button {0} state changed to {1}", state.Offset, state.Value);

                    }
                    else if (state.Offset.ToString().StartsWith("Point"))
                    {

                        // POV controller
                        povChanged(state.Offset, state.Value);

                    }
                    else
                    {

                        //is an axis
                        int range = 32767; // this is for main joysticks. Might have to change if there are issues
                        axisMoved(state.Offset, state.Value, range);

                    }

                }
            }
        }
Пример #30
0
        static void MainForJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }
            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
            string s = "there is a cat";
            string[] words = s.Split(' ');
            foreach (string word in words)
            {
                Console.WriteLine(word);
            }
            // Poll events from joystick
            var originX = 0;
            var originY = 0;
            var lastStateX = -1;
            var lastStateY = -1;
            var startFlag = false;
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                double theta = 0.0;
                double radius = 0.0;

                foreach (var state in datas)
                {
                    if (state.Sequence == 1)
                    {
                        s = (state.Offset).ToString();
                        if (s == "X")
                            originX = state.Value;
                        else if (s == "Y")
                            originY = state.Value;
                    }
                    s = (state.Offset).ToString();
                    if (s == "X")
                        lastStateX = state.Value;
                    else if (s == "Y")
                        lastStateY = state.Value;
                    startFlag = true;
                }
                if (startFlag && datas.Length == 0 && lastStateX != -1 && lastStateY != -1)
                {
                    var slope = 0.0;
                    if ((lastStateX - originX) == 0)
                        slope = Math.PI / 2;
                    else
                        slope = (lastStateY - originY) / (lastStateX - originX);
                    theta = Math.Atan(slope);
                    radius = Math.Sqrt(Math.Pow(originX - lastStateX, 2) + Math.Pow(originY - lastStateY, 2));
                    originX = lastStateX;
                    originY = lastStateY;
                    Console.WriteLine(theta);
                    Console.WriteLine(radius);
                    startFlag = false;
                }
            }
        }
        static void Main(string[] args)
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid  = Guid.Empty;
            var joystickGuid2 = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Driving,
                                                                  DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid2 == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Other,
                                                                      DeviceEnumerationFlags.AllDevices))
                {
                    //joystickGuid2 = deviceInstance.InstanceGuid;
                    //deviceInstance.GetType;
                    if (deviceInstance.ProductName == "HTC Vive")
                    {
                        Console.WriteLine("YES");
                        joystickGuid2 = deviceInstance.InstanceGuid;
                    }
                    Console.WriteLine(deviceInstance.ProductName);
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid2 == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            //byte[] array = joystickGuid2.ToByteArray();

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();

            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            byte[] array;

            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    Console.WriteLine(state.X + " " + state.Y + " " + state.RotationZ);
                    //Console.WriteLine("TIRA DE BYTES: ");
                    array = joystickGuid2.ToByteArray();
                    String arrayString = "";
                    for (int i = 0; i < array.Length; i++)
                    {
                        arrayString += array[i];
                        arrayString += " ";
                    }
                    //Console.WriteLine(arrayString);
                }
            }
        }
Пример #32
0
        static void Main(string[] args)
        {
            if (client == null)
            {
                // create client instance
                client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

                string clientId = Guid.NewGuid().ToString();
                client.Connect(clientId, "guest", "guest");

                SubscribeMessage();
            }
            // Initialize DirectInput

            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
            const int stop = 32511;
            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.Offset.ToString() == "X" && state.Value > stop)
                    {
                        MoveRobot("MOVE", "R");
                        Console.WriteLine("Kanan");
                    }
                    else if(state.Offset.ToString() == "X" && state.Value < stop)
                    {
                        MoveRobot("MOVE", "L");

                        Console.WriteLine("Kiri");
                    }
                    else if (state.Offset.ToString() == "Y" && state.Value < stop)
                    {
                        MoveRobot("MOVE", "F");

                        Console.WriteLine("Maju");
                    }
                    else if (state.Offset.ToString() == "Y" && state.Value > stop)
                    {
                        MoveRobot("MOVE", "B");

                        Console.WriteLine("Mundur");
                    }
                    else
                    {
                        MoveRobot("MOVE", "S");

                        Console.WriteLine("Stop");
                    }

                }

            }
        }
    static void Main()
    {
        // Initialize DirectInput
        var directInput = new DirectInput();

        // Find a Joystick Guid
        var joystickGuid = Guid.Empty;

        foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                                                              DeviceEnumerationFlags.AllDevices))
        {
            joystickGuid = deviceInstance.InstanceGuid;
        }

        // If Gamepad not found, look for a Joystick
        if (joystickGuid == Guid.Empty)
        {
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                                                                  DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }
        }

        // If Joystick not found, throws an error
        if (joystickGuid == Guid.Empty)
        {
            Console.WriteLine("No joystick/Gamepad found.");
            Console.ReadKey();
            Environment.Exit(1);
        }

        // Instantiate the joystick
        var joystick = new Joystick(directInput, joystickGuid);

        Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

        // Query all suported ForceFeedback effects
        var allEffects = joystick.GetEffects();

        foreach (var effectInfo in allEffects)
        {
            Console.WriteLine("Effect available {0}", effectInfo.Name);
        }

        // Set BufferSize in order to use buffered data.
        joystick.Properties.BufferSize = 128;

        // Acquire the joystick
        joystick.Acquire();

        // Poll events from joystick
        while (true)
        {
            joystick.Poll();
            var datas = joystick.GetBufferedData();
            foreach (var state in datas)
            {
                Console.WriteLine(state);
            }
        }
    }
Пример #34
0
        static void Main(string[] args)
        {
            string         name;
            string         message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread         readThread     = new Thread(Read);

            // Create a new SerialPort object with default settings.
            _serialPort = new SerialPort();

            // Allow the user to set the appropriate properties.
            _serialPort.PortName  = "COM8";      //SetPortName(_serialPort.PortName);
            _serialPort.BaudRate  = 9600;        //SetPortBaudRate(_serialPort.BaudRate);
            _serialPort.Parity    = SetPortParity(_serialPort.Parity);
            _serialPort.DataBits  = 8;           //SetPortDataBits(_serialPort.DataBits);
            _serialPort.StopBits  = (StopBits)1; //SetPortStopBits(_serialPort.StopBits);
            _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

            // Set the read/write timeouts
            _serialPort.ReadTimeout  = 500;
            _serialPort.WriteTimeout = 500;

            _serialPort.Open();
            _continue = true;
            readThread.Start(); s

            /*Console.Write("Name: ");
             * name = Console.ReadLine();
             *
             * Console.WriteLine("Type QUIT to exit");
             */
            Console.WriteLine("Please Wait");

            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                                                                  DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                                                                      DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();

            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            while (_continue)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    String temp   = "";
                    String offset = state.Offset.ToString();
                    int    value  = state.Value;

                    if (offset == "Y")
                    {
                        temp = "[L" + value + "]\r\n";
                    }
                    else if (offset == "RotationY")
                    {
                        temp = "[R" + value + "]\r\n";
                    }

                    else if (offset == "Buttons0" && value == 128)
                    {
                        temp = "X\r\n";
                    }
                    else if (offset == "Buttons0" && value == 0)
                    {
                        temp = "x\r\n";
                    }

                    else if (offset == "Buttons1" && value == 128)
                    {
                        temp = "C\r\n";
                    }
                    else if (offset == "Buttons1" && value == 0)
                    {
                        temp = "c\r\n";
                    }

                    else if (offset == "Buttons2" && value == 128)
                    {
                        temp = "S\r\n";
                    }
                    else if (offset == "Buttons2" && value == 0)
                    {
                        temp = "s\r\n";
                    }

                    else if (offset == "Buttons3" && value == 128)
                    {
                        temp = "T\r\n";
                    }
                    else if (offset == "Buttons3" && value == 0)
                    {
                        temp = "t\r\n";
                    }

                    Console.Write(temp);
                    _serialPort.WriteLine(temp);
                }
            }
            readThread.Join();
            _serialPort.Close();
        }
Пример #35
0
        public void DoProcessing(IProgress <string> message, IProgress <string> xUpdate, IProgress <string> rawXUpdate, IProgress <string> yUpdate, IProgress <string> rawYUpdate, Joystick joystick, Keyboard keyboard, CancellationToken cancellationToken)
        {
            ViGEmClient               client            = new ViGEmClient();
            Xbox360Controller         controller        = new Xbox360Controller(client);
            ControllerBindingsStorage bindingStorage    = new ControllerBindingsStorage();
            Dictionary <int, int>     bindings          = bindingStorage.load();
            Xbox360Axes?              analogStickAxisX  = null;
            Xbox360Axes?              analogStickAxisY  = null;
            Xbox360Axes?              digitalStickAxisX = null;
            Xbox360Axes?              digitalStickAxisY = null;
            Xbox360Buttons?           joystickButton0   = null;
            bool leftTriggerLastPressed       = false;
            bool leftTriggerPressed           = false;
            bool rightTriggerLastPressed      = false;
            bool rightTriggerPressed          = false;
            bool digitalStickUpLastPressed    = false;
            bool digitalStickUpPressed        = false;
            bool digitalStickDownLastPressed  = false;
            bool digitalStickDownPressed      = false;
            bool digitalStickLeftLastPressed  = false;
            bool digitalStickLeftPressed      = false;
            bool digitalStickRightLastPressed = false;
            bool digitalStickRightPressed     = false;

            foreach (KeyValuePair <int, int> binding in bindings)
            {
                if (binding.Key == (int)Xbox360StorageButtons.AnalogStick)
                {
                    AnalogStickBinding analogStickBinding = (AnalogStickBinding)Enum.Parse(typeof(AnalogStickBinding), binding.Value.ToString());

                    switch (analogStickBinding)
                    {
                    case AnalogStickBinding.LeftStick:
                        analogStickAxisX  = Xbox360Axes.LeftThumbX;
                        analogStickAxisY  = Xbox360Axes.LeftThumbY;
                        digitalStickAxisX = Xbox360Axes.RightThumbX;
                        digitalStickAxisY = Xbox360Axes.RightThumbY;

                        break;

                    case AnalogStickBinding.RightStick:
                        analogStickAxisX  = Xbox360Axes.RightThumbX;
                        analogStickAxisY  = Xbox360Axes.RightThumbY;
                        digitalStickAxisX = Xbox360Axes.LeftThumbX;
                        digitalStickAxisY = Xbox360Axes.LeftThumbY;

                        break;
                    }
                }

                if (binding.Value == (int)Key.JoystickButton)
                {
                    joystickButton0 = (Xbox360Buttons)Enum.Parse(typeof(Xbox360Buttons), binding.Key.ToString());
                }
            }

            controller.Connect();
            message.Report("Virtual Xbox 360 controller created!");

            Xbox360Report report = new Xbox360Report();

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    controller.Disconnect();
                    return;
                }

                joystick.Poll();

                JoystickUpdate[] updates = joystick.GetBufferedData();

                foreach (JoystickUpdate update in updates)
                {
                    int value = (update.Value - 32767);

                    if (update.Offset == JoystickOffset.X || update.Offset == JoystickOffset.Y || update.Offset == JoystickOffset.Buttons0)
                    {
                        if (analogStickAxisX != null && analogStickAxisX.HasValue && analogStickAxisY != null && analogStickAxisY.HasValue)
                        {
                            if (update.Offset == JoystickOffset.X)
                            {
                                short x = getConstrainedValue(value);

                                report.SetAxis(analogStickAxisX.Value, x);
                                xUpdate.Report(x.ToString());
                                rawXUpdate.Report((update.Value - 32767).ToString());
                            }

                            if (update.Offset == JoystickOffset.Y)
                            {
                                short y = getConstrainedValue(value * -1);

                                report.SetAxis(analogStickAxisY.Value, y);
                                yUpdate.Report(y.ToString());
                                rawYUpdate.Report(((update.Value - 32767) * -1).ToString());
                            }
                        }

                        if (update.Offset == JoystickOffset.Buttons0 && joystickButton0 != null && joystickButton0.HasValue)
                        {
                            bool buttonValue = update.Value > 0 ? true : false;

                            report.SetButtonState(joystickButton0.Value, buttonValue);
                        }
                    }

                    message.Report(update.Offset.ToString() + ": " + value.ToString());
                }

                keyboard.Poll();

                KeyboardUpdate[] keyboardUpdates = keyboard.GetBufferedData();

                foreach (KeyboardUpdate keyboardUpdate in keyboardUpdates)
                {
                    foreach (KeyValuePair <int, int> binding in bindings)
                    {
                        if ((int)keyboardUpdate.Key == binding.Value)
                        {
                            Xbox360Buttons?button = null;

                            switch (binding.Key)
                            {
                            case (int)Xbox360StorageButtons.Guide:
                                button = Xbox360Buttons.Guide;
                                break;

                            case (int)Xbox360StorageButtons.Start:
                                button = Xbox360Buttons.Start;
                                break;

                            case (int)Xbox360StorageButtons.Back:
                                button = Xbox360Buttons.Back;
                                break;

                            case (int)Xbox360StorageButtons.LeftShoulder:
                                button = Xbox360Buttons.LeftShoulder;
                                break;

                            case (int)Xbox360StorageButtons.RightShoulder:
                                button = Xbox360Buttons.RightShoulder;
                                break;

                            case (int)Xbox360StorageButtons.LeftTrigger:
                                leftTriggerPressed = keyboardUpdate.Value == 128 ? true : false;
                                break;

                            case (int)Xbox360StorageButtons.RightTrigger:
                                rightTriggerPressed = keyboardUpdate.Value == 128 ? true : false;
                                break;

                            case (int)Xbox360StorageButtons.A:
                                button = Xbox360Buttons.A;
                                break;

                            case (int)Xbox360StorageButtons.B:
                                button = Xbox360Buttons.B;
                                break;

                            case (int)Xbox360StorageButtons.X:
                                button = Xbox360Buttons.X;
                                break;

                            case (int)Xbox360StorageButtons.Y:
                                button = Xbox360Buttons.Y;
                                break;

                            case (int)Xbox360StorageButtons.Up:
                                button = Xbox360Buttons.Up;
                                break;

                            case (int)Xbox360StorageButtons.Down:
                                button = Xbox360Buttons.Down;
                                break;

                            case (int)Xbox360StorageButtons.Left:
                                button = Xbox360Buttons.Left;
                                break;

                            case (int)Xbox360StorageButtons.Right:
                                button = Xbox360Buttons.Right;
                                break;

                            case (int)Xbox360StorageButtons.LeftThumb:
                                button = Xbox360Buttons.LeftThumb;
                                break;

                            case (int)Xbox360StorageButtons.RightThumb:
                                button = Xbox360Buttons.RightThumb;
                                break;

                            case (int)Xbox360StorageButtons.DigitalStickUp:
                                digitalStickUpPressed = keyboardUpdate.Value == 128 ? true : false;
                                break;

                            case (int)Xbox360StorageButtons.DigitalStickDown:
                                digitalStickDownPressed = keyboardUpdate.Value == 128 ? true : false;
                                break;

                            case (int)Xbox360StorageButtons.DigitalStickLeft:
                                digitalStickLeftPressed = keyboardUpdate.Value == 128 ? true : false;
                                break;

                            case (int)Xbox360StorageButtons.DigitalStickRight:
                                digitalStickRightPressed = keyboardUpdate.Value == 128 ? true : false;
                                break;
                            }

                            if (button != null && button.HasValue)
                            {
                                bool pressed = keyboardUpdate.Value == 128 ? true : false;

                                report.SetButtonState(button.Value, pressed);
                            }

                            message.Report("Keyboard - Key: " + keyboardUpdate.Key + " Value: " + keyboardUpdate.Value);
                        }
                    }
                }

                if (leftTriggerPressed != leftTriggerLastPressed)
                {
                    if (leftTriggerPressed)
                    {
                        report.LeftTrigger = 255;
                    }
                    else
                    {
                        report.LeftTrigger = 0;
                    }

                    leftTriggerLastPressed = leftTriggerPressed;
                }

                if (rightTriggerPressed != rightTriggerLastPressed)
                {
                    if (rightTriggerPressed)
                    {
                        report.RightTrigger = 255;
                    }
                    else
                    {
                        report.RightTrigger = 0;
                    }

                    rightTriggerLastPressed = rightTriggerPressed;
                }

                if (digitalStickUpPressed != digitalStickUpLastPressed)
                {
                    if (digitalStickUpPressed)
                    {
                        report.SetAxis(digitalStickAxisY.Value, 32767);
                    }
                    else
                    {
                        report.SetAxis(digitalStickAxisY.Value, 0);
                    }

                    digitalStickUpLastPressed = digitalStickUpPressed;
                }

                if (digitalStickDownPressed != digitalStickDownLastPressed)
                {
                    if (digitalStickDownPressed)
                    {
                        report.SetAxis(digitalStickAxisY.Value, -32768);
                    }
                    else
                    {
                        report.SetAxis(digitalStickAxisY.Value, 0);
                    }

                    digitalStickDownLastPressed = digitalStickDownPressed;
                }

                if (digitalStickLeftPressed != digitalStickLeftLastPressed)
                {
                    if (digitalStickLeftPressed)
                    {
                        report.SetAxis(digitalStickAxisX.Value, -32768);
                    }
                    else
                    {
                        report.SetAxis(digitalStickAxisX.Value, 0);
                    }

                    digitalStickLeftLastPressed = digitalStickLeftPressed;
                }

                if (digitalStickRightPressed != digitalStickRightLastPressed)
                {
                    if (digitalStickRightPressed)
                    {
                        report.SetAxis(digitalStickAxisX.Value, 32767);
                    }
                    else
                    {
                        report.SetAxis(digitalStickAxisX.Value, 0);
                    }

                    digitalStickRightLastPressed = digitalStickRightPressed;
                }

                controller.SendReport(report);
                Thread.Sleep(1);
            }
        }
Пример #36
0
        public void PollJoystick()
        {
            while (!_QuitPolling)
            {
                if (!directInput.IsDeviceAttached(joystick.Information.InstanceGuid))
                {
                    MessageBox.Show("Потеряна связь с джойстиком", "Джойстик", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }

                joystick.Poll();
                JoystickUpdate[] datas = joystick.GetBufferedData();
                JoystickButtonPressedEventArgs args    = new JoystickButtonPressedEventArgs();
                JoystickPacket_CAEventArgs     argc_CA = new JoystickPacket_CAEventArgs();
                foreach (JoystickUpdate state in datas)
                {
                    skip_data = false;
                    switch (state.Offset)
                    {
                    case JoystickOffset.RotationX:

                        args.Value = state.Value;
                        OnJoystickRotationXchange(args);
                        break;

                    case JoystickOffset.RotationY:
                        args.Value = state.Value;
                        OnJoystickRotationYchange(args);
                        break;

                    case JoystickOffset.X:
                        packet_CA.axis_X = (byte)(state.Value / 256);
                        args.Value       = state.Value;
                        OnJoystickXchange(args);
                        break;

                    case JoystickOffset.Y:
                        packet_CA.axis_Y = (byte)(state.Value / 256);
                        args.Value       = state.Value;
                        OnJoystickYchange(args);
                        break;

                    case JoystickOffset.Sliders0:
                        packet_CA.axis_Z = (byte)(state.Value / 256);
                        args.Value       = state.Value;
                        OnJoystickZchange(args);
                        break;

                    case JoystickOffset.Buttons0:
                        packet_CA.button1 = (state.Value > 0) ? (byte)1 : (byte)0;
                        break;

                    default:
                        skip_data = true;
                        break;
                    }
                }
                if (datas.Length > 0 && !skip_data)
                {
                    argc_CA.packet_CA = packet_CA;
                    OnPacket_CA_change(argc_CA);
                }


                Thread.Sleep(10);
            }
        }
Пример #37
0
        static void MainForJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();

            foreach (var effectInfo in allEffects)
            {
                Console.WriteLine("Effect available {0}", effectInfo.Name);
            }

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick

            int axisCoef = 512;

            byte[] message = new byte[3];
            byte   XPin    = 63;
            byte   YPin    = 63;
            byte   ZPin    = 0;

            message[0] = XPin;
            message[1] = YPin;
            message[2] = ZPin;

            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                //if (Server.CurrentConnections > 0)
                //{
                foreach (var state in datas)
                {
                    //Console.WriteLine(state);
                    if (state.Offset.Equals(JoystickOffset.X))
                    {
                        if (state.Value >= JoystickConf.Min && state.Value < JoystickConf.Center - JoystickConf.Deadzone)
                        {
                            // LEFT
                            XPin = (byte)((JoystickConf.Max - state.Value) / axisCoef);
                        }
                        else if (state.Value > JoystickConf.Center + JoystickConf.Deadzone)
                        {
                            // RIGHT
                            XPin = (byte)((JoystickConf.Max - state.Value) / axisCoef);
                        }
                    }
                    else if (state.Offset.Equals(JoystickOffset.Y))
                    {
                        if (state.Value >= JoystickConf.Min && state.Value < JoystickConf.Center - JoystickConf.Deadzone)
                        {
                            // UP
                            YPin = (byte)(state.Value / axisCoef);
                        }
                        else if (state.Value > JoystickConf.Center + JoystickConf.Deadzone)
                        {
                            // DOWN
                            YPin = (byte)(state.Value / axisCoef);
                        }
                    }
                    else if (state.Offset.Equals(JoystickOffset.Z))
                    {
                        // THROTTLE
                        ZPin = Convert.ToByte((JoystickConf.Max - state.Value) / axisCoef);
                    }
                }
                if (message[0] != XPin || message[1] != YPin || message[2] != ZPin || ZPin == 127)
                {
                    if (ZPin > 115)
                    {
                        ZPin = 127;
                    }
                    if (ZPin == 1)
                    {
                        ZPin = 0;
                    }
                    if (XPin == 64 || XPin == 65)
                    {
                        XPin = 63;
                    }
                    if (YPin == 64 || YPin == 65)
                    {
                        YPin = 63;
                    }
                    message[0] = XPin;
                    message[1] = YPin;
                    message[2] = ZPin;
                    Server.SendToAll(message);
                    //Thread.Sleep(60);
                    Console.WriteLine(message[0] + " " + message[1] + " " + message[2]);
                }
            }

            //}
        }
Пример #38
0
        private void joystickManagerThreadStart()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            foreach (var deviceInstance in directInput.GetDevices())
            {
                if (deviceInstance.InstanceName.Contains("X52 Pro"))
                {
                    Console.WriteLine(deviceInstance.InstanceName+", "+deviceInstance.InstanceGuid);
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }
            // Instantiate the joystick
            joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.Offset == JoystickOffset.Y)
                    {
                        Y_Axis = (state.Value - (Y_MAX_VAL / 2.0)) / (Y_MAX_VAL / 2.0);
                        if (Math.Abs(Y_Axis) <= 0.025)
                            Y_Axis = 0;
                        if (Y_INVERT)
                            Y_Axis *= -1;
                    }

                    if (state.Offset == JoystickOffset.X)
                    {
                        X_Axis = (state.Value - (X_MAX_VAL / 2.0)) / (X_MAX_VAL / 2.0);
                        if (Math.Abs(X_Axis) <= DEAD_ZONE)
                            X_Axis = 0;
                        if (X_INVERT)
                            X_Axis *= -1;
                    }

                    if(state.Offset == JoystickOffset.Z)
                    {
                        throttle = (state.Value) / ((double)X_MAX_VAL);
                        if (THROTTLE_INVERT)
                            throttle = (1 - throttle);
                    }

                    if(state.Offset == JoystickOffset.Buttons0)
                    {
                        if (state.Value == 128)
                            fire = true;
                        else
                            fire = false;
                    }
                }
            }
        }