Implementation of Wiimote
Inheritance: IDisposable
Exemplo n.º 1
0
        public Wiimote()
        {
            innerWiimote = new WiimoteLib.Wiimote();
            innerWiimote.WiimoteChanged += innerWiimote_WiimoteChanged;

            lastY = Double.PositiveInfinity;
        }
Exemplo n.º 2
0
        public Form1()
        {
            foreach (Process p in Process.GetProcessesByName("googleearth"))
            {
                p.Kill();
            }

            InitializeComponent();

            ge = new EARTHLib.ApplicationGE();

            ShowWindowAsync(ge.GetMainHwnd(), 0);
            SetParent(ge.GetRenderHwnd(), this.Handle.ToInt32());

            Wiimote wm = new Wiimote();

            // setup the event to handle state changes
            wm.WiimoteChanged += wm_WiimoteChanged;

            // connect to the Wiimote
            wm.Connect();

            // set the report type to return the IR sensor and accelerometer data (buttons always come back)
            wm.SetReportType(InputReport.IRAccel, true);

            ResizeGoogleControl();
        }
Exemplo n.º 3
0
        public override void Load()
        {
            IsEnabled = true;

            try
            {
                _wiimote = new Wiimote();
                _wiimote.Connect();
                _wiimote.InitializeMotionPlus();
                _wiimote.WiimoteChanged += wiimote_WiimoteChanged;

                _wiimote.SetRumble(true);
                _wiimote.SetLEDs(true, false, false, true);
                Thread.Sleep(40);
                _wiimote.SetRumble(false);

                RawPosition = new Vector3D();
            }
            catch (Exception exc)
            {
                Logger.Instance.Error(exc.Message, exc);
                try
                {
                    _wiimote.SetLEDs(false, false, false, false);
                }
                catch (Exception exception)
                {
                    Logger.Instance.Error(exception.Message, exception);
                }
                IsEnabled = false;
            }
        }
        /// <summary>
        /// Instantiate the class and initialize the private members as needed.
        /// </summary>
        public WiiRemoteConnection()
        {
            rawDataQueue = new Queue<RawData>();

            wm = new Wiimote();
            wm.WiimoteChanged += wm_WiimoteChanged;
        }
        public WiimoteInput(Wiimote wiimote) : base()
        {
            wiimote.WiimoteChanged += wiimote_WiimoteChanged;
            wiimote.WiimoteExtensionChanged += wiimote_WiimoteExtensionChanged;

            wiimote.Connect();

            if (wiimote.WiimoteState.ExtensionType != ExtensionType.BalanceBoard)
            {
                wiimote.SetReportType(InputReport.IRExtensionAccel, IRSensitivity.Maximum, true);
            }

            this.wiimote = wiimote;

            List<String> validAxes = new List<String>();
            foreach (Axis axis in Enum.GetValues(typeof(Axis)))
            {
                validAxes.Add(axis.ToString());
            }

            List<String> validButtons = new List<String>();
            foreach (Button button in Enum.GetValues(typeof(Button)))
            {
                validButtons.Add(button.ToString());
            }

            CreateMapping(validButtons, validAxes);
        }
Exemplo n.º 6
0
 /// <summary>
 /// Creates the basic structures, but this constructor doesn’t raise the actual wiimote.
 /// This works in that way because assumes that the inexistent Wiimotes are up with default values.
 /// </summary>
 private Wiimote(int _playerIndex)
 {
     wiimote      = new WiimoteLib.Wiimote();
     playerIndex  = _playerIndex;
     isConnected  = false;
     wiimoteState = new WiimoteState();
 } // Wiimote
Exemplo n.º 7
0
        public Buttons(GamePanel panel, Wiimote wm)
            : base(panel, wm)
        {
            timer = new Timer {Interval = 5000};
            timer.Tick += TimerClock;

            starTimer = new Timer { Interval = 1000 };
            starTimer.Tick += StartTimerClock;
        }
Exemplo n.º 8
0
        public ClickMe(GamePanel panel, Wiimote wm)
            : base(panel, wm)
        {
            Wm.SetRumble(false);

            timer = new Timer { Interval = 1000 };
            timer.Tick += TimerClock;

            viewTimer = new Timer { Interval = 15 };
            viewTimer.Tick += ViewTimerClock;
        }
 protected static bool CheckIfDeviceExists(Wiimote wiimote, List<GenericInput> currentDevices)
 {
     for (int i = 0; i < currentDevices.Count; i++)
     {
         if (wiimote.HIDDevicePath.ToString() == currentDevices[i].DeviceInstanceId)
         {
             return true;
         }
     }
     return false;
 }
Exemplo n.º 10
0
        /// <summary>Creates a 800x600 window with the specified title.</summary>
        public Game()
            : base(800, 600, GraphicsMode.Default, "OpenTK Quick Start Sample")
        {
            VSync = VSyncMode.On;

            _wm = new Wiimote();
            _wm.WiimoteChanged += wm_WiimoteChanged;
            _wm.Connect();
            _wm.SetReportType(InputReport.IRAccel, true);
            _wm.SetLEDs(false, true, true, false);
        }
Exemplo n.º 11
0
 private static void RaiseDisconnected(Wiimote wiimote, DisconnectReason reason, bool?removeDevice = null)
 {
     Debug.WriteLine($"{wiimote} Disconnected: {reason}");
     Disconnected?.Invoke(null, new WiimoteDisconnectedEventArgs(wiimote, reason));
     wiimote.RaiseDisconnected(reason);
     if (removeDevice ?? unpairOnDisconnect)
     {
         wiimote.Device.Bluetooth.RemoveDevice();
     }
     UpdateTaskMode();
 }
Exemplo n.º 12
0
 /// <summary>Connects the Wiimote with the specified address.</summary>
 /// <param name="address">The address of the Wiimote.</param>
 /// <returns>The created Wiimote.</returns>
 public static Wiimote Connect(BluetoothAddress address)
 {
     lock (wiimotes) {
         Wiimote connected = wiimotes.Find(wm => wm.Address == address);
         if (connected != null)
         {
             throw new WiimoteAlreadyConnectedException(connected, address);
         }
         return(Connect(new WiimoteDeviceInfo(address)));
     }
 }
Exemplo n.º 13
0
        } // Wiimote

        /// <summary>
        /// Assign the wiimoteLib object to the correct Wiimote object.
        /// </summary>
        private void AssignWiimote(WiimoteLib.Wiimote _wiimote)
        {
            wiimote = _wiimote;
            // Init the IR camera
            if (wiimote.WiimoteState.ExtensionType != ExtensionType.BalanceBoard)
            {
                wiimote.SetReportType(InputReport.IRExtensionAccel, IRSensitivity.Maximum, true);
            }
            // Display the player number using the wiimote's lights
            wiimote.SetLEDs(playerIndex);
            isConnected = true;
        } // AssignWiimote
Exemplo n.º 14
0
 /// <summary>Disconnects the Wiimote.</summary>
 /// <param name="wiimote">The Wiimote to disconnect.</param>
 /// <param name="removeDevice">Should the device be removed. If null, the default
 /// action will be performed.</param>
 public static void Disconnect(Wiimote wiimote, bool?removeDevice = null)
 {
     lock (wiimotes) {
         if (!wiimotes.Contains(wiimote))
         {
             throw new ArgumentException($"{wiimote} is not connected!", nameof(wiimote));
         }
         wiimote.Dispose();
         wiimotes.Remove(wiimote);
         RaiseDisconnected(wiimote, DisconnectReason.User, removeDevice);
     }
 }
Exemplo n.º 15
0
 public override void Unload()
 {
     try
     {
         _wiimote.SetLEDs(false, false, false, false);
         _wiimote.Disconnect();
     }
     catch (Exception exc)
     {
         Logger.Instance.Error(exc.Message, exc);
     }
     _wiimote = null;
 }
Exemplo n.º 16
0
 /// <summary>Disconnects the Wiimote with the specified address.</summary>
 /// <param name="address">The address of the Wiimote.</param>
 /// <param name="removeDevice">Should the device be removed. If null, the default
 /// action will be performed.</param>
 public static void Disconnect(BluetoothAddress address, bool?removeDevice = null)
 {
     lock (wiimotes) {
         Wiimote wiimote = wiimotes.Find(wm => wm.Address == address);
         if (wiimote == null)
         {
             throw new ArgumentException($"Wiimote {{{address}}} is not connected!", nameof(address));
         }
         wiimote.Dispose();
         wiimotes.Remove(wiimote);
         RaiseDisconnected(wiimote, DisconnectReason.User, removeDevice);
     }
 }
