# Set EPICS record SCAN field for the auto-generated
# FEED register readback PVs. This is to aid in acquisition 
# of long data sets. It has been observed that there are
# missing waveform data at the 10-second EPICS scan task rate.

import re
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-f','--dbfile',help='db file, rfCryomoduleShort.db',dest='dbfile',type=str,default='/usr/local/lcls/epics/iocCommon/sioc-l1b-rf01/iocSpecificRelease/db/rfCryomoduleShort.db')
parser.add_argument('-c','--cryomodule',help='set PVs for which cryomodule: 2 for cryomodule 200, 3 for cryomodule 300, default 0 for both cryomodule 2 and 3',dest='cryo',type=int,default=0,choices=[0,2,3])
parser.add_argument('-s','--scan',help='scan on/off, scan on means use the default 10 second scan, scan off means passive',dest='scan',type=str,choices=['on','off'],required=True)
clargs=parser.parse_args()

cryolist={0:[2,3],2:[2],3:[3]}
cryo=cryolist[clargs.cryo]
scan=True if clargs.scan=='on' else False

f=open(clargs.dbfile)
s=f.read()
f.close()
s1=re.sub('#([\s\S]*?)$','',s,flags=re.M)
rs=re.findall('record\((?P<pvtype>\S+),\s*"(?P<pvname>\S+)"\)\s*\{([\S\s]*?)\}',s1)
pvlist=[i[1] for i in rs if re.match('[\s\S]*REGSCAN[\s\S]*',i[2])]
pva=[re.sub('\$\(CM,undefined\)','ACCL:L1B:0%d',pv) for pv in pvlist]
pvb=[re.sub('\$\(CM,recursive\)','ACCL:L1B:0%d',pv) for pv in pva]
pvs=[]
for d in cryo:#[2]:#,3]:
    pvs.extend([i%d for i in pvb])

import cothread
import cothread.catools as ca
length=len(pvs)
index=1
for pv in pvs:
    scanval=ca.caget('%s.SCAN'%pv)
# 10 second: .SCAN = 3
# Passive: .SCAN = 0

    if scan:
	val = 3
    else:
	val = 0

    # Set .SCAN to requested value unless already set to that value
    if scanval != val:
        ca.caput('%s.SCAN'%pv, val)
        print '%d of %d setting '%(index,length),val,pv
    else:
        print '%d of %d passing'%(index,length),scanval,pv

    index=index+1

#cavity prefix:
#ACCL:L1B:0xx0:
#    cm prefix:
#ACCL:L1B:0x00:
#$(CM,undefined)00:RFS1A:REG11_RBV
