71 lines
2.2 KiB
Python
71 lines
2.2 KiB
Python
import zmq
|
|
import socket
|
|
import sys
|
|
|
|
class ZMQBase:
|
|
def __init__(self, host='127.0.0.1',port = 5678):
|
|
|
|
self.host=host
|
|
self.port = port
|
|
self.msg={'action':'','PV':'','host':'','pid':0}
|
|
|
|
self.REQUEST_TIMEOUT = 500
|
|
self.REQUEST_RETRIES = 2
|
|
self.SERVER_ENDPOINT = "tcp://%s:%d" % (host,port)
|
|
self.serverIsOffline=False # assume that it is online
|
|
|
|
def ZMQServerInfo(self,PVroot,host,pid):
|
|
self.msg['PV']=PVroot
|
|
self.msg['host']=host
|
|
self.msg['pid']=pid
|
|
|
|
|
|
def ZMQPoll(self,tag='ping'):
|
|
self.msg['action']=tag
|
|
context = zmq.Context()
|
|
client = context.socket(zmq.REQ)
|
|
client.connect(self.SERVER_ENDPOINT)
|
|
client.send_pyobj(self.msg)
|
|
|
|
retries_left = self.REQUEST_RETRIES
|
|
while True:
|
|
if (client.poll(self.REQUEST_TIMEOUT) & zmq.POLLIN) != 0:
|
|
reply = client.recv_pyobj()
|
|
check = self.ZMQIdentifyReply(reply)
|
|
if self.serverIsOffline:
|
|
self.logger.info("Watchdog server came online")
|
|
self.serverIsOffline=False
|
|
if check:
|
|
if reply['action'] == 'quit':
|
|
client.close()
|
|
context.term()
|
|
return (reply['action'] == 'quit')
|
|
else:
|
|
self.logger.warning("Malformed reply from server")
|
|
continue
|
|
|
|
retries_left -= 1
|
|
# Socket is confused. Close and remove it.
|
|
client.setsockopt(zmq.LINGER, 0)
|
|
client.close()
|
|
if retries_left == 0:
|
|
if not self.serverIsOffline:
|
|
self.logger.info("Watchdog server seems to be offline")
|
|
self.serverIsOffline=True
|
|
context.term()
|
|
return False
|
|
|
|
# Create new connection
|
|
client = context.socket(zmq.REQ)
|
|
client.connect(self.SERVER_ENDPOINT)
|
|
client.send_pyobj(self.msg)
|
|
|
|
|
|
def ZMQIdentifyReply(self,reply):
|
|
for field in ['PV','host','pid']:
|
|
if not reply[field] == self.msg[field]:
|
|
return False
|
|
return True
|
|
|
|
|