#!../../bin/linuxRT-x86_64/sim

## You may have to change iocSim to something else
## everywhere it appears in this file

< envPaths

# ===========================================
#            ENVIRONMENT VARIABLES
# ===========================================

# *********************************************
# **** Environment variables for YCPSWASYN ****

# CPSW Port name
epicsEnvSet("CPSW_PORT","SIM1")

# Yaml File
epicsEnvSet("YAML_FILE", "yaml/Lcls2PrlMaster_project.yaml/000TopLevel.yaml")

# FPGA IP address
epicsEnvSet("FPGA_IP", "192.168.1.20")

# Use Automatic generation of records from the YAML definition
# 0 = No, 1 = Yes
epicsEnvSet("AUTO_GEN", 1)

# Automatically generated record prefix
epicsEnvSet("PREFIX","SIM20")

# Dictionary file for manual (empty string if none)
epicsEnvSet("DICT_FILE", "")

epicsEnvSet("AREA","SYS2")

# Beckhoff 
epicsEnvSet("BKH_P",  "BKHF:$(AREA):MS02")
epicsEnvSet("PRL_P",  "PRL:$(AREA):11")
epicsEnvSet("LOC",    "L2CID-04")
epicsEnvSet("BKH_IP", "bkhf-sys2-ms02")

# *********************************************
# **** Environment variables for IOC Admin ****

epicsEnvSet(IOC_NAME,"SIOC:$(AREA):MS02")


cd ${TOP}

# ===========================================
#               DBD LOADING
# ===========================================
## Register all support components
dbLoadDatabase("dbd/sim.dbd",0,0)
sim_registerRecordDeviceDriver(pdbbase)

# ===========================================
#              DRIVER SETUP
# ===========================================

# ************************************
# **** Driver setup for YCPSWAsyn ****
## Configure asyn port driver
# YCPSWASYNConfig(
#    Port Name,                 # the name given to this port driver
#    Yaml Doc,                  # Path to the YAML file
#    Root Path                  # OPTIONAL: Root path to start the generation. If empty, the Yaml root will be used
#    IP Address,                # OPTIONAL: Target FPGA IP Address. If not given it is taken from the YAML file
#    Record name Prefix,        # Record name prefix
#    Record name Length Max,    # Record name maximum length (must be greater than lenght of prefix + 4)
#    Use DB Autogeneration,     # Set to 1 for autogeneration of records from the YAML definition. Set to 0 to disable it
#    Load dictionary,           # Dictionary file path with registers to load. An empty string will disable this function
#YCPSWASYNConfig("${CPSW_PORT}", "${YAML_FILE}", "", "${FPGA_IP}", "${PREFIX}", 50, "${AUTO_GEN}", "${DICT_FILE}")

cpswLoadYamlFile("${YAML_FILE}", "NetIODev", "yaml/Lcls2PrlMaster_project.yaml", "${FPGA_IP}")
cpswLoadConfigFile("yaml/config/sioc-sys2-ms02.yaml", "mmio", "yaml/config")

# ************************************
# **** Driver setup for YCPSWAsyn ****
# YCPSWASYNConfig(
#    PORT_NAME,             # the name given to this port driver
#    ROOT_PATH,             # root path to start the generation, if empty, the root will be used
#    PREFIX,                # record name prefix
#    AUTO_GEN_MODE,         # 0: disable auto-generation, 1: enable autogeneration using mapped names
#                           # 2: enable autogeneration using hashed names
#    DICIT_FILE             # dictionary file path with registers to load, an empty string will disable this function
# )
YCPSWASYNConfig("${CPSW_PORT}","", "${PREFIX}", "${AUTO_GEN}", "${DICT_FILE}")

# ************************************
# **** Driver setup for Beckhoff ****
drvAsynIPPortConfigure("$(BKH_P)", "$(BKH_IP):502", 0,0,1)
modbusInterposeConfig("$(BKH_P)", 0, 1000)
drvMBusConfig("$(BKH_P)", 0, 0, 125, 0, "$(BKH_P)", 10)
#
#
# drvBkhAsynConfig(id, port, func, addr, len, nch, msec)
# id is a unique module type identifier: 0 - coupler, 1 - analogSigned,
#     2 - analogUnsigned, 3 - digitalIn, 4 - digitalOut, 5 - motor.
# port is the asyn port name for the driver (pick a unique short name for each module as below)
# func is the modbus function (e.g. 5 - digitalOut, 2 - digitalIn, 3 - analog In/Out)
# addr is the modbus starting address of the memory image (group all modules of the same modbus function together)
# len is the length of the memory image, in bits (digital modules) or 16 bit words (analog modules)
# nch is the number of channels
# msec is poll routine timeout in milliseconds
#
# These are standard bus coupler commands
drvBkhAsynConfig(0,   "DEBUG", 3,      0, 125,  2,    0)
drvBkhAsynConfig(0,   "B900R", 3, 0x1000,  33, 33,    0)
drvBkhAsynConfig(0,   "B900W", 3, 0x110a,  26, 26,    0)
#
# These are for the bus terminals
drvBkhAsynConfig(3, "1408_01", 2,      0,   8,  8,  250)
drvBkhAsynConfig(4, "2408_01", 5,      0,   8,  8,    0)
drvBkhAsynConfig(4, "2124_01", 5,      8,   4,  4,    0)
drvBkhAsynConfig(4, "2124_02", 5,     12,   4,  4,    0)
drvBkhAsynConfig(2, "3172_01", 3,      0,   4,  2,  250)
drvBkhAsynConfig(1, "3222_01", 3,      4,   4,  2,  500)
drvBkhAsynConfig(2, "3122_01", 3,      8,   4,  2,  500)

