Skip to main content

Script Management

Script management is used to maintain runtime scripts for gateways. Scripts can be used for variable data conversion, memory variable calculation, data forwarding templates, dynamic SQL (custom entry statements or table structures), MQTT RPC (MQTT reverse write or query requests), and other scenarios. After saving the script, it must be compiled successfully for related functions to use the latest content.

Convert a raw value to engineering units​

For a numeric source that returns 1234, this example produces 123.4 without changing the source register layout.

  1. Open Development Configuration → Script Management → Local Scripts, add ScaleByTen, and select Data Conversion.
  2. Enter the following method body; do not wrap it in another class or method.
// 将设备的整数原始值换算为带一位小数的工程值。
return Math.Round(Convert.ToDouble(raw) * 0.1, 1);
  1. Click Compile and Save. Confirm compilation, loading, and saving have all succeeded.

ScaleByTen body and successful compilation

  1. Edit the collection variable, select ScaleByTen as its Read Expression, and save.
  2. Wait for the next sample. Raw value should remain 1234 and current value should become 123.4. Keep the source data type appropriate for its register; displaying a decimal does not make an integer register a Float.

Raw value 1234 and converted current value 123.4

Compilation does not bind the script to a variable. A read expression changes its final runtime value, which is then used by memory calculations, alarms, rules, and forwarding. Raw value retains the device reading. This read conversion does not write to the field device or supply reverse write conversion. To remove it, clear the variable's read-expression selection, save, and verify the next sample. For configurable scale and offset, use the parameterized example.

Create and edit scripts​

First, look at terminology​

terminologyOn-site understanding
scriptInternal reusable calculation or conversion logic within the gateway is used to process variable values, generate uploaded content, or handle external requests.
CompileValidates and builds the code. Loading, consumer binding, and actual execution must also succeed before the new behavior is verified.
Data ConversionConvert the original equipment values into engineering values required on site, such as scale conversion, unit conversion, and status text conversion.
Memory variable scriptsScripts for calculating internal variables of the gateway, which do not read directly from the PLC but read existing variables or internal states.
Dynamic models / templatesGenerate uploaded content in formats specified by external systems, such as custom JSON fields, device fields, or alarm fields.
Dynamic SQLCustom statements or table structures written into the database, commonly used in scenarios where fixed-width tables or special field naming are required in projects.
MQTT RPCreceives write, query, or control requests from external systems via MQTT, and is parsed and returned by scripts.
Complete codeAdvanced extension methods. You need to understand C# code and its operational impact; for regular field configurations, it's not recommended to start here.

Page Entry​

After logging into TGateway Web, click the "Development Configuration → Script Management" menu on the left.

Script Management Page

Page Structure​

AreaDescription
Local ScriptsMaintains scripts saved at the current runtime, supporting addition, editing, compilation, deletion, and batch operations.
Loaded scriptView scripts that are already accessible to the gateway, displaying information such as name, class, type, and data type in read-only.
Name SearchFilter the list by script name.
Category FilteringFiltering by script category, local categories come from saved scripts.
Type FilteringFiltering by script type, such as data transformation, memory variable, MQTT RPC.
Tool buttonsOrder: Add, batch compile, batch delete, refresh; For the batch button, you need to check the script first.

List Field​

FieldDescription
NameThe script's unique name in the system.
ClassificationUsed to organize scripts by business, device, or purpose, which can be empty.
TypeScript expression type, which determines the editor template, available inputs, and subsequent references.
Update TimeThe last time the library was saved or compiled and written.
OperationsEdit, compile, or delete the current script.

Create a new script​

Click the 'Add Script' button in the top right corner of the list to open the "New Script" popup.

New Script Dialog

Configuration ItemsDescription
Script NameRequired. It is recommended to use English, numbers, and underscores. After saving names, they will be referenced by variables, rules, data forwarding, or RPC configurations, so frequent modifications are not recommended.
Script TypeRequired. After selecting, a corresponding writing prompt will appear at the bottom of the pop-up window.
ClassificationOptional. You can select an existing category or directly enter a new category.
Descriptionoptional. Record script usage, citation locations, and maintenance precautions.
Type DescriptionRead-only prompt explaining the purpose and writing requirements of the current script type.

After clicking "OK," the system will create a script and automatically enter the script editor.

Script Type​

TypeApplicable Scenarios
Data ConversionPerform unit conversion, formatting, range mapping, or state transformation on the original values of collected variables.
Memory VariablesCompute memory variables, which can be read from other variables to generate derived results.
Dynamic Model - Variable DataConverts variable data into custom upload objects.
Dynamic Model - Device DataConverts device status into a custom upload object.
Dynamic Model - Alarm VariableTransforms alarm data into a custom upload object.
Dynamic Model - Plugin EventConverts plugin event into a custom upload object.
Dynamic SQL-*Custom relational storage by entity type; history alarm storage uses the alarm-data type.
Time-Series History ScriptCustom QuestDB, TDengine, or IoTDB history schema and storage, mutually exclusive with custom SQL.
MQTT RPCprocesses MQTT RPC messages, suitable for write scenarios where message parsing and organizing responses as agreed on the site are required.
Complete CodeWrite complete C# code suitable for advanced extensions. Before use, confirm the compilation requirements and operational impact.

Script Editor​

The Script Editor includes the top operation bar, code editing area, and bottom information panel.

Script Editor Page

