forked from peplin/pygatt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial_mock.py
48 lines (39 loc) · 1.23 KB
/
serial_mock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# for Python 2/3 compatibility
try:
import queue
except ImportError:
import Queue as queue
from mock import MagicMock
class SerialMock(object):
"""
Spoof a serial.Serial object.
"""
def __init__(self, port, timeout):
self._isOpen = True
self._port = port
self._timeout = timeout
self._output_queue = queue.Queue()
self._active_packet = None
self._expected_input_queue = queue.Queue()
def open(self):
self._isOpen = True
def close(self):
self._isOpen = False
write = MagicMock()
def flush(self):
pass
def read(self):
if self._active_packet is None:
try:
self._active_packet = self._output_queue.get_nowait()
except queue.Empty:
# When no bytes to read, serial.read() returns empty bytes
return bytes()
read_byte = self._active_packet[0]
if len(self._active_packet) == 1: # we read the last byte
self._active_packet = None
else:
self._active_packet = self._active_packet[1:]
return bytearray([read_byte])
def stage_output(self, next_output):
self._output_queue.put(bytearray(next_output))