Source

luausb / demo / lsusb

Full commit
   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
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
#!/usr/bin/env lua

package.path = "demo/?.lua;"..package.path

local usb = require 'usb'
local names = require 'names'
local bit
if _VERSION == 'Lua 5.2' then
	bit = require 'bit32'
elseif _VERSION == 'Lua 5.1' then
	bit = require 'bit'
else
	error("unsupported Lua version")
end
local serial = require 'serial'
require 'serial.util'
--require 'util'

names.init("demo/usb.ids")

local USB_DIR_OUT         = 0           -- to device
local USB_DIR_IN          = 0x80        -- to host

local USB_ENDPOINT_IN = USB_DIR_IN
local USB_ENDPOINT_OUT = USB_DIR_OUT

-- USB types, the second of three bRequestType fields
local USB_TYPE_MASK           = (0x03 * 2^5)
local USB_TYPE_STANDARD       = (0x00 * 2^5)
local USB_TYPE_CLASS          = (0x01 * 2^5)
local USB_TYPE_VENDOR         = (0x02 * 2^5)
local USB_TYPE_RESERVED       = (0x03 * 2^5)

-- USB recipients, the third of three bRequestType fields
local USB_RECIP_MASK          = 0x1f
local USB_RECIP_DEVICE        = 0x00
local USB_RECIP_INTERFACE     = 0x01
local USB_RECIP_ENDPOINT      = 0x02
local USB_RECIP_OTHER         = 0x03
-- From Wireless USB 1.0
local USB_RECIP_PORT          = 0x04
local USB_RECIP_RPIPE         = 0x05

-- Standard requests, for the bRequest field of a SETUP packet.
--
-- These are qualified by the bRequestType field, so that for example
-- TYPE_CLASS or TYPE_VENDOR specific feature flags could be retrieved
-- by a GET_STATUS request.
local USB_REQ_GET_STATUS          = 0x00
local USB_REQ_CLEAR_FEATURE       = 0x01
local USB_REQ_SET_FEATURE         = 0x03
local USB_REQ_SET_ADDRESS         = 0x05
local USB_REQ_GET_DESCRIPTOR      = 0x06
local USB_REQ_SET_DESCRIPTOR      = 0x07
local USB_REQ_GET_CONFIGURATION   = 0x08
local USB_REQ_SET_CONFIGURATION   = 0x09
local USB_REQ_GET_INTERFACE       = 0x0A
local USB_REQ_SET_INTERFACE       = 0x0B
local USB_REQ_SYNCH_FRAME         = 0x0C

local USB_REQ_SET_ENCRYPTION      = 0x0D    -- Wireless USB
local USB_REQ_GET_ENCRYPTION      = 0x0E
local USB_REQ_RPIPE_ABORT         = 0x0E
local USB_REQ_SET_HANDSHAKE       = 0x0F
local USB_REQ_RPIPE_RESET         = 0x0F
local USB_REQ_GET_HANDSHAKE       = 0x10
local USB_REQ_SET_CONNECTION      = 0x11
local USB_REQ_SET_SECURITY_DATA   = 0x12
local USB_REQ_GET_SECURITY_DATA   = 0x13
local USB_REQ_SET_WUSB_DATA       = 0x14
local USB_REQ_LOOPBACK_DATA_WRITE = 0x15
local USB_REQ_LOOPBACK_DATA_READ  = 0x16
local USB_REQ_SET_INTERFACE_DS    = 0x17

-- from USB 2.0 spec and updates
local USB_DT_DEVICE_QUALIFIER		= 0x06
local USB_DT_OTHER_SPEED_CONFIG		= 0x07
local USB_DT_OTG					= 0x09
local USB_DT_DEBUG					= 0x0a
local USB_DT_INTERFACE_ASSOCIATION	= 0x0b
local USB_DT_SECURITY				= 0x0c
local USB_DT_KEY					= 0x0d
local USB_DT_ENCRYPTION_TYPE		= 0x0e
local USB_DT_BOS					= 0x0f
local USB_DT_DEVICE_CAPABILITY		= 0x10
local USB_DT_WIRELESS_ENDPOINT_COMP	= 0x11
local USB_DT_WIRE_ADAPTER			= 0x21
local USB_DT_RPIPE					= 0x22

local USB_DT_RC_INTERFACE			= 0x23

-- Descriptor types ... USB 2.0 spec table 9.5
local USB_DT_DEVICE           = 0x01
local USB_DT_CONFIG           = 0x02
local USB_DT_STRING           = 0x03
local USB_DT_INTERFACE        = 0x04
local USB_DT_ENDPOINT         = 0x05
local USB_DT_DEVICE_QUALIFIER     = 0x06
local USB_DT_OTHER_SPEED_CONFIG   = 0x07
local USB_DT_INTERFACE_POWER      = 0x08
-- these are from a minor usb 2.0 revision (ECN)
local USB_DT_OTG          = 0x09
local USB_DT_DEBUG            = 0x0a
local USB_DT_INTERFACE_ASSOCIATION    = 0x0b
-- these are from the Wireless USB spec
local USB_DT_SECURITY         = 0x0c
local USB_DT_KEY          = 0x0d
local USB_DT_ENCRYPTION_TYPE      = 0x0e
local USB_DT_BOS          = 0x0f
local USB_DT_DEVICE_CAPABILITY    = 0x10
local USB_DT_WIRELESS_ENDPOINT_COMP   = 0x11
local USB_DT_WIRE_ADAPTER     = 0x21
local USB_DT_RPIPE            = 0x22
local USB_DT_CS_RADIO_CONTROL     = 0x23
-- From the USB 3.0 spec
local USB_DT_SS_ENDPOINT_COMP     = 0x30

-- Conventional codes for class-specific descriptors.  The convention is
-- defined in the USB "Common Class" Spec (3.11).  Individual class specs
-- are authoritative for their usage, not the "common class" writeup.
local USB_DT_CS_DEVICE        = bit.bor(USB_TYPE_CLASS, USB_DT_DEVICE)
local USB_DT_CS_CONFIG        = bit.bor(USB_TYPE_CLASS, USB_DT_CONFIG)
local USB_DT_CS_STRING        = bit.bor(USB_TYPE_CLASS, USB_DT_STRING)
local USB_DT_CS_INTERFACE     = bit.bor(USB_TYPE_CLASS, USB_DT_INTERFACE)
local USB_DT_CS_ENDPOINT      = bit.bor(USB_TYPE_CLASS, USB_DT_ENDPOINT)


-- Device and/or Interface Class codes
-- as found in bDeviceClass or bInterfaceClass
-- and defined by www.usb.org documents
local USB_CLASS_PER_INTERFACE     = 0   -- for DeviceClass
local USB_CLASS_AUDIO         = 1
local USB_CLASS_COMM          = 2
local USB_CLASS_HID           = 3
local USB_CLASS_PHYSICAL      = 5
local USB_CLASS_STILL_IMAGE       = 6
local USB_CLASS_PRINTER       = 7
local USB_CLASS_MASS_STORAGE      = 8
local USB_CLASS_HUB           = 9
local USB_CLASS_CDC_DATA      = 0x0a
local USB_CLASS_CSCID         = 0x0b    -- chip+ smart card
local USB_CLASS_CONTENT_SEC       = 0x0d    -- content security
local USB_CLASS_VIDEO         = 0x0e
local USB_CLASS_WIRELESS_CONTROLLER   = 0xe0
local USB_CLASS_MISC          = 0xef
local USB_CLASS_APP_SPEC      = 0xfe
local USB_CLASS_VENDOR_SPEC       = 0xff

