Skip to content
Open
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
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<Nullable>warnings</Nullable>
</PropertyGroup>
</Project>
4 changes: 2 additions & 2 deletions examples/SharpBrick.PoweredUp.Examples/BaseExample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public async Task InitExampleAndDiscoverAsync(IServiceProvider serviceProvider,

Host = serviceProvider.GetService<PoweredUpHost>();

Log = serviceProvider.GetService<ILoggerFactory>().CreateLogger("Example");
Log = serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Example");

var enableTrace = bool.TryParse(configuration["EnableTrace"], out var x) && x;

Expand All @@ -49,7 +49,7 @@ public virtual Task DiscoverAsync(bool enableTrace)
// add this when you are interested in a tracing of the message ("human readable")
if (enableTrace)
{
var tracer = hub.ServiceProvider.GetService<TraceMessages>();
var tracer = hub.ServiceProvider.GetRequiredService<TraceMessages>();
await tracer.ExecuteAsync();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public override async Task ExecuteAsync()

var motor = technicMediumHub.A.GetDevice<TechnicLargeLinearMotor>();

var calibration = ServiceProvider.GetService<LinearMidCalibration>();
var calibration = ServiceProvider.GetRequiredService<LinearMidCalibration>();
await calibration.ExecuteAsync(motor);
await technicMediumHub.WaitButtonClickAsync();

Expand Down
4 changes: 2 additions & 2 deletions examples/SharpBrick.PoweredUp.Examples/ExampleRampUp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public override async Task ExecuteAsync()
var motor = technicMediumHub.A.GetDevice<TechnicLargeLinearMotor>();

// ramp up with linear speed
var rampUp = ServiceProvider.GetService<LinearSpeedChange>();
var rampUp = ServiceProvider.GetRequiredService<LinearSpeedChange>();

await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red);

Expand All @@ -33,7 +33,7 @@ public override async Task ExecuteAsync()
await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Orange);

// ramp down with linear speed
var rampDown = ServiceProvider.GetService<LinearSpeedChange>();
var rampDown = ServiceProvider.GetRequiredService<LinearSpeedChange>();

var beforeOrangePhase = stopWatch.ElapsedMilliseconds;
await rampDown.ExecuteAsync(motor, 100, 0, 100, 20_000);
Expand Down
8 changes: 6 additions & 2 deletions examples/SharpBrick.PoweredUp.Examples/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ static async Task Main(string[] args)
var typeToExecute = Assembly
.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(x => x.FullName.StartsWith($"Example.Example{exampleToExecute}"));
.FirstOrDefault(x => x.FullName?.StartsWith($"Example.Example{exampleToExecute}") == true);

if (typeToExecute is null)
{
Expand All @@ -45,7 +45,11 @@ static async Task Main(string[] args)
}

var example = Activator.CreateInstance(typeToExecute) as Example.BaseExample;

if (example is null)
{
Console.WriteLine("Could not create example instance.");
return;
}

// (2) build the DI container
var serviceCollection = new ServiceCollection();
Expand Down
4 changes: 2 additions & 2 deletions examples/SharpBrick.PoweredUp.ExampplesOnProtocol/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
.BuildServiceProvider();

// getting utilities
var bt = serviceProvider.GetService<IPoweredUpBluetoothAdapter>();
var host = serviceProvider.GetService<PoweredUpHost>();
var bt = serviceProvider.GetRequiredService<IPoweredUpBluetoothAdapter>();
var host = serviceProvider.GetRequiredService<PoweredUpHost>();

// discover a LWP bluetooth device
var tcs = new TaskCompletionSource<ILegoWirelessProtocol>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
TraceDebug = options.Value.TraceDebug;
BgLib = new Bluegiga.BGLibDebug();
BleModuleConnection = new BleModuleConnection(BgLib);
BleModuleConnection.Start(options.Value.COMPortName, 0);

Check warning on line 49 in src/SharpBrick.PoweredUp.BlueGigaBLE/BlueGigaBLEPoweredUpBluetoothAdapater.cs

View workflow job for this annotation

GitHub Actions / build

'BleModuleConnection.Start(string, int)' is obsolete: 'The port thread sleep parameter has no effect anymore and this constructor will be removed in future releases'

Check warning on line 49 in src/SharpBrick.PoweredUp.BlueGigaBLE/BlueGigaBLEPoweredUpBluetoothAdapater.cs

