<< Click to Display Table of Contents >> Navigation: Modbus Universal MasterOPC Server > Lua 5.1 Reference Manual > Examples and Other Useful Things > Example 1. Processing a quality > Creating a Script |
Let's develop an algorithm of decision of our task:
1.Read a current tag value and a quality
2.If the quality is "good", execute additional check of the Status tag.
3.Read a value of the Status tag.
4.Check the bits 0 and 1 of the value of Status. If they are True, write to the tag the quality Sensor_Failure and the latest valid value.
5.Check the bit 2 of the value of Status. If it is True, write to the tag the quality Device_Failure and the latest valid value.
Below is the final code:
OldValue=0
-- Initialization
function OnInit()
end
-- Uninitialization
function OnClose()
end
-- Processing
function OnRead()
Val,Qual=server.ReadCurrentTag(); --read a value and a quality of the current tag
if Qual==OPC_QUALITY_GOOD then
Status=server.ReadTagByRelativeName("Status") --read the status
if bit.BitFromData(Status,0) or bit.BitFromData(Status,1) then --check bits 0 and 1
server.WriteCurrentTag(OldValue,OPC_QUALITY_SENSOR_FAILURE ) --write an old value and the quality "sensor failure"
return --exit
end
if bit.BitFromData(Status,2) then --check the bit 2
server.WriteCurrentTag(OldValue,OPC_QUALITY_DEVICE_FAILURE ) --write an old value and the quality "device failure"
return --exit
end
end
OldValue=Val --save the current value
end
In the script beginning, we create the variable OldValue. At each successful cycle of poll, we will save a current value to that variable. In further, if a failure is detected, we will write an OldValue value together with the invalidity constant.
Next, using the function server.ReadCurrentTag, a tag value and a tag quality are read out. A quality is compared with the constant OPC_QUALITY_GOOD. If the value is valid, the Status tag can be checked. Next, using the function server.ReadTagByRelativeName, a value of the Status tag is read out, and that value is checked, that is, bits 0, 1 and 2 are extracted, using the function bit.BitFromData.
If one of conditions is true, the function server.WriteCurrentTag writes to the current tag a stored value of OldValue and the correct invalidity constant. The statement return is used in order to exit the function; if it is omitted, a current invalid value might be written into OldValue.