Skip to content

Instantly share code, notes, and snippets.

@cpq
Created October 17, 2018 09:38
Show Gist options
  • Save cpq/9281c3216836578c1e2c1793e7822993 to your computer and use it in GitHub Desktop.
Save cpq/9281c3216836578c1e2c1793e7822993 to your computer and use it in GitHub Desktop.
google iot <-> firebase cloud function
import base64
import json
import firebase_admin
from firebase_admin import db
firebase_admin.initialize_app(
credential=None,
options={'databaseURL' : 'https://YOUR_FIREBASE_DB_NAME.firebaseio.com'},
)
def iot2fb(data, ctx):
# Attributes attached to messages from IoT devices are described here:
# https://cloud.google.com/iot/docs/how-tos/mqtt-bridge#publishing_telemetry_events
attrs = data["attributes"]
dev_id = attrs.get("deviceId")
if not dev_id:
# Not an IoT event? How did it get here?
return
# data.data is base64-encoded by pubsub,
# the data itself is supposed a JSON object (as sent by the device).
dev_data = json.loads(base64.b64decode(data["data"]))
assert(type(dev_data) is dict)
db.reference().child("dev_events").child(dev_id).push(dev_data)
print("Rec'd from %s: %s" % (dev_id, dev_data))
firebase-admin>=2.13.0
google-cloud-firestore>=0.29.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment