-
Notifications
You must be signed in to change notification settings - Fork 30
/
port.dart
414 lines (347 loc) · 11.9 KB
/
port.dart
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
* Based on libserialport (https://sigrok.org/wiki/Libserialport).
*
* Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
* Copyright (C) 2010-2015 Uwe Hermann <uwe@hermann-uwe.de>
* Copyright (C) 2013-2015 Martin Ling <martin-libserialport@earth.li>
* Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
* Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
* Copyright (C) 2020 J-P Nurmi <jpnurmi@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:ffi' as ffi;
import 'dart:typed_data';
import 'package:ffi/ffi.dart' as ffi;
import 'package:libserialport/src/bindings.dart';
import 'package:libserialport/src/config.dart';
import 'package:libserialport/src/dylib.dart';
import 'package:libserialport/src/enums.dart';
import 'package:libserialport/src/error.dart';
import 'package:libserialport/src/util.dart';
/// Serial port.
///
/// Provides means to:
///
/// - obtaining a list of serial ports on the system
/// - opening, closing and getting information about ports
/// - signals, modem control lines, breaks, etc.
/// - low-level reading and writing data, and buffer management
///
/// **Note:** The port must be disposed using [dispose()] when done.
///
/// # Error handling
///
/// Serial Port for Dart throws [SerialPortError] in case something goes wrong
/// under the hood in libserialport and it returns an error code:
///
/// final port = SerialPort(...);
/// port.write(...);
/// try {
/// } on SerialPortError catch (e) {
/// print(SerialPort.lastError);
/// }
///
/// The error message is that provided by the OS, using the current language
/// settings. The library does not define its own error codes or messages to
/// accompany other return codes.
///
/// See also:
/// - [SerialPortReader]
/// - [SerialPortConfig]
/// - [SerialPortError]
abstract class SerialPort {
/// Creates a serial port for `name`.
///
/// **Note:** Call [dispose()] to release the resources after you're done
/// with the serial port.
factory SerialPort(String name) => _SerialPortImpl(name);
/// @internal
factory SerialPort.fromAddress(int address) =>
_SerialPortImpl.fromAddress(address);
/// @internal
int get address;
/// Lists the serial ports available on the system.
static List<String> get availablePorts => _SerialPortImpl.availablePorts;
/// Releases all resources associated with the serial port.
///
/// @note Call this function after you're done with the serial port.
void dispose();
/// Opens the serial port in the specified `mode`.
///
/// See also:
/// - [SerialPortMode]
bool open({required int mode});
/// Opens the serial port for reading only.
bool openRead();
/// Opens the serial port for writing only.
bool openWrite();
/// Opens the serial port for reading and writing.
bool openReadWrite();
/// Closes the serial port.
bool close();
/// Gets whether the serial port is open.
bool get isOpen;
/// Gets the name of the port.
///
/// The name returned is whatever is normally used to refer to a port on the
/// current operating system; e.g. for Windows it will usually be a "COMn"
/// device name, and for Unix it will be a device path beginning with "/dev/".
String? get name;
/// Gets the description of the port, for presenting to end users.
String? get description;
/// Gets the transport type used by the port.
///
/// See also:
/// - [SerialPortTransport]
int get transport;
/// Gets the USB bus number of a USB serial adapter port.
int? get busNumber;
/// Gets the USB device number of a USB serial adapter port.
int? get deviceNumber;
/// Gets the USB vendor ID of a USB serial adapter port.
int? get vendorId;
/// Gets the USB Product ID of a USB serial adapter port.
int? get productId;
/// Get the USB manufacturer of a USB serial adapter port.
String? get manufacturer;
/// Gets the USB product name of a USB serial adapter port.
String? get productName;
/// Gets the USB serial number of a USB serial adapter port.
String? get serialNumber;
/// Gets the MAC address of a Bluetooth serial adapter port.
String? get macAddress;
/// Gets the current configuration of the serial port.
SerialPortConfig get config;
/// Sets the configuration for the serial port.
///
/// For each parameter in the configuration, there is a special value
/// (usually -1, but see the documentation for each field). These values
/// will be ignored and the corresponding setting left unchanged on the port.
///
/// Upon errors, the configuration of the serial port is unknown since
/// partial/incomplete config updates may have happened.
set config(SerialPortConfig config);
/// Read data from the serial port.
///
/// The operation attempts to read N `bytes` of data.
///
/// If `timeout` is 0 or greater, the read operation is blocking.
/// The timeout is specified in milliseconds. Pass 0 to wait infinitely.
Uint8List read(int bytes, {int timeout = -1});
/// Write data to the serial port.
///
/// If `timeout` is 0 or greater, the write operation is blocking.
/// The timeout is specified in milliseconds. Pass 0 to wait infinitely.
///
/// Returns the amount of bytes written.
int write(Uint8List bytes, {int timeout = -1});
/// Gets the amount of bytes available for reading.
int get bytesAvailable;
/// Gets the amount of bytes waiting to be written.
int get bytesToWrite;
/// Flushes serial port buffers. Data in the selected buffer(s) is discarded.
///
/// See also:
/// - [SerialPortBuffer]
void flush([int buffers = SerialPortBuffer.both]);
/// Waits for buffered data to be transmitted.
void drain();
/// Gets the status of the control signals for the serial port.
int get signals;
/// Puts the port transmit line into the break state.
bool startBreak();
/// Takes the port transmit line out of the break state.
bool endBreak();
/// Gets the error for a failed operation.
static SerialPortError? get lastError => _SerialPortImpl.lastError;
}
class _SerialPortImpl implements SerialPort {
final ffi.Pointer<sp_port> _port;
SerialPortConfig? _config;
_SerialPortImpl(String name) : _port = _init(name);
_SerialPortImpl.fromAddress(int address)
: _port = ffi.Pointer<sp_port>.fromAddress(address);
@override
int get address => _port.address;
static ffi.Pointer<sp_port> _init(String name) {
final out = ffi.calloc<ffi.Pointer<sp_port>>();
final cstr = Util.toUtf8(name);
Util.call(() => dylib.sp_get_port_by_name(cstr, out));
final port = out[0];
ffi.calloc.free(out);
ffi.calloc.free(cstr);
return port;
}
static List<String> get availablePorts {
final out = ffi.calloc<ffi.Pointer<ffi.Pointer<sp_port>>>();
final rv = Util.call(() => dylib.sp_list_ports(out));
if (rv != sp_return.SP_OK) {
ffi.calloc.free(out);
return <String>[];
}
var i = -1;
final ports = <String>[];
final array = out.value;
while (array[++i] != ffi.nullptr) {
final port = Util.fromUtf8(dylib.sp_get_port_name(array[i]));
if (port != null) ports.add(port);
}
dylib.sp_free_port_list(array);
return ports;
}
@override
void dispose() {
_config?.dispose();
dylib.sp_free_port(_port);
}
@override
bool open({required int mode}) =>
dylib.sp_open(_port, mode) == sp_return.SP_OK;
@override
bool openRead() => open(mode: SerialPortMode.read);
@override
bool openWrite() => open(mode: SerialPortMode.write);
@override
bool openReadWrite() => open(mode: SerialPortMode.readWrite);
@override
bool close() => dylib.sp_close(_port) == sp_return.SP_OK;
@override
bool get isOpen {
final handle = Util.getInt((ptr) {
return dylib.sp_get_port_handle(_port, ptr.cast());
})!;
return handle > 0;
}
@override
String? get name => Util.fromUtf8(dylib.sp_get_port_name(_port));
@override
String? get description {
return Util.fromUtf8(dylib.sp_get_port_description(_port));
}
@override
int get transport => dylib.sp_get_port_transport(_port);
@override
int? get busNumber {
return Util.getInt((ptr) {
return dylib.sp_get_port_usb_bus_address(_port, ptr, ffi.nullptr);
});
}
@override
int? get deviceNumber {
return Util.getInt((ptr) {
return dylib.sp_get_port_usb_bus_address(_port, ffi.nullptr, ptr);
});
}
@override
int? get vendorId {
return Util.getInt((ptr) {
return dylib.sp_get_port_usb_vid_pid(_port, ptr, ffi.nullptr);
});
}
@override
int? get productId {
return Util.getInt((ptr) {
return dylib.sp_get_port_usb_vid_pid(_port, ffi.nullptr, ptr);
});
}
@override
String? get manufacturer {
return Util.fromUtf8(dylib.sp_get_port_usb_manufacturer(_port));
}
@override
String? get productName {
return Util.fromUtf8(dylib.sp_get_port_usb_product(_port));
}
@override
String? get serialNumber {
return Util.fromUtf8(dylib.sp_get_port_usb_serial(_port));
}
@override
String? get macAddress {
return Util.fromUtf8(dylib.sp_get_port_bluetooth_address(_port));
}
@override
SerialPortConfig get config {
if (_config == null) {
_config = SerialPortConfig();
final ptr = ffi.Pointer<sp_port_config>.fromAddress(_config!.address);
Util.call(() => dylib.sp_get_config(_port, ptr));
}
return _config!;
}
@override
set config(SerialPortConfig config) {
if (_config != config) {
_config?.dispose();
}
_config = config;
final ptr = ffi.Pointer<sp_port_config>.fromAddress(config.address);
Util.call(() => dylib.sp_set_config(_port, ptr));
}
@override
Uint8List read(int bytes, {int timeout = -1}) {
return Util.read(bytes, (ffi.Pointer<ffi.Uint8> ptr) {
return timeout < 0
? dylib.sp_nonblocking_read(_port, ptr.cast(), bytes)
: dylib.sp_blocking_read(_port, ptr.cast(), bytes, timeout);
});
}
@override
int write(Uint8List bytes, {int timeout = -1}) {
return Util.write(bytes, (ffi.Pointer<ffi.Uint8> ptr) {
return timeout < 0
? dylib.sp_nonblocking_write(_port, ptr.cast(), bytes.length)
: dylib.sp_blocking_write(_port, ptr.cast(), bytes.length, timeout);
});
}
@override
int get bytesAvailable => dylib.sp_input_waiting(_port);
@override
int get bytesToWrite => dylib.sp_output_waiting(_port);
@override
void flush([int buffers = SerialPortBuffer.both]) {
dylib.sp_flush(_port, buffers);
}
@override
void drain() => dylib.sp_drain(_port);
@override
int get signals {
final ptr = ffi.calloc<ffi.Int32>();
Util.call(() => dylib.sp_get_signals(_port, ptr));
final value = ptr.value;
ffi.calloc.free(ptr);
return value;
}
@override
bool startBreak() => dylib.sp_start_break(_port) == sp_return.SP_OK;
@override
bool endBreak() => dylib.sp_end_break(_port) == sp_return.SP_OK;
static SerialPortError? get lastError {
final ptr = dylib.sp_last_error_message();
final str = Util.fromUtf8(ptr);
if (str == null) return null;
dylib.sp_free_error_message(ptr);
return SerialPortError(str, dylib.sp_last_error_code());
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is _SerialPortImpl && _port == other._port;
}
@override
int get hashCode => _port.hashCode;
@override
String toString() => 'SerialPort($_port)';
}