diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..91af8f7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +root = true + +[*.cs] +dotnet_diagnostic.CA1822.severity = none \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..7a9f6fc --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "omnisharp.enableRoslynAnalyzers": true, + "editor.formatOnPaste": true, + "editor.formatOnSave": true, + "editor.formatOnType": true +} \ No newline at end of file diff --git a/README.md b/README.md index 1b4d73f..ac32f54 100644 --- a/README.md +++ b/README.md @@ -210,7 +210,7 @@ The `poweredup` command line utility intends to allow the inspection of LEGO Wir ## Installation Instruction -1. Install the [latest .NET (Core)](https://dotnet.microsoft.com/download) on your machine (e.g. .NET Core 3.1). +1. Install the [latest .NET](https://dotnet.microsoft.com/download) on your machine (e.g. .NET 5). 2. Install the `poweredup` dotnet utility using the following instruction ```` dotnet tool install -g SharpBrick.PoweredUp.Cli @@ -260,7 +260,7 @@ DI Container Elements ## Implementation Status - Bluetooth Adapter - - [X] .NET Core 3.1 (on Windows 10 using WinRT Bluetooth) + - [X] .NET Core 3.1 (on Windows 10 using WinRT Bluetooth). Please use version v3.4.0 and consider upgrading to .NET 5 - [X] .NET 5 (on Windows 10 using WinRT Bluetooth) - [ ] UWP (most likely December 2021; UWP currently does not support .NET Standard 2.1 and C# 8.0+) - [ ] .NET Framework 4.8 (will never be supported; .NET Framework does not and will never support .NET Standard 2.1 and C# 8.0+) diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByKnownAddress.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByKnownAddress.cs index 577eeca..6fd68b6 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByKnownAddress.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByKnownAddress.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -21,22 +20,21 @@ public override async Task DiscoverAsync(bool enableTrace) public override async Task ExecuteAsync() { - using (var technicMediumHub = DirectlyConnectedHub) - { - await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); + using var technicMediumHub = DirectlyConnectedHub; - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); - await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); + await Task.Delay(2000); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); - await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0xff, 0x00); + await Task.Delay(2000); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0xff, 0x00); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(2000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByName.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByName.cs index 6a137ac..cb2bd82 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByName.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByName.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -10,22 +9,21 @@ public class ExampleBluetoothByName : BaseExample public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByName("Technic Hub")) - { - await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); + using var technicMediumHub = Host.FindByName("Technic Hub"); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); - await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); + await Task.Delay(2000); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); - await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0xff, 0x00); + await Task.Delay(2000); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0xff, 0x00); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(2000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleCalibrationSteering.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleCalibrationSteering.cs index 6a732b9..dc95302 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleCalibrationSteering.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleCalibrationSteering.cs @@ -10,22 +10,21 @@ public class ExampleCalibrationSteering : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var motor = technicMediumHub.A.GetDevice(); + using var technicMediumHub = Host.FindByType(); - var calibration = ServiceProvider.GetService(); - await calibration.ExecuteAsync(motor); - await technicMediumHub.WaitButtonClickAsync(); + var motor = technicMediumHub.A.GetDevice(); - await motor.GotoPositionAsync(CW * 50, 20, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile); - await technicMediumHub.WaitButtonClickAsync(); + var calibration = ServiceProvider.GetService(); + await calibration.ExecuteAsync(motor); + await technicMediumHub.WaitButtonClickAsync(); - await motor.GotoPositionAsync(CCW * 50, 20, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile); - await Task.Delay(5000); + await motor.GotoPositionAsync(CW * 50, 20, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile); + await technicMediumHub.WaitButtonClickAsync(); - await technicMediumHub.SwitchOffAsync(); - } + await motor.GotoPositionAsync(CCW * 50, 20, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile); + await Task.Delay(5000); + + await technicMediumHub.SwitchOffAsync(); } diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleColors.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleColors.cs index 1b0b71c..3c2b6df 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleColors.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleColors.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -8,14 +7,13 @@ public class ExampleColors : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); + using var technicMediumHub = Host.FindByType(); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(2000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleDiscoverByType.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleDiscoverByType.cs index 5bc8939..345c633 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleDiscoverByType.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleDiscoverByType.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -20,22 +19,21 @@ public override async Task DiscoverAsync(bool enableTrace) public override async Task ExecuteAsync() { - using (var technicMediumHub = DirectlyConnectedHub) - { - await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); + using var technicMediumHub = DirectlyConnectedHub; - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); - await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); + await Task.Delay(2000); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); - await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0xff, 0x00); + await Task.Delay(2000); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0xff, 0x00); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(2000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleDuploTrainBase.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleDuploTrainBase.cs index bf8a762..892b630 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleDuploTrainBase.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleDuploTrainBase.cs @@ -9,63 +9,62 @@ public class ExampleDuploTrainBase : BaseExample { public override async Task ExecuteAsync() { - using (var train = Host.FindByType()) - { - await train.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => { }) - ); + using var train = Host.FindByType(); - using var d1 = train.Voltage.VoltageSObservable.Subscribe(x => Log.LogWarning($"Voltage: {x.Pct}% / {x.SI}")); - using var d2 = train.Motor.OnSecondsObservable.Subscribe(x => Log.LogWarning($"Seconds: {x}")); - using var d3 = train.Speedometer.SpeedObservable.Subscribe(x => Log.LogWarning($"Speed: {x.Pct}% / {x.SI}")); - using var d4 = train.Speedometer.CountObservable.Subscribe(x => Log.LogWarning($"Count: {x}")); - using var d5 = train.ColorSensor.ColorObservable.Subscribe(x => Log.LogWarning($"Color: {x}")); - using var d6 = train.ColorSensor.ColorTagObservable.Subscribe(x => Log.LogWarning($"Color Tag: {x}")); // does not work - using var d7 = train.ColorSensor.ReflectionObservable.Subscribe(x => Log.LogWarning($"Reflection: {x}")); - using var d8 = train.ColorSensor.RgbObservable.Subscribe(x => Log.LogWarning($"RGB {x.red}/{x.green}/{x.blue}")); + await train.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => { }) + ); - await train.Voltage.SetupNotificationAsync(train.Voltage.ModeIndexVoltageS, true); + using var d1 = train.Voltage.VoltageSObservable.Subscribe(x => Log.LogWarning($"Voltage: {x.Pct}% / {x.SI}")); + using var d2 = train.Motor.OnSecondsObservable.Subscribe(x => Log.LogWarning($"Seconds: {x}")); + using var d3 = train.Speedometer.SpeedObservable.Subscribe(x => Log.LogWarning($"Speed: {x.Pct}% / {x.SI}")); + using var d4 = train.Speedometer.CountObservable.Subscribe(x => Log.LogWarning($"Count: {x}")); + using var d5 = train.ColorSensor.ColorObservable.Subscribe(x => Log.LogWarning($"Color: {x}")); + using var d6 = train.ColorSensor.ColorTagObservable.Subscribe(x => Log.LogWarning($"Color Tag: {x}")); // does not work + using var d7 = train.ColorSensor.ReflectionObservable.Subscribe(x => Log.LogWarning($"Reflection: {x}")); + using var d8 = train.ColorSensor.RgbObservable.Subscribe(x => Log.LogWarning($"RGB {x.red}/{x.green}/{x.blue}")); - // Motor: motor can either be queried for seconds active OR be instructed to run - //await train.Motor.SetupNotificationAsync(train.Motor.ModeIndexOnSec, false); + await train.Voltage.SetupNotificationAsync(train.Voltage.ModeIndexVoltageS, true); - await train.Speedometer.TryLockDeviceForCombinedModeNotificationSetupAsync(train.Speedometer.ModeIndexSpeed, train.Speedometer.ModeIndexCount); - await train.Speedometer.SetupNotificationAsync(train.Speedometer.ModeIndexSpeed, true, deltaInterval: 1); - await train.Speedometer.SetupNotificationAsync(train.Speedometer.ModeIndexCount, true, deltaInterval: 1); - await train.Speedometer.UnlockFromCombinedModeNotificationSetupAsync(true); + // Motor: motor can either be queried for seconds active OR be instructed to run + //await train.Motor.SetupNotificationAsync(train.Motor.ModeIndexOnSec, false); - // ColorSensor: either this combination - // await train.ColorSensor.TryLockDeviceForCombinedModeNotificationSetupAsync(train.ColorSensor.ModeIndexColor, train.ColorSensor.ModeIndexReflection, train.ColorSensor.ModeIndexRgb); - // await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexColor, true, deltaInterval: 1); - // await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexReflection, true, deltaInterval: 1); - // await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexRgb, true, deltaInterval: 1); - // await train.ColorSensor.UnlockFromCombinedModeNotificationSetupAsync(true); + await train.Speedometer.TryLockDeviceForCombinedModeNotificationSetupAsync(train.Speedometer.ModeIndexSpeed, train.Speedometer.ModeIndexCount); + await train.Speedometer.SetupNotificationAsync(train.Speedometer.ModeIndexSpeed, true, deltaInterval: 1); + await train.Speedometer.SetupNotificationAsync(train.Speedometer.ModeIndexCount, true, deltaInterval: 1); + await train.Speedometer.UnlockFromCombinedModeNotificationSetupAsync(true); - // ColorSensor: or standalone - await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexColorTag, true, deltaInterval: 1); + // ColorSensor: either this combination + // await train.ColorSensor.TryLockDeviceForCombinedModeNotificationSetupAsync(train.ColorSensor.ModeIndexColor, train.ColorSensor.ModeIndexReflection, train.ColorSensor.ModeIndexRgb); + // await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexColor, true, deltaInterval: 1); + // await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexReflection, true, deltaInterval: 1); + // await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexRgb, true, deltaInterval: 1); + // await train.ColorSensor.UnlockFromCombinedModeNotificationSetupAsync(true); - await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.Horn); - await train.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red); - await Task.Delay(1_000); - await train.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Yellow); - await Task.Delay(1_000); - await train.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Green); - await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.StationDeparture); + // ColorSensor: or standalone + await train.ColorSensor.SetupNotificationAsync(train.ColorSensor.ModeIndexColorTag, true, deltaInterval: 1); - await train.Motor.StartPowerAsync(40); - await Task.Delay(3_000); - await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.Steam); - await train.Motor.StartPowerAsync(-40); - await Task.Delay(3_000); - await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.Brake); - await train.Motor.StopByFloatAsync(); - await Task.Delay(1_000); - await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.WaterRefill); + await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.Horn); + await train.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red); + await Task.Delay(1_000); + await train.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Yellow); + await Task.Delay(1_000); + await train.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Green); + await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.StationDeparture); - await Task.Delay(1_000); + await train.Motor.StartPowerAsync(40); + await Task.Delay(3_000); + await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.Steam); + await train.Motor.StartPowerAsync(-40); + await Task.Delay(3_000); + await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.Brake); + await train.Motor.StopByFloatAsync(); + await Task.Delay(1_000); + await train.Speaker.PlaySoundAsync(DuploTrainBaseSound.WaterRefill); - await train.SwitchOffAsync(); - } + await Task.Delay(1_000); + + await train.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleDynamicDevice.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleDynamicDevice.cs index 7042137..b3b786c 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleDynamicDevice.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleDynamicDevice.cs @@ -30,47 +30,46 @@ public override void Configure(IServiceCollection services) public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - // deployment model verification with unknown devices - await technicMediumHub.VerifyDeploymentModelAsync(mb => mb - .AddAnyHub(hubBuilder => hubBuilder - .AddAnyDevice(0)) - ); + using var technicMediumHub = Host.FindByType(); - var dynamicDeviceWhichIsAMotor = technicMediumHub.Port(0).GetDevice(); + // deployment model verification with unknown devices + await technicMediumHub.VerifyDeploymentModelAsync(mb => mb + .AddAnyHub(hubBuilder => hubBuilder + .AddAnyDevice(0)) + ); - // or also direct from a protocol - //var dynamicDeviceWhichIsAMotor = new DynamicDevice(technicMediumHub.Protocol, technicMediumHub.HubId, 0); + var dynamicDeviceWhichIsAMotor = technicMediumHub.Port(0).GetDevice(); - // discover the unknown device using the LWP - await dynamicDeviceWhichIsAMotor.DiscoverAsync(); - Log.LogInformation("Discovery completed"); + // or also direct from a protocol + //var dynamicDeviceWhichIsAMotor = new DynamicDevice(technicMediumHub.Protocol, technicMediumHub.HubId, 0); - // use combined mode values from the device - await dynamicDeviceWhichIsAMotor.TryLockDeviceForCombinedModeNotificationSetupAsync(2, 3); - await dynamicDeviceWhichIsAMotor.SetupNotificationAsync(2, true); - await dynamicDeviceWhichIsAMotor.SetupNotificationAsync(3, true); - await dynamicDeviceWhichIsAMotor.UnlockFromCombinedModeNotificationSetupAsync(true); + // discover the unknown device using the LWP + await dynamicDeviceWhichIsAMotor.DiscoverAsync(); + Log.LogInformation("Discovery completed"); - // get the individual modes for input and output - var powerMode = dynamicDeviceWhichIsAMotor.SingleValueMode(0); - var posMode = dynamicDeviceWhichIsAMotor.SingleValueMode(2); - var aposMode = dynamicDeviceWhichIsAMotor.SingleValueMode(3); + // use combined mode values from the device + await dynamicDeviceWhichIsAMotor.TryLockDeviceForCombinedModeNotificationSetupAsync(2, 3); + await dynamicDeviceWhichIsAMotor.SetupNotificationAsync(2, true); + await dynamicDeviceWhichIsAMotor.SetupNotificationAsync(3, true); + await dynamicDeviceWhichIsAMotor.UnlockFromCombinedModeNotificationSetupAsync(true); - // use their observables to report values - using var disposable = posMode.Observable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}")); - using var disposable2 = aposMode.Observable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}")); + // get the individual modes for input and output + var powerMode = dynamicDeviceWhichIsAMotor.SingleValueMode(0); + var posMode = dynamicDeviceWhichIsAMotor.SingleValueMode(2); + var aposMode = dynamicDeviceWhichIsAMotor.SingleValueMode(3); - // or even write to them - await powerMode.WriteDirectModeDataAsync(0x64); // That is StartPower on a motor - await Task.Delay(2_000); - await powerMode.WriteDirectModeDataAsync(0x00); // That is Stop on a motor + // use their observables to report values + using var disposable = posMode.Observable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}")); + using var disposable2 = aposMode.Observable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}")); - await Task.Delay(10_000); + // or even write to them + await powerMode.WriteDirectModeDataAsync(0x64); // That is StartPower on a motor + await Task.Delay(2_000); + await powerMode.WriteDirectModeDataAsync(0x00); // That is Stop on a motor - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(10_000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleHubActions.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleHubActions.cs index 1c38f1b..620af5c 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleHubActions.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleHubActions.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -8,22 +7,21 @@ public class ExampleHubActions : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0xff); + using var technicMediumHub = Host.FindByType(); - await Task.Delay(2000); + await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0xff); - await technicMediumHub.ActivateBusyIndicatorAsync(); // technic medium hub => blinking with color from above + await Task.Delay(2000); - await Task.Delay(5000); + await technicMediumHub.ActivateBusyIndicatorAsync(); // technic medium hub => blinking with color from above - await technicMediumHub.ResetBusyIndicatorAsync(); // stop blinking + await Task.Delay(5000); - await Task.Delay(2000); + await technicMediumHub.ResetBusyIndicatorAsync(); // stop blinking - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(2000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleHubAlert.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleHubAlert.cs index f17d9fa..b403407 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleHubAlert.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleHubAlert.cs @@ -8,18 +8,17 @@ public class ExampleHubAlert : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - technicMediumHub.AlertObservable.Subscribe(x => Console.WriteLine($"Alert: {x}")); + using var technicMediumHub = Host.FindByType(); - await technicMediumHub.EnableAlertNotificationAsync(HubAlert.LowSignalStrength); + technicMediumHub.AlertObservable.Subscribe(x => Console.WriteLine($"Alert: {x}")); - await Task.Delay(60_000); // run + await technicMediumHub.EnableAlertNotificationAsync(HubAlert.LowSignalStrength); - await technicMediumHub.DisableAlertNotification(HubAlert.LowSignalStrength); + await Task.Delay(60_000); // run - await technicMediumHub.SwitchOffAsync(); - } + await technicMediumHub.DisableAlertNotification(HubAlert.LowSignalStrength); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleHubPropertyObserving.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleHubPropertyObserving.cs index c3b4cfd..5c5d0ac 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleHubPropertyObserving.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleHubPropertyObserving.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SharpBrick.PoweredUp; @@ -10,26 +9,25 @@ public class ExampleHubPropertyObserving : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - using var d1 = technicMediumHub.ButtonObservable.Subscribe(x => Log.LogInformation($"Buttom: {x}")); - technicMediumHub.PropertyChanged += (sender, ea) => { Log.LogInformation($"Change on Property {ea.PropertyName}"); }; + using var technicMediumHub = Host.FindByType(); - // optionally: trigger explicit request (like done during initialization) - await technicMediumHub.RequestHubPropertySingleUpdate(HubProperty.Button); + using var d1 = technicMediumHub.ButtonObservable.Subscribe(x => Log.LogInformation($"Buttom: {x}")); + technicMediumHub.PropertyChanged += (sender, ea) => { Log.LogInformation($"Change on Property {ea.PropertyName}"); }; - // and then observe it - await technicMediumHub.SetupHubPropertyNotificationAsync(HubProperty.Button, true); + // optionally: trigger explicit request (like done during initialization) + await technicMediumHub.RequestHubPropertySingleUpdate(HubProperty.Button); - await Task.Delay(5_000); + // and then observe it + await technicMediumHub.SetupHubPropertyNotificationAsync(HubProperty.Button, true); - await technicMediumHub.SetupHubPropertyNotificationAsync(HubProperty.Button, false); - Log.LogInformation("Button no longer observed"); + await Task.Delay(5_000); - await Task.Delay(5_000); + await technicMediumHub.SetupHubPropertyNotificationAsync(HubProperty.Button, false); + Log.LogInformation("Button no longer observed"); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(5_000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMarioAccelerometer.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMarioAccelerometer.cs index 37a0238..2feb319 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMarioAccelerometer.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMarioAccelerometer.cs @@ -9,22 +9,21 @@ public class ExampleMarioAccelerometer : BaseExample { public override async Task ExecuteAsync() { - using (var mario = Host.FindByType()) - { - await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => { }) - ); + using var mario = Host.FindByType(); - var d1 = mario.Accelerometer.GestureObservable.Subscribe(x => Log.LogWarning($"Gesture: {x[0]}/{x[1]}")); + await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => { }) + ); - await mario.Accelerometer.SetupNotificationAsync(mario.Accelerometer.ModeIndexGesture, true); + var d1 = mario.Accelerometer.GestureObservable.Subscribe(x => Log.LogWarning($"Gesture: {x[0]}/{x[1]}")); - await Task.Delay(20_000); + await mario.Accelerometer.SetupNotificationAsync(mario.Accelerometer.ModeIndexGesture, true); - d1.Dispose(); + await Task.Delay(20_000); - await mario.SwitchOffAsync(); - } + d1.Dispose(); + + await mario.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMarioBarcode.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMarioBarcode.cs index 49a2281..fba72df 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMarioBarcode.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMarioBarcode.cs @@ -9,26 +9,25 @@ public class ExampleMarioBarcode : BaseExample { public override async Task ExecuteAsync() { - using (var mario = Host.FindByType()) - { - await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => { }) - ); + using var mario = Host.FindByType(); - // for a normal scenario, a combined mode would not be needed. The tag sensor is able to detect brick colors AND the barcode on its own. The RGB scanner is neither very accurate and is scaled strangely. - var tagSensor = mario.TagSensor; - await tagSensor.SetupNotificationAsync(tagSensor.ModeIndexTag, true); + await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => { }) + ); - var d1 = tagSensor.BarcodeObservable.Subscribe(x => Log.LogWarning($"Barcode: {x}")); - var d2 = tagSensor.ColorNoObservable.Subscribe(x => Log.LogWarning($"Color No: {x}")); + // for a normal scenario, a combined mode would not be needed. The tag sensor is able to detect brick colors AND the barcode on its own. The RGB scanner is neither very accurate and is scaled strangely. + var tagSensor = mario.TagSensor; + await tagSensor.SetupNotificationAsync(tagSensor.ModeIndexTag, true); - await Task.Delay(20_000); + var d1 = tagSensor.BarcodeObservable.Subscribe(x => Log.LogWarning($"Barcode: {x}")); + var d2 = tagSensor.ColorNoObservable.Subscribe(x => Log.LogWarning($"Color No: {x}")); - d1.Dispose(); - d2.Dispose(); + await Task.Delay(20_000); - await mario.SwitchOffAsync(); - } + d1.Dispose(); + d2.Dispose(); + + await mario.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMarioPants.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMarioPants.cs index 78f08aa..0d9d88d 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMarioPants.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMarioPants.cs @@ -9,24 +9,23 @@ public class ExampleMarioPants : BaseExample { public override async Task ExecuteAsync() { - using (var mario = Host.FindByType()) - { - await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => { }) - ); + using var mario = Host.FindByType(); - var pants = mario.Pants; + await mario.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => { }) + ); - var d1 = pants.PantsObservable.Subscribe(x => Log.LogWarning($"Pants: {x}")); + var pants = mario.Pants; - await pants.SetupNotificationAsync(pants.ModeIndexPants, true); + var d1 = pants.PantsObservable.Subscribe(x => Log.LogWarning($"Pants: {x}")); - await Task.Delay(20_000); + await pants.SetupNotificationAsync(pants.ModeIndexPants, true); - d1.Dispose(); + await Task.Delay(20_000); - await mario.SwitchOffAsync(); - } + d1.Dispose(); + + await mario.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMixedBag.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMixedBag.cs index a699929..35e4541 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMixedBag.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMixedBag.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; using static SharpBrick.PoweredUp.Directions; @@ -12,36 +11,35 @@ public class ExampleMixedBag : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) + using var technicMediumHub = Host.FindByType(); + + await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(technicMediumHub.A) + ) + ); + + await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); + + technicMediumHub.Current.CurrentLObservable.Subscribe(v => { - await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(technicMediumHub.A) - ) - ); - - await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); - - technicMediumHub.Current.CurrentLObservable.Subscribe(v => - { - Log.LogWarning($"Current: {v.Pct}% {v.SI}mA / {technicMediumHub.Current.CurrentL}mA"); - }); - - await technicMediumHub.Current.SetupNotificationAsync(0x00, true, 1); - - // simple motor control - var motor = technicMediumHub.A.GetDevice(); - - await motor.GotoPositionAsync(CW * 45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(2000); - await motor.GotoPositionAsync(CCW * 45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(2000); - await motor.StartPowerAsync(100); - await Task.Delay(5000); - await motor.StartPowerAsync(0); - - await technicMediumHub.SwitchOffAsync(); - } + Log.LogWarning($"Current: {v.Pct}% {v.SI}mA / {technicMediumHub.Current.CurrentL}mA"); + }); + + await technicMediumHub.Current.SetupNotificationAsync(0x00, true, 1); + + // simple motor control + var motor = technicMediumHub.A.GetDevice(); + + await motor.GotoPositionAsync(CW * 45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(2000); + await motor.GotoPositionAsync(CCW * 45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(2000); + await motor.StartPowerAsync(100); + await Task.Delay(5000); + await motor.StartPowerAsync(0); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorControl.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorControl.cs index 3cad526..4ad6903 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorControl.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorControl.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -8,40 +7,39 @@ public class ExampleMotorControl : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(technicMediumHub.A) - ) - ); + using var technicMediumHub = Host.FindByType(); - var motor = technicMediumHub.A.GetDevice(); + await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(technicMediumHub.A) + ) + ); - await motor.SetAccelerationTimeAsync(3000); - await motor.SetDecelerationTimeAsync(1000); - await motor.StartSpeedForTimeAsync(6000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); + var motor = technicMediumHub.A.GetDevice(); - await Task.Delay(10_000); + await motor.SetAccelerationTimeAsync(3000); + await motor.SetDecelerationTimeAsync(1000); + await motor.StartSpeedForTimeAsync(6000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); - await motor.StartSpeedForDegreesAsync(180, -10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(10_000); - await Task.Delay(10_000); + await motor.StartSpeedForDegreesAsync(180, -10, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await motor.StartSpeedAsync(100, 90, SpeedProfiles.None); - await Task.Delay(2000); - await motor.StartSpeedAsync(-100, 90, SpeedProfiles.None); - await Task.Delay(2000); - await motor.StartSpeedAsync(0, 90, SpeedProfiles.None); + await Task.Delay(10_000); - await Task.Delay(10_000); + await motor.StartSpeedAsync(100, 90, SpeedProfiles.None); + await Task.Delay(2000); + await motor.StartSpeedAsync(-100, 90, SpeedProfiles.None); + await Task.Delay(2000); + await motor.StartSpeedAsync(0, 90, SpeedProfiles.None); - await motor.GotoPositionAsync(45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(2000); - await motor.GotoPositionAsync(-45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(10_000); - await technicMediumHub.SwitchOffAsync(); - } + await motor.GotoPositionAsync(45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(2000); + await motor.GotoPositionAsync(-45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputAbsolutePosition.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputAbsolutePosition.cs index 90f4702..646e78e 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputAbsolutePosition.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputAbsolutePosition.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,71 +10,70 @@ public class ExampleMotorInputAbsolutePosition : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(technicMediumHub.A) - ) - ); - - var motor = technicMediumHub.A.GetDevice(); - - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red); - - // align physical and reset position to it. - await motor.GotoRealZeroAsync(); - - await Task.Delay(2000); - - await motor.SetZeroAsync(); - - await motor.TryLockDeviceForCombinedModeNotificationSetupAsync(motor.ModeIndexAbsolutePosition, motor.ModeIndexPosition); - await motor.SetupNotificationAsync(motor.ModeIndexAbsolutePosition, true); - await motor.SetupNotificationAsync(motor.ModeIndexPosition, true); - await motor.UnlockFromCombinedModeNotificationSetupAsync(true); - - using var disposable = motor.AbsolutePositionObservable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}")); - using var disposable2 = motor.PositionObservable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}")); - motor.PropertyChanged += (sender, ea) => { Log.LogInformation($"Change on Property {ea.PropertyName}"); }; - - // relative movement from current positions - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Pink); - - await motor.StartSpeedForDegreesAsync(30, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - await motor.StartSpeedForDegreesAsync(30, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - await motor.StartSpeedForDegreesAsync(30, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - - // absolute movement to relative to zero point (SetZeroAsync or initial boot position) - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Orange); - - await motor.GotoPositionAsync(0, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - await motor.GotoPositionAsync(90, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - await motor.GotoPositionAsync(180, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - await motor.GotoPositionAsync(-90, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await Task.Delay(1000); - - await motor.GotoRealZeroAsync(); - await Task.Delay(2000); - - // time to turn the axis by hand to see notification feedback. Reformat input as GotoRealZero destroys them. - await motor.TryLockDeviceForCombinedModeNotificationSetupAsync(motor.ModeIndexAbsolutePosition, motor.ModeIndexPosition); - await motor.SetupNotificationAsync(motor.ModeIndexAbsolutePosition, true); - await motor.SetupNotificationAsync(motor.ModeIndexPosition, true); - await motor.UnlockFromCombinedModeNotificationSetupAsync(true); - - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Green); - await motor.StopByFloatAsync(); - await Task.Delay(10_000); - - await technicMediumHub.SwitchOffAsync(); - } + using var technicMediumHub = Host.FindByType(); + + await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(technicMediumHub.A) + ) + ); + + var motor = technicMediumHub.A.GetDevice(); + + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red); + + // align physical and reset position to it. + await motor.GotoRealZeroAsync(); + + await Task.Delay(2000); + + await motor.SetZeroAsync(); + + await motor.TryLockDeviceForCombinedModeNotificationSetupAsync(motor.ModeIndexAbsolutePosition, motor.ModeIndexPosition); + await motor.SetupNotificationAsync(motor.ModeIndexAbsolutePosition, true); + await motor.SetupNotificationAsync(motor.ModeIndexPosition, true); + await motor.UnlockFromCombinedModeNotificationSetupAsync(true); + + using var disposable = motor.AbsolutePositionObservable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}")); + using var disposable2 = motor.PositionObservable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}")); + motor.PropertyChanged += (sender, ea) => { Log.LogInformation($"Change on Property {ea.PropertyName}"); }; + + // relative movement from current positions + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Pink); + + await motor.StartSpeedForDegreesAsync(30, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + await motor.StartSpeedForDegreesAsync(30, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + await motor.StartSpeedForDegreesAsync(30, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + + // absolute movement to relative to zero point (SetZeroAsync or initial boot position) + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Orange); + + await motor.GotoPositionAsync(0, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + await motor.GotoPositionAsync(90, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + await motor.GotoPositionAsync(180, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + await motor.GotoPositionAsync(-90, 20, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(1000); + + await motor.GotoRealZeroAsync(); + await Task.Delay(2000); + + // time to turn the axis by hand to see notification feedback. Reformat input as GotoRealZero destroys them. + await motor.TryLockDeviceForCombinedModeNotificationSetupAsync(motor.ModeIndexAbsolutePosition, motor.ModeIndexPosition); + await motor.SetupNotificationAsync(motor.ModeIndexAbsolutePosition, true); + await motor.SetupNotificationAsync(motor.ModeIndexPosition, true); + await motor.UnlockFromCombinedModeNotificationSetupAsync(true); + + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Green); + await motor.StopByFloatAsync(); + await Task.Delay(10_000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputCombinedMode.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputCombinedMode.cs index 60673ae..bb89f6a 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputCombinedMode.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorInputCombinedMode.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,46 +10,45 @@ public class ExampleMotorInputCombinedMode : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(technicMediumHub.A) - ) - ); + using var technicMediumHub = Host.FindByType(); - var motor = technicMediumHub.A.GetDevice(); + await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(technicMediumHub.A) + ) + ); - await motor.TryLockDeviceForCombinedModeNotificationSetupAsync(motor.ModeIndexSpeed, motor.ModeIndexPosition, motor.ModeIndexAbsolutePosition); + var motor = technicMediumHub.A.GetDevice(); - await motor.SetupNotificationAsync(motor.ModeIndexSpeed, true); - await motor.SetupNotificationAsync(motor.ModeIndexPosition, true); - await motor.SetupNotificationAsync(motor.ModeIndexAbsolutePosition, true); + await motor.TryLockDeviceForCombinedModeNotificationSetupAsync(motor.ModeIndexSpeed, motor.ModeIndexPosition, motor.ModeIndexAbsolutePosition); - await motor.UnlockFromCombinedModeNotificationSetupAsync(true); + await motor.SetupNotificationAsync(motor.ModeIndexSpeed, true); + await motor.SetupNotificationAsync(motor.ModeIndexPosition, true); + await motor.SetupNotificationAsync(motor.ModeIndexAbsolutePosition, true); - await motor.StartPowerAsync(80); + await motor.UnlockFromCombinedModeNotificationSetupAsync(true); - var disposable1 = motor.SpeedObservable.Subscribe(x => Log.LogWarning($"Speed: {x.SI} / {x.Pct}")); + await motor.StartPowerAsync(80); - var disposable2 = motor.PositionObservable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}")); + var disposable1 = motor.SpeedObservable.Subscribe(x => Log.LogWarning($"Speed: {x.SI} / {x.Pct}")); - var disposable3 = motor.AbsolutePositionObservable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}")); + var disposable2 = motor.PositionObservable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}")); - await Task.Delay(2000); + var disposable3 = motor.AbsolutePositionObservable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}")); - Log.LogWarning($"Position: {motor.AbsolutePosition}"); + await Task.Delay(2000); - await Task.Delay(2000); + Log.LogWarning($"Position: {motor.AbsolutePosition}"); - await motor.StartPowerAsync(0); + await Task.Delay(2000); - disposable1.Dispose(); - disposable2.Dispose(); - disposable3.Dispose(); + await motor.StartPowerAsync(0); - await technicMediumHub.SwitchOffAsync(); - } + disposable1.Dispose(); + disposable2.Dispose(); + disposable3.Dispose(); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorVirtualPort.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorVirtualPort.cs index b6159d2..0c14b58 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMotorVirtualPort.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMotorVirtualPort.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -8,40 +7,39 @@ public class ExampleMotorVirtualPort : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(0) - .AddDevice(2) - ) - ); + using var technicMediumHub = Host.FindByType(); - var virtualPort = await technicMediumHub.CreateVirtualPortAsync(0, 2); + await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(0) + .AddDevice(2) + ) + ); - var motorsOnVirtualPort = virtualPort.GetDevice(); + var virtualPort = await technicMediumHub.CreateVirtualPortAsync(0, 2); - await motorsOnVirtualPort.GotoPositionAsync(90, -45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + var motorsOnVirtualPort = virtualPort.GetDevice(); - await Task.Delay(3000); + await motorsOnVirtualPort.GotoPositionAsync(90, -45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await motorsOnVirtualPort.StartSpeedAsync(100, 50, 100, SpeedProfiles.None); + await Task.Delay(3000); - await Task.Delay(2000); + await motorsOnVirtualPort.StartSpeedAsync(100, 50, 100, SpeedProfiles.None); - await motorsOnVirtualPort.StartPowerAsync(10, 100); + await Task.Delay(2000); - await Task.Delay(3000); + await motorsOnVirtualPort.StartPowerAsync(10, 100); - await motorsOnVirtualPort.StartPowerAsync(0, 0); + await Task.Delay(3000); - await Task.Delay(1000); + await motorsOnVirtualPort.StartPowerAsync(0, 0); + await Task.Delay(1000); - await technicMediumHub.CloseVirtualPortAsync(virtualPort.PortId); - await technicMediumHub.SwitchOffAsync(); - } + await technicMediumHub.CloseVirtualPortAsync(virtualPort.PortId); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubColors.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubColors.cs index 5a7f9ee..7f10d44 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubColors.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubColors.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -8,18 +7,17 @@ public class ExampleMoveHubColors : BaseExample { public override async Task ExecuteAsync() { - using (var moveHub = Host.FindByType()) - { - await moveHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); + using var moveHub = Host.FindByType(); - await Task.Delay(2000); - - await moveHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); + await moveHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00); - await Task.Delay(2000); + await Task.Delay(2000); - await moveHub.SwitchOffAsync(); - } + await moveHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00); + + await Task.Delay(2000); + + await moveHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubExternalMediumLinearMotorControl.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubExternalMediumLinearMotorControl.cs index 3b6bf25..acee44a 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubExternalMediumLinearMotorControl.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubExternalMediumLinearMotorControl.cs @@ -7,19 +7,18 @@ public class ExampleMoveHubExternalMediumLinearMotorControl : BaseExample { public override async Task ExecuteAsync() { - using (var moveHub = Host.FindByType()) - { - // This is if you have a linear motor plugged into port D (ie. R2D2) - var externalMotor = moveHub.D.GetDevice(); + using var moveHub = Host.FindByType(); - await externalMotor.SetAccelerationTimeAsync(3000); - await externalMotor.SetDecelerationTimeAsync(1000); - await externalMotor.StartSpeedForTimeAsync(2000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); + // This is if you have a linear motor plugged into port D (ie. R2D2) + var externalMotor = moveHub.D.GetDevice(); - await Task.Delay(50000); + await externalMotor.SetAccelerationTimeAsync(3000); + await externalMotor.SetDecelerationTimeAsync(1000); + await externalMotor.StartSpeedForTimeAsync(2000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); - await moveHub.SwitchOffAsync(); - } + await Task.Delay(50000); + + await moveHub.SwitchOffAsync(); } } } diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubInternalTachoMotorControl.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubInternalTachoMotorControl.cs index c1c5e1e..821f6b5 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubInternalTachoMotorControl.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubInternalTachoMotorControl.cs @@ -7,29 +7,28 @@ public class ExampleMoveHubInternalTachoMotorControl : BaseExample { public override async Task ExecuteAsync() { - using (var moveHub = Host.FindByType()) - { - var internalMotor = moveHub.MotorAtAB; - await internalMotor.StartSpeedAsync(50, 100); - await internalMotor.StartSpeedForTimeAsync(2000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); + using var moveHub = Host.FindByType(); - await Task.Delay(3000); - await internalMotor.StopByBrakeAsync(); + var internalMotor = moveHub.MotorAtAB; + await internalMotor.StartSpeedAsync(50, 100); + await internalMotor.StartSpeedForTimeAsync(2000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); - var leftMotor = moveHub.LeftMotorAtB; - var rightMotor = moveHub.RightMotorAtA; - await leftMotor.StartSpeedAsync(10, 100); - await leftMotor.StartSpeedForTimeAsync(1000, 10, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); - await rightMotor.StartSpeedAsync(90, 100); - await rightMotor.StartSpeedForTimeAsync(1000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); + await Task.Delay(3000); + await internalMotor.StopByBrakeAsync(); - await Task.Delay(2000); + var leftMotor = moveHub.LeftMotorAtB; + var rightMotor = moveHub.RightMotorAtA; + await leftMotor.StartSpeedAsync(10, 100); + await leftMotor.StartSpeedForTimeAsync(1000, 10, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); + await rightMotor.StartSpeedAsync(90, 100); + await rightMotor.StartSpeedForTimeAsync(1000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); - await leftMotor.StopByBrakeAsync(); - await rightMotor.StopByBrakeAsync(); + await Task.Delay(2000); - await moveHub.SwitchOffAsync(); - } + await leftMotor.StopByBrakeAsync(); + await rightMotor.StopByBrakeAsync(); + + await moveHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubTiltSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubTiltSensor.cs index 5c5ded4..a0d43dc 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubTiltSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleMoveHubTiltSensor.cs @@ -9,47 +9,46 @@ public class ExampleMoveHubTiltSensor : BaseExample { public override async Task ExecuteAsync() { - using (var moveHub = Host.FindByType()) - { - var device = moveHub.TiltSensor; - await device.TiltConfigOrientationAsync(TiltConfigOrientation.Front); + using var moveHub = Host.FindByType(); - // Note that you can only have 1 notification running at a time + var device = moveHub.TiltSensor; + await device.TiltConfigOrientationAsync(TiltConfigOrientation.Front); - await device.SetupNotificationAsync(device.ModeIndexTwoAxisFull, true, 1); - using var twoAxisFullSubscription = device.TwoAxisFullObservable.Subscribe(x => Log.LogWarning($"Two Axis Values - Roll: {x.roll}, Pitch: {x.pitch}")); + // Note that you can only have 1 notification running at a time - Console.WriteLine("Press any key to continue"); - Console.ReadKey(); + await device.SetupNotificationAsync(device.ModeIndexTwoAxisFull, true, 1); + using var twoAxisFullSubscription = device.TwoAxisFullObservable.Subscribe(x => Log.LogWarning($"Two Axis Values - Roll: {x.roll}, Pitch: {x.pitch}")); - await device.SetupNotificationAsync(device.ModeIndexTwoAxisState, true, 1); - using var twoAxisStateSubscription = device.TwoAxisStateObservable.Subscribe(x => Log.LogWarning($"Two Axis State: {x}")); + Console.WriteLine("Press any key to continue"); + Console.ReadKey(); - Console.WriteLine("Press any key to continue"); - Console.ReadKey(); + await device.SetupNotificationAsync(device.ModeIndexTwoAxisState, true, 1); + using var twoAxisStateSubscription = device.TwoAxisStateObservable.Subscribe(x => Log.LogWarning($"Two Axis State: {x}")); - await device.SetupNotificationAsync(device.ModeIndexThreeAxisState, true, 1); - using var threeAxisStateSubscription = device.ThreeAxisStateObservable.Subscribe(x => Log.LogWarning($"Three Axis State: {x}")); + Console.WriteLine("Press any key to continue"); + Console.ReadKey(); - Console.WriteLine("Press any key to continue"); - Console.ReadKey(); + await device.SetupNotificationAsync(device.ModeIndexThreeAxisState, true, 1); + using var threeAxisStateSubscription = device.ThreeAxisStateObservable.Subscribe(x => Log.LogWarning($"Three Axis State: {x}")); - await device.SetupNotificationAsync(device.ModeIndexThreeAxisFull, true, 1); - using var threeAxisFullSubscription = device.ThreeAxisFullObservable.Subscribe(x => Log.LogWarning($"Three Axis Values - Roll: {x.roll}, Pitch: {x.pitch}, Yaw: {x.yaw}")); + Console.WriteLine("Press any key to continue"); + Console.ReadKey(); - Console.WriteLine("Press any key to continue"); - Console.ReadKey(); + await device.SetupNotificationAsync(device.ModeIndexThreeAxisFull, true, 1); + using var threeAxisFullSubscription = device.ThreeAxisFullObservable.Subscribe(x => Log.LogWarning($"Three Axis Values - Roll: {x.roll}, Pitch: {x.pitch}, Yaw: {x.yaw}")); - // This configures a minimum threshold for an impact to be registered (should be a light tap) and subscribes to the count of impacts - await device.TiltConfigImpactAsync(10, 1270); - await device.SetupNotificationAsync(device.ModeIndexImpacts, true, deltaInterval: 1); - using var impactSubscription = device.ImpactsObservable.Subscribe(x => Log.LogWarning($"Impact Count: {x.SI}")); + Console.WriteLine("Press any key to continue"); + Console.ReadKey(); - Console.WriteLine("Press any key to continue"); - Console.ReadKey(); + // This configures a minimum threshold for an impact to be registered (should be a light tap) and subscribes to the count of impacts + await device.TiltConfigImpactAsync(10, 1270); + await device.SetupNotificationAsync(device.ModeIndexImpacts, true, deltaInterval: 1); + using var impactSubscription = device.ImpactsObservable.Subscribe(x => Log.LogWarning($"Impact Count: {x.SI}")); - await moveHub.SwitchOffAsync(); - } + Console.WriteLine("Press any key to continue"); + Console.ReadKey(); + + await moveHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleRampUp.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleRampUp.cs index 0be2091..a6806a8 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleRampUp.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleRampUp.cs @@ -11,40 +11,39 @@ public class ExampleRampUp : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var stopWatch = new Stopwatch(); + using var technicMediumHub = Host.FindByType(); - var motor = technicMediumHub.A.GetDevice(); + var stopWatch = new Stopwatch(); - // ramp up with linear speed - var rampUp = ServiceProvider.GetService(); + var motor = technicMediumHub.A.GetDevice(); - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red); + // ramp up with linear speed + var rampUp = ServiceProvider.GetService(); - stopWatch.Start(); - await rampUp.ExecuteAsync(motor, 20, 100, 40, 10_000); - var redPhase = stopWatch.ElapsedMilliseconds; + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Red); - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Green); + stopWatch.Start(); + await rampUp.ExecuteAsync(motor, 20, 100, 40, 10_000); + var redPhase = stopWatch.ElapsedMilliseconds; - await Task.Delay(2_000); + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Green); - await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Orange); + await Task.Delay(2_000); - // ramp down with linear speed - var rampDown = ServiceProvider.GetService(); + await technicMediumHub.RgbLight.SetRgbColorNoAsync(PoweredUpColor.Orange); - var beforeOrangePhase = stopWatch.ElapsedMilliseconds; - await rampDown.ExecuteAsync(motor, 100, 0, 100, 20_000); - var orangePhase = stopWatch.ElapsedMilliseconds - beforeOrangePhase; - stopWatch.Stop(); + // ramp down with linear speed + var rampDown = ServiceProvider.GetService(); - await technicMediumHub.SwitchOffAsync(); + var beforeOrangePhase = stopWatch.ElapsedMilliseconds; + await rampDown.ExecuteAsync(motor, 100, 0, 100, 20_000); + var orangePhase = stopWatch.ElapsedMilliseconds - beforeOrangePhase; + stopWatch.Stop(); - // time delays (parameter) + 100s of BLE messages async/await ops - Log.LogInformation($"Red Phase: {redPhase}ms; Orange Phase: {orangePhase}ms"); - } + await technicMediumHub.SwitchOffAsync(); + + // time delays (parameter) + 100s of BLE messages async/await ops + Log.LogInformation($"Red Phase: {redPhase}ms; Orange Phase: {orangePhase}ms"); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlButton.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlButton.cs index 9247ed4..e0e4dd3 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlButton.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlButton.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,46 +10,45 @@ public class ExampleRemoteControlButton : BaseExample { public override async Task ExecuteAsync() { - using (var twoPortHandset = Host.FindByType()) - { - var device = twoPortHandset.A; + using var twoPortHandset = Host.FindByType(); - await device.SetupNotificationAsync(device.ModeIndexBitField, true, deltaInterval: 1); + var device = twoPortHandset.A; - await twoPortHandset.RgbLight.SetRgbColorsAsync(0xFF, 0x00, 0x00); + await device.SetupNotificationAsync(device.ModeIndexBitField, true, deltaInterval: 1); - Log.LogInformation("Press the '+' button on port A (left)"); + await twoPortHandset.RgbLight.SetRgbColorsAsync(0xFF, 0x00, 0x00); - await device.PlusObservable.Any(x => x); + Log.LogInformation("Press the '+' button on port A (left)"); - Log.LogInformation("Thanks! Now press the 'red' button on port A (left)"); + await device.PlusObservable.Any(x => x); - await device.RedObservable.Any(x => x); + Log.LogInformation("Thanks! Now press the 'red' button on port A (left)"); - Log.LogInformation("Thanks! Now press the '-' button on port A (left)"); + await device.RedObservable.Any(x => x); - await device.MinusObservable.Any(x => x); + Log.LogInformation("Thanks! Now press the '-' button on port A (left)"); - Log.LogInformation("Thanks! Now press the '+' and '-' buttons on port A (left) at the same time"); + await device.MinusObservable.Any(x => x); - await device.ButtonsObservable.Any(x => x.Minus && x.Plus); + Log.LogInformation("Thanks! Now press the '+' and '-' buttons on port A (left) at the same time"); - var disposable = device.ButtonsObservable.Subscribe(x => Log.LogWarning($"Buttons: {x.Plus} - {x.Stop} - {x.Minus}")); - var disposable2 = device.PlusObservable.Subscribe(x => Log.LogWarning($"Plus: {x}")); - var disposable3 = device.RedObservable.Subscribe(x => Log.LogWarning($"Red: {x}")); - var disposable4 = device.MinusObservable.Subscribe(x => Log.LogWarning($"Minus: {x}")); + await device.ButtonsObservable.Any(x => x.Minus && x.Plus); - Log.LogInformation("Thanks! You now have 20 seconds to press any button combinations"); + var disposable = device.ButtonsObservable.Subscribe(x => Log.LogWarning($"Buttons: {x.Plus} - {x.Stop} - {x.Minus}")); + var disposable2 = device.PlusObservable.Subscribe(x => Log.LogWarning($"Plus: {x}")); + var disposable3 = device.RedObservable.Subscribe(x => Log.LogWarning($"Red: {x}")); + var disposable4 = device.MinusObservable.Subscribe(x => Log.LogWarning($"Minus: {x}")); - await Task.Delay(20_000); + Log.LogInformation("Thanks! You now have 20 seconds to press any button combinations"); - disposable.Dispose(); - disposable2.Dispose(); - disposable3.Dispose(); - disposable4.Dispose(); + await Task.Delay(20_000); - await twoPortHandset.SwitchOffAsync(); - } + disposable.Dispose(); + disposable2.Dispose(); + disposable3.Dispose(); + disposable4.Dispose(); + + await twoPortHandset.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlRssi.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlRssi.cs index 915c453..8c478c6 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlRssi.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleRemoteControlRssi.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,24 +10,23 @@ public class ExampleRemoteControlRssi : BaseExample { public override async Task ExecuteAsync() { - using (var twoPortHandset = Host.FindByType()) - { - var device = twoPortHandset.RemoteControlRssi; + using var twoPortHandset = Host.FindByType(); - await device.SetupNotificationAsync(device.ModeIndexRssi, true, deltaInterval: 1); + var device = twoPortHandset.RemoteControlRssi; - var disposable = device.RssiObservable.Subscribe(x => Log.LogWarning($"RSSI: {x}")); + await device.SetupNotificationAsync(device.ModeIndexRssi, true, deltaInterval: 1); - await twoPortHandset.RgbLight.SetRgbColorsAsync(0x00, 0xFF, 0x00); + var disposable = device.RssiObservable.Subscribe(x => Log.LogWarning($"RSSI: {x}")); - Log.LogInformation("Watching RSSI changes for the next 20 seconds"); + await twoPortHandset.RgbLight.SetRgbColorsAsync(0x00, 0xFF, 0x00); - await Task.Delay(20_000); + Log.LogInformation("Watching RSSI changes for the next 20 seconds"); - disposable.Dispose(); + await Task.Delay(20_000); - await twoPortHandset.SwitchOffAsync(); - } + disposable.Dispose(); + + await twoPortHandset.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleSetHubProperty.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleSetHubProperty.cs index 782124d..a130d5c 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleSetHubProperty.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleSetHubProperty.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SharpBrick.PoweredUp; @@ -10,29 +9,27 @@ public class ExampleSetHubProperty : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - using var d1 = technicMediumHub.AdvertisementNameObservable.Subscribe(x => Log.LogInformation($"From Observable for AdvertisementName: {x}")); - using var d2 = technicMediumHub.PropertyChangedObservable.Subscribe(x => Log.LogInformation($"Property Changed: {x}")); + using var technicMediumHub = Host.FindByType(); + using var d1 = technicMediumHub.AdvertisementNameObservable.Subscribe(x => Log.LogInformation($"From Observable for AdvertisementName: {x}")); + using var d2 = technicMediumHub.PropertyChangedObservable.Subscribe(x => Log.LogInformation($"Property Changed: {x}")); - var originalName = technicMediumHub.AdvertisingName; + var originalName = technicMediumHub.AdvertisingName; - Log.LogInformation($"Original Name: {originalName}"); + Log.LogInformation($"Original Name: {originalName}"); - await technicMediumHub.SetAdvertisingNameAsync("Hello World"); + await technicMediumHub.SetAdvertisingNameAsync("Hello World"); - Log.LogInformation($"New Name is: {technicMediumHub.AdvertisingName}"); + Log.LogInformation($"New Name is: {technicMediumHub.AdvertisingName}"); - await technicMediumHub.ResetAdvertisingNameAsync(); + await technicMediumHub.ResetAdvertisingNameAsync(); - Log.LogInformation($"Resetted Name is: {technicMediumHub.AdvertisingName}"); + Log.LogInformation($"Resetted Name is: {technicMediumHub.AdvertisingName}"); - await technicMediumHub.SetAdvertisingNameAsync(originalName); + await technicMediumHub.SetAdvertisingNameAsync(originalName); - Log.LogInformation($"Name Cleanup to: {originalName}"); + Log.LogInformation($"Name Cleanup to: {originalName}"); - await technicMediumHub.SwitchOffAsync(); - } + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicColorSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicColorSensor.cs index 91d023b..1dd8215 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicColorSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicColorSensor.cs @@ -9,36 +9,35 @@ public class ExampleTechnicColorSensor : BaseExample { public override async Task ExecuteAsync() { - using (var hub = Host.FindByType()) - { - await hub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(hub.A) - ) - ); + using var hub = Host.FindByType(); - var technicColorSensor = hub.A.GetDevice(); + await hub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(hub.A) + ) + ); - var m1 = technicColorSensor.ColorObservable.Subscribe(x => Log.LogWarning($"Color: {x}")); - var m2 = technicColorSensor.ReflectionObservable.Subscribe(x => Log.LogWarning($"Reflection: {x}")); - var m3 = technicColorSensor.AmbientLightObservable.Subscribe(x => Log.LogWarning($"Ambient Light: {x}")); - var m6 = technicColorSensor.RgbObservable.Subscribe(x => Log.LogWarning($"RGB: {x.red}/{x.green}/{x.blue}/{x.fourthValue}")); - var m7 = technicColorSensor.HsvObservable.Subscribe(x => Log.LogWarning($"RGB: {x.hue}/{x.saturation}/{x.value}")); + var technicColorSensor = hub.A.GetDevice(); - await technicColorSensor.SetupNotificationAsync(technicColorSensor.ModeIndexColor, true); + var m1 = technicColorSensor.ColorObservable.Subscribe(x => Log.LogWarning($"Color: {x}")); + var m2 = technicColorSensor.ReflectionObservable.Subscribe(x => Log.LogWarning($"Reflection: {x}")); + var m3 = technicColorSensor.AmbientLightObservable.Subscribe(x => Log.LogWarning($"Ambient Light: {x}")); + var m6 = technicColorSensor.RgbObservable.Subscribe(x => Log.LogWarning($"RGB: {x.red}/{x.green}/{x.blue}/{x.fourthValue}")); + var m7 = technicColorSensor.HsvObservable.Subscribe(x => Log.LogWarning($"RGB: {x.hue}/{x.saturation}/{x.value}")); - await Task.Delay(20_000); + await technicColorSensor.SetupNotificationAsync(technicColorSensor.ModeIndexColor, true); - // set only subset of the lights - await technicColorSensor.SetSectorLightAsync(0, 0, 100); + await Task.Delay(20_000); + // set only subset of the lights + await technicColorSensor.SetSectorLightAsync(0, 0, 100); - //await technicColorSensor.SetRgbColors2Async(100, 0, 0); - await Task.Delay(5_000); + //await technicColorSensor.SetRgbColors2Async(100, 0, 0); - await hub.SwitchOffAsync(); - } + await Task.Delay(5_000); + + await hub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicDistanceSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicDistanceSensor.cs index 34749a8..4321867 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicDistanceSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicDistanceSensor.cs @@ -9,33 +9,32 @@ public class ExampleTechnicDistanceSensor : BaseExample { public override async Task ExecuteAsync() { - using (var hub = Host.FindByType()) - { - await hub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(hub.A)) - ); + using var hub = Host.FindByType(); - var technicDistanceSensor = hub.A.GetDevice(); + await hub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(hub.A)) + ); - // measure distances (only single subscription) - using var m1 = technicDistanceSensor.DistanceObservable.Subscribe(x => Log.LogWarning($"Distl: {x}")); - using var m2 = technicDistanceSensor.DistsObservable.Subscribe(x => Log.LogWarning($"Dists: {x}")); - using var m3 = technicDistanceSensor.SinglObservable.Subscribe(x => Log.LogWarning($"Singl: {x}")); + var technicDistanceSensor = hub.A.GetDevice(); - await technicDistanceSensor.SetupNotificationAsync(technicDistanceSensor.ModeIndexDistance, true); + // measure distances (only single subscription) + using var m1 = technicDistanceSensor.DistanceObservable.Subscribe(x => Log.LogWarning($"Distl: {x}")); + using var m2 = technicDistanceSensor.DistsObservable.Subscribe(x => Log.LogWarning($"Dists: {x}")); + using var m3 = technicDistanceSensor.SinglObservable.Subscribe(x => Log.LogWarning($"Singl: {x}")); - // play with the eye lights (0-100) - for (byte idx = 0; idx < 100; idx += 5) - { - await technicDistanceSensor.SetEyeLightAsync(0b0000_0000, idx, 0b0110_0100, idx); + await technicDistanceSensor.SetupNotificationAsync(technicDistanceSensor.ModeIndexDistance, true); - Log.LogWarning($"Brightness: {idx}"); - await Task.Delay(2_000); - } + // play with the eye lights (0-100) + for (byte idx = 0; idx < 100; idx += 5) + { + await technicDistanceSensor.SetEyeLightAsync(0b0000_0000, idx, 0b0110_0100, idx); - await hub.SwitchOffAsync(); + Log.LogWarning($"Brightness: {idx}"); + await Task.Delay(2_000); } + + await hub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumAngularMotorGrey.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumAngularMotorGrey.cs index 4f77eb4..89d95ce 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumAngularMotorGrey.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumAngularMotorGrey.cs @@ -1,10 +1,5 @@ -using System; -using System.Threading.Tasks; -using System.Reactive.Linq; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; +using System.Threading.Tasks; using SharpBrick.PoweredUp; -using SharpBrick.PoweredUp.Protocol.Messages; namespace Example { @@ -12,40 +7,39 @@ public class ExampleTechnicMediumAngularMotorGrey : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(technicMediumHub.A) - ) - ); + using var technicMediumHub = Host.FindByType(); - var motor = technicMediumHub.A.GetDevice(); + await technicMediumHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(technicMediumHub.A) + ) + ); - await motor.GotoPositionAsync(45, 50, 100); + var motor = technicMediumHub.A.GetDevice(); - await Task.Delay(2000); + await motor.GotoPositionAsync(45, 50, 100); - await motor.SetZeroAsync(); + await Task.Delay(2000); - await Task.Delay(2000); + await motor.SetZeroAsync(); - await motor.StartSpeedForDegreesAsync(90, 50, 100); + await Task.Delay(2000); - await Task.Delay(2000); + await motor.StartSpeedForDegreesAsync(90, 50, 100); - // align physical and reset position to it. - await motor.GotoPositionAsync(0, 50, 100); + await Task.Delay(2000); - await Task.Delay(2000); + // align physical and reset position to it. + await motor.GotoPositionAsync(0, 50, 100); - // does not reset back to marked position on device - await motor.GotoRealZeroAsync(); + await Task.Delay(2000); - await Task.Delay(2000); + // does not reset back to marked position on device + await motor.GotoRealZeroAsync(); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(2000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubAccelerometer.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubAccelerometer.cs index bba450f..ae6bcbe 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubAccelerometer.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubAccelerometer.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,20 +10,19 @@ public class ExampleTechnicMediumHubAccelerometer : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device = technicMediumHub.Accelerometer; + using var technicMediumHub = Host.FindByType(); - await device.SetupNotificationAsync(device.ModeIndexGravity, true); + var device = technicMediumHub.Accelerometer; - var disposable = device.GravityObservable.Subscribe(x => Log.LogWarning($"Gravity: {x.x} / {x.y} / {x.z}")); + await device.SetupNotificationAsync(device.ModeIndexGravity, true); - await Task.Delay(10_000); + var disposable = device.GravityObservable.Subscribe(x => Log.LogWarning($"Gravity: {x.x} / {x.y} / {x.z}")); - disposable.Dispose(); + await Task.Delay(10_000); - await technicMediumHub.SwitchOffAsync(); - } + disposable.Dispose(); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGestSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGestSensor.cs index 9654aa4..0816560 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGestSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGestSensor.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,18 +10,17 @@ public class ExampleTechnicMediumHubGestSensor : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device = technicMediumHub.GestureSensor; + using var technicMediumHub = Host.FindByType(); - await device.SetupNotificationAsync(0, true, deltaInterval: 0); + var device = technicMediumHub.GestureSensor; - using var _ = device.GestureObservable.Subscribe(x => Log.LogInformation($"Gesture {x}")); + await device.SetupNotificationAsync(0, true, deltaInterval: 0); - await Task.Delay(30_000); + using var _ = device.GestureObservable.Subscribe(x => Log.LogInformation($"Gesture {x}")); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(30_000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGyroSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGyroSensor.cs index 2802833..65c04ab 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGyroSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubGyroSensor.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,20 +10,19 @@ public class ExampleTechnicMediumHubGyroSensor : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device = technicMediumHub.GyroSensor; + using var technicMediumHub = Host.FindByType(); - await device.SetupNotificationAsync(device.ModeIndexRotation, true); + var device = technicMediumHub.GyroSensor; - var disposable = device.RotationObservable.Subscribe(x => Log.LogWarning($"Rotation: {x.x} / {x.y} / {x.z}")); + await device.SetupNotificationAsync(device.ModeIndexRotation, true); - await Task.Delay(10_000); + var disposable = device.RotationObservable.Subscribe(x => Log.LogWarning($"Rotation: {x.x} / {x.y} / {x.z}")); - disposable.Dispose(); + await Task.Delay(10_000); - await technicMediumHub.SwitchOffAsync(); - } + disposable.Dispose(); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensor.cs index f9bb6bd..3432350 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensor.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,20 +10,19 @@ public class ExampleTechnicMediumHubTiltSensor : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device = technicMediumHub.TiltSensor; + using var technicMediumHub = Host.FindByType(); - // await device.TiltConfigOrientationAsync(TiltConfigOrientation.Front); // does not work on technic medium hub + var device = technicMediumHub.TiltSensor; - await device.SetupNotificationAsync(device.ModeIndexPosition, true); + // await device.TiltConfigOrientationAsync(TiltConfigOrientation.Front); // does not work on technic medium hub - using var disposable = device.PositionObservable.Subscribe(x => Log.LogWarning($"Tilt: {x.x} / {x.y} / {x.z}")); + await device.SetupNotificationAsync(device.ModeIndexPosition, true); - await Task.Delay(10_000); + using var disposable = device.PositionObservable.Subscribe(x => Log.LogWarning($"Tilt: {x.x} / {x.y} / {x.z}")); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(10_000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensorImpacts.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensorImpacts.cs index 6cbdfd6..5258588 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensorImpacts.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumHubTiltSensorImpacts.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,20 +10,19 @@ public class ExampleTechnicMediumHubTiltSensorImpacts : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device = technicMediumHub.TiltSensor; + using var technicMediumHub = Host.FindByType(); - await device.TiltConfigImpactAsync(2, 1270); + var device = technicMediumHub.TiltSensor; - await device.SetupNotificationAsync(device.ModeIndexImpacts, true, deltaInterval: 1); + await device.TiltConfigImpactAsync(2, 1270); - using var disposable = device.ImpactsObservable.Subscribe(x => Log.LogWarning($"Impact: {x.SI} / {x.Pct} / {x.Raw}")); + await device.SetupNotificationAsync(device.ModeIndexImpacts, true, deltaInterval: 1); - await Task.Delay(10_000); + using var disposable = device.ImpactsObservable.Subscribe(x => Log.LogWarning($"Impact: {x.SI} / {x.Pct} / {x.Raw}")); - await technicMediumHub.SwitchOffAsync(); - } + await Task.Delay(10_000); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumTemperatureSensor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumTemperatureSensor.cs index 5a539a4..6f4cd1e 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumTemperatureSensor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTechnicMediumTemperatureSensor.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,27 +10,26 @@ public class ExampleTechnicMediumTemperatureSensor : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device1 = technicMediumHub.Temperature1; + using var technicMediumHub = Host.FindByType(); - await device1.SetupNotificationAsync(device1.ModeIndexTemperature, true); + var device1 = technicMediumHub.Temperature1; - var disposable1 = device1.TemperatureObservable.Subscribe(x => Log.LogWarning($"Temperature 1: {x.SI}° ({x.Pct}%)")); + await device1.SetupNotificationAsync(device1.ModeIndexTemperature, true); - var device2 = technicMediumHub.Temperature1; + var disposable1 = device1.TemperatureObservable.Subscribe(x => Log.LogWarning($"Temperature 1: {x.SI}° ({x.Pct}%)")); - await device2.SetupNotificationAsync(device2.ModeIndexTemperature, true); + var device2 = technicMediumHub.Temperature1; - var disposable2 = device2.TemperatureObservable.Subscribe(x => Log.LogWarning($"Temperature 2: {x.SI}° ({x.Pct}%)")); + await device2.SetupNotificationAsync(device2.ModeIndexTemperature, true); - await Task.Delay(10_000); + var disposable2 = device2.TemperatureObservable.Subscribe(x => Log.LogWarning($"Temperature 2: {x.SI}° ({x.Pct}%)")); - disposable1.Dispose(); - disposable2.Dispose(); + await Task.Delay(10_000); - await technicMediumHub.SwitchOffAsync(); - } + disposable1.Dispose(); + disposable2.Dispose(); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleTwoPortHubMediumLinearMotor.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleTwoPortHubMediumLinearMotor.cs index 34d94b2..5a6f464 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleTwoPortHubMediumLinearMotor.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleTwoPortHubMediumLinearMotor.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using SharpBrick.PoweredUp; @@ -8,36 +7,35 @@ public class ExampleTwoPortHubMediumLinearMotor : BaseExample { public override async Task ExecuteAsync() { - using (var twoPortHub = Host.FindByType()) - { - await twoPortHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder - .AddHub(hubBuilder => hubBuilder - .AddDevice(twoPortHub.A) - ) - ); + using var twoPortHub = Host.FindByType(); - var motor = twoPortHub.A.GetDevice(); + await twoPortHub.VerifyDeploymentModelAsync(modelBuilder => modelBuilder + .AddHub(hubBuilder => hubBuilder + .AddDevice(twoPortHub.A) + ) + ); - await motor.SetAccelerationTimeAsync(3000); - await motor.SetDecelerationTimeAsync(1000); - await motor.StartSpeedForTimeAsync(6000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); + var motor = twoPortHub.A.GetDevice(); - await Task.Delay(10_000); + await motor.SetAccelerationTimeAsync(3000); + await motor.SetDecelerationTimeAsync(1000); + await motor.StartSpeedForTimeAsync(6000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile); - await motor.StartSpeedForDegreesAsync(180, -10, 100, SpecialSpeed.Brake, SpeedProfiles.None); + await Task.Delay(10_000); - await Task.Delay(10_000); + await motor.StartSpeedForDegreesAsync(180, -10, 100, SpecialSpeed.Brake, SpeedProfiles.None); - await motor.StartSpeedAsync(100, 90, SpeedProfiles.None); - await Task.Delay(2000); - await motor.StartSpeedAsync(-100, 90, SpeedProfiles.None); - await Task.Delay(2000); - await motor.StartSpeedAsync(0, 90, SpeedProfiles.None); + await Task.Delay(10_000); - await Task.Delay(10_000); + await motor.StartSpeedAsync(100, 90, SpeedProfiles.None); + await Task.Delay(2000); + await motor.StartSpeedAsync(-100, 90, SpeedProfiles.None); + await Task.Delay(2000); + await motor.StartSpeedAsync(0, 90, SpeedProfiles.None); - await twoPortHub.SwitchOffAsync(); - } + await Task.Delay(10_000); + + await twoPortHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/ExampleVoltage.cs b/examples/SharpBrick.PoweredUp.Examples/ExampleVoltage.cs index 9803691..5dd1944 100644 --- a/examples/SharpBrick.PoweredUp.Examples/ExampleVoltage.cs +++ b/examples/SharpBrick.PoweredUp.Examples/ExampleVoltage.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using System.Reactive.Linq; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp; namespace Example @@ -11,20 +10,19 @@ public class ExampleVoltage : BaseExample { public override async Task ExecuteAsync() { - using (var technicMediumHub = Host.FindByType()) - { - var device = technicMediumHub.Voltage; + using var technicMediumHub = Host.FindByType(); - await device.SetupNotificationAsync(device.ModeIndexVoltageL, true); + var device = technicMediumHub.Voltage; - var disposable = device.VoltageLObservable.Subscribe(x => Log.LogWarning($"Voltage L: {x.SI}mV ({x.Pct}%)")); + await device.SetupNotificationAsync(device.ModeIndexVoltageL, true); - await Task.Delay(10_000); + var disposable = device.VoltageLObservable.Subscribe(x => Log.LogWarning($"Voltage L: {x.SI}mV ({x.Pct}%)")); - disposable.Dispose(); + await Task.Delay(10_000); - await technicMediumHub.SwitchOffAsync(); - } + disposable.Dispose(); + + await technicMediumHub.SwitchOffAsync(); } } } \ No newline at end of file diff --git a/examples/SharpBrick.PoweredUp.Examples/Program.cs b/examples/SharpBrick.PoweredUp.Examples/Program.cs index f2d1b13..e9cb7a8 100644 --- a/examples/SharpBrick.PoweredUp.Examples/Program.cs +++ b/examples/SharpBrick.PoweredUp.Examples/Program.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Example; +using System.Threading.Tasks; namespace SharpBrick.PoweredUp.Examples { @@ -54,7 +52,7 @@ static async Task Main(string[] args) // NOTE: Examples are programmed object oriented style. Base class implements methods Configure, DiscoverAsync and ExecuteAsync to be overwriten on demand. await example.InitHostAndDiscoverAsync(enableTrace); - if (example.SelectedHub != null) + if (example.SelectedHub is not null) { await example.ExecuteAsync(); } diff --git a/src/SharpBrick.PoweredUp.Cli/Commands/DevicesList.cs b/src/SharpBrick.PoweredUp.Cli/Commands/DevicesList.cs index 53ce9b4..f0588a2 100644 --- a/src/SharpBrick.PoweredUp.Cli/Commands/DevicesList.cs +++ b/src/SharpBrick.PoweredUp.Cli/Commands/DevicesList.cs @@ -32,7 +32,7 @@ public async Task ExecuteAsync(SystemType knownSystemType) await discoverPorts.ExecuteAsync(); - await protocol.SendMessageReceiveResultAsync(new HubActionMessage() { HubId = 0, Action = HubAction.SwitchOffHub }, result => result.Action == HubAction.HubWillSwitchOff); + await protocol.SendMessageReceiveResultAsync(new HubActionMessage(HubAction.SwitchOffHub) { HubId = 0 }, result => result.Action == HubAction.HubWillSwitchOff); Console.WriteLine(string.Empty); diff --git a/src/SharpBrick.PoweredUp.Cli/Commands/DumpStaticPortInfo.cs b/src/SharpBrick.PoweredUp.Cli/Commands/DumpStaticPortInfo.cs index e1bd1de..622c6c9 100644 --- a/src/SharpBrick.PoweredUp.Cli/Commands/DumpStaticPortInfo.cs +++ b/src/SharpBrick.PoweredUp.Cli/Commands/DumpStaticPortInfo.cs @@ -31,7 +31,7 @@ public async Task ExecuteAsync(SystemType knownSystemType, byte portId, bool hea await discoverPorts.ExecuteAsync(portId); - await protocol.SendMessageReceiveResultAsync(new HubActionMessage() { HubId = 0, Action = HubAction.SwitchOffHub }, result => result.Action == HubAction.HubWillSwitchOff); + await protocol.SendMessageReceiveResultAsync(new HubActionMessage(HubAction.SwitchOffHub) { HubId = 0 }, result => result.Action == HubAction.HubWillSwitchOff); Console.WriteLine(string.Empty); @@ -63,32 +63,21 @@ private byte[] CreateAttachedIOHeader(byte portId) return MessageEncoder.Encode(portInfo switch { - { IsVirtual: false } => new HubAttachedIOForAttachedDeviceMessage() + { IsVirtual: false } => new HubAttachedIOForAttachedDeviceMessage(portId, portInfo.IOTypeId, portInfo.HardwareRevision, portInfo.SoftwareRevision) { HubId = 0, - PortId = portId, - IOTypeId = portInfo.IOTypeId, - HardwareRevision = portInfo.HardwareRevision, - SoftwareRevision = portInfo.SoftwareRevision, }, - { IsVirtual: true } => new HubAttachedIOForAttachedVirtualDeviceMessage() + { IsVirtual: true } => new HubAttachedIOForAttachedVirtualDeviceMessage(portId, portInfo.IOTypeId, portInfo.PortAId, portInfo.PortBId) { HubId = 0, - PortId = portId, - IOTypeId = portInfo.IOTypeId, - PortAId = portInfo.PortAId, - PortBId = portInfo.PortBId, } }, protocol.Knowledge); } private byte[] CreateSystemTypeHeader(SystemType knownSystemType) - => MessageEncoder.Encode(new HubPropertyMessage() + => MessageEncoder.Encode(new HubPropertyMessage(HubProperty.SystemTypeId, HubPropertyOperation.Update, knownSystemType) { HubId = 0, - Property = HubProperty.SystemTypeId, - Operation = HubPropertyOperation.Update, - Payload = knownSystemType, }, protocol.Knowledge); } } diff --git a/src/SharpBrick.PoweredUp.Cli/Commands/PrettyPrint.cs b/src/SharpBrick.PoweredUp.Cli/Commands/PrettyPrint.cs index 9da22cd..3dedca3 100644 --- a/src/SharpBrick.PoweredUp.Cli/Commands/PrettyPrint.cs +++ b/src/SharpBrick.PoweredUp.Cli/Commands/PrettyPrint.cs @@ -1,10 +1,8 @@ using System; using System.IO; using System.Threading.Tasks; -using SharpBrick.PoweredUp.Functions; using SharpBrick.PoweredUp.Protocol; using SharpBrick.PoweredUp.Bluetooth.Mock; -using SharpBrick.PoweredUp.Protocol.Messages; using SharpBrick.PoweredUp.Protocol.Knowledge; namespace SharpBrick.PoweredUp.Cli @@ -40,7 +38,7 @@ public async Task ExecuteAsync(TextReader reader, byte systemType, ushort device var foundAttachedIO = false; var line = await reader.ReadLineAsync(); - while (line != null) + while (line is not null) { if (line.Substring(6, 8) == "01-0B-06") // property msg - systemtype - update { diff --git a/src/SharpBrick.PoweredUp.Cli/Program.cs b/src/SharpBrick.PoweredUp.Cli/Program.cs index 0a88ec0..8a6b54a 100644 --- a/src/SharpBrick.PoweredUp.Cli/Program.cs +++ b/src/SharpBrick.PoweredUp.Cli/Program.cs @@ -22,12 +22,14 @@ class Program static async Task Main(string[] args) { - var app = new CommandLineApplication(); + var app = new CommandLineApplication + { + Name = "poweredup", + Description = "A command line interface to investigate LEGO Powered UP hubs and devices.", + UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue, + }; - app.Name = "poweredup"; - app.Description = "A command line interface to investigate LEGO Powered UP hubs and devices."; app.HelpOption(); - app.UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue; app.OnExecute(() => { Console.WriteLine($"See {app.Name} --help for Options"); @@ -55,7 +57,7 @@ static async Task Main(string[] args) { try { - var enableTrace = bool.TryParse(traceOption.Value(), out var x) ? x : false; + var enableTrace = bool.TryParse(traceOption.Value(), out var x) && x; var serviceProvider = CreateServiceProvider(enableTrace); (ulong bluetoothAddress, SystemType systemType) = FindAndSelectHub(serviceProvider.GetService()); @@ -100,7 +102,7 @@ static async Task Main(string[] args) { try { - var enableTrace = bool.TryParse(traceOption.Value(), out var x) ? x : false; + var enableTrace = bool.TryParse(traceOption.Value(), out var x) && x; var headerEnabled = headerOption.Values.Count > 0; var serviceProvider = CreateServiceProvider(enableTrace); @@ -153,7 +155,7 @@ static async Task Main(string[] args) { try { - var enableTrace = bool.TryParse(traceOption.Value(), out var x0) ? x0 : false; + var enableTrace = bool.TryParse(traceOption.Value(), out var x0) && x0; var systemType = byte.TryParse(systemTypeOption.Value(), out var x1) ? x1 : (byte)0; var hubId = byte.TryParse(hubOption.Value(), out var x2) ? x2 : (byte)0; var portId = byte.TryParse(portOption.Value(), out var x3) ? x3 : (byte)0; diff --git a/src/SharpBrick.PoweredUp.WinRT/SharpBrick.PoweredUp.WinRT.csproj b/src/SharpBrick.PoweredUp.WinRT/SharpBrick.PoweredUp.WinRT.csproj index f20ac31..9c503c2 100644 --- a/src/SharpBrick.PoweredUp.WinRT/SharpBrick.PoweredUp.WinRT.csproj +++ b/src/SharpBrick.PoweredUp.WinRT/SharpBrick.PoweredUp.WinRT.csproj @@ -1,13 +1,9 @@ - netcoreapp3.1;net5.0-windows10.0.19041.0 + net5.0-windows10.0.19041.0 - - - - diff --git a/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothAdapter.cs b/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothAdapter.cs index 12f0806..01e7b08 100644 --- a/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothAdapter.cs +++ b/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothAdapter.cs @@ -12,8 +12,11 @@ public class WinRTPoweredUpBluetoothAdapter : IPoweredUpBluetoothAdapter { public void Discover(Func discoveryHandler, CancellationToken cancellationToken = default) { - BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher(); - watcher.ScanningMode = BluetoothLEScanningMode.Active; + var watcher = new BluetoothLEAdvertisementWatcher + { + ScanningMode = BluetoothLEScanningMode.Active + }; + watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(new Guid(PoweredUpBluetoothConstants.LegoHubService)); watcher.Received += ReceivedHandler; @@ -38,11 +41,9 @@ async void ReceivedHandler(BluetoothLEAdvertisementWatcher watcher, BluetoothLEA info.ManufacturerData = data; - using (var device = BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).AsTask().Result) - { - info.Name = device.Name; - } + using var device = BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).AsTask().Result; + info.Name = device.Name; } info.BluetoothAddress = eventArgs.BluetoothAddress; diff --git a/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothCharacteristic.cs b/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothCharacteristic.cs index f6490ac..c194ecf 100644 --- a/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothCharacteristic.cs +++ b/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothCharacteristic.cs @@ -9,7 +9,7 @@ namespace SharpBrick.PoweredUp.WinRT public class WinRTPoweredUpBluetoothCharacteristic : IPoweredUpBluetoothCharacteristic { - private GattCharacteristic _characteristic; + private readonly GattCharacteristic _characteristic; public Guid Uuid => _characteristic.Uuid; public WinRTPoweredUpBluetoothCharacteristic(GattCharacteristic characteristic) diff --git a/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothService.cs b/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothService.cs index 8a441d6..b890b78 100644 --- a/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothService.cs +++ b/src/SharpBrick.PoweredUp.WinRT/WinRTPoweredUpBluetoothService.cs @@ -28,7 +28,7 @@ public async Task GetCharacteristicAsync(Guid { var characteristics = await _service.GetCharacteristicsForUuidAsync(guid); - if (characteristics.Status == GattCommunicationStatus.Success && characteristics.Characteristics.Count() > 0) + if (characteristics.Status == GattCommunicationStatus.Success && characteristics.Characteristics.Count > 0) { var characteristic = characteristics.Characteristics.FirstOrDefault(); diff --git a/src/SharpBrick.PoweredUp/Bluetooth/BluetoothKernel.cs b/src/SharpBrick.PoweredUp/Bluetooth/BluetoothKernel.cs index ac4f954..7d99eeb 100644 --- a/src/SharpBrick.PoweredUp/Bluetooth/BluetoothKernel.cs +++ b/src/SharpBrick.PoweredUp/Bluetooth/BluetoothKernel.cs @@ -20,7 +20,7 @@ public BluetoothKernel(IPoweredUpBluetoothAdapter bluetoothAdapter, ILogger _characteristic != null; + public bool IsConnected => _characteristic is not null; public async Task ConnectAsync() { @@ -47,7 +47,7 @@ public Task DisconnectAsync() public async Task SendBytesAsync(byte[] data) { - if (_characteristic == null) + if (_characteristic is null) { throw new InvalidOperationException($"Cannot invoke {nameof(SendBytesAsync)} when device is not connected ({nameof(_characteristic)} is null)"); } @@ -60,7 +60,7 @@ public async Task SendBytesAsync(byte[] data) public async Task ReceiveBytesAsync(Func handler) { - if (_characteristic == null) + if (_characteristic is null) { throw new InvalidOperationException($"Cannot invoke {nameof(SendBytesAsync)} when device is not connected ({nameof(_characteristic)} is null)"); } diff --git a/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothCharacteristicMock.cs b/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothCharacteristicMock.cs index b53945d..1962038 100644 --- a/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothCharacteristicMock.cs +++ b/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothCharacteristicMock.cs @@ -39,13 +39,9 @@ public Task WriteUpstreamAsync(params byte[] message) public List DownstreamMessages { get; } = new List(); public Task AttachIO(DeviceType deviceType, byte hubId, byte portId, Version hw, Version sw) - => WriteUpstreamAsync(MessageEncoder.Encode(new HubAttachedIOForAttachedDeviceMessage() + => WriteUpstreamAsync(MessageEncoder.Encode(new HubAttachedIOForAttachedDeviceMessage(portId, deviceType, hw, sw) { HubId = hubId, - PortId = portId, - IOTypeId = deviceType, - HardwareRevision = hw, - SoftwareRevision = sw, }, null)); } } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothDeviceMock.cs b/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothDeviceMock.cs index a89ba87..4d685d3 100644 --- a/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothDeviceMock.cs +++ b/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothDeviceMock.cs @@ -5,7 +5,7 @@ namespace SharpBrick.PoweredUp.Bluetooth.Mock { public class PoweredUpBluetoothDeviceMock : IPoweredUpBluetoothDevice { - private PoweredUpBluetoothServiceMock _mockService; + private readonly PoweredUpBluetoothServiceMock _mockService; public PoweredUpBluetoothDeviceMock(PoweredUpBluetoothServiceMock mockService) { @@ -15,7 +15,9 @@ public PoweredUpBluetoothDeviceMock(PoweredUpBluetoothServiceMock mockService) public string Name => "Mock Device"; public void Dispose() - { } + { + GC.SuppressFinalize(this); + } public Task GetServiceAsync(Guid serviceId) => Task.FromResult(_mockService); diff --git a/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothServiceMock.cs b/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothServiceMock.cs index 14c6652..b8b4901 100644 --- a/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothServiceMock.cs +++ b/src/SharpBrick.PoweredUp/Bluetooth/Mock/PoweredUpBluetoothServiceMock.cs @@ -5,17 +5,18 @@ namespace SharpBrick.PoweredUp.Bluetooth.Mock { public class PoweredUpBluetoothServiceMock : IPoweredUpBluetoothService { - private PoweredUpBluetoothCharacteristicMock _mockCharacteristic; + private readonly PoweredUpBluetoothCharacteristicMock _mockCharacteristic; public PoweredUpBluetoothServiceMock(PoweredUpBluetoothCharacteristicMock mockCharacteristic) { - this._mockCharacteristic = mockCharacteristic; + _mockCharacteristic = mockCharacteristic; } public Guid Uuid => Guid.Empty; public void Dispose() { + GC.SuppressFinalize(this); } public Task GetCharacteristicAsync(Guid guid) diff --git a/src/SharpBrick.PoweredUp/Deployment/DeploymentModel.cs b/src/SharpBrick.PoweredUp/Deployment/DeploymentModel.cs index 03702e3..4f79e3e 100644 --- a/src/SharpBrick.PoweredUp/Deployment/DeploymentModel.cs +++ b/src/SharpBrick.PoweredUp/Deployment/DeploymentModel.cs @@ -58,7 +58,7 @@ public DeploymentModelError[] Verify(ILegoWirelessProtocol protocol, byte hubId, var hubInfo = protocol.Knowledge.Hub(hubId); - if (hubModel.HubType != null && hubModel.HubType != hubInfo.SystemType) + if (hubModel.HubType is not null && hubModel.HubType != hubInfo.SystemType) { result.Add(new DeploymentModelError(1002, hubInfo.HubId, null, $"Hub {hubInfo.HubId} with system type {hubInfo.SystemType} does not match expected {hubModel.HubType}.")); } @@ -73,7 +73,7 @@ public DeploymentModelError[] Verify(ILegoWirelessProtocol protocol, byte hubId, .Select(t => t switch { (var Device, var PortInfo) when !PortInfo.IsDeviceConnected => (Error: 1000, t.Device, t.PortInfo), // no device connected - (var Device, var PortInfo) when Device.DeviceType != null && PortInfo.IOTypeId != Device.DeviceType => (Error: 1001, t.Device, t.PortInfo), // wrong device connected + (var Device, var PortInfo) when Device.DeviceType is not null && PortInfo.IOTypeId != Device.DeviceType => (Error: 1001, t.Device, t.PortInfo), // wrong device connected _ => (Error: 0, t.Device, t.PortInfo), }) .Where(t => t.Error != 0) @@ -83,7 +83,7 @@ public DeploymentModelError[] Verify(ILegoWirelessProtocol protocol, byte hubId, t.Device.PortId, t.Error switch { - 1000 when t.Device.DeviceType == null => $"No device connected to port {t.Device.PortId}. Expected some device.", + 1000 when t.Device.DeviceType is null => $"No device connected to port {t.Device.PortId}. Expected some device.", 1000 => $"No device connected to port {t.Device.PortId}. Expected {t.Device.DeviceType} on port {t.Device.PortId}.", 1001 => $"No {t.Device.DeviceType} connected to port {t.Device.PortId}. Currently connected: {t.PortInfo.IOTypeId}.", _ => "A deployment model verificaiton failed." diff --git a/src/SharpBrick.PoweredUp/Deployment/DeploymentModelBuilder.cs b/src/SharpBrick.PoweredUp/Deployment/DeploymentModelBuilder.cs index 2201174..cc91ea0 100644 --- a/src/SharpBrick.PoweredUp/Deployment/DeploymentModelBuilder.cs +++ b/src/SharpBrick.PoweredUp/Deployment/DeploymentModelBuilder.cs @@ -6,7 +6,7 @@ namespace SharpBrick.PoweredUp.Deployment { public class DeploymentModelBuilder { - private List _hubs = new List(); + private readonly List _hubs = new(); /// /// Add a hub with the given hub type to the model diff --git a/src/SharpBrick.PoweredUp/Deployment/DeploymentModelHubBuilder.cs b/src/SharpBrick.PoweredUp/Deployment/DeploymentModelHubBuilder.cs index 90c04da..1360bcd 100644 --- a/src/SharpBrick.PoweredUp/Deployment/DeploymentModelHubBuilder.cs +++ b/src/SharpBrick.PoweredUp/Deployment/DeploymentModelHubBuilder.cs @@ -6,7 +6,7 @@ namespace SharpBrick.PoweredUp.Deployment { public class DeploymentModelHubBuilder { - private List _devices = new List(); + private readonly List _devices = new(); private SystemType? _hubType = null; @@ -32,6 +32,6 @@ public DeploymentModelHubBuilder AddDevice(DeviceType? deviceType, byte portId) } public DeploymentHubModel Build() - => new DeploymentHubModel(_hubType, _devices.ToArray()); + => new(_hubType, _devices.ToArray()); } } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Devices/AbsoluteMotor.cs b/src/SharpBrick.PoweredUp/Devices/AbsoluteMotor.cs index 516da4d..8551b4f 100644 --- a/src/SharpBrick.PoweredUp/Devices/AbsoluteMotor.cs +++ b/src/SharpBrick.PoweredUp/Devices/AbsoluteMotor.cs @@ -47,17 +47,16 @@ public async Task GotoPositionAsync(int absolutePosition, sbyte sp AssertValidMaxPower(maxPower, nameof(maxPower)); AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandGotoAbsolutePositionMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandGotoAbsolutePositionMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + absolutePosition, + speed, + maxPower, + endState, + profile) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - AbsolutePosition = absolutePosition, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, }); return response; @@ -85,18 +84,17 @@ public async Task GotoPositionAsync(int absolutePosition1, int abs AssertIsConnected(); AssertIsVirtualPort(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandGotoAbsolutePosition2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandGotoAbsolutePosition2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + absolutePosition1, absolutePosition2, + speed, + maxPower, + endState, + profile + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - AbsolutePosition1 = absolutePosition1, - AbsolutePosition2 = absolutePosition2, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, }); return response; diff --git a/src/SharpBrick.PoweredUp/Devices/BasicMotor.cs b/src/SharpBrick.PoweredUp/Devices/BasicMotor.cs index 37fd20e..f638a69 100644 --- a/src/SharpBrick.PoweredUp/Devices/BasicMotor.cs +++ b/src/SharpBrick.PoweredUp/Devices/BasicMotor.cs @@ -39,13 +39,13 @@ public async Task StartPowerAsync(sbyte power) AssertValidPower(power, nameof(power)); AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPowerMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPowerMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + power + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Power = power, }); return response; @@ -86,14 +86,13 @@ public async Task StartPowerAsync(sbyte powerOnMotor1, sbyte power AssertIsConnected(); AssertIsVirtualPort(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPower2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPower2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + powerOnMotor1, powerOnMotor2 + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Power1 = powerOnMotor1, - Power2 = powerOnMotor2, }); return response; diff --git a/src/SharpBrick.PoweredUp/Devices/Device.cs b/src/SharpBrick.PoweredUp/Devices/Device.cs index bc9bd3a..dbb8a9e 100644 --- a/src/SharpBrick.PoweredUp/Devices/Device.cs +++ b/src/SharpBrick.PoweredUp/Devices/Device.cs @@ -13,8 +13,8 @@ namespace SharpBrick.PoweredUp { public abstract class Device : IDisposable, INotifyPropertyChanged { - private CompositeDisposable _compositeDisposable = new CompositeDisposable(); - private ConcurrentDictionary _modes = new ConcurrentDictionary(); + private CompositeDisposable _compositeDisposable = new(); + private readonly ConcurrentDictionary _modes = new(); protected readonly ILegoWirelessProtocol _protocol; protected readonly byte _hubId; @@ -22,7 +22,7 @@ public abstract class Device : IDisposable, INotifyPropertyChanged protected readonly IObservable _portValueObservable; public IReadOnlyDictionary Modes => _modes; - public bool IsConnected => (_protocol != null); + public bool IsConnected => (_protocol is not null); public Device() { } @@ -78,13 +78,14 @@ public async Task SetupNotificationAsync(byte modeIndex, bool enabled, uint delt deltaInterval = GetDefaultDeltaInterval(modeIndex); } - await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage( + _portId, + modeIndex, + deltaInterval, + enabled + ) { HubId = _hubId, - PortId = _portId, - Mode = modeIndex, - DeltaInterval = deltaInterval, - NotificationEnabled = enabled, }); } @@ -123,31 +124,27 @@ public async Task TryLockDeviceForCombinedModeNotificationSetupAsync(param if (combinationModeIndex <= 7) // spec chapter 3.18.1 max combination mode index { - await _protocol.SendMessageAsync(new PortInputFormatSetupCombinedModeMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupCombinedModeMessage( + _portId, + PortInputFormatSetupCombinedSubCommand.LockDeviceForSetup + ) { HubId = _hubId, - PortId = _portId, - SubCommand = PortInputFormatSetupCombinedSubCommand.LockDeviceForSetup, }); // if this needs to be performed after the port formats, cache it for the unlock function - await _protocol.SendMessageAsync(new PortInputFormatSetupCombinedModeForSetModeDataSetMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupCombinedModeForSetModeDataSetMessage( + _portId, + combinationModeIndex, + modeIndices + .Select(m => _protocol.Knowledge.PortMode(_hubId, _portId, m)) + .SelectMany(mode => Enumerable + .Range(0, mode.NumberOfDatasets) + .Select(dataSetPosition => new PortInputFormatSetupCombinedModeModeDataSet(mode.ModeIndex, (byte)dataSetPosition))) + .ToArray() // manage DataSet for device which has (A) multiple modes and (B) returns for a mode more than one data set (e.g. R, G, B for color). + ) { HubId = _hubId, - PortId = _portId, - SubCommand = PortInputFormatSetupCombinedSubCommand.SetModeAndDataSetCombination, - - CombinationIndex = combinationModeIndex, - ModeDataSets = modeIndices - .Select(m => _protocol.Knowledge.PortMode(_hubId, _portId, m)) - .SelectMany(mode => Enumerable - .Range(0, mode.NumberOfDatasets) - .Select(dataSetPosition => new PortInputFormatSetupCombinedModeModeDataSet() - { - Mode = mode.ModeIndex, - DataSet = (byte)dataSetPosition, - })) - .ToArray(), // manage DataSet for device which has (A) multiple modes and (B) returns for a mode more than one data set (e.g. R, G, B for color). }); result = true; @@ -160,13 +157,14 @@ public async Task UnlockFromCombinedModeNotificationSetupAsync(bool enableUpdate { AssertIsConnected(); - await _protocol.SendMessageAsync(new PortInputFormatSetupCombinedModeMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupCombinedModeMessage( + _portId, + enableUpdates + ? PortInputFormatSetupCombinedSubCommand.UnlockAndStartWithMultiUpdateEnabled + : PortInputFormatSetupCombinedSubCommand.UnlockAndStartWithMultiUpdateDisabled + ) { HubId = _hubId, - PortId = _portId, - SubCommand = enableUpdates - ? PortInputFormatSetupCombinedSubCommand.UnlockAndStartWithMultiUpdateEnabled - : PortInputFormatSetupCombinedSubCommand.UnlockAndStartWithMultiUpdateDisabled, }); } diff --git a/src/SharpBrick.PoweredUp/Devices/DeviceFactory.cs b/src/SharpBrick.PoweredUp/Devices/DeviceFactory.cs index c41c77f..c8eec5a 100644 --- a/src/SharpBrick.PoweredUp/Devices/DeviceFactory.cs +++ b/src/SharpBrick.PoweredUp/Devices/DeviceFactory.cs @@ -17,14 +17,14 @@ public IPoweredUpDevice Create(DeviceType deviceType) { var type = GetTypeFromDeviceType(deviceType); - return (type == null) ? null : (IPoweredUpDevice)ActivatorUtilities.CreateInstance(_serviceProvider, type); + return (type is null) ? null : (IPoweredUpDevice)ActivatorUtilities.CreateInstance(_serviceProvider, type); } public IPoweredUpDevice CreateConnected(DeviceType deviceType, ILegoWirelessProtocol protocol, byte hubId, byte portId) { var type = GetTypeFromDeviceType(deviceType); - return (type == null) ? new DynamicDevice(protocol, hubId, portId) : (IPoweredUpDevice)ActivatorUtilities.CreateInstance(_serviceProvider, type, protocol, hubId, portId); + return (type is null) ? new DynamicDevice(protocol, hubId, portId) : (IPoweredUpDevice)ActivatorUtilities.CreateInstance(_serviceProvider, type, protocol, hubId, portId); } public Type GetTypeFromDeviceType(DeviceType deviceType) diff --git a/src/SharpBrick.PoweredUp/Devices/DuploTrainBaseMotor.cs b/src/SharpBrick.PoweredUp/Devices/DuploTrainBaseMotor.cs index f95e588..f70361d 100644 --- a/src/SharpBrick.PoweredUp/Devices/DuploTrainBaseMotor.cs +++ b/src/SharpBrick.PoweredUp/Devices/DuploTrainBaseMotor.cs @@ -53,13 +53,13 @@ public async Task StartPowerAsync(sbyte power) AssertValidPower(power, nameof(power)); AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPowerMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPowerMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + power + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Power = power, }); return response; @@ -100,14 +100,13 @@ public async Task StartPowerAsync(sbyte powerOnMotor1, sbyte power AssertIsConnected(); AssertIsVirtualPort(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPower2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartPower2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + powerOnMotor1, powerOnMotor2 + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Power1 = powerOnMotor1, - Power2 = powerOnMotor2, }); return response; diff --git a/src/SharpBrick.PoweredUp/Devices/DynamicDevice.cs b/src/SharpBrick.PoweredUp/Devices/DynamicDevice.cs index c582439..5e7ef53 100644 --- a/src/SharpBrick.PoweredUp/Devices/DynamicDevice.cs +++ b/src/SharpBrick.PoweredUp/Devices/DynamicDevice.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using SharpBrick.PoweredUp.Functions; using SharpBrick.PoweredUp.Protocol; -using SharpBrick.PoweredUp.Protocol.Messages; namespace SharpBrick.PoweredUp { diff --git a/src/SharpBrick.PoweredUp/Devices/Mode.cs b/src/SharpBrick.PoweredUp/Devices/Mode.cs index c2123bc..49c2b48 100644 --- a/src/SharpBrick.PoweredUp/Devices/Mode.cs +++ b/src/SharpBrick.PoweredUp/Devices/Mode.cs @@ -13,12 +13,12 @@ namespace SharpBrick.PoweredUp [DebuggerDisplay("Mode {_modeInfo.HubId}-{_modeInfo.PortId}-{_modeInfo.ModeIndex} {Name}")] public class Mode : IDisposable, INotifyPropertyChanged { - private CompositeDisposable _compositeDisposable = new CompositeDisposable(); - private ILegoWirelessProtocol _protocol; - private PortModeInfo _modeInfo; + private readonly CompositeDisposable _compositeDisposable = new(); + private readonly ILegoWirelessProtocol _protocol; + private readonly PortModeInfo _modeInfo; protected IObservable _modeValueObservable; - public bool IsConnected => (_protocol != null); + public bool IsConnected => (_protocol is not null); public string Name => _modeInfo.Name; public string Symbol => _modeInfo.Symbol; @@ -27,9 +27,7 @@ public static Mode Create(ILegoWirelessProtocol protocol, byte hubId, byte portI { var modeInfo = protocol.Knowledge.PortMode(hubId, portId, modeIndex); - Mode result = null; - - result = (modeInfo.DatasetType, modeInfo.NumberOfDatasets) switch + Mode result = (modeInfo.DatasetType, modeInfo.NumberOfDatasets) switch { (PortModeInformationDataType.SByte, 1) => new SingleValueMode(protocol, modeInfo, modeValueObservable), (PortModeInformationDataType.SByte, _) => new MultiValueMode(protocol, modeInfo, modeValueObservable), @@ -65,13 +63,13 @@ public async Task WriteDirectModeDataAsync(params byte[] data) throw new InvalidOperationException("The protocol knowledge declares that this mode cannot be written to (IsOutput = false)"); } - var response = await _protocol.SendPortOutputCommandAsync(new GenericWriteDirectModeDataMessage(_modeInfo.ModeIndex) + var response = await _protocol.SendPortOutputCommandAsync(new GenericWriteDirectModeDataMessage( + _modeInfo.PortId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + _modeInfo.ModeIndex, + data) { HubId = _modeInfo.HubId, - PortId = _modeInfo.PortId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Data = data, }); return response; @@ -99,13 +97,9 @@ public async Task SetupNotificationAsync(bool enabled, uint deltaInterval = 5) throw new InvalidOperationException("The protocol knowledge declares that this mode cannot be read (IsInput = false)"); } - await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage(_modeInfo.PortId, _modeInfo.ModeIndex, deltaInterval, enabled) { HubId = _modeInfo.HubId, - PortId = _modeInfo.PortId, - Mode = _modeInfo.ModeIndex, - DeltaInterval = deltaInterval, - NotificationEnabled = enabled, }); } diff --git a/src/SharpBrick.PoweredUp/Devices/MoveHubTiltSensor.cs b/src/SharpBrick.PoweredUp/Devices/MoveHubTiltSensor.cs index 0a69bf8..00ae75c 100644 --- a/src/SharpBrick.PoweredUp/Devices/MoveHubTiltSensor.cs +++ b/src/SharpBrick.PoweredUp/Devices/MoveHubTiltSensor.cs @@ -95,17 +95,17 @@ public async Task TiltImpactPresetAsync(int presetValue) if (presetValue < 0) { - throw new ArgumentOutOfRangeException("PresetValue has to be between 0 and int.MaxValue", nameof(presetValue)); + throw new ArgumentOutOfRangeException(nameof(presetValue), "PresetValue has to be between 0 and int.MaxValue"); } - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltImpactPresetMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltImpactPresetMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + presetValue + ) { HubId = _hubId, - PortId = _portId, ModeIndex = ModeIndexImpacts, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - PresetValue = presetValue, }); return response; @@ -123,23 +123,23 @@ public async Task TiltConfigImpactAsync(sbyte impactThreshold, sho if (impactThreshold < 0) { - throw new ArgumentOutOfRangeException("Impact Threshold has to be between 0 and 127", nameof(impactThreshold)); + throw new ArgumentOutOfRangeException(nameof(impactThreshold), "Impact Threshold has to be between 0 and 127"); } if (bumpHoldoffInMs < 10 || bumpHoldoffInMs > 1270) { - throw new ArgumentOutOfRangeException("Hold off has to be between 10 and 1270 ms (in steps of 10ms)", nameof(bumpHoldoffInMs)); + throw new ArgumentOutOfRangeException(nameof(bumpHoldoffInMs), "Hold off has to be between 10 and 1270 ms (in steps of 10ms)"); } - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigImpactMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigImpactMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + impactThreshold, + (sbyte)((float)bumpHoldoffInMs / 10) + ) { HubId = _hubId, - PortId = _portId, ModeIndex = ModeIndexImpactsConfig, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - ImpactThreshold = impactThreshold, - BumpHoldoff = (sbyte)((float)bumpHoldoffInMs / 10), }); return response; @@ -154,21 +154,21 @@ public async Task TiltConfigOrientationAsync(TiltConfigOrientation { AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigOrientationMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigOrientationMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + orientation + ) { HubId = _hubId, - PortId = _portId, ModeIndex = ModeIndexOrientationConfig, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Orientation = orientation }); return response; } public IEnumerable GetStaticPortInfoMessages(Version softwareVersion, Version hardwareVersion, SystemType systemType) - => + => @" 0B-00-43-3A-01-06-08-FF-00-00-00 07-00-43-3A-02-1F-00 diff --git a/src/SharpBrick.PoweredUp/Devices/RgbLight.cs b/src/SharpBrick.PoweredUp/Devices/RgbLight.cs index 8542186..bc2728e 100644 --- a/src/SharpBrick.PoweredUp/Devices/RgbLight.cs +++ b/src/SharpBrick.PoweredUp/Devices/RgbLight.cs @@ -26,13 +26,13 @@ public async Task SetRgbColorNoAsync(PoweredUpColor color) { AssertIsConnected(); - await _protocol.SendMessageAsync(new PortOutputCommandSetRgbColorNoMessage() + await _protocol.SendMessageAsync(new PortOutputCommandSetRgbColorNoMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + color + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - ColorNo = color, }); } @@ -47,24 +47,18 @@ public async Task SetRgbColorsAsync(byte red, byte green, byte blu { AssertIsConnected(); - await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage(_portId, 0x01, 10000, false) { HubId = _hubId, - PortId = _portId, - Mode = 0x01, - DeltaInterval = 10000, - NotificationEnabled = false, }); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandSetRgbColorNo2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandSetRgbColorNo2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + red, green, blue + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - RedColor = red, - GreenColor = green, - BlueColor = blue, }); return response; diff --git a/src/SharpBrick.PoweredUp/Devices/TachoMotor.cs b/src/SharpBrick.PoweredUp/Devices/TachoMotor.cs index 3fe4769..96c82ed 100644 --- a/src/SharpBrick.PoweredUp/Devices/TachoMotor.cs +++ b/src/SharpBrick.PoweredUp/Devices/TachoMotor.cs @@ -53,14 +53,14 @@ public async Task SetAccelerationTimeAsync(ushort timeInMs, SpeedP } AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandSetAccTimeMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandSetAccTimeMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + timeInMs, + profileNumber + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = timeInMs, - Profile = profileNumber, }); return response; @@ -85,14 +85,14 @@ public async Task SetDecelerationTimeAsync(ushort timeInMs, SpeedP } AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandSetDecTimeMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandSetDecTimeMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + timeInMs, + profileNumber + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = timeInMs, - Profile = profileNumber, }); return response; @@ -114,15 +114,15 @@ public async Task StartSpeedAsync(sbyte speed, byte maxPower, Spee AssertValidMaxPower(maxPower, nameof(maxPower)); AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + speed, + maxPower, + profile + ) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Speed = speed, - MaxPower = maxPower, - Profile = profile, }); return response; @@ -150,16 +150,14 @@ public async Task StartSpeedAsync(sbyte speedOnMotor1, sbyte speed AssertIsConnected(); AssertIsVirtualPort(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeed2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeed2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + speedOnMotor1, speedOnMotor2, + maxPower, + profile) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Speed1 = speedOnMotor1, - Speed2 = speedOnMotor2, - MaxPower = maxPower, - Profile = profile, }); return response; @@ -183,17 +181,16 @@ public async Task StartSpeedForTimeAsync(ushort timeInMs, sbyte sp AssertValidMaxPower(maxPower, nameof(maxPower)); AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForTimeMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForTimeMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + timeInMs, + speed, + maxPower, + endState, + profile) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = timeInMs, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, }); return response; @@ -223,18 +220,16 @@ public async Task StartSpeedForTimeAsync(ushort timeInMs, sbyte sp AssertIsConnected(); AssertIsVirtualPort(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForTime2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForTime2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + timeInMs, + speedOnMotor1, speedOnMotor2, + maxPower, + endState, + profile) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = timeInMs, - Speed1 = speedOnMotor1, - Speed2 = speedOnMotor2, - MaxPower = maxPower, - EndState = endState, - Profile = profile, }); return response; @@ -261,17 +256,16 @@ public async Task StartSpeedForDegreesAsync(uint degrees, sbyte sp AssertValidMaxPower(maxPower, nameof(maxPower)); AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForDegreesMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForDegreesMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + degrees, + speed, + maxPower, + endState, + profile) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Degrees = degrees, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, }); return response; @@ -301,18 +295,16 @@ public async Task StartSpeedForDegreesAsync(uint degrees, sbyte sp AssertIsConnected(); AssertIsVirtualPort(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForDegrees2Message() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandStartSpeedForDegrees2Message( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + degrees, + speedOnMotor1, speedOnMotor2, + maxPower, + endState, + profile) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Degrees = degrees, - Speed1 = speedOnMotor1, - Speed2 = speedOnMotor2, - MaxPower = maxPower, - EndState = endState, - Profile = profile, }); return response; @@ -327,14 +319,13 @@ public async Task SetZeroAsync(int position = 0) { AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandPresetEncoderMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandPresetEncoderMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + position) { HubId = _hubId, - PortId = _portId, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, ModeIndex = ModeIndexPosition, // GotoAbsolutePosition and input POS is aligned with this adjustment - Position = position, }); return response; diff --git a/src/SharpBrick.PoweredUp/Devices/TechnicColorSensor.cs b/src/SharpBrick.PoweredUp/Devices/TechnicColorSensor.cs index 9dfc3d9..6c20bc1 100644 --- a/src/SharpBrick.PoweredUp/Devices/TechnicColorSensor.cs +++ b/src/SharpBrick.PoweredUp/Devices/TechnicColorSensor.cs @@ -61,13 +61,9 @@ public async Task SetSectorLightAsync(byte sector1, byte sector2, byte sector3) AssertIsConnected(); await _lightMode.WriteDirectModeDataAsync(new byte[] { sector1, sector2, sector3 }); - await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage() + await _protocol.SendMessageAsync(new PortInputFormatSetupSingleMessage(_portId, ModeIndexLight, 10000, false) { HubId = _hubId, - PortId = _portId, - Mode = ModeIndexLight, - DeltaInterval = 10000, - NotificationEnabled = false, }); } diff --git a/src/SharpBrick.PoweredUp/Devices/TechnicMediumHubTiltSensor.cs b/src/SharpBrick.PoweredUp/Devices/TechnicMediumHubTiltSensor.cs index 932d7d4..da3d63a 100644 --- a/src/SharpBrick.PoweredUp/Devices/TechnicMediumHubTiltSensor.cs +++ b/src/SharpBrick.PoweredUp/Devices/TechnicMediumHubTiltSensor.cs @@ -46,17 +46,17 @@ public async Task TiltImpactPresetAsync(int presetValue) if (presetValue < 0) { - throw new ArgumentOutOfRangeException("PresetValue has to be between 0 and int.MaxValue", nameof(presetValue)); + throw new ArgumentOutOfRangeException(nameof(presetValue), "PresetValue has to be between 0 and int.MaxValue"); } - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltImpactPresetMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltImpactPresetMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + presetValue + ) { HubId = _hubId, - PortId = _portId, ModeIndex = ModeIndexImpacts, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - PresetValue = presetValue, }); return response; @@ -74,23 +74,23 @@ public async Task TiltConfigImpactAsync(sbyte impactThreshold, sho if (impactThreshold < 0) { - throw new ArgumentOutOfRangeException("Impact Threshold has to be between 0 and 127", nameof(impactThreshold)); + throw new ArgumentOutOfRangeException(nameof(impactThreshold), "Impact Threshold has to be between 0 and 127"); } if (bumpHoldoffInMs < 10 || bumpHoldoffInMs > 1270) { - throw new ArgumentOutOfRangeException("Hold off has to be between 10 and 1270 ms (in steps of 10ms)", nameof(bumpHoldoffInMs)); + throw new ArgumentOutOfRangeException(nameof(bumpHoldoffInMs), "Hold off has to be between 10 and 1270 ms (in steps of 10ms)"); } - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigImpactMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigImpactMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + impactThreshold, + (sbyte)((float)bumpHoldoffInMs / 10) + ) { HubId = _hubId, - PortId = _portId, ModeIndex = ModeIndexConfig, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - ImpactThreshold = impactThreshold, - BumpHoldoff = (sbyte)((float)bumpHoldoffInMs / 10), }); return response; @@ -107,14 +107,13 @@ public async Task TiltConfigOrientationAsync(TiltConfigOrientation { AssertIsConnected(); - var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigOrientationMessage() + var response = await _protocol.SendPortOutputCommandAsync(new PortOutputCommandTiltConfigOrientationMessage( + _portId, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + orientation) { HubId = _hubId, - PortId = _portId, ModeIndex = ModeIndexConfig, // TODO ??? - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Orientation = orientation }); return response; diff --git a/src/SharpBrick.PoweredUp/Functions/DiscoverPorts.cs b/src/SharpBrick.PoweredUp/Functions/DiscoverPorts.cs index daa43de..3ca5267 100644 --- a/src/SharpBrick.PoweredUp/Functions/DiscoverPorts.cs +++ b/src/SharpBrick.PoweredUp/Functions/DiscoverPorts.cs @@ -11,7 +11,7 @@ namespace SharpBrick.PoweredUp.Functions { public class DiscoverPorts { - private object lockObject = new object(); + private readonly object lockObject = new(); private readonly ILegoWirelessProtocol _protocol; private readonly byte _hubId; @@ -67,8 +67,8 @@ private async Task RequestPortProperties(PortInfo port) SentMessages += 2; } - await _protocol.SendMessageAsync(new PortInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, InformationType = PortInformationType.ModeInfo, }); - await _protocol.SendMessageAsync(new PortInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, InformationType = PortInformationType.PossibleModeCombinations, }); + await _protocol.SendMessageAsync(new PortInformationRequestMessage(port.PortId, PortInformationType.ModeInfo) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortInformationRequestMessage(port.PortId, PortInformationType.PossibleModeCombinations) { HubId = _hubId }); } private async Task RequestPortModePropertiesAsync(PortInfo port) @@ -81,13 +81,13 @@ private async Task RequestPortModePropertiesAsync(PortInfo port) SentMessages += 7; } - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.Name, }); - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.Raw, }); - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.Pct, }); - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.SI, }); - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.Symbol, }); - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.Mapping, }); - await _protocol.SendMessageAsync(new PortModeInformationRequestMessage() { HubId = _hubId, PortId = port.PortId, Mode = modeIndex, InformationType = PortModeInformationType.ValueFormat, }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.Name) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.Raw) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.Pct) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.SI) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.Symbol) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.Mapping) { HubId = _hubId }); + await _protocol.SendMessageAsync(new PortModeInformationRequestMessage(port.PortId, modeIndex, PortModeInformationType.ValueFormat) { HubId = _hubId }); } // safeguard after awaits. first when all messages are sent out, completion can be reached. diff --git a/src/SharpBrick.PoweredUp/Functions/TraceMessages.cs b/src/SharpBrick.PoweredUp/Functions/TraceMessages.cs index 29698f5..65278d3 100644 --- a/src/SharpBrick.PoweredUp/Functions/TraceMessages.cs +++ b/src/SharpBrick.PoweredUp/Functions/TraceMessages.cs @@ -1,16 +1,14 @@ using System; -using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using SharpBrick.PoweredUp.Protocol; using SharpBrick.PoweredUp.Protocol.Messages; -using SharpBrick.PoweredUp.Utils; namespace SharpBrick.PoweredUp.Functions { public class TraceMessages { - private ILegoWirelessProtocol _protocol; + private readonly ILegoWirelessProtocol _protocol; private readonly ILogger _logger; public TraceMessages(ILegoWirelessProtocol protocol, ILogger logger = default) diff --git a/src/SharpBrick.PoweredUp/Hubs/Hub.cs b/src/SharpBrick.PoweredUp/Hubs/Hub.cs index 32b60bb..41344c9 100644 --- a/src/SharpBrick.PoweredUp/Hubs/Hub.cs +++ b/src/SharpBrick.PoweredUp/Hubs/Hub.cs @@ -12,7 +12,7 @@ namespace SharpBrick.PoweredUp { public abstract partial class Hub : IDisposable { - private CompositeDisposable _compositeDisposable = new CompositeDisposable(); + private readonly CompositeDisposable _compositeDisposable = new(); private readonly ILogger _logger; private readonly IDeviceFactory _deviceFactory; private readonly SystemType _knownSystemType; @@ -21,7 +21,7 @@ public abstract partial class Hub : IDisposable public ILegoWirelessProtocol Protocol { get; private set; } public byte HubId { get; private set; } public IServiceProvider ServiceProvider { get; } - public bool IsConnected => Protocol != null; + public bool IsConnected => Protocol is not null; public Hub(ILegoWirelessProtocol protocol, IDeviceFactory deviceFactory, ILogger logger, IServiceProvider serviceProvider, SystemType knownSystemType, Port[] knownPorts, IEnumerable knownProperties = default) { @@ -47,7 +47,7 @@ public void Configure(byte hubId) #region Disposable Pattern ~Hub() => Dispose(false); - public void Dispose() => Dispose(true); + public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { _compositeDisposable?.Dispose(); diff --git a/src/SharpBrick.PoweredUp/Hubs/HubFactory.cs b/src/SharpBrick.PoweredUp/Hubs/HubFactory.cs index 1147592..e56ccad 100644 --- a/src/SharpBrick.PoweredUp/Hubs/HubFactory.cs +++ b/src/SharpBrick.PoweredUp/Hubs/HubFactory.cs @@ -14,7 +14,7 @@ public HubFactory(IServiceProvider serviceProvider) public Hub CreateByBluetoothManufacturerData(byte[] manufacturerData) { - var hub = (manufacturerData == null || manufacturerData.Length < 3) ? null : Create(GetTypeFromSystemType(GetSystemTypeFromManufacturerData((PoweredUpHubManufacturerData)manufacturerData[1]))); + var hub = (manufacturerData is null || manufacturerData.Length < 3) ? null : Create(GetTypeFromSystemType(GetSystemTypeFromManufacturerData((PoweredUpHubManufacturerData)manufacturerData[1]))); hub.Configure(0x00); return hub; diff --git a/src/SharpBrick.PoweredUp/Hubs/Hub_Actions.cs b/src/SharpBrick.PoweredUp/Hubs/Hub_Actions.cs index 6df3480..1d0fb91 100644 --- a/src/SharpBrick.PoweredUp/Hubs/Hub_Actions.cs +++ b/src/SharpBrick.PoweredUp/Hubs/Hub_Actions.cs @@ -15,10 +15,9 @@ public async Task SwitchOffAsync() { AssertIsConnected(); - await Protocol.SendMessageReceiveResultAsync(new HubActionMessage + await Protocol.SendMessageReceiveResultAsync(new HubActionMessage(HubAction.SwitchOffHub) { HubId = HubId, - Action = HubAction.SwitchOffHub }, action => action.Action == HubAction.HubWillSwitchOff); await Protocol.DisconnectAsync(); @@ -32,10 +31,9 @@ public async Task DisconnectAsync() { AssertIsConnected(); - await Protocol.SendMessageReceiveResultAsync(new HubActionMessage + await Protocol.SendMessageReceiveResultAsync(new HubActionMessage(HubAction.Disconnect) { HubId = HubId, - Action = HubAction.Disconnect }, action => action.Action == HubAction.HubWillDisconnect); await Protocol.DisconnectAsync(); @@ -49,10 +47,9 @@ public async Task VccPortControlOnAsync() { AssertIsConnected(); - await Protocol.SendMessageAsync(new HubActionMessage + await Protocol.SendMessageAsync(new HubActionMessage(HubAction.VccPortControlOn) { HubId = HubId, - Action = HubAction.VccPortControlOn, }); } @@ -64,10 +61,9 @@ public async Task VccPortControlOffAsync() { AssertIsConnected(); - await Protocol.SendMessageAsync(new HubActionMessage + await Protocol.SendMessageAsync(new HubActionMessage(HubAction.VccPortControlOff) { HubId = HubId, - Action = HubAction.VccPortControlOff, }); } @@ -79,10 +75,9 @@ public async Task ActivateBusyIndicatorAsync() { AssertIsConnected(); - await Protocol.SendMessageAsync(new HubActionMessage + await Protocol.SendMessageAsync(new HubActionMessage(HubAction.ActivateBusyIndication) { HubId = HubId, - Action = HubAction.ActivateBusyIndication, }); } @@ -94,10 +89,9 @@ public async Task ResetBusyIndicatorAsync() { AssertIsConnected(); - await Protocol.SendMessageAsync(new HubActionMessage + await Protocol.SendMessageAsync(new HubActionMessage(HubAction.ResetBusyIndication) { HubId = HubId, - Action = HubAction.ResetBusyIndication, }); } diff --git a/src/SharpBrick.PoweredUp/Hubs/Hub_Alerts.cs b/src/SharpBrick.PoweredUp/Hubs/Hub_Alerts.cs index b637e4e..5d2599f 100644 --- a/src/SharpBrick.PoweredUp/Hubs/Hub_Alerts.cs +++ b/src/SharpBrick.PoweredUp/Hubs/Hub_Alerts.cs @@ -19,21 +19,17 @@ private void SetupHubAlertObservable(IObservable upstreamMe public async Task EnableAlertNotificationAsync(HubAlert alert) { - await Protocol.SendMessageAsync(new HubAlertMessage() + await Protocol.SendMessageAsync(new HubAlertMessage(alert, HubAlertOperation.EnableUpdates) { HubId = HubId, - Operation = HubAlertOperation.EnableUpdates, - Alert = alert, }); } public async Task DisableAlertNotification(HubAlert alert) { - await Protocol.SendMessageAsync(new HubAlertMessage() + await Protocol.SendMessageAsync(new HubAlertMessage(alert, HubAlertOperation.DisableUpdates) { HubId = HubId, - Operation = HubAlertOperation.DisableUpdates, - Alert = alert, }); } } diff --git a/src/SharpBrick.PoweredUp/Hubs/Hub_Ports.cs b/src/SharpBrick.PoweredUp/Hubs/Hub_Ports.cs index 8790e10..7d6ec9b 100644 --- a/src/SharpBrick.PoweredUp/Hubs/Hub_Ports.cs +++ b/src/SharpBrick.PoweredUp/Hubs/Hub_Ports.cs @@ -12,7 +12,7 @@ namespace SharpBrick.PoweredUp { public abstract partial class Hub { - private ConcurrentDictionary _ports = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _ports = new(); public IObservable PortChangeObservable { get; private set; } @@ -33,7 +33,7 @@ private void SetupOnPortChangeObservable(IObservable upstre private async Task ExpectedDevicesCompletedAsync() => await PortChangeObservable - .Where(msg => Ports.All(p => p.ExpectedDevice == null || (p.ExpectedDevice != null && p.DeviceType == p.ExpectedDevice))) + .Where(msg => Ports.All(p => p.ExpectedDevice is null || (p.ExpectedDevice is not null && p.DeviceType == p.ExpectedDevice))) .FirstAsync() .GetAwaiter(); @@ -68,12 +68,9 @@ public async Task CreateVirtualPortAsync(byte portId1, byte portId2) throw new InvalidOperationException("One of the devices does not support logical synchronization"); } - var virtualPortAttachedMessage = await Protocol.SendMessageReceiveResultAsync(new VirtualPortSetupForConnectedMessage() + var virtualPortAttachedMessage = await Protocol.SendMessageReceiveResultAsync(new VirtualPortSetupForConnectedMessage(portId1, portId2) { HubId = HubId, - SubCommand = VirtualPortSubCommand.Connected, - PortAId = portId1, - PortBId = portId2, }, msg => msg.PortAId == portId1 && msg.PortBId == portId2); var port = OnHubAttachedVirtualIOMessage(virtualPortAttachedMessage); @@ -97,22 +94,21 @@ public async Task CloseVirtualPortAsync(byte virtualPortId) throw new ArgumentException("Port not present or not virtual", nameof(virtualPortId)); } - await Protocol.SendMessageAsync(new VirtualPortSetupForDisconnectedMessage() + await Protocol.SendMessageAsync(new VirtualPortSetupForDisconnectedMessage(virtualPortId) { HubId = HubId, - SubCommand = VirtualPortSubCommand.Connected, - PortId = virtualPortId, + //SubCommand = VirtualPortSubCommand.Connected, // TODO: was Connected before C# 9 migration, but is now (correctly?) disconnected }); } private void OnHubAttachedIOMessage(HubAttachedIOMessage hubAttachedIO) { - Port port = null; + Port port; switch (hubAttachedIO) { case HubAttachedIOForAttachedDeviceMessage attachedDeviceMessage: port = Port(attachedDeviceMessage.PortId); - if (port == null) + if (port is null) { _logger?.LogInformation($"Hub sent notification of attached device with port id '{hubAttachedIO.PortId}' but hub type '{GetType().Name}' is not configured for this port"); return; @@ -123,7 +119,7 @@ private void OnHubAttachedIOMessage(HubAttachedIOMessage hubAttachedIO) break; case HubAttachedIOForDetachedDeviceMessage detachedDeviceMessage: port = Port(detachedDeviceMessage.PortId); - if (port == null) + if (port is null) { _logger?.LogInformation($"Hub sent notification of detached device with port id '{hubAttachedIO.PortId}' but hub type '{GetType().Name}' is not configured for this port"); return; @@ -138,7 +134,7 @@ private void OnHubAttachedIOMessage(HubAttachedIOMessage hubAttachedIO) break; - // Note - HubAttachedIOForAttachedVirtualDeviceMessage is handled directly in OnHubChange not here + // Note - HubAttachedIOForAttachedVirtualDeviceMessage is handled directly in OnHubChange not here } } diff --git a/src/SharpBrick.PoweredUp/Hubs/Hub_Properties.cs b/src/SharpBrick.PoweredUp/Hubs/Hub_Properties.cs index 8a401c4..0dab631 100644 --- a/src/SharpBrick.PoweredUp/Hubs/Hub_Properties.cs +++ b/src/SharpBrick.PoweredUp/Hubs/Hub_Properties.cs @@ -96,11 +96,9 @@ public Task RequestHubPropertySingleUpdate(HubProperty property) { AssertIsConnected(); - return Protocol.SendMessageReceiveResultAsync(new HubPropertyMessage() + return Protocol.SendMessageReceiveResultAsync(new HubPropertyMessage(property, HubPropertyOperation.RequestUpdate) { HubId = HubId, - Property = property, - Operation = HubPropertyOperation.RequestUpdate }, msg => msg.Operation == HubPropertyOperation.Update && msg.Property == property); } @@ -117,11 +115,9 @@ public async Task SetupHubPropertyNotificationAsync(HubProperty property, bool e AssertIsConnected(); - await Protocol.SendMessageAsync(new HubPropertyMessage() + await Protocol.SendMessageAsync(new HubPropertyMessage(property, enabled ? HubPropertyOperation.EnableUpdates : HubPropertyOperation.DisableUpdates) { HubId = HubId, - Operation = enabled ? HubPropertyOperation.EnableUpdates : HubPropertyOperation.DisableUpdates, - Property = property, }); } @@ -137,12 +133,9 @@ public async Task SetHubPropertyAsync(HubProperty property, T value) AssertIsConnected(); - await Protocol.SendMessageAsync(new HubPropertyMessage() + await Protocol.SendMessageAsync(new HubPropertyMessage(property, HubPropertyOperation.Set, value) { HubId = HubId, - Operation = HubPropertyOperation.Set, - Property = property, - Payload = value, }); await RequestHubPropertySingleUpdate(property); @@ -159,11 +152,9 @@ public async Task ResetHubPropertyAsync(HubProperty property) AssertIsConnected(); - await Protocol.SendMessageAsync(new HubPropertyMessage() + await Protocol.SendMessageAsync(new HubPropertyMessage(property, HubPropertyOperation.Reset) { HubId = HubId, - Operation = HubPropertyOperation.Reset, - Property = property, }); await RequestHubPropertySingleUpdate(property); diff --git a/src/SharpBrick.PoweredUp/Hubs/IHubFactory.cs b/src/SharpBrick.PoweredUp/Hubs/IHubFactory.cs index c78113b..48aae83 100644 --- a/src/SharpBrick.PoweredUp/Hubs/IHubFactory.cs +++ b/src/SharpBrick.PoweredUp/Hubs/IHubFactory.cs @@ -1,5 +1,3 @@ -using System; - namespace SharpBrick.PoweredUp.Hubs { public interface IHubFactory diff --git a/src/SharpBrick.PoweredUp/Hubs/Port.cs b/src/SharpBrick.PoweredUp/Hubs/Port.cs index 5bb61ef..5a83af9 100644 --- a/src/SharpBrick.PoweredUp/Hubs/Port.cs +++ b/src/SharpBrick.PoweredUp/Hubs/Port.cs @@ -10,7 +10,7 @@ public class Port public DeviceType? ExpectedDevice { get; } public bool IsVirtual { get; } - public bool IsDeviceAttached => (_device != null); + public bool IsDeviceAttached => (_device is not null); public DeviceType? DeviceType { get; private set; } public Port(byte portId, string friendlyName, bool externalPort, DeviceType? expectedDevice = null, bool isVirtual = false) diff --git a/src/SharpBrick.PoweredUp/Hubs/TwoPortHandset.cs b/src/SharpBrick.PoweredUp/Hubs/TwoPortHandset.cs index a05f553..14ce6f3 100644 --- a/src/SharpBrick.PoweredUp/Hubs/TwoPortHandset.cs +++ b/src/SharpBrick.PoweredUp/Hubs/TwoPortHandset.cs @@ -32,7 +32,7 @@ public TwoPortHandset(ILegoWirelessProtocol protocol, IDeviceFactory deviceFacto HubProperty.HardwareNetworkId, HubProperty.PrimaryMacAddress, //HubProperty.SecondaryMacAddress, // unsupported on the two port handset - HubProperty.HardwareNetworkFamily, + HubProperty.HardwareNetworkFamily, }) { } diff --git a/src/SharpBrick.PoweredUp/PoweredUpHost.cs b/src/SharpBrick.PoweredUp/PoweredUpHost.cs index 7eb9ca7..16a941d 100644 --- a/src/SharpBrick.PoweredUp/PoweredUpHost.cs +++ b/src/SharpBrick.PoweredUp/PoweredUpHost.cs @@ -17,7 +17,7 @@ public class PoweredUpHost private readonly IPoweredUpBluetoothAdapter _bluetoothAdapter; public IServiceProvider ServiceProvider { get; } private readonly ILogger _logger; - private ConcurrentBag<(PoweredUpBluetoothDeviceInfo Info, Hub Hub)> _hubs = new ConcurrentBag<(PoweredUpBluetoothDeviceInfo, Hub)>(); + private readonly ConcurrentBag<(PoweredUpBluetoothDeviceInfo Info, Hub Hub)> _hubs = new(); public IEnumerable Hubs => _hubs.Select(i => i.Hub); @@ -47,7 +47,7 @@ public void Discover(Func onDiscovery, CancellationToken token = defa { try { - if (!_hubs.Any(i => i.Item1.BluetoothAddress == deviceInfo.BluetoothAddress)) + if (!_hubs.Any(i => i.Info.BluetoothAddress == deviceInfo.BluetoothAddress)) { var hub = CreateHubInBluetoothScope(deviceInfo.BluetoothAddress, hubFactory => hubFactory.CreateByBluetoothManufacturerData(deviceInfo.ManufacturerData)); diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/CommonMessageHeaderEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/CommonMessageHeaderEncoder.cs index f092f4c..a51cab1 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/CommonMessageHeaderEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/CommonMessageHeaderEncoder.cs @@ -7,11 +7,15 @@ public static class CommonMessageHeaderEncoder { public static void DecodeAndApply(in Span data, LegoWirelessMessage message) { - var (length, hubId, messageType, headerLength) = ParseCommonHeader(data); + var (length, hubId, messageType, _) = ParseCommonHeader(data); message.Length = length; message.HubId = hubId; - message.MessageType = (MessageType)messageType; + + if (message.MessageType != (MessageType)messageType) + { + throw new InvalidOperationException("Message Type does not match between data and decoded message"); + } } public static (ushort length, byte hubId, byte messageType, ushort headerLength) ParseCommonHeader(in Span data) diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/GenericErrorMessageEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/GenericErrorMessageEncoder.cs index 93da55b..1764ec8 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/GenericErrorMessageEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/GenericErrorMessageEncoder.cs @@ -9,13 +9,9 @@ public ushort CalculateContentLength(LegoWirelessMessage message) => throw new NotImplementedException(); public LegoWirelessMessage Decode(byte hubId, in Span data) - => new GenericErrorMessage() - { - CommandType = data[0], - ErrorCode = (ErrorCode)data[1], - }; + => new GenericErrorMessage(data[0], (ErrorCode)data[1]); public void Encode(LegoWirelessMessage message, in Span data) - => throw new NotImplementedException(); + => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubActionEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubActionEncoder.cs index b86fcfa..d264ec0 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubActionEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubActionEncoder.cs @@ -9,11 +9,11 @@ public ushort CalculateContentLength(LegoWirelessMessage message) => 1; public LegoWirelessMessage Decode(byte hubId, in Span data) - => new HubActionMessage() { Action = (HubAction)data[0] }; + => new HubActionMessage((HubAction)data[0]); public void Encode(LegoWirelessMessage message, in Span data) { - var hubActionMessage = message as HubActionMessage ?? throw new ArgumentException(nameof(message)); + var hubActionMessage = message as HubActionMessage ?? throw new ArgumentException("message is null or not HubActionMessage", nameof(message)); data[0] = (byte)hubActionMessage.Action; } diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAlertEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAlertEncoder.cs index f0c21f2..a06059c 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAlertEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAlertEncoder.cs @@ -7,16 +7,16 @@ public class HubAlertEncoder : IMessageContentEncoder { public ushort CalculateContentLength(LegoWirelessMessage message) { - var hubAlertMessage = message as HubAlertMessage ?? throw new ArgumentException(nameof(message)); + var hubAlertMessage = message as HubAlertMessage ?? throw new ArgumentException("message is null or not HubAlertMessage", nameof(message)); return (ushort)(hubAlertMessage.Operation == HubAlertOperation.Update ? 3 : 2); } public LegoWirelessMessage Decode(byte hubId, in Span data) - => new HubAlertMessage() { Alert = (HubAlert)data[0], Operation = (HubAlertOperation)data[1], DownstreamPayload = (byte)((data[1] == (byte)HubAlertOperation.Update) ? data[2] : 0) }; + => new HubAlertMessage((HubAlert)data[0], (HubAlertOperation)data[1], (byte)((data[1] == (byte)HubAlertOperation.Update) ? data[2] : 0)); public void Encode(LegoWirelessMessage message, in Span data) { - var hubAlertMessage = message as HubAlertMessage ?? throw new ArgumentException(nameof(message)); + var hubAlertMessage = message as HubAlertMessage ?? throw new ArgumentException("message is null or not HubAlertMessage", nameof(message)); data[0] = (byte)hubAlertMessage.Alert; data[1] = (byte)hubAlertMessage.Operation; diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAttachedIOEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAttachedIOEncoder.cs index b4635f6..159a2d1 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAttachedIOEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubAttachedIOEncoder.cs @@ -58,25 +58,22 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) HubAttachedIOEvent ev = (HubAttachedIOEvent)data[1]; HubAttachedIOMessage message = ev switch { - HubAttachedIOEvent.AttachedIO => new HubAttachedIOForAttachedDeviceMessage() - { - IOTypeId = (DeviceType)BitConverter.ToUInt16(data.Slice(2, 2)), - HardwareRevision = VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(4, 4))), - SoftwareRevision = VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(8, 4))), - }, - HubAttachedIOEvent.AttachedVirtualIO => new HubAttachedIOForAttachedVirtualDeviceMessage() - { - IOTypeId = (DeviceType)BitConverter.ToUInt16(data.Slice(2, 2)), - PortAId = data[4], - PortBId = data[5], - }, - HubAttachedIOEvent.DetachedIO => new HubAttachedIOForDetachedDeviceMessage(), + HubAttachedIOEvent.AttachedIO => new HubAttachedIOForAttachedDeviceMessage( + portId, + (DeviceType)BitConverter.ToUInt16(data.Slice(2, 2)), + VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(4, 4))), + VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(8, 4))) + ), + HubAttachedIOEvent.AttachedVirtualIO => new HubAttachedIOForAttachedVirtualDeviceMessage( + portId, + (DeviceType)BitConverter.ToUInt16(data.Slice(2, 2)), + data[4], + data[5] + ), + HubAttachedIOEvent.DetachedIO => new HubAttachedIOForDetachedDeviceMessage(portId), _ => throw new NotImplementedException(), }; - message.PortId = portId; - message.Event = ev; - return message; } diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubPropertiesEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubPropertiesEncoder.cs index 642912d..341585f 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/HubPropertiesEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/HubPropertiesEncoder.cs @@ -6,7 +6,7 @@ namespace SharpBrick.PoweredUp.Protocol.Formatter public class HubPropertiesEncoder : IMessageContentEncoder { public ushort CalculateContentLength(LegoWirelessMessage message) - => CalculateMessageLength(message as HubPropertyMessage ?? throw new ArgumentException(nameof(message))); + => CalculateMessageLength(message as HubPropertyMessage ?? throw new ArgumentException("No message provided", nameof(message))); public ushort CalculateMessageLength(HubPropertyMessage message) { @@ -46,7 +46,7 @@ public ushort CalculateMessageLength(HubPropertyMessage message) } public void Encode(LegoWirelessMessage message, in Span data) - => Encode(message as HubPropertyMessage ?? throw new ArgumentException(nameof(message)), data); + => Encode(message as HubPropertyMessage ?? throw new ArgumentException("No message provided", nameof(message)), data); public void Encode(HubPropertyMessage message, Span data) { @@ -61,11 +61,11 @@ public void Encode(HubPropertyMessage message, Span data) byte[] stringAsBytes = Encoding.ASCII.GetBytes(msg.Payload); stringAsBytes.CopyTo(data.Slice(2, stringAsBytes.Length)); break; - case HubPropertyMessage msg: + case HubPropertyMessage: throw new NotImplementedException(); //data[2] = (byte)(msg.Payload ? 0x01 : 0x00); - case HubPropertyMessage msg: + case HubPropertyMessage: throw new NotImplementedException(); - case HubPropertyMessage msg: + case HubPropertyMessage: throw new NotImplementedException(); //data[2] = (byte)msg.Payload; case HubPropertyMessage msg: data[2] = (byte)msg.Payload; @@ -79,30 +79,30 @@ public void Encode(HubPropertyMessage message, Span data) public LegoWirelessMessage Decode(byte hubId, in Span data) { + var property = (HubProperty)data[0]; + var operation = (HubPropertyOperation)data[1]; + HubPropertyMessage message = (HubProperty)data[0] switch { - HubProperty.AdvertisingName => new HubPropertyMessage() { Payload = Encoding.ASCII.GetString(data.Slice(2)) }, - HubProperty.Button => new HubPropertyMessage() { Payload = (data[2] == 0x01) }, - HubProperty.FwVersion => new HubPropertyMessage() { Payload = VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(2, 4))) }, - HubProperty.HwVersion => new HubPropertyMessage() { Payload = VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(2, 4))) }, - HubProperty.Rssi => new HubPropertyMessage() { Payload = unchecked((sbyte)data[2]) }, - HubProperty.BatteryVoltage => new HubPropertyMessage() { Payload = data[2] }, - HubProperty.BatteryType => new HubPropertyMessage() { Payload = (BatteryType)data[2] }, - HubProperty.ManufacturerName => new HubPropertyMessage() { Payload = Encoding.ASCII.GetString(data.Slice(2)) }, - HubProperty.RadioFirmwareVersion => new HubPropertyMessage() { Payload = Encoding.ASCII.GetString(data.Slice(2)) }, - HubProperty.LegoWirelessProtocolVersion => new HubPropertyMessage() { Payload = LwpVersionNumberEncoder.Decode(data[2], data[3]) }, - HubProperty.SystemTypeId => new HubPropertyMessage() { Payload = (SystemType)data[2] }, - HubProperty.HardwareNetworkId => new HubPropertyMessage() { Payload = data[2] }, - HubProperty.PrimaryMacAddress => new HubPropertyMessage() { Payload = data.Slice(2, 6).ToArray() }, - HubProperty.SecondaryMacAddress => new HubPropertyMessage() { Payload = data.Slice(2, 6).ToArray() }, - HubProperty.HardwareNetworkFamily => new HubPropertyMessage() { Payload = data[2] }, + HubProperty.AdvertisingName => new HubPropertyMessage(property, operation, Encoding.ASCII.GetString(data[2..])), + HubProperty.Button => new HubPropertyMessage(property, operation, (data[2] == 0x01)), + HubProperty.FwVersion => new HubPropertyMessage(property, operation, VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(2, 4)))), + HubProperty.HwVersion => new HubPropertyMessage(property, operation, VersionNumberEncoder.Decode(BitConverter.ToInt32(data.Slice(2, 4)))), + HubProperty.Rssi => new HubPropertyMessage(property, operation, unchecked((sbyte)data[2])), + HubProperty.BatteryVoltage => new HubPropertyMessage(property, operation, data[2]), + HubProperty.BatteryType => new HubPropertyMessage(property, operation, (BatteryType)data[2]), + HubProperty.ManufacturerName => new HubPropertyMessage(property, operation, Encoding.ASCII.GetString(data[2..])), + HubProperty.RadioFirmwareVersion => new HubPropertyMessage(property, operation, Encoding.ASCII.GetString(data[2..])), + HubProperty.LegoWirelessProtocolVersion => new HubPropertyMessage(property, operation, LwpVersionNumberEncoder.Decode(data[2], data[3])), + HubProperty.SystemTypeId => new HubPropertyMessage(property, operation, (SystemType)data[2]), + HubProperty.HardwareNetworkId => new HubPropertyMessage(property, operation, data[2]), + HubProperty.PrimaryMacAddress => new HubPropertyMessage(property, operation, data.Slice(2, 6).ToArray()), + HubProperty.SecondaryMacAddress => new HubPropertyMessage(property, operation, data.Slice(2, 6).ToArray()), + HubProperty.HardwareNetworkFamily => new HubPropertyMessage(property, operation, data[2]), _ => throw new InvalidOperationException(), }; - message.Property = (HubProperty)data[0]; - message.Operation = (HubPropertyOperation)data[1]; - return message; } diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/MessageEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/MessageEncoder.cs index 04cf500..fb5f01a 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/MessageEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/MessageEncoder.cs @@ -10,25 +10,25 @@ public static byte[] Encode(LegoWirelessMessage message, ProtocolKnowledge knowl { var messageType = message switch { - HubPropertyMessage msg => MessageType.HubProperties, - HubActionMessage msg => MessageType.HubActions, - HubAlertMessage msg => MessageType.HubAlerts, - HubAttachedIOMessage msg => MessageType.HubAttachedIO, - GenericErrorMessage msg => MessageType.GenericErrorMessages, - - PortInformationRequestMessage msg => MessageType.PortInformationRequest, - PortModeInformationRequestMessage msg => MessageType.PortModeInformationRequest, - PortInputFormatSetupSingleMessage msg => MessageType.PortInputFormatSetupSingle, - PortInputFormatSetupCombinedModeMessage msg => MessageType.PortInputFormatSetupCombinedMode, - PortInformationMessage msg => MessageType.PortInformation, - PortModeInformationMessage msg => MessageType.PortModeInformation, - PortValueSingleMessage msg => MessageType.PortValueSingle, - PortValueCombinedModeMessage msg => MessageType.PortValueCombinedMode, - PortInputFormatSingleMessage msg => MessageType.PortInputFormatSingle, - PortInputFormatCombinedModeMessage msg => MessageType.PortInputFormatCombinedMode, - VirtualPortSetupMessage msg => MessageType.VirtualPortSetup, - PortOutputCommandMessage msg => MessageType.PortOutputCommand, - PortOutputCommandFeedbackMessage msg => MessageType.PortOutputCommandFeedback, + HubPropertyMessage => MessageType.HubProperties, + HubActionMessage => MessageType.HubActions, + HubAlertMessage => MessageType.HubAlerts, + HubAttachedIOMessage => MessageType.HubAttachedIO, + GenericErrorMessage => MessageType.GenericErrorMessages, + + PortInformationRequestMessage => MessageType.PortInformationRequest, + PortModeInformationRequestMessage => MessageType.PortModeInformationRequest, + PortInputFormatSetupSingleMessage => MessageType.PortInputFormatSetupSingle, + PortInputFormatSetupCombinedModeMessage => MessageType.PortInputFormatSetupCombinedMode, + PortInformationMessage => MessageType.PortInformation, + PortModeInformationMessage => MessageType.PortModeInformation, + PortValueSingleMessage => MessageType.PortValueSingle, + PortValueCombinedModeMessage => MessageType.PortValueCombinedMode, + PortInputFormatSingleMessage => MessageType.PortInputFormatSingle, + PortInputFormatCombinedModeMessage => MessageType.PortInputFormatCombinedMode, + VirtualPortSetupMessage => MessageType.VirtualPortSetup, + PortOutputCommandMessage => MessageType.PortOutputCommand, + PortOutputCommandFeedbackMessage => MessageType.PortOutputCommandFeedback, _ => throw new NotImplementedException(), }; @@ -41,7 +41,7 @@ public static byte[] Encode(LegoWirelessMessage message, ProtocolKnowledge knowl byte[] data = new byte[commonHeaderLength + contentLength]; CommonMessageHeaderEncoder.Encode(contentLength, message.HubId, messageType, data.AsSpan().Slice(0, commonHeaderLength)); - encoder.Encode(message, data.AsSpan().Slice(commonHeaderLength)); + encoder.Encode(message, data.AsSpan()[commonHeaderLength..]); return data; } @@ -77,23 +77,27 @@ public static LegoWirelessMessage Decode(in Span data, ProtocolKnowledge k var encoder = CreateEncoder((MessageType)messageType, knowledge); - var content = data.Slice(headerLength); + var content = data[headerLength..]; LegoWirelessMessage result; - if (encoder != null) + if (encoder is not null) { var message = encoder?.Decode(hubId, content); message.Length = length; message.HubId = hubId; - message.MessageType = (MessageType)messageType; + + if (message.MessageType != (MessageType)messageType) + { + throw new InvalidOperationException("type in data does not match message type"); + } result = message; } else { - result = new UnknownMessage() { Data = data.ToArray() }; + result = new UnknownMessage(messageType, data.ToArray()); } return result; diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationEncoder.cs index 75699ed..6d0698a 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationEncoder.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using SharpBrick.PoweredUp.Protocol.Messages; namespace SharpBrick.PoweredUp.Protocol.Formatter @@ -19,21 +18,17 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) switch (informationType) { case PortInformationType.ModeInfo: - result = new PortInformationForModeInfoMessage() - { - PortId = portId, - InformationType = informationType, - - // capabilities - OutputCapability = (data[2] & 0x01) == 0x01, // seen from hub - InputCapability = (data[2] & 0x02) == 0x02, // seen from hub - LogicalCombinableCapability = (data[2] & 0x04) == 0x04, - LogicalSynchronizableCapability = (data[2] & 0x08) == 0x08, - - TotalModeCount = data[3], - InputModes = BitConverter.ToUInt16(data.Slice(4, 2)), - OutputModes = BitConverter.ToUInt16(data.Slice(6, 2)), - }; + result = new PortInformationForModeInfoMessage( + portId, + informationType, + OutputCapability: (data[2] & 0x01) == 0x01, // seen from hub + InputCapability: (data[2] & 0x02) == 0x02, // seen from hub + LogicalCombinableCapability: (data[2] & 0x04) == 0x04, + LogicalSynchronizableCapability: (data[2] & 0x08) == 0x08, + TotalModeCount: data[3], + InputModes: BitConverter.ToUInt16(data.Slice(4, 2)), + OutputModes: BitConverter.ToUInt16(data.Slice(6, 2)) + ); break; case PortInformationType.PossibleModeCombinations: @@ -45,13 +40,11 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) combinations[idx] = BitConverter.ToUInt16(data.Slice(2 + idx * 2, 2)); } - result = new PortInformationForPossibleModeCombinationsMessage() - { - PortId = portId, - InformationType = informationType, - - ModeCombinations = combinations, - }; + result = new PortInformationForPossibleModeCombinationsMessage( + portId, + informationType, + combinations + ); break; } diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationRequestEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationRequestEncoder.cs index 4447c30..451c83c 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationRequestEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInformationRequestEncoder.cs @@ -12,7 +12,7 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) => throw new NotImplementedException(); public void Encode(LegoWirelessMessage message, in Span data) - => Encode(message as PortInformationRequestMessage ?? throw new ArgumentException(nameof(message)), data); + => Encode(message as PortInformationRequestMessage ?? throw new ArgumentException("No message provided", nameof(message)), data); public void Encode(PortInformationRequestMessage message, in Span data) { diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatCombinedModeEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatCombinedModeEncoder.cs index a8e65fc..0131611 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatCombinedModeEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatCombinedModeEncoder.cs @@ -13,15 +13,14 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) { ushort bitMask = BitConverter.ToUInt16(data.Slice(2, 2)); - return new PortInputFormatCombinedModeMessage() - { - PortId = data[0], - UsedCombinationIndex = (byte)(data[1] & 0b0000_0111), - MultiUpdateEnabled = (byte)(data[1] & 0b1000_0000) > 0, - ConfiguredModeDataSetIndex = Enumerable.Range(0, 16).Select(pos => + return new PortInputFormatCombinedModeMessage( + PortId: data[0], + UsedCombinationIndex: (byte)(data[1] & 0b0000_0111), + MultiUpdateEnabled: (byte)(data[1] & 0b1000_0000) > 0, + ConfiguredModeDataSetIndex: Enumerable.Range(0, 16).Select(pos => (bitMask & (0x01 << pos)) > 0 ? pos : -1 - ).Where(mdi => mdi >= 0).ToArray(), - }; + ).Where(mdi => mdi >= 0).ToArray() + ); } public void Encode(LegoWirelessMessage message, in Span data) diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoder.cs index 32768d7..49f032c 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoder.cs @@ -12,7 +12,7 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) => throw new NotImplementedException(); public void Encode(LegoWirelessMessage message, in Span data) - => Encode(message as PortInputFormatSetupCombinedModeMessage ?? throw new ArgumentException(nameof(message)), data); + => Encode(message as PortInputFormatSetupCombinedModeMessage ?? throw new ArgumentException("Message not provided", nameof(message)), data); public void Encode(PortInputFormatSetupCombinedModeMessage message, in Span data) { data[0] = message.PortId; diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupSingleEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupSingleEncoder.cs index 4d65a05..3c04d6c 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupSingleEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupSingleEncoder.cs @@ -13,7 +13,7 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) => throw new NotImplementedException(); public void Encode(LegoWirelessMessage message, in Span data) - => Encode(message as PortInputFormatSetupSingleMessage ?? throw new ArgumentException(nameof(message)), data); + => Encode(message as PortInputFormatSetupSingleMessage ?? throw new ArgumentException("message is null or not PortInputFormatSetupSingleMessage", nameof(message)), data); public void Encode(PortInputFormatSetupSingleMessage message, in Span data) { data[0] = message.PortId; diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSingleEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSingleEncoder.cs index d028410..2b65f83 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSingleEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSingleEncoder.cs @@ -20,12 +20,11 @@ public void Encode(PortInputFormatSingleMessage message, in Span data) } public LegoWirelessMessage Decode(byte hubId, in Span data) - => new PortInputFormatSingleMessage() - { - PortId = data[0], - ModeIndex = data[1], - DeltaInterval = BitConverter.ToUInt32(data.Slice(2, 4)), - NotificationEnabled = (data[6] == 0x01), - }; + => new PortInputFormatSingleMessage( + PortId: data[0], + ModeIndex: data[1], + DeltaInterval: BitConverter.ToUInt32(data.Slice(2, 4)), + NotificationEnabled: (data[6] == 0x01) + ); } } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationEncoder.cs index 46e19b9..3e66364 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationEncoder.cs @@ -14,87 +14,52 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) var portId = data[0]; var mode = data[1]; var informationType = (PortModeInformationType)data[2]; - var innerData = data.Slice(3); + var payload = data[3..]; var message = informationType switch { - PortModeInformationType.Name => DecodeName(innerData), - PortModeInformationType.Raw => DecodeRaw(innerData), - PortModeInformationType.Pct => DecodePct(innerData), - PortModeInformationType.SI => DecodeSI(innerData), - PortModeInformationType.Symbol => DecodeSymbol(innerData), - PortModeInformationType.Mapping => DecodeMapping(innerData), + PortModeInformationType.Name => new PortModeInformationForNameMessage(portId, mode, Encoding.ASCII.GetString(payload.Slice(0, payload.IndexOf(0x00)))), + PortModeInformationType.Raw => new PortModeInformationForRawMessage(portId, mode, RawMin: BitConverter.ToSingle(payload.Slice(0, 4)), RawMax: BitConverter.ToSingle(payload.Slice(4, 4))), + PortModeInformationType.Pct => new PortModeInformationForPctMessage(portId, mode, PctMin: BitConverter.ToSingle(payload.Slice(0, 4)), PctMax: BitConverter.ToSingle(payload.Slice(4, 4))), + PortModeInformationType.SI => new PortModeInformationForSIMessage(portId, mode, SIMin: BitConverter.ToSingle(payload.Slice(0, 4)), SIMax: BitConverter.ToSingle(payload.Slice(4, 4))), + PortModeInformationType.Symbol => new PortModeInformationForSymbolMessage(portId, mode, Symbol: Encoding.ASCII.GetString(payload.Slice(0, payload.IndexOf(0x00)))), + PortModeInformationType.Mapping => DecodeMapping(portId, mode, payload), PortModeInformationType.InternalUse => throw new NotImplementedException(), PortModeInformationType.MotorBias => throw new NotImplementedException(), PortModeInformationType.CapabilityBits => throw new NotImplementedException(), - PortModeInformationType.ValueFormat => DecodeValueFormat(innerData), + PortModeInformationType.ValueFormat => DecodeValueFormat(portId, mode, payload), _ => throw new NotImplementedException(), }; - message.PortId = portId; - message.Mode = mode; - message.InformationType = informationType; - return message; } - private PortModeInformationMessage DecodeName(in Span data) - => new PortModeInformationForNameMessage() - { - Name = Encoding.ASCII.GetString(data.Slice(0, data.IndexOf(0x00))), - }; - - private PortModeInformationMessage DecodeRaw(in Span data) - => new PortModeInformationForRawMessage() - { - RawMin = BitConverter.ToSingle(data.Slice(0, 4)), - RawMax = BitConverter.ToSingle(data.Slice(4, 4)), - }; - - private PortModeInformationMessage DecodePct(in Span data) - => new PortModeInformationForPctMessage() - { - PctMin = BitConverter.ToSingle(data.Slice(0, 4)), - PctMax = BitConverter.ToSingle(data.Slice(4, 4)), - }; - - private PortModeInformationMessage DecodeSI(in Span data) - => new PortModeInformationForSIMessage() - { - SIMin = BitConverter.ToSingle(data.Slice(0, 4)), - SIMax = BitConverter.ToSingle(data.Slice(4, 4)), - }; - - private PortModeInformationMessage DecodeSymbol(in Span data) - => new PortModeInformationForSymbolMessage() - { - Symbol = Encoding.ASCII.GetString(data.Slice(0, data.IndexOf(0x00))), - }; + private PortModeInformationMessage DecodeMapping(byte portId, byte mode, in Span data) + => new PortModeInformationForMappingMessage( + portId, + mode, + InputSupportsNull: (data[0] & 0b1000_0000) > 0, + InputSupportFunctionalMapping20: (data[0] & 0b0100_0000) > 0, + InputAbsolute: (data[0] & 0b0001_0000) > 0, + InputRelative: (data[0] & 0b0000_1000) > 0, + InputDiscrete: (data[0] & 0b0000_0100) > 0, - private PortModeInformationMessage DecodeMapping(in Span data) - => new PortModeInformationForMappingMessage() - { - InputSupportsNull = (data[0] & 0b1000_0000) > 0, - InputSupportFunctionalMapping20 = (data[0] & 0b0100_0000) > 0, - InputAbsolute = (data[0] & 0b0001_0000) > 0, - InputRelative = (data[0] & 0b0000_1000) > 0, - InputDiscrete = (data[0] & 0b0000_0100) > 0, - - OutputSupportsNull = (data[1] & 0b1000_0000) > 0, - OutputSupportFunctionalMapping20 = (data[1] & 0b0100_0000) > 0, - OutputAbsolute = (data[1] & 0b0001_0000) > 0, - OutputRelative = (data[1] & 0b0000_1000) > 0, - OutputDiscrete = (data[1] & 0b0000_0100) > 0, - }; + OutputSupportsNull: (data[1] & 0b1000_0000) > 0, + OutputSupportFunctionalMapping20: (data[1] & 0b0100_0000) > 0, + OutputAbsolute: (data[1] & 0b0001_0000) > 0, + OutputRelative: (data[1] & 0b0000_1000) > 0, + OutputDiscrete: (data[1] & 0b0000_0100) > 0 + ); - private PortModeInformationMessage DecodeValueFormat(in Span data) - => new PortModeInformationForValueFormatMessage() - { - NumberOfDatasets = data[0], - DatasetType = (PortModeInformationDataType)data[1], - TotalFigures = data[2], - Decimals = data[3], - }; + private PortModeInformationMessage DecodeValueFormat(byte portId, byte mode, in Span data) + => new PortModeInformationForValueFormatMessage( + portId, + mode, + NumberOfDatasets: data[0], + DatasetType: (PortModeInformationDataType)data[1], + TotalFigures: data[2], + Decimals: data[3] + ); public void Encode(LegoWirelessMessage message, in Span data) => throw new NotImplementedException(); diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationRequestEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationRequestEncoder.cs index 515c40a..a744c9b 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationRequestEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortModeInformationRequestEncoder.cs @@ -12,7 +12,7 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) => throw new NotImplementedException(); public void Encode(LegoWirelessMessage message, in Span data) - => Encode(message as PortModeInformationRequestMessage ?? throw new ArgumentException(nameof(message)), data); + => Encode(message as PortModeInformationRequestMessage ?? throw new ArgumentException("No message provided", nameof(message)), data); public void Encode(PortModeInformationRequestMessage message, in Span data) { diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandEncoder.cs index 0f20da3..79e495c 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandEncoder.cs @@ -10,27 +10,27 @@ public ushort CalculateContentLength(LegoWirelessMessage message) { PortOutputCommandMessage portOutputMessage => 3 + portOutputMessage switch { - PortOutputCommandStartPower2Message msg => 2, - PortOutputCommandSetAccTimeMessage msg => 3, - PortOutputCommandSetDecTimeMessage msg => 3, - PortOutputCommandStartSpeedMessage msg => 3, - PortOutputCommandStartSpeed2Message msg => 4, - PortOutputCommandStartSpeedForTimeMessage msg => 6, - PortOutputCommandStartSpeedForTime2Message msg => 7, - PortOutputCommandStartSpeedForDegreesMessage msg => 8, - PortOutputCommandStartSpeedForDegrees2Message msg => 9, - PortOutputCommandGotoAbsolutePositionMessage msg => 8, - PortOutputCommandGotoAbsolutePosition2Message msg => 12, + PortOutputCommandStartPower2Message => 2, + PortOutputCommandSetAccTimeMessage => 3, + PortOutputCommandSetDecTimeMessage => 3, + PortOutputCommandStartSpeedMessage => 3, + PortOutputCommandStartSpeed2Message => 4, + PortOutputCommandStartSpeedForTimeMessage => 6, + PortOutputCommandStartSpeedForTime2Message => 7, + PortOutputCommandStartSpeedForDegreesMessage => 8, + PortOutputCommandStartSpeedForDegrees2Message => 9, + PortOutputCommandGotoAbsolutePositionMessage => 8, + PortOutputCommandGotoAbsolutePosition2Message => 12, PortOutputCommandWriteDirectModeDataMessage directWriteModeDataMessage => 1 + directWriteModeDataMessage switch { GenericWriteDirectModeDataMessage msg => msg.Data.Length, - PortOutputCommandStartPowerMessage msg => 1, - PortOutputCommandSetRgbColorNoMessage msg => 1, - PortOutputCommandSetRgbColorNo2Message msg => 3, - PortOutputCommandPresetEncoderMessage msg => 4, - PortOutputCommandTiltImpactPresetMessage msg => 4, - PortOutputCommandTiltConfigImpactMessage msg => 2, - PortOutputCommandTiltConfigOrientationMessage msg => 1, + PortOutputCommandStartPowerMessage => 1, + PortOutputCommandSetRgbColorNoMessage => 1, + PortOutputCommandSetRgbColorNo2Message => 3, + PortOutputCommandPresetEncoderMessage => 4, + PortOutputCommandTiltImpactPresetMessage => 4, + PortOutputCommandTiltConfigImpactMessage => 2, + PortOutputCommandTiltConfigOrientationMessage => 1, _ => throw new NotSupportedException(), }, @@ -136,7 +136,7 @@ public void Encode(PortOutputCommandMessage message, in Span data) switch (directWriteModeDataMessage) { case GenericWriteDirectModeDataMessage msg: - msg.Data.CopyTo(data.Slice(4, data.Length - 4)); + msg.Data.CopyTo(data[4..]); break; case PortOutputCommandStartPowerMessage msg: data[4] = (byte)msg.Power; diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandFeedbackEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandFeedbackEncoder.cs index 01ff835..4698924 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandFeedbackEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortOutputCommandFeedbackEncoder.cs @@ -17,20 +17,13 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) while (remainingSlice.Length >= 2) { - var feedback = new PortOutputCommandFeedback() - { - PortId = remainingSlice[0], - Feedback = (PortFeedback)remainingSlice[1], - }; + var feedback = new PortOutputCommandFeedback(remainingSlice[0], (PortFeedback)remainingSlice[1]); result.Add(feedback); - remainingSlice = remainingSlice.Slice(2); + remainingSlice = remainingSlice[2..]; } - return new PortOutputCommandFeedbackMessage() - { - Feedbacks = result.ToArray(), - }; + return new PortOutputCommandFeedbackMessage(result.ToArray()); } public void Encode(LegoWirelessMessage message, in Span data) diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueCombinedModeEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueCombinedModeEncoder.cs index 408df40..4a50d8b 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueCombinedModeEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueCombinedModeEncoder.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using SharpBrick.PoweredUp.Protocol.Knowledge; using SharpBrick.PoweredUp.Protocol.Messages; @@ -40,7 +39,7 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) .ToDictionary(pmi => pmi.ModeIndex, pmi => new byte[pmi.NumberOfDatasets * PortValueSingleEncoder.GetLengthOfDataType(pmi)]); var currentDataSetInMessageIndex = 0; - var remainingSlice = data.Slice(3); + var remainingSlice = data[3..]; while (remainingSlice.Length > 0) { @@ -56,27 +55,17 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) var dataSlice = remainingSlice.Slice(0, lengthOfDataType); // copy data into buffer position - dataSlice.CopyTo(dataBuffers[modeInfo.ModeIndex].AsSpan().Slice(modeDataSet.DataSet * lengthOfDataType)); + dataSlice.CopyTo(dataBuffers[modeInfo.ModeIndex].AsSpan()[(modeDataSet.DataSet * lengthOfDataType)..]); - remainingSlice = remainingSlice.Slice(lengthOfDataType); + remainingSlice = remainingSlice[lengthOfDataType..]; } - return new PortValueCombinedModeMessage() - { - PortId = port, - Data = influencedModes - .Select(mode => - { - var value = PortValueSingleEncoder.CreatPortValueData(mode, dataBuffers[mode.ModeIndex]); - - value.PortId = mode.PortId; - value.ModeIndex = mode.ModeIndex; - value.DataType = mode.DatasetType; - - return value; - }) - .ToArray(), - }; + return new PortValueCombinedModeMessage( + port, + influencedModes + .Select(mode => PortValueSingleEncoder.CreatPortValueData(mode, dataBuffers[mode.ModeIndex])) + .ToArray() + ); } public void Encode(LegoWirelessMessage message, in Span data) diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueSingleEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueSingleEncoder.cs index 7e1f8c3..e1d1f3f 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueSingleEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/PortValueSingleEncoder.cs @@ -39,18 +39,11 @@ public LegoWirelessMessage Decode(byte hubId, in Span data) var value = PortValueSingleEncoder.CreatPortValueData(modeInfo, dataSlice); - value.PortId = port; - value.DataType = modeInfo.DatasetType; - value.ModeIndex = mode; - result.Add(value); - remainingSlice = remainingSlice.Slice(1 + lengthOfDataType * modeInfo.NumberOfDatasets); + remainingSlice = remainingSlice[(1 + lengthOfDataType * modeInfo.NumberOfDatasets)..]; } - return new PortValueSingleMessage() - { - Data = result.ToArray(), - }; + return new PortValueSingleMessage(result.ToArray()); } internal static int GetLengthOfDataType(PortModeInfo modeInfo) @@ -85,12 +78,14 @@ internal static PortValueData CreatePortValueDataSByte(PortModeInfo modeI true => new sbyte[rawValues.Length], }; - return new PortValueData() - { - InputValues = rawValues, - SIInputValues = siValues, - PctInputValues = pctValues, - }; + return new PortValueData( + PortId: modeInfo.PortId, + ModeIndex: modeInfo.ModeIndex, + DataType: modeInfo.DatasetType, + InputValues: rawValues, + SIInputValues: siValues, + PctInputValues: pctValues + ); } internal static PortValueData CreatePortValueDataInt16(PortModeInfo modeInfo, in Span dataSlice) @@ -104,12 +99,14 @@ internal static PortValueData CreatePortValueDataInt16(PortModeInfo modeI true => new short[rawValues.Length], }; - return new PortValueData() - { - InputValues = rawValues, - SIInputValues = siValues, - PctInputValues = pctValues, - }; + return new PortValueData( + PortId: modeInfo.PortId, + ModeIndex: modeInfo.ModeIndex, + DataType: modeInfo.DatasetType, + InputValues: rawValues, + SIInputValues: siValues, + PctInputValues: pctValues + ); } internal static PortValueData CreatePortValueDataInt32(PortModeInfo modeInfo, in Span dataSlice) @@ -129,12 +126,14 @@ internal static PortValueData CreatePortValueDataInt32(PortModeInfo modeInf _ => rawValues.Select(rv => Scale(rv, modeInfo.RawMin, modeInfo.RawMax, modeInfo.PctMin, modeInfo.PctMax)).Select(f => Convert.ToInt32(f)).ToArray(), }; - return new PortValueData() - { - InputValues = rawValues, - SIInputValues = siValues, - PctInputValues = pctValues, - }; + return new PortValueData( + PortId: modeInfo.PortId, + ModeIndex: modeInfo.ModeIndex, + DataType: modeInfo.DatasetType, + InputValues: rawValues, + SIInputValues: siValues, + PctInputValues: pctValues + ); } internal static PortValueData CreatePortValueDataSingle(PortModeInfo modeInfo, in Span dataSlice) @@ -148,12 +147,14 @@ internal static PortValueData CreatePortValueDataSingle(PortModeInfo mode true => new float[rawValues.Length], }; - return new PortValueData() - { - InputValues = rawValues, - SIInputValues = siValues, - PctInputValues = pctValues, - }; + return new PortValueData( + PortId: modeInfo.PortId, + ModeIndex: modeInfo.ModeIndex, + DataType: modeInfo.DatasetType, + InputValues: rawValues, + SIInputValues: siValues, + PctInputValues: pctValues + ); } internal static float Scale(float value, float rawMin, float rawMax, float min, float max) diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/VersionNumberEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/VersionNumberEncoder.cs index 8a43a40..fb1b514 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/VersionNumberEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/VersionNumberEncoder.cs @@ -22,7 +22,7 @@ public static int Encode(Version version) { if (version.Major > 7 || version.Minor > 15 || version.Build > 99 || version.Revision > 9999) { - throw new ArgumentException(nameof(version)); + throw new ArgumentException("version is not valid", nameof(version)); } return (version.Major << 28) + diff --git a/src/SharpBrick.PoweredUp/Protocol/Formatter/VirtualPortSetupEncoder.cs b/src/SharpBrick.PoweredUp/Protocol/Formatter/VirtualPortSetupEncoder.cs index 9113c45..ec990cf 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Formatter/VirtualPortSetupEncoder.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Formatter/VirtualPortSetupEncoder.cs @@ -8,8 +8,8 @@ public class VirtualPortSetupEncoder : IMessageContentEncoder public ushort CalculateContentLength(LegoWirelessMessage message) => message switch { - VirtualPortSetupForConnectedMessage msg => 3, - VirtualPortSetupForDisconnectedMessage msg => 2, + VirtualPortSetupForConnectedMessage => 3, + VirtualPortSetupForDisconnectedMessage => 2, _ => throw new NotSupportedException(), }; diff --git a/src/SharpBrick.PoweredUp/Protocol/ILegoWirelessProtocolExtensions.cs b/src/SharpBrick.PoweredUp/Protocol/ILegoWirelessProtocolExtensions.cs index 8b24241..9611063 100644 --- a/src/SharpBrick.PoweredUp/Protocol/ILegoWirelessProtocolExtensions.cs +++ b/src/SharpBrick.PoweredUp/Protocol/ILegoWirelessProtocolExtensions.cs @@ -12,7 +12,7 @@ public static async Task SendMessageReceiveResultAsync() - .Where(resultMessage => filter == null || filter(resultMessage)) + .Where(resultMessage => filter is null || filter(resultMessage)) .FirstAsync() .GetAwaiter(); // make sure the subscription is present at the moment the message is sent. diff --git a/src/SharpBrick.PoweredUp/Protocol/Knowledge/KnowledgeManager.cs b/src/SharpBrick.PoweredUp/Protocol/Knowledge/KnowledgeManager.cs index 5303c1f..0cbacab 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Knowledge/KnowledgeManager.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Knowledge/KnowledgeManager.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; using SharpBrick.PoweredUp.Devices; using SharpBrick.PoweredUp.Protocol.Formatter; using SharpBrick.PoweredUp.Protocol.Messages; @@ -184,25 +183,32 @@ private static void AddCachePortAndPortModeInformation(DeviceType type, Version { var device = deviceFactory.Create(type); - if (device != null) + if (device is not null) { foreach (var message in device.GetStaticPortInfoMessages(hardwareRevision, softwareRevision, hub.SystemType).Select(b => MessageEncoder.Decode(b, null))) { - switch (message) + var messageToProcess = message; + switch (messageToProcess) { case PortModeInformationMessage pmim: - pmim.HubId = port.HubId; - pmim.PortId = port.PortId; + messageToProcess = pmim with + { + HubId = port.HubId, + PortId = port.PortId, + }; break; case PortInformationMessage pim: - pim.HubId = port.HubId; - pim.PortId = port.PortId; + messageToProcess = pim with + { + HubId = port.HubId, + PortId = port.PortId, + }; break; } - ApplyStaticProtocolKnowledge(message, knowledge); + ApplyStaticProtocolKnowledge(messageToProcess, knowledge); - if (message is PortModeInformationMessage pmim2 && pmim2.InformationType == PortModeInformationType.Name) + if (messageToProcess is PortModeInformationMessage pmim2 && pmim2.InformationType == PortModeInformationType.Name) { device.ExtendPortMode(knowledge.PortMode(pmim2.HubId, pmim2.PortId, pmim2.Mode)); } diff --git a/src/SharpBrick.PoweredUp/Protocol/Knowledge/ProtocolKnowledge.cs b/src/SharpBrick.PoweredUp/Protocol/Knowledge/ProtocolKnowledge.cs index 085a332..e85a539 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Knowledge/ProtocolKnowledge.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Knowledge/ProtocolKnowledge.cs @@ -1,20 +1,17 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; namespace SharpBrick.PoweredUp.Protocol.Knowledge { public class ProtocolKnowledge { - private ConcurrentDictionary _hubs = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _hubs = new(); public IEnumerable Hubs => _hubs.Values; public HubInfo Hub(byte hubId) { - HubInfo result; - - if (!_hubs.TryGetValue(hubId, out result)) + if (!_hubs.TryGetValue(hubId, out HubInfo result)) { result = new HubInfo() { @@ -32,8 +29,7 @@ public PortInfo Port(byte hubId, byte portId) { var hub = Hub(hubId); - PortInfo result; - if (!hub.Ports.TryGetValue(portId, out result)) + if (!hub.Ports.TryGetValue(portId, out PortInfo result)) { result = new PortInfo() { @@ -53,7 +49,7 @@ public PortModeInfo PortMode(byte hubId, byte portId, byte modeIndex) if (!(port.Modes.TryGetValue(modeIndex, out var result))) { - throw new ArgumentException(nameof(modeIndex)); + throw new ArgumentException("modeIndex is null", nameof(modeIndex)); } return result; diff --git a/src/SharpBrick.PoweredUp/Protocol/LegoWirelessProtocol.cs b/src/SharpBrick.PoweredUp/Protocol/LegoWirelessProtocol.cs index 08ac36c..0ca3494 100644 --- a/src/SharpBrick.PoweredUp/Protocol/LegoWirelessProtocol.cs +++ b/src/SharpBrick.PoweredUp/Protocol/LegoWirelessProtocol.cs @@ -16,7 +16,7 @@ public class LegoWirelessProtocol : ILegoWirelessProtocol private readonly BluetoothKernel _kernel; private readonly ILogger _logger; private readonly IDeviceFactory _deviceFactory; - private Subject<(byte[] data, LegoWirelessMessage message)> _upstreamSubject = null; + private readonly Subject<(byte[] data, LegoWirelessMessage message)> _upstreamSubject; public ProtocolKnowledge Knowledge { get; } = new ProtocolKnowledge(); @@ -29,19 +29,16 @@ public LegoWirelessProtocol(BluetoothKernel kernel, ILogger(); } public async Task ConnectAsync(SystemType knownSystemType = default) { // sets initial system type to provided value. This alllows sensitive IPoweredUpDevice to provide the right GetStaticPortInfo (even on initial HubAttachedIO before a HubProperty can be queried). - await KnowledgeManager.ApplyDynamicProtocolKnowledge(new HubPropertyMessage() + await KnowledgeManager.ApplyDynamicProtocolKnowledge(new HubPropertyMessage(HubProperty.SystemTypeId, HubPropertyOperation.Update, knownSystemType) { HubId = 0x00, - Operation = HubPropertyOperation.Update, - Property = HubProperty.SystemTypeId, - Payload = knownSystemType, }, Knowledge, _deviceFactory); await _kernel.ConnectAsync(); diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/GenericErrorMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/GenericErrorMessage.cs deleted file mode 100644 index 9d58a0c..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/GenericErrorMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.9.1 - public class GenericErrorMessage : LegoWirelessMessage - { - public byte CommandType { get; set; } - public ErrorCode ErrorCode { get; set; } - - public override string ToString() - => $"Error - {ErrorCode} from {(MessageType)CommandType}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/HubActionMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/HubActionMessage.cs deleted file mode 100644 index a46060c..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/HubActionMessage.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.6.1 - public class HubActionMessage : LegoWirelessMessage - { - public HubAction Action { get; set; } - - public override string ToString() - => $"Hub Action - {this.Action}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/HubAlertMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/HubAlertMessage.cs deleted file mode 100644 index 4188462..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/HubAlertMessage.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.7.1 - public class HubAlertMessage : LegoWirelessMessage - { - public HubAlert Alert { get; set; } - public HubAlertOperation Operation { get; set; } - - public byte DownstreamPayload { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/HubAttachedIOMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/HubAttachedIOMessage.cs deleted file mode 100644 index 376c461..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/HubAttachedIOMessage.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; - -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.8.1 - public abstract class HubAttachedIOMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public HubAttachedIOEvent Event { get; set; } - } - - // spec chapter: 3.8.1 - public class HubAttachedIOForAttachedDeviceMessage : HubAttachedIOMessage - { - public HubAttachedIOForAttachedDeviceMessage() - { - Event = HubAttachedIOEvent.AttachedIO; - } - - public DeviceType IOTypeId { get; set; } - public Version HardwareRevision { get; set; } - public Version SoftwareRevision { get; set; } - - public override string ToString() - => $"Attached IO - Port {HubId}/{PortId} of device type {IOTypeId} (HW: {HardwareRevision} / SW: {SoftwareRevision})"; - } - - // spec chapter: 3.8.1 - public class HubAttachedIOForAttachedVirtualDeviceMessage : HubAttachedIOMessage - { - public HubAttachedIOForAttachedVirtualDeviceMessage() - { - Event = HubAttachedIOEvent.AttachedVirtualIO; - } - - public DeviceType IOTypeId { get; set; } - public byte PortAId { get; set; } - public byte PortBId { get; set; } - - public override string ToString() - => $"Attached Virtual IO - Port {HubId}/{PortId} using ports {PortAId} + {PortBId} of device type {IOTypeId}"; - } - - // spec chapter: 3.8.1 - public class HubAttachedIOForDetachedDeviceMessage : HubAttachedIOMessage - { - public HubAttachedIOForDetachedDeviceMessage() - { - Event = HubAttachedIOEvent.DetachedIO; - } - - public override string ToString() - => $"Dettached IO - Port {HubId}{PortId}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/HubPropertyMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/HubPropertyMessage.cs deleted file mode 100644 index 2badcb5..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/HubPropertyMessage.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using SharpBrick.PoweredUp.Utils; - -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.5.2 - - public class HubPropertyMessage : LegoWirelessMessage - { - public HubProperty Property { get; set; } - public HubPropertyOperation Operation { get; set; } - } - public class HubPropertyMessage : HubPropertyMessage - { - public TPayload Payload { get; set; } - - public override string ToString() - => this switch - { - HubPropertyMessage msg => $"Hub Property - {msg.Property}: {BytesStringUtil.DataToString(msg.Payload)}", - _ => $"Hub Property - {this.Property}: {this.Payload}", - }; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/LegoWirelessMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/LegoWirelessMessage.cs index e03de92..14eae24 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/LegoWirelessMessage.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/LegoWirelessMessage.cs @@ -1,14 +1,27 @@ -using System; +using SharpBrick.PoweredUp.Utils; namespace SharpBrick.PoweredUp.Protocol.Messages { // spec chapter: 3.1 - public abstract class LegoWirelessMessage + // Length: spec chapter: 3.2; encoded as byte or ushort + public abstract record LegoWirelessMessage(MessageType MessageType) { - // spec chapter: 3.2 - // encoded as byte or ushort public ushort Length { get; set; } public byte HubId { get; set; } - public MessageType MessageType { get; set; } + } + + // spec chapter: 3.9.1 + public record GenericErrorMessage(byte CommandType, ErrorCode ErrorCode) + : LegoWirelessMessage(MessageType.GenericErrorMessages) + { + public override string ToString() + => $"Error - {ErrorCode} from {(MessageType)CommandType}"; + } + + public record UnknownMessage(byte MessageTypeAsByte, byte[] Data) + : LegoWirelessMessage((MessageType)MessageTypeAsByte) + { + public override string ToString() + => $"Unknown Message Type: {(MessageType)this.MessageType} Length: {this.Length} Content: {BytesStringUtil.DataToString(this.Data)}"; } } diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueSingleMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/MessageOfPortValuesModel.cs similarity index 69% rename from src/SharpBrick.PoweredUp/Protocol/Messages/PortValueSingleMessage.cs rename to src/SharpBrick.PoweredUp/Protocol/Messages/MessageOfPortValuesModel.cs index 5fbdd43..b6b6ca9 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueSingleMessage.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/MessageOfPortValuesModel.cs @@ -2,10 +2,9 @@ namespace SharpBrick.PoweredUp.Protocol.Messages { - public class PortValueSingleMessage : LegoWirelessMessage + public record PortValueSingleMessage(PortValueData[] Data) + : LegoWirelessMessage(MessageType.PortValueSingle) { - public PortValueData[] Data { get; set; } - public static string FormatPortValueDataArray(byte hubId, in PortValueData[] data) => string.Join(";", data.Select(d => d switch { @@ -19,4 +18,10 @@ public static string FormatPortValueDataArray(byte hubId, in PortValueData[] dat public override string ToString() => "Port Values - " + FormatPortValueDataArray(HubId, Data); } + public record PortValueCombinedModeMessage(byte PortId, PortValueData[] Data) + : LegoWirelessMessage(MessageType.PortValueCombinedMode) + { + public override string ToString() + => $"Port Values (Combined Mode) - " + PortValueSingleMessage.FormatPortValueDataArray(HubId, Data); + } } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfHubsModel.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfHubsModel.cs new file mode 100644 index 0000000..754649a --- /dev/null +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfHubsModel.cs @@ -0,0 +1,68 @@ +using System; +using SharpBrick.PoweredUp.Utils; + +namespace SharpBrick.PoweredUp.Protocol.Messages +{ + // spec chapter: 3.5.2 + public record HubPropertyMessage(HubProperty Property, HubPropertyOperation Operation) + : LegoWirelessMessage(MessageType.HubProperties); + public record HubPropertyMessage(HubProperty Property, HubPropertyOperation Operation, TPayload Payload) + : HubPropertyMessage(Property, Operation) + { + public override string ToString() + => this switch + { + HubPropertyMessage msg => $"Hub Property - {msg.Property}: {BytesStringUtil.DataToString(msg.Payload)}", + _ => $"Hub Property - {this.Property}: {this.Payload}", + }; + } + + // spec chapter: 3.6.1 + public record HubActionMessage(HubAction Action) + : LegoWirelessMessage(MessageType.HubActions) + { + public override string ToString() + => $"Hub Action - {this.Action}"; + } + + // spec chapter: 3.7.1 + public record HubAlertMessage(HubAlert Alert, HubAlertOperation Operation, byte DownstreamPayload = 0x00) + : LegoWirelessMessage(MessageType.HubAlerts); + + // spec chapter: 3.8.1 + public abstract record HubAttachedIOMessage(byte PortId, HubAttachedIOEvent Event) + : LegoWirelessMessage(MessageType.HubAttachedIO); + + // spec chapter: 3.8.1 + public record HubAttachedIOForAttachedDeviceMessage(byte PortId, DeviceType IOTypeId, Version HardwareRevision, Version SoftwareRevision) + : HubAttachedIOMessage(PortId, HubAttachedIOEvent.AttachedIO) + { + public override string ToString() + => $"Attached IO - Port {HubId}/{PortId} of device type {IOTypeId} (HW: {HardwareRevision} / SW: {SoftwareRevision})"; + } + + // spec chapter: 3.8.1 + public record HubAttachedIOForAttachedVirtualDeviceMessage(byte PortId, DeviceType IOTypeId, byte PortAId, byte PortBId) + : HubAttachedIOMessage(PortId, HubAttachedIOEvent.AttachedVirtualIO) + { + public override string ToString() + => $"Attached Virtual IO - Port {HubId}/{PortId} using ports {PortAId} + {PortBId} of device type {IOTypeId}"; + } + + // spec chapter: 3.8.1 + public record HubAttachedIOForDetachedDeviceMessage(byte PortId) + : HubAttachedIOMessage(PortId, HubAttachedIOEvent.DetachedIO) + { + public override string ToString() + => $"Dettached IO - Port {HubId}{PortId}"; + } + + public record VirtualPortSetupMessage(VirtualPortSubCommand SubCommand) + : LegoWirelessMessage(MessageType.VirtualPortSetup); + + public record VirtualPortSetupForDisconnectedMessage(byte PortId) + : VirtualPortSetupMessage(VirtualPortSubCommand.Disconnected); + + public record VirtualPortSetupForConnectedMessage(byte PortAId, byte PortBId) + : VirtualPortSetupMessage(VirtualPortSubCommand.Connected); +} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortFormatModel.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortFormatModel.cs new file mode 100644 index 0000000..1646591 --- /dev/null +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortFormatModel.cs @@ -0,0 +1,26 @@ +namespace SharpBrick.PoweredUp.Protocol.Messages +{ + public record PortInputFormatCombinedModeMessage(byte PortId, byte UsedCombinationIndex, bool MultiUpdateEnabled, int[] ConfiguredModeDataSetIndex) + : LegoWirelessMessage(MessageType.PortInputFormatCombinedMode) + { + public override string ToString() + => $"Port Input Format (Combined Mode) - Port {HubId}/{PortId} UsedCombinationIndex {UsedCombinationIndex} Enabled {MultiUpdateEnabled} Confirmed Modes/DataSet Indices {string.Join(",", ConfiguredModeDataSetIndex)}"; + } + public record PortInputFormatSetupCombinedModeMessage(byte PortId, PortInputFormatSetupCombinedSubCommand SubCommand) + : LegoWirelessMessage(MessageType.PortInputFormatSetupCombinedMode); + + public record PortInputFormatSetupCombinedModeForSetModeDataSetMessage(byte PortId, byte CombinationIndex, PortInputFormatSetupCombinedModeModeDataSet[] ModeDataSets) + : PortInputFormatSetupCombinedModeMessage(PortId, PortInputFormatSetupCombinedSubCommand.SetModeAndDataSetCombination); + + // spec chapter: 3.17 + public record PortInputFormatSetupSingleMessage(byte PortId, byte Mode, uint DeltaInterval, bool NotificationEnabled) + : LegoWirelessMessage(MessageType.PortInputFormatSetupSingle); + + // spec chapter: 3.23 + public record PortInputFormatSingleMessage(byte PortId, byte ModeIndex, uint DeltaInterval, bool NotificationEnabled) + : LegoWirelessMessage(MessageType.PortInputFormatSingle) + { + public override string ToString() + => $"Port Input Format (Single) - Mode {HubId}/{PortId}/{ModeIndex}: Threshold {DeltaInterval}, Notification {NotificationEnabled}"; + } +} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortOutputCommandModel.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortOutputCommandModel.cs new file mode 100644 index 0000000..7114520 --- /dev/null +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortOutputCommandModel.cs @@ -0,0 +1,236 @@ +using System.Linq; + +namespace SharpBrick.PoweredUp.Protocol.Messages +{ + public record PortOutputCommandFeedbackMessage(PortOutputCommandFeedback[] Feedbacks) + : LegoWirelessMessage(MessageType.PortOutputCommandFeedback) + { + public override string ToString() + => $"Port Output Command Feedback - " + string.Join(",", this.Feedbacks.Select(f => $"Port {this.HubId}/{f.PortId} -> {f.Feedback}")); + } + + public abstract record PortOutputCommandMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + PortOutputSubCommand SubCommand + ) : LegoWirelessMessage(MessageType.PortOutputCommand); + + public record PortOutputCommandWriteDirectMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.WriteDirect); + + public record PortOutputCommandWriteDirectModeDataMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + byte ModeIndex + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.WriteDirectModeData); + + public record GenericWriteDirectModeDataMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + byte ModeIndex, + byte[] Data + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, ModeIndex); + + // spec chapter: 3.27.1 + public record PortOutputCommandStartPowerMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + sbyte Power + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0x00); + + // spec chapter: 3.27.2 + public record PortOutputCommandStartPower2Message( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + sbyte Power1, + sbyte Power2 + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartPower2); + + // spec chapter: 3.27.3 + public record PortOutputCommandSetAccTimeMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + ushort Time, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.SetAccTime); + + // spec chapter: 3.27.4 + public record PortOutputCommandSetDecTimeMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + ushort Time, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.SetDecTime); + + // spec chapter: 3.27.5 + public record PortOutputCommandStartSpeedMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + sbyte Speed, + byte MaxPower, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartSpeed); + + // spec chapter: 3.27.6 + public record PortOutputCommandStartSpeed2Message( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + sbyte Speed1, + sbyte Speed2, + byte MaxPower, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartSpeed2); + + // spec chapter: 3.27.7 + public record PortOutputCommandStartSpeedForTimeMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + ushort Time, + sbyte Speed, + byte MaxPower, + SpecialSpeed EndState, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartSpeedForTime); + + // spec chapter: 3.27.8 + public record PortOutputCommandStartSpeedForTime2Message( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + ushort Time, + sbyte Speed1, + sbyte Speed2, + byte MaxPower, + SpecialSpeed EndState, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartSpeedForTime2); + + // spec chapter: 3.27.9 + public record PortOutputCommandStartSpeedForDegreesMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + uint Degrees, + sbyte Speed, + byte MaxPower, + SpecialSpeed EndState, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartSpeedForDegrees); + + // spec chapter: 3.27.10 + public record PortOutputCommandStartSpeedForDegrees2Message( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + uint Degrees, + sbyte Speed1, + sbyte Speed2, + byte MaxPower, + SpecialSpeed EndState, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.StartSpeedForDegrees2); + + // spec chapter: 3.27.11 + public record PortOutputCommandGotoAbsolutePositionMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + int AbsolutePosition, + sbyte Speed, + byte MaxPower, + SpecialSpeed EndState, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.GotoAbsolutePosition); + // spec chapter: 3.27.12 + public record PortOutputCommandGotoAbsolutePosition2Message( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + int AbsolutePosition1, + int AbsolutePosition2, + sbyte Speed, + byte MaxPower, + SpecialSpeed EndState, + SpeedProfiles Profile + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.GotoAbsolutePosition2); + + // spec chapter: 3.27.13 + public record PortOutputCommandPresetEncoderMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + int Position + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0xFF); //TODO find out mode + + // spec chapter: 3.27.14 + public record PortOutputCommandPreset2EncoderMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + int Position1, + int Position2 + ) : PortOutputCommandMessage(PortId, StartupInformation, CompletionInformation, PortOutputSubCommand.PresetEncoder2); + + // spec chapter: 3.27.15 + public record PortOutputCommandTiltImpactPresetMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + int PresetValue + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0x03); + + // spec chapter: 3.27.16 + public record PortOutputCommandTiltConfigOrientationMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + TiltConfigOrientation Orientation + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0x05); + + // spec chapter: 3.27.17 + public record PortOutputCommandTiltConfigImpactMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + sbyte ImpactThreshold, + sbyte BumpHoldoff + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0x06); + + // spec chapter: 3.27.19 + public record PortOutputCommandGenericZeroSetHardwareMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation + ) : PortOutputCommandWriteDirectMessage(PortId, StartupInformation, CompletionInformation); + + // spec chapter: 3.27.20 + public record PortOutputCommandSetRgbColorNoMessage( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + PoweredUpColor ColorNo + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0x00); + + // spec chapter: 3.27.21 + public record PortOutputCommandSetRgbColorNo2Message( + byte PortId, + PortOutputCommandStartupInformation StartupInformation, + PortOutputCommandCompletionInformation CompletionInformation, + byte RedColor, + byte GreenColor, + byte BlueColor + ) : PortOutputCommandWriteDirectModeDataMessage(PortId, StartupInformation, CompletionInformation, 0x01); +} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortsModel.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortsModel.cs new file mode 100644 index 0000000..801842c --- /dev/null +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/MessagesOfPortsModel.cs @@ -0,0 +1,94 @@ +using System.Linq; + +namespace SharpBrick.PoweredUp.Protocol.Messages +{ + + // spec chapter: 3.15.1 + public record PortInformationRequestMessage(byte PortId, PortInformationType InformationType) + : LegoWirelessMessage(MessageType.PortInformationRequest); + + // spec chapter: 3.16.1 + public record PortModeInformationRequestMessage(byte PortId, byte Mode, PortModeInformationType InformationType) + : LegoWirelessMessage(MessageType.PortModeInformationRequest); + + // spec chapter: 3.19.1 + public abstract record PortInformationMessage(byte PortId, PortInformationType InformationType) + : LegoWirelessMessage(MessageType.PortInformation); + + // spec chapter: 3.19.1 + public record PortInformationForModeInfoMessage( + byte PortId, + PortInformationType InformationType, + bool OutputCapability, + bool InputCapability, + bool LogicalCombinableCapability, + bool LogicalSynchronizableCapability, + byte TotalModeCount, + ushort InputModes, + ushort OutputModes + ) : PortInformationMessage(PortId, InformationType) + { + public override string ToString() + => $"Port Information - Port {HubId}/{PortId} Total Modes {TotalModeCount} / Capabilities Output:{OutputCapability}, Input:{InputCapability}, LogicalCombinable:{LogicalCombinableCapability}, LogicalSynchronizable:{LogicalSynchronizableCapability} / InputModes: {InputModes:X}, OutputModes: {InputModes:X}"; + } + + // spec chapter: 3.19.1 + public record PortInformationForPossibleModeCombinationsMessage(byte PortId, PortInformationType InformationType, ushort[] ModeCombinations) + : PortInformationMessage(PortId, InformationType) + { + public override string ToString() + => $"Port Information (Combinations) - Port {HubId}/{PortId} Combinations: {string.Join(",", ModeCombinations.Select(x => x.ToString("X")))}"; + } + + // spec chapter: 3.20.1 + public abstract record PortModeInformationMessage(byte PortId, byte Mode, PortModeInformationType InformationType) + : LegoWirelessMessage(MessageType.PortModeInformation); + + // spec chapter: 3.20.1 + public record PortModeInformationForNameMessage(byte PortId, byte Mode, string Name) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.Name); + + // spec chapter: 3.20.1 + public record PortModeInformationForRawMessage(byte PortId, byte Mode, float RawMin, float RawMax) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.Raw); + + // spec chapter: 3.20.1 + public record PortModeInformationForPctMessage(byte PortId, byte Mode, float PctMin, float PctMax) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.Pct); + + // spec chapter: 3.20.1 + public record PortModeInformationForSIMessage(byte PortId, byte Mode, float SIMin, float SIMax) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.SI); + + // spec chapter: 3.20.1 + public record PortModeInformationForSymbolMessage(byte PortId, byte Mode, string Symbol) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.Symbol); + + // spec chapter: 3.20.1 + public record PortModeInformationForMappingMessage( + byte PortId, byte Mode, + bool InputSupportsNull, + bool InputSupportFunctionalMapping20, + bool InputAbsolute, + bool InputRelative, + bool InputDiscrete, + bool OutputSupportsNull, + bool OutputSupportFunctionalMapping20, + bool OutputAbsolute, + bool OutputRelative, + bool OutputDiscrete + ) : PortModeInformationMessage(PortId, Mode, PortModeInformationType.Mapping); + + // spec chapter: 3.20.1 + public record PortModeInformationForMotorBiasMessage(byte PortId, byte Mode, byte MotorBias) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.MotorBias); + + // spec chapter: 3.20.1 + public record PortModeInformationForCapabilityBitsMessage(byte PortId, byte Mode, byte[] CapabilityBits) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.CapabilityBits); + + // spec chapter: 3.20.1 + public record PortModeInformationForValueFormatMessage(byte PortId, byte Mode, byte NumberOfDatasets, PortModeInformationDataType DatasetType, byte TotalFigures, byte Decimals) + : PortModeInformationMessage(PortId, Mode, PortModeInformationType.ValueFormat); + +} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInformationMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInformationMessage.cs deleted file mode 100644 index 08422c0..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInformationMessage.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Linq; - -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.19.1 - public abstract class PortInformationMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public PortInformationType InformationType { get; set; } - } - - // spec chapter: 3.19.1 - public class PortInformationForModeInfoMessage : PortInformationMessage - { - public bool OutputCapability { get; set; } - public bool InputCapability { get; set; } - public bool LogicalCombinableCapability { get; set; } - public bool LogicalSynchronizableCapability { get; set; } - - public byte TotalModeCount { get; set; } - public ushort InputModes { get; set; } - public ushort OutputModes { get; set; } - - public override string ToString() - => $"Port Information - Port {HubId}/{PortId} Total Modes {TotalModeCount} / Capabilities Output:{OutputCapability}, Input:{InputCapability}, LogicalCombinable:{LogicalCombinableCapability}, LogicalSynchronizable:{LogicalSynchronizableCapability} / InputModes: {InputModes:X}, OutputModes: {InputModes:X}"; - } - - // spec chapter: 3.19.1 - public class PortInformationForPossibleModeCombinationsMessage : PortInformationMessage - { - public ushort[] ModeCombinations { get; set; } - - public override string ToString() - => $"Port Information (Combinations) - Port {HubId}/{PortId} Combinations: {string.Join(",", ModeCombinations.Select(x => x.ToString("X")))}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInformationRequestMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInformationRequestMessage.cs deleted file mode 100644 index b3acbb8..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInformationRequestMessage.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.15.1 - public class PortInformationRequestMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public PortInformationType InformationType { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatCombinedModeMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatCombinedModeMessage.cs deleted file mode 100644 index aa13560..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatCombinedModeMessage.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public class PortInputFormatCombinedModeMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public byte UsedCombinationIndex { get; set; } - public bool MultiUpdateEnabled { get; set; } - public int[] ConfiguredModeDataSetIndex { get; set; } - - public override string ToString() - => $"Port Input Format (Combined Mode) - Port {HubId}/{PortId} UsedCombinationIndex {UsedCombinationIndex} Enabled {MultiUpdateEnabled} Confirmed Modes/DataSet Indices {string.Join(",", ConfiguredModeDataSetIndex)}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeMessage.cs deleted file mode 100644 index 5034abe..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeMessage.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public class PortInputFormatSetupCombinedModeMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public PortInputFormatSetupCombinedSubCommand SubCommand { get; set; } - } - - public class PortInputFormatSetupCombinedModeForSetModeDataSetMessage : PortInputFormatSetupCombinedModeMessage - { - public byte CombinationIndex { get; set; } - public PortInputFormatSetupCombinedModeModeDataSet[] ModeDataSets { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeModeDataSet.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeModeDataSet.cs index 0491a63..9954fae 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeModeDataSet.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupCombinedModeModeDataSet.cs @@ -1,8 +1,4 @@ namespace SharpBrick.PoweredUp.Protocol.Messages { - public class PortInputFormatSetupCombinedModeModeDataSet - { - public byte Mode { get; set; } - public byte DataSet { get; set; } - } + public record PortInputFormatSetupCombinedModeModeDataSet(byte Mode, byte DataSet); } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupSingleMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupSingleMessage.cs deleted file mode 100644 index 1d50111..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSetupSingleMessage.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.17 - public class PortInputFormatSetupSingleMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public byte Mode { get; set; } - public uint DeltaInterval { get; set; } - public bool NotificationEnabled { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSingleMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSingleMessage.cs deleted file mode 100644 index de3a49f..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortInputFormatSingleMessage.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.23 - public class PortInputFormatSingleMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public byte ModeIndex { get; set; } - public uint DeltaInterval { get; set; } - public bool NotificationEnabled { get; set; } - - public override string ToString() - => $"Port Input Format (Single) - Mode {HubId}/{PortId}/{ModeIndex}: Threshold {DeltaInterval}, Notification {NotificationEnabled}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortModeInformationMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortModeInformationMessage.cs deleted file mode 100644 index 741df44..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortModeInformationMessage.cs +++ /dev/null @@ -1,80 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.20.1 - public abstract class PortModeInformationMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public byte Mode { get; set; } - public PortModeInformationType InformationType { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForNameMessage : PortModeInformationMessage - { - public string Name { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForRawMessage : PortModeInformationMessage - { - public float RawMin { get; set; } - public float RawMax { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForPctMessage : PortModeInformationMessage - { - public float PctMin { get; set; } - public float PctMax { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForSIMessage : PortModeInformationMessage - { - public float SIMin { get; set; } - public float SIMax { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForSymbolMessage : PortModeInformationMessage - { - public string Symbol { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForMappingMessage : PortModeInformationMessage - { - public bool InputSupportsNull { get; set; } - public bool InputSupportFunctionalMapping20 { get; set; } - public bool InputAbsolute { get; set; } - public bool InputRelative { get; set; } - public bool InputDiscrete { get; set; } - - public bool OutputSupportsNull { get; set; } - public bool OutputSupportFunctionalMapping20 { get; set; } - public bool OutputAbsolute { get; set; } - public bool OutputRelative { get; set; } - public bool OutputDiscrete { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForMotorBiasMessage : PortModeInformationMessage - { - public byte MotorBias { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForCapabilityBitsMessage : PortModeInformationMessage - { - public byte[] CapabilityBits { get; set; } - } - - // spec chapter: 3.20.1 - public class PortModeInformationForValueFormatMessage : PortModeInformationMessage - { - public byte NumberOfDatasets { get; set; } - public PortModeInformationDataType DatasetType { get; set; } - public byte TotalFigures { get; set; } - public byte Decimals { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortModeInformationRequestMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortModeInformationRequestMessage.cs deleted file mode 100644 index 8e30967..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortModeInformationRequestMessage.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - // spec chapter: 3.16.1 - public class PortModeInformationRequestMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - public byte Mode { get; set; } - public PortModeInformationType InformationType { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedback.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedback.cs index 2ee9ed0..3cbb32a 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedback.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedback.cs @@ -1,9 +1,4 @@ namespace SharpBrick.PoweredUp.Protocol.Messages { - public class PortOutputCommandFeedback - { - public byte PortId { get; set; } - - public PortFeedback Feedback { get; set; } - } + public record PortOutputCommandFeedback(byte PortId, PortFeedback Feedback); } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedbackMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedbackMessage.cs deleted file mode 100644 index 84d6e5d..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandFeedbackMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Linq; - -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public class PortOutputCommandFeedbackMessage : LegoWirelessMessage - { - public PortOutputCommandFeedback[] Feedbacks { get; set; } - - public override string ToString() - => $"Port Output Command Feedback - " + string.Join(",", this.Feedbacks.Select(f => $"Port {this.HubId}/{f.PortId} -> {f.Feedback}")); - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandMessage.cs deleted file mode 100644 index 2eec7ea..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortOutputCommandMessage.cs +++ /dev/null @@ -1,217 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public abstract class PortOutputCommandMessage : LegoWirelessMessage - { - public PortOutputCommandMessage(PortOutputSubCommand subCommand) - { - SubCommand = subCommand; - } - public byte PortId { get; set; } - public PortOutputCommandStartupInformation StartupInformation { get; set; } - public PortOutputCommandCompletionInformation CompletionInformation { get; set; } - - public PortOutputSubCommand SubCommand { get; set; } - } - - public class PortOutputCommandWriteDirectMessage : PortOutputCommandMessage - { - public PortOutputCommandWriteDirectMessage() - : base(PortOutputSubCommand.WriteDirect) - { } - } - public class PortOutputCommandWriteDirectModeDataMessage : PortOutputCommandMessage - { - public PortOutputCommandWriteDirectModeDataMessage(byte modeIndex) - : base(PortOutputSubCommand.WriteDirectModeData) - { - ModeIndex = modeIndex; - } - - public byte ModeIndex { get; set; } - } - public class GenericWriteDirectModeDataMessage : PortOutputCommandWriteDirectModeDataMessage - { - public GenericWriteDirectModeDataMessage(byte modeIndex) - : base(modeIndex) - { } - - public byte[] Data { get; set; } - } - - // spec chapter: 3.27.1 - public class PortOutputCommandStartPowerMessage : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandStartPowerMessage() : base(0x00) { } - public sbyte Power { get; set; } - } - - // spec chapter: 3.27.2 - public class PortOutputCommandStartPower2Message : PortOutputCommandMessage - { - public PortOutputCommandStartPower2Message() : base(PortOutputSubCommand.StartPower2) { } - public sbyte Power1 { get; set; } - public sbyte Power2 { get; set; } - } - - // spec chapter: 3.27.3 - public class PortOutputCommandSetAccTimeMessage : PortOutputCommandMessage - { - public PortOutputCommandSetAccTimeMessage() : base(PortOutputSubCommand.SetAccTime) { } - public ushort Time { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.4 - public class PortOutputCommandSetDecTimeMessage : PortOutputCommandMessage - { - public PortOutputCommandSetDecTimeMessage() : base(PortOutputSubCommand.SetDecTime) { } - public ushort Time { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.5 - public class PortOutputCommandStartSpeedMessage : PortOutputCommandMessage - { - public PortOutputCommandStartSpeedMessage() : base(PortOutputSubCommand.StartSpeed) { } - public sbyte Speed { get; set; } - public byte MaxPower { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.6 - public class PortOutputCommandStartSpeed2Message : PortOutputCommandMessage - { - public PortOutputCommandStartSpeed2Message() : base(PortOutputSubCommand.StartSpeed2) { } - public sbyte Speed1 { get; set; } - public sbyte Speed2 { get; set; } - public byte MaxPower { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.7 - public class PortOutputCommandStartSpeedForTimeMessage : PortOutputCommandMessage - { - public PortOutputCommandStartSpeedForTimeMessage() : base(PortOutputSubCommand.StartSpeedForTime) { } - public ushort Time { get; set; } - public sbyte Speed { get; set; } - public byte MaxPower { get; set; } - public SpecialSpeed EndState { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.8 - public class PortOutputCommandStartSpeedForTime2Message : PortOutputCommandMessage - { - public PortOutputCommandStartSpeedForTime2Message() : base(PortOutputSubCommand.StartSpeedForTime2) { } - public ushort Time { get; set; } - public sbyte Speed1 { get; set; } - public sbyte Speed2 { get; set; } - public byte MaxPower { get; set; } - public SpecialSpeed EndState { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.9 - public class PortOutputCommandStartSpeedForDegreesMessage : PortOutputCommandMessage - { - public PortOutputCommandStartSpeedForDegreesMessage() : base(PortOutputSubCommand.StartSpeedForDegrees) { } - public uint Degrees { get; set; } - public sbyte Speed { get; set; } - public byte MaxPower { get; set; } - public SpecialSpeed EndState { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.10 - public class PortOutputCommandStartSpeedForDegrees2Message : PortOutputCommandMessage - { - public PortOutputCommandStartSpeedForDegrees2Message() : base(PortOutputSubCommand.StartSpeedForDegrees2) { } - public uint Degrees { get; set; } - public sbyte Speed1 { get; set; } - public sbyte Speed2 { get; set; } - public byte MaxPower { get; set; } - public SpecialSpeed EndState { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.11 - public class PortOutputCommandGotoAbsolutePositionMessage : PortOutputCommandMessage - { - public PortOutputCommandGotoAbsolutePositionMessage() : base(PortOutputSubCommand.GotoAbsolutePosition) { } - public int AbsolutePosition { get; set; } // UNSPECED: relative to what? (to the position of the motor start) - public sbyte Speed { get; set; } - public byte MaxPower { get; set; } - public SpecialSpeed EndState { get; set; } - public SpeedProfiles Profile { get; set; } - } - // spec chapter: 3.27.12 - public class PortOutputCommandGotoAbsolutePosition2Message : PortOutputCommandMessage - { - public PortOutputCommandGotoAbsolutePosition2Message() : base(PortOutputSubCommand.GotoAbsolutePosition2) { } - public int AbsolutePosition1 { get; set; } - public int AbsolutePosition2 { get; set; } - public sbyte Speed { get; set; } - public byte MaxPower { get; set; } - public SpecialSpeed EndState { get; set; } - public SpeedProfiles Profile { get; set; } - } - - // spec chapter: 3.27.13 - public class PortOutputCommandPresetEncoderMessage : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandPresetEncoderMessage() : base(0xFF) { }//TODO find out mode - public int Position { get; set; } - } - - // spec chapter: 3.27.14 - public class PortOutputCommandPreset2EncoderMessage : PortOutputCommandMessage - { - public PortOutputCommandPreset2EncoderMessage() : base(PortOutputSubCommand.PresetEncoder2) { } - public int Position1 { get; set; } - public int Position2 { get; set; } - } - - // spec chapter: 3.27.15 - public class PortOutputCommandTiltImpactPresetMessage : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandTiltImpactPresetMessage() : base(0x03) { } - public int PresetValue { get; set; } - } - - // spec chapter: 3.27.16 - public class PortOutputCommandTiltConfigOrientationMessage : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandTiltConfigOrientationMessage() : base(0x05) { } - public TiltConfigOrientation Orientation { get; set; } - } - - // spec chapter: 3.27.17 - public class PortOutputCommandTiltConfigImpactMessage : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandTiltConfigImpactMessage() : base(0x06) { } - public sbyte ImpactThreshold { get; set; } - public sbyte BumpHoldoff { get; set; } - } - - // spec chapter: 3.27.19 - public class PortOutputCommandGenericZeroSetHardwareMessage : PortOutputCommandWriteDirectMessage - { } - - // spec chapter: 3.27.20 - public class PortOutputCommandSetRgbColorNoMessage : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandSetRgbColorNoMessage() : base(0x00) { } - - public PoweredUpColor ColorNo { get; set; } - } - - // spec chapter: 3.27.21 - public class PortOutputCommandSetRgbColorNo2Message : PortOutputCommandWriteDirectModeDataMessage - { - public PortOutputCommandSetRgbColorNo2Message() : base(0x01) { } - - public byte RedColor { get; set; } - public byte GreenColor { get; set; } - public byte BlueColor { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueCombinedModeMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueCombinedModeMessage.cs deleted file mode 100644 index b971bdd..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueCombinedModeMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public class PortValueCombinedModeMessage : LegoWirelessMessage - { - public byte PortId { get; set; } - - public PortValueData[] Data { get; set; } - - public override string ToString() - => $"Port Values (Combined Mode) - " + PortValueSingleMessage.FormatPortValueDataArray(HubId, Data); - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueData.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueData.cs index 0f3aeb1..18e4bb6 100644 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueData.cs +++ b/src/SharpBrick.PoweredUp/Protocol/Messages/PortValueData.cs @@ -1,15 +1,6 @@ namespace SharpBrick.PoweredUp.Protocol.Messages { - public class PortValueData - { - public byte PortId { get; set; } - public byte ModeIndex { get; set; } - public PortModeInformationDataType DataType { get; set; } - } - public class PortValueData : PortValueData - { - public TPayload[] InputValues { get; set; } - public TPayload[] SIInputValues { get; set; } - public TPayload[] PctInputValues { get; set; } - } + public record PortValueData(byte PortId, byte ModeIndex, PortModeInformationDataType DataType); + public record PortValueData(byte PortId, byte ModeIndex, PortModeInformationDataType DataType, TPayload[] InputValues, TPayload[] SIInputValues, TPayload[] PctInputValues) + : PortValueData(PortId, ModeIndex, DataType); } \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/UnknownMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/UnknownMessage.cs deleted file mode 100644 index 5389ce8..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/UnknownMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -using SharpBrick.PoweredUp.Utils; - -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public class UnknownMessage : LegoWirelessMessage - { - public byte[] Data { get; set; } - - public override string ToString() - => $"Unknown Message Type: {(MessageType)this.MessageType} Length: {this.Length} Content: {BytesStringUtil.DataToString(this.Data)}"; - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/Protocol/Messages/VirtualPortSetupMessage.cs b/src/SharpBrick.PoweredUp/Protocol/Messages/VirtualPortSetupMessage.cs deleted file mode 100644 index 8a08c1f..0000000 --- a/src/SharpBrick.PoweredUp/Protocol/Messages/VirtualPortSetupMessage.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace SharpBrick.PoweredUp.Protocol.Messages -{ - public class VirtualPortSetupMessage : LegoWirelessMessage - { - public VirtualPortSubCommand SubCommand { get; set; } - } - - public class VirtualPortSetupForDisconnectedMessage : VirtualPortSetupMessage - { - public byte PortId { get; set; } - } - - public class VirtualPortSetupForConnectedMessage : VirtualPortSetupMessage - { - public byte PortAId { get; set; } - public byte PortBId { get; set; } - } -} \ No newline at end of file diff --git a/src/SharpBrick.PoweredUp/SharpBrick.PoweredUp.csproj b/src/SharpBrick.PoweredUp/SharpBrick.PoweredUp.csproj index 2424fb9..1276a28 100644 --- a/src/SharpBrick.PoweredUp/SharpBrick.PoweredUp.csproj +++ b/src/SharpBrick.PoweredUp/SharpBrick.PoweredUp.csproj @@ -1,7 +1,7 @@ - netstandard2.1 + net5.0 diff --git a/src/SharpBrick.PoweredUp/Utils/BytesStringUtil.cs b/src/SharpBrick.PoweredUp/Utils/BytesStringUtil.cs index ef066fa..0e32197 100644 --- a/src/SharpBrick.PoweredUp/Utils/BytesStringUtil.cs +++ b/src/SharpBrick.PoweredUp/Utils/BytesStringUtil.cs @@ -11,6 +11,6 @@ public static byte[] StringToData(string messageAsString) => messageAsString.Split("-").Select(s => byte.Parse(s, NumberStyles.HexNumber)).ToArray(); public static string ToBitString(ushort data) - => new string(Enumerable.Range(0, 16).Reverse().Select(idx => (((1 << idx) & data) > 0) ? '1' : '0').ToArray()); + => new(Enumerable.Range(0, 16).Reverse().Select(idx => (((1 << idx) & data) > 0) ? '1' : '0').ToArray()); } } \ No newline at end of file diff --git a/test/SharpBrick.PoweredUp.Test/Devices/VoltageTest.cs b/test/SharpBrick.PoweredUp.Test/Devices/VoltageTest.cs index 8b31cfe..808149c 100644 --- a/test/SharpBrick.PoweredUp.Test/Devices/VoltageTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Devices/VoltageTest.cs @@ -19,13 +19,9 @@ public async Task Voltage_VoltageLObservable_Receive() var (protocol, mock) = CreateProtocolAndMock(SystemType.LegoTechnic_MediumHub); // announce voltage device in protocol - await mock.WriteUpstreamAsync(new HubAttachedIOForAttachedDeviceMessage() + await mock.WriteUpstreamAsync(new HubAttachedIOForAttachedDeviceMessage(0x20, DeviceType.Voltage, Version.Parse("1.0.0.0"), Version.Parse("1.0.0.0")) { HubId = 0, - PortId = 0x20, - IOTypeId = DeviceType.Voltage, - HardwareRevision = Version.Parse("1.0.0.0"), - SoftwareRevision = Version.Parse("1.0.0.0"), }); //await mock.WriteUpstreamAsync("0F-00-04-20-01-14-00-00-00-00-10-00-00-00-10"); @@ -51,12 +47,9 @@ await mock.WriteUpstreamAsync(new HubAttachedIOForAttachedDeviceMessage() // switch to other mode await voltageDevice.SetupNotificationAsync(voltageDevice.ModeIndexVoltageS, true, 1); // .. and device confirms it - await mock.WriteUpstreamAsync(new PortInputFormatSingleMessage() + await mock.WriteUpstreamAsync(new PortInputFormatSingleMessage(0x20, 1, 0, true) { HubId = 0, - PortId = 0x20, - ModeIndex = 1, - NotificationEnabled = true, }); // act diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/CommonMessageHeaderEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/CommonMessageHeaderEncoderTest.cs index 50f8f01..2baff09 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/CommonMessageHeaderEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/CommonMessageHeaderEncoderTest.cs @@ -1,6 +1,4 @@ -using System; -using SharpBrick.PoweredUp.Protocol.Formatter; -using Xunit; +using Xunit; namespace SharpBrick.PoweredUp.Protocol.Formatter { diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubActionsEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubActionsEncoderTest.cs index 750d514..d17d2c2 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubActionsEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubActionsEncoderTest.cs @@ -1,5 +1,3 @@ -using System.Globalization; -using System.Linq; using SharpBrick.PoweredUp.Protocol.Messages; using SharpBrick.PoweredUp.Utils; using Xunit; @@ -22,7 +20,7 @@ public class HubActionsEncoderTest public void HubActionsEncoder_Encode(HubAction action, string expectedData) { // arrange - var message = new HubActionMessage() { Action = action }; + var message = new HubActionMessage(action); // act var data = MessageEncoder.Encode(message, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAlertEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAlertEncoderTest.cs index 03394e8..390adb4 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAlertEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAlertEncoderTest.cs @@ -1,5 +1,3 @@ -using System.Globalization; -using System.Linq; using SharpBrick.PoweredUp.Protocol.Messages; using SharpBrick.PoweredUp.Utils; using Xunit; @@ -20,7 +18,7 @@ public class HubAlertEncoderTest public void HubAlertEncoder_Encode(HubAlert alert, HubAlertOperation operation, byte payload, string expectedData) { // arrange - var message = new HubAlertMessage() { Alert = alert, Operation = operation, DownstreamPayload = payload }; + var message = new HubAlertMessage(alert, operation, payload); // act var data = MessageEncoder.Encode(message, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAttachedIOEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAttachedIOEncoderTest.cs index 9b7feb5..73a8f99 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAttachedIOEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubAttachedIOEncoderTest.cs @@ -1,6 +1,4 @@ using System; -using System.Globalization; -using System.Linq; using SharpBrick.PoweredUp.Protocol.Messages; using SharpBrick.PoweredUp.Utils; using Xunit; @@ -22,7 +20,7 @@ public class HubAttachedIOEncoderTest public void HubAttachedIOEncoder_Decode_Attached(string messageAsString, DeviceType expectedType, byte expectedPortId, string expectedHwVersion, string expectedSwVersion) { // arrange - var data = BytesStringUtil.StringToData(messageAsString).AsSpan().Slice(3); + var data = BytesStringUtil.StringToData(messageAsString).AsSpan()[3..]; // act var message = new HubAttachedIOEncoder().Decode(0x00, data) as HubAttachedIOForAttachedDeviceMessage; @@ -34,14 +32,7 @@ public void HubAttachedIOEncoder_Decode_Attached(string messageAsString, Devi Assert.Equal(new Version(expectedSwVersion), message.SoftwareRevision); // reverse test - var reverseMessage = new HubAttachedIOForAttachedDeviceMessage() - { - Event = HubAttachedIOEvent.AttachedIO, - IOTypeId = expectedType, - PortId = expectedPortId, - HardwareRevision = Version.Parse(expectedHwVersion), - SoftwareRevision = Version.Parse(expectedSwVersion), - }; + var reverseMessage = new HubAttachedIOForAttachedDeviceMessage(expectedPortId, expectedType, Version.Parse(expectedHwVersion), Version.Parse(expectedSwVersion)); // act var reverseData = MessageEncoder.Encode(reverseMessage, null); @@ -56,7 +47,7 @@ public void HubAttachedIOEncoder_Decode_Attached(string messageAsString, Devi public void HubAttachedIOEncoder_Decode_AttachedVirutalIO(string messageAsString, DeviceType expectedType, byte expectedPortId, byte portA, byte portB) { // arrange - var data = BytesStringUtil.StringToData(messageAsString).AsSpan().Slice(3); + var data = BytesStringUtil.StringToData(messageAsString).AsSpan()[3..]; // act var message = new HubAttachedIOEncoder().Decode(0x00, data) as HubAttachedIOForAttachedVirtualDeviceMessage; diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubPropertiesEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubPropertiesEncoderTest.cs index 6756079..42e9501 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubPropertiesEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/HubPropertiesEncoderTest.cs @@ -1,6 +1,4 @@ using System; -using System.Globalization; -using System.Linq; using SharpBrick.PoweredUp.Protocol.Messages; using SharpBrick.PoweredUp.Utils; using Xunit; @@ -24,7 +22,7 @@ public class HubPropertiesEncoderTest public void HubPropertiesEncoder_Decode_UpdateUpstream(string messageAsString, HubProperty expectedProperty, HubPropertyOperation expectedPropertyOperation, T payload) { // arrange - var data = BytesStringUtil.StringToData(messageAsString).AsSpan().Slice(3); + var data = BytesStringUtil.StringToData(messageAsString).AsSpan()[3..]; // act var message = new HubPropertiesEncoder().Decode(0x00, data) as HubPropertyMessage; @@ -57,7 +55,7 @@ public void HubPropertiesEncoder_Decode_UpdateUpstream_StringShim(string message public void HubPropertiesEncoder_Encode_Downstream(HubProperty property, HubPropertyOperation operation, string expectedData) { // act - var data = MessageEncoder.Encode(new HubPropertyMessage() { Property = property, Operation = operation }, null); + var data = MessageEncoder.Encode(new HubPropertyMessage(property, operation), null); // assert Assert.Equal(expectedData, BytesStringUtil.DataToString(data)); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInformationRequestEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInformationRequestEncoderTest.cs index 8927302..6666388 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInformationRequestEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInformationRequestEncoderTest.cs @@ -15,7 +15,7 @@ public class PortInformationRequestEncoderTest public void PortInformationRequestEncoder_Encode(byte portId, PortInformationType informationType, string expectedData) { // arrange - var message = new PortInformationRequestMessage() { PortId = portId, InformationType = informationType }; + var message = new PortInformationRequestMessage(portId, informationType); // act var data = MessageEncoder.Encode(message, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoderTest.cs index a0a94c6..b55dc7a 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoderTest.cs @@ -15,11 +15,7 @@ public class PortInputFormatSetupCombinedModeEncoderTest public void PortInputFormatSetupCombinedModeEncoder_Encode_SimpleCommands(string expectedDataAsString, byte portId, PortInputFormatSetupCombinedSubCommand subCommand) { // arrange - var message = new PortInputFormatSetupCombinedModeMessage() - { - PortId = portId, - SubCommand = subCommand - }; + var message = new PortInputFormatSetupCombinedModeMessage(portId, subCommand); // act var data = MessageEncoder.Encode(message, null); @@ -29,20 +25,16 @@ public void PortInputFormatSetupCombinedModeEncoder_Encode_SimpleCommands(string } [Theory] - [InlineData("09-00-42-00-01-00-10-20-30", 0x00, PortInputFormatSetupCombinedSubCommand.SetModeAndDataSetCombination, new byte[] { 0x10, 0x20, 0x30 })] - public void PortInputFormatSetupCombinedModeEncoder_Encode_ModeDataSetCommands(string expectedDataAsString, byte portId, PortInputFormatSetupCombinedSubCommand subCommand, byte[] modeDataSets) + [InlineData("09-00-42-00-01-00-10-20-30", 0x00, new byte[] { 0x10, 0x20, 0x30 })] + public void PortInputFormatSetupCombinedModeEncoder_Encode_ModeDataSetCommands(string expectedDataAsString, byte portId, byte[] modeDataSets) { // arrange - var message = new PortInputFormatSetupCombinedModeForSetModeDataSetMessage() - { - PortId = portId, - SubCommand = subCommand, - ModeDataSets = modeDataSets.Select(b => new PortInputFormatSetupCombinedModeModeDataSet() - { - Mode = (byte)((b & 0xF0) >> 4), - DataSet = (byte)(b & 0x0F), - }).ToArray(), - }; + var message = new PortInputFormatSetupCombinedModeForSetModeDataSetMessage(portId, 0, + modeDataSets.Select(b => new PortInputFormatSetupCombinedModeModeDataSet( + Mode: (byte)((b & 0xF0) >> 4), + DataSet: (byte)(b & 0x0F) + )).ToArray() + ); // act var data = MessageEncoder.Encode(message, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupSingleEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupSingleEncoderTest.cs index 2cdc163..0c08c5d 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupSingleEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSetupSingleEncoderTest.cs @@ -11,13 +11,7 @@ public class PortInputFormatSetupSingleEncoderTest public void PortInputFormatSetupSingleEncoder_Encode(string expectedDataAsString, byte portId, byte mode, uint deltaInterval, bool notificationEnabled) { // arrange - var message = new PortInputFormatSetupSingleMessage() - { - PortId = portId, - Mode = mode, - DeltaInterval = deltaInterval, - NotificationEnabled = notificationEnabled, - }; + var message = new PortInputFormatSetupSingleMessage(portId, mode, deltaInterval, notificationEnabled); // act var data = MessageEncoder.Encode(message, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSingleEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSingleEncoderTest.cs index 8d67648..4d217e4 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSingleEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortInputFormatSingleEncoderTest.cs @@ -23,13 +23,9 @@ public void PortInputFormatSingleEncoder_Decode(string dataAsString, byte expect Assert.Equal(expectedNotificationEnabled, message.NotificationEnabled); // reverse - var reverseMessage = new PortInputFormatSingleMessage() + var reverseMessage = new PortInputFormatSingleMessage(expectedPortId, expectedMode, expectedDeltaInterval, expectedNotificationEnabled) { HubId = 0, - PortId = expectedPortId, - ModeIndex = expectedMode, - DeltaInterval = expectedDeltaInterval, - NotificationEnabled = expectedNotificationEnabled, }; var reverseData = MessageEncoder.Encode(reverseMessage, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortModeInformationRequestEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortModeInformationRequestEncoderTest.cs index 55a63f5..69c3fa9 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortModeInformationRequestEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortModeInformationRequestEncoderTest.cs @@ -23,7 +23,7 @@ public class PortModeInformationRequestEncoderTest public void PortModeInformationRequestEncoder_Encode(byte portId, byte mode, PortModeInformationType informationType, string expectedData) { // arrange - var message = new PortModeInformationRequestMessage() { PortId = portId, Mode = mode, InformationType = informationType }; + var message = new PortModeInformationRequestMessage(portId, mode, informationType); // act var data = MessageEncoder.Encode(message, null); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortOutputCommandEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortOutputCommandEncoderTest.cs index 0180949..c0bd225 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortOutputCommandEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortOutputCommandEncoderTest.cs @@ -1,5 +1,3 @@ -using System; -using SharpBrick.PoweredUp.Devices; using SharpBrick.PoweredUp.Protocol.Messages; using SharpBrick.PoweredUp.Utils; using Xunit; @@ -12,26 +10,22 @@ public class PortOutputCommandEncoderTest [Theory] [InlineData("09-00-81-00-11-05-B8-0B-01", 0, 3000, SpeedProfiles.AccelerationProfile)] public void PortOutputCommandEncoder_Encode_PortOutputCommandSetAccTimeMessage(string expectedData, byte port, ushort time, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetAccTimeMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = time, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetAccTimeMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Time: time, + Profile: profile + )); [Theory] [InlineData("09-00-81-00-11-06-E8-03-02", 0, 1000, SpeedProfiles.DecelerationProfile)] public void PortOutputCommandEncoder_Encode_PortOutputCommandSetDecTimeMessage(string expectedData, byte port, ushort time, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetDecTimeMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = time, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetDecTimeMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Time: time, + Profile: profile + )); [Theory] [InlineData("09-00-81-00-11-07-64-5A-03", 0, 100, 90, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile)] @@ -39,15 +33,13 @@ public void PortOutputCommandEncoder_Encode_PortOutputCommandSetDecTimeMessage(s [InlineData("09-00-81-00-11-07-9C-5A-03", 0, -100, 90, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile)] [InlineData("09-00-81-00-11-07-00-5A-03", 0, 0, 90, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeedMessage(string expectedData, byte port, sbyte speed, byte maxPower, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Speed = speed, - MaxPower = maxPower, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Speed: speed, + MaxPower: maxPower, + Profile: profile + )); [Theory] [InlineData("0A-00-81-00-11-08-64-64-5A-03", 0, 100, 100, 90, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile)] @@ -55,112 +47,98 @@ public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeedMessage(s [InlineData("0A-00-81-00-11-08-9C-64-5A-03", 0, -100, 100, 90, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile)] [InlineData("0A-00-81-00-11-08-00-64-5A-03", 0, 0, 100, 90, SpeedProfiles.AccelerationProfile | SpeedProfiles.DecelerationProfile)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeed2Message(string expectedData, byte port, sbyte speed1, sbyte speed2, byte maxPower, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeed2Message() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Speed1 = speed1, - Speed2 = speed2, - MaxPower = maxPower, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeed2Message( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Speed1: speed1, + Speed2: speed2, + MaxPower: maxPower, + Profile: profile + )); [Theory] [InlineData("0C-00-81-00-11-09-B8-0B-5A-64-7E-00", 0, 3000, 90, 100, SpecialSpeed.Hold, SpeedProfiles.None)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeedForTimeMessage(string expectedData, byte port, ushort time, sbyte speed, byte maxPower, SpecialSpeed endState, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForTimeMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = time, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForTimeMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Time: time, + Speed: speed, + MaxPower: maxPower, + EndState: endState, + Profile: profile + )); [Theory] [InlineData("0D-00-81-00-11-0A-B8-0B-5A-64-64-7E-00", 0, 3000, 90, 100, 100, SpecialSpeed.Hold, SpeedProfiles.None)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeedForTime2Message(string expectedData, byte port, ushort time, sbyte speed1, sbyte speed2, byte maxPower, SpecialSpeed endState, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForTime2Message() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Time = time, - Speed1 = speed1, - Speed2 = speed2, - MaxPower = maxPower, - EndState = endState, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForTime2Message( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Time: time, + Speed1: speed1, + Speed2: speed2, + MaxPower: maxPower, + EndState: endState, + Profile: profile + )); [Theory] [InlineData("0E-00-81-00-11-0B-B4-00-00-00-F6-64-7F-00", 0, 180, -10, 100, SpecialSpeed.Brake, SpeedProfiles.None)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeedForDegreesMessage(string expectedData, byte port, uint degrees, sbyte speed, byte maxPower, SpecialSpeed endState, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForDegreesMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Degrees = degrees, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForDegreesMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Degrees: degrees, + Speed: speed, + MaxPower: maxPower, + EndState: endState, + Profile: profile + )); [Theory] [InlineData("0F-00-81-00-11-0C-B4-00-00-00-F6-64-64-7F-00", 0, 180, -10, 100, 100, SpecialSpeed.Brake, SpeedProfiles.None)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartSpeedForDegrees2Message(string expectedData, byte port, uint degrees, sbyte speed1, sbyte speed2, byte maxPower, SpecialSpeed endState, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForDegrees2Message() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Degrees = degrees, - Speed1 = speed1, - Speed2 = speed2, - MaxPower = maxPower, - EndState = endState, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartSpeedForDegrees2Message( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Degrees: degrees, + Speed1: speed1, + Speed2: speed2, + MaxPower: maxPower, + EndState: endState, + Profile: profile + )); [Theory] [InlineData("0E-00-81-00-11-0D-2D-00-00-00-0A-64-7F-00", 0, 45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None)] [InlineData("0E-00-81-00-11-0D-D3-FF-FF-FF-0A-64-7F-00", 0, -45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None)] public void PortOutputCommandEncoder_Encode_PortOutputCommandGotoAbsolutePositionMessage(string expectedData, byte port, int absPosition, sbyte speed, byte maxPower, SpecialSpeed endState, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandGotoAbsolutePositionMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - AbsolutePosition = absPosition, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandGotoAbsolutePositionMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + AbsolutePosition: absPosition, + Speed: speed, + MaxPower: maxPower, + EndState: endState, + Profile: profile + )); [Theory] [InlineData("12-00-81-00-11-0E-2D-00-00-00-00-00-00-00-0A-64-7F-00", 0, 45, 0, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None)] [InlineData("12-00-81-00-11-0E-D3-FF-FF-FF-2D-00-00-00-0A-64-7F-00", 0, -45, 45, 10, 100, SpecialSpeed.Brake, SpeedProfiles.None)] public void PortOutputCommandEncoder_Encode_PortOutputCommandGotoAbsolutePosition2Message(string expectedData, byte port, int absPos1, int absPos2, sbyte speed, byte maxPower, SpecialSpeed endState, SpeedProfiles profile) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandGotoAbsolutePosition2Message() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - AbsolutePosition1 = absPos1, - AbsolutePosition2 = absPos2, - Speed = speed, - MaxPower = maxPower, - EndState = endState, - Profile = profile, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandGotoAbsolutePosition2Message( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + AbsolutePosition1: absPos1, + AbsolutePosition2: absPos2, + Speed: speed, + MaxPower: maxPower, + EndState: endState, + Profile: profile + )); [Theory] [InlineData("08-00-81-00-11-51-00-64", 0, 100)] @@ -168,13 +146,11 @@ public void PortOutputCommandEncoder_Encode_PortOutputCommandGotoAbsolutePositio [InlineData("08-00-81-00-11-51-00-9C", 0, -100)] [InlineData("08-00-81-00-11-51-00-00", 0, 0)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartPowerMessage(string expectedData, byte port, sbyte power) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartPowerMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Power = power - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartPowerMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Power: power + )); [Theory] [InlineData("08-00-81-00-11-02-64-0A", 0, 100, 10)] @@ -182,104 +158,94 @@ public void PortOutputCommandEncoder_Encode_PortOutputCommandStartPowerMessage(s [InlineData("08-00-81-00-11-02-9C-0A", 0, -100, 10)] [InlineData("08-00-81-00-11-02-00-0A", 0, 0, 10)] public void PortOutputCommandEncoder_Encode_PortOutputCommandStartPower2Message(string expectedData, byte port, sbyte power1, sbyte power2) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartPower2Message() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Power1 = power1, - Power2 = power2, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandStartPower2Message( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Power1: power1, + Power2: power2 + )); [Theory] [InlineData("0A-00-81-32-11-51-01-00-FF-00", 50, 0x00, 0xFF, 0x00)] public void PortOutputCommandEncoder_Encode_PortOutputCommandSetRgbColorNo2Message(string expectedData, byte port, byte r, byte g, byte b) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetRgbColorNo2Message() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - RedColor = r, - GreenColor = g, - BlueColor = b, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetRgbColorNo2Message( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + r, g, b + )); [Theory] [InlineData("08-00-81-32-11-51-00-05", 50, PoweredUpColor.Cyan)] public void PortOutputCommandEncoder_Encode_PortOutputCommandSetRgbColorNoMessage(string expectedData, byte port, PoweredUpColor color) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetRgbColorNoMessage() - { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - ColorNo = color, - }); + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandSetRgbColorNoMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + ColorNo: color + )); [Theory] [InlineData("0B-00-81-03-11-51-02-00-00-00-00", 3, 2, 0)] [InlineData("0B-00-81-01-11-51-03-0F-00-00-00", 1, 3, 15)] public void PortOutputCommandEncoder_Encode_PortOutputCommandPresetEncoderMessage(string expectedData, byte port, byte modeIndex, int position) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandPresetEncoderMessage() + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandPresetEncoderMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Position: position + ) { - PortId = port, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, ModeIndex = modeIndex, - Position = position, }); [Theory] [InlineData("0B-00-81-63-11-51-01-00-00-00-00", 99, 1, 0)] [InlineData("0B-00-81-63-11-51-01-0F-00-00-00", 99, 1, 15)] public void PortOutputCommandEncoder_Encode_PortOutputCommandTiltImpactPresetMessage(string expectedData, byte port, byte modeIndex, int presetValue) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandTiltImpactPresetMessage() + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandTiltImpactPresetMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + PresetValue: presetValue + ) { - PortId = port, ModeIndex = modeIndex, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - PresetValue = presetValue, }); [Theory] [InlineData("09-00-81-63-11-51-02-02-03", 99, 2, 2, 3)] [InlineData("09-00-81-63-11-51-02-04-05", 99, 2, 4, 5)] public void PortOutputCommandEncoder_Encode_PortOutputCommandTiltConfigImpactMessage(string expectedData, byte port, byte modeIndex, sbyte impactThreshold, sbyte bumpHoldoff) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandTiltConfigImpactMessage() + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandTiltConfigImpactMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + ImpactThreshold: impactThreshold, + BumpHoldoff: bumpHoldoff + ) { - PortId = port, ModeIndex = modeIndex, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - ImpactThreshold = impactThreshold, - BumpHoldoff = bumpHoldoff, }); [Theory] [InlineData("08-00-81-63-11-51-02-00", 99, 2, TiltConfigOrientation.Bottom)] [InlineData("08-00-81-63-11-51-02-03", 99, 2, TiltConfigOrientation.Left)] public void PortOutputCommandEncoder_Encode_PortOutputCommandTiltConfigOrientationMessage(string expectedData, byte port, byte modeIndex, TiltConfigOrientation orientation) - => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandTiltConfigOrientationMessage() + => PortOutputCommandEncoder_Encode(expectedData, new PortOutputCommandTiltConfigOrientationMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + Orientation: orientation + ) { - PortId = port, ModeIndex = modeIndex, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Orientation = orientation, }); [Theory] [InlineData("0A-00-81-63-11-51-02-01-02-03", 99, 2, new byte[] { 1, 2, 3 })] [InlineData("09-00-81-63-11-51-02-05-06", 99, 2, new byte[] { 5, 6 })] public void PortOutputCommandEncoder_Encode_GenericWriteDirectModeDataMessage(string expectedData, byte port, byte modeIndex, byte[] data) - => PortOutputCommandEncoder_Encode(expectedData, new GenericWriteDirectModeDataMessage(modeIndex) - { - PortId = port, - ModeIndex = modeIndex, - StartupInformation = PortOutputCommandStartupInformation.ExecuteImmediately, - CompletionInformation = PortOutputCommandCompletionInformation.CommandFeedback, - Data = data, - }); + => PortOutputCommandEncoder_Encode(expectedData, new GenericWriteDirectModeDataMessage( + port, + PortOutputCommandStartupInformation.ExecuteImmediately, PortOutputCommandCompletionInformation.CommandFeedback, + modeIndex, + data + )); private void PortOutputCommandEncoder_Encode(string expectedDataAsString, LegoWirelessMessage message) { diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueCombinedModeEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueCombinedModeEncoderTest.cs index 729298a..32a6519 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueCombinedModeEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueCombinedModeEncoderTest.cs @@ -21,18 +21,16 @@ public void PortValueCombinedModeEncoder_Decode(string dataAsString, byte expect .AddPoweredUp() .BuildServiceProvider(); - KnowledgeManager.ApplyDynamicProtocolKnowledge(new HubAttachedIOForAttachedDeviceMessage() { HubId = 0, IOTypeId = DeviceType.TechnicLargeLinearMotor, MessageType = MessageType.HubAttachedIO, Event = HubAttachedIOEvent.AttachedIO, PortId = 0x00, HardwareRevision = new Version("0.0.0.1"), SoftwareRevision = new Version("0.0.0.1") }, knowledge, serviceProvider.GetService()); - KnowledgeManager.ApplyDynamicProtocolKnowledge(new PortInputFormatSetupCombinedModeForSetModeDataSetMessage() - { - PortId = 0, - SubCommand = PortInputFormatSetupCombinedSubCommand.SetModeAndDataSetCombination, - CombinationIndex = 0, // should refer 0b0000_0000_0000_1110 => SPEED POS APOS - ModeDataSets = new PortInputFormatSetupCombinedModeModeDataSet[] { - new PortInputFormatSetupCombinedModeModeDataSet() { Mode = 0x01, DataSet = 0, }, - new PortInputFormatSetupCombinedModeModeDataSet() { Mode = 0x02, DataSet = 0, }, - new PortInputFormatSetupCombinedModeModeDataSet() { Mode = 0x03, DataSet = 0, }, + KnowledgeManager.ApplyDynamicProtocolKnowledge(new HubAttachedIOForAttachedDeviceMessage(0x00, DeviceType.TechnicLargeLinearMotor, new Version("0.0.0.1"), new Version("0.0.0.1")) { HubId = 0 }, knowledge, serviceProvider.GetService()); + KnowledgeManager.ApplyDynamicProtocolKnowledge(new PortInputFormatSetupCombinedModeForSetModeDataSetMessage( + PortId: 0x00, + CombinationIndex: 0, // should refer 0b0000_0000_0000_1110 => SPEED POS APOS + ModeDataSets: new PortInputFormatSetupCombinedModeModeDataSet[] { + new PortInputFormatSetupCombinedModeModeDataSet(0x01, 0), + new PortInputFormatSetupCombinedModeModeDataSet(0x02, 0), + new PortInputFormatSetupCombinedModeModeDataSet(0x03, 0), } - }, knowledge, serviceProvider.GetService()); + ), knowledge, serviceProvider.GetService()); // arrange var data = BytesStringUtil.StringToData(dataAsString); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueEncoderTest.cs index af72608..35ba6e1 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/PortValueEncoderTest.cs @@ -25,7 +25,7 @@ private void PortValueSingleEncoder_Decode(string dataAsString, byte expected .BuildServiceProvider(); - KnowledgeManager.ApplyDynamicProtocolKnowledge(new HubAttachedIOForAttachedDeviceMessage() { HubId = 0, IOTypeId = DeviceType.TechnicMediumHubTiltSensor, MessageType = MessageType.HubAttachedIO, Event = HubAttachedIOEvent.AttachedIO, PortId = 0x63, HardwareRevision = new Version("0.0.0.1"), SoftwareRevision = new Version("0.0.0.1") }, knowledge, serviceProvider.GetService()); + KnowledgeManager.ApplyDynamicProtocolKnowledge(new HubAttachedIOForAttachedDeviceMessage(0x63, DeviceType.TechnicMediumHubTiltSensor, new Version("0.0.0.1"), new Version("0.0.0.1")) { HubId = 0 }, knowledge, serviceProvider.GetService()); // arrange var data = BytesStringUtil.StringToData(dataAsString); diff --git a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/VirtualPortSetupEncoderTest.cs b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/VirtualPortSetupEncoderTest.cs index 298099f..dad9642 100644 --- a/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/VirtualPortSetupEncoderTest.cs +++ b/test/SharpBrick.PoweredUp.Test/Protocol/Formatter/VirtualPortSetupEncoderTest.cs @@ -12,7 +12,7 @@ public class VirtualPortSetupEncoderTest public void PortModeInformationRequestEncoder_Encode_Connected(byte portA, byte portB, string expectedData) { // arrange - var message = new VirtualPortSetupForConnectedMessage() { PortAId = portA, PortBId = portB, }; + var message = new VirtualPortSetupForConnectedMessage(portA, portB); // act var data = MessageEncoder.Encode(message, null); @@ -26,7 +26,7 @@ public void PortModeInformationRequestEncoder_Encode_Connected(byte portA, byte public void PortModeInformationRequestEncoder_Encode_Disconnected(byte port, string expectedData) { // arrange - var message = new VirtualPortSetupForDisconnectedMessage() { PortId = port, }; + var message = new VirtualPortSetupForDisconnectedMessage(port); // act var data = MessageEncoder.Encode(message, null);