【发布时间】:2020-08-04 19:11:57
【问题描述】:
我是谷歌云平台的初学者,我正在玩 iot-core、pub/sub 和 can 函数。我想为通过 pub/sub 向云端发送消息的设备制作一个简单的故障检测器。
为简单起见,我想直接将遥测数据用作心跳,但我很难将所有这些数据放在一起。
我草绘了这段代码,这是错误的,但我希望能帮助理解我想要做什么。 这个想法是捕获遥测消息并在每次有新消息时保存相应的 id。然后,每 10 分钟检查一次是否所有以前的存活者都还在。
/* devices on system */
var alive = [1,2];
/* heartbeats */
var received = [];
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
exports.messagePubSub = (event, context) => {
// extract device id from message
const payload = Buffer.from(event.data, 'base64').toString();
const info = JSON.parse(payload);
const device = info.id;
// heartbeat
if (!received.includes(device){
received.push(device);
console.log('${device} is alive');
}
};
/**
* Triggered every 10 minutes
*/
exports.scheduledFunctionCrontab =
functions.pubsub.schedule('*/10 * * * *').onRun((context) => {
const topicName = "..."
// find dead devices
var deads = [];
for (i = 0; i < alive.length; i++) {
if (!received.includes(alive[i])){
deads.push(alive[i]);
delete alive[i];
}
}
// restore device
for (i = 0; i < received.length; i++) {
if (!alive.includes(received[i])){
alive.push(received[i]);
}
}
// build payload
const messageObj = {
data: {
deads: deads
}
};
const messageBuffer = Buffer.from(JSON.stringify(messageObj), 'utf8');
console.log(messageObj);
// publish failures
try {
await pubSubClient.topic(topicName).publisher().publish(messageBuffer);
console.log("Message sent!")
} catch (err) {
console.error(err);
return Promise.reject(err);
}
// reset
received = []
});
谢谢!
【问题讨论】:
标签: google-cloud-platform google-cloud-functions