[#KINECTSDK] Kinect Missile Launcher (II): moving the rocket missile launcher


image

Buenas,

In the post yesterday explaining how to work with a HID device. Today we will see how to work with it, sending information to the device.

The first thing we must do is decide that library will use to work with a HID device. In my case I will use one that works pretty well, created by Florian Leitner-Fischer, and that can be downloaded from here.

In the post on the previous link, Florian explains the necessary groundwork about how works its creation. In this post we will do the following:

  • Connect to the device
  • Validate the connection
  • Send a message to move the Lance missiles USB

For this we follow the following steps

1. Create a console application

2. Add a reference to the USBHIDDRIVER library

image

3 Change the settings so that the application is X 86, rather than AnyCPU

4. Already we have our application list

Next we need to determine the VendorId and ProductId of our application. While we saw in the previous post, the following lines of code show us all HID devices you have connected

   1: var getAllDevices = new USBHIDDRIVER.USBInterface("_");

   2: getAllDevices.Connect();

   3: var devices = getAllDevices.getDeviceList();

   4: foreach (var device in devices)

   5: {

   6:     Console.WriteLine("device: " + device);

   7: }

When we run the application, we see this output in the console Windows

device: \\?\hid#vid_413c & pid_3012 # 7 & 39484631 & 0 & 0000 # {4d1e55b2-f16f-11cf-88cb-001111000030}

device: \\?\hid#vid_0a81 & pid_ff01 # 7 & b08aa68 & 0 & 0000 # {4d1e55b2-f16f-11cf-88cb-001111000030}

Assuming that our device is the second, the values be thus:

  • VendorId = vid_0a81
  • ProductId = pid_ff01

If for example move the missile down, we have to pass an array of bytes with 2 elements, zero and two. The code would be as follows:

   1: var usb = new USBHIDDRIVER.USBInterface(@"vid_0a81", @"pid_ff01");

   2: usb.Connect();

   3: var startCMD = new byte[2] {0, 2};

   4: // move down

   5: usb.UsbDevice.writeDataSimple(startCMD);

Well, if you you’ve downloaded the library of Florian, you see that the writeDataSimple() function does not exist. This is because Florian adds a double validation process to send always "clean" arrays to USB devices.

I am a person who lives to the limit and since I have no fear of the BSOD, create the following function to send messages to the device.

   1: public bool writeDataSimple(byte[] bDataToWrite)

   2: {

   3:     var success = false;

   4:     if (getConnectionState())

   5:     {

   6:         try

   7:         {

   8:             var myOutputReport = new OutputReport();

   9:             success = myOutputReport.Write(bDataToWrite, myUSB.HidHandle);

  10:         }

  11:         catch (AccessViolationException ex)

  12:         {

  13:             success = false;

  14:         }

  15:     }

  16:     return success;

  17: }

The previous function avoids validations on the buffer to send to the device and sends directly to the array of bytes. On many occasions this might return us a false or throw an exception not handled, but if we already know that the Lance missile works with a buffer of 2 bytes, because we have it easier.

Now, for this information I returned using the SimpleHIDWrite tool. The same when you select a device shows the number of items must have the input array.

image

In my case, and knowing that they were 2 bytes to implement buffer writing, because I began to try the method of trial/error and came to the following values:

  • 00, 00. Stop
  • 00, 01. Down
  • 00, 02. Up
  • 00, 04. Rotation schedule anti
  • 00, 08. Rotation schedule
  • 00, 10. It shoots missiles

With this data I already have almost everything to start. But of course, in the way I find that CodePlex is a project that already gives me interaction with the Lance missiles, with the Wii remote, etc. But of course, it doesn’t work the first and I have no place to write why. But they have an implementation of a class Rocket, the truth is that is very well.

So I replaced the component used for connection with the HID, I’ve done a little refactoring and I has been a class with the following structure.

image

Is now only a little work with KinectSDK and ready!

References:

 

 

Saludos @ Home

El Bruno

image image image

[#KINECTSDK] Kinect Missile Launcher (II): Moviendo el lanza misiles


image

Buenas.

En el post de ayer explicaba como trabajar con un dispositivo HID. Hoy veremos como trabajar con el mismo, enviando información al device.

Lo primero que tenemos que hacer es decidir que biblioteca utilizaremos para trabajar con un dispositivo HID. En mi caso utilizaré una que funciona bastante bien, creada por Florian Leitner-Fischer, y que se puede descargar desde aquí.

En el post del link anterior, Florian explica las bases necesarias sobre como funciona su creación. En este post haremos lo siguiente:

  • Conectarnos al dispositivo
  • Validar la conexión
  • Enviar un mensaje para mover el lanza misiles USB

Para esto seguimos los siguientes pasos

1. Crear una aplicación de Consola

2. Agregar una referencia a la biblioteca USBHIDDRIVER

image

3. Cambiamos la configuración para que la aplicación sea X86, en lugar de AnyCPU

4. Ya tenemos lista nuestra aplicación

Lo siguiente es determinar el VendorId y el ProductId de nuestra aplicación. Si bien lo vimos en el post anterior, las siguientes líneas de código nos muestran todos los dispositivos HID que tengamos conectados

   1: var getAllDevices = new USBHIDDRIVER.USBInterface("_");

   2: getAllDevices.Connect();

   3: var devices = getAllDevices.getDeviceList();

   4: foreach (var device in devices)

   5: {

   6:     Console.WriteLine("device: " + device);

   7: }

Cuando ejecutamos la aplicación, vemos este output en la consola de Windows

device: \\?\hid#vid_413c&pid_3012#7&39484631&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}

device: \\?\hid#vid_0a81&pid_ff01#7&b08aa68&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}

Asumiendo que nuestro dispositivo es el segundo, los valores quedarían así:

  • VendorId = vid_0a81
  • ProductId = pid_ff01

Si queremos por ejemplo mover el lanzamisiles hacia abajo, tenemos que pasar un array de bytes con 2 elementos, zero y dos. El código quedaría de la siguiente forma:

   1: var usb = new USBHIDDRIVER.USBInterface(@"vid_0a81", @"pid_ff01");

   2: usb.Connect();

   3: var startCMD = new byte[2] {0, 2};

   4: // move down

   5: usb.UsbDevice.writeDataSimple(startCMD);

Ahora bien, si te has bajado la biblioteca de Florian, verás que la funcion writeDataSimple() no existe. Esto es porque Florian agrega un proceso de doble validación para enviar siempre arrays “limpios” a los dispositivos USB.

Yo soy una persona que vive al límite y como no le tengo miedo al BSOD, cree la siguiente función para enviar mensajes al dispositivo.

   1: public bool writeDataSimple(byte[] bDataToWrite)

   2: {

   3:     var success = false;

   4:     if (getConnectionState())

   5:     {

   6:         try

   7:         {

   8:             var myOutputReport = new OutputReport();

   9:             success = myOutputReport.Write(bDataToWrite, myUSB.HidHandle);

  10:         }

  11:         catch (AccessViolationException ex)

  12:         {

  13:             success = false;

  14:         }

  15:     }

  16:     return success;

  17: }

La función anterior evita validaciones sobre el buffer a enviar al dispositivo y le envía directamente el array de bytes. En bastantes ocasiones esto nos puede retornar un false o lanzar una excepción no manejada, pero si ya sabemos que el lanza misiles funciona con un buffer de 2 bytes, pues lo tenemos más fácil.

Ahora bien, para conocer esta información he vuelto a utilizar la herramienta SimpleHIDWrite. La misma cuando se selecciona un dispositivo nos muestra la cantidad de elementos que tiene que tener el array de entrada.

image

En mi caso, y sabiendo que eran 2 los bytes a poner en el buffer de escritura, pues comencé a probar con el método de prueba/error y llegué a los siguientes valores:

  • 00, 00. Stop
  • 00, 01. Down
  • 00, 02. Up
  • 00, 04. Giro anti horario
  • 00, 08. Giro horario
  • 00, 10. Dispara misiles

Con estos datos ya tengo casi todo para comenzar. Pero claro, en el camino me encuentro con que en CodePlex hay un proyecto que ya me da interacción con el lanza misiles, con el WiiMote, etc. Pero claro, no funciona a la primera y no tengo lugar para escribir el porqué. Pero tienen una implementación de una clase Rocket, que la verdad es que está muy bien.

Así que he reemplazado el componente que se utiliza para la conexión con el HID, he hecho un poco de refactoring y me ha quedado una clase con la siguiente estructura.

image

Ahora solo queda un poco de trabajo con KinectSDK y listo !!!

 

Referencias:

 

 

Saludos @ Home

El Bruno

image image image

[# KINECTSDK] Kinect Missile Launcher (I): identifying the HID device


image

Buenas,

in the past 2 Weeks ago we’re playing with the Valentino to the Kinect Star Wars and I have to admit that my dwarf plays much better than me. Today while we were ordering a bit my toys, find my USB missile launchers and of course, the Valentino asked me that we reviewed.

Once I had installed the software is what di the Valentino and of course when I had to come and use the keyboard and the mouse was a bit of stick.

image

After months of playing with an iPad, a tablet with Windows 8 and with the Kinect, this keyboard and the mouse doesn’t like anything.

So as a good father that I am, I put hands to work in order to control the Lance missiles with the Kinect.

Item so I faced with considerable optimism, because a couple of years ago he had already created an extension to Team Build that threw a missile when a build failed, the programmer who "broke the build".

Before I had a question in mind that perhaps pulled me the project below:

Will have Windows 8 changed the way of detecting HID devices?

Luckily, no. This is important because usually these devices have no SDK, or anything like. Windows recognizes likewise that recognizes a keyboard or a mouse, and there should be a little reverse engineering in order to understand how the same.

A detail, if I’ve been able to understand is because it is not so complicated. So always try to explain, making an analogy with 2 buffers of data, one entrance and one exit for the USB port. Everytime we want a device to perform a specific action, we have to know the set of bytes that we need to "send". In the same way, we must learn to interpret the input data to "read" the information you send us the device.

Before starting to "read" and "send" information to the USB device, we must identify the same. This Windows makes it a simple way, and we as developers have 2 options

1 Spend 4 days playing Windows registry information

2 Use a tool like HID Device Info to know the details of our HID device

This tool can be downloaded from HID Page, an excellent site with much information to work with HID from.NET. The following image shows the data of devices that I have connected to my PC.

image

In the case of the Rocket Baby, the data that we should point out are:

  • Vendor Name
  • Product Name
  • VID
  • PID
  • Revision

This is important because then the class.NET that we use to interact with the device uses these data to identify it.

As well, I keep the sample code integrated with the Kinect for the next post and I’m going to control other things more with the Kinect Guiño

References:

Saludos @ Home

El Bruno

image image image

[#KINECTSDK] Kinect Missile Launcher (I): Identificando el dispositivo HID


image

Buenas

Hace 2 semanas que estamos jugando con el Valentino al Kinect Star Wars y tengo que admitir que mi enano juega mucho mejor que yo. Hoy mientras estábamos ordenando un poco mis juguetes, encontramos mi lanzamisiles USB y claro, el Valentino me pidió que lo probáramos.

Una vez que hube instalado el software se lo di al Valentino y claro, cuando tuve que acercarse y utilizar el teclado y el mouse se quedó un poco de palo.

image

Después de meses de jugar con un iPad, una tableta con Windows 8 y con el Kinect, esto del teclado y el mouse no le gusta nada.

Así que como buen padre que soy, me puse manos a la obra para poder controlar el lanza misiles con el Kinect.

Al tema lo encaré con bastante optimismo, porque ya hace un par de años había creado una extensión para Team Build que lanzaba un misil cuando una build fallaba, al programador que “rompió la build”.

Antes de comenzar tenía una pregunta en mente que tal vez me tiraba el proyecto abajo:

Windows 8 habrá cambiado la forma de detectar dispositivos HID?

Por suerte, no. Esto es importante porque por lo general estos dispositivos no tienen SDK, ni nada por el estilo. Windows los reconoce de la misma forma en la que se reconoce un teclado o un mouse, y a partir de allí hay que hacer un poco de ingeniería inversa para poder entender como funcionan los mismos.

Un detalle, si yo lo he podido entender es porque no es tan complicado. Siempre lo trato de explicar, haciendo una analogía con 2 buffers de datos, uno de entrada y otro de salida para el puerto USB. Cada vez que queremos que un dispositivo realice una acción específica, tenemos que conocer el set de bytes que tenemos que “enviar”. De la misma forma, tenemos que aprender a interpretar los datos de entrada para “leer” la información que nos envía el dispositivo.

Antes de comenzar a “leer” y “enviar” información al dispositivo USB, tenemos que identificar el mismo. Esto Windows lo hace una forma simple, y nosotros como developers tenemos 2 opciones

1. Pasarnos 4 días interpretando información del registro de Windows

2. Utilizar una herramienta como HID Device Info para conocer los datos de nuestro dispositivo HID

Esta herramienta se puede descargar desde HID Page, un excelente sitio con mucha información para trabajar con HID desde .Net. La siguiente imagen muestra los datos de los dispositivos que tengo conectado a mi PC.

image

En el caso del Rocket Baby, los datos que debemos apuntar son:

  • Vendor Name
  • Product Name
  • VID
  • PID
  • Revision

Esto es importante porque luego la clase .Net que utilizamos para interactuar con el dispositivo utiliza estos datos para identificar el mismo.

Pues bien, me guardo el ejemplo de código integrado con el Kinect para el próximo post y me voy a controlar otras cosillas más con el Kinect Guiño

 

Referencias:

 

Saludos @ Home

El Bruno

image image image

[#VS11] CodeMaid: Excellent extension with the 3 things that you always need


image

Buenas,

those who know me know that I am a staunch enemy of the mouse. Eye! This does not mean that he is a friend of the touch, but rather than attempt to always work with keyboard shortcuts.

So was that a couple of days ago I installed an extension in Visual Studio called CodeMaid, but it wasn’t until yesterday that I had the opportunity to use it. In fact, one of the keyboard shortcuts for keyboard "stepped" with another that I use and there I realized that had the installed extension.

I’ve been 2 days and the truth is that CodeMaid, I like. I like it because it is free, because it is open source, because it points to simple but effective things and because it works on the latest 4 updates for Visual Studio.

image

For example, has struck me how well it works the "Cleanup" option. This action is responsible for "clean" our code looking for details as

  • unused using statements
  • removes unnecessary whitespace
  • delete consecutive blank lines
  • etc.

So I’ve implemented a couple of files that I knew that they had room for improvement, and it has done really well.

Another option that I like is "Reorganize" a class. This option reorganizes the code of a class based on the specifications of StyleCop. If we then execute the analysis of StyleCop, we will see that it takes us much work above.

Note: recalls that in Avanade Spain , is highly probable that you touch pass a review with StyleCop as mandatory for the coding style rule.

Finally, an action which I think is great. The ability to switch between related files. As usual we usually do when edit WPF between the XAML and the XAML.cs

image

As well, only emphasize those 3 things although I know has more. CodeMaid has been worth for 2 days of work.

Meanwhile, I shall return to activate ReSharper and will work with it that gives me the same options Sonrisa and know him much better.

Download:
http://www.codemaid.net/

 

Saludos @ Home

El Bruno

image image image

[#VS11] CodeMaid: Excelente extensión con las 3 cosas que siempre te faltan


image

Buenas,

los que me conocen saben que soy un enemigo acérrimo del mouse. Ojo! eso no significa que sea un amigo de lo táctil, sino más bien que intento siempre trabajar con atajos de teclado.

Así fue que hace un par de días me instalé una extensión en Visual Studio llamada CodeMaid, pero no fue hasta ayer que tuve la oportunidad de utilizarla. En realidad, uno de los atajos de teclado de teclado “se pisó” con otro de los que utilizo y ahí me di cuenta de que tenía la extensión instalada.

Llevo 2 días y la verdad es que CodeMaid, me gusta. Me gusta porque es gratis, porque es de código abierto, porque apunta a cosas sencillas pero efectivas y porque funciona en las últimas 4 versiones de Visual Studio.

image

Por ejemplo, me ha llamado la atención lo bien que funciona la opción “Cleanup”. Esta acción se encarga de “limpiar” nuestro código buscando detalles como

  • sentencias using no utilizadas
  • elimina espacios en blanco no necesarios
  • elimina líneas en blanco consecutivas
  • etc.

Lo he ejecutado en un par de ficheros que sabía que tenían margen de mejora y lo ha hecho realmente bien.

Otra opción que me gusta es “Reorganize” una clase. Esta opción reorganiza el código de una clase basado en las especificaciones de StyleCop. Si luego ejecutamos el análisis de StyleCop, veremos que nos saca mucho trabajo de arriba.

Nota: Recuerda que en Avanade Spain, es altamente probable que te toque pasar una revisión con StyleCop como regla obligatoria para el estilo de código.

Finalmente, una acción que me parece genial. La capacidad de cambiar entre archivos relacionados. Lo más usual que solemos hacer cuando editamos WPF entre el XAML y el XAML.cs

image

Pues bien, solo remarcar esas 3 cosillas aunque sé que tiene más. CodeMaid ha merecido la pena para los 2 días de trabajo.

Mientras, volveré a activar ReSharper y trabajaré con el mismo que me da las mismas opciones Sonrisa y lo conozco bastante mejor.

Descarga:
http://www.codemaid.net/

Saludos @ Home

El Bruno

image image image

[#TFSERVICE] Team Foundation Service Whitepaper released by ALM Rangers


image

Buenas,

a few days ago, our friends the ALM Rangers have released an extremely useful guide:

Team Foundation Service Preview

Practical experience from the ALM Rangers

As its name suggests, it is a guide where reflected different experiences of working with TFService by the ALM Rangers.

If you still do not know, the ALM Ranger are a group of people whose specialty is ALM but "on the field", i.e., not talking about height 10000kms, but rather from a point of view quite practical, experience-based. This working group is composed of people from Microsoft, MVPs, partners, etc. It is a fairly diverse group and where there are several conflicting views, as the experiences and requirements of each individual job they are different.

  • As well, in this whitepaper (still in beta), we can find different topics such as:
  • What is Team Foundation Service?
  • Different ways to organize a distributed team
  • Why is TFService a service designed for organizations?
  • etc.

We are going there that is everything a little, as in apothecary. I have given you a look initial and effectively, there is everything a little. The good news is that what serves me I keep it and the rest,… as well as a one-eyed dog, will leave it aside Sonrisa

 

Saludos @ Home

El Bruno

image image image

[#TFSERVICE] Team Foundation Service Whitepaper released by ALM Rangers


image

Buenas,

hace unos días, nuestros amigos los ALM Rangers han liberado una guía extremadamente útil:

Team Foundation Service Preview

Practical experience from the ALM Rangers

Como su nombre lo indica, es una guía donde se recogen diferentes experiencias de trabajo con TFService por parte de los ALM Rangers.

Si todavía no los conoces, los ALM Ranger son un grupo de personas cuya especialidad es ALM pero “on the field”, es decir, no hablando a 10000kms de altura, sino más bien desde un punto de vista bastante práctico basado en la experiencia. Este grupo de trabajo está compuesto por personas de Microsoft, MVPs, partners, etc. Es un grupo bastante variado y donde hay bastantes opiniones encontradas, ya que las experiencias y requerimientos de trabajo de cada persona son diferentes entre sí.

  • Pues bien, en este whitepaper (still in beta), podemos encontrar diferentes temas como:
  • Qué es Team Foundation Service?
  • Diferentes formas de organizar un equipo de trabajo distribuido
  • Por qué TFService es un servicio pensado para organizaciones?
  • etc.

Vamos que hay de todo un poco, como en botica. Yo le he dado un vistazo inicial y efectivamente, hay de todo un poco. Lo bueno, es que lo que me sirve me lo guardo y lo demás, … pues bien como un perro tuerto, lo dejaré de lado Sonrisa

 

Saludos @ Home

El Bruno

image image image

[#WINDOWS8] HowTo: Enable Hyper-V in Windows8


image

Buenas,

While it is true that Microsoft was always a step (or two) behind in relation to virtualization technology, with Windows 8 has been a big change, and I think that it is for the better:

They have decided to unify the virtualization technology in operating systems for server and client in Hyper-v.

Often golazo! As well, now already we can begin using 64-bit virtual machines, without having to resort to VirtualBox, and finally we move away from the unmentionable VirtualPC.

Enable the Hyper-V role is very simple:

1 Press Win – W to access the Search Settings

2 Write "features"

3. In the form of Windows features, select "Hyper-V"

image

4. We expect the features to be installed.

5 Restart a couple of times (16 seconds clock!)

6. Now we can already launch Hyper-v. To do this press the Windows key, write "Hyper", and will have access to "Hyper-V Manager"

image

From here the Hyper-V for Windows 8 options are quite similar to other products, management of disks, virtual machines, etc.

However it is a great platform to work with virtual machines, which fortunately is already part of the operating system Risa

 

Saludos @ Home

El Bruno

image image image

[#WINDOWS8] HowTo: Habilitar Hyper-V en Windows8


image

Buenas,

si bien es cierto que Microsoft estaba siempre un paso (o dos) por detrás en lo referido a tecnología de virtualización, con Windows 8 han dado un gran cambio, y que creo que es para mejor:

Han decidido unificar la tecnología de virtualización en sistemas operativos de servidor y de cliente en Hyper-V.

Menudo golazo! Pues bien, ahora ya podemos comenzar a utilizar máquinas virtuales de 64 bits, sin tener que recurrir a VirtualBox, y por fin nos alejamos del innombrable VirtualPC.

La forma de habilitar el rol de Hyper-V es muy simple:

1. Presionamos Win-W para acceder a las búsquedas de Settings

2. Escribimos “features”

3. En el formulario de features de Windows, seleccionamos “Hyper-V”

image

4. Esperamos que se instalen las features.

5. Reiniciamos un par de veces (16 segundos de reloj!!!)

6. Ahora ya podemos lanzar Hyper-V. Para esto presionamos la tecla de Windows, escribimos “Hyper”, y tendremos acceso a “Hyper-V Manager”

image

A partir de aquí las opciones de Hyper-V para Windows 8 son bastante similares a otros productos, gestión de discos, de máquinas virtuales, etc.

Sin embargo es una gran plataforma para poder trabajar con máquinas virtuales que por suerte ya es parte del Sistema Operativo Risa

 

Saludos @ Home

El Bruno

image image image