-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndex.js
More file actions
314 lines (289 loc) · 8.49 KB
/
Copy pathIndex.js
File metadata and controls
314 lines (289 loc) · 8.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/**
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const functions = require('firebase-functions');
const {smarthome} = require('actions-on-google');
const {google} = require('googleapis');
const util = require('util');
const admin = require('firebase-admin');
// Initialize Firebase
admin.initializeApp();
const firebaseRef = admin.database().ref('/');
// Initialize Homegraph
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/homegraph']
});
const homegraph = google.homegraph({
version: 'v1',
auth: auth
});
exports.fakeauth = functions.https.onRequest((request, response) => {
const responseurl = util.format('%s?code=%s&state=%s',
decodeURIComponent(request.query.redirect_uri), 'xxxxxx',
request.query.state);
console.log(responseurl);
return response.redirect(responseurl);
});
exports.faketoken = functions.https.onRequest((request, response) => {
const grantType = request.query.grant_type
? request.query.grant_type : request.body.grant_type;
const secondsInDay = 86400; // 60 * 60 * 24
const HTTP_STATUS_OK = 200;
console.log(`Grant type ${grantType}`);
let obj;
if (grantType === 'authorization_code') {
obj = {
token_type: 'bearer',
access_token: '123access',
refresh_token: '123refresh',
expires_in: secondsInDay,
};
} else if (grantType === 'refresh_token') {
obj = {
token_type: 'bearer',
access_token: '123access',
expires_in: secondsInDay,
};
}
response.status(HTTP_STATUS_OK)
.json(obj);
});
const app = smarthome({
debug: true,
});
app.onSync((body) => {
return {
requestId: body.requestId,
payload: {
agentUserId: '123',
devices: [{
id: 'washer',
type: 'action.devices.types.GRILL',
traits: [
'action.devices.traits.OnOff',
'action.devices.traits.StartStop',
'action.devices.traits.Timer',
'action.devices.traits.Modes'
],
name: {
defaultNames: ['My Washer'],
name: 'Washer',
nicknames: ['Washer'],
},
deviceInfo: {
manufacturer: 'Acme Co',
model: 'acme-washer',
hwVersion: '1.0',
swVersion: '1.0.1',
},
willReportState: true,
attributes: {
pausable: true,
maxTimerLimitSec : 3600,
commandOnlyTimer : false,
availableModes: [{
name: 'needles',
name_values: [{
name_synonym: ['needles'],
lang: 'en',
}],
settings: [{
setting_name: 'rest',
setting_values: [{
setting_synonym: ['rest'],
lang: 'en'
}]
}, {
setting_name: 'pasta',
setting_values: [{
setting_synonym: ['pasta'],
lang: 'en'
}]
}, {
setting_name: 'large',
setting_values: [{
setting_synonym: ['large'],
lang: 'en'
}]
}],
ordered: true
}],
},
}],
},
};
});
const queryFirebase = async (deviceId) => {
const snapshot = await firebaseRef.child(deviceId).once('value');
const snapshotVal = snapshot.val();
return {
on: snapshotVal.OnOff.on,
isPaused: snapshotVal.StartStop.isPaused,
isRunning: snapshotVal.StartStop.isRunning,
timerRemainingSec: snapshotVal.Timer.timerRemainingSec,
needles: snapshotVal.Modes.needles,
};
}
const queryDevice = async (deviceId) => {
const data = await queryFirebase(deviceId);
//const maxTimerLimitSec = 3600;
return {
//timerRemainingSec: -1,
on: data.on,
isPaused: data.isPaused,
isRunning: data.isRunning,
/* currentRunCycle: [{
currentCycle: 'rinse',
nextCycle: 'spin',
lang: 'en',
}], */
timerRemainingSec: data.timerRemainingSec,
currentModeSettings: {
needles: data.needles,
},
};
}
app.onQuery(async (body) => {
const {requestId} = body;
const payload = {
devices: {},
};
const queryPromises = [];
const intent = body.inputs[0];
for (const device of intent.payload.devices) {
const deviceId = device.id;
queryPromises.push(queryDevice(deviceId)
.then((data) => {
// Add response to device payload
payload.devices[deviceId] = data;
}
));
}
// Wait for all promises to resolve
await Promise.all(queryPromises)
return {
requestId: requestId,
payload: payload,
};
});
const updateDevice = async (execution,deviceId) => {
const {params,command} = execution;
let state, ref;
switch (command) {
case 'action.devices.commands.OnOff':
state = {on: params.on};
ref = firebaseRef.child(deviceId).child('OnOff');
break;
case 'action.devices.commands.StartStop':
state = {isRunning: params.start};
ref = firebaseRef.child(deviceId).child('StartStop');
break;
case 'action.devices.commands.PauseUnpause':
state = {isPaused: params.pause};
ref = firebaseRef.child(deviceId).child('StartStop');
break;
case 'action.devices.commands.TimerStart':
state = {timerRemainingSec: params.timerTimeSec};
ref = firebaseRef.child(deviceId).child('Timer')
break;
case 'action.devices.commands.SetModes':
state = {needles: params.updateModeSettings.needles};
ref = firebaseRef.child(deviceId).child('Modes');
break;
}
return ref.update(state)
.then(() => state);
};
app.onExecute(async (body) => {
const {requestId} = body;
// Execution results are grouped by status
const result = {
ids: [],
status: 'SUCCESS',
states: {
online: true,
},
};
const executePromises = [];
const intent = body.inputs[0];
for (const command of intent.payload.commands) {
for (const device of command.devices) {
for (const execution of command.execution) {
executePromises.push(
updateDevice(execution,device.id)
.then((data) => {
result.ids.push(device.id);
Object.assign(result.states, data);
})
.catch(() => console.error(`Unable to update ${device.id}`))
);
}
}
}
await Promise.all(executePromises)
return {
requestId: requestId,
payload: {
commands: [result],
},
};
});
exports.smarthome = functions.https.onRequest(app);
exports.requestsync = functions.https.onRequest(async (request, response) => {
response.set('Access-Control-Allow-Origin', '*');
console.info('Request SYNC for user 123');
try {
const res = await homegraph.devices.requestSync({
requestBody: {
agentUserId: '123'
}
});
console.info('Request sync response:', res.status, res.data);
response.json(res.data);
} catch (err) {
console.error(err);
response.status(500).send(`Error requesting sync: ${err}`)
}
});
/**
* Send a REPORT STATE call to the homegraph when data for any device id
* has been changed.
*/
exports.reportstate = functions.database.ref('{deviceId}').onWrite((change, context) => {
console.info('Firebase write event triggered this cloud function');
// TODO: Get latest state and call HomeGraph API
const snapshot = change.after.val();
const requestBody = {
requestId: 'ffffffff', /* Any unique ID */
agentUserId: '123', /* Hardcoded user ID */
payload: {
devices: {
states: {
/* Report the current state of our washer */
[context.params.deviceId]: {
on: snapshot.OnOff.on,
isPaused: snapshot.StartStop.isPaused,
isRunning: snapshot.StartStop.isRunning,
timerRemainingSec: snapshot.Timer.timerRemainingSec,
currentModeSettings: {
needles: snapshot.Modes.needles,
},
},
},
},
},
};
});