1+ #!/usr/bin/env python
2+
13import re
24import binascii
5+ import crcmod .predefined
6+ import struct
37
48#DEVICE_HID_VID = 0x04d8
59#DEVICE_HID_PID = 0x0f32
1014KIT_APP_COMMAND_SET_TIME = 0
1115
1216
17+ def kit_crc (data ):
18+ """Return bytes object of the crc based on the input data bytes"""
19+ crc16 = crcmod .predefined .Crc ('crc-16' )
20+ crc16 .update (bytes (data ))
21+ return struct .pack ('<H' , int ('{:016b}' .format (crc16 .crcValue )[::- 1 ], 2 ))
22+
23+
1324class KitError (Exception ):
1425 def __init__ (self , error_info ):
1526 self .error_code = error_info ['error_code' ]
@@ -23,7 +34,7 @@ def __init__(self, device):
2334 self .report_size = 64
2435 self .next_app_cmd_id = 0
2536 self .app_responses = {}
26- self .kit_reply_regex = re .compile ('^ ([0-9a-zA-Z]{2})\\ (([^)]*)\\ )' )
37+ self .kit_reply_regex = re .compile ('([0-9a-zA-Z]{2})\\ (([^)]*)\\ )' )
2738
2839 def open (self , vendor_id = DEVICE_HID_VID , product_id = DEVICE_HID_PID ):
2940 """Opens HID device for the Kit. Adjusts default VID/PID for the kit."""
@@ -58,7 +69,7 @@ def kit_read(self, timeout_ms=0):
5869 data = data [:data .index (10 )+ 1 ] # Trim any data after the newline
5970 return '' .join (map (chr , data )) # Convert data from list of integers into string
6071
61- def parse_kit_reply (self , data ):
72+ def kit_parse_reply (self , data ):
6273 """Perform basic parsing of the kit protocol replies.
6374
6475 - XX(YYZZ...)
@@ -68,3 +79,26 @@ def parse_kit_reply(self, data):
6879 if match is None :
6980 raise ValueError ('Unable to parse kit protocol reply: %s' % data )
7081 return {'status' : int (match .group (1 ), 16 ), 'data' : match .group (2 )}
82+
83+ def kit_list (self , idx ):
84+ """Request the address of the device associated with the index"""
85+ self .kit_write ('b:d' , struct .pack ("<B" , idx ))
86+ return int (self .kit_parse_reply (self .kit_read (0 ))['data' ], 16 )
87+
88+ def kit_select (self , dev ):
89+ """Select the device with the given address"""
90+ self .kit_write ('e:p:s' , struct .pack ("<B" , dev ))
91+ return self .kit_read (0 )
92+
93+ def kit_command (self , opcode , param1 , param2 , data = b'' , timeout_ms = 0 ):
94+ l2s = len (data ) + 7 # length(1) + opcode(1) + param1(1) + param2(2) + crc(2)
95+ # Make Packet
96+ d2s = struct .pack ("<BBBH" , l2s , opcode , param1 , param2 )
97+ # Append CRC
98+ d2s += kit_crc (d2s )
99+ # Send the command
100+ self .kit_write ('e:t' , d2s )
101+ # Get the response
102+ resp = self .kit_read (timeout_ms = timeout_ms )
103+ # Parse the response
104+ return self .kit_parse_reply (resp )
0 commit comments