Project

General

Profile

Javascript » History » Version 21

Torbjorn Carlqvist Admin, 01/12/2023 09:27 AM

1 2 Torbjorn Carlqvist Admin
h1. Javascript guide for DTXr code IDE
2 1 Torbjorn Carlqvist Admin
3 9 Torbjorn Carlqvist Admin
Shows the various commands and events that can be used to build automation scripts.
4 1 Torbjorn Carlqvist Admin
5 12 Torbjorn Carlqvist Admin
[[#Commands|Commands]]
6
[[#Events|Events]]
7 10 Torbjorn Carlqvist Admin
8 11 Torbjorn Carlqvist Admin
---
9
10 6 Torbjorn Carlqvist Admin
h2. Commands
11
12 19 Torbjorn Carlqvist Admin
<pre><code class="javascript">
13 21 Torbjorn Carlqvist Admin
    //Set this to THIS device id.
14
    //The var is used in commands below for convinience.
15
    var gThisDeviceId = 123456;   
16
    //Set this to A REMOTE device id on your network.
17
    //The var is used in commands below for convinience.
18
    var gRemoteDeviceId = 121212;   
19
    
20
    /** LOG/DEBUG **/
21
    
22
    //Prints to console log window as well as autmation.log
23
    //Note that automation.js is also written to by various services in DTX by
24
    //default, not only what you do with print() in your code.
25
    //Consider this as a volatile log where you debug and then clear from time to time.
26
    //10Mbyte is max then it will rollover to time-stamped zip file and automation.js is cleared.
27
    print("hello");
28
    
29
    //Prints to automation_user.log
30
    //This statement is the only source for loggin in this file.
31
    //Consider this to be a persistant log of important process matters.
32
    //10Mbyte is max then it will rollover to time-stamped zip file anf automation-user.js is cleared.
33
    Controller.printToUserLog("hello user log");
34
        
35
    /** BACnet related **/
36
    
37
    //Translation helper for BACnet object ID->NAME
38
    //Many even arguments are enumerated where theese function can help
39
    print(getObjectTypeById(4)); //Binary Output
40
    print(getPropertyTypeById(85)); //presentValue
41 1 Torbjorn Carlqvist Admin
42 21 Torbjorn Carlqvist Admin
    // *** Write a value to an object property ***
43
    Controller.writeProperty(gThisDeviceId,analogValue,0,presentValue,priority_1,active);
44
    Controller.writeProperty(gRemoteDeviceId,analogValue,0,presentValue,priority_1,active);
45
    
46
    // *** Read a value from a property. *** 
47
    //Will return both primitiv and constructed (JSON) values
48
    
49
    //Primitive
50
    print(Controller.readProperty(gThisDeviceId,analogValue,0,presentValue));
51
    print(Controller.readProperty(gRemoteDeviceId,analogValue,0,presentValue));
52
    
53
    //Constructed (always JSON format from complex values)
54
    //A priorityArray property is one example of constructed result
55
    print(Controller.readProperty(gThisDeviceId,analogValue,0,statusFlags));
56
    
57
    // *** COV Subscribtion ***
58
    
59
    //With auto incremented process id, sensitivity (increment) of 1 (analog values) and subscription lifetime of 300s
60
    Controller.COVSubscribe(covProcIncr,gRemoteDeviceId,analogValue,instance_0,noCovConfirmation,presentValue,1 /*sensitivity*/,300 /*lifetime (s)*/);
61
    
62
    //With fixed process id 123, sensitivity (increment) no sesnitivity (binary values) and subscription lifetime of 300s
63
    Controller.COVSubscribe(123,gRemoteDeviceId,analogValue,instance_0,noCovConfirmation,presentValue,null,300 /*lifetime (s)*/);
64
    
65
    //UN-Subscribe with specific process id 10
66
    Controller.COVSubscribe(123,gRemoteDeviceId,analogValue,instance_0,null,presentValue,defaultIncrement,null);
67
    
68
    // *** Intrinsic Reporting (Alarms and Events) ***
69 1 Torbjorn Carlqvist Admin
70 21 Torbjorn Carlqvist Admin
    //Remote Event Subscribe
71
    Controller.eventSubscribe(gRemoteDeviceId/*device id*/,instance_0/*Notification Class*/);
72
    
73
    //Enable event/alarm reporting on object
74
    Controller.enableIntrinsicReporting(0/*NotificationClass*/,3/*delay*/,3/*delayNormal*/,analogValue,instance_0,notifyTypeEvent);
75
    
76
    Controller.writeProperty(analogValue,instance_0,presentValue,priority_1,50);
77
    //TextMessage
78
    Controller.sendTextMessage(gThisDeviceId,"SOME_TYPE_OF_MSG","hello myself, what's up?");
79
    
80
    //Acknowledge alarm and events
81
    Controller.acknowledgeAlarm(gThisDeviceId,analogValue,instance_0,processIdZero,
82
                        ackNormal,1584383651150,"Toca",new Date().getTime());
83
    
84
    //Issue an alert for a specific object via an Alert Enrollment Object
85
    //The recipients in the notification class connected to the shosen alert enrollment object will receive the alert
86
    var alertEnrollmentObjectInstance = 0;
87
    var propretaryEventType = 666;
88
    Controller.issueAlert(alertEnrollmentObjectInstance,analogValue,0,"To high!",propretaryEventType);     
89
    
90
    Controller.getEnrollmentSummary(gThisDeviceId);
91
                        
92
    //Send event notif local or remote nodes
93
    //DeviceId,NotificationClass,AckRequired,Message
94
    Controller.sendNotification(gThisDeviceId,0,1,"Coffe anyone?");
95
      
96
    //Get all alarms for a specific device. Return JSON
97
    resp =  print(Controller.getAlarmSummary(gThisDeviceId));
98 1 Torbjorn Carlqvist Admin
99 21 Torbjorn Carlqvist Admin
    //Get all events for a specific device. Return JSON
100
    resp =  print(Controller.getEventSummary(gThisDeviceId));
101 1 Torbjorn Carlqvist Admin
102 21 Torbjorn Carlqvist Admin
    // *** Special Object Types *** //
103
    
104
    //Read a range of datapoints from a TrendLog object
105
    //The response is JSON with an array of value/timestamp
106
    Controller.readRange(gThisDeviceId,trendLogMultiple,0);
107 1 Torbjorn Carlqvist Admin
108 21 Torbjorn Carlqvist Admin
    // *** HTTP REST and Web Socket ***
109
    
110
    //HTTP GET Request. Returns respons as string
111
    resp = Controller.HTTP_GET('https://httpbin.org','get','Accept:application/json|Content-Type:application/json','myparam=hello');
112
    
113
    //HTTP POST(also PUT and PATCH) Request. Return response as string
114
    resp = Controller.HTTP_POST('https://httpbin.org/post'
115
                ,'Accept:application/json|Content-Type:application/json'
116
                ,'myparam=hello'
117
                ,'any payload string data');  
118
                
119
    //Web socket call to any webpage in the project file
120
    //This require that the page has loaded the Ws.js import.
121
    //Se HTTP Websocket template from the project tree sub menu
122
    Controller.sendToWS("mypage","Hello My Page this is a payload"); 
123
              
124
    //Connect to a Web Socket
125
    //DTX has a built in single web socket client.
126
    //Connect
127
    Controller.connectWebSocket("wss://any.websocket.host");
128
    //Send a message once connection is established
129
    Controller.sendWebSocketText("Hello");
130
    
131
    // *** SQL relational database access ***
132
    
133
    //Note, SQL db is not embedded so JDBC config is made in settings in advance.
134
    //Only PostgresSQL is supported for the moment!
135
    
136
    //Simple query. Result (if any) will always be JSON!
137
    print(Controller.sqlExecuteQuery("select * from anytable"));
138
    
139
    //Inserts and updates are preferably solved with functions or procedures on
140
    //the databas side. The CALL statement can then be utilized:
141
    Controller.sqlExecuteQuery("CALL upsert_anytable("+name+",'"+age+"')");
142
    
143
    //But of course a simple insert can also be sent...
144
    print(Controller.sqlExecuteQuery("insert into anytable values('kalle','13')"));
145
    
146
    // *** Timers and Schedulers ***
147 1 Torbjorn Carlqvist Admin
148 21 Torbjorn Carlqvist Admin
    //Show all current jobs (including system jobs)
149
    Controller.schedulerSummary();
150
    
151
    //Pause all jobs
152
    Controller.pauseAllJobs();
153
    
154
    //Pause a specific job
155
    Controller.pauseJob("JobA");
156
    
157
    //Resume all jobs
158
    Controller.resumeAllJobs();
159
    
160
    //Resume a specific job
161
    Controller.resumeJob("JobA");
162
    
163
    //Start job
164
    //Eg. executes function myCallbackFunction() with argument "df" after 10 seconds
165
    Controller.startJob('Job1',10,'myCallbackFunction("df")');
166
    //Eg. executes function myCallbackFunction() repeatedly every minute
167
    //with a start delay of 5 seconds
168
    Controller.startJob('Job2',5,60,'myCallbackFunction');
169
    
170
    //Eg. start a CRON job that executes myCallbackFunction
171
    //at 00:10 AM (10 minute past midnight) every day
172
    Controller.startCronJob("Job3",'0 10 0 ? * * *','myCallbackFunction');
173
    //Note: CRON can be difficult to construct. 
174
    //Use the below link to both crete and also verify your CRON strings.
175
    //https://www.freeformatter.com/cron-expression-generator-quartz.html
176
    
177
    //Cancel a job by using the name provided above
178
    Controller.cancelJob("Job3");
179
    
180
    //Cancel all jobs
181
    Controller.cancelAllJobs();        
182
    
183
    //Cancel a specific jobs
184
    Controller.cancelJob("JobG");        
185 1 Torbjorn Carlqvist Admin
186 21 Torbjorn Carlqvist Admin
    //This is a special function where you can schedule the execution of
187
    //a code snippet.
188
    //Arg1: Som job identifier - To use when pause/cancel the job if neccesary.
189
    //Arg2: start delay (s) - Time until first exec
190
    //Arg3: period(s) - Time between exec, set to 0 if no repetition is required/wanted.
191
    //Arg4: repeates - Number of repeates, null if infinit, 0 if no repeat
192
    //Arg5: code - Any Javascript
193
    Controller.scheduleExecution("wait05",5,0,0,"print('print once in 5 sec');");
194 1 Torbjorn Carlqvist Admin
195 21 Torbjorn Carlqvist Admin
    // *** MISC ***
196
    
197
    //Send an email. Note, needs smtp-server config first
198
    Controller.SendEmail("torbjorn.carlqvist@davitor.com","anysubject","some body");
199
    
200
    // *** Embedded JSON storage ***
201
    
202
    //Perfect to use when automation settings, states, structures etc must be persisted and
203
    //the use of an external SQL database is unnecessary
204
    
205
    //Push a string to spcified queue (queue will be created if not exist)
206
    //This queue is persistant during reboot of the evice
207
    //All queues and records are stored in the collection "jsonstore.json" which can be found in project folder
208
    Controller.JSONPush("toca","msg5");
209
    //Pop a string from the specified queue. FIFO!
210
    //Returns null if no strings found
211
    print(Controller.JSONPop("toca"));
212 1 Torbjorn Carlqvist Admin
213 21 Torbjorn Carlqvist Admin
    print(Controller.JSONPersist("nisse"));
214
    print(Controller.JSONPersist("1588058754445","palle"));
215
    
216
    print(Controller.JSONRestore("1588058754445"));
217
    
218
    print(Controller.JSONBrowse("toca"));
219
    
220
    //Change name on multiple local objects
221
    //This can be used when a group of objects need to have save name prefix.
222
    //eg. when a sensor has multiple object and you want them to share same sensor name.
223
    Controller.updateLocalObjectNames("TestBI","newname");
224
    
225
    //This method should be used when javascript forms a link between
226
    //an external interaface and the object stack.
227
    //Typically when a button on a HMI should update an binaryInput or
228
    //a reception of a BLE Beacon should update an analogInput.
229
    //This method will create an object if no object exists with same profilName property
230
    Controller.createOrUpdateLocalObject(analogInput,null,"MyObjectName",123);
231
    
232
    //As an addition use this function to control the reliability of the obejct in real time.
233
    //This will create events and alarms accordingly of intrinsic reporting is enanbled.
234
    Controller.setLocalObjectReliability(binaryOutput,0,'shorted-loop');
235
    Controller.setLocalObjectReliability(binaryOutput,0,'no-fault-detected');
236
    
237
    //Yet another addition is this function to set the overridden flag on local objects.
238
    //The meaning of this flag is to tell BACnet that this physical point is not 
239
    //longer reliable or commandable.
240
    Controller.setLocalObjectOverridden(binaryOutput,0,true);
241
    Controller.setLocalObjectOverridden(binaryOutput,0,false);
242
    
243
    // *** File access ***/
244
    
245
    //Basic file R/W/List for files in project folder (and sub folders)
246
    Controller.writeFile("file_rw_test.txt","Hello file handling!");
247
    print(Controller.readFile("file_rw_test.txt"));
248
    print(Controller.listFiles(".txt",null));
249
    print(Controller.listFiles(".json","mysubfolder"));    
250
    print(Controller.removeFiles(".txt",null));    
251
    
252
    // *** OS operations ***/
253
    
254
    //Run commands on host operatice system
255
    //Result is JSON string
256
    //The exit_code tells if successful or not.
257
    //There is a built in timeout if you accedently start a job that does not 
258
    //stop of it's own. Like doing unlimited ping on Linux
259
    //No, there is no way to stop a command with Ctrl-C from JS.
260
    //Note, the process is running in foreground so if DTX dies the process dies too.
261
    print(Controller.execCommand("ping -n 3 google.com"));
262
    
263
    // *** Serial Ports ***/
264
    
265
    //List all connected serial ports. The response is JSON and can tell a lot
266
    //about the serial port. For example in which USB socket it is connected.
267
    print(Controller.listSerialPorts());
268
    
269
    //Connect to a serial port (multiple connection is allowed)
270
    //Use the serial port name from the response from listSerialPorts() above.
271
    //As argument form a JSON according to specification.
272
    //Example of setting up a serial connection to ttyACM0 that handles 
273
    //delimited responses with a "Return(0d)" at the END with a speed of 115200baud
274
    //Note that if a connection already occurs in this name it will be closed automatically
275
    Controller.setupSerialPort("ttyACM0",'{"msgDelim":true,"baudrate":115200,"delimPattern":"0d","delimPosition":"end"}');
276
    
277
    //Send ASCII data to the connected port
278
    Controller.writeSerialAscii("ttyACM0","hello");
279
    
280
    //Send HEX data to the serial port
281
    Controller.writeSerialHex("ttyACM0","03"); //Eg. Ctrl-C in HEX
282
    
283
    //Close serial port
284
    Controller.closeSerialPort("ttyACM0");
285
    
286
    //NOTE: all received serial data enters the event callback "onSerialReceive"
287
    
288
    /*** MODBUS ***/
289
    
290
    /* Modbus TCP */
291
    
292
    //If needed, use this to simulate a slave on THIS device for test purpose. 
293
    //Will setup a demo image of regs and coils
294
    Controller.modbusTCPCreateSlave();
295
    
296
    //Read coils (true/false)
297
    //Args: Slave IP, Slave Port, Start Addr, Count
298
    //Return: JSON Array with result
299
    print(Controller.modbusTCPReadCoils("localhost",502,1,1));
300 18 Torbjorn Carlqvist Admin
301 21 Torbjorn Carlqvist Admin
    //Reading input discretes (true/false)
302
    //Args: Slave IP, Slave Port, Start Addr, Count
303
    //Return: JSON Array with result
304
    print(Controller.modbusTCPReadInputDiscretes("localhost",502,1,5));
305
    
306
    //Reading input registers (Analog Inputs)
307
    //Can be either signed or unsigned 16-bit values.
308
    //Args: Slave IP, Slave Port, Start Addr, Count
309
    //Return: JSON Array with result
310
    print(Controller.modbusTCPReadInputRegisters("localhost",502,1,5));
311
    
312
    //Reading holding registers (Analog Outputs)
313
    //Can be either signed or unsigned 16-bit values.
314
    //Args: Slave IP, Slave Port, Start Addr, Count
315
    //Return: JSON Array with result
316
    print(Controller.modbusTCPReadHoldingRegisters("localhost",502,1,5));
317 14 Torbjorn Carlqvist Admin
318 21 Torbjorn Carlqvist Admin
    //Write to coil (!CAUTION!)
319
    //Note, always returns null
320
    //Args: Slave IP, Slave Port, Addr, Status (true=On/1, false=Off/0)
321
    Controller.modbusTCPWriteCoil("localhost",502,1,false);
322
    
323
   
324
    /* Modbus Serial */
325
    //Note, setting null as port settings defaults to 9600/8N1
326
    
327
    //A mock-up test slave for serial modbus
328
    //Args: Port, Port Settings, RTU
329
    Controller.modbusSerialCreateSlave("COM1",null,false);
330
    //Writing to a MODBUS slave coil via Serial RTU
331
    //Args: Port, Port Settings,RTU,reg address, value/state 
332
    Controller.modbusSerialWriteCoil("COM2",null,false,2,true);
333
    //Reading from a MODBUS slave coil via Serial RTU
334
    //Args: Port, Port Settings,RTU,reg address
335
    Controller.modbusSerialReadCoils("COM2",null,false,1,2);
336
    
337
    /*** Controller management ***/
338
    
339
    //Running reInit() will completly clear the JS-engine, stop all jobs and
340
    //re-actiavate the code and finally call the init() method.
341
    Controller.reInit();
342 1 Torbjorn Carlqvist Admin
</code></pre>
343
344
345
h2. Events
346
347
h3. *eventNotificationReceived* - Called when an intrinsic report notification is received.
348
349
<pre><code class="javascript">
350
/***********************************************************************************************
351
 * @param {Number} processIdentifier - Event process on the caller side
352
 * @param {Number} initiatingDevice - The device that send the event
353
 * @param {Number} object - The source object in readable format 
354
 * @param {Number} objectType - The source object of the event
355
 * @param {Number} objectInstance - The instance of source object
356
 * @param {String} timeStampUTC - Event timestamp in UTC format
357
 * @param {Number} notificationClass - The NC handling this event on remote node
358
 * @param {Number} priority - Event priority
359
 * @param {Number} eventType - The type of event received
360
 * @param {String} messageText - Readable notification message
361
 * @param {Number} notifyType - Type of notification [0:Event,1:Alamr,2:AckNotif]
362
 * @param {Boolean} ackRequired - true if ack is required to clear this event on the remote node
363
 * @param {String} fromState - The previous state
364
 * @param {String} toState - The current state after the change
365
 * @param {Object} eventValues - A map of specific map of values for the particular eventType
366
 ***********************************************************************************************/
367
function eventNotificationReceived(processIdentifier,initiatingDevice,object,objectType,objectInstance,timeStampUTC,notificationClass,priority,eventType,messageText,notifyType,ackRequired,fromState,toState,eventValues){
368
//Use this event to act on notifications that is set to be subscribed by this device.
369
}
370
</code></pre>