-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathProgram.cs
87 lines (71 loc) · 2.21 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
using System;
using System.Threading;
using System.Device.Gpio;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Hosting
{
public class Program
{
public static void Main()
{
IHostBuilder builder = new HostBuilder();
builder.ConfigureServices(services =>
{
services.AddSingleton(typeof(HardwareService));
services.AddHostedService(typeof(LedHostedService));
});
IHost host = builder.Build();
// blink for 5 seconds and then stop and dispose of host
host.StartAsync();
Thread.Sleep(5000);
host.StopAsync();
host.Dispose();
}
}
internal class HardwareService : IDisposable
{
public GpioController GpioController { get; private set; }
public HardwareService()
{
GpioController = new GpioController();
}
public void Dispose()
{
GpioController.Dispose();
}
}
internal class LedHostedService : BackgroundService
{
private readonly HardwareService _hardware;
public LedHostedService(HardwareService hardware)
{
_hardware = hardware;
}
public override void StartAsync(CancellationToken cancellationToken)
{
Debug.WriteLine("LED Hosted Service running.");
base.StartAsync(cancellationToken);
}
protected override void ExecuteAsync(CancellationToken cancellationToken)
{
var ledPin = 16;
GpioPin led = _hardware.GpioController.OpenPin(ledPin, PinMode.Output);
while (!cancellationToken.IsCancellationRequested)
{
led.Toggle();
Thread.Sleep(100);
}
}
public override void StopAsync(CancellationToken cancellationToken)
{
Debug.WriteLine("LED Hosted Service stopped.");
base.StopAsync(cancellationToken);
}
}
}