Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warnings and defensive coding #429

Merged
merged 2 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions Source/v2/Meadow.CLI.Core/DFU/DfuSharp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,21 +278,20 @@ public class DfuDevice : IDisposable

public DfuDevice(IntPtr device, InterfaceDescriptor interface_descriptor, DfuFunctionDescriptor dfu_descriptor)
{
interface_descriptor = interface_descriptor;
dfu_descriptor = dfu_descriptor;
this.interface_descriptor = interface_descriptor;
this.dfu_descriptor = dfu_descriptor;

if (NativeMethods.libusb_open(device, ref handle) < 0)
{
throw new Exception("Error opening device");
}
}

public event UploadingEventHandler Uploading;
public event UploadingEventHandler Uploading = default!;

protected virtual void OnUploading(UploadingEventArgs e)
{
if (Uploading != null)
Uploading(this, e);
Uploading?.Invoke(this, e);
}
public void ClaimInterface()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ public partial class PackageManager
public const string PostLinkDirectoryName = "postlink_bin";
public const string PackageOutputDirectoryName = "mpak";

private string? _meadowAssembliesPath;
private string _meadowAssembliesPath = string.Empty;

private string? MeadowAssembliesPath
private string MeadowAssembliesPath
{
get
{
if (_meadowAssembliesPath == null)
if (string.IsNullOrWhiteSpace(_meadowAssembliesPath))
{ // for now we only support F7
// TODO: add switch and support for other platforms
var store = _fileManager.Firmware["Meadow F7"];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ public record DeployOptions
public bool? IncludePDBs { get; set; }
}
}
}
}
12 changes: 6 additions & 6 deletions Source/v2/Meadow.Cli/AppManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static async Task DeployApplication(
string localBinaryDirectory,
bool includePdbs,
bool includeXmlDocs,
ILogger logger,
ILogger? logger,
CancellationToken cancellationToken)
{
// TODO: add sub-folder support when HCOM supports it
Expand All @@ -43,7 +43,7 @@ public static async Task DeployApplication(
var dependencies = packageManager.GetDependencies(new FileInfo(Path.Combine(localBinaryDirectory, "App.dll")));
dependencies.Add(Path.Combine(localBinaryDirectory, "App.dll"));

logger.LogInformation("Generating the list of files to deploy...");
logger?.LogInformation("Generating the list of files to deploy...");
foreach (var file in dependencies)
{
// TODO: add any other filtering capability here
Expand All @@ -65,7 +65,7 @@ public static async Task DeployApplication(

if (localFiles.Count() == 0)
{
logger.LogInformation($"No new files to deploy");
logger?.LogInformation($"No new files to deploy");
}

// get a list of files on-device, with CRCs
Expand All @@ -85,7 +85,7 @@ public static async Task DeployApplication(
// delete those files
foreach (var file in removeFiles)
{
logger.LogInformation($"Deleting file '{file}'...");
logger?.LogInformation($"Deleting file '{file}'...");
await connection.DeleteFile(file, cancellationToken);
}

Expand All @@ -94,7 +94,7 @@ public static async Task DeployApplication(
{
var existing = deviceFiles.FirstOrDefault(f => Path.GetFileName(f.Name) == Path.GetFileName(localFile.Key));

if (existing != null)
if (existing != null && existing.Crc != null)
{
if (uint.Parse(existing.Crc.Substring(2), System.Globalization.NumberStyles.HexNumber) == localFile.Value)
{
Expand All @@ -107,7 +107,7 @@ public static async Task DeployApplication(

if (!await connection?.WriteFile(localFile.Key, null, cancellationToken))
{
logger.LogWarning($"Error sending'{Path.GetFileName(localFile.Key)}'. Retrying.");
logger?.LogWarning($"Error sending'{Path.GetFileName(localFile.Key)}'. Retrying.");
await Task.Delay(100);
goto send_file;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ protected override async ValueTask ExecuteCommand()
file = new FileInfo(path);
}

var targetDirectory = file.DirectoryName;
var targetDirectory = file.DirectoryName!;

await AppManager.DeployApplication(_packageManager, connection, targetDirectory, true, false, Logger, CancellationToken);

Expand Down
2 changes: 1 addition & 1 deletion Source/v2/Meadow.Cli/Commands/Current/App/AppRunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Meadow.CLI.Commands.DeviceManagement;
public class AppRunCommand : BaseDeviceCommand<AppRunCommand>
{
private readonly IPackageManager _packageManager;
private string _lastFile;
private string? _lastFile;

[CommandOption("no-prefix", 'n', IsRequired = false, Description = "When set, the message source prefix (e.g. 'stdout>') is suppressed during 'listen'")]
public bool NoPrefix { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected override async ValueTask ExecuteCommand()
Logger?.LogInformation("Retrieving your user and organization information...");

var userOrgs = await _userService.GetUserOrgs(Host, CancellationToken).ConfigureAwait(false);
if (!userOrgs.Any())
if (userOrgs == null || !userOrgs.Any())
{
Logger?.LogInformation($"Please visit {Host} to register your account.");
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ protected override async ValueTask ExecuteCommand()

if (Version == null)
{
Logger?.LogInformation($"Default firmware is '{collection.DefaultPackage.Version}'.");
Logger?.LogInformation($"Default firmware is '{collection?.DefaultPackage?.Version}'.");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public class FirmwareWriteCommand : BaseDeviceCommand<FirmwareWriteCommand>
private ISettingsManager Settings { get; }

private ILibUsbDevice? _libUsbDevice;
private bool _fileWriteError = false;

public FirmwareWriteCommand(ISettingsManager settingsManager, FileManager fileManager, MeadowConnectionManager connectionManager, ILoggerFactory loggerFactory)
: base(connectionManager, loggerFactory)
Expand Down Expand Up @@ -201,11 +200,17 @@ private async ValueTask WriteFiles(IMeadowConnection connection, FirmwareType[]
};
connection.FileWriteFailed += (s, e) =>
{
_fileWriteError = true;
Logger?.LogError("Error writing file");
};

var package = await GetSelectedPackage();

if (package == null)
{
Logger?.LogError($"Firware write failed - unable to find selected package");
return;
}

var wasRuntimeEnabled = await connection!.Device!.IsRuntimeEnabled(CancellationToken);

if (wasRuntimeEnabled)
Expand Down Expand Up @@ -246,7 +251,7 @@ private async ValueTask WriteFiles(IMeadowConnection connection, FirmwareType[]
return;
}

if (FirmwareFileTypes.Contains(FirmwareType.ESP))
if (FirmwareFileTypes != null && FirmwareFileTypes.Contains(FirmwareType.ESP))
{
Logger?.LogInformation($"{Environment.NewLine}Writing Coprocessor files...");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ private async Task CallConfigCommand(string selectedPort)
Settings = new string[] { "route", selectedPort }
};

await setCommand.ExecuteAsync(Console);
if (Console != null)
{
await setCommand.ExecuteAsync(Console);
}
}
}
27 changes: 19 additions & 8 deletions Source/v2/Meadow.Cli/Commands/Legacy/FlashOsCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ protected override async ValueTask ExecuteCommand()
{
var package = await GetSelectedPackage();

if (package == null)
{
Logger?.LogError($"Unable to get selected OS package");
return;
}

var files = new List<FirmwareType>();
if (!SkipOS) files.Add(FirmwareType.OS);
if (!SkipEsp) files.Add(FirmwareType.ESP);
Expand All @@ -62,7 +68,7 @@ protected override async ValueTask ExecuteCommand()

if (Files == null)
{
Logger.LogInformation($"Writing all firmware for version '{package.Version}'...");
Logger?.LogInformation($"Writing all firmware for version '{package.Version}'...");

Files = new FirmwareType[]
{
Expand All @@ -80,7 +86,7 @@ protected override async ValueTask ExecuteCommand()

bool deviceSupportsOta = false; // TODO: get this based on device OS version

if (package?.OsWithoutBootloader == null
if (package.OsWithoutBootloader == null
|| !deviceSupportsOta
|| UseDfu)
{
Expand Down Expand Up @@ -259,7 +265,14 @@ private async ValueTask WriteFiles()
Logger?.LogInformation(message);
};

var package = await GetSelectedPackage();

var pack = await GetSelectedPackage();

if (pack == null)
{
Logger?.LogError($"Unable to get selected OS package");
}
FirmwarePackage package = pack!;

var wasRuntimeEnabled = await connection.Device.IsRuntimeEnabled(CancellationToken);

Expand All @@ -275,7 +288,7 @@ private async ValueTask WriteFiles()
Console?.Output.Write($"Writing {e.fileName}: {p:0}% \r");
};

if (Files.Contains(FirmwareType.OS))
if (Files!.Contains(FirmwareType.OS))
{
if (UseDfu)
{
Expand All @@ -288,7 +301,7 @@ private async ValueTask WriteFiles()
throw new NotSupportedException("OtA writes for the OS are not yet supported");
}
}
if (Files.Contains(FirmwareType.Runtime))
if (Files!.Contains(FirmwareType.Runtime))
{
Logger?.LogInformation($"{Environment.NewLine}Writing Runtime {package.Version}...");

Expand All @@ -299,7 +312,7 @@ private async ValueTask WriteFiles()

await connection.Device.WriteRuntime(rtpath, CancellationToken);
}
if (Files.Contains(FirmwareType.ESP))
if (Files!.Contains(FirmwareType.ESP))
{
Logger?.LogInformation($"{Environment.NewLine}Writing Coprocessor files...");

Expand All @@ -313,8 +326,6 @@ private async ValueTask WriteFiles()
await connection.Device.WriteCoprocessorFiles(fileList, CancellationToken);
}

Logger?.LogInformation($"{Environment.NewLine}");

if (wasRuntimeEnabled)
{
await connection.Device.RuntimeEnable();
Expand Down
2 changes: 1 addition & 1 deletion Source/v2/Meadow.Cloud.Client/Messages/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

public record User
{
public string Id { get; set; }

Check warning on line 5 in Source/v2/Meadow.Cloud.Client/Messages/User.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Non-nullable property 'Id' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
public string Email { get; set; }

Check warning on line 6 in Source/v2/Meadow.Cloud.Client/Messages/User.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Non-nullable property 'Email' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public void TestInvalidPortName()
}

[Fact]
public async void TestListen()
public void TestListen()
{
using (var connection = new SerialConnection(ValidPortName))
{
Expand Down
10 changes: 5 additions & 5 deletions Source/v2/Meadow.Hcom/Connections/SerialConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ public partial class SerialConnection : ConnectionBase, IDisposable
public const int ReadBufferSizeBytes = 0x2000;
private const int DefaultTimeout = 5000;

private event EventHandler<string> FileReadCompleted = delegate { };
private event EventHandler FileWriteAccepted;
private event EventHandler<string> FileDataReceived;
public event ConnectionStateChangedHandler ConnectionStateChanged = delegate { };
private event EventHandler<string> FileReadCompleted = default!;
private event EventHandler FileWriteAccepted = default!;
private event EventHandler<string> FileDataReceived = default!;
public event ConnectionStateChangedHandler ConnectionStateChanged = default!;

private readonly SerialPort _port;
private readonly ILogger? _logger;
Expand Down Expand Up @@ -1178,7 +1178,7 @@ public override async Task<string> GetPublicKey(CancellationToken? cancellationT
{
var command = RequestBuilder.Build<GetPublicKeyRequest>();

string? contents = null;
string contents = string.Empty;

void OnFileDataReceived(object? sender, string data)
{
Expand Down
4 changes: 2 additions & 2 deletions Source/v2/Meadow.Hcom/Connections/TcpConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ namespace Meadow.Hcom;

public class TcpConnection : ConnectionBase
{
private HttpClient _client;
private string _baseUri;
private readonly HttpClient _client;
private readonly string _baseUri;

public override string Name => _baseUri;

Expand Down
2 changes: 1 addition & 1 deletion Source/v2/Meadow.Hcom/SerialRequests/RequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
{
public static class RequestBuilder
{
private static uint _sequenceNumber;
//private static uint _sequenceNumber;

public static T Build<T>(uint userData = 0, ushort extraData = 0, ushort protocol = Protocol.HCOM_PROTOCOL_HCOM_VERSION_NUMBER)
where T : Request, new()
Expand Down
2 changes: 1 addition & 1 deletion Source/v2/Meadow.SoftwareManager/DownloadFileStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Meadow.Software;

internal class DownloadFileStream : Stream, IDisposable
{
public event EventHandler<long> DownloadProgress;
public event EventHandler<long> DownloadProgress = default!;

private readonly Stream _stream;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
public class F7FirmwarePackageCollection : IFirmwarePackageCollection
{
/// <inheritdoc/>
public event EventHandler<long> DownloadProgress;
public event EventHandler<long> DownloadProgress = default!;

public event EventHandler<FirmwarePackage?> DefaultVersionChanged;

public string PackageFileRoot { get; }

private List<FirmwarePackage> _f7Packages = new();
private readonly List<FirmwarePackage> _f7Packages = new();

public static string DefaultF7FirmwareStoreRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Expand All @@ -34,7 +34,7 @@

public FirmwarePackage this[int index] => _f7Packages[index];

internal F7FirmwarePackageCollection(string rootPath)

Check warning on line 37 in Source/v2/Meadow.SoftwareManager/F7FirmwarePackageCollection.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Non-nullable event 'DefaultVersionChanged' must contain a non-null value when exiting constructor. Consider declaring the event as nullable.
{
if (!Directory.Exists(rootPath))
{
Expand Down Expand Up @@ -85,13 +85,13 @@

// if we're deleting the default, we need to det another default
var i = _f7Packages.Count - 1;
while (DefaultPackage.Version == _f7Packages[i].Version)
while (DefaultPackage?.Version == _f7Packages[i].Version)
{
i--;
}
var newDefault = _f7Packages[i].Version;
_f7Packages.Remove(DefaultPackage);

Check warning on line 93 in Source/v2/Meadow.SoftwareManager/F7FirmwarePackageCollection.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Possible null reference argument for parameter 'item' in 'bool List<FirmwarePackage>.Remove(FirmwarePackage item)'.
SetDefaultPackage(newDefault);

Check warning on line 94 in Source/v2/Meadow.SoftwareManager/F7FirmwarePackageCollection.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

var path = Path.Combine(PackageFileRoot, version);

Expand Down
2 changes: 1 addition & 1 deletion Source/v2/Meadow.SoftwareManager/FirmwarePackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
{
internal IFirmwarePackageCollection _collection;

internal FirmwarePackage(IFirmwarePackageCollection collection)

Check warning on line 9 in Source/v2/Meadow.SoftwareManager/FirmwarePackage.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Non-nullable property 'Version' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 9 in Source/v2/Meadow.SoftwareManager/FirmwarePackage.cs

View workflow job for this annotation

GitHub Actions / Build and Optionally Publish Meadow.CLI nuget

Non-nullable property 'Targets' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
{
_collection = collection;
}

public string GetFullyQualifiedPath(string file)
public string GetFullyQualifiedPath(string? file)
{
return Path.Combine(_collection.PackageFileRoot, Version, file);
}
Expand Down
Loading