Math and Logic Help
Math and Logic Help
Math and Logic Help
Version 7.1
Math and Logic Help
TABLE OF CONTENTS
Introduction ........................................................................................................7
Compatibility and Compliance ................................................................................... 7
What Should I Do Next?......................................................................................8
Learn How Math and Logic Works ............................................................................. 8
Read a Quick-Start Guide ......................................................................................... 8
Get Detailed Information on the Configuration Editors ............................................... 8
Verify That It’s Working or Troubleshoot a Problem ................................................... 8
Print a Copy of This Document ................................................................................. 8
Contact Technical Support ........................................................................................ 8
Theory of Operation ............................................................................................9
Math and Logic ........................................................................................................ 9
Main Server Features ............................................................................................. 13
Quick Start Guide ..............................................................................................16
Creating a Math and Logic Device ........................................................................... 16
Creating a Math and Logic Data Item ...................................................................... 20
Editing the Math and Logic Program ....................................................................... 22
Saving the Configuration and Updating the Server ................................................... 38
Verifying Your Configuration ................................................................................... 39
Configuration Editor Reference ........................................................................45
Address Space ....................................................................................................... 46
Device Folders ................................................................................................... 46
Math and Logic Devices ...................................................................................... 49
Folders .............................................................................................................. 55
Math and Logic Data Items ................................................................................. 58
Math and Logic Editor ......................................................................................... 66
Conversions .......................................................................................................... 76
Simulation Signals ................................................................................................. 76
Alarm Definitions ................................................................................................... 77
Network Connections ............................................................................................. 77
OPC Crosslinks ...................................................................................................... 77
Saving and Undoing Configuration Changes ............................................................ 78
Configuration Import/Export ................................................................................... 78
Editor Options ....................................................................................................... 78
Validation and Troubleshooting ........................................................................80
Data Monitor ......................................................................................................... 80
Cyberlogic OPC Client ............................................................................................ 80
Status Items.......................................................................................................... 80
Math and Logic Status Item Definitions ................................................................ 81
Debugging Aids ..................................................................................................... 87
Appendix A: C-logic Language Reference .........................................................91
Comments............................................................................................................. 92
Constants .............................................................................................................. 93
Integer Constants............................................................................................... 93
Floating Point Constants ..................................................................................... 95
String Constants ................................................................................................. 95
Predefined Constants .......................................................................................... 95
Local Declarations .................................................................................................. 96
INTRODUCTION
The Cyberlogic OPC Server provides OPC Data Access, Alarms & Events and XML Data
Access functions. Its modular structure supports a variety of industrial devices and
communication networks. As a result, the server maintains a set of common features, but
has the flexibility to allow the addition of optional features as required for specific
applications.
Math and Logic is one of these optional features. With it, you can create mathematical or
logical functions that can operate on any data items that are available to the OPC server.
The results of the functions are available as OPC data to any attached OPC client. The
Math and Logic feature is included with Cyberlogic's OPC Crosslink Premier Suite, DHX
OPC Premier Suite and MBX OPC Premier Suite.
This document includes only the information that is specific to the Math and Logic
Note
feature. For information on the common features of the Cyberlogic OPC Server, refer to
the Cyberlogic OPC Server Help.
Cyberlogic OPC products provide full compliance with the OPC Foundation specifications
for:
Data Access 3.0, 2.05a and 1.0a
Alarms & Events 1.1
XML Data Access 1.0
Data Access Automation 2.02
These products are tested for compliance to the OPC specifications using the latest test
software from the OPC Foundation. All Cyberlogic OPC products are certified for
compliance by the OPC Foundation's Independent Testing Laboratory. In addition, they
are tested annually for interoperability with other OPC products at the OPC Foundation’s
Interoperability Workshops.
This document describes only the features specific to Math and Logic. For information on
the common features of the Cyberlogic OPC Server, refer to the Cyberlogic OPC Server
Help.
THEORY OF OPERATION
This section will familiarize you with the main features of the Cyberlogic OPC Server as
they relate to Math and Logic. Refer to the Cyberlogic OPC Server Help for a full
discussion of the common features of the Cyberlogic OPC Server. If you are new to OPC
or the Cyberlogic OPC Server, we strongly recommend that you read the OPC Tutorial
first. You will find it in the Help section of your product installation.
The basic function of an OPC server is illustrated in the figure above. The server obtains
data from field components and presents it, in a standard way, to OPC client
applications. Typically, these field components are PLCs or similar devices. More
advanced servers will also allow you to process the incoming raw data prior to making it
available to the client applications.
Basic OPC servers get data from field devices, such as PLCs, and present it to OPC client
software. They may provide a limited ability to convert the values into engineering units,
and may also have some ability to simulate the data. If you need to do anything more
complex than those simple functions, the client software will have to handle it.
That may be acceptable for simple systems. But if your needs require you to program
numerous clients to perform the same calculations, that approach quickly becomes
inefficient and error-prone. Furthermore, it limits your choice of client software to high-
end packages that include the needed math and logic functions.
A far better approach is to use Cyberlogic's Math and Logic to process the data in the
OPC server. This has several advantages:
You program the calculations and logical functions once for the entire
system.
The programs are located and maintained on a single system for easy
maintenance. All clients will receive the same data.
A single math and logic engine for all of your users means that you have
only one editor and one programming language to learn.
You will not need to purchase client software to perform the math and logic
functions.
Your client software options are not limited to only those packages that
include math and logic functions.
Math and Logic provides you with a general programming language, C-logic, that gives
you the freedom to manipulate the data as you wish. This opens many possibilities.
Conversion
Most OPC servers have simple linear and square-root conversion functions built-in. With
Math and Logic, you can create much more complex conversions that involve:
Logarithmic, exponential, stepwise or other types of functions
Clipping and range limiting
Conversions that can be controlled by data items, allowing you to adjust
their parameters in real time
Simulation
Not only can you generate a nearly limitless variety of waveforms, but you have a broad
range of control over them. Possibilities include:
Two sine waves, with an adjustable phase difference
Two square waves in quadrature to each other, to simulate an encoder
Alarms
Instead of simple alarms that trigger when a value is outside of predetermined limits, you
can program alarms for much more complex scenarios:
A process with temperature requirements that vary depending on the
pressure, so you want an alarm when the combination is out of limits
A tank's fluid level is dropping too rapidly, even if it is still within limits
A flow rate with limits that vary depending on the current step in the process
You can write programs that will minimize the effect of inconsistencies in sensor readings
or other measurements:
Average the readings of two pressure transducers
The comparison and logical functions allow you to program complex decisions:
Rank four machines in order of their cycle times
Identify which of three lines is the closest to going down for scheduled
maintenance
Turn off the heater when three out of four probes reach the temperature set
point
You can write programs to control other features of the Cyberlogic OPC Server:
Trigger Crosslink transfers
Enable and disable dynamic Access Paths
Execute other programs
Cyberlogic's Math and Logic implementation includes many advanced features, some of
which are unique to Cyberlogic.
Editing Features
Familiar programming syntax, similar to the C programming language
Program statements are color-coded, using configurable colors
Browse window for easy insertion of OPC data item variables
Power
Extensive set of preprogrammed functions
Each program can produce multiple outputs
A program can dynamically create data items in the address space, which
can be used as inputs, outputs or both
Flexibility
Broad selection of data types from 1 to 64 bits, including Boolean, signed
and unsigned integer, floating point, and string, as well as OPC UA data
types
Support for arrays
Works with DirectAccess data
Program inputs can override default deadbands and sampling rates with
individual settings
Continue with Main Server Features for a general description of how Math and Logic fits
into the server configuration. For an example of how to configure this feature, skip to the
Quick Start Guide. Refer to Appendix A: C-logic Language Reference for a complete guide
to the C-logic language.
When you open the Cyberlogic OPC Server Configuration editor, you will find six main
trees, representing the six main areas that you will configure. These are:
This is where you actually configure Math and Logic. To do this, you will create Math and
Logic data items and organize these into Math and Logic Devices. You will then write a
program for each data item, which will calculate the value that will be assigned to it. For
detailed information on how to edit this tree, refer to the Configuration Editor Reference.
Math and logic devices group related data items in your configuration. All data items
under a device share some common controls and default settings. For example, the
device settings specify when the group is enabled, and the default conditions under
which the logic will be run. You can choose to enable logic execution, disable it, or use
the value of a data item to control the enable and disable. When execution is enabled,
you can specify that programs should run when the input data changes, at a fixed
interval, or when triggered by a change in the value of a specified data item. Each data
item in the device can use these default settings, or define its own.
You program the math and logic operation in a data item. When the program runs, its
result will be available to clients as the value of the data item. It is also possible for a
single program to have multiple output values. Refer to Data Item Declarations for more
information on how to do this.
Conversions Tree
The Conversions Tree is optional. In it, you can define formulas that can be used to
convert raw data values obtained from the field equipment into a form that is more
useful to the client. For example, you can change a transducer’s voltage value into a
pressure value in psi. You can also apply conversions to Math and Logic data items. This
allows you to do the calculations on the raw values, and then use a conversion to
present the result in engineering units. Refer to the Cyberlogic OPC Server Help for a full
discussion of this tree.
This tree is also optional. If you want to be able to use simulated data item values
instead of real values, you can create various types of simulated data functions in this
tree. Simulations are often useful for troubleshooting client applications. You might want
to simulate a Math and Logic data item initially, while you work on its program. Refer to
the Cyberlogic OPC Server Help for a full discussion of this tree.
You will use this optional tree to interface to OPC Alarms & Events clients. This tree
allows you to define the desired alarm conditions and specify what information should be
passed as they occur and clear. When you apply these to a Math and Logic data item,
the result of the calculation will determine what alarm is triggered. Refer to the
Cyberlogic OPC Server Help for a full discussion of this tree.
This tree is where you configure communication to OPC servers, PLCs and other data
sources. You will select the networks and interface devices you will use, and configure
each of the field components as nodes on those networks. This tree is not directly
involved in Math and Logic configuration. However, the network nodes you define here
typically provide the input data for the Math and Logic calculations. Refer to the driver
agent help files for more information.
The OPC Crosslinks Tree lets you identify the data that you want to transfer among PLCs
and OPC servers. You can use Math and Logic data items to enable and disable these
transfers, and to control when they occur. You can also set up crosslinks to write the
results of your Math and Logic programs to other OPC servers or PLCs. Refer to the
Cyberlogic OPC Server Help for a full discussion of this tree.
This section shows how to configure the Address Space tree for Math and Logic. It does
not cover any of the other parts of the configuration. For a step-by-step example of how
to configure a complete OPC server, refer to the Cyberlogic OPC Server Help.
You should use this example only as a guideline of how to configure the most common
features. For detailed information on all of the Math and Logic features, refer to the
Configuration Editor Reference. The software also includes a configuration file with a set
of sample programs. These will help you to understand how the various functions work.
They will also give you ideas about what you can do with C-logic, and they can be
modified and used in creating your own programs.
For this example, we will assume we have a process for which a temperature
measurement is critical. We have three temperature transducers and want to report the
average of their readings. However, if a transducer fails, we will average only the values
from the good transducers.
1. To start the editor, open the Windows Start menu, locate the Cyberlogic OPC
product you have installed, then open the Configuration sub-menu and select OPC
Server and Crosslink.
If you are running the Cyberlogic OPC Server Configuration Editor for the first time,
the editor will prompt you for a configuration file. Click the dialog box's Create
New... button to start with an empty configuration.
You will see the above screen. For this exercise, we will assume that the three
temperature sensors have already been configured. If you want to read about how
to do that, refer to the Cyberlogic OPC Server Help.
2. Right-click on the Address Space tree, then select New from the context menu,
and then Device and finally Math and Logic.
3. Select the General tab and enter Process Monitoring in the Name field.
This will keep the programs for all of the data items in the device enabled to run.
This will cause the program to calculate the average temperature whenever there is
a change in any of the sensor values.
8. Click Apply.
1. Right-click on the Process Monitoring Math and Logic device, then select New
from the context menu, and then select Data Item.
The editor will create a data item and open it for editing.
2. Select the General tab and enter OvenTemperature in the Name field.
3. Select the Program tab, and then click the Edit... button.
For this example, we will need three temperature sensor inputs, which we assume have
already been configured as data items obtained from a PLC.
varAvg = 0;
varCount = 0;
{
varAvg = varAvg+Temp1;
varCount = varCount+1;
}
if(IsQualityGOOD(Temp2))
{
varAvg = varAvg+Temp2;
varCount = varCount+1;
}
if(IsQualityGOOD(Temp3))
{
varAvg = varAvg+Temp3;
varCount = varCount+1;
}
It is possible to simply type the program in the Code View pane just as it is shown.
Note
Instead, we will use the editor's built-in tools to demonstrate how they can help in
creating your program.
1. Go to the Expressions ribbon, and click on Add Items to open the Add Items
pane.
The editor will populate the browser tree with all items in the server's Address Space.
3. Open the Address Space items to display a tree showing the available data items.
Notice that this includes status and DirectAccess items.
The data items we need have been configured as Oven Temp 1, Oven Temp 2 and
Oven Temp 3 in the Main Process Control PLC.
5. In the Item Name field, enter Temp1. This is the name the program will use for
this data item.
7. Repeat the preceding steps for the other data items, calling them Temp2 and
Temp3.
The additional items appear in reverse order, because the editor always inserts new
items at the top of the program.
9. The editor will begin a VAR declaration statement. Complete it by typing varAvg; in
the editing window.
10. Repeat the process to enter the declaration int varCount; on the next line.
varAvg = 0;
varCount = 0;
These lines will initialize the two variables each time the program runs.
12. Type // to add a comment to your code. The double-slash and anything that follows
it on the same line is considered to be a comment. The compiler will ignore it.
14. Place the cursor within the if() parentheses, then open the Operators menu and
select !, which is the logical NOT operator.
Click the expand button at the lower right corner of any of the groups to pop up a list
Note
of items available in that group, along with an explanation of their meaning and a
sample syntax.
15. Go to the Functions ribbon and select IsQualityGOOD from the OPC Quality
group.
16. The default argument for the function is VariableName. This is a hint to remind you
to type the name of an OPC variable in its place. In this case, type Temp1.
17. Use the Operators menu to enter the logical AND operator, && into the expression.
The ribbon tools will help you to enter the expressions quickly and accurately. As you
Note
become more familiar with the editor, you may prefer to simply type the functions and
operators directly.
19. Place the cursor between the braces and type varAvg. (being sure to include the
period). You will see a context menu appear, displaying the available properties of
the object. Select Quality.
20. Type the assignment operator, =, then go to the Expressions ribbon and select
QUALITY_SENSOR_FAILURE from the Constants group.
If a variable that is returned from a program has a BAD quality, the value previously
Note
assigned to this variable becomes irrelevant.
21. Type a semicolon to complete the statement, then insert a comment line above the
statement.
The logic up to this point checks to see if none of the three sensors have good
quality data, and, if so, reports a sensor failure. (Refer to Appendix B: OPC Quality
Flags for information about OPC data quality.)
24. Go to the Home ribbon's Clipboard group. Use the Copy and Paste tools to make
two additional copies of the preceding if statement.
Now we have the sum of the values from the good sensors. Next, we will calculate
the average.
varAvg = varAvg/varCount;
This completes the program editing. The last step is to compile the program.
The editor will save the program, and then compile it into the binary form that is
executed by the server. If the compiler finds any errors, it will display them in the
Status pane.
31. Click the Save & Update Server button to save the modified configuration and load
it to the OPC server for execution.
It is not mandatory to perform the Save & Update Server operation within the Math
Note
and Logic editor. If you prefer, you can close the editor and do additional edits to your
server configuration, and then Save & Update Server from the main menu or toolbar.
If you make changes to the program, and leave the Math and Logic editor without
Note
compiling it, the program in the Logic window will be shown on a red background. The
data item icon in the address space tree will also turn red. This is to remind you, that
there is no executable code associated with your program.
33. If you did not Save & Update Server within the Math and Logic editor, click Apply to
save the program as part of the data item.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
1. Open the File menu and select Save & Update Server.
2. Be sure to repeat this step every time you change the configuration.
The next step, Verifying Your Configuration, will introduce you to the diagnostic features
of the product.
To test the Math and Logic program, we will simulate the three temperature inputs and
use Data Monitor to set their values. We will then check the value of the Math and Logic
data item to verify that it is correct.
1. Select the device that contains the temperature sensors. In the example shown, it is
called Main Process Control.
3. Click Apply.
The icons for the temperature sensors will turn yellow to indicate that their values
are simulated.
4. On the toolbar, click the button to save and update the server.
5. Right-click on the Main Process Control device and select Data Monitor from the
context menu.
The Data Monitor pane will open to show the values of the sensors, along with status
information.
Notice that the Substatus for the three Oven Temp values is Local Override. This
indicates that the values are simulated.
6. Right-click on Oven Temp 3 and select Write Item from the context menu.
7. In the Write Item dialog box, enter a value for the item, and then click OK.
8. Verify that the value was written as expected, then repeat the procedure to set
values for the other two sensors.
The Data Monitor pane will show the value of the OvenTemperature Math and Logic
data item, along with status information.
10. Verify that the value of OvenTemperature is the average of the three simulated
temperature sensor values.
11. Select Main Process Control again and change the temperature sensor values.
When you return to viewing Process Monitoring, you should see a corresponding
change in the OvenTemperature value.
This concludes the Quick-Start Guide. To learn more about the features of the server,
refer to the Theory of Operation section. To learn more about configuration, refer to the
Configuration Editor Reference. To learn more about verifying your configuration and
troubleshooting tools, refer to the Cyberlogic OPC Server Help.
This section describes the editor features that you will use to configure Math and Logic.
If you are a new user and want a procedure to guide you through a typical configuration
session, refer to the Quick Start Guide.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
To launch the editor from the Windows Start menu, navigate to Cyberlogic OPC
Crosslink Suite, Cyberlogic DHX OPC Premier Suite or Cyberlogic MBX OPC
Premier Suite, then open the Configuration submenu and select the OPC Server
menu item.
The left pane of the main workspace window includes the six main configuration trees.
The first part of this reference explains how to create and configure Math and Logic in
the Address Space tree. This includes three sections:
Math and Logic Devices
Math and Logic Data Items
Math and Logic Editor
Following that is a very brief description of the Conversions, Simulation Signals, Alarm
Definitions, Network Connections and OPC Crosslinks trees. For a full discussion of these
trees and other important topics including configuration import/export, editor options and
connecting to OPC client software, please refer to the Cyberlogic OPC Server Help.
The last sections in this configuration editor reference cover important tips and
techniques for Saving and Undoing Configuration Changes, Configuration Import/Export
and Editor Options
Address Space
The Address Space Tree describes the hierarchical address structure of the Cyberlogic
OPC Server. The branches of the tree that relate to Math and Logic are Device Folders,
Math and Logic Devices, and Folders. Its ―leaves‖ are Math and Logic Data Items. The
intent of this structure is to permit the user to organize the data items into logical
groups.
Device Folders
A device folder groups devices and other device folders. You can place a device folder
directly under the Address Space root folder or under another device folder, up to four
levels deep.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
Right-click on the Address Space root folder or an existing device folder. Select New and
then Device Folder from the context menu.
You can create multiple device folders in a single operation by duplicating an existing
one. This can help you to quickly create similarly-configured device folders. To duplicate
a device folder, right-click on it and select Duplicate… from the context menu.
The above dialog box opens. You must specify how the duplicates are to be named by
entering values for the Base Text, First Number, Numeric Places and Number
Increment fields. To name the duplicated device folders, the editor begins with the
base text and appends a number to it. The first duplicate uses the First Number value
with the specified number of digits. The editor then adds Number Increment to that
value for each of the remaining duplicates.
As an example, if Numeric Places is 3 and First Number is 2, the number 002 will be
appended to the base text.
Use the Number Of Duplicates field to specify the number of device folders you wish
to create. If you want to duplicate all branches within the original device folder, check
the Including Subtree checkbox.
To delete an existing device folder, select it and press the Delete key, or right-click on
the device folder and select Delete from the context menu.
General Tab
Name
The Name identifies this device folder. It can be up to 50 characters long, may contain
spaces, but must not begin with a space. It also may not contain any periods.
Description
This optional field further describes the device folder. It can be up to 255 characters
long.
Simulate
Check this box to enable data simulation for all data items at this level or below. This
provides a quick way to switch between real and simulated data for a large number of
data items. Refer to the Cyberlogic OPC Server Help for a full discussion about simulating
data.
If the Simulate checkbox is grayed-out, it indicates that simulation has already been
Note
selected at a higher level.
Disable Writes
Check this box to disable write requests for all data items at this level or below. By
default, this box is not checked and writes are enabled.
If the Disable Writes checkbox is grayed-out, it indicates that writes have already been
Note
disabled a higher level.
A Math and Logic device contains Math and Logic data items. The program enable and
execution criteria are configured in the device, so users typically group data items that
have the same criteria within the same device. You can place Math and Logic devices
directly in the Address Space root folder or in a device folder. A Math and Logic device
also functions as a folder; it can contain folders and Math and Logic data items.
All programs under a Math and Logic device execute in the context of a single thread.
Note
That means that if multiple programs are ready for execution, they will execute
sequentially in the order in which they became ready for execution.
If your application requires concurrency, or if you want to better utilize a multi-core
CPU, you should create multiple Math and Logic devices, and group the data items
(programs) appropriately.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
Right-click on the Address Space root folder or a device folder. Select New and then
Device and then Math and Logic from the context menu.
You can create multiple Math and Logic Devices in a single operation by duplicating an
existing one. This can help you to quickly create similarly-configured devices. To
duplicate a Math and Logic Device, right-click on it and select Duplicate… from the
context menu.
The above dialog box opens. You must specify how the duplicates are to be named by
entering values for the Base Text, First Number, Numeric Places and Number
Increment fields. To name the duplicates, the editor begins with the base text and
appends a number to it. The first duplicate uses the selected First Number value with the
specified number of digits. The editor then adds Number Increment to that value for
each of the remaining duplicates.
Use the Number Of Duplicates field to specify the number of Math and Logic Devices
you wish to create. If you want to duplicate all branches within the original device, check
the Including Subtree checkbox.
In the example, a single digit will be appended to the base text Monitoring – Line (there
is a space at the end). The numbering begins with 2, and three duplicates will be
created. They will be called Monitoring – Line 2, Monitoring – Line 3 and Monitoring –
Line 4.
To delete an existing Math and Logic device, select it and press the Delete key, or right-
click on the device and select Delete from the context menu.
General Tab
Name
The name identifies the Math and Logic device. It can be up to 50 characters long, may
contain spaces, but must not begin with a space. It also may not contain any periods.
Description
This optional field further describes the Math and Logic device. It can be up to 255
characters long.
Simulate
Check this box to enable data simulation for all Math and Logic data items on this device.
This provides a quick way to switch between real and simulated data for a large number
of data items. Refer to the Cyberlogic OPC Server Help for a full discussion about
simulating data.
If the Simulate checkbox is grayed-out, it indicates that simulation has already been
Note
selected at a higher level.
Disable Writes
Check this box to disable write requests for all data items at this level and below. By
default, this box is not checked and writes are enabled.
If the Disable Writes checkbox is grayed-out, it indicates that writes have already been
Note
disabled a higher level.
This radio selection allows you to enable or disable the Math and Logic programs for the
data items in the device. When device logic is enabled, the Run Logic criteria will cause
the programs to execute. When device logic is disabled, the programs will not run,
regardless of the Run Logic criteria. You will configure the default settings for the Run
Logic criteria on the Settings tab, but each data item can override the default.
If you select Use Data Item To Enable, you must specify a data item that will control
the device logic. You must also enter a value for Interval to indicate how often the
value of the data item will be checked. If the value of the specified data item is true,
device logic will be enabled, otherwise it will be disabled. You can click the Browse...
button to open a window that will allow you to browse for the desired data item.
If the item you choose contains numeric data, a value of zero is taken as false and a
Note
nonzero value is true.
Settings Tab
This tab is used to specify the default settings used by all data items under this device.
Each data item can either use these settings, or define its own.
Data Sampling
Math and Logic programs use OPC data items as inputs. This section allows you to
specify how often to check these data items for a change in their value. You do this by
entering a sampling interval and a deadband. These are default values. Each data item
declaration in a program can override these defaults, if desired. Refer to the Data Item
Declarations section for information on how to do this.
Interval
You may specify the default interval, in milliseconds, at which you want the input data to
be sampled. The ITEM variable declaration in your program can override this value.
Deadband
Here you may specify the default deadband in percent of full scale. This is the minimum
amount that will be considered a change in the value. The deadband helps to eliminate
problems caused by values that jitter. The ITEM variable declaration in your program can
override this value, if desired. Refer to the Data Item Declarations section for information
on how to do this.
Run Logic
This section allows you to specify when to run the programs in the Math and Logic data
items. There are three methods available, and you can choose any combination. If you
choose more than one, the programs will run when any one of the conditions are met.
This is a default setting. Each data item can override this default, if desired. Refer to the
discussion of the Advanced... button on the Data Item Program tab for information on
how to do this.
On Data Change
Check this box to run the programs whenever their input data values change.
If a program has more than one input, it will run when any input changes.
Programs can exclude some inputs from triggering On Data Change execution. Refer to
Note:
the Data Item Declarations section for information on how to do this.
Check this box to run the programs at the interval you specify.
If multiple Run Logic conditions are used, the Fixed Interval is restarted each time any
Note
of the Run Logic conditions triggers the program execution.
Triggered
Check this box to run the programs when the specified data item changes state.
If you choose this option, you must specify an Item ID, Mode and Interval. You may also
specify a Trigger Deadband.
Item ID
Specify a data item to use as the trigger. When the value of the trigger data item
changes state as specified in the Mode selection, the programs run. Click the Browse...
button to open a window that will allow you to browse for the desired data item.
Interval
You must specify an interval when using triggered execution. This value specifies how
often the trigger data item will be read to see if it has changed state.
Deadband
Here you may specify the deadband in percent of full scale. This is the minimum amount
that will be considered a change in the value. The deadband helps to eliminate problems
caused by values that jitter.
Mode
You must choose the type of change in the trigger item that will cause the logic to run.
Choose False to True to trigger when the value changes from false to true.
Choose True to False to trigger when the value changes from true to false.
Choose Any Change to trigger when any change in the value occurs.
Folders
A folder logically groups data items and other folders. You can place folders directly
under devices or under other folders, up to four levels deep.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
Right-click on an existing device or folder, and select New and then Folder from the
context menu.
Duplicating a Folder
You can create multiple folders in a single operation by duplicating an existing one. This
can help you to quickly create similarly-configured folders. To duplicate a folder, right-
click on it and select Duplicate… from the context menu.
The above dialog box opens. You must specify how the duplicates are to be named by
entering values for the Base Text, First Number, Numeric Places and Number
Increment fields. To name the duplicated folders, the editor begins with the base text
and appends a number to it. The first duplicate uses the selected First Number value
with the specified number of digits. The editor then adds Number Increment to that
value for each of the remaining duplicates.
As an example, if Numeric Places is 3 and First Number is 2, the number 002 will be
appended to the base text.
Use the Number Of Duplicates field to specify the number of folders you wish to
create. If you want to duplicate all branches within the original folder, check the
Including Subtree checkbox.
Deleting a Folder
To delete an existing folder, select it and press the Delete key, or right-click on the
folder and select Delete from the context menu.
General Tab
Name
The Name identifies this folder. It can be up to 50 characters long, may contain spaces,
but must not begin with a space. It also may not contain any periods.
Description
This optional field further describes the folder. It can be up to 255 characters long.
Simulate
Check this box to enable data simulation for all data items at this level or below. This
provides a quick way to switch between real and simulated data for a large number of
data items. Refer to the Cyberlogic OPC Server Help for a full discussion about simulating
data.
If the Simulate checkbox is grayed-out, it indicates that simulation has already been
Note
selected at a higher level.
Disable Writes
Check this box to disable write requests for all data items at this level or below. By
default, this box is not checked and writes are enabled.
If the Disable Writes checkbox is grayed-out, it indicates that writes have already been
Note
disabled a higher level.
Math and Logic data items contain the Math and Logic programs. They take the value
that the program returns when it executes. You can place Math and Logic data items
directly in a Math and Logic device, or in a folder within a Math and Logic device.
Normally, the programs are enabled and run according to criteria you configure in the
parent device. However, an advanced configuration feature allows you to modify the
enable criteria and override the Run Logic criteria.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
Right-click on a Math and Logic device or a folder within a Math and Logic device. Select
New and then Data Item from the context menu.
To delete an existing Math and Logic data item, select it and press the Delete key, or
right-click on the data item and select Delete from the context menu.
General Tab
Name
The Name identifies the data item. It can be up to 50 characters long, may contain
spaces, but must not begin with a space. It also may not contain any periods.
Description
This optional field further describes the data item. It can be up to 255 characters long.
Simulate
Check this box to enable data simulation for this data item. Refer to the Cyberlogic OPC
Server Help for a full discussion about how to simulate data.
If the Simulate checkbox is grayed-out, it indicates that simulation has already been
Note
selected at a higher level.
Disable Writes
Check this box to disable all write requests for this data item. By default, this box is not
checked and writes are enabled.
If the Disable Writes checkbox is grayed-out, it indicates that writes have already been
Note
disabled a higher level.
Program Tab
Logic
This section is where you view and edit the data item's Math and Logic program. The
large field provides a display-only view of the program.
If the background color for the Logic window is red, it indicates that the program has
Note
not yet been compiled, and therefore no executable code exists.
Edit...
Click this button to open the Math and Logic Editor. This is where you edit, compile and
debug the program.
You can also start the Math and Logic Editor by double-clicking on the selected data
Note
item in the address space tree.
Advanced...
Click this button to open the Advanced editing window. Normally, the criteria that enable
and run the program are configured in the Math and Logic device. This window allows
advanced users to modify these criteria. You can modify the conditions that enable the
logic, and override the criteria that cause it to run.
By default, the program runs only when at least one client subscribes to the data item.
This reduces the load on the processor. However, the Item Logic Enable selection lets
you request that the logic run continuously, even without any subscriptions.
The Run Logic Override section lets you declare that the run criteria in the Math and
Logic device should be ignored, and the criteria you specify here should be used instead.
For details on editing these criteria, refer to the Math and Logic device Settings Tab
discussion.
OPC Client
This section allows you to configure how the program's result will be presented to the
OPC client software.
Select the data type you want to use to present the results to the client. The default is
VT_R8 (floating-point double).
Array
Check this box to specify that the returned data will be in the form of an array.
Elements
Lower Bound
Use Conversion
Check this box to apply a conversion to the data before it is presented to the client. You
must then select the conversion you want to use from the list of defined Conversions.
Simulation Tab
Signal
If you enabled simulation on the General tab or at a higher level, you must select how to
simulate the data item's value. Your choices are: a fixed value, an echo of the last value
written to the item, or one of the previously-defined Simulation Signals.
Value
When simulation is enabled and the Signal field is set to Fixed Value, the data item will
be set to this value.
Alarms Tab
Generate Alarms
If this box is checked, the server will test the alarm conditions for this data item. It will
then generate alarms as appropriate.
Only OPC clients that support the OPC Alarms & Events specification can receive
Note
alarms.
Refer to the Cyberlogic OPC Server Help for a full discussion about how to create and use
alarms.
Message Prefix
Enter the text for the first part of the alarm message. The second part will be the body
text of the specific alarm that is generated.
Alarm
Select one of the previously-defined Alarm Definitions to serve as the alarm template for
this data item.
Properties Tab
In addition to the main data item properties—value, quality and timestamp—the OPC
specification includes several optional properties that your client application may use.
This tab allows you to set these data item properties. These properties are static and do
not change while the server is running.
Engineering Units
This is OPC property ID 100. It specifies the engineering units text, such as DEGC or
GALLONS. It can be up to 50 characters long.
Open Label
This is OPC property ID 107, and is presented only for discrete data. This text describes
the contact when it is in the open (zero) state, such as STOP, OPEN, DISABLE or
UNSAFE. It can be up to 50 characters long.
Close Label
This is OPC property ID 106, and is presented only for discrete data. This text describes
the contact when it is in the closed (non-zero) state, such as RUN, CLOSE, ENABLE or
SAFE. It can be up to 50 characters long.
Default Display
This is OPC property ID 200. It is the name of an operator display associated with this
data item. It can be up to 255 characters long.
BMP File
This is OPC property ID 204. It is the name of a bitmap file associated with this data
item, for example C:\MEDIA\FIC101.BMP. It can be up to 255 characters long.
HTML File
This is OPC property ID 206. It is the name of the HTML file associated with this data
item, for example http://mypage.com/FIC101.HTML. It can be up to 255 characters long.
Sound File
This is OPC property ID 205. It is the name of the sound file associated with this data
item, for example C:\MEDIA\FIC101.WAV. It can be up to 255 characters long.
AVI File
This is OPC property ID 207. It is the name of the AVI file associated with this data item,
for example C:\MEDIA\FIC101.AVI. It can be up to 255 characters long.
Foreground Color
This is OPC property ID 201. Click on the box and select the foreground color used to
display the item.
Background Color
This is OPC property ID 202. Click on the box and select the background color used to
display the item.
Blink
This is OPC property ID 203. Check this box to indicate that displays of the item should
blink.
The Math and Logic Editor allows you to create, edit and compile your programs using
Cyberlogic's C-logic programming language. (Refer to Appendix A: C-logic Language
Reference for detailed information on programming in C-logic.) To launch the editor,
select a Math and Logic data item and go to its Program tab, and then click the Edit...
button. You can also launch the editor by double-clicking on the data item in the address
space tree.
To get help with any function keyword or symbol in the C-logic editor, just put the
Note
cursor on the function name or keyword, or select the symbol, and press <F1>.
The Code View pane is the main working area of the editor. This is where you edit your
program, either by adding items from the ribbon, or by direct text editing.
The Add Items pane will assist you in adding data items as inputs or outputs for your
program. To open it, click on the Add Items button at the right edge of the editor.
In this pane, you can browse through all of the configured data items, status items and
DirectAccess tags that are available to the OPC server. Select the item you want to use,
and then enter a name for it in the Item Name field. This is the local variable name you
will use for the data item in your program.
If you wish, you can override the default deadband and sampling rate for the data item.
You can also exclude the item from triggering On Data Change execution. Refer to the
Data Item Declarations section for information on how to do this.
Once you have edited the OPC Properties fields as desired, click Add Item to create a
variable declaration in the Code View pane.
The example above shows an ITEM declaration created by the Add Items pane. It
includes the Item Name that the user entered, followed by the full ItemID. In this case,
the user elected to override the default deadband and sampling rate, so the declaration
shows the user-specified values.
The ITEM statement is always inserted at the top of the program, regardless of the
Note
current cursor position.
Status Pane
The Status pane provides error messages that the compiler generates to help in
debugging your program.
In this example, line 4 has two operators in a row. The Status pane shows that the error
occurred in line 4 and gives a description of the problem. The red icon at the left side of
the Code View pane visually flags the error location.
The compiler stops after the first error is found. Therefore, if multiple errors are
Note
present, only the first one found will be shown.
Home Ribbon
Logic Group
Clipboard Group
This group contains the standard clipboard functions, and the editor also supports their
standard keyboard shortcuts:
Cut (Ctrl-X)
Copy (Ctrl-C)
Paste (Ctrl-V)
Select All (Ctrl-A)
Editing Group
These editing functions, and their keyboard shortcuts, work just as they do in standard
text editors:
Undo (Ctrl-Z)
Redo (Ctrl-Y)
Find (Ctrl-F) Click the arrow beside the Find button to access Goto, which
allows you to jump directly to any line in the program.
Replace (Ctrl-H)
To convert one or more lines of code into comments, select them and click the Comment
button. It will insert a double-slash at the beginning of each of the selected lines.
To remove the double-slash from these commented lines, select them and click
Uncomment.
Options Group
This group lets you adjust the view according to your preferences.
The Preferences button opens an editor that provides an extensive selection of choices
that you can use to customize the appearance of the editor. These include font style, size
and color, along with indentation options.
Show Windows lets you choose how to display or hide the Code View, Status and Add
Items panes.
Functions Ribbon
Each group on the Functions ribbon contains a gallery of functions and help screens.
Click a group's down arrow to expand its gallery of functions.
Click the dialog box launcher to open a help screen for the group. This screen
contains a list of the functions with a description and example for each. The function
names are hyperlinks. Click them to open the help file to the section for that function.
On the help screen for the Operators group, the function names are not underlined.
Note
This makes it easier to read the individual symbols. However, the names are still
hyperlinked to the help file.
Another way you can get help with any function, keyword or symbol in the C-logic
Note
editor is to place the cursor on the function name or keyword, or select the symbol,
and then press <F1>.
Math Group
Refer to the Math Functions section for a detailed description of each of these functions.
String Group
The String group includes string manipulation, conversion, search, replace and property
functions.
Refer to the String Functions section for a detailed description of each of these functions.
Bitwise Group
The Bitwise functions allow you to extract ranges of bits within a value, and to shift bits
left and right.
Refer to the Bitwise Functions section for a detailed description of each of these
functions.
The Date and Time Group includes functions to retrieve, format and modify date and
time values.
Refer to the Date & Time Functions section for a detailed description of each of these
functions.
All C-logic variables include Error and Quality properties. This group contains the Error
and OPC Quality functions, which simplify the interpretation of these properties.
Refer to the Variable Properties Functions section for a detailed description of each of
these functions.
Refer to Appendix B: OPC Quality Flags for information about OPC data quality.
Other Group
These functions help you to debug the program and control its execution.
Refer to the Other Functions section for a detailed description of each of these functions.
Expressions Ribbon
Each group on the Expressions ribbon contains a gallery of elements you can use to
create expressions, and corresponding help screens. They are accessed in the same way
as the galleries and help screens on the Functions ribbon.
Constants Group
This group contains several pre-defined constant values, including the OPC quality codes,
and the mathematical constants π and e.
Variables Group
The Variables group allows you to create custom constants, typed and untyped local
variables, OPC data item variables, and date and time variables in your program.
Refer to the Local Declarations section for detailed information on the types of constants
and variables you can create.
Operators Group
This group provides the operators for mathematical and logical operations.
Statements Group
Refer to the Statements section for details of how to construct these types of statements.
Conversions
The results of your Math and Logic programs may be process values that are not
expressed in engineering units. To simplify operations on the data, the Cyberlogic OPC
Server allows you to associate a conversion with each data item.
A user can define many different conversions. A number of data items can then use each
conversion. As a result, the user need not define the same conversion many times over.
Simulation Signals
The server can simulate the data for each of the data items, including Math and Logic
data items, according to a predefined formula. This makes it easy to perform client-side
testing without the need for a working Math and Logic program.
A user can define many different types of simulation signals. A number of data items can
then use each such signal. As a result, the user need not define the same simulation
signal many times over.
Each signal has parameters that define properties such as amplitude, phase and number
of steps.
Alarm Definitions
The Cyberlogic OPC Server supports the OPC Alarms and Events specification, permitting
it to generate alarms based on the value of data items.
The user may define many different alarm conditions. A number of data items can then
use each such condition. As a result, the user need not define the same alarm condition
many times over.
There are two categories of alarms: digital and limit. Digital alarms are normally used
with Boolean data items, and limit alarms are normally used with numeric data items.
However, both types of alarms may be used with either data type. Alarms cannot be
used with string or array data items, or with bit fields larger than 64 bits.
Configuring alarms is meaningful only if your client software also supports the OPC
Note
Alarms & Events specification. Consult your client software documentation to see what
specifications it supports.
Network Connections
Network connections allow you to configure the networks you will use to communicate to
network nodes. The network nodes may be PLCs, other OPC servers or other devices
that provide data to the OPC server. Typically, the data you receive from these network
nodes will be used as inputs or outputs for the Math and Logic programs.
OPC Crosslinks
OPC Crosslinks allow you to transfer data from an OPC server or PLC to other OPC
servers or PLCs. The data item you read from is called the crosslink input. You may write
its value to any number of data items, and these are called crosslink outputs. You can
use Math and Logic data items to enable or disable these transfers, and to control when
the transfers occur.
After you edit the configuration, you must open the File menu and select Save &
Caution!
Update Server, or click the Save & Update Server toolbar button, for the changes
you have made to take effect. Otherwise, the server will still be running with the old
configuration.
To save the configuration without updating the server, open the File menu and select
Save, or click the Save button on the toolbar. The changes will be saved but the server
will still be running with the old configuration.
To save the configuration and update the server, open the File menu and select Save &
Update Server, or click the Save & Update Server button on the toolbar.
To undo configuration changes and revert to the previously saved configuration, open
the File menu and select Undo Changes, or click the Undo Changes button on the
toolbar.
Configuration Import/Export
The Import/Export feature allows you to export the configuration data to text file format
and import configuration data from these exported files. It also allows you to import
comma separated values (csv) files from other vendors’ OPC servers and programming
software.
For details on this important feature and instructions in its operation, refer to the
Cyberlogic OPC Server Help.
Editor Options
The Cyberlogic OPC Server Configuration editor has several options that may be set to
adjust the operation of the editor to suit your preferences and to set security levels as
needed for communication with client software. For a full discussion, refer to the
Cyberlogic OPC Server Help.
Data Monitor
The Data Monitor lets you monitor the values and status of the data items. Its use is
described in detail in the Cyberlogic OPC Server Help.
Status Items
The Cyberlogic OPC Server provides status items that are accessible to any connected
OPC client application. These items provide health and performance information about
the server itself, as well as the network connections, network nodes, devices and
crosslinks. For complete information on the standard status items and how to access
them, refer to the Cyberlogic OPC Server Help. This section describes status items that
are specific to Math and Logic.
When you connect to the Cyberlogic OPC Server with a client application and browse for
items to display, the status items are shown in folders called _Status. The contents of
each folder depend on the type of item that it provides status for.
Device Status
Device Status
The following items are shown in folders called _Status located directly under the Math
and Logic device branches in the address space.
Description
IsSimulated
This indicates whether or not the data items under this device are simulated.
ResetAllErrorCounts
An Off to On transition of this item resets all program error counts to zero.
This resets only the counts; the last error information is not cleared. Any OPC client can
write to this item.
WritesDisabled
Indicates whether or not writes are enabled for data items under this device.
IsEnabled
Programs_ExeCount
This is the total execution count for all programs associated with this Math and Logic
device.
The counter is incremented each time any program associated with this device executes.
This counter cannot be reset.
Programs_ErrorCount
This is the total error count for all programs associated with this Math and Logic device.
The counter is incremented each time any program associated with this device generates
an error. Refer to ResetAllErrorCounts, above, to see how to reset this counter to zero.
ProgramTriggers_ErrorCount
This is the total error count for all program trigger data items associated with this Math
and Logic device. It is incremented each time bad quality data is received for any
program trigger data item. Refer to Appendix B: OPC Quality Flags for information about
OPC data quality.
EnableDevice_ErrorCount
This is the error count associated with the control input used to enable this Math and
Logic device. It is incremented each time bad quality data is received for this data item.
(Refer to Appendix B: OPC Quality Flags for information about OPC data quality.)
This item is not present if the device enable control input is not configured. Refer to the
Device Logic Enable group for more information.
EnableDevice_ItemID
This is the item ID string associated with the device enable control input.
This item is not present if the device enable control input is not configured. Refer to the
Device Logic Enable group for more information.
EnableDevice_UpdateCount
The number of times the device enable control input has changed from enabled to
disabled or disabled to enabled. This count is incremented each time IsEnabled changes
state.
This item is not present if the device enable control input is not configured. Refer to the
Device Logic Enable group for more information.
EnableDevice_LastError
The last error code associated with the device enable control input.
This item is not present if the device enable control input is not configured. Refer to the
Device Logic Enable group for more information.
EnableDevice_LastErrorQuality
The last error quality associated with the device enable control input. (Refer to Appendix
B: OPC Quality Flags for information about OPC data quality.)
This item is not present if the device enable control input is not configured. Refer to the
Device Logic Enable group for more information.
EnableDevice_LastErrorString
The last error code string associated with the device enable control input.
This item is not present if the device enable control input is not configured. Refer to the
Device Logic Enable group for more information.
The following items are shown in folders called _Status located in the ${Item Name}
folder, which is located in the same folder as the associated data item.
Program_ErrorCount
This is the error count associated with the data item's program. It is incremented each
time the program execution encounters a runtime error.
Note When a program generates a runtime error, its current execution is terminated.
Program_LastError
Program_LastErrorLine
This is the line number in the program's source code at which the last runtime error
occurred.
Program_LastErrorQuality
The last error quality associated with this program. (Refer to Appendix B: OPC Quality
Flags for information about OPC data quality.)
Program_LastErrorString
Program_ExeCount
Program_ExeTimeLast
This is the duration of the last program execution. The time is expressed in
microseconds.
All programs executing under Windows are subject to interruptions (device driver
Note
interrupts, preemptions by higher priority programs, etc.). The value of the
Program_ExeTimeLast includes the time of these interruptions. Therefore, your
program's last execution time will generally be lower than the value in the
Program_ExeTimeLast.
Program_ExeTimeMin
This is the minimum duration of the program's execution. The time is expressed in
microseconds.
Each Save & Update Server operation resets the Program_ExeTimeMin value to
Note
zero.
Program_ExeTimeMax
This is the maximum duration of the program's execution. The time is expressed in
microseconds.
All programs executing under Windows are subject to interruptions (device driver
Note
interrupts, preemptions by higher priority programs, etc.). The value of the
Program_ExeTimeMax includes the time of these interruptions. Therefore, your
program's maximum execution time will generally be lower than the value in the
Program_ExeTimeMax.
Each Save & Update Server operation resets the Program_ExeTimeMax value to
Note
zero.
ProgramTrigger_ErrorCount
The total error count associated with the trigger program execution control input. This
counter is incremented each time bad quality data is received for this input. (Refer to
Appendix B: OPC Quality Flags for information about OPC data quality.)
This item is not present if the trigger program execution input is not configured.
ProgramTrigger_ItemID
This is the Item ID string associated with the trigger program execution control input.
This item is not present if the trigger program execution input is not configured.
ProgramTrigger_LastError
The last error code associated with the trigger program execution control input.
This item is not present if the trigger program execution input is not configured.
ProgramTrigger_LastErrorQuality
The last error quality associated with the trigger program execution control input. (Refer
to Appendix B: OPC Quality Flags for information about OPC data quality.)
This item is not present if the trigger program execution input is not configured.
ProgramTrigger_LastErrorString
The last error code string associated with the trigger program execution control input.
This item is not present if the trigger program execution input is not configured.
ProgramTrigger_LastValue
The last data value associated with the trigger program execution control input.
This item is not present if the trigger program execution input is not configured.
ProgramTrigger_UpdateCount
The total update count for the trigger program execution control input. This counter is
incremented each time an OnDataChange callback delivers a new value for the trigger
program execution control input.
This item is not present if the trigger program execution input is not configured.
Debugging Aids
Once you have written it, your program may not work as expected. It may fail to compile
because of fatal syntax errors, it may compile successfully but not run, or it may run with
incorrect results.
To help you fix these problems, the Cyberlogic OPC server includes a number of
debugging tools.
Status Window
If the compiler detects errors in your code, it displays an explanation of these errors in
the status window.
In this example, line 4 has two operators in a row. The Status pane shows that the error
occurred in line 4 and gives a description of the problem. The red icon at the left side of
the Code View pane visually flags the error location.
Status Items
The status items are data items, available to any OPC client application, that provide key
information about the functioning of your program. You can find detailed information
about them in the Status Items section.
You can use the following procedure to evaluate your program at runtime:
1. Examine the Program_ExeCount status item to verify that the program is running.
This count will increment each time the program executes. If it is not increasing, the
program is not running.
2. Examine the Program_ErrorCount to see if any errors have been recorded. This data
item records the number of runtime errors that the software has detected.
Note The error counts for all programs can be reset to zero by an Off to On transition of the
ResetAllErrorCounts status item. This item is located in the _Status folder directly under
the Math and Logic device.
DebugOutput Function
It is frequently helpful to be able to see the values of internal variables as the program is
running. The DebugOutput function allows you to do this. With it, you can output any
value in the program to a data item that is available for viewing in an OPC client
application.
Writing to debug outputs extends the execution time. Therefore, you should remove or
comment out all DebugOutput calls once the program is running as desired.
Public Variables
You can declare typed variables in your program to be public. These Public Variables will
then be available to the OPC clients, appearing just as regular, configured OPC data
items. This makes it very easy for you to view these variables during program execution.
To provide you with additional examples, the software also includes a configuration file
Note
with a set of sample programs. These will help you to understand how the various
functions work. They will also give you ideas about what you can do with C-logic, and
they can be modified and used in creating your own programs. You will find a listing of
some of the sample programs in Appendix D: Sample Programs.
This program adds the absolute values of three data items, excluding those that have a
bad quality. The local variable declarations are at the top of the program, followed by the
executable statements.
varX = 0;
varY = 0;
varZ = 0;
General Rules
You must place all local declarations for constants and variables at the beginning of the
program, before any executable statements.
All names and keywords in the language are case-insensitive. Numeric values that
contain letters (0t47, 0x5FC2, -2.5e-4) are also case-insensitive. However, character and
string values ('A', "Crosslink") are case-sensitive.
At the start of each program execution, the values of all public variables and variables of
type ITEM are set to the current values of their associated data items. If the OPC server
receives new data from an external device, the OPC data items’ values will be updated,
but the new values will not be applied to the corresponding local variables until the
beginning of the next program execution. For more information on data item variables,
refer to the Data Item Declarations section.
Variables used in expressions must have GOOD or UNCERTAIN quality, or the expression
cannot be evaluated. For the result to have GOOD quality, all operands must have GOOD
quality. If any operands have UNCERTAIN quality, the result will have UNCERTAIN
quality. An attempt to operate on a variable with BAD quality will terminate the
processing of the expression and generate an error.
However, for conversions between signed and unsigned integers with the same number
of bits, the value is not checked for overflow. For example:
A signed 8-bit integer value of –1 will convert to an unsigned 8-bit integer
value of 255.
An unsigned 8-bit integer value of 254 will convert to a signed 8-bit integer
value of –2.
The same rules apply to conversions between any pair of integers of 8, 16,
32 or 64 bits, when the lengths are the same.
Comments
The C-logic compiler supports single-line comments. Comments begin with two forward
slashes (//) and are terminated by the next new line character. They cannot extend to a
second line.
Comments do not affect the generated code or the program's execution speed, but
greatly improve readability.
Constants
There are three types of constants:
Integer Constants (decimal, hex, octal, binary, character)
Floating Point Constants
String Constants
Several commonly-used constants are predefined and need not be declared. You will find
a list of these in the Predefined Constants section.
The Linear Conversion Sample Program and Two Sines Sample Program include
examples of the use of constants.
Integer Constants
Integer constants can be of type decimal, hexadecimal, octal or binary. Decimal numbers
must not contain a decimal point.
Binary, octal and hexadecimal constants are always taken as a 64-bit signed integer, with
the most significant bit extended to fill any unspecified bit positions. Therefore, if the
value you specify has 1 as the most significant bit, it will be interpreted as a negative
number. To force such a value to be interpreted as positive, you must add a leading 0.
For example, 0xFF will be taken as -1. Its MSB is 1, and that will be extended to produce
the 64-bit signed integer FFFFFFFFFFFFFFFF. If you intend it to be taken as 255, you
must enter the value as 0x0FF. Doing so forces the MSB to be 0, and the 64-bit
representation will then be 00000000000000FF.
This is a concern for binary numbers with a most significant bit of 1, octal numbers with
a most significant digit in the range 4-7, and hexadecimal numbers with a most
significant digit in the range of 8-F.
This is not an issue for decimal numbers, because they are always assumed to be
positive unless the "–" sign is present.
Character Constants
Character constants are also integer constants. They consist of a character enclosed in
single quotation marks. For example:
'A' // ASCII A
' ' // Space character
Escape Sequences
Escape sequences are character combinations that consist of a backslash (\) followed by
a letter or by a combination of digits. They provide literal representations of carriage
control codes, nonprinting characters, and other characters that have special meanings.
If you want to create a character constant that contains one of these special characters,
you must use an escape sequence. An escape sequence is regarded as a single
character, and is therefore valid as an integer constant.
The following table lists the ANSI escape sequences supported by C-logic and the
characters they represent.
If a backslash precedes a character that does not appear in the table, the character is
undefined. The compiler handles this undefined character as the character itself. For
example, \c is treated as c.
You can omit either the digits before the decimal point (the integer portion), or the digits
after the decimal point (the fractional portion), but not both. You can omit the decimal
point only if you include an exponent. No white-space characters are permitted. Here are
some examples:
100. // = 100.0
100.25 // = 100.25
1.575E1 // = 15.75
1575e-2 // = 15.75
-2.5e-3 // = -0.0025
25E-4 // = 0.0025
100 // INVALID: no decimal point and no exponent
-2.5 e-3 // INVALID: contains a space
String Constants
You can use numeric string constants in arithmetic expressions. They will be converted to
numbers before the expression is evaluated. For example:
Predefined Constants
Several commonly-used constants are predefined, and need not be declared. Here is a
list of these constants:
Local Declarations
You must place all local declarations at the beginning of the program, before any
executable statements. There are four types of local declarations:
Constant Declarations
Data Item Declarations
Typed, Untyped and Public Variable Declarations
Each variable has a set of Standard Variable Properties that you can access within your
program. The Date & Time Variables have additional properties related to date and time,
as explained in the Date & Time Variable Declarations section.
Constant Declarations
A constant declaration assigns a name to a constant. You can then use the name in your
program in place of the actual constant value. Here is the syntax:
Where:
Examples:
An item declaration assigns a variable name to an OPC data item. This declaration is
required before you can use the value and properties of that data item within your
program.
At the start of each program execution, the values of all public variables and variables
Caution!
of type ITEM are set to the current values of their associated data items. If the OPC
server receives new data from an external device, the OPC data items’ values will be
updated, but the new values will not be applied to the corresponding local variables
until the beginning of the next program execution.
Where:
ItemID Item ID string for the OPC data item. This can either be
a full or relative Item ID. See below for more
information on relative Item IDs.
ExcludeFrom
OnDataChangeTrigger Optional flag. When true, it excludes this data item from
triggering On Data Change executions of a program.
Commonly used when declaring data items that are used
only as outputs. If omitted, it defaults to false.
Examples:
In addition to the full Item IDs, the ItemID string can specify a data item reference that
is relative to the data item being programmed. Here are the rules for creating relative
Item IDs:
Each period ('.') in front of the Item ID represents one level back from the
current data item.
Examples:
You cannot write to individual properties of variables of type ITEM. You can modify them
only by assigning a new value to the entire item variable.
Example:
ITEM x ("ItemId");
x.Quality = QUALITY_SENSOR_FAILURE; // Invalid
x = y; // Valid (y.Quality may be BAD)
The ability to write to ITEM variables is one way you can create programs with multiple
outputs; another way is to use Public Variables. An assignment to an ITEM variable
updates the server's cache for the associated data item. This type of assignment persists
between program executions.
If a variable of type ITEM is associated with a bit or register in an external device, the
Caution!
assignment will not initiate a write to that device. Only the cached value in the server
will be updated.
Furthermore, it is likely that the assigned data will be overwritten when the server
obtains new data from the external device. Therefore, you should assign values to data
items only if they are simulated with the Echo simulation selection.
If you need to write to an external device, setup a crosslink that is triggered from your
program. Refer to the Cyberlogic OPC Server Help for more information.
Assignments to ITEM variables are much slower than similar assignments to the local
Caution!
variables. Avoid multiple assignments to the same variable during the same program
execution.
A variable declaration creates a local or public variable and assigns it a name. This
declaration is required before you can use the variable within your program.
Local variables may be typed or untyped. When the program makes an assignment to a
typed variable, it converts the value to the variable's type. When it makes an assignment
to an untyped variable, the variable's value assumes the type of the assigned expression.
Public variables are a form of typed variable with the added capability of being browsed
and read just like a configured OPC server data item.
Local and public variables support the Standard Variable Properties. The Timestamp
property of all local variables is initialized to the current time at the start of each program
execution. This value will change when the program makes assignments to a variable or
to its Timestamp property. The Timestamp of public variables, however, is modified only
during the variable assignments, and individual writes to the Timestamp property (as well
as Quality and Error) are not allowed.
Untyped Variables
Where:
Example:
Untyped variables support the Standard Variable Properties. The Quality and Error
properties of uninitialized untyped variables are set as follows:
Initialized untyped variables are set to their initialization value only once. This is done
when the variable is created, which happens before the first program execution.
Subsequent changes to the variable's value are persistent across program executions.
Therefore, each program execution starts with variables whose values are the same as
they were at the end of the previous program execution.
Data assigned to typed and untyped variables persists between program executions,
Caution!
but does not persist following the Save & Update Server operation. All local variables
are reinitialized each time a Save & Update Server is done.
Use public variables if it is crucial that your variables persist across the Save & Update
Server operations.
Typed Variables
Where:
LowerBound Optional lower bound value for the array. If not used, it
defaults to 0.
A Variable Type entry in the following table may contain multiple names. Each of these
Note
names are equivalent and can be used interchangeably.
Examples:
Typed variables support the Standard Variable Properties. The Quality and Error
properties of uninitialized typed variables are set as follows:
Initialized typed variables are set to their initialization value(s) only once. This is done
when the variable is created, which happens before the first program execution.
Subsequent changes to the variable's value are persistent across program executions.
Therefore, each program execution will start with variables whose values are the same
as those at the end of the previous program execution.
Data assigned to typed and untyped variables persists between program executions,
Caution!
but does not persist following the Save & Update Server operation. All local variables
are reinitialized each time a Save & Update Server is done.
Use public variables if it is crucial that your variables persist across the Save & Update
Server operations.
Public Variables
Public variables are a form of typed variable with the added capability of being browsed
and read just like any configured OPC server data item.
Unlike the ITEM variables, which refer to data items that already exist in the server's
address space, public variables need not be configured outside of a program. They are
automatically added to the folder named ${Item Name}, which is located in the same
folder as the associated data item.
Public variables are convenient for defining inputs and outputs for a program. They can
also help you debug a program by temporarily making all or some of the program's
variables public. By doing so, internal variables are made externally visible, so that you
can monitor them during the program execution.
At the start of each program execution, the values of all public variables and variables
Caution!
of type ITEM are set to the current values of their associated data items. If the OPC
server receives new data from an external device, the OPC data items’ values will be
updated, but the new values will not be applied to the corresponding local variables
until the beginning of the next program execution.
Assignments to public variables are much slower than similar assignments to local
Caution!
variables. Therefore, you should not declare all variables public, except when
debugging.
ExcludeFrom
OnDataChangeTrigger Optional flag. When true, it excludes this data item from
triggering On Data Change executions of a program.
Commonly used when declaring data items that are used
only as outputs. If omitted, it defaults to false.
LowerBound Optional lower bound value for the array. If not used, it
defaults to 0.
Examples:
public int x; // Uninitialized, all defaults
public int x(5); // Initialized, rest default
public double x[10]({1,2,3}); // Initialized public array
public int x(5,,100); // Initialized, sample @ 100 ms
Unlike untyped and typed local variables, uninitialized public variables initialize to the
default value for their data type: zero for numeric types, and an empty string for strings.
Initialized public variables are set to their initialization values only once. This is done
when the variable is created, which happens before the first program execution.
Subsequent changes to the variable's value are persistent across program executions.
Therefore, each program execution will start with variables whose values are the same
as those at the end of the previous program execution, unless they were written to
externally.
Data assigned to public variables persists between program executions and Save &
Note
Update Server operations. This is different than the typed and untyped local variables,
which are reinitialized each time a Save & Update Server is done.
Public variables support the Standard Variable Properties. Similar to the ITEM variables,
you cannot write to the individual properties of public variables. You can modify them
only by assigning a new value to the entire variable.
Example:
public int x;
x.Quality = QUALITY_SENSOR_FAILURE; // Invalid
A date and time variable declaration creates a variable of type DATETIME. This type of
variable simplifies date and time manipulations. Date and time declarations use the
following syntax.
DATETIME Name[(Type)];
Where:
Variables of type DATETIME have the Standard Variable Properties, and the following
additional properties. These are interpreted as either Local or UTC time, according to the
Type setting. They can be read and written individually. The initial setting for DATETIME
variables is January 1, 2010 at 00:00:00.000
Month January = 1
February = 2
March = 3
April = 4
May = 5
June = 6
July = 7
August = 8
September = 9
October = 10
November = 11
December = 12
DayOfWeek Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
You can access DATETIME variables directly, in which case the value is an OPC-
compatible timestamp. An OPC timestamp is a 64-bit signed integer (int64) value equal
to the number of 100-nanosecond intervals since January 1, 1601. It is always expressed
in UTC time.
Example:
The Array to Date & Time Sample Program and Time in Your Time Zone #1 Sample
Program also include examples of the use of date and time declarations and properties.
Examples:
Properties of local variables can be read and written individually. ITEM and public
variable properties can be read, but cannot be written. When reading a property, the
returned quality is always GOOD, and the error code is set to zero (S_OK).
The Maintenance Time Tracking Sample Program and Linear Conversion Sample Program
include examples of how to test and set variable properties.
Expressions
The C-logic language supports four types of expressions:
Arithmetic
Relational
Logical
Bitwise
The operands in an expression must have either GOOD or UNCERTAIN quality for the
expression to be fully evaluated. An operand with a BAD quality immediately stops the
evaluation of the remaining part of an expression, and causes the current program to
terminate. However, data with BAD quality can be assigned to a local variable without
terminating the program.
The following table summarizes the rules for determining the quality of an expression:
In a simple variable assignment, such as "x=y;", the Timestamp of x will be the same
Note
as the Timestamp of y. However, if you would rather use the current time instead,
modify this assignment to include at least one operator (e.g. "x=+y;").
Arithmetic
If all operands in an arithmetic expression are integers or booleans, they are converted
to 64-bit signed integers before the expression is evaluated, and the result of the
expression is also a 64-bit signed integer. Otherwise, the operands are converted to 64-
bit floating point (double) values, and the result is a 64-bit floating point value.
A special rule applies to addition with string operands. If all operands are strings, the
result of the addition is a string that is a concatenation of the operands.
Example:
To force an arithmetic operation instead, use a numeric value for the first operand.
Example:
The Linear Conversion Sample Program also includes examples of arithmetic expressions.
Relational
The result of a relational expression is a value of type bool. The following relational
operations are supported.
If both operands in a relational expression are strings, they are compared using
lexicographic (dictionary) order. If both operands are integers or booleans, they are
converted to 64-bit signed integers (int) before the expression is evaluated. Otherwise,
the operands are converted to 64-bit floating point (double) values.
Logical
The operands in a logical expression are always converted to type bool before the
expression is evaluated. The result of the expression is also of type bool. The following
logical operations are supported.
Bitwise
The operands in a bitwise expression are converted to 64-bit signed integers (int) before
the expression is evaluated. The result of the expression is also of type int. The following
bitwise operations are supported:
C-logic operators follow a strict precedence, which defines the evaluation order of
expressions. Operators associate with either the expression to their left or the expression
to their right, a property called "associativity". Operators with equal precedence are
evaluated left to right in an expression, unless explicitly forced by parentheses.
The following table shows the precedence and associativity of C-logic operators, from
highest to lowest precedence.
Statements
Programs consist of three types of executable statements:
Conditional Branch (If-Else) Statements
Assignment (=) Statements
Return Statements
The if-else statement controls conditional branching. The syntax is shown below. If the
value of expression is true, statement1 is executed. If the value of expression is false and
the optional else is present, statement2 is executed.
Syntax:
if (expression)
{
statement1;
}
[else
{
statement2;
}]
Where:
The program block delimiting characters ('{' and '}') in the "If" and the "else" sections
Note
can be omitted if a block consists of a single executable statement.
Example:
if(x > y)
{
z = x;
}
else
z = y;
The Linear Conversion Sample Program also includes examples of conditional branch
statements.
Syntax:
VarName = expression;
Where:
Example:
x = y;
circumference = 2*pi*radius;
An assignment to a variable modifies its value, and all of its properties. However, an
assignment to an array element does not change the quality, timestamp, or error code
for the whole array. An expression assigned to an array element must not have BAD
quality, or an exception will be generated and the program will terminate.
An assignment to a property of a local variable modifies only the selected property. If the
assigned expression has BAD quality, an exception will be generated and the program
will terminate. Assignments to individual properties for ITEM and public variables are not
allowed.
If VarName is a typed local variable, the result of the expression is converted to the
variable type before the assignment. If VarName is a typed array, the element counts of
both arrays must match, however, the lower bound value of the VarName is preserved.
The assignment persists between program executions, but does not persist between
Save & Update Server operations.
If VarName is an untyped local variable (VAR), the result is not converted, but instead
the variable assumes the expression's data type. The assignment persists between
program executions, but does not persist between Save & Update Server operations.
If VarName is of type ITEM or public, the assignment will update the server's cache for
the associated data item. If VarName is a typed array, the element counts of both arrays
must match, however, the lower bound value of the VarName is preserved. This type of
assignment persists between program executions and Save & Update Server operations.
Return Statements
The return statement ends the program execution and optionally returns a result of an
expression.
Syntax:
return [expression];
Where:
Example:
The result of the returned expression is converted to the data type of the data item
associated with the program. Its value is then assigned to that data item. Typically, a
program will have one return statement, but may have more than one, or none.
The Maintenance Time Tracking Sample Program is an example of a program that uses
multiple return statements.
Math Functions
The supported math functions are:
Abs
Syntax
Where:
Expression The value for which you want the absolute value.
Return value
Remarks
For integer arguments, the Abs function returns an integer absolute value. For all other
types, the argument is converted to double and the result of type double is returned.
Examples
x = Abs(z);
y = Abs(a-b);
Acos
Syntax
Where:
Return value
Remarks
If the value of Expression is less than –1 or greater than 1, acos returns an indefinite.
Examples
x = Acos(0.3);
y = Acos(z);
Asin
Syntax
Where:
Return value
Remarks
If the value of Expression is less than –1 or greater than 1, asin returns an indefinite.
Examples
x = Asin(0.3);
y = Asin(z);
Atan
Syntax
Where:
Return value
Examples
x = Atan(0.3);
y = Atan(z);
Ceil
Syntax
Where:
Expression The value for which you want the ceiling value.
Return value
Returns a double value representing the smallest integer greater than or equal to
Expression.
Remarks
Examples
x = Ceil(2.7); // Returns 3
y = Ceil(-2.7); // Returns -2
Cos
Syntax
Where:
Return value
Remarks
If Angle is greater than or equal to 263, or less than or equal to –263, a loss of
significance in the result occurs.
Examples
x = Cos(pi/2);
y = Cos(varAngle + varPhase);
Exp
Syntax
Where:
Return value
Returns the exponential (natural antilogarithm) of the argument. That is, the result is e
to the power Expression, where e is the base of the natural logarithm.
Remarks
Examples
x = Exp(3);
y = Exp(z);
Floor
Syntax
Where:
Expression The value for which you want the floor value.
Return value
Returns a double value representing the greatest integer less than or equal to
Expression.
Remarks
Examples
x = Floor(2.7); // Returns 2
y = Floor(-2.7); // Returns -3
IsFiniteNumber
Syntax
Where:
Return value
Returns true if Expression is not infinite; that is, if –INF < Expression < +INF. It returns
false if Expression is infinite or NAN.
Remarks
Examples
IsValidNumber
Syntax
Where:
Return value
Remarks
Examples
Ln
Syntax
Where:
Return value
Remarks
Examples
x = Ln(27.5);
y = Ln(z);
Log
Syntax
Where:
Return value
Remarks
Examples
x = Log(y);
pH = -1*Log(varConcH);
Max
Syntax
Where:
Return value
Remarks
For integer arguments, the Max function returns an integer value. For all other types, the
argument is converted to double and a result of type double is returned.
Examples
x = Max(a,b);
y = Max(varSetPoint,20);
Min
Syntax
Where:
Return value
Remarks
For integer arguments, the Min function returns an integer value. For all other types, the
argument is converted to double and a result of type double is returned.
Examples
x = Min(a,b);
y = Min(Evil1,Evil2); // Returns the lesser of two evils
Pow
Syntax
Where:
Return value
Remarks
Pow does not recognize integral floating-point values greater than 264, such as 1.0E100.
Examples
Rand
Syntax
int Rand()
Return value
Remarks
The Rand function uses the operating system to generate cryptographically secure
random numbers.
Examples
Round
Syntax
Where:
Return value
Returns the value of Number rounded to the specified number of decimal places.
Remarks
If Places is zero, it will be possible to obtain a floating point value that exactly represents
the rounded number, so the return value is of type double.
If Places is greater than zero, it may not be possible to represent the exact value in
floating point form. Therefore, the return value is of type string.
Examples
Sin
Syntax
Where:
Return value
Remarks
If Angle is greater than or equal to 263, or less than or equal to –263, a loss of
significance in the result occurs.
Examples
x = Sin(2*pi);
y = Sin(varAngle);
The Two Sines Sample Program also includes examples of this function.
Sqrt
Syntax
Where:
Expression The value for which you want to determine the square
root.
Return value
Remarks
Examples
x = Sqrt(25.);
y = Sqrt(varMeanSquare);
The Square Root Conversion Sample Program also includes examples of this function.
Tan
Syntax
Where:
Return value
Remarks
If Angle is greater than or equal to 263, or less than or equal to –263, a loss of
significance in the result occurs.
Examples
x = Tan(pi/4);
y = Tan(varAngle);
String Functions
The supported string functions are:
Compare
Syntax
Where:
Return value
Returns a 64-bit signed integer indicating the lexical (dictionary order) relationship
between the two strings.
Value Condition
Less than zero StringA is less than StringB.
Zero StringA equals StringB.
Greater than zero StringA is greater than StringB.
Examples
Concat
Syntax
Where:
Return value
Remarks
Two variables of type string can also be concatenated by using a plus sign ('+') in an
expression. For example, Concat("abc", "123") is equivalent to an expression: "abc" +
"123".
Examples
Contains
Returns a boolean indicating whether the specified SeekString occurs within the String.
Syntax
Where:
Return value
Returns a boolean indicating whether the specified SeekString occurs within the String.
Remarks
Returns true if the SeekString occurs within the String, or if SeekString is the empty
string (""); otherwise, returns false.
Examples
EndOf
Syntax
Where:
Return value
Returns a string equivalent to the substring of length Length that ends at the end of
String.
Examples
EndsWith
Syntax
Where:
Return value
Returns true if EndString matches the end of String; otherwise returns false.
Remarks
Compares EndString to the substring at the end of String that is the same length as
EndString, and indicates whether they are equal. To be equal, EndString must be an
empty string, or match the end of String.
Examples
Format
Syntax
Where:
Return value
Returns a copy of FormatString in which the format items have been replaced by the
string equivalent of the corresponding Argument.
Remarks
Each Argument (if any) is converted and output according to the corresponding format
specification in FormatString. A null character is appended after the last character
written. Refer to Appendix C: Format Specification Fields for details on how the format
specifications are interpreted.
Examples
The Time in Your Time Zone #1 Sample Program also includes examples of this function.
IndexOf
Reports the index of the first occurrence of the specified string within another string. The
search starts at a specified character position.
Syntax
Where:
Return value
Returns the zero-based index of the first occurrence of a specified string within another
string, starting from a specified position. If the search fails to locate a match, the
function returns a value of -1.
Examples
The ABC to abc Sample Program also includes an example of this function.
Insert
Syntax
Where:
Return value
Returns a new string equivalent to String but with InsertString inserted at position Index.
Remarks
If Index is equal to the length of String, InsertString is appended to the end of String.
Examples
Length
Syntax
Where:
Return value
Returns the number of characters in String, not including a terminating null character.
Examples
x = Length("Montana"); // Returns 7
y = Length(varFirstName);
Like
Syntax
Where:
Return value
Remarks
Searches for Pattern inside String and returns a boolean that indicates whether or not
Pattern is contained in String.
You can use the following symbols in Pattern to provide wildcard matches:
CharList can specify a range of characters by separating the lower and upper bounds of
the range with a hyphen (-). For example, [A-Z] results in a match if the corresponding
character position in String contains any uppercase letter. You can specify multiple
ranges in a single CharList (e.g. [A-Z0-9]).
When you use a range of characters, you must specify it in ascending sort order,
that is, from lowest to highest. [A-Z] is a valid CharList, but [Z-A] is not.
To match the special characters left bracket ([), question mark (?), number sign (#), or
Note
asterisk (*), enclose them in brackets. You cannot use a right bracket (])within a
CharList to match itself, but you can use it outside a CharList as an individual
character.
The Like function performs a character-by-character comparison of the String and the
Note
Pattern strings. If these strings have different length, then the function will return
false, unless the * (asterisk) is used.
Examples
PadEnd
Left-aligns the characters in a string, padding on the right with a specified Unicode
character for a specified total length.
Syntax
Where:
Return value
A new string that is equivalent to String, but left-aligned and padded on the right with as
many PaddingChar characters as needed to create a length of TotalLength. Or, if
TotalLength is less than the length of String, a new string that is identical to String.
Remarks
Examples
PadStart
Right-aligns the characters in a string, padding on the left with a specified Unicode
character for a specified total length.
Syntax
Where:
Return value
A new string that is equivalent to String, but right-aligned and padded on the left with as
many PaddingChar characters as needed to create a length of TotalLength. Or, if
TotalLength is less than the length of String, a new string that is identical to String.
Remarks
Examples
Remove
Syntax
Where:
Return value
Remarks
If CharCount is not specified, this function deletes all the characters from String
beginning at a specified Index position and continuing through the last position.
Examples
Replace
Replaces all occurrences of a specified string in the Source string, with another specified
string.
Syntax
Where:
Return value
Returns a string equivalent to the Source string, but with all instances of OldString
replaced with NewString.
Remarks
Examples
StartOf
Syntax
Where:
Return value
Returns a string equivalent to the substring of length Length that begins at start of
String.
Examples
StartsWith
Syntax
Where:
Return value
Returns true if StartString matches the beginning of String; otherwise returns false.
Remarks
Compares StartString to the substring at the beginning of String that is the same length
as StartString, and indicates whether they are equal. To be equal, StartString must be an
empty string, or match the beginning of String.
Examples
Substring
Syntax
Where:
Return value
Returns a string equivalent to the substring of length Length that begins at StartIndex in
String. If Length is not specified, the substring will continue through the end of String.
Returns an empty string ("") if Length is zero, or if Length is not specified and StartIndex
is equal to the length of String.
Returns an error if StartIndex plus Length is greater than the length of String.
Examples
ToLower
Syntax
Where:
Return value
Remarks
The conversion depends on the default system locale, therefore different results may be
produced depending on the system language setting.
Examples
ToNumber
Syntax
Where:
Return value
If Base is 0 or is not specified, then you must use the b|B|t|T|x|X notation to indicate
Caution!
binary, octal or hexadecimal numbers. The specified value is always taken as a 64-bit
signed integer, with the most significant bit extended to fill any unspecified bit
positions. Therefore, if the value you specify has 1 as the most significant bit, it will be
interpreted as a negative number. To force such a value to be interpreted as positive,
you must add a leading 0.
For example, "0xFF" will be taken as -1. Its MSB is 1, and that will be extended to
produce the 64-bit signed integer FFFFFFFFFFFFFFFF. If you intend it to be taken as
255, you must enter the value as "0x0FF". Doing so forces the MSB to be 0, and the
64-bit representation will then be 00000000000000FF.
This is a concern for binary numbers with a most significant bit of 1, octal numbers
with a most significant digit in the range 4-7, and hexadecimal numbers with a most
significant digit in the range of 8-F.
This is not an issue for decimal numbers, because they are always assumed to be
positive unless the "–" sign is present.
Examples
ToString
Syntax
Where:
Return value
Returns a string that represents a converted integer Number in the specified base.
Examples
ToUpper
Syntax
string ToUpper(String)
Where:
Return value
Remarks
The conversion depends on the default system locale, therefore different results may be
produced depending on the system language setting.
Examples
Trim
Removes all instances of a specified set of characters from the beginning and end of a
specified string.
Syntax
Where:
Return value
Returns the string that remains after all occurrences of the characters in TrimChars are
removed from the beginning and end of String.
Remarks
The TrimChars parameter is optional. If not present, whitespace characters are trimmed
instead. The whitespace characters are: space, horizontal tab ('\t'), new line ('\n'),
carriage return ('\r'), form feed ('\f') and vertical tab ('\v').
Examples
TrimEnd
Removes all instances of a specified set of characters from the end of a specified string.
Syntax
Where:
Return value
Returns the string that remains after all occurrences of the characters in TrimChars are
removed from the end of String.
Remarks
The TrimChars parameter is optional. If not present, whitespace is trimmed instead. The
whitespace characters are: space, horizontal tab ('\t'), new line ('\n'), carriage return
('\r'), form feed ('\f') and vertical tab ('\v').
Examples
TrimStart
Removes all instances of a specified set of characters from the beginning of a specified
string.
Syntax
Where:
Return value
Returns the string that remains after all occurrences of the characters in TrimChars are
removed from the beginning of String.
Remarks
The TrimChars parameter is optional. If not present, whitespace characters are trimmed
instead. The whitespace characters are: space, horizontal tab ('\t'), new line ('\n'),
carriage return ('\r'), form feed ('\f') and vertical tab ('\v').
Examples
Bitwise Functions
The supported bitwise functions are:
GetBitField
Syntax
Where:
StartBit Zero-based index of the first bit of the desired bit field.
Return value
Remarks
This function shifts the specified Number right by the StartBit count, and then masks off
the high bits above the LS BitCount bits. As a result, the masked off high bits are always
cleared, and the returned result is not sign extended.
Examples
x = GetBitField(0xE6,2,4); // Returns 9
y = GetBitField(z,5,2);
SAR
Syntax
Where:
Return value
Returns an integer number that is the result of the specified arithmetic right shift.
Remarks
The SAR (shift arithmetic right) function shifts the bits in the Number argument to the
right (toward the less significant bit locations). For each shift count, the most significant
bit of the result is filled with the sign of the unshifted Number, and the least significant
bit is shifted out.
Examples
SHL
Syntax
Where:
Return value
Returns an integer number that is the result of the specified logical left shift.
Remarks
The SHL (shift logical left) function shifts the bits in the Number argument to the left
(toward the more significant bit locations). For each shift count, the most significant bit
of the result is shifted out, and the least significant bit is cleared.
Examples
SHR
Syntax
Where:
Return value
Returns an integer number that is the result of the specified logical right shift.
Remarks
The SHR (shift logical right) function shifts the bits in the Number argument to the right
(toward the less significant bit locations). For each shift count, the most significant bit of
the result is cleared, and the least significant bit is shifted out.
Examples
AddSeconds
Syntax
Where:
Return value
Returns a DATETIME-compatible UTC value that represents the date and time after
Seconds have been added to DateTime.
Remarks
Examples
The Time in Your Time Zone #1 Sample Program also includes examples of this function.
FormatDate
Formats a value of type DATETIME as a string containing the date in the local locale.
Syntax
Where:
Return value
Remarks
The date is always formatted according to the locale (language) for the system and
represents the local date, even if the DateTime variable was configured for the UTC time
zone.
Examples
FormatTime
Formats a value of type DATETIME as a string containing the time in the local locale.
Syntax:
Where:
Return value
Remarks
The time is always formatted according to the locale (language) for the system and
represents the local time, even if the DateTime variable was configured for the UTC time
zone.
Examples
GetTimeZoneOffset
Returns the local time zone offset from UTC (Coordinated Universal Time).
Syntax
double GetTimeZoneOffset()
Return value
Remarks
GetTimeZoneOffset uses the current settings for the time zone and daylight saving time.
Therefore, when daylight saving time is in effect, this function will take it into account.
Examples
// This program returns a string showing the GMT time,
// using the system locale settings
int dt; // Current local time
TimeNow
Syntax
DATETIME TimeNow()
Return value
Remarks
Examples
The Time in Your Time Zone #1 Sample Program and Two Sines Sample Program also
include examples of this function.
The valid error code values are the same as the Microsoft HRESULT error codes. These
are 32-bit values with several fields encoded within the value. They can represent either
success or failure conditions.
The valid quality values are the same as the OPC Foundation quality codes. Refer to
Appendix B: OPC Quality Flags for information about OPC data quality.
GetErrorString
Returns the error string for the Error code of the specified argument.
Syntax
string GetErrorString(Argument)
Where:
Return value
Returns the error string associated with the Error code of Argument.
Remarks
Examples
ErrorStr = GetErrorString(x);
IsErrorFAILURE
Syntax
bool IsErrorFAILURE(Argument)
Where:
Return value
Remarks
Examples
if(IsErrorFAILURE(x))
{
return;
}
IsErrorSUCCESS
Syntax
bool IsErrorSUCCESS(Argument)
Where:
Return value
Remarks
Examples
if(IsErrorSUCCESS(x))
{
varX = x;
}
IsQualityBAD
Determines if the quality of the specified argument is BAD. (Refer to Appendix B: OPC
Quality Flags for information about OPC data quality.)
Syntax
bool IsQualityBAD(Argument )
Where:
Return value
Remarks
Examples
if(IsQualityBAD(x))
{
varResult.Quality = QUALITY_SENSOR_FAILURE;
}
The Maintenance Time Tracking Sample Program also includes examples of how to test
the Quality property.
IsQualityGOOD
Determines if the quality of the specified argument is GOOD. (Refer to Appendix B: OPC
Quality Flags for information about OPC data quality.)
Syntax
bool IsQualityGOOD(Argument)
Where:
Return value
Remarks
Examples
if(IsQualityGOOD(x))
{
varX = x;
}
The Maintenance Time Tracking Sample Program also includes examples of how to test
the Quality property.
IsQualityUNCERTAIN
Syntax
bool IsQualityUNCERTAIN(Argument )
Where:
Return value
Remarks
Examples
if(IsQualityUNCERTAIN(x))
{
x.Quality = QUALITY_BAD; // Treat UNCERTAIN as BAD
}
The Maintenance Time Tracking Sample Program also includes examples of how to test
the Quality property.
QualityLimitField
Returns the limit bits of the quality for the selected variable. (Refer to Appendix B: OPC
Quality Flags for information about OPC data quality.)
Syntax
int QualityLimitField(Argument)
Where:
Return value
Remarks
The operation performed by this function is equivalent to the following line of code:
The value returned by this function is typically used in comparisons to the following
Predefined Constants:
QUALITY_LIMIT_OK
QUALITY_LIMIT_LOW
QUALITY_LIMIT_HIGH
QUALITY_LIMIT_CONST
Examples
if(QualityLimitField(x) == LIMIT_HIGH)
{
// Treat values at high limit as BAD
x.Quality = QUALITY_BAD;
}
QualityStatusCode
Returns the quality with no limit bits for the specified argument. Refer to Appendix B:
OPC Quality Flags for information about OPC data quality.
Syntax
int QualityStatusCode(Argument)
Where:
Return value
Remarks
The operation performed by this function is equivalent to the following line of code:
The value returned by this function is typically used in comparisons to the following
predefined constants:
QUALITY_GOOD
QUALITY_BAD
QUALITY_NOT_CONNECTED
QUALITY_SENSOR_FAILURE
QUALITY_COMM_FAILURE
QUALITY_WAITING_FOR_INITIAL_DATA
QUALITY_LAST_USABLE
QUALITY_EGU_EXCEEDED
QUALITY_LOCAL_OVERRIDE
QUALITY_CONFIG_ERROR
QUALITY_DEVICE_FAILURE
QUALITY_LAST_KNOWN
QUALITY_OUT_OF_SERVICE
QUALITY_UNCERTAIN
QUALITY_SENSOR_CAL
QUALITY_SUB_NORMAL
Examples
if(QualityStatusCode(x) == QUALITY_LAST_USABLE)
{
// Treat QUALITY_LAST_USABLE as GOOD
x.Quality = QUALITY_GOOD;
}
Other Functions
Additional functions are:
ArrayBounds Returns an array with the lower bound values for each array
dimension
ArrayDimElements Returns an array with the number of elements for each array
dimension
DebugOutput Sends a formatted data string to a debug output
GetFixedInterval Returns the fixed interval used for running the program
IndexSort Ranks array elements according to either ascending or descending
order
IsArray Determines if the Argument is an array
SetFixedInterval Sets the fixed interval for running the program to a specified value
Sort Sorts the input array as specified
ArrayBounds
Returns an array containing the lower-bound values for each dimension of a given array.
Syntax
int[] ArrayBounds(ArrayVariable)
Where:
Return value
Remarks
Examples
double Array[10];
var ArrayBounds;
ArrayBounds = ArrayBounds(Array);
x = ArrayBounds[0]; // x is set to 0
ArrayDimElements
Returns an array containing the number of elements for each dimension of a given array.
Syntax
int[] ArrayDimElements(ArrayVariable)
Where:
Return value
Remarks
Examples
double Array[10];
var DimElements;
DimElements = ArrayDimElements(Array);
x = DimElements[0]; // x is set to 10
DebugOutput
Syntax
Where:
Return value
Returns a copy of FormatString in which each format item has been replaced by the
string equivalent of the corresponding Argument.
Remarks
This function uses the same format-control string specification as the Format function
(Refer to Appendix C: Format Specification Fields for complete information on the format
specifications.)
However, in addition to returning a formatted string, it writes the string to the selected
debug output. The debug outputs are automatically created in the ${Item Name} folder,
which is located in the same folder as the program's data item. The number of debug
outputs depends on the number of OutputIndex values used in the program. The name
of a debug output is "DebugOutputXX", where XX is a two-digit decimal representation of
the corresponding OutputIndex. (The OutputIndex values 0-9 will have leading zeros
appended to them.)
Examples
The Using Debug Outputs Sample Program also includes examples of this function.
GetFixedInterval
Returns the value of the current fixed interval used for running the program.
Syntax
int GetFixedInterval()
Return Value
Returns the value of the fixed interval, in milliseconds, that is used to schedule program
execution. If the fixed interval is not defined, it returns 0.
Remarks
Each C-logic program can be statically configured to run at a fixed interval. (Refer to the
Settings Tab help for more information.) A program can also dynamically set or modify
this interval at runtime by calling the SetFixedInterval function. The GetFixedInterval
function returns the current setting for this interval.
Examples
x = GetFixedInterval();
The Maintenance Time Tracking Sample Program also includes examples of this function.
IndexSort
Syntax
int[] IndexSort(ArrayVariable)
Where:
Return value
The order of the returned indexes indicates the order of the elements of ArrayVariable if
they were sorted as specified.
Remarks
The returned array's lower bound is zero. The returned indexes incorporate
ArrayVariable's lower-bound value. Because C-logic allows strings to be viewed as arrays,
it is possible to rank a string. When ranking a string, the IgnoreCase parameter is valid.
Strings are always considered to have a lower-bound of zero, and so that is used for the
returned indexes.
Examples
int Array[3]({3,1,2});
var Ranking;
The Rank Machine Performance Sample Program also includes an example of this
function.
IsArray
Syntax
int IsArray(Argument)
Where:
Return value
If Argument is an array, this function returns the number of dimensions in that array.
Otherwise, it returns 0.
Remarks
Examples
x = IsArray(Array); // Returns 1
x = IsArray(y); // Returns 0
SetFixedInterval
Sets the fixed interval for running the program to a specified value.
Syntax
Where:
Return Value
Returns the previous value of the fixed interval, in milliseconds, before the new
FixedInterval value was assigned. If the fixed interval was not defined, it returns 0.
Remarks
Each C-logic program can be statically configured to run at a fixed interval. (Refer to the
Settings Tab help for more information.) A program can also dynamically set or modify
this interval at runtime by calling the SetFixedInterval function. The program's data item
need not be statically configured to run at a fixed interval for the SetFixedInterval
function to succeed. Setting the interval to 0 disables the fixed interval execution.
Examples
The Maintenance Time Tracking Sample Program also includes examples of this function.
Sort
Syntax
SortedArray Sort(ArrayVariable)
Where:
Return value
Remarks
The returned array's lower bound matches the lower bound of the original ArrayVariable.
Because C-logic allows strings to be viewed as arrays, it is possible to sort a string. When
sorting a string, the IgnoreCase parameter is valid.
Examples
int Array[3]({3,1,2});
var Sorted;
The low eight bits of the Quality flags are defined in the form of three bit fields; Quality,
Substatus and Limit status. The Quality bits are arranged as follows:
QQSSSSLL
The high eight bits of the Quality Word are available for vendor-specific use. If these bits
are used, the standard OPC Quality bits must still be set as accurately as possible to
indicate what assumptions the client can make about the returned data. In addition, it is
the responsibility of any client interpreting vendor specific quality information to ensure
that the server providing it uses the same rules as the client. The details of such a
negotiation are not specified in this standard, although a QueryInterface call to the
server for a vendor specific interface such as IMyQualityDefinitions is a possible
approach.
The following sections provide details of the OPC standard quality bits.
Clients should check the Quality bit field of all results, even if they do not check the
Substatus or Limit fields.
The contents of the Value field must be a well-defined VARIANT even if the Quality is
BAD, indicating that it does not contain an accurate value. This simplifies error handling
in client applications. For example, clients are always expected to call VariantClear() on
the results of a Synchronous Read. Similarly the IAdviseSink must be able to interpret
and unpack the Value and Data included in the Stream, even if that data is BAD.
If the server has no known value to return, then it must return a reasonable default
value, such as a NUL string or a 0 numeric value.
Servers that do not support Substatus should return 0. Note that an old value may be
returned with the Quality set to BAD (0) and the Substatus set to 5. This is for
consistency with the Fieldbus Specification. This is the only case in which a client may
assume that a BAD value is still usable by the application.
The optional fields, which appear before the type character, control other aspects of the
formatting, as follows:
flags
These are optional characters that control justification of output and treatment of signs,
blanks, decimal points, and octal and hexadecimal prefixes. Refer to the flag characters
table in the Flag Directives section for a list and definitions. More than one flag can
appear in a format specification.
width
This is an optional number that specifies the minimum number of characters output.
Refer to the Width Specification section for details.
precision
This is an optional number that specifies the maximum number of characters output for
all or part of the output field, or the minimum number of digits output for integer values.
For details, refer to the table in the Precision Specification section.
h | w | l | L | ll | I | I32 | I64
These are optional prefixes to type that specify the size of the argument. Refer to the
prefixes table in Size and Distance Specification.
type
Flag Directives
The first optional field of the format specification is flags. A flag directive is a character
that justifies output and controls the output of signs, blanks, decimal points, and octal
and hexadecimal prefixes. More than one flag directive may appear in a format
specification.
– Left align the result within the given field width. Right align.
+ Prefix the output value with a sign (+ or –) if the Sign appears only for
output value is of a signed type. negative signed values
(–).
blank Prefix the output value with a blank if the output No blank appears.
(' ') value is signed and positive. The blank is ignored
if both the blank and + flags appear.
When used with the g or G format, the # flag Decimal point appears
forces the output value to contain a decimal only if digits follow it.
point in all cases and prevents the truncation of Trailing zeros are
trailing zeros. truncated.
Width Specification
The width specification is a nonnegative decimal integer that controls the minimum
number of characters output.
If the number of characters in the output value is less than the specified width, blanks
are added until the minimum width is reached. If the "–" (left alignment) flag is specified,
the blanks are appended to the right of the value; otherwise, they are appended to the
left. If width is prefixed with 0, zeros are added until the minimum width is reached.
The width specification never causes a value to be truncated. If the number of characters
in the output value is greater than the specified width, or if width is not specified, all
characters of the value are output, subject to the precision specification.
Precision Specification
The precision specification indicates the number of characters to be output, the number
of decimal places, or the number of significant digits. It is a nonnegative decimal integer,
preceded by a period (.). Refer to the table for details on how the precision specification
is used with each data type.
Unlike the width specification, the precision specification can cause either truncation of
the output value or rounding of a floating-point value. If precision is specified as 0 and
the value to be converted is 0, the result is no characters output, as shown below:
The type determines the interpretation of precision, and the default when precision is
omitted, as shown in the following table.
Value Output
+ infinity 1.#INFrandom-digits
– infinity –1.#INFrandom-digits
NAN digit.#NANrandom-digits
int32 l (lowercase L) d or i
uint32 l o, u, x, or X
int64 ll d, i, o, x, or X
int16 h d or i
uint16 h o, u, x, or X
int32 I32 d or i
uint32 I32 o, u, x, or X
uint64 I64 o, u, x, or X
int32 I d or i
uint32 I o, u, x, or X
double l or L f
sbyte h c or C
int16 l c or C
string l s or S
int16 w c
string w s
Thus to output single-byte or wide-characters with Format function, use format specifiers
as follows.
E double Identical to the e format except that E rather than e introduces the
exponent.
f double Signed value having the form [ – ]dddd.dddd, where dddd is one
or more decimal digits. The number of digits before the decimal
point depends on the magnitude of the number, and the number of
digits after the decimal point depends on the requested precision.
a double Signed hexadecimal double precision floating point value having the
form [−]0xh.hhhh p±ddd, where h.hhhh are the hex digits (using
lower case letters) of the mantissa, and ddd are three digits for the
exponent. The precision specifies the number of digits after the
point.
A double Signed hexadecimal double precision floating point value having the
form [−]0Xh.hhhh P±ddd, where h.hhhh are the hex digits (using
upper case letters) of the mantissa, and ddd are three digits for the
exponent. The precision specifies the number of digits after the
point.
In this appendix, we will discuss some of these programs. For additional sample
programs, refer to the Math & Logic Sample Configuration.mdb file.
if(index >= 0)
{
// Replace uppercase "ABC" with lowercase "abc"
s[index] = 'a';
s[index+1] = 'b';
s[index+2] = 'c';
}
return s;
double WarningLevel;
double TimeInHours;
var Temp;
return 0;
}
if(Input || LastInput)
{
// Convert 100-nanosecond ticks to hours
TimeInHours = TimeNow() / 36000000000.0;
CycleStartTime = TimeInHours;
SetFixedInterval(100);
}
if(IsQualityBAD(WarningLevel))
// Calculate warning level only once
WarningLevel = WarningPercent * MaintDueTime / 100.0;
return TotalTime;
}
if(GetFixedInterval())
// Disable timer execution
SetFixedInterval(0);
//
// Notes:
// To use a different input array, replace Item ID in the "ITEM
// InputArray" declaration.
//===============================================================
if(Hold)
{
// Turn the Holding output ON
Holding = true;
if(Holding)
// Turn the Holding output OFF
Holding = false;
Result = LowClamp;
dt.Year = Array[0];
dt.Month = Array[1];
//dt.DayOfWeek = Array[2]; // Ignore the DayOfWeek (must
be valid, but the value is irrelevant)
dt.Day = Array[3];
dt.Hour = Array[4];
dt.Minute = Array[5];
dt.Second = Array[6];
dt.Milliseconds = Array[7];
// Format the output string using the date & time properties
return Format("Your time: %d/%d/%d %d:%d:%d\n", dt.Month, dt.Day,
dt.Year, dt.Hour, dt.Minute, dt.Second);