Scripts & Data Enrichment (Tutorial) teaches you to:
- Create calculated tags using expressions
- Build reusable logic with Script Classes
- Automate processes with Script Tasks
- Handle events and data transformations
- Monitor script performance and debugging
Prerequisites:
- Complete Solution (Tutorial) - uses TankFarm tags
- Basic understanding of C# or VB.NET syntax
In this page:
Table of Contents maxLevel 2 minLevel 2 indent 10px exclude Steps style none
Create Tag Expressions
- Navigate to Scripts → Expressions
- Add temperature conversion:
Field | Value |
---|---|
Object | Tag.Tank1_TempF (create as Double) |
Expression | Tag.Tank1_Temp * 1.8 + 32 |
Execution | OnChange |
Domain | Server |
Add status logic:
Field | Value |
---|---|
Object | Tag.System_Status (create as String) |
Expression | TIF(Tag.Tank1_Status = 2, "Running", "Stopped") |
Execution | OnChange |
Domain | Server |
Add calculations, business logic, and data transformations using FrameworX's scripting capabilities. Create expressions, tasks, and classes for advanced functionality.
What You'll Learn
- Write tag expressions
- Create script tasks
- Build script classes
- Use multiple languages (C#, VB.NET, Python)
Prerequisites
- Basic programming knowledge
- Tags configured in UNS
Step 1: Simple Tag Expressions
- Navigate to Unified Namespace → Tags
- Add calculated tag:
Temperature Conversion:
- Name:
Tank1_TempF
- Expression:
@Tag.Tank1_TempC * 9/5 + 32
- Type: Double
- Description: Temperature in Fahrenheit
Conditional Logic:
- Name:
System_Status
- Expression:
@Tag.Motor1_Running AND @Tag.Pump1_Running ? "Running" : "Stopped"
- Type: Text
Create Script Task
- Go to Scripts → Tasks
- Add new task:
- Click plus icon, name:
ShiftCounter
Use Server.DateTimeInfo.Hour as Trigger
- Double-click to open Code Editor
- Enter code (no method wrapper):
csharp
// Reset counter at shift change
DateTimeint nowhour = DateTime@Server.DateTimeInfo.NowHour;
if (now.Hourhour == 6 || now.Hourhour == 14 || now.Hourhour == 22)
{
if (@Tag.ShiftReset == false)
{
@Tag.Units_Previous = @Tag.Units_Produced;
@Tag.Units_Produced = 0;
@Tag.ShiftReset = true;
}
}
else
{
@Tag.ShiftReset = false;
}
Configure:
- Trigger: Timer
- Rate: 60000ms (1 minute)
- Domain: Server
Build Script Class
- Navigate to Scripts → Classes
- Create class:
-
TankCalculations
- Enter methods (no class declaration):
csharp
public class TankCalculations
{
public static double CalculateVolume(double level, double diameter)
{
double radius = diameter / 2;
return Math.PI * radius * radius * level;
}
public static double FlowRateCalculateFlowRate(double volumeStart, double volumeEnd, int minutes)
{
{
if (minutes == 0) return 0;
return (volumeEnd - volumeStart) / minutes;
}
public static string GetAlarmTextGetStatusText(double value, double limit)
{
if (value > limit)
return $"High: {value:F2} (Limit: {limit:F2})";
else
return "Normal";
}
}
Step 4: Use Class in Expression
- Go to Scripts → Expressions
In tag expressions:
csharp
@Script- Create volume calculation:
Field | Value |
---|---|
Object | Tag.Tank1_Volume |
Expression | Script.Class.TankCalculations.CalculateVolume( |
Tag.Tank1_Level, |
10.5) |
Step 5: Python Integration
- Scripts → Settings
- Enable Python
- Create Python script:
python
import numpy as np
from datetime import datetime
def calculate_statistics(values):
"""Calculate statistical values"""
arr = np.array(values)
return {
'mean': np.mean(arr),
'std': np.std(arr),
'max': np.max(arr),
'min': np.min(arr)
}
def predict_value(history, hours_ahead):
"""Simple linear prediction"""
# Implementation here
return predicted_value
# Set tag values
tags['Stats_Mean'] = calculate_statistics(history)['mean']
Step 6: Event-Driven Scripts
Create event handler:
csharp
Execution | OnChange |
Note: No @ symbol needed in expressions
Event-Driven Task
- Create task:
TemperatureMonitor
- Configure trigger on tag change:
csharp
// On tag change event
public void OnTemperatureChange()
{
if (@Tag.Tank1_TemperatureTemp > @Tag.HighLimit)
{
@Tag.Alarm_Active = true;
@Script.Class.Notifications.SendEmail(
"operator@company.com",
"High Temperature Alert",
$"Tank 1@Tag.Alarm_Message = $"High Temperature: {@Tag.Tank1_TemperatureTemp:F1}°C"
);
}
}
Bind to tag:
- Tag: Tank1_Temperature
- Event: OnValueChange
- Script: OnTemperatureChange
Step 7: Database Operations
Script for database logging:
csharp
public void LogProduction()
{
string query = @"
INSERT INTO ProductionLog@Tag.Alarm_Time = DateTime.Now;
// Log (Timestamp, Product, Quantity, Operator) to historian
VALUES
(@time, @product, @qty, @user)";
@Dataset.DB.SqlExecuteCommand(query,@Script.Class.ServerMain.LogEvent(
"@time", DateTime.Now,
"@product", @Tag.Current_Product,
Temperature Alarm",
"@qty", @Tag.UnitsTank1_Produced,Temp
"@user", @Client.UserName
);
}
Step 8: Test Scripts
Configure:
- Trigger: Tag.Tank1_Temp
- Domain: Server
Add External References
- Go to Scripts → References
- Add DLL if using external libraries
- Open Code Editor
- Click Namespace Declarations
- Add required namespaces
Test and Debug
- Build verification:
- Check green checkmark in BuildStatus
- Review BuildErrors if red X
- Runtime monitoring:
- Start Runtime with debugger
- Set breakpoints in scripts
- Monitor script execution:
- Go to
- Scripts → Monitor
- Check execution time
- View error messages
Best Practices
- Handle exceptions properly
- Log important events
- Optimize for performance
- Comment complex logic
- Test edge cases
- Use meaningful variable names
Next Steps
- ExecutionCount
- Review LastCPUTime
- Debug with breakpoints:
- Enable debug in Runtime → Build and Publish
- Set breakpoints in Code Editor
- Attach debugger during runtime
Step-by-step guide to add calculations, automation, and data enrichment to your TankFarm solution using Scripts module capabilities.
In this section...
Page Tree | ||||
---|---|---|---|---|
|