FirebaseClient Arduino Library

repository·main·Indexed 42 days ago

https://github.com/mobizt/firebaseclient

An asynchronous, network-independent Arduino library providing REST API access to Firebase and Google Cloud services, including Realtime Database, Firestore, FCM, and Storage. Optimized for ESP8266, ESP32, and other 32-bit MCUs, it supports multiple authentication methods (User, Service Account, Custom Tokens) and offers both Async and Sync/Await operational modes. Version 2.1.0+ is network independent, allowing developers to specify their own network stack or SSL client.

Tokens
52.6K
Snippets
189
Records
250
Agent score
52%

What's inside FirebaseClient

  1. Overview of FirebaseClient capabilities

    main

    FirebaseClient is an asynchronous REST API-based library for Arduino that allows IoT devices to interact with various Firebase and Google Cloud products. It is designed for serverless applications like data logging, automation, and IoT.

    Supported services include:

    • Firebase Realtime Database
    • Cloud Firestore Database
    • Cloud Messaging (FCM)
    • Firebase Storage
    • Google Cloud Functions
    • Google Cloud Storage
    • Security Rules Management

    Key features:

    • Authentication: Supports multiple authentication types, user account management (sign up, delete, verify, reset password), and both auto- and one-time authentication.
    • OTA Updates: Provides Over-the-Air firmware update functionality using Realtime Database data or Firebase/Cloud Storage objects.
    • Security: Supports using Firebase Security Rules for fine-grained access control via custom claims.

    Limitations: Because this library uses the Firebase REST API, it does not support Firestore data change listening or Realtime Database disconnected events.

  2. Explore Realtime Database examples

    main
    The examples/RealtimeDatabase directory contains a comprehensive suite of implementation patterns for using the Firebase Realtime Database with this library. These examples cover everything from basic CRUD operations to advanced streaming, security, and performance testing. Use these examples to understand how to implement specific features like filtering, indexing, and concurrency management.
  3. User Management examples in FirebaseClient

    main

    The UserManagement directory contains several example implementations for handling Firebase Authentication tasks. These examples demonstrate how to manage user lifecycles and security flows using the FirebaseClient library.

    Available user management patterns include:

    • Anonymous Sign Up: Using anonymous authentication to allow users to interact with the app without a permanent account initially.
    • Sign Up: Creating new user accounts with email and password.
    • Delete User: Removing a user account from the Firebase project.
    • Reset Password: Initiating the password reset flow for existing users.
    • Verify: Sending a verification link to the user's registered email address to confirm their identity.
  4. Explore Firestore Database Document operations

    main

    The examples/FirestoreDatabase/Documents directory contains various implementation examples for interacting with Firestore documents using the FirebaseClient library. These examples cover fundamental CRUD operations, batch processing, and advanced field updates.

    Available operation patterns include:

    • Basic CRUD: Get, CreateDocument, Patch, Delete, and List documents.
    • Batch Operations: BatchGet and BatchWrite for handling multiple documents efficiently.
    • Atomic Commits: Using Commit to perform complex updates like AppendArray, IncrementFieldValue, and SetUpdateDelete.
    • Advanced Queries: RunQuery for retrieving documents based on specific criteria.
    • Collection Management: ListCollectionIds to discover sub-collections within a document.
  5. Explore Firestore Database examples

    main

    The examples/FirestoreDatabase directory contains comprehensive usage patterns for interacting with Google Cloud Firestore using the FirebaseClient library. These examples are organized by functional area, allowing you to implement specific Firestore features in your project.

    Key functional areas include:

    • CollectionGroups: Managing indexes for collection groups.
    • Databases: Administrative tasks such as creating, deleting, updating, listing, and managing database-level indexes or document imports/exports.
    • Documents: Core CRUD operations and advanced manipulation, including:
      • Batch Operations: BatchGet and BatchWrite.
      • Atomic Commits: Using Commit for complex operations like AppendArray, IncrementFieldValue, and SetUpdateDelete.
      • Document Lifecycle: CreateDocument, Get, Delete, List, and Patch (including partial updates with AppendMapValue).
      • Queries: Using RunQuery to retrieve specific datasets.
  6. Manage Firestore composite indexes

    main

    The Firestore API allows you to create, get, list, and delete composite indexes to enable complex queries.

    Important Requirements:

    • Authentication: All index management functions require ServiceAuth authentication.
    • Project ID: Use only the project name (exclude .firebaseio.com).
    • Database ID: Use (default) or an empty string "" for the Firestore database ID.

    Functions are available in three modes:

    1. Synchronous (Returns String): Returns the response payload directly.
    2. Async with Result Object: Uses an AsyncResult object to track the operation.
    3. Async with Callback: Uses an AsyncResultCallback for asynchronous handling.
  7. Create a Firestore Document

    main

    The Document class represents a single document within a Google Cloud Firestore database. You can instantiate a document in two ways:

    1. By Resource Name: Provide the full resource path of the document.
    2. By Key-Value Pair: Create a document containing a single field using a key and a Values::Value object.

    To build a document with multiple fields, use the .add() method to append Values::Value objects to the document instance.

    // Option 1: Initialize with resource name
    Document doc("projects/my-project/databases/(default)/documents/my-collection/my-doc");
    
    // Option 2: Initialize with a single key-value pair
    Document doc("my_key", my_value_object);
    
    // Adding more fields to an existing document
    doc.add("another_key", another_value_object);
  8. Use FirebaseApp to manage authentication and authorization

    main

    The FirebaseApp class is the central component for handling authentication and authorization tasks within the library. It manages the lifecycle of authentication tokens, handles JWT signing, and coordinates async tasks for all Firebase services associated with the app.

    Key Responsibilities:

    • Token Management: Retrieves ID tokens, access tokens, and refresh tokens.
    • Authentication Lifecycle: Monitors if the user is authenticated, if tokens are expired, and handles re-authentication.
    • Service Integration: Applies credentials to Firebase services like RealtimeDatabase, Storage, Messaging, CloudStorage, and CloudFunctions via getApp().
    • Task Coordination: The loop() method maintains the async task queue for all AsyncClient instances assigned to this app.
    // Conceptual usage of FirebaseApp
    FirebaseApp app;
    // ... initialization logic ...
    if (app.ready()) {
        RealtimeDatabase database;
        app.getApp(database);
        // database is now authenticated
    }
  9. Use the Messaging class for Google Cloud Messaging

    main

    The Messaging class provides functionality for interacting with Google Cloud Messaging (FCM). It allows you to send messages to specific targets using the Firebase HTTP v1 API.

    Important Requirements:

    • Authentication: Sending messages requires ServiceAuth authentication.
    • Project ID Format: When providing the Firebase Project ID (typically via the Messages::Parent object), use only the project name without the .firebaseio.com suffix.
    • Client: Most operations require an instance of AsyncClientClass to handle asynchronous communication.
  10. Configure consistency_selector in QueryOptions

    main

    When using runQuery(), you must configure a consistency_selector within the QueryOptions object. You can choose exactly one of the following modes, but they cannot be mixed:

    1. transaction: Used to run the query within an already active transaction. Requires a base64-encoded string representing the transaction.
    2. newTransaction: Starts a new transaction and reads the documents. By default, this is a read-only transaction. The new transaction ID is returned as the first response in the stream.
    3. readTime: Reads the documents as they existed at a specific point in time.
  11. Handle SSE (HTTP Streaming) events in RealtimeDatabaseResult

    main

    When using SSE mode (HTTP Streaming) for real-time updates, the RealtimeDatabaseResult object provides metadata about the stream and the specific event received. Use these methods to process incoming data changes:

    • isStream(): Returns true if the task is in SSE mode.
    • dataPath(): Returns the relative path of the data that changed.
    • event(): Returns the event type (e.g., put, patch, keep-alive, cancel, auth_revoked).
    • data(): Returns the actual data payload that changed.
    • eventTimeout(): Returns true if the SSE event timed out.
    • ETag(): Returns the ETag from the get function.