Javascript » History » Version 23
Torbjorn Carlqvist Admin, 01/12/2023 09:31 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 | 22 | Torbjorn Carlqvist Admin | /** |
351 | * Called when controller starts. Good place to do init stuff |
||
352 | */ |
||
353 | function init(){ |
||
354 | print("init!"); |
||
355 | |||
356 | } |
||
357 | |||
358 | |||
359 | 1 | Torbjorn Carlqvist Admin | /*********************************************************************************************** |
360 | 23 | Torbjorn Carlqvist Admin | * Called when the controller receives a notification (intrinsic reporting) from this or another device |
361 | * @param {processIdentifier} Can be used to process events/alarms different consumed. Users choice. |
||
362 | * @param {Number} initiatingDevice - The device ID that send the event and the device where the triggered object belongs |
||
363 | * @param {String} object - A convinient string to describe objectype:instance in text |
||
364 | * @param {Number} objectType - The source object of the event |
||
365 | 1 | Torbjorn Carlqvist Admin | * @param {Number} objectInstance - The instance of source object |
366 | 23 | Torbjorn Carlqvist Admin | * @param {Number} timeStampUTC - EPOC type of timestamp where the event/alarm trigger fired |
367 | * @param {Number} notificationClassInstance - An instance pointer to the connected class |
||
368 | * @param {Number} priority - Priority of this event |
||
369 | * @param {Number} eventType - The type of event received. Eg. 'outOfRange' |
||
370 | * @param {String} messageText - Free text that can be used describing the event |
||
371 | * @param {String} notifyType - Type of notification. Can be 'alarm' or 'event' |
||
372 | * @param {Boolean} ackRequired - Tell wether this event/alarm needs acknowledgment or not |
||
373 | 1 | Torbjorn Carlqvist Admin | * @param {String} fromState - The previous state |
374 | * @param {String} toState - The current state after the change |
||
375 | 23 | Torbjorn Carlqvist Admin | * @param {Object} eventValuesStr - A JSON object of specific values for this particular eventType |
376 | 1 | Torbjorn Carlqvist Admin | ***********************************************************************************************/ |
377 | 23 | Torbjorn Carlqvist Admin | function eventNotificationReceived(processIdentifier,initiatingDevice,object,objectType,objectInstance,timeStampUTC,notificationClassInstance,priority,eventType,messageText,notifyType,ackRequired,fromState,toState,eventValuesStr){ |
378 | 22 | Torbjorn Carlqvist Admin | |
379 | 23 | Torbjorn Carlqvist Admin | var eventDeviceName = Controller.readProperty(initiatingDevice,device,initiatingDevice,objectName); |
380 | var ncObjectName = Controller.readProperty(initiatingDevice,ObjectType.notificationClass,notificationClassInstance,objectName); |
||
381 | var eventObjectName = Controller.readProperty(initiatingDevice,objectType,objectInstance,objectName); |
||
382 | 22 | Torbjorn Carlqvist Admin | |
383 | 23 | Torbjorn Carlqvist Admin | var summary = "Received " +eventType+" "+notifyType+" from "+eventDeviceName+" for object "+eventObjectName+" at "+new Date(timeStampUTC).toTimeString(); |
384 | |||
385 | print(summary); |
||
386 | |||
387 | print("Current state:"); |
||
388 | try{ |
||
389 | var eventValues = JSON.parse(eventValuesStr); |
||
390 | 22 | Torbjorn Carlqvist Admin | |
391 | |||
392 | 23 | Torbjorn Carlqvist Admin | for (var key in eventValues) { |
393 | if (eventValues.hasOwnProperty(key)) { |
||
394 | |||
395 | print(" - "+key + " " + eventValues[key]); |
||
396 | |||
397 | /*** Tip, enter code here to act on a specific key/value ***/ |
||
398 | |||
399 | } |
||
400 | } |
||
401 | 22 | Torbjorn Carlqvist Admin | |
402 | 23 | Torbjorn Carlqvist Admin | }catch(e){ |
403 | print("eventValuesStr not JSON!") |
||
404 | } |
||
405 | |||
406 | if (notifyType === 'ackNotification' ){ |
||
407 | var ackedstate = " - Acked state "+toState; |
||
408 | print(ackedstate); |
||
409 | summary = summary + ackedstate; |
||
410 | 22 | Torbjorn Carlqvist Admin | }else{ |
411 | 23 | Torbjorn Carlqvist Admin | var transistion = " - State changed from "+fromState+" to "+toState; |
412 | print(transistion); |
||
413 | summary = summary + transistion; |
||
414 | 22 | Torbjorn Carlqvist Admin | } |
415 | |||
416 | 23 | Torbjorn Carlqvist Admin | print(" - Priority "+priority); |
417 | print(" - Ack required "+ackRequired); |
||
418 | if ( messageText !== undefined && messageText !== "") |
||
419 | print(" - Message "+messageText); |
||
420 | print(" - Class "+ncObjectName) |
||
421 | |||
422 | //Due the the standard, a notifying device does not save un-acked |
||
423 | //transitions during reboot so it is best practise to make persistant. |
||
424 | Controller.printToUserLog(summary); |
||
425 | |||
426 | 22 | Torbjorn Carlqvist Admin | } |
427 | |||
428 | /******************************************************************************* |
||
429 | * Called when Change Of value Notification received from remote device |
||
430 | * In order to receive Change Of value notification the remote device must first |
||
431 | * be subscribed on the particular object instance. |
||
432 | * Eg. subscribe to Analog Input 0 on device 403 |
||
433 | * - Controller.remoteCOVSubscribe(403,0,0); |
||
434 | * It is also possible to subscribe on local objects and in case of a local |
||
435 | * notification the device argument is null. |
||
436 | * Eg. subscribe on local Binary Value 1 and no increment (null) |
||
437 | * - Controller.COVSubscribe(0,0,null); |
||
438 | * @param {Number} epoch - A timestamp (nb of sec since 1970 kind of timestamp. |
||
439 | * @param {Number} processId - COV process id used by the requester in this subscription |
||
440 | * @param {Number} deviceId - Remote device that sent the notification |
||
441 | * @param {Number} objectType - The source object of the event |
||
442 | * @param {Number} objectInstance - The instance of source object |
||
443 | * @param {Number} propertyId - The instance of source object* |
||
444 | * @param {String} value - The new value. |
||
445 | *******************************************************************************/ |
||
446 | function covNotificationReceived(epoch,processId,deviceId,objectType,objectInstance,propertyId,value){ |
||
447 | print("covNotificationReceived - "+ "Process: " + processId + " Device: " + deviceId + " ObjectType: " + |
||
448 | objectType+" ObjectInstance: " + objectInstance + " propertyId: " + propertyId + |
||
449 | " New Value: " + value + " Time: " + new Date(epoch*1000)); |
||
450 | |||
451 | } |
||
452 | |||
453 | |||
454 | /********************************************************** |
||
455 | * Called when the controller receives a HTTP GET request |
||
456 | * @param {String} resource - The REST resource |
||
457 | * @param {Object} params - The HTTP url parameters |
||
458 | *********************************************************/ |
||
459 | function HTTP_GET(resource,params){ |
||
460 | print(new Date().toISOString() + " HTTP GET - Resource: " + resource + " Params:" + params); |
||
461 | } |
||
462 | |||
463 | /********************************************************** |
||
464 | * Called when the controller receives a HTTP POST request |
||
465 | * @param {String} resource - The complete URI in the request |
||
466 | * @param {Object} payload - The HTTP header parameters |
||
467 | *********************************************************/ |
||
468 | function HTTP_POST(resource,payload){ |
||
469 | print("HTTP POST - Resource:" + resource + " Payload:" + payload); |
||
470 | } |
||
471 | |||
472 | /**************************************************************** |
||
473 | * Called when a Web Socket request is made from a Web Client. |
||
474 | * |
||
475 | * @param {String} context - The key of the page |
||
476 | * |
||
477 | * The context can be made up by three parts URI + APP + SESSION |
||
478 | * where URI is the only mandatory part. |
||
479 | * |
||
480 | * @param {String} payloadTxt - The data sent from the WS-client |
||
481 | *****************************************************************/ |
||
482 | function receiveFromWs(context,payloadTxt){ |
||
483 | print("WS Callback from context "+context +" payload:\n" + payloadTxt); |
||
484 | |||
485 | /** This is a snippet to listen on Web Page Demo Template **/ |
||
486 | /** Use it or remove it **/ |
||
487 | if ( context.indexOf("page-demo") > 0 ) { |
||
488 | |||
489 | try{ |
||
490 | var jsonObjPayload = JSON.parse(payloadTxt); |
||
491 | print(jsonObjPayload.msg); |
||
492 | print(jsonObjPayload.action); |
||
493 | |||
494 | //Answer to web page using incoming context |
||
495 | Controller.sendToWS(context,"Oh, Hi! I am a Web Socket request. Look for me in automation.js"); |
||
496 | |||
497 | } |
||
498 | catch(e){ |
||
499 | print("Err"+e); |
||
500 | } |
||
501 | |||
502 | } |
||
503 | } |
||
504 | |||
505 | /** |
||
506 | * Called when a BACnet object on this device changed. |
||
507 | * @param {type} objectType |
||
508 | * @param {type} objectInstance |
||
509 | * @param {type} propertyId |
||
510 | * @param {type} oldValue |
||
511 | * @param {type} newValue |
||
512 | * @returns {undefined} |
||
513 | */ |
||
514 | function localPropertyChanged(objectType,objectInstance,propertyId,oldValue,newValue){ |
||
515 | //print('property changed on '+objectType+':'+objectInstance+' for prop '+propertyId +' where old value is '+oldValue +' and new value is '+newValue); |
||
516 | } |
||
517 | |||
518 | /************************************************************************************************** |
||
519 | * Callback when this controller receives a I Am notification from a remote device on the network |
||
520 | * @param {Number} device - Remote device that says hello |
||
521 | * @param {String} mac - The BACnet mac address of the sending device |
||
522 | **************************************************************************************************/ |
||
523 | function iAmReceived(device,mac){ |
||
524 | //print("IAM received from device:" + device + " MAC:"+mac); |
||
525 | } |
||
526 | |||
527 | /************************************************************************************************** |
||
528 | * Callback when this controller receives a BACnet private message request |
||
529 | * @param {Number} sourceDeviceId - Remote device that speeks |
||
530 | * @param {String} messageClass - See BACnet standard for usage. Could be use as any string data |
||
531 | * @param {String} messagePriority - See BACnet standard for usage. Could be use as any string data |
||
532 | * @param {String} message - Send message data |
||
533 | **************************************************************************************************/ |
||
534 | function textMessageReceived(sourceDeviceId,messageClass,messagePriority,message){ |
||
535 | print("textMessageReceived:"+message); |
||
536 | } |
||
537 | |||
538 | /*********************************************************************************************** |
||
539 | * Called when the controller receives a write request from from a remote client |
||
540 | * on one of the local objects. |
||
541 | * @param {Number} objectType - The type of the object that is requested to be written |
||
542 | * @param {Number} objectInstance - The instance of the object that is requested to be written |
||
543 | * @param {Number} property - The property id that requested to be written |
||
544 | * @param {Number} priority - The priority of the value that is requested to be written |
||
545 | * @param {String} value - The new value |
||
546 | ***********************************************************************************************/ |
||
547 | function propertyWritten(objectType,objectInstance,property,priority,value){ |
||
548 | print("propertyWritten - ObjectType: "+objectType+" ObjectInstance: "+ objectInstance + " Property: "+ property + " Priority: "+ priority + " Value: "+value); |
||
549 | } |
||
550 | |||
551 | /*********************************************************************************************** |
||
552 | * Called when a file is put in file input directory |
||
553 | * The file input directory path is configured in setting page and is by default empty |
||
554 | * |
||
555 | * @param {String} fileName - The name of the file put in the file input directory |
||
556 | * @param {String} fileContent - The content of the file |
||
557 | * |
||
558 | * Note: There is special mapping for CSV file which are converted to JSON! |
||
559 | * Other file types are just received as is |
||
560 | ***********************************************************************************************/ |
||
561 | function receivedFile(fileName,fileContent){ |
||
562 | print("Received file "+fileName+ " with content "+ fileContent); |
||
563 | } |
||
564 | |||
565 | /*********************************************************************************************** |
||
566 | * Called receiving data on an activated serial port |
||
567 | * |
||
568 | * Note, see Controller.setupSerialPort(..) for activate a serial port |
||
569 | * |
||
570 | * @param {String} port - Wich port the data comes from |
||
571 | * @param {String} payload - The data |
||
572 | * |
||
573 | ***********************************************************************************************/ |
||
574 | function onSerialReceive(port, payload){ |
||
575 | |||
576 | print("Serial data received on port: "+port+" data: "+payload); |
||
577 | } |
||
578 | |||
579 | |||
580 | /************************************************************************** |
||
581 | * This callback catches unexpected runtime errors like timeouts when |
||
582 | * writing or subscribing to a remote device currently absent. |
||
583 | * @param {String} type - Type or source of exception |
||
584 | * @param {String} message - Short description of the issue in plain text |
||
585 | * @param {String} details - Optional information in JSON format |
||
586 | **************************************************************************/ |
||
587 | function exceptionCatch(type,message,details){ |
||
588 | print("Exception catched, type:"+type+" message:" + message + " details:" + details ); |
||
589 | } |
||
590 | |||
591 | /** |
||
592 | * When supported by the platform and enabled in the setting "beacon Station under Bluetooth" |
||
593 | * this method is invoked with advertisment from all Bluetooth LE devices nerby |
||
594 | * |
||
595 | * @param {String} mac - The sending Bluetooth device MAC adress |
||
596 | * @param {String} rssi - The signal strengh of the sending beacon |
||
597 | * @param {String} bt_payload - The beacon data |
||
598 | */ |
||
599 | function onBTBeaconAdvertising(mac,rssi,bt_payload){ |
||
600 | |||
601 | //Example of whitelist filter |
||
602 | if( mac.includes("38FE") || mac.includes("CD8E")){ |
||
603 | |||
604 | print("Beacon adv from mac: "+ mac + " rssi: "+rssi+" data:"+bt_payload); |
||
605 | |||
606 | //Here you can parse the payload from the beacon as you wish |
||
607 | //If the beacon is a Ruuvi, DTXr has a built in javascript library for the format 5 |
||
608 | //See documentation on DTXr wiki |
||
609 | //https://collab.davitor.com/redmine/projects/dtxr/wiki |
||
610 | //More info on Ruuvi format and how to parse here |
||
611 | //https://ruuvi.com/custom-ruuvi-data-format-in-a-day/ |
||
612 | |||
613 | |||
614 | } |
||
615 | } |
||
616 | |||
617 | /** |
||
618 | * Received an MQTT publish request |
||
619 | * @param {type} topic |
||
620 | * @param {type} payload |
||
621 | */ |
||
622 | function MQTTOnPublish(topic,payload){ |
||
623 | print("MQTT client published " + payload + " on topic " + topic); |
||
624 | } |
||
625 | |||
626 | /** |
||
627 | * Received a web socket client text response |
||
628 | * @param {type} text |
||
629 | */ |
||
630 | 1 | Torbjorn Carlqvist Admin | function WebsocketOnClientReceiveText(text){ |
631 | print("WebsocketOnClientReceiveText: "+text); |
||
632 | } |
||
633 | </code></pre> |