Ejemplo n.º 1
0
		public devices.IDevice ResolveDevice (IHIDDevice hidDevice)
		{
			int i = 0;

			int inx;

			//Give Unity Update(Input works only in Update on Main single thread
			//and this funciton is happen on Event on other thread)
			//to be done so GetJoysticksNames return something
			//!!! Not tested yet on WIN
			System.Threading.Thread.Sleep (300);//sleep this Event add device thread
                    
			//find device match based on "names"
			string[] names = Input.GetJoystickNames ();
			inx = Array.IndexOf (names, hidDevice.Name);


			Debug.Log (String.Join (",", names));

			if (inx < 0)
				return null;

			if (inx > 3) {
				Debug.LogWarning ("Unity supports up to 4 Joysticks");
				return null;
			}

			DeviceProfile profile = hidDevice.loadProfile ();

					
                           
                        

			JoystickDevice device = new JoystickDevice (inx, hidDevice.PID, hidDevice.VID, hidDevice.ID, 12, 20, this);
			device.Name = hidDevice.Name;
			device.profile = profile;

			int numAxis = device.Axis.Count;
			int numButtons = device.Buttons.Count;

			for (; i < numAxis; i++) {
				device.Axis [i] = new AxisDetails ();
				if (profile != null && profile.axisNaming.Length > i) {
					device.Axis [i].name = profile.axisNaming [i];

				}
                
			}

			for (i=0; i < numButtons; i++) {
				device.Buttons [i] = new ButtonDetails ();
				if (profile != null && profile.buttonNaming.Length > i) {
					device.Buttons [i].name = profile.buttonNaming [i];
				}
			}
				
				

			return device;
		}
Ejemplo n.º 2
0
        public IDevice ResolveDevice(IHIDDevice info)
        {

            GenericHIDDevice genericDevice = (GenericHIDDevice)info;

            _hidInterface = info.hidInterface;

           

            JoystickDevice joystick;

            int numAxes = genericDevice.numAxes; //info.Extension.axes;
            int numButtons = genericDevice.numButtons; //info.Extension.buttons;

         
              joystick = new JoystickDevice(info.index, info.PID, info.VID,info.ID, Math.Max(8,numAxes),numButtons, this);
              joystick.Name = info.Name;

                    

                    int index = 0;

                    for (; index < numButtons; index++)
                    {
                        joystick.Buttons[index] = new ButtonDetails();
                    }

             
                    for (index = 0; index < numAxes; index++)
                    {
                                             
                          joystick.Axis[index] = new AxisDetails();
                       
                    }

                    //joystick.numPOV = 1;
               



                   // joystick.Axis[index - 1].isHat = true;
                   //joystick.Axis[index - 2].isHat = true;

                    return joystick;

        }
Ejemplo n.º 3
0
        void CloseJoystick(int player_index)
        {
            lock (sync)
            {
                if (IsValid(player_index))
                {
                    int device_index = player_to_index[player_index];

                    JoystickDevice <WinMMJoyDetails> stick =
                        sticks[index_to_stick[device_index]] as JoystickDevice <WinMMJoyDetails>;

                    if (stick != null)
                    {
                        index_to_stick.Remove(device_index);
                        player_to_index.Remove(player_index);
                    }
                }
            }
        }
    void OnJoystickConnect(int index)
    {
        IntPtr joystick = SDL.SDL_JoystickOpen(index);

        if (joystick != IntPtr.Zero)
        {
            Debug.Log("Added joystick device " + index);

            JoystickDevice gamepad = new JoystickDevice(joystick);
            joysticks.Add(gamepad);
            devices.Add(gamepad);

            Debug.Log("Joystick count = " + joysticks.Count);
            Debug.Log("Device count = " + devices.Count);
        }
        else
        {
            Debug.LogError("Failed to get SDL Joystick address " + index + ". " + SDL.SDL_GetError());
        }
    }
Ejemplo n.º 5
0
        public IDevice ResolveDevice(IHIDDevice info)
        {
            GenericHIDDevice genericDevice = (GenericHIDDevice)info;

            _hidInterface = info.hidInterface;



            JoystickDevice joystick;

            int numAxes    = genericDevice.numAxes;    //info.Extension.axes;
            int numButtons = genericDevice.numButtons; //info.Extension.buttons;


            joystick      = new JoystickDevice(info.index, info.PID, info.VID, info.ID, Math.Max(8, numAxes), numButtons, this);
            joystick.Name = info.Name;



            int index = 0;

            for (; index < numButtons; index++)
            {
                joystick.Buttons[index] = new ButtonDetails();
            }


            for (index = 0; index < numAxes; index++)
            {
                joystick.Axis[index] = new AxisDetails();
            }

            //joystick.numPOV = 1;



            // joystick.Axis[index - 1].isHat = true;
            //joystick.Axis[index - 2].isHat = true;

            return(joystick);
        }
        public static string GetDeviceName(object nativeDevice)
        {
            JoystickDevice jsDevice       = (JoystickDevice)nativeDevice;
            string         rawDescription = jsDevice.Description;

            if (rawDescription == null)
            {
                rawDescription = GetDeviceButtonCount(jsDevice) + " Buttons/" + GetDeviceAxis1dCount(jsDevice) + " Axes";
            }
            int ignoreThrough = rawDescription.IndexOf('#');

            if (ignoreThrough != -1)
            {
                string newDescription = rawDescription.Substring(ignoreThrough + 2).Trim();
                if (newDescription.Length != 0)
                {
                    rawDescription = "Joystick " + newDescription;
                }
            }
            return(rawDescription);
        }
Ejemplo n.º 7
0
        private void refreshDevices()
        {
            var newDevices = new List <JoystickDevice>();

            // Update devices and add them to newDevices if still connected
            foreach (var dev in devices)
            {
                dev.Refresh();

                if (dev.RawState.IsConnected)
                {
                    newDevices.Add(dev);
                }
                else
                {
                    mostSeenDevices--;
                    if (dev.LastState != null)
                    {
                        handleState(dev, new JoystickState());
                    }
                }
            }

            // Find any newly-connected devices
            while (true)
            {
                var newDevice = new JoystickDevice(mostSeenDevices);
                if (!newDevice.Capabilities.IsConnected)
                {
                    break;
                }

                Logger.Log($"Connected joystick device: {newDevice.Guid}");

                newDevices.Add(newDevice);
                mostSeenDevices++;
            }

            devices = newDevices;
        }
Ejemplo n.º 8
0
            public OpenTKJoystickState(JoystickDevice device)
            {
                // Populate axes
                var axes = new List <JoystickAxis>();

                for (int i = 0; i < JoystickDevice.MAX_AXES; i++)
                {
                    var value = device.RawState.GetAxis(i);
                    if (!Precision.AlmostEquals(value, 0, device.DefaultDeadzones?[i] ?? Precision.FLOAT_EPSILON))
                    {
                        axes.Add(new JoystickAxis(i, value));
                    }
                }

                Axes = axes;

                // Populate normal buttons
                for (int i = 0; i < JoystickDevice.MAX_BUTTONS; i++)
                {
                    if (device.RawState.GetButton(i) == ButtonState.Pressed)
                    {
                        Buttons.SetPressed(JoystickButton.FirstButton + i, true);
                    }
                }

                // Populate hat buttons
                for (int i = 0; i < JoystickDevice.MAX_HATS; i++)
                {
                    foreach (var hatButton in getHatButtons(device, i))
                    {
                        Buttons.SetPressed(hatButton, true);
                    }
                }

                // Populate axis buttons (each axis has two buttons)
                foreach (var axis in Axes)
                {
                    Buttons.SetPressed((axis.Value < 0 ? JoystickButton.FirstAxisNegative : JoystickButton.FirstAxisPositive) + axis.Axis, true);
                }
            }
Ejemplo n.º 9
0
        public void Initialize()
        {
            joystick = new JoystickDevice();
            joystick.Initialize("/dev/input/js0");
            joystick.InputReceived +=
                (sender, e) =>
            {
                //LastCommand = new Vector2D(e.Axis[(int)0], e.Axis[(int)1]);

                if (CommandReceived != null)
                {
                    CommandReceived(this, new CommandEventArgs {
                        Command = LastCommand
                    });
                }
            };

            new Thread(() =>
            {
                joystick.ProcessEvents();
            }).Start();
        }
Ejemplo n.º 10
0
 public void ProcessJoystickEvent(JoyHatEvent ev)
 {
     int id = ev.Which;
     if (IsJoystickInstanceValid(id))
     {
         int index = sdl_instanceid_to_joysticks[id];
         JoystickDevice<Sdl2JoystickDetails> joystick = (JoystickDevice<Sdl2JoystickDetails>)joysticks[index];
         if (ev.Hat >= 0 && ev.Hat < JoystickState.MaxHats)
         {
             joystick.Details.Hat[ev.Hat] = new JoystickHatState(TranslateHat(ev.Value));
         }
         else
         {
             Debug.Print("[SDL2] Hat {0} out of range [0, {1}]", ev.Hat, JoystickState.MaxHats);
         }
         joystick.Details.PacketNumber = Math.Max(0, unchecked(joystick.Details.PacketNumber + 1));
     }
     else
     {
         Debug.Print("[SDL2] Invalid joystick id {0} in {1}", id, ev.Type);
     }
 }
Ejemplo n.º 11
0
        JoystickDevice <X11JoyDetails> OpenJoystick(string base_path, int number)
        {
            string path = base_path + number.ToString();
            JoystickDevice <X11JoyDetails> stick = null;
            int fd = -1;

            try
            {
                fd = UnsafeNativeMethods.open(path, OpenFlags.NonBlock);
                if (fd == -1)
                {
                    return(null);
                }
                // Check joystick driver version (must be 1.0+)
                int driver_version = 0x00000800;
                UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Version, ref driver_version);
                if (driver_version < 0x00010000)
                {
                    return(null);
                }
                // Get number of joystick axes
                int axes = 0;
                UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Axes, ref axes);
                // Get number of joystick buttons
                int buttons = 0;
                UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Buttons, ref buttons);
                stick = new JoystickDevice <X11JoyDetails>(fd, axes, buttons);
                Debug.Print("Found joystick on path {0}", path);
            }
            finally
            {
                if (stick == null && fd != -1)
                {
                    UnsafeNativeMethods.close(fd);
                }
            }

            return(stick);
        }
Ejemplo n.º 12
0
            private IEnumerable <JoystickButton> getHatButtons(JoystickDevice device, int hat)
            {
                var state = device.State.GetHat(JoystickHat.Hat0 + hat);

                if (state.IsUp)
                {
                    yield return(JoystickButton.FirstHatUp + hat);
                }
                else if (state.IsDown)
                {
                    yield return(JoystickButton.FirstHatDown + hat);
                }

                if (state.IsLeft)
                {
                    yield return(JoystickButton.FirstHatLeft + hat);
                }
                else if (state.IsRight)
                {
                    yield return(JoystickButton.FirstHatRight + hat);
                }
            }
Ejemplo n.º 13
0
        // BE CAREFUL!  RUNS ON A SEPARATE THREAD!
        public NodeDriver ReadConfiguration()
        {
            var driver = NodeDriver.BuildWith(
                new FieldGuid(SnapDriver.GAMECONTROLLERS_DRIVER_ID), // TypeId
                new FieldString(string.Empty),                       // Address
                new FieldBase64(string.Empty),                       // Configuration
                new FieldString(Resources.Strings.DriverName));      // DriverName

            driver = driver.SetRunning(new FieldBool(Running));      // status only
            if (Running && this.directInput != null)                 // Running property is threadsafe
            {
                var devicesMutable  = new Collection <NodeDevice>();
                var joystickDevices = getJoystickCompatibleDevices();
                foreach (var joystickDevice in joystickDevices)
                {
                    var dev = JoystickDevice.StaticBuild(this.directInput, joystickDevice);
                    devicesMutable.Add(dev);
                }
                driver = driver.NodeDeviceChildren.Append(
                    new ReadOnlyCollection <NodeDevice>(devicesMutable));
            }
            return(driver);
        }
Ejemplo n.º 14
0
        void CloseJoystick(JoystickDevice <X11JoyDetails> js)
        {
            UnsafeNativeMethods.close(js.Details.FileDescriptor);
            js.Details.State          = new JoystickState(); // clear joystick state
            js.Details.FileDescriptor = -1;

            // find and remove the joystick index from index_to_stick
            int key = -1;

            foreach (int i in index_to_stick.Keys)
            {
                if (sticks[index_to_stick[i]] == js)
                {
                    key = i;
                    break;
                }
            }

            if (index_to_stick.ContainsKey(key))
            {
                index_to_stick.Remove(key);
            }
        }
Ejemplo n.º 15
0
        private JoystickDevice <Sdl2JoystickDetails> OpenJoystick(int id)
        {
            JoystickDevice <Sdl2JoystickDetails> joystick = null;
            int num_axes    = 0;
            int num_buttons = 0;
            int num_hats    = 0;
            int num_balls   = 0;

            IntPtr handle = SDL.JoystickOpen(id);

            if (handle != IntPtr.Zero)
            {
                num_axes    = SDL.JoystickNumAxes(handle);
                num_buttons = SDL.JoystickNumButtons(handle);
                num_hats    = SDL.JoystickNumHats(handle);
                num_balls   = SDL.JoystickNumBalls(handle);

                joystick                    = new JoystickDevice <Sdl2JoystickDetails>(id, num_axes, num_buttons);
                joystick.Description        = SDL.JoystickName(handle);
                joystick.Details.Handle     = handle;
                joystick.Details.InstanceId = SDL.JoystickInstanceID(handle);
                joystick.Details.Guid       = SDL.JoystickGetGUID(handle).ToGuid();
                joystick.Details.HatCount   = num_hats;
                joystick.Details.BallCount  = num_balls;

                Debug.Print("[SDL2] Joystick device {0} opened successfully. ", id);
                Debug.Print("\t\t'{0}' has {1} axes, {2} buttons, {3} hats, {4} balls",
                            joystick.Description, joystick.Axis.Count, joystick.Button.Count,
                            joystick.Details.HatCount, joystick.Details.BallCount);
            }
            else
            {
                Debug.Print("[SDL2] Failed to open joystick device {0}", id);
            }

            return(joystick);
        }
Ejemplo n.º 16
0
        private void refreshDevices()
        {
            // Update devices and add them to newDevices if still connected
            for (int i = 0; i < devices.Count; i++)
            {
                var dev = devices[i];

                dev.Refresh();

                if (!dev.RawState.IsConnected)
                {
                    mostSeenDevices--;
                    if (dev.LastState != null)
                    {
                        handleState(dev, new JoystickState());
                    }

                    devices.RemoveAt(i--);
                }
            }

            // Find any newly-connected devices
            while (true)
            {
                if (!OpenTK.Input.Joystick.GetCapabilities(mostSeenDevices).IsConnected)
                {
                    break;
                }

                var newDevice = new JoystickDevice(mostSeenDevices);

                Logger.Log($"Connected joystick device: {newDevice.Guid}");

                devices.Add(newDevice);
                mostSeenDevices++;
            }
        }
Ejemplo n.º 17
0
        JoystickDevice <WinMMJoyDetails> OpenJoystick(int number)
        {
            lock (sync)
            {
                JoystickDevice <WinMMJoyDetails> stick = null;

                JoyCaps       caps;
                JoystickError result = UnsafeNativeMethods.joyGetDevCaps(number, out caps, JoyCaps.SizeInBytes);
                if (result == JoystickError.NoError)
                {
                    if (caps.NumAxes > JoystickState.MaxAxes)
                    {
                        Debug.Print("[Input] Device has {0} axes, which is higher than OpenTK maximum {1}. Please report a bug at http://www.opentk.com",
                                    caps.NumAxes, JoystickState.MaxAxes);
                        caps.NumAxes = JoystickState.MaxAxes;
                    }

                    if (caps.NumAxes > JoystickState.MaxButtons)
                    {
                        Debug.Print("[Input] Device has {0} buttons, which is higher than OpenTK maximum {1}. Please report a bug at http://www.opentk.com",
                                    caps.NumButtons, JoystickState.MaxButtons);
                        caps.NumButtons = JoystickState.MaxButtons;
                    }

                    JoystickCapabilities joycaps = new JoystickCapabilities(
                        caps.NumAxes,
                        caps.NumButtons,
                        (caps.Capabilities & JoystCapsFlags.HasPov) != 0 ? 1 : 0,
                        true);

                    int num_axes = caps.NumAxes;
                    if ((caps.Capabilities & JoystCapsFlags.HasPov) != 0)
                    {
                        num_axes += 2;
                    }

                    stick         = new JoystickDevice <WinMMJoyDetails>(number, num_axes, caps.NumButtons);
                    stick.Details = new WinMMJoyDetails(joycaps);

                    // Make sure to reverse the vertical axes, so that +1 points up and -1 points down.
                    for (int axis = 0; axis < caps.NumAxes; axis++)
                    {
                        stick.Details.Min[axis] = caps.GetMin(axis);
                        stick.Details.Max[axis] = caps.GetMax(axis);
                    }

                    if ((caps.Capabilities & JoystCapsFlags.HasPov) != 0)
                    {
                        stick.Details.PovType = PovType.Exists;
                        if ((caps.Capabilities & JoystCapsFlags.HasPov4Dir) != 0)
                        {
                            stick.Details.PovType |= PovType.Discrete;
                        }
                        if ((caps.Capabilities & JoystCapsFlags.HasPovContinuous) != 0)
                        {
                            stick.Details.PovType |= PovType.Continuous;
                        }
                    }

                    // Todo: Implement joystick name detection for WinMM.
                    stick.Description = String.Format("Joystick/Joystick #{0} ({1} axes, {2} buttons)", number, stick.Axis.Count, stick.Button.Count);
                    // Todo: Try to get the device name from the registry. Oh joy!
                    //string key_path = String.Format("{0}\\{1}\\{2}", RegistryJoyConfig, caps.RegKey, RegstryJoyCurrent);
                    //RegistryKey key = Registry.LocalMachine.OpenSubKey(key_path, false);
                    //if (key == null)
                    //    key = Registry.CurrentUser.OpenSubKey(key_path, false);
                    //if (key == null)
                    //    stick.Description = String.Format("USB Joystick {0} ({1} axes, {2} buttons)", number, stick.Axis.Count, stick.Button.Count);
                    //else
                    //{
                    //    key.Close();
                    //}

                    Debug.Print("Found joystick on device number {0}", number);
                    index_to_stick.Add(number, sticks.Count);
                    player_to_index.Add(player_to_index.Count, number);
                    sticks.Add(stick);
                }

                return(stick);
            }
        }
Ejemplo n.º 18
0
        public devices.IDevice ResolveDevice(IHIDDevice hidDevice)
        {
            int i = 0;

            int inx;

            //Give Unity Update(Input works only in Update on Main single thread
            //and this funciton is happen on Event on other thread)
            //to be done so GetJoysticksNames return something
            //!!! Not tested yet on WIN
            System.Threading.Thread.Sleep(300);             //sleep this Event add device thread

            //find device match based on "names"
            string[] names = Input.GetJoystickNames();
            inx = Array.IndexOf(names, hidDevice.Name);


            Debug.Log(String.Join(",", names));

            if (inx < 0)
            {
                return(null);
            }

            if (inx > 3)
            {
                Debug.LogWarning("Unity supports up to 4 Joysticks");
                return(null);
            }

            DeviceProfile profile = hidDevice.loadProfile();



            JoystickDevice device = new JoystickDevice(inx, hidDevice.PID, hidDevice.VID, hidDevice.ID, 12, 20, this);

            device.Name    = hidDevice.Name;
            device.profile = profile;

            int numAxis    = device.Axis.Count;
            int numButtons = device.Buttons.Count;

            for (; i < numAxis; i++)
            {
                device.Axis [i] = new AxisDetails();
                if (profile != null && profile.axisNaming.Length > i)
                {
                    device.Axis [i].name = profile.axisNaming [i];
                }
            }

            for (i = 0; i < numButtons; i++)
            {
                device.Buttons [i] = new ButtonDetails();
                if (profile != null && profile.buttonNaming.Length > i)
                {
                    device.Buttons [i].name = profile.buttonNaming [i];
                }
            }



            return(device);
        }
Ejemplo n.º 19
0
        private void SettingsLoad(object sender, EventArgs e)
        {
            if (!Helper.HasFeature(Enums.Features.Settings))
            {
                using (var cp = new CheckPassword())
                {
                    cp.ShowDialog(this);
                }
            }

            if (!Helper.HasFeature(Enums.Features.Settings))
            {
                MessageBox.Show(this, LocRm.GetString("AccessDenied"));
                Close();
                return;
            }

            UISync.Init(this);
            tcTabs.SelectedIndex = InitialTab;

            _rkApp = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", false);

            SetColors();



            int i = 0, selind = 0;

            foreach (TranslationsTranslationSet set in LocRm.TranslationSets.OrderBy(p => p.Name))
            {
                if (set.CultureCode == MainForm.Conf.Language)
                {
                    selind = i;
                }
                i++;
            }

            SetSSLText();



            _jst = new JoystickDevice();
            var ij = 0;

            _sticks = _jst.FindJoysticks();
            i       = 1;
            foreach (string js in _sticks)
            {
                var nameid = js.Split('|');

                if (nameid[1] == MainForm.Conf.Joystick.id)
                {
                    ij = i;
                }
                i++;
            }



            HideTab(tabPage11, Helper.HasFeature(Enums.Features.Plugins));

            //important leave here:

            if (Helper.HasFeature(Enums.Features.Plugins))
            {
                ListPlugins();
            }



            _loaded = true;
        }
Ejemplo n.º 20
0
 public JoystickBehavior(JoystickDevice j)
 {
     yaw              = roll = 0;
     j.InputReceived += Joystick_InputReceived;
     this.j           = j;
 }
Ejemplo n.º 21
0
        JoystickDevice <WinMMJoyDetails> OpenJoystick(int number)
        {
            JoystickDevice <WinMMJoyDetails> stick = null;

            JoyCaps       caps;
            JoystickError result = UnsafeNativeMethods.joyGetDevCaps(number, out caps, JoyCaps.SizeInBytes);

            if (result != JoystickError.NoError)
            {
                return(null);
            }

            int num_axes = caps.NumAxes;

            if ((caps.Capabilities & JoystCapsFlags.HasPov) != 0)
            {
                num_axes += 2;
            }

            stick         = new JoystickDevice <WinMMJoyDetails>(number, num_axes, caps.NumButtons);
            stick.Details = new WinMMJoyDetails(num_axes);

            // Make sure to reverse the vertical axes, so that +1 points up and -1 points down.
            int axis = 0;

            if (axis < caps.NumAxes)
            {
                stick.Details.Min[axis] = caps.XMin; stick.Details.Max[axis] = caps.XMax; axis++;
            }
            if (axis < caps.NumAxes)
            {
                stick.Details.Min[axis] = caps.YMax; stick.Details.Max[axis] = caps.YMin; axis++;
            }
            if (axis < caps.NumAxes)
            {
                stick.Details.Min[axis] = caps.ZMax; stick.Details.Max[axis] = caps.ZMin; axis++;
            }
            if (axis < caps.NumAxes)
            {
                stick.Details.Min[axis] = caps.RMin; stick.Details.Max[axis] = caps.RMax; axis++;
            }
            if (axis < caps.NumAxes)
            {
                stick.Details.Min[axis] = caps.UMin; stick.Details.Max[axis] = caps.UMax; axis++;
            }
            if (axis < caps.NumAxes)
            {
                stick.Details.Min[axis] = caps.VMax; stick.Details.Max[axis] = caps.VMin; axis++;
            }

            if ((caps.Capabilities & JoystCapsFlags.HasPov) != 0)
            {
                stick.Details.PovType = PovType.Exists;
                if ((caps.Capabilities & JoystCapsFlags.HasPov4Dir) != 0)
                {
                    stick.Details.PovType |= PovType.Discrete;
                }
                if ((caps.Capabilities & JoystCapsFlags.HasPovContinuous) != 0)
                {
                    stick.Details.PovType |= PovType.Continuous;
                }
            }

#warning "Implement joystick name detection for WinMM."
            stick.Description = String.Format("Joystick/Joystick #{0} ({1} axes, {2} buttons)", number, stick.Axis.Count, stick.Button.Count);
            // Todo: Try to get the device name from the registry. Oh joy!
            //string key_path = String.Format("{0}\\{1}\\{2}", RegistryJoyConfig, caps.RegKey, RegstryJoyCurrent);
            //RegistryKey key = Registry.LocalMachine.OpenSubKey(key_path, false);
            //if (key == null)
            //    key = Registry.CurrentUser.OpenSubKey(key_path, false);
            //if (key == null)
            //    stick.Description = String.Format("USB Joystick {0} ({1} axes, {2} buttons)", number, stick.Axis.Count, stick.Button.Count);
            //else
            //{
            //    key.Close();
            //}

            if (stick != null)
            {
                Debug.Print("Found joystick on device number {0}", number);
            }
            return(stick);
        }
Ejemplo n.º 22
0
        JoystickDevice <X11JoyDetails> OpenJoystick(string path)
        {
            JoystickDevice <X11JoyDetails> stick = null;

            int number = GetJoystickNumber(Path.GetFileName(path));

            if (number >= 0)
            {
                int fd = -1;
                try
                {
                    fd = UnsafeNativeMethods.open(path, OpenFlags.NonBlock);
                    if (fd == -1)
                    {
                        return(null);
                    }

                    // Check joystick driver version (must be 1.0+)
                    int driver_version = 0x00000800;
                    UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Version, ref driver_version);
                    if (driver_version < 0x00010000)
                    {
                        return(null);
                    }

                    // Get number of joystick axes
                    int axes = 0;
                    UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Axes, ref axes);

                    // Get number of joystick buttons
                    int buttons = 0;
                    UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Buttons, ref buttons);

                    stick = new JoystickDevice <X11JoyDetails>(number, axes, buttons);

                    StringBuilder sb = new StringBuilder(128);
                    UnsafeNativeMethods.ioctl(fd, JoystickIoctlCode.Name128, sb);
                    stick.Description = sb.ToString();

                    stick.Details.FileDescriptor = fd;
                    stick.Details.State.SetIsConnected(true);
                    stick.Details.Guid = CreateGuid(stick, path, number);

                    // Find the first disconnected joystick (if any)
                    int i;
                    for (i = 0; i < sticks.Count; i++)
                    {
                        if (!sticks[i].Details.State.IsConnected)
                        {
                            break;
                        }
                    }

                    // If no disconnected joystick exists, append a new slot
                    if (i == sticks.Count)
                    {
                        sticks.Add(stick);
                    }
                    else
                    {
                        sticks[i] = stick;
                    }

                    // Map player index to joystick
                    index_to_stick.Add(index_to_stick.Count, i);

                    Debug.Print("Found joystick on path {0}", path);
                }
                finally
                {
                    if (stick == null && fd != -1)
                    {
                        UnsafeNativeMethods.close(fd);
                    }
                }
            }

            return(stick);
        }
Ejemplo n.º 23
0
        private void handleState(JoystickDevice device, JoystickState newState)
        {
            PendingInputs.Enqueue(new JoystickButtonInput(newState.Buttons, device.LastState?.Buttons));

            device.LastState = newState;
        }
Ejemplo n.º 24
0
        public IDevice ResolveDevice(IHIDDevice hidDevice)
        {
            _hidInterface = hidDevice.hidInterface;

            JoystickDevice device;

            //Get jostick capabilities
            Native.JoyCaps       caps;
            Native.JoystickError result = Native.JoystickError.InvalidParameters;



            DeviceProfile profile;



            int i;

            for (i = 0; i < 16; i++)
            {
                result = Native.joyGetDevCaps(i, out caps, Native.JoyCaps.SizeInBytes);


                if (result == Native.JoystickError.NoError && caps.PID == hidDevice.PID && hidDevice.VID == caps.VID)
                {
                    //UnityEngine.Debug.Log("ID:"+i+" on PID:"+info.PID+" VID:"+info.VID+" info:"+info.DevicePath+"Bts"+caps.NumButtons.ToString()+"axes"+caps.NumAxes
                    //  +"ProdID"+caps.PID+" name:"+caps.ProductName+" regkey"+caps.RegKey+"Man:"+caps.VID);



                    int num_axes = caps.NumAxes;

                    //!!! save ordNumber(I don't have still function that would return ordNum for WinMM from PID);
                    ((GenericHIDDevice)hidDevice).ord = i;

                    profile = hidDevice.loadProfile();

                    device           = new JoystickDevice(hidDevice.index, hidDevice.PID, hidDevice.VID, hidDevice.ID, 8, caps.NumButtons, this);
                    device.Extension = new WinDefaultExtension();
                    device.Name      = hidDevice.Name;
                    device.profile   = profile;

                    int buttonIndex = 0;
                    for (; buttonIndex < caps.NumButtons; buttonIndex++)
                    {
                        device.Buttons[buttonIndex] = new ButtonDetails();

                        if (profile != null && profile.buttonNaming.Length > buttonIndex)
                        {
                            device.Buttons[buttonIndex].name = profile.buttonNaming[buttonIndex];
                        }
                    }


                    // Make sure to reverse the vertical axes, so that +1 points up and -1 points down.
                    int         axis = 0;
                    AxisDetails axisDetails;
                    if (axis < num_axes)
                    {
                        axisDetails       = new AxisDetails();
                        axisDetails.max   = caps.XMax;
                        axisDetails.min   = caps.XMin;
                        device.Axis[axis] = axisDetails;
                        //if(axisDetails.min==0 && axisDetails.max==255) axisDetails.isTrigger=true;

                        if (profile != null && profile.axisNaming.Length > axis)
                        {
                            axisDetails.name = profile.axisNaming[axis];
                        }

                        axis++;
                    }
                    if (axis < num_axes)
                    {
                        axisDetails     = new AxisDetails();
                        axisDetails.max = caps.YMax;
                        axisDetails.min = caps.YMin;
                        // if (axisDetails.min == 0 && axisDetails.max == 32767) axisDetails.isTrigger = true;
                        device.Axis[axis] = axisDetails;


                        if (profile != null && profile.axisNaming.Length > axis)
                        {
                            axisDetails.name = profile.axisNaming[axis];
                        }

                        //	stick.Details.Min[axis] = caps.YMin; stick.Details.Max[axis] = caps.YMax;
                        axis++;
                    }
                    if (axis < num_axes)
                    {
                        axisDetails     = new AxisDetails();
                        axisDetails.max = caps.ZMax;
                        axisDetails.min = caps.ZMin;
                        //if(axisDetails.min==0) axisDetails.isTrigger=true;
                        device.Axis[axis] = axisDetails;

                        if (profile != null && profile.axisNaming.Length > axis)
                        {
                            axisDetails.name = profile.axisNaming[axis];
                        }

                        axis++;
                    }

                    if (axis < num_axes)
                    {
                        axisDetails     = new AxisDetails();
                        axisDetails.min = caps.RMin;
                        axisDetails.max = caps.RMax;
                        //    if (axisDetails.min == 0 && axisDetails.max == 255) axisDetails.isTrigger = true;
                        device.Axis[axis] = axisDetails;

                        if (profile != null && profile.axisNaming.Length > axis)
                        {
                            axisDetails.name = profile.axisNaming[axis];
                        }

                        axis++;
                    }

                    if (axis < num_axes)
                    {
                        axisDetails     = new AxisDetails();
                        axisDetails.min = caps.UMin;
                        axisDetails.max = caps.UMax;
                        //     if (axisDetails.min == 0 && axisDetails.max == 255) axisDetails.isTrigger = true;
                        device.Axis[axis] = axisDetails;
                        if (profile != null && profile.axisNaming.Length > axis)
                        {
                            axisDetails.name = profile.axisNaming[axis];
                        }
                        axis++;
                    }

                    if (axis < num_axes)
                    {
                        axisDetails     = new AxisDetails();
                        axisDetails.max = caps.VMax;
                        axisDetails.min = caps.VMin;
                        //     if (axisDetails.min == 0 && axisDetails.max == 255) axisDetails.isTrigger = true;
                        device.Axis[axis] = axisDetails;

                        if (profile != null && profile.axisNaming.Length > axis)
                        {
                            axisDetails.name = profile.axisNaming[axis];
                        }
                        axis++;
                    }

                    if ((caps.Capabilities & Native.JoystCapsFlags.HasPov) != 0)
                    {
                        device.Axis[JoystickAxis.AxisPovX] = new AxisDetails();
                        device.Axis[JoystickAxis.AxisPovY] = new AxisDetails();

                        if (profile != null && profile.axisNaming.Length > (int)JoystickAxis.AxisPovX)
                        {
                            device.Axis[JoystickAxis.AxisPovX].name = profile.axisNaming[(int)JoystickAxis.AxisPovX];
                        }

                        if (profile != null && profile.axisNaming.Length > (int)JoystickAxis.AxisPovY)
                        {
                            device.Axis[JoystickAxis.AxisPovY].name = profile.axisNaming[(int)JoystickAxis.AxisPovY];
                        }


                        device.numPOV = 1;

                        //                        WinDefaultExtension extension = joystick.Extension as WinDefaultExtension;
                        //
                        //                        extension.PovType = Native.PovType.Exists;
                        //                        if ((caps.Capabilities & Native.JoystCapsFlags.HasPov4Dir) != 0)
                        //                            extension.PovType |= Native.PovType.Discrete;
                        //                        if ((caps.Capabilities & Native.JoystCapsFlags.HasPovContinuous) != 0)
                        //                            extension.PovType |= Native.PovType.Continuous;
                    }



                    //  UnityEngine.Debug.Log(" max:" + caps.YMax + " min:" + caps.YMin + " max:" + caps.ZMax + " min:" + caps.ZMin);

                    //    UnityEngine.Debug.Log(" max:" + caps.RMax + " min:" + caps.RMin + " max:" + caps.UMax + " min:" + caps.UMin);

                    return(device);
                }
            }


            return(null);

            //return (IDevice<IAxisDetails, IButtonDetails, IDeviceExtension>)joystick;
        }
