本文整理汇总了Python中hid.device方法的典型用法代码示例。如果您正苦于以下问题:Python hid.device方法的具体用法?Python hid.device怎么用?Python hid.device使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hid
的用法示例。
在下文中一共展示了hid.device方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remote_property
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def remote_property(name, get_command, set_command, field_name, doc=None):
"""Property decorator that facilitates writing properties for values from a remote device.
Arguments:
name: The field name to use on the local object to store the cached property.
get_command: A function that returns the remote value of the property.
set_command: A function that accepts a new value for the property and sets it remotely.
field_name: The name of the field to retrieve from the response message to get operations.
"""
def getter(self):
try:
return getattr(self, name)
except AttributeError:
value = getattr(self.sendCommand(get_command()), field_name)
setattr(self, name, value)
return value
def setter(self, value):
setattr(self, name, value)
self.sendCommand(set_command(value))
return property(getter, setter, doc=doc)
示例2: hid_open
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def hid_open(self, send_magic_table=True):
""" Open connection to HID device. If connection is already open,
then only the counter of requests is incremented (so hid_close()
knows how many sub-processes keep the HID handle)
Parameters
----------
send_magic_table : bool
If True then the internal "magic table" will be sent to
the device (it is used for decryption)
"""
if self._status == 0:
# If connection was not opened before
self._h.open(self._info['vendor_id'], self._info['product_id'])
if send_magic_table:
self._h.send_feature_report(self._magic_table)
self._status += 1
示例3: __init__
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def __init__(self, vendor_id=None, product_id=None):
self.vendor_id = vendor_id
self.product_id = product_id
self.emi_version = None
self._dev = hid.device()
self._dev.open(self.vendor_id, self.product_id)
self._dev.set_nonblocking(1)
self.serial = self._dev.get_serial_number_string()
active_emi = self._get_active_emi_type()
if active_emi:
self.emi_version = active_emi
else:
self._get_supported_emi_type()
self._set_emi_type()
self._check_bus_connection_status()
self._get_device_descriptor()
self.init_connection()
self._check_bus_connection_status()
示例4: hid_close
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def hid_close(self, force=False):
""" Close connection to HID device. If there were several hid_open()
attempts then the connection will be closed only after respective
number of calls to hid_close() method
Parameters
----------
force : bool
Force-close of connection irrespectively of the counter of
open requests
"""
if force:
self._status = 0
elif self._status > 0:
self._status -= 1
if self._status == 0:
self._h.close()
示例5: init
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def init():
"""Connect to the keyboard, switch all lights off"""
global bufferC # Buffer with the full key/lights mapping
global device
print("Opening Keyboard device...")
device=hid.device()
try:
device.open(NATIVE_INSTRUMENTS, INSTR_ADDR)
except Exception as e:
print("Error: " + str(e))
quit()
device.write([0xa0])
bufferC = [0x00] * 249
notes_off()
return True
示例6: start_encryption
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def start_encryption(self):
# setup encryption on the link
# - pick our own key pair, IV for AES
# - send IV and pubkey to device
# - it replies with own pubkey
# - determine what the session key was/is
pubkey = self.ec_setup()
msg = CCProtocolPacker.encrypt_start(pubkey)
his_pubkey, fingerprint, xpub = self.send_recv(msg, encrypt=False)
self.session_key = self.ec_mult(his_pubkey)
# capture some public details of remote side's master key
# - these can be empty/0x0 when no secrets on device yet
self.master_xpub = str(xpub, 'ascii')
self.master_fingerprint = fingerprint
#print('sess key = %s' % b2a_hex(self.session_key))
self.aes_setup(self.session_key)
示例7: check_mitm
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def check_mitm(self, expected_xpub=None, sig=None):
# Optional? verification against MiTM attack:
# Using the master xpub, check a signature over the session public key, to
# verify we talking directly to the real Coldcard (no active MitM between us).
# - message is just the session key itself; no digests or prefixes
# - no need for this unless concerned about *active* mitm on USB bus
# - passive attackers (snoopers) will get nothing anyway, thanks to diffie-helman sauce
# - unfortunately might be too slow to do everytime?
xp = expected_xpub or self.master_xpub
assert xp, "device doesn't have any secrets yet"
assert self.session_key, "connection not yet in encrypted mode"
# this request is delibrately slow on the device side
if not sig:
sig = self.send_recv(CCProtocolPacker.check_mitm(), timeout=5000)
assert len(sig) == 65
ok = self.mitm_verify(sig, xp)
if ok != True:
raise RuntimeError("Possible active MiTM attack in progress! Incorrect signature.")
示例8: __init__
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def __init__(self, path, password='', expert=False):
super(LedgerClient, self).__init__(path, password, expert)
if path.startswith('tcp'):
split_path = path.split(':')
server = split_path[1]
port = int(split_path[2])
self.dongle = DongleServer(server, port, logging.getLogger().getEffectiveLevel() == logging.DEBUG)
else:
device = hid.device()
device.open_path(path.encode())
device.set_nonblocking(True)
self.dongle = HIDDongleHIDAPI(device, True, logging.getLogger().getEffectiveLevel() == logging.DEBUG)
self.app = btchip(self.dongle)
# Must return a dict with the xpub
# Retrieves the public key at the specified BIP 32 derivation path
示例9: open
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def open(self) -> None:
self.handle = hid.device()
try:
self.handle.open_path(self.path)
except (IOError, OSError) as e:
if sys.platform.startswith("linux"):
e.args = e.args + (UDEV_RULES_STR,)
raise e
# On some platforms, HID path stays the same over device reconnects.
# That means that someone could unplug a Trezor, plug a different one
# and we wouldn't even know.
# So we check that the serial matches what we expect.
serial = self.handle.get_serial_number_string()
if serial != self.serial:
self.handle.close()
self.handle = None
raise TransportException(
"Unexpected device {} on path {}".format(serial, self.path.decode())
)
self.handle.set_nonblocking(True)
if self.hid_version is None:
self.hid_version = self.probe_hid_version()
示例10: send_frame
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def send_frame(data, device):
data = bytearray(data)
data_len = len(data)
seq = 0
idx = 0
write = []
while idx < data_len:
if idx == 0:
# INIT frame
write = data[idx: idx + min(data_len, usb_report_size - 7)]
device.write(b'\0' + struct.pack(">IBH", HWW_CID, HWW_CMD, data_len & 0xFFFF) + write + b'\xEE' * (usb_report_size - 7 - len(write)))
else:
# CONT frame
write = data[idx: idx + min(data_len, usb_report_size - 5)]
device.write(b'\0' + struct.pack(">IB", HWW_CID, seq) + write + b'\xEE' * (usb_report_size - 5 - len(write)))
seq += 1
idx += len(write)
示例11: read_frame
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def read_frame(device):
# INIT response
read = bytearray(device.read(usb_report_size))
cid = ((read[0] * 256 + read[1]) * 256 + read[2]) * 256 + read[3]
cmd = read[4]
data_len = read[5] * 256 + read[6]
data = read[7:]
idx = len(read) - 7
while idx < data_len:
# CONT response
read = bytearray(device.read(usb_report_size))
data += read[5:]
idx += len(read) - 5
assert cid == HWW_CID, '- USB command ID mismatch'
assert cmd == HWW_CMD, '- USB command frame mismatch'
return data
示例12: send_plain
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def send_plain(msg, device):
reply = ""
try:
if isinstance(device, BitboxSimulator):
r = device.send_recv(msg)
else:
firm_ver = get_firmware_version(device)
if (firm_ver[0] == 2 and firm_ver[1] == 0) or (firm_ver[0] == 1):
hidBufSize = 4096
device.write('\0' + msg + '\0' * (hidBufSize - len(msg)))
r = bytearray()
while len(r) < hidBufSize:
r += bytearray(device.read(hidBufSize))
else:
send_frame(msg, device)
r = read_frame(device)
r = r.rstrip(b' \t\r\n\0')
r = r.replace(b"\0", b'')
r = to_string(r, 'utf8')
reply = json.loads(r)
except Exception as e:
reply = json.loads('{"error":"Exception caught while sending plaintext message to DigitalBitbox ' + str(e) + '"}')
return reply
示例13: __init__
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def __init__(self, path, password, expert=False):
super(DigitalbitboxClient, self).__init__(path, password, expert)
if not password:
raise NoPasswordError('Password must be supplied for digital BitBox')
if path.startswith('udp:'):
split_path = path.split(':')
ip = split_path[1]
port = int(split_path[2])
self.device = BitboxSimulator(ip, port)
else:
self.device = hid.device()
self.device.open_path(path.encode())
self.password = password
# Must return a dict with the xpub
# Retrieves the public key at the specified BIP 32 derivation path
示例14: get_pubkey_at_path
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def get_pubkey_at_path(self, path):
if '\'' not in path and 'h' not in path and 'H' not in path:
raise BadArgumentError('The digital bitbox requires one part of the derivation path to be derived using hardened keys')
reply = send_encrypt('{"xpub":"' + path + '"}', self.password, self.device)
if 'error' in reply:
raise DBBError(reply)
if self.is_testnet:
result = {'xpub': xpub_main_2_test(reply['xpub'])}
else:
result = {'xpub': reply['xpub']}
if self.expert:
xpub_obj = ExtendedKey()
xpub_obj.deserialize(reply['xpub'])
result.update(xpub_obj.get_printable_dict())
return result
# Must return a hex string with the signed transaction
# The tx must be in the PSBT format
示例15: setup_device
# 需要导入模块: import hid [as 别名]
# 或者: from hid import device [as 别名]
def setup_device(self, label='', passphrase=''):
# Make sure this is not initialized
reply = send_encrypt('{"device" : "info"}', self.password, self.device)
if 'error' not in reply or ('error' in reply and (reply['error']['code'] != 101 and reply['error']['code'] != '101')):
raise DeviceAlreadyInitError('Device is already initialized. Use wipe first and try again')
# Need a wallet name and backup passphrase
if not label or not passphrase:
raise BadArgumentError('The label and backup passphrase for a new Digital Bitbox wallet must be specified and cannot be empty')
# Set password
to_send = {'password': self.password}
reply = send_plain(json.dumps(to_send).encode(), self.device)
# Now make the wallet
key = stretch_backup_key(passphrase)
backup_filename = format_backup_filename(label)
to_send = {'seed': {'source': 'create', 'key': key, 'filename': backup_filename}}
reply = send_encrypt(json.dumps(to_send).encode(), self.password, self.device)
if 'error' in reply:
return {'success': False, 'error': reply['error']['message']}
return {'success': True}
# Wipe this device