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:
- Independent Execution: Each event executes independently
- Sequential Actions: Actions within an event execute in order (top to bottom)
- 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 valueWriteTag(tagName, value): Write value to tagQueryHistorian(tagName, startTime, endTime): Query historian data
Data Management:
QueryData(tableName, whereClause): Query data table recordsInsertData(tableName, record): Insert a new recordClearData(tableName, whereClause): Delete records
System Control:
ShowNotification(message, type): Display system notificationNavigateToView(viewName): Navigate to a different viewSetComponentProperty(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 Type | Parameter | Description |
|---|---|---|
| Input Change | event.target.value | Current control value |
| Cell Selection | event.cell.name | Selected cell field name |
| Cell Selection | event.cell.value | Selected cell field value |
| Cell Selection | event.row.cells[index].name | Field name of cell in selected row |
| Cell Selection | event.row.cells[index].value | Field value of cell in selected row |
| Barcode Scan | event.code | Scanned 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:
- Insert record to quality database
- Send notification
- Update statistics tag
- 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:
- Query production data for the shift
- Calculate KPIs (output, efficiency, downtime)
- Generate report view
- Export to PDF
- 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:
- Query product information from database
- Load corresponding recipe
- Update view with product details
- 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:
- Creating Event-Actions: Learn how to configure events, conditions, and actions
- Scripts Reference: Explore all available event types, actions, and system commands
Related Topics
- Understanding Tags: Learn about tag monitoring and variable operations
- Understanding Alarms: Configure alarm-triggered events
- Understanding Data Management: Work with data tables in scripts