-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial_handler.py
184 lines (158 loc) · 5.43 KB
/
serial_handler.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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python
# Copyright (c) Quectel Wireless Solution, Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: UTF-8 -*-
"""
@Project:Factory_test
@File:serial_handler.py
@Author:rivern.yuan
@Date:2022/9/6 15:03
"""
import serial
import time
import asyncio
class SerialPort(object):
'''
class for serial operation
'''
def __init__(self, port, baud):
self._port = port
self._baud = baud
self._conn = None
def _open_conn(self):
try:
self._conn = serial.Serial(self._port, self._baud)
return self._conn
except IOError as e:
print("Failed reason: %s" % str(e))
def _close_conn(self):
self._conn.close()
self._conn = None
def _send_cmd(self, cmd):
self._conn.write((cmd + '\r\n').encode())
def _recv_cmd(self):
time.sleep(.2)
byte_n = self._conn.inWaiting()
if byte_n > 0:
return self._conn.read(byte_n)
def _test_conn(self):
self._send_cmd("1")
# recv: b'1\r\n1\r\n>>> ' 测试正常交互
test_recv = self._recv_cmd()
if test_recv:
if len(test_recv) == 10:
return True
else:
print(test_recv)
raise SerialError(self._port, "串口持续输出中,请检查运行状态")
else:
raise SerialError(self._port, "串口堵塞,请检查串口连通性")
class SerialHandler(SerialPort):
"""write test script & read test result """
def __init__(self, port, baud=115200):
super(SerialHandler, self).__init__(port, baud)
self.init()
async def init_module(self, imei_text_ctrl, iccid_text_ctrl):
self._send_cmd("import sim")
self._send_cmd("import modem")
await asyncio.sleep(.1)
self._conn.flushInput() # 丢弃接收缓存中的所有数据
try:
self._send_cmd("modem.getDevImei()")
await asyncio.sleep(.1)
imei = self.ret_result().split("\r\n")[1]
# print("imei: {}".format(imei))
except Exception as e:
print("get imei error: {}".format(e))
imei = "-1"
finally:
imei_text_ctrl.SetValue(imei[1:-1])
try:
self._send_cmd("sim.getIccid()")
await asyncio.sleep(.1)
iccid = self.ret_result().split("\r\n")[1]
# print("iccid: {}".format(iccid))
if iccid == "-1":
iccid = "'No SIM card'"
except Exception as e:
print("get iccid error: {}".format(e))
iccid = "-1"
finally:
iccid_text_ctrl.SetValue(iccid[1:-1])
return imei[1:-1], iccid[1:-1]
def write_module(self, source, py_cmd, filename="test.py"):
try:
if self._test_conn():
self._conn.write(b"\x01")
self._send_cmd("f=open('/usr/" + filename + "','wb')") # 写入文件
self._send_cmd("w=f.write")
while True:
time.sleep(.1)
data = source.read(255)
if not data:
break
else:
self._send_cmd("w(" + repr(data) + ")")
self._conn.write(b"\x04")
self._send_cmd("f.close()")
self._conn.write(b"\x04")
self._conn.write(b"\x02")
self._conn.write(b"\x04")
# self._conn.write(b"\x02")
else:
print("串口异常")
except Exception as e:
print("文件写入异常:{}".format(e))
finally:
source.close()
return self.exec_cmd(py_cmd[0])
def exec_py(self, cmd):
self._send_cmd(cmd[0])
self._conn.flushInput()
self._send_cmd(cmd[1])
time.sleep(1)
return self.ret_result()
def exec_cmd(self, cmd):
self._send_cmd(cmd)
async def run_cmd(self,source:list, log_text_ctrl):
result_list = ""
for i in source:
self._send_cmd(i)
await asyncio.sleep(.1)
result_list += self.ret_result()
log_text_ctrl.SetValue(result_list)
return result_list
def ret_result(self):
data = ""
for i in range(30):
data += self._conn.read(self._conn.inWaiting()).decode("utf-8", errors="ignore")
if data.endswith(">>> "):
break
time.sleep(0.5)
return data
def exit_test(self):
self._close_conn()
def init(self):
self._open_conn()
class SerialError(Exception):
'''
exception for serial blocking connection
'''
def __init__(self, _port, _error):
self._port = _port
self._error = _error
def __str__(self):
return self._port + " " + self._error
if __name__ == '__main__':
ser = SerialHandler("COM63")