Ejemplo n.º 25
0
        Guid CreateGuid(JoystickDevice <X11JoyDetails> js, string path, int number)
        {
            byte[] bytes = new byte[16];
            for (int i = 0; i < Math.Min(bytes.Length, js.Description.Length); i++)
            {
                bytes[i] = (byte)js.Description[i];
            }
            return(new Guid(bytes));

#if false // Todo: move to /dev/input/event* from /dev/input/js*
            string evdev_path = Path.Combine(Path.GetDirectoryName(path), "event" + number);
            if (!File.Exists(evdev_path))
            {
                return(new Guid());
            }

            int event_fd = UnsafeNativeMethods.open(evdev_path, OpenFlags.NonBlock);
            if (event_fd < 0)
            {
                return(new Guid());
            }

            try
            {
                EventInputId id;
                if (UnsafeNativeMethods.ioctl(event_fd, EvdevInputId.Id, out id) < 0)
                {
                    return(new Guid());
                }

                int    i   = 0;
                byte[] bus = BitConverter.GetBytes(id.BusType);
                bytes[i++] = bus[0];
                bytes[i++] = bus[1];
                bytes[i++] = 0;
                bytes[i++] = 0;

                if (id.Vendor != 0 && id.Product != 0 && id.Version != 0)
                {
                    byte[] vendor  = BitConverter.GetBytes(id.Vendor);
                    byte[] product = BitConverter.GetBytes(id.Product);
                    byte[] version = BitConverter.GetBytes(id.Version);
                    bytes[i++] = vendor[0];
                    bytes[i++] = vendor[1];
                    bytes[i++] = 0;
                    bytes[i++] = 0;
                    bytes[i++] = product[0];
                    bytes[i++] = product[1];
                    bytes[i++] = 0;
                    bytes[i++] = 0;
                    bytes[i++] = version[0];
                    bytes[i++] = version[1];
                    bytes[i++] = 0;
                    bytes[i++] = 0;
                }
                else
                {
                    for (; i < bytes.Length; i++)
                    {
                        bytes[i] = (byte)js.Description[i];
                    }
                }

                return(new Guid(bytes));
            }
            finally
            {
                UnsafeNativeMethods.close(event_fd);
            }
#endif
        }
