Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. // The "Cloud Functions for Firebase" SDK to create Cloud Functions and setup triggers:
  2. const functions = require('firebase-functions');
  3.  
  4. // The Firebase Admin SDK to access the Firebase Realtime Database:
  5. const admin = require('firebase-admin');
  6. admin.initializeApp();
  7.  
  8. // Definition of the Cloud Function reacting to publication on the telemetry topic:
  9. exports.detectTelemetryEvents = functions.pubsub.topic('weather-telemetry-topic').onPublish(
  10. (message, context) => {
  11. // The onPublish() trigger function requires a handler function that receives
  12. // 2 arguments: one related to the message published and
  13. // one related to the context of the message.
  14.  
  15. // Firebase SDK for Cloud Functions has a 'json' helper property to decode
  16. // the message. We also round numbers to match DHT22 accuracy.
  17. const temp = message.json.temp.toFixed(1);
  18. const humidity = Math.round(message.json.humidity);
  19.  
  20. // A Pub/Sub message has an 'attributes' property. This property has itself some properties,
  21. // one of them being 'deviceId' to know which device published the message:
  22. const deviceId = message.attributes.deviceId;
  23. // The date the message was issued lies in the context object not in the message object:
  24. const timestamp = context.timestamp
  25. // Log telemetry activity:
  26. console.log(`Device=${deviceId}, Temp=${temp}°C, Humidity=${humidity}%, Timestamp=${timestamp}`);
  27. // Push to Firebase Realtime Database telemetry data sorted by device:
  28. return admin.database().ref(`devices-telemetry/${deviceId}`).push({
  29. timestamp: timestamp,
  30. temp: temp,
  31. humidity: humidity
  32. })
  33. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement