Project

General

Profile

Javascript » History » Version 22

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