84 lines
2.0 KiB
Dart
84 lines
2.0 KiB
Dart
import 'package:common_utils/common_utils.dart';
|
|
import 'package:flutter_libserialport/flutter_libserialport.dart';
|
|
|
|
import 'package:pj_supermarket_cloud/common/index.dart';
|
|
|
|
class SerialBase {
|
|
String _name = "未知";
|
|
String _portName = "";
|
|
int _baudRate = 9600;
|
|
int _readTimeout = 500;
|
|
|
|
late SerialPort serialClient;
|
|
SerialPortReader? readPort;
|
|
|
|
bool isConnect = false;
|
|
|
|
set name(String name) {
|
|
_name = name;
|
|
}
|
|
|
|
set portName(String portName) {
|
|
_portName = portName;
|
|
}
|
|
|
|
set baudRate(int baudRate) {
|
|
_baudRate = baudRate;
|
|
}
|
|
|
|
set readTimeout(int readTimeout) {
|
|
_readTimeout = readTimeout;
|
|
}
|
|
|
|
Future<void> connect() async {
|
|
try {
|
|
if (ObjectUtil.isEmpty(_portName)) return;
|
|
if (isConnect) return;
|
|
serialClient = SerialPort(_portName);
|
|
if (serialClient.isOpen) {
|
|
serialClient.close();
|
|
}
|
|
bool isOpenRead = serialClient.openReadWrite();
|
|
if (isOpenRead && serialClient.isOpen) {
|
|
SerialPortConfig config = serialClient.config;
|
|
config.baudRate = _baudRate;
|
|
serialClient.config = config;
|
|
isConnect = true;
|
|
logger.d(logMsg("连接成功"));
|
|
}
|
|
} catch (e) {
|
|
logger.e(logMsg("连接失败error:|$e|"));
|
|
}
|
|
}
|
|
|
|
Future<void> listen(Function(List<int>) fc) async {
|
|
if (isConnect == false) return;
|
|
readPort = SerialPortReader(serialClient, timeout: _readTimeout);
|
|
if (ObjectUtil.isEmpty(readPort)) return;
|
|
logger.d(logMsg("开始监听串口数据"));
|
|
readPort!.stream.listen((event) async {
|
|
// logger.w(logMsg("监听串口数据:event:|$event|string:${bytesToString(event)}"));
|
|
fc(event);
|
|
});
|
|
}
|
|
|
|
void readerClose() {
|
|
if (ObjectUtil.isNotEmpty(readPort)) {
|
|
readPort!.close();
|
|
readPort = null;
|
|
}
|
|
}
|
|
|
|
void close() {
|
|
if (isConnect == true) {
|
|
serialClient.close();
|
|
serialClient.dispose();
|
|
isConnect = false;
|
|
}
|
|
}
|
|
|
|
String logMsg(String msg) {
|
|
return "串口设备|$_name|$msg";
|
|
}
|
|
}
|