def test_load_method(self, mock): """Test PyArlo ArloMediaLibrary.load() method.""" from pyarlo import PyArlo from pyarlo.media import ArloMediaLibrary mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.get(DEVICES_ENDPOINT, text=load_fixture('pyarlo_devices.json')) mock.post(LIBRARY_ENDPOINT, text=load_fixture('pyarlo_videos.json')) arlo = PyArlo(USERNAME, PASSWORD, preload=False) library = ArloMediaLibrary(arlo, preload=False) camera = arlo.lookup_camera_by_id('48B14C1299999') videos = library.load(days=1, limit=3, only_cameras=camera) self.assertEqual(len(videos), 2)
def test_camera_attributes(self, mock): """Test ArloCamera attributes.""" from pyarlo import PyArlo from pyarlo.camera import ArloCamera mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.get(DEVICES_ENDPOINT, text=load_fixture('pyarlo_devices.json')) mock.post(LIBRARY_ENDPOINT, text=load_fixture('pyarlo_videos.json')) arlo = PyArlo(USERNAME, PASSWORD, preload=False) arlo_devices = arlo.devices self.assertTrue(arlo_devices.get('cameras', arlo.cameras)) cameras = arlo.cameras self.assertEqual(len(cameras), 2) for camera in cameras: self.assertTrue(camera.__repr__().startswith('<ArloCamera:')) self.assertIsNone(arlo.refresh_attributes(camera)) self.assertIsInstance(camera, ArloCamera) self.assertTrue(camera.device_type, 'camera') self.assertTrue(camera.user_id, USERID) self.assertEqual(camera.hw_version, 'H7') self.assertEqual(camera.timezone, 'America/New_York') self.assertEqual(camera.user_role, 'ADMIN') self.assertTrue(len(camera.captured_today), 1) if camera.name == 'Front Door': self.assertTrue(camera.device_id, '48B14CAAAAAAA') self.assertEqual(camera.unique_id, '235-48B14CAAAAAAA') self.assertEquals(camera.unseen_videos, 39) self.assertEqual(camera.xcloud_id, '1005-123-999999') # unseen videos mock_url = RESET_CAM_ENDPOINT.format(camera.unique_id) mock.get(mock_url, json=MOCK_DATA) self.assertTrue(camera.unseen_videos_reset) if camera.name == 'Patio': self.assertTrue(camera.model_id, 'VMC3030') self.assertEqual(camera.unique_id, '999-123456_48B14C1299999') self.assertEquals(camera.unseen_videos, 233) # unseen videos mock_url = RESET_CAM_ENDPOINT.format(camera.unique_id) mock.get(mock_url, json=MOCK_DATA) self.assertTrue(camera.unseen_videos_reset)
def setup(hass, config): """Set up an Arlo component.""" conf = config[DOMAIN] username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) persistent_notification = loader.get_component('persistent_notification') try: from pyarlo import PyArlo arlo = PyArlo(username, password, preload=False) if not arlo.is_connected: return False hass.data[DATA_ARLO] = arlo except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Netgar Arlo: %s", str(ex)) persistent_notification.create( hass, 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False return True
def load_base_station(self, mock): mock.post(LOGIN_ENDPOINT, text=load_fixture("pyarlo_authentication.json")) mock.get(DEVICES_ENDPOINT, text=load_fixture("pyarlo_devices.json")) mock.post(LIBRARY_ENDPOINT, text=load_fixture("pyarlo_videos.json")) arlo = PyArlo(USERNAME, PASSWORD, days=1) return arlo.base_stations[0]
def cameras(request): username = environ.get("arlo_username") password = environ.get("arlo_password") arlo = PyArlo(username, password) serializer = ArloCameraSerializer(arlo.cameras, many=True) return Response(serializer.data)
def summary(request): username = environ.get("arlo_username") password = environ.get("arlo_password") arlo = PyArlo(username, password) serializer = ArloStatusSerializer({"base_station": arlo.base_stations[0], "cameras": arlo.cameras}, many=False) return Response(serializer.data)
def arlo_mode(username, password, mode): arlo = PyArlo(username, password) base = arlo.base_stations[0] available_modes = base.available_modes if mode not in available_modes: raise RuntimeError("No such mode: {}\n" "Available Modes: {}".format(mode, available_modes)) base.mode = mode
def load_arlo(self, mock): mock.post(LOGIN_ENDPOINT, text=load_fixture("pyarlo_authentication.json")) mock.get(DEVICES_ENDPOINT, text=load_fixture("pyarlo_devices.json")) mock.post(LIBRARY_ENDPOINT, text=load_fixture("pyarlo_videos.json")) mock.post(NOTIFY_ENDPOINT.format(BASE_STATION_ID), text=load_fixture("pyarlo_camera_properties.json")) mock.get(UNSUBSCRIBE_ENDPOINT) return PyArlo(USERNAME, PASSWORD, preload=False)
def __getArlo(self): """ Lazy loads Arlo. """ if self.arlo is None: from pyarlo import PyArlo self.arlo = PyArlo(self.arlo_email, self.arlo_password) logging.debug('Lazy loading Arlo') return self.arlo
def initialize(self): self.log('Starting Arlo Alarm Control Panel...') config_arlo = self.args['arlo'] config_mqtt = self.args['mqtt'] self.pending_time = self.args[ 'pending_time'] if 'pending_time' in self.args else 0 self.state_topic = self.args[ 'state_topic'] if 'state_topic' in self.args else 'home/alarm' self.command_topic = self.args[ 'command_topic'] if 'command_topic' in self.args else 'home/alarm/set' self.availability_topic = self.args[ 'availability_topic'] if 'availability_topic' in self.args else 'home/alarm/availability' # Connect to Arlo self.lock = threading.Lock() self.arlo = PyArlo(config_arlo['username'], config_arlo['password'], preload=False) self.base = self.arlo.base_stations[0] self.previous_mode = 'unknown' self.pending_command = None self.handle = self.run_in(self.update_state, 1) # Setup MQTT Client self.client = mqtt.Client(userdata=self.base.name) self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_message = self.on_message self.client.will_set(self.availability_topic, 'offline', qos=1, retain=True) if 'username' in config_mqtt: self.client.username_pw_set(config_mqtt['username'], password=config_mqtt['password']) self.client.connect_async(config_mqtt['host'], config_mqtt['port'], 60) self.client.loop_start()
def load_base_station(self, mock): mock.post(LOGIN_ENDPOINT, text=load_fixture("pyarlo_authentication.json")) mock.get(DEVICES_ENDPOINT, text=load_fixture("pyarlo_devices.json")) mock.post(LIBRARY_ENDPOINT, text=load_fixture("pyarlo_videos.json")) arlo = PyArlo(USERNAME, PASSWORD, days=1) base_station = arlo.base_stations[0] mock.post(NOTIFY_ENDPOINT.format(base_station.device_id), text=load_fixture("pyarlo_success.json")) return base_station
def test_preload_devices(self, mock): """Test PyArlo preloading videos from the last day.""" from pyarlo import PyArlo mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.get(DEVICES_ENDPOINT, text=load_fixture('pyarlo_devices.json')) mock.post(LIBRARY_ENDPOINT, text=load_fixture('pyarlo_videos.json')) arlo = PyArlo(USERNAME, PASSWORD, days=1) self.assertTrue(len(arlo.ArloMediaLibrary.videos), 3)
def test_general_attributes(self, mock): """Test PyArlo without preloading videos.""" from pyarlo import PyArlo from pyarlo.camera import ArloCamera mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.get(DEVICES_ENDPOINT, text=load_fixture('pyarlo_devices.json')) mock.post(LIBRARY_ENDPOINT, text=load_fixture('pyarlo_videos.json')) mock.get(RESET_ENDPOINT, json={'success': True}) arlo = PyArlo(USERNAME, PASSWORD, days=1) self.assertEqual(arlo.__repr__(), '<PyArlo: 999-123456>') self.assertIsInstance(arlo.lookup_camera_by_id('48B14CAAAAAAA'), ArloCamera) self.assertRaises(IndexError, arlo.lookup_camera_by_id, 'FAKEID') self.assertTrue(arlo.is_connected) self.assertTrue(arlo.unseen_videos_reset) self.assertIsNone(arlo.update())
def test_arlo_media_library(self, mock): """Test PyArlo MediaLibrary tests.""" from pyarlo import PyArlo mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.post(LIBRARY_ENDPOINT, text=load_fixture('pyarlo_videos.json')) arlo = PyArlo(USERNAME, PASSWORD, preload=False) self.assertEqual(arlo.ArloMediaLibrary.__repr__(), '<ArloMediaLibrary: 999-123456>')
def get_arlo_mode(): arlo = PyArlo('*****@*****.**', '3rNQFmBLNBrK') if arlo is None or arlo.base_stations is None: print('Could not read arlo mode.') return base = arlo.base_stations[0] arlo_mode = base.mode print("Is mode " + arlo_mode) return arlo_mode
def lambda_handler(event, context): try: # EXECUTION CODE print('Received event : ', event) arlo = PyArlo(login, senha, 0) print("Data e Hora: " + str(datetime.now())) basestations = arlo.base_stations print("Quantidade de bases encontradas: " + str(len(basestations))) dyndb_s3_ses_email(arlo) except Exception as e: print ("Erro no final da função lambda_handler: " + str(e)) #return respond(e) return respond(None,'Hello world from camera-arlo')
def connect_tensor_xray(): try: arlo = PyArlo('user', read_file("pass.txt")) # connect to pyarlo library cam = arlo.cameras[2] # selecting cam cam.schedule_snapshot() # take picture time.sleep(3) # wait if is necesarry r = requests.get("url_endpoint" + cam.snapshot_url) # todo: change for a post call return r except Exception as e: return [{"error"}]
def setup(hass, config): """Set up an Arlo component.""" conf = config[DOMAIN] username = conf.get(CONF_USERNAME) password = conf.get(CONF_PASSWORD) scan_interval = conf.get(CONF_SCAN_INTERVAL) try: from pyarlo import PyArlo arlo = PyArlo(username, password, preload=False) if not arlo.is_connected: return False # assign refresh period to base station thread arlo_base_station = next((station for station in arlo.base_stations), None) if arlo_base_station is not None: arlo_base_station.refresh_rate = scan_interval.total_seconds() elif not arlo.cameras: _LOGGER.error("No Arlo camera or base station available.") return False hass.data[DATA_ARLO] = arlo except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Netgear Arlo: %s", str(ex)) hass.components.persistent_notification.create( "Error: {}<br />" "You will need to restart hass after fixing." "".format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) return False def hub_refresh(event_time): """Call ArloHub to refresh information.""" _LOGGER.debug("Updating Arlo Hub component") hass.data[DATA_ARLO].update(update_cameras=True, update_base_station=True) dispatcher_send(hass, SIGNAL_UPDATE_ARLO) # register service hass.services.register(DOMAIN, "update", hub_refresh) # register scan interval for ArloHub track_time_interval(hass, hub_refresh, scan_interval) return True
def test_without_preload(self, mock): """Test PyArlo without preloading videos.""" from pyarlo import PyArlo from pyarlo.media import ArloMediaLibrary mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) arlo = PyArlo(USERNAME, PASSWORD, preload=False) self.assertTrue(arlo.country_code, 'US') self.assertTrue(arlo.authenticated, 1498801924) self.assertTrue(arlo.userid, USERID) self.assertIsInstance(arlo.ArloMediaLibrary, ArloMediaLibrary) self.assertListEqual(arlo.ArloMediaLibrary.videos, [])
def test_without_preload_devices(self, mock): """Test PyArlo without preloading videos but loading devices.""" from pyarlo import PyArlo from pyarlo.camera import ArloCamera from pyarlo.base_station import ArloBaseStation mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.get(DEVICES_ENDPOINT, text=load_fixture('pyarlo_devices.json')) arlo = PyArlo(USERNAME, PASSWORD, preload=False) arlo_devices = arlo.devices self.assertTrue(arlo_devices.get('base_station', arlo.base_stations)) self.assertTrue(arlo_devices.get('cameras', arlo.cameras)) cameras = arlo.cameras self.assertEqual(len(cameras), 2) for camera in cameras: self.assertIsNone(arlo.refresh_attributes(camera)) self.assertIsInstance(camera, ArloCamera) self.assertTrue(camera.device_type, 'camera') self.assertTrue(camera.user_id, USERID) if camera.name == 'Front Door': self.assertTrue(camera.device_id, '48B14CAAAAAAA') if camera.name == 'Patio': self.assertTrue(camera.model_id, 'VMC3030') base = arlo.base_stations[0] self.assertIsInstance(base, ArloBaseStation) self.assertTrue(base.device_type, 'basestation') self.assertTrue(base.user_id, USERID) self.assertTrue(base.hw_version, 'VMB3010r2') self.assertIsNone(base.serial_number)
def set_arlo_mode(mode_name): arlo = PyArlo('*****@*****.**', '3rNQFmBLNBrK') if arlo is None or arlo.base_stations is None: print('Could not read arlo mode.') return base = arlo.base_stations[0] base_mode = base.mode print("Is mode " + base_mode) if base_mode != mode_name: print("Setting mode " + mode_name) base.mode = mode_name base.update() else: print("Mode not set")
def set_arlo_mode(self, mode_name): """ Sets Arlo mode to mode_name """ try: from pyarlo import PyArlo arlo = PyArlo(self.arlo_email, self.arlo_password) base = arlo.base_stations[0] logging.info("Setting Arlo mode to " + mode_name) base.mode = mode_name annex_activate.email_notify( 'Arlo change', 'Alarm change state. Changing state of Arlo to [' + mode_name + '].') except TypeError: logging.error('Got type error. Doing nothing. ', exc_info=True)
def get_arlo_mode(self): """ Returns the Arlo mode. """ from pyarlo import PyArlo arlo = PyArlo(self.arlo_email, self.arlo_password) if arlo is None or arlo.base_stations is None: logging.error('Could not read arlo base station.') raise TypeError('Could not read arlo base station.') base = arlo.base_stations[0] arlo_mode = base.mode if arlo_mode is None: logging.error('Could not read arlo mode.') raise TypeError('Could not read arlo mode.') logging.info("Is mode " + arlo_mode) return arlo_mode
def test_load_method(self, mock): """Test PyArlo ArloMediaLibrary.load() method.""" from pyarlo import PyArlo from pyarlo.camera import ArloCamera mock.post(LOGIN_ENDPOINT, text=load_fixture('pyarlo_authentication.json')) mock.get(DEVICES_ENDPOINT, text=load_fixture('pyarlo_devices.json')) mock.post(LIBRARY_ENDPOINT, text=load_fixture('pyarlo_videos.json')) arlo = PyArlo(USERNAME, PASSWORD, days=1) for video in arlo.ArloMediaLibrary.videos: self.assertTrue(video.id, video.created_at) self.assertEqual(video.content_type, 'video/mp4') self.assertIsInstance(video.camera, ArloCamera) self.assertGreaterEqual(video.media_duration_seconds, 45) self.assertEqual(video.triggered_by, 'motionRecord') self.assertTrue(video.thumbnail_url.startswith('https://')) self.assertTrue(video.video_url.startswith('https://')) if video.id == '1498880152142': vstr = '<ArloVideo: Patio' self.assertTrue(video.__repr__().startswith(vstr))
from pyarlo import PyArlo import mysql.connector import time import sys # MySQL CONNECTION INFO mysqlConnection = mysql.connector.connect( host="MYSQL_ADDRESS", user="******", passwd="MYSQL_PASSWORD", database="MYSQL_DATABASE" ) mysqlCursor = mysqlConnection.cursor() # ARLO CONNECTION INFO arlo = PyArlo('ARLO_USERNAME', 'ARLO_PASSWORD') def writeData(cam): sql = "INSERT INTO arlo.telemetry(serial_number,name,model,battery_level,signal_strength) VALUES(%s,%s,%s,%s,%s)" mysqlCursor.execute(sql, (cam.serial_number,cam.name,cam.model_id,cam.battery_level,cam.signal_strength)) mysqlConnection.commit() def main(): cams = arlo.cameras for cam in cams: writeData(cam) time.sleep(15) sys.exit() if __name__ == "__main__": main()
from influxdb import InfluxDBClient import time import sys # INFLUXDB CONNECTION INFO host = "192.168.1.67" port = 8086 user = "******" password = "******" dbname = "database_name" # CREATE CLIENT OBJECT client = InfluxDBClient(host, port, user, password, dbname) # ARLO CONNECTION INFO arlo = PyArlo('*****@*****.**', 'password') def writeData(i, base): model_id = arlo.cameras[i].model_id serial_number = arlo.cameras[i].serial_number battery_level = arlo.cameras[i].battery_level signal_strength = arlo.cameras[i].signal_strength measurement = base + "-" + model_id + "-" + serial_number data1 = [{ "measurement": measurement + "-" + "battery_level", "fields": { "battery_level": battery_level }
class ArloAlarmControlPanel(hass.Hass): def initialize(self): self.log('Starting Arlo Alarm Control Panel...') config_arlo = self.args['arlo'] config_mqtt = self.args['mqtt'] self.pending_time = self.args[ 'pending_time'] if 'pending_time' in self.args else 0 self.state_topic = self.args[ 'state_topic'] if 'state_topic' in self.args else 'home/alarm' self.command_topic = self.args[ 'command_topic'] if 'command_topic' in self.args else 'home/alarm/set' self.availability_topic = self.args[ 'availability_topic'] if 'availability_topic' in self.args else 'home/alarm/availability' # Connect to Arlo self.lock = threading.Lock() self.arlo = PyArlo(config_arlo['username'], config_arlo['password'], preload=False) self.base = self.arlo.base_stations[0] self.previous_mode = 'unknown' self.pending_command = None self.handle = self.run_in(self.update_state, 1) # Setup MQTT Client self.client = mqtt.Client(userdata=self.base.name) self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_message = self.on_message self.client.will_set(self.availability_topic, 'offline', qos=1, retain=True) if 'username' in config_mqtt: self.client.username_pw_set(config_mqtt['username'], password=config_mqtt['password']) self.client.connect_async(config_mqtt['host'], config_mqtt['port'], 60) self.client.loop_start() def terminate(self): self.log('Terminating Arlo Alarm Control Panel') self.lock.acquire() try: del self.arlo self.arlo = None self.client.loop_stop() self.client.disconnect() del self.client finally: self.lock.release() def on_connect(self, client, userdata, flags, rc): self.log(f'[{userdata}] MQTT client Connected with result code {rc}') client.subscribe(self.command_topic, qos=1) client.publish(self.availability_topic, 'online', qos=1, retain=True) def on_disconnect(self, client, userdata, flags): self.log(f'[{userdata}] MQTT client disconnected') def on_message(self, client, userdata, msg): self.cancel_timer(self.handle) self.cancel_timer(self.pending_command) if msg.payload == b'DISARM': self.client.publish(self.state_topic, 'pending', qos=1, retain=False) self.pending_command = self.run_in(self._set_alarm_mode, self._pending_time('disarmed'), mode='disarmed') elif msg.payload == b'ARM_AWAY': self.client.publish(self.state_topic, 'pending', qos=1, retain=False) self.pending_command = self.run_in( self._set_alarm_mode, self._pending_time('armed_away'), mode='armed') else: self.log( f'[{userdata}] MQTT: {msg.topic} {msg.payload} (qos={msg.qos})' ) self.handle = self.run_in(self.update_state, 1) def _pending_time(self, mode): if mode in self.args and 'pending_time' in self.args[mode]: return self.args[mode]['pending_time'] return self.pending_time def _set_alarm_mode(self, kwargs): self.lock.acquire() try: if self.arlo == None: return mode = kwargs['mode'] self.log(f'[{self.base.name}] Setting mode to {mode}') self.base.publish(action='set', resource='modes', mode=mode, publish_response=True) self.previous_mode = 'pending' finally: self.lock.release() def update_state(self, kwargs): self.lock.acquire() try: if self.arlo == None: return mode = self.base.mode if mode == None: self.log('Detected stale connection. Re-authenticating.') try: self.arlo.login() except: e = sys.exc_info()[0] self.log(e) raise elif mode == 'armed': mode = 'armed_away' if mode != None and self.previous_mode != mode: self.log(f'[{self.base.name}] New alarm mode is {mode}') self.previous_mode = mode res = self.client.publish(self.state_topic, mode, qos=1, retain=True) res.wait_for_publish() self.handle = self.run_in(self.update_state, 1) finally: self.lock.release()
def load_arlo(self, mock): mock.post(LOGIN_ENDPOINT, text=load_fixture("pyarlo_authentication.json")) mock.get(DEVICES_ENDPOINT, text=load_fixture("pyarlo_devices.json")) mock.post(LIBRARY_ENDPOINT, text=load_fixture("pyarlo_videos.json")) return PyArlo(USERNAME, PASSWORD, preload=False)
from pyarlo import PyArlo from influxdb import InfluxDBClient # INFLUXDB CONNECTION INFO host = "192.168.1.67" port = 8086 user = "******" password = "******" dbname = "readings" # CREATE CLIENT OBJECT client = InfluxDBClient(host, port, user, password, dbname) # ARLO CONNECTION INFO arlo = PyArlo('*****@*****.**', 'password') # SET VARIABLES cam = arlo.cameras cam = len(cam) # COLLECT & UPLOAD DATA if cam <> 0: for i in range(cam): model_id = arlo.cameras[i].model_id serial_number = arlo.cameras[i].serial_number battery_level = arlo.cameras[i].battery_level signal_strength = arlo.cameras[i].signal_strength measurement = "jupitor-" + model_id + "-" + serial_number data = [{