-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathLightbulb.cs
133 lines (114 loc) · 3.79 KB
/
Lightbulb.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
using System.Threading.Tasks;
using Orleankka;
using Orleankka.Behaviors;
using Orleans;
namespace Example
{
[Serializable, GenerateSerializer] public class PressSwitch {}
[Serializable, GenerateSerializer] public class Touch {}
[Serializable, GenerateSerializer] public class HitWithHammer {}
[Serializable, GenerateSerializer] public class Fix {}
public interface ILightbulb : IActorGrain, IGrainWithStringKey {}
public class Lightbulb : ActorGrain, ILightbulb
{
readonly Behavior behavior;
public Lightbulb()
{
behavior = new Behavior();
behavior.Initial(Off);
}
public override async Task<object> Receive(object message)
{
var result = await DoReceive(message);
if (behavior.Previous != behavior.Current)
await SaveState();
return result;
}
static Task SaveState() => Task.CompletedTask;
Task LoadState() => Task.CompletedTask;
async Task<object> DoReceive(object message)
{
// any "global" message handling here
switch (message)
{
case Activate _ :
await LoadState();
return Done;
case HitWithHammer _ when behavior.Current.Name != nameof(Smashed):
await behavior.BecomeStacked(Smashed);
return "Smashed!";
case Deactivate _:
Console.WriteLine("Deactivated");
await Task.Delay(2000);
return "";
}
// if not handled, use behavior specific
return await behavior.Receive(message);
}
async Task<object> Smashed(object message)
{
switch (message)
{
case PressSwitch _:
return "Broken";
case Touch _:
return "OW!";
case Fix _:
await behavior.Unbecome();
return "Fixed";
default:
return Unhandled;
}
}
async Task<object> Off(object message)
{
switch (message)
{
case PressSwitch _:
await behavior.Become(On);
return "Turning on";
case Touch _:
return "Cold";
default:
return Unhandled;
}
}
async Task<object> On(object message)
{
switch (message)
{
case Reminder _:
Console.WriteLine("Reminded");
return Done;
case Activate _:
await NotifyLightsOn();
return "";
case Deactivate _:
await CleanupOn();
return "";
case PressSwitch _:
await behavior.Become(Off);
return "Turning off";
case Touch _:
return "Hot!";
default:
return Unhandled;
}
async Task NotifyLightsOn()
{
await Reminders.Register("123", TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60));
Timers.Register("123", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), () =>
{
Console.WriteLine("Lights, on!!!");
return Task.CompletedTask;
});
}
async Task CleanupOn()
{
Timers.Unregister("123");
await Reminders.Unregister("123");
}
}
}
}