bitcoin-atm
bitcoin atm for pyc inc.
git clone https://9o.is/git/bitcoin-atm.git
Network.scala
(2356B)
1 package inc.pyc.chimera
2
3 import akka.actor._
4 import concurrent._
5 import duration._
6 import dispatch._
7
8 trait NetworkHelper {
9 this: Overlord with FSM[State, Data] =>
10
11 /**
12 * Interval to ping the network.
13 */
14 val pingInterval: FiniteDuration = 20 seconds
15
16 /**
17 * Network Actor
18 */
19 lazy val network = context.actorOf(
20 Props(classOf[Network], pingInterval), "Network")
21
22 /**
23 * Initializes the network actor
24 * by sending it a ping.
25 */
26 final def initNetwork {
27 network ! "ping"
28 }
29
30 /**
31 * Stops the network actor from checking connection.
32 */
33 final def stopNetwork {
34 network ! PoisonPill
35 }
36
37 when(NetworkOutage) {
38 case Event(NetworkOutage, r: Reason) =>
39 stay
40
41 case Event(NetworkEstablished, _) =>
42 log info "Network reestablished"
43 goto (Idle) using NullData
44 }
45
46 /**
47 * Add this to unhandled `StateFunction`.
48 * Notifies that the network is unreachable and
49 * becomes `Malfunctioning`
50 */
51 def handleNetworkOutage: StateFunction = {
52 case Event(NetworkOutage, _) =>
53 log error "Network unreachable"
54 val reason =
55 if(sensitiveState) Reason(Msg.networkUnreachableTx)
56 else Reason(Msg.networkUnreachable)
57
58 goto (NetworkOutage) using reason
59 }
60 }
61
62 /**
63 * Checks network connectivity.
64 * @param n interval to check connection in seconds.
65 */
66 class Network(n: FiniteDuration) extends Actor with ActorLogging {
67 import Defaults._
68 import context.system
69
70 val ping = "https://www.google.com/"
71
72 override def preStart {
73 system.scheduler.schedule(n, n, self, "ping")
74 }
75
76 def receive: Receive = {
77 case "ping" =>
78 check(operating = true)
79 }
80
81 def disconnected: Receive = {
82 case "ping" =>
83 check(operating = false)
84 }
85
86 def check(operating: Boolean) {
87 Http(url(ping) OK as.String).either() match {
88 case Left(_) =>
89 context.become(disconnected)
90 if(operating) {
91 context.parent ! NetworkOutage
92 }
93
94 case Right(_) =>
95 context.become(receive)
96 if(!operating) {
97 context.parent ! NetworkEstablished
98 }
99 }
100 }
101 }
102
103 /**
104 * The network is okay.
105 */
106 case object NetworkEstablished