Connecting to the driver and receiving events

This document describes how a client program connects to the driver through the UPDD API, registers callbacks to receive notification of events internal to the driver, and handles those events. It applies to UPDD V6 and V7 on all platforms; where the two versions differ this is stated. The files involved are listed in the UPDD API overview.

Opening the connection

Most API functions require an open connection to the driver, so check you do not make calls before calling TBApiOpen or after calling TBApiClose. Call TBApiOpen once only, at the beginning of your program, and TBApiClose once, at the end.

The exceptions to this rule are:

  • TBApiGetApiVersion
  • TBApiRegisterEvent, which before TBApiOpen can only be used to register to receive _EventTypeConfiguration events (CONFIG_EVENT_CONNECT / CONFIG_EVENT_DISCONNECT)
  • TBApiGetBootstrapSetting, which reads the bootstrap file updd.ini and is available before a driver connection is available

TBApiOpen executes asynchronously. A client must wait for the connection either synchronously or asynchronously.

The synchronous approach involves calling TBApiIsDriverConnected in a loop until true is returned:

while (!TBApiIsDriverConnected())
{
#ifdef _WIN32
  Sleep(10);
#else
  usleep(100);
#endif
}

For the asynchronous approach, register to receive configuration notifications before calling TBApiOpen. MyConnectCallback will be called when the connection is made:

TBApiRegisterEvent(0, 0, _EventTypeConfiguration, MyConnectCallback);
TBApiOpen();

static void TBCALL MyConnectCallback(unsigned long long /*context*/, _PointerEvent* ev)
{
  if (ev->pe.config.configEventType == CONFIG_EVENT_CONNECT)
  {
    ...
  }
}

Both approaches are illustrated in the cbconsole example below. In a Qt application, use TBApiIsDriverConnectedNoDispatch once signal / slot connections have been made; see Qt application considerations.

The header names this event type _EventTypeConfiguration. The older name _EventConfiguration is an obsolescent alias, retained for compatibility and due to be removed: use _EventTypeConfiguration in new code.

Driver connection considerations

An application that uses the API should terminate if it receives a callback event of type _EventTypeConfiguration with CONFIG_EVENT_UNLOAD, or an event of type _EventTypeUnload. This allows the uninstaller to delete files that would otherwise be locked. All programs which will run for more than a second or so must register for this and exit when it is received.

Additionally, the program might react to callback events of type _EventTypeConfiguration with CONFIG_EVENT_CONNECT / CONFIG_EVENT_DISCONNECT. These indicate situations where the driver becomes available or unavailable. A program might, for example, avoid making API calls or otherwise alter its behaviour while the driver is not connected.

Registering for events

Using the API, an application can register callbacks to receive notification of a wide range of events internal to the driver. To receive notification of these events, register interest with TBApiRegisterEvent, specifying the relevant event type constants (which can be ORed together):

TBBOOL TBAPI TBApiRegisterEvent(HTBDEVICE aDeviceHandle, unsigned long long aContext, unsigned long aTypes, TB_EVENT_CALL aFunc);
TBBOOL TBAPI TBApiUnregisterEvent(TB_EVENT_CALL aFunc);
  • aDeviceHandle: specify 0 to receive callbacks for all active devices, or a handle for a specific device (see TBApiGetRelativeDevice).
  • aContext: a value passed unchanged to the callback function for identification purposes.
  • aTypes: the event types required, e.g. _EventTypeUnload | _EventTypeDigitiserEvent.
  • aFunc: the callback function.

All functions registered must be unregistered with TBApiUnregisterEvent before the program terminates.

The nature of the registered callback determines the type of data returned in the _PointerEvent structure (struct _PointerEvent in upddapi.h), although not all events are accompanied by additional data. The event types and the data delivered with each are described in the API event reference.

The callback has this form:

void TBCALL MyCallback(unsigned long long context, _PointerEvent* ev);

On 64-bit builds, which includes all UPDD V7 builds and all macOS builds, the context parameter of the callback and of TBApiRegisterEvent is unsigned long long; on 32-bit builds it is unsigned long. The UPDD V6 header declares it as unsigned long on all platforms. upddapi.h defines the macro UPDD_CONTEXT as the correct type for the build.

When working with multi-touch devices, the stylus number (hStylus, also known as the contact number or touch number) in the callback packet is exactly that sent by the controller.

The callback thread

The callback function is executed in the context of a dedicated thread. Therefore only thread-safe (re-entrant) functions should be called from the callback function; many windowing API functions are not re-entrant. If you need to call non-re-entrant functions you must provide synchronisation management. A common way to achieve this is to post a message to the primary process thread and perform all non-re-entrant operations from the primary thread.

When using callbacks you must not call other API functions from the context of the callback thread.

The API provides a pair of functions to simplify dispatching callback events to the primary thread. This is particularly useful in more complicated applications and allows this logic to be implemented on a per-application basis without losing the flexibility of the API's dispatching features:

  1. Create a callback function of type TB_EVENT_CALL_SOURCE and pass its address to TBApiRegisterEventSource. This function should post every received event for processing in the application's primary thread, using a method appropriate to the client.
  2. The receiving handler in the primary thread passes the received values to TBApiEventSink.

Having done so, callbacks registered with TBApiRegisterEvent execute in the primary thread context.

