#==============================================================
#
#  Abs:  Generic MPS Link Node Start Up
#
#  Name:  st.cmd.mps
#
#  Rem:  Upon entry we expect to be at location TOP
#        and the following macros must be defined.
#        Note that all other environment variables 
#        used within this file are defined in envPaths.
#
#           EPICS_IOCS            - Top level boot dir for all iocs
#           ACF_FILE              - Access Control File with path  
#           INIT_ACF              - CA security seutp file including path
#           INIT_LOG              - log message seutp file including path
#           EPICS_CA_PUT_LOG_ADDR - iocLogAndFwdServer on host
#
#         defined in app st.cmd
#           IOC_NAME       - IOC Device name   (ie. SIOC:BC2B:SP01)
#           LOCATION       - Location of IOC   (ie. cpu-bc2b-sp01)
#           LOCA           - Machine Area      (ie. BC2B)
#           LOCATION_INDEX - IOC unit          (ie. 01, for SP01)
#           SLOT           - TPR Instance      (ie. 0)
#           
#         Upon exit, this script will leave the ioc sitting
#         at the application TOP directory.
#
#         WARNING!!!
#         The TOP environment variable is defined in
#         envPaths, however in development (afs), the 
#         definitionmay include "slac.stanford.edu", which is
#         not understood by linuxRT. However, when "cram" is used
#         to release to production,"slac" is substituted for
#         "slac.stanford.edu", which fixes the problem.  
#
#  Facility:  EED Shared Platform Controls
#
#  Auth: 09-Sep-2021, K. Leleux       (KLELEUX)
#  Rev:  dd-mmm-yyyy, Reviewer's Name (USERNAME)
#--------------------------------------------------------------
#  Mod:
#        11-May-2022, K. Luchini      (LUCHINI):
#          extracted from atca_receiver.cmd
#
#==============================================================
#
# Set environment variables
epicsEnvSet("ENGINEER","Jeremy Mock")
< ../../common/st.cmd

# Set environment variables for yaml
# CPSW Port names
epicsEnvSet("L2MPSASYN_PORT","L2MPSASYN_PORT")
epicsEnvSet("YCPSWASYN_PORT","YCPSWASYN_PORT")

# Point 'YAML_PATH' to the yaml_fixes directory
epicsEnvSet("YAML_PATH", "${TOP}/firmware/yaml_fixes")

# Location to download the YAML file from the FPGA
epicsEnvSet("YAML_DIR","${IOC_DATA}/${IOC}/yaml")

# YAML file
epicsEnvSet("YAML","${YAML_DIR}/000TopLevel.yaml")

# YCPSWASYN Dictionary file
epicsEnvSet("YCPSWASYN_DICT_FILE", "firmware/llrf_bsa.dict")

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

## yamlDownloader
DownloadYamlFile("${FPGA_IP}", "${YAML_DIR}")

## yamlLoader
cpswLoadYamlFile("${YAML}", "NetIODev", "", "${FPGA_IP}")

# ==========================================
# Load default configurations
# ==========================================
# Load the default configuration
# cpswLoadConfigFile("${DEFAULTS_FILE}", "mmio")

## Set MPS Configuration location
# setMpsConfigurationPath(
#   Path)                   # Path to the MPS configuraton TOP directory
setMpsConfigurationPath("${FACILITY_ROOT}/physics/mps_configuration/current/link_node_db")

# ==========================================
#    Driver setup for L2MPSASYNConfig 
# ==========================================
## Configure asyn port driver
# L2MPSASYNConfig(
#    Port Name)                 # the name given to this port driver
L2MPSASYNConfig("${L2MPSASYN_PORT}")

