Beispiel #1
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
     # pylint: disable=protected-access
     self.blink._auth_header = {
         'Host': 'test.url.tld',
         'TOKEN_AUTH': 'foobar123'
     }
     self.blink.urls = blinkpy.BlinkURLHandler('test')
     self.blink.sync['test'] = BlinkSyncModule(self.blink, 'test', '1234',
                                               [])
     self.camera = BlinkCamera(self.blink.sync)
     self.mock_start = [
         {
             'syncmodule': {
                 'id': 1234,
                 'network_id': 5678,
                 'serial': '12345678',
                 'status': 'foobar'
             }
         },
         {
             'event': True
         },
         {},
         {},
         None,
         {
             'devicestatus': {}
         },
     ]
Beispiel #2
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME,
                                password=PASSWORD,
                                motion_interval=0)
     # pylint: disable=protected-access
     self.blink._auth_header = {
         "Host": "test.url.tld",
         "TOKEN_AUTH": "foobar123"
     }
     self.blink.last_refresh = 0
     self.blink.urls = blinkpy.BlinkURLHandler("test")
     self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", "1234",
                                               [])
     self.camera = BlinkCamera(self.blink.sync)
     self.mock_start = [
         {
             "syncmodule": {
                 "id": 1234,
                 "network_id": 5678,
                 "serial": "12345678",
                 "status": "foobar",
             }
         },
         {
             "event": True
         },
         {},
         {},
         None,
         {
             "devicestatus": {}
         },
     ]
     self.blink.sync["test"].network_info = {"network": {"armed": True}}
Beispiel #3
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
     # pylint: disable=protected-access
     self.blink._auth_header = {
         'Host': 'test.url.tld',
         'TOKEN_AUTH': 'foobar123'
     }
     self.blink.urls = blinkpy.BlinkURLHandler('test')
     self.config = {
         'device_id': 1111,
         'name': 'foobar',
         'armed': False,
         'active': 'disabled',
         'thumbnail': '/test',
         'video': '/test.mp4',
         'temp': 80,
         'battery': 3,
         'notifications': 2,
         'region_id': 'test',
         'device_type': 'camera'
     }
     self.blink.sync = MockSyncModule(self.blink, self.blink._auth_header)
     self.blink.session = create_session()
     self.camera = BlinkCamera(self.config, self.blink.sync)
Beispiel #4
0
 def connect(self, username, password):
     if self.use_local==True:
         click.echo("Loading locally Blink test object from " + self.pickle_path())
         self.pickle_load()
     else:
         click.echo("Opening connection to Blink servers")
         self.blink = blinkpy.Blink(username=username, password=password)
         self.blink.start()
Beispiel #5
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
     # pylint: disable=protected-access
     self.blink._auth_header = {
         'Host': 'test.url.tld',
         'TOKEN_AUTH': 'foobar123'
     }
     self.blink.urls = blinkpy.BlinkURLHandler('test')
     self.blink.session = create_session()
Beispiel #6
0
def setup(hass, config):
    """Set up Blink System."""
    from blinkpy import blinkpy

    conf = config[BLINK_DATA]
    username = conf[CONF_USERNAME]
    password = conf[CONF_PASSWORD]
    scan_interval = conf[CONF_SCAN_INTERVAL]
    is_legacy = bool(conf[CONF_MODE] == "legacy")
    motion_interval = conf[CONF_OFFSET]
    hass.data[BLINK_DATA] = blinkpy.Blink(
        username=username,
        password=password,
        motion_interval=motion_interval,
        legacy_subdomain=is_legacy,
    )
    hass.data[BLINK_DATA].refresh_rate = scan_interval.total_seconds()
    hass.data[BLINK_DATA].start()

    platforms = [
        ("alarm_control_panel", {}),
        ("binary_sensor", conf[CONF_BINARY_SENSORS]),
        ("camera", {}),
        ("sensor", conf[CONF_SENSORS]),
    ]

    for component, schema in platforms:
        discovery.load_platform(hass, component, DOMAIN, schema, config)

    def trigger_camera(call):
        """Trigger a camera."""
        cameras = hass.data[BLINK_DATA].cameras
        name = call.data[CONF_NAME]
        if name in cameras:
            cameras[name].snap_picture()
        hass.data[BLINK_DATA].refresh(force_cache=True)

    def blink_refresh(event_time):
        """Call blink to refresh info."""
        hass.data[BLINK_DATA].refresh(force_cache=True)

    async def async_save_video(call):
        """Call save video service handler."""
        await async_handle_save_video_service(hass, call)

    hass.services.register(DOMAIN, SERVICE_REFRESH, blink_refresh)
    hass.services.register(DOMAIN,
                           SERVICE_TRIGGER,
                           trigger_camera,
                           schema=SERVICE_TRIGGER_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_SAVE_VIDEO,
                           async_save_video,
                           schema=SERVICE_SAVE_VIDEO_SCHEMA)
    return True
Beispiel #7
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME,
                                password=PASSWORD)
     # pylint: disable=protected-access
     self.blink._auth_header = {
         'Host': 'test.url.tld',
         'TOKEN_AUTH': 'foobar123'
     }
     self.blink.urls = blinkpy.BlinkURLHandler('test')
     self.blink.sync['test'] = BlinkSyncModule(self.blink, 'test', '1234')
     self.camera = BlinkCamera(self.blink.sync)
Beispiel #8
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
     header = {
         'Host': 'abc.zxc',
         'TOKEN_AUTH': mresp.LOGIN_RESPONSE['authtoken']['authtoken']
     }
     # pylint: disable=protected-access
     self.blink._auth_header = header
     self.blink.session = create_session()
     self.blink.urls = BlinkURLHandler('test')
     self.blink.sync['test'] = BlinkSyncModule(self.blink, 'test', 1234, [])
     self.camera = BlinkCamera(self.blink.sync['test'])
     self.camera.name = 'foobar'
     self.blink.sync['test'].cameras['foobar'] = self.camera
Beispiel #9
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
     header = {
         "Host": "abc.zxc",
         "TOKEN_AUTH": mresp.LOGIN_RESPONSE["authtoken"]["authtoken"],
     }
     # pylint: disable=protected-access
     self.blink._auth_header = header
     self.blink.session = create_session()
     self.blink.urls = BlinkURLHandler("test")
     self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", 1234, [])
     self.camera = BlinkCamera(self.blink.sync["test"])
     self.camera.name = "foobar"
     self.blink.sync["test"].cameras["foobar"] = self.camera
Beispiel #10
0
 def test_download_video_exit(self, mock_req):
     """Test we exit method when provided bad response."""
     blink = blinkpy.Blink()
     # pylint: disable=protected-access
     blinkpy._LOGGER.setLevel(logging.DEBUG)
     blink.last_refresh = 0
     mock_req.return_value = {}
     formatted_date = get_time(blink.last_refresh)
     expected_log = [
         "INFO:blinkpy.blinkpy:Retrieving videos since {}".format(formatted_date),
         "DEBUG:blinkpy.blinkpy:Processing page 1",
         "INFO:blinkpy.blinkpy:No videos found on page 1. Exiting.",
     ]
     with self.assertLogs() as dl_log:
         blink.download_videos("/tmp")
     self.assertEqual(dl_log.output, expected_log)
Beispiel #11
0
    def setUp(self):
        """Set up Blink module."""
        self.blink = blinkpy.Blink(username=USERNAME,
                                   password=PASSWORD)
        self.camera_config = {
            'device_id': 1111,
            'name': 'foobar',
            'armed': False,
            'active': 'disarmed',
            'thumbnail': '/test/image',
            'video': '/test/clip/clip.mp4',
            'temp': 70,
            'battery': 3,
            'notifications': 2,
            'region_id': 'test'
        }

        self.blink.urls = blinkpy.BlinkURLHandler('test')
        self.blink.network_id = '0000'
Beispiel #12
0
 def test_parse_camera_not_in_list(self, mock_req, mock_sess):
     """Test ability to parse downloaded items list."""
     blink = blinkpy.Blink()
     # pylint: disable=protected-access
     blinkpy._LOGGER.setLevel(logging.DEBUG)
     generic_entry = {
         'created_at': '1970',
         'device_name': 'foo',
         'deleted': True,
         'media': '/bar.mp4'
     }
     result = [generic_entry]
     mock_req.return_value = {'media': result}
     blink.last_refresh = 0
     formatted_date = get_time(blink.last_refresh)
     expected_log = [
         "INFO:blinkpy.blinkpy:Retrieving videos since {}".format(
             formatted_date), "DEBUG:blinkpy.blinkpy:Processing page 1",
         "DEBUG:blinkpy.blinkpy:Skipping videos for foo."
     ]
     with self.assertLogs() as dl_log:
         blink.download_videos('/tmp', camera='bar', stop=2)
     self.assertEqual(dl_log.output, expected_log)
