def smarthome_post(self, s): logger.debug(s.headers) a = s.headers.get('Authorization', None) token = None if a is not None: types, tokenH = a.split() if types.lower() == 'bearer': token = Auth['tokens'].get(tokenH, None) if token is None: raise SmartHomeError(ERR_PROTOCOL_ERROR, 'not authorized access!!') message = json.loads(s.body) self._request_id = message.get('requestId') logger.info( "Request " + json.dumps(message, indent=2, sort_keys=False, ensure_ascii=False)) response = self.smarthome_process(message, token) try: if 'errorCode' in response['payload']: logger.info('Error handling message %s: %s' % (message, response['payload'])) except: pass s.send_json(200, json.dumps(response, ensure_ascii=False).encode('utf-8'), True) logger.info("Response " + json.dumps( response, indent=2, sort_keys=False, ensure_ascii=False))
def track(self, tracking_data): logger.debug('Tracking VAC delivery for ref: {}'.format(tracking_data)) platform_meta = self.get_platform_meta() tracking_url = get_value(platform_meta, 'url') tracking_id = get_value(tracking_data, 'VT_TRACKING_ID') dob_year = get_value(tracking_data, 'USER_DOB_YEAR') # Decrement month cos values are set by indices dob_month = int(get_value(tracking_data, 'USER_DOB_MONTH')) - 1 dob_day = get_value(tracking_data, 'USER_DOB_DAY') dob = '{0}/{1}/{2}'.format(dob_year, dob_month, dob_day) self.browser.get(tracking_url) tracking_id_input = self.get_element('tracking_id_input_selector') date_input = self.get_element('date_input_selector') tracking_id_input.clear() tracking_id_input.send_keys(tracking_id) date_input.click() year_input = Select(self.get_element('year_picker_selector')) year_input.select_by_value(str(dob_year)) month_input = Select(self.get_element('month_picker_selector')) month_input.select_by_value(str(dob_month)) day_input = self.browser.find_element_by_xpath( "//a[text()='{}']".format(dob_day)) day_input.click()
def getDevices(devices="all", idx="0"): global aogDevs global deviceList url = "" if "all" == devices: url = DOMOTICZ_URL + DOMOTICZ_GET_ALL_DEVICES_URL + configuration['Domoticz'][ 'roomplan'] + '&filter=all&used=true' elif "scene" == devices: url = DOMOTICZ_URL + DOMOTICZ_GET_SCENES_URL elif "id" == devices: url = DOMOTICZ_URL + DOMOTICZ_GET_ONE_DEVICE_URL + idx r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) if r.status_code == 200: devs = r.json()['result'] for d in devs: aog = getAog(d) if aog is None: continue aogDevs[aog.entity_id] = aog req = {aog.name: {}} req[aog.name]['idx'] = int(aog.id) req[aog.name]['type'] = aog.domain req[aog.name]['state'] = aog.state req[aog.name]['nicknames'] = aog.nicknames req[aog.name]['willReportState'] = aog.report_state logger.debug(json.dumps(req, indent=2, sort_keys=False, ensure_ascii=False)) devlist = [(d.name, int(d.id), d.domain, d.state, d.room, d.nicknames, d.report_state) for d in aogDevs.values()] devlist.sort(key=takeSecond) deviceList = json.dumps(devlist)
def track(self, tracking_id): logger.debug('Tracking DHL delivery for ref: {}'.format(tracking_id)) platform_meta = self.get_platform_meta() tracking_url = get_value(platform_meta, 'url') self.browser.get(tracking_url) text_input = self.get_element('text_input_selector') submit_button = self.get_element('submit_button_selector') text_input.clear() text_input.send_keys(tracking_id) submit_button.click()
def getDevices(devices="all", idx="0"): global aogDevs global deviceList url = "" if "all" == devices: url = DOMOTICZ_URL + DOMOTICZ_GET_ALL_DEVICES_URL + configuration[ 'Domoticz']['roomplan'] + '&filter=all&used=true' elif "scene" == devices: url = DOMOTICZ_URL + DOMOTICZ_GET_SCENES_URL elif "id" == devices: url = DOMOTICZ_URL + DOMOTICZ_GET_ONE_DEVICE_URL + idx r = requests.get(url, auth=CREDITS) if r.status_code == 200: devs = r.json()['result'] for d in devs: aog = getAog(d) if aog is None: continue aogDevs[aog.entity_id] = aog if 'loglevel' in configuration and ( configuration['loglevel']).lower() == 'debug': req = {aog.name: {}} req[aog.name]['idx'] = int(aog.id) req[aog.name]['type'] = aog.domain req[aog.name]['state'] = aog.state req[aog.name]['lastupdate'] = aog.lastupdate if aog.nicknames is not None: req[aog.name]['nicknames'] = aog.nicknames if aog.modes_idx is not None: req[aog.name]['modes_idx'] = aog.modes_idx if aog.hide is not False: req[aog.name]['hidden'] = aog.hide if aog.actual_temp_idx is not None: req[aog.name]['actual_temp_idx'] = aog.actual_temp_idx if aog.merge_thermo_idx is not None: req[aog.name]['merge_thermo_idx'] = aog.merge_thermo_idx req[aog.name]['willReportState'] = aog.report_state logger.debug( json.dumps(req, indent=2, sort_keys=False, ensure_ascii=False)) devlist = [(d.name, int(d.id), d.domain, d.state, d.room, d.nicknames, d.report_state) for d in aogDevs.values()] devlist.sort(key=takeSecond) deviceList = json.dumps(devlist)
def getSettings(): """Get domoticz settings.""" global settings url = DOMOTICZ_URL + DOMOTICZ_GET_SETTINGS_URL r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) if r.status_code == 200: devs = r.json() settings['SecPassword'] = devs['SecPassword'] settings["SecOnDelay"] = devs["SecOnDelay"] settings['TempUnit'] = devs['TempUnit'] settings['Language'] = devs['Language'] logger.debug(json.dumps(settings, indent=2, sort_keys=False, ensure_ascii=False))
def archive_ocio_payload(output_dir=prefix, filename="ocio_streamlit.tar"): """ Creates a compressed archive of the compiled library and headers. """ archive_path = f"{output_dir}/{filename}" src = fs.open_fs(f"{prefix}") glob_filters = [ "**/OpenColorIO/**/*.h", "**/ocio*", "**/lib/**/*penColor*" ] files_to_archive = [p.path for g in glob_filters for p in src.glob(g)] with fs.open_fs(f"tar:///{archive_path}", writeable=True, create=True) as dst: for file in files_to_archive: fs.copy.copy_file(src, file, dst, file) logger.debug(f"Archived {archive_path}") return archive_path
def is_ocio_installed(): """ Checks if `PyOpenColorIO` is installed and importable. """ python_version = get_python_version() pyopencolorio_path = f"{prefix}/lib/python{python_version}/site-packages" if local.path(pyopencolorio_path).is_dir(): if pyopencolorio_path not in sys.path: sys.path.append(pyopencolorio_path) try: import PyOpenColorIO logger.debug( f"PyOpenColorIO v{PyOpenColorIO.__version__} is installed.") return True except ImportError: return False
def fetch_ocio(version=config.libs.OpenColorIO.version, force=False): # Only download if not importable if not force: try: import PyOpenColorIO if version == PyOpenColorIO.__version__: return except ImportError: pass # fetch archive key = f"OCIO v{version}" archive_path = get_dependency_local_path(key) archive = fs.open_fs(f"tar://{archive_path}") prefix = get_dependency_data(key).metadata.prefix # unpack with fs.open_fs(prefix, writeable=True) as dst: fs.copy.copy_dir(archive, prefix, dst, ".") # append to system path dst = fs.open_fs(prefix) sys.path.extend( [dst.getsyspath(p.path) for p in dst.glob("**/site-packages/")]) # validate try: import PyOpenColorIO except ImportError: with st_stdout("error"): print("""***NICE WORK, GENIUS: *** You've managed to build, archive, retrieve, and deploy OCIO... yet you couldn't manage to import PyOpenColorIO.""") logger.debug(f"OpenColorIO v{version} installed!")
def get_element(self, selector_id): platform_meta = self.get_platform_meta() selector = get_value(platform_meta, selector_id) logger.debug('Getting element with CSS selector: {}'.format(selector)) return self.browser.find_element_by_css_selector(selector)
DOMOTICZ_GET_ONE_DEVICE_URL, DOMOTICZ_GET_SCENES_URL, groupDOMAIN, sceneDOMAIN, CONFIGFILE, LOGFILE, lightDOMAIN, switchDOMAIN, blindsDOMAIN, pushDOMAIN, climateDOMAIN, tempDOMAIN, lockDOMAIN, invlockDOMAIN, colorDOMAIN, mediaDOMAIN, speakerDOMAIN, cameraDOMAIN, REQUEST_SYNC_BASE_URL, REPORT_STATE_BASE_URL, securityDOMAIN, outletDOMAIN, sensorDOMAIN, doorDOMAIN, selectorDOMAIN, fanDOMAIN, ATTRS_BRIGHTNESS, ATTRS_THERMSTATSETPOINT, ATTRS_COLOR_TEMP, ATTRS_PERCENTAGE, VERSION) from helpers import (configuration, readFile, saveFile, SmartHomeError, SmartHomeErrorNoChallenge, AogState, uptime, getTunnelUrl, FILE_DIR, logger, ReportState, Auth, logfilepath) DOMOTICZ_URL = configuration['Domoticz']['ip'] + ':' + configuration[ 'Domoticz']['port'] try: logger.debug("Connecting to Domoticz on %s" % DOMOTICZ_URL) r = requests.get( DOMOTICZ_URL + '/json.htm?type=command¶m=addlogmessage&message=Connected to Google Assistant with DZGA v' + VERSION, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password']), timeout=(2, 5)) except Exception as e: logger.error('Connection to Domoticz refused with error: %s' % e) try: import git repo = git.Repo(FILE_DIR) except: repo = None
def getAog(device): domain = AogGetDomain(device) if domain is None: return None aog = AogState() aog.name = device["Name"] # .encode('ascii', 'ignore') aog.domain = domain aog.id = device["idx"] aog.entity_id = domain + aog.id aog.plan = device.get("PlanID") aog.state = device.get("Data", "Scene") aog.level = device.get("LevelInt", 0) aog.temp = device.get("Temp") aog.humidity = device.get("Humidity") aog.setpoint = device.get("SetPoint") if aog.domain is "Color": aog.color = device.get("Color") aog.protected = device.get("Protected") aog.maxdimlevel = device.get("MaxDimLevel") aog.battery = device.get("BatteryLevel") aog.hardware = device.get("HardwareName") aog.selectorLevelName = device.get("LevelNames") aog.lastupdate = device.get("LastUpdate") aog.language = settings.get("Language") aog.tempunit = settings.get("TempUnit") if aog.domain is "Security": aog.seccode = settings.get("SecPassword") aog.secondelay = settings.get("SecOnDelay") # Try to get device specific voice control configuration from Domoticz # Read it from the configuration file if not in Domoticz (for backward compatibility) desc = getDeviceConfig(device.get("Description")) if desc is not None: logger.debug('<voicecontrol> tags found for idx %s in domoticz description.', aog.id) logger.debug('Device_Config for idx %s will be ignored in config.yaml!', aog.id) if desc is None: desc = getDesc(aog) if desc is not None: dt = desc.get('devicetype', None) if dt is not None: if aog.domain in [domains['blinds']]: if dt.lower() in ['window', 'gate', 'garage', 'door']: aog.domain = domains[dt.lower()] if aog.domain in [domains['light'], domains['switch']]: if dt.lower() in ['window', 'door', 'gate', 'garage', 'light', 'ac_unit', 'bathtub', 'coffeemaker', 'dishwasher', 'dryer', 'fan', 'heater', 'kettle', 'media', 'microwave', 'outlet', 'oven', 'speaker', 'switch', 'vacuum', 'washer', 'waterheater']: aog.domain = domains[dt.lower()] if aog.domain in [domains['door']]: if dt.lower() in ['window', 'gate', 'garage']: aog.domain = domains[dt.lower()] if aog.domain in [domains['selector']]: if dt.lower() in ['vacuum']: aog.domain = domains[dt.lower()] pn = desc.get('name', None) if pn is not None: aog.name = pn n = desc.get('nicknames', None) if n is not None: aog.nicknames = n r = desc.get('room', None) if r is not None: aog.room = r ack = desc.get('ack', False) if ack: aog.ack = ack report_state = desc.get('report_state', True) if not ReportState.enable_report_state(): aog.report_state = False if not report_state: aog.report_state = report_state if domains['thermostat'] == aog.domain: at_idx = desc.get('actual_temp_idx', None) if at_idx is not None: aog.actual_temp_idx = at_idx try: aog.state = str(aogDevs[domains['temperature'] + at_idx].temp) aogDevs[domains['temperature'] + at_idx].domain = domains['merged'] + aog.id + ')' except: logger.error('Merge Error, Cant find temperature device with idx %s', at_idx) modes_idx = desc.get('selector_modes_idx', None) if modes_idx is not None: aog.modes_idx = modes_idx try: aog.level = aogDevs[domains['selector'] + modes_idx].level aog.selectorLevelName = aogDevs[domains['selector'] + modes_idx].selectorLevelName aogDevs[domains['selector'] + modes_idx].domain = domains['merged'] + aog.id + ')' except: logger.error('Merge Error, Cant find selector device with idx %s', modes_idx) if aog.domain in [domains['heater'], domains['kettle'], domains['waterheater'], domains['oven']]: tc_idx = desc.get('merge_thermo_idx', None) if tc_idx is not None: aog.merge_thermo_idx = tc_idx try: aog.temp = aogDevs[domains['thermostat'] + tc_idx].state aog.setpoint = aogDevs[domains['thermostat'] + tc_idx].setpoint aogDevs[domains['thermostat'] + tc_idx].domain = domains['merged'] + aog.id + ')' except: logger.error('Merge Error, Cant find thermostat device with idx %s', tc_idx) hide = desc.get('hide', False) if hide: if aog.domain not in [domains['scene'], domains['group']]: aog.domain = domains['hidden'] else: logger.error('Scenes and Groups does not support function "hide" yet') if aog.domain in [domains['camera']]: aog.report_state = False if domains['light'] == aog.domain and "Dimmer" == device["SwitchType"]: aog.attributes = ATTRS_BRIGHTNESS if domains['fan'] == aog.domain and "Selector" == device["SwitchType"]: aog.attributes = ATTRS_FANSPEED if domains['outlet'] == aog.domain and "Dimmer" == device["SwitchType"]: aog.attributes = ATTRS_BRIGHTNESS if domains['color'] == aog.domain and "Dimmer" == device["SwitchType"]: aog.attributes = ATTRS_BRIGHTNESS if domains['color'] == aog.domain and device["SubType"] in ["RGBWW", "White"]: aog.attributes = ATTRS_COLOR_TEMP if domains['thermostat'] == aog.domain and "Thermostat" == device["Type"]: aog.attributes = ATTRS_THERMSTATSETPOINT if domains['blinds'] == aog.domain and "Blinds Percentage" == device["SwitchType"]: aog.attributes = ATTRS_PERCENTAGE if domains['blindsinv'] == aog.domain and "Blinds Percentage Inverted" == device["SwitchType"]: aog.attributes = ATTRS_PERCENTAGE if domains['vacuum'] == aog.domain and "Selector" == device["SwitchType"]: aog.attributes = ATTRS_VACUUM_MODES if aog.room == None: if aog.domain not in [domains['scene'], domains['group']]: if aog.plan is not "0": aog.room = getPlans(aog.plan) return aog
def build_ocio( prefix=config.libs.prefix, version=config.libs.OpenColorIO.version, build_shared=False, build_apps=False, force=False, ): """ Builds and installs OpenColorIO. Parameters ---------- prefix : unicode, optional Destination directory for installed libraries and headers version : unicode, optional Library version to build and install. If value does not match a known version, the main branch of the github repository will be used. build_shared : bool, optional Whether to build shared libraries instead of static. build_apps : bool, optional Whether to build and install cli applications. force : bool, optional Whether to force a re-build and re-install, even if the library is already installed. Returns ------- bool Definition success. """ def is_ocio_installed(): """ Checks if `PyOpenColorIO` is installed and importable. """ python_version = get_python_version() pyopencolorio_path = f"{prefix}/lib/python{python_version}/site-packages" if local.path(pyopencolorio_path).is_dir(): if pyopencolorio_path not in sys.path: sys.path.append(pyopencolorio_path) try: import PyOpenColorIO logger.debug( f"PyOpenColorIO v{PyOpenColorIO.__version__} is installed.") return True except ImportError: return False def archive_ocio_payload(output_dir=prefix, filename="ocio_streamlit.tar"): """ Creates a compressed archive of the compiled library and headers. """ archive_path = f"{output_dir}/{filename}" src = fs.open_fs(f"{prefix}") glob_filters = [ "**/OpenColorIO/**/*.h", "**/ocio*", "**/lib/**/*penColor*" ] files_to_archive = [p.path for g in glob_filters for p in src.glob(g)] with fs.open_fs(f"tar:///{archive_path}", writeable=True, create=True) as dst: for file in files_to_archive: fs.copy.copy_file(src, file, dst, file) logger.debug(f"Archived {archive_path}") return archive_path if is_ocio_installed(): if force: # Clean prefix and proceed with build + install logger.debug("Removing existing OCIO artifacts...") install_root = fs.open_fs(f"{prefix}") glob_filters = [ "**/OpenColorIO/**/*.h", "**/ocio*", "**/lib/**/*penColor*" ] _ = [ p.remove() for g in glob_filters for p in install_root.glob(g) ] else: # Bypass build + install return True mkdir, cmake, make, rm, git, tar = [ local[bin] for bin in ["mkdir", "cmake", "make", "rm", "git", "tar"] ] # Configure build variables url = "https://github.com/AcademySoftwareFoundation/OpenColorIO.git" git_clone = git["clone"] if version in ["2.0.0beta1", "2.0.0beta2", "2.0.0rc1", "2.0.0"]: branch = re.sub(r"(\d)(\w)", r"\1-\2", f"v{version}") git_clone = git_clone["--branch", branch] git_clone = git_clone[url] ldflags = f"-Wl,-rpath,{prefix}/lib" cxxflags = "-Wno-deprecated-declarations -fPIC" cmake_options = [ # '-G', 'Ninja', f"-DOCIO_BUILD_APPS={build_apps}", "-DOCIO_BUILD_NUKE=OFF", "-DOCIO_BUILD_DOCS=OFF", "-DOCIO_BUILD_TESTS=OFF", "-DOCIO_BUILD_GPU_TESTS=OFF", "-DOCIO_USE_HEADLESS=ON", "-DOCIO_BUILD_PYTHON=ON", "-DOCIO_BUILD_JAVA=OFF", f"-DBUILD_SHARED_LIBS={build_shared}", f"-DCMAKE_INSTALL_PREFIX={prefix}", "-DCMAKE_BUILD_TYPE=Release", "-DCMAKE_CXX_STANDARD=14", "-DOCIO_INSTALL_EXT_PACKAGES=MISSING", "-DOCIO_WARNING_AS_ERROR=OFF", ] # create temporary dir for building tmp_dir = "/tmp/build" mkdir["-p"](tmp_dir) with local.cwd(tmp_dir): git_repo_path = local.cwd / "OpenColorIO" build_dir = local.cwd / "build" # clone release tag (or master branch) if not git_repo_path.is_dir(): logger.debug(f"cloning to {git_repo_path}") git_clone(git_repo_path) # clean build dir rm["-rf"](build_dir) mkdir["-p"](build_dir) with local.cwd(build_dir): # build and install OCIO with local.env(CXXFLAGS=cxxflags, LDFLAGS=ldflags): logger.debug("Invoking CMake...") cmake[cmake_options](git_repo_path) logger.debug("Building and installing...") make["-j1"]("install") _ = archive_ocio_payload() logger.info(f"Built and installed OpenColorIO ({version}): {prefix}") if is_ocio_installed(): # Clean up build dir fs.open_fs(tmp_dir).removetree(".") return True else: raise ChildProcessError("Could not install OpenColorIO.")