code:
============================================================
rotary-encoder - a generic driver for GPIO connected devices
============================================================

:Author: Daniel Mack <daniel@caiaq.de>, Feb 2009

Function
--------

Rotary encoders are devices which are connected to the CPU or other
peripherals with two wires. The outputs are phase-shifted by 90 degrees
and by triggering on falling and rising edges, the turn direction can
be determined.

Some encoders have both outputs low in stable states, others also have
a stable state with both outputs high (half-period mode) and some have
a stable state in all steps (quarter-period mode).

The phase diagram of these two outputs look like this::

                  _____       _____       _____
                 |     |     |     |     |     |
  Channel A  ____|     |_____|     |_____|     |____

                 :  :  :  :  :  :  :  :  :  :  :  :
            __       _____       _____       _____
              |     |     |     |     |     |     |
  Channel B   |_____|     |_____|     |_____|     |__

                 :  :  :  :  :  :  :  :  :  :  :  :
  Event          a  b  c  d  a  b  c  d  a  b  c  d

                |<-------->|
	          one step

                |<-->|
	          one step (half-period mode)

                |<>|
	          one step (quarter-period mode)

For more information, please see
	https://en.wikipedia.org/wiki/Rotary_encoder

Events / state machine
----------------------

In half-period mode, state a) and c) above are used to determine the
rotational direction based on the last stable state. Events are reported in
states b) and d) given that the new stable state is different from the last
(i.e. the rotation was not reversed half-way).

Otherwise, the following apply:

a) Rising edge on channel A, channel B in low state
	This state is used to recognize a clockwise turn

b) Rising edge on channel B, channel A in high state
	When entering this state, the encoder is put into 'armed' state,
	meaning that there it has seen half the way of a one-step transition.

c) Falling edge on channel A, channel B in high state
	This state is used to recognize a counter-clockwise turn

d) Falling edge on channel B, channel A in low state
	Parking position. If the encoder enters this state, a full transition
	should have happened, unless it flipped back on half the way. The
	'armed' state tells us about that.

Platform requirements
---------------------

As there is no hardware dependent call in this driver, the platform it is
used with must support gpiolib. Another requirement is that IRQs must be
able to fire on both edges.

Board integration
-----------------

To use this driver in your system, register a platform_device with the
name 'rotary-encoder' and associate the IRQs and some specific platform
data with it. Because the driver uses generic device properties, this can
be done either via device tree, ACPI, or using static board files, like in
example below:

::

	/* board support file example */

	#include <linux/input.h>
	#include <linux/gpio/machine.h>
	#include <linux/property.h>

	#define GPIO_ROTARY_A 1
	#define GPIO_ROTARY_B 2

	static struct gpiod_lookup_table rotary_encoder_gpios = {
		.dev_id = "rotary-encoder.0",
		.table = {
			GPIO_LOOKUP_IDX("gpio-0",
					GPIO_ROTARY_A, NULL, 0, GPIO_ACTIVE_LOW),
			GPIO_LOOKUP_IDX("gpio-0",
					GPIO_ROTARY_B, NULL, 1, GPIO_ACTIVE_HIGH),
			{ },
		},
	};

	static const struct property_entry rotary_encoder_properties[] = {
		PROPERTY_ENTRY_U32("rotary-encoder,steps-per-period", 24),
		PROPERTY_ENTRY_U32("linux,axis",		      ABS_X),
		PROPERTY_ENTRY_U32("rotary-encoder,relative_axis",    0),
		{ },
	};

	static const struct software_node rotary_encoder_node = {
		.properties = rotary_encoder_properties,
	};

	static struct platform_device rotary_encoder_device = {
		.name		= "rotary-encoder",
		.id		= 0,
	};

	...

	gpiod_add_lookup_table(&rotary_encoder_gpios);
	device_add_software_node(&rotary_encoder_device.dev, &rotary_encoder_node);
	platform_device_register(&rotary_encoder_device);

	...

Please consult device tree binding documentation to see all properties
supported by the driver.


code:
.. include:: <isonum.txt>

=================
Sentelic Touchpad
=================

:Copyright: |copy| 2002-2011 Sentelic Corporation.

:Last update: Dec-07-2011

Finger Sensing Pad Intellimouse Mode (scrolling wheel, 4th and 5th buttons)
============================================================================

A) MSID 4: Scrolling wheel mode plus Forward page(4th button) and Backward
   page (5th button)

1. Set sample rate to 200;
2. Set sample rate to 200;
3. Set sample rate to 80;
4. Issuing the "Get device ID" command (0xF2) and waits for the response;
5. FSP will respond 0x04.

