/*!
* @file libhid.c
* @brief HID Library - User API (Generic HID Access using MGE HIDParser)
*
* @author Copyright (C) 2003 - 2005
* Arnaud Quette <arnaud.quette@free.fr> && <arnaud.quette@mgeups.com>
* John Stamp <kinsayder@hotmail.com>
* 2005 Peter Selinger <selinger@users.sourceforge.net>
*
* This program is sponsored by MGE UPS SYSTEMS - opensource.mgeups.com
*
* The logic of this file is ripped from mge-shut driver (also from
* Arnaud Quette), which is a "HID over serial link" UPS driver for
* Network UPS Tools <http://www.networkupstools.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* -------------------------------------------------------------------------- */
#include <stdio.h>
#include <string.h>
/* #include <math.h> */
#include "hidparser.h"
#include "hidtypes.h"
#include "libhid.h"
#include "common.h" /* for xmalloc, upsdebugx prototypes */
/* Communication layers and drivers (USB and MGE SHUT) */
#ifdef SHUT_MODE
#include "libshut.h"
communication_subdriver_t *comm_driver = &shut_subdriver;
#else
#include "libusb.h"
communication_subdriver_t *comm_driver = &usb_subdriver;
#endif
#include <errno.h>
/* support functions */
static float logical_to_physical(HIDData_t *Data, long logical);
static long physical_to_logical(HIDData_t *Data, float physical);
static const char *hid_lookup_path(unsigned int usage, usage_tables_t *utab);
static int hid_lookup_usage(char *name, usage_tables_t *utab);
static int string_to_path(char *HIDpath, HIDPath_t *path, usage_tables_t *utab);
static int path_to_string(char *HIDpath, HIDPath_t *path, usage_tables_t *utab);
static long get_unit_expo(long UnitType);
static float expo(int a, int b);
/* report buffer structure: holds data about most recent report for
each given report id */
struct reportbuf_s {
time_t ts[256]; /* timestamp when report was retrieved */
int len[256]; /* size of report data */
unsigned char *data[256]; /* report data (allocated) */
};
typedef struct reportbuf_s reportbuf_t;
/* global variables */
static HIDDesc_t *pDesc = NULL; /* parsed Report Descriptor */
static reportbuf_t *rbuf = NULL; /* buffer for most recent reports */
#define min(x,y) ((x)>(y) ? (y) : (x))
/* ---------------------------------------------------------------------- */
/* report buffering system */
/* HID data items are retrieved via "reports". Each report is
identified by a report ID, which is an integer in the range
0-255. Each report can hold several items. To avoid retrieving a
given report multiple times in short succession, we use a data
structure called a "report buffer". The functions in this group
operate on entire *reports*, not individual data items. */
/* allocate a new report buffer. Return pointer on success, else NULL
with errno set. The returned data structure must later be freed
with free_report_buffer(). */
reportbuf_t *new_report_buffer(void) {
reportbuf_t *rbuf;
int i;
rbuf = malloc(sizeof(reportbuf_t));
if (!rbuf) {
return NULL;
}
for (i=0; i<256; i++) {
rbuf->ts[i] = 0;
rbuf->len[i] = 0;
rbuf->data[i] = NULL;
}
return rbuf;
}
void free_report_buffer(reportbuf_t *rbuf) {
int i;
if (rbuf) {
for (i=0; i<256; i++) {
free(rbuf->data[i]);
}
}
free(rbuf);
}
/* refresh the report with the given id in the report buffer rbuf. If
the report is not yet in the buffer, or if it is older than "age"
seconds, then the report is freshly read from the USB
device. Otherwise, it is unchanged. Return 0 on success, -1 on
error with errno set. */
int refresh_report_buffer(reportbuf_t *rbuf, int id, int age, HIDDesc_t *pDesc, hid_dev_handle_t *udev) {
int len = pDesc->replen[id]; /* length of report */
unsigned char *data;
int r;
if (rbuf->data[id] != NULL && rbuf->ts[id] + age > time(0)) {
/* buffered report is still good; nothing to do */
return 0;
}
data = malloc(len+1); /* first byte holds report id */
if (!data) {
return -1;
}
memset(data, 0, len+1);
r = comm_driver->get_report(udev, id, data, len+1);
if (r <= 0) {
return -1;
}
/* have valid report */
free(rbuf->data[id]);
rbuf->data[id] = data;
rbuf->ts[id] = time(0);
rbuf->len[id] = r; /* normally equal to len+1, but could be less? */
upsdebug_hex (3, "Report[r]", rbuf->data[id], rbuf->len[id]);
return 0;
}
/* send the report with the given id to the HID device. Return 0 on
* success, or -1 on failure with errno set. */
int set_report_from_buffer(reportbuf_t *rbuf, int id, hid_dev_handle_t *udev) {
int r;
r = comm_driver->set_report(udev, id, rbuf->data[id], rbuf->len[id]);
if (r <= 0) {
return -1;
}
return 0;
}
/* file a given report in the report buffer. This is used when the
report has been obtained without having been explicitly requested,
e.g., it arrived through an interrupt transfer. Returns 0 on
success, -1 on error with errno set. Note: len >= 1, and the first
byte holds the report id. */
int file_report_buffer(reportbuf_t *rbuf, u_char *report, int len) {
unsigned char *data;
int id;
id = report[0];
data = malloc(len);
if (!data) {
return -1;
}
memcpy(data, report, len);
/* have valid report */
free(rbuf->data[id]);
rbuf->data[id] = data;
rbuf->ts[id] = time(0);
rbuf->len[id] = len;
upsdebug_hex (3, "Report[i]", rbuf->data[id], rbuf->len[id]);
return 0;
}
/* ---------------------------------------------------------------------- */
/* the functions in this next group operate on buffered reports, but
operate on individual items, not whole reports. */
/* read the logical value for the given pData. No logical to physical
conversion is performed. If age>0, the read operation is buffered
if the item's age is less than "age". On success, return 0 and
store the answer in *value. On failure, return -1 and set errno. */
int get_item_buffered(reportbuf_t *rbuf, HIDData_t *pData, int age, HIDDesc_t *pDesc, hid_dev_handle_t *udev, long *Value) {
int r;
int id;
id = pData->ReportID;
r = refresh_report_buffer(rbuf, id, age, pDesc, udev);
if (r<0) {
return -1;
}
GetValue(rbuf->data[id], pData, Value);
return 0;
}
/* set the logical value for the given pData. No physical to logical
conversion is performed. On success, return 0, and failure, return
-1 and set errno. The updated value is sent to the device, and also
stored in the local buffer. */
int set_item_buffered(reportbuf_t *rbuf, HIDData_t *pData, HIDDesc_t *pDesc, hid_dev_handle_t *udev, long Value) {
int id, r;
id = pData->ReportID;
SetValue(pData, rbuf->data[id], Value);
r = set_report_from_buffer(rbuf, id, udev);
return r;
}
/* ---------------------------------------------------------------------- */
/* FIXME: we currently "hard-wire" the report buffer size in the calls
to libxxx_get_report() below to 8 bytes. This is not really a great
idea, but it is necessary because Belkin models will crash,
sometimes with permanent firmware damage, if called with a larger
buffer size (never mind the USB specification). Let's hope for now
that no other UPS needs a buffer greater than 8. Ideally, the
libhid library should calculate the *exact* size of the required
report buffer from the report descriptor. */
#define REPORT_SIZE 8
/* Units and exponents table (HID PDC, 3.2.3) */
#define NB_HID_UNITS 10
static const long HIDUnits[NB_HID_UNITS][2]=
{
{0x00000000,0}, /* None */
{0x00F0D121,7}, /* Voltage */
{0x00100001,0}, /* Ampere */
{0x0000D121,7}, /* VA */
{0x0000D121,7}, /* Watts */
{0x00001001,0}, /* second */
{0x00010001,0}, /* K */
{0x00000000,0}, /* percent */
{0x0000F001,0}, /* Hertz */
{0x00101001,0}, /* As */
};
/* ---------------------------------------------------------------------- */
/* matchers */
/* helper function: version of strcmp that tolerates NULL
* pointers. NULL is considered to come before all other strings
* alphabetically. */
static inline int strcmp_null(char *s1, char *s2) {
if (s1 == NULL && s2 == NULL) {
return 0;
}
if (s1 == NULL) {
return -1;
}
if (s2 == NULL) {
return 1;
}
return strcmp(s1, s2);
}
/* private callback function for exact matches */
static int match_function_exact(HIDDevice_t *d, void *privdata) {
HIDDevice_t *data = (HIDDevice_t *)privdata;
if (d->VendorID != data->VendorID) {
return 0;
}
if (d->ProductID != data->ProductID) {
return 0;
}
if (strcmp_null(d->Vendor, data->Vendor) != 0) {
return 0;
}
if (strcmp_null(d->Product, data->Product) != 0) {
return 0;
}
if (strcmp_null(d->Serial, data->Serial) != 0) {
return 0;
}
/* note: the exact matcher ignores the "Bus" field, because
it can change during a reconnect. */
return 1;
}
/* constructor: return a new matcher that matches the exact HIDDevice_t
* d. Return NULL with errno set on error. */
HIDDeviceMatcher_t *new_exact_matcher(HIDDevice_t *d) {
HIDDeviceMatcher_t *m;
HIDDevice_t *data;
m = (HIDDeviceMatcher_t *)malloc(sizeof(HIDDeviceMatcher_t));
if (!m) {
return NULL;
}
data = (HIDDevice_t *)malloc(sizeof(HIDDevice_t));
if (!data) {
free(m);
return NULL;
}
data->VendorID = d->VendorID;
data->ProductID = d->ProductID;
data->Vendor = d->Vendor ? strdup(d->Vendor) : NULL;
data->Product = d->Product ? strdup(d->Product) : NULL;
data->Serial = d->Serial ? strdup(d->Serial) : NULL;
m->match_function = &match_function_exact;
m->privdata = (void *)data;
m->next = NULL;
return m;
}
/* destructor: free matcher previously created with new_exact_matcher */
void free_exact_matcher(HIDDeviceMatcher_t *matcher) {
HIDDevice_t *data;
if (matcher) {
data = (HIDDevice_t *)matcher->privdata;
free(data->Vendor);
free(data->Product);
free(data->Serial);
free(data);
free(matcher);
}
}
/* Private function for compiling a regular expression. On success,
store the compiled regular expression (or NULL) in *compiled, and
return 0. On error with errno set, return -1. If the supplied
regular expression is unparseable, return -2 (an error message can
then be retrieved with regerror(3)). Note that *compiled will be an
allocated value, and must be freed with regfree(), then free(), see
regex(3). As a special case, if regex==NULL, then set
*compiled=NULL (regular expression NULL is intended to match
anything). */
static inline int compile_regex(regex_t **compiled, char *regex, int cflags) {
int r;
regex_t *preg;
if (regex == NULL) {
*compiled = NULL;
return 0;
}
preg = (regex_t *)malloc(sizeof(regex_t));
if (!preg) {
return -1;
}
r = regcomp(preg, regex, cflags);
if (r) {
return -2;
}
*compiled = preg;
return 0;
}
/* Private function for regular expression matching. Check if the
entire string str (minus any initial and trailing whitespace)
matches the compiled regular expression preg. Return 1 if it
matches, 0 if not. Return -1 on error with errno set. Special
cases: if preg==NULL, it matches everything (no contraint). If
str==NULL, then it is treated as "". */
static int match_regex(regex_t *preg, char *str) {
int r;
regmatch_t pmatch[1];
char *p, *q;
int len;
if (preg == NULL) {
return 1;
}
if (str == NULL) {
str = "";
}
/* make a copy of str with whitespace stripped */
for (q=str; *q==' ' || *q=='\t' || *q=='\n'; q++) {
/* empty */
}
len = strlen(q);
p = (char *)malloc(len+1);
if (!p) {
return -1;
}
memcpy(p, q, len+1);
while (len>0 && (p[len-1]==' ' || p[len-1]=='\t' || p[len-1]=='\n')) {
len--;
}
p[len] = 0;
/* test the regular expression */
r = regexec(preg, p, 1, pmatch, 0);
free(p);
if (r) {
return 0;
}
/* check that the match is the entire string */
if (pmatch[0].rm_so != 0 || pmatch[0].rm_eo != len) {
return 0;
}
return 1;
}
/* Private function, similar to match_regex, but the argument being
* matched is a (hexadecimal) number, rather than a string. It is
* converted to a 4-digit hexadecimal string. */
static inline int match_regex_hex(regex_t *preg, int n) {
char buf[10];
sprintf(buf, "%04x", n);
return match_regex(preg, buf);
}
/* private data type: hold a set of compiled regular expressions. */
struct regex_matcher_data_s {
regex_t *regex[6];
};
typedef struct regex_matcher_data_s regex_matcher_data_t;
/* private callback function for regex matches */
static int match_function_regex(HIDDevice_t *d, void *privdata) {
regex_matcher_data_t *data = (regex_matcher_data_t *)privdata;
int r;
r = match_regex_hex(data->regex[0], d->VendorID);
if (r != 1) {
return r;
}
r = match_regex_hex(data->regex[1], d->ProductID);
if (r != 1) {
return r;
}
r = match_regex(data->regex[2], d->Vendor);
if (r != 1) {
return r;
}
r = match_regex(data->regex[3], d->Product);
if (r != 1) {
return r;
}
r = match_regex(data->regex[4], d->Serial);
if (r != 1) {
return r;
}
r = match_regex(data->regex[5], d->Bus);
if (r != 1) {
return r;
}
return 1;
}
/* constructor: create a regular expression matcher. This matcher is
based on six regular expression strings in regex_array[0..5],
corresponding to: vendorid, productid, vendor, product, serial,
bus. Any of these strings can be NULL, which matches
everything. Cflags are as in regcomp(3). Typical values for cflags
are REG_ICASE (case insensitive matching) and REG_EXTENDED (use
extended regular expressions). On success, return 0 and store the
matcher in *matcher. On error, return -1 with errno set, or return
i=1--5 to indicate that the regular expression regex_array[i] was
ill-formed (an error message can then be retrieved with
regerror(3)). */
int new_regex_matcher(HIDDeviceMatcher_t **matcher, char *regex_array[6], int cflags) {
HIDDeviceMatcher_t *m = NULL;
regex_matcher_data_t *data = NULL;
int r, i;
m = (HIDDeviceMatcher_t *)malloc(sizeof(HIDDeviceMatcher_t));
if (!m) {
return -1;
}
data = (regex_matcher_data_t *)malloc(sizeof(regex_matcher_data_t));
if (!data) {
free(m);
return -1;
}
for (i=0; i<6; i++) {
r = compile_regex(&data->regex[i], regex_array[i], cflags);
if (r==-2) {
r = i;
}
if (r) {
free(m);
free(data);
return r;
}
}
m->match_function = &match_function_regex;
m->privdata = (void *)data;
m->next = NULL;
*matcher = m;
return 0;
}
void free_regex_matcher(HIDDeviceMatcher_t *matcher) {
int i;
regex_matcher_data_t *data;
if (matcher) {
data = (regex_matcher_data_t *)matcher->privdata;
for (i=0; i<6; i++) {
if (data->regex[i]) {
regfree(data->regex[i]);
free(data->regex[i]);
}
}
free(data);
free(matcher);
}
}
/* ---------------------------------------------------------------------- */
/* CAUTION: be careful when modifying the output format of this function,
* since it's used to produce sub-drivers "stub" using
* scripts/subdriver/path-to-subdriver.sh
*/
void HIDDumpTree(hid_dev_handle_t *udev, usage_tables_t *utab)
{
int j;
char path[128], type[10];
float value;
HIDData_t *pData;
for (j=0; j<pDesc->nitems; j++)
{
pData = &pDesc->item[j];
/* Build the path */
path_to_string(path, &pData->Path, utab);
/* Get data type */
type[0] = '\0';
switch (pData->Type)
{
case ITEM_FEATURE:
strcat(type, "Feature");
break;
case ITEM_INPUT:
strcat(type, "Input");
break;
case ITEM_OUTPUT:
strcat(type, "Output");
break;
default:
strcat(type, "Unknown");
break;
}
/* FIXME: enhance this or fix/change the HID parser (see libhid project) */
if ( strstr(path, "000000") == NULL) {
/* Get data value */
if (HIDGetItemValue(udev, path, &value, utab) > 0)
upsdebugx(1, "Path: %s, Type: %s, ReportID: 0x%02x, Offset: %i, Size: %i, Value: %f",
path, type, pData->ReportID, pData->Offset, pData->Size, value);
else
upsdebugx(1, "Path: %s, Type: %s, ReportID: 0x%02x, Offset: %i, Size: %i",
path, type, pData->ReportID, pData->Offset, pData->Size);
}
}
}
/* Matcher is a linked list of matchers (see libhid.h), and the opened
device must match all of them. On success, set *udevp and *hd and
return hd. On failure, return NULL. Mode is MODE_OPEN or MODE_REOPEN. */
HIDDevice_t *HIDOpenDevice(hid_dev_handle_t **udevp, HIDDevice_t *hd, HIDDeviceMatcher_t *matcher, int mode)
{
int ReportSize;
unsigned char ReportDesc[4096];
if ( mode == MODE_REOPEN )
{
upsdebugx(2, "Reopening device");
}
/* get and parse descriptors (dev, cfg and report) */
ReportSize = comm_driver->open(udevp, hd, matcher, ReportDesc, mode);
if (ReportSize == -1)
return NULL;
else
{
if ( mode == MODE_REOPEN )
{
upsdebugx(2, "Device reopened successfully");
return hd;
}
upsdebugx(2, "Report Descriptor size = %d", ReportSize);
upsdebug_hex(3, "Report Descriptor", ReportDesc, ReportSize);
/* Parse Report Descriptor */
Free_ReportDesc(pDesc);
pDesc = Parse_ReportDesc(ReportDesc, ReportSize);
if (!pDesc) {
upsdebugx(0, "Failed to parse report descriptor: %s", strerror(errno));
HIDCloseDevice(*udevp);
*udevp = NULL;
return NULL;
}
/* prepare report buffer */
free_report_buffer(rbuf);
rbuf = new_report_buffer();
if (!rbuf) {
upsdebugx(0, "Failed to allocate report buffer: %s", strerror(errno));
HIDCloseDevice(*udevp);
*udevp = NULL;
return NULL;
}
}
return hd;
}
/* return 1 if OK, 0 on fail, <= -1 otherwise (ie disconnect). TODO:
return value should be checked. Returns the logical value
associated with the given path in *Value (i.e., don't do any
logical->physical conversion. Also returns pointer to the
corresponding HIDData_t item in *ppData, if ppData!=NULL. */
static int HIDGetItemLogical(hid_dev_handle_t *udev, char *path, usage_tables_t *utab, long *Value, HIDData_t **ppData)
{
int i, r;
long hValue;
HIDData_t *pData;
HIDPath_t Path;
r = string_to_path(path, &Path, utab);
if (r <= 0) {
return 0;
}
upsdebugx(4, "Path depth = %i", Path.Size);
for (i = 0; i<Path.Size; i++) {
upsdebugx(4, "%i: Usage(%08x)", i, Path.Node[i]);
}
/* Get info on object (reportID, offset and size) */
pData = FindObject_with_Path(pDesc, &Path, ITEM_FEATURE);
if (!pData) {
upsdebugx(2, "Can't find object %s", path);
return 0;
}
r = get_item_buffered(rbuf, pData, MAX_TS, pDesc, udev, &hValue);
if (r<0) {
upsdebugx(2, "Can't retrieve Report %i (%i): %s", pData->ReportID, errno, strerror(errno));
return -errno;
}
*Value = hValue;
if (ppData != NULL) {
*ppData = pData;
}
return 1;
}
/* return 1 if OK, 0 on fail, -errno otherwise (ie disconnect). TODO:
return value should be checked. Return the physical value
associated with the given path. */
int HIDGetItemValue(hid_dev_handle_t *udev, char *path, float *Value, usage_tables_t *utab)
{
int r;
float physical;
long hValue;
HIDData_t *pData;
r = HIDGetItemLogical(udev, path, utab, &hValue, &pData);
if (r <= 0) {
return r;
}
upsdebugx(4, "=>> Before exponent: %ld, %i/%i)", hValue,
(int)pData->UnitExp, (int)get_unit_expo(pData->Unit) );
/* Convert Logical Min, Max and Value into Physical */
physical = logical_to_physical(pData, hValue);
/* Process exponents and units */
physical *= (float) expo(10,(int)pData->UnitExp - get_unit_expo(pData->Unit));
hValue = (long) physical;
upsdebugx(4, "=>> After conversion: %f (%ld), %i/%i)"