def set_door_lock_state(self, area, state): """ args: area (string): area/name of lock state (string): Possible values: lock unlock """ #Find Door lock id deviceLabel = None for doorLock in self.overview['doorLockStatusList']: if doorLock['area'].replace(' ', '') == area: deviceLabel = doorLock['deviceLabel'] break try: if self.logout: self.session = verisure.Session(self.verisure_username, self.verisure_password) self.session.login() if self.system_name is not None: self._change_installation() self.session.set_lock_state(self.verisure_pin, deviceLabel, state.decode("utf-8")) if self.logout: self.session.logout() return True except verisure.session.ResponseError as ex: logging.info(ex) return False
def verisure_session(): session = verisure.Session(os.environ['VerisureUsername'], os.environ['VerisurePassword'], cookieFileName='/tmp/verisure_cookie') session.login() yield session session.logout()
def set_smart_plug_state(self, area, state): """ args: area (string): area/name of lock state (boolean): Possible values: True = ON False = OFF """ #Find Smart Plug id deviceLabel = None for smartPlug in self.overview['smartPlugs']: if smartPlug['area'].replace(' ', '') == area: deviceLabel = smartPlug['deviceLabel'] break try: if self.logout: self.session = verisure.Session(self.verisure_username, self.verisure_password) self.session.login() if self.system_name is not None: self._change_installation() self.session.set_smartplug_state(deviceLabel, state.decode("utf-8")) if self.logout: self.session.logout() return True except verisure.session.ResponseError as ex: logging.info(ex) return False
def setSmartplugState(self, device_label, state): try: session = verisure.Session(self.config('username'), self.config('password')) session.login() session.set_smartplug_state(device_label, state) session.logout() except Exception as e: logging.warning('Could not communicate with Verisur') return
def asyncFetch(): # This is run in a separate thread and can block try: session = verisure.Session(self.config('username'), self.config('password')) session.login() overview = session.get_overview() session.logout() except Exception as e: logging.warning("Could not fetch Verisure data") return Application().queue(parseValues, overview)
def onCommand(self, Unit, Command, Level, Hue): Domoticz.Debug('onCommand called for Unit ' + str(Unit) + ': Parameter '' + str(Command) + '', Level: ' + str(Level)) try: turn_on = (Command == 'On') deviceLabel = Devices[Unit].Options['deviceLabel'] with verisure.Session(Parameters['Username'], Parameters['Password']) as session: session.set_smartplug_state(deviceLabel, turn_on) Devices[Unit].Update(nValue=1 if turn_on else 0, sValue=str(Command)) except verisure.Error as e: Domoticz.Error('Verisure exception: {}'.format(e)) pass return True
def __init__(self, domain_config): """Initialize the Verisure hub.""" self.overview = {} self.imageseries = {} self.config = domain_config self._lock = threading.Lock() self.session = verisure.Session(domain_config[CONF_USERNAME], domain_config[CONF_PASSWORD]) self.giid = domain_config.get(CONF_GIID)
def __init__(self, domain_config, verisure): """Initialize the Verisure hub.""" self.overview = {} self.imageseries = {} self.config = domain_config self._verisure = verisure self._lock = threading.Lock() self.session = verisure.Session(domain_config[CONF_USERNAME], domain_config[CONF_PASSWORD]) import jsonpath self.jsonpath = jsonpath.jsonpath
def _load_status(self): """ Load status of all devices """ try: self.session = verisure.Session(self.verisure_username, self.verisure_password) self.session.login() if self.system_name is not None: self._change_installation() overview = self.session.get_overview() if self.logout: self.session.logout() return overview except verisure.session.ResponseError as ex: logging.info(ex) return None
def lambda_handler(event, context): devices = event['devices'] ssm = boto3.client('ssm') password = ssm.get_parameter(Name='/lambda/vsure/password', WithDecryption=True) password = password['Parameter']['Value'] login = ssm.get_parameter(Name='/lambda/vsure/login') login = login['Parameter']['Value'] for device_id in devices.keys(): session = verisure.Session(login, password, cookieFileName='/tmp/verisure-cookie') session.login() values = session.get_climate(devices[device_id]) measurement = values[0]['simpleClimateSamples'][-1] if not is_latest_measurement(measurement, device_id): endpoint = 'a1gq7cu6baut56-ats.iot.eu-west-1.amazonaws.com' client = get_iot_client(device_id, endpoint) connect_iot(client, device_id, measurement)
def set_arm_state(self, state): """ args: state (string): Possible values: ARMED_HOME ARMED_AWAY DISARMED """ try: if self.logout: self.session = verisure.Session(self.verisure_username, self.verisure_password) self.session.login() if self.system_name is not None: self._change_installation() self.session.set_arm_state(self.verisure_pin, state.decode("utf-8")) if self.logout: self.session.logout() return True except verisure.session.ResponseError as ex: logging.info(ex) return False
def main(): """ Start verisure command line """ parser = argparse.ArgumentParser( description='Read or change status of verisure devices') parser.add_argument( 'username', help='MyPages username') parser.add_argument( 'password', help='MyPages password') parser.add_argument( '-i', '--installation', help='Installation number', type=int, default=1) commandsparser = parser.add_subparsers( help='commands', dest='command') # installations command commandsparser.add_parser( COMMAND_INSTALLATIONS, help='Get information about installations') # overview command overview_parser = commandsparser.add_parser( COMMAND_OVERVIEW, help='Read status of one or many device types') overview_parser.add_argument( 'filter', nargs='*', help='Read status for device type') # armstate command commandsparser.add_parser( COMMAND_ARMSTATE, help='Get arm state') # Set command set_parser = commandsparser.add_parser( COMMAND_SET, help='Set status of a device') set_device = set_parser.add_subparsers( help='device', dest='device') # Set smartplug set_smartplug = set_device.add_parser( 'smartplug', help='set smartplug value') set_smartplug.add_argument( 'device_label', help='device label') set_smartplug.add_argument( 'new_value', choices=[ 'on', 'off'], help='new value') # Set alarm set_alarm = set_device.add_parser( 'alarm', help='set alarm status') set_alarm.add_argument( 'code', help='alarm code') set_alarm.add_argument( 'new_status', choices=[ 'ARMED_HOME', 'ARMED_AWAY', 'DISARMED'], help='new status') # Set lock set_lock = set_device.add_parser( 'lock', help='set lock status') set_lock.add_argument( 'code', help='alarm code') set_lock.add_argument( 'serial_number', help='serial number') set_lock.add_argument( 'new_status', choices=[ 'lock', 'unlock'], help='new status') # Get climate history history_climate = commandsparser.add_parser( COMMAND_CLIMATE, help='get climate history') history_climate.add_argument( 'device_label', help='device label') # Event log command eventlog_parser = commandsparser.add_parser( COMMAND_EVENTLOG, help='Get event log') eventlog_parser.add_argument( '-p', '--pagesize', type=int, default=15, help='Number of elements on one page') eventlog_parser.add_argument( '-o', '--offset', type=int, default=0, help='Page offset') eventlog_parser.add_argument( '-f', '--filter', nargs='*', default=[], choices=[ 'ARM', 'DISARM', 'FIRE', 'INTRUSION', 'TECHNICAL', 'SOS', 'WARNING'], help='Filter event log') # Capture command capture_parser = commandsparser.add_parser( COMMAND_CAPTURE, help='Capture image') capture_parser.add_argument( 'device_label', help='Device label') # Image series command commandsparser.add_parser( COMMAND_IMAGESERIES, help='Get image series') # Get image command getimage_parser = commandsparser.add_parser( COMMAND_GETIMAGE, help='Download image') getimage_parser.add_argument( 'device_label', help='Device label') getimage_parser.add_argument( 'image_id', help='image ID') getimage_parser.add_argument( 'file_name', help='Output file name') # Vacation mode command commandsparser.add_parser( COMMAND_VACATIONMODE, help='Get vacation mode info') args = parser.parse_args() session = verisure.Session(args.username, args.password) session.login() try: session.set_giid(session.installations[args.installation - 1]['giid']) if args.command == COMMAND_INSTALLATIONS: print_result(session.installations) if args.command == COMMAND_OVERVIEW: print_result(session.get_overview(), *args.filter) if args.command == COMMAND_ARMSTATE: print_result(session.get_arm_state()) if args.command == COMMAND_SET: if args.device == 'smartplug': session.set_smartplug_state( args.device_label, args.new_value == 'on') if args.device == 'alarm': print_result(session.set_arm_state( args.code, args.new_status)) if args.device == 'lock': print_result(session.set_lock_state( args.code, args.serial_number, args.new_status)) if args.command == COMMAND_CLIMATE: print_result(session.get_climate(args.device_label)) if args.command == COMMAND_EVENTLOG: print_result( session.get_history( args.filter, pagesize=args.pagesize, offset=args.offset)) if args.command == COMMAND_CAPTURE: session.capture_image(args.device_label) if args.command == COMMAND_IMAGESERIES: print_result(session.get_camera_imageseries()) if args.command == COMMAND_GETIMAGE: session.download_image( args.device_label, args.image_id, args.file_name) if args.command == COMMAND_VACATIONMODE: print_result(session.get_vacation_mode()) except verisure.session.ResponseError as ex: print_result(ex.text) finally: session.logout()
import logging import os import time import verisure from prometheus_client import start_http_server from devices import temperature_gauge HTTP_PORT = os.getenv('HTTP_PORT', 8000) VERISURE_MYPAGES_USERNAME = os.environ['VERISURE_MYPAGES_USERNAME'] VERISURE_MYPAGES_PASSWORD = os.environ['VERISURE_MYPAGES_PASSWORD'] logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(asctime)s - %(message)s') session = verisure.Session(VERISURE_MYPAGES_USERNAME, VERISURE_MYPAGES_PASSWORD) session.login() logging.info('Successful Verisure My Pages authentication') temperature_gauge.measure_temperature(session) session.logout() start_http_server(HTTP_PORT) logging.info(f'Serving metrics at port {HTTP_PORT}') while True: time.sleep(1)
print("No humidity") date = sensor['time'] datetime_object = datetime.strptime(date.replace("T", "-").replace(".000Z", "").replace(":", "-"), '%Y-%m-%d-%H-%M-%S') try: datapoints = [] datapoints.append((datetime_object, temperature)) client.datapoints.insert(datapoints,external_id=name + "-temp") try: datapoints = [] datapoints.append((datetime_object, humidity)) client.datapoints.insert(datapoints,external_id=name + "-humidity") except: print("No humidity") except: print("Failed to insert datapoint in CDP") print(name) except: print("Failed to insert datapoint in CDP") time.sleep(60) if __name__ == "__main__": session = verisure.Session(username, password) session.login() session._get_installations() project = "verisure" client = CogniteClient() stream_verisure_data(client)
def _updateDevices(self): Domoticz.Debug('Updating devices') try: with verisure.Session(Parameters['Username'], Parameters['Password']) as session: overview = session.get_overview() except verisure.Error as e: Domoticz.Error('Verisure exception: {}'.format(e)) return False pass current_devices = self._getDomoticzDeviceList() remote_devices = set() for plug in overview['smartPlugs']: is_on = (plug['currentState'] == 'ON') device = plug['deviceLabel'] remote_devices.add(device) if device not in current_devices: Domoticz.Log('Adding smart plug ({label}) in {area}'.format(label=plug['deviceLabel'], area=plug['area'])) Domoticz.Device(Name='Smart plug', Unit=self.next_unit, TypeName='Switch', Options={'deviceLabel': device}).Create() current_devices[device] = self.next_unit self.next_unit = self.next_unit + 1 unit = current_devices[device] Devices[unit].Update(nValue=1 if is_on else 0, sValue='On' if is_on else 'Off') for climate in overview['climateValues']: has_humidity = 'humidity' in climate device = climate['deviceLabel'] remote_devices.add(device) if device not in current_devices: Domoticz.Log('Adding climate sensor ({label}) in {area}'.format(label=climate['deviceLabel'], area=climate['deviceArea'])) if has_humidity: Domoticz.Device(Name='Climate sensor', Unit=self.next_unit, TypeName='Temp+Hum', Options={'deviceLabel': device}).Create() else: Domoticz.Device(Name='Climate sensor', Unit=self.next_unit, TypeName='Temperature', Options={'deviceLabel': device}).Create() current_devices[device] = self.next_unit self.next_unit = self.next_unit + 1 unit = current_devices[device] temperature = climate['temperature'] if has_humidity: humidity = int(climate['humidity']) Devices[unit].Update(nValue=0, sValue='{t:.1f} C;{h};1'.format(t=temperature, h=humidity)) else: Devices[unit].Update(nValue=0, sValue='{t:.1f} C'.format(t=temperature)) # for doorWindow in overview['doorWindow']['doorWindowDevice']: # device = doorWindow['deviceLabel'] # remote_devices.add(device) # if device not in current_devices: # Domoticz.Log('Adding door/window sensor ({label}) in {area}'.format(label=doorWindow['deviceLabel'], area=doorWindow['area'])) # Domoticz.Device(Name='Door/window sensor', Unit=self.next_unit, TypeName='Switch', Switchtype=2, Options={'deviceLabel': device}).Create() # current_devices[device] = self.next_unit # self.next_unit = self.next_unit + 1 removed_devices = current_devices.keys() - remote_devices for device in removed_devices: unit = current_devices[device] Domoticz.Log('Removing device {unit} (\'{device}\')'.format(unit=unit, device=device)) Devices[unit].Delete() Domoticz.Debug('Updating devices - done') return True