blinkpy Python Library

repository·dev·Indexed 20 days ago

https://github.com/fronzbot/blinkpy

A Python 3.10+ library for communicating with the Blink Camera system, optimized for Home Assistant. It provides functionality to authenticate via OAuth 2.0 with PKCE and 2FA, manage system arming/disarming, control camera actions (record, snap, liveview), retrieve sensor data, and manage video clips and thumbnails from both cloud and local storage.

Tokens
12.4K
Snippets
45
Records
53
Agent score
71%

What's inside blinkpy

  1. Arm and Disarm the Blink System

    dev

    You can programmatically arm or disarm your Blink network to start or stop recording and reporting motion events.

    Note on Asynchronous Execution: Calling the /arm or /disarm endpoints does not mean the command has completed. The response will contain a command/request ID. You must capture this ID and poll the Command Status endpoint to verify when the operation has successfully finished.

    # Arm the network
    curl -H "Host: prod.immedia-semi.com" -H "TOKEN_AUTH: *authtoken from login*" --data-binary --compressed https://rest.prod.immedia-semi.com/network/*network_id*/arm
    
    # Disarm the network
    curl -H "Host: prod.immedia-semi.com" -H "TOKEN_AUTH: *authtoken from login*" --data-binary --compressed https://rest.prod.immedia-semi.com/network/*network_id*/disarm
  2. Access Events, Thumbnails, and Video Clips

    dev

    You can retrieve a list of events for a specific network, which includes URLs for video clips and thumbnails.

    • Get Event List: Returns a JSON list of events with URLs.
    • Get Video Clip: Use the .mp4 URL from the event list.
    • Get Thumbnail: Replace the .mp4 extension in the event URL with .jpg to retrieve the thumbnail.
    • Trigger New Capture: You can manually trigger a new thumbnail or video clip for a specific camera using the /camera/*camera_id*/thumbnail or /camera/*camera_id*/clip endpoints.
    # Get events for a network
    curl -H "Host: prod.immedia-semi.com" -H "TOKEN_AUTH: *authtoken from login*" --compressed https://rest.prod.immedia-semi.com/events/network/*network_id*
    
    # Download a video clip
    curl -H "Host: prod.immedia-semi.com" -H "TOKEN_AUTH: *authtoken from login*" --compressed https://rest.prod.immedia-semi.com/video_url_from_events_list.mp4 > video.mp4
    
    # Download a thumbnail (replace .mp4 with .jpg)
    curl -H "Host: prod.immedia-semi.com" -H "TOKEN_AUTH: *authtoken from login*" --compressed https://rest.prod.immedia-semi.com/video_url_from_events_list.jpg > video_thumb.jpg
  3. Load and save credentials from a JSON file

    dev

    You can manage credentials using JSON files to avoid repeated logins.

    To load credentials: Use blinkpy.helpers.util.json_load to load a JSON file containing at least username and password into an Auth object.

    To save credentials: Use await blink.save("<File location>"). This saves authentication tokens and unique IDs to streamline future sessions.

    import asyncio
    from aiohttp import ClientSession
    from blinkpy.blinkpy import Blink
    from blinkpy.auth import Auth
    from blinkpy.helpers.util import json_load
    
    async def start():
        blink = Blink()
        auth = Auth(await json_load("<File Location>"))
        blink.auth = auth
        try:
            await blink.start()
        except BlinkTwoFARequiredError:
            await blink.prompt_2fa()
        return blink
    
    blink = asyncio.run(start())
    
    # To save credentials for later:
    # await blink.save("<File location>")
  4. Quick Start with Blink.start()

    dev

    The simplest way to use blinkpy is to call await Blink.start(). This method will interactively prompt you for your Blink username and password. If Two-Factor Authentication (2FA) is enabled, you will be prompted to enter the PIN sent to your email address.

    Note: HTTP requests are throttled internally using the Blink.refresh_rate variable, which defaults to 30 seconds. It is recommended not to make API calls faster than every 60 seconds to avoid overwhelming Blink's servers.

    import asyncio
    from aiohttp import ClientSession
    from blinkpy.blinkpy import Blink
    
    async def start():
        blink = Blink(session=ClientSession())
        try:
            await blink.start()
        except BlinkTwoFARequiredError:
            await blink.prompt_2fa()
        return blink
    
    blink = asyncio.run(start())
  5. Install blinkpy via pip

    dev

    Install the stable version of blinkpy using pip:

    pip install blinkpy

    To install the current development version from source:

    $ cd ~
    $ git clone https://github.com/fronzbot/blinkpy.git
    $ cd blinkpy
    $ pip install .
    pip install blinkpy
  6. Start Blink without interactive prompts

    dev

    For non-interactive environments (like automated scripts), you must set no_prompt=True when initializing the Auth handler and provide a dictionary containing your username and password.

    If 2FA is required, you must manually call auth.send_auth_key(blink, <key>) with the code received via email, followed by await blink.setup_post_verify().

    import asyncio
    from aiohttp import ClientSession
    from blinkpy.blinkpy import Blink
    from blinkpy.auth import Auth
    
    async def start():
        blink = Blink(session=ClientSession())
        # Can set no_prompt when initializing auth handler
        auth = Auth({"username": <your username>, "password": <your password>}, no_prompt=True)
        blink.auth = auth
        try:
            await blink.start()
        except BlinkTwoFARequiredError:
            await blink.prompt_2fa()
        return blink
    
    blink = asyncio.run(start())
    
    # If 2FA is needed in non-interactive mode:
    # await auth.send_auth_key(blink, <your key>)
    # await blink.setup_post_verify()
  7. Wait for command completion

    dev
    Many Blink API commands are asynchronous on the server side. wait_for_command polls the server using request_command_status to check if a command (identified by id and network_id in the initial response) has finished. It will retry up to MAX_RETRY (120) times with a COMMAND_POLL_TIME (1 second) delay between checks.
  8. How BlinkSyncModule manages camera updates

    dev

    The BlinkSyncModule maintains a dictionary of cameras where keys are camera names and values are instances of camera classes (e.g., BlinkCamera, BlinkCameraMini, or BlinkDoorbell).

    When update_cameras() or refresh() is called, the module:

    1. Queries the server for camera configurations.
    2. Maps the configuration type to the appropriate class.
    3. Instantiates the camera object and calls its .update() method to sync its internal state with the server.
  9. Retrieve video clips and thumbnails

    dev

    To access video clips stored on a Sync Module's local storage, follow this workflow:

    1. Request a manifest update: Call request_local_storage_manifest to tell the Sync Module to generate a new list of clips.
    2. Wait for completion: The manifest request returns a response that must be processed.
    3. Get the manifest: Use get_local_storage_manifest with the manifest_request_id returned from the previous step to retrieve the list of available clips.
    4. Prepare a clip for download: Use request_local_storage_clip with the manifest_id and the specific clip_id to get the download URL.
  10. OAuth 2.0 Authorization Code Flow with PKCE

    dev

    The library implements the full OAuth 2.0 flow required for Blink authentication. The process follows these steps:

    1. oauth_authorize_request: Initiates the request to the authorization URL using a code_challenge (PKCE).
    2. oauth_get_signin_page: Fetches the sign-in page to extract the necessary csrf_token.
    3. oauth_signin: Submits credentials. This may return SUCCESS or 2FA_REQUIRED.
    4. oauth_verify_2fa: If 2FA is required, use this to submit the user's code.
    5. oauth_get_authorization_code: Retrieves the authorization code from the redirect URL.
    6. oauth_exchange_code_for_token: Exchanges the code and code_verifier for access and refresh tokens.
    7. oauth_refresh_token: Uses a refresh token to obtain a new access token when the current one expires.
  11. Login to Blink Servers

    dev

    To interact with the Blink API, you must first authenticate to obtain an authtoken. This token must be included in the TOKEN_AUTH header for all subsequent requests. The login response also provides your networks and the region code required to construct the correct REST endpoint URLs.

    Important: Regional Endpoints Depending on your registered region, you must use the appropriate base URL. For example, if your device is registered in Germany, change the endpoint from https://rest.prod.immedia-semi.com to https://rest.prde.immedia-semi.com.

    curl -H "Host: prod.immedia-semi.com" -H "Content-Type: application/json" --data-binary '{ "password" : "*your blink password*", "client_specifier" : "iPhone 9.2 | 2.2 | 222", "email" : "*your blink login/email*" }' --compressed https://rest.prod.immedia-semi.com/login
  12. Retrieve Camera Sensor Data

    dev

    To get real-time sensor information for a specific camera, such as WiFi strength, temperature, and battery level, use the /signals endpoint.

    curl -H "Host: prod.immedia-semi.com" -H "TOKEN_AUTH: *authtoken from login*" --compressed https://rest.prod.immedia-semi.com/network/*network_id*/camera/*camera_id*/signals