View workflow job for this annotation

GitHub Actions / build

'BleModuleConnection.Start(string, int)' is obsolete: 'The port thread sleep parameter has no effect anymore and this constructor will be removed in future releases'
Devices = new ConcurrentDictionary<ulong, BlueGigaBLEPoweredUpBluetoothDevice>();
DevicesInfo = new ConcurrentDictionary<ulong, PoweredUpBluetoothDeviceInfoWithMacAddress>();
}
Expand Down Expand Up @@ -85,8 +85,7 @@
//we only want to discover Lego-devices
//filter for correct service-GUID for LEGO-Hub, containing manufacturerData and the name
var addressNumber = BlueGigaBLEHelper.ByteArrayToUlong(e.Address);
var bleAdvertisingListFound = bleParsedData.TryGetValue(addressNumber, out var actualListAdvertisingData);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this change necessary?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the additional variable, the compiler can no longer correctly infer that actualListAdvertisingData cannot be null if TryGetValue returns true.

if (!bleAdvertisingListFound)
if (!bleParsedData.TryGetValue(addressNumber, out var actualListAdvertisingData))
{
actualListAdvertisingData = bleParsedData.AddOrUpdate(addressNumber, new List<BleAdvertisingData>(), (oldkey, oldvalue) => oldvalue = new List<BleAdvertisingData>());
}
Expand Down
14 changes: 7 additions & 7 deletions src/SharpBrick.PoweredUp.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ static async Task<int> Main(string[] args)

await AddTraceWriterAsync(scopedServiceProvider, enableTrace);

scopedServiceProvider.GetService<BluetoothKernel>().BluetoothDeviceInfo = bluetoothDeviceInfo;
scopedServiceProvider.GetRequiredService<BluetoothKernel>().BluetoothDeviceInfo = bluetoothDeviceInfo;

var deviceListCli = scopedServiceProvider.GetService<DevicesList>(); // ServiceLocator ok: transient factory
var deviceListCli = scopedServiceProvider.GetRequiredService<DevicesList>(); // ServiceLocator ok: transient factory

await deviceListCli.ExecuteAsync(systemType);
}
Expand Down Expand Up @@ -138,11 +138,11 @@ static async Task<int> Main(string[] args)

await AddTraceWriterAsync(scopedServiceProvider, enableTrace);

scopedServiceProvider.GetService<BluetoothKernel>().BluetoothDeviceInfo = bluetoothDeviceInfo;
scopedServiceProvider.GetRequiredService<BluetoothKernel>().BluetoothDeviceInfo = bluetoothDeviceInfo;

var dumpStaticPortInfoCommand = scopedServiceProvider.GetService<DumpStaticPortInfo>(); // ServiceLocator ok: transient factory
var dumpStaticPortInfoCommand = scopedServiceProvider.GetRequiredService<DumpStaticPortInfo>(); // ServiceLocator ok: transient factory

var port = byte.Parse(portOption.Value());
var port = byte.TryParse(portOption.Value(), out var parsedPort) ? parsedPort : (byte)0;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is not that a behavior change to the CLI?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess technically, yes. But wasn't the behavior before that omitting the -p port option would lead to an exception here?


await dumpStaticPortInfoCommand.ExecuteAsync(systemType, port, headerEnabled);
}
Expand Down Expand Up @@ -193,7 +193,7 @@ static async Task<int> Main(string[] args)

await AddTraceWriterAsync(scopedServiceProvider, enableTrace);

var prettyPrintCommand = scopedServiceProvider.GetService<PrettyPrint>(); // ServiceLocator ok: transient factory
var prettyPrintCommand = scopedServiceProvider.GetRequiredService<PrettyPrint>(); // ServiceLocator ok: transient factory

TextReader reader = Console.In;

Expand Down Expand Up @@ -273,7 +273,7 @@ public static async Task AddTraceWriterAsync(IServiceProvider serviceProvider, b
{
if (enableTrace)
{
var traceMessages = serviceProvider.GetService<TraceMessages>(); // ServiceLocator ok: transient factory
var traceMessages = serviceProvider.GetRequiredService<TraceMessages>(); // ServiceLocator ok: transient factory

await traceMessages.ExecuteAsync();
}
Expand Down
2 changes: 1 addition & 1 deletion src/SharpBrick.PoweredUp/Deployment/HubExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ private static Action<DeploymentModelError[]> LogErrors(Hub self)
{
return errors =>
{
var logger = self.ServiceProvider.GetService<ILoggerFactory>().CreateLogger<Hub>();
var logger = self.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<Hub>();
if (errors.Length > 0)
{

Expand Down
13 changes: 11 additions & 2 deletions src/SharpBrick.PoweredUp/Hubs/HubFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,24 @@ public HubFactory(IServiceProvider serviceProvider)

public Hub CreateByBluetoothManufacturerData(byte[] manufacturerData)
{
var hub = (manufacturerData is null || manufacturerData.Length < 3) ? null : Create(GetTypeFromSystemType(GetSystemTypeFromManufacturerData((PoweredUpHubManufacturerData)manufacturerData[1])));
if (manufacturerData is null)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if this is right change. Maybe the function needs a Hub? as a result. Obviously the init line needs to change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just tried to keep the changes minimal.
Before this change, the call to Configure later would throw a NullReferenceException anyway, and I figured that throwing a more meaningful exception would be better.

{
throw new ArgumentNullException(nameof(manufacturerData));
}
if (manufacturerData.Length < 3)
{
throw new ArgumentException("Manufacturer data must be at least 3 bytes long.", nameof(manufacturerData));
}

var hub = Create(GetTypeFromSystemType(GetSystemTypeFromManufacturerData((PoweredUpHubManufacturerData)manufacturerData[1])));
hub.Configure(0x00);

return hub;
}

public THub Create<THub>() where THub : Hub
{
var hub = Create(typeof(THub)) as THub;
var hub = (THub)Create(typeof(THub));
hub.Configure(0x00);

return hub;
Expand Down
2 changes: 1 addition & 1 deletion src/SharpBrick.PoweredUp/PoweredUpHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public IServiceScope CreateProtocolScope(IPoweredUpBluetoothDeviceInfo bluetooth
var scopedServiceProvider = scope.ServiceProvider;

// initialize scoped bluetooth kernel to bluetooth address.
var kernel = scopedServiceProvider.GetService<BluetoothKernel>();
var kernel = scopedServiceProvider.GetRequiredService<BluetoothKernel>();
kernel.BluetoothDeviceInfo = bluetoothDeviceInfo;

return scope;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public static LegoWirelessMessage Decode(in Span<byte> data, ProtocolKnowledge k

if (encoder is not null)
{
var message = encoder?.Decode(hubId, content);
var message = encoder.Decode(hubId, content);

message.Length = length;
message.HubId = hubId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ public static async Task<PortFeedback> SendPortOutputCommandAsync(this ILegoWire

var response = await self.SendMessageReceiveResultAsync<PortOutputCommandFeedbackMessage>(message, msg => msg.Feedbacks.Any(f => f.PortId == portId));

return response.Feedbacks.FirstOrDefault(f => f.PortId == portId).Feedback;
return response.Feedbacks.First(f => f.PortId == portId).Feedback;
}
}
2 changes: 1 addition & 1 deletion test/SharpBrick.PoweredUp.Test/Devices/VoltageTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ await mock.WriteUpstreamAsync(new PortInputFormatSingleMessage(0x20, 1, 0, true)

var poweredUpBluetoothAdapterMock = serviceProvider.GetMockBluetoothAdapter();

var protocol = serviceProvider.GetService<ILegoWirelessProtocol>();
var protocol = serviceProvider.GetRequiredService<ILegoWirelessProtocol>();

protocol.ConnectAsync(knownSystemType).Wait();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ public void HubActionsEncoder_Decode(HubAction expectedAction, string dataAsStri
var data = BytesStringUtil.StringToData(dataAsString);

// act
var message = MessageEncoder.Decode(data, null) as HubActionMessage;
var message = MessageEncoder.Decode(data, null);

// assert
Assert.Equal(expectedAction, message.Action);
var hubActionMessage = Assert.IsType<HubActionMessage>(message);
Assert.Equal(expectedAction, hubActionMessage.Action);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ public void HubAlertEncoder_Decode(HubAlert expectedAlert, HubAlertOperation exp
var data = BytesStringUtil.StringToData(dataAsString);

// act
var message = MessageEncoder.Decode(data, null) as HubAlertMessage;
var message = MessageEncoder.Decode(data, null);

// assert
Assert.Equal(expectedAlert, message.Alert);
Assert.Equal(expectedOperation, message.Operation);
Assert.Equal(expectedPayload, message.DownstreamPayload);
var hubAlertMessage = Assert.IsType<HubAlertMessage>(message);
Assert.Equal(expectedAlert, hubAlertMessage.Alert);
Assert.Equal(expectedOperation, hubAlertMessage.Operation);
Assert.Equal(expectedPayload, hubAlertMessage.DownstreamPayload);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@ public void HubAttachedIOEncoder_Decode_Attached<T>(string messageAsString, Devi
var data = BytesStringUtil.StringToData(messageAsString).AsSpan()[3..];

// act
var message = new HubAttachedIOEncoder().Decode(0x00, data) as HubAttachedIOForAttachedDeviceMessage;
var message = new HubAttachedIOEncoder().Decode(0x00, data);

// assert
Assert.Equal(expectedPortId, message.PortId);
Assert.Equal(expectedType, message.IOTypeId);
Assert.Equal(new Version(expectedHwVersion), message.HardwareRevision);
Assert.Equal(new Version(expectedSwVersion), message.SoftwareRevision);
var hubAttachedIOForAttachedDeviceMessage = Assert.IsType<HubAttachedIOForAttachedDeviceMessage>(message);
Assert.Equal(expectedPortId, hubAttachedIOForAttachedDeviceMessage.PortId);
Assert.Equal(expectedType, hubAttachedIOForAttachedDeviceMessage.IOTypeId);
Assert.Equal(new Version(expectedHwVersion), hubAttachedIOForAttachedDeviceMessage.HardwareRevision);
Assert.Equal(new Version(expectedSwVersion), hubAttachedIOForAttachedDeviceMessage.SoftwareRevision);

// reverse test
var reverseMessage = new HubAttachedIOForAttachedDeviceMessage(expectedPortId, expectedType, Version.Parse(expectedHwVersion), Version.Parse(expectedSwVersion));
Expand All @@ -50,12 +51,13 @@ public void HubAttachedIOEncoder_Decode_AttachedVirutalIO(string messageAsString
var data = BytesStringUtil.StringToData(messageAsString).AsSpan()[3..];

// act
var message = new HubAttachedIOEncoder().Decode(0x00, data) as HubAttachedIOForAttachedVirtualDeviceMessage;
var message = new HubAttachedIOEncoder().Decode(0x00, data);

// assert
Assert.Equal(expectedPortId, message.PortId);
Assert.Equal(expectedType, message.IOTypeId);
Assert.Equal(portA, message.PortAId);
Assert.Equal(portB, message.PortBId);
var hubAttachedIOForAttachedVirtualDeviceMessage = Assert.IsType<HubAttachedIOForAttachedVirtualDeviceMessage>(message);
Assert.Equal(expectedPortId, hubAttachedIOForAttachedVirtualDeviceMessage.PortId);
Assert.Equal(expectedType, hubAttachedIOForAttachedVirtualDeviceMessage.IOTypeId);
Assert.Equal(portA, hubAttachedIOForAttachedVirtualDeviceMessage.PortAId);
Assert.Equal(portB, hubAttachedIOForAttachedVirtualDeviceMessage.PortBId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ public void HubPropertiesEncoder_Decode_UpdateUpstream<T>(string messageAsString
var data = BytesStringUtil.StringToData(messageAsString).AsSpan()[3..];

// act
var message = new HubPropertiesEncoder().Decode(0x00, data) as HubPropertyMessage<T>;
var message = new HubPropertiesEncoder().Decode(0x00, data);

// assert
Assert.Equal(expectedProperty, message.Property);
Assert.Equal(expectedPropertyOperation, message.Operation);
Assert.Equal(payload, message.Payload);
var hubPropertyMessage = Assert.IsType<HubPropertyMessage<T>>(message);
Assert.Equal(expectedProperty, hubPropertyMessage.Property);
Assert.Equal(expectedPropertyOperation, hubPropertyMessage.Operation);
Assert.Equal(payload, hubPropertyMessage.Payload);
}

[Theory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,19 @@ public void PortInformationEncoder_Decode_PortInformationForModeInfoMessage(byte
var data = BytesStringUtil.StringToData(dataAsString);

// act
var message = MessageEncoder.Decode(data, null) as PortInformationForModeInfoMessage;
var message = MessageEncoder.Decode(data, null);

// assert
Assert.Equal(expectedPort, message.PortId);
Assert.Equal(expectedType, message.InformationType);
Assert.Equal(expectedOutput, message.OutputCapability);
Assert.Equal(expectedInput, message.InputCapability);
Assert.Equal(expectedLogicalCombinable, message.LogicalCombinableCapability);
Assert.Equal(expectedLogicalSynchronizable, message.LogicalSynchronizableCapability);
Assert.Equal(expectedTotalCount, message.TotalModeCount);
Assert.Equal(expectedInputModes, message.InputModes);
Assert.Equal(expectedOutputModes, message.OutputModes);
var portInformationForModeInfoMessage = Assert.IsType<PortInformationForModeInfoMessage>(message);
Assert.Equal(expectedPort, portInformationForModeInfoMessage.PortId);
Assert.Equal(expectedType, portInformationForModeInfoMessage.InformationType);
Assert.Equal(expectedOutput, portInformationForModeInfoMessage.OutputCapability);
Assert.Equal(expectedInput, portInformationForModeInfoMessage.InputCapability);
Assert.Equal(expectedLogicalCombinable, portInformationForModeInfoMessage.LogicalCombinableCapability);
Assert.Equal(expectedLogicalSynchronizable, portInformationForModeInfoMessage.LogicalSynchronizableCapability);
Assert.Equal(expectedTotalCount, portInformationForModeInfoMessage.TotalModeCount);
Assert.Equal(expectedInputModes, portInformationForModeInfoMessage.InputModes);
Assert.Equal(expectedOutputModes, portInformationForModeInfoMessage.OutputModes);
}


Expand All @@ -43,11 +44,12 @@ public void PortInformationEncoder_Decode_PortInformationForPossibleModeCombinat
var data = BytesStringUtil.StringToData(dataAsString);

// act
var message = MessageEncoder.Decode(data, null) as PortInformationForPossibleModeCombinationsMessage;
var message = MessageEncoder.Decode(data, null);

// assert
Assert.Equal(expectedPort, message.PortId);
Assert.Equal(expectedType, message.InformationType);
Assert.Collection(message.ModeCombinations, expectedCombinations.Select<ushort, Action<ushort>>(combination => { return (item) => Assert.Equal(combination, item); }).ToArray());
var portInformationForPossibleModeCombinationsMessage = Assert.IsType<PortInformationForPossibleModeCombinationsMessage>(message);
Assert.Equal(expectedPort, portInformationForPossibleModeCombinationsMessage.PortId);
Assert.Equal(expectedType, portInformationForPossibleModeCombinationsMessage.InformationType);
Assert.Collection(portInformationForPossibleModeCombinationsMessage.ModeCombinations, expectedCombinations.Select<ushort, Action<ushort>>(combination => { return (item) => Assert.Equal(combination, item); }).ToArray());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ public void PortInputFormatCombinedModeEncoder_Decode(string dataAsString, byte
var data = BytesStringUtil.StringToData(dataAsString);

// act
var message = MessageEncoder.Decode(data, null) as PortInputFormatCombinedModeMessage;
var message = MessageEncoder.Decode(data, null);

// assert
Assert.Equal(expectedPortId, message.PortId);
Assert.Equal(expectedCombinationIndex, message.UsedCombinationIndex);
Assert.Equal(expectedEnabled, message.MultiUpdateEnabled);
Assert.Collection(message.ConfiguredModeDataSetIndex, expectedIndexes.Select<int, Action<int>>(exp => (act) => Assert.Equal(exp, act)).ToArray());
var portInputFormatCombinedModeMessage = Assert.IsType<PortInputFormatCombinedModeMessage>(message);
Assert.Equal(expectedPortId, portInputFormatCombinedModeMessage.PortId);
Assert.Equal(expectedCombinationIndex, portInputFormatCombinedModeMessage.UsedCombinationIndex);
Assert.Equal(expectedEnabled, portInputFormatCombinedModeMessage.MultiUpdateEnabled);
Assert.Collection(portInputFormatCombinedModeMessage.ConfiguredModeDataSetIndex, expectedIndexes.Select<int, Action<int>>(exp => (act) => Assert.Equal(exp, act)).ToArray());
}
}
Loading
Loading