1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-24 00:18:26 +00:00
trezor-firmware/trezorlib/transport_serial.py

42 lines
1.2 KiB
Python
Raw Normal View History

2016-05-20 20:27:20 +00:00
from __future__ import print_function
2012-11-13 14:09:39 +00:00
'''SerialTransport implements wire transport over serial port.'''
# Local serial port loopback: socat PTY,link=COM8 PTY,link=COM9
import serial
2012-11-15 20:08:02 +00:00
from select import select
2016-05-05 01:16:17 +00:00
from .transport import Transport
2012-11-13 14:09:39 +00:00
class SerialTransport(Transport):
def __init__(self, device, *args, **kwargs):
self.serial = None
super(SerialTransport, self).__init__(device, *args, **kwargs)
2016-02-10 15:46:58 +00:00
2012-11-13 14:09:39 +00:00
def _open(self):
self.serial = serial.Serial(self.device, 115200, timeout=10, writeTimeout=10)
2016-02-10 15:46:58 +00:00
2012-11-13 14:09:39 +00:00
def _close(self):
self.serial.close()
self.serial = None
2016-02-10 15:46:58 +00:00
2012-11-15 20:08:02 +00:00
def ready_to_read(self):
rlist, _, _ = select([self.serial], [], [], 0)
return len(rlist) > 0
2016-02-10 15:46:58 +00:00
2014-07-26 14:27:28 +00:00
def _write(self, msg, protobuf_msg):
2012-11-13 14:09:39 +00:00
try:
self.serial.write(msg)
self.serial.flush()
except serial.SerialException:
2016-05-05 01:16:17 +00:00
print("Error while writing to socket")
2012-11-13 14:09:39 +00:00
raise
2016-02-10 15:46:58 +00:00
2012-11-13 14:09:39 +00:00
def _read(self):
try:
(msg_type, datalen) = self._read_headers(self.serial)
return (msg_type, self.serial.read(datalen))
except serial.SerialException:
2016-05-05 01:16:17 +00:00
print("Failed to read from device")
2014-07-26 14:27:28 +00:00
raise