Beispiel #13
0
 def test_parse_downloaded_items(self, mock_req):
     """Test ability to parse downloaded items list."""
     blink = blinkpy.Blink()
     # pylint: disable=protected-access
     blinkpy._LOGGER.setLevel(logging.DEBUG)
     generic_entry = {
         "created_at": "1970",
         "device_name": "foo",
         "deleted": True,
         "media": "/bar.mp4",
     }
     result = [generic_entry]
     mock_req.return_value = {"media": result}
     blink.last_refresh = 0
     formatted_date = get_time(blink.last_refresh)
     expected_log = [
         "INFO:blinkpy.blinkpy:Retrieving videos since {}".format(formatted_date),
         "DEBUG:blinkpy.blinkpy:Processing page 1",
         "DEBUG:blinkpy.blinkpy:foo: /bar.mp4 is marked as deleted.",
     ]
     with self.assertLogs() as dl_log:
         blink.download_videos("/tmp", stop=2, delay=0)
     self.assertEqual(dl_log.output, expected_log)
Beispiel #14
0
    def setUp(self):
        """Set up Blink module."""
        self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
        self.camera_config = {
            'device_id': 1111,
            'name': 'foobar',
            'armed': False,
            'active': 'disarmed',
            'thumbnail': '/test/image',
            'video': '/test/clip/clip.mp4',
            'temp': 70,
            'battery': 3,
            'notifications': 2,
            'region_id': 'test'
        }

        header = {
            'Host': 'abc.zxc',
            'TOKEN_AUTH': mresp.LOGIN_RESPONSE['authtoken']['authtoken']
        }
        self.blink.session = create_session()
        self.blink.urls = BlinkURLHandler('test')
        self.blink.network_id = '0000'
        self.sync = BlinkSyncModule(self.blink, header, self.blink.urls)
Beispiel #15
0
VIDEO_FILENAME = "BlinkVideo.mp4"
IMAGE_FILENAME = "BlinkImage.png"
OFFSET_SECONDS = 60
TIMEOUT_SECONDS = 60
NOTIFY_ENTITY_NAMES = ["mobile_app_dullage_s_iphone", "mobile_app_iphone"]
# NOTIFY_ENTITY_NAMES = ["mobile_app_dullage_s_iphone"]  # Debug

VIDEO_FILE = os.path.join(SAVE_PATH, VIDEO_FILENAME)
IMAGE_FILE = os.path.join(SAVE_PATH, IMAGE_FILENAME)

with open(SECRETS_FILE, "r") as secrets_file:
    secrets = yaml.load(secrets_file)

blink = blinkpy.Blink(
    username=secrets["blinkUsername"],
    password=secrets["blinkPassword"],
    device_id="Doorbell Script",
    no_prompt=True,
)
blink.start()

from_time = time.time() - OFFSET_SECONDS
loop_start = datetime.today()
while True:
    videos = api.request_videos(blink, time=from_time)["media"]

    if len(videos) >= 1:
        break

    if datetime.today() >= (loop_start + timedelta(seconds=TIMEOUT_SECONDS)):
        break
Beispiel #16
0
from blinkpy import blinkpy

try:
    username = environ['USERNAME']
except KeyError:
    sys.exit("'USERNAME' environment variable is not set")
try:
    password = environ['PASSWORD']
except KeyError:
    sys.exit("'PASSWORD' environment variable is not set")
try:
    camera_names = environ['CAMERAS'].split(',')
except KeyError:
    sys.exit("'CAMERAS' environment variable is not set")

blink = blinkpy.Blink(username=username, password=password)
blink.start()

print(f'Taking pictures for cameras: {", ".join(camera_names)}')

for camera_name in camera_names:
    camera = blink.cameras[camera_name]
    camera.snap_picture()
    blink.refresh()

    path = f'/images/{camera_name}-{datetime.utcnow().isoformat(timespec="seconds")}.jpg'

    camera.image_to_file(path)
    print(f'Image from {camera_name} saved to {path}')
Beispiel #17
0
parser.add_argument("--destination", default=".", help="Save path")
parser.add_argument("--debug",
                    action="store_true",
                    help="Save matched list of videos to file")
args = parser.parse_args()

# Connect to Blink server.
if args.username and args.password:
    USERNAME = args.username
    PASSWORD = args.password
else:
    with open(args.secrets, "r") as secrets_file:
        secrets = yaml.safe_load(secrets_file)
    USERNAME = secrets[args.secrets_username]
    PASSWORD = secrets[args.secrets_password]
blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
blink.start()

# Fetch list of latest videos.
from_time = time.time() - args.offset
loop_start = datetime.today()
while True:
    videos = api.request_videos(blink, time=from_time)["media"]

    if args.camera:
        videos_device = []
        for video in videos:
            if video.get("device_name") == args.camera:
                videos_device.append(video)
        videos = videos_device
Beispiel #18
0
 def setUp(self):
     """Set up Blink module."""
     self.blink_no_cred = blinkpy.Blink()
     self.blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
Beispiel #19
0
def start():
    """Startup blink app."""
    blink = blinkpy.Blink(username=USERNAME, password=PASSWORD)
    blink.start()
    return blink
Beispiel #20
0
import os
from blinkpy import blinkpy

username = os.getenv('BLINK_USERNAME', 'fake')
password = os.getenv('BLINK_PASSWORD', 'fake')

blink = blinkpy.Blink(username=username, password=password, refresh_rate=30)
blink.start()
blink.refresh()

for name, camera in blink.cameras.items():
    print(name)  # Name of the camera
    print('Temp is {}'.format(camera.temperature_c))

camera_name = os.getenv('BLINK_CAMERA_NAME', 'Main Garden')
camera = blink.cameras[camera_name]
camera.snap_picture()
blink.refresh()

# Hard code saving of file, this assumes docker in use. Might want to change this.
camera.image_to_file('/data/bob.jpg')
Beispiel #21
0
 def __init__(self):
     self.blink = blinkpy.Blink(
         username=config.blink['username'], password=config.blink['password'], refresh_rate=config.blink['refresh_rate'])
     self.blink.start()
Beispiel #22
0
from blinkpy import blinkpy


blink = blinkpy.Blink(username='******', password='******', refresh_rate=30)

blink.start()

for name, camera in blink.cameras.items():
  print(name)                   # Name of the camera
  print(camera.attributes['temperature'])      # Print available attributes of camera
  print(camera.attributes['motion_enabled'])
  print(camera.attributes['motion_detected'])
Beispiel #23
0
def login(USER, PASS):
    blink = blinkpy.Blink(username=USER, password=PASS)
    blink.start()
    blink.refresh()  # Get new information from server
    return blink
Beispiel #24
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = blinkpy.Blink()
     self.blink.urls = BlinkURLHandler("test")
Beispiel #25
0
import codecs
import pickle
import threading
from shutil import copyfileobj
import json
from urllib.request import urlopen, Request

import webview
from flask import Flask, render_template, request, jsonify, redirect, make_response, url_for
from blinkpy import blinkpy
from blinkpy.helpers.util import BlinkException
from blinkpy import api as blinkapi

import certifi

blink = blinkpy.Blink()
cache = {}
CACHEDIR = os.path.abspath(
    os.path.expanduser(os.path.join('~', '.blinky_cache')))
print("CACHEDIR: %s" % CACHEDIR)

import blinky

PKGDIR = os.path.dirname(os.path.abspath(blinky.__file__))
print("PKGDIR: %s" % PKGDIR)

app = Flask(
    __name__,
    #template_folder=os.path.join(PKGDIR, 'templates'),
    #static_folder=os.path.join(PKGDIR, 'static'),
    root_path=PKGDIR)
def get_blink_module(username, password):
    blink = blinkpy.Blink(username=username, password=password, refresh_rate=15)
    blink.start()
    return blink
Beispiel #27
0
 def __init__(self, username, password, network, logger):
     self._logger = logger
     self._network = network
     self._logger.info("Connecting to Blink")
     self._blink = blinkpy.Blink(username, password)
     self._blink.start()