Skip to content

Commit

Permalink
Refactor DfuUtils.cs to use more modern async patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
CartBlanche committed Jul 3, 2024
1 parent 3a18977 commit f8c791c
Show file tree
Hide file tree
Showing 13 changed files with 314 additions and 741 deletions.
51 changes: 32 additions & 19 deletions Source/v2/Meadow.CLI/Commands/Current/Firmware/FirmwareUpdater.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ public class FirmwareUpdater<T> where T : BaseDeviceCommand<T>
private string? serialNumber;
private readonly MeadowConnectionManager connectionManager;
private readonly ILogger? logger;
private readonly bool provisioninInProgress;
private readonly CancellationToken cancellationToken;
private readonly ISettingsManager settings;
private readonly FileManager fileManager;

private int _lastWriteProgress = 0;
private int lastWriteProgress = 0;

private BaseDeviceCommand<T> command;

public event EventHandler<string> UpdateProgress = default!;
public event EventHandler<(string message, double percentage)> UpdateProgress = default!;

public FirmwareUpdater(BaseDeviceCommand<T> command, ISettingsManager settings, FileManager fileManager, MeadowConnectionManager connectionManager, string? individualFile, FirmwareType[]? firmwareFileTypes, bool useDfu, string? osVersion, string? serialNumber, ILogger? logger, CancellationToken cancellationToken)
{
Expand All @@ -38,6 +39,7 @@ public FirmwareUpdater(BaseDeviceCommand<T> command, ISettingsManager settings,
this.osVersion = osVersion;
this.serialNumber = serialNumber;
this.logger = logger;
this.provisioninInProgress = logger == null;
this.cancellationToken = cancellationToken;
}

Expand Down Expand Up @@ -94,19 +96,30 @@ public async Task<bool> UpdateFirmware()

if (firmwareFileTypes.Contains(FirmwareType.OS))
{
UpdateProgress?.Invoke(this, "Flashing OS");
UpdateProgress?.Invoke(this, ("Flashing OS", 20));
await WriteOSFiles(connection, deviceInfo, package, useDfu);
}

if (!string.IsNullOrWhiteSpace(serialNumber))
{
connection = await GetConnectionAndDisableRuntime(await MeadowConnectionManager.GetRouteFromSerialNumber(serialNumber!));
deviceInfo = await connection.GetDeviceInfo(cancellationToken);
connection = await GetConnectionAndDisableRuntime(await MeadowConnectionManager.GetRouteFromSerialNumber(serialNumber));
if (connection != null)
{
if (provisioninInProgress)
{
connection.ConnectionMessage += (o, e) =>
{
UpdateProgress?.Invoke(this, (e, 0));
};
}

deviceInfo = await connection.GetDeviceInfo(cancellationToken);
}
}

if (firmwareFileTypes.Contains(FirmwareType.Runtime) || Path.GetFileName(individualFile) == F7FirmwarePackageCollection.F7FirmwareFiles.RuntimeFile)
{
UpdateProgress?.Invoke(this, "Writing Runtime");
UpdateProgress?.Invoke(this, ("Writing Runtime", 40));
await WriteRuntimeFiles(connection, deviceInfo, package, individualFile);
}

Expand All @@ -115,7 +128,7 @@ public async Task<bool> UpdateFirmware()
|| Path.GetFileName(individualFile) == F7FirmwarePackageCollection.F7FirmwareFiles.CoprocApplicationFile
|| Path.GetFileName(individualFile) == F7FirmwarePackageCollection.F7FirmwareFiles.CoprocBootloaderFile)
{
UpdateProgress?.Invoke(this, "Writing ESP");
UpdateProgress?.Invoke(this, ("Writing ESP", 60));
await WriteEspFiles(connection, deviceInfo, package);
}

Expand All @@ -130,7 +143,7 @@ public async Task<bool> UpdateFirmware()

