Introducción.
Antes de publicar el código fuente del HelloWii, decidí hacer un poco de refactory obteniendo los siguientes productos y conclusiones.
- La clase WiiController que es un recubrimiento (wrapper) de la librería WiimoteLib y que simplifica su acceso. Está desarrollada en C#.
- Se utilizó el patrón observador (interfaz WiiControllerObserver) para permitirle a los interesados registrarse con el control para ser notificados de sus cambios de estado. De igual manera es posible obtener información de este por demanda.
- Si el observador es el mismo componente de UI (Form por ejemplo) es recomendable remover el registro del observador (unregisterObserver) antes de cerrar/destruír la componente/aplicación y evitar así excepciones generadas durante intentos de actualización mientras se cierra el componente.
- Se adaptó la aplicación de demostración para utilizar a un objeto WiiController como interfaz en lugar de utilizar a la librería directamente.
- Con el rediseño se esperaba evitar el problema del cross-threading pero no fue posible.
Como se mencionó no fue posible obviar la situación generada por la ejecución de instrucciones entre distintos hilos: la interfaz de usuario y la librería de acceso al wiimote que genera los problemas y explicación ya fueron expuestos. Sin embargo, revisando el foro de WiimoteProject encontré que es posible indicarle al componente visual de .NET que se encuentre accediendo a la librería (inclusive indirectamente a través de WiiController) que ignore este tipo de accesos ilegales entre hilo al evitando su revisión, esto se logra agregando la siguiente instrucción al constructor del componente.
CheckForIllegalCrossThreadCalls = false;
API de la clase WiiController.
La clase WiiController cuenta con los siguientes métodos.
- public void connect() – Creates the conexion with the wiimote.
- public void disconnect() – Makes the disconnection of the wiimote..
- public bool isConnected() – Checks if the wiimote has been already connected..
- public void refreshStatus(WiimoteState source) – Updates the references to the internal information of the wiimote.
- public void setReportType(WiimoteLib.InputReport type) – Selects the the type of information report that is expected from the controller.
- public float getBattery() – Gets the battery level of the wiimote.
- public String getId() – Gets the ID of the controller.
- public bool[] getAllButtonsStatus() – State of all buttons of the wiimote.
- public bool getButtonStatus(String name) – The status of a button on the wiimote.
- public bool[] getAllLedsStatus() – The status of all leds of the wiimote.
- public bool getLedStatus(int id) – The status of an individual led.
- public void setLeds(bool l1, bool l2, bool l3, bool l4) – Change the state of the wiimote’s leds.
- public void setLeds(bool[] leds) – Change the state of the wiimote’s leds.
- public void turnLed(int index, bool status) – Change the state of an individual led.
- public int[] getAcceleration() – Obtains the acceleration of the wiimote.
- public int getAcceleration(String axis) – Obtains the acceleration of the wiimote.
- public bool isRumbling() – Checks if the rumbling device is active.
- public void rumble(bool status) – Change the state of the wiimote’s rumbling device.
- public bool isObserver(WiiControllerObserver observer) – Checks if an observer is already registered.
- public bool registerObserver(WiiControllerObserver observer) – Register a new observer on the controller.
- public bool unregisterObserver(WiiControllerObserver observer) – Unregister an observer from the controller.
- public bool isExtensionConnected() – Checks if a wiimote’s extension is connected.
- public String getExtensionTypeConnected() – Get the type name of the connected extension.
- public int[] getNunchukAcceleration() – Get the acceleration of the nunchuk extension.
- public int getNunchukAcceleration(String axis) – Get the acceleration of the nunchuk extension.
- public bool[] getAllNunchukButtonsStatus() – Get the state of the buttons on the nunchuk extension.
- public bool getNunchukButtonStatus(String name) – Get the state of a button on the nunchuk extension.
- public int[] getNunchukJoystick() – Get the joystick state on the nunchuk extension.
- public int getNunchukJoystick(String axis) – Get the joystick value on a selected axis from the nunchuk extension.
Para mas información acerca del API de la clase y de su respectiva utilización consulte la documentación del código fuente inmersa en el archivo WiiController.cs y en WiiForm.cs (aplicación de demostración).
Registrar observadores.
Para registrarse como observador de eventos del wiimote la clase debe implementar la interfaz jimezam.wii.controller.WiiControllerObserver. Esta interfaz obliga a que se implementen los siguientes métodos.
- void update() – Invoked when the status of the wiimote is changed.
- void updateExtension() -Invoked when an extension is connected/disconnected to the wiimote.
La manipulación del registro de un observador se realiza utilizando los métodos registerObserver y unregisterObserver de la clase WiiController descritos anteriormente.
Enlaces.
- Fuentes y binarios de la clase WiiController y la aplicación de demostración HelloWii.
http://demo.jorgeivanmeza.com/NET/WiiController/
Genial tu post… y voy a proceder a revizar tu hellowii….
Tengo una pregunta….
Si puedo conocer los ID de los controles WII…..
Puedo conectar varios wiimote al computador…. y en c# utilizarlos por separado?
q el reconozca q boton de q control fue oprimido?
Saludos Jorge. Hace un buen tiempo que no he vuelto a utilizar esta librería (https://wiimotelib.codeplex.com/). Sin embargo revisando su documentación encuentro que incluye la clase WiimoteCollection para manejar a múltiples wiimotes.