Exemplo n.º 17
0
 /// <summary>Disconnects the Wiimote with the specified device path.</summary>
 /// <param name="devicePath">The HID device path of the Wiimote.</param>
 /// <param name="removeDevice">Should the device be removed. If null, the default
 /// action will be performed.</param>
 public static void Disconnect(string devicePath, bool?removeDevice = null)
 {
     lock (wiimotes) {
         Wiimote wiimote = wiimotes.Find(wm => wm.DevicePath == devicePath);
         if (wiimote == null)
         {
             throw new ArgumentException($"Wiimote ({devicePath}) is not connected!", nameof(devicePath));
         }
         wiimote.Dispose();
         wiimotes.Remove(wiimote);
         RaiseDisconnected(wiimote, DisconnectReason.User, removeDevice);
     }
 }
Exemplo n.º 18
0
 /// <summary>Connects the Wiimote with the specified address.</summary>
 /// <param name="address">The address of the Wiimote.</param>
 /// <returns>The created Wiimote.</returns>
 public static Wiimote Connect(string devicePath, bool dolphinBarMode)
 {
     //FIXME: Quick fix to support both Bluetooth and DolphinBar connections.
     //       Determine a better public implementation.
     lock (wiimotes) {
         Wiimote connected = wiimotes.Find(wm => wm.DevicePath == devicePath);
         if (connected != null)
         {
             throw new WiimoteAlreadyConnectedException(connected, devicePath);
         }
         return(Connect(new WiimoteDeviceInfo(devicePath, dolphinBarMode)));
     }
 }
Exemplo n.º 19
0
        private void button_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                // Find all connected Wii devices.

                var deviceCollection = new WiimoteCollection();
                deviceCollection.FindAllWiimotes();

                for (int i = 0; i < deviceCollection.Count; i++)
                {
                    wiiDevice = deviceCollection[i];

                    // Device type can only be found after connection, so prompt for multiple devices.

                    if (deviceCollection.Count > 1)
                    {
                        var devicePathId = new Regex("e_pid&.*?&(.*?)&").Match(wiiDevice.HIDDevicePath).Groups[1].Value.ToUpper();

                        var response = MessageBox.Show("Connect to HID " + devicePathId + " device " + (i + 1) + " of " + deviceCollection.Count + " ?", "Multiple Wii Devices Found", MessageBoxButtons.YesNoCancel);
                        if (response == DialogResult.Cancel) return;
                        if (response == DialogResult.No) continue;
                    }

                    // Setup update handlers.

                    wiiDevice.WiimoteChanged += wiiDevice_WiimoteChanged;
                    wiiDevice.WiimoteExtensionChanged += wiiDevice_WiimoteExtensionChanged;

                    // Connect and send a request to verify it worked.

                    wiiDevice.Connect();
                    wiiDevice.SetReportType(InputReport.IRAccel, false); // FALSE = DEVICE ONLY SENDS UPDATES WHEN VALUES CHANGE!
                    wiiDevice.SetLEDs(true, false, false, false);

                    // Enable processing of updates.

                    infoUpdateTimer.Enabled = true;

                    // Prevent connect being pressed more than once.

                    button_Connect.Enabled = false;
                    //button_BluetoothAddDevice.Enabled = false;
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 20
0
 void MainWindowLoaded(object sender, System.Windows.RoutedEventArgs e)
 {
     try
     {
         wm = new Wiimote();
         wm.WiimoteChanged += OnWiimoteChanged;
         wm.Connect();
         wm.SetReportType(InputReport.IRAccel, true);
         wm.SetLEDs(false, false, false, false);
     }
     catch
     {
         wm = null;
     }
 }
Exemplo n.º 21
0
 private void Init()
 {
     try
     {
         Wiimote wm = new Wiimote();
         wm.WiimoteChanged += wm_WiimoteChanged;
         wm.Connect();
         wm.SetReportType(InputReport.IRAccel, true);
     }
     catch (Exception)
     {
         MessageBox.Show("Balance Board not connected", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         App.Current.Shutdown();
     }
 }
Exemplo n.º 22
0
        public WiimoteControl(int id, Wiimote wiimote)
        {
            this.Wiimote = wiimote;
            this.Status = new WiimoteStatus();
            this.Status.ID = id;

            this.handlerFactory = new HandlerFactory();

            this.keyMapper = new WiiKeyMapper(id,handlerFactory);

            this.keyMapper.OnButtonDown += WiiButton_Down;
            this.keyMapper.OnButtonUp += WiiButton_Up;
            this.keyMapper.OnConfigChanged += WiiKeyMap_ConfigChanged;
            this.keyMapper.OnRumble += WiiKeyMap_OnRumble;
        }
Exemplo n.º 23
0
        public MarathonForm()
        {
            AutoScaleDimensions = new SizeF(6F, 13F);
            AutoScaleMode = AutoScaleMode.Font;
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;

            Name = "Marathon des millions";

            // Rajout des choix à la grammaire du prog
            var grammar = new GrammarBuilder();
            grammar.Append(new Choices("1", "2", "3", "4", "Yes", "No"));

            recognizer = new SpeechRecognitionEngine();
            recognizer.SetInputToDefaultAudioDevice();
            recognizer.UnloadAllGrammars();
            recognizer.LoadGrammar(new Grammar(grammar));
            recognizer.SpeechRecognized += SpeechRecognized;
            recognizer.AudioLevelUpdated += AudioLevelUpdated;
            recognizer.RecognizeAsync(RecognizeMode.Multiple);

            // create a new instance of the Wiimote
            wm = new Wiimote();

            scorePanel = new ScorePanel();
            gamePanel = new GamePanel(wm);
            questionPanel = new QuestionPanel(gamePanel);

            // setup the event to handle state changes
            wm.WiimoteChanged += WiimoteChanged;

            // setup the event to handle insertion/removal of extensions
            wm.WiimoteExtensionChanged += WiimoteExtensionChanged;

            // connect to the Wiimote
            wm.Connect();

            // set the report type to return the IR sensor and accelerometer data (buttons always come back)
            wm.SetReportType(InputReport.IRAccel, IRSensitivity.WiiLevel5, true);

            Layout += MarathonLayout;

            Controls.Add(questionPanel);
            Controls.Add(scorePanel);
            Controls.Add(gamePanel);

            questionPanel.Start();
        }
Exemplo n.º 24
0
        /// <summary>Adds a write request to the write queue.</summary>
        /// <param name="request">The request to write.</param>
        /// <returns>The position in the queue.</returns>

        /*internal static int QueueWriteRequest(WriteRequest request) {
         *      lock (writeQueue) {
         *              writeQueue.Enqueue(request);
         *              return writeQueue.Count - 1;
         *      }
         * }*/

        /// <summary>Adds a write request to the write queue.</summary>
        /// <param name="request">The request to write.</param>
        /// <returns>The position in the queue.</returns>
        internal static int QueueWriteRequest(Wiimote wiimote, byte[] buff)
        {
            WriteRequest request = new WriteRequest(wiimote, buff);

            if (!request.Send())
            {
                //Debug.WriteLine($"Failed to send: {request}");
            }
            return(0);

            /*lock (writeQueue) {
             *      writeQueue.Enqueue(new WriteRequest(wiimote, buff));
             *      writeReady.Set();
             *      return writeQueue.Count - 1;
             * }*/
        }
        private void seachWiimote()
        {
            // find all wiimotes connected to the system
            WiimoteCollection wiimoteCollection = new WiimoteCollection();
            //while (canSearch)
            //{
            try
            {
                wiimoteCollection.FindAllWiimotes();
            }
            catch (WiimoteNotFoundException ex)
            {
                //MessageBox.Show(ex.Message, "Wiimote not found error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (WiimoteException ex)
            {
                //MessageBox.Show(ex.Message, "Wiimote error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Unknown error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (wiimoteCollection.Count == 1)
            {
                Connected = true;

                wiimote = wiimoteCollection[0];

                // connect it and set it up as always
                wiimote.WiimoteChanged += wiimoteChanged;
                wiimote.WiimoteExtensionChanged += wiimoteExtensionChanged;

                wiimote.Connect();

                if (wiimote.WiimoteState.ExtensionType != ExtensionType.BalanceBoard)
                    wiimote.SetReportType(InputReport.IRExtensionAccel, IRSensitivity.Maximum, true);

                wiimote.SetLEDs(false, true, true, false);
            }
            else
            {
                Connected = false;
            }
            //}
        }
Exemplo n.º 26
0
        public WiiMotePlayer(LevelChangedEventArgs eventArgs, int id)
            : base(eventArgs, id, false)
        {
            while (true)
            {
                try
                {
                    _wiimote = new Wiimote();
                    _wiimote.Connect();
                    break;
                }
                catch (WiimoteNotFoundException)
                {
                    MessageBox.Show("Please ensure a wiimote is paired to your computer via Bluetooth, then press OK to try again");
                }

            }
            _wiimote.SetLEDs(id + 1);
        }
Exemplo n.º 27
0
        public Form1()
        {
            InitializeComponent();

            //soundplayer
            Stream str = JetFighter2D.Resource2.Lost_Woods_Dubstep_Remix___Ephixa_Download_at_www;
            sp = new SoundPlayer(str);

            wm = new Wiimote();
            wm.Connect();
            wm.SetLEDs(true, false, true, false);
            wm.SetReportType(InputReport.Buttons, true);

            //connect Wiimote
            GV.wm.Connect();
            GV.wm.SetLEDs(true, false, true, false);

            GV.wm.WiimoteChanged += new EventHandler<WiimoteChangedEventArgs>(Wiimote_changed);
        }
Exemplo n.º 28
0
        public MainViewModel(Dispatcher dispatcher, HelixViewport3D view)
        {
            this.dispatcher = dispatcher;
            this.view = view;

            Heel = 0;
            Trim = 0;
            Heave = 0;
            Length = 200;
            HullBrush = Brushes.Red;

            try
            {
                wm = new Wiimote();
                wm.WiimoteChanged += WiimoteChanged;
            }
            catch
            {
                wm = null;
            }
        }
Exemplo n.º 29
0
        /// <summary>Connects the Wiimote device.</summary>
        /// <param name="device">The Wiimote device to connect.</param>
        /// <returns>The created Wiimote.</returns>
        private static Wiimote Connect(WiimoteDeviceInfo device)
        {
            lock (wiimotes) {
                if (device.IsOpen)
                {
                    throw new ArgumentException("Cannot connect to device that is already in use!",
                                                nameof(device));
                }
                Wiimote connected = wiimotes.Find(wm => wm.Address == device.Address);
                if (connected != null)
                {
                    throw new WiimoteAlreadyConnectedException(connected);
                }

                Wiimote wiimote = new Wiimote(device);
                wiimotes.Add(wiimote);
                wiimote.SetPlayerLED(wiimotes.Count);
                RaiseConnected(wiimote);
                return(wiimote);
            }
        }
Exemplo n.º 30
0
        public GamePanel(Wiimote wm)
        {
            this.wm = wm;

            Layout += GameLayout;

            bigGame = new BigGame(this, wm);

            games = new MiniGame[]
            {
                new Labyrinth(this, wm),
                new ClickMe(this, wm),
                new Run(this, wm),
                new Buttons(this, wm)
            };

            Layout += GameLayout;

            startTimer = new Timer {Interval = 3000};
            startTimer.Tick += StartGame;
            startTimer.Start();
        }
Exemplo n.º 31
0
        public WiimoteRC()
        {
            wiimote = new Wiimote();
            rcPort = new SerialPort();

            // ResourceManager is used to get string values used to communicate with the bot from the external resources file
            rm = new ResourceManager("WiimoteRC.WiimoteRC-Resources", System.Reflection.Assembly.GetExecutingAssembly());

            Debug.Listeners.Add(new TextWriterTraceListener(System.Console.Out));

            m_bConnected = false;

            // TODO: Provide ways to configure serial port data
            rcPort.BaudRate = 2400;
            rcPort.DataBits = 8;
            rcPort.Parity = Parity.None;
            rcPort.StopBits = StopBits.One;

            rcPort.ReadTimeout = 1500;
            rcPort.WriteTimeout = 1500;

            wiimote.WiimoteChanged += new WiimoteChangedEventHandler(wiimote_WiimoteChanged);
        }
Exemplo n.º 32
0
        public Engine()
        {
            graphics = new GraphicsDeviceManager(this);
            balanceBoard = new Wiimote();
            graphics.PreferredBackBufferHeight = 720;
            graphics.PreferredBackBufferWidth = 1000;
            graphics.ToggleFullScreen();

            Content.RootDirectory = "Content";
            usingBalanceBoard = false;
            balanceBoards = new WiimoteCollection();
            //old
            //level = new PlayScreen(this,balanceBoard);
            level = new PlayScreen(this, balanceBoards);
            //old
            //menu = new Menu(this, balanceBoard);
            menu = new Menu(this, balanceBoards);
            saveScore = new SaveScore(this);
            this.Components.Add(menu);
            this.Components.Add(saveScore);
            this.Components.Add(level);
            status = 0;
        }
Exemplo n.º 33
0
        private static bool HIDDiscoverLoop(CancellationToken token)
        {
            var hids = HIDDeviceInfo.EnumerateDevices(token, MatchHID);

            foreach (HIDDeviceInfo hid in hids)
            {
                if (token.IsCancellationRequested)
                {
                    return(false);
                }
                Wiimote wiimote = null;
                lock (wiimotes) {
                    wiimote = wiimotes.Find(wm => wm.DevicePath == hid.DevicePath);
                }

                if (wiimote == null)
                {
                    if (autoConnect)
                    {
                        //FIXME: Handle BOTH Bluetooth and DolphinBarMode more gracefully.
                        WiimoteDeviceInfo wiimoteDevice = new WiimoteDeviceInfo(hid, true);                        // DolphinBarMode);
                        try {
                            Connect(wiimoteDevice);
                        }
                        catch (Exception ex) {
                            RaiseConnectionFailed(wiimoteDevice, ex);
                        }
                    }
                    else if (!RaiseDiscovered(null, hid))
                    {
                        return(false);
                    }
                }
            }
            token.Sleep(1000);
            return(true);
        }
Exemplo n.º 34
0
        public WiimoteControl(int id, Wiimote wiimote)
        {
            this.Wiimote = wiimote;
            this.Status = new WiimoteStatus();
            this.Status.ID = id;

            lastpoint = new CursorPos(0,0,0);

            this.screenBounds = Util.ScreenBounds;

            ulong touchStartID = (ulong)(id - 1) * 4 + 1; //This'll make sure the touch point IDs won't be the same. DuoTouch uses a span of 4 IDs.
            this.duoTouch = new DuoTouch(this.screenBounds, Properties.Settings.Default.pointer_positionSmoothing, touchStartID);
            this.keyMapper = new WiiKeyMapper(id);

            this.keyMapper.OnButtonDown += WiiButton_Down;
            this.keyMapper.OnButtonUp += WiiButton_Up;
            this.keyMapper.OnConfigChanged += WiiKeyMap_ConfigChanged;
            this.keyMapper.OnRumble += WiiKeyMap_OnRumble;

            this.inputSimulator = new InputSimulator();
            this.screenPositionCalculator = new ScreenPositionCalculator();
            this.useCustomCursor = Settings.Default.pointer_customCursor;
            if (this.useCustomCursor)
            {
                Color myColor = CursorColor.getColor(this.Status.ID);
                this.masterCursor = new D3DCursor((this.Status.ID-1)*2,myColor);
                this.slaveCursor = new D3DCursor((this.Status.ID-1)*2+1,myColor);

                masterCursor.Hide();
                slaveCursor.Hide();

                D3DCursorWindow.Current.AddCursor(masterCursor);
                D3DCursorWindow.Current.AddCursor(slaveCursor);

                this.keyMapper.SendConfigChangedEvt();
            }
        }
Exemplo n.º 35
0
        public WiimoteDevice()
        {
            _wiimote = new WiimoteLib.Wiimote();

            _buttonA = new ButtonDeviceComponent(this) { Name = "A" };
            _buttonB = new ButtonDeviceComponent(this) { Name = "B" };
            _buttonMinus = new ButtonDeviceComponent(this) { Name = "Minus" };
            _buttonPlus = new ButtonDeviceComponent(this) { Name = "Plus" };
            _buttonUp = new ButtonDeviceComponent(this) { Name = "Up" };
            _buttonDown = new ButtonDeviceComponent(this) { Name = "Down" };
            _buttonLeft = new ButtonDeviceComponent(this) { Name = "Left" };
            _buttonRight = new ButtonDeviceComponent(this) { Name = "Right" };
            _button1 = new ButtonDeviceComponent(this) { Name = "1" };
            _button2 = new ButtonDeviceComponent(this) { Name = "2" };
            _buttonHome = new ButtonDeviceComponent(this) { Name = "Home" };

            _classicUp = new ButtonDeviceComponent(this) { Name = "Classic Up" };
            _classicDown = new ButtonDeviceComponent(this) { Name = "Classic Down" };
            _classicLeft = new ButtonDeviceComponent(this) { Name = "Classic Left" };
            _classicRight = new ButtonDeviceComponent(this) { Name = "Classic Right" };

            _irComponent = new PositionalDeviceComponent(this) { Name = "IR" };
            _accelerometer = new AccelerometerDeviceComponent(this) { Name = "Accelerometer" };
        }
Exemplo n.º 36
0
 public static bool Two_Pressed(Wiimote wiimote)
 {
     return wiimote.WiimoteState.ButtonState.Two;
 }
Exemplo n.º 37
0
        public static List <Wiimote> GetConnectedWiimotes()
        {
            List <Wiimote> motes = new List <Wiimote>();

            int  index = 0;
            bool found = false;
            Guid guid;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while (HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                if (IntPtr.Size == 8)
                {
                    diDetail.cbSize = 8;
                }
                else
                {
                    diDetail.cbSize = 5;
                }

                // actually get the detail struct
                if (HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(index + " " + diDetail.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    SafeFileHandle mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if (HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if (attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            Debug.WriteLine("Found it!");
                            found = true;

                            Wiimote mote = new Wiimote();
                            mote.mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);
                            mote.mHandle = mHandle;

                            // start an async read operation on it
                            mote.BeginAsyncRead();

                            // read the calibration info from the controller
                            try
                            {
                                mote.ReadCalibration();
                            }
                            catch
                            {
                                // if we fail above, try the alternate HID writes
                                mote.mAltWriteMethod = true;
                                mote.ReadCalibration();
                            }


                            // force a status check to get the state of any extensions plugged in at startup
                            mote.GetStatus();

                            motes.Add(mote);
                        }
                        else
                        {
                            // otherwise this isn't the controller, so close up the file handle
                            mHandle.Close();
                        }
                    }
                }
                else
                {
                    // failed to get the detail struct
                    throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if (!found)
            {
                throw new Exception("Wiimote not found in HID device list.");
            }

            return(motes);
        }
Exemplo n.º 38
0
        private static bool BluetoothDiscoverLoop(CancellationToken token)
        {
            HashSet <BluetoothAddress> missingDevices = new HashSet <BluetoothAddress>(ConnectedAddresses);
            var       devices   = BluetoothDeviceInfo.EnumerateDevices(token, MatchBluetooth);
            Stopwatch watch     = Stopwatch.StartNew();
            bool      anyPaired = false;

            foreach (BluetoothDeviceInfo device in devices)
            {
                if (token.IsCancellationRequested)
                {
                    return(false);
                }
                Debug.WriteLine($"Took {watch.ElapsedMilliseconds}ms to enumerate bluetooth device");
                Wiimote wiimote = null;
                lock (wiimotes) {
                    wiimote = wiimotes.Find(wm => wm.Address == device.Address);
                }


                if (device.Connected)
                {
                    if (wiimote != null)
                    {
                        // Give Wiimote the updated Bluetooth device
                        wiimote.Device.Bluetooth = device;
                        missingDevices.Remove(device.Address);
                    }
                    else
                    {
                        HIDDeviceInfo hid = HIDDeviceInfo.GetDevice(device.Address);
                        // Drivers must not be installed yet, let's wait a bit
                        if (hid != null)
                        {
                            if (autoConnect)
                            {
                                WiimoteDeviceInfo wiimoteDevice = new WiimoteDeviceInfo(device, hid);
                                try {
                                    Connect(wiimoteDevice);
                                }
                                catch (Exception ex) {
                                    RaiseConnectionFailed(wiimoteDevice, ex);
                                }
                            }
                            else if (!RaiseDiscovered(device, hid))
                            {
                                return(false);
                            }
                        }

                        /*else if (device.PairDevice(token)) {
                         *      anyPaired = true;
                         * }
                         * else {
                         *      Debug.WriteLine("{device} pair failed!");
                         * }*/
                    }
                }
                else
                {
                    if (wiimote != null)
                    {
                        lock (wiimotes) {
                            wiimote.Dispose();
                            wiimotes.Remove(wiimote);
                            RaiseDisconnected(wiimote, DisconnectReason.ConnectionLost);
                        }
                    }
                    else if (device.IsDiscoverable() /*|| !device.Remembered*/)
                    {
                        if (pairOnDiscover)
                        {
                            if (device.PairDevice(token))
                            {
                                anyPaired = true;
                            }
                            else
                            {
                                Debug.WriteLine("{device} pair failed!");
                            }
                        }
                    }
                    else if (device.Remembered && unpairOnDisconnect)
                    {
                        device.RemoveDevice(token);
                    }
                }
                watch.Restart();
            }
            token.Sleep((anyPaired ? driverInstallDelay : 0) + 1000);
            return(true);
        }
Exemplo n.º 39
0
        private void LoadControls()
        {
            controlHandler = new ControlHandler();
            keyBindings = controlHandler.GetKeyBindings();
            originalKeybindings = controlHandler.GetKeyBindings();

            controlsEnabled = true;
            int posX = 0;
            int posY = 0;
            pointerPos = new Vector2(xPositions[posX], yPositions[posY]);

            if (controlHandler.GetNumberOfWiimotes() > 0)
                wm = controlHandler.GetWiimote(0);
        }
Exemplo n.º 40
0
 private static void RaiseOutOfRange(Wiimote wiimote)
 {
     Debug.WriteLine($"{wiimote} Out of Range");
     OutOfRange?.Invoke(null, new WiimoteRangeEventArgs(wiimote, false));
     wiimote.RaiseOutOfRange();
 }
Exemplo n.º 41
0
 private static void RaiseConnected(Wiimote wiimote)
 {
     Debug.WriteLine($"{wiimote} Connected");
     Connected?.Invoke(null, new WiimoteEventArgs(wiimote));
     UpdateTaskMode();
 }
Exemplo n.º 42
0
 private static void RaiseInRange(Wiimote wiimote)
 {
     Debug.WriteLine($"{wiimote} In Range");
     InRange?.Invoke(null, new WiimoteRangeEventArgs(wiimote, true));
     wiimote.RaiseInRange();
 }
Exemplo n.º 43
0
 public static bool Up_Pressed(Wiimote wiimote)
 {
     return wiimote.WiimoteState.ButtonState.Up;
 }
Exemplo n.º 44
0
 internal static void RaiseStateChanged(Wiimote wiimote)
 {
     //Debug.WriteLine($"{wiimote} State");
     StateChanged?.Invoke(null, new WiimoteStateEventArgs(wiimote));
 }
Exemplo n.º 45
0
 public static bool Z_Pressed(Wiimote wiimote)
 {
     return wiimote.WiimoteState.NunchukState.Z;
 }
Exemplo n.º 46
0
 private void pullNunchukJoystick(Wiimote wiimote)
 {
     nunchuk_X = (int)(wiimote.WiimoteState.NunchukState.Joystick.X * 100);
     nunchuk_Y = (int)(wiimote.WiimoteState.NunchukState.Joystick.Y * 100);
 }
Exemplo n.º 47
0
 internal static void RaiseExtensionChanged(Wiimote wiimote, ExtensionType type, bool inserted)
 {
     Debug.WriteLine($"{wiimote} Extension: {type} {(inserted ? "Inserted" : "Removed")}");
     ExtensionChanged?.Invoke(wiimote, new WiimoteExtensionEventArgs(wiimote, type, inserted));
 }
 public WiimoteInfo(Wiimote wm)
     : this()
 {
     mWiimote = wm;
 }
Exemplo n.º 49
0
        // Called by Wiimote

        internal static void RaiseWiimoteException(Wiimote wiimote, Exception ex)
        {
            Debug.WriteLine($"{wiimote} Exception: {ex}");
            WiimoteException?.Invoke(null, new WiimoteExceptionEventArgs(wiimote, ex));
        }