API
    • 14 Jan 2022
    • 25 Minutes to read
    • PDF

    API

    • PDF

    Article summary

    Each script has access to the $ object containing several other objects and functions to interface with

    N3uron’s API. The following can be accessed using $.NAME:

    sprintf(format, arg1, arg2, …)

    The $.paths object contains different paths for N3uron, irrespective of where N3uron is installed or the operating system. The $.paths object has two nested objects, one labelled global and one labelled local. These refer both to the paths used by N3uron itself, and those used by this specific instance of Scripting. For instance, if using the default windows installation folder and the current Scripting instance named as “Scripting”, the $.paths object would be formatted as follows:

    $.sprintf("Numbers are: %d and %i", 10, 15.7) 
    //Numbers are: 10 and 15 
     
    $.sprintf("String is: %s", "Hello world!"); 
    //String is: Hello world! 
     
    $.sprintf("The binary representation of 5 is: %b", 5); 
    // The binary representation of 5 is: 101 
     
    $.sprintf("The ASCII character with decimal value 48 is %c", 48); 
    // The ASCII character with decimal value 48 is 0 
     
    $.sprintf("1000 in scientific notation is: %e", 1000); 
    1000 in scientific notation is: 1e3 
     
    $.sprintf("1234 in scientific notation and 2 decimals is: %.2e", 1234); 
    //1234 in scientific notation and 2 decimals is: 1.23e3  
    $.sprintf("12.34 in floating point notation is: %f", 12.34) 
    //12.34 in floating point notation is: 12.34 
     
    $.sprintf("12.3456 in fixed point notation is: %.3g", 12.3456); 
    //12.3456 in fixed point notation is: 12.3 
     
    $.sprintf("12 in octal is: %o", 12); 
    //12 in octal is: 14 
     
    $.sprintf("-10 in unsigned integer format is: %u", -10) 
    //-10 in unsigned integer format is: 4294967286 
     
    $.sprintf("30 in hexadecimal is: %x", 30); 
    //10 in hexadecimal is: 1e 
     
    $.sprintf("30 in uppercase hexadecimal is: %X", 30); 
    //30 in uppercase hexadecimal is: 1E 
     var buf = new Buffer(["Hello world! "]); 
    $.sprintf("The buffer is: %r", buf); 
    //The buffer is: <48 65 6c 6c 6f 20 77 6f 72 6c 64 21>; 
    


    $.global

    The $.global object is an object shared with all the tasks in the module. This can be used to share data between scripts from different tasks.   

    $.local

    The $.local object is shared by all the scripts within the same task, but will not be shared between tasks. An example use for this object is for initializing a resource in a Start-up action, and then using it in a Periodic action.

    $.lib

    The $.lib object is where all static libraries are stored. These libraries can be used directly by using $.lib.libraryName. The Libraries section of this manual provides more details about the use of libraries.

    $.paths

    The $.paths object contains different paths for N3uron, irrespective of where N3uron is installed or the operating system. The $.paths object has two nested objects, one labelled global and one labelled local. These refer both to the paths used by N3uron itself, and those used by this specific instance of Scripting. For instance, if using the default windows installation folder and the current Scripting instance named as “Scripting”, the $.paths object would be formatted as follows:

    {  base: C:\Program Files (x86)\N3uron,
      global: { 
      	bin: C:\Program Files (x86)\N3uron\bin,
       	config: C:\Program Files (x86)\N3uron\config,
       	log: C:\Program Files (x86)\N3uron\log,
       	data: C:\Program Files (x86)\N3uron\data,
       	licenses: C:\Program Files (x86)\N3uron\licenses 
     }, 
     local: { 
      	bin: C:\Program Files (x86)\N3uron\bin\modules\Scripting,
       	config: C:\Program Files (x86)\N3uron\config\Scripting,
       	log: C:\Program Files (x86)\N3uron\log\Scripting,
       	data: C:\Program Files (x86)\N3uron\data\Scripting 
     } 
    } 
    


    $.exit([err])

    The $.exit function is used to indicate that the current execution has finished. This function needs to be called every time the script execution is over, otherwise the script will always be marked as running, even if the actual code execution has finished. The $.exit function can take one parameter, which can be an Error object or a String to signify that the execution has ended with an error. When calling the $.exit function, the addition of a return clause is recommended in order to guarantee that the $.exit function is the last function to be called.

    $.event

    The $.event object contains information about what triggered the current execution. This object will vary depending on which type of action launched the script. See below list of the $. event objects for all actions:

    • Start-up

    $.event.startTime: Time the module was started, in UNIX epoch with milliseconds.

    • Shutdown. 

    $.event.stopTime: Time the module was stopped, in UNIX epoch with milliseconds.

    • Periodic. 

    $.event.time: Time when the periodic action was triggered, in UNIX epoch with milliseconds. 

    • Tag change

    $.event.tag: The full path of the tag that changed.

    $.event.oldValue: Old value of the tag before the change. Should be an object containing value (value type depends on the tag type), quality (quality - a number representing the OPC quality) and timestamp (ts - value in UNIX Epoch milliseconds).

    $.event.newValue: New value as an object containing value, quality and timestamp.

    $.event.changes: An object containing Boolean values for each tag’s properties, representing which properties have changed in the update. True means that the property has changed, false means it remains the same as the old value.

    • Condition 

    $.event.tag: The full path of the tag that triggered the condition. 

    $.event.value: Object containing the value that triggered the condition, or the current value if the condition type is whileTrue or whileFalse. The object contains value, quality and timestamp. 

    The following code block contains examples of all the different $.event objects:

    //Startup at 2018-01-15 14:00:00 
    $.event.startTime -> 1516021200000 
     
    //Shutdown at 2018-01-15 15:00:00 $.event.stopTime -> 1516024800000 
     
    //Periodic trigger at 2018-01-15 14:10:00 
    $.event.time -> 1516021800000 
     
    //Tag /Plant1/ActivePower changes from 1000 to 1020 
    $.event.tag -> "/Plant1/ActivePower"  
    $.event.oldValue -> {value:1000, quality: 192, ts: 1516021800000} 
    $.event.newValue -> {value:1020, quality: 192, ts: 1516023000000} 
    $.event.changes -> {value:true, quality: false, ts: true}  
    //Tag /Plant1/Alarm changes from 0 to 1, triggering a condition 
    $.event.tag -> "/Plant1/Alarm" 
    $.event.value -> {value:1, quality:192, ts: 1516023000000} 
    


    $.config

    The $.config object contains static information about the action that triggered the script. This object contains the following data: 

    $.config.type: An enumeration that identifies the action that triggered this script. The values for this enumeration are the following:

    • Start-up: 0
    • Shutdown: 1
    • Periodic: 2
    • Tag change: 3
    • Condition: 4

    $.logger(message, …arguments)

    The $.logger object is used to log messages to disk, and can be used for both debugging and informative purposes. The log file can be found in N3uron/log/ScriptingInstance/. It is shared by both the internal module code and any messages written by users, which can be easily distinguished by the “User” string appended to them. The logger has five different logging levels:

    • $.logger.error()
    • $.logger.warn()
    • $.logger.info()
    • $.logger.debug()
    • $.logger.trace()

    Each logging function has two arguments:

    • (String) message: Format string using printf formatting (using the “%” character).
    • (Any) arguments: Arguments that will replace placeholders in the format string.

    $.api

    The $.api object is used to interface with N3uron, and provides access to several elements, such as tags, links, host machine stats, etc. Each of these functions is hosted in a different namespace. For example, functions that affect tags are hosted in the tag namespace, functions that provide the status of a host machine are hosted in the system subspace and so on:

    The different subspaces and their functions are as follows:

    $.api.system  

    $.api.system.status(callback(err, result))

    This function queries the status of the host system, and returns an object with information about the current hardware, the host name, uptime, etc. It requires a single parameter:

    • (Function) callback (err, result): The callback function will be called when the asynchronous operation has finished. It has two parameters:
      • (String) err: An error string if the operation fails, or null if it has completed without errors.
      • (Object) result: The result of the function. This object has the following structure:
    $.api.system.status(function(err, result));
    {
    	"n3": {
    		"pid": 3440,
    		"up": 32808799,
    		"versions": ["1.18.0-180806.1233", "1.30.0-180917.1720"],
    		"node": "n3-dev",
    		"tags": {
    			"local": 181,
    			"remote": 0
    		}
    	},
    	"sys": {
    		"hostname": "N3uron-Dev",
    		"ts": 1542286072492,
    		"up": 52247758,
    		"cpu": ["Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz", 2592, 4],
    		"usage": {
    			"cpu": [1632, 10000],
    			"ram": [2034872320, 4294434816],
    			"disk": [110533468160, 390679490560]
    		}
    	}
    }
    


    $.api.link

    $.api.link.get(callback (err, result))

    This function retrieves information about the link status of the current node, as well as any links it has established. The function has a single parameter:

    • (Function) callback (err, result): This function will be called when the asynchronous request finishes. It has two parameters: 
      • (String) err: Error string if the operation fails, or null if it succeeds.
      • (Object) result: Resulting object with information about the current node and any established links. The following is an example of this object:
    $.api.link.get(function(err, result));
    {
    	"ts": "2018-11-15T14:36:16.105Z",
    	"nodeInfo": {
    		"name": " n3-dev"
    	},
    	"sfPauseRequests": {
    		"bootstrap": false,
    		"WebUI": false,
    		"Historian": false,
    		"Modbus Client": false,
    		"Scripting": false,
    	},
    	"sfPaused": false,
    	"links": {
    		"Remote": {
    			"name": "Remote",
    			"type": "out",
    			"online": false,
    			"subscription": null,
    			"buffer": {
    				"pendig": false,
    				"folder": "D:\n3uron\data\bootstrap\							links\Remote\sf",
    				"capacity": 10000,
    				"packetSize": 10000,
    				"count": 0
    			},
    			"sfPauseRequests": {
    				"Scripting": true
    			},
    			"sfPaused": true
    		}
    	}
    }


    $.api.link.sfPause(link, paused) 

    This function is used to pause the store and forward mechanisms for a specific link. In this way, no more tag events reach this node until the current ones have been processed. The arguments are: 

    • (String) link: The name of the link whose S&F mechanism will be paused
    • (Boolean) paused: True pauses the S&F mechanism, false resumes the S&F.

    $.api.tag 

    $.api.tag.browse(path, options, callback(err, result)) 

    This function returns all the tags and tag groups present in the given path. It runs with three arguments: 

    • (String) path: Selects which tag group to browse. To browse the root path, this argument should be ‘/’.  
    • (Object) options:This can be any of the following. To use default values, this setting can be set as an empty object ({}):
      • (Boolean) hideTags: If true, exclude tags from the result. Default: false
      • (Boolean) hideGroups; If true, exclude groups from the result. Default: false
      • (Boolean) recurrent: If true, the result also contains tags inside other tag groups in the path. Default: true
      • (Boolean) flat: If true, returns a flat array instead of an object tree. Default: false
    • (Function) callback(err, res): This function is called after the asynchronous browse completes. It has two arguments:
      • (String) err: Error message if the browse operation fails, or null if the operation succeeded.
      • (Array | Object)result: An array or an object containing the tags and groups in the current path, depending on the options.
    $.api.tag.browse("/Scripting/", {recurrent:true, flat:true }, function(err, res));
    
    ["Scripting/Tag1",
    "Scripting/Input/Tag1",
    "Scripting/Input1/Tag2",
    "Scripting/Output1/Tag2", 
    "Scripting/Output1/Tag2"]
    
    $.api.tag.browse("/Scripting/", {recurrent:true}, function(err, res));
    
    "Scripting": {
    "tags": ["Tag1"],
    	"groups": {
    	"Input": {
    		"tags": ["Tag1", "Tag2"]
    		},	
    		"Output": {
    			"tags": ["Tag1", "Tag2"]
    		}
    	}
    }
    


    $.api.tag.read(path, options, callback(err, result))

    This function reads the value of one or more tags in the specified path. It runs with 3 arguments:

    • (String) path: The path of the tag to be read, or a group. If it’s the latter, the path has to end with ‘*’.  
    • (Object) options:This can be any of the following, or an empty object ({}) to set the values to default:
      • (Boolean) recurrent: If true, it will read the values of all the tags nested inside other tag groups in the specified path. Default: false
      • (String) filter: Regular expression used to filter which tags to read from the current path. This string can be any regular expression, but it can’t have any regular expression flags.
    • (Function) callback (err, result):This callback will be called after the asynchronous request finishes. It has two arguments:
      • (String) err: Error message if the operation fails, or null if it is successful.
      • (Object) result: An object containing the result from the reading. The result contains value, quality and timestamp.
    $.api.tag.read("/Scripting/Tag1",{}, function(err, result));
    
    {
        "status": {
            "value": 1,
            "ts": "2018-11-15T15:45:49.487Z"
        },
    //data contains the current value, quality and timestamp
        "data": {
            "value":20,
             "quality": 192,
            "ts": "2018-11-15T15:45:49.487Z"
        }
    }
    $.api.tag.read("/Scripting/*",{recurrent:true, filter: "(?:In|Out)put"}, function(err, result)); 
    {
    "tags": {
    //Tag1 is not present because it doesn’t match the filter
    },
    	"groups": {
    		"Input": {
    			"tags": {
    				"Tag1": {
    					"status": {...},
    					"data": {...}
    "Tag2": {
    					"status": {...},
    					"data": {...}
    				}
    			}
    		},
    		"Output": {
    			"tags": {
    				"Tag1": {
    					"status": {...},
    					"data": {...}
    				},
    				"Tag2": {
    					"status": {...},
    					"data": {...}
    				}
    			}
    		}
    
    


    $.api.tag.details(path, options, callback(err, res)) 

    This function is used to obtain details about a tag or a tag group, including its inner tags. It has three arguments: 

    • (String) path: The path of the tag to be read, or a group. If it’s the latter, the path must end with ‘*’.
    • (Object) options: This can be any of the following, or an empty object to set the values to default: 
      • (Boolean) recurrent: If true, it will read the values of all the tags nested inside other tag groups in the specified path. Default: false
      • (String) filter: Regular expression used to filter which tags to read from the current path. This string can be any regular expression, but it can’t have any regular expression flags.
    •  (Function) callback (err, result): This callback will be called after the asynchronous request finishes. It has two arguments:
      • (String) err: Error message if the operation fails, or null if it succeeds.
      • (Object) result: An object containing the result from the reading. The result contains the details about the tags in the given path. 
    $.api.tag.details("/Scripting/Tag1",{}, function(err, result));
    
    {
    	"fullPath": "/Scripting/Tag1",
    	"remote": null,
    	"status": {
    		"value": 1,
    		"ts": "2018-11-15T15:45:49.487Z"
    	},
    	"data": {
    		"value": null,
    		"quality": 192,
    		"ts": "2018-11-15T15:45:49.487Z"
    	},
    	"config": {
    		"description": "",
    		"type": "number",
    		"format": null,
    		"deadband": "0.1u",
    		"clientAccess": "R",
    		"engUnits": "",
    		"default": null,
    		"simulation": {
    			"enabled": false
    		},
    		"security": {},
    		"extensions": {
    			"scaling": {
    				"enabled": false,
    				"raw": [0, 1000],
    				"eu": [0, 1000],
    				"clamp": [false, false]
    			},
    
    			"source": {
    				"enabled": false,
    				"type": "",
    				"module": ""
    			},
    "history": {
    				"enabled": false,
    				"module": ""
    			},
    			"events": {
    				"enabled": false
    			}
    		}
    	}
    }
    


    $.api.tag.history(tag, start, end, options, callback(err, result)) 

    This function is used to obtain historical information about a tag. It has five arguments:

    • (String) tag: The historical data will be returned to this tag.
    • (String) start: The start time of the historical data, in ISO format.
    • (String) end: The end time of the historical data, in ISO format.
    • (Object) options: These options will be used to select how to return the historical data. It can be any of the following:
      • (String) mode: It can be “raw”, “aggregated”, “filter” or “delta”. It has the same effect as these mods in the Historical view of N3uron WebUI.
      • (String) method: Specifies the aggregation method. It can be “first”, “last”, “min”, “max” and “avg”.
      • (Number) interval: Specifies the aggregation interval, in milliseconds.
    • (Function) callback (err, result):This callback will be called after the asynchronous request finishes. It has two arguments: 
      • (String) err: Error message if the operation fails, or null if it succeeds.
      • (Object) result: An object containing the result from the reading. The result contains the details about the tags in the given path. The below block shows an example with a single tag:
    $.api.tag.history("/Scripting/Tag1", "2018-11-15T15:48:10.000Z", "2018-11-15T16:48:10.000Z", {mode:"raw"}, function(err, result));
    {
    	"request": {
    		"tag": "/Scripting/Tag1",
    		"start": 1542296890000,
    		"end": 1542300490000,
    		"options": {
    			"mode": "raw"
    		}
    	},
    	"data": [
    		[1542299626765, 63226],
    		[1542299636765, 63236],
    		[1542299646766, 63246],
    		[1542299656765, 63256],
    		[1542300256898, 63856]
    	]
    }
    


    $.api.tag.write(tag, value, callback(err)) 

    This function is used to write a value to a tag. It has three arguments:

    • (String) tag: The tag where the value will be written. It can only be a tag, it can’t be a group.
    • (String | Number | Boolean) value: The value that will be written to the tag. It can be either a string, number or Boolean depending on the type of the tag.
    • (Function) callback (err):This callback will be called after the asynchronous request finishes. It has one argument:
      • (String) err: Error message if the operation fails, or null if it succeeds.

    $.api.tag.getViews (options, callback(err, views)) 

    Returns an array of available view options in this node as strings. It takes two arguments:  

    • (Object) options: An object containing options applicable to this function. There are currently no options used in this function, but the object is present here for future expansion opportunities.
    • (Function) callback (err, views): A callback function to be called when the view request finishes. This callback takes two parameters:
      • (String) err: Indicates the string containing an error message if the function has not been completed successfully or null if successful.
      • (String[]) views: Strings containing the names of the different view options available in this node.
    //If the node has the following views: "Read Only", "Outer Link1", "Outer Link2"
    $.api.tag.getViews({}, function(err, result));
    Result -> ["Read Only", "Outer Link1", "Outer Link2"]
    


    $.api.tag.update (tag, value [quality], [ts], [force]) 

    This function updates the value of a specified tag. It takes the following parameters:  

    • (String) tag: Strings containing the tag path to be updated. If the path is invalid or the tag is not a Scripting source tag, a warning will be logged and the tag will not be updated.
    • (String|number|bool) value: The value that the tag will be updated with. This can be a string, a number or a boolean, depending on the type of the tag. Null is also permitted.
    • (Number) quality: The quality of the event that caused the update. This value is optional and if not provided the tag will be automatically be updated with quality 192 (good). This value must be a number in the range of 0-255. While the quality can be any value within that range, N3uron uses a different enumeration that is a subset of all of these numbers. This enum can be found at $.utils.qualityCodes.
    • (Number) ts: The timestamp of the corresponding event, displayed in UNIX Epoch format with milliseconds. This value is optional and if not provided, the event timestamp will be set to the  same time when the update function was called.  
    • (Boolean) force: Controls whether the update will be forced or not. By default, updates will only be sent to tags if either the value or quality changes. By setting force to true, updates will always be sent.
    //Assuming two tags:
    // /Scripting/Source/Tag1 -> Value: 20
    // /Scripting/Tag2 -> Value: 30
    $.api.tag.update("/Scripting/Source/Tag1", 15, 192, 1585138500000)
    // /Scripting/Source/Tag1 -> Value: 15
    // /Scripting/Tag2 -> Value: 30
    


    $.api.tag.updateAlias (alias, value [quality], [ts], [force]) 

    This function updates the value of a specified tag. It takes the following parameters:  

    • (String) alias: A string containing the alias to be updated. If the alias is invalid, a warning is logged and no tags will be updated. If multiple tags share the same alias, an update will be generated with the same value, quality and ts for each tag sharing this alias.
    • (String|number|bool) value: The value that the tag will be updated with. This can be a string, a number or a boolean, depending on the tag type. Null is also permitted.
    • (Number) quality: The quality of the event that caused the update. This value is optional and if not provided, the tag will automatically be updated with quality 192 (good). This value must be a number in the range of 0-255. While the quality can be any value in that range, N3uron uses a different enumeration that is a subset of all of these numbers. This enum can be found at $.utils.qualityCodes.
    • (Number) ts: The timestamp of the event, displayed in UNIX Epoch format with milliseconds. This value is optional and if not provided, the event timestamp will be set to the same time as when the update function was called.  
    • (Boolean) force: Controls whether the update will be forced or not. By default, updates will only be sent to tags if either the value or the quality changes. By setting force to true, updates will always be sent.
    //Assuming three tags:
    // /Scripting/Source/Tag1, Alias: Tag1 -> Value: 20
    // /Scripting/Tag1; Alias: Tag1 -> Value: 12
    // /Scripting/Tag2; Alias: Tag2 -> Value: 30
    $.api.tag.updateAlias("Tag1", 15, 192, 1585138500000) 
    // /Scripting/Source/Tag1 -> Value: 15
    // /Scripting/Tag1 -> Value: 15
    // /Scripting/Tag2 -> Value: 30
    


    $.api.tag.browseSource (path, options) 

    This function returns any source tags present in a given path. When successful, it will return an array of full tag paths for all source tags present within the group given by the path:  

    • (String) path: The path to be browsed. This path must start and end with a “/”, otherwise, an empty array will be returned.
    • (Object) options: Object used to pass options to the browse function. Accepts the following properties:
      • (Boolean) recurrent: If this option is set to true, subgroups will automatically be included within the path. Otherwise, only tags present within that path group will be returned.
    //Assuming three tags:
    // /Scripting/Source/Tag1, Alias: Tag1 -> Value: 20
    // /Scripting/Tag1; Alias: Tag1 -> Value: 12
    // /Scripting/Tag2; Alias: Tag2 -> Value: 30
    $.api.tag.browseSource("/Scripting/", {});
    //Returns -> ["Scripting/Tag1", "Scripting/Tag2"]  
    $.api.tag.browseSource("/Scripting/", {recurrent: true});
    //Returns -> ["Scripting/Source/Tag1", "Scripting/Tag1", "Scripting/Tag2"]  
    
    


    $.api.tag.browseAlias () 

    This function is used to browse all tag aliases specified for this Scripting instance. It does not take any arguments and the return value will be an array containing all tag aliases available to this Scripting instance, displayed as a string.

    //Assuming three tags:
    // /Scripting/Source/Tag1, Alias: Tag1 -> Value: 20
    // /Scripting/Tag1; Alias: Tag1 -> Value: 12
    // /Scripting/Tag2; Alias: Tag2 -> Value: 30
    $.api.tag.browseAlias();
    //Returns -> ["Tag1", "Tag2"]  
    


    $.api.tag.onWrite (function(tag, value, cb)) 

    This function is used to register a handler for a write command on a source tag. By default, tag writes have no handler and will finish with an error. This function takes the following parameter:  

    • (Function) handler: The handler function will be called whenever a Scripting source tag receives a write command. The handler takes the following parameters:  
      • (String) tag: The full path of the tag receiving the write command.  
      • (Function) value: The value that was written to the tag. It can be a String, Number or Boolean, depending on the tag type.  
      • (Function) cb: Callback function that must be called when writing is finished. If the callback is not called, the write command will be considered as pending and will eventually time out. As such, the callback must always be called when an error is encountered during writing, or when the write command is successful. It accepts a single parameter in the form of a string containing an error message. If writing is successful, the callback must be called without any parameters.  

     

    $.api.tag.onWriteAlias (function(alias, value, cb)) 

    This function is used to register a handler for a write command on a source tag. By default, tag writes have no handler and will finish with an error. This function takes the following parameter:  

    • (Function) handler: The handler function will be called whenever a Scripting source tag receives a write command. The handler takes the following parameters:  
      • (String) alias: The alias of the tag receiving the write command.  
      • (Function) value: The value that was written to the tag. It can be a String, Number or Boolean, depending on the tag type.  
      • (Function) cb: Callback function that must be called when writing is finished. If the callback is not called, the write command will be considered as pending and will eventually time out. As such, the callback must always be called when an error is encountered during writing, or when the write command is successful. It accepts a single parameter in the form of a string containing an error message. If writing is successful, the callback must be called without any parameters.
    //Assuming four tags:
    // /Scripting/Source/Tag1
    // /Scripting/Source/Tag2, Alias: Tag2
    // /Scripting/Tag1; Alias: Tag1
    // /Scripting/Tag2; Alias: Tag2
    $.api.tag.onWrite(logTagWrite);
    $.api.tag.onWriteAlias(logAliasWrite);
    
    function logTagWrite(tag, value, cb) {
      $.logger.debug("Tag write received: %s -> %s", tag, value);
      cb();
    }
    
    function logAliasWrite(alias, value, cb) {
      $.logger.debug("Alias write received: %s -> %s", alias, value);
      cb();
    }
    
    //Write command on /Scripting/Source/Tag1; Value: 10
    //Message logged: Tag write received: /Scripting/Source/Tag1 -> 10;
    
    //Write command on /Scripting/Source/Tag2; Value: 7
    //Message logged: Alias write received: Tag2 -> 7;
    
    //Write command on /Scripting/Tag2; Value: 23
    //Message logged: Alias write received: Tag2 -> 23;
    


    $.api.tag.addTagListener(tag, listener(tag, data)) 

    This function is used to add a listener that will be called every time the given tag has an update. An example use for this function is to cache tags in the memory in order to avoid having to execute an asynchronous reading and instead, simply accessing this cache. It has two parameters:

    • (String) tag: The tag that the listener will be attached to.
    • (Function) listener (tag, data):This listener will be called whenever the tag updates. It has two parameters:
      • (String) tag: The updated tag
      • (Object) data:The event that triggered the tag update. It is an object with three fields:
        • (Number | String |Boolean) value: The value of the tag update.
        • (Number) quality: The quality of the tag update.
        • (Number) ts: The timestamp of the tag update, in ISO format.
    $.api.tag.addTagListener("/Modbus/40001",function(tag, data){
    	$.logger.trace("Tag updated: %s -> %j", tag, data)
    });
    
    //tag /Modbus/40001 update with value 40
    
    Logger |TRACE| => Tag updated: /Modbus/40001 -> {"value":40, "quality":192, ts: 2018-11-16T09:39:10.771Z}
    
    Note:
    $.api.tag-addTagListener function must only be called once (during startup for instance) in order to create only one instance of the listener. If this function is called within a periodic script, a new listener will be created each time the script is executed and eventually it will consume all the available hardware resources.


    $.api.alarm 

    $.api.alarm.get(path, options, callback(err, data))

    This function is used to retrieve a list of all alarms associated with tags in the given path. It can also retrieve alarms from subfolders, as well as to filter alarms so that only a subset of the alarms is returned. It has three arguments:

    • (String) path: Path corresponding to the target group.
    • (Object) options:These options are used to enable browsing of subfolders or for applying a filter:
      • (Boolean) recurrent: If enabled, this option will return alarms from all subfolders of a given path. If disabled, only alarms from the tags in the target group will be returned.
      • (Object) filter: This object contains the filter used to filter out which alarms should be received from the target group. Any of the following options can be applied:
      • (String) path: Regular expression used to filter alarms according to their full path. Set to null, undefined or “” to disable filtering by full path.
      • (Number[]) filter: Array of alarm status codes to include in the results. This can be multiple elements if several status codes are required. Set to null or undefined to disable filtering by status. The valid alarm status codes are:
        • 0: Cleared and acked 
        • 1: Active and acked
        • 2: Cleared and unacked
        • 3: Active and unacked
      • (Number) Priority:Minimum alarm priority in order for it to be included in the results. Any alarm with the same priority level or higher will be included. Set to null, undefined or 0 to disable filtering by priority. The valid priorities are:
        • 0: Low 
        • 1: Medium
        • 2: High
        • 3: Critical
    • (Function) callback (err, result):This callback will be called once the asynchronous request has finished. It has the following arguments:
      • (String) err: Error message if the operation fails, or null if it succeeds.
      • (Object[]) result:Array of alarm information objects. These objects have the following structure:
        • (String) path: Alarm full path.
        • (String) description: Alarm description.
        • (Number) priority: Alarm priority (same values as the priority values used in the filter object).
        • (Number) status: Alarm status (same values as the status values used in the filter object).
        • (Number) ts: Timestamp of the last status change, in Unix Epoch format with milliseconds.
        • (Number) value: The value that triggered the active/cleared status change.
        • (Object) ackInfo: Object containing information about the last acknowledgement, or null if the alarm hasn’t been acknowledged. It has the following properties:
          • (String) msg: Acknowledgement message.
          • (String) user: User who acknowledged the alarm.
          • (String) module: The module that provided the acknowledgement.
          • (String) node: The node that provided the acknowledgement.
    var path = "/CABIN01/";
    $.api.alarm.get (path,{recurrent:true, filter:{status: [2,3]}}, function(err, result){
    	if(err) {
    		$.logger.warn(err);
    		return $.exit(err);
    	}
    	$.logger.trace("Alarm list: %s -> %j", path, result);
         $.exit();
    });
    
    //Assuming two tags, HighWindSpeed and HighTemperatureAlarm with active alarms (the former being acked by "user01" with message "" ", this function will return the following array:
    [
    	{
    		path: "/CABIN01/HighWindSpeed.HiHi",
    		description: "Very high wind speed"
    		priority: 3,
    		status: 2,
    		value: 50,
    		ts: 1571131652000,
    		ackInfo: {
    			user: "user01",
    			msg: "Checked",
    			module: "Scripting"
    			node: "main"
    		}
    	},
    	{
    		path: "/CABIN01/HighTemperatureAlarm.Hi",
    		description: "High temperature"
    		priority: 2,
    		status: 3,
    		value: 81,
    		ts: 1571131652000,
    		ackInfo: null
    	},
    


    $.api.alarm.count(path, options, callback(err, count))

    This function returns the number of alarms present in a target path. This includes all alarms, both cleared and active. If only a subset of alarms is required, a filter must be included. This function has 3 arguments:

    • (String) path: Path corresponding to the target group.
    • (Object) options: These options are used to enable browsing of subfolders or for applying a filter to the results. It holds the same structure as the option object in $.api.alarm.get:
    • (Function) callback (err, count):This callback will be called once the alarm count request finishes. It has the following arguments:
      • (String) err: Error message if the operation fails, or null if it succeeds.
      • (Number) count: Number of alarms in the target path that also match the given filter.

     $.api.alarm.history(path, start, end, options, callback(err, result))

    This function returns the number of alarms present in a target path. This includes all alarms, both cleared and active. If only a subset of alarms is required, a filter must be included. This function has 3 arguments:

    • (String) path: Path corresponding to the target group.
    • (Number | String) start: Start date of the historical request, in either UNIX Epoch format with milliseconds, or ISO String.
    • (Number | String) end: End date of the historical request, in either UNIX Epoch format with milliseconds, or ISO String.
    • (Object) options: These options are used to enable browsing of subfolders, or for applying a filter to the results. It holds the same structure as the option object in $.api.alarm.get:
    • (Function) callback (err, result):This callback will be called once the historical request finishes. It has the following arguments:
      • (String) err: Error message if the request fails, or null if it succeeds.
      • (Object) result: Object containing two elements: a copy of the request & data from the historical request.
        • (Object) request: Copy of the request, including the path, start, end and options objects.
        • (Object[]) data: Array of alarm information objects, identical to those returned by $.api.alarm.get. Note that this array may include duplicates of the same alarm as it includes all alarm state changes (for example: Active unacked -> active acked -

    > cleared acked).

     $.api.alarm.ack(paths, msg, user, callback(err))

    This function is used to acknowledge one or multiple alarms containing messages, including those from a specific user. It has four arguments:

    • (String | String[]) paths: Alarm target path or an array of paths when acknowledging multiple alarms at the same time. This should be the path of the alarm to be acknowledged, not the path of a tag. For example, if the tag /C01/TemperatureAlarm has a “HiHi" alarm, the path of the alarm would be /C01/TemperaturaAlarm.HiHi
    • (String) msg: Message used to acknowledge the alarm.
    • (String) user: User who acknowledged the alarm.
    • (Function) callback (err): This callback will be called once the acknowledgement request finishes. It has the following arguments:
      • (String) err: Error message if the operation fails, or null if it succeeds.


    $.utils

    The utils header contains several functions that don’t directly interface with the API, but which can be used to simplify the resulting code.

    • $.utils.qualityCodes 

    This enumeration provides different OPC quality codes that can be used to compare against the quality value of a tag. The different qualities, along with their values are:

    $.utils.qualityCodes = {
    BAD_NON_SPECIFIC: 0x00, //0
    BAD_CONFIG_ERR0R: 0x04, //4
    BAD_NOT_CONNECTED: 0x08, //8
    BAD_DEVICE_FAILURE: 0x0C, //12
    BAD_SENSOR_FAILURE: 0x10, //16
    BAD_LAST_KNOWN_VALUE: 0x14, //20
    BAD_COMM_FAILURE: 0x18, //24
    BAD_OUT_OF_SERVICE: 0x1C, //28
    BAD_UNINITIALIZED: 0x20, //32
    
    UNCERTAIN_NON_SPECIFIC: 0x40, //64
    UNCERTAIN_LAST_USABLE_VALUE: 0x44, //68
    UNCERTAIN_SENSOR_NOT_ACCURATE: 0x50, //80
    UNCERTAIN_EU_UNITS_EXCEEDED: 0x54, //84
    UNCERTAIN_SUB_NORMAL: 0x58, //88
    
    GOOD_NON_SPECIFIC: 0xC0, //192
    GOOD_LOCAL_OVERRIDE: 0xD8 //216
    }
    


    • $.utils.checkFolder(path) 

    This function checks if a folder exists in the given path, and recursively creates it if it doesn’t. This function can be used to create a data folder if it doesn’t exist at the start time. It is a synchronous function, which means it doesn’t allow any other code to run while creating these different folders. An example of this function can be seen in the following code:

    //Save data to N3uron/data/Scripting/Folder1/Folder2/Folder3. 
    //Create the folder to hold the data
    var folderPath = path.join($.paths.local.data, "Folder1", "Folder2", "Fold-er3");
    $.utils.checkFolder(folderPath);
    //1 - Creates N3uron/data/Scripting/Folder1
    //2 - Creates N3uron/data/Scripting/Folder1/Folder2
    //3 - Creates N3uron/data/Scripting/Folder1/Folder2/Folder3
    fs.writeFile(path.join(folderPath, "data.dat"), data, function(err){
    	if(err) return $.exit(err);
    	$.logger.info("Data written OK");
    	$.exit()
    });
    


    • $.utils.getProp(obj, prop) 

    This function recursively retrieves the nested property “prop” from the provided object. Prop is a string with object keys separated by periods to represent nested objects. It can also use array indexing to access arrays in the given object. If the property is not found, an error will be returned. See below for an example in the following code block:

    //If working with the following object:
    var example = {
        outerVariable:1,
        nestedObject: {
            nestedKey:5,
            nestedArray: [
                10,
                {
                    innermostVariable:100
                }
            ]
        }
    }
    $.utils.getProp(example, "outerVariable") -> 1
    $.utils.getProp(example, "nestedObject.nestedKey") -> 5
    $.utils.getProp(example, "nestedObject.nestedArray[0] ") -> 10
    $.utils.getProp(example, "nestedObject.nestedArray[1].innermostVariable" -> 100
    $.utils.getProp(example, "nonExistent") -> Thrown error
    




    Was this article helpful?

    What's Next