import zmq
import time
import psana
import numpy as np

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:12322")
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)

#run = 8
#ds = psana.DataSource('exp=xppl3816:run=%d:smd' %run)
ds = psana.DataSource('shmem=XPP.0:stop=no')
epics = ds.env().epicsStore()
opal_0_detector = psana.Detector('opal_0')
opal_1_detector = psana.Detector('opal_1')
#ipm3_src = psana.Source('BldInfo(XppSb3_Ipm)')

t0 = time.time()
for i, evt in enumerate(ds.events()):
    events = dict(poller.poll(0))
    if socket in events and events[socket] == zmq.POLLIN:
        opal_0 = opal_0_detector.raw(evt)
        opal_1 = opal_1_detector.raw(evt)
        cntr = ds.env().configStore().get(psana.ControlData.ConfigV3, psana.Source()).pvControls()
        if len(cntr) > 0:
          cpvName = cntr[0].name()
          cpvValue = cntr[0].value()
        else:
          cpvName = None
          cpvValue = None
    
        if opal_0 is None or opal_1 is None:
            print 'missing opal'
            continue
        message = socket.recv()
        socket.send_pyobj( dict( opal0 = opal_0, opal1 = opal_1, cPv = dict(name=cpvName,value=cpvValue)) )
        print 'Shot',i, 'sent; time since starting:', time.time()-t0