typedef void (TBCALL* TB_EVENT_CALL_SOURCE)(_PointerEvent* aEvent);
TBBOOL TBAPI TBApiRegisterEventSource(TB_EVENT_CALL_SOURCE aFunc);
TBBOOL TBAPI TBApiEventSink(unsigned long long context, _PointerEvent* aEvent);

Errors and diagnostics

Most API functions return a Boolean value (OK / fail). TBApiGetLastError provides a text explanation of the last error.

TBApiEnableApiTrace provides debug output from all API functions to assist in diagnostics.

TBApiIsDeviceConnected provides a supported means to see if a plug and play device is connected.

Example: the cbconsole program

An example UPDD API program, cbconsole, shipped with source code, demonstrates the UPDD API interface and can be downloaded from here.

The cbconsole sample is a simple console mode application written in C++ to illustrate use of the UPDD API in its most basic form, without the complexities of a GUI. It is intended as a starting point for integration of the UPDD API into UPDD client applications. In addition to illustrating the initialisation of the API interface, the example shows how to enumerate the list of defined devices and then read touch data from them.

Build the software as appropriate on your target system using appropriate development tools. The example output is shown below:

The source of the console program, available in the download and reproduced here, may answer any immediate source related queries:

#include "upddapi.h"

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#ifdef _LINUX_
#include <sys/types.h>
#include <sys/wait.h>
#endif

int DoList();
static void TBCALL MyCallback(unsigned long long context, _PointerEvent* data);
static void TBCALL MyConnectCallback(unsigned long long context, _PointerEvent* data);
bool running = true;
bool connected = false;

int main(int argc, char* argv[])
{
  // TBApiOpen executes asynchronously
  // a client program must wait for a connection
  // register to receive events when the connection to the driver is made or broken
  // this is the only type of event that can be registered before TBApiOpen is called;
  TBApiRegisterEvent(0, 0, _EventTypeConfiguration, MyConnectCallback);

  TBApiOpen();

  while (!connected) // in this contrived example we just wait for the connect event; in a real scenario something useful would be done at this point such as executing a program's message dispatch loop
  {
#ifdef _WIN32
    Sleep(10);
#else
    usleep(100);
#endif
  }

  DoList();

  // register for various data callbacks to receive information from UPDD
  // NB ALL programs which will run for more than a second or so MUST register _EventTypeUnload and exit if this message is received
  TBApiRegisterEvent(0,  // specify 0 to receive callbacks for all active devices or a handle for a specific device
                     0,  // this value gets passed to the callback function
                     _EventTypeUnload |        // notification that we must unload (during driver uninstall)
                     _EventTypeDigitiserEvent, // digitiser events give information related to touches
                     MyCallback);

  while(running)
  {
#ifdef _WIN32
    Sleep(1000);
#else
    usleep(10000);
#endif
  }

  // tell the api we no longer want to receive callbacks
  TBApiUnregisterEvent(MyCallback);
  TBApiClose();
  return(0);
}

int DoList()
{
  HTBDEVICE device = TBApiGetRelativeDevice(0);

  for(int i=0; device != TB_INVALID_HANDLE_VALUE;)
  {
    char deviceName[256];
    TBApiGetSetting(device,"device_name",deviceName,sizeof(deviceName));

    int monitor_number;
    TBApiGetSettingAsInt(device, "monitor_number", &monitor_number);

    cout << (char)(device + '0') << "\t" << deviceName << "\tMonitor " << monitor_number << endl;
    device = TBApiGetRelativeDevice(++i);
  }
  return(0);
}

static void TBCALL MyConnectCallback(unsigned long long /*context*/, _PointerEvent* ev)
{
  if (ev->pe.config.configEventType == CONFIG_EVENT_CONNECT)
  {
    connected = true;
  }
}

static void TBCALL MyCallback(unsigned long long /*context*/, _PointerEvent* ev)
{
  // the api calls this function to send events of the type we requested with TBApiRegisterEvent()
  // NB this callback is called in the context of its own thread
  // the user must implement thread synchronisation code when performing operations that might contend with
  // operations in other threads

  switch(ev->type)
  {
  case _EventTypeUnload:
    //[upddapi] driver is being uninstalled - all api programs must terminate
    TBApiClose();
    exit(0);
    break;
  case _EventTypeDigitiserEvent:
    {
      cout << "x: " << ev->pe.digitiserEvent.screenx
        << " y: " << ev->pe.digitiserEvent.screeny
        << (ev->pe.digitiserEvent.de.touchEvent.touchingLeft ? " touching" : " not touching") << ends << endl;
      break;
    }
  }
}

For review

Callback thread rule: the old article says "you must not call other API functions from the context of the callback thread", but the shipped cbconsole example calls TBApiClose() from its callback on _EventTypeUnload (examples/cbconsole/main.cpp), the V5-to-V6 notes said "the V6 API is fully re-entrant", and the header (api/upddapi.h, TBApiRegisterEvent usage note) only says to call thread-safe functions. Both statements are kept; please confirm which rule applies to API calls from a callback.

The download is still the V6-era cbconsoleV6.zip on v6download.touch-base.com; the listing here matches the current examples/cbconsole/main.cpp except that it uses _EventTypeConfiguration and a connected flag (the repository copy uses _EventConfiguration and TBApiIsDriverConnected, and also registers the legacy _EventTypeXY / _EventTypeLogicalEvent types).