Skip to content

Commit d93e386

Browse files
authored
Cleanup IServiceProvider (as service locator usage)
- Remove many Service Locator usages - Move HubFactory to be based on DI - Move Protocol creation into DI and out of hub etc. - Adjust CLI - Fix await warnings #46 non-breaking (all types internal)
1 parent 061acb1 commit d93e386

41 files changed

Lines changed: 342 additions & 259 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

README.md

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,21 @@ Console.WriteLine($"Or directly read the latest value: {aposMode.SI} / {aposMode
159159
## Connect to Hub and Send a Message and retrieving answers (directly on protocol layer)
160160

161161
````csharp
162-
using (var kernel = new BluetoothKernel(poweredUpBluetoothAdapter, bluetoothAddress, loggerFactory.CreateLogger<BluetoothKernel>()))
163-
{
164-
var protocol = new PoweredUpProtocol(kernel);
165162

166-
await protocol.ConnectAsync();
163+
var serviceProvider = new ServiceCollection()
164+
.AddLogging()
165+
.AddPoweredUp()
166+
.AddSingleton<IPoweredUpBluetoothAdapter, WinRTPoweredUpBluetoothAdapter>() // using WinRT Bluetooth on Windows
167+
.BuildServiceProvider();
168+
169+
using (var scope = serviceProvider.CreateScope()) // create a scoped DI container per intented active connection/protocol. If disposed, disposes all disposable artifacts.
170+
{
171+
// init BT layer with right bluetooth address
172+
scope.ServiceProvider.GetService<BluetoothKernel>().BluetoothAddress = bluetoothAddress;
173+
174+
var protocol = scope.GetService<IPoweredUpProtocol>();
175+
176+
await protocol.ConnectAsync(); // also connects underlying BT connection
167177
168178
using disposable = protocol.UpstreamMessages.Subscribe(message =>
169179
{
@@ -178,7 +188,7 @@ using (var kernel = new BluetoothKernel(poweredUpBluetoothAdapter, bluetoothAddr
178188
Operation = HubPropertyOperation.RequestUpdate
179189
});
180190

181-
Console.Readline(); // allow the messages to be processed and displayed.
191+
Console.Readline(); // allow the messages to be processed and displayed. (alternative: SendMessageReceiveResultAsync, SendPortOutputCommandAsync, ..)
182192
183193
// fun with light on hub 0 and built-in LED on port 50
184194
var rgbLight = new RgbLight(protocol, 0, 50);
@@ -209,6 +219,26 @@ Basic Architecture within the SDK
209219
+---------+
210220
````
211221

222+
223+
DI Container Elements
224+
225+
````
226+
PoweredUpHost +----+
227+
+ |
228+
| |
229+
+-------------------- Scoped Service Provider ---------------------+
230+
| | | |
231+
| v +--->IPoweredUp
232+
| LinearMidCalibration + HubFactory | | BluetoothAdapter
233+
| | | |
234+
| TechnicMediumHub +---+-> PoweredUpProtocol +-> BluetoothKernel + |
235+
| + + |
236+
| | | |
237+
| +-----------------------+--------> DeviceFactory |
238+
| |
239+
+------------------------------------------------------------------+
240+
````
241+
212242
## Implementation Status
213243

214244
- Bluetooth Adapter

examples/SharpBrick.PoweredUp.Examples/BaseExample.cs

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ namespace Example
1212
{
1313
public abstract class BaseExample
1414
{
15-
protected PoweredUpHost host;
16-
protected IServiceProvider serviceProvider;
17-
public Hub selectedHub;
15+
protected PoweredUpHost Host { get; set; }
16+
protected IServiceProvider ServiceProvider { get; set; }
17+
public Hub SelectedHub { get; set; }
18+
19+
public ILogger Log { get; private set; }
1820

1921
public abstract Task ExecuteAsync();
2022

@@ -27,46 +29,47 @@ public virtual void Configure(IServiceCollection serviceCollection)
2729
public async Task InitHostAndDiscoverAsync(bool enableTrace)
2830
{
2931
InitHost(enableTrace);
32+
33+
Log = ServiceProvider.GetService<ILoggerFactory>().CreateLogger("Example");
34+
3035
await DiscoverAsync(enableTrace);
3136
}
3237

3338
public virtual Task DiscoverAsync(bool enableTrace)
3439
{
35-
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger("Main");
36-
3740
Hub result = null;
3841

39-
logger.LogInformation("Finding Service");
42+
Log.LogInformation("Finding Service");
4043
var cts = new CancellationTokenSource();
41-
host.Discover(async hub =>
44+
Host.Discover(async hub =>
4245
{
4346
// add this when you are interested in a tracing of the message ("human readable")
4447
if (enableTrace)
4548
{
46-
var tracer = new TraceMessages(hub.Protocol, serviceProvider.GetService<ILoggerFactory>().CreateLogger<TraceMessages>());
49+
var tracer = hub.ServiceProvider.GetService<TraceMessages>();
4750

4851
await tracer.ExecuteAsync();
4952
}
5053

51-
logger.LogInformation("Connecting to Hub");
54+
Log.LogInformation("Connecting to Hub");
5255
await hub.ConnectAsync();
5356

5457
result = hub;
5558

56-
logger.LogInformation(hub.AdvertisingName);
57-
logger.LogInformation(hub.SystemType.ToString());
59+
Log.LogInformation(hub.AdvertisingName);
60+
Log.LogInformation(hub.SystemType.ToString());
5861

5962
cts.Cancel();
6063

61-
logger.LogInformation("Press RETURN to continue to the action");
64+
Log.LogInformation("Press RETURN to continue to the action");
6265
}, cts.Token);
6366

64-
logger.LogInformation("Press RETURN to cancel Scanning");
67+
Log.LogInformation("Press RETURN to cancel Scanning");
6568
Console.ReadLine();
6669

6770
cts.Cancel();
6871

69-
selectedHub = result;
72+
SelectedHub = result;
7073

7174
return Task.CompletedTask;
7275
}
@@ -90,9 +93,9 @@ public void InitHost(bool enableTrace)
9093

9194
Configure(serviceCollection);
9295

93-
serviceProvider = serviceCollection.BuildServiceProvider();
96+
ServiceProvider = serviceCollection.BuildServiceProvider();
9497

95-
host = serviceProvider.GetService<PoweredUpHost>();
98+
Host = ServiceProvider.GetService<PoweredUpHost>();
9699
}
97100
}
98101
}

examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByKnownAddress.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ public class ExampleBluetoothByKnownAddress : BaseExample
1212
// device needs to be switched on!
1313
public override async Task DiscoverAsync(bool enableTrace)
1414
{
15-
var hub = host.Create<TechnicMediumHub>(ChangeMe_BluetoothAddress);
15+
var hub = Host.Create<TechnicMediumHub>(ChangeMe_BluetoothAddress);
1616

17-
selectedHub = DirectlyConnectedHub = hub;
17+
SelectedHub = DirectlyConnectedHub = hub;
1818

1919
await hub.ConnectAsync();
2020
}

examples/SharpBrick.PoweredUp.Examples/ExampleBluetoothByName.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class ExampleBluetoothByName : BaseExample
1010

1111
public override async Task ExecuteAsync()
1212
{
13-
using (var technicMediumHub = host.FindByName<TechnicMediumHub>("Technic Hub"))
13+
using (var technicMediumHub = Host.FindByName<TechnicMediumHub>("Technic Hub"))
1414
{
1515
await technicMediumHub.RgbLight.SetRgbColorsAsync(0xff, 0x00, 0x00);
1616

examples/SharpBrick.PoweredUp.Examples/ExampleCalibrationSteering.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ public class ExampleCalibrationSteering : BaseExample
1010
{
1111
public override async Task ExecuteAsync()
1212
{
13-
using (var technicMediumHub = host.FindByType<TechnicMediumHub>())
13+
using (var technicMediumHub = Host.FindByType<TechnicMediumHub>())
1414
{
1515
var motor = technicMediumHub.A.GetDevice<TechnicLargeLinearMotor>();
1616

17-
var calibration = serviceProvider.GetService<LinearMidCalibration>();
17+
var calibration = ServiceProvider.GetService<LinearMidCalibration>();
1818
await calibration.ExecuteAsync(motor);
1919

2020
await Task.Delay(5000);

examples/SharpBrick.PoweredUp.Examples/ExampleColors.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class ExampleColors : BaseExample
88
{
99
public override async Task ExecuteAsync()
1010
{
11-
using (var technicMediumHub = host.FindByType<TechnicMediumHub>())
11+
using (var technicMediumHub = Host.FindByType<TechnicMediumHub>())
1212
{
1313
await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0x00);
1414

examples/SharpBrick.PoweredUp.Examples/ExampleDiscoverByType.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ public class ExampleDiscoverByType : BaseExample
1111
// device needs to be switched on!
1212
public override async Task DiscoverAsync(bool enableTrace)
1313
{
14-
var hub = await host.DiscoverAsync<TechnicMediumHub>();
14+
var hub = await Host.DiscoverAsync<TechnicMediumHub>();
1515

16-
selectedHub = DirectlyConnectedHub = hub;
16+
SelectedHub = DirectlyConnectedHub = hub;
1717

1818
await hub.ConnectAsync();
1919
}

examples/SharpBrick.PoweredUp.Examples/ExampleDynamicDevice.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,7 @@ public override void Configure(IServiceCollection services)
3030

3131
public override async Task ExecuteAsync()
3232
{
33-
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<ExampleDynamicDevice>();
34-
35-
using (var technicMediumHub = host.FindByType<TechnicMediumHub>())
33+
using (var technicMediumHub = Host.FindByType<TechnicMediumHub>())
3634
{
3735
// deployment model verification with unknown devices
3836
await technicMediumHub.VerifyDeploymentModelAsync(mb => mb
@@ -47,7 +45,7 @@ await technicMediumHub.VerifyDeploymentModelAsync(mb => mb
4745

4846
// discover the unknown device using the LWP
4947
await dynamicDeviceWhichIsAMotor.DiscoverAsync();
50-
logger.LogInformation("Discovery completed");
48+
Log.LogInformation("Discovery completed");
5149

5250
// use combined mode values from the device
5351
await dynamicDeviceWhichIsAMotor.TryLockDeviceForCombinedModeNotificationSetupAsync(2, 3);
@@ -61,8 +59,8 @@ await technicMediumHub.VerifyDeploymentModelAsync(mb => mb
6159
var aposMode = dynamicDeviceWhichIsAMotor.SingleValueMode<short>(3);
6260

6361
// use their observables to report values
64-
using var disposable = posMode.Observable.Subscribe(x => logger.LogWarning($"Position: {x.SI} / {x.Pct}"));
65-
using var disposable2 = aposMode.Observable.Subscribe(x => logger.LogWarning($"Absolute Position: {x.SI} / {x.Pct}"));
62+
using var disposable = posMode.Observable.Subscribe(x => Log.LogWarning($"Position: {x.SI} / {x.Pct}"));
63+
using var disposable2 = aposMode.Observable.Subscribe(x => Log.LogWarning($"Absolute Position: {x.SI} / {x.Pct}"));
6664

6765
// or even write to them
6866
await powerMode.WriteDirectModeDataAsync(0x64); // That is StartPower on a motor

examples/SharpBrick.PoweredUp.Examples/ExampleHubActions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class ExampleHubActions : BaseExample
88
{
99
public override async Task ExecuteAsync()
1010
{
11-
using (var technicMediumHub = host.FindByType<TechnicMediumHub>())
11+
using (var technicMediumHub = Host.FindByType<TechnicMediumHub>())
1212
{
1313
await technicMediumHub.RgbLight.SetRgbColorsAsync(0x00, 0xff, 0xff);
1414

examples/SharpBrick.PoweredUp.Examples/ExampleHubAlert.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class ExampleHubAlert : BaseExample
88
{
99
public override async Task ExecuteAsync()
1010
{
11-
using (var technicMediumHub = host.FindByType<TechnicMediumHub>())
11+
using (var technicMediumHub = Host.FindByType<TechnicMediumHub>())
1212
{
1313
technicMediumHub.AlertObservable.Subscribe(x => Console.WriteLine($"Alert: {x}"));
1414

0 commit comments

Comments
 (0)