Javascript » History » Version 26
Torbjorn Carlqvist Admin, 01/12/2023 09:35 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 | 25 | Torbjorn Carlqvist Admin | |
| 9 | 26 | Torbjorn Carlqvist Admin | +NOTE, the below spec is 100% compatible with version 3.1.7. Ask DAVITOR for compatibility with previous versions or update your device.+ |
| 10 | 25 | Torbjorn Carlqvist Admin | |
| 11 | 11 | Torbjorn Carlqvist Admin | --- |
| 12 | |||
| 13 | 6 | Torbjorn Carlqvist Admin | h2. Commands |
| 14 | |||
| 15 | 19 | Torbjorn Carlqvist Admin | <pre><code class="javascript"> |
| 16 | 21 | Torbjorn Carlqvist Admin | //Set this to THIS device id. |
| 17 | //The var is used in commands below for convinience. |
||
| 18 | var gThisDeviceId = 123456; |
||
| 19 | //Set this to A REMOTE device id on your network. |
||
| 20 | //The var is used in commands below for convinience. |
||
| 21 | var gRemoteDeviceId = 121212; |
||
| 22 | |||
| 23 | /** LOG/DEBUG **/ |
||
| 24 | |||
| 25 | //Prints to console log window as well as autmation.log |
||
| 26 | //Note that automation.js is also written to by various services in DTX by |
||
| 27 | //default, not only what you do with print() in your code. |
||
| 28 | //Consider this as a volatile log where you debug and then clear from time to time. |
||
| 29 | //10Mbyte is max then it will rollover to time-stamped zip file and automation.js is cleared. |
||
| 30 | print("hello"); |
||
| 31 | |||
| 32 | //Prints to automation_user.log |
||
| 33 | //This statement is the only source for loggin in this file. |
||
| 34 | //Consider this to be a persistant log of important process matters. |
||
| 35 | //10Mbyte is max then it will rollover to time-stamped zip file anf automation-user.js is cleared. |
||
| 36 | Controller.printToUserLog("hello user log"); |
||
| 37 | |||
| 38 | /** BACnet related **/ |
||
| 39 | |||
| 40 | //Translation helper for BACnet object ID->NAME |
||
| 41 | //Many even arguments are enumerated where theese function can help |
||
| 42 | print(getObjectTypeById(4)); //Binary Output |
||
| 43 | print(getPropertyTypeById(85)); //presentValue |
||
| 44 | 1 | Torbjorn Carlqvist Admin | |
| 45 | 21 | Torbjorn Carlqvist Admin | // *** Write a value to an object property *** |
| 46 | Controller.writeProperty(gThisDeviceId,analogValue,0,presentValue,priority_1,active); |
||
| 47 | Controller.writeProperty(gRemoteDeviceId,analogValue,0,presentValue,priority_1,active); |
||
| 48 | |||
| 49 | // *** Read a value from a property. *** |
||
| 50 | //Will return both primitiv and constructed (JSON) values |
||
| 51 | |||
| 52 | //Primitive |
||
| 53 | print(Controller.readProperty(gThisDeviceId,analogValue,0,presentValue)); |
||
| 54 | print(Controller.readProperty(gRemoteDeviceId,analogValue,0,presentValue)); |
||
| 55 | |||
| 56 | //Constructed (always JSON format from complex values) |
||
| 57 | //A priorityArray property is one example of constructed result |
||
| 58 | print(Controller.readProperty(gThisDeviceId,analogValue,0,statusFlags)); |
||
| 59 | |||
| 60 | // *** COV Subscribtion *** |
||
| 61 | |||
| 62 | //With auto incremented process id, sensitivity (increment) of 1 (analog values) and subscription lifetime of 300s |
||
| 63 | Controller.COVSubscribe(covProcIncr,gRemoteDeviceId,analogValue,instance_0,noCovConfirmation,presentValue,1 /*sensitivity*/,300 /*lifetime (s)*/); |
||
| 64 | |||
| 65 | //With fixed process id 123, sensitivity (increment) no sesnitivity (binary values) and subscription lifetime of 300s |
||
| 66 | Controller.COVSubscribe(123,gRemoteDeviceId,analogValue,instance_0,noCovConfirmation,presentValue,null,300 /*lifetime (s)*/); |
||
| 67 | |||
| 68 | //UN-Subscribe with specific process id 10 |
||
| 69 | Controller.COVSubscribe(123,gRemoteDeviceId,analogValue,instance_0,null,presentValue,defaultIncrement,null); |
||
| 70 | |||
| 71 | // *** Intrinsic Reporting (Alarms and Events) *** |
||
| 72 | 1 | Torbjorn Carlqvist Admin | |
| 73 | 21 | Torbjorn Carlqvist Admin | //Remote Event Subscribe |
| 74 | Controller.eventSubscribe(gRemoteDeviceId/*device id*/,instance_0/*Notification Class*/); |
||
| 75 | |||
| 76 | //Enable event/alarm reporting on object |
||
| 77 | Controller.enableIntrinsicReporting(0/*NotificationClass*/,3/*delay*/,3/*delayNormal*/,analogValue,instance_0,notifyTypeEvent); |
||
| 78 | |||
| 79 | Controller.writeProperty(analogValue,instance_0,presentValue,priority_1,50); |
||
| 80 | //TextMessage |
||
| 81 | Controller.sendTextMessage(gThisDeviceId,"SOME_TYPE_OF_MSG","hello myself, what's up?"); |
||
| 82 | |||
| 83 | //Acknowledge alarm and events |
||
| 84 | Controller.acknowledgeAlarm(gThisDeviceId,analogValue,instance_0,processIdZero, |
||
| 85 | ackNormal,1584383651150,"Toca",new Date().getTime()); |
||
| 86 | |||
| 87 | //Issue an alert for a specific object via an Alert Enrollment Object |
||
| 88 | //The recipients in the notification class connected to the shosen alert enrollment object will receive the alert |
||
| 89 | var alertEnrollmentObjectInstance = 0; |
||
| 90 | var propretaryEventType = 666; |
||
| 91 | Controller.issueAlert(alertEnrollmentObjectInstance,analogValue,0,"To high!",propretaryEventType); |
||
| 92 | |||
| 93 | Controller.getEnrollmentSummary(gThisDeviceId); |
||
| 94 | |||
| 95 | //Send event notif local or remote nodes |
||
| 96 | //DeviceId,NotificationClass,AckRequired,Message |
||
| 97 | Controller.sendNotification(gThisDeviceId,0,1,"Coffe anyone?"); |
||
| 98 | |||
| 99 | //Get all alarms for a specific device. Return JSON |
||
| 100 | resp = print(Controller.getAlarmSummary(gThisDeviceId)); |
||
| 101 | 1 | Torbjorn Carlqvist Admin | |
| 102 | 21 | Torbjorn Carlqvist Admin | //Get all events for a specific device. Return JSON |
| 103 | resp = print(Controller.getEventSummary(gThisDeviceId)); |
||
| 104 | 1 | Torbjorn Carlqvist Admin | |
| 105 | 21 | Torbjorn Carlqvist Admin | // *** Special Object Types *** // |
| 106 | |||
| 107 | //Read a range of datapoints from a TrendLog object |
||
| 108 | //The response is JSON with an array of value/timestamp |
||
| 109 | Controller.readRange(gThisDeviceId,trendLogMultiple,0); |
||
| 110 | 1 | Torbjorn Carlqvist Admin | |
| 111 | 21 | Torbjorn Carlqvist Admin | // *** HTTP REST and Web Socket *** |
| 112 | |||
| 113 | //HTTP GET Request. Returns respons as string |
||
| 114 | resp = Controller.HTTP_GET('https://httpbin.org','get','Accept:application/json|Content-Type:application/json','myparam=hello'); |
||
| 115 | |||
| 116 | //HTTP POST(also PUT and PATCH) Request. Return response as string |
||
| 117 | resp = Controller.HTTP_POST('https://httpbin.org/post' |
||
| 118 | ,'Accept:application/json|Content-Type:application/json' |
||
| 119 | ,'myparam=hello' |
||
| 120 | ,'any payload string data'); |
||
| 121 | |||
| 122 | //Web socket call to any webpage in the project file |
||
| 123 | //This require that the page has loaded the Ws.js import. |
||
| 124 | //Se HTTP Websocket template from the project tree sub menu |
||
| 125 | Controller.sendToWS("mypage","Hello My Page this is a payload"); |
||
| 126 | |||
| 127 | //Connect to a Web Socket |
||
| 128 | //DTX has a built in single web socket client. |
||
| 129 | //Connect |
||
| 130 | Controller.connectWebSocket("wss://any.websocket.host"); |
||
| 131 | //Send a message once connection is established |
||
| 132 | Controller.sendWebSocketText("Hello"); |
||
| 133 | |||
| 134 | // *** SQL relational database access *** |
||
| 135 | |||
| 136 | //Note, SQL db is not embedded so JDBC config is made in settings in advance. |
||
| 137 | //Only PostgresSQL is supported for the moment! |
||
| 138 | |||
| 139 | //Simple query. Result (if any) will always be JSON! |
||
| 140 | print(Controller.sqlExecuteQuery("select * from anytable")); |
||
| 141 | |||
| 142 | //Inserts and updates are preferably solved with functions or procedures on |
||
| 143 | //the databas side. The CALL statement can then be utilized: |
||
| 144 | Controller.sqlExecuteQuery("CALL upsert_anytable("+name+",'"+age+"')"); |
||
| 145 | |||
| 146 | //But of course a simple insert can also be sent... |
||
| 147 | print(Controller.sqlExecuteQuery("insert into anytable values('kalle','13')")); |
||
| 148 | |||
| 149 | // *** Timers and Schedulers *** |
||
| 150 | 1 | Torbjorn Carlqvist Admin | |
| 151 | 21 | Torbjorn Carlqvist Admin | //Show all current jobs (including system jobs) |
| 152 | Controller.schedulerSummary(); |
||
| 153 | |||
| 154 | //Pause all jobs |
||
| 155 | Controller.pauseAllJobs(); |
||
| 156 | |||
| 157 | //Pause a specific job |
||
| 158 | Controller.pauseJob("JobA"); |
||
| 159 | |||
| 160 | //Resume all jobs |
||
| 161 | Controller.resumeAllJobs(); |
||
| 162 | |||
| 163 | //Resume a specific job |
||
| 164 | Controller.resumeJob("JobA"); |
||
| 165 | |||
| 166 | //Start job |
||
| 167 | //Eg. executes function myCallbackFunction() with argument "df" after 10 seconds |
||
| 168 | Controller.startJob('Job1',10,'myCallbackFunction("df")'); |
||
| 169 | //Eg. executes function myCallbackFunction() repeatedly every minute |
||
| 170 | //with a start delay of 5 seconds |
||
| 171 | Controller.startJob('Job2',5,60,'myCallbackFunction'); |
||
| 172 | |||
| 173 | //Eg. start a CRON job that executes myCallbackFunction |
||
| 174 | //at 00:10 AM (10 minute past midnight) every day |
||
| 175 | Controller.startCronJob("Job3",'0 10 0 ? * * *','myCallbackFunction'); |
||
| 176 | //Note: CRON can be difficult to construct. |
||
| 177 | //Use the below link to both crete and also verify your CRON strings. |
||
| 178 | //https://www.freeformatter.com/cron-expression-generator-quartz.html |
||
| 179 | |||
| 180 | //Cancel a job by using the name provided above |
||
| 181 | Controller.cancelJob("Job3"); |
||
| 182 | |||
| 183 | //Cancel all jobs |
||
| 184 | Controller.cancelAllJobs(); |
||
| 185 | |||
| 186 | //Cancel a specific jobs |
||
| 187 | Controller.cancelJob("JobG"); |
||
| 188 | 1 | Torbjorn Carlqvist Admin | |
| 189 | 21 | Torbjorn Carlqvist Admin | //This is a special function where you can schedule the execution of |
| 190 | //a code snippet. |
||
| 191 | //Arg1: Som job identifier - To use when pause/cancel the job if neccesary. |
||
| 192 | //Arg2: start delay (s) - Time until first exec |
||
| 193 | //Arg3: period(s) - Time between exec, set to 0 if no repetition is required/wanted. |
||
| 194 | //Arg4: repeates - Number of repeates, null if infinit, 0 if no repeat |
||
| 195 | //Arg5: code - Any Javascript |
||
| 196 | Controller.scheduleExecution("wait05",5,0,0,"print('print once in 5 sec');"); |
||
| 197 | 1 | Torbjorn Carlqvist Admin | |
| 198 | 21 | Torbjorn Carlqvist Admin | // *** MISC *** |
| 199 | |||
| 200 | //Send an email. Note, needs smtp-server config first |
||
| 201 | Controller.SendEmail("torbjorn.carlqvist@davitor.com","anysubject","some body"); |
||
| 202 | |||
| 203 | // *** Embedded JSON storage *** |
||
| 204 | |||
| 205 | //Perfect to use when automation settings, states, structures etc must be persisted and |
||
| 206 | //the use of an external SQL database is unnecessary |
||
| 207 | |||
| 208 | //Push a string to spcified queue (queue will be created if not exist) |
||
| 209 | //This queue is persistant during reboot of the evice |
||
| 210 | //All queues and records are stored in the collection "jsonstore.json" which can be found in project folder |
||
| 211 | Controller.JSONPush("toca","msg5"); |
||
| 212 | //Pop a string from the specified queue. FIFO! |
||
| 213 | //Returns null if no strings found |
||
| 214 | print(Controller.JSONPop("toca")); |
||
| 215 | 1 | Torbjorn Carlqvist Admin | |
| 216 | 21 | Torbjorn Carlqvist Admin | print(Controller.JSONPersist("nisse")); |
| 217 | print(Controller.JSONPersist("1588058754445","palle")); |
||
| 218 | |||
| 219 | print(Controller.JSONRestore("1588058754445")); |
||
| 220 | |||
| 221 | print(Controller.JSONBrowse("toca")); |
||
| 222 | |||
| 223 | //Change name on multiple local objects |
||
| 224 | //This can be used when a group of objects need to have save name prefix. |
||
| 225 | //eg. when a sensor has multiple object and you want them to share same sensor name. |
||
| 226 | Controller.updateLocalObjectNames("TestBI","newname"); |
||
| 227 | |||
| 228 | //This method should be used when javascript forms a link between |
||
| 229 | //an external interaface and the object stack. |
||
| 230 | //Typically when a button on a HMI should update an binaryInput or |
||
| 231 | //a reception of a BLE Beacon should update an analogInput. |
||
| 232 | //This method will create an object if no object exists with same profilName property |
||
| 233 | Controller.createOrUpdateLocalObject(analogInput,null,"MyObjectName",123); |
||
| 234 | |||
| 235 | //As an addition use this function to control the reliability of the obejct in real time. |
||
| 236 | //This will create events and alarms accordingly of intrinsic reporting is enanbled. |
||
| 237 | Controller.setLocalObjectReliability(binaryOutput,0,'shorted-loop'); |
||
| 238 | Controller.setLocalObjectReliability(binaryOutput,0,'no-fault-detected'); |
||
| 239 | |||
| 240 | //Yet another addition is this function to set the overridden flag on local objects. |
||
| 241 | //The meaning of this flag is to tell BACnet that this physical point is not |
||
| 242 | //longer reliable or commandable. |
||
| 243 | Controller.setLocalObjectOverridden(binaryOutput,0,true); |
||
| 244 | Controller.setLocalObjectOverridden(binaryOutput,0,false); |
||
| 245 | |||
| 246 | // *** File access ***/ |
||
| 247 | |||
| 248 | //Basic file R/W/List for files in project folder (and sub folders) |
||
| 249 | Controller.writeFile("file_rw_test.txt","Hello file handling!"); |
||
| 250 | print(Controller.readFile("file_rw_test.txt")); |
||
| 251 | print(Controller.listFiles(".txt",null)); |
||
| 252 | print(Controller.listFiles(".json","mysubfolder")); |
||
| 253 | print(Controller.removeFiles(".txt",null)); |
||
| 254 | |||
| 255 | // *** OS operations ***/ |
||
| 256 | |||
| 257 | //Run commands on host operatice system |
||
| 258 | //Result is JSON string |
||
| 259 | //The exit_code tells if successful or not. |
||
| 260 | //There is a built in timeout if you accedently start a job that does not |
||
| 261 | //stop of it's own. Like doing unlimited ping on Linux |
||
| 262 | //No, there is no way to stop a command with Ctrl-C from JS. |
||
| 263 | //Note, the process is running in foreground so if DTX dies the process dies too. |
||
| 264 | print(Controller.execCommand("ping -n 3 google.com")); |
||
| 265 | |||
| 266 | // *** Serial Ports ***/ |
||
| 267 | |||
| 268 | //List all connected serial ports. The response is JSON and can tell a lot |
||
| 269 | //about the serial port. For example in which USB socket it is connected. |
||
| 270 | print(Controller.listSerialPorts()); |
||
| 271 | |||
| 272 | //Connect to a serial port (multiple connection is allowed) |
||
| 273 | //Use the serial port name from the response from listSerialPorts() above. |
||
| 274 | //As argument form a JSON according to specification. |
||
| 275 | //Example of setting up a serial connection to ttyACM0 that handles |
||
| 276 | //delimited responses with a "Return(0d)" at the END with a speed of 115200baud |
||
| 277 | //Note that if a connection already occurs in this name it will be closed automatically |
||
| 278 | Controller.setupSerialPort("ttyACM0",'{"msgDelim":true,"baudrate":115200,"delimPattern":"0d","delimPosition":"end"}'); |
||
| 279 | |||
| 280 | //Send ASCII data to the connected port |
||
| 281 | Controller.writeSerialAscii("ttyACM0","hello"); |
||
| 282 | |||
| 283 | //Send HEX data to the serial port |
||
| 284 | Controller.writeSerialHex("ttyACM0","03"); //Eg. Ctrl-C in HEX |
||
| 285 | |||
| 286 | //Close serial port |
||
| 287 | Controller.closeSerialPort("ttyACM0"); |
||
| 288 | |||
| 289 | //NOTE: all received serial data enters the event callback "onSerialReceive" |
||
| 290 | |||
| 291 | /*** MODBUS ***/ |
||
| 292 | |||
| 293 | /* Modbus TCP */ |
||
| 294 | |||
| 295 | //If needed, use this to simulate a slave on THIS device for test purpose. |
||
| 296 | //Will setup a demo image of regs and coils |
||
| 297 | Controller.modbusTCPCreateSlave(); |
||
| 298 | |||
| 299 | //Read coils (true/false) |
||
| 300 | //Args: Slave IP, Slave Port, Start Addr, Count |
||
| 301 | //Return: JSON Array with result |
||
| 302 | print(Controller.modbusTCPReadCoils("localhost",502,1,1)); |
||
| 303 | 18 | Torbjorn Carlqvist Admin | |
| 304 | 21 | Torbjorn Carlqvist Admin | //Reading input discretes (true/false) |
| 305 | //Args: Slave IP, Slave Port, Start Addr, Count |
||
| 306 | //Return: JSON Array with result |
||
| 307 | print(Controller.modbusTCPReadInputDiscretes("localhost",502,1,5)); |
||
| 308 | |||
| 309 | //Reading input registers (Analog Inputs) |
||
| 310 | //Can be either signed or unsigned 16-bit values. |
||
| 311 | //Args: Slave IP, Slave Port, Start Addr, Count |
||
| 312 | //Return: JSON Array with result |
||
| 313 | print(Controller.modbusTCPReadInputRegisters("localhost",502,1,5)); |
||
| 314 | |||
| 315 | //Reading holding registers (Analog Outputs) |
||
| 316 | //Can be either signed or unsigned 16-bit values. |
||
| 317 | //Args: Slave IP, Slave Port, Start Addr, Count |
||
| 318 | //Return: JSON Array with result |
||
| 319 | print(Controller.modbusTCPReadHoldingRegisters("localhost",502,1,5)); |
||
| 320 | 14 | Torbjorn Carlqvist Admin | |
| 321 | 21 | Torbjorn Carlqvist Admin | //Write to coil (!CAUTION!) |
| 322 | //Note, always returns null |
||
| 323 | //Args: Slave IP, Slave Port, Addr, Status (true=On/1, false=Off/0) |
||
| 324 | Controller.modbusTCPWriteCoil("localhost",502,1,false); |
||
| 325 | |||
| 326 | |||
| 327 | /* Modbus Serial */ |
||
| 328 | //Note, setting null as port settings defaults to 9600/8N1 |
||
| 329 | |||
| 330 | //A mock-up test slave for serial modbus |
||
| 331 | //Args: Port, Port Settings, RTU |
||
| 332 | Controller.modbusSerialCreateSlave("COM1",null,false); |
||
| 333 | //Writing to a MODBUS slave coil via Serial RTU |
||
| 334 | //Args: Port, Port Settings,RTU,reg address, value/state |
||
| 335 | Controller.modbusSerialWriteCoil("COM2",null,false,2,true); |
||
| 336 | //Reading from a MODBUS slave coil via Serial RTU |
||
| 337 | //Args: Port, Port Settings,RTU,reg address |
||
| 338 | Controller.modbusSerialReadCoils("COM2",null,false,1,2); |
||
| 339 | |||
| 340 | /*** Controller management ***/ |
||
| 341 | |||
| 342 | //Running reInit() will completly clear the JS-engine, stop all jobs and |
||
| 343 | //re-actiavate the code and finally call the init() method. |
||
| 344 | Controller.reInit(); |
||
| 345 | 1 | Torbjorn Carlqvist Admin | </code></pre> |
| 346 | |||
| 347 | |||
| 348 | h2. Events |
||
| 349 | |||
| 350 | h3. *eventNotificationReceived* - Called when an intrinsic report notification is received. |
||
| 351 | |||
| 352 | <pre><code class="javascript"> |
||
| 353 | 22 | Torbjorn Carlqvist Admin | /** |
| 354 | * Called when controller starts. Good place to do init stuff |
||
| 355 | */ |
||
| 356 | function init(){ |
||
| 357 | print("init!"); |
||
| 358 | |||
| 359 | } |
||
| 360 | |||
| 361 | |||
| 362 | 1 | Torbjorn Carlqvist Admin | /*********************************************************************************************** |
| 363 | 23 | Torbjorn Carlqvist Admin | * Called when the controller receives a notification (intrinsic reporting) from this or another device |
| 364 | * @param {processIdentifier} Can be used to process events/alarms different consumed. Users choice. |
||
| 365 | * @param {Number} initiatingDevice - The device ID that send the event and the device where the triggered object belongs |
||
| 366 | * @param {String} object - A convinient string to describe objectype:instance in text |
||
| 367 | * @param {Number} objectType - The source object of the event |
||
| 368 | 1 | Torbjorn Carlqvist Admin | * @param {Number} objectInstance - The instance of source object |
| 369 | 23 | Torbjorn Carlqvist Admin | * @param {Number} timeStampUTC - EPOC type of timestamp where the event/alarm trigger fired |
| 370 | * @param {Number} notificationClassInstance - An instance pointer to the connected class |
||
| 371 | * @param {Number} priority - Priority of this event |
||
| 372 | * @param {Number} eventType - The type of event received. Eg. 'outOfRange' |
||
| 373 | * @param {String} messageText - Free text that can be used describing the event |
||
| 374 | * @param {String} notifyType - Type of notification. Can be 'alarm' or 'event' |
||
| 375 | * @param {Boolean} ackRequired - Tell wether this event/alarm needs acknowledgment or not |
||
| 376 | 1 | Torbjorn Carlqvist Admin | * @param {String} fromState - The previous state |
| 377 | * @param {String} toState - The current state after the change |
||
| 378 | 23 | Torbjorn Carlqvist Admin | * @param {Object} eventValuesStr - A JSON object of specific values for this particular eventType |
| 379 | 1 | Torbjorn Carlqvist Admin | ***********************************************************************************************/ |
| 380 | 23 | Torbjorn Carlqvist Admin | function eventNotificationReceived(processIdentifier,initiatingDevice,object,objectType,objectInstance,timeStampUTC,notificationClassInstance,priority,eventType,messageText,notifyType,ackRequired,fromState,toState,eventValuesStr){ |
| 381 | 22 | Torbjorn Carlqvist Admin | |
| 382 | 23 | Torbjorn Carlqvist Admin | var eventDeviceName = Controller.readProperty(initiatingDevice,device,initiatingDevice,objectName); |
| 383 | var ncObjectName = Controller.readProperty(initiatingDevice,ObjectType.notificationClass,notificationClassInstance,objectName); |
||
| 384 | var eventObjectName = Controller.readProperty(initiatingDevice,objectType,objectInstance,objectName); |
||
| 385 | 22 | Torbjorn Carlqvist Admin | |
| 386 | 23 | Torbjorn Carlqvist Admin | var summary = "Received " +eventType+" "+notifyType+" from "+eventDeviceName+" for object "+eventObjectName+" at "+new Date(timeStampUTC).toTimeString(); |
| 387 | |||
| 388 | print(summary); |
||
| 389 | |||
| 390 | print("Current state:"); |
||
| 391 | try{ |
||
| 392 | var eventValues = JSON.parse(eventValuesStr); |
||
| 393 | 22 | Torbjorn Carlqvist Admin | |
| 394 | |||
| 395 | 23 | Torbjorn Carlqvist Admin | for (var key in eventValues) { |
| 396 | if (eventValues.hasOwnProperty(key)) { |
||
| 397 | |||
| 398 | print(" - "+key + " " + eventValues[key]); |
||
| 399 | |||
| 400 | /*** Tip, enter code here to act on a specific key/value ***/ |
||
| 401 | |||
| 402 | } |
||
| 403 | } |
||
| 404 | 22 | Torbjorn Carlqvist Admin | |
| 405 | 23 | Torbjorn Carlqvist Admin | }catch(e){ |
| 406 | print("eventValuesStr not JSON!") |
||
| 407 | } |
||
| 408 | |||
| 409 | if (notifyType === 'ackNotification' ){ |
||
| 410 | var ackedstate = " - Acked state "+toState; |
||
| 411 | print(ackedstate); |
||
| 412 | summary = summary + ackedstate; |
||
| 413 | 22 | Torbjorn Carlqvist Admin | }else{ |
| 414 | 23 | Torbjorn Carlqvist Admin | var transistion = " - State changed from "+fromState+" to "+toState; |
| 415 | print(transistion); |
||
| 416 | summary = summary + transistion; |
||
| 417 | 22 | Torbjorn Carlqvist Admin | } |
| 418 | |||
| 419 | 23 | Torbjorn Carlqvist Admin | print(" - Priority "+priority); |
| 420 | print(" - Ack required "+ackRequired); |
||
| 421 | if ( messageText !== undefined && messageText !== "") |
||
| 422 | print(" - Message "+messageText); |
||
| 423 | print(" - Class "+ncObjectName) |
||
| 424 | |||
| 425 | 24 | Torbjorn Carlqvist Admin | //Due to the standard, a notifying device does not save un-acked notifs |
| 426 | //transitions during reboot so it is best practise to make persistant on |
||
| 427 | //the receiver side. |
||
| 428 | 23 | Torbjorn Carlqvist Admin | Controller.printToUserLog(summary); |
| 429 | |||
| 430 | 22 | Torbjorn Carlqvist Admin | } |
| 431 | |||
| 432 | /******************************************************************************* |
||
| 433 | * Called when Change Of value Notification received from remote device |
||
| 434 | * In order to receive Change Of value notification the remote device must first |
||
| 435 | * be subscribed on the particular object instance. |
||
| 436 | * Eg. subscribe to Analog Input 0 on device 403 |
||
| 437 | * - Controller.remoteCOVSubscribe(403,0,0); |
||
| 438 | * It is also possible to subscribe on local objects and in case of a local |
||
| 439 | * notification the device argument is null. |
||
| 440 | * Eg. subscribe on local Binary Value 1 and no increment (null) |
||
| 441 | * - Controller.COVSubscribe(0,0,null); |
||
| 442 | * @param {Number} epoch - A timestamp (nb of sec since 1970 kind of timestamp. |
||
| 443 | * @param {Number} processId - COV process id used by the requester in this subscription |
||
| 444 | * @param {Number} deviceId - Remote device that sent the notification |
||
| 445 | * @param {Number} objectType - The source object of the event |
||
| 446 | * @param {Number} objectInstance - The instance of source object |
||
| 447 | * @param {Number} propertyId - The instance of source object* |
||
| 448 | * @param {String} value - The new value. |
||
| 449 | *******************************************************************************/ |
||
| 450 | function covNotificationReceived(epoch,processId,deviceId,objectType,objectInstance,propertyId,value){ |
||
| 451 | print("covNotificationReceived - "+ "Process: " + processId + " Device: " + deviceId + " ObjectType: " + |
||
| 452 | objectType+" ObjectInstance: " + objectInstance + " propertyId: " + propertyId + |
||
| 453 | " New Value: " + value + " Time: " + new Date(epoch*1000)); |
||
| 454 | |||
| 455 | } |
||
| 456 | |||
| 457 | |||
| 458 | /********************************************************** |
||
| 459 | * Called when the controller receives a HTTP GET request |
||
| 460 | * @param {String} resource - The REST resource |
||
| 461 | * @param {Object} params - The HTTP url parameters |
||
| 462 | *********************************************************/ |
||
| 463 | function HTTP_GET(resource,params){ |
||
| 464 | print(new Date().toISOString() + " HTTP GET - Resource: " + resource + " Params:" + params); |
||
| 465 | } |
||
| 466 | |||
| 467 | /********************************************************** |
||
| 468 | * Called when the controller receives a HTTP POST request |
||
| 469 | * @param {String} resource - The complete URI in the request |
||
| 470 | * @param {Object} payload - The HTTP header parameters |
||
| 471 | *********************************************************/ |
||
| 472 | function HTTP_POST(resource,payload){ |
||
| 473 | print("HTTP POST - Resource:" + resource + " Payload:" + payload); |
||
| 474 | } |
||
| 475 | |||
| 476 | /**************************************************************** |
||
| 477 | * Called when a Web Socket request is made from a Web Client. |
||
| 478 | * |
||
| 479 | * @param {String} context - The key of the page |
||
| 480 | * |
||
| 481 | * The context can be made up by three parts URI + APP + SESSION |
||
| 482 | * where URI is the only mandatory part. |
||
| 483 | * |
||
| 484 | * @param {String} payloadTxt - The data sent from the WS-client |
||
| 485 | *****************************************************************/ |
||
| 486 | function receiveFromWs(context,payloadTxt){ |
||
| 487 | print("WS Callback from context "+context +" payload:\n" + payloadTxt); |
||
| 488 | |||
| 489 | /** This is a snippet to listen on Web Page Demo Template **/ |
||
| 490 | /** Use it or remove it **/ |
||
| 491 | if ( context.indexOf("page-demo") > 0 ) { |
||
| 492 | |||
| 493 | try{ |
||
| 494 | var jsonObjPayload = JSON.parse(payloadTxt); |
||
| 495 | print(jsonObjPayload.msg); |
||
| 496 | print(jsonObjPayload.action); |
||
| 497 | |||
| 498 | //Answer to web page using incoming context |
||
| 499 | Controller.sendToWS(context,"Oh, Hi! I am a Web Socket request. Look for me in automation.js"); |
||
| 500 | |||
| 501 | } |
||
| 502 | catch(e){ |
||
| 503 | print("Err"+e); |
||
| 504 | } |
||
| 505 | |||
| 506 | } |
||
| 507 | } |
||
| 508 | |||
| 509 | /** |
||
| 510 | * Called when a BACnet object on this device changed. |
||
| 511 | * @param {type} objectType |
||
| 512 | * @param {type} objectInstance |
||
| 513 | * @param {type} propertyId |
||
| 514 | * @param {type} oldValue |
||
| 515 | * @param {type} newValue |
||
| 516 | * @returns {undefined} |
||
| 517 | */ |
||
| 518 | function localPropertyChanged(objectType,objectInstance,propertyId,oldValue,newValue){ |
||
| 519 | //print('property changed on '+objectType+':'+objectInstance+' for prop '+propertyId +' where old value is '+oldValue +' and new value is '+newValue); |
||
| 520 | } |
||
| 521 | |||
| 522 | /************************************************************************************************** |
||
| 523 | * Callback when this controller receives a I Am notification from a remote device on the network |
||
| 524 | * @param {Number} device - Remote device that says hello |
||
| 525 | * @param {String} mac - The BACnet mac address of the sending device |
||
| 526 | **************************************************************************************************/ |
||
| 527 | function iAmReceived(device,mac){ |
||
| 528 | //print("IAM received from device:" + device + " MAC:"+mac); |
||
| 529 | } |
||
| 530 | |||
| 531 | /************************************************************************************************** |
||
| 532 | * Callback when this controller receives a BACnet private message request |
||
| 533 | * @param {Number} sourceDeviceId - Remote device that speeks |
||
| 534 | * @param {String} messageClass - See BACnet standard for usage. Could be use as any string data |
||
| 535 | * @param {String} messagePriority - See BACnet standard for usage. Could be use as any string data |
||
| 536 | * @param {String} message - Send message data |
||
| 537 | **************************************************************************************************/ |
||
| 538 | function textMessageReceived(sourceDeviceId,messageClass,messagePriority,message){ |
||
| 539 | print("textMessageReceived:"+message); |
||
| 540 | } |
||
| 541 | |||
| 542 | /*********************************************************************************************** |
||
| 543 | * Called when the controller receives a write request from from a remote client |
||
| 544 | * on one of the local objects. |
||
| 545 | * @param {Number} objectType - The type of the object that is requested to be written |
||
| 546 | * @param {Number} objectInstance - The instance of the object that is requested to be written |
||
| 547 | * @param {Number} property - The property id that requested to be written |
||
| 548 | * @param {Number} priority - The priority of the value that is requested to be written |
||
| 549 | * @param {String} value - The new value |
||
| 550 | ***********************************************************************************************/ |
||
| 551 | function propertyWritten(objectType,objectInstance,property,priority,value){ |
||
| 552 | print("propertyWritten - ObjectType: "+objectType+" ObjectInstance: "+ objectInstance + " Property: "+ property + " Priority: "+ priority + " Value: "+value); |
||
| 553 | } |
||
| 554 | |||
| 555 | /*********************************************************************************************** |
||
| 556 | * Called when a file is put in file input directory |
||
| 557 | * The file input directory path is configured in setting page and is by default empty |
||
| 558 | * |
||
| 559 | * @param {String} fileName - The name of the file put in the file input directory |
||
| 560 | * @param {String} fileContent - The content of the file |
||
| 561 | * |
||
| 562 | * Note: There is special mapping for CSV file which are converted to JSON! |
||
| 563 | * Other file types are just received as is |
||
| 564 | ***********************************************************************************************/ |
||
| 565 | function receivedFile(fileName,fileContent){ |
||
| 566 | print("Received file "+fileName+ " with content "+ fileContent); |
||
| 567 | } |
||
| 568 | |||
| 569 | /*********************************************************************************************** |
||
| 570 | * Called receiving data on an activated serial port |
||
| 571 | * |
||
| 572 | * Note, see Controller.setupSerialPort(..) for activate a serial port |
||
| 573 | * |
||
| 574 | * @param {String} port - Wich port the data comes from |
||
| 575 | * @param {String} payload - The data |
||
| 576 | * |
||
| 577 | ***********************************************************************************************/ |
||
| 578 | function onSerialReceive(port, payload){ |
||
| 579 | |||
| 580 | print("Serial data received on port: "+port+" data: "+payload); |
||
| 581 | } |
||
| 582 | |||
| 583 | |||
| 584 | /************************************************************************** |
||
| 585 | * This callback catches unexpected runtime errors like timeouts when |
||
| 586 | * writing or subscribing to a remote device currently absent. |
||
| 587 | * @param {String} type - Type or source of exception |
||
| 588 | * @param {String} message - Short description of the issue in plain text |
||
| 589 | * @param {String} details - Optional information in JSON format |
||
| 590 | **************************************************************************/ |
||
| 591 | function exceptionCatch(type,message,details){ |
||
| 592 | print("Exception catched, type:"+type+" message:" + message + " details:" + details ); |
||
| 593 | } |
||
| 594 | |||
| 595 | /** |
||
| 596 | * When supported by the platform and enabled in the setting "beacon Station under Bluetooth" |
||
| 597 | * this method is invoked with advertisment from all Bluetooth LE devices nerby |
||
| 598 | * |
||
| 599 | * @param {String} mac - The sending Bluetooth device MAC adress |
||
| 600 | * @param {String} rssi - The signal strengh of the sending beacon |
||
| 601 | * @param {String} bt_payload - The beacon data |
||
| 602 | */ |
||
| 603 | function onBTBeaconAdvertising(mac,rssi,bt_payload){ |
||
| 604 | |||
| 605 | //Example of whitelist filter |
||
| 606 | if( mac.includes("38FE") || mac.includes("CD8E")){ |
||
| 607 | |||
| 608 | print("Beacon adv from mac: "+ mac + " rssi: "+rssi+" data:"+bt_payload); |
||
| 609 | |||
| 610 | //Here you can parse the payload from the beacon as you wish |
||
| 611 | //If the beacon is a Ruuvi, DTXr has a built in javascript library for the format 5 |
||
| 612 | //See documentation on DTXr wiki |
||
| 613 | //https://collab.davitor.com/redmine/projects/dtxr/wiki |
||
| 614 | //More info on Ruuvi format and how to parse here |
||
| 615 | //https://ruuvi.com/custom-ruuvi-data-format-in-a-day/ |
||
| 616 | |||
| 617 | |||
| 618 | } |
||
| 619 | } |
||
| 620 | |||
| 621 | /** |
||
| 622 | * Received an MQTT publish request |
||
| 623 | * @param {type} topic |
||
| 624 | * @param {type} payload |
||
| 625 | */ |
||
| 626 | function MQTTOnPublish(topic,payload){ |
||
| 627 | print("MQTT client published " + payload + " on topic " + topic); |
||
| 628 | } |
||
| 629 | |||
| 630 | /** |
||
| 631 | * Received a web socket client text response |
||
| 632 | * @param {type} text |
||
| 633 | */ |
||
| 634 | 1 | Torbjorn Carlqvist Admin | function WebsocketOnClientReceiveText(text){ |
| 635 | print("WebsocketOnClientReceiveText: "+text); |
||
| 636 | } |
||
| 637 | </code></pre> |