]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - apps/tidep0084.git/blob - prebuilt/iot-gateway/cloudAdapter/awsCloudAdapter.js
ff7e4edc3e0938e6437fdbc670fd878f81e4dfc9
[apps/tidep0084.git] / prebuilt / iot-gateway / cloudAdapter / awsCloudAdapter.js
2 /******************************************************************************
4  @file awsCloudAdapter.js
6  @brief Adapter between the cloudAgent and the Amazon AWS IoT Cloud 
8  Group: WCS LPC
9  $Target Devices: Linux: AM335x, Embedded Devices: CC1310, CC1350$
11  ******************************************************************************
12  $License: BSD3 2016 $
13   
14    Copyright (c) 2015, Texas Instruments Incorporated
15    All rights reserved.
16   
17    Redistribution and use in source and binary forms, with or without
18    modification, are permitted provided that the following conditions
19    are met:
20   
21    *  Redistributions of source code must retain the above copyright
22       notice, this list of conditions and the following disclaimer.
23   
24    *  Redistributions in binary form must reproduce the above copyright
25       notice, this list of conditions and the following disclaimer in the
26       documentation and/or other materials provided with the distribution.
27   
28    *  Neither the name of Texas Instruments Incorporated nor the names of
29       its contributors may be used to endorse or promote products derived
30       from this software without specific prior written permission.
31   
32    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
33    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
34    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
35    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
37    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
38    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
39    OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
40    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
41    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
42    EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  ******************************************************************************
44  $Release Name: TI-15.4Stack Linux x64 SDK$
45  $Release Date: July 14, 2016 (2.00.00.30)$
46  *****************************************************************************/
48 var events = require("events");
49 var awsIot = require('aws-iot-device-sdk');
51 /* AWS Cloud Adapter Singleton */
52 var awsCloudAdapterInstance;
54 /*!
55  * @brief      Constructor for AWS Cloud Adapter
56  *
57  * @param      none
58  *
59  * @retun      none
60  */
61 function AwsCloudAdapter() {
63         if (typeof awsCloudAdapterInstance !== "undefined") {
64                 return awsCloudAdapterInstance;
65         }
67         /* Set up to emit events */
68         events.EventEmitter.call(this);
69         awsCloudAdapterInstance = this;
71         awsCloudAdapterInstance.connected = false;
72         awsCloudAdapterInstance.registered = [];
74         var awsCfg = require('./awsConfig.json');
75         var thingShadows = awsIot.thingShadow({
76                 keyPath: awsCfg.certDir + awsCfg.keyPath,
77                 certPath: awsCfg.certDir + awsCfg.certPath,
78                 caPath: awsCfg.certDir + awsCfg.caPath,
79                 clientId: awsCfg.clientId + '_' + new Date().getTime(),
80                 region: awsCfg.region,
81                 port: awsCfg.port,
82                 host: awsCfg.host,
83                 debug: awsCfg.debug
84         });
86         thingShadows.on('connect', function() {
87                 console.log('Connected to AWS IoT');
88                 awsCloudAdapterInstance.connected = true;
89                 awsCloudAdapterInstance.registered = [];
90         });
92         thingShadows.on('close', function() {
93                 console.log('AWS Cloud Adapter close');
94         });
96         thingShadows.on('reconnect', function() {
97                 console.log('AWS Cloud Adapter reconnect');
98         });
100         thingShadows.on('offline', function() {
101                 console.log('AWS Cloud Adapter offline');
102         });
104         thingShadows.on('error', function(error) {
105                 console.log('AWS Cloud Adapter error', error);
106         });
108         thingShadows.on('message', function(topic, payload) {
109                 console.log('AWS Cloud Adapter message');
110         });
112         thingShadows.on('status', function(thingName, stat, clientToken, stateObject) {
113                 //console.log('AWS Cloud Adapter ()');
114         /* Print only if the status is not an error message */
115         /* see 'Optomistic Locking' at:
116          *   http://docs.aws.amazon.com/iot/latest/developerguide/using-thing-shadows.html
117          * for an example.
118         */
119         if(stateObject.hasOwnProperty('state'))
120             console.log('status : ' + thingName + ' reporting data');
121             //console.log(thingName + ':\n' + JSON.stringify(stateObject.state.reported, null, 4));
122         else
123             console.log("status : error msg"); 
125     });
127         /* All requests from the Cloud will be received in this Delta event */  
128         thingShadows.on('delta', function(thingName, stateObject) {
129                 //console.log('AWS Cloud Adapter delta');
130                 //console.log('Delta on: ' + thingName);
131                 //console.log(JSON.stringify(stateObject, null, 4));
133                 /* Check the stateObject for an open/close command or a toggleLED command */
134                 if (stateObject.state.state === "open") {
135                         awsCloudAdapterInstance.emit('updateNetworkState', {action : "open"});
136                         console.log('delta : ' + thingName + ' open network');
137                 }
138                 if (stateObject.state.state === "close") {
139                         awsCloudAdapterInstance.emit('updateNetworkState', {action : "close"});
140                         console.log('delta : ' + thingName + ' close network');
141                 }
142                 if (stateObject.state.toggleLED === "true") {
143                         var index = thingName.lastIndexOf("_");
144                         var extAddr = thingName.substr(index+1);
145                         awsCloudAdapterInstance.emit('deviceActuation', {dstAddr : extAddr});
146                         console.log('delta : ' + thingName + ' toggle LED');
147                 }
148         });
150         thingShadows.on('timeout', function(thingName, clientToken) {
151                 //console.log('AWS Cloud Adapter timeout');
152         console.log('timeout : ' + thingName);
153         });
155         AwsCloudAdapter.prototype.cloudAdapter_sendNetworkInfoMsg = function (nwkInfo) {
156                 if (awsCloudAdapterInstance.connected != true) {
157                         return;
158                 }
160                 /* Format the device topics for the full AWS specific Device Thing Shadow topic */
161                 var devices = nwkInfo.devices.slice();
162                 for (i = 0; i < devices.length; i++) {
163                         devices[i].topic = '$aws/things/' + devices[i].topic + '/shadow';
164                 }
165                 nwkInfo.devices = devices.slice();
167                 var reported = nwkInfo;
168                 var nwkInfoThing = 'ti_iot_' + nwkInfo.ext_addr + '_network';
169                 /* If the network thing isn't registered yet, then register it before sending the update */
170                 if (awsCloudAdapterInstance.registered[nwkInfoThing] != 1) {
171                         thingShadows.register(nwkInfoThing, { ignoreDeltas : false, persistentSubscribe : false });
172                         /* Amazon requires a delay between Thing registration and its first update */
173                         setTimeout (function() {
174                                 thingShadows['update'](nwkInfoThing, { state : { reported }});
175                         }, 5000);
176                         awsCloudAdapterInstance.registered[nwkInfoThing] = 1;
177                 }
178                 else {
179                         thingShadows['update'](nwkInfoThing, { state : { reported }});
180                 }
181         }
183         AwsCloudAdapter.prototype.cloudAdapter_sendDeviceInfoMsg = function (devInfo, nwkExtAddr) {
184                 if (awsCloudAdapterInstance.connected != true) {
185                         return;
186                 }
187                 
188                 var devInfoThing = 'ti_iot_' + nwkExtAddr + '_' + devInfo.ext_addr;
189                 var reported = devInfo;
190                 /* If the device thing ins't registered yet, then register it before sending the update */
191                 if (awsCloudAdapterInstance.registered[devInfoThing] != 1) {
192                         thingShadows.register(devInfoThing, { ignoreDeltas : false, persistentSubscribe : false });
193                         /* Amazon requires a delay between Thing registration and its first update */
194                         setTimeout (function() {
195                                 /* Set desired to null in order to remove any toggleLED requests */
196                                 thingShadows['update'](devInfoThing, { state : { desired: null, reported }});
197                         }, 5000);
198                         awsCloudAdapterInstance.registered[devInfoThing] = 1;
199                 }       
200                 else {
201                         /* Set desired to null in order to remove any toggleLED requests */
202                         thingShadows['update'](devInfoThing, { state : { desired: null, reported }});
203                 }
204         }
207 AwsCloudAdapter.prototype.__proto__ = events.EventEmitter.prototype;
209 module.exports = AwsCloudAdapter;