USB Protocol and Keypads: Difference between pages

From Hackspire
(Difference between pages)
Jump to navigation Jump to search
(OS installation: Adjust for CX II)
 
(Fix On key for CX and CX II)
 
Line 1: Line 1:
This article describes the protocol used for USB communication between the computer and the TI-Nspire. It has been documented from TI's official linking software ''Computer Link Software'', an analysis of USB captures of data traffic, and results of tests with a custom host implementation. This documentation may be used to build a full-featured third-party implementation of the computer program, to use features provided by the link not available from Computer Link Software's GUI, to indirectly gather additional information on the TI-Nspire hardware and software, and to discover exploitable flaws in the TI-Nspire OS's implementation of the protocol. An implementation of the protocol is available in [http://lpg.ticalc.org/prj_tilp/ TiLP].
==Key maps==


The documentation is currently incomplete, sometimes vague or too restrictive, and may be wrong on some points. Feel free to contribute to its enhancement and refinement. Interrogations and information based on assumptions which needs to be confirmed by a deeper analysis, more tests with Computer Link Software or tests with a third-party host implementation are <span style="color: IndianRed">formatted in indian red</span>. Once enough tests have been made to validate or correct these parts, please edit them and remove the highlighting.
Each bit in the 900E0010-900E001F registers represents a key. Only bits 0 to 10 are used in each halfword. The mapping depends on the currently used keypad.


The descriptions of the packets of the protocol let sometimes appear hard-coded value, for which it is not clear whether the corresponding field is constant or may vary under certain conditions. You may edit these descriptions to document additional logic found for them. Borderline cases have not all been tested: most of the time the TI-Nspire's implementation of the protocol handles them and make use of error codes. These error codes have not all been documented yet.
'''Clickpad keypad map:'''


==Loopback transfers==
If the bit is cleared, the key is being pressed.
When the TI-Nspire is connected to a computer, but Computer Link Software is ''not'' running, sending the Operating System from the menu of the document management screen make it act as if it was sending and receiving the OS at the same time. The storage memory consumption increases during the loopback transfer, as it does for a real OS upgrade. The same behavior appears when trying to send documents from there contextual menu. The received documents are copied with a new name that has numerical suffix. Loopback transfers don't seem to be faster than real ones, probably because nearly the whole connectivity stack is used, and the physical transfer is not what limits the speed.


