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