import 'dart:async'; import 'dart:io'; import 'package:star_lock/talk/udp/udp_reciverData.dart'; import '../../blue/io_tool/io_model.dart'; import '../../blue/io_tool/manager_event_bus.dart'; class UDPManage{ static UDPManage? _manager; UDPManage._init() { initUdp(); _streamSubscription = EventBusManager().eventBus!.on().listen((EventSendModel sendModel) { // print("sendModel.sendChannel:${sendModel.sendChannel}"); if(sendModel.sendChannel == DataChannel.udp){ List data = sendModel.data; sendData(data); } }); } static UDPManage _share(){ _manager ??= UDPManage._init(); return _manager!; } factory UDPManage() => _share(); UDPManage get manager => _share(); StreamSubscription? _streamSubscription; RawDatagramSocket? _udpSocket; // String host = '47.106.143.213'; // int port = 8056; // String? _mIp = ''; String host = ''; int port = 0; String lockId = '';// 锁id 通过锁id来判断是哪把锁发对讲过来 void initUdp() async { var listAddress = InternetAddress.lookup(host!); listAddress.then((list) { list.forEach((element) { // print('Udp ----> element.address:${element.address} element.host:${element.host}'); host = element.address; }); }); await _initUdp(); } Future _initUdp() async { if(port == 0){ print('❌ Udp ----> _port == 0'); return; } print('Udp ----> host:$host port:$port'); var addressIListenFrom = InternetAddress.anyIPv4; int portIListenOn = 62288; RawDatagramSocket.bind(addressIListenFrom, portIListenOn).then((RawDatagramSocket socket){ _udpSocket = socket; ///广播功能 _udpSocket!.broadcastEnabled = true; _onReceiveData(socket); }); } void _onReceiveData(RawDatagramSocket socket) { socket.listen((RawSocketEvent event) { if(event == RawSocketEvent.read){ Datagram? dg = socket.receive(); try { // print('Did received data on the stream (length --> ${dg!.data.length}) dg!.data:${dg!.data}'); // EventBusManager().eventBusFir(EventReceiveModel(data: dg?.data,sendChannel: DataChannel.udp)); CommandUDPReciverManager.appDataReceive(dg!.data); } catch (e) { print('❌ Udp ----> $e'); } } }); } void sendData(List data) { if(null == _udpSocket || null == data || data.isEmpty || host == ''){ if(null == _udpSocket ){ print('❌ Udp ----> null == _udpSocket'); initUdp(); } return; } try { // print("sendData:$data"); var result = _udpSocket?.send(data, InternetAddress(host!), port!); if(result != data.length) { print('❌Udp ----> send data $result ${data.length}'); _udpSocket = null; } }catch (e){ } } bool exit() { if(null != _udpSocket) { print('❌ Udp ----> close'); _udpSocket?.close(); } return true; } void disposed() { _streamSubscription?.cancel(); } }