1. Overview

The Stream Built-in Functions provide a comprehensive set of utilities for Magic Box components to interact with the Stream platform. These functions are organized into logical categories and provide safe, scoped access to platform features.

All Stream functions are available through the Stream object in your Magic Box JavaScript code:

// Access Stream functions Stream.Tag.GetValueNum('Temperature.Value'); Stream.Navigation.GoToPage('Dashboard2'); Stream.UI.ShowNotification('Hello World!', 'info');

Function Availability: All Stream functions are automatically available in Magic Box components and page scripts. No additional imports or setup is required.

2. Tag Operations

Stream.Tag

Functions for reading and writing tag values, checking tag existence, and managing data connections.

GetValueNum(tagName)

Stream.Tag.GetValueNum(tagName) → number

Gets the numeric value of a tag. Returns 0 if the tag doesn't exist or has an invalid value.

Example:

const temperature = Stream.Tag.GetValueNum('Temperature.Value'); console.log('Current temperature:', temperature);

GetValueStr(tagName)

Stream.Tag.GetValueStr(tagName) → string

Gets the string value of a tag. Returns empty string if the tag doesn't exist.

Example:

const status = Stream.Tag.GetValueStr('System.Status'); if (status === 'Running') { console.log('System is operational'); }

SetValueNum(tagName, value)

Stream.Tag.SetValueNum(tagName, value) → boolean

Sets the numeric value of a tag. Returns true if successful, false otherwise.

Example:

const success = Stream.Tag.SetValueNum('Setpoint.Value', 75.5); if (success) { Stream.UI.ShowNotification('Setpoint updated', 'success'); }

SetValueStr(tagName, value)

Stream.Tag.SetValueStr(tagName, value) → boolean

Sets the string value of a tag. Returns true if successful, false otherwise.

Example:

const success = Stream.Tag.SetValueStr('Process.Command', 'START'); if (success) { console.log('Process start command sent'); }

Exists(tagName)

Stream.Tag.Exists(tagName) → boolean

Checks if a tag exists in the system. Returns true if the tag exists, false otherwise.

Example:

if (Stream.Tag.Exists('Temperature.Value')) { const temp = Stream.Tag.GetValueNum('Temperature.Value'); console.log('Temperature:', temp); } else { console.log('Temperature tag not found'); }

3. Navigation Functions

Stream.Navigation

Functions for navigating between dashboards, refreshing pages, and opening external URLs.

GoToPage(pageName)

Stream.Navigation.GoToPage(pageName) → boolean

Navigates to another dashboard page. Returns true if successful, false otherwise.

Example:

// Navigate to another dashboard Stream.Navigation.GoToPage('Production_Dashboard'); // Navigate with confirmation Stream.UI.ShowConfirm('Go to Production Dashboard?', function(result) { if (result) { Stream.Navigation.GoToPage('Production_Dashboard'); } });

RefreshPage()

Stream.Navigation.RefreshPage() → boolean

Refreshes the current dashboard page. Returns true if successful, false otherwise.

Example:

// Refresh page after data update Stream.Tag.SetValueStr('Data.Refresh', '1'); Stream.Navigation.RefreshPage();

OpenURL(url, windowName)

Stream.Navigation.OpenURL(url, windowName) → boolean

Opens a URL in a new window or tab. Returns true if successful, false otherwise.

Example:

// Open external documentation Stream.Navigation.OpenURL('https://docs.example.com', 'Documentation'); // Open with specific window name Stream.Navigation.OpenURL('https://reports.example.com/report.pdf', 'Report');

4. UI Functions

Stream.UI

Functions for displaying notifications, confirmations, prompts, and other user interface elements.

ShowNotification(message, type, duration)

Stream.UI.ShowNotification(message, type, duration) → boolean

Shows a notification message to the user. Returns true if successful, false otherwise.

Parameter

Type

Description

Options

message

string

Notification message text

Any text string

type

string

Notification type

'info', 'success', 'warning', 'error'

duration

number

Display duration in milliseconds

Default: 3000

Example:

