-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFelica.cs
80 lines (64 loc) · 1.93 KB
/
Felica.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
using FelicaLiteLib.Args;
using FelicaLiteLib.Enums;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace FelicaLiteLib {
/// <summary>
/// Felicaリーダーのポーリング処理を制御するクラスです。
/// ここでイベント処理を追加してポーリングをすると使用できます。
/// </summary>
public class Felica : IDisposable {
/// <summary>
/// ポーリングに成功した時に発火するイベントです
/// </summary>
public event EventHandler<CardSetEventHandlerArgs> CardSetEvent;
private readonly FelicaDevice _Device;
public FelicaDevice Device => _Device;
private CancellationTokenSource cts;
public Felica() {
_Device = new FelicaDevice();
}
private Task PollingTask(CancellationToken token, ushort SystemCode, byte TimeSlot = 0) {
while (!token.IsCancellationRequested) {
if (_Device.Polling(SystemCode, TimeSlot)) {
// Polling 成功
CardSetEvent?.Invoke(this, new CardSetEventHandlerArgs(new FelicaCard(_Device)));
StopPolling(); // 自主的に終了させる
}
}
return Task.CompletedTask;
}
/// <summary>
/// ポーリングを開始します。
/// </summary>
/// <param name="System_Code">ポーリング対象のシステムコード</param>
public void StartPolling(SystemCode System_Code) {
if (cts is null) {
cts = new CancellationTokenSource();
Task.Run(async () => {
await PollingTask(cts.Token, (ushort) System_Code);
}).ConfigureAwait(false);
}
}
/// <summary>
/// ポーリングを終了します。
/// </summary>
/// <remarks>
/// ポーリング成功時は自動的に呼び出されます。
/// </remarks>
public void StopPolling() {
if (cts is null) return;
if (cts.IsCancellationRequested) return;
cts.Cancel();
cts.Dispose();
cts = null;
}
public void Dispose() {
_Device.Dispose();
}
~Felica() {
Dispose();
}
}
}