Skip to content

Commit

Permalink
fix #3
Browse files Browse the repository at this point in the history
  • Loading branch information
FengChendian committed Jul 29, 2021
1 parent f6d2b0d commit 213e56c
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 41 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.2.2

- change `readBytesOnListen` API
- add `readBytesOnce`, `openStatus` ...

## 0.1.2

- add `readOnListen` API
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ port.ReadIntervalTimeout = 10;
### Read

```dart
print(await ports.readBytes(2));
port.readBytesOnListen(8, (value) => print(value));
```

### Write
Expand Down
11 changes: 10 additions & 1 deletion example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,17 @@ class MyHomePage extends StatefulWidget {

class _MyHomePageState extends State<MyHomePage> {
var ports = <String>[];
late SerialPort port;

String data = '';
void _getPorts() {
ports = SerialPort.getAvailablePorts();
print(ports);
if (ports.isNotEmpty){
port = SerialPort(ports[0]);
port.readBytesOnListen(8, (value) {data = value.toString(); setState(() {

});});
}
setState(() {

});
Expand All @@ -41,6 +48,7 @@ class _MyHomePageState extends State<MyHomePage> {
// });
}


@override
Widget build(BuildContext context) {
return Scaffold(
Expand All @@ -60,6 +68,7 @@ class _MyHomePageState extends State<MyHomePage> {
ports.toString(),
style: Theme.of(context).textTheme.headline4,
),
Text(data),
],
),
),
Expand Down
4 changes: 2 additions & 2 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ packages:
path: ".."
relative: true
source: path
version: "0.1.1"
version: "0.2.2"
sky_engine:
dependency: transitive
description: flutter
Expand Down Expand Up @@ -169,6 +169,6 @@ packages:
name: win32
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.5"
version: "2.2.5"
sdks:
dart: ">=2.13.0 <3.0.0"
70 changes: 40 additions & 30 deletions lib/src/serial_port.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class SerialPort {

static final Map<String, SerialPort> _cache = <String, SerialPort>{};

/// for read loop
Timer? _timer;

/// reusable instance using [factory]
factory SerialPort(
String portName, {
Expand Down Expand Up @@ -205,6 +208,11 @@ class SerialPort {
_setCommState();
}

/// change [isOpened] value if necessary
set openStatus(bool status) {
_isOpened = status;
}

/// [ReadIntervalTimeout]
///
/// The maximum time allowed to elapse before the arrival of the next byte on the communications line,
Expand Down Expand Up @@ -268,8 +276,8 @@ class SerialPort {
_setCommTimeouts();
}

/// [readBytes] is an [async] function
Future<Uint8List> readBytes(int bytesSize) async {
/// [_read] is a fundamental read function/
Future<Uint8List> _read(int bytesSize) async {
final lpBuffer = calloc<Uint16>(bytesSize);
Uint8List uint8list;

Expand All @@ -284,38 +292,40 @@ class SerialPort {
return uint8list;
}

/// [readBytesOnListen] can listen operation when function was called.
/// It returns a StreamSubscription value
/// you can use onData to get data, use onListen and onError and soon.
Future<StreamSubscription> readBytesOnListen(
int bytesSize, Function(Uint8List value) onData,
{required Function() onListen}) async {
final lpBuffer = calloc<Uint16>(bytesSize);
Uint8List uint8list;
/// [readBytesOnce] read data only once.
Future<Uint8List> readBytesOnce(int bytesSize) async {
if (_timer != null) {
throw Exception("You need to remover the read listener!");
}
return _read(bytesSize);
}

final _closeController = StreamController<String>(
onListen: onListen,
);
final _closeSink = _closeController.sink;
/// [readBytesOnListen] can constantly listen data, you can use [onData] to get data.
void readBytesOnListen(int bytesSize, Function(Uint8List value) onData,
{void onBefore()?, Duration? duration}) async {
_cancelTimer();
if (onBefore != null) {
onBefore();
}
_timer = Timer.periodic(duration ?? Duration(milliseconds: 20), (timer) {
_read(bytesSize).then((value) {
if (value.isEmpty) {
return;
}
onData(value);
});
});
}

///事件订阅对象
StreamSubscription _closeSubscription =
_closeController.stream.listen((event) {});
/// [removeReadListener] will remove listener in [readBytesOnlisten]
void removeReadListener() {
_cancelTimer();
}

try {
ReadFile(handler!, lpBuffer, bytesSize, _bytesRead, _over);
} catch (e) {
_closeSink.addError(e.toString());
} finally {
/// Uint16 need to be casted for real Uint8 data
uint8list = lpBuffer.cast<Uint8>().asTypedList(_bytesRead.value);
onData(uint8list);
free(lpBuffer);
_closeController.close();
_closeSink.close();
void _cancelTimer() {
if (_timer != null) {
_timer!.cancel();
}

return _closeSubscription;
}

/// [writeBytesFromString] will convert String to ANSI Code corresponding to char
Expand Down
2 changes: 1 addition & 1 deletion pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,6 @@ packages:
name: win32
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.2.3"
version: "2.2.5"
sdks:
dart: ">=2.13.0 <3.0.0"
4 changes: 2 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: serial_port_win32
description: A SerialPort library using win32 API, for connecting real device by serial port. Now only supports Windows.
version: 0.1.2
version: 0.2.2
homepage: https://github.com/FengChendian/serial_port_win32
repository: https://github.com/FengChendian/serial_port_win32
issue_tracker: https://github.com/FengChendian/serial_port_win32/issues
Expand All @@ -12,7 +12,7 @@ dependencies:
ffi: ^1.1.2
flutter:
sdk: flutter
win32: ^2.1.5
win32: ^2.2.5

dev_dependencies:
flutter_test:
Expand Down
9 changes: 5 additions & 4 deletions test/serial_port_win32_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:io';

import 'package:serial_port_win32/src/serial_port.dart';
import 'package:win32/win32.dart';

Expand All @@ -6,10 +8,9 @@ void main() async {
print(ports);
if (ports.isNotEmpty) {
var port = SerialPort(ports[0]);
for (var i = 0; i < 100; i++) {
print(await port.readBytes(2));
}
port.readBytesOnListen(8, (value) => print(value));
sleep(Duration(seconds: 10));
// port.BaudRate = CBR_115200;
port.close();
// port.close();
}
}

0 comments on commit 213e56c

Please sign in to comment.