Documentation for unifi_video

See the project README for install instructions and a quick-start guide, and the FAQ for answers to questions you are likely to have. For an API reference, see the Modules section.

Table of Contents

unifi-video-api

Build Status Documentation Status

Python API for interfacing with UniFi Video.

Supported UniFi Video versions: v3.9.12 to v3.10.13

Supported Ubiquiti camera models: UVC, UVC G3, UVC G3 Dome, UVC Dome, UVC Pro, UVC G3 Pro, UVC G3 Flex, UVC Micro, UVC G3 Micro, airCam, airCam Dome, and airCam Mini, UVC G4 Bullet, UVC G4 Pro.

Features

For a single UniFi Video server:

  • Support both username/password and API key auths
  • Provide GET, POST, PUT, and DELETE methods
  • Handle session tracking and login when necessary
  • Provide iterable collections for cameras and recordings that the UniFi Video server is aware of

Per camera:

  • Set or show picture settings: brightness, contrast, saturation, hue, denoise, sharpness, dynamic range
  • Set or show IR led state
  • Set or show on-display text
  • Set or show timestamp state
  • Set or show watermark/logo state
  • Set recording mode to fulltime, motion, or disabled
  • Set recording pre/post padding
  • Take and download pictures (snapshots)
  • Download camera footage between arbitrary start and end times

Per recording:

  • Delete
  • Download
  • Snapshot (thumbnail) download

Installation

Either grab it from PyPI

pip install unifi-video

or download a release and manually place unifi_video in your project directory, or any path in $PYTHONPATH.

You shouldn’t need any external libraries, unless you want to run the tests or build the docs (see requirements_dev.txt). unifi-video-api does use the six library but will fallback to using the included six should it fail to import six from system level packages.

Both python 2.7+ and python3 are supported.

Usage

See the docs for an API reference.

from unifi_video import UnifiVideoAPI

# Default kwargs: addr = 'localhost', port = 7080, schema = http
uva = UnifiVideoAPI(username='username', password='password', addr='10.3.2.1')

