Basic IF ElIF in Tag Value Changed script

I'm struggling with the formatting of an IF statement in the Value Change script of a tag in Vision. If I comment out my "if" statements and make one of the gain paths fixed, the readBlocking and writeBlocking works fine and "ScriptValue" displays the correct value of my if conditions.

I'm sure this is something basic, Python isn't my strong suit.

def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):
	value = currentValue
	if value == 0:
		gainpaths = ["[~]PGainTunedSlow","[~]IGainTunedSlow","[~]DGainTunedSlow"]
	elif value == 1:
		gainpaths = ["[~]PGainTunedMed","[~]IGainTunedMed","[~]DGainTunedMed"]
	elif value == 2:
		gainpaths = ["[~]PGainTunedFast","[~]IGainTunedFast","[~]DGainTunedFast"]
	gainvalues = system.tag.readBlocking(gainpaths)
	writevalue = [value,gainvalues[0],gainvalues[1],gainvalues[2]]
	writepath = ["[~]Scriptvalue","[~]PGain","[~]IGain","[~]DGain"]
	system.tag.writeBlocking(writepath,writevalue)

currentValue is a qualified value object, not the raw value of the tag. Use:

	value = currentValue.value

Note that readBlocking() delivers a list of qualified values, not raw values, but the rest of your script works because writeBlocking() also accepts qualified values.

3 Likes

Good grief, I've been working on that for two hours...thanks Phil :slight_smile:

BTW, tag events don't run in Vision. They run in the gateway. So this isn't really a Vision question.

Good to know. I haven't played with the scripting much. But working on some PID exercises and needed to change the gains outside of the PLC

This is going to blow up if value is not 0, 1, or 2, because gainpaths won't be defined.

Good catch!

Works great now. Where can I learn more about what you you mean by a qualified object?

For what it's worth, I would write this script like this:

gainTypes = ['TunedSlow','TunedMed','TunedFast']

#limits currentValue between 0 and the length of gainTypes.
#Other logic can be used.
value = max(0, min(currentValue.value,len(gainTypes)-1) 

gainPaths = ['[~]' + gain + gainTypes[value] for gain in ('PGain','IGain','DGain']

writeValues  = [value] +  [qv.value for qv in system.tag.readBlocking(gainPaths)]
system.tag.writeBlocking(['[~]ScriptValue','[~]PGain','[~]IGain','[~]DGain'],writeValues)

You can learn about Qualified Value Objects here:

Very nice. I'm following it but definitely need to brush up on scripting.