import phantasy

"""
Explanation: Element
Import modules/packages
End of explanation
"""


mp = phantasy.MachinePortal(machine='FRIB_FE', segment='LEBT')

"""
Explanation: Model Machine
End of explanation
"""


mp.get_all_types()

"""
Explanation: Get Element by type
End of explanation
"""


equads = mp.get_elements(type='EQUAD')

equads

# first equad
equad0 = equads[0]
equad0

"""
Explanation: Example: Electric static Quadrupole
Get the first equad
End of explanation
"""


print("Index    : %d" % equad0.index)
print("Name     : %s" % equad0.name)
print("Family   : %s" % equad0.family)
print("Location : (begin) %f (end) %f" % (equad0.sb, equad0.se))
print("Length   : %f" % equad0.length)
print("Groups   : %s" % equad0.group)
print("PVs      : %s" % equad0.pv())
print("Tags     : %s" % equad0.tags)
print("Fields   : %s" % equad0.fields)

"""
Explanation: Investigate the equad
End of explanation
"""


equad0.V

"""
Explanation: Dynamic field: V
All available dynamic fields could be retrieved by equad0.fields (for equad0 here, there is only one field, i.e. V).
End of explanation
"""


# Approach 1: dynamic field feature (readback PV)
print("Readback: %f" % equad0.V)

# Approach 2: caget(pv_name)
pv_rdbk = equad0.pv(field='V', handle='readback')
print("Readback: %s" % phantasy.caget(pv_rdbk))

# Approach 3: CaField
v_field = equad0.get_field('V')
print("Readback: %f" % v_field.get(handle='readback'))
print("Setpoint: %f" % v_field.get(handle='setpoint'))
print("Readset : %f" % v_field.get(handle='readset'))

"""
Explanation: Get values
If only readback value is of interest, Approach 1 is recommanded and most natural.
End of explanation
"""


# Save orignal set value for 'V' field
v0 = equad0.get_field('V').get(handle='setpoint')

# Approach 1: dynamic field feature (setpoint PV)
equad0.V = 2000

# Approach 2: caput(pv_name)
pv_cset = equad0.pv(field='V', handle='setpoint')
phantasy.caput(pv_cset, 1000)

# Approach 3: CaField
v_field = equad0.get_field('V')
v_field.set(handle='setpoint', value=1500)

"""
Explanation: Set values
Always Approach 1 is recommanded.
End of explanation
"""