// Show different types of notifications Stream.UI.ShowNotification('Process completed successfully', 'success', 5000); Stream.UI.ShowNotification('Warning: High temperature detected', 'warning'); Stream.UI.ShowNotification('Error: Connection failed', 'error', 10000);

ShowConfirm(message, callback)

Stream.UI.ShowConfirm(message, callback) → boolean

Shows a confirmation dialog to the user. Returns true if successful, false otherwise.

Example:

// Simple confirmation Stream.UI.ShowConfirm('Are you sure you want to stop the process?', function(result) { if (result) { Stream.Tag.SetValueStr('Process.Command', 'STOP'); Stream.UI.ShowNotification('Process stopped', 'info'); } }); // Confirmation with different actions Stream.UI.ShowConfirm('Save changes before leaving?', function(result) { if (result) { // Save changes Stream.Tag.SetValueStr('Data.Save', '1'); Stream.UI.ShowNotification('Changes saved', 'success'); } else { // Discard changes Stream.UI.ShowNotification('Changes discarded', 'warning'); } });

ShowPrompt(message, defaultValue, callback)

Stream.UI.ShowPrompt(message, defaultValue, callback) → boolean

Shows a prompt dialog for user input. Returns true if successful, false otherwise.

Example:

// Get user input Stream.UI.ShowPrompt('Enter new setpoint value:', '100', function(value) { if (value !== null) { const numValue = parseFloat(value); if (!isNaN(numValue)) { Stream.Tag.SetValueNum('Setpoint.Value', numValue); Stream.UI.ShowNotification('Setpoint updated to ' + numValue, 'success'); } else { Stream.UI.ShowNotification('Invalid number entered', 'error'); } } }); // Get string input Stream.UI.ShowPrompt('Enter process name:', 'Process_1', function(name) { if (name && name.trim() !== '') { Stream.Tag.SetValueStr('Process.Name', name.trim()); Stream.UI.ShowNotification('Process name updated', 'info'); } });

5. Utility Functions

Stream.Utils

Utility functions for formatting, timing, math operations, and other common tasks.

FormatNumber(value, decimals)

Stream.Utils.FormatNumber(value, decimals) → string

Formats a number with specified decimal places. Returns formatted string.

Example:

const temperature = Stream.Tag.GetValueNum('Temperature.Value'); const formatted = Stream.Utils.FormatNumber(temperature, 2); console.log('Temperature: ' + formatted + '°C'); // Format for display const pressure = Stream.Tag.GetValueNum('Pressure.Value'); const pressureStr = Stream.Utils.FormatNumber(pressure, 1) + ' bar';

GetTimestamp()

Stream.Utils.GetTimestamp() → number

Gets the current timestamp in milliseconds. Returns timestamp number.

Example:

const startTime = Stream.Utils.GetTimestamp(); // ... do some work ... const endTime = Stream.Utils.GetTimestamp(); const duration = endTime - startTime; console.log('Operation took ' + duration + 'ms');

FormatDate(date, format)

Stream.Utils.FormatDate(date, format) → string

Formats a date according to the specified format. Returns formatted date string.

Example:

const now = new Date(); const formatted = Stream.Utils.FormatDate(now, 'YYYY-MM-DD HH:mm:ss'); console.log('Current time: ' + formatted); // Format with different patterns const shortDate = Stream.Utils.FormatDate(now, 'MM/DD/YYYY'); const timeOnly = Stream.Utils.FormatDate(now, 'HH:mm:ss');

Delay(ms, callback)

Stream.Utils.Delay(ms, callback) → number

Executes a callback function after a specified delay. Returns timeout ID.

Example:

// Delay execution Stream.Utils.Delay(2000, function() { Stream.UI.ShowNotification('Delayed message', 'info'); }); // Chain delays Stream.Utils.Delay(1000, function() { console.log('First delay'); Stream.Utils.Delay(1000, function() { console.log('Second delay'); }); });

Repeat(ms, callback)

Stream.Utils.Repeat(ms, callback) → number

Repeats a callback function at specified intervals. Returns interval ID.

Example:

