/// <summary> /// 从文件中获取数据包,并将其保存在list中 /// </summary> /// 4G集中器一包512个字节,2G集中器一包1024个字节 public static void GetDataPack(int FileSize, string romPath) { //清空缓存数据包列表 Frm_Main.DataPacks.Clear(); //新建缓存buffer byte[] buffer = new byte[FileSize]; //打开文件 System.IO.FileStream file = new System.IO.FileStream(romPath, FileMode.Open, FileAccess.Read); //句柄 //循环读取文件 while (true) { //加锁 lock (buffer) { //情况缓存buffer Array.Clear(buffer, 0, FileSize); //异步读取文件 Task <int> r = file.ReadAsync(buffer, 0, FileSize); //返回结果为零则表示读取完了 if (r.Result == 0) { file.Close(); return; } //将读取到的buffer封包 Dstruct bufStruct = (Dstruct)UpdateHelper.BytesToStruct(buffer, typeof(Dstruct)); //添加到缓存列表中 DataPacks.Add(bufStruct); } } }
/// <summary> /// 获取固件包 /// </summary> /// <param name="reportBuffer">串口上报的数据,用于解析请求的index</param> /// <returns></returns> public static byte[] getFirmwarePag(byte[] reportBuffer) { try { //转读固件包结构 ReadUpdateP readPag = (ReadUpdateP)BytesToStruct(reportBuffer, typeof(ReadUpdateP)); //获取Index int index = readPag.index; //Index 赋值 Frm_Main.packetIndex = index + 1; //取升级固件包 Dstruct dataSt = Frm_Main.DataPacks[index]; byte[] data = StructToBytes(dataSt); //升级包数据域 Updatestruct upStruct = new Updatestruct(); //创建包头 StructHeader header = new StructHeader(); // 添加包头 header.HEAD = GSMCMDEnum.frameHead; //通信地址 byte[] comAddr = { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; header.COMADDR = comAddr; //源类型 header.SRC = 0xE1; //目标类型 header.DEST = 0xA1; //命令码 header.CMD = GSMCMDEnum.ackFirmware; //帧长度 header.LEN = 14 + 256 + 2 + 3; //转换大小端 header.LEN = BytesArrayHelper.SwapUInt16(header.LEN); //升级包编号 upStruct.index = (byte)index; //固件总长度 UInt16 fileLength = (UInt16)Frm_Main.fileLenth; //转换大端 fileLength = BytesArrayHelper.SwapUInt16(fileLength); //设置总长度 upStruct.fileLength = fileLength; //升级包 upStruct.dPack = data; //数据域 byte[] dataBytes = new byte[259]; //赋值固件包数据 dataBytes = StructToBytes(upStruct); //转换包头 byte[] headerBytes = StructToBytes(header); //创建总包bytes byte[] sendBytes = new byte[headerBytes.Length + dataBytes.Length + 2 + 3]; //拷贝Header Array.Copy(headerBytes, 0, sendBytes, 0, headerBytes.Length); //拷贝xxTea Array.Copy(dataBytes, 0, sendBytes, headerBytes.Length, dataBytes.Length); //crc UInt16 crc = Crc16.GetCRC16(sendBytes, sendBytes.Length - 5); // 创建2字节byte数组用于存放校验位 byte[] Check_Arr = new byte[2]; // 获取校验位高8位 Check_Arr[1] = Convert.ToByte(crc >> 8); // 获取校验位低8位 Check_Arr[0] = Convert.ToByte(crc & 0xFF); //拷贝crc Array.Copy(Check_Arr, 0, sendBytes, sendBytes.Length - 5, 2); //包尾 sendBytes[sendBytes.Length - 3] = 0x2d; sendBytes[sendBytes.Length - 2] = 0x2d; sendBytes[sendBytes.Length - 1] = 0x45; //返回数据 return(sendBytes); } catch (Exception) { //若发送报错则关闭套接字 return(null); } }