# ===========================================
#               ASYN MASKS
# ===========================================

# **********************************
# **** Asyn Masks for YCPSWAsyn ****

#asynSetTraceMask(${PORT},, -1, 9)

# **********************************
# **** Asyn Masks for Beckhoff ****
#asynSetTraceIOMask("3172_01", 0, 4)
#asynSetTraceMask("3172_01", 0, 0x9)

# ===========================================
#               DB LOADING
# ===========================================

# ***************************
# **** Load YCPSWAsyn db ****

#Save/Load configuration related records
#dbLoadRecords("db/saveLoadConfig.db", "P=${AMC_CARRIER_PREFIX}, PORT=${CPSW_PORT}, SAVE_FILE=/tmp/configDump.yaml, LOAD_FILE=yaml/defaults_bergoz.yaml")

# Automatic initialization
#dbLoadRecords("db/monitorFPGAReboot.db", "P=${AMC_CARRIER_PREFIX}, KEY=-66686157")

# ***************************
# **** Load Beckhoff db ****
dbLoadRecords("db/bkh_l0vco.db", "P=$(BKH_P), PRL_P=$(PRL_P), LOC=$(LOC), IOC=$(IOC)")


# **************************************
# *** Load high level PVs for SIM module

dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:PHASESHIFT_RBV,DESC=Phase Shift Readback,EGU=Degree,INAM=,SNAM=getDegree,INPA=SIM20:M:PRLMST:PhaseShift:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:PHASEERR1,DESC=Raw Phase Error,EGU=Degree,INAM=,SNAM=getDegree,INPA=SIM20:M:PRLMST:RawPhiErr:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:PHASEERR2,DESC=Phi Phase Error,EGU=Degree,INAM=,SNAM=getDegree,INPA=SIM20:M:PRLMST:PhiErrFinal:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:W0SCALE_RBV,DESC=w0 scale readback,EGU=Hz,INAM=,SNAM=getFixed1805,INPA=SIM20:M:PRLMST:w0_scale:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:W1_RBV,DESC=w1 in radian,EGU=RAD,INAM=,SNAM=getFixed1805,INPA=SIM20:M:PRLMST:w1:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:PRAMPSLOPE_RBV,DESC=Phase Ramp Slope,EGU=Slope,INAM=,SNAM=getSigned18,INPA=SIM20:M:PRLMST:Phase_ramp_gain:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:ADCAMP0_RBV,DESC=ADC0_Amp volt,EGU=Volt,INAM=,SNAM=getADCVolt,INPA=SIM20:M:PRLMST:ADC0_Amp:Rd,SCAN=1 second")
dbLoadRecords("db/subRec.db", "NAME=PRL:SYS2:01:ADCAMP1_RBV,DESC=ADC1_Amp volt,EGU=Volt,INAM=,SNAM=getADCVolt,INPA=SIM20:M:PRLMST:ADC1_Amp:Rd,SCAN=1 second")

dbLoadRecords("db/subRecSet.db", "NAME=PRL:SYS2:01:PHASESHIFT,DESC=set value for phase shifter,INAM=,SNAM=setDegree,OUTPV=SIM20:M:PRLMST:PhaseShift:St")
dbLoadRecords("db/subRecSet.db", "NAME=PRL:SYS2:01:W0SCALE,DESC=set value for w0 scale,INAM=,SNAM=setFixed1805,OUTPV=SIM20:M:PRLMST:w0_scale:St")
dbLoadRecords("db/subRecSet.db", "NAME=PRL:SYS2:01:W1,DESC=w1 setvalue in radian,INAM=,SNAM=setFixed1805,OUTPV=SIM20:M:PRLMST:w1:St")
dbLoadRecords("db/subRecSet.db", "NAME=PRL:SYS2:01:PRAMPSLOPE,DESC=set value for slope,INAM=,SNAM=setSigned18,OUTPV=SIM20:M:PRLMST:Phase_ramp_gain:St")

dbLoadRecords("db/led.db", "NAME=PRL:SYS2:01:LED,INPPV=SIM20:M:PRLMST:LED:Rd,SCAN=1 second")

