import 'io_protocol/io_addUser.dart'; import 'io_protocol/io_getPublicKey.dart'; import 'io_protocol/io_openDoor.dart'; import 'io_protocol/io_reply.dart'; import 'io_protocol/io_type.dart'; import 'io_tool/io_tool.dart'; import 'io_tool/manager_event_bus.dart'; class CommandReciverManager { static Future parseRobot(List data) async { int commandIdx = data[1]; int len = data.length; var dataDetail = data.sublist(4,len -2); int ioType = data[3]; CommandType commandType = ExtensionCommandType.getCommandType(ioType); int endIndex = dataDetail.length - 1; var reply; switch(commandType) { case CommandType.getLockPublicKey: { reply = GetPublicKeyReply.parseData(commandType, dataDetail); } break; case CommandType.addUser: { reply = AddUserReply.parseData(commandType, dataDetail); } break; case CommandType.openDoor: { reply = OpenDoorReply.parseData(commandType, dataDetail); } break; } return reply; } static int _bufSize = 0; static int _index = 0; static int _remainSize = 0; static int _maxBufferSize = 260; static List _buffer = []; static void _clearBuffer(){ _buffer = []; _index = 0; _bufSize = 0; } static void appDataReceive(List data,{bool clear = false}) async { ///解析数据 if(clear){ _clearBuffer(); } int data_size = data.length; if(data_size > _maxBufferSize){ return; } if(_bufSize+data_size > _maxBufferSize){ _index = 0; _bufSize = 0; } if(_index+_bufSize+data_size > _maxBufferSize){ _buffer = _buffer.sublist(_index,_index + _bufSize); _index = 0; } _buffer.addAll(data); _bufSize += data.length; int error; // print('✅ 执行开始 _buffer:${_buffer.length}'); do { error = await appCheckProtocol(_buffer.sublist(_index),_bufSize); // print('⚠️ $error'); switch(error){ case 0: { int protocolLen = _bufSize - _remainSize; List tempData = _buffer.sublist(_index,_index + protocolLen); _index += (_bufSize - _remainSize); _bufSize = _remainSize; if(tempData.isNotEmpty){ parseRobot(tempData).then((value){ EventBusManager().eventBusFir(value); }); } } break; case 1: break; case 2: { ++_index; --_bufSize; } break; default: error = 1; break; } }while(error != 1); // print('✅ 执行结束 _buffer:${_buffer.length}'); } static Future appCheckProtocol(List data,int size) async{ if(size < 7) return 1; if(data[0] != 0xFA) return 2; int payloadSize = data[2]; if(payloadSize == 0) return 2; int protocolSize = payloadSize +5; if(size < protocolSize) return 1; if(data[protocolSize-1] != 0xFF) return 2; if(data[protocolSize-2] != checkSum(data.sublist(0,protocolSize - 2))) return 2; _remainSize = size - protocolSize; return 0; } }