Ejemplo n.º 26
0
        private void SettingsLoad(object sender, EventArgs e)
        {
            if (!Helper.HasFeature(Enums.Features.Settings))
            {
                using (var cp = new CheckPassword())
                {
                    cp.ShowDialog(this);
                }
            }

            if (!Helper.HasFeature(Enums.Features.Settings))
            {
                MessageBox.Show(this, LocRm.GetString("AccessDenied"));
                Close();
                return;
            }

            UISync.Init(this);
            tcTabs.SelectedIndex       = InitialTab;
            chkErrorReporting.Checked  = MainForm.Conf.Enable_Error_Reporting;
            chkCheckForUpdates.Checked = MainForm.Conf.Enable_Update_Check;

            chkShowGettingStarted.Checked = MainForm.Conf.Enabled_ShowGettingStarted;
            _rkApp             = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", false);
            chkStartup.Checked = (_rkApp != null && _rkApp.GetValue("iSpy") != null);

            mediaDirectoryEditor1.Init(MainForm.Conf.MediaDirectories);

            btnDetectColor.BackColor     = MainForm.Conf.ActivityColor.ToColor();
            btnNoDetectColor.BackColor   = MainForm.Conf.NoActivityColor.ToColor();
            btnColorTracking.BackColor   = MainForm.Conf.TrackingColor.ToColor();
            btnColorVolume.BackColor     = MainForm.Conf.VolumeLevelColor.ToColor();
            btnColorMain.BackColor       = MainForm.Conf.MainColor.ToColor();
            btnColorArea.BackColor       = MainForm.Conf.AreaColor.ToColor();
            btnColorBack.BackColor       = MainForm.Conf.BackColor.ToColor();
            btnBorderHighlight.BackColor = MainForm.Conf.BorderHighlightColor.ToColor();
            btnBorderDefault.BackColor   = MainForm.Conf.BorderDefaultColor.ToColor();
            chkAutoSchedule.Checked      = MainForm.Conf.AutoSchedule;
            numMaxCPU.Value = MainForm.Conf.CPUMax;
            numMaxRecordingThreads.Value = MainForm.Conf.MaxRecordingThreads;
            numRedraw.Value              = MainForm.Conf.MaxRedrawRate;
            numMediaPanelItems.Value     = MainForm.Conf.PreviewItems;
            txtTrayIcon.Text             = MainForm.Conf.TrayIconText;
            chkMinimise.Checked          = MainForm.Conf.MinimiseOnClose;
            chkSpeechRecognition.Checked = MainForm.Conf.SpeechRecognition;
            chkMinimiseToTray.Checked    = MainForm.Conf.TrayOnMinimise;

            if (chkMonitor.Checked && !MainForm.Conf.Monitor)
            {
                Process.Start(Program.AppPath + "iSpyMonitor.exe");
            }
            chkMonitor.Checked = MainForm.Conf.Monitor;

            tbOpacity.Value = MainForm.Conf.Opacity;
            SetColors();

            chkBalloon.Checked = MainForm.Conf.BalloonTips;

            txtIPCameraTimeout.Value      = MainForm.Conf.IPCameraTimeout;
            txtServerReceiveTimeout.Value = MainForm.Conf.ServerReceiveTimeout;
            txtServerName.Text            = MainForm.Conf.ServerName;
            rtbAccessList.Text            = MainForm.Conf.AllowedIPList;

            int i = 0, selind = 0;

            foreach (TranslationsTranslationSet set in LocRm.TranslationSets.OrderBy(p => p.Name))
            {
                ddlLanguage.Items.Add(new ListItem(set.Name, new[] { set.CultureCode }));
                if (set.CultureCode == MainForm.Conf.Language)
                {
                    selind = i;
                }
                i++;
            }
            ddlLanguage.SelectedIndex    = selind;
            chkAlertWindows.Checked      = MainForm.Conf.CreateAlertWindows;
            chkOverlay.Checked           = MainForm.Conf.ShowOverlayControls;
            chkInterrupt.Checked         = MainForm.Conf.ScreensaverWakeup;
            chkEnableIPv6.Checked        = !MainForm.Conf.IPv6Disabled;
            chkRecycle.Checked           = MainForm.Conf.DeleteToRecycleBin;
            txtAppendLinkText.Text       = MainForm.Conf.AppendLinkText;
            numMJPEGStreamInterval.Value = MainForm.Conf.MJPEGStreamInterval;
            txtAlertOnDisconnect.Text    = MainForm.Conf.AlertOnDisconnect;
            txtAlertOnReconnect.Text     = MainForm.Conf.AlertOnReconnect;
            txtArchive.Text = MainForm.Conf.Archive;
            SetSSLText();


            txtAlertSubject.Text = MainForm.Conf.MailAlertSubject;
            txtAlertBody.Text    = MainForm.Conf.MailAlertBody;
            txtSMSBody.Text      = MainForm.Conf.SMSAlert;

            foreach (string s in StartupModes)
            {
                ddlStartupMode.Items.Add(LocRm.GetString(s));
            }

            foreach (string s in Priorities)
            {
                ddlPriority.Items.Add(LocRm.GetString(s));
            }
            ddlStartupMode.SelectedIndex = MainForm.Conf.StartupMode;

            foreach (var grid in MainForm.Conf.GridViews)
            {
                ddlStartUpForm.Items.Add(grid.name);
            }

            ddlPriority.SelectedIndex = MainForm.Conf.Priority - 1;

            ddlStartUpForm.SelectedItem = MainForm.Conf.StartupForm;
            if (ddlStartUpForm.SelectedItem == null)
            {
                ddlStartUpForm.SelectedIndex = 0;
            }

            ddlPlayback.Items.AddRange(PlaybackModes);

            if (MainForm.Conf.PlaybackMode < 0)
            {
                MainForm.Conf.PlaybackMode = 0;
            }

            if (MainForm.Conf.PlaybackMode < ddlPlayback.Items.Count)
            {
                ddlPlayback.SelectedIndex = MainForm.Conf.PlaybackMode;
            }
            try
            {
                numJPEGQuality.Value = MainForm.Conf.JPEGQuality;
            }
            catch (Exception)
            {
            }
            chkBigButtons.Checked = MainForm.Conf.BigButtons;

            selind = -1;
            i      = 1;
            try
            {
                ddlTalkMic.Items.Add(LocRm.GetString("None"));

                for (int n = 0; n < WaveIn.DeviceCount; n++)
                {
                    ddlTalkMic.Items.Add(WaveIn.GetCapabilities(n).ProductName);
                    if (WaveIn.GetCapabilities(n).ProductName == MainForm.Conf.TalkMic)
                    {
                        selind = i;
                    }
                    i++;
                }
                ddlTalkMic.Enabled = true;
                if (selind > -1)
                {
                    ddlTalkMic.SelectedIndex = selind;
                }
                else
                {
                    if (ddlTalkMic.Items.Count == 1)
                    {
                        ddlTalkMic.Items.Add(_noDevices);
                        ddlTalkMic.Enabled       = false;
                        ddlTalkMic.SelectedIndex = 1;
                    }
                    else
                    {
                        ddlTalkMic.SelectedIndex = 0;
                    }
                }
            }
            catch (ApplicationException ex)
            {
                MainForm.LogExceptionToFile(ex);
                ddlTalkMic.Items.Add(_noDevices);
                ddlTalkMic.Enabled = false;
            }

            ddlJoystick.Items.Add(LocRm.GetString("None"));

            _jst = new JoystickDevice();
            var ij = 0;

            _sticks = _jst.FindJoysticks();
            i       = 1;
            foreach (string js in _sticks)
            {
                var nameid = js.Split('|');
                ddlJoystick.Items.Add(nameid[0]);
                if (nameid[1] == MainForm.Conf.Joystick.id)
                {
                    ij = i;
                }
                i++;
            }

            ddlJoystick.SelectedIndex = ij;


            jaxis1.ID          = MainForm.Conf.Joystick.XAxis;
            jaxis1.SupportDPad = true;
            jaxis1.Invert      = MainForm.Conf.Joystick.InvertXAxis;

            jaxis2.ID     = MainForm.Conf.Joystick.YAxis;
            jaxis2.Invert = MainForm.Conf.Joystick.InvertYAxis;

            jaxis3.ID     = MainForm.Conf.Joystick.ZAxis;
            jaxis3.Invert = MainForm.Conf.Joystick.InvertZAxis;

            jbutton1.ID = MainForm.Conf.Joystick.Record;
            jbutton2.ID = MainForm.Conf.Joystick.Snapshot;
            jbutton3.ID = MainForm.Conf.Joystick.Talk;
            jbutton4.ID = MainForm.Conf.Joystick.Listen;
            jbutton5.ID = MainForm.Conf.Joystick.Play;
            jbutton6.ID = MainForm.Conf.Joystick.Next;
            jbutton7.ID = MainForm.Conf.Joystick.Previous;
            jbutton8.ID = MainForm.Conf.Joystick.Stop;
            jbutton9.ID = MainForm.Conf.Joystick.MaxMin;

            jbutton1.GetInput += JbuttonGetInput;
            jbutton2.GetInput += JbuttonGetInput;
            jbutton3.GetInput += JbuttonGetInput;
            jbutton4.GetInput += JbuttonGetInput;
            jbutton5.GetInput += JbuttonGetInput;
            jbutton6.GetInput += JbuttonGetInput;
            jbutton7.GetInput += JbuttonGetInput;
            jbutton8.GetInput += JbuttonGetInput;
            jbutton9.GetInput += JbuttonGetInput;

            jaxis1.GetInput += JaxisGetInput;
            jaxis2.GetInput += JaxisGetInput;
            jaxis3.GetInput += JaxisGetInput;

            chkGZip.Checked = MainForm.Conf.EnableGZip;
            numDisconnectNotification.Value = MainForm.Conf.DisconnectNotificationDelay;
            mediaDirectoryEditor1.Enabled   = Helper.HasFeature(Enums.Features.Storage);
            HideTab(tabPage11, Helper.HasFeature(Enums.Features.Plugins));

            //important leave here:
            chkPasswordProtect.Checked = MainForm.Conf.Enable_Password_Protect;
            if (Helper.HasFeature(Enums.Features.Plugins))
            {
                ListPlugins();
            }

            chkUseiSpy.Checked      = !MainForm.Conf.UseSMTP;
            txtSMTPFromAddress.Text = MainForm.Conf.SMTPFromAddress;
            txtSMTPUsername.Text    = MainForm.Conf.SMTPUsername;
            txtSMTPPassword.Text    = MainForm.Conf.SMTPPassword;
            txtSMTPServer.Text      = MainForm.Conf.SMTPServer;
            chkSMTPUseSSL.Checked   = MainForm.Conf.SMTPSSL;
            numSMTPPort.Value       = MainForm.Conf.SMTPPort;

            ftpEditor1.Init(MainForm.Conf.FTPServers);
            chkOpenGrabs.Checked = MainForm.Conf.OpenGrabs;
            numFileCache.Value   = MainForm.Conf.VLCFileCache;
            rtbReferrers.Text    = MainForm.Conf.Referers;
            chkPasswordProtectOnStart.Checked = MainForm.Conf.Password_Protect_Startup;

            chkEnableLogging.Checked = MainForm.Conf.Logging.Enabled;
            numMaxLogSize.Value      = MainForm.Conf.Logging.FileSize;
            numKeepLogs.Value        = MainForm.Conf.Logging.KeepDays;

            _loaded = true;
        }
 private JoystickProgram(JoystickDevice device)
 {
     this.device = device;
     config      = JoystickConfig.GetConfig(device.Name);
 }
Ejemplo n.º 28
0
        public JoystickState GetState(int player_index)
        {
            lock (sync)
            {
                JoystickState state = new JoystickState();

                if (IsValid(player_index))
                {
                    int device_index = player_to_index[player_index];
                    int index        = index_to_stick[device_index];
                    JoystickDevice <WinMMJoyDetails> stick =
                        sticks[index] as JoystickDevice <WinMMJoyDetails>;

                    // For joysticks with fewer than three axes or four buttons, we must
                    // use joyGetPos; otherwise, joyGetPosEx. This is not just a cosmetic
                    // difference, simple devices will return incorrect results if we use
                    // joyGetPosEx on them.
                    if (stick.Details.Capabilities.AxisCount <= 3 || stick.Details.Capabilities.ButtonCount <= 4)
                    {
                        // Use joyGetPos
                        JoyInfo info = new JoyInfo();

                        JoystickError result = UnsafeNativeMethods.joyGetPos(device_index, ref info);
                        if (result == JoystickError.NoError)
                        {
                            for (int i = 0; i < stick.Details.Capabilities.AxisCount; i++)
                            {
                                state.SetAxis(JoystickAxis.Axis0 + i, CalculateOffset(info.GetAxis(i), stick.Details.Min[i], stick.Details.Max[i]));
                            }

                            for (int i = 0; i < stick.Details.Capabilities.ButtonCount; i++)
                            {
                                state.SetButton(JoystickButton.Button0 + i, (info.Buttons & 1 << i) != 0);
                            }

                            state.SetIsConnected(true);
                        }
                        else if (result == JoystickError.Unplugged)
                        {
                            UnplugJoystick(player_index);
                        }
                    }
                    else
                    {
                        // Use joyGetPosEx
                        JoyInfoEx info = new JoyInfoEx();
                        info.Size  = JoyInfoEx.SizeInBytes;
                        info.Flags = JoystickFlags.All;

                        JoystickError result = UnsafeNativeMethods.joyGetPosEx(device_index, ref info);
                        if (result == JoystickError.NoError)
                        {
                            for (int i = 0; i < stick.Details.Capabilities.AxisCount; i++)
                            {
                                state.SetAxis(JoystickAxis.Axis0 + i, CalculateOffset(info.GetAxis(i), stick.Details.Min[i], stick.Details.Max[i]));
                            }

                            for (int i = 0; i < stick.Details.Capabilities.ButtonCount; i++)
                            {
                                state.SetButton(JoystickButton.Button0 + i, (info.Buttons & 1 << i) != 0);
                            }

                            state.SetIsConnected(true);
                        }
                        else if (result == JoystickError.Unplugged)
                        {
                            UnplugJoystick(player_index);
                        }
                    }
                }

                return(state);
            }
        }
