python-trezor/trezorlib/device_udp.py

71 lines
2.2 KiB
Python

# This file is part of the TREZOR project.
#
# Copyright (C) 2012-2016 Marek Palatinus <slush@satoshilabs.com>
# Copyright (C) 2012-2016 Pavol Rusnak <stick@satoshilabs.com>
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
'''UDP Socket implementation of Device'''
import socket
class UdpDevice(object):
def __init__(self, path):
super(UdpDevice, self).__init__(path)
self.sock = None
@staticmethod
def enumerate():
devices = []
DEFAULT = ('127.0.0.1', 21324) # default host and port
for path in [DEFAULT]:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(path)
sock.settimeout(10)
sock.sendall(b'PINGPING')
data = sock.recv(8)
if data == b'PONGPONG':
devices.append(path)
sock.close()
except:
pass
return devices
def open(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.connect(self.path)
self.sock.settimeout(10)
def close(self):
self.sock.close()
self.sock = None
def write_chunk(self, chunk):
if len(chunk) != 64:
raise Exception('Unexpected data length')
self.sock.sendall(chunk)
def read_chunk(self):
while True:
try:
data = self.sock.recv(64)
break
except socket.timeout:
continue
if len(data) != 64:
raise Exception('Unexpected chunk size: %d' % len(data))
return bytearray(data)