# Use API key (can be set per user in Unifi NVR user settings)
uva = UnifiVideoAPI(api_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', addr='10.3.2.1')

# Skip version checking
uva = UnifiVideoAPI(api_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', addr='10.3.2.1',
  check_ufv_version=False)

# Use HTTPS and skip cert verification
uva = UnifiVideoAPI(api_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', addr='10.3.2.1',
  port=7443, schema='https', verify_cert=False)

# Save snapshot from camera whose id, name or onscreen display text
# is "Garage"
uva.get_camera('Garage').snapshot('some/path/snapshot.jpg')

# List all cameras UniFi Video is aware of
for camera in uva.cameras:
  print(camera)

# Save snapshot from every currently online camera managed by the UniFi Video
# instance. Default filepath: # ./snapshot_{camera ID}_{timestamp}.jpg
for camera in uva.active_cameras:
  camera.snapshot()

# List all cameras managed by the UniFi Video instance, online or not
for camera in uva.managed_cameras:
  camera.snapshot()

# Get footage from camera "Garage" for specific timespan.
# (The resulting file will be 0 bytes when no footage is found.)
uva.get_camera('Garage').recording_between('2018-12-01 00:00:00',
  '2018-12-01 00:05:00')

# Specify filename
uva.get_camera('Garage').recording_between('2018-12-01 00:00:00',
  '2018-12-01 00:05:00', 'first_mins_of_dec.mp4')

# Change onscreen display text
uva.get_camera('Garage').set_onscreen_text('Home garage')

# Set IR leds to auto mode
uva.get_camera('Garage').ir_leds('auto')

# Turn off IR leds (manual mode implied)
uva.get_camera('Garage').ir_leds('off')

# Turn on IR leds (manual mode implied)
uva.get_camera('Garage').ir_leds('on')

# Set camera to record at all times and to pre capture 5 secs
uva.get_camera('Garage').set_recording_settings('fulltime',
  pre_padding_secs=5)

# Set camera to record motion events only
uva.get_camera('Garage').set_recording_settings('motion')

# Disable recording altogether
uva.get_camera('Garage').set_recording_settings('disable')

# List recordings whose details were fetched during initialization
for rec in uva.recordings:
  print(rec)

# Download recording, write to local file recording01.mp4
uva.recordings['xxxxxxxxxxxxxxxxxxxx'].download('recording01.mp4')

Warning

This software has been tested against a limited set of API versions and hardware. While unlikely, should any of the POST payloads result in software or hardware failure, the maintainer of this package is not liable.

Proceed at your own risk.

Frequently asked questions

How do I use it with an untested version of UniFi Video?

Use the keyword argument check_ufv_version when creating an API instance:

from unifi_video import UnifiVideoAPI
uva = UnifiVideoAPI(api_key='xxxxxx', addr='10.3.2.1', check_ufv_version=False)

How to skip cert verification?

Use the keyword argument verify_cert when creating an API instance:

from unifi_video import UnifiVideoAPI
uva = UnifiVideoAPI(api_key='xxxxxx', addr='10.3.2.1', verify_cert=False)

How do I use an open file descriptor, or another file-like object to save a snapshot with?

The filename param of snapshot() can be set to True to force the method to return the raw response body. You can then do with it as you please.

from unifi_video import UnifiVideoAPI

uva = UnifiVideoAPI(api_key='xxxxxx', addr='10.3.2.1')
camera = uva.get_camera('Garage')

some_file_like_object.write(camera.snapshot(filename=True))

This goes for all the download methods:

What is the difference between the three camera collections?

A UnifiVideoAPI object has three camera collections:

from unifi_video import UnifiVideoAPI

uva = UnifiVideoAPI(api_key='xxxxxx', addr='10.3.2.1')

for camera in uva.cameras:
  print(camera)

for camera in uva.active_cameras:
  print(camera)

for camera in uva.managed_cameras:
  print(camera)

UnifiVideoAPI.cameras

Contains every camera the associated UniFi Video server is aware of. These could be anything from an unmanaged camera on the network to an old long ago removed camera that still has a lingering database entry.

UnifiVideoAPI.managed_cameras

Only contains cameras that are managed by the UniFi Video server. Note that this does not exclude cameras that are offline.

UnifiVideoAPI.active_cameras

Cameras that are both managed by the UniFi Video server and currently online.

unifi-video-api, unifi-video, unifi_video: which is it?

unifi-video-api is the name of the Github repository, unifi_video is the name of the python package, and unifi-video is the name of the PyPI package that contains the unifi_video python package.

API unifi_video.api

class unifi_video.api.UnifiVideoAPI(api_key=None, username=None, password=None, addr=u'localhost', port=7080, schema=u'http', verify_cert=True, check_ufv_version=True, utc_offset_sec=None)[source]

Bases: object

Encapsulates a single UniFi Video server.

Parameters:
  • api_key (str) – UniFi Video API key
  • username (str) – UniFi Video account username
  • password (str) – UniFi Video account pasword
  • addr (str) – UniFi Video host address
  • port (int) – UniFi Video host port
  • schema (str) – Protocol schema to use. Valid values: http, https
  • verify_cert (bool) – Whether to verify UniFi Video’s TLS cert when connecting over HTTPS
  • check_ufv_version (bool) – Set to False to use with untested UniFi Video versions
  • utc_offset_sec (int or NoneType) – UniFi Video server’s UTC offset in seconds.

Note

At minimum, you have to

  • provide either an API key or a username:password pair
  • set the host address and port to wherever your UniFi Video is listening at
Variables:
  • _data (dict) – UniFi Video “bootstrap” JSON as a dict
  • base_url (str) – API base URL
  • api_key (str or NoneType) – API key (from input params)
  • username (str or NoneType) – Username (from input params)
  • password (str or NoneType) – Password (from input params)
  • name (str or NoneType) – UniFi Video server name
  • version (str or NoneType) – UniFi Video version
  • jsession_av (str or NoneType) – UniFi Video session ID
  • cameras (UnifiVideoCollection) – Collection of UnifiVideoCamera objects. Includes all cameras that the associated UniFi Video instance is aware of
  • active_cameras (UnifiVideoCollection) – Like UnifiVideoAPI.cameras but only includes cameras that are both connected and managed by the UniFi Video instance.
  • managed_cameras (UnifiVideoCollection) – Includes all cameras that are managed by the UniFi Video instance, whether they’re online or not.
  • recordings (UnifiVideoCollection) – Collection of UnifiVideoRecording objects
delete(url, data=None, raw=False)[source]

Send DELETE request.

Thin wrapper around post(); the same parameter/return semantics apply here.

delete_all_recordings()[source]

Delete all existing recordings

get(url, raw=False, url_params={})[source]

Send GET request.

Parameters:
  • url (str) – API endpoint (relative to the API base URL)
  • raw (str or bool, optional) – Set str filename if you want to save the response to a file. Set to True if you want the to return raw response data.
  • url_params (dict, optional) – URL parameters as a dict. Gets turned into query string and appended to url
Returns:

Response JSON (as dict) when Content-Type response header is application/json

True if raw is str (filename) and a file was successfully written to

Raw response body (as bytes) if the raw input param is of type bool

False on HTTP 4xx - 5xx

Return type:

NoneType, bool, dict, bytes

get_camera(search_term, managed_only=False)[source]

Get camera by its ObjectID, name or overlay text

Parameters:
  • search_term (str) – String to test against name, _id, and overlay_text.
  • managed_only (bool) – Whether to search unmanaged cameras as well.
Returns:

UnifiVideoCamera or NoneType depending on whether or not search_term was matched to a camera.

Tip

Do not attempt to find an unmanaged camera by it’s overlay text; UniFi Video provides limited detail for unmanaged cameras.

get_recordings(rec_type=u'all', camera=None, start_time=None, end_time=None, limit=0, order=u'desc', req_each=False)[source]

Fetch recording listing

Parameters:
  • rec_type (str, optional) – Type of recordings to fetch: all, motion or fulltime
  • camera (UnifiVideoCamera or str or list of UnifiVideoCamera or list of str, optional) – Camera or cameras whose recordings to fetch
  • start_time (datetime or str or int, optional) – Recording start time. (See dt_resolvable_to_ms().)
  • end_time (datetime or str or int, optional) – Recording end time. (See dt_resolvable_to_ms().)
  • order (str, optional) – Sort order: desc or asc. Recordings are sorted by their start time.
  • limit (int, optional) – Limit the number of recordings
  • req_each (bool, optional) – Whether to save bandwidth on the initial request and to fetch each recordings’ details individually or to ask for each recordings’ details to be included in the one and only initial request. True can potentially save you in total bytes transferred but will cost you in the number of HTTP requests made.
Returns:

Iterable[UnifiVideoRecording]

Note

You can use naive datetime objects or strings when you want to mark time in the UniFi Server’s local time. Otherwise, use Unix timestamps (int, in seconds) or timezone aware datetime objects.

static params_to_query_str(params_dict)[source]

Build query string from dict of URL parameters

Parameters:params_dict (dict) – URL parameters
Returns:Query string
Return type:str
post(url, data=None, raw=False, _method=None)[source]

Send POST request.

Parameters:
  • url (str) – API endpoint (relative to the API base URL)
  • data (dict or NoneType) – Request body
  • raw (str or bool) – Filename (str) if you want the response saved to a file, True (bool) if you want the response body as return value
Returns:

See get().

put(url, data=None, raw=False)[source]

Send PUT request.

Thin wrapper around post(); the same parameter/return semantics apply here.

refresh_cameras()[source]

GET cameras from the server and update camera collections

Touches UnifiVideoAPI.cameras, UnifiVideoAPI.active_cameras, and UnifiVideoAPI.managed_cameras

refresh_recordings(limit=300)[source]

GET recordings from the server and update self.recordings.

Parameters:limit (int) – Limit the number of recording items to fetch (0 for no limit).

Camera unifi_video.camera

exception unifi_video.camera.CameraModelError(message=None)[source]

Bases: exceptions.ValueError

Unsupported camera model

class unifi_video.camera.UnifiVideoCamera(api, data=None)[source]

Bases: unifi_video.single.UnifiVideoSingle

Represents a single camera connected to a UniFi Video server (UnifiVideoAPI).

Variables:
  • name (str or NoneType) – Camera name
  • model (str or NoneType) – Camera model
  • platform (str or NoneType) – Firmware platform
  • overlay_text (str) – Custom text overlayd over the image
  • mac_addr (str) – Camera MAC address
  • utc_h_offset (int or NoneType) – UTC offset in hours
  • state (str) – Camera state
  • managed (bool) – Whether camera is managed by the UniFi Video instance
  • provisioned (bool) – Whether camera is provisioned
  • managed_by_others (bool) – Whether camera is managed by some other UniFi Video instance
  • disconnect_reason (str) – Reason for most recent disconnect
  • connected (bool) – Whether camera is connected (ie, not disconnected or in process of rebooting or being upgraded)
  • last_recording_id (str) – MongoDB ObjectID of latest recording
  • last_recording_start_time (int) – Unix timestamp (in ms): start time of latest recording
  • last_seen (int) –

    Unix timestamp (in ms). Meaning depends on the value of UnifiVideoCamera.state:

    • CONNECTED: timestamp for when the camera came online
    • DISCONNECTED: timestamp for when the camera went offline
  • last_seen_ndt (datetime or NoneType) – UnifiVideoCamera.last_seen as naive datetime object
  • _id (str) – Camera ID (MongoDB ObjectID as hex string)
  • _data (dict) – Complete camera JSON from UniFi Video server
  • _isp_actionables (list) – List of supported image settings

Warning

Attributes having to do with camera state reflect the state as it was during object instantiation.

Warning

UnifiVideoCamera.last_seen changes were observed on UniFi Video v3.10.13. No attempt has been made to verify UnifiVideoCamera.last_seen acts the same way across all supported UniFi Video versions.

brightness(val=None)

Control image brightness

Parameters:value (int or NoneType) – New brightness value (min: 0, max: 100)
Returns:True or False, depending on whether new value value was successfully registered. Current brightness value when called without input value.
Return type:bool or int
contrast(val=None)

Control image contrast

Parameters:value (int or NoneType) – New contrast value (min: 0, max: 100)
Returns:True or False, depending on whether new value value was successfully registered. Current contrast value when called without input value.
Return type:bool or int
denoise(val=None)

Control image denoise

Parameters:value (int or NoneType) – New denoise value (min: 0, max: 100)
Returns:True or False, depending on whether new value value was successfully registered. Current denoise value when called without input value.
Return type:bool or int
dynamic_range(val=None)[source]

Control image WDR (dynamic range). Input should be either None or an int between 0 and 3.

Parameters:wdr (int or None) – New WDR value
Returns:If value provided: True or False, depending on whether new value was registered. If no value provided: current WDR value.
Return type:bool or int
get_recording_settings(all=False)[source]

Get camera’s recording settings

Parameters:all (bool) – Whether to show all available settings. The default is to only show the settings that are controllable by calling set_recording_settings().
hue(val=None)

Control image hue

Parameters:value (int or NoneType) – New hue value (min: 0, max: 100)
Returns:True or False, depending on whether new value value was successfully registered. Current hue value when called without input value.
Return type:bool or int
ir_leds(led_state=None)[source]

Control IR leds.

Parameters:led_state (str or None) – New led state (auto, on, or off).
Returns:True or False depending on successful value change. Current led state if called with no args.
Return type:bool or str
onscreen_text(text=None)[source]

Set or get on-screen text.

Parameters:text (str or None) – New on-screen text
Returns:True for successful value change, Fail for failed attempt, current str value if called without text.
Return type:bool or str
onscreen_timestamp(enabled=None)[source]

Set or get on-screen timestamp state.

Parameters:enabled (bool or None) – New state
Returns:True for successful state change, Fail for failed attempt. Either of the two for current state (when called without the enabled arg)
Return type:bool
onscreen_watermark(enabled=None)[source]

Enable or disable on-screen watermark. Call without args to get current setting.

Parameters:enabled (bool or None) – Enable or disable
Returns:True for successful change, Fail for failed attempt. One or the other for calls without args.
Return type:bool
recording_between(start_time, end_time, filename=None)[source]

Download a recording of the camera’s footage from an arbitrary timespan, between start_time and end_time.

Parameters:
  • start_time (datetime or str or int) – Recording start time. (See dt_resolvable_to_ms().)
  • end_time (datetime or str or int) – Recording end time. (See dt_resolvable_to_ms().)
  • filename (str, optional) – Filename to save the recording to (a ZIP file). Will use whatever the server provides if left out.

Tip

Widen the time span by a few seconds at each end. UniFi Video often falls a little short of the exact start and end times.

saturation(val=None)

Control image saturation

Parameters:value (int or NoneType) – New saturation value (min: 0, max: 100)
Returns:True or False, depending on whether new value value was successfully registered. Current saturation value when called without input value.
Return type:bool or int
set_recording_settings(recording_mode=None, pre_padding_secs=None, post_padding_secs=None)[source]

Set recording mode and pre/post padding.

Possible recording modes:
  • disable: don’t record
  • fulltime: record at all times
  • motion: record when motion detected
Parameters:
  • recording_mode (str) – See above
  • pre_padding_secs (int) – Number of seconds to include pre-motion footage of
  • post_padding_secs (int) – Number of seconds to include post-motion footage of
sharpness(val=None)

Control image sharpness

Parameters:value (int or NoneType) – New sharpness value (min: 0, max: 100)
Returns:True or False, depending on whether new value value was successfully registered. Current sharpness value when called without input value.
Return type:bool or int
snapshot(filename=None, width=0)[source]

Take and download snapshot.

Parameters:
  • filename (str or None) – Filename to save the snapshot to
  • width (int) – Image width in pixels
update(save=False)[source]

Update settings from remote UniFi Video server (self._api). Call with True to write local settings to remote before updating.

Parameters:save (bool) – Whether to push settings to the camera

Recording unifi_video.recording

class unifi_video.recording.UnifiVideoRecording(api, data=None)[source]

Bases: unifi_video.single.UnifiVideoSingle

Recording container

Variables:
  • _id (str) – Recording ID (MongoDB ObjectID as hex string)
  • start_time (datetime) – Recording start time and date (local time)
  • end_time (datetime) – Recording end time and date (local time)
  • start_time_utc (datetime) – Recording start time and date (UTC)
  • end_time_utc (datetime) – Recording end time and date (UTC)
  • rec_type (str) – Recording type. Either motionRecording, or fullTimeRecording.
  • locked (bool, NoneType) – Whether or not recording is locked
  • in_progress (bool, NoneType) – Recording is in progress
  • marked_for_deletion (bool, NoneType) – Recording is marked for deletion
  • cameras (list) – List of camera IDs
delete()[source]

Delete recording

download(filename=None)[source]

Download recording

Parameters:filename (str, NoneType, bool) – Filename (str) to save the image as or True (bool) if you want the response body as a return value. You can also leave this out or set it to None or False and a filename will be generated for you.
Return value:

Depends on input params.

  • When filename is str, NoneType or False: True if write to file was successful, otherwise NoneType
  • When filename is True: raw response body (str)
motion(filename=None)[source]

Download recording motion

Parameters:filename (str, NoneType, bool) – Filename (str) to save the image as or True (bool) if you want the response body as a return value. You can also leave this out or set it to None or False and a filename will be generated for you.
Return value:

Depends on input params.

  • When filename is str, NoneType or False: True if write to file was successful, otherwise NoneType
  • When filename is True: raw response body (str)
snapshot(width=600, filename=None)[source]

Download recording thumbnail

Parameters:
  • width (int) – Image pixel width
  • filename (str, NoneType, bool) – Filename (str) to save the image as or True (bool) if you want the response body as a return value. You can also leave this out or set it to None or False and a filename will be generated for you.
Return value:

Depends on input params.

  • When filename is str, NoneType or False: True if write to file was successful, otherwise NoneType
  • When filename is True: raw response body (str)

Utils unifi_video.utils

unifi_video.utils.dt_resolvable_to_ms(resolvable, utc_offset=0, resolution=60000.0)[source]

Convert datetime resolvable to milliseconds since the Unix epoch.

Parameters:
  • resolvable (datetime or int or str) – Object that is resolvable to a date and time (see below)
  • utc_offset (int) – UTC offset in seconds
  • resolution (int) – Max resolution (in ms) for the returned timestamp. Default is to mimic UniFi Video frontend in providing at most minute granularity.
Returns:

Milliseconds since the Unix epoch

Return type:

int

On datetime resolvables

The type of the resolvable parameter will affect the return value.

datetime: Naive datetime values are offset by utc_offset while TZ aware datetime values are offset by whatever timedelta their datetime.datetime.utcoffset() returns.

str: Strings are treated as naive datetime values and should follow ISO8601 in including at least the YYYY, MM, and DD parts in either YYYY-MM-DD or YYYYMMDD.

int: Ints are assumed to be UNIX timestamps; only ms conversion and granularity changes will be applied.

unifi_video.utils.parse_gmt_offset(gmt_hhmm)[source]

Parse UTC offset as reported by UniFi Video

Parameters:gmt_hhmm (str) – UTC offset from /bootstrap JSON (settings.systemSettings.gmtOffset)
Returns
int: UTC offset in seconds