public void DownloadPreview() { //TODO: Возможность задавать путь или как-то переделать. А то кешированние - хорошо, //но тут выходит частный случай его использованния. Не гут. string pcName = string.Format("Data//Cache//{0}.p", Index); string dName = string.Format("{0}.p", Index); if (File.Exists(pcName)) { UInt32 dCRC32 = Parrent.ContentTable.PreviewHashes[Index]; UInt32 pcCRC32 = CrCHandler.CRC32(pcName); if (dCRC32 == pcCRC32) { PreviewCache = new Bitmap(pcName); return; } ; } var fileSender = Parrent.Master.FileReceiver(FileTransfer.FileTransferSecurityFlags.VerifyLengh | FileTransfer.FileTransferSecurityFlags.VerifyCheckSum); fileSender.PacketLength = 2000; if (!fileSender.ReceiveFileSync(pcName, dName)) { throw new FileHandlerException("Не удалось передать миниатюру вектора"); } PreviewCache = new Bitmap(pcName); LoadedPreview = true; }
private void HandleLocalFile(string newPath, string fileName) { if (new ReceiveDialog(Master, fileName, newPath).ShowDialog() == DialogResult.OK) { var locHash = CrCHandler.CRC32(newPath); var res = System.Diagnostics.Process.Start(newPath); res.WaitForExit(); if (CrCHandler.CRC32(newPath) != locHash) { if (System.Windows.Forms.MessageBox.Show("Файл был изменен. Хотите отправить его на устройство?", "Передача", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { new SendDialog(Master, newPath, fileName).ShowDialog(); TrySetupFolder(); } } } }
private unsafe bool CompareHash() { var deviceHash = Master.ph.File_GetCrC32(); if (deviceHash.Status != GeneralPacketHandler.WriteReadFileHandleResult.OK) { RaiseErrorEvent(new FileSenderErrorArgs(FileSenderError.CantGetHashOfFile, true)); return(false); } UInt32 localHash = 0; fixed(byte *bytes = _data) localHash = CrCHandler.CRC32(bytes, (UInt32)_data.Length); if (BitConverter.ToUInt32(deviceHash.Result, 0) != localHash) { RaiseErrorEvent(new FileSenderErrorArgs(FileSenderError.HashesNotEqual, false)); } return(true); }
private void TryToCoputeLenghAndHash(bool action = false) { UInt16 Command; byte[] Sender; byte[] DataBytes = new byte[0]; try { Command = BitConverter.ToUInt16(new byte[] { byte.Parse(textBox_command_b1.Text), byte.Parse(textBox_command_b2.Text) }, 0); } catch { label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Command"]; return; } try { Sender = new byte[8] { byte.Parse(textBox_sender_b1.Text), byte.Parse(textBox_sender_b2.Text), byte.Parse(textBox_sender_b3.Text), byte.Parse(textBox_sender_b4.Text), byte.Parse(textBox_sender_b5.Text), byte.Parse(textBox_sender_b6.Text), byte.Parse(textBox_sender_b7.Text), byte.Parse(textBox_sender_b8.Text), }; } catch { label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.SenderBytes"]; return; } if (textBox_data.Text != "") { try { DataBytes = textBox_data.Text.Split(',').Select(p => byte.Parse(p)).ToArray(); } catch { label_err.Text = label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Data"]; return; } } UInt16 Length = (UInt16)(DataBytes.Length + 14 + 255); byte[] lengthBytes; try { lengthBytes = checkBox_size.Checked ? new byte[] { byte.Parse(textBox_size_b1.Text), byte.Parse(textBox_size_b2.Text) } : BitConverter.GetBytes(Length); } catch { label_err.Text = label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Size"];; return; } if (!checkBox_size.Checked) { textBox_size_b1.Text = lengthBytes[0].ToString(); textBox_size_b2.Text = lengthBytes[1].ToString(); } byte[] crc; if (!checkBox_hash.Checked) { var crcH = new CrCHandler(); crc = crcH.ComputeChecksumBytes(DataBytes); textBox_hash_b1.Text = crc[0].ToString(); textBox_hash_b2.Text = crc[1].ToString(); } else { try { crc = new byte[] { byte.Parse(textBox_hash_b1.Text), byte.Parse(textBox_hash_b2.Text) }; } catch { label_err.Text = label_err.Text = TB.L.Phrase["Connection.Error"] + ": " + TB.L.Phrase["Connection.Error.Hash"]; return; } } if (action) { byte[] totalBytes = new byte[DataBytes.Length + 14]; Buffer.BlockCopy(lengthBytes, 0, totalBytes, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes(Command), 0, totalBytes, 2, 2); Buffer.BlockCopy(Sender, 0, totalBytes, 4, 8); Buffer.BlockCopy(DataBytes, 0, totalBytes, 12, DataBytes.Length); Buffer.BlockCopy(crc, 0, totalBytes, 12 + DataBytes.Length, 2); Requests.Add(new Packet() { Command = Command, Data = DataBytes, Sender = new Sender(Sender), TotalData = totalBytes, Size = (Int16)(Length - 255) }); listBox.Items.Add($"R{Requests.Count}. ${TB.L.Phrase["Connection.Error.Command"]}: ({textBox_command_b1.Text}, {textBox_command_b2.Text})"); try { Answers.Add(GetResult(totalBytes)); listBox.Items.Add($"A{Answers.Count}. ${TB.L.Phrase["Connection.Status"]}: {Answers.Last().Status}. ${TB.L.Phrase["Connection.AnswerTo"]}: {Answers.Last().Command}"); } catch (Exception e) { label_err.Text = TB.L.Phrase["Connection.Error.SendingError"]; MessageBox.Show( string.Format( TB.L.Phrase["Form_PrintMaster.ErrorText"], e.GetType().FullName, e.StackTrace, e.Message), TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } label_err.Text = "Sended"; return; } label_err.Text = "Ok"; }
public bool UploadVector(Vector vector, string name) { UInt16 index = (UInt16)(CountOfVectors + 1); string previewName = string.Format("{0}.p", index); string vectorName = string.Format("{0}.v", index); string metaDataName = string.Format("{0}.m", index); string previewPcName = string.Format("{1}\\Data\\Cache\\{0}", previewName, Environment.CurrentDirectory); string vectorPcName = string.Format("{1}\\Data\\Cache\\{0}", vectorName, Environment.CurrentDirectory); string metaDataPcName = string.Format("{1}\\Data\\Cache\\{0}", metaDataName, Environment.CurrentDirectory); var preview = new Bitmap(vector.ToBitmap(Color.White, Color.Black), new Size(500, 500)); var bytes = vector.ToBinnaryVector(); var meta = new VectorMetaData(this) { Height = (UInt16)vector.Header.Height, Index = index, Name = name, Type = vector.Header.VectType, Width = (UInt16)vector.Header.Width }; preview.Save(previewPcName); File.WriteAllBytes(vectorPcName, bytes); File.WriteAllBytes(metaDataPcName, meta.ToByteArray()); //Находим хэш файла пк. var localHash = CrCHandler.CRC32(vectorPcName); if (ContentTable.PreviewHashes.Values.Contains(localHash)) { //Если файл с таким хэшем есть на устройстве, то нечего его переотправлять. return(true); } var fileSender = Master.FileSender(FileTransferSecurityFlags.VerifyLengh | FileTransferSecurityFlags.VerifyCheckSum); fileSender.PacketLength = 2000; if (!fileSender.SendFileSync(vectorPcName, vectorName)) { return(false); } if (!fileSender.SendFileSync(previewPcName, previewName)) { return(false); } if (!fileSender.SendFileSync(metaDataPcName, metaDataName)) { return(false); } //Добавляем в нашу таблицу хэш данного вектора. ContentTable.VectorHashes.Add(index, CrCHandler.CRC32(vectorPcName)); //Хэш превью изображения. ContentTable.PreviewHashes.Add(index, CrCHandler.CRC32(previewPcName)); //Сам адресс вектора. ContentTable.VectorAdresses.Add(index); //Загружаем измененный конфиг на девайс. try { ContentTable.Upload(); } catch { //Особо неважно, что именно произошло. return(false); } return(true); }
public bool ReceiveFileSync(string pcName, string DeviceName) { //if (ParentMaster.isClosed) //TODO: –азобратьс¤ с мастерами //throw .CloseEx; DTPMaster.CheckConnAndVal(); TimerThread = new Thread(TimerThreadMethod); TimerThread.Start(); DateTime startTime = DateTime.Now; MainFile = new SdCardFile(DeviceName, Master); //TODO: сделать мастер/ MainFile! try { if (!MainFile.IsExists) { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.FileNotExists, true)); return(false); } } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantOpenFile, true)); return(false); } try { MainFile.Open(false); } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantOpenFile, true)); return(false); } var bf = MainFile.BinnaryFile; bf.CursorPos = 0; UInt32 len = 0; try { len = MainFile.Length; } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantGetFileSize, true)); return(false); } byte[] buffer = new byte[len]; UInt32 currentPacket = 0; UInt32 totalPackets = (UInt32)(len / PacketLength); UInt32 currIndex = 0, delta = 0, index = 0; while (currIndex < len) { if (currIndex + PacketLength > len) { delta = len - currIndex; currIndex = len; } else { currIndex += (UInt32)PacketLength; delta = (UInt32)PacketLength; } SdCardBinnaryFileReadResult <byte[]> res; try { res = bf.ReadByteArray(delta); } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantGetPacket, true)); return(false); } if (!res.Succeed) { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantGetPacket, true)); return(false); } else { if (ForceStop) { try { MainFile.Close(); } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantCloseFile, true)); } RaiseEndEvent(new FileTransferEndArgs((DateTime.Now - startTime).TotalSeconds, true)); return(false); } currentPacket++; RaiseProcessEvent(new FileTransferProcessArgs((long)(DateTime.Now - startTime).TotalSeconds, LeftTime, totalPackets - currentPacket, currentPacket, Speed, PacketLength)); Buffer.BlockCopy(res.Result, 0, buffer, (int)index, (int)delta); index += delta; } } File.Create(pcName).Close(); File.WriteAllBytes(pcName, buffer); if (CheckLen) { if (len != new FileInfo(pcName).Length) { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.NotEqualSizes, false)); } } if (CheckSum) { UInt32 localHash = CrCHandler.CRC32(pcName); UInt32 deviceHash = 0; try { deviceHash = MainFile.CRC32; } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantGetHashOfFile, true)); return(false); } if (localHash != deviceHash) { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.HashesNotEqual, false)); } } try { MainFile.Close(); } catch { RaiseErrorEvent(new FileReceiverErrorArgs(FileReceiverError.CantCloseFile, true)); return(false); } RaiseEndEvent(new FileTransferEndArgs((DateTime.Now - startTime).TotalSeconds, false)); return(true); }