AreaDescription
Back ButtonReturn to Script List. Unsaved content should be compiled and saved first.
Script Name TagDisplays the current script name, classification, and script type.
Compile and SaveTop-right action. Compile and load the result, then save the current source and parameters.
Code editingMaintains C# code, supporting syntax highlighting, undo, redo, and comment switching.
Bottom panelcontains tabs for "Compilation," "Node Information," and "Input Parameters."

Bottom tab​

tabDescription
Compilation logDisplays compilation process, errors, warnings, and success information. Clicking on errors or warnings can locate the corresponding code location.
Node informationMaintenance script names and categories. After modification, compilation and saving are required for persistence.
Input parametersOnly the types "Data Transformation" and "Memory Variable" are displayed. Used to define configurable parameters.

Enter parameter field​

fieldDescription
Parameter nameParameter identifier, read by this name in the script.
Data typeParameter value type. For numbers, select integer or decimal type; for switches, select boolean type; for text, select string; for time, select date and time; It should match the actual input values in the script.
Initial valueC# initialization expression in the script definition. Consumer arguments are separate JSON values.
DescriptionParameter usage description for easier subsequent maintenance.

Definition defaults and binding arguments​

TypeDefinition defaultConsumer argument
Int32/Int64/ByteC# numeric expression within range.JSON number within range.
Float/Double/DecimalC# expression, for example Decimal 19.95m.JSON number 19.95, without a C# suffix.
Booleantrue or false.JSON Boolean.
StringC# string such as "Alpha".Quoted JSON string.
DateTimeExplicit-zone C# date expression.ISO JSON string such as "2026-10-11T00:00:00Z".
ObjectAppropriate C# initializer.JSON object, array, or scalar consumed by the script.

Explicit arguments override defaults. Empty text is not JSON null or a default argument. For a calculated sum of 40, Scale 0.5 should yield 20, then 2 should yield 80. Changing only argument values needs no recompilation; verify saving and the next execution. Renaming/adding/removing parameters requires code changes and compilation, then clear/reselect the binding to populate current keys.

Completion, documentation, and diagnostics​

Undo, redo, formatting, and Compile and Save are grouped in the top row. Roslyn connection settings are hidden by default; expand Roslyn Service to view them. The default address is https://roslyn.thingsgateway.cn, and a self-hosted Studio can also be used.

Type GlobalData. or press Ctrl+Space for gateway members. Members declared in the current user source also participate in completion. Hover over GlobalData.GetEnableVariables() to read its XML summary, remarks, and return documentation. See Code Completion, Documentation, and Diagnostics for connections, user-method comments, and signature help.

GlobalData method documentation and return description

Verify a revised script​

Compilation, registration, consumer binding, and execution are separate steps. A consumer can retain an earlier script instance after same-name compilation. Save/reload the referencing variable or target and test two inputs that distinguish the formulas. Check every consumer in the maintenance scope. Compilable code can still fail on runtime conversion or input errors. AOT runtimes cannot dynamically load these scripts; use a runtime package supporting dynamic loading.

Compile and maintain​

An existing script keeps its saved type during compilation. To use another type, create a script with the required type and update its consumers.

Compilation Log​

After clicking "Compile and Save" at the top, the "Compilation Log" tab at the bottom will display the complete process.

Script Editor Compiles Logs

Log EntriesDescription
Start Compiling ScriptsMark the start of this compilation and display the script name.
Script TypeDisplays the current expression type, such as "Data Transformation".
Compilation successfulmeans the script has been compiled.
Compilation OutputDisplays compiled output information for on-site troubleshooting of loading issues.
Error/Warning StatisticsThe number of errors and warnings is displayed on the right side of the bottom panel.

If compilation fails, the red error should be handled first; Warnings do not necessarily prevent compilation, but it is recommended to address them before going live.

Compile and Save validates and loads the compiled result before saving the current source and parameters. Failed compilation or loading preserves the previous published files and registrations; the failed source does not replace the saved source through this action. Keep the draft and correct the diagnostics. If publication succeeds but saving fails, keep the editor content, resolve the storage error, resubmit, and reopen to check saved source. Runtime publication and database saving have separate outcomes.

Common Operations​

OperationsSteps
Edit ScriptClick "Edit" in the list, enter the editor, modify code or parameters, then click "Compile and Save".
Single CompilationClick "Compile" in the list, which is suitable for quickly verifying whether existing scripts can still be compiled.
Batch CompilationCheck multiple scripts and click the Batch Compilation button on the toolbar. Commonly used for unified verification after upgrades.
Delete the scriptClick "Delete" and confirm. Before deletion, confirm that the script is no longer referenced in variables, data forwarding, MQTT RPC, or rules.
View Loaded ScriptsSwitch to the "Loaded Scripts" tab to confirm the currently available expressions at runtime.

Use Note:​

ScenariosRecommended
Script NamingUse stable naming and avoid frequent renaming. Variables, rules, data forwarding, and RPC configurations may be referenced by script name.
Production modificationBefore modifying the production environment script, export the configuration or record the original script content.
Compilation failureCheck the first error in the compilation log; usually, subsequent errors are chain results.
The loaded list is emptyFirst confirm that the script has been successfully compiled, then refresh the "Loaded Scripts" tab.
AOT runtimeDoes not support dynamically loading these scripts. Use a Runtime package that supports dynamic code loading for Web script compilation and use.