local USB_SUBCLASS_VENDOR_SPEC    = 0xff

local USB_CLASS_VIDEO				= 0x0e

local USB_CLASS_APPLICATION	       	= 0xfe

local VERBLEVEL_DEFAULT = 0	-- 0 gives lspci behaviour; 1, lsusb-0.9

local CTRL_RETRIES	= 2
local CTRL_TIMEOUT	= (5*1000)	-- milliseconds

local HUB_STATUS_BYTELEN	= 3	-- max 3 bytes status = hub + 23 ports

local do_report_desc = true
local verblevel = 0
local lua_report = false

local function printf(format, ...)
	io.write(string.format(format, ...))
end

local function le16_to_cpu(x) return x end

local function get_vendor_string(vid)
	return names.vendor[vid] or ''
end

local function get_product_string(vid, pid)
	return names.product[vid] and names.product[vid][pid] or ''
end

local function get_class_string(cls)
	return names.class[cls] or ''
end

local function get_subclass_string(cls, subcls)
	return names.subclass[cls] and names.subclass[cls][subcls] or ''
end

local function get_protocol_string(cls, subcls, proto)
	return names.protocol[cls] and names.protocol[cls][subcls] and names.protocol[cls][subcls][proto] or ''
end

local function get_string(dev, id)
	return id >= 1 and dev:get_string_descriptor_ascii(id, 1024) or ''
end

local function dump_bytes(buf, len)
	for i=1,len do
		printf(" %02x", string.byte(buf, i))
	end
	printf("\n")
end

local function dump_junk(buf, indent, len)
	local ds = string.byte(buf, 1)
	if ds <= len then
		return
	end
	printf("%sjunk at descriptor end:", indent)
	for i=len+1,ds do
		printf(" %02x", string.byte(buf, i))
	end
	printf("\n")
end

local function dump_report_desc(b, l)
	b = {string.byte(b, 1, l)}
	local t, j, btag
	local data, hut = 0xffff, 0xffff
--	int i;
	local types = { "Main", "Global", "Local", "reserved" }
	local indent = "                            "

	printf("          Report Descriptor: (length is %d)\n", l)
	local i = 1
	while i <= l do
		t = b[i]
		local bsize = bit.band(b[i], 0x03)
		if bsize == 3 then
			bsize = 4
		end
		local btype = bit.band(bit.rshift(b[i], 2), 0x03)
		local btag = bit.band(bit.rshift(b[i], 2), 0x3f) -- 2 LSB bits encode length
		printf("            Item(%-6s): %s, data=", types[btype+1], names.reporttag[btag * 4])
		if bsize > 0 then
			printf(" [ ")
			data = 0
			for j=0,bsize-1 do
				printf("0x%02x ", b[i+1+j])
				data = data + b[i+1+j] * 2^(8*j)
			end
			printf("] %d", data)
		else
			printf("none")
		end
		printf("\n")
		if btag==0x01 then -- Usage Page
			printf("%s%s\n", indent, names.huts[data] or "(null)")
			hut = data

		elseif btag==0x02 -- Usage
			or btag==0x06 -- Usage Minimum
			or btag==0x0a then -- Usage Maximum
			printf("%s%s\n", indent,
					names.hutus[hut * 2^16 + data] or "(null)")

		elseif btag==0x15 then -- Unit Exponent
			printf("%sUnit Exponent: %i\n", indent,
					data)

		elseif btag==0x19 then -- Unit
			printf("%s", indent)
			dump_unit(data, bsize)

		elseif btag==0x28 then -- Collection
			printf("%s", indent)
			if data==0x00 then
				printf("Physical\n")

			elseif data==0x01 then
				printf("Application\n")

			elseif data==0x02 then
				printf("Logical\n")

			elseif data==0x03 then
				printf("Report\n")

			elseif data==0x04 then
				printf("Named Array\n")

			elseif data==0x05 then
				printf("Usage Switch\n")

			elseif data==0x06 then
				printf("Usage Modifier\n")

			else
				if bit.band(data, 0x80) > 0 then
					printf("Vendor defined\n")
				else
					printf("Reserved for future use.\n")
				end
			end
		elseif btag==0x20 -- Input
			or btag==0x24 -- Output
			or btag==0x2c then -- Feature
			printf("%s%s %s %s %s %s\n%s%s %s %s %s\n",
			       indent,
			       bit.band(data, 0x01) > 0 and "Constant" or "Data",
			       bit.band(data, 0x02) > 0 and "Variable" or "Array",
			       bit.band(data, 0x04) > 0 and "Relative" or "Absolute",
			       bit.band(data, 0x08) > 0 and "Wrap" or "No_Wrap",
			       bit.band(data, 0x10) > 0 and "Non_Linear" or "Linear",
			       indent,
			       bit.band(data, 0x20) > 0 and "No_Preferred_State" or "Preferred_State",
			       bit.band(data, 0x40) > 0 and "Null_State" or "No_Null_Position",
			       bit.band(data, 0x80) > 0 and "Volatile" or "Non_Volatile",
			       bit.band(data,0x100) > 0 and "Buffered Bytes" or "Bitfield"
			)
		end
		i = i + 1 + bsize
	end
end

local tags = serial.util.enum{
	-- main items
	input              = 0x20,
	output             = 0x24,
	feature            = 0x2c,
	collection         = 0x28,
	end_collection     = 0x30,
	-- global items
	usage_page         = 0x01,
	logical_minimum    = 0x05,
	logical_maximum    = 0x09,
	physical_minimum   = 0x0d,
	physical_maximum   = 0x11,
	unit_exponent      = 0x15,
	unit               = 0x19,
	report_size        = 0x1d,
	report_id          = 0x21,
	report_count       = 0x25,
	push               = 0x29,
	pop                = 0x2d,
	-- local items
	usage              = 0x02,
	usage_minimum      = 0x06,
	usage_maximum      = 0x0a,
	designator_index   = 0x0e,
	designator_minimum = 0x12,
	designator_maximum = 0x16,
	string_index       = 0x1e,
	string_minimum     = 0x22,
	string_maximum     = 0x26,
	delimiter          = 0x2a,
}

local flags = {
	constant = 2^0,
	variable = 2^1,
	relative = 2^2,
	wrap = 2^3,
	non_linear = 2^4,
	no_preferred_state = 2^5,
	null_state = 2^6,
	volatile = 2^7,
	buffered_bytes = 2^8,
}

local collection_types = serial.util.enum{
	["Physical"]       = 0x00,
	["Application"]    = 0x01,
	["Logical"]        = 0x02,
	["Report"]         = 0x03,
	["Named Array"]    = 0x04,
	["Usage Switch"]   = 0x05,
	["Usage Modifier"] = 0x06,
}

names.huts = serial.util.enum(names.huts)

function serial.read.report_descriptor_item_datasize(stream)
	local size = serial.read.uint(stream, 2, 'be')
	if size==3 then
		return 4
	else
		return size
	end
