Skip to content

Commit

Permalink
Merge pull request #520 from WildernessLabs/feature/firmware-write-cl…
Browse files Browse the repository at this point in the history
…eanup

string replacements.  Remove all warnings from firmware write command
  • Loading branch information
adrianstevens committed Mar 7, 2024
2 parents 8e1eb65 + f33333c commit 2e75512
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ public FirmwareWriteCommand(ISettingsManager settingsManager, FileManager fileMa

private int _lastWriteProgress = 0;

private async Task<IMeadowConnection?> GetConnectionAndDisableRuntime(string? route = null)
private async Task<IMeadowConnection> GetConnectionAndDisableRuntime(string? route = null)
{
IMeadowConnection? connection = null;
IMeadowConnection connection;

if (route != null)
{
Expand All @@ -54,7 +54,7 @@ public FirmwareWriteCommand(ISettingsManager settingsManager, FileManager fileMa
connection = await GetCurrentConnection(true);
}

if (await connection.Device.IsRuntimeEnabled())
if (await connection.Device!.IsRuntimeEnabled())
{
Logger?.LogInformation($"{Strings.DisablingRuntime}...");
await connection.Device.RuntimeDisable();
Expand Down Expand Up @@ -93,11 +93,13 @@ public FirmwareWriteCommand(ISettingsManager settingsManager, FileManager fileMa
private bool RequiresDfuForRuntimeUpdates(DeviceInfo info)
{
return true;

/*
restore this when we support OtA-style updates again
if (System.Version.TryParse(info.OsVersion, out var version))
{
return version.Major >= 2;
}
*/
}

private bool RequiresDfuForEspUpdates(DeviceInfo info)
Expand Down Expand Up @@ -191,12 +193,14 @@ protected override async ValueTask ExecuteCommand()
// get a list of ports - it will not have our meadow in it (since it should be in DFU mode)
var initialPorts = await MeadowConnectionManager.GetSerialPorts();

if (await WriteOsWithDfu(dfuDevice, osFileWithBootloader) == false)
try
{
throw new CommandException(Strings.DfuWriteFailed);
await WriteOsWithDfu(dfuDevice, osFileWithBootloader!);
}
finally
{
dfuDevice?.Dispose();
}

dfuDevice?.Dispose();

await Task.Delay(1500);

Expand Down Expand Up @@ -248,7 +252,7 @@ protected override async ValueTask ExecuteCommand()
Logger?.LogInformation(Strings.FirmwareUpdatedSuccessfully);
}

async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)
private async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)
{
IMeadowConnection? connection = null;

Expand Down Expand Up @@ -282,7 +286,7 @@ async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)
}
}

Logger?.LogInformation($"Meadow found at {newPort}");
Logger?.LogInformation($"{Strings.MeadowFoundAt} {newPort}");

connection = await GetConnectionAndDisableRuntime();

Expand All @@ -296,7 +300,9 @@ async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)