private async Task WriteEspFiles(IMeadowConnection? connection, DeviceInfo? deviceInfo, FirmwarePackage package)
{
connection ??= await GetConnectionAndDisableRuntime();
connection ??= await GetConnectionAndDisableRuntime(await MeadowConnectionManager.GetRouteFromSerialNumber(serialNumber));

await WriteEsp(connection, deviceInfo, package);

Expand Down Expand Up @@ -202,7 +215,7 @@ private async Task WriteOSFiles(IMeadowConnection? connection, DeviceInfo? devic

connection ??= await FindMeadowConnection(initialPorts);

await connection.WaitForMeadowAttach();
await connection.WaitForMeadowAttach(cancellationToken);
}
else
{
Expand Down Expand Up @@ -254,7 +267,7 @@ private async Task WriteOSFiles(IMeadowConnection? connection, DeviceInfo? devic

if (!string.IsNullOrWhiteSpace(serialNumber))
{
return meadowsInDFU.Where(device => device.GetDeviceSerialNumber() == serialNumber).FirstOrDefault();
return meadowsInDFU.Where(device => device.SerialNumber == serialNumber).FirstOrDefault();
}
else if (meadowsInDFU.Count == 1 || IgnoreSerialNumberForDfu(provider))
{ //IgnoreSerialNumberForDfu is a macOS-specific hack for Mark's machine
Expand All @@ -272,7 +285,7 @@ private bool IgnoreSerialNumberForDfu(LibUsbProvider provider)

if (devices.Count == 2)
{
if (devices[0].GetDeviceSerialNumber().Length > 12 || devices[1].GetDeviceSerialNumber().Length > 12)
if (devices[0].SerialNumber.Length > 12 || devices[1].SerialNumber.Length > 12)
{
return true;
}
Expand All @@ -286,7 +299,7 @@ private async Task<IMeadowConnection> GetConnectionAndDisableRuntime(string? rou
{
IMeadowConnection connection;

if (route != null)
if (!string.IsNullOrWhiteSpace(route))
{
connection = await command.GetConnectionForRoute(route, true);
}
Expand All @@ -301,15 +314,15 @@ private async Task<IMeadowConnection> GetConnectionAndDisableRuntime(string? rou
await connection.Device.RuntimeDisable();
}

_lastWriteProgress = 0;
lastWriteProgress = 0;

connection.FileWriteProgress += (s, e) =>
{
var p = (int)(e.completed / (double)e.total * 100d);
// don't report < 10% increments (decrease spew on large files)
if (p - _lastWriteProgress < 10) { return; }
if (p - lastWriteProgress < 10) { return; }

_lastWriteProgress = p;
lastWriteProgress = p;

logger?.LogInformation($"{Strings.Writing} {e.fileName}: {p:0}% {(p < 100 ? string.Empty : "\r\n")}");
};
Expand Down Expand Up @@ -349,7 +362,7 @@ private async Task WriteOsWithDfu(ILibUsbDevice libUsbDevice, string osFile, boo
{ //validate device
if (string.IsNullOrWhiteSpace(serialNumber))
{
serialNumber = libUsbDevice.GetDeviceSerialNumber();
serialNumber = libUsbDevice.SerialNumber;
}
}
catch
Expand All @@ -368,7 +381,7 @@ await DfuUtils.FlashFile(
osFile,
serialNumber,
logger: logger,
format: string.IsNullOrEmpty(serialNumber) ? DfuUtils.DfuFlashFormat.ConsoleOut : DfuUtils.DfuFlashFormat.None);
format: provisioninInProgress ? DfuUtils.DfuFlashFormat.None : DfuUtils.DfuFlashFormat.ConsoleOut);
}
catch (ArgumentException)
{
Expand Down Expand Up @@ -474,7 +487,7 @@ private async Task<IList<string>> WaitForNewSerialPorts(IList<string>? ignorePor

private async Task<IMeadowConnection?> WriteRuntime(IMeadowConnection? connection, DeviceInfo? deviceInfo, string runtimePath, string destinationFilename)
{
connection ??= await GetConnectionAndDisableRuntime();
connection ??= await GetConnectionAndDisableRuntime(await MeadowConnectionManager.GetRouteFromSerialNumber(serialNumber));

logger?.LogInformation($"{Environment.NewLine}{Strings.WritingRuntime}...");

Expand Down Expand Up @@ -520,7 +533,7 @@ private async Task<IList<string>> WaitForNewSerialPorts(IList<string>? ignorePor

private async Task WriteEsp(IMeadowConnection? connection, DeviceInfo? deviceInfo, FirmwarePackage package)
{
connection ??= await GetConnectionAndDisableRuntime();
connection ??= await GetConnectionAndDisableRuntime(await MeadowConnectionManager.GetRouteFromSerialNumber(serialNumber));

if (connection == null) { return; } // couldn't find a connected device

Expand Down
Loading

0 comments on commit f8c791c

Please sign in to comment.