Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Create Script Expressions, Tasks and Classes.

TutorialsScripts| Tutorial | How-to Guide | Reference


This 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:

Table of Contents
maxLevel2
minLevel2
indent10px
excludeTutorial
stylenone



1. Create Tag Expressions

  1. Navigate to Scripts → Expressions
  2. Add temperature conversion:
FieldValue
ObjectTag.Tank1_TempF (create as Double)
ExpressionTag.Tank1_Temp * 1.8 + 32
ExecutionOnChange
DomainServer

Add status logic:

FieldValue
ObjectTag.System_Status (create as String)
ExpressionTIF(Tag.Tank1_Status = 2, "Running", "Stopped")
ExecutionOnChange
DomainServer

2.

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

  1. Navigate to Unified Namespace → Tags
  2. 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
Step 2:

Create Script Task

  1. Go to Scripts → Tasks
  2. Add new task:

Production Counter:

csharp

  1. Click plus icon, name: ShiftCounter
  2. Choose language CSharp
  3. Press OK
  4. Use Server.DateTimeInfo.Hour as Trigger
  5. Double-click to open Code Editor
  6. Enter code (no method wrapper):


// 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

  • Step 3:

    3. Build Script Class

    1. Navigate to Scripts → Classes
    2. Create class:
    TankCalculations
    1. TankCalculations
    2. 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

    1. Go to Scripts → Expressions

    In tag expressions:

    csharp

    @Script
    1. Create volume calculation:
    FieldValue
    ObjectTag.Tank1_Volume
    ExpressionScript.Class.TankCalculations.CalculateVolume(
    @Tag
    Tag.Tank1_Level,
    10.5)

    Step 5: Python Integration

    1. Scripts → Settings
    2. Enable Python
    3. 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

    // On tag change event
    public void OnTemperatureChange()
    {
        if (@Tag.Tank1_Temperature > @Tag.HighLimit)
        {
            @Tag.Alarm_Active = true;
            @Script.Class.Notifications.SendEmail(
                "operator@company.com",
                "High Temperature Alert",
                $"Tank 1: {@Tag.Tank1_Temperature}°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 
            (Timestamp, Product, Quantity, Operator) 
            VALUES 
            (@time, @product, @qty, @user)";
        
        @Dataset.DB.SqlExecuteCommand(query,
            "@time", DateTime.Now,
            "@product", @Tag.Current_Product,
            "@qty", @Tag.Units_Produced,
            "@user", @Client.UserName
        );
    }

    Step 8: Test Scripts

    1. Start Runtime with debugger
    2. Set breakpoints in scripts
    3. Monitor script execution:
      • 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

  • [SQL Database Query] - Database integration
  • [Reports Module] - Automated reporting
  • [Create Dashboards] - Display calculations
    ExecutionOnChange

    Note: No @ symbol needed in expressions



    Test and Debug

    1. Build verification:
      • Check green checkmark in BuildStatus
      • Review BuildErrors if red X
    2. Runtime monitoring:
      • Go to Scripts → Scripts Monitor
      • Check Counter
      • Review LastRun
    3. Debug with breakpoints:

    Excerpt Include
    Scripts Module
    Scripts Module
    nopaneltrue


    In this section...

    Page Tree
    root@parent
    spaces93DRAF