#!/usr/bin/env python
from __future__ import print_function

import os
import epics
import time

@epics.ca.withCA
def getMultiplePVs(pvs, timeout):
    '''Get the values of multiple PV's - wait for a timeout. PVs is a list of PVs; we return a list of values'''
    pv2chids = {}
    pv2vals = {}
    os.environ['EPICS_CA_CONN_TMO'] = str(timeout)
    def connect_cb(pvname, chid, conn):
        pv2chids[pvname] = chid
        try:
            # If the IOC goes down between the channel connect and the get, we'd get a virtual circuit disconnect connectionException
            val = epics.ca.get(chid, wait=False, timeout=None)
            if val:
                pv2vals[pvname] = val
        except Exception:
            pass
    for pv in pvs:
        channel = epics.ca.create_channel(pv, connect=False, callback=connect_cb)
    time.sleep(timeout)
    for pv in pvs:
        if pv in pv2chids:
            val = epics.ca.get_complete(pv2chids[pv])
            if val:
                pv2vals[pv] = val
    return pv2vals


if __name__ == "__main__":
    pvs = ['SIOC:SYS0:ML00:APP_DIR1', 'SIOC:SYS0:ML00:Non_Existent', 'SIOC:SYS0:ML00:APP_DIR2', 'SIOC:SYS0:ML00:APP_DIR3_Nonexistent', 'SIOC:SYS0:ML00:Non_Existent2']
    vals = getMultiplePVs(pvs, 5)
    print(vals)