// Update display every 5 seconds const updateInterval = Stream.Utils.Repeat(5000, function() { const temp = Stream.Tag.GetValueNum('Temperature.Value'); $('#temperature-display').text(temp + '°C'); }); // Stop repeating after 1 minute Stream.Utils.Delay(60000, function() { Stream.Utils.StopRepeat(updateInterval); console.log('Stopped temperature updates'); });

StopRepeat(intervalId)

Stream.Utils.StopRepeat(intervalId) → void

Stops a repeating interval. Takes the interval ID returned by Repeat().

Example:

let updateInterval; // Start updates function startUpdates() { updateInterval = Stream.Utils.Repeat(1000, function() { // Update logic here }); } // Stop updates function stopUpdates() { if (updateInterval) { Stream.Utils.StopRepeat(updateInterval); updateInterval = null; } }

Math.Clamp(value, min, max)

Stream.Utils.Math.Clamp(value, min, max) → number

Clamps a value between minimum and maximum bounds. Returns clamped value.

Example:

const temperature = Stream.Tag.GetValueNum('Temperature.Value'); const clamped = Stream.Utils.Math.Clamp(temperature, 0, 100); console.log('Clamped temperature:', clamped); // Ensure setpoint is within valid range const setpoint = Stream.Tag.GetValueNum('Setpoint.Value'); const validSetpoint = Stream.Utils.Math.Clamp(setpoint, 10, 90); Stream.Tag.SetValueNum('Setpoint.Value', validSetpoint);

Math.Map(value, fromMin, fromMax, toMin, toMax)

Stream.Utils.Math.Map(value, fromMin, fromMax, toMin, toMax) → number

Maps a value from one range to another. Returns mapped value.

Example:

// Map temperature to percentage const temperature = Stream.Tag.GetValueNum('Temperature.Value'); const percentage = Stream.Utils.Math.Map(temperature, 0, 100, 0, 100); console.log('Temperature percentage:', percentage); // Map sensor value to display range const sensorValue = Stream.Tag.GetValueNum('Sensor.Raw'); const displayValue = Stream.Utils.Math.Map(sensorValue, 0, 1023, 0, 100);

6. System Information

Stream.System

Functions for getting system information, current user, and component context.

GetCurrentUser()

Stream.System.GetCurrentUser() → string

Gets the current logged-in user name. Returns user name string.

Example:

const currentUser = Stream.System.GetCurrentUser(); console.log('Current user:', currentUser); // Use in UI $('#user-info').text('Logged in as: ' + currentUser);

GetCurrentPage()

Stream.System.GetCurrentPage() → string

Gets the current dashboard page name. Returns page name string.

Example:

const currentPage = Stream.System.GetCurrentPage(); console.log('Current page:', currentPage); // Show page info Stream.UI.ShowNotification('Current page: ' + currentPage, 'info');

GetContainer()

Stream.System.GetContainer() → Element

Gets the Magic Box container element. Returns DOM element.

Example:

const container = Stream.System.GetContainer(); console.log('Container element:', container); // Use container for scoped operations const elements = container.querySelectorAll('.custom-element'); elements.forEach(function(el) { el.style.color = 'blue'; });

8. Best Practices

Performance Optimization

  • Use appropriate update intervals: Don't update too frequently (avoid intervals less than 100ms)
  • Clean up resources: Always stop intervals and timeouts when no longer needed
  • Cache DOM elements: Store frequently accessed DOM elements in variables
  • Minimize DOM manipulation: Batch DOM updates when possible

Error Handling

  • Check function return values: Always check if Stream functions return true/false
  • Validate user input: Check input values before using them
  • Handle tag errors: Check if tags exist before reading values
  • Use try-catch blocks: Wrap risky operations in try-catch blocks

Code Organization

  • Use meaningful variable names: Make your code self-documenting
  • Group related functions: Organize code into logical sections
  • Add comments: Explain complex logic and business rules
  • Test incrementally: Test each feature as you build it

Security Considerations

  • Validate all inputs: Never trust user input without validation
  • Use Stream functions: Prefer Stream functions over direct DOM manipulation
  • Avoid eval(): Never use eval() with user input
  • Sanitize data: Clean any data before displaying it

Remember: The Magic Box component provides a powerful but controlled environment. Always use the provided Stream functions for platform integration and follow security best practices to ensure safe operation.