Ejemplo n.º 29
0
		/// <summary>
		/// Resolves the device.
		/// </summary>
		/// <returns>returns JoystickDevice if driver is for this device or null</returns>
		/// <param name="info">Info.</param>
		/// <param name="hidDevice">Hid device.</param>
		public IDevice ResolveDevice (IHIDDevice hidDevice)
		{
	
			this._hidInterface = hidDevice.hidInterface;

			IntPtr deviceRef=hidDevice.deviceHandle;

			JoystickDevice device;
			int axisIndex=0;
			int buttonIndex=0;

			Native.CFArray elements=new Native.CFArray();
			IOHIDElementRef element;
			IOHIDElementType type;

			//copy all matched 
			elements.typeRef=Native.IOHIDDeviceCopyMatchingElements(deviceRef, IntPtr.Zero,(int)Native.IOHIDOptionsType.kIOHIDOptionsTypeNone );
			
			int numButtons=0;
		
			int numPov=0;

			int numElements=elements.Length;
			int HIDElementType=Native.IOHIDElementGetTypeID();

			//check for profile
			DeviceProfile profile = hidDevice.loadProfile();




					




			IAxisDetails axisDetailsPovX=null;
			IAxisDetails axisDetailsPovY=null;

			List<IAxisDetails> axisDetailsList = new List <IAxisDetails>();
		

			IAxisDetails axisDetails;
			
							for (int elementIndex = 0; elementIndex < numElements; elementIndex++){

									element =  elements[elementIndex].typeRef;


								if(element!=IntPtr.Zero && Native.CFGetTypeID(element) == HIDElementType){
												
												type = Native.IOHIDElementGetType(element);
							
							
												// All of the axis elements I've ever detected have been kIOHIDElementTypeInput_Misc. kIOHIDElementTypeInput_Axis is only included for good faith...
												if (type == IOHIDElementType.kIOHIDElementTypeInput_Misc ||
												    type == IOHIDElementType.kIOHIDElementTypeInput_Axis) {
												


													axisDetails=new AxisDetails();
													
													axisDetails.uid=Native.IOHIDElementGetCookie(element);
													axisDetails.min=(int)Native.IOHIDElementGetLogicalMin(element);
													axisDetails.max=(int)Native.IOHIDElementGetLogicalMax(element);
													axisDetails.isNullable=Native.IOHIDElementHasNullState(element);

													

					

										            
													if(Native.IOHIDElementGetUsage(element)==(uint)Native.HIDUsageGD.Hatswitch){
												
														axisDetails.isHat=true;
														axisDetailsPovX=axisDetails;
		
														axisDetailsPovY=new AxisDetails();
														
														axisDetailsPovY.uid=Native.IOHIDElementGetCookie(element);
														axisDetailsPovY.min=(int)Native.IOHIDElementGetLogicalMin(element);
														axisDetailsPovY.max=(int)Native.IOHIDElementGetLogicalMax(element);
														axisDetailsPovY.isNullable=Native.IOHIDElementHasNullState(element);
														axisDetailsPovY.isHat=true;

							numPov++;


													}else{
							if(axisDetails.min==0) axisDetails.isTrigger=true;
							axisDetailsList.Add(axisDetails);

						}

										          
											
												} else if (type == IOHIDElementType.kIOHIDElementTypeInput_Button) {
													numButtons++;
												}
								}
			
						}


			if (axisDetailsPovX != null) {
				int diff;

				diff=axisDetailsList.Count -8;
				//need 2 slots for Pov X,Y
				if(diff>=0){
					//just insert them
					axisDetailsList.Insert((int)JoystickAxis.AxisPovX,axisDetailsPovX);
					axisDetailsList.Insert((int)JoystickAxis.AxisPovY,axisDetailsPovY);
				}else if(diff<-1){
					diff=diff+2;
					while(diff<0){
						axisDetailsList.Add(null);
						diff+=1;
					}

					axisDetailsList.Add(axisDetailsPovX);
					axisDetailsList.Add(axisDetailsPovY);

				}else{//=-1
					axisDetailsList.Resize (9);
					axisDetailsList[(int)JoystickAxis.AxisPovX]=axisDetailsPovX;
					axisDetailsList[(int)JoystickAxis.AxisPovY]=axisDetailsPovY;
				}

								
								
			}


			device=new JoystickDevice(hidDevice.index,hidDevice.PID,hidDevice.VID,hidDevice.ID,axisDetailsList.Count,numButtons,this);
			device.Name = hidDevice.Name;
			device.numPOV = numPov;
			device.profile = profile;

			for(;axisIndex<device.Axis.Count;axisIndex++)
			{
				
				device.Axis[(JoystickAxis)axisIndex]=axisDetailsList[axisIndex];
				if (profile != null && profile.axisNaming.Length > axisIndex && device.Axis[axisIndex]!=null) {
					device.Axis[axisIndex].name = profile.axisNaming [axisIndex];
					
				}

			}
			

			
			
			
			for (int elementIndex = 0; elementIndex < numElements; elementIndex++){
				element = elements[elementIndex].typeRef;

				if(element!=IntPtr.Zero && Native.CFGetTypeID(element) == HIDElementType){
				type = Native.IOHIDElementGetType(element);
				 if (type == IOHIDElementType.kIOHIDElementTypeInput_Button) {
								//
								device.Buttons[buttonIndex]=new ButtonDetails(Native.IOHIDElementGetCookie(element));


						if (profile != null && profile.buttonNaming.Length > buttonIndex) {
							device.Buttons[buttonIndex].name = profile.buttonNaming [buttonIndex];
						}
						buttonIndex++;
							
				}
			}
				
		}







			//joystick.isReady = false;

						device.Extension=new OSXDefaultExtension();








             return device;

		}
Ejemplo n.º 30
0
        /// <summary>
        /// Ons the position update.
        /// </summary>
        /// <param name="data">Data.</param>
        protected void onRead(object data)
        {
            WebHIDReport report = (WebHIDReport)data;

            // GenericHIDDevice info = Json.Deserialize(args.Message) as GenericHIDDevice;

            if (report.Status == HIDReport.ReadStatus.Success || report.Status == HIDReport.ReadStatus.Buffered)
            {
                JoystickDevice device = InputEx.Devices.GetDeviceAt(report.index) as JoystickDevice;


                // UnityEngine.Debug.Log("onPositionUpdate:Joy" + info.index);


                // UnityEngine.Debug.Log(device);
                // UnityEngine.Debug.Log(info.axes);
                // UnityEngine.Debug.Log(info.axes.Count + " " + device.Axis.Count);


                //UPDATING AXIS BUTTONS

                //UnityEngine.Debug.Log("buttons" + info.buttons.);
                // UnityEngine.Debug.Log("buttons" + info.buttons.Count);

                int i = 0;

                foreach (var obj in report.buttons)
                {
                    //if(i==0) {_webHidBehavior.Log("button:"+obj+" "+obj.GetType()+" "+Convert.ToSingle(obj));
                    //    device.Buttons[i++].value = Convert.ToSingle(obj);
                    //}

                    device.Buttons[i++].value = Convert.ToSingle(obj);
                }


//_webHidBehavior.Log(device.Buttons[0].value.ToString() + device.Buttons[1].value.ToString()+device.Buttons[2].value.ToString());


                i = 0;
                float value = 0;

                float dreadZone = 0.001f;//TODO this shouldn't be hard coded
                // string axisValues="";
                //  int numAxes=device.Axis.Count;


                //!!! FF gives 7 axis and the last 2 are POW on test Thrustmaster
                //!!! Chrome gives 10 axis and last 4 are POW 2 by 2 but they give some strange values

                foreach (var obj in report.axes)
                {
                    value = Convert.ToSingle(obj);
                    if (value < dreadZone && value > -dreadZone)
                    {
                        value = 0;
                    }

                    //LAST 4 axes are POV probably
                    //if (numAxes > 8)
                    //{
                    //    if (i == (int)JoystickAxis.AxisPovX)
                    //    {
                    //        device.Axis[numAxes - 2].value = Convert.ToSingle(Math.Min(1f, Math.Max(-1, value)));
                    //        i++;
                    //        continue;
                    //    }
                    //    else if (i == (int)JoystickAxis.AxisPovY)
                    //    {
                    //        device.Axis[numAxes - 1].value = Convert.ToSingle(Math.Min(1f, Math.Max(-1, value)));
                    //        i++;
                    //        continue;
                    //    }
                    //    else if (i == numAxes - 2)
                    //    {
                    //        device.Axis[JoystickAxis.AxisPovX].value = Convert.ToSingle(Math.Min(1f, Math.Max(-1, value)));
                    //        i++;
                    //        continue;
                    //    }
                    //    else if (i == numAxes - 1)
                    //    {
                    //        device.Axis[JoystickAxis.AxisPovY].value = Convert.ToSingle(Math.Min(1f, Math.Max(-1, value)));
                    //        i++;
                    //        continue;
                    //    }
                    //}



                    // UnityEngine.Debug.Log(obj.GetType());

                    device.Axis[i++].value = Convert.ToSingle(Math.Min(1f, Math.Max(-1, value)));
                    // axisValues
                    //  UnityEngine.Debug.Log("axes value:" +device.Axis[i-1].value);
                }
            }


            // switch(guess always the last axes are hats
            //if (numAxes > 8)
            //{
            //    value = device.Axis[JoystickAxis.AxisPovX].value;
            //    device.Axis[JoystickAxis.AxisPovX].value = device.Axis[numAxes - 2].value;
            //    device.Axis[numAxes - 2].value = value;

            //    value = device.Axis[JoystickAxis.AxisPovY].value;
            //    device.Axis[JoystickAxis.AxisPovY].value = device.Axis[numAxes - 1].value;
            //    device.Axis[numAxes - 1].value = value;

            //}


//_webHidBehavior.Log("numaxis: "+device.Axis[0].value.ToString()+device.Axis[1].value.ToString()+ device.Axis[2].value.ToString() + device.Axis[8].value.ToString()+device.Axis[9].value.ToString());

            //_webHidBehavior.Log("numaxis: "+ device.Axis[7].value.ToString() + device.Axis[8].value.ToString()+device.Axis[9].value.ToString());

            // UnityEngine.Debug.Log(device.Axis[0].value + " " + device.Axis[1].value);
            // device.isReady = true;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Resolves the device.
        /// </summary>
        /// <returns>returns JoystickDevice if driver is for this device or null</returns>
        /// <param name="info">Info.</param>
        /// <param name="hidDevice">Hid device.</param>
        public IDevice ResolveDevice(IHIDDevice hidDevice)
        {
            this._hidInterface = hidDevice.hidInterface;

            IntPtr deviceRef = hidDevice.deviceHandle;

            JoystickDevice device;
            int            axisIndex   = 0;
            int            buttonIndex = 0;

            Native.CFArray   elements = new Native.CFArray();
            IOHIDElementRef  element;
            IOHIDElementType type;

            //copy all matched
            elements.typeRef = Native.IOHIDDeviceCopyMatchingElements(deviceRef, IntPtr.Zero, (int)Native.IOHIDOptionsType.kIOHIDOptionsTypeNone);

            int numButtons = 0;

            int numPov = 0;

            int numElements    = elements.Length;
            int HIDElementType = Native.IOHIDElementGetTypeID();

            //check for profile
            DeviceProfile profile = hidDevice.loadProfile();



            IAxisDetails axisDetailsPovX = null;
            IAxisDetails axisDetailsPovY = null;

            List <IAxisDetails> axisDetailsList = new List <IAxisDetails>();


            IAxisDetails axisDetails;

            for (int elementIndex = 0; elementIndex < numElements; elementIndex++)
            {
                element = elements[elementIndex].typeRef;


                if (element != IntPtr.Zero && Native.CFGetTypeID(element) == HIDElementType)
                {
                    type = Native.IOHIDElementGetType(element);


                    // All of the axis elements I've ever detected have been kIOHIDElementTypeInput_Misc. kIOHIDElementTypeInput_Axis is only included for good faith...
                    if (type == IOHIDElementType.kIOHIDElementTypeInput_Misc ||
                        type == IOHIDElementType.kIOHIDElementTypeInput_Axis)
                    {
                        axisDetails = new AxisDetails();

                        axisDetails.uid        = Native.IOHIDElementGetCookie(element);
                        axisDetails.min        = (int)Native.IOHIDElementGetLogicalMin(element);
                        axisDetails.max        = (int)Native.IOHIDElementGetLogicalMax(element);
                        axisDetails.isNullable = Native.IOHIDElementHasNullState(element);



                        if (Native.IOHIDElementGetUsage(element) == (uint)Native.HIDUsageGD.Hatswitch)
                        {
                            axisDetails.isHat = true;
                            axisDetailsPovX   = axisDetails;

                            axisDetailsPovY = new AxisDetails();

                            axisDetailsPovY.uid        = Native.IOHIDElementGetCookie(element);
                            axisDetailsPovY.min        = (int)Native.IOHIDElementGetLogicalMin(element);
                            axisDetailsPovY.max        = (int)Native.IOHIDElementGetLogicalMax(element);
                            axisDetailsPovY.isNullable = Native.IOHIDElementHasNullState(element);
                            axisDetailsPovY.isHat      = true;

                            numPov++;
                        }
                        else
                        {
                            if (axisDetails.min == 0)
                            {
                                axisDetails.isTrigger = true;
                            }
                            axisDetailsList.Add(axisDetails);
                        }
                    }
                    else if (type == IOHIDElementType.kIOHIDElementTypeInput_Button)
                    {
                        numButtons++;
                    }
                }
            }


            if (axisDetailsPovX != null)
            {
                int diff;

                diff = axisDetailsList.Count - 8;
                //need 2 slots for Pov X,Y
                if (diff >= 0)
                {
                    //just insert them
                    axisDetailsList.Insert((int)JoystickAxis.AxisPovX, axisDetailsPovX);
                    axisDetailsList.Insert((int)JoystickAxis.AxisPovY, axisDetailsPovY);
                }
                else if (diff < -1)
                {
                    diff = diff + 2;
                    while (diff < 0)
                    {
                        axisDetailsList.Add(null);
                        diff += 1;
                    }

                    axisDetailsList.Add(axisDetailsPovX);
                    axisDetailsList.Add(axisDetailsPovY);
                }
                else                  //=-1
                {
                    axisDetailsList.Resize(9);
                    axisDetailsList[(int)JoystickAxis.AxisPovX] = axisDetailsPovX;
                    axisDetailsList[(int)JoystickAxis.AxisPovY] = axisDetailsPovY;
                }
            }


            device         = new JoystickDevice(hidDevice.index, hidDevice.PID, hidDevice.VID, hidDevice.ID, axisDetailsList.Count, numButtons, this);
            device.Name    = hidDevice.Name;
            device.numPOV  = numPov;
            device.profile = profile;

            for (; axisIndex < device.Axis.Count; axisIndex++)
            {
                device.Axis[(JoystickAxis)axisIndex] = axisDetailsList[axisIndex];
                if (profile != null && profile.axisNaming.Length > axisIndex && device.Axis[axisIndex] != null)
                {
                    device.Axis[axisIndex].name = profile.axisNaming [axisIndex];
                }
            }



            for (int elementIndex = 0; elementIndex < numElements; elementIndex++)
            {
                element = elements[elementIndex].typeRef;

                if (element != IntPtr.Zero && Native.CFGetTypeID(element) == HIDElementType)
                {
                    type = Native.IOHIDElementGetType(element);
                    if (type == IOHIDElementType.kIOHIDElementTypeInput_Button)
                    {
                        //
                        device.Buttons[buttonIndex] = new ButtonDetails(Native.IOHIDElementGetCookie(element));


                        if (profile != null && profile.buttonNaming.Length > buttonIndex)
                        {
                            device.Buttons[buttonIndex].name = profile.buttonNaming [buttonIndex];
                        }
                        buttonIndex++;
                    }
                }
            }



            //joystick.isReady = false;

            device.Extension = new OSXDefaultExtension();



            return(device);
        }
Ejemplo n.º 32
0
		public IDevice ResolveDevice(IHIDDevice hidDevice)
		{
			_hidInterface = hidDevice.hidInterface;
			
			JoystickDevice device;
			
			//Get jostick capabilities
			Native.JoyCaps caps;
			Native.JoystickError result = Native.JoystickError.InvalidParameters;



            DeviceProfile profile;

          
			
			int i;
			for (i = 0; i < 16; i++)
			{
				
				result = Native.joyGetDevCaps(i, out caps, Native.JoyCaps.SizeInBytes);
				
				
				if (result == Native.JoystickError.NoError && caps.PID == hidDevice.PID && hidDevice.VID == caps.VID)
				{
					
					
					//UnityEngine.Debug.Log("ID:"+i+" on PID:"+info.PID+" VID:"+info.VID+" info:"+info.DevicePath+"Bts"+caps.NumButtons.ToString()+"axes"+caps.NumAxes
					//  +"ProdID"+caps.PID+" name:"+caps.ProductName+" regkey"+caps.RegKey+"Man:"+caps.VID);
					
					
					
					
					
					
					
					int num_axes = caps.NumAxes;
					
					//!!! save ordNumber(I don't have still function that would return ordNum for WinMM from PID);
					((GenericHIDDevice)hidDevice).ord = i;
					
                    profile=hidDevice.loadProfile();
					
					device = new JoystickDevice(hidDevice.index, hidDevice.PID, hidDevice.VID,hidDevice.ID, 8, caps.NumButtons, this);
					device.Extension = new WinDefaultExtension();
					device.Name = hidDevice.Name;
					device.profile = profile;
					
					int buttonIndex = 0;
					for (; buttonIndex < caps.NumButtons; buttonIndex++)
					{
						device.Buttons[buttonIndex] = new ButtonDetails();
						
						if (profile != null && profile.buttonNaming.Length > buttonIndex)
						{
							device.Buttons[buttonIndex].name = profile.buttonNaming[buttonIndex];
						}
					}
					
					
					// Make sure to reverse the vertical axes, so that +1 points up and -1 points down.
					int axis = 0;
					AxisDetails axisDetails;
					if (axis < num_axes)
					{
						axisDetails = new AxisDetails();
						axisDetails.max = caps.XMax;
						axisDetails.min = caps.XMin;
						device.Axis[axis] = axisDetails;
						//if(axisDetails.min==0 && axisDetails.max==255) axisDetails.isTrigger=true;
						
						if (profile != null && profile.axisNaming.Length > axis)
						{
							axisDetails.name = profile.axisNaming[axis];
							
						}
						
						axis++;
					}
					if (axis < num_axes)
					{
						axisDetails = new AxisDetails();
						axisDetails.max = caps.YMax;
						axisDetails.min = caps.YMin;
						// if (axisDetails.min == 0 && axisDetails.max == 32767) axisDetails.isTrigger = true;
						device.Axis[axis] = axisDetails;
						
						
						if (profile != null && profile.axisNaming.Length > axis)
						{
							axisDetails.name = profile.axisNaming[axis];
							
						}
						
						//	stick.Details.Min[axis] = caps.YMin; stick.Details.Max[axis] = caps.YMax; 
						axis++;
					}
					if (axis < num_axes)
					{
						axisDetails = new AxisDetails();
						axisDetails.max = caps.ZMax;
						axisDetails.min = caps.ZMin;
						//if(axisDetails.min==0) axisDetails.isTrigger=true;
						device.Axis[axis] = axisDetails;
						
						if (profile != null && profile.axisNaming.Length > axis)
						{
							axisDetails.name = profile.axisNaming[axis];
							
						}
						
						axis++;
					}
					
					if (axis < num_axes)
					{
						axisDetails = new AxisDetails();
						axisDetails.min = caps.RMin;
						axisDetails.max = caps.RMax;
						//    if (axisDetails.min == 0 && axisDetails.max == 255) axisDetails.isTrigger = true;
						device.Axis[axis] = axisDetails;
						
						if (profile != null && profile.axisNaming.Length > axis)
						{
							axisDetails.name = profile.axisNaming[axis];
							
						}
						
						axis++;
					}
					
					if (axis < num_axes)
					{
						axisDetails = new AxisDetails();
						axisDetails.min = caps.UMin;
						axisDetails.max = caps.UMax;
						//     if (axisDetails.min == 0 && axisDetails.max == 255) axisDetails.isTrigger = true;
						device.Axis[axis] = axisDetails;
						if (profile != null && profile.axisNaming.Length > axis)
						{
							axisDetails.name = profile.axisNaming[axis];
							
						}
						axis++;
					}
					
					if (axis < num_axes)
					{
						axisDetails = new AxisDetails();
						axisDetails.max = caps.VMax;
						axisDetails.min = caps.VMin;
						//     if (axisDetails.min == 0 && axisDetails.max == 255) axisDetails.isTrigger = true;
						device.Axis[axis] = axisDetails;
						
						if (profile != null && profile.axisNaming.Length > axis)
						{
							axisDetails.name = profile.axisNaming[axis];
							
						}
						axis++;
					}
					
					if ((caps.Capabilities & Native.JoystCapsFlags.HasPov) != 0)
					{
						device.Axis[JoystickAxis.AxisPovX] = new AxisDetails();
						device.Axis[JoystickAxis.AxisPovY] = new AxisDetails();
						
						if (profile != null && profile.axisNaming.Length > (int)JoystickAxis.AxisPovX)
						{
							device.Axis[JoystickAxis.AxisPovX].name = profile.axisNaming[(int)JoystickAxis.AxisPovX];
							
						}
						
						if (profile != null && profile.axisNaming.Length > (int)JoystickAxis.AxisPovY)
						{
							device.Axis[JoystickAxis.AxisPovY].name = profile.axisNaming[(int)JoystickAxis.AxisPovY];
							
						}
						
						
						device.numPOV = 1;
						
						//                        WinDefaultExtension extension = joystick.Extension as WinDefaultExtension;
						//
						//                        extension.PovType = Native.PovType.Exists;
						//                        if ((caps.Capabilities & Native.JoystCapsFlags.HasPov4Dir) != 0)
						//                            extension.PovType |= Native.PovType.Discrete;
						//                        if ((caps.Capabilities & Native.JoystCapsFlags.HasPovContinuous) != 0)
						//                            extension.PovType |= Native.PovType.Continuous;
					}
					
					
					
					//  UnityEngine.Debug.Log(" max:" + caps.YMax + " min:" + caps.YMin + " max:" + caps.ZMax + " min:" + caps.ZMin);
					
					//    UnityEngine.Debug.Log(" max:" + caps.RMax + " min:" + caps.RMin + " max:" + caps.UMax + " min:" + caps.UMin);
					
					return device;
					
					
				}
			}
			
			
			return null;
			
			//return (IDevice<IAxisDetails, IButtonDetails, IDeviceExtension>)joystick;
		}
Ejemplo n.º 33
0
        public JoystickState GetState(int player_index)
        {
            lock (sync)
            {
                JoystickState state = new JoystickState();

                if (IsValid(player_index))
                {
                    int device_index = player_to_index[player_index];
                    int index        = index_to_stick[device_index];
                    JoystickDevice <WinMMJoyDetails> stick =
                        sticks[index] as JoystickDevice <WinMMJoyDetails>;

                    // For joysticks with fewer than three axes or four buttons, we must
                    // use joyGetPos; otherwise, joyGetPosEx. This is not just a cosmetic
                    // difference, simple devices will return incorrect results if we use
                    // joyGetPosEx on them.
                    if (stick.Details.Capabilities.AxisCount <= 3 || stick.Details.Capabilities.ButtonCount <= 4)
                    {
                        // Use joyGetPos
                        JoyInfo info = new JoyInfo();

                        JoystickError result = UnsafeNativeMethods.joyGetPos(device_index, ref info);
                        if (result == JoystickError.NoError)
                        {
                            for (int i = 0; i < stick.Details.Capabilities.AxisCount; i++)
                            {
                                state.SetAxis(JoystickAxis.Axis0 + i, CalculateOffset(info.GetAxis(i), stick.Details.Min[i], stick.Details.Max[i]));
                            }

                            for (int i = 0; i < stick.Details.Capabilities.ButtonCount; i++)
                            {
                                state.SetButton(JoystickButton.Button0 + i, (info.Buttons & 1 << i) != 0);
                            }

                            state.SetIsConnected(true);
                        }
                        else if (result == JoystickError.Unplugged)
                        {
                            UnplugJoystick(player_index);
                        }
                    }
                    else
                    {
                        // Use joyGetPosEx
                        JoyInfoEx info_ex = new JoyInfoEx();
                        info_ex.Size  = JoyInfoEx.SizeInBytes;
                        info_ex.Flags = JoystickFlags.All;

                        JoystickError result = UnsafeNativeMethods.joyGetPosEx(device_index, ref info_ex);
                        if (result == JoystickError.NoError)
                        {
                            for (int i = 0; i < stick.Details.Capabilities.AxisCount; i++)
                            {
                                state.SetAxis(JoystickAxis.Axis0 + i, CalculateOffset(info_ex.GetAxis(i), stick.Details.Min[i], stick.Details.Max[i]));
                            }

                            for (int i = 0; i < stick.Details.Capabilities.ButtonCount; i++)
                            {
                                state.SetButton(JoystickButton.Button0 + i, (info_ex.Buttons & 1 << i) != 0);
                            }

                            for (int i = 0; i < stick.Details.Capabilities.HatCount; i++)
                            {
                                // A discrete POV returns specific values for left, right, etc.
                                // A continuous POV returns an integer indicating an angle in degrees * 100, e.g. 18000 == 180.00 degrees.
                                // The vast majority of joysticks have discrete POVs, so we'll treat all of them as discrete for simplicity.
                                if ((JoystickPovPosition)info_ex.Pov != JoystickPovPosition.Centered)
                                {
                                    HatPosition hatpos = HatPosition.Centered;
                                    if (info_ex.Pov < 4500 || info_ex.Pov >= 31500)
                                    {
                                        hatpos |= HatPosition.Up;
                                    }
                                    if (info_ex.Pov >= 4500 && info_ex.Pov < 13500)
                                    {
                                        hatpos |= HatPosition.Right;
                                    }
                                    if (info_ex.Pov >= 13500 && info_ex.Pov < 22500)
                                    {
                                        hatpos |= HatPosition.Down;
                                    }
                                    if (info_ex.Pov >= 22500 && info_ex.Pov < 31500)
                                    {
                                        hatpos |= HatPosition.Left;
                                    }

                                    state.SetHat(JoystickHat.Hat0 + i, new JoystickHatState(hatpos));
                                }
                            }

                            state.SetIsConnected(true);
                        }
                        else if (result == JoystickError.Unplugged)
                        {
                            UnplugJoystick(player_index);
                        }
                    }
                }

                return(state);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Initializes for the window. This setups the data back-end framework, as well searches for joystick
        /// configuration. Set-ups interface controls.
        /// </summary>
        public LiveTelemetry()
        {
            // Use EN-US for compatibility with functions as Convert.ToDouble etc.
            // This is mainly used within track parsers.
            Application.CurrentCulture = new CultureInfo("en-US");

            if (false)
            {
                TelemetryViewer t = new TelemetryViewer();
                t.ShowDialog();
                return;
            }

            // Boot up the telemetry service. Wait for it to start and register events that trigger interface changes.
            Telemetry.m.Run();
            while (Telemetry.m.Sims == null)
            {
                System.Threading.Thread.Sleep(1);
            }
            Telemetry.m.Sim_Start     += mUpdateUI;
            Telemetry.m.Sim_Stop      += mUpdateUI;
            Telemetry.m.Session_Start += mUpdateUI;
            Telemetry.m.Session_Stop  += mUpdateUI;

            System.Threading.Thread.Sleep(500);
            if (Telemetry.m.Sim != null)
            {
                Telemetry.m.Sim.Garage.Scan();
            }

            // TODO: Detect hardware devices (COM-ports or USB devices)
            // GameData is used for my own hardware extension projects.
            // Race dashboard:
            // https://dl.dropbox.com/u/207647/IMAG0924.jpg
            // https://dl.dropbox.com/u/207647/IMAG1204.jpg
            // Switchboard:
            // https://dl.dropbox.com/u/207647/IMAG0928.jpg
            // https://dl.dropbox.com/u/207647/IMAG0934.jpg
            //GameData g = new GameData();

            // Form of singleton for public StatusMenu access.
            _liveTelemetry = this;

            // Read joystick configuration.
            if (File.Exists("config.txt") == false)
            {
                // TODO: Needs fancy dialogs to first-time setup.
                File.Create("config.txt");
                MessageBox.Show(
                    "Please edit config.txt:\r\ncontroller=[your controller you want to use for cyclign through panels]\r\nbutton=[the button on the controller you want to use]\r\n\r\nJust type the name of your controller (G25 alone is enough usually) and look up the button in Devices -> Game Controllers.");
            }
            else
            {
                string[] lines              = File.ReadAllLines("config.txt");
                string   controller         = "";
                bool     controlleruseindex = false;
                int      controllerindex    = 0;
                foreach (string line in lines)
                {
                    string[] p = line.Trim().Split("=".ToCharArray());
                    if (line.StartsWith("button"))
                    {
                        Joystick_Button = Convert.ToInt32(p[1]);
                    }
                    if (line.StartsWith("index"))
                    {
                        controlleruseindex = true;
                        controllerindex    = Convert.ToInt32(p[1]);
                    }
                    if (line.StartsWith("controller"))
                    {
                        controller = p[1];
                    }
                }

                // Search for the joystick.
                List <JoystickDevice> devices = JoystickDevice.Search();
                if (devices.Count == 0)
                {
                    //MessageBox.Show("No (connected) joystick found for display panel control.\r\nTo utilize this please connect a joystick, configure and restart this program.");
                }
                else
                {
                    if (controlleruseindex)
                    {
                        Joystick_Instance          = new Joystick(devices[controllerindex]);
                        Joystick_Instance.Release += Joy_Release;
                    }
                    else
                    {
                        int i = 0;
                        foreach (JoystickDevice jd in devices)
                        {
                            if (jd.Name.Contains(controller.Trim()))
                            {
                                Joystick_Instance          = new Joystick(jd);
                                Joystick_Instance.Release += Joy_Release;
                            }
                            i++;
                        }
                    }
                }
            }

            // Set-up the main interface.
            FormClosing += LiveTelemetry_FormClosing;
            SizeChanged += Telemetry_ResizePanels;

            InitializeComponent();

            this.SuspendLayout();
            BackColor     = Color.Black;
            ucLaps        = new Gauge_Laps();
            ucSplits      = new Gauge_Splits();
            ucA1GP        = new Gauge_A1GP(Joystick_Instance);
            ucTyres       = new Gauge_Tyres();
            ucSessionData = new ucSessionInfo();
            ucTrackmap    = new LiveTrackMap();
            ucLapChart    = new LapChart();
            btGarage      = new Button();
            btNetwork     = new Button();
            btSettings    = new Button();

            // Garage button
            btGarage.Text      = "Garage";
            btGarage.Size      = new Size(75, 25);
            btGarage.BackColor = Color.White;
            btGarage.Location  = new Point(10, 10);
            btGarage.Click    += new EventHandler(btGarage_Click);

            // Settings button
            btSettings.Text      = "Settings";
            btSettings.Size      = new Size(75, 25);
            btSettings.BackColor = Color.White;
            btSettings.Location  = new Point(95, 10);
            btSettings.Click    += new EventHandler(btSettings_Click);

            // Network
            btNetwork.Text      = "Network";
            btNetwork.Size      = new Size(75, 25);
            btNetwork.BackColor = Color.White;
            btNetwork.Location  = new Point(180, 10);
            btNetwork.Click    += new EventHandler(btNetwork_Click);

            // Timers
            Tmr_HiSpeed = new Timer {
                Interval = 20
            };                                    // 30fps
            Tmr_MdSpeed = new Timer {
                Interval = 450
            };                                       // ~2fps
            Tmr_LwSpeed = new Timer {
                Interval = 1000
            };                                      // 1fps

            Tmr_HiSpeed.Tick += Tmr_HiSpeed_Tick;
            Tmr_MdSpeed.Tick += Tmr_MdSpeed_Tick;
            Tmr_LwSpeed.Tick += Tmr_LwSpeed_Tick;

            Tmr_HiSpeed.Start();
            Tmr_MdSpeed.Start();
            Tmr_LwSpeed.Start();

            System.Threading.Thread.Sleep(500);
#if DEBUG
            // This is for hardware peripheral support
            new GameData();
#endif
            SetupUI();
            this.ResumeLayout(false);
        }