private async Task<IMeadowConnection?> WriteRuntime(IMeadowConnection? connection, DeviceInfo? deviceInfo, FirmwarePackage package)
{
Logger?.LogInformation($"{Environment.NewLine}Getting runtime for {package.Version}...");
Logger?.LogInformation($"{Environment.NewLine}{Strings.GettingRuntimeFor} {package.Version}...");

if (package.Runtime == null) { return null; }

// get the path to the runtime file
var rtpath = package.GetFullyQualifiedPath(package.Runtime);
Expand All @@ -308,10 +314,15 @@ async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)
{
connection ??= await GetConnectionAndDisableRuntime();

Logger?.LogInformation($"{Environment.NewLine}Writing Runtime ...");
Logger?.LogInformation($"{Environment.NewLine}{Strings.WritingRuntime} ...");

deviceInfo ??= await connection.GetDeviceInfo(CancellationToken);

if (deviceInfo == null)
{
throw new CommandException(Strings.UnableToGetDeviceInfo);
}

if (UseDfu || RequiresDfuForRuntimeUpdates(deviceInfo))
{
var initialPorts = await MeadowConnectionManager.GetSerialPorts();
Expand All @@ -320,7 +331,7 @@ async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)
if (!await connection!.Device!.WriteRuntime(runtimePath, CancellationToken))
{
// TODO: implement a retry timeout
Logger?.LogInformation($"Error writing runtime - retrying");
Logger?.LogInformation($"{Strings.ErrorWritingRuntime} - {Strings.Retrying}");
goto write_runtime;
}

Expand All @@ -330,14 +341,14 @@ async Task<IMeadowConnection> FindMeadowConnection(IList<string> portsToIgnore)
{
var newPort = await WaitForNewSerialPort(initialPorts);

if (newPort != null)
if (newPort == null)
{
throw CommandException.MeadowDeviceNotFound;
}

connection = await GetCurrentConnection(true);

Logger?.LogInformation($"Meadow found at {newPort}");
Logger?.LogInformation($"{Strings.MeadowFoundAt} {newPort}");

// configure the route to that port for the user
Settings.SaveSetting(SettingsManager.PublicSettings.Route, newPort);
Expand All @@ -357,7 +368,7 @@ private async Task WriteEspFiles(IMeadowConnection? connection, DeviceInfo? devi

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

Logger?.LogInformation($"{Environment.NewLine}Writing Coprocessor files...");
Logger?.LogInformation($"{Environment.NewLine}{Strings.WritingCoprocessorFiles}...");

string[] fileList;

Expand All @@ -377,6 +388,8 @@ private async Task WriteEspFiles(IMeadowConnection? connection, DeviceInfo? devi

deviceInfo ??= await connection.GetDeviceInfo(CancellationToken);

if (deviceInfo == null) { throw new CommandException(Strings.UnableToGetDeviceInfo); }

if (UseDfu || RequiresDfuForEspUpdates(deviceInfo))
{
await connection.Device!.WriteCoprocessorFiles(fileList, CancellationToken);
Expand Down Expand Up @@ -425,7 +438,7 @@ private async Task WriteEspFiles(IMeadowConnection? connection, DeviceInfo? devi
return devices[0];
}
}
throw new CommandException("Multiple devices found in bootloader mode - only connect one device");
throw new CommandException(Strings.MultipleDfuDevicesFound);
}

private async Task<FirmwarePackage?> GetSelectedPackage()
Expand All @@ -442,34 +455,31 @@ private async Task WriteEspFiles(IMeadowConnection? connection, DeviceInfo? devi

if (existing == null)
{
Logger?.LogError($"Requested firmware version '{Version}' not found");
Logger?.LogError(string.Format(Strings.SpecifiedFirmwareVersionNotFound, Version));
return null;
}
package = existing;
}
else
{
Version = collection.DefaultPackage?.Version ?? throw new CommandException("No default version set");
Version = collection.DefaultPackage?.Version ?? throw new CommandException($"{Strings.NoDefaultVersionSet}. {Strings.UseCommandFirmwareDefault}.");

package = collection.DefaultPackage;
}

return package;
}

private async Task<bool> WriteOsWithDfu(ILibUsbDevice? libUsbDevice, string osFile)
private async Task WriteOsWithDfu(ILibUsbDevice? libUsbDevice, string osFile)
{
// get the device's serial number via DFU - we'll need it to find the device after it resets
if (libUsbDevice == null)
{
try
{
libUsbDevice = GetLibUsbDeviceForCurrentEnvironment();
}
catch (Exception ex)
libUsbDevice = GetLibUsbDeviceForCurrentEnvironment();

if (libUsbDevice == null)
{
Logger?.LogError(ex.Message);
return false;
throw new CommandException(Strings.NoDfuDeviceDetected);
}
}

Expand All @@ -479,8 +489,7 @@ private async Task<bool> WriteOsWithDfu(ILibUsbDevice? libUsbDevice, string osFi
}
catch
{
Logger?.LogError("Firmware write failed - unable to read device serial number (make sure device is connected)");
return false;
throw new CommandException($"{Strings.FirmwareWriteFailed} - {Strings.UnableToReadSerialNumber} ({Strings.MakeSureDeviceisConnected})");
}

try
Expand All @@ -493,8 +502,7 @@ await DfuUtils.FlashFile(
}
catch (ArgumentException)
{
Logger?.LogWarning("Unable to write firmware - is Dfu-util installed? Run `meadow dfu install` to install");
return false;
throw new CommandException($"{Strings.FirmwareWriteFailed} - {Strings.IsDfuUtilInstalled} {Strings.RunMeadowDfuInstall}");
}
catch (Exception ex)
{
Expand All @@ -504,13 +512,11 @@ await DfuUtils.FlashFile(
// TODO: catch the Win10 DFU error here and change the global provider configuration to "classic"
Settings.SaveSetting(SettingsManager.PublicSettings.LibUsb, "classic");

Logger?.LogWarning("This machine requires an older version of LibUsb. The CLI settings have been updated, re-run the 'firmware write' command to update your device.");
return false;
throw new CommandException("This machine requires an older version of LibUsb. The CLI settings have been updated, re-run the 'firmware write' command to update your device.");
}
return true;
}

private async Task<IList<string>> WaitForNewSerialPorts(IList<string> ignorePorts)
private async Task<IList<string>> WaitForNewSerialPorts(IList<string>? ignorePorts)
{
var ports = await MeadowConnectionManager.GetSerialPorts();

Expand All @@ -520,16 +526,20 @@ private async Task<IList<string>> WaitForNewSerialPorts(IList<string> ignorePort
{
if (retryCount++ > 10)
{
throw new CommandException("New meadow device not found");
throw new CommandException(Strings.NewMeadowDeviceNotFound);
}
await Task.Delay(500);
ports = await MeadowConnectionManager.GetSerialPorts();
}

return ports.Except(ignorePorts).ToList();
if (ignorePorts != null)
{
return ports.Except(ignorePorts).ToList();
}
return ports.ToList();
}

private async Task<string> WaitForNewSerialPort(IList<string>? ignorePorts)
private async Task<string?> WaitForNewSerialPort(IList<string>? ignorePorts)
{
var ports = await WaitForNewSerialPorts(ignorePorts);

Expand Down
17 changes: 17 additions & 0 deletions Source/v2/Meadow.Cli/Strings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public static class Strings
public const string InvalidApplicationPath = "Invalid application path";
public const string InvalidParameter = "Invalid parameter";
public const string GettingDeviceInfo = "Getting device info...";
public const string UnableToGetDeviceInfo = "Unable to get device info";
public const string RetrievingUserAndOrgInfo = "Retrieving your user and organization information...";
public const string MemberOfMoreThanOneOrg = "You are a member of more than 1 organization. Please specify the desired orgId for this device provisioning.";
public const string UnableToFindMatchingOrg = "Unable to find an organization with a Name or ID matching '{0}'";
Expand Down Expand Up @@ -44,4 +45,20 @@ public static class Strings
public const string PathMeadowApplication = "Path to the Meadow application";
public const string PathToMeadowProject = "Path to the Meadow project file";
public const string NoLinkAssemblies = "Assemblies to skip during linking";
public const string WritingCoprocessorFiles = "Writing Coprocessor files";
public const string MeadowFoundAt = "Meadow found at";
public const string GettingRuntimeFor = "Getting runtime for";
public const string WritingRuntime = "Writing runtime for";
public const string ErrorWritingRuntime = "Error writing runtime for";
public const string Retrying = "retrying";
public const string MultipleDfuDevicesFound = "Multiple devices found in bootloader mode - only connect one device";
public const string SpecifiedFirmwareVersionNotFound = "Requested firmware version '{0}' not found";
public const string NoDefaultVersionSet = "No default version set";
public const string UseCommandFirmwareDefault = "Use 'meadow firmare default' to set a default version";
public const string FirmwareWriteFailed = "Firmware write failed";
public const string UnableToReadSerialNumber = "unable to read device serial number";
public const string MakeSureDeviceisConnected = "make sure a device is connected";
public const string IsDfuUtilInstalled = "Is dfu-util installed?";
public const string RunMeadowDfuInstall = "Run 'meadow dfu install' to install";
public const string NewMeadowDeviceNotFound = "New Meadow device not found";
}

0 comments on commit 2e75512

Please sign in to comment.