-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserial.py
More file actions
339 lines (260 loc) · 9.35 KB
/
serial.py
File metadata and controls
339 lines (260 loc) · 9.35 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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the uPiot project, https://github.com/gepd/upiot/
#
# MIT License
#
# Copyright (c) 2017 GEPD
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sublime
from time import sleep
from ..tools import pyserial
from ..tools import SETTINGS_NAME
from .pyserial.tools import list_ports
from ..tools import errors
from ..tools import status_color
in_use = []
serial_dict = {}
setting_key = 'serial_port'
class Serial:
def __init__(self, port, baudrate=115200, timeout=1):
self._serial = pyserial.Serial()
self._serial.port = port
self._serial.baudrate = baudrate
self._serial.timeout = timeout
self._serial.dtr = False
self._serial.rts = False
self._serial.interCharTimeout = 1
self._stop_task = True
def open(self):
"""Open port
Opens the port given in the construct.
_stop_task: is used to avoid an error when it's closed.
in_use: list of port already open
serial_dict: dictionary with the serial object
"""
global in_use
global serial_dict
self._serial.open()
self._stop_task = False
# store port used
port = self._serial.port
if(port not in in_use):
in_use.append(port)
serial_dict[port] = self
def raw(self):
"""Return Serial object
Returns the Serial object from pyserial instead of this serial class
Returns:
Serial -- serial object
"""
return self._serial
def stop_task(self):
"""Stop keep listen
Stops the keep_listen loop and flush the in and out serial data
"""
self._stop_task = True
self.flush()
def receive(self):
"""Receive data
Receive the data from the selected port
Returns:
bytes -- Bytes read from the port
"""
return self._serial.readline()
def readable(self):
"""Convert data from byte to string
Returns in a readable characters/string the byte data received in
the serial port. It will also replace the end lines to be compatible
with the Sublime Text end lines (\n)
Returns:
str -- readable received data
"""
data = self.receive()
data = data.decode('utf-8', 'replace')
data = data.replace('\r\n', '\n'). replace('\r', '\n')
return data
def is_running(self):
"""Check if the port is running
This method will be set to false before the port is closed, it will
avoid to get the overlaped error, when the is_open object is used
Returns:
bool -- True if the port is running (open) false if not
"""
return self._serial.is_open
def write(self, data):
"""Write bytedata to the port
Writes bytedata to the selected serial port
Arguments:
data {byte} -- data to send
Returns:
int -- Number of bytes written.
"""
return self._serial.write(data)
def writable(self, data, line_ending='\r\n'):
"""Write bytes from string
Writes bytes in the selected port from the readable string sent
Arguments:
data {str} -- data to send
Returns:
int -- Number of bytes written.
"""
data = line_ending if data == ' ' else data + line_ending
data = data.encode('utf-8', 'replace')
return self._serial.write(data)
def keep_listen(self, printer):
"""Listen port
Listen for new data in the selected port
Arguments:
printer {obj} -- function or method to print the data
"""
# clean in and out
sleep(1.5)
self.flush()
self._stop_task = False
while(not self._stop_task):
try:
data = self.readable()
except pyserial.serialutil.SerialException:
self.disconnect()
self.destroy()
printer("\n\nSerialError: device disconected")
break
if(not printer):
break
if(data.strip()):
printer(data)
def flush(self):
"""Clean input and output
Cleans the input and output in the connected serial port
"""
if(self.is_running):
self._serial.flushOutput()
self._serial.flushInput()
def disconnect(self):
self._stop_task = True
self._serial.close()
def destroy(self, clean_color=True):
"""Close serial connection
Closes the serial connection in the port selected.
_stop_task will be updated before close the port to avoid the overlaped
error,
"""
port = self._serial.port
in_use.remove(port)
del serial_dict[port]
if(clean_color):
status_color.set("error", 2000)
def establish_connection(port):
"""establish serial connection and listen
Establishs a connection in the given port and if the printer_callback is
given, calls to keep_listen to receive new data from the port
Arguments:
port {str} -- port name to make the connection
"""
from ..tools import message
from threading import Thread
global serial_dict
try:
link = serial_dict[port]
except:
link = Serial(port)
txt = message.open(port)
if(not link.is_running()):
try:
link.open()
except pyserial.serialutil.SerialException as e:
if('could not open port' in str(e)):
txt.print(errors.serialError_noaccess)
status_color.remove()
return
status_color.set("success")
Thread(target=link.keep_listen, args=(txt.print,)).start()
def ports_list():
"""List of serial ports
Return the list of serial ports availables on the system.
Returns:
[list/list] -- list of list like [['port1 fullname',
port_name]['port2 fullname', 'port_name']]
"""
ports = list(list_ports.comports())
dev_names = ['ttyACM', 'ttyUSB', 'tty.', 'cu.']
serial_ports = []
for port_no, description, address in ports:
for dev_name in dev_names:
if(address != 'n/a' and
dev_name in port_no or sublime.platform() == 'windows'):
serial_ports.append([description, port_no])
break
return serial_ports
def check_port(port):
"""Check serial port
Checks if the given serial port exits or if isn't busy
Arguments:
port {str} -- serial port name
Returns:
bool -- True if exist/not busy False if not
"""
serial = pyserial.Serial()
serial.port = port
try:
serial.open()
except pyserial.serialutil.SerialException as e:
if('PermissionError' in str(e)):
print("Your port is busy")
return False
elif('FileNotFoundError' in str(e)):
print("Port not found")
return False
return True
def selected_port(request_port=False):
"""Get serial port
If there is only one port available, it will be automatically used,
even if it is not in the preferences, if there is more than one port,
the user selection will be used, if not setting stored or it's outdated
one, the user will prompted to select one.
Keyword Arguments:
request_port {bool} -- True: show the quick panel to select a port if
there no selection or the selected one is not avaialble
anymore (default: {False})
Returns:
str -- selected port, false with any problem
"""
ports = ports_list()
if(ports):
items = []
for port in ports:
items.append(port[1])
ports = items
settings = sublime.load_settings(SETTINGS_NAME)
port_setting = settings.get(setting_key, None)
if(ports and len(ports) == 1):
return ports[0]
elif(ports and len(ports) == 0):
return False
elif(not port_setting):
if(request_port):
sublime.active_window().run_command('upiot_select_port')
return False
elif(port_setting not in ports):
if(request_port):
sublime.active_window().run_command('upiot_select_port')
return False
return port_setting