No data is exchanged with the computer during a loopback transfer (USB analyzers don't report anything, and it works even when the TI-Nspire driver is not installed).
{|border="1" cellspacing="0" cellpadding="5"
|-
! offset
! bit 0
! bit 1
! bit 2
! bit 3
! bit 4
! bit 5
! bit 6
! bit 7
! bit 8
! bit 9
! bit 10
|-
| 0010
| ret
| enter
| space
| (-)
| Z
| .
| Y
| 0
| X
| on
| theta
|-
| 0012
| ,
| +
| W
| 3
| V
| 2
| U
| 1
| T
| e^x
| pi
|-
| 0014
| ?
| -
| S
| 6
| R
| 5
| Q
| 4
| P
| 10^x
| EE
|-
| 0016
| :
| *
| O
| 9
| N
| 8
| M
| 7
| L
| x^2
| i
|-
| 0018
| "
| /
| K
| tan
| J
| cos
| I
| sin
| H
| ^
| >
|-
| 001A
| '
| cat
| G
| )
| F
| (
| E
| var
| D
| shift
| <
|-
| 001C
| flag
| click
| C
| home
| B
| menu
| A
| esc
| &#124;
| tab
| bgcolor=lightgray |
|-
| 001E
| up
| u+r
| right
| r+d
| down
| d+l
| left
| l+u
| del
| ctrl
| =
|}


==USB descriptors==
'''TI-84+ keypad map:'''
Here is the interesting part (i.e. different from the TI-84 Plus and Titanium) of the USB descriptors advertised by the TI-NSpire in standard (not TI-84 Plus emulation) mode.


Device Descriptor:
If the bit is cleared, the key is being pressed.
idProduct E012h (reminder: E001 : Silverlink, E004: Titanium, E008: TI-84 Plus, E022: Nspire CX II)
bcdDevice 0100h // 1.00
iProduct       // "TI-Nspire(tm) Handheld"
Configuration Descriptor:
bmAttributes   80h // Bus Powered (Titanium: Self Powered Remote Wakeup)
bMaxPower   32h // 100 mA (Titanium: 0 mA)
OTG Descriptor // As on Titanium and TI-84 Plus
Interface descriptor: Vendor Specific class, 1 Bulk IN endpoint, 2 Bulk OUT endpoints (64 bytes)
(was 1 Bulk IN and 1 Bulk OUT on Titanium/TI-84 Plus, 64 bytes)
When a TI-84 Plus is [[TI-84 Plus Emulation|emulated]] by the TI-Nspire, the descriptors are the same as a real TI-84 Plus except:
Device Descriptor:
idProduct E004h // Titanium!
bcdDevice 0200h // 2.00 (Real TI-84 Plus: 1.10)
iProduct       // "TI-84 Plus Silver Edition (Emulation)"
Configuration Descriptor: // Same as the real TI-84 Plus
bmAttributes   C0h // Self Powered
bMaxPower   00h // 0 mA
Interface and enpoint descriptors: same as the TI-84 Plus (1 Bulk IN , 1 Bulk OUT)


==Introduction==
{|border="1" cellspacing="0" cellpadding="5"
We will call '''host''' the participant of the communication which is the USB host, i.e. the computer for a transfer between a computer and a TI-Nspire. <span style="color: IndianRed">The host of a transfer between two TI-Nspires is probably also the USB host, determined with the Host Negotiation Protocol of [http://en.wikipedia.org/wiki/USB_OTG USB On-The-Go]</span>. The communication model of the TI-Nspire seems to allow multiple devices to communicate simultaneously with the same host, through not yet released [http://www.ti-nspire.com/tools/nspire/resources/connect_class.html USB hubs], similar to [http://education.ti.com/educationportal/sites/US/productDetail/us_ti_navigator.html TI-Navigator] available for former calculator models. The TI-Nspire and the computer thus have each a dynamically assigned '''address''' used to identify the source and destination of a packet. A message sent from a source host/device to a destination host/device will be called a '''packet''' in the rest of this documentation. It is actually a protocol packet which may be transparently split into several USB packets by the USB device and host stacks if its length is greater or equal than the maximum USB packet size supported by the TI-Nspire (64 bytes). It seems that a protocol packet does not need to end at an USB packet boundary, but because of the sequencial nature of the exchanges, this feature is useless.
|-
! offset
! bit 0
! bit 1
! bit 2
! bit 3
! bit 4
! bit 5
! bit 6
! bit 7
! bit 8
! bit 9
! bit 10
|-
| 0010
| down
| left
| right
| up
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 0012
| enter
| +
| -
| *
| /
| ^
| clear
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 0014
| (-)
| 3
| 6
| 9
| )
| tan
| vars
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 0016
| .
| 2
| 5
| 8
| (
| cos
| prgm
| stat
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 0018
| 0
| 1
| 4
| 7
| ,
| sin
| apps
| X
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 001A
| on
| sto
| ln
| log
| x^2
| x^-1
| math
| alpha
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 001C
| graph
| trace
| zoom
| wind
| y=
| 2nd
| mode
| del
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 001E
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
|}


Packets are exchanged between '''services''' of the host and the device. A service is a software module which produce and interpret a subset of packet types. A service is identified by a two bytes identifier. Each packet contains both the source and destination service identifiers. A service of a participant sending a packet choose the target service it wants to talk with. Service IDs are similar to TCP ports, except that multiple source and destination services are used during the same session (more specifically for acknowledgment) as we will see.
'''Touchpad/CX/CM/CX II keypad map:'''


We will use further in the documentation notations of the form: <tt>6400:8001->6401:4060</tt> where 6400 is here the source address, 8001 the source service, 6401 the destination address and 4060 the destination service.
If the bit is set, the key is being pressed.


After a connection reset (described further) and once a device has been declared to the host, transfers are initiated by the host and have this form (each line represents a packet):
The On/Home button is not visible here (and can not generate a keypad interrupt) but accessible on the Touchpad/CX/CM at bit 4 of 0x900B0028 and on the CX II at bit 8 of 0x90140810. Both are inverted, i.e. 0 = pressed, 1 = not pressed.
Host: Request
libndls' <code>on_key_pressed()</code> function handles that for all models.
Device: Acknowledgment
Device: Response
Host: Acknowledgment
What could be called a "functional request" (for example "transfer a file") may use several exchanges of this type. The host and the device have stateful sessions and can keep track of the current state between these exchanges (for example when listing the content of a directory, which requires one pair of request/response for each file, the device keeps track of the current file).


==Packet format==
{|border="1" cellspacing="0" cellpadding="5"
Packets send by a host or a device have the same format. A packet has a 16 bytes header and may have an optional data part of variable length.
|-
54 FD SA SA SS SS DA DA DS DS DC DC SZ AK SQ CK [data part] (data less than 255 bytes in size)
! offset
54 FD SA SA SS SS DA DA DS DS DC DC FF AK SQ CK SZ SZ SZ SZ [data part] (data more than 254 bytes in size)
! bit 0
The different fields of the header part are:
! bit 1
*<tt>54 FD</tt>: constant
! bit 2
*<tt>SA SA</tt>: source address
! bit 3
*<tt>SS SS</tt>: source service ID
! bit 4
*<tt>DA DA</tt>: destination address
! bit 5
*<tt>DS DS</tt>: destination service ID
! bit 6
*<tt>DC DC</tt>: checksum of the data part
! bit 7
*<tt>SZ</tt>: size of the data part
! bit 8
*<tt>AK</tt>: used for acknowledgment packets, 00 for other packets.
! bit 9
*<tt>SQ</tt>: sequence number
! bit 10
*<tt>CK</tt>: checksum of the header: the sum of the preceding bytes modulo 256
|-
Here is additional information for the fields not obvious and not described before.
| 0010
| ret
| enter
| bgcolor=lightgray |
| (-)
| space
| Z
| Y
| 0
| ?!
| bgcolor=lightgray |
| bgcolor=lightgray |
|-
| 0012
| X
| W
| V
| 3
| U
| T
| S
| 1
| pi
| trig
| 10^x
|-
| 0014
| R
| Q
| P
| 6
| O
| N
| M
| 4
| EE
| x^2
| bgcolor=lightgray |
|-
| 0016
| L
| K
| J
| 9
| I
| H
| G
| 7
| /
| e^x
| bgcolor=lightgray |
|-
| 0018
| F
| E
| D
| bgcolor=lightgray |
| C
| B
| A
| =
| *
| ^
| bgcolor=lightgray |
|-
| 001A
| bgcolor=lightgray |
| var
| -
| )
| .
| (
| 5
| cat
| frac
| del
| scratch
|-
| 001C
| flag
| bgcolor=lightgray |
| +
| doc
| 2
| menu
| 8
| esc
| bgcolor=lightgray |
| tab
| bgcolor=lightgray |
|-
| 001E
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| bgcolor=lightgray |
| shift
| ctrl
| ,
|}


===Service identifiers===
==Touchpad I²C==
The host which always initiate the transfers (except address assignment during described further) chooses the service ID it uses for standard (not acknowledgment) packets. It will be the source service ID that appears in the packets sent to the device, and the destination service ID of the responses of the device. Any non-standard service ID may be chosen. Computer link Software uses service ID greater or equal than 0x8001. The service ID must be chosen before starting to exchange packets with a new service of the device. When using another service of the device, the host must disconnect itself from the previous service (this process is described further), and choose a new local service ID for the subsequent packets for the new target service. Each time a new host service ID is chosen, it ''must'' be different that the previous ones. The device won't answer to packets with a source service ID which matches a host service which has previously asked to disconnect itself. The same service IDs can be reused only once the connection with the device is reset. At each generation Computer Link Software increments by one the service ID to ensures unique generation, but this is actually not mandatory.


The identifiers (in hexadecimal) of the currently known standard services on the device side are:
Communication with the actual touchpad is done with the [http://en.wikipedia.org/wiki/I%C2%B2C I²C] protocol.
*<tt>00D3</tt>: nACK packet - destination service not available
*<tt>00FE</tt>, <tt>00FF</tt>: packet reception acknowledgment
*<tt>4001</tt>: null <span style="color: IndianRed">(?)</span>
*<tt>4002</tt>: echo
*<tt>4003</tt>: device address request
*<tt>4004</tt>: service tuning <span style="color: IndianRed">(?)</span>
*<tt>4020</tt>: device information
*<tt>4021</tt>: screen capture
*<tt>4022</tt>: event <span style="color: IndianRed">(?)</span>
*<tt>4023</tt>: shutdown <span style="color: IndianRed">(?)</span>
*<tt>4024</tt>: screen capture with RLE
*<tt>4041</tt>: service activity <span style="color: IndianRed">(?)</span>
*<tt>4042</tt>: TE_MLPDEV <span style="color: IndianRed">(?)</span>
*<tt>4043</tt>: TE_RPC <span style="color: IndianRed">(?)</span> (not yet enabled in the OS)
*<tt>4050</tt>: login
*<tt>4051</tt>: message <span style="color: IndianRed">(?)</span>
*<tt>4054</tt>: hub connection <span style="color: IndianRed">(?)</span>
*<tt>4060</tt>: file management (sync service)
*<tt>4080</tt>: OS installation
*<tt>5000</tt>: EXTECHO <span style="color: IndianRed">(?)</span>
*<span style="color: IndianRed">To be completed</span>


The identifiers of the services on the host side are:
On the original Touchpad models, the I2C protocol is bitbanged through the GPIO: GPIO 1 is the Serial Clock (SCL) and GPIO 3 is the Serial Data Line (SDA). On the CX and CX II models, there is a dedicated [[Memory-mapped_I/O_ports#90050000_-_I2C_controller|I2C controller]] for accessing it.
*<tt>00FE</tt>, <tt>00FF</tt>: packet reception acknowledgment
*<tt>4003</tt>: device address assignment
*<tt>40DE</tt>: service disconnect
*<span style="color: IndianRed">To be completed</span>


===Sequence number===
Calculators before the CX II HW rev. AK use the Synaptics protocol, but later versions (indicated by bit 0 of the [[NAND_Memory_Layout#Manuf_Format|HW flags]]) use a custom touchpad and protocol called "CapTIvate".
<span style="color: IndianRed">Sequence numbers are solely used for proper acknowledgment of packets</span>. Each participant manages itself the generation of the sequence numbers for the packets it sends (a communication between a computer and a TI-Nspire brings into play two sequences). Each packet (except acknowledgment packets, see further, and except in the case of an overflow) has it own sequence number. The number is incremented each time a packet has been acknowledged by other side (<span style="color: IndianRed">do they really need to be consecutive?</span>). The generation is common for all the services of a participant, i.e. two consecutive packets sent by/to different services will have consecutive sequence numbers. The sequence number has to be reinitialized to 1 after an address assignment; any other value will make transfer fail. The sequence number which follows 255 is 1, 0 is never used (<span style="color: IndianRed">is there really a reason for this or does it still work with 0?</span>).


===Acknowledgment===
===Synaptics protocol===
An acknowledgment packet from the TI-Nspire acknowledges only the ''reception'' of another packet, ''not'' the fact that the packet acknowledged has correctly been taken into account by its destination service. The TI-Nspire may even acknowledge packets with an incorrect header, for example with a bad header or data checksum, or with a duplicate sequence number.


Whether sent by the host or a device, an acknowledgment packet has '''0x00FF''' as source service ID, '''except''' :  
The touchpad seems to be a [http://read.pudn.com/downloads64/doc/fileformat/229278/510-501-rev4-tm603.pdf TM-603].
* when the sequence number of the acknowledge packet is zero, in which case the service ID '''0x00FE''' is used
[http://lxr.free-electrons.com/source/drivers/input/mouse/synaptics_i2c.c The linux driver] is a good source for documentation.
* when the packet acknowledged contained an invalid destination service ID, in which case the service ID '''0x00D3''', which should be considered as an error
The destination service ID must be the source service ID of the previously received packet the participant acknowledges. The sequence number must be the same as the one of the packet acknowledged. The field <tt>AK</tt> of the header must contain '''0x0A'''. The 2 byte-long data part must contain the destination service ID of the packet acknowledged (i.e. a local service ID). Here is an example of an acknowledgment packet sent by a TI-Nspire to a computer:
6401:00FF->6400:8001 AK=0A SQ=02
data part: 40 60
Here the device acknowledges the reception of a packet sent by the service 8001 of the host, which had 02 as sequence number, and was sent to the service 4060 of the TI-Nspire.


The device replies to requests with an invalid destination service ID with packets similar to acknowledgement packets, but with a special source service ID : '''0x00D3'''.
it responds to messages with address 0x20. A write message consists of the first port to write to, followed by the values to write: the port number auto-increments, so a message of <tt>00 de ad</tt> writes <tt>de</tt> to port <tt>00</tt> and <tt>ad</tt> to port <tt>01</tt>. A read message reads from whatever port was set by the previous write message, so it generally has to be preceded by an empty write to set the port.


===Data part checksum===
A list of some of the touchpad's ports follows. All 16-bit numbers are big-endian.
The 2 byte-long checksum is more or less a CRC checksum. The checksum is 00 00 if there is no data part in the packet. Here is an implementation in [http://www.python.org Python] of the algorithm:
def checksum(data):
    acc = 0
    for byte in data:
        first = (ord(byte) << 8) | acc >> 8
        acc = acc & 0xFF
          second = (((acc & 0xF) << 4) ^ acc) << 8
        third = second >> 5
        acc = third >> 7
        acc = (acc ^ first ^ second ^ third) & 0xFFFF
    return acc
# A few examples
assert checksum('\x00\xFF') == 0xFF00
assert checksum('\x05\x00\x00') == 0x57AD
assert checksum('\x20\x00\x00\x00\x00\x00\x00\x00\x05\x01\x00') == 0xA095
===Data part===
The format and interpretation of the data part depends on the source and destination services for the packet, and on the current state of the exchange:


- multiple-bytes integers that appear in the data part (service identifiers in ack packets for instance) are in big endian (most significant byte first),
* Any page:
** FF: Page number
* Page 04 (default):
** 00: Contact (usually is 01 if proximity >= 0x2F, 00 otherwise)
** 01: Proximity
** 02-03: X position
** 04-05: Y position
** 06: relative X
** 07: relative Y (both refresh on irq)
** 0A: 1 if touchpad pressed down, 0 if not
** 0B: Status (reading this clears the low bits)
*** Bit 0 (0x01): Set when proximity is nonzero
*** Bit 1 (0x02): Set when velocity bytes are nonzero
*** Bit 2 (0x04): Set when unknown byte at 08 is nonzero
*** Bit 3 (0x08): Set when pressed byte has changed
*** Bit 6 (0x40): Set when the touchpad is configured
*** Bit 7 (0x80): Set when an error occured
** E4-E7: Firmware version
* Page 10:
** 04-05: Maximum X coordinate (0x0918)
** 06-07: Maximum Y coordinate (0x069B)


- strings are terminated with a null byte (the examples shown in this documentation will always make the null byte appear to prevent from forgetting it). Sizes are expressed in bytes,
===CapTIvate protocol===


- blocks of pure data always start with a single ID byte (the command byte which is service dependent). When the ID byte is provided in a Request packet, the ID byte is repeated in the response Packet as first byte (even if data has to be split into several packets).
The captivate touchpad seems to use an entirely custom protocol with less capabilities. It has a simpler structure: The first byte is a command byte, then data is either read or written, depending on the command.
Unlike the synaptics protocol, multi-byte values are little-endian.


Common packets with a data part are those which indicates the success or failure of the processing initiated by the previous request packet (or response packet in the case of a processing by the host). These packets should not be confused with packets [[#Acknowledgment|acknowledging the ''reception'']]: for example a request packet can be received successfully, but its data part can contain incorrect data - the device would here return an ACK packet and then a ''failure'' packet. These '''success''' and '''failure''' packets are 2 bytes long, starts with '''0xFF''' and are followed by '''0x00''' in case of success, or an error code in case of failure. The error code is not specific to a type of request (<span style="color: IndianRed">but is it specific to a service?</span>), some codes are reused when they have the same meaning (for example in the case of the [[#File management|file management service]]).
====01: Read "WHY_BOTHER_ME"====


Note: if data to be sent/received is bigger than packet size, data has to be split into several packets.
* Byte 0: 0/Unknown
* Byte 1: Flag byte
** Bit 0: Set if touchpad pressed
** Bit 1: Set if touchpad touched
** Bit 2: Clear if touchpad touched (?)
** Bit 3: Set if something changed after the last read
* Byte 2+3: X position
* Byte 4+5: Y position


==Services==
====03: Write unknown====
Now that we have seen the common parts of the protocol, let's review the functions offered by each service. The descriptions of the various IN (from the device to the host) and OUT (from the host to the device) packets will be presented in this format (random values are used here):
OUT: 6400:8001->6401:4060
FF 00
In this example the service 0x8001 of the host whose address is 0x6400 sends to the service 0x4060 of the device with address 0x6401 the 2 byte-long sequence <tt>FF 00</tt> in the data part of the packet (which is a [[#Data part|success packet]]). The examples in the following sections will most of time use for common packets 0x6400 as host address, 0x6401 as device address and 0x8001 as generated host service ID. Values which are ''not'' example values will appear in bold. Multi-bytes fields in the data part of some packets which are not constant values will be surrounded with square brackets. If the field has a constant length, its length will appear just after the opening bracket. Fields with no specified length have a variable length.
[2 device address]: a 2 byte-long field containing the device address
[directory path] 00: a field of variable length containing the path as a null-terminated string
Mandatory IN and OUT acknowledgment packets will never be shown, only ''request'' and ''response'' packets will be described. Exchanges which don't fit in this type of description will be presented with enough details to fully understand their special features.


===Address assignment===
The OS writes a single byte here.
Before starting any communication with the device, whether the host program has already been started and the device has just been plugged in, or the host program has just been started and the device was already plugged, the host must first:
#reset the connection
#assign an address to the device
The connection reset is mandatory because it forces the device to forget the [[#Service identifiers|identifiers of the host services]] and [[#Sequence number|sequence numbers]] used in the previous communication. Not resetting the connection may cause the reuse of these unique elements, and thus the absence of response to the host requests. A connection reset is triggered by issuing the [http://msdn2.microsoft.com/en-us/library/ms793191.aspx IOCTL_INTERNAL_USB_RESET_PORT] kernel-mode I/O request on Microsoft Windows.


Just after the reset, the device will spontaneously send an '''address request''' packet, with a sequence number set to 1:
====06: Read status====
IN: '''0000:4003->0000:4003'''
The host must response with an '''address assignment''' packet. The sequence number of this paquet doesn't matter, Computer Link Software uses 1.
OUT: 6400:'''4003'''->6401:'''4003'''
[2 device address] FF 00
In this example, the address which appears in the data part of the packet would be 6401 (the same as the destination address in the header). Note that the host should use in the source address field of the header the address it has chosen for itself, and keep it for all the subsequent packets. Computer Link Software always choose 6400 as host address and assigns the address 6401 to the device (<span style="color: IndianRed">what if more than one TI-Nspire is plugged to the computer?</span>). The two bytes <tt>FF 00</tt> mean that the host accepts the address request.


In the special case of address assignment, the device will ''not'' send an acknowledgment packet for the address assignment packet.
* Byte 0: 0/Unknown
* Byte 1: Whether the touchpad is configured
* Byte 2-5: Unknown


The host can now use whatever device service he would like to. It has to choose before a [[#Service identifiers|service identifier]], and will do this before starting to use any service. Remember that an address assignment forces the sequence numbers of both host and device to reinitialize to 1 for the next packet sent by each.
====07: Read size====


===Login request===
* Byte 0: 0/Unknown
* Byte 1: 0/Unknown
* Byte 2+3: Width
* Byte 4+5: Height


Starting at OS 1.2.xxxx, the NSpire attempts to connect to the LOGIN service just after address assignment:
====08: Read firmware version====


IN: 6401:8013->6400:'''4050'''
    0, 0, 1, 0, 0, 4
  02 00 00 00 00 00


and the computer simply replies that service is not available:
====0A: Read unknown====


OUT: 6400:'''00d3'''->6401:8013
Six unknown bytes.
  40 50


From OS 1.4.xxxx, the Nspire adds disconnection from service. So, we have more packets:
====0C: Write unknown====


IN: 6401:40de->6400:4050
The OS writes a single byte here.
  80 00


OUT: 6400:00ff->6401:8000
==Keypad Connector==
  40 50
The Connector joining the keypads to the nspire itself has a very basic design concept: There are a bunch of GPIO pins, VCC, and GND. The OS memory-maps the pins to the bit chart seen above, using half as input, half as output. The same pins the touchpad uses for its I2C connection are used for buttons on the clickpad.


Please note that hand-held request LOGIN connection three seconds after device reset. If your program is designed as one thread listening on all ports (sequential, like TiLP), you have to take this into account. Otherwise, you will get spurious LOGIN request at any time during transfer.
The pins are as follows:
1. Ground
2. Vcc
3-30. GPIO pins, alternating Column-Row-Column-Row


If your program is designed as a real daemon launching one thread per port (parallel), you don't have to be bothered by this.
On the 84+ Pad:
Pin 23 = Link port wire 1
Pin 25 = Link port wire 2


===Device Information===
To request Device Information:


OUT: XX
The OS is constantly doing iskeypressed() on all the keys, so the pins end up looking like a square wave if read by a 'scope. Input pins only show the wave if one of their buttons is pressed, but output pins show the whole wave regardless.
where XX is the command byte; current values are:
01 -> serial number
02 -> device name
03 -> list of supported file extensions


The response to 01 is:
If you can't envision how the keys actually work yet, this might help:
IN: 01 raw data
All the buttons have 2 connectors, that get shorted when they are pressed.
The bits in the table above represent columns of buttons. It's not layed out perfectly because it has more than 8 buttons per column, so it gets offset strangely.
The bits in the offsets (the rows) represent rows of buttons.


Raw data contents:
The columns are each hooked to one Input pin.
@00d (8 bytes): FLASH free
The rows are each hooked to one output pin.
@08d (8 bytes): FLASH physical
The calculator turns on ''One'' output pin, and looks for any signals on the inputs. If there are any, it records the button that matches the input pin and that column.
@16d (8 bytes): RAM free
It then repeats this process for all the other columns, and the iskeypressed() process is complete.
@24d (8 bytes): RAM physical
--
@32d (1 byte): battery level - FF=unknown, 00=powered, 01=low, 7F=OK
@33d (2 bytes): 1 if charging, else 0
@35d (1 byte): clock speed in Mhz
--
@36d (4 bytes): product version (X.Y.ZZZZ) stored as XX YY ZZ ZZ
@40d (4 bytes): same for boot1 version
@44d (4 bytes): same for boot2 version
--
@48d (4 bytes): hardware version - 1 if TI-Nspire CAS, 0 if TI-Nspire
@52d (2 bytes): runLevel - 1 for boot code (for example in recovery mode), 2 for OS
--
@54d (2 bytes): LCD x
@56d (2 bytes): LCD y
@58d (2 bytes): LCD w
@60d (2 bytes): LCD h
@62d (1 byte): 4 bits per pixel
@63d (1 byte): sample model (always 0 which means [http://en.wikipedia.org/wiki/Packed_pixel packed])
--
@64d (1 byte): device - 0E if TI-Nspire CAS, 1E if TI-Nspire
--
@65d (17 bytes): a part of the Electronic Id (16 digits) stored as a null-terminated string (the first two digits and the last 8 ones are missing)
@82d (27 bytes): the full Electronic Id (26 digits) stored as a null-terminated string


The response to 02 is:
If this doesn't make any sense still, email me (willrandship at gmail dot com) and I'll see if I can help.
IN: 02 T I - N S p i r e 00
--[[User:Willrandship|William Shipley]] 05:38, 16 September 2011 (CEST)
 
The response to 03 is:
IN: 03 . t n s 00 . t n o 00
 
The first string is the file extension and the second one is the OS extension.
 
===Service disconnection===
Nothing special needs to be sent by the host to connect to a service of a device before using it. Simply using the correct destination service ID in the request packets it sends is enough.
 
Once the host has started to use a device service, it needs to disconnect from the current service before using a different service. The request is:
OUT: 6400:'''40DE'''->6401:[id of the device service from which to disconnect]
[id of the host service which was used until then to communicate with the device service]
For example if the host uses the device service 4060 with the generated host service ID 8001 and wants to disconnect from it:
(... The host uses the service. Some requests with the header:
  OUT: 6400:8001->6401:4060
...)
OUT: 6400:40DE->6401:4060
8001
Note that Computer Link Software disconnects very often from the services it uses, even between requests to the same service (for example between a directory listing and a file attributes request to the file management service). This is not necessary.
 
===File management===
The data part of the packets exchanged with the file management service of the TI-Nspire contains either a success or failure code (see the section on the [[#Data part|data part]]), or a structure specific to each command. For the latter, the first byte is the command byte; current values are:
 
03: put file
04: ok to put/get file
05: file contents
07: get file
0a: create folder
0b: delete folder
0d: start dirlist
0e: get next dirlist entry
0f: stop dirlist
10: directory list entry
20: get directory or file attributes
 
We will use the names given by Computer Link Software to the different commands.
 
Note: NSpire uses UTF-8 to encode directory and file names. <span style="color: IndianRed">Is there any size limit for directory/file names?</span>
 
====Directory listing====
Listing the content of a directory requires multiple sets of requests and responses. A typical sequence would be:
OUT: DirEnumInit
IN: Success/Failure
OUT: DirEnumNext
IN: Directory or file info
OUT: DirEnumNext
...
IN: No more directory or file
OUT: DirEnumDone
IN: Success
Only the data part of the different packets will be shown in the following descriptions.
 
=====DirEnumInit=====
Initiates a directory listing.
OUT: 0D [>=8 directory name] 00
''Directory name'' is the name of the directory to list, with or without leading and/or trailing slash. It can be "/" get a list of the different directories on the TI-Nspire. The TI-Nspire only supports one level of directories. The name must be at least 8 characters long, padded with null characters if needed. The response is one of:
IN:
- FF 00: success
- FF 0A: the directory doesn't exist
- FF 0F: invalid directory name
 
=====DirEnumNext=====
Get information about the next file in the directory being listed, if there are any more.
OUT: 0E
If information about the next file or directory can be returned, the response is:
IN: 10 00 [1 data part size - 3] [name of the directory or the file] 00 [4 size of the file] [4 date?] [1 directory flag] 00
File names have the suffix ''.tns''. "''data part size - 3''" is the size of the file information structure without the 3 header bytes. The size of a directory is always 0. The meaning of the date is currently not very clear (<span style="color: IndianRed">more to come</span>). "''directory flag''" is 00 for a file, and 01 for a directory.
 
Else the response is <tt>FF XX</tt>, where <tt>XX</tt> is 11 if there are no more file or directory in the list, or 10 if we are not currently listing a directory or if the previous ''DirEnumInit'' failed.
 
=====DirEnumDone=====
<span style="color: IndianRed">Probably needed before trying to list another directory.</span>
OUT: 0F
IN: FF 00
 
====Directory and file attributes====
This command is returns the attributes of a directory or a file:
OUT: 20 01 [>=8 directory or file path] 00
IN: 20 [4 size, 0 for a directory] [4 date] [00 if file, 01 if directory] [1 flags(?): always 00]
The directory or file path must be at least 8 characters long, padded with null characters if needed. <tt>FF 0A</tt> is returned by the device if the path does not exist.
 
(<span style="color: IndianRed">TODO: clarify this point</span>) <tt>date</tt> is the date of the file. It changes each time the file is saved. It could be the age of the file in seconds (but what would be a date of 0, and how does the TI-Nspire track this?)
 
If the file or directory does not exist, the TI-Nspire sends:
IN: FF 0A
 
====Sending a file====
The command ''PutFile'' should be issued, then the content of the file split into as many packets as needed.
OUT: 03 01 [>=8 file path] 00 [4 file size]
''File path'' is the full path to the file to create on the device. The target directory should already exist. The directory name may have a leading slash. The file name must be terminated by the extension ''".tns"''. An example could be ''"/Examples/myfile.tns"''. ''File size'' can be 0 for an empty file  (although empty files couldn't be opened by the TI-Nspire after reception).
 
The device response is <tt>04</tt> if it is ready to receive the file content, <tt>FF 14</tt> if the file path is invalid, <tt>FF 15</tt> if the file path doesn't have a ''".tns"'' extension:
 
IN: 04
 
The file content is then split into 253 byte-long chunks (since the maximum length of the data part is 254 bytes, and since the data part starts with a command byte). The last packet must be less than 253 bytes long. If the file is zero bytes long, nothing is sent by the host.
OUT: 05 [253 file content chunk #1]
OUT: 05 [253 file content chunk #2]
...
OUT: 05 [<253 last file content chunk]
The device response is <tt>FF 00</tt> if the file has been correctly received, <tt>FF 09</tt> if the parent folder doesn't not exist: the file has not been created. The device does send a response if the host was transmitting an empty file.
 
IN: FF 00
 
====Creating a directory====
Request:
OUT: 0A 03 [>=8 directory path] 00
 
Acknowledgement:
IN: FF 00
 
====Receiving a file====
The command ''GetFile'' should be issued, then the content of the file split into as many packets as needed.
 
OUT: 07 01 [>=8 file path] 00
 
''File path'' is the full path to the file to retrieve on the device. The target directory should already exist. The directory name may have a leading slash. The file name must be terminated by the extension "''.tns''". An example could be "''/Examples/myfile.tns''".
 
The NSpire send size of file:
 
IN: 03 01 [9 00] [4 size of file]
 
The device response is 04 if it is ready to receive the file content, FF 0A if the path does not exist.
 
OUT: 04
 
The file contents is then split into 253 byte-long chunks (since the maximum length of the data part is 254 bytes, and since the data part starts with a command byte). The last packet must be less than 253 bytes long. If the file is zero bytes long, nothing is sent by the host.
 
IN: 05 [253 file content chunk #1]
IN: 05 [253 file content chunk #2]
...
IN: 05 [<253 last file content chunk]
 
Please note that data contents is the same as file contents (i.e. a set of XML files compressed with PK-ZIP).
 
To finish, computer send a final acknowledgment:
 
OUT: FF 00
 
====Deleting a file====
Request:
OUT: 09 01 [>=8 file path] 00
The constraints on ''file path'' are the same as those described in [[#Sending_a_file|Sending a file]].
 
Acknowledgement:
IN: FF 00
 
====Deleting a directory====
Request:
OUT: 0B 03 [>=8 directory path] 00
 
Acknowledgement:
IN: FF 00
If the directory is not empty, the files it contains are also deleted.
 
====Renaming a file or directory====
Request:
OUT: 21 01 [>=8 initial file path] [>=9 new file path]
The constraints on the file pathes are the same as those described in [[#Sending_a_file|Sending a file]].
 
Acknowledgement:
IN: FF 00
 
====Copying a file====
Request:
OUT: 0C 01 [>=8 initial file path] [>=9 new file path]
 
Acknowledgement:
IN: FF 00
(<span style="color: IndianRed">TODO: possible error codes</span>)
 
To copy a directory, the target directory must be created, the source directory must be listed, and each file must be copied independently.
 
===Screenshot (RLE)===
To request a screenshot:
OUT: 00
 
The first response is:
IN: 01 raw data
 
where raw data contents is:
@00d (4 bytes): RLE raw data size
@04d (2 bytes): y (?) - always 0
@06d (2 bytes): x (?) - always 0
@08d (2 bytes): LCD width in pixels (0140 = 320 pixels)
@10d (2 bytes): LCD height in pixels (00F0 = 240 pixels)
@12d (1 byte): bits per pixel (4)
@13d (1 byte): sample model - always 0 which means [http://en.wikipedia.org/wiki/Packed_pixel packed]
 
The RLE raw data is then split into as much 270 bytes-long packets (254 bytes long for the data part) as needed. The last packet will be shorter than 270 bytes.
IN: 02 [253 RLE raw data]
where ''raw data'' is the screenshot encoded with an implementation of Run Length Encoding ([http://en.wikipedia.org/wiki/Run-length_encoding RLE]) described below. The encoding is applied to the screenshot ''before'' it is split into packets.
 
The encoded stream is made of sequences of blocks on the same pattern as <tt>LL DD DD DD  ... DD</tt>. The first byte ''LL'' is a signed byte representing a length:
* if it is equal to or greater than zero, then it is the length of the next "run" minus one. The next byte is the value to repeat. For instance <tt>FF FF FF FF FF</tt> would be encoded as <tt>04 FF</tt>. Note that if a run is longer than the maximum length which could be encoded like this (128), then run is divided into sub-runs with a length equal or lower than 128 (for instance <tt>7F 01 7F 01 03 01</tt> represents a run of 128 + 128 + 4 = 260 times the byte 01).
* if it is lower than zero, then it is <tt>-(L - 1)</tt>, where ''L'' is the length (greater than zero) of a sequence not encoded which follows. This is used for sequences of isolated values for which the RLE encoded version would take more space than the original one. For instance <tt>01 03 04 06</tt> could be encoded as <tt>FD 01 03 04 06</tt> (<tt>FD</tt> is the signed byte -3).
 
In the RLE-decoded stream, each pixel is coded with a 4 bit gray scale (16 colors), where <tt>0b000</tt> is black and <tt>0b1111</tt> is white.
 
===OS installation===
 
To send an OS:
 
OUT: 03 [4 size of OS]
IN : 04 (*)
OUT: 05 [OS file contents chunk]
IN:  Either FF 00 (header validated) or 04 (send more data until FF 00)
OUT: 05 [next file contents chunk]
...
OUT: 05 [last file contents chunk]
 
(*) if NSpire rejects OS, it sends 02 00 00 00 00 00 or FF XX, with XX != 0
 
Next, the NSpire continuously send progress bar value (0..65h) until maximum value is reached (101d = 65h):
 
IN : 06 06 (  6%)
IN : 06 0B ( 11%)
...
IN : 06 65 (101%)
 
If OS can not be installed, NSpire will reply with:
 
IN : 06 06
...
IN : 06 60
IN : FF 04
 
===Echo===
 
The echo service simply echoes any received data as follows:
 
OUT: raw data
IN: raw data
 
==Testing==
===Computer Link Software===
Computer Link Software's functions can be tested on the command line using the testing code embedded in the Java binding ''NavNet.jar'' for the low-level connector. <tt>TESTNUM</tt> is the number of the test to run (remove the echo at the beginning and the file redirection at the end the first time to understand how it works). The command line to use with [http://www.cygwin.com/ Cygwin] on Microsoft Windows is:
$ echo $TESTNUM | java -cp "C:\Program Files\TI Education\TI-Nspire Computer Link\lib\navnet.jar" com.ti.eps.navnet.main  >logs 2>&1
The logs of both the native NavNet connector and the Java testing program will be written to the output file. The verbosity of the native logs can be tuned in <tt>Main.class</tt>:
NavNet.init("-c X -d X -p connectors"); // X (initially 4) should be between 0 (no logs) and 5 (finest)
 
===USB traffic analysis===
<span style="color: IndianRed">Any suggestions of a ''free'' USB analyzer for Microsoft Windows?</span>
 
Tools:
 
- somewhat old (2002) but working on Windows9x/XP: [http://sourceforge.net/projects/usbsnoop/ SnoopyPro]
 
- another tool derivated from SniffUsb (free of use but not free software): [http://www.pcausa.com/Utilities/UsbSnoop/default.htm SniffUsb-2]
 
Unfortunately these tools don't seem to work on Windows Vista.
 
The TiLP team can provide you some tools to make traffic analysis more convenient:
 
- xml2hex which turns SnoopyPro log into hexadecimal log,
 
- OR log2hex which turns SniffUsb log into hexadecimal log,
 
- and hex2nsp which turns hexadecimal log into ready-to-read NSpire packet listing.
Both of them are available on the <[http://svn.tilp.info/cgi-bin/viewcvs.cgi/linkguide/trunk/analysis/ TiLP LinkGuide repository]>.
 
If you want to help, you can take a look at some NSpire <[http://svn.tilp.info/cgi-bin/viewcvs.cgi/linkguide/trunk/analysis/logs/nspire/ logs]>.
 
==TODO==
*Find the differences between PC/TI-Nspire transfers and TI-Nspire/TI-Nspire transfers.
*Test and document the [[#Service identifiers|services available]]

Latest revision as of 21:41, 20 December 2022

Key maps

Each bit in the 900E0010-900E001F registers represents a key. Only bits 0 to 10 are used in each halfword. The mapping depends on the currently used keypad.

Clickpad keypad map:

If the bit is cleared, the key is being pressed.

offset bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 bit 8 bit 9 bit 10
0010 ret enter space (-) Z . Y 0 X on theta
0012 , + W 3 V 2 U 1 T e^x pi
0014 ? - S 6 R 5 Q 4 P 10^x EE
0016 : * O 9 N 8 M 7 L x^2 i
0018 " / K tan J cos I sin H ^ >
001A ' cat G ) F ( E var D shift <
001C flag click C home B menu A esc | tab
001E up u+r right r+d down d+l left l+u del ctrl =

TI-84+ keypad map:

If the bit is cleared, the key is being pressed.

offset bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 bit 8 bit 9 bit 10
0010 down left right up
0012 enter + - * / ^ clear
0014 (-) 3 6 9 ) tan vars
0016 . 2 5 8 ( cos prgm stat
0018 0 1 4 7 , sin apps X
001A on sto ln log x^2 x^-1 math alpha
001C graph trace zoom wind y= 2nd mode del
001E

Touchpad/CX/CM/CX II keypad map:

If the bit is set, the key is being pressed.

The On/Home button is not visible here (and can not generate a keypad interrupt) but accessible on the Touchpad/CX/CM at bit 4 of 0x900B0028 and on the CX II at bit 8 of 0x90140810. Both are inverted, i.e. 0 = pressed, 1 = not pressed. libndls' on_key_pressed() function handles that for all models.

offset bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 bit 8 bit 9 bit 10
0010 ret enter (-) space Z Y 0 ?!
0012 X W V 3 U T S 1 pi trig 10^x
0014 R Q P 6 O N M 4 EE x^2
0016 L K J 9 I H G 7 / e^x
0018 F E D C B A = * ^
001A var - ) . ( 5 cat frac del scratch
001C flag + doc 2 menu 8 esc tab
001E shift ctrl ,

Touchpad I²C

Communication with the actual touchpad is done with the I²C protocol.

On the original Touchpad models, the I2C protocol is bitbanged through the GPIO: GPIO 1 is the Serial Clock (SCL) and GPIO 3 is the Serial Data Line (SDA). On the CX and CX II models, there is a dedicated I2C controller for accessing it.

Calculators before the CX II HW rev. AK use the Synaptics protocol, but later versions (indicated by bit 0 of the HW flags) use a custom touchpad and protocol called "CapTIvate".

Synaptics protocol

The touchpad seems to be a TM-603. The linux driver is a good source for documentation.

it responds to messages with address 0x20. A write message consists of the first port to write to, followed by the values to write: the port number auto-increments, so a message of 00 de ad writes de to port 00 and ad to port 01. A read message reads from whatever port was set by the previous write message, so it generally has to be preceded by an empty write to set the port.

A list of some of the touchpad's ports follows. All 16-bit numbers are big-endian.

  • Any page:
    • FF: Page number
  • Page 04 (default):
    • 00: Contact (usually is 01 if proximity >= 0x2F, 00 otherwise)
    • 01: Proximity
    • 02-03: X position
    • 04-05: Y position
    • 06: relative X
    • 07: relative Y (both refresh on irq)
    • 0A: 1 if touchpad pressed down, 0 if not
    • 0B: Status (reading this clears the low bits)
      • Bit 0 (0x01): Set when proximity is nonzero
      • Bit 1 (0x02): Set when velocity bytes are nonzero
      • Bit 2 (0x04): Set when unknown byte at 08 is nonzero
      • Bit 3 (0x08): Set when pressed byte has changed
      • Bit 6 (0x40): Set when the touchpad is configured
      • Bit 7 (0x80): Set when an error occured
    • E4-E7: Firmware version
  • Page 10:
    • 04-05: Maximum X coordinate (0x0918)
    • 06-07: Maximum Y coordinate (0x069B)

CapTIvate protocol

The captivate touchpad seems to use an entirely custom protocol with less capabilities. It has a simpler structure: The first byte is a command byte, then data is either read or written, depending on the command. Unlike the synaptics protocol, multi-byte values are little-endian.

01: Read "WHY_BOTHER_ME"

  • Byte 0: 0/Unknown
  • Byte 1: Flag byte
    • Bit 0: Set if touchpad pressed
    • Bit 1: Set if touchpad touched
    • Bit 2: Clear if touchpad touched (?)
    • Bit 3: Set if something changed after the last read
  • Byte 2+3: X position
  • Byte 4+5: Y position

03: Write unknown

The OS writes a single byte here.

06: Read status

  • Byte 0: 0/Unknown
  • Byte 1: Whether the touchpad is configured
  • Byte 2-5: Unknown

07: Read size

  • Byte 0: 0/Unknown
  • Byte 1: 0/Unknown
  • Byte 2+3: Width
  • Byte 4+5: Height

08: Read firmware version

   0, 0, 1, 0, 0, 4

0A: Read unknown

Six unknown bytes.

0C: Write unknown

The OS writes a single byte here.

Keypad Connector

The Connector joining the keypads to the nspire itself has a very basic design concept: There are a bunch of GPIO pins, VCC, and GND. The OS memory-maps the pins to the bit chart seen above, using half as input, half as output. The same pins the touchpad uses for its I2C connection are used for buttons on the clickpad.

The pins are as follows: 1. Ground 2. Vcc 3-30. GPIO pins, alternating Column-Row-Column-Row

On the 84+ Pad: Pin 23 = Link port wire 1 Pin 25 = Link port wire 2


The OS is constantly doing iskeypressed() on all the keys, so the pins end up looking like a square wave if read by a 'scope. Input pins only show the wave if one of their buttons is pressed, but output pins show the whole wave regardless.

If you can't envision how the keys actually work yet, this might help: All the buttons have 2 connectors, that get shorted when they are pressed. The bits in the table above represent columns of buttons. It's not layed out perfectly because it has more than 8 buttons per column, so it gets offset strangely. The bits in the offsets (the rows) represent rows of buttons.

The columns are each hooked to one Input pin. The rows are each hooked to one output pin. The calculator turns on One output pin, and looks for any signals on the inputs. If there are any, it records the button that matches the input pin and that column. It then repeats this process for all the other columns, and the iskeypressed() process is complete.

If this doesn't make any sense still, email me (willrandship at gmail dot com) and I'll see if I can help. --William Shipley 05:38, 16 September 2011 (CEST)