-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnet_manage.py
319 lines (265 loc) · 9.3 KB
/
net_manage.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# 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.
"""
@file :net_manage.py
@author :Jack Sun (jack.sun@quectel.com)
@brief :Net management.
@version :1.2.0
@date :2022-10-31 10:45:46
@copyright :Copyright (c) 2022
"""
import sys
import net
import sim
import ntptime
import osTimer
import _thread
import dataCall
import checkNet
import utime as time
try:
from modules.logging import getLogger
except ImportError:
from usr.modules.logging import getLogger
log = getLogger(__name__)
class NetManage:
"""This class is for net management."""
def __init__(self, project_name, project_version):
self.__checknet = checkNet.CheckNetwork(project_name, project_version)
self.__checknet.poweron_print_once()
@property
def status(self):
"""Read device net status.
Returns:
bool: True - net is connected, False - net is disconnected.
"""
res = False
try:
data_call_info = dataCall.getInfo(1, 0)
net_state = net.getState()
if isinstance(data_call_info, tuple) and data_call_info[2][0] == 1 and \
isinstance(net_state, tuple) and len(net_state) >= 2 and net_state[1][0] in (1, 5):
res = True
else:
res = False
except Exception as e:
sys.print_exception(e)
return res
@property
def sim_status(self):
"""Read sim card status.
Returns:
int: 1 - sim is ready, other - sim is not ready.
"""
return sim.getStatus()
def wait_connect(self, timeout=60):
"""Wait net connected.
Args:
timeout (int): timeout seconds. (default: `60`)
Returns:
tuple: (3, 1) - success, other - failed.
"""
return self.__checknet.waitNetworkReady(timeout)
def connect(self):
"""Set net connect.
Returns:
bool: True - success, False - failed.
"""
if net.setModemFun(1) == 0:
return True
return False
def disconnect(self, val=4):
"""Set net disconnect.
Args:
val (int): 0 - all close, 4 - fly mode. (default: `4`)
Returns:
bool: True - success, False - failed.
"""
if val in (0, 4) and net.setModemFun(val) == 0:
return True
return False
def reconnect(self):
"""Net reconnect.
Returns:
bool: True - success, False - failed.
"""
if self.disconnect():
time.sleep_ms(200)
return self.connect()
return False
def sync_time(self, timezone=8):
"""Sync device time from server.
Args:
timezone (int): timezone. range: [-12, 12] (default: `8`)
Returns:
bool: True - success, False - failed.
"""
return True if self.status and timezone >= -12 and timezone <= 12 and ntptime.settime(timezone) == 0 else False
def set_callback(self, callback):
"""Set callback to recive net change status.
Args:
callback (function): callback funtion.
Returns:
bool: True - success, False - failed.
"""
if callable(callback):
res = dataCall.setCallback(callback)
return True if res == 0 else False
return False
class NetManager:
def __init__(self):
self.__conn_flag = 0
self.__disconn_flag = 0
self.__reconn_flag = 0
self.__callback = None
self.__net_check_timer = osTimer()
self.__net_check_cycle = 5 * 60 * 1000
self.__reconn_tid = None
dataCall.setCallback(self.__net_callback)
def __net_callback(self, args):
log.debug("profile id[%s], net state[%s], last args[%s]" % args)
if args[1] == 0:
self.__net_check_timer.stop()
self.net_check(None)
self.__net_check_timer.start(self.__net_check_cycle, 1, self.net_check)
if callable(self.__callback):
self.__callback(args)
def set_callback(self, callback):
if callable(callback):
self.__callback = callback
return True
return False
def net_connect(self):
res = -1
if self.__conn_flag != 0:
return -2
self.__conn_flag = 1
try:
# Reconnect net.
if net.getModemFun() != 1:
_res = self.net_disconnect()
log.debug("net_connect net_disconnect %s" % _res)
time.sleep(5)
_res = net.setModemFun(1)
log.debug("net.setModemFun(1) %s" % _res)
if _res != 0:
return -3
# Check sim status
if self.sim_status() != 1:
log.error("SIM card is not ready.")
return -4
# Wait net connect.
_res = checkNet.waitNetworkReady(300)
log.debug("checkNet.waitNetworkReady %s" % str(_res))
res = 0 if _res == (3, 1) else -5
except Exception as e:
sys.print_exception(e)
log.error(str(e))
finally:
self.__conn_flag = 0
self.__net_check_timer.stop()
self.__net_check_timer.start(self.__net_check_cycle, 1, self.net_check)
return res
def net_disconnect(self):
if self.__disconn_flag != 0:
return False
self.__disconn_flag = 1
res = True if (net.setModemFun(4) == 0) else (net.setModemFun(0) == 0)
self.__net_check_timer.stop()
self.__disconn_flag = 0
return res
def net_reconnect(self):
if self.__reconn_flag != 0:
return False
self.__reconn_flag = 1
res = self.net_connect() if self.net_disconnect() else False
self.__reconn_flag = 0
self.__reconn_tid = None
return res
def net_status(self):
return True if self.sim_status() == 1 and self.net_state() and self.call_state() else False
def net_state(self):
try:
_net_state_ = net.getState()
log.debug("net.getState() %s" % str(_net_state_))
return True if isinstance(_net_state_, tuple) and len(_net_state_) >= 2 and _net_state_[1][0] in (1, 5) else False
except Exception as e:
sys.print_exception(e)
log.error(str(e))
return False
def net_config(self, state=None):
if state is None:
return net.getConfig()
elif state in (0, 5, 6):
return (net.setConfig(state) == 0)
return False
def net_mode(self):
_net_mode_ = net.getNetMode()
if _net_mode_ == -1 or not isinstance(_net_mode_, tuple) or len(_net_mode_) < 4:
return -1
if _net_mode_[3] in (0, 1, 3):
return 2
elif _net_mode_[3] in (2, 4, 5, 6, 8):
return 3
elif _net_mode_[3] in (7, 9):
return 4
return -1
def net_check(self, args):
if not self.net_status():
try:
if not self.__reconn_tid or (self.__reconn_tid and not _thread.threadIsRunning(self.__reconn_tid)):
_thread.stack_size(0x2000)
self.__reconn_tid = _thread.start_new_thread(self.net_reconnect, ())
except Exception as e:
sys.print_exception(e)
log.error(str(e))
def call_state(self):
try:
call_info = self.call_info()
log.debug("dataCall.getInfo %s" % str(call_info))
return True if isinstance(call_info, tuple) and len(call_info) >= 3 and call_info[2][0] == 1 else False
except Exception as e:
sys.print_exception(e)
log.error(str(e))
return False
def call_info(self):
return dataCall.getInfo(1, 0)
def sim_status(self):
# # Check net modem.
# if net.getModemFun() == 0:
# net.setModemFun(1)
# Check sim status.
count = 0
while sim.getStatus() == -1 and count < 3:
time.sleep_ms(100)
count += 1
return sim.getStatus()
def sim_imsi(self):
return sim.getImsi()
def sim_iccid(self):
return sim.getIccid()
def signal_csq(self):
return net.csqQueryPoll()
def signal_level(self):
signal = self.signal_csq()
_signal_level_ = int(signal * 5 / 31) if 0 <= signal <= 31 else 0
return _signal_level_
def sync_time(self, timezone=8):
"""Sync device time from server.
Args:
timezone (int): timezone. range: [-12, 12] (default: `8`)
Returns:
bool: True - success, False - failed.
"""
return (self.net_status() and timezone in range(-12, 13) and ntptime.settime(timezone) == 0)