Repository navigation
Expand file tree
/
Copy pathsocketIot.py
More file actions
273 lines (238 loc) · 8.72 KB
/
Copy pathsocketIot.py
File metadata and controls
273 lines (238 loc) · 8.72 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
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
# 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.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file :tcp.py
@author :Elian.wang (elian.wang@quectel.com)
@version :1.0.0
@date :2022-08-05 10:48:43
@copyright :Copyright (c) 2022
"""
try:
import usys # type: ignore
except ImportError:
import sys as usys
import utime
import _thread
import usocket
from usr.modules.logging import getLogger
from usr.modules.common import CloudObservable
from usr.modules.common import option_lock, Singleton
logger = getLogger(__name__)
_socket_lock = _thread.allocate_lock()
class Socket(CloudObservable):
"""This class is tcp socket"""
def __init__(self, ip_type=None, protocol = "TCP", keep_alive=None, domain=None, port=None):
super().__init__()
if protocol == "TCP" or protocol == None:
self.__protocol = "TCP"
else:
self.__protocol = "UDP"
if ip_type == "IPv6":
self.__ip_type = usocket.AF_INET6
else:
self.__ip_type = usocket.AF_INET
self.__port = port
self.__domain = domain
self.__addr = None
self.__socket = None
self.__socket_args = []
self.__timeout = 50
self.__keep_alive = keep_alive
self.__listen_thread_id = None
self.__init_addr()
self.__init_socket()
def __init_addr(self):
"""Get ip and port from domain.
Raises:
ValueError: Domain DNS parsing falied.
"""
if self.__domain is not None:
if self.__port is None:
self.__port = 8883 if self.__domain.startswith("https://") else 1883
try:
addr_info = usocket.getaddrinfo(self.__domain, self.__port)
self.__ip = addr_info[0][-1][0]
except Exception as e:
usys.print_exception(e) # type: ignore
raise ValueError("Domain %s DNS parsing error. %s" % (self.__domain, str(e)))
self.__addr = (self.__ip, self.__port)
def __init_socket(self):
"""Init socket by ip, port and method
Raises:
ValueError: ip or domain or method is illegal.
"""
if self.__protocol == 'TCP':
socket_type = usocket.SOCK_STREAM
socket_proto = usocket.IPPROTO_TCP
elif self.__protocol == 'UDP':
socket_type = usocket.SOCK_DGRAM
socket_proto = usocket.IPPROTO_UDP
else:
raise ValueError("Args method is TCP or UDP, not %s" % self.__protocol)
self.__socket_args = (self.__ip_type, socket_type, socket_proto)
@option_lock(_socket_lock)
def __connect(self):
"""Socket connect when method is TCP
Returns:
bool: True - success, False - falied
"""
if self.__socket_args:
try:
self.__socket = usocket.socket(*self.__socket_args)
if self.__protocol == "TCP":
if (
self.__addr is None
or not isinstance(self.__addr, tuple)
or None in self.__addr
):
raise ValueError("Socket address is not properly initialized: %s" % str(self.__addr))
self.__socket.connect(self.__addr)
return True
except Exception as e:
usys.print_exception(e) # type: ignore
return False
@option_lock(_socket_lock)
def __disconnect(self):
"""Socket disconnect
Returns:
bool: True - success, False - falied
"""
if self.__socket is not None:
try:
self.__socket.close()
self.__socket = None
return True
except Exception as e:
usys.print_exception(e) # type: ignore
return False
else:
return True
def __recv(self):
"""Read data by socket.
"""
while True:
data = b""
try:
if self.__socket is not None:
data = self.__socket.recv(1024)
except Exception as e:
if e.args[0] != 110:
logger.error("%s read falied. error: %s" % (self.__protocol, str(e)))
break
else:
if data != b"":
try:
self.notifyObservers(self, *("raw_data", {"topic":None, "data":data} ) )
except Exception as e:
logger.error("{}".format(e))
utime.sleep_ms(50)
@option_lock(_socket_lock)
def __send(self, data):
"""Send data by socket.
Args:
data(str): To be send data
Returns:
bool: True - success, False - falied.
"""
if self.__socket is not None:
try:
write_data_num = self.__socket.write(data)
if write_data_num == len(data):
return True
except Exception as e:
usys.print_exception(e) # type: ignore
return False
def __listen(self):
self.__listen_thread_id = _thread.start_new_thread(self.__recv, ())
def init(self, enforce=False):
"""Socket connect and register receive thread
Args:
enforce (bool, optional): Whether to force initialization. Defaults to False.
Returns:
bool: True - success, False - falied.
"""
if enforce is False:
if self.get_status() == 0:
return True
if self.__socket is not None:
try:
self.__disconnect()
except Exception as e:
logger.error("tcp disconnect falied. %s" % e)
try:
if self.__listen_thread_id is not None:
_thread.stop_thread(self.__listen_thread_id) # type: ignore
except Exception as e:
logger.error("stop listen thread falied. %s" % e)
# FIX: when connect failed we return False instead of raise Exception for another try(self.init when post data.)
if not self.__connect():
return False
if self.__socket is None:
logger.error("socket connect failed.")
raise Exception("socket connect failed")
if self.__keep_alive != 0:
try:
self.__socket.setsockopt(usocket.SOL_SOCKET, usocket.TCP_KEEPALIVE, self.__keep_alive)
except Exception as e:
self.__socket.close()
logger.error("socket option set error:", e)
raise Exception("socket option set error")
self.__socket.settimeout(self.__timeout)
# Start receive socket data
self.__listen()
logger.debug("self.get_status(): %s" % self.get_status())
if self.get_status() == 0:
return True
else:
return False
def get_status(self):
"""Get socket connection status
Returns:
[int]:
-1: Error
0: Connected
1: Connecting
2: Disconnect
"""
_status = -1
if self.__socket is not None:
try:
if self.__protocol == "TCP":
socket_sta = self.__socket.getsocketsta()
if socket_sta in range(4):
# Connecting
_status = 1
elif socket_sta == 4:
# Connected
_status = 0
elif socket_sta in range(5, 11):
# Disconnect
_status = 2
elif self.__protocol == "UDP":
_status = 0
except Exception as e:
usys.print_exception(e) # type: ignore
return _status
def through_post_data(self, data, topic_id):
return self.__send(data)
def post_data(self, data):
return False
def ota_request(self):
return False
def ota_action(self, action, module=None):
return False
def device_report(self):
return False