Ejemplo n.º 1
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)
Ejemplo n.º 2
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}.')
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
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))
Ejemplo n.º 5
0
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
Ejemplo n.º 6
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"]
Ejemplo n.º 7
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()
Ejemplo n.º 8
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)
Ejemplo n.º 9
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)
Ejemplo n.º 10
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]
Ejemplo n.º 11
0
def login(USERNAME, PASSWORD):
    global arlo
    arlo = Arlo(USERNAME, PASSWORD)
    global basestations
    basestations = arlo.GetDevices('basestation')
Ejemplo n.º 12
0
    # 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)
        arlo.Arm(device)
        device = getDeviceFromName("Bridge_AZMichael", devices)
        arlo.Arm(device)
        device = getDeviceFromName("Bridge_AZSabine", devices)
Ejemplo n.º 13
0
USERNAME = '******'
PASSWORD = '******'

videopath = 'videos'

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
    # and includes Arlo Q devices, re: https://github.com/jeffreydwalter/arlo/wiki/FAQ#frequently-asked-questions
    cameras = arlo.GetDevices('camera')
    arloq = arlo.GetDevices('arloq')
    arloqs = arlo.GetDevices('arloqs')

    cameras = cameras + arloq + arloqs
    cameras_by_id = {}

    # setup a hash where each camera deviceId is assocaited with its name for lookup later
    for camera in cameras:
        cameras_by_id[camera['deviceId']] = camera['deviceName']

    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)
Ejemplo n.º 14
0
    # Credentials for Arlo
    USERNAME = config.get("CREDENTIALS", "USERNAME")
    PASSWORD = str(
        base64.b64encode(
            config.get("CREDENTIALS", "PASSWORD").encode("utf-8")), "utf-8")

    # Base Station (currently only one base station supported!)
    BASESTATIONNAME = config.get("BASESTATION", "NAME")

    # 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 device objects
    devices = arlo.GetDevices(devicetype)

    # Get base station object
    basestation = getDeviceFromName(BASESTATIONNAME, devices)

    if command == 'list-devices':
        # List all devices
        # Get the list of devices and filter on device type.
        # This will return an array which includes all of the devices's associated metadata.
        for device in devices:
            print(device['deviceName'], " : ", device['deviceType'], " : ",
                  device['deviceId'], " : ", device['uniqueId'])

    elif command == 'list-modes':
        # List all modes for a specific device
        modes = arlo.GetAutomationDefinitions()
Ejemplo n.º 15
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],
Ejemplo n.º 16
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
Ejemplo n.º 17
0
from arlo import Arlo
import cv2

from datetime import timedelta, date
import datetime

arlo = Arlo("*****@*****.**", "Surui12109")

# 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')

basestations = cameras

print("Connected to Camera successfully")


# 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.
def get_snapshot():
    # 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])

    arlo.DownloadSnapshot(snapshot_url, 'temp.jpg')
    img = cv2.imread('temp.jpg')
    img = cv2.resize(img, (1000, 500))
    return img