Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Program to see if there is a live connection with heaven
- import sys
- import time
- from datetime import datetime
- import zmq
- from zmq.eventloop.ioloop import IOLoop, PeriodicCallback
- from zmq.eventloop.zmqstream import ZMQStream
- context = zmq.Context()
- import infoPack_pb2
- # Set up publisher connection to send messages to the sendBroker
- publisher = context.socket(zmq.PUB)
- publisher.bind('tcp://*:12345')
- # Set up subscriber connection to receive the heartbeats back
- subscriber = context.socket(zmq.SUB)
- subscriber.connect('tcp://localhost:54321')
- subscriber.setsockopt(zmq.SUBSCRIBE, '')
- loop = IOLoop.instance()
- timeout = None
- subscriber = ZMQStream(subscriber, loop)
- handshake = False
- print('\nWait for handshake from heaven')
- def beat():
- """Send a heart beat"""
- global handshake
- beat = infoPack_pb2.heartBeat()
- beat.heartBeat = 1
- beatPb = beat.SerializeToString()
- publisher.send(beatPb)
- if handshake != False:
- sys.stdout.write('.')
- sys.stdout.flush()
- def handleSilence():
- """Call this function is no messages have been received in a while"""
- if handshake != False: print('Heaven is silent')
- resetTimeout()
- def resetTimeout():
- """Reset the timeout when no messages have been received"""
- global timeout
- if timeout: loop.remove_timeout(timeout)
- timeout = loop.add_timeout(time.time() + 2, handleSilence)
- def handleHeartBeat(message):
- """If a heartBeat has been received from hemel the timeout should be reset"""
- beat = infoPack_pb2.heartBeat()
- beat.ParseFromString(message)
- if beat.heartBeat == 1:
- global handshake
- if handshake == False:
- handshake = True
- print('Handshake received from heaven')
- resetTimeout()
- # Send heart beat every second
- sendHeartBeats = PeriodicCallback(beat, 1000, loop)
- sendHeartBeats.start()
- # Start inital 'no messages' timeout
- resetTimeout()
- # Set handler for received heartbeats
- subscriber.on_recv(handleHeartBeat)
- # Start event loop
- loop.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement