Skip to main content
Version: Next

Understanding Scripts

What is the Scripts System?

The Scripts system in AI SCADA provides powerful automation capabilities through C# scripting and visual event-action configuration. It enables you to handle complex, customized requirements that standard SCADA functionality cannot address, such as cross-system integration, advanced data processing, and custom business logic.

When to Use Scripts?

The Scripts system is essential for:

  • Complex Integration: Connect with third-party systems using custom protocols or APIs
  • Advanced Data Processing: Implement sophisticated data transformation and calculation logic
  • Custom Business Logic: Handle unique production workflows and decision-making processes
  • Automated Responses: Trigger actions based on complex conditions and events
  • System Orchestration: Coordinate multiple components and subsystems

Core Components

1. Event-Action System

The event-action system is the foundation of automation in AI SCADA. It follows a simple but powerful pattern:

Event → Condition → Action

Event: Something happens (button click, alarm trigger, timer, etc.)
Condition: Optional logic to determine if actions should execute
Action: What to do when the event occurs (and conditions are met)

📷 [Screenshot: Event-Action configuration panel showing event types, conditions, and actions]

2. C# Script Editor

The built-in C# script editor provides:

  • Syntax Highlighting: Color-coded syntax for better readability
  • IntelliSense: Auto-completion for variables, functions, and system APIs
  • Real-time Debugging: Test scripts immediately and view execution results
  • System API Access: Built-in methods for variable operations, data queries, and more

📷 [Screenshot: C# Script Editor interface with code example]

3. System Commands

Pre-built system commands provide quick access to common operations:

  • Variable Operations: Read/write tag values, query historian data
  • Data Management: Query, insert, and clear data table records
  • System Control: Navigate views, show notifications, control components

Event-Action Architecture

The event-action system supports three levels of event scope:

Component Events

Events that occur on specific components:

  • Mouse Events: Click, double-click, right-click, hover, etc.
  • Lifecycle Events: Component load, component exit
  • Input Events: Value changes in input controls
  • Selection Events: Cell selection in tables

Configuration Entry: Select component → Event tab → Add Event

View Events

Events that occur at the view level:

  • View Load: Triggered when a view is loaded
  • View Exit: Triggered when leaving a view
  • View-level Tag Monitoring: Monitor tags while the view is active

Configuration Entry: Click canvas → Event tab → View tab → Add Event

Global Events

System-wide events that are always active:

  • System Startup: Triggered when the runtime starts
  • Global Tag Monitoring: Monitor tags across all views
  • Scheduled Tasks: Execute actions at specific times or intervals
  • Alarm Events: Respond to alarm triggers and recoveries
  • Barcode Scanning: Handle USB barcode scanner input
  • Broadcast Events: Receive and respond to broadcast messages

Configuration Entry: Click canvas → Event tab → Global Events tab → Add Event


Execution Flow

Basic Flow

Multiple Events

When multiple events are configured on the same component or view:

  1. Independent Execution: Each event executes independently
  2. Sequential Actions: Actions within an event execute in order (top to bottom)
  3. Parallel Events: If an event triggers again before completion, both executions run in parallel

⚠️ Caution: Be careful with recursive event triggers (e.g., Event A triggers Event B, which triggers Event A). This will cause an error and prevent execution.


Script Execution Context

Available APIs

Scripts have access to the following system APIs:

Variable Operations:

  • ReadTag(tagName): Read current tag value
  • WriteTag(tagName, value): Write value to tag
  • QueryHistorian(tagName, startTime, endTime): Query historian data

Data Management:

  • QueryData(tableName, whereClause): Query data table records
  • InsertData(tableName, record): Insert a new record
  • ClearData(tableName, whereClause): Delete records

System Control:

  • ShowNotification(message, type): Display system notification
  • NavigateToView(viewName): Navigate to a different view
  • SetComponentProperty(componentId, property, value): Control component properties

💡 Tip: Use IntelliSense (Ctrl+Space) in the script editor to discover available APIs and their parameters.

Event Parameters

Some events provide additional context through event parameters:

Event TypeParameterDescription
Input Changeevent.target.valueCurrent control value
Cell Selectionevent.cell.nameSelected cell field name
Cell Selectionevent.cell.valueSelected cell field value
Cell Selectionevent.row.cells[index].nameField name of cell in selected row
Cell Selectionevent.row.cells[index].valueField value of cell in selected row
Barcode Scanevent.codeScanned barcode content

Usage Example:

// In an Input Change event
var inputValue = event.target.value;
WriteTag("UserInput", inputValue);

Use Cases

1. Automated Quality Control

Scenario: When a product fails quality inspection, automatically:

  • Record the failure in a database
  • Send notification to quality team
  • Update production statistics
  • Trigger alarm

Implementation:

  • Event: Tag monitoring (quality result tag changes to "Failed")
  • Condition: Check if production line is active
  • Actions:
    1. Insert record to quality database
    2. Send notification
    3. Update statistics tag
    4. Trigger alarm

2. Shift Report Generation

Scenario: Automatically generate and export shift reports at the end of each shift.

Implementation:

  • Event: Scheduled task (every 8 hours)
  • Condition: Check if production data is available
  • Actions:
    1. Query production data for the shift
    2. Calculate KPIs (output, efficiency, downtime)
    3. Generate report view
    4. Export to PDF
    5. Send email notification

3. Equipment Interlock

Scenario: Prevent equipment from starting if safety conditions are not met.

Implementation:

  • Event: Button click (Start Equipment button)
  • Condition: Check safety tags (door closed, emergency stop released, etc.)
  • Actions:
    • If conditions met: Write "Start" command to equipment
    • If conditions not met: Show warning notification

4. Barcode-Driven Production

Scenario: Scan product barcode to automatically load recipe and start production.

Implementation:

  • Event: Barcode scan
  • Condition: Validate barcode format
  • Actions:
    1. Query product information from database
    2. Load corresponding recipe
    3. Update view with product details
    4. Enable start button

Best Practices

Event Configuration

Keep Events Focused:

  • Each event should handle a single responsibility
  • Avoid creating overly complex event chains
  • Use descriptive event names

Optimize Event Frequency:

  • For tag monitoring events, set appropriate trigger conditions (value change vs. periodic check)
  • Avoid monitoring tags that change very frequently unless necessary
  • Use scheduled tasks instead of continuous monitoring when possible

Condition Logic

Use Clear Expressions:

  • Write readable condition expressions
  • Add comments for complex logic
  • Test conditions thoroughly before deployment

Avoid Redundant Checks:

  • Combine related conditions using logical operators (AND, OR)
  • Use switch/case for multiple value comparisons
  • Leverage event parameters to reduce condition complexity

Action Design

Maintain Action Order:

  • Actions execute sequentially from top to bottom
  • Place critical actions first
  • Use "Wait" action when timing is important

Handle Errors Gracefully:

  • Anticipate potential failures (network issues, invalid data, etc.)
  • Provide user feedback for important operations
  • Log errors for troubleshooting

Script Development

Follow Coding Standards:

  • Use meaningful variable names
  • Add comments for complex logic
  • Keep scripts modular and reusable

Test Incrementally:

  • Test scripts in development environment first
  • Use debug output to verify logic
  • Test edge cases and error conditions

Performance Considerations:

  • Avoid long-running operations in scripts
  • Use asynchronous operations for network calls
  • Cache frequently accessed data

Next Steps

Now that you understand the Scripts system architecture, you can: