Esempio n. 1
0
 def test_login(self):
     """
     """
     arlo = Arlo(USERNAME, PASSWORD)
     response = arlo.Login(USERNAME, PASSWORD)
     
     assert response["token"] == LOGIN_JSON["data"]["token"]
Esempio n. 2
0
def handler(event, context):

    # config values
    USERNAME = os.getenv('USERNAME')
    PASSWORD = os.getenv('PASSWORD')
    S3BUCKET = os.getenv('S3BUCKET')
    prefix = os.getenv('prefix')

    arlo = Arlo(USERNAME, PASSWORD)

    s3 = boto3.client('s3')

    # get basestation, camera pairs
    # camera['parentId'] refers to basestation['deviceId']
    basestations = arlo.GetDevices('basestation')
    cameras = arlo.GetDevices('camera')

    for camera in cameras:
        basestation = [
            b for b in basestations if b['deviceId'] == camera['parentId']
        ][0]

        url = arlo.TriggerFullFrameSnapshot(basestation, camera)
        print(url)

        content_key = prefix + camera['deviceName'] + '/' + str(
            datetime.datetime.now()) + '.jpg'
        r = requests.get(url, stream=True)
        r.raw.decode_content = True

        print('uploading to: s3://' + S3BUCKET + '/' + content_key)
        s3.upload_fileobj(r.raw, S3BUCKET, content_key)
Esempio n. 3
0
    def __init__(self):
        super(ArloWrap, self).__init__()
        self.USERNAME = os.getenv("ARLO_USER")
        self.PASSWORD = os.getenv("ARLO_PASS")
        self.arlo = Arlo(self.USERNAME, self.PASSWORD)

        # Get the list of devices and filter on device type to only get the basestation.
        # This will return an array which includes all of the basestation's associated metadata.
        self.basestation = self.arlo.GetDevices("basestation")[0]

        # Get the list of devices and filter on device type to only get the cameras.
        # This will return an array of cameras, including all of the cameras' associated metadata.
        self.camera = self.arlo.GetDevices("camera")[1]
Esempio n. 4
0
def get_snapshot():
    while True:
        try:
            snapshot_url = camera_selenium.get_url_selenium()
            # print(snapshot_url)

            username, password = util.get_creds()
            # print(username)
            arlo = Arlo(username, password)

            arlo.DownloadSnapshot(snapshot_url, 'temp.jpg')
            img = cv2.imread('temp.jpg')
            img = cv2.resize(img, (1000, 500))
            return img
        except Exception as e:
            print(e)
def motion_detection():

    global nb_alert, time_lastalert
    nb_alert = 0
    time_lastalert = datetime.datetime.now() - datetime.timedelta(
        days=1)  # On initialise la variable time_lastalert à J-1
    print("ARLO - Motion detection (uniquement lorsque la caméra est armée)")
    while True:
        try:
            arlo = Arlo(ArloLogin, ArloPassword)
            base = arlo.GetDevices('basestation')[
                0]  # get base station info, assuming only 1 is available
            arlo.SubscribeToMotionEvents(base, motion_callback)
            #arlo.HandleEvents(base, motion_callback)

        except Exception as e:
            print(e)
            time.sleep(10)  # Si erreur, on fait une pause de 10s
Esempio n. 6
0
    def test_get_service_level_v4(self):
        """
        """
        mocked_url = "https://my.arlo.com/hmsweb/users/serviceLevel/v4"
        mock_json = {}

        with open('./responses/expected_get_service_level_v4_response.json') as json_file:
            mock_json = json.load(json_file)

        responses.add(
            method = responses.GET,
            url = mocked_url,
            json = mock_json,
            status = 200
        )

        arlo = Arlo(USERNAME, PASSWORD)
        response = arlo.GetServiceLevelV4()
        
        assert response["planDetails"]["planId"] == mock_json["data"]["planDetails"]["planId"]
Esempio n. 7
0
    def test_get_payment_offers_v4(self):
        """
        """
        mocked_url = "https://my.arlo.com/hmsweb/users/payment/offers/v4"
        mock_json = {}

        with open('./responses/expected_get_payment_offers_v4_response.json') as json_file:
            mock_json = json.load(json_file)

        responses.add(
            method = responses.GET,
            url = mocked_url,
            json = mock_json,
            status = 200
        )

        arlo = Arlo(USERNAME, PASSWORD)
        response = arlo.GetPaymentOffersV4()
        
        assert response[0]["planId"] == mock_json["data"][0]["planId"]
Esempio n. 8
0
    def test_get_modes_v2(self):
        """
        """
        mocked_url = "https://my.arlo.com/hmsweb/users/devices/automation/active"
        mock_json = {}

        with open('./responses/expected_get_modes_v2_response.json') as json_file:
            mock_json = json.load(json_file)

        responses.add(
            method = responses.GET,
            url = mocked_url,
            json = mock_json,
            status = 200
        )

        arlo = Arlo(USERNAME, PASSWORD)
        response = arlo.GetModesV2()
        
        assert response[0]["uniqueId"] == mock_json["data"][0]["uniqueId"]
Esempio n. 9
0
    def test_get_account(self):
        """
        """
        mocked_url = "https://my.arlo.com/hmsweb/users/account"
        mock_json = {}

        with open('./responses/expected_get_account_response.json') as json_file:
            mock_json = json.load(json_file)

        responses.add(
            method = responses.GET,
            url = mocked_url,
            json = mock_json,
            status = 200
        )

        arlo = Arlo(USERNAME, PASSWORD)
        response = arlo.GetAccount()
        
        assert response["email"] == mock_json["data"]["email"]
Esempio n. 10
0
    def test_get_devices(self):
        """
        """
        mocked_url = "https://my.arlo.com/hmsweb/users/devices"
        mock_json = {}

        with open('./responses/expected_get_devices_response.json') as json_file:
            mock_json = json.load(json_file)

        responses.add(
            method = responses.GET,
            url = mocked_url,
            json = mock_json,
            status = 200
        )

        arlo = Arlo(USERNAME, PASSWORD)
        response = arlo.GetDevices()
        
        assert response[0]["deviceName"] == mock_json["data"][0]["deviceName"]
Esempio n. 11
0
    def run(self):
        self.log.info('Connecting to Arlo')
        self.arlo = Arlo(self.arlo_user, self.arlo_pass)
        self.arlo_bases = {}
        self.arlo_cams = {}

        self.report_thread.start()

        try:
            while True:
                if self.stop.wait(self.report_interval * 2):
                    break

                if time.time(
                ) - self.last_reported_ts > self.report_interval * 2:
                    self.log.error('Report timeout')
                    break
        finally:
            self.log.info('Main thread stopped')
            self.stop.set()
Esempio n. 12
0
    def test_get_profile(self):
        """
        """
        mocked_url = "https://my.arlo.com/hmsweb/users/profile"
        mock_json = {}

        with open('./responses/expected_get_profile_response.json') as json_file:
            mock_json = json.load(json_file)

        responses.add(
            method = responses.GET,
            url = mocked_url,
            json = mock_json,
            status = 200
        )

        arlo = Arlo(USERNAME, PASSWORD)
        response = arlo.GetProfile()
        
        assert response["firstName"] == mock_json["data"]["firstName"]
        assert response["lastName"] == mock_json["data"]["lastName"]
Esempio n. 13
0
    def _capture(self):
        print(f'Starting capture.')
        try:
            arlo = Arlo(self._username, self._password)

            base_stations = arlo.GetDevices('basestation')
            cameras = arlo.GetDevices('camera', filter_provisioned=True)

            for camera in cameras:
                name = camera['deviceName']
                if self._camera_names is not None and name not in self._camera_names:
                    continue

                print(f'- Taking snapshot from {name}')
                url = arlo.TriggerFullFrameSnapshot(base_stations[0], camera)

                if url is not None:
                    file_name = name + '_' + str(time.time())
                    file_name = file_name.replace(' ', '_')

                    arlo.DownloadSnapshot(
                        url, f'{self._snapshot_dir }/{file_name}.jpg')
                else:
                    print(f'-- Snapshot failed from {name}.')
        except HTTPError as e:
            print(f'Error during capture: {e}.')
Esempio n. 14
0
def click_picture_from_arlo(
        ctx,
        folder,
        filetag,
        username,
        password):
    # Instantiating the Arlo object automatically calls Login(),
    # which returns an oAuth token that gets cached.
    # Subsequent successful calls to login will update the oAuth token.
    arlo = Arlo(username, password)

    # Get the list of devices and filter on device type to only get the basestation.
    # This will return an array which includes all of the basestation's associated metadata.
    basestations = arlo.GetDevices('basestation')
    # Get the list of devices and filter on device type to only get the camera.
    # This will return an array which includes all of the camera's associated metadata.
    cameras = arlo.GetDevices('camera')

    # Tells the Arlo basestation to trigger a snapshot on the given camera.
    # This snapshot is not instantaneous, so this method waits for the response and returns the url
    # for the snapshot, which is stored on the Amazon AWS servers.
    snapshot_url = arlo.TriggerFullFrameSnapshot(basestations[0], cameras[0])

    # This method requests the snapshot for the given url and writes the image data to the location specified.
    # Note: Snapshots are in .jpg format.
    timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    filename = filetag + '_' + str(timestamp) + '.jpg'
    filepath = folder + '\\' + filename
    arlo.DownloadSnapshot(snapshot_url, filepath)
    ctx.obj['path-to-picture'] = filepath
    ctx.obj['filename'] = filename
    print('Downloaded snapshot to ' + filepath)
Esempio n. 15
0
 def disarmarlo(message):
     """disarm arlo
        Disable motion detection for the Arlo system.
     """
     if (os.environ['TARGET_DEVICE'] != 'all'
             and os.environ['TARGET_DEVICE'] != device_name):
         return
     post = slackmq(os.environ['API_TOKEN'], message.body['channel'],
                    message.body['ts'])
     if not post.ack():
         return
     if eval(os.environ['DEBUG']):
         debug = "[{}] ".format(device_name)
     else:
         debug = ""
     message.send(":rotating_light: {}Disarming Arlo.".format(debug))
     arlo = Arlo(settings.servers.arlo.username,
                 settings.servers.arlo.password)
     basestations = arlo.GetDevices('basestation')
     arlo.Disarm(basestations[0])
     message.send(":rotating_light: {}Arlo is disarmed.".format(debug))
     post.unack()
def switch(command, i=0):

    try:
        arlo = Arlo(ArloLogin, ArloPassword)
        base = arlo.GetDevices('basestation')[
            0]  # get base station info, assuming only 1 is available
        camera = arlo.GetDevices('camera')[
            0]  # get camera info, assuming only 1 is available

        print("Command: " + command)

        if command == "status":
            print("ARLO -- Camera current mode: " + get_current_state(arlo))

        elif command == "armed":
            #print("ARLO -- Camera old mode: " + get_current_state(arlo))
            arlo.Arm(base)
            print("ARLO -- Camera new mode: " + get_current_state(arlo))

        else:
            #print("ARLO -- Camera old mode: " + get_current_state(arlo))
            arlo.Disarm(base)
            print("ARLO -- Camera new mode: " + get_current_state(arlo))

    # On tente d'exécuter la commande 8 fois maximum
    except Exception as e:
        print(e)
        if i < 8:
            print("ARLO -- Connexion Error - new try ... (" + str(i + 1) +
                  "/8)")
            switch(command, i + 1)
            return
        else:
            print("ARLO -- Connexion Errors -- command failed " + str(i) +
                  " times. Exit")
            raise SystemExit(1)  # Return failure

    # Enregistre l'état de la batterie (pour lecture dans Domoticz)
    time.sleep(1)
    cam_battery_level = arlo.GetCameraState(
        base)["properties"][0]["batteryLevel"]
    print("ARLO -- Camera Battery: " + str(cam_battery_level) +
          " % -> into file /tmp/arlo_cam1.txt")
    with open('/tmp/arlo_cam1.txt', 'w') as f:
        f.write(str(cam_battery_level))
Esempio n. 17
0
class ArloWrap:
    def __init__(self):
        super(ArloWrap, self).__init__()
        self.USERNAME = os.getenv("ARLO_USER")
        self.PASSWORD = os.getenv("ARLO_PASS")
        self.arlo = Arlo(self.USERNAME, self.PASSWORD)

        # Get the list of devices and filter on device type to only get the basestation.
        # This will return an array which includes all of the basestation's associated metadata.
        self.basestation = self.arlo.GetDevices("basestation")[0]

        # Get the list of devices and filter on device type to only get the cameras.
        # This will return an array of cameras, including all of the cameras' associated metadata.
        self.camera = self.arlo.GetDevices("camera")[1]

    def take_snapshot(self):
        try:
            start = time.time()

            # Trigger the snapshot.
            url = self.trigger_timeout()

            if url:
                timezone = pytz.timezone("Europe/London")
                now = datetime.now(timezone).replace(microsecond=0)
                fname = f"snapshot-{now.isoformat()}.jpg"

                # with SFTP() as sftp:
                #     sftp.upload_snaphot(url, fname)
                upload_image_file(url, "arlocam-snapshots", fname)

                print(f"uploaded shot: {fname}")

                result = db.snapshots.insert_one(
                    {"file_name": fname, "created_date": now}
                )
                print(f"Data inserted with record ids: {result.inserted_id}")

            else:
                print("skipped, url not found")

            print(time.time() - start)

        except Exception as e:
            print(e)

    def trigger_timeout(self):
        try:
            url = func_timeout(
                60,
                self.arlo.TriggerFullFrameSnapshot,
                args=(self.basestation, self.camera),
            )

        except FunctionTimedOut:
            print("timed out")
            url = None

        return url

    def start_stream(self):
        try:

            # Open the event stream to act as a keep-alive for our stream.
            self.arlo.Subscribe(self.basestation)

            # Send the command to start the stream and return the stream url.
            url = self.arlo.StartStream(self.basestation, self.camera)
            return url

        except Exception as e:
            print(e)
            return None
Esempio n. 18
0
from arlo import Arlo

USERNAME = '******'
PASSWORD = '******'

try:
    # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
    # Subsequent successful calls to login will update the oAuth token.
    arlo = Arlo(USERNAME, PASSWORD)
    # At this point you're logged into Arlo.

    # Get the list of devices and filter on device type to only get the basestation.
    # This will return an array which includes all of the basestation's associated metadata.
    basestations = arlo.GetDevices('basestation')

    # Get the list of devices and filter on device type to only get the camera.
    # This will return an array which includes all of the camera's associated metadata.
    cameras = arlo.GetDevices('camera')

    # Get current state payload
    state = arlo.GetCameraState(cameras[0])
    print(state["properties"][0]["nightLight"])

    # night light on
    arlo.SetNightLightOn(cameras[0])

    # night light timer on
    arlo.SetNightLightTimerOn(cameras[0], 500)

    # night light color mode
    arlo.SetNightLightMode(cameras[0],
Esempio n. 19
0
import requests
import json
from arlo import Arlo

USERNAME = ''
PASSWORD = ''

print('Api is listening\n')

try:

    arlo = Arlo(USERNAME, PASSWORD)

    basestations = arlo.GetDevices('basestation')

    def callback(arlo, event):

        print("Motion has been Detected")

        body = json.dumps({
            "notification": "Motion has been Detected",
            "accessCode": ""
        })
        requests.post(url="https://api.notifymyecho.com/v1/NotifyMe",
                      data=body)

    arlo.SubscribeToMotionEvents(basestations[0], callback)

except Exception as e:
    print(e)
Esempio n. 20
0
#!/usr/bin/env python3
from arlo import Arlo
import argparse
import sys
import settings

parser = argparse.ArgumentParser(description="Arlo Device Listererer")
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='Enable verbose output')
args = parser.parse_args()

device_map = {}

try:
    if args.verbose:
        print(sys.argv[0] + ": Logging in with", settings.USERNAME)
    arlo = Arlo(settings.USERNAME, settings.PASSWORD)

    if args.verbose:
        print(sys.argv[0] + ": Fetching devices")
    # build a map of device Names to device IDs
    # as names are not exposed in GetCameraState()
    devices = arlo.GetDevices()
    for d in devices:
        _deviceId = d['deviceId']
        device_map[_deviceId] = {}
        device_map[_deviceId]['name'] = d['deviceName']

    # fetch basestations
    if args.verbose:
        print(sys.argv[0] + ": Fetching basestations")
    basestations = arlo.GetDevices('basestation')
Esempio n. 21
0
        except Exception as e:
            print("Failed to request state information from Basestation")
            print(e)
            # Wait before retrying
            time.sleep(INTERVAL)


## Initiate MQTT client
client = mqtt.Client()
client.connect(MQTT_HOST, MQTT_PORT, 60)
client.loop_start()

# Instantiating the Arlo object automatically calls Login(), which returns an oAuth token 
# that gets cached. Subsequent successful calls to login will update the oAuth token.
arlo = Arlo(USERNAME, PASSWORD)
# At this point you're logged into Arlo.

# Get the list of devices and filter on device type to only get the basestation.
# This will return an array which includes all of the basestation's associated metadata.
basestations = arlo.GetDevices('basestation')

x = threading.Thread(target=stateEventGenerator, args=(arlo, basestations[0]))
x.start()

while True:
    try:
        print('Listen for ARLO events...')
        arlo.HandleEvents(basestations[0], ArloHandler(client))
    except queue.Empty as e:
        continue
Esempio n. 22
0
def login(USERNAME, PASSWORD):
    global arlo
    arlo = Arlo(USERNAME, PASSWORD)
    global basestations
    basestations = arlo.GetDevices('basestation')
Esempio n. 23
0
from arlo import Arlo

from datetime import timedelta, date
import datetime
import sys
import os.path

USERNAME = '******'
PASSWORD = '******'

try:
        # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
        # Subsequent successful calls to login will update the oAuth token.
        arlo = Arlo(USERNAME, PASSWORD)
        # At this point you're logged into Arlo.

        today = (date.today()-timedelta(days=0)).strftime("%Y%m%d")
        seven_days_ago = (date.today()-timedelta(days=7)).strftime("%Y%m%d")

        # Get all of the recordings for a date range.
        library = arlo.GetLibrary(seven_days_ago, today)

        # Iterate through the recordings in the library.
        for recording in library:
                videofilename = datetime.datetime.fromtimestamp(int(recording['name'])//1000).strftime('%Y-%m-%d %H-%M-%S') + ' ' + recording['uniq$
                ##
                # The videos produced by Arlo are pretty small, even in their longest, best quality settings,
                # but you should probably prefer the chunked stream (see below). 

                #    # Download the whole video into memory as a single chunk.
                #    video = arlo.GetRecording(recording['presignedContentUrl'])
Esempio n. 24
0
    with open(videofilename, 'wb') as f:
        for chunk in stream:
            f.write(chunk)
        f.close()
    return


if __name__ == "__main__":

    USERNAME = '******'
    PASSWORD = '******'

    try:
        # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
        # Subsequent successful calls to login will update the oAuth token.
        arlo = Arlo(USERNAME, PASSWORD)

        today = (date.today() - timedelta(days=0)).strftime("%Y%m%d")
        yesterday = (date.today() - timedelta(days=1)).strftime("%Y%m%d")

        # Get all of the recordings for a date range.
        library = arlo.GetLibrary(yesterday, today)

        # Get most recent 4 videos in the library.
        for num in range(4):
            recording = library[num]
            vfname = "media/video" + str(num + 1) + ".mp4"
            writeVideoFile(arlo, recording, vfname)

        print("Successfully downloaded and updated 4 videos")
Esempio n. 25
0
    print(
        "Please hold on while we recieve cameras and start detection threads..."
    )

    print("Setting up source_list...")

    print("Adding local cameras...")
    source_list = [0]
    if use_arlo:
        print("Waiting for Arlo cameras...")
        try:

            # Instantiating the Arlo object automatically calls Login(),
            # which returns an oAuth token that gets cached.
            # Subsequent successful calls to login will update the oAuth token.
            arlo = Arlo(USERNAME, PASSWORD)
            # At this point you're logged into Arlo.

            # Get the list of devices and filter on device type to only get the cameras.
            # This will return an array which includes all of the canera's associated metadata.
            cameras = arlo.GetDevices('camera')

            # Get the list of devices and filter on device type to only get the basestation.
            # This will return an array which includes all of the basestation's associated metadata.
            basestations = arlo.GetDevices('basestation')

            # Open the event stream to act as a keep-alive for our stream.
            arlo.Subscribe(basestations[0])

            # Send the command to start the stream and return the stream url.
            #url = arlo.StartStream(basestations[0], cameras[0])
Esempio n. 26
0
class ArloMqtt:
    def __init__(self, args):
        self.log = logging.getLogger(type(self).__name__)
        if args.debug:
            self.log.setLevel(logging.DEBUG)

        self.report_interval = args.report_interval

        self.report_thread = threading.Thread(target=self.report_thread_fn,
                                              daemon=True)
        self.stop = threading.Event()
        self.last_reported_ts = time.time()

        self.arlo_user = args.arlo_user
        self.arlo_pass = args.arlo_pass

        self.mqtt_settings = {
            'MQTT_BROKER': args.broker,
            'MQTT_PORT': args.port,
            'MQTT_USERNAME': args.mqtt_user,
            'MQTT_PASSWORD': args.mqtt_pass,
        }

    def report_thread_fn(self):
        try:
            while True:
                self.report()
                self.last_reported_ts = time.time()

                if self.stop.wait(self.report_interval):
                    break
        except Exception:
            self.log.exception('Report thread failed')
        finally:
            self.log.info('Report thread stopped')
            self.stop.set()

    def run(self):
        self.log.info('Connecting to Arlo')
        self.arlo = Arlo(self.arlo_user, self.arlo_pass)
        self.arlo_bases = {}
        self.arlo_cams = {}

        self.report_thread.start()

        try:
            while True:
                if self.stop.wait(self.report_interval * 2):
                    break

                if time.time(
                ) - self.last_reported_ts > self.report_interval * 2:
                    self.log.error('Report timeout')
                    break
        finally:
            self.log.info('Main thread stopped')
            self.stop.set()

    def report(self):
        self.log.info('Reporting status')

        # Fetching devices and states from Arlo
        devices = [
            dev for dev in self.arlo.GetDevices() if dev['state'] != 'removed'
        ]

        bases = {
            dev['deviceId']: dev
            for dev in devices if dev['deviceType'] == 'basestation'
        }

        cams = {
            dev['deviceId']: dev
            for dev in devices if dev['deviceType'] == 'camera'
        }

        for mode in self.arlo.GetModesV2():
            id = mode['gatewayId']
            if id in bases:
                bases[id]['modeState'] = mode

        for base in bases.values():
            for state in self.arlo.GetCameraState(base)['properties']:
                id = state['serialNumber']
                if id in cams:
                    cams[id]['cameraState'] = state

        # Syncing devices and states to MQTT Homie
        for id, base in bases.items():
            if id not in self.arlo_bases:
                self.arlo_bases[id] = HomieArloBaseStation(
                    id=id,
                    name=base['deviceName'],
                    mqtt_settings=self.mqtt_settings,
                    arlo=self.arlo,
                    base_station=base,
                    log=self.log.getChild('homie'),
                )

            self.arlo_bases[id].node.active_modes = ','.join(
                base['modeState']['activeModes'])

        for id in [id for id in self.arlo_bases if id not in bases]:
            del self.arlo_bases[id]

        for id, cam in cams.items():
            if id not in self.arlo_cams:
                self.arlo_cams[id] = HomieArloCamera(
                    id=id,
                    name=cam['deviceName'],
                    mqtt_settings=self.mqtt_settings,
                    arlo=self.arlo,
                    base_station=bases[cam['parentId']],
                    log=self.log.getChild('homie'),
                )

            self.arlo_cams[id].node.privacy_active = cam['cameraState'][
                'privacyActive']
            self.arlo_cams[id].node.battery_level = cam['cameraState'][
                'batteryLevel']
            self.arlo_cams[id].node.charging_state = cam['cameraState'][
                'chargingState']
            self.arlo_cams[id].node.connection_state = cam['cameraState'][
                'connectionState']
            self.arlo_cams[id].node.signal_strength = cam['cameraState'][
                'signalStrength']
            self.arlo_cams[id].node.last_image = cam['presignedLastImageUrl']

        for id in [id for id in self.arlo_cams if id not in cams]:
            del self.arlo_cams[id]
Esempio n. 27
0
def handler(event, context):

    # config values
    USERNAME = os.getenv('USERNAME')
    PASSWORD = os.getenv('PASSWORD')
    QUEUENAME = os.getenv('QUEUENAME')
    S3BUCKET = os.getenv('S3BUCKET')
    prefix = os.getenv('prefix')
    cacheprefix = prefix + 'cache/'

    cache = Cache(S3BUCKET, cacheprefix)

    sqs = boto3.client('sqs')

    print(event)
    print(context)
    print(USERNAME)
    print(PASSWORD)
    print(QUEUENAME)
    print(S3BUCKET)
    print(prefix)
    print(cache)

    # get list of recent arlo media objects from past 7 days
    arlo = Arlo(USERNAME, PASSWORD)
    today = (date.today() - timedelta(days=0)).strftime("%Y%m%d")
    seven_days_ago = (date.today() - timedelta(days=7)).strftime("%Y%m%d")
    library = arlo.GetLibrary(seven_days_ago, today)

    # only process library items that have arrived since our last processing time
    latest_saved_media_timestamp = cache.get('latest_saved_media_timestamp')
    library = [
        l for l in library if l['lastModified'] > latest_saved_media_timestamp
    ]

    if len(library) > 0:
        latest_saved_media_timestamp = max(
            [l['lastModified'] for l in library])

    cameras = arlo.GetDevices('camera')
    camera_id2name = {}
    for c in cameras:
        camera_id2name[c['deviceId']] = c['deviceName']

    for media in library:
        camera_name = camera_id2name.get(media['deviceId'], 'unknown_device')
        filename = camera_name + '_' + datetime.datetime.fromtimestamp(
            int(media['name']) // 1000).strftime('%Y-%m-%d %H-%M-%S')
        message = {
            "media": media,
            "metadata": {
                "s3bucket": S3BUCKET,
                "content_key": prefix + 'media/' + filename + '.mp4',
                "thumbnail_key":
                prefix + 'media/' + filename + '_thumbnail.jpg'
            }
        }
        print(message)

        response = sqs.send_message(QueueUrl=QUEUENAME,
                                    MessageBody=json.dumps(message))

    cache.set('latest_saved_media_timestamp', latest_saved_media_timestamp,
              3600 * 24 * 30)
Esempio n. 28
0
import re

USERNAME = '******'
PASSWORD = '******'

videopath = 'videos'
cameraNumber = 2
datetimeFrom = datetime.datetime.strptime('2018-08-11 03:00:00', '%Y-%m-%d %H:%M:%S');
datetimeTo = datetime.datetime.strptime('2018-08-11 04:00:00', '%Y-%m-%d %H:%M:%S');


try:
    print "Downloading cvr videos from " + datetimeFrom.strftime("%Y-%m-%d %H:%M:%S") + " to " + datetimeTo.strftime("%Y-%m-%d %H:%M:%S")
    # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
    # Subsequent successful calls to login will update the oAuth token.
    arlo = Arlo(USERNAME, PASSWORD)
    # At this point you're logged into Arlo.

    # Get the list of devices and filter on device type to only get the basestation.
    # This will return an array which includes all of the basestation's associated metadata.
    basestations = arlo.GetDevices('basestation')

    # Get the list of devices and filter on device type to only get the camera.
    # This will return an array which includes all of the camera's associated metadata.
    cameras = arlo.GetDevices('camera')

    # Get all of the recordings for a date range.
    playlist = arlo.GetCvrPlaylist(cameras[cameraNumber], datetimeFrom.strftime("%Y%m%d"), datetimeTo.strftime("%Y%m%d"))

    # If no recordings are available exit
    if not playlist['playlist']:
Esempio n. 29
0
    # Credentials for Arlo
    USERNAME = config.get("CREDENTIALS", "USERNAME")
    PASSWORD = config.get("CREDENTIALS", "PASSWORD")

    # Check command line parameters
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'command',
        choices=['aktiviert', 'deaktiviert', 'garten', 'garten_hinten'])
    args = parser.parse_args()
    command = args.command

    # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
    # Subsequent successful calls to login will update the oAuth token.
    arlo = Arlo(USERNAME, PASSWORD)
    # At this point you're logged into Arlo.

    # Get all devices
    devices = arlo.GetDevices('')

    if command == 'deaktiviert':
        device = getDeviceFromName("Home", devices)
        arlo.Disarm(device)
        device = getDeviceFromName("Bridge_AZMichael", devices)
        arlo.Disarm(device)
        device = getDeviceFromName("Bridge_AZSabine", devices)
        arlo.Disarm(device)

    elif command == 'aktiviert':
        device = getDeviceFromName("Home", devices)
Esempio n. 30
0
from arlo import Arlo

USERNAME = '******'
PASSWORD = '******'

try:
    # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
    # Subsequent successful calls to login will update the oAuth token.
    arlo = Arlo(USERNAME, PASSWORD)
    # At this point you're logged into Arlo.

    # Get the list of devices and filter on device type to only get the basestation.
    # This will return an array which includes all of the basestation's associated metadata.
    basestations = arlo.GetDevices('basestation')

    # Get the list of devices and filter on device type to only get the camera.
    # This will return an array which includes all of the camera's associated metadata.
    cameras = arlo.GetDevices('camera')

    # Tells the Arlo basestation to trigger a snapshot on the given camera.
    # This snapshot is not instantaneous, so this method waits for the response and returns the url
    # for the snapshot, which is stored on the Amazon AWS servers.
    snapshot_url = arlo.TriggerFullFrameSnapshot(basestations[0], cameras[0])

    # This method requests the snapshot for the given url and writes the image data to the location specified.
    # In this case, to the current directory as a file named "snapshot.jpg"
    # Note: Snapshots are in .jpg format.
    arlo.DownloadSnapshot(snapshot_url, 'snapshot.jpg')

except Exception as e:
    print(e)