Filter:   InfoImg
download libhid.c
Language: C
License: GPL
Copyright: (C) 2003 - 2005
LOC: 911
Project Info
nut
Server: Debian-SVN
Type: svn
...an‑SVN\n\nut\trunk\drivers\
   al175.c
   al175.h
   apc-hid.c
   apc-hid.h
   apccmib.h
   apcsmart.c
   apcsmart.h
   bcmxcp.c
   bcmxcp.h
   bcmxcp_io.h
   bcmxcp_ser.c
   bcmxcp_usb.c
   belkin-hid.c
   belkin-hid.h
   belkin.c
   belkin.h
   belkinunv.c
   belkinunv.h
   bestfcom.c
   bestfcom.h
   bestuferrups.c
   bestuferrups.h
   bestups.c
   bestups.h
   cpsups.c
   cpsups.h
   cyberpower.c
   cyberpower.h
   dstate-hal.c
   dstate-hal.h
   dstate.c
   dstate.h
   dummy-ups.c
   dummy-ups.h
   energizerups.c
   etapro.c
   etapro.h
   everups.c
   everups.h
   explore-hid.c
   explore-hid.h
   gamatronic.c
   gamatronic.h
   genericups.c
   genericups.h
   hidparser.c
   hidparser.h
   hidtypes.h
   ietfmib.h
   isbmex.c
   isbmex.h
   libhid.c
   libhid.h
   libshut.c
   libshut.h
   libusb.c
   libusb.h
   liebert.c
   liebert.h
   main-hal.c
   main-hal.h
   main.c
   main.h
   Makefile.am
   masterguard.c
   masterguard.h
   megatec.c
   megatec.h
   megatec_usb.c
   metasys.c
   metasys.h
   mge-hid.c
   mge-hid.h
   mge-shut.c
   mge-shut.h
   mge-utalk.c
   mge-utalk.h
   mgemib.h
   netvisionmib.h
   nitram.c
   nitram.h
   nut_usb.c
   nut_usb.h
   oneac.c
   oneac.h
   optiups.c
   optiups.h
   powercom.c
   powercom.h
   powerpanel.c
   powerpanel.h
   pwmib.h
   rhino.c
   safenet.c
   safenet.h
   serial.c
   serial.h
   skel.c
   snmp-ups.c
   snmp-ups.h
   solis.c
   solis.h
   tripplite-hid.c
   tripplite-hid.h
   tripplite.c
   tripplite.h
   tripplite_usb.c
   tripplitesu.c
   tripplitesu.h
   upscode2.c
   upscode2.h
   upsdrvctl.c
   usbhid-ups.c
   usbhid-ups.h
   victronups.c
   victronups.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
/*!
 * @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)"</