|
1 |
| -import mqtt from 'mqtt' |
| 1 | +import * as iot from '@google-cloud/iot' |
2 | 2 | import { AutomatronContext } from './types'
|
3 | 3 |
|
| 4 | +const iotClient = new iot.v1.DeviceManagerClient() |
| 5 | + |
4 | 6 | export async function sendHomeCommand(
|
5 | 7 | context: AutomatronContext,
|
6 | 8 | cmd: string | string[]
|
7 | 9 | ) {
|
8 |
| - var client = await getMQTTClient(context) |
9 |
| - if (Array.isArray(cmd)) { |
10 |
| - cmd.forEach(c => client.publish('home', c)) |
11 |
| - } else { |
12 |
| - client.publish('home', cmd) |
13 |
| - } |
14 |
| -} |
15 |
| - |
16 |
| -async function getMQTTClient(context: AutomatronContext) { |
17 |
| - const unsafeGlobal = global as any |
18 |
| - if (unsafeGlobal.automatronMqttPromise) { |
19 |
| - return unsafeGlobal.automatronMqttPromise |
20 |
| - } |
21 |
| - const promise = new Promise((resolve, reject) => { |
22 |
| - var client = mqtt.connect(context.secrets.MQTT_URL) |
23 |
| - client.on('connect', function() { |
24 |
| - resolve(client) |
25 |
| - }) |
26 |
| - client.on('error', function(error) { |
27 |
| - reject(error) |
28 |
| - unsafeGlobal.automatronMqttPromise = null |
| 10 | + const cmds = Array.isArray(cmd) ? cmd : [cmd] |
| 11 | + const formattedName = context.secrets.CLOUD_IOT_CORE_DEVICE_PATH |
| 12 | + return Promise.all( |
| 13 | + cmds.map(async (command) => { |
| 14 | + const id = |
| 15 | + new Date().toJSON() + |
| 16 | + Math.floor(Math.random() * 10000) |
| 17 | + .toString() |
| 18 | + .padStart(2, '0') |
| 19 | + const commandMessage = JSON.stringify({ |
| 20 | + id: id, |
| 21 | + topic: 'home', |
| 22 | + data: command, |
| 23 | + }) |
| 24 | + const binaryData = Buffer.from(commandMessage) |
| 25 | + const request = { |
| 26 | + name: formattedName, |
| 27 | + binaryData: binaryData, |
| 28 | + } |
| 29 | + await iotClient.sendCommandToDevice(request) |
29 | 30 | })
|
30 |
| - }) |
31 |
| - unsafeGlobal.automatronMqttPromise = promise |
32 |
| - return promise |
| 31 | + ) |
33 | 32 | }
|
0 commit comments