Project

General

Profile

Javascript » History » Version 20

Torbjorn Carlqvist Admin, 12/02/2022 02:30 PM

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 18 Torbjorn Carlqvist Admin
//Set this to THIS device id.
14
//The var is used in commands below for convinience.
15 20 Torbjorn Carlqvist Admin
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 1 Torbjorn Carlqvist Admin
20 18 Torbjorn Carlqvist Admin
/** LOG/DEBUG **/
21 1 Torbjorn Carlqvist Admin
22 18 Torbjorn Carlqvist Admin
//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 1 Torbjorn Carlqvist Admin
29 18 Torbjorn Carlqvist Admin
//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 1 Torbjorn Carlqvist Admin
37 18 Torbjorn Carlqvist Admin
//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 1 Torbjorn Carlqvist Admin
print(getPropertyTypeById(85)); //presentValue
41
42
// *** Write a value to an object property ***
43 20 Torbjorn Carlqvist Admin
Controller.writeProperty(gThisDeviceId,analogValue,0,presentValue,priority_1,active);
44
Controller.writeProperty(gRemoteDeviceId,analogValue,0,presentValue,priority_1,active);
45 18 Torbjorn Carlqvist Admin
46
// *** Read a value from a property. *** 
47 1 Torbjorn Carlqvist Admin
//Will return both primitiv and constructed (JSON) values
48
49 18 Torbjorn Carlqvist Admin
//Primitive
50 20 Torbjorn Carlqvist Admin
print(Controller.readProperty(gThisDeviceId,analogValue,0,presentValue));
51
print(Controller.readProperty(gRemoteDeviceId,analogValue,0,presentValue));
52 18 Torbjorn Carlqvist Admin
53
//Constructed (always JSON format from complex values)
54
//A priorityArray property is one example of constructed result
55 20 Torbjorn Carlqvist Admin
print(Controller.readProperty(gThisDeviceId,analogValue,0,statusFlags));
56 18 Torbjorn Carlqvist Admin
57 1 Torbjorn Carlqvist Admin
// *** COV Subscribtion ***
58 18 Torbjorn Carlqvist Admin
59 1 Torbjorn Carlqvist Admin
//With auto incremented process id, sensitivity (increment) of 1 (analog values) and subscription lifetime of 300s
60 20 Torbjorn Carlqvist Admin
Controller.COVSubscribe(covProcIncr,gRemoteDeviceId,analogValue,instance_0,noCovConfirmation,presentValue,1 /*sensitivity*/,300 /*lifetime (s)*/);
61 18 Torbjorn Carlqvist Admin
62
//With fixed process id 123, sensitivity (increment) no sesnitivity (binary values) and subscription lifetime of 300s
63 20 Torbjorn Carlqvist Admin
Controller.COVSubscribe(123,gRemoteDeviceId,analogValue,instance_0,noCovConfirmation,presentValue,null,300 /*lifetime (s)*/);
64 18 Torbjorn Carlqvist Admin
65
//UN-Subscribe with specific process id 10
66 20 Torbjorn Carlqvist Admin
Controller.COVSubscribe(123,gRemoteDeviceId,analogValue,instance_0,null,presentValue,defaultIncrement,null);
67 18 Torbjorn Carlqvist Admin
68
// *** Intrinsic Reporting (Alarms and Events) ***
69
70
//Remote Event Subscribe
71 20 Torbjorn Carlqvist Admin
Controller.eventSubscribe(gRemoteDeviceId/*device id*/,instance_0/*Notification Class*/);
72 1 Torbjorn Carlqvist Admin
73 18 Torbjorn Carlqvist Admin
//Enable event/alarm reporting on object
74 1 Torbjorn Carlqvist Admin
Controller.enableIntrinsicReporting(0/*NotificationClass*/,3/*delay*/,analogValue,instance_0,notifyTypeEvent);
75
76
Controller.writeProperty(analogValue,instance_0,presentValue,priority_1,50);
77 18 Torbjorn Carlqvist Admin
//TextMessage
78
Controller.sendTextMessage(gThisDeviceId,"SOME_TYPE_OF_MSG","hello myself, what's up?");
79
80
//Acknowledge alarm and events
81 20 Torbjorn Carlqvist Admin
Controller.acknowledgeAlarm(gThisDeviceId,analogValue,instance_0,processIdZero,
82 18 Torbjorn Carlqvist Admin
					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 20 Torbjorn Carlqvist Admin
var alertEnrollmentObjectInstance = 0;
87
var propretaryEventType = 666;
88
Controller.issueAlert(alertEnrollmentObjectInstance,analogValue,0,"To high!",propretaryEventType);     
89 18 Torbjorn Carlqvist Admin
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
99
//Get all events for a specific device. Return JSON
100
resp =  print(Controller.getEventSummary(gThisDeviceId));
101
102
// *** 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
108
// *** 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
148
//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
186
//This is a special function where you can schedule the execution of
187
//a code snippet.
188
//Arg1: job identifier - To paus/cancel the job.
189
//Arg2: start delay (s) - Time until first exec
190
//Arg3: period(s) - Time between exec, set to 0 if no repetition is required.
191
//Arg4: repeates - Number of repeates, null if infinit, 0 if no repeat
192
//Arg5: code - Any Javascript
193
Controller.scheduleExecution(5,0,0,"print('print once in 5 sec');");
194
195
// *** 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
213
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
// *** File access ***/
233
234
//Basic file R/W/List for files in project folder (and sub folders)
235
Controller.writeFile("file_rw_test.txt","Hello file handling!");
236
print(Controller.readFile("file_rw_test.txt"));
237
print(Controller.listFiles(".txt",null));
238
print(Controller.listFiles(".json","mysubfolder"));    
239
print(Controller.removeFiles(".txt",null));    
240
241
// *** OS operations ***/
242
243
//Run commands on host operatice system
244
//Result is JSON string
245
//The exit_code tells if successful or not.
246
//There is a built in timeout if you accedently start a job that does not 
247
//stop of it's own. Like doing unlimited ping on Linux
248
//No, there is no way to stop a command with Ctrl-C from JS.
249
//Note, the process is running in foreground so if DTX dies the process dies too.
250
print(Controller.execCommand("ping -n 3 google.com"));
251
252
// *** Serial Ports ***/
253
254
//List all connected serial ports. The response is JSON and can tell a lot
255
//about the serial port. For example in which USB socket it is connected.
256
print(Controller.listSerialPorts());
257
258
//Connect to a serial port (multiple connection is allowed)
259
//Use the serial port name from the response from listSerialPorts() above.
260
//As argument form a JSON according to specification.
261
//Example of setting up a serial connection to ttyACM0 that handles 
262
//delimited responses with a "Return(0d)" at the END with a speed of 115200baud
263
//Note that if a connection already occurs in this name it will be closed automatically
264
Controller.setupSerialPort("ttyACM0",'{"msgDelim":true,"baudrate":115200,"delimPattern":"0d","delimPosition":"end"}');
265
266
//Send ASCII data to the connected port
267
Controller.writeSerialAscii("ttyACM0","hello");
268
269
//Send HEX data to the serial port
270
Controller.writeSerialHex("ttyACM0","03"); //Eg. Ctrl-C in HEX
271
272
//Close serial port
273
Controller.closeSerialPort("ttyACM0");
274
275
//NOTE: all received serial data enters the event callback "onSerialReceive"
276
277
/*** MODBUS ***/
278
279
/* Modbus TCP */
280
281
//If needed, use this to simulate a slave on THIS device for test purpose. 
282
//Will setup a demo image of regs and coils
283
Controller.modbusTCPCreateSlave();
284
285
//Read coils (true/false)
286
//Args: Slave IP, Slave Port, Start Addr, Count
287
//Return: JSON Array with result
288
print(Controller.modbusTCPReadCoils("localhost",502,1,1));
289
290
//Reading input discretes (true/false)
291
//Args: Slave IP, Slave Port, Start Addr, Count
292
//Return: JSON Array with result
293
print(Controller.modbusTCPReadInputDiscretes("localhost",502,1,5));
294
295
//Reading input registers (Analog Inputs)
296
//Can be either signed or unsigned 16-bit values.
297
//Args: Slave IP, Slave Port, Start Addr, Count
298
//Return: JSON Array with result
299
print(Controller.modbusTCPReadInputRegisters("localhost",502,1,5));
300
301
//Reading holding registers (Analog Outputs)
302
//Can be either signed or unsigned 16-bit values.
303
//Args: Slave IP, Slave Port, Start Addr, Count
304
//Return: JSON Array with result
305
print(Controller.modbusTCPReadHoldingRegisters("localhost",502,1,5));
306
307
//Write to coil (!CAUTION!)
308
//Note, always returns null
309
//Args: Slave IP, Slave Port, Addr, Status (true=On/1, false=Off/0)
310
Controller.modbusTCPWriteCoil("localhost",502,1,false);
311
312
313
/* Modbus Serial */
314
//Note, setting null as port settings defaults to 9600/8N1
315
316
//A mock-up test slave for serial modbus
317
//Args: Port, Port Settings, RTU
318
Controller.modbusSerialCreateSlave("COM1",null,false);
319
//Writing to a MODBUS slave coil via Serial RTU
320
//Args: Port, Port Settings,RTU,reg address, value/state 
321
Controller.modbusSerialWriteCoil("COM2",null,false,2,true);
322
//Reading from a MODBUS slave coil via Serial RTU
323
//Args: Port, Port Settings,RTU,reg address
324
Controller.modbusSerialReadCoils("COM2",null,false,1,2);
325
326
/*** Controller management ***/
327
328
//Running reInit() will completly clear the JS-engine, stop all jobs and
329
//re-actiavate the code and finally call the init() method.
330 1 Torbjorn Carlqvist Admin
Controller.reInit();
331 14 Torbjorn Carlqvist Admin
</code></pre>
332 19 Torbjorn Carlqvist Admin
333 1 Torbjorn Carlqvist Admin
334 14 Torbjorn Carlqvist Admin
h2. Events
335
336
h3. *eventNotificationReceived* - Called when an intrinsic report notification is received.
337 1 Torbjorn Carlqvist Admin
338 6 Torbjorn Carlqvist Admin
<pre><code class="javascript">
339 14 Torbjorn Carlqvist Admin
/***********************************************************************************************
340 6 Torbjorn Carlqvist Admin
 * @param {Number} processIdentifier - Event process on the caller side
341 1 Torbjorn Carlqvist Admin
 * @param {Number} initiatingDevice - The device that send the event
342 7 Torbjorn Carlqvist Admin
 * @param {Number} object - The source object in readable format 
343 5 Torbjorn Carlqvist Admin
 * @param {Number} objectType - The source object of the event
344 4 Torbjorn Carlqvist Admin
 * @param {Number} objectInstance - The instance of source object
345 1 Torbjorn Carlqvist Admin
 * @param {String} timeStampUTC - Event timestamp in UTC format
346
 * @param {Number} notificationClass - The NC handling this event on remote node
347
 * @param {Number} priority - Event priority
348
 * @param {Number} eventType - The type of event received
349
 * @param {String} messageText - Readable notification message
350
 * @param {Number} notifyType - Type of notification [0:Event,1:Alamr,2:AckNotif]
351
 * @param {Boolean} ackRequired - true if ack is required to clear this event on the remote node
352
 * @param {String} fromState - The previous state
353
 * @param {String} toState - The current state after the change
354
 * @param {Object} eventValues - A map of specific map of values for the particular eventType
355
 ***********************************************************************************************/
356
function eventNotificationReceived(processIdentifier,initiatingDevice,object,objectType,objectInstance,timeStampUTC,notificationClass,priority,eventType,messageText,notifyType,ackRequired,fromState,toState,eventValues){
357
//Use this event to act on notifications that is set to be subscribed by this device.
358
}
359
</code></pre>