-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclass_sim800.py
More file actions
78 lines (61 loc) · 1.89 KB
/
class_sim800.py
File metadata and controls
78 lines (61 loc) · 1.89 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from pyb import UART
import uasyncio as asyncio
import utime as time
class sim_uart():
def __init__(self, uart_no = 2, timeout=4000):
self.uart = UART(uart_no, 9600, timeout=timeout)
self.loop = asyncio.get_event_loop()
self.deadline = None
self.result = ''
async def writeline(self, command):
self.uart.write("{}\r\n".format(command))
print("<", command)
async def write(self, command):
self.uart.write("{}".format(command))
print("<", command)
def stop(self, in_advance=False):
if not in_advance:
print("no time left - deadline")
else:
print("stopped in advance - found expected string")
self.deadline = None
def running(self):
return self.deadline is not None
def postpone(self, duration = 1000):
self.deadline = time.ticks_add(time.ticks_ms(), duration)
def read(self, expect=None, duration=1000):
self.result = ''
self.postpone(duration)
self.loop.create_task(self.read_killer(expect, duration))
async def read_killer(self, expect=None, duration=1000):
time_left = time.ticks_diff(self.deadline, time.ticks_ms())
while time_left > 0:
line = self.uart.readline()
if line:
line = convert_to_string(line)
print(">", line)
self.result += line
if expect and line.find(expect)==0:
# if expect and expect in line:
self.stop(True)
return True
self.postpone(duration)
time_left = time.ticks_diff(self.deadline, time.ticks_ms())
self.stop()
async def command(self, command, expect=None, duration=1000):
await self.writeline(command)
self.read(expect, duration)
while self.running():
await asyncio.sleep(0.2) # Pause 0.2s
result = self.result
return result
def convert_to_string(buf):
try:
tt = buf.decode('utf-8').strip()
return tt
except UnicodeError:
tmp = bytearray(buf)
for i in range(len(tmp)):
if tmp[i]>127:
tmp[i] = ord('#')
return bytes(tmp).decode('utf-8').strip()