dbLoadRecords("db/bi.db", "NAME=PRL:SYS2:01:INPUTMUX_RBV,DESC=readback for input MUX,ZNAM=Chn1-Chn2,ONAM=Chn2-Chn1,INPPV=SIM20:M:PRLMST:Input_MUX:Rd,SCAN=1 second")
dbLoadRecords("db/bi.db", "NAME=PRL:SYS2:01:LOOPFILTER_RESET_RBV,DESC=readback for loop filter reset,ZNAM=Normal,ONAM=Reset,INPPV=SIM20:M:PRLMST:LoopReset:Rd,SCAN=1 second")
dbLoadRecords("db/bi.db", "NAME=PRL:SYS2:01:LOCKDISABLE_RBV,DESC=readback for loop lock disable,ZNAM=Enable,ONAM=Disable,INPPV=SIM20:M:PRLMST:LockDisable:Rd,SCAN=1 second")
dbLoadRecords("db/bi.db", "NAME=PRL:SYS2:01:LOCKRESET_RBV,DESC=readback for state machine reset,ZNAM=Normal,ONAM=Reset,INPPV=SIM20:M:PRLMST:StateReset:Rd,SCAN=1 second")

dbLoadRecords("db/bo.db", "NAME=PRL:SYS2:01:INPUTMUX,DESC=input mux,ZNAM=Chn1-Chn2,ONAM=Chn2-Chn1,OUTPV=SIM20:M:PRLMST:Input_MUX:St")
dbLoadRecords("db/bo.db", "NAME=PRL:SYS2:01:LOOPFILTER_RESET,DESC=loop filter reset,ZNAM=Normal,ONAM=Reset,OUTPV=SIM20:M:PRLMST:LoopReset:St")
dbLoadRecords("db/bo.db", "NAME=PRL:SYS2:01:LOCKDISABLE,DESC=loop lock disable,ZNAM=Enable,ONAM=Disable,OUTPV=SIM20:M:PRLMST:LockDisable:St")
dbLoadRecords("db/bo.db", "NAME=PRL:SYS2:01:LOCKRESET,DESC=state machine reset,ZNAM=Normal,ONAM=Reset,OUTPV=SIM20:M:PRLMST:StateReset:St")

dbLoadRecords("db/alias.db", "ALIAS=PRL:SYS2:01:SIMVER,REC=SIM20:M:PRLMST:Version:Rd")
dbLoadRecords("db/alias.db", "ALIAS=PRL:SYS2:01:LOCK,REC=SIM20:M:PRLMST:LockLogicState:Rd")



# **********************************************************************
# **** Load iocAdmin databases to support IOC Health and monitoring ****
dbLoadRecords("db/iocAdminSoft.db","IOC=${IOC_NAME}")
dbLoadRecords("db/iocAdminScanMon.db","IOC=${IOC_NAME}")

# The following database is a result of a python parser
# which looks at RELEASE_SITE and RELEASE to discover
# versions of software your IOC is referencing
# The python parser is part of iocAdmin
dbLoadRecords("db/iocRelease.db","IOC=${IOC_NAME}")

# ===========================================
#           SETUP AUTOSAVE/RESTORE
# ===========================================

# ============================================================
# If all PVs don't connect continue anyway
# ============================================================
save_restoreSet_IncompleteSetsOk(1)

# ============================================================
# created save/restore backup files with date string
# useful for recovery.
# ============================================================
save_restoreSet_DatedBackupFiles(1)

# ============================================================
# Where to find the list of PVs to save
# ============================================================
#set_requestfile_path("${IOC_DATA}/${IOC}/autosave-req")
set_requestfile_path("${IOC_DATA}/sioc-sys2-ms02", "autosave-req")

# ============================================================
# Where to write the save files that will be used to restore
# ============================================================
#set_savefile_path("${IOC_DATA}/${IOC}/autosave")
set_savefile_path("${IOC_DATA}/sioc-sys2-ms02", "autosave")

# ============================================================
# Prefix that is use to update save/restore status database
# records
# ============================================================
save_restoreSet_status_prefix("${IOC}:")

## Restore datasets
set_pass0_restoreFile("info_positions.sav")
set_pass1_restoreFile("info_positions.sav"
set_pass0_restoreFile("info_settings.sav")
set_pass1_restoreFile("info_settings.sav")


# ===========================================
#          CHANNEL ACESS SECURITY
# ===========================================
# This is required if you use caPutLog.
# Set access security filea
# Load common LCLS Access Configuration File
< ${ACF_INIT}


# ===========================================
#               IOC INIT
# ===========================================
iocInit()

# Turn on caPutLogging:
# Log values only on change to the iocLogServer:
caPutLogInit("${EPICS_CA_PUT_LOG_ADDR}")
caPutLogShow(2)


# Start autosave routines to save our data
# optional, needed if the IOC takes a very long time to boot.
#epicsThreadSleep( 1.0)

cd("/data/${IOC}/autosave-req")
makeAutosaveFiles()

# Start the save_restore task
# save changes on change, but no faster
# than every 5 seconds.
# Note: the last arg cannot be set to 0
create_monitor_set("info_positions.req", 5 )
create_monitor_set("info_settings.req" , 30 )

cd ${TOP}



dbpf("PRL:SYS2:01:LOCK.SCAN", "1 second")
dbpf("SIM20:M:HwC:TxFrameRate:Rd.SCAN", "1 second")
dbpf("SIM20:M:HwC:RxFrameRate:Rd.SCAN", "1 second")