::

    Packet 1
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |Y|X|y|x|1|M|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 | | |B|F|W|W|W|W|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7 => Y overflow
	    Bit6 => X overflow
	    Bit5 => Y sign bit
	    Bit4 => X sign bit
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X Movement(9-bit 2's complement integers)
    Byte 3: Y Movement(9-bit 2's complement integers)
    Byte 4: Bit3~Bit0 => the scrolling wheel's movement since the last data report.
			valid values, -8 ~ +7
	    Bit4 => 1 = 4th mouse button is pressed, Forward one page.
		    0 = 4th mouse button is not pressed.
	    Bit5 => 1 = 5th mouse button is pressed, Backward one page.
		    0 = 5th mouse button is not pressed.

B) MSID 6: Horizontal and Vertical scrolling

- Set bit 1 in register 0x40 to 1

FSP replaces scrolling wheel's movement as 4 bits to show horizontal and
vertical scrolling.

::

    Packet 1
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |Y|X|y|x|1|M|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 | | |B|F|r|l|u|d|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7 => Y overflow
	    Bit6 => X overflow
	    Bit5 => Y sign bit
	    Bit4 => X sign bit
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X Movement(9-bit 2's complement integers)
    Byte 3: Y Movement(9-bit 2's complement integers)
    Byte 4: Bit0 => the Vertical scrolling movement downward.
	    Bit1 => the Vertical scrolling movement upward.
	    Bit2 => the Horizontal scrolling movement leftward.
	    Bit3 => the Horizontal scrolling movement rightward.
	    Bit4 => 1 = 4th mouse button is pressed, Forward one page.
		    0 = 4th mouse button is not pressed.
	    Bit5 => 1 = 5th mouse button is pressed, Backward one page.
		    0 = 5th mouse button is not pressed.

C) MSID 7

FSP uses 2 packets (8 Bytes) to represent Absolute Position.
so we have PACKET NUMBER to identify packets.

  If PACKET NUMBER is 0, the packet is Packet 1.
  If PACKET NUMBER is 1, the packet is Packet 2.
  Please count this number in program.

MSID6 special packet will be enable at the same time when enable MSID 7.

Absolute position for STL3886-G0
================================

1. Set bit 2 or 3 in register 0x40 to 1
2. Set bit 6 in register 0x40 to 1

::

    Packet 1 (ABSOLUTE POSITION)
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|V|1|1|M|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |r|l|d|u|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordination packet
		    => 10, Notify packet
	    Bit5 => valid bit
	    Bit4 => 1
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit4 => scroll up
	    Bit5 => scroll down
	    Bit6 => scroll left
	    Bit7 => scroll right

    Notify Packet for G0
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |1|0|0|1|1|M|R|L|  2  |C|C|C|C|C|C|C|C|  3 |M|M|M|M|M|M|M|M|  4 |0|0|0|0|0|0|0|0|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordination packet
		    => 10, Notify packet
	    Bit5 => 0
	    Bit4 => 1
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: Message Type => 0x5A (Enable/Disable status packet)
	    Mode Type => 0xA5 (Normal/Icon mode status)
    Byte 3: Message Type => 0x00 (Disabled)
			=> 0x01 (Enabled)
	    Mode Type    => 0x00 (Normal)
			=> 0x01 (Icon)
    Byte 4: Bit7~Bit0 => Don't Care

Absolute position for STL3888-Ax
================================

::

    Packet 1 (ABSOLUTE POSITION)
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|V|A|1|L|0|1|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |x|x|y|y|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordination packet
		    => 10, Notify packet
		    => 11, Normal data packet with on-pad click
	    Bit5 => Valid bit, 0 means that the coordinate is invalid or finger up.
		    When both fingers are up, the last two reports have zero valid
		    bit.
	    Bit4 => arc
	    Bit3 => 1
	    Bit2 => Left Button, 1 is pressed, 0 is released.
	    Bit1 => 0
	    Bit0 => 1
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit5~Bit4 => y1_g
	    Bit7~Bit6 => x1_g

    Packet 2 (ABSOLUTE POSITION)
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|V|A|1|R|1|0|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |x|x|y|y|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordinates packet
		    => 10, Notify packet
		    => 11, Normal data packet with on-pad click
	    Bit5 => Valid bit, 0 means that the coordinate is invalid or finger up.
		    When both fingers are up, the last two reports have zero valid
		    bit.
	    Bit4 => arc
	    Bit3 => 1
	    Bit2 => Right Button, 1 is pressed, 0 is released.
	    Bit1 => 1
	    Bit0 => 0
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit5~Bit4 => y2_g
	    Bit7~Bit6 => x2_g

    Notify Packet for STL3888-Ax
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |1|0|1|P|1|M|R|L|  2  |C|C|C|C|C|C|C|C|  3 |0|0|F|F|0|0|0|i|  4 |r|l|d|u|0|0|0|0|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordinates packet
		    => 10, Notify packet
		    => 11, Normal data packet with on-pad click
	    Bit5 => 1
	    Bit4 => when in absolute coordinates mode (valid when EN_PKT_GO is 1):
		    0: left button is generated by the on-pad command
		    1: left button is generated by the external button
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: Message Type => 0xB7 (Multi Finger, Multi Coordinate mode)
    Byte 3: Bit7~Bit6 => Don't care
	    Bit5~Bit4 => Number of fingers
	    Bit3~Bit1 => Reserved
	    Bit0 => 1: enter gesture mode; 0: leaving gesture mode
    Byte 4: Bit7 => scroll right button
	    Bit6 => scroll left button
	    Bit5 => scroll down button
	    Bit4 => scroll up button
		* Note that if gesture and additional button (Bit4~Bit7)
		happen at the same time, the button information will not
		be sent.
	    Bit3~Bit0 => Reserved

Sample sequence of Multi-finger, Multi-coordinate mode:

	notify packet (valid bit == 1), abs pkt 1, abs pkt 2, abs pkt 1,
	abs pkt 2, ..., notify packet (valid bit == 0)

Absolute position for STL3888-B0
================================

::

    Packet 1(ABSOLUTE POSITION)
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|V|F|1|0|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |r|l|u|d|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordinates packet
		    => 10, Notify packet
		    => 11, Normal data packet with on-pad click
	    Bit5 => Valid bit, 0 means that the coordinate is invalid or finger up.
		    When both fingers are up, the last two reports have zero valid
		    bit.
	    Bit4 => finger up/down information. 1: finger down, 0: finger up.
	    Bit3 => 1
	    Bit2 => finger index, 0 is the first finger, 1 is the second finger.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit4 => scroll down button
	    Bit5 => scroll up button
	    Bit6 => scroll left button
	    Bit7 => scroll right button

    Packet 2 (ABSOLUTE POSITION)
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|V|F|1|1|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |r|l|u|d|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordination packet
		    => 10, Notify packet
		    => 11, Normal data packet with on-pad click
	    Bit5 => Valid bit, 0 means that the coordinate is invalid or finger up.
		    When both fingers are up, the last two reports have zero valid
		    bit.
	    Bit4 => finger up/down information. 1: finger down, 0: finger up.
	    Bit3 => 1
	    Bit2 => finger index, 0 is the first finger, 1 is the second finger.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit4 => scroll down button
	    Bit5 => scroll up button
	    Bit6 => scroll left button
	    Bit7 => scroll right button

Notify Packet for STL3888-B0::

    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |1|0|1|P|1|M|R|L|  2  |C|C|C|C|C|C|C|C|  3 |0|0|F|F|0|0|0|i|  4 |r|l|u|d|0|0|0|0|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordination packet
		    => 10, Notify packet
		    => 11, Normal data packet with on-pad click
	    Bit5 => 1
	    Bit4 => when in absolute coordinates mode (valid when EN_PKT_GO is 1):
		    0: left button is generated by the on-pad command
		    1: left button is generated by the external button
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: Message Type => 0xB7 (Multi Finger, Multi Coordinate mode)
    Byte 3: Bit7~Bit6 => Don't care
	    Bit5~Bit4 => Number of fingers
	    Bit3~Bit1 => Reserved
	    Bit0 => 1: enter gesture mode; 0: leaving gesture mode
    Byte 4: Bit7 => scroll right button
	    Bit6 => scroll left button
	    Bit5 => scroll up button
	    Bit4 => scroll down button
		* Note that if gesture and additional button(Bit4~Bit7)
		happen at the same time, the button information will not
		be sent.
	    Bit3~Bit0 => Reserved

Sample sequence of Multi-finger, Multi-coordinate mode:

	notify packet (valid bit == 1), abs pkt 1, abs pkt 2, abs pkt 1,
	abs pkt 2, ..., notify packet (valid bit == 0)

Absolute position for STL3888-Cx and STL3888-Dx
===============================================

::

    Single Finger, Absolute Coordinate Mode (SFAC)
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|0|P|1|M|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |r|l|B|F|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordinates packet
		    => 10, Notify packet
	    Bit5 => Coordinate mode(always 0 in SFAC mode):
		    0: single-finger absolute coordinates (SFAC) mode
		    1: multi-finger, multiple coordinates (MFMC) mode
	    Bit4 => 0: The LEFT button is generated by on-pad command (OPC)
		    1: The LEFT button is generated by external button
		    Default is 1 even if the LEFT button is not pressed.
	    Bit3 => Always 1, as specified by PS/2 protocol.
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit4 => 4th mouse button(forward one page)
	    Bit5 => 5th mouse button(backward one page)
	    Bit6 => scroll left button
	    Bit7 => scroll right button

    Multi Finger, Multiple Coordinates Mode (MFMC):
    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |0|1|1|P|1|F|R|L|  2  |X|X|X|X|X|X|X|X|  3 |Y|Y|Y|Y|Y|Y|Y|Y|  4 |r|l|B|F|X|X|Y|Y|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordination packet
		    => 10, Notify packet
	    Bit5 => Coordinate mode (always 1 in MFMC mode):
		    0: single-finger absolute coordinates (SFAC) mode
		    1: multi-finger, multiple coordinates (MFMC) mode
	    Bit4 => 0: The LEFT button is generated by on-pad command (OPC)
		    1: The LEFT button is generated by external button
		    Default is 1 even if the LEFT button is not pressed.
	    Bit3 => Always 1, as specified by PS/2 protocol.
	    Bit2 => Finger index, 0 is the first finger, 1 is the second finger.
		    If bit 1 and 0 are all 1 and bit 4 is 0, the middle external
		    button is pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: X coordinate (xpos[9:2])
    Byte 3: Y coordinate (ypos[9:2])
    Byte 4: Bit1~Bit0 => Y coordinate (xpos[1:0])
	    Bit3~Bit2 => X coordinate (ypos[1:0])
	    Bit4 => 4th mouse button(forward one page)
	    Bit5 => 5th mouse button(backward one page)
	    Bit6 => scroll left button
	    Bit7 => scroll right button

When one of the two fingers is up, the device will output four consecutive
MFMC#0 report packets with zero X and Y to represent 1st finger is up or
four consecutive MFMC#1 report packets with zero X and Y to represent that
the 2nd finger is up.  On the other hand, if both fingers are up, the device
will output four consecutive single-finger, absolute coordinate(SFAC) packets
with zero X and Y.

Notify Packet for STL3888-Cx/Dx::

    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |1|0|0|P|1|M|R|L|  2  |C|C|C|C|C|C|C|C|  3 |0|0|F|F|0|0|0|i|  4 |r|l|u|d|0|0|0|0|
	  |---------------|     |---------------|    |---------------|    |---------------|

    Byte 1: Bit7~Bit6 => 00, Normal data packet
		    => 01, Absolute coordinates packet
		    => 10, Notify packet
	    Bit5 => Always 0
	    Bit4 => 0: The LEFT button is generated by on-pad command(OPC)
		    1: The LEFT button is generated by external button
		    Default is 1 even if the LEFT button is not pressed.
	    Bit3 => 1
	    Bit2 => Middle Button, 1 is pressed, 0 is not pressed.
	    Bit1 => Right Button, 1 is pressed, 0 is not pressed.
	    Bit0 => Left Button, 1 is pressed, 0 is not pressed.
    Byte 2: Message type:
	    0xba => gesture information
	    0xc0 => one finger hold-rotating gesture
    Byte 3: The first parameter for the received message:
	    0xba => gesture ID (refer to the 'Gesture ID' section)
	    0xc0 => region ID
    Byte 4: The second parameter for the received message:
	    0xba => N/A
	    0xc0 => finger up/down information

Sample sequence of Multi-finger, Multi-coordinates mode:

	notify packet (valid bit == 1), MFMC packet 1 (byte 1, bit 2 == 0),
	MFMC packet 2 (byte 1, bit 2 == 1), MFMC packet 1, MFMC packet 2,
	..., notify packet (valid bit == 0)

	That is, when the device is in MFMC mode, the host will receive
	interleaved absolute coordinate packets for each finger.

FSP Enable/Disable packet
=========================

::

    Bit 7 6 5 4 3 2 1 0       7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0      7 6 5 4 3 2 1 0
    BYTE  |---------------|BYTE |---------------|BYTE|---------------|BYTE|---------------|
      1   |Y|X|0|0|1|M|R|L|  2  |0|1|0|1|1|0|1|E|  3 | | | | | | | | |  4 | | | | | | | | |
	  |---------------|     |---------------|    |---------------|    |---------------|

    FSP will send out enable/disable packet when FSP receive PS/2 enable/disable
    command. Host will receive the packet which Middle, Right, Left button will
    be set. The packet only use byte 0 and byte 1 as a pattern of original packet.
    Ignore the other bytes of the packet.

    Byte 1: Bit7 => 0, Y overflow
	    Bit6 => 0, X overflow
	    Bit5 => 0, Y sign bit
	    Bit4 => 0, X sign bit
	    Bit3 => 1
	    Bit2 => 1, Middle Button
	    Bit1 => 1, Right Button
	    Bit0 => 1, Left Button
    Byte 2: Bit7~1 => (0101101b)
	    Bit0 => 1 = Enable
		    0 = Disable
    Byte 3: Don't care
    Byte 4: Don't care (MOUSE ID 3, 4)
    Byte 5~8: Don't care (Absolute packet)

PS/2 Command Set
================

FSP supports basic PS/2 commanding set and modes, refer to following URL for
details about PS/2 commands:

http://www.computer-engineering.org/ps2mouse/

Programming Sequence for Determining Packet Parsing Flow
========================================================

1. Identify FSP by reading device ID(0x00) and version(0x01) register

2. For FSP version < STL3888 Cx, determine number of buttons by reading
   the 'test mode status' (0x20) register::

	buttons = reg[0x20] & 0x30

	if buttons == 0x30 or buttons == 0x20:
		# two/four buttons
		Refer to 'Finger Sensing Pad PS/2 Mouse Intellimouse'
		section A for packet parsing detail(ignore byte 4, bit ~ 7)
	elif buttons == 0x10:
		# 6 buttons
		Refer to 'Finger Sensing Pad PS/2 Mouse Intellimouse'
		section B for packet parsing detail
	elif buttons == 0x00:
		# 6 buttons
		Refer to 'Finger Sensing Pad PS/2 Mouse Intellimouse'
		section A for packet parsing detail

3. For FSP version >= STL3888 Cx:
	Refer to 'Finger Sensing Pad PS/2 Mouse Intellimouse'
	section A for packet parsing detail (ignore byte 4, bit ~ 7)

Programming Sequence for Register Reading/Writing
=================================================

Register inversion requirement:

Following values needed to be inverted(the '~' operator in C) before being
sent to FSP::

	0xe8, 0xe9, 0xee, 0xf2, 0xf3 and 0xff.

Register swapping requirement:

Following values needed to have their higher 4 bits and lower 4 bits being
swapped before being sent to FSP::

	10, 20, 40, 60, 80, 100 and 200.

Register reading sequence:

	1. send 0xf3 PS/2 command to FSP;

	2. send 0x66 PS/2 command to FSP;

	3. send 0x88 PS/2 command to FSP;

	4. send 0xf3 PS/2 command to FSP;

	5. if the register address being to read is not required to be
	inverted(refer to the 'Register inversion requirement' section),
	goto step 6

	  a. send 0x68 PS/2 command to FSP;

	  b. send the inverted register address to FSP and goto step 8;

	6. if the register address being to read is not required to be
	swapped(refer to the 'Register swapping requirement' section),
	goto step 7

	  a. send 0xcc PS/2 command to FSP;

	  b. send the swapped register address to FSP and goto step 8;

	7. send 0x66 PS/2 command to FSP;

	  a. send the original register address to FSP and goto step 8;

	8. send 0xe9(status request) PS/2 command to FSP;

	9. the 4th byte of the response read from FSP should be the
	requested register value(?? indicates don't care byte)::

		host: 0xe9
		3888: 0xfa (??) (??) (val)

	* Note that since the Cx release, the hardware will return 1's
	  complement of the register value at the 3rd byte of status request
	  result::

		host: 0xe9
		3888: 0xfa (??) (~val) (val)

Register writing sequence:

	1. send 0xf3 PS/2 command to FSP;

	2. if the register address being to write is not required to be
	inverted(refer to the 'Register inversion requirement' section),
	goto step 3

	  a. send 0x74 PS/2 command to FSP;

	  b. send the inverted register address to FSP and goto step 5;

	3. if the register address being to write is not required to be
	swapped(refer to the 'Register swapping requirement' section),
	goto step 4

	  a. send 0x77 PS/2 command to FSP;

	  b. send the swapped register address to FSP and goto step 5;

	4. send 0x55 PS/2 command to FSP;

	  a. send the register address to FSP and goto step 5;

	5. send 0xf3 PS/2 command to FSP;

	6. if the register value being to write is not required to be
	inverted(refer to the 'Register inversion requirement' section),
	goto step 7

	  a. send 0x47 PS/2 command to FSP;

	  b. send the inverted register value to FSP and goto step 9;

	7. if the register value being to write is not required to be
	swapped(refer to the 'Register swapping requirement' section),
	goto step 8

	  a. send 0x44 PS/2 command to FSP;

	  b. send the swapped register value to FSP and goto step 9;

	8. send 0x33 PS/2 command to FSP;

	  a. send the register value to FSP;

	9. the register writing sequence is completed.

	* Since the Cx release, the hardware will return 1's
	  complement of the register value at the 3rd byte of status request
	  result. Host can optionally send another 0xe9 (status request) PS/2
	  command to FSP at the end of register writing to verify that the
	  register writing operation is successful (?? indicates don't care
	  byte)::

		host: 0xe9
		3888: 0xfa (??) (~val) (val)

Programming Sequence for Page Register Reading/Writing
======================================================

In order to overcome the limitation of maximum number of registers
supported, the hardware separates register into different groups called
'pages.' Each page is able to include up to 255 registers.

The default page after power up is 0x82; therefore, if one has to get
access to register 0x8301, one has to use following sequence to switch
to page 0x83, then start reading/writing from/to offset 0x01 by using
the register read/write sequence described in previous section.

Page register reading sequence:

	1. send 0xf3 PS/2 command to FSP;

	2. send 0x66 PS/2 command to FSP;

	3. send 0x88 PS/2 command to FSP;

	4. send 0xf3 PS/2 command to FSP;

	5. send 0x83 PS/2 command to FSP;

	6. send 0x88 PS/2 command to FSP;

	7. send 0xe9(status request) PS/2 command to FSP;

	8. the response read from FSP should be the requested page value.

Page register writing sequence:

	1. send 0xf3 PS/2 command to FSP;

	2. send 0x38 PS/2 command to FSP;

	3. send 0x88 PS/2 command to FSP;

	4. send 0xf3 PS/2 command to FSP;

	5. if the page address being written is not required to be
	inverted(refer to the 'Register inversion requirement' section),
	goto step 6

	  a. send 0x47 PS/2 command to FSP;

	  b. send the inverted page address to FSP and goto step 9;

	6. if the page address being written is not required to be
	swapped(refer to the 'Register swapping requirement' section),
	goto step 7

	  a. send 0x44 PS/2 command to FSP;

	  b. send the swapped page address to FSP and goto step 9;

	7. send 0x33 PS/2 command to FSP;

	8. send the page address to FSP;

	9. the page register writing sequence is completed.

Gesture ID
==========

Unlike other devices which sends multiple fingers' coordinates to host,
FSP processes multiple fingers' coordinates internally and convert them
into a 8 bits integer, namely 'Gesture ID.'  Following is a list of
supported gesture IDs:

	======= ==================================
	ID	Description
	======= ==================================
	0x86	2 finger straight up
	0x82	2 finger straight down
	0x80	2 finger straight right
	0x84	2 finger straight left
	0x8f	2 finger zoom in
	0x8b	2 finger zoom out
	0xc0	2 finger curve, counter clockwise
	0xc4	2 finger curve, clockwise
	0x2e	3 finger straight up
	0x2a	3 finger straight down
	0x28	3 finger straight right
	0x2c	3 finger straight left
	0x38	palm
	======= ==================================

Register Listing
================

Registers are represented in 16 bits values. The higher 8 bits represent
the page address and the lower 8 bits represent the relative offset within
that particular page.  Refer to the 'Programming Sequence for Page Register
Reading/Writing' section for instructions on how to change current page
address::

 offset	width		default	r/w	name
 0x8200	bit7~bit0	0x01	RO	device ID

 0x8201	bit7~bit0		RW	version ID
					0xc1: STL3888 Ax
					0xd0 ~ 0xd2: STL3888 Bx
					0xe0 ~ 0xe1: STL3888 Cx
					0xe2 ~ 0xe3: STL3888 Dx

 0x8202	bit7~bit0	0x01	RO	vendor ID

 0x8203	bit7~bit0	0x01	RO	product ID

 0x8204	bit3~bit0	0x01	RW	revision ID

 0x820b					test mode status 1
	bit3		1	RO	0: rotate 180 degree
					1: no rotation
					*only supported by H/W prior to Cx

 0x820f					register file page control
	bit2		0	RW	1: rotate 180 degree
					0: no rotation
					*supported since Cx

	bit0		0	RW	1 to enable page 1 register files
					*only supported by H/W prior to Cx

 0x8210				RW	system control 1
	bit0		1	RW	Reserved, must be 1
	bit1		0	RW	Reserved, must be 0
	bit4		0	RW	Reserved, must be 0
	bit5		1	RW	register clock gating enable
					0: read only, 1: read/write enable
	(Note that following registers does not require clock gating being
	enabled prior to write: 05 06 07 08 09 0c 0f 10 11 12 16 17 18 23 2e
	40 41 42 43.  In addition to that, this bit must be 1 when gesture
	mode is enabled)

 0x8220					test mode status
	bit5~bit4		RO	number of buttons
					11 => 2, lbtn/rbtn
					10 => 4, lbtn/rbtn/scru/scrd
					01 => 6, lbtn/rbtn/scru/scrd/scrl/scrr
					00 => 6, lbtn/rbtn/scru/scrd/fbtn/bbtn
					*only supported by H/W prior to Cx

 0x8231				RW	on-pad command detection
	bit7		0	RW	on-pad command left button down tag
					enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

 0x8234				RW	on-pad command control 5
	bit4~bit0	0x05	RW	XLO in 0s/4/1, so 03h = 0010.1b = 2.5
	(Note that position unit is in 0.5 scanline)
					*only supported by H/W prior to Cx

	bit7		0	RW	on-pad tap zone enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

 0x8235				RW	on-pad command control 6
	bit4~bit0	0x1d	RW	XHI in 0s/4/1, so 19h = 1100.1b = 12.5
	(Note that position unit is in 0.5 scanline)
					*only supported by H/W prior to Cx

 0x8236				RW	on-pad command control 7
	bit4~bit0	0x04	RW	YLO in 0s/4/1, so 03h = 0010.1b = 2.5
	(Note that position unit is in 0.5 scanline)
					*only supported by H/W prior to Cx

 0x8237				RW	on-pad command control 8
	bit4~bit0	0x13	RW	YHI in 0s/4/1, so 11h = 1000.1b = 8.5
	(Note that position unit is in 0.5 scanline)
					*only supported by H/W prior to Cx

 0x8240				RW	system control 5
	bit1		0	RW	FSP Intellimouse mode enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

	bit2		0	RW	movement + abs. coordinate mode enable
					0: disable, 1: enable
	(Note that this function has the functionality of bit 1 even when
	bit 1 is not set. However, the format is different from that of bit 1.
	In addition, when bit 1 and bit 2 are set at the same time, bit 2 will
	override bit 1.)
					*only supported by H/W prior to Cx

	bit3		0	RW	abs. coordinate only mode enable
					0: disable, 1: enable
	(Note that this function has the functionality of bit 1 even when
	bit 1 is not set. However, the format is different from that of bit 1.
	In addition, when bit 1, bit 2 and bit 3 are set at the same time,
	bit 3 will override bit 1 and 2.)
					*only supported by H/W prior to Cx

	bit5		0	RW	auto switch enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

	bit6		0	RW	G0 abs. + notify packet format enable
					0: disable, 1: enable
	(Note that the absolute/relative coordinate output still depends on
	bit 2 and 3.  That is, if any of those bit is 1, host will receive
	absolute coordinates; otherwise, host only receives packets with
	relative coordinate.)
					*only supported by H/W prior to Cx

	bit7		0	RW	EN_PS2_F2: PS/2 gesture mode 2nd
					finger packet enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

 0x8243				RW	on-pad control
	bit0		0	RW	on-pad control enable
					0: disable, 1: enable
	(Note that if this bit is cleared, bit 3/5 will be ineffective)
					*only supported by H/W prior to Cx

	bit3		0	RW	on-pad fix vertical scrolling enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

	bit5		0	RW	on-pad fix horizontal scrolling enable
					0: disable, 1: enable
					*only supported by H/W prior to Cx

 0x8290				RW	software control register 1
	bit0		0	RW	absolute coordination mode
					0: disable, 1: enable
					*supported since Cx

	bit1		0	RW	gesture ID output
					0: disable, 1: enable
					*supported since Cx

	bit2		0	RW	two fingers' coordinates output
					0: disable, 1: enable
					*supported since Cx

	bit3		0	RW	finger up one packet output
					0: disable, 1: enable
					*supported since Cx

	bit4		0	RW	absolute coordination continuous mode
					0: disable, 1: enable
					*supported since Cx

	bit6~bit5	00	RW	gesture group selection
					00: basic
					01: suite
					10: suite pro
					11: advanced
					*supported since Cx

	bit7		0	RW	Bx packet output compatible mode
					0: disable, 1: enable
					*supported since Cx
					*supported since Cx

 0x833d				RW	on-pad command control 1
	bit7		1	RW	on-pad command detection enable
					0: disable, 1: enable
					*supported since Cx

 0x833e				RW	on-pad command detection
	bit7		0	RW	on-pad command left button down tag
					enable. Works only in H/W based PS/2
					data packet mode.
					0: disable, 1: enable
					*supported since Cx

repo_name: angery/linux


code:
===========================
Walkera WK-0701 transmitter
===========================

Walkera WK-0701 transmitter is supplied with a ready to fly Walkera
helicopters such as HM36, HM37, HM60. The walkera0701 module enables to use
this transmitter as joystick

Devel homepage and download:
http://zub.fei.tuke.sk/walkera-wk0701/

or use cogito:
cg-clone http://zub.fei.tuke.sk/GIT/walkera0701-joystick

Connecting to PC
================

At back side of transmitter S-video connector can be found. Modulation
pulses from processor to HF part can be found at pin 2 of this connector,
pin 3 is GND. Between pin 3 and CPU 5k6 resistor can be found. To get
modulation pulses to PC, signal pulses must be amplified.

Cable: (walkera TX to parport)

Walkera WK-0701 TX S-VIDEO connector::

 (back side of TX)
     __   __              S-video:                                  canon25
    /  |_|  \             pin 2 (signal)              NPN           parport
   / O 4 3 O \            pin 3 (GND)        LED        ________________  10 ACK
  ( O 2   1 O )                                         | C
   \   ___   /      2 ________________________|\|_____|/
    | [___] |                                 |/|   B |\
     -------        3 __________________________________|________________ 25 GND
                                                          E

I use green LED and BC109 NPN transistor.

Software
========

Build kernel with walkera0701 module. Module walkera0701 need exclusive
access to parport, modules like lp must be unloaded before loading
walkera0701 module, check dmesg for error messages. Connect TX to PC by
cable and run jstest /dev/input/js0 to see values from TX. If no value can
be changed by TX "joystick", check output from /proc/interrupts. Value for
(usually irq7) parport must increase if TX is on.

Technical details
=================

Driver use interrupt from parport ACK input bit to measure pulse length
using hrtimers.

Frame format:
Based on walkera WK-0701 PCM Format description by Shaul Eizikovich.
(downloaded from http://www.smartpropoplus.com/Docs/Walkera_Wk-0701_PCM.pdf)

Signal pulses
-------------

::

                     (ANALOG)
      SYNC      BIN   OCT
    +---------+      +------+
    |         |      |      |
  --+         +------+      +---

Frame
-----

::

 SYNC , BIN1, OCT1, BIN2, OCT2 ... BIN24, OCT24, BIN25, next frame SYNC ..

pulse length
------------

::

   Binary values:		Analog octal values:

   288 uS Binary 0		318 uS       000
   438 uS Binary 1		398 uS       001
				478 uS       010
				558 uS       011
				638 uS       100
  1306 uS SYNC			718 uS       101
				798 uS       110
				878 uS       111

24 bin+oct values + 1 bin value = 24*4+1 bits  = 97 bits

(Warning, pulses on ACK are inverted by transistor, irq is raised up on sync
to bin change or octal value to bin change).

Binary data representations
---------------------------

One binary and octal value can be grouped to nibble. 24 nibbles + one binary
values can be sampled between sync pulses.

Values for first four channels (analog joystick values) can be found in
first 10 nibbles. Analog value is represented by one sign bit and 9 bit
absolute binary value. (10 bits per channel). Next nibble is checksum for
first ten nibbles.

Next nibbles 12 .. 21 represents four channels (not all channels can be
directly controlled from TX). Binary representations are the same as in first
four channels. In nibbles 22 and 23 is a special magic number. Nibble 24 is
checksum for nibbles 12..23.

After last octal value for nibble 24 and next sync pulse one additional
binary value can be sampled. This bit and magic number is not used in
software driver. Some details about this magic numbers can be found in
Walkera_Wk-0701_PCM.pdf.

Checksum calculation
--------------------

Summary of octal values in nibbles must be same as octal value in checksum
nibble (only first 3 bits are used). Binary value for checksum nibble is
calculated by sum of binary values in checked nibbles + sum of octal values
in checked nibbles divided by 8. Only bit 0 of this sum is used.


code:
=======================================================
xpad - Linux USB driver for Xbox compatible controllers
=======================================================

This driver exposes all first-party and third-party Xbox compatible
controllers. It has a long history and has enjoyed considerable usage
as Window's xinput library caused most PC games to focus on Xbox
controller compatibility.

Due to backwards compatibility all buttons are reported as digital.
This only effects Original Xbox controllers. All later controller models
have only digital face buttons.

Rumble is supported on some models of Xbox 360 controllers but not of
Original Xbox controllers nor on Xbox One controllers. As of writing
the Xbox One's rumble protocol has not been reverse engineered but in
the future could be supported.

Notes
=====

The number of buttons/axes reported varies based on 3 things:

- if you are using a known controller
- if you are using a known dance pad
- if using an unknown device (one not listed below), what you set in the
  module configuration for "Map D-PAD to buttons rather than axes for unknown
  pads" (module option dpad_to_buttons)

If you set dpad_to_buttons to N and you are using an unknown device
the driver will map the directional pad to axes (X/Y).
If you said Y it will map the d-pad to buttons, which is needed for dance
style games to function correctly. The default is Y.

dpad_to_buttons has no effect for known pads. A erroneous commit message
claimed dpad_to_buttons could be used to force behavior on known devices.
This is not true. Both dpad_to_buttons and triggers_to_buttons only affect
unknown controllers.

Normal Controllers
------------------

With a normal controller, the directional pad is mapped to its own X/Y axes.
The jstest-program from joystick-1.2.15 (jstest-version 2.1.0) will report 8
axes and 10 buttons.

All 8 axes work, though they all have the same range (-32768..32767)
and the zero-setting is not correct for the triggers (I don't know if that
is some limitation of jstest, since the input device setup should be fine. I
didn't have a look at jstest itself yet).

All of the 10 buttons work (in digital mode). The six buttons on the
right side (A, B, X, Y, black, white) are said to be "analog" and
report their values as 8 bit unsigned, not sure what this is good for.

I tested the controller with quake3, and configuration and
in game functionality were OK. However, I find it rather difficult to
play first person shooters with a pad. Your mileage may vary.

Xbox Dance Pads
---------------

When using a known dance pad, jstest will report 6 axes and 14 buttons.

For dance style pads (like the redoctane pad) several changes
have been made.  The old driver would map the d-pad to axes, resulting
in the driver being unable to report when the user was pressing both
left+right or up+down, making DDR style games unplayable.

Known dance pads automatically map the d-pad to buttons and will work
correctly out of the box.

If your dance pad is recognized by the driver but is using axes instead
of buttons, see section 0.3 - Unknown Controllers

I've tested this with Stepmania, and it works quite well.

Unknown Controllers
-------------------

If you have an unknown xbox controller, it should work just fine with
the default settings.

HOWEVER if you have an unknown dance pad not listed below, it will not
work UNLESS you set "dpad_to_buttons" to 1 in the module configuration.

USB adapters
============

All generations of Xbox controllers speak USB over the wire.

- Original Xbox controllers use a proprietary connector and require adapters.
- Wireless Xbox 360 controllers require a 'Xbox 360 Wireless Gaming Receiver
  for Windows'
- Wired Xbox 360 controllers use standard USB connectors.
- Xbox One controllers can be wireless but speak Wi-Fi Direct and are not
  yet supported.
- Xbox One controllers can be wired and use standard Micro-USB connectors.

Original Xbox USB adapters
--------------------------

Using this driver with an Original Xbox controller requires an
adapter cable to break out the proprietary connector's pins to USB.
You can buy these online fairly cheap, or build your own.

Such a cable is pretty easy to build. The Controller itself is a USB
compound device (a hub with three ports for two expansion slots and
the controller device) with the only difference in a nonstandard connector
(5 pins vs. 4 on standard USB 1.0 connectors).

You just need to solder a USB connector onto the cable and keep the
yellow wire unconnected. The other pins have the same order on both
connectors so there is no magic to it. Detailed info on these matters
can be found on the net ([1]_, [2]_, [3]_).

Thanks to the trip splitter found on the cable you don't even need to cut the
original one. You can buy an extension cable and cut that instead. That way,
you can still use the controller with your X-Box, if you have one ;)

Driver Installation
===================

Once you have the adapter cable, if needed, and the controller connected
the xpad module should be auto loaded. To confirm you can cat
/sys/kernel/debug/usb/devices. There should be an entry like those:

.. code-block:: none
   :caption: dump from InterAct PowerPad Pro (Germany)

    T:  Bus=01 Lev=03 Prnt=04 Port=00 Cnt=01 Dev#=  5 Spd=12  MxCh= 0
    D:  Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=32 #Cfgs=  1
    P:  Vendor=05fd ProdID=107a Rev= 1.00
    C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
    I:  If#= 0 Alt= 0 #EPs= 2 Cls=58(unk. ) Sub=42 Prot=00 Driver=(none)
    E:  Ad=81(I) Atr=03(Int.) MxPS=  32 Ivl= 10ms
    E:  Ad=02(O) Atr=03(Int.) MxPS=  32 Ivl= 10ms

.. code-block:: none
   :caption: dump from Redoctane Xbox Dance Pad (US)

    T:  Bus=01 Lev=02 Prnt=09 Port=00 Cnt=01 Dev#= 10 Spd=12  MxCh= 0
    D:  Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
    P:  Vendor=0c12 ProdID=8809 Rev= 0.01
    S:  Product=XBOX DDR
    C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
    I:  If#= 0 Alt= 0 #EPs= 2 Cls=58(unk. ) Sub=42 Prot=00 Driver=xpad
    E:  Ad=82(I) Atr=03(Int.) MxPS=  32 Ivl=4ms
    E:  Ad=02(O) Atr=03(Int.) MxPS=  32 Ivl=4ms

Supported Controllers
=====================

For a full list of supported controllers and associated vendor and product
IDs see the xpad_device[] array\ [4]_.

As of the historic version 0.0.6 (2006-10-10) the following devices
were supported::

 original Microsoft XBOX controller (US),    vendor=0x045e, product=0x0202
 smaller  Microsoft XBOX controller (US),    vendor=0x045e, product=0x0289
 original Microsoft XBOX controller (Japan), vendor=0x045e, product=0x0285
 InterAct PowerPad Pro (Germany),            vendor=0x05fd, product=0x107a
 RedOctane Xbox Dance Pad (US),              vendor=0x0c12, product=0x8809

Unrecognized models of Xbox controllers should function as Generic
Xbox controllers. Unrecognized Dance Pad controllers require setting
the module option 'dpad_to_buttons'.

If you have an unrecognized controller please see 0.3 - Unknown Controllers

Manual Testing
==============

To test this driver's functionality you may use 'jstest'.

For example::

    > modprobe xpad
    > modprobe joydev
    > jstest /dev/js0

If you're using a normal controller, there should be a single line showing
18 inputs (8 axes, 10 buttons), and its values should change if you move
the sticks and push the buttons.  If you're using a dance pad, it should
show 20 inputs (6 axes, 14 buttons).

It works? Voila, you're done ;)

Thanks
======

I have to thank ITO Takayuki for the detailed info on his site
    http://euc.jp/periphs/xbox-controller.ja.html.

His useful info and both the usb-skeleton as well as the iforce input driver
(Greg Kroah-Hartmann; Vojtech Pavlik) helped a lot in rapid prototyping
the basic functionality.

References
==========

.. [1] http://euc.jp/periphs/xbox-controller.ja.html (ITO Takayuki)
.. [2] http://xpad.xbox-scene.com/
.. [3] http://www.markosweb.com/www/xboxhackz.com/
.. [4] https://elixir.bootlin.com/linux/latest/ident/xpad_device

Historic Edits
==============

2002-07-16 - Marko Friedemann <mfr@bmx-chemnitz.de>
 - original doc

2005-03-19 - Dominic Cerquetti <binary1230@yahoo.com>
 - added stuff for dance pads, new d-pad->axes mappings

Later changes may be viewed with
'git log --follow Documentation/input/devices/xpad.rst'


code:
===============================================
Driver documentation for yealink usb-p1k phones
===============================================

Status
======

The p1k is a relatively cheap usb 1.1 phone with:

  - keyboard		full support, yealink.ko / input event API
  - LCD			full support, yealink.ko / sysfs API
  - LED			full support, yealink.ko / sysfs API
  - dialtone		full support, yealink.ko / sysfs API
  - ringtone		full support, yealink.ko / sysfs API
  - audio playback   	full support, snd_usb_audio.ko / alsa API
  - audio record     	full support, snd_usb_audio.ko / alsa API

For vendor documentation see http://www.yealink.com

keyboard features
=================

The current mapping in the kernel is provided by the map_p1k_to_key
function::

   Physical USB-P1K button layout	input events

              up			     up
        IN           OUT		left,	right
             down			    down

      pickup   C    hangup		enter, backspace, escape
        1      2      3			1, 2, 3
        4      5      6			4, 5, 6,
        7      8      9			7, 8, 9,
        *      0      #			*, 0, #,

The "up" and "down" keys, are symbolised by arrows on the button.
The "pickup" and "hangup" keys are symbolised by a green and red phone
on the button.

LCD features
============

The LCD is divided and organised as a 3 line display::

    |[]   [][]   [][]   [][]   in   |[][]
    |[] M [][] D [][] : [][]   out  |[][]
                              store

    NEW REP         SU MO TU WE TH FR SA

    [] [] [] [] [] [] [] [] [] [] [] []
    [] [] [] [] [] [] [] [] [] [] [] []

  Line 1  Format (see below)	: 18.e8.M8.88...188
	  Icon names		:   M  D  :  IN OUT STORE
  Line 2  Format		: .........
	  Icon name		: NEW REP SU MO TU WE TH FR SA
  Line 3  Format		: 888888888888

Format description:
  From a userspace perspective the world is separated into "digits" and "icons".
  A digit can have a character set, an icon can only be ON or OFF.

  Format specifier::

    '8' :  Generic 7 segment digit with individual addressable segments

    Reduced capability 7 segment digit, when segments are hard wired together.
    '1' : 2 segments digit only able to produce a 1.
    'e' : Most significant day of the month digit,
          able to produce at least 1 2 3.
    'M' : Most significant minute digit,
          able to produce at least 0 1 2 3 4 5.

    Icons or pictograms:
    '.' : For example like AM, PM, SU, a 'dot' .. or other single segment
	  elements.

Driver usage
============

For userland the following interfaces are available using the sysfs interface::

  /sys/.../
           line1	Read/Write, lcd line1
           line2	Read/Write, lcd line2
           line3	Read/Write, lcd line3

	   get_icons    Read, returns a set of available icons.
	   hide_icon    Write, hide the element by writing the icon name.
	   show_icon    Write, display the element by writing the icon name.

	   map_seg7	Read/Write, the 7 segments char set, common for all
			yealink phones. (see map_to_7segment.h)

	   ringtone	Write, upload binary representation of a ringtone,
			see yealink.c. status EXPERIMENTAL due to potential
			races between async. and sync usb calls.

lineX
~~~~~

Reading /sys/../lineX will return the format string with its current value.

  Example::

    cat ./line3
    888888888888
    Linux Rocks!

Writing to /sys/../lineX will set the corresponding LCD line.

 - Excess characters are ignored.
 - If less characters are written than allowed, the remaining digits are
   unchanged.
 - The tab '\t'and '\n' char does not overwrite the original content.
 - Writing a space to an icon will always hide its content.

  Example::

    date +"%m.%e.%k:%M"  | sed 's/^0/ /' > ./line1

  Will update the LCD with the current date & time.

get_icons
~~~~~~~~~

Reading will return all available icon names and its current settings::

  cat ./get_icons
  on M
  on D
  on :
     IN
     OUT
     STORE
     NEW
     REP
     SU
     MO
     TU
     WE
     TH
     FR
     SA
     LED
     DIALTONE
     RINGTONE

show/hide icons
~~~~~~~~~~~~~~~

Writing to these files will update the state of the icon.
Only one icon at a time can be updated.

If an icon is also on a ./lineX the corresponding value is
updated with the first letter of the icon.

  Example - light up the store icon::

    echo -n "STORE" > ./show_icon

    cat ./line1
    18.e8.M8.88...188
		  S

  Example - sound the ringtone for 10 seconds::

    echo -n RINGTONE > /sys/..../show_icon
    sleep 10
    echo -n RINGTONE > /sys/..../hide_icon

Sound features
==============

Sound is supported by the ALSA driver: snd_usb_audio

One 16-bit channel with sample and playback rates of 8000 Hz is the practical
limit of the device.

  Example - recording test::

    arecord -v -d 10 -r 8000 -f S16_LE -t wav  foobar.wav

  Example - playback test::

    aplay foobar.wav

Troubleshooting
===============

:Q: Module yealink compiled and installed without any problem but phone
    is not initialized and does not react to any actions.
:A: If you see something like:
    hiddev0: USB HID v1.00 Device [Yealink Network Technology Ltd. VOIP USB Phone
    in dmesg, it means that the hid driver has grabbed the device first. Try to
    load module yealink before any other usb hid driver. Please see the
    instructions provided by your distribution on module configuration.

:Q: Phone is working now (displays version and accepts keypad input) but I can't
    find the sysfs files.
:A: The sysfs files are located on the particular usb endpoint. On most
    distributions you can do: "find /sys/ -name get_icons" for a hint.

Credits & Acknowledgments
=========================

  - Olivier Vandorpe, for starting the usbb2k-api project doing much of
    the reverse engineering.
  - Martin Diehl, for pointing out how to handle USB memory allocation.
  - Dmitry Torokhov, for the numerous code reviews and suggestions.


code:
.. _input-event-codes:

=================
Input event codes
=================

The input protocol uses a map of types and codes to express input device values
to userspace. This document describes the types and codes and how and when they
may be used.

A single hardware event generates multiple input events. Each input event
contains the new value of a single data item. A special event type, EV_SYN, is
used to separate input events into packets of input data changes occurring at
the same moment in time. In the following, the term "event" refers to a single
input event encompassing a type, code, and value.

The input protocol is a stateful protocol. Events are emitted only when values
of event codes have changed. However, the state is maintained within the Linux
input subsystem; drivers do not need to maintain the state and may attempt to
emit unchanged values without harm. Userspace may obtain the current state of
event code values using the EVIOCG* ioctls defined in linux/input.h. The event
reports supported by a device are also provided by sysfs in
class/input/event*/device/capabilities/, and the properties of a device are
provided in class/input/event*/device/properties.

Event types
===========

Event types are groupings of codes under a logical input construct. Each
type has a set of applicable codes to be used in generating events. See the
Codes section for details on valid codes for each type.

* EV_SYN:

  - Used as markers to separate events. Events may be separated in time or in
    space, such as with the multitouch protocol.

* EV_KEY:

  - Used to describe state changes of keyboards, buttons, or other key-like
    devices.

* EV_REL:

  - Used to describe relative axis value changes, e.g. moving the mouse 5 units
    to the left.

* EV_ABS:

  - Used to describe absolute axis value changes, e.g. describing the
    coordinates of a touch on a touchscreen.

* EV_MSC:

  - Used to describe miscellaneous input data that do not fit into other types.

* EV_SW:

  - Used to describe binary state input switches.

* EV_LED:

  - Used to turn LEDs on devices on and off.

* EV_SND:

  - Used to output sound to devices.

* EV_REP:

  - Used for autorepeating devices.

* EV_FF:

  - Used to send force feedback commands to an input device.

* EV_PWR:

  - A special type for power button and switch input.

* EV_FF_STATUS:

  - Used to receive force feedback device status.

Event codes
===========

Event codes define the precise type of event.

EV_SYN
------

EV_SYN event values are undefined. Their usage is defined only by when they are
sent in the evdev event stream.

* SYN_REPORT:

  - Used to synchronize and separate events into packets of input data changes
    occurring at the same moment in time. For example, motion of a mouse may set
    the REL_X and REL_Y values for one motion, then emit a SYN_REPORT. The next
    motion will emit more REL_X and REL_Y values and send another SYN_REPORT.

* SYN_CONFIG:

  - TBD

* SYN_MT_REPORT:

  - Used to synchronize and separate touch events. See the
    multi-touch-protocol.txt document for more information.

* SYN_DROPPED:

  - Used to indicate buffer overrun in the evdev client's event queue.
    Client should ignore all events up to and including next SYN_REPORT
    event and query the device (using EVIOCG* ioctls) to obtain its
    current state.

EV_KEY
------

EV_KEY events take the form KEY_<name> or BTN_<name>. For example, KEY_A is used
to represent the 'A' key on a keyboard. When a key is depressed, an event with
the key's code is emitted with value 1. When the key is released, an event is
emitted with value 0. Some hardware send events when a key is repeated. These
events have a value of 2. In general, KEY_<name> is used for keyboard keys, and
BTN_<name> is used for other types of momentary switch events.

A few EV_KEY codes have special meanings:

* BTN_TOOL_<name>:

  - These codes are used in conjunction with input trackpads, tablets, and
    touchscreens. These devices may be used with fingers, pens, or other tools.
    When an event occurs and a tool is used, the corresponding BTN_TOOL_<name>
    code should be set to a value of 1. When the tool is no longer interacting
    with the input device, the BTN_TOOL_<name> code should be reset to 0. All
    trackpads, tablets, and touchscreens should use at least one BTN_TOOL_<name>
    code when events are generated. Likewise all trackpads, tablets, and
    touchscreens should export only one BTN_TOOL_<name> at a time. To not break
    existing userspace, it is recommended to not switch tool in one EV_SYN frame
    but first emitting the old BTN_TOOL_<name> at 0, then emit one SYN_REPORT
    and then set the new BTN_TOOL_<name> at 1.

* BTN_TOUCH:

    BTN_TOUCH is used for touch contact. While an input tool is determined to be
    within meaningful physical contact, the value of this property must be set
    to 1. Meaningful physical contact may mean any contact, or it may mean
    contact conditioned by an implementation defined property. For example, a
    touchpad may set the value to 1 only when the touch pressure rises above a
    certain value. BTN_TOUCH may be combined with BTN_TOOL_<name> codes. For
    example, a pen tablet may set BTN_TOOL_PEN to 1 and BTN_TOUCH to 0 while the
    pen is hovering over but not touching the tablet surface.

Note: For appropriate function of the legacy mousedev emulation driver,
BTN_TOUCH must be the first evdev code emitted in a synchronization frame.

Note: Historically a touch device with BTN_TOOL_FINGER and BTN_TOUCH was
interpreted as a touchpad by userspace, while a similar device without
BTN_TOOL_FINGER was interpreted as a touchscreen. For backwards compatibility
with current userspace it is recommended to follow this distinction. In the
future, this distinction will be deprecated and the device properties ioctl
EVIOCGPROP, defined in linux/input.h, will be used to convey the device type.

* BTN_TOOL_FINGER, BTN_TOOL_DOUBLETAP, BTN_TOOL_TRIPLETAP, BTN_TOOL_QUADTAP:

  - These codes denote one, two, three, and four finger interaction on a
    trackpad or touchscreen. For example, if the user uses two fingers and moves
    them on the touchpad in an effort to scroll content on screen,
    BTN_TOOL_DOUBLETAP should be set to value 1 for the duration of the motion.
    Note that all BTN_TOOL_<name> codes and the BTN_TOUCH code are orthogonal in
    purpose. A trackpad event generated by finger touches should generate events
    for one code from each group. At most only one of these BTN_TOOL_<name>
    codes should have a value of 1 during any synchronization frame.

Note: Historically some drivers emitted multiple of the finger count codes with
a value of 1 in the same synchronization frame. This usage is deprecated.

Note: In multitouch drivers, the input_mt_report_finger_count() function should
be used to emit these codes. Please see multi-touch-protocol.txt for details.

EV_REL
------

EV_REL events describe relative changes in a property. For example, a mouse may
move to the left by a certain number of units, but its absolute position in
space is unknown. If the absolute position is known, EV_ABS codes should be used
instead of EV_REL codes.

A few EV_REL codes have special meanings:

* REL_WHEEL, REL_HWHEEL:

  - These codes are used for vertical and horizontal scroll wheels,
    respectively. The value is the number of detents moved on the wheel, the
    physical size of which varies by device. For high-resolution wheels
    this may be an approximation based on the high-resolution scroll events,
    see REL_WHEEL_HI_RES. These event codes are legacy codes and
    REL_WHEEL_HI_RES and REL_HWHEEL_HI_RES should be preferred where
    available.

* REL_WHEEL_HI_RES, REL_HWHEEL_HI_RES:

  - High-resolution scroll wheel data. The accumulated value 120 represents
    movement by one detent. For devices that do not provide high-resolution
    scrolling, the value is always a multiple of 120. For devices with
    high-resolution scrolling, the value may be a fraction of 120.

    If a vertical scroll wheel supports high-resolution scrolling, this code
    will be emitted in addition to REL_WHEEL or REL_HWHEEL. The REL_WHEEL
    and REL_HWHEEL may be an approximation based on the high-resolution
    scroll events. There is no guarantee that the high-resolution data
    is a multiple of 120 at the time of an emulated REL_WHEEL or REL_HWHEEL
    event.

EV_ABS
------

EV_ABS events describe absolute changes in a property. For example, a touchpad
may emit coordinates for a touch location.

A few EV_ABS codes have special meanings:

* ABS_DISTANCE:

  - Used to describe the distance of a tool from an interaction surface. This
    event should only be emitted while the tool is hovering, meaning in close
    proximity of the device and while the value of the BTN_TOUCH code is 0. If
    the input device may be used freely in three dimensions, consider ABS_Z
    instead.
  - BTN_TOOL_<name> should be set to 1 when the tool comes into detectable
    proximity and set to 0 when the tool leaves detectable proximity.
    BTN_TOOL_<name> signals the type of tool that is currently detected by the
    hardware and is otherwise independent of ABS_DISTANCE and/or BTN_TOUCH.

* ABS_PROFILE:

  - Used to describe the state of a multi-value profile switch.  An event is
    emitted only when the selected profile changes, indicating the newly
    selected profile value.

* ABS_MT_<name>:

  - Used to describe multitouch input events. Please see
    multi-touch-protocol.txt for details.

* ABS_PRESSURE/ABS_MT_PRESSURE:

   - For touch devices, many devices converted contact size into pressure.
     A finger flattens with pressure, causing a larger contact area and thus
     pressure and contact size are directly related. This is not the case
     for other devices, for example digitizers and touchpads with a true
     pressure sensor ("pressure pads").

     A device should set the resolution of the axis to indicate whether the
     pressure is in measurable units. If the resolution is zero, the
     pressure data is in arbitrary units. If the resolution is non-zero, the
     pressure data is in units/gram. For example, a value of 10 with a
     resolution of 1 represents 10 gram, a value of 10 with a resolution of
     1000 represents 10 microgram.

EV_SW
-----

EV_SW events describe stateful binary switches. For example, the SW_LID code is
used to denote when a laptop lid is closed.

Upon binding to a device or resuming from suspend, a driver must report
the current switch state. This ensures that the device, kernel, and userspace
state is in sync.

Upon resume, if the switch state is the same as before suspend, then the input
subsystem will filter out the duplicate switch state reports. The driver does
not need to keep the state of the switch at any time.

EV_MSC
------

EV_MSC events are used for input and output events that do not fall under other
categories.

A few EV_MSC codes have special meaning:

* MSC_TIMESTAMP:

  - Used to report the number of microseconds since the last reset. This event
    should be coded as an uint32 value, which is allowed to wrap around with
    no special consequence. It is assumed that the time difference between two
    consecutive events is reliable on a reasonable time scale (hours).
    A reset to zero can happen, in which case the time since the last event is
    unknown.  If the device does not provide this information, the driver must
    not provide it to user space.

EV_LED
------

EV_LED events are used for input and output to set and query the state of
various LEDs on devices.

EV_REP
------

EV_REP events are used for specifying autorepeating events.

EV_SND
------

EV_SND events are used for sending sound commands to simple sound output
devices.

EV_FF
-----

EV_FF events are used to initialize a force feedback capable device and to cause
such device to feedback.

EV_PWR
------

EV_PWR events are a special type of event used specifically for power
management. Its usage is not well defined. To be addressed later.

Device properties
=================

Normally, userspace sets up an input device based on the data it emits,
i.e., the event types. In the case of two devices emitting the same event
types, additional information can be provided in the form of device
properties.

INPUT_PROP_DIRECT + INPUT_PROP_POINTER
--------------------------------------

The INPUT_PROP_DIRECT property indicates that device coordinates should be
directly mapped to screen coordinates (not taking into account trivial
transformations, such as scaling, flipping and rotating). Non-direct input
devices require non-trivial transformation, such as absolute to relative
transformation for touchpads. Typical direct input devices: touchscreens,
drawing tablets; non-direct devices: touchpads, mice.

The INPUT_PROP_POINTER property indicates that the device is not transposed
on the screen and thus requires use of an on-screen pointer to trace user's
movements.  Typical pointer devices: touchpads, tablets, mice; non-pointer
device: touchscreen.

If neither INPUT_PROP_DIRECT or INPUT_PROP_POINTER are set, the property is
considered undefined and the device type should be deduced in the
traditional way, using emitted event types.

INPUT_PROP_BUTTONPAD
--------------------

For touchpads where the button is placed beneath the surface, such that
pressing down on the pad causes a button click, this property should be
set. Common in Clickpad notebooks and Macbooks from 2009 and onwards.

Originally, the buttonpad property was coded into the bcm5974 driver
version field under the name integrated button. For backwards
compatibility, both methods need to be checked in userspace.

INPUT_PROP_SEMI_MT
------------------

Some touchpads, most common between 2008 and 2011, can detect the presence
of multiple contacts without resolving the individual positions; only the
number of contacts and a rectangular shape is known. For such
touchpads, the SEMI_MT property should be set.

Depending on the device, the rectangle may enclose all touches, like a
bounding box, or just some of them, for instance the two most recent
touches. The diversity makes the rectangle of limited use, but some
gestures can normally be extracted from it.

If INPUT_PROP_SEMI_MT is not set, the device is assumed to be a true MT
device.

INPUT_PROP_TOPBUTTONPAD
-----------------------

Some laptops, most notably the Lenovo 40 series provide a trackstick
device but do not have physical buttons associated with the trackstick
device. Instead, the top area of the touchpad is marked to show
visual/haptic areas for left, middle, right buttons intended to be used
with the trackstick.

If INPUT_PROP_TOPBUTTONPAD is set, userspace should emulate buttons
accordingly. This property does not affect kernel behavior.
The kernel does not provide button emulation for such devices but treats
them as any other INPUT_PROP_BUTTONPAD device.

INPUT_PROP_ACCELEROMETER
------------------------

Directional axes on this device (absolute and/or relative x, y, z) represent
accelerometer data. Some devices also report gyroscope data, which devices
can report through the rotational axes (absolute and/or relative rx, ry, rz).

All other axes retain their meaning. A device must not mix
regular directional axes and accelerometer axes on the same event node.

Guidelines
==========

The guidelines below ensure proper single-touch and multi-finger functionality.
For multi-touch functionality, see the multi-touch-protocol.rst document for
more information.

Mice
----

REL_{X,Y} must be reported when the mouse moves. BTN_LEFT must be used to report
the primary button press. BTN_{MIDDLE,RIGHT,4,5,etc.} should be used to report
further buttons of the device. REL_WHEEL and REL_HWHEEL should be used to report
scroll wheel events where available.

Touchscreens
------------

ABS_{X,Y} must be reported with the location of the touch. BTN_TOUCH must be
used to report when a touch is active on the screen.
BTN_{MOUSE,LEFT,MIDDLE,RIGHT} must not be reported as the result of touch
contact. BTN_TOOL_<name> events should be reported where possible.

For new hardware, INPUT_PROP_DIRECT should be set.

Trackpads
---------

Legacy trackpads that only provide relative position information must report
events like mice described above.

Trackpads that provide absolute touch position must report ABS_{X,Y} for the
location of the touch. BTN_TOUCH should be used to report when a touch is active
on the trackpad. Where multi-finger support is available, BTN_TOOL_<name> should
be used to report the number of touches active on the trackpad.

For new hardware, INPUT_PROP_POINTER should be set.

Tablets
-------

BTN_TOOL_<name> events must be reported when a stylus or other tool is active on
the tablet. ABS_{X,Y} must be reported with the location of the tool. BTN_TOUCH
should be used to report when the tool is in contact with the tablet.
BTN_{STYLUS,STYLUS2} should be used to report buttons on the tool itself. Any
button may be used for buttons on the tablet except BTN_{MOUSE,LEFT}.
BTN_{0,1,2,etc} are good generic codes for unlabeled buttons. Do not use
meaningful buttons, like BTN_FORWARD, unless the button is labeled for that
purpose on the device.

For new hardware, both INPUT_PROP_DIRECT and INPUT_PROP_POINTER should be set.


code:
========================
Force feedback for Linux
========================

:Author: Johann Deneux <johann.deneux@gmail.com> on 2001/04/22.
:Updated: Anssi Hannula <anssi.hannula@gmail.com> on 2006/04/09.

You may redistribute this file. Please remember to include shape.svg and
interactive.svg as well.

Introduction
~~~~~~~~~~~~

This document describes how to use force feedback devices under Linux. The
goal is not to support these devices as if they were simple input-only devices
(as it is already the case), but to really enable the rendering of force
effects.
This document only describes the force feedback part of the Linux input
interface. Please read joydev/joystick.rst and input.rst before reading further
this document.

Instructions to the user
~~~~~~~~~~~~~~~~~~~~~~~~

To enable force feedback, you have to:

1. have your kernel configured with evdev and a driver that supports your
   device.
2. make sure evdev module is loaded and /dev/input/event* device files are
   created.

Before you start, let me WARN you that some devices shake violently during the
initialisation phase. This happens for example with my "AVB Top Shot Pegasus".
To stop this annoying behaviour, move your joystick to its limits. Anyway, you
should keep a hand on your device, in order to avoid it to break down if
something goes wrong.

If you have a serial iforce device, you need to start inputattach. See
joydev/joystick.rst for details.

Does it work ?
--------------

There is an utility called fftest that will allow you to test the driver::

    % fftest /dev/input/eventXX

Instructions to the developer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All interactions are done using the event API. That is, you can use ioctl()
and write() on /dev/input/eventXX.
This information is subject to change.

Querying device capabilities
----------------------------

::

    #include <linux/input.h>
    #include <sys/ioctl.h>

    #define BITS_TO_LONGS(x) \
	    (((x) + 8 * sizeof (unsigned long) - 1) / (8 * sizeof (unsigned long)))
    unsigned long features[BITS_TO_LONGS(FF_CNT)];
    int ioctl(int file_descriptor, int request, unsigned long *features);

"request" must be EVIOCGBIT(EV_FF, size of features array in bytes )

Returns the features supported by the device. features is a bitfield with the
following bits:

- FF_CONSTANT	can render constant force effects
- FF_PERIODIC	can render periodic effects with the following waveforms:

  - FF_SQUARE	  square waveform
  - FF_TRIANGLE	  triangle waveform
  - FF_SINE	  sine waveform
  - FF_SAW_UP	  sawtooth up waveform
  - FF_SAW_DOWN	  sawtooth down waveform
  - FF_CUSTOM	  custom waveform

- FF_RAMP       can render ramp effects
- FF_SPRING	can simulate the presence of a spring
- FF_FRICTION	can simulate friction
- FF_DAMPER	can simulate damper effects
- FF_RUMBLE	rumble effects
- FF_INERTIA    can simulate inertia
- FF_GAIN	gain is adjustable
- FF_AUTOCENTER	autocenter is adjustable

.. note::

    - In most cases you should use FF_PERIODIC instead of FF_RUMBLE. All
      devices that support FF_RUMBLE support FF_PERIODIC (square, triangle,
      sine) and the other way around.

    - The exact syntax FF_CUSTOM is undefined for the time being as no driver
      supports it yet.

::

    int ioctl(int fd, EVIOCGEFFECTS, int *n);

Returns the number of effects the device can keep in its memory.

Uploading effects to the device
-------------------------------

::

    #include <linux/input.h>
    #include <sys/ioctl.h>

    int ioctl(int file_descriptor, int request, struct ff_effect *effect);

"request" must be EVIOCSFF.

"effect" points to a structure describing the effect to upload. The effect is
uploaded, but not played.
The content of effect may be modified. In particular, its field "id" is set
to the unique id assigned by the driver. This data is required for performing
some operations (removing an effect, controlling the playback).
The "id" field must be set to -1 by the user in order to tell the driver to
allocate a new effect.

Effects are file descriptor specific.

See <uapi/linux/input.h> for a description of the ff_effect struct.  You
should also find help in a few sketches, contained in files shape.svg
and interactive.svg:

.. kernel-figure:: shape.svg

    Shape

.. kernel-figure:: interactive.svg

    Interactive

Removing an effect from the device
----------------------------------

::

    int ioctl(int fd, EVIOCRMFF, effect.id);

This makes room for new effects in the device's memory. Note that this also
stops the effect if it was playing.

Controlling the playback of effects
-----------------------------------

Control of playing is done with write(). Below is an example:

::

    #include <linux/input.h>
    #include <unistd.h>

	struct input_event play;
	struct input_event stop;
	struct ff_effect effect;
	int fd;
   ...
	fd = open("/dev/input/eventXX", O_RDWR);
   ...
	/* Play three times */
	play.type = EV_FF;
	play.code = effect.id;
	play.value = 3;

	write(fd, (const void*) &play, sizeof(play));
   ...
	/* Stop an effect */
	stop.type = EV_FF;
	stop.code = effect.id;
	stop.value = 0;

	write(fd, (const void*) &stop, sizeof(stop));

Setting the gain
----------------

Not all devices have the same strength. Therefore, users should set a gain
factor depending on how strong they want effects to be. This setting is
persistent across access to the driver.

::

    /* Set the gain of the device
    int gain;		/* between 0 and 100 */
    struct input_event ie;	/* structure used to communicate with the driver */

    ie.type = EV_FF;
    ie.code = FF_GAIN;
    ie.value = 0xFFFFUL * gain / 100;

    if (write(fd, &ie, sizeof(ie)) == -1)
	perror("set gain");

Enabling/Disabling autocenter
-----------------------------

The autocenter feature quite disturbs the rendering of effects in my opinion,
and I think it should be an effect, which computation depends on the game
type. But you can enable it if you want.

::

    int autocenter;		/* between 0 and 100 */
    struct input_event ie;

    ie.type = EV_FF;
    ie.code = FF_AUTOCENTER;
    ie.value = 0xFFFFUL * autocenter / 100;

    if (write(fd, &ie, sizeof(ie)) == -1)
	perror("set auto-center");

A value of 0 means "no auto-center".

Dynamic update of an effect
---------------------------

Proceed as if you wanted to upload a new effect, except that instead of
setting the id field to -1, you set it to the wanted effect id.
Normally, the effect is not stopped and restarted. However, depending on the
type of device, not all parameters can be dynamically updated. For example,
the direction of an effect cannot be updated with iforce devices. In this
case, the driver stops the effect, up-load it, and restart it.

Therefore it is recommended to dynamically change direction while the effect
is playing only when it is ok to restart the effect with a replay count of 1.

Information about the status of effects
---------------------------------------

Every time the status of an effect is changed, an event is sent. The values
and meanings of the fields of the event are as follows::

    struct input_event {
    /* When the status of the effect changed */
	    struct timeval time;

    /* Set to EV_FF_STATUS */
	    unsigned short type;

    /* Contains the id of the effect */
	    unsigned short code;

    /* Indicates the status */
	    unsigned int value;
    };

    FF_STATUS_STOPPED	The effect stopped playing
    FF_STATUS_PLAYING	The effect started to play

.. note::

    - Status feedback is only supported by iforce driver. If you have
      a really good reason to use this, please contact
      linux-joystick@atrey.karlin.mff.cuni.cz or anssi.hannula@gmail.com
      so that support for it can be added to the rest of the drivers.


code:
---------------------------
Linux Gamepad Specification
---------------------------

:Author: 2013 by David Herrmann <dh.herrmann@gmail.com>

Introduction
~~~~~~~~~~~~
Linux provides many different input drivers for gamepad hardware. To avoid
having user-space deal with different button-mappings for each gamepad, this
document defines how gamepads are supposed to report their data.

Geometry
~~~~~~~~
As "gamepad" we define devices which roughly look like this::

            ____________________________              __
           / [__ZL__]          [__ZR__] \               |
          / [__ TL __]        [__ TR __] \              | Front Triggers
       __/________________________________\__         __|
      /                                  _   \          |
     /      /\           __             (N)   \         |
    /       ||      __  |MO|  __     _       _ \        | Main Pad
   |    <===DP===> |SE|      |ST|   (W) -|- (E) |       |
    \       ||    ___          ___       _     /        |
    /\      \/   /   \        /   \     (S)   /\      __|
   /  \________ | LS  | ____ |  RS | ________/  \       |
  |         /  \ \___/ /    \ \___/ /  \         |      | Control Sticks
  |        /    \_____/      \_____/    \        |    __|
  |       /                              \       |
   \_____/                                \_____/

       |________|______|    |______|___________|
         D-Pad    Left       Right   Action Pad
                 Stick       Stick

                   |_____________|
                      Menu Pad

Most gamepads have the following features:

  - Action-Pad
    4 buttons in diamonds-shape (on the right side). The buttons are
    differently labeled on most devices so we define them as NORTH,
    SOUTH, WEST and EAST.
  - D-Pad (Direction-pad)
    4 buttons (on the left side) that point up, down, left and right.
  - Menu-Pad
    Different constellations, but most-times 2 buttons: SELECT - START
    Furthermore, many gamepads have a fancy branded button that is used as
    special system-button. It often looks different to the other buttons and
    is used to pop up system-menus or system-settings.
  - Analog-Sticks
    Analog-sticks provide freely moveable sticks to control directions. Not
    all devices have both or any, but they are present at most times.
    Analog-sticks may also provide a digital button if you press them.
  - Triggers
    Triggers are located on the upper-side of the pad in vertical direction.
    Not all devices provide them, but the upper buttons are normally named
    Left- and Right-Triggers, the lower buttons Z-Left and Z-Right.
  - Rumble
    Many devices provide force-feedback features. But are mostly just
    simple rumble motors.

Detection
~~~~~~~~~

All gamepads that follow the protocol described here map BTN_GAMEPAD. This is
an alias for BTN_SOUTH/BTN_A. It can be used to identify a gamepad as such.
However, not all gamepads provide all features, so you need to test for all
features that you need, first. How each feature is mapped is described below.

Legacy drivers often don't comply to these rules. As we cannot change them
for backwards-compatibility reasons, you need to provide fixup mappings in
user-space yourself. Some of them might also provide module-options that
change the mappings so you can advise users to set these.

All new gamepads are supposed to comply with this mapping. Please report any
bugs, if they don't.

There are a lot of less-featured/less-powerful devices out there, which re-use
the buttons from this protocol. However, they try to do this in a compatible
fashion. For example, the "Nintendo Wii Nunchuk" provides two trigger buttons
and one analog stick. It reports them as if it were a gamepad with only one
analog stick and two trigger buttons on the right side.
But that means, that if you only support "real" gamepads, you must test
devices for _all_ reported events that you need. Otherwise, you will also get
devices that report a small subset of the events.

No other devices, that do not look/feel like a gamepad, shall report these
events.

Events
~~~~~~

Gamepads report the following events:

- Action-Pad:

  Every gamepad device has at least 2 action buttons. This means, that every
  device reports BTN_SOUTH (which BTN_GAMEPAD is an alias for). Regardless
  of the labels on the buttons, the codes are sent according to the
  physical position of the buttons.

  Please note that 2- and 3-button pads are fairly rare and old. You might
  want to filter gamepads that do not report all four.

    - 2-Button Pad:

      If only 2 action-buttons are present, they are reported as BTN_SOUTH and
      BTN_EAST. For vertical layouts, the upper button is BTN_EAST. For
      horizontal layouts, the button more on the right is BTN_EAST.

    - 3-Button Pad:

      If only 3 action-buttons are present, they are reported as (from left
      to right): BTN_WEST, BTN_SOUTH, BTN_EAST
      If the buttons are aligned perfectly vertically, they are reported as
      (from top down): BTN_WEST, BTN_SOUTH, BTN_EAST

    - 4-Button Pad:

      If all 4 action-buttons are present, they can be aligned in two
      different formations. If diamond-shaped, they are reported as BTN_NORTH,
      BTN_WEST, BTN_SOUTH, BTN_EAST according to their physical location.
      If rectangular-shaped, the upper-left button is BTN_NORTH, lower-left
      is BTN_WEST, lower-right is BTN_SOUTH and upper-right is BTN_EAST.

- D-Pad:

  Every gamepad provides a D-Pad with four directions: Up, Down, Left, Right
  Some of these are available as digital buttons, some as analog buttons. Some
  may even report both. The kernel does not convert between these so
  applications should support both and choose what is more appropriate if
  both are reported.

    - Digital buttons are reported as:

      BTN_DPAD_*

    - Analog buttons are reported as:

      ABS_HAT0X and ABS_HAT0Y

  (for ABS values negative is left/up, positive is right/down)

- Analog-Sticks:

  The left analog-stick is reported as ABS_X, ABS_Y. The right analog stick is
  reported as ABS_RX, ABS_RY. Zero, one or two sticks may be present.
  If analog-sticks provide digital buttons, they are mapped accordingly as
  BTN_THUMBL (first/left) and BTN_THUMBR (second/right).

  (for ABS values negative is left/up, positive is right/down)

- Triggers:

  Trigger buttons can be available as digital or analog buttons or both. User-
  space must correctly deal with any situation and choose the most appropriate
  mode.

  Upper trigger buttons are reported as BTN_TR or ABS_HAT1X (right) and BTN_TL
  or ABS_HAT1Y (left). Lower trigger buttons are reported as BTN_TR2 or
  ABS_HAT2X (right/ZR) and BTN_TL2 or ABS_HAT2Y (left/ZL).

  If only one trigger-button combination is present (upper+lower), they are
  reported as "right" triggers (BTN_TR/ABS_HAT1X).

  (ABS trigger values start at 0, pressure is reported as positive values)

- Menu-Pad:

  Menu buttons are always digital and are mapped according to their location
  instead of their labels. That is:

    - 1-button Pad:

      Mapped as BTN_START

    - 2-button Pad:

      Left button mapped as BTN_SELECT, right button mapped as BTN_START

  Many pads also have a third button which is branded or has a special symbol
  and meaning. Such buttons are mapped as BTN_MODE. Examples are the Nintendo
  "HOME" button, the XBox "X"-button or Sony "PS" button.

- Rumble:

  Rumble is advertised as FF_RUMBLE.

- Profile:

  Some pads provide a multi-value profile selection switch.  An example is the
  XBox Adaptive and the XBox Elite 2 controllers.  When the active profile is
  switched, its newly selected value is emitted as an ABS_PROFILE event.


code:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Programming gameport drivers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A basic classic gameport
~~~~~~~~~~~~~~~~~~~~~~~~

If the gameport doesn't provide more than the inb()/outb() functionality,
the code needed to register it with the joystick drivers is simple::

	struct gameport gameport;

	gameport.io = MY_IO_ADDRESS;
	gameport_register_port(&gameport);

Make sure struct gameport is initialized to 0 in all other fields. The
gameport generic code will take care of the rest.

If your hardware supports more than one io address, and your driver can
choose which one to program the hardware to, starting from the more exotic
addresses is preferred, because the likelihood of clashing with the standard
0x201 address is smaller.

E.g. if your driver supports addresses 0x200, 0x208, 0x210 and 0x218, then
0x218 would be the address of first choice.

If your hardware supports a gameport address that is not mapped to ISA io
space (is above 0x1000), use that one, and don't map the ISA mirror.

Also, always request_region() on the whole io space occupied by the
gameport. Although only one ioport is really used, the gameport usually
occupies from one to sixteen addresses in the io space.

Please also consider enabling the gameport on the card in the ->open()
callback if the io is mapped to ISA space - this way it'll occupy the io
space only when something really is using it. Disable it again in the
->close() callback. You also can select the io address in the ->open()
callback, so that it doesn't fail if some of the possible addresses are
already occupied by other gameports.

Memory mapped gameport
~~~~~~~~~~~~~~~~~~~~~~

When a gameport can be accessed through MMIO, this way is preferred, because
it is faster, allowing more reads per second. Registering such a gameport
isn't as easy as a basic IO one, but not so much complex::

	struct gameport gameport;

	void my_trigger(struct gameport *gameport)
	{
		my_mmio = 0xff;
	}

	unsigned char my_read(struct gameport *gameport)
	{
		return my_mmio;
	}

	gameport.read = my_read;
	gameport.trigger = my_trigger;
	gameport_register_port(&gameport);

.. _gameport_pgm_cooked_mode:

Cooked mode gameport
~~~~~~~~~~~~~~~~~~~~

There are gameports that can report the axis values as numbers, that means
the driver doesn't have to measure them the old way - an ADC is built into
the gameport. To register a cooked gameport::

	struct gameport gameport;

	int my_cooked_read(struct gameport *gameport, int *axes, int *buttons)
	{
		int i;

		for (i = 0; i < 4; i++)
			axes[i] = my_mmio[i];
		buttons[0] = my_mmio[4];
	}

	int my_open(struct gameport *gameport, int mode)
	{
		return -(mode != GAMEPORT_MODE_COOKED);
	}

	gameport.cooked_read = my_cooked_read;
	gameport.open = my_open;
	gameport.fuzz = 8;
	gameport_register_port(&gameport);

The only confusing thing here is the fuzz value. Best determined by
experimentation, it is the amount of noise in the ADC data. Perfect
gameports can set this to zero, most common have fuzz between 8 and 32.
See analog.c and input.c for handling of fuzz - the fuzz value determines
the size of a gaussian filter window that is used to eliminate the noise
in the data.

More complex gameports
~~~~~~~~~~~~~~~~~~~~~~

Gameports can support both raw and cooked modes. In that case combine either
examples 1+2 or 1+3. Gameports can support internal calibration - see below,
and also lightning.c and analog.c on how that works. If your driver supports
more than one gameport instance simultaneously, use the ->private member of
the gameport struct to point to your data.

Unregistering a gameport
~~~~~~~~~~~~~~~~~~~~~~~~

Simple::

    gameport_unregister_port(&gameport);

The gameport structure
~~~~~~~~~~~~~~~~~~~~~~

::

    struct gameport {

	void *port_data;

A private pointer for free use in the gameport driver. (Not the joystick
driver!)

::

	char name[32];

Driver's name as set by driver calling gameport_set_name(). Informational
purpose only.

::

	char phys[32];

gameport's physical name/description as set by driver calling gameport_set_phys().
Informational purpose only.

::

	int io;

I/O address for use with raw mode. You have to either set this, or ->read()
to some value if your gameport supports raw mode.

::

	int speed;

Raw mode speed of the gameport reads in thousands of reads per second.

::

	int fuzz;

If the gameport supports cooked mode, this should be set to a value that
represents the amount of noise in the data. See
:ref:`gameport_pgm_cooked_mode`.

::

	void (*trigger)(struct gameport *);

Trigger. This function should trigger the ns558 oneshots. If set to NULL,
outb(0xff, io) will be used.

::

	unsigned char (*read)(struct gameport *);

Read the buttons and ns558 oneshot bits. If set to NULL, inb(io) will be
used instead.

::

	int (*cooked_read)(struct gameport *, int *axes, int *buttons);

If the gameport supports cooked mode, it should point this to its cooked
read function. It should fill axes[0..3] with four values of the joystick axes
and buttons[0] with four bits representing the buttons.

::

	int (*calibrate)(struct gameport *, int *axes, int *max);

Function for calibrating the ADC hardware. When called, axes[0..3] should be
pre-filled by cooked data by the caller, max[0..3] should be pre-filled with
expected maximums for each axis. The calibrate() function should set the
sensitivity of the ADC hardware so that the maximums fit in its range and
recompute the axes[] values to match the new sensitivity or re-read them from
the hardware so that they give valid values.

::

	int (*open)(struct gameport *, int mode);

Open() serves two purposes. First a driver either opens the port in raw or
in cooked mode, the open() callback can decide which modes are supported.
Second, resource allocation can happen here. The port can also be enabled
here. Prior to this call, other fields of the gameport struct (namely the io
member) need not to be valid.

::

	void (*close)(struct gameport *);

Close() should free the resources allocated by open, possibly disabling the
gameport.

::

	struct timer_list poll_timer;
	unsigned int poll_interval;     /* in msecs */
	spinlock_t timer_lock;
	unsigned int poll_cnt;
	void (*poll_handler)(struct gameport *);
	struct gameport *parent, *child;
	struct gameport_driver *drv;
	struct mutex drv_mutex;		/* protects serio->drv so attributes can pin driver */
	struct device dev;
	struct list_head node;

For internal use by the gameport layer.

::

    };

Enjoy!


code:
=============================
The Linux Input Documentation
=============================

Contents:

.. toctree::
   :maxdepth: 2

   input_uapi
   input_kapi
   devices/index

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`