##########################################################################
# Description:
# This template contains database for phase shifter gap PVs used from a UI
#
# Macros:
# P 	- Device prefix
# M    	- MOTR              
# DMAX	- Max shaft rotations of of the motor
# GMAX 	- Max allowable gap 
# GMIN  - Minimum allowable gap
##########################################################################

# Gap desired from USER and actual gap reported 
record(ao, "$(P):GapDes") {
  field(DESC, "Phase shifter GAP setpoint")
  field(PREC, "3")
  field(DRVH, "$(GMAX)")
  field(DRVL, "$(GMIN)")
  field(EGU, "mm")
  field(HIGH, "$(GMAX)")
  field(LOW, "$(GMIN)")
  field(HSV, "MINOR")
  field(LSV, "MINOR")
  field(FLNK, "$(P):Gap2Deg")
  info(autosaveFields,"DRVH DRVL HIGH LOW VAL")
}

record(ai, "$(P):GapAct"){
  field(DESC, "Phase Shifter actual gap")
  field(DTYP, "Soft Channel")
  field(INP, "$(P):Deg2Gap.VAL CP")
  field(PREC, "3")
  field(EGU, "mm")
  field(HIGH, "$(GMAX)")
  field(LOW, "$(GMIN)")
  field(HSV, "MINOR")
  field(LSV, "MINOR")
  info(autosaveFields,"HIGH LOW")
}

# As the motor controller calculates the moves in rotations or degrees
# Convert the gap to deg for request
# Convert the deg readback to gap for actual position
record(calc, "$(P):Gap2Deg") {
  field(CALC, "(A+D)/C*B")
  field(INPA, "$(P):GapDes PP")
  field(INPB, "$(P):MaxMotorDeg")
  field(INPC, "$(P):MaxGap")
  field(INPD, "$(P):GapOffset")
  field(EGU, "deg")
  info(autosaveFields,"CALC")
}

record(calcout, "$(P):Deg2Gap") {
  field(FLNK, "$(P):$(M)")
  field(CALC, "(A/B)*C+D")
  field(INPA, "$(P):$(M).RBV CP")
  field(INPB, "$(P):MaxMotorDeg")
  field(INPC, "$(P):MaxGap")
  field(INPD, "$(P):GapOffset")
  field(OUT, "$(P):GapAct")
  field(EGU, "mm")
  info(autosaveFields,"CALC")
}

# Phase shifter gap range 
record(ao, "$(P):MaxGap"){
  field(DESC, "Phase Shifter max gap")
  field(PREC, "3")
  field(EGU, "mm")
  field(PINI, "YES")
  field(VAL, "$(GMAX)")
  info(autosaveFields,"VAL EGU")
}

record(ao, "$(P):MinGap"){
  field(DESC, "Phase Shifter min gap")
  field(PREC, "3")
  field(EGU, "mm")
  field(PINI, "YES")
  field(VAL, "$(GMIN)")
  info(autosaveFields,"VAL EGU")
}

# Phase Shifter max motor shaft rotation
record(ao, "$(P):MaxMotorDeg"){
  field(DESC, "Phase Shifter max rotation")
  field(EGU, "deg")
  field(PINI, "YES")
  field(VAL, "$(DMAX)")
  info(autosaveFields,"VAL")
}

# Phase Shifter gap offset
record(ao, "$(P):GapOffset"){
  field(DESC, "Phase Shifter gap offset")
  field(EGU, "mm")
  field(PINI, "YES")
  field(VAL, 0)
  info(autosaveFields,"VAL")
}

# Move request initiates a sequence
record(bo, "$(P):TRIM") {
  field(DESC, "Start changing PS gap")
  field(ZNAM, "Standby")
  field(ONAM, "Trim ")
}

record(bi, "$(P):TRIMSTS") {
  field(DESC, "Trim status")
  field(ZNAM, "Move Done")
  field(ONAM, "Move Requested")
}
record(bi, "$(P):TRIM_DBG") {
  field(DESC, "Trim debug")
  field(ZNAM, "Off")
  field(ONAM, "On")
}

