public DfuStatus GetStatus() { byte[] status = DfuIn(DfuRequest.GetStatus, 0, 6); DfuStatus ds = new DfuStatus(status); // Todo: return custom string if status ErrVendor. return(ds); }
public void ProgramFirmware(byte[] FirmwareData) { if ((Attributes & DfuAttributes.CanDnload) == 0) { // Device is unable to download firmware. throw new Exception("DFU Device is not capable of downloading firmware."); } DfuStatus status = GetStatus(); if (status.State != DfuState.AppIdle && status.State != DfuState.DfuIdle) { // Currently don't have any logic to apply corrective actions to this state. throw new Exception("Expect DFU to be in idle state before programming. Status: " + status.ToString()); } int blockSize = 4096; if (blockSize > MaxTransferSize) { blockSize = MaxTransferSize; } byte[] block = new byte[blockSize]; // Send the firmware to the device in blocks. int cursor = 0; int blockIndex = 0; while (cursor < FirmwareData.Length) { int copyLength = FirmwareData.Length - cursor; if (copyLength > blockSize) { copyLength = blockSize; } Array.Copy(FirmwareData, cursor, block, 0, copyLength); if (copyLength < blockSize) { Array.Clear(block, copyLength, blockSize - copyLength); } DfuDnload(blockIndex, block); int timeout = 30000; while (true) { status = GetStatus(); if (status.Status != DfuStatusValue.Ok) { throw new Exception("DFU Error status while downloading firmware: " + status.ToString()); } if (status.State == DfuState.DfuDownloadIdle) { // Continue sending data break; } timeout -= status.Polltimeout + 15; if (timeout < 0) { throw new Exception("Timeout while waiting for DFU status. Current: " + status.ToString()); } System.Threading.Thread.Sleep(status.Polltimeout); } cursor += copyLength; } // Transfer is completed, now send a zero-length DFU Dnload request followed by getting status to complete the transfer. DfuDnload(0, new byte[0] { }); status = GetStatus(); if (status.Status != DfuStatusValue.Ok) { throw new Exception("DFU Error status while manifesting firmware: " + status.ToString()); } if (status.State != DfuState.DfuManifest) { throw new Exception("DFU unexpected state while manifesting firmware: " + status.ToString()); } }