import struct
import hid
import argparse
import sys

CMD_GET_USAGE_TIME = ord('Z')
CMD_GET_FW_VERSION = ord('*')
CMD_GET_BOARD_SERIAL = ord('%')
CMD_GET_HMD_SERIAL = ord('&')
CMD_GET_TRACKING_SERIAL = ord('~')
CMD_SUCCESS = ord('$')
CMD_ERROR = ord('E')

def wait_for_hid_packet(hid_handle: hid.Device, matching_tags: list):
    recbytes = b''
    while(len(recbytes) == 0):
        recbytes = hid_handle.read(65, 0)
        if((len(recbytes) > 0) and (recbytes[0] in matching_tags)):
            return recbytes
        recbytes = b''

# open the HID device
bigs = hid.Device(vid = 0x35bd, pid = 0x0101)
# send the request
reqs = bytes([CMD_GET_BOARD_SERIAL])
bigs.send_feature_report(bytes([0]) + reqs)
# wait for reply
pktback = wait_for_hid_packet(bigs, [CMD_GET_BOARD_SERIAL, CMD_ERROR])
if(pktback[0] == CMD_GET_BOARD_SERIAL):
    #print(', '.join(['{:02X}'.format(bb) for bb in pktback]))
    print('board serial ',end='')
    print(pktback[1:].decode('utf8'))
else:
    print('Error - couldn\'t get data')
    
    
reqs = bytes([CMD_GET_USAGE_TIME,0])
bigs.send_feature_report(bytes([0]) + reqs)
# wait for reply
pktback = wait_for_hid_packet(bigs, [CMD_GET_USAGE_TIME, CMD_ERROR])
if(pktback[0] == CMD_GET_USAGE_TIME):
    print('usage time (0) ',end='')
    unpacked = struct.unpack('<I',pktback[1:5])
    print(str(unpacked[0]))
    #print(', '.join(['{:02X}'.format(bb) for bb in pktback]))
    #print(pktback[1:].decode('utf8'))
else:
    print('Error - couldn\'t get data')
    
reqs = bytes([CMD_GET_USAGE_TIME,1])
bigs.send_feature_report(bytes([0]) + reqs)
# wait for reply
pktback = wait_for_hid_packet(bigs, [CMD_GET_USAGE_TIME, CMD_ERROR])
if(pktback[0] == CMD_GET_USAGE_TIME):
    print('usage time (1) ',end='')
    unpacked = struct.unpack('<I',pktback[1:5])
    print(str(unpacked[0]))
    #print(', '.join(['{:02X}'.format(bb) for bb in pktback]))
    #print(pktback[1:].decode('utf8'))
else:
    print('Error - couldn\'t get data')
    
reqs = bytes([CMD_GET_USAGE_TIME,2])
bigs.send_feature_report(bytes([0]) + reqs)
# wait for reply
pktback = wait_for_hid_packet(bigs, [CMD_GET_USAGE_TIME, CMD_ERROR])
if(pktback[0] == CMD_GET_USAGE_TIME):
    print('usage time (2) ',end='')
    unpacked = struct.unpack('<I',pktback[1:5])
    print(str(unpacked[0]))
    #print(', '.join(['{:02X}'.format(bb) for bb in pktback]))
    #print(pktback[1:].decode('utf8'))
else:
    print('Error - couldn\'t get data')