View difference between Paste ID: tvvSZeNR and zvCU4vx8
SHOW: | | - or go back to the newest paste.
1-
# Program to see if there is a live connection with hemel
1+
# Program to see if there is a live connection with heaven
2
import sys
3
import time
4
from datetime import datetime
5
6
import zmq
7
from zmq.eventloop.ioloop import IOLoop, PeriodicCallback
8
from zmq.eventloop.zmqstream import ZMQStream
9
context = zmq.Context()
10
11
import infoPack_pb2
12
13
# Set up publisher connection to send messages to the sendBroker
14
publisher = context.socket(zmq.PUB)
15
publisher.bind('tcp://*:12345')
16
17
# Set up subscriber connection to receive the heartbeats back
18
subscriber = context.socket(zmq.SUB)
19
subscriber.connect('tcp://localhost:54321')
20
subscriber.setsockopt(zmq.SUBSCRIBE, '')
21
22
loop = IOLoop.instance()
23
timeout = None
24
subscriber = ZMQStream(subscriber, loop)
25
26
handshake = False
27
print('\nWait for handshake from heaven')
28
29
def beat():
30
    """Send a heart beat"""
31
    global handshake
32
    beat = infoPack_pb2.heartBeat()
33
    beat.heartBeat = 1
34
    beatPb = beat.SerializeToString()
35
    publisher.send(beatPb)
36
    if handshake != False:
37
        sys.stdout.write('.')
38
        sys.stdout.flush()
39
40
def handleSilence():
41
    """Call this function is no messages have been received in a while"""
42
    if handshake != False: print('Heaven is silent')
43
    resetTimeout()
44
45
def resetTimeout():
46
    """Reset the timeout when no messages have been received"""
47
    global timeout
48
    if timeout: loop.remove_timeout(timeout)
49
    timeout = loop.add_timeout(time.time() + 2, handleSilence)
50
51
def handleHeartBeat(message):
52
    """If a heartBeat has been received from hemel the timeout should be reset"""
53
    beat = infoPack_pb2.heartBeat()
54
    beat.ParseFromString(message)
55
    if beat.heartBeat == 1:
56
        global handshake
57
        if handshake == False:
58
            handshake = True
59
            print('Handshake received from heaven')
60
        resetTimeout()
61
62
# Send heart beat every second
63
sendHeartBeats = PeriodicCallback(beat, 1000, loop)
64
sendHeartBeats.start()
65
# Start inital 'no messages' timeout
66
resetTimeout()
67
# Set handler for received heartbeats
68
subscriber.on_recv(handleHeartBeat)
69
# Start event loop
70
loop.start()