# In DEV, the MpsManager runs in lcls-dev3, default port number.
# Don't think this is needed. -KEL
# L2MPSASYNSetManagerHost("lcls-daemon2", 1975)
# L2MPSASYNSetManagerHost("lcls-dev1", 1975)
## Configure asyn port driverx
# YCPSWASYNConfig(
#    Port Name,                 # the name given to this port driver
#    Root Path                  # OPTIONAL: Root path to start the generation. If empty, the Yaml root will be used
#    Record name Prefix,        # Record name prefix
#    DB Autogeneration mode,    # Set autogeneration of records. 0: disabled, 1: Enable using maps, 2: Enabled using hash names.
#    Load dictionary,           # Dictionary file path with registers to load. An empty string will disable this function
YCPSWASYNConfig("${YCPSWASYN_PORT}", "", "", "0", "${YCPSWASYN_DICT_FILE}", "")

## Configure the tprTrigger driver
# tprTriggerAsynDriverConfigure(
#    Port name,                 # The name given to this port driver
#    Root path)                 # Root path to the AmcCarrierCore register area
tprTriggerAsynDriverConfigure("TPRTRIGGER_PORT", "mmio/AmcCarrierCore")

# ==========================================
# Connect to the crossbar
# ==========================================
crossbarControlAsynDriverConfigure("crossbar", "mmio/AmcCarrierCore/AxiSy56040")

# ==========================================
# Load application specific configurations
# ==========================================
# cpswLoadConfigFile("iocBoot/common/configs/specificsLN.yaml", "mmio")

# ===========================================
#               ASYN MASKS
# ===========================================
asynSetTraceMask("${L2MPSASYN_PORT}",, -1, 0)
asynSetTraceMask("${YCPSWASYN_PORT}",, -1, 0)

# ===========================================
#               DB LOADING
# ===========================================
dbLoadRecords("db/tprTrig.db",          "PORT=TPRTRIGGER_PORT,LOCA=${LOCA},IOC_UNIT=SP${LOCATION_INDEX},INST=${SLOT}")
dbLoadRecords("db/crossbarCtrl.db",     "DEV=${IOC_NAME}:${SLOT},PORT=crossbar")
dbLoadRecords("db/iocAdminScanMon.db",  "IOC=${IOC_NAME}")
dbLoadRecords("db/llrf_bsa_all.db",     "P=${IOC_NAME}, PORT=${YCPSWASYN_PORT}")
dbLoadRecords("db/llrf_bsa_core.db",    "P=${IOC_NAME}, BSA=0, PORT=${YCPSWASYN_PORT}")
dbLoadRecords("db/llrf_bsa_core.db",    "P=${IOC_NAME}, BSA=1, PORT=${YCPSWASYN_PORT}")
dbLoadRecords("db/llrf_bsa_core.db",    "P=${IOC_NAME}, BSA=2, PORT=${YCPSWASYN_PORT}")
dbLoadRecords("db/llrf_bsa_core.db",    "P=${IOC_NAME}, BSA=3, PORT=${YCPSWASYN_PORT}")
dbLoadRecords("db/amc_carrier_core.db", "P=${IOC_NAME}, PORT=${YCPSWASYN_PORT}")

# Setup autosave/restore
< iocBoot/common/init_restore.cmd

# Stat EPICS
iocInit()

# Initialize caPutLog
caPutLogInit("${EPICS_CA_PUT_LOG_ADDR}")

#  Start autosave 
< iocBoot/common/restore.cmd

# After call to restore thresholds, clear lcls1 timeout so MPS is functional
dbpf $(IOC_NAME):$(SLOT):TCRB0:OUTPUTCONFIG BP
dbpf $(IOC_NAME):$(SLOT):TCRB1:OUTPUTCONFIG BP
dbpf $(IOC_NAME):$(SLOT):TCRB2:OUTPUTCONFIG BP
dbpf $(IOC_NAME):$(SLOT):TCRB3:OUTPUTCONFIG BP
dbpf $(L2MPS_PREFIX):THR_LOADED 1
dbpf $(L2MPS_PREFIX):MPS_EN 1

# End of script






