109 lines
2.8 KiB
Dart
109 lines
2.8 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<bool> checkAvailable() async {
|
|
if (isConnect) return true;
|
|
if (ObjectUtil.isEmpty(_portName)) return false;
|
|
try {
|
|
return SerialPort.availablePorts.contains(_portName);
|
|
} catch (e) {
|
|
logger.e(logMsg("检查设备失败error:|$e|"));
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// 子类通过此钩子将实际连接结果同步到统一设备状态,不改变原连接接口。
|
|
void onConnectionStatusChanged(bool connected) {}
|
|
|
|
Future<void> connect() async {
|
|
try {
|
|
if (ObjectUtil.isEmpty(_portName)) {
|
|
onConnectionStatusChanged(false);
|
|
return;
|
|
}
|
|
if (isConnect) {
|
|
onConnectionStatusChanged(true);
|
|
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;
|
|
onConnectionStatusChanged(true);
|
|
logger.d(logMsg("连接成功"));
|
|
return;
|
|
}
|
|
onConnectionStatusChanged(false);
|
|
} catch (e) {
|
|
onConnectionStatusChanged(false);
|
|
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";
|
|
}
|
|
}
|