end

function serial.fstruct.report_descriptor_item(self)
	self 'name' ('enum', tags, 'uint', 6, 'be')
--	print(">", self.name)
	if self.name=='usage_page' then
		self 'value' ('sizedvalue', {'report_descriptor_item_datasize'}, {'enum', names.huts, 'uint', '*', 'le'})
	elseif self.name=='collection' then
		self 'value' ('sizedvalue', {'report_descriptor_item_datasize'}, {'enum', collection_types, 'uint', '*', 'le'})
	elseif self.name=='usage' or self.name=='report_count' or self.name=='report_size' then
		self 'value' ('sizedvalue', {'report_descriptor_item_datasize'}, {'uint', '*', 'le'})
	elseif self.name=='logical_minimum' or self.name=='logical_maximum' then
		self 'value' ('sizedvalue', {'report_descriptor_item_datasize'}, {'sint', '*', 'le'})
	elseif self.name=='input' or self.name=='output' or self.name=='feature' then
		self 'value' ('sizedvalue', {'report_descriptor_item_datasize'}, {'flags', flags, 'uint', '*', 'le'})
	else
		self 'value' ('sizedvalue', {'report_descriptor_item_datasize'}, {'bytes2hex', '*'})
	end
--	print(">>", self.bsize, string.format("0x%0"..(2*self.bsize).."x", self.data))
--	self 'bsize' ('uint', 2, 'be')
--	local bsize = self.bsize==3 and 4 or self.bsize
end

serial.alias.report_descriptor = {'array', '*', 'report_descriptor_item'}

local function dump_report_desc_lua(descriptor)
	local b = serial.buffer(descriptor, 'be')
	local d = assert(serial.read.report_descriptor(b))
	printf("          Report Descriptor: (length is %d)\n", #descriptor)
	local indent,hut = 0
	for _,item in ipairs(d) do
		if item.name=='end_collection' then
			indent = indent - 1
		end
		local value,a,b = item.value,"",""
		if item.name=='usage' then
			value = hut and names.hutus[hut * 2^16 + value] or "(unknown)"
		elseif item.name=='input' or item.name=='output' or item.name=='feature' then
			local t = {}
			for flag in pairs(value) do t[#t+1] = flag end
			value = table.concat(t, ", ")
			if item.name=='input' then
				a,b = '\027[32m','\027[m'
			elseif item.name=='output' then
				a,b = '\027[31m','\027[m'
			elseif item.name=='feature' then
				a,b = '\027[33m','\027[m'
			end
		end
		printf("            %s%s%s%s: %s\n", string.rep("  ", indent), a, item.name, b, tostring(value))
		if item.name=='collection' then
			indent = indent + 1
		elseif item.name=='usage_page' then
--			print(">", hut)
			hut = names.huts[item.value]
--			print(">", item.value, names.huts[item.value])
		end
	end
--	util.dumptable(d, io.stdout, 1)
--[[

	local b = {string.byte(descriptor, 1, #descriptor)}
	local t, j, btag
	local data, hut = 0xffff, 0xffff
--	int i;
	local types = { "Main", "Global", "Local", "reserved" }
	local indent = "                            "

	printf("          Report Descriptor: (length is %d)\n", l)
	local i = 1
	while i <= l do
		t = b[i]
		local bsize = bit.band(b[i], 0x03)
		if bsize == 3 then
			bsize = 4
		end
		local btype = bit.band(bit.rshift(b[i], 2), 0x03)
		local btag = bit.band(bit.rshift(b[i], 2), 0x3f) -- 2 LSB bits encode length
		printf("            Item(%-6s): %s, data=", types[btype+1], names.reporttag[btag * 4])
		if bsize > 0 then
			printf(" [ ")
			data = 0
			for j=0,bsize-1 do
				printf("0x%02x ", b[i+1+j])
				data = data + b[i+1+j] * 2^(8*j)
			end
			printf("] %d", data)
		else
			printf("none")
		end
		printf("\n")
		if btag==0x01 then -- Usage Page
			printf("%s%s\n", indent, names.huts[data] or "(null)")
			hut = data

		elseif btag==0x02 -- Usage
			or btag==0x06 -- Usage Minimum
			or btag==0x0a then -- Usage Maximum
			printf("%s%s\n", indent,
					names.hutus[hut * 2^16 + data] or "(null)")

		elseif btag==0x15 then -- Unit Exponent
			printf("%sUnit Exponent: %i\n", indent,
					data)

		elseif btag==0x19 then -- Unit
			printf("%s", indent)
			dump_unit(data, bsize)

		elseif btag==0x28 then -- Collection
			printf("%s", indent)
			if data==0x00 then
				printf("Physical\n")

			elseif data==0x01 then
				printf("Application\n")

			elseif data==0x02 then
				printf("Logical\n")

			elseif data==0x03 then
				printf("Report\n")

			elseif data==0x04 then
				printf("Named Array\n")

			elseif data==0x05 then
				printf("Usage Switch\n")

			elseif data==0x06 then
				printf("Usage Modifier\n")

			else
				if bit.band(data, 0x80) > 0 then
					printf("Vendor defined\n")
				else
					printf("Reserved for future use.\n")
				end
			end
		elseif btag==0x20 -- Input
			or btag==0x24 -- Output
			or btag==0x2c then -- Feature
			printf("%s%s %s %s %s %s\n%s%s %s %s %s\n",
			       indent,
			       bit.band(data, 0x01) > 0 and "Constant" or "Data",
			       bit.band(data, 0x02) > 0 and "Variable" or "Array",
			       bit.band(data, 0x04) > 0 and "Relative" or "Absolute",
			       bit.band(data, 0x08) > 0 and "Wrap" or "No_Wrap",
			       bit.band(data, 0x10) > 0 and "Non_Linear" or "Linear",
			       indent,
			       bit.band(data, 0x20) > 0 and "No_Preferred_State" or "Preferred_State",
			       bit.band(data, 0x40) > 0 and "Null_State" or "No_Null_Position",
			       bit.band(data, 0x80) > 0 and "Volatile" or "Non_Volatile",
			       bit.band(data,0x100) > 0 and "Buffered Bytes" or "Bitfield"
			)
		end
		i = i + 1 + bsize
	end

	--]]
end

local function dump_hid_device(dev, interface, buf)
--	unsigned int i, len;
--	int n;
--	unsigned char dbuf[8192];

	local ds = string.byte(buf, 1)
	local dt = string.byte(buf, 2)
	if dt ~= usb.DT_HID then
		printf("      Warning: Invalid descriptor\n")
	elseif ds < 6+3*string.byte(buf, 6) then
		printf("      Warning: Descriptor too short\n");
	end
	printf([[
        HID Device Descriptor:
          bLength             %5u
          bDescriptorType     %5u
          bcdHID              %2x.%02x
          bCountryCode        %5u %s
          bNumDescriptors     %5u
]],
	       string.byte(buf, 1), string.byte(buf, 2), string.byte(buf, 4), string.byte(buf, 3), string.byte(buf, 5),
	       names.countrycode[string.byte(buf, 5)] or "Unknown", string.byte(buf, 6))
	local bNumDescriptors = string.byte(buf, 6)
	for i=0,bNumDescriptors-1 do
		local bDescriptorType = string.byte(buf, 7+3*i)
		printf([[
          bDescriptorType     %5u %s
          wDescriptorLength   %5u
]],
		       bDescriptorType, names.hid[bDescriptorType],
		       string.byte(buf, 8+3*i) + string.byte(buf, 9+3*i) * 2^8)
	end
	dump_junk(buf, "        ", 6+3*string.byte(buf, 6))
	if not do_report_desc then
		return
	end

	if not dev then
		printf([[
         Report Descriptors: 
           ** UNAVAILABLE **
]])
		return
	end

	for i=0,string.byte(buf, 6)-1 do
		-- we are just interested in report descriptors
		if string.byte(buf, 7+3*i) == usb.DT_REPORT then

		local len = string.byte(buf, 8+3*i) + string.byte(buf, 9+3*i) * 2^8
	--	if len > sizeof(dbuf) then
	--		printf("report descriptor too long\n")
	--		continue
	--	end
		if dev:claim_interface(interface.bInterfaceNumber) then
			local retries = 3
			local dbuf,msg
			while not dbuf and retries > 0 do
				dbuf,msg = dev:control_transfer(
					bit.bor(
						usb.ENDPOINT_IN,
						usb.REQUEST_TYPE_STANDARD,
						usb.RECIPIENT_INTERFACE),
					usb.REQUEST_GET_DESCRIPTOR,
					usb.DT_REPORT * 2^8,
					interface.bInterfaceNumber,
					len,
					CTRL_TIMEOUT)
				retries = retries - 1
			 end

			if dbuf then
				if #dbuf < len then
					printf("          Warning: incomplete report descriptor\n")
				end
				if lua_report then
					dump_report_desc_lua(dbuf)
				else
					dump_report_desc(dbuf, #dbuf)
				end
			end
			dev:release_interface(interface.bInterfaceNumber)
		else
			-- recent Linuxes require claim() for RECIP_INTERFACE,
			-- so "rmmod hid" will often make these available.
			printf([[
         Report Descriptors: 
           ** UNAVAILABLE **
]]);
		end

		end
	end
end

local function dump_device(dev, descriptor)
	local vendor = get_vendor_string(descriptor.idVendor)
	local product = get_product_string(descriptor.idVendor, descriptor.idProduct)
	local cls = get_class_string(descriptor.bDeviceClass)
	local subcls = get_subclass_string(descriptor.bDeviceClass, descriptor.bDeviceSubClass)
	local proto = get_protocol_string(descriptor.bDeviceClass, descriptor.bDeviceSubClass, descriptor.bDeviceProtocol)
	local mfg = get_string(dev, descriptor.iManufacturer)
	local prod = get_string(dev, descriptor.iProduct)
	local serial = get_string(dev, descriptor.iSerialNumber)
	printf([[
Device Descriptor:
  bLength             %5u
  bDescriptorType     %5u
  bcdUSB              %2x.%02x
  bDeviceClass        %5u %s
  bDeviceSubClass     %5u %s
  bDeviceProtocol     %5u %s
  bMaxPacketSize0     %5u
  idVendor           0x%04x %s
  idProduct          0x%04x %s
  bcdDevice           %2x.%02x
  iManufacturer       %5u %s
  iProduct            %5u %s
  iSerial             %5u %s
  bNumConfigurations  %5u
]],
	       descriptor.bLength, descriptor.bDescriptorType,
	       math.floor(descriptor.bcdUSB / 256), descriptor.bcdUSB % 256,
	       descriptor.bDeviceClass, cls,
	       descriptor.bDeviceSubClass, subcls,
	       descriptor.bDeviceProtocol, proto,
	       descriptor.bMaxPacketSize0,
	       descriptor.idVendor, vendor, descriptor.idProduct, product,
	       math.floor(descriptor.bcdDevice / 256), descriptor.bcdDevice % 256,
	       descriptor.iManufacturer, mfg,
	       descriptor.iProduct, prod,
	       descriptor.iSerialNumber, serial,
	       descriptor.bNumConfigurations)
end

local typeattr = { "Control", "Isochronous", "Bulk", "Interrupt" }
local syncattr = { "None", "Asynchronous", "Adaptive", "Synchronous" }
local usage = { "Data", "Feedback", "Implicit feedback Data", "(reserved)" }
local hb = { "1x", "2x", "3x", "(??)" }

local function dump_endpoint(dev, interface, endpoint)
	local wmax = le16_to_cpu(endpoint.wMaxPacketSize)

	printf([[
      Endpoint Descriptor:
        bLength             %5u
        bDescriptorType     %5u
        bEndpointAddress     0x%02x  EP %u %s
        bmAttributes        %5u
          Transfer Type            %s
          Synch Type               %s
          Usage Type               %s
        wMaxPacketSize     0x%04x  %s %d bytes
        bInterval           %5u
]],
	       endpoint.bLength, endpoint.bDescriptorType, endpoint.bEndpointAddress, endpoint.bEndpointAddress % 16,
	       bit.band(endpoint.bEndpointAddress, 0x80)~=0 and "IN" or "OUT", endpoint.bmAttributes,
	       typeattr[endpoint.bmAttributes % 4 + 1], syncattr[math.floor(endpoint.bmAttributes / 2^2) % 4 + 1],
	       usage[math.floor(endpoint.bmAttributes / 2^4) % 4 + 1],
	       wmax, hb[math.floor(wmax / 2^11) % 4 + 1], wmax % 0x800,
	       endpoint.bInterval);
	-- only for audio endpoints
	if endpoint.bLength == 9 then
		printf([[
        bRefresh            %5u
        bSynchAddress       %5u
]],
		       endpoint.bRefresh, endpoint.bSynchAddress)
	end

	-- avoid re-ordering or hiding descriptors for display
	if endpoint.extra then
		local size = #endpoint.extra
		local buf = endpoint.extra
		while size >= 2 do
			local ds = string.byte(buf, 1)
			if ds < 2 then
				dump_junk(buf, "        ", size)
				break
			end
			local dt = string.byte(buf, 2)
			if dt==assert(USB_DT_CS_ENDPOINT) then
				if interface.bInterfaceClass == 1 and interface.bInterfaceSubClass == 2 then
					dump_audiostreaming_endpoint(buf)
				elseif interface.bInterfaceClass == 1 and interface.bInterfaceSubClass == 3 then
					dump_midistreaming_endpoint(buf)
				end
			elseif dt==assert(USB_DT_CS_INTERFACE) then
				-- MISPLACED DESCRIPTOR ... less indent
				local ic = interface.bInterfaceClass
				if interface.bInterfaceClass==assert(USB_CLASS_COMM)
				or interface.bInterfaceClass==assert(USB_CLASS_DATA) then -- comm data
					dump_comm_descriptor(dev, buf,
						"      ")
				else
					printf("        INTERFACE CLASS: ")
					dump_bytes(buf, ds)
				end
			elseif dt==assert(USB_DT_OTG) then
				-- handled separately
			elseif dt==assert(USB_DT_INTERFACE_ASSOCIATION) then
				dump_association(dev, buf)
			else
				-- often a misplaced class descriptor
				printf("        ** UNRECOGNIZED: ")
				dump_bytes(buf, ds)
			end
			size = size - ds
			buf = buf:sub(ds+1)
		end
	end
end

local function dump_altsetting(dev, interface)
	local cls = get_class_string(interface.bInterfaceClass)
	local subcls = get_subclass_string(interface.bInterfaceClass, interface.bInterfaceSubClass)
	local proto = get_protocol_string(interface.bInterfaceClass, interface.bInterfaceSubClass, interface.bInterfaceProtocol)
	local ifstr = get_string(dev, interface.iInterface)
	printf([[
    Interface Descriptor:
      bLength             %5u
      bDescriptorType     %5u
      bInterfaceNumber    %5u
      bAlternateSetting   %5u
      bNumEndpoints       %5u
      bInterfaceClass     %5u %s
      bInterfaceSubClass  %5u %s
      bInterfaceProtocol  %5u %s
      iInterface          %5u %s
]],
	       interface.bLength, interface.bDescriptorType, interface.bInterfaceNumber,
	       interface.bAlternateSetting, interface.bNumEndpoints, interface.bInterfaceClass, cls,
	       interface.bInterfaceSubClass, subcls, interface.bInterfaceProtocol, proto,
	       interface.iInterface, ifstr)

	-- avoid re-ordering or hiding descriptors for display
	if interface.extra then
		local size = #interface.extra
		local buf = interface.extra
		while size >= 2 do
			local ds = string.byte(buf, 1)
			if ds < 2 then
				dump_junk(buf, "      ", size)
				break
			end

			local dt = string.byte(buf, 2)

			local function dump()
				printf("      ** UNRECOGNIZED: ")
				dump_bytes(buf, ds)
			end

			-- This is the polite way to provide class specific
			-- descriptors: explicitly tagged, using common class
			-- spec conventions.
			if dt==assert(USB_DT_CS_DEVICE)
			or dt==assert(USB_DT_CS_INTERFACE) then
				if interface.bInterfaceClass==assert(USB_CLASS_AUDIO) then
					if interface.bInterfaceSubClass==1 then
						dump_audiocontrol_interface(dev, buf)
					elseif interface.bInterfaceSubClass==2 then
						dump_audiostreaming_interface(buf)
					elseif interface.bInterfaceSubClass==3 then
						dump_midistreaming_interface(dev, buf)
					else
						dump()
					end
				elseif interface.bInterfaceClass==assert(USB_CLASS_COMM) then
					dump_comm_descriptor(dev, buf,
						"      ")
				elseif interface.bInterfaceClass==assert(USB_CLASS_VIDEO) then
					if interface.bInterfaceSubClass==1 then
						dump_videocontrol_interface(dev, buf)
					elseif interface.bInterfaceSubClass==2 then
						dump_videostreaming_interface(buf)
					else
						dump()
					end
				elseif interface.bInterfaceClass==assert(USB_CLASS_APPLICATION) then
					if interface.bInterfaceSubClass==1 then
						dump_dfu_interface(buf)
					else
						dump()
					end
				elseif interface.bInterfaceClass==assert(USB_CLASS_HID) then
					dump_hid_device(dev, interface, buf)
				else
					dump()
				end

			-- This is the ugly way:  implicitly tagged,
			-- each class could redefine the type IDs.
			else
			--	switch (interface->bInterfaceClass) {
				if interface.bInterfaceClass==assert(USB_CLASS_HID) then
					dump_hid_device(dev, interface, buf)
				elseif interface.bInterfaceClass==0x0b then -- chip/smartcard
					dump_ccid_device(buf)
				elseif interface.bInterfaceClass==0xe0 then -- wireless
					if interface.bInterfaceSubClass==1 then
						if interface.bInterfaceProtocol==2 then
							dump_rc_interface(buf)
						else
							dump()
						end
					elseif interface.bInterfaceSubClass==2 then
						dump_wire_adapter(buf)
					else
						dump()
					end
				else
					-- ... not everything is class-specific
					local dt = string.byte(buf, 2)
					if dt==assert(USB_DT_OTG) then
						-- handled separately
					elseif dt==assert(USB_DT_INTERFACE_ASSOCIATION) then
						dump_association(dev, buf);
					else
						-- often a misplaced class descriptor
						dump()
					end
				end
			end
			size = size - ds
			buf = buf:sub(ds+1)
		end
	end

	for i=1,interface.bNumEndpoints do
		dump_endpoint(dev, interface, interface.endpoint[i])
	end
end

local function dump_interface(dev, interface)
	for i=1,interface.num_altsetting do
		dump_altsetting(dev, interface.altsetting[i])
	end
end

local function dump_hub(prefix, p, has_tt)
--	unsigned int l, i, j;
	local wHubChar = p[5] * 2^8 + p[4]

	printf("%sHub Descriptor:\n", prefix)
	printf("%s  bLength             %3u\n", prefix, p[1])
	printf("%s  bDescriptorType     %3u\n", prefix, p[2])
	printf("%s  nNbrPorts           %3u\n", prefix, p[3])
	printf("%s  wHubCharacteristic 0x%04x\n", prefix, wHubChar)
	local tmp = bit.band(wHubChar, 0x03)
--	switch (wHubChar & 0x03) {
	if tmp==tmp0 then
		printf("%s    Ganged power switching\n", prefix);
	elseif tmp==1 then
		printf("%s    Per-port power switching\n", prefix);
	else
		printf("%s    No power switching (usb 1.0)\n", prefix);
	end
	if bit.band(wHubChar, 0x04) > 0 then
		printf("%s    Compound device\n", prefix)
	end
	local tmp = bit.band(bit.rshift(wHubChar, 3), 0x03)
	if tmp==0 then
		printf("%s    Ganged overcurrent protection\n", prefix)
	elseif tmp==1 then
		printf("%s    Per-port overcurrent protection\n", prefix);
	else
		printf("%s    No overcurrent protection\n", prefix);
	end
	if has_tt then
		local l = bit.band(bit.rshift(wHubChar, 5), 0x03)
		printf("%s    TT think time %d FS bits\n", prefix, (l + 1) * 8);
	end
	if bit.band(wHubChar, 2^7) > 0 then
		printf("%s    Port indicators\n", prefix)
	end
	printf("%s  bPwrOn2PwrGood      %3u * 2 milli seconds\n", prefix, p[6])
	printf("%s  bHubContrCurrent    %3u milli Ampere\n", prefix, p[7])
	local l = bit.rshift(p[3], 3) + 1 -- this determines the variable number of bytes following
	if l > HUB_STATUS_BYTELEN then
	 	l = HUB_STATUS_BYTELEN
	end
	printf("%s  DeviceRemovable   ", prefix)
	for i=0,l-1 do
		printf(" 0x%02x", p[8+i])
	end
	printf("\n%s  PortPwrCtrlMask   ", prefix)
 	for j=0,l-1 do
 		printf(" 0x%02x", p[8+l+j]);
	end
 	printf("\n");
end

local function do_hub(fd, has_tt)
	local bufsize = 7 --[[ base descriptor ]]
			+ 2 --[[ bitmasks ]] * assert(HUB_STATUS_BYTELEN)
--	int i, ret;
	local buf

	buf = assert(fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_CLASS,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_DESCRIPTOR,
			usb.DT_HUB * 2^8, 0,
			bufsize, CTRL_TIMEOUT))
	if #buf < 9 --[[ at least one port's bitmasks ]] then
		error()
--		if (ret >= 0)
--			fprintf(stderr,
--				"incomplete hub descriptor, %d bytes\n",
--				ret);
--		--[[ Linux returns EHOSTUNREACH for suspended devices ]]
--		else if (errno != EHOSTUNREACH)
--			perror ("can't get hub descriptor");
		return
	end
	buf = {string.byte(buf, 1, #buf)}
	dump_hub("", buf, has_tt)

	printf(" Hub Port Status:\n")
	for i=0,buf[3]-1 do
	--	unsigned char stat [4];

		local stat = assert(fd:control_transfer(
				bit.bor(
					usb.ENDPOINT_IN,
					usb.REQUEST_TYPE_CLASS,
					usb.RECIPIENT_OTHER),
				usb.REQUEST_GET_STATUS,
				0, i + 1,
				4,
				CTRL_TIMEOUT))
	--	if (ret < 0) {
	--		fprintf(stderr,
	--			"cannot read port %d status, %s (%d)\n",
	--			i + 1, strerror(errno), errno);
	--		break;
	--	}
		stat = {string.byte(stat, 1, #stat)}

		printf("   Port %d: %02x%02x.%02x%02x", i + 1,
			stat[4], stat [3],
			stat[2], stat [1])
		-- CAPS are used to highlight "transient" states
		printf("%s%s%s%s%s",
			bit.band(stat[3], 0x10) > 0 and " C_RESET" or "",
			bit.band(stat[3], 0x08) > 0 and " C_OC" or "",
			bit.band(stat[3], 0x04) > 0 and " C_SUSPEND" or "",
			bit.band(stat[3], 0x02) > 0 and " C_ENABLE" or "",
			bit.band(stat[3], 0x01) > 0 and " C_CONNECT" or "")
		printf("%s%s%s%s%s%s%s%s%s%s\n",
			bit.band(stat[2], 0x10) > 0 and " indicator" or "",
			bit.band(stat[2], 0x08) > 0 and " test" or "",
			bit.band(stat[2], 0x04) > 0 and " highspeed" or "",
			bit.band(stat[2], 0x02) > 0 and " lowspeed" or "",
			bit.band(stat[2], 0x01) > 0 and " power" or "",
			bit.band(stat[1], 0x10) > 0 and " RESET" or "",
			bit.band(stat[1], 0x08) > 0 and " oc" or "",
			bit.band(stat[1], 0x04) > 0 and " suspend" or "",
			bit.band(stat[1], 0x02) > 0 and " enable" or "",
			bit.band(stat[1], 0x01) > 0 and " connect" or "")
	end
end

local function dump_config(dev, config)
	local cfg = get_string(dev, config.iConfiguration)
	printf([[
  Configuration Descriptor:
    bLength             %5u
    bDescriptorType     %5u
    wTotalLength        %5u
    bNumInterfaces      %5u
    bConfigurationValue %5u
    iConfiguration      %5u %s
    bmAttributes         0x%02x
]],
	       config.bLength, config.bDescriptorType,
	       le16_to_cpu(config.wTotalLength),
	       config.bNumInterfaces, config.bConfigurationValue,
	       config.iConfiguration,
	       cfg, config.bmAttributes)
	if bit.band(config.bmAttributes, 0x80)==0 then
		printf("      (Missing must-be-set bit!)\n")
	end
	if bit.band(config.bmAttributes, 0x40)~=0 then
		printf("      Self Powered\n")
	else
		printf("      (Bus Powered)\n")
	end
	if bit.band(config.bmAttributes, 0x20)~=0 then
		printf("      Remote Wakeup\n");
	end
	if bit.band(config.bmAttributes, 0x10)~=0 then
		printf("      Battery Powered\n")
	end
	printf("    MaxPower            %5umA\n", config.MaxPower * 2)

	-- avoid re-ordering or hiding descriptors for display
	if config.extra then
		local size = #config.extra
		local buf = string.byte(config.extra, 1, size)

		while size >= 2 do
			local ds = string.byte(buf, 1)
			if ds < 2 then
				dump_junk(buf, "        ", size)
				break
			end
			local dt = string.byte(buf, 2)
			if dt==assert(USB_DT_OTG) then
				-- handled separately
			elseif dt==assert(USB_DT_INTERFACE_ASSOCIATION) then
				dump_association(dev, buf)
			elseif dt==assert(USB_DT_SECURITY) then
				dump_security(buf)
			elseif dt==assert(USB_DT_ENCRYPTION_TYPE) then
				dump_encryption_type(buf)
			else
				-- often a misplaced class descriptor
				printf("    ** UNRECOGNIZED: ")
				dump_bytes(buf, ds)
			end
			size = size - ds
			buf = buf:sub(ds+1)
		end
	end
	for i=1,config.bNumInterfaces do
		dump_interface(dev, config.interface[i])
	end
end

local function dump_device_status(fd, otg, wireless)
	local status,msg,errno

	status,msg,errno = fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_STATUS,
			0, 0,
			2,
			CTRL_TIMEOUT)
	if not status then
		print("cannot read device status, "..msg.." ("..errno..")")
		return
	end
	status = {string.byte(status, 1, #status)}

	printf("Device Status:     0x%02x%02x\n",
			status[2], status[1])
	if bit.band(status[1], 2^0) > 0 then
		printf("  Self Powered\n")
	else
		printf("  (Bus Powered)\n")
	end
	if bit.band(status[1], 2^1) > 0 then
		printf("  Remote Wakeup Enabled\n")
	end
	if bit.band(status[1], 2^2) > 0 then
		-- for high speed devices
		if not wireless then
			printf("  Test Mode\n")
		-- for devices with Wireless USB support
		else
			printf("  Battery Powered\n")
		end
	end
	-- if both HOST and DEVICE support OTG
	if otg then
		if bit.band(status[1], 2^3) > 0 then
			printf("  HNP Enabled\n")
		end
		if bit.band(status[1], 2^4) > 0 then
			printf("  HNP Capable\n")
		end
		if bit.band(status[1], 2^5) > 0 then
			printf("  ALT port is HNP Capable\n")
		end
	end
	-- for high speed devices with debug descriptors
	if bit.band(status[1], 2^6) > 0 then
		printf("  Debug Mode\n")
	end

	if not wireless then
		return
	end

	-- Wireless USB exposes FIVE different types of device status,
	-- accessed by distinct wIndex values.
	status = assert(fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_STATUS,
			0, 1 --[[ wireless status ]],
			1,
			CTRL_TIMEOUT))
--	if (ret < 0) {
--		fprintf(stderr,
--			"cannot read wireless %s, %s (%d)\n",
--			"status",
--			strerror(errno), errno);
--		return;
--	}
	status = {string.byte(status, 1, #status)}
	printf("Wireless Status:     0x%02x\n", status[1])
	if bit.band(status[1], 2^0) > 0 then
		printf("  TX Drp IE\n")
	end
	if bit.band(status[1], 2^1) > 0 then
		printf("  Transmit Packet\n")
	end
	if bit.band(status[1], 2^2) > 0 then
		printf("  Count Packets\n")
	end
	if bit.band(status[1], 2^3) > 0 then
		printf("  Capture Packet\n")
	end

	status = assert(fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_STATUS,
			0, 2 --[[ Channel Info ]],
			1,
			CTRL_TIMEOUT))
--	if (ret < 0) {
--		fprintf(stderr,
--			"cannot read wireless %s, %s (%d)\n",
--			"channel info",
--			strerror(errno), errno);
--		return;
--	}
	status = {string.byte(status, 1, #status)}
	printf("Channel Info:        0x%02x\n", status[1])

	-- 3=Received data: many bytes, for count packets or capture packet

	status = assert(fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_STATUS,
			0, 3 --[[ MAS Availability ]],
			8,
			CTRL_TIMEOUT))
--	if (ret < 0) {
--		fprintf(stderr,
--			"cannot read wireless %s, %s (%d)\n",
--			"MAS info",
--			strerror(errno), errno);
--		return;
--	}
	status = {string.byte(status, 1, #status)}
	printf("MAS Availability:    ")
	dump_bytes(status, 8)

	status = assert(fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_STATUS,
			0, 5 --[[ Current Transmit Power ]],
			2,
			CTRL_TIMEOUT))
--	if (ret < 0) {
--		fprintf(stderr,
--			"cannot read wireless %s, %s (%d)\n",
--			"transmit power",
--			strerror(errno), errno);
--		return;
--	}
	status = {string.byte(status, 1, #status)}
	printf("Transmit Power:\n");
	printf(" TxNotification:     0x%02x\n", status[1]);
	printf(" TxBeacon:     :     0x%02x\n", status[2]);
end

local function do_dualspeed(fd)
--	unsigned char buf [10];
--	char cls[128], subcls[128], proto[128];
--	int ret;
	local bufsize,buf = 10

	local buf,msg = fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_DESCRIPTOR,
			assert(USB_DT_DEVICE_QUALIFIER) * 2^8, 0,
			bufsize, CTRL_TIMEOUT)
	if not buf and msg~='pipe' then
		print("can't get device qualifier")
	end
	if not buf then return end
	buf = {string.byte(buf, 1, #buf)}

	-- all dual-speed devices have a qualifier
	if #buf ~= bufsize
			or buf[1] ~= #buf
			or buf[2] ~= assert(USB_DT_DEVICE_QUALIFIER) then
		return
	end

	local cls = get_class_string(buf[5])
	local subcls = get_subclass_string(buf[5], buf[6])
	local proto = get_protocol_string(buf[5], buf[6], buf[7])
	printf([[
Device Qualifier (for other device speed):
  bLength             %5u
  bDescriptorType     %5u
  bcdUSB              %2x.%02x
  bDeviceClass        %5u %s
  bDeviceSubClass     %5u %s
  bDeviceProtocol     %5u %s
  bMaxPacketSize0     %5u
  bNumConfigurations  %5u
]],
	       buf[1], buf[2],
	       buf[4], buf[3],
	       buf[5], cls,
	       buf[6], subcls,
	       buf[7], proto,
	       buf[8], buf[9])

	-- FIXME also show the OTHER_SPEED_CONFIG descriptors
end

local function do_debug(fd)
	local bufsize = 4

	local buf,msg = fd:control_transfer(
			bit.bor(
				usb.ENDPOINT_IN,
				usb.REQUEST_TYPE_STANDARD,
				usb.RECIPIENT_DEVICE),
			usb.REQUEST_GET_DESCRIPTOR,
			assert(USB_DT_DEBUG) * 2^8, 0,
			bufsize, CTRL_TIMEOUT)
	if not buf and msg~='pipe' then
		print("can't get debug descriptor")
	end
	if not buf then return end
	buf = {string.byte(buf, 1, #buf)}

	-- some high speed devices are also "USB2 debug devices", meaning
	-- you can use them with some EHCI implementations as another kind
	-- of system debug channel:  like JTAG, RS232, or a console.
	if #buf ~= bufsize
			or buf[1] ~= #buf
			or buf[12] ~= assert(USB_DT_DEBUG) then
		return
	end

	printf([[
Debug descriptor:\n"
  bLength              %4u
  bDescriptorType      %4u
  bDebugInEndpoint     0x%02x
  bDebugOutEndpoint    0x%02x
]],
	       buf[1], buf[2],
	       buf[3], buf[4])
end

local function dumpdev(dev)
	local otg,wireless

	local udev = dev:open()
	if not udev then
		printf("Couldn't open device, some information will be missing\n")
		return
	end

	local descriptor = assert(dev:get_device_descriptor())
	dump_device(udev, descriptor)
	if descriptor.bcdUSB >= 0x0250 then
		wireless = do_wireless(udev)
	end
	if descriptor.bNumConfigurations > 0 then
	--	local config = dev:get_config_descriptor(0)
	--	otg = do_otg(config) or otg
		for i=0,descriptor.bNumConfigurations-1 do
			dump_config(udev, dev:get_config_descriptor(i))
		end
	end
	
	if descriptor.bDeviceClass == usb.CLASS_HUB then
		do_hub(udev, descriptor.bDeviceProtocol)
	end
	if descriptor.bcdUSB >= 0x0200 then
		do_dualspeed(udev)
		do_debug(udev)
	end
	dump_device_status(udev, otg, wireless)
	udev:close()
end

local function list_devices(busnum, devnum, vendorid, productid)
	assert(usb.init())
	local devices = assert(usb.get_device_list())
	for _,device in ipairs(devices) do
		local descriptor = assert(device:get_device_descriptor())
		if (not vendorid or vendorid==descriptor.idVendor)
			and (not productid or productid==descriptor.idProduct) then
			local vendor = get_vendor_string(descriptor.idVendor)
			local product = get_product_string(descriptor.idVendor, descriptor.idProduct)
			if verblevel > 0 then
				printf("\n")
			end
			printf("Bus %03d Device %03d: ID %04x:%04x %s %s\n",
					device:get_bus_number(),
					device:get_device_address(),
					descriptor.idVendor,
					descriptor.idProduct,
					vendor, product);
			if verblevel > 0 then
				dumpdev(device)
			end
		end
	end
end

local busnum, devnum, vendorid, productid

local args = {...}
for i=1,#args do
	if args[i]:match("^%-[^-]") then
		for char in args[i]:sub(2):gmatch(".") do
			if char=='d' then
				vendorid,productid = args[i+1]:match("(%x+):(%x+)")
				if not vendorid then
					vendorid = args[i+1]
				end
				vendorid = tonumber(vendorid, 16)
				productid = tonumber(productid, 16)
			elseif char=='v' then
				verblevel = verblevel + 1
			elseif char=='l' then
				lua_report = true
			end
		end
	end
end

list_devices(busnum, devnum, vendorid, productid)


--[===[
local context = assert(usb.init())

local verbose = 1

local classes = {
	[0] = "(Defined at Interface level)",
	[3] = "Human Interface Device",
	[9] = "Hub",
}
local subclasses = {
	[3] = {
		[0] = "No Subclass",
		[1] = "Boot Interface Subclass",
	},
	[9] = {
		[0] = "Unused",
	},
}
local protocols = {
	[3] = {
		[0] = "None",
		[2] = "Mouse",
	},
	[9] = {
		[0] = "Full speed (or root) hub",
		[2] = "TT per port",
	},
}
local vendors = {
	[0x1d6b] = "Linux Foundation",
}
local products = {
	[0x1d6b] = {
		[0x0001] = "1.1 root hub",
		[0x0002] = "2.0 root hub",
	},
}

print(context)
local devices = assert(context:get_device_list())
local handles = {}
for i,device in ipairs(devices) do
	local descriptor = assert(device:get_device_descriptor())
	print(string.format("Bus %03d Device %03d: ID %04x:%04x %s",
		device:get_bus_number(),
		device:get_device_address(),
		descriptor.idVendor,
		descriptor.idProduct,
		""))
	
	local handle = device:open()
	handles[device] = handle

	if verbose >= 1 then
		printf("Device descriptor:\n")
		printf("  bLength                %2d\n", descriptor.bLength)
		printf("  bDescriptorType        %2d\n", descriptor.bDescriptorType)
		printf("  bcdUSB              %2x.%02x\n", math.floor(descriptor.bcdUSB/256), descriptor.bcdUSB%256)
		printf("  bDeviceClass           %2d\n", descriptor.bDeviceClass)
			..(classes[descriptor.bDeviceClass] and ' '..classes[descriptor.bDeviceClass] or '')
		printf("  bDeviceSubClass        %2d\n", descriptor.bDeviceSubClass)
			..(subclasses[descriptor.bDeviceClass] and subclasses[descriptor.bDeviceClass][descriptor.bDeviceSubClass] and ' '..subclasses[descriptor.bDeviceClass][descriptor.bDeviceSubClass] or '')
		printf("  bDeviceProtocol        %2d\n", descriptor.bDeviceProtocol)
			..(protocols[descriptor.bDeviceClass] and protocols[descriptor.bDeviceClass][descriptor.bDeviceProtocol] and ' '..protocols[descriptor.bDeviceClass][descriptor.bDeviceProtocol] or '')
		printf("  bMaxPacketSize0        %2d\n", descriptor.bMaxPacketSize0)
		printf("  idVendor           0x%04x\n", descriptor.idVendor)
			..(vendors[descriptor.idVendor] and ' '..vendors[descriptor.idVendor] or '')
		printf("  idProduct          0x%04x\n", descriptor.idProduct)
			..(products[descriptor.idVendor] and products[descriptor.idVendor][descriptor.idProduct] and ' '..products[descriptor.idVendor][descriptor.idProduct] or '')
		printf("  bcdDevice           %2x.%02x\n", math.floor(descriptor.bcdDevice/256), descriptor.bcdDevice%256)
		printf("  iManufacturer          %2d\n", descriptor.iManufacturer)
			..(descriptor.iManufacturer~=0 and handle and ' '..handle:get_string_descriptor_ascii(descriptor.iManufacturer, 1024) or '')
		printf("  iProduct               %2d\n", descriptor.iProduct)
			..(descriptor.iProduct~=0 and handle and ' '..handle:get_string_descriptor_ascii(descriptor.iProduct, 1024) or '')
		printf("  iSerial                %2d\n", descriptor.iSerialNumber)
			..(descriptor.iSerialNumber~=0 and handle and ' '..handle:get_string_descriptor_ascii(descriptor.iSerialNumber, 1024) or '')
		printf("  bNumConfigurations     %2d\n", descriptor.bNumConfigurations)

		for i=0,descriptor.bNumConfigurations-1 do
			local descriptor = device:get_config_descriptor(i)
			print("  Configuration Descriptor:\n")
			printf("    bLength                %2d\n", descriptor.bLength)
			printf("    bDescriptorType        %2d\n", descriptor.bDescriptorType)
			printf("    wTotalLength        %5d\n", descriptor.wTotalLength)
			printf("    bNumInterfaces         %2d\n", descriptor.bNumInterfaces)
			printf("    bConfigurationValue    %2d\n", descriptor.bConfigurationValue)
			printf("    iConfiguration         %2d\n", descriptor.iConfiguration)
				..(descriptor.iConfiguration~=0 and handle and ' '..handle:get_string_descriptor_ascii(descriptor.iConfiguration, 1024) or '')
			printf("    bmAttributes         0x%02x\n", descriptor.bmAttributes)
		--	printf("      Self Powered")
		--	printf("      Remote Wakeup")
			printf("    MaxPower              %3dmA\n", descriptor.MaxPower * 2)
			for i=1,descriptor.bNumInterfaces do
				local descriptor = descriptor.interface[i].altsetting[1]
				printf("    Interface Descriptor:\n")
				printf("      bLength                %2d\n", descriptor.bLength)
				printf("      bDescriptorType        %2d\n", descriptor.bDescriptorType)
				printf("      bInterfaceNumber       %2d\n", descriptor.bInterfaceNumber)
				printf("      bAlternateSetting      %2d\n", descriptor.bAlternateSetting)
				printf("      bNumEndpoints          %2d\n", descriptor.bNumEndpoints)
				printf("      bInterfaceClass        %2d\n", descriptor.bInterfaceClass)
					..(classes[descriptor.bInterfaceClass] and ' '..classes[descriptor.bInterfaceClass] or '')
				printf("      bInterfaceSubClass     %2d\n", descriptor.bInterfaceSubClass)
					..(subclasses[descriptor.bInterfaceClass] and subclasses[descriptor.bInterfaceClass][descriptor.bInterfaceSubClass] and ' '..subclasses[descriptor.bInterfaceClass][descriptor.bInterfaceSubClass] or '')
				printf("      bInterfaceProtocol     %2d\n", descriptor.bInterfaceProtocol)
					..(protocols[descriptor.bInterfaceClass] and protocols[descriptor.bInterfaceClass][descriptor.bInterfaceProtocol] and ' '..protocols[descriptor.bInterfaceClass][descriptor.bInterfaceProtocol] or '')
				printf("      iInterface             %2d\n", descriptor.iInterface)
					..(descriptor.iInterface~=0 and handle and ' '..handle:get_string_descriptor_ascii(descriptor.iInterface, 1024) or '')
				for i=1,descriptor.bNumEndpoints do
					local descriptor = descriptor.endpoint[i]
					printf("      Endpoint Descriptor:\n")
					printf("        bLength                 7\n")
					printf("        bDescriptorType         5\n")
					printf("        bEndpointAddress     0x81  EP 1 IN\n")
					printf("        bmAttributes            3\n")
					printf("          Transfer Type            Interrupt\n")
					printf("          Synch Type               None\n")
					printf("          Usage Type               Data\n")
					printf("        wMaxPacketSize     0x0004  1x 4 bytes\n")
					printf("        bInterval              12\n")
				end
			end
--			descriptor:free_config_descriptor()
		end

		if i~=#devices then
			print()
		end
	end
end


--[[
print(trackball)

print(trackball:get_descriptor(LIBUSB_DT_ENDPOINT, 0, 256))


print(trackball:interrupt_transfer(1, 8, 0))
--local result,msg = trackball:interrupt_transfer(1, 8, 0)
--print(type(result), msg)
--]]

for _,handle in pairs(handles) do
--	handle:close()
end

for _,device in ipairs(devices) do
--	device:unref_device()
end

--context:exit()

print("exited successfully")
--]===]