def smarthome_process(self, message, token): request_id = self._request_id # type: str inputs = message.get('inputs') # type: list if len(inputs) != 1: return { 'requestId': request_id, 'payload': {'errorCode': ERR_PROTOCOL_ERROR} } handler = smarthomeControlMappings.get(inputs[0].get('intent')) if handler is None: return {'requestId': request_id, 'payload': {'errorCode': ERR_PROTOCOL_ERROR}} try: result = handler(self, inputs[0].get('payload'), token) return {'requestId': request_id, 'payload': result} except SmartHomeError as err: return {'requestId': request_id, 'payload': {'errorCode': err.code}} except Exception as e: logger.error(e) return {'requestId': request_id, 'payload': {'errorCode': ERR_UNKNOWN_ERROR}}
def connect_to_broker(): """Connects to MQTT broker""" # initiate mqtt client mqtt_c = mqtt.Client() # register event handlers mqtt_c.on_connect = on_connect mqtt_c.on_message = on_message mqtt_c.on_subscribe = on_subscribe mqtt_c.on_disconnect = on_disconnect mqtt_c.on_log = on_log # connect client with authentication try: mqtt_c.username_pw_set(username, password) app_logger.info("Username and password have been set.") except Exception as e: app_logger.error("There's a problem with the username or password: "******"Initiation of connection to broker.") except Exception as e: app_logger.error( "A problem was experienced while connecting to the broker: " + str(e)) # loop forever mqtt_c.loop_forever()
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=True, ensure_ascii=False)) response = self.smarthome_process(message, token) try: if 'errorCode' in response['payload']: logger.error('Error handling message %s: %s' % (message, response['payload'])) except: pass s.send_json(200, json.dumps(response, ensure_ascii=False).encode('utf-8'), True)
def settings(self, s): public_url = PUBLIC_URL try: getDevices() except Exception as e: logger.error( 'Connection to Domoticz refused!. Check configuration') if 'ngrok_tunnel' in configuration and configuration['ngrok_tunnel']: tunnels = getTunnelUrl() tunnel = tunnels[0].public_url if 'https' not in tunnel: public_url = tunnel.replace('http', 'https') else: public_url = tunnel user = self.getSessionUser() if user == None or user.get('uid', '') == '': s.redirect('/login?redirect_uri={0}'.format('/settings')) return message = '' meta = '<!-- <meta http-equiv="refresh" content="5"> -->' code = readFile(CONFIGFILE) logs = readFile(LOGFILE) template = TEMPLATE.format(message=message, uptime=uptime(), list=deviceList, meta=meta, code=code, conf=confJSON, public_url=public_url, logs=logs, update=update) s.send_message(200, template)
def getDeviceConfig(descstr): ISLIST = ['nicknames'] rawconfig = re.findall(r'<voicecontrol>(.*?)</voicecontrol>', descstr, re.DOTALL) if len(rawconfig) > 0: try: lines = rawconfig[0].strip().splitlines() cfgdict = {} for l in lines: assign = l.split('=') varname = assign[0].strip().lower() if varname != "": if varname in ISLIST: allvalues = assign[1].split(',') varvalues = [] for val in allvalues: varvalues.append(val.strip()) cfgdict[varname] = varvalues else: varvalue = assign[1].strip() if varvalue.lower() == "true": varvalue = True elif varvalue.lower() == "false": varvalue = False cfgdict[varname] = varvalue except: logger.error( 'Error parsing device configuration from Domoticz device description:', rawconfig[0]) return None return cfgdict return None
def login_post(self, s): user = self.getUser(s.form.get("username", None), s.form.get("password", None)) if user is None: if s.headers['X-Forwarded-For'] == None: logger.error("Failed login from %s", s.address_string()) else: logger.error("Failed login from %s", s.headers['X-Forwarded-For']) s.redirect( 'login?client_id=%s&redirect_uri=%s&redirect=%s&state=%s' % (s.form.get("client_id", None), s.form.get( "redirect_uri", None), s.form.get( "redirect", None), s.form.get("state", None)), 301) return self.setSessionUser(user) authCode = self.generateAuthCode(user['uid'], s.form.get("client_id", None)) if authCode is not None: s.redirect( '%s?code=%s&state=%s' % (urllib.parse.unquote( urllib.parse.unquote(s.form.get("redirect_uri", None))), authCode, s.form.get("state", None)), 301) return s.send_message(500, "Internal server error")
def settings(self, s): try: getDevices() except Exception as e: logger.error( 'Connection to Domoticz refused! Check configuration.') user = self.getSessionUser() if user == None or user.get('uid', '') == '': s.redirect('/login?redirect_uri={0}'.format('/settings')) return update = checkupdate() confJSON = json.dumps(configuration) public_url = getTunnelUrl() message = '' meta = '<!-- <meta http-equiv="refresh" content="5"> -->' code = readFile(CONFIGFILE) logs = readFile(LOGFILE) template = TEMPLATE.format(message=message, uptime=uptime(), list=deviceList, meta=meta, code=code, conf=confJSON, public_url=public_url, logs=logs, update=update) s.send_message(200, template)
def shutdown_network(*, teams: Optional[List[int]], **_kwargs): if teams is None: logger.error('Specify all required parameters: teams') exit(1) remove_drop_rules() all_rules = OPEN_NETWORK_RULES + INIT_RULES + get_team2vuln_rules(teams) remove_rules(all_rules)
def test_log_info(self, l): logger = helpers.logger.setup_normal_logger('logger_name') logger.info('a message') logger.error('an error') l.check( ('logger_name', 'INFO', 'a message'), ('logger_name', 'ERROR', 'an error'), )
def isolate_team(teams, team, *_args, **_kwargs): if teams is None or team is None: logger.error('Specify all required parameters: teams, team') exit(1) forward_init_rules = list( filter(lambda x: x.startswith('FORWARD'), INIT_RULES)) count_before = len(forward_init_rules) + len(get_team2vuln_rules(teams)) insert_rules(get_isolation_rules(team), count_before)
def valid_files(self): logger.info('Selecting of valid files started here') try: with os.scandir(self.src_folder) as entries: for file in entries: info = file.stat() if info.st_size != 0: self.file_names.append(file.name) logger.info('Selecting of valid files finished here') except FileNotFoundError as e: logger.error(f'{e.strerror} ({self.src_folder})') os._exit(250)
def save(self): """Persists sensor data to Influx database""" self.check_db() try: self.db_client.write_points(self.compile_sensor_data(), time_precision='s') app_logger.info("Save to database") return True except exceptions.InfluxDBClientError as e: app_logger.error(str(e)) except exceptions.InfluxDBServerError as e1: app_logger.error(str(e1))
def create_brochure(username, apikey, out): try: client = pdfcrowd.PdfToPdfClient(username, apikey) for pdf in gen_pdfs(username, apikey): client.addPdfRawData(pdf) logger.info('joining PDF files into %s', out) client.convertToFile(out) except pdfcrowd.Error as why: logger.error('Pdfcrowd Error: %s', why) sys.exit(1)
def check_db(): # get all databases all_dbs_list = Database.db_client.get_list_database() # check if current database exists and if not create it if Database.cnf.INFLUX_DB not in [ str(x['name']) for x in all_dbs_list ]: try: app_logger.info("Creating db {0}".format( Database.cnf.INFLUX_DB)) Database.db_client.create_database(Database.cnf.INFLUX_DB) app_logger.info("A new InfluxDB database has been created.") return True except exceptions.InfluxDBClientError as e: app_logger.error(str(e)) except exceptions.InfluxDBServerError as e1: app_logger.error(str(e1)) else: try: app_logger.info("Reusing db {0}".format( Database.cnf.INFLUX_DB)) Database.db_client.switch_database(Database.cnf.INFLUX_DB) app_logger.info("Switched to db {}".format( Database.cnf.INFLUX_DB)) return True except exceptions.InfluxDBClientError as e: app_logger.error(str(e)) except exceptions.InfluxDBServerError as e1: app_logger.error(str(e1))
def init_network(*, teams: List[int], **_kwargs): if teams is None: logger.error('Specify all required parameters: teams') exit(1) rules = INIT_RULES + get_team2vuln_rules(teams) add_rules(rules) add_drop_rules() logger.info('Enabling ip forwarding') if not DRY_RUN: with open('/proc/sys/net/ipv4/ip_forward', 'w') as f: f.write('1')
def __init__(self, url, progress_callback=None): """ Construct the YouTubeVideo object. args: url: The URL of a YouTube video progress_callback: The name of the callback function to be called """ super().__init__(url, progress_callback) self.error = False try: self.yt = YouTube(url, on_progress_callback=progress_callback) logger.info(f"URL: {self.url}") except RegexMatchError: # Catches a Regex Error from URLs with invalid format logger.error("Caught error: RegexMatchError") logger.error(f"Inputted link \"{url}\" is not a valid URL") self.error = f"{url} is an invalid URL" except VideoUnavailable: # Catches a VideoUnavailable Error if pytube cannot # process the video logger.error(f"Caught error: VideoUnavailable") logger.error(f"Inputted link \"{url}\" does not exist") self.error = f"{url} does not exist" except Exception as errorMessage: # Catches any other unexpected error exceptionName = errorMessage.__class__.__name__ self.logger.error(f"General Error Caught: {exceptionName}") self.logger.error(f"{errorMessage}") self.error = f"{exceptionName}:\n{errorMessage}"
def forceDevicesSync(self): userAgent = self.getUserAgent() enableReport = ReportState.enable_report_state() if userAgent is None: return 500 # internal error data = {"agentUserId": userAgent} if enableReport: r = ReportState.call_homegraph_api(REQUEST_SYNC_BASE_URL, data) elif 'Homegraph_API_Key' in configuration and configuration['Homegraph_API_Key'] != 'ADD_YOUR HOMEGRAPH_API_KEY_HERE': r = ReportState.call_homegraph_api_key(REQUEST_SYNC_BASE_URL, data) else: logger.error("No configuration for request_sync available") return r
def checkupdate(): try: r = requests.get( 'https://raw.githubusercontent.com/DewGew/Domoticz-Google-Assistant/master/const.py' ) text = r.text if VERSION not in text: update = 1 logger.info("========") logger.info(" New version is availible on Github!") else: update = 0 return update except Exception as e: logger.error('Connection to Github refused!. Check configuration')
def on_connect(mqtt_client, userdata, flags, rc): return_code = { 0: "Connection successful", 1: "Connection refused – incorrect protocol version", 2: "Connection refused – invalid client identifier", 3: "Connection refused – server unavailable", 4: "Connection refused – bad username or password", 5: "Connection refused – not authorised" } if rc == 0: app_logger.info("Broker connection was successful") mqtt_client.subscribe(topic, int(qos)) else: app_logger.error( return_code.get(rc, "Unable to identify return code error!"))
def checkupdate(): if repo is not None and 'CheckForUpdates' in configuration and configuration['CheckForUpdates'] == True: try: r = requests.get( 'https://raw.githubusercontent.com/DewGew/Domoticz-Google-Assistant/' + branch + '/const.py') response = r.text if VERSION not in response: update = 1 else: update = 0 return update except Exception as e: logger.error('Connection to Github refused! Check configuration.') return 0 else: return 0
def convert_pages(username, apikey, pages, out): if not os.path.isdir(out): os.makedirs(out) try: client = pdfcrowd.HtmlToPdfClient(username, apikey) client.setFailOnMainUrlError(True) for i, url in enumerate(gen_urls(pages)): file_name = os.path.join(out, 'generated_{}.pdf'.format(i)) logger.info('creating %s from %s', file_name, url) client.convertUrlToFile(url, file_name) except pdfcrowd.Error as why: logger.error('Pdfcrowd Error: %s', why) sys.exit(1)
def forceDevicesSync(self): userAgent = self.getUserAgent() if userAgent == None: return 500 #internal error url = REQUEST_SYNC_BASE_URL + '?key=' + configuration[ 'Homegraph_API_Key'] j = {"agentUserId": userAgent} r = requests.post(url, json=j) if 'error' in r.text: logger.error(r.text) return r.status_code == requests.codes.ok
def smarthome_exec(self, payload, token): """Handle action.devices.EXECUTE request. https://developers.google.com/actions/smarthome/create-app#actiondevicesexecute """ entities = {} results = {} for command in payload['commands']: for device, execution in product(command['devices'], command['execution']): entity_id = device['id'] # Happens if error occurred. Skip entity for further processing if entity_id in results: continue if entity_id not in entities: if len(aogDevs) == 0: getDevices() getSettings() state = aogDevs.get(entity_id, None) if state is None: results[entity_id] = {'ids': [entity_id], 'status': 'ERROR', 'errorCode': ERR_DEVICE_OFFLINE} continue entities[entity_id] = _GoogleEntity(state) try: entities[entity_id].execute(execution['command'], execution.get('params', {}), execution.get('challenge', None)) except SmartHomeError as err: results[entity_id] = {'ids': [entity_id], 'status': 'ERROR', 'errorCode': err.code} logger.error(err) except SmartHomeErrorNoChallenge as err: results[entity_id] = {'ids': [entity_id], 'status': 'ERROR', 'errorCode': err.code, 'challengeNeeded': {'type': err.desc}} logger.error(err) final_results = list(results.values()) for entity in entities.values(): if entity.entity_id in results: continue entity.async_update() final_results.append({'ids': [entity.entity_id], 'status': 'SUCCESS', 'states': entity.query_serialize()}) return {'commands': final_results}
def checkupdate(): if 'CheckForUpdates' in configuration and configuration['CheckForUpdates'] == True: try: r = requests.get( 'https://raw.githubusercontent.com/DewGew/Domoticz-Google-Assistant/' + repo.active_branch.name + '/const.py') text = r.text if VERSION not in text: update = 1 logger.info("========") logger.info(" New version is availible on Github!") else: update = 0 return update except Exception as e: logger.error('Connection to Github refused! Check configuration.') return 0 else: return 0
def compile_sensor_data(self): """Compiles sensor related data into a single object Return: db_data (list): compiled sensor data object """ try: sensor_type = parser.get_sensor_type(self._sensor_topic) db_data = [{ "measurement": sensor_type, "tags": { "id": uuid.uuid4() }, "fields": parser.parse_multiple_sensor_data_to_dict(self._sensor_data) }] app_logger.info("Sensor data compiled successfully.") return db_data except Exception as e: app_logger.error(str(e))
def __init__(self, exe_name: str): """ Gets the process ID for the executable, then a handle for that process, then we get the base memory address for our process using the handle. With the base memory address known, we can then perform our standard memory calls (read_int, etc) to get data from memory. :param exe_name: The executable name of the program we want to read memory from """ self.exe = exe_name try: self.pid = self._get_process_id() self.handle = self._get_process_handle() self.base_address = self._get_base_address() # There is definitely a better way to get lots of base memory data, but # this is v1 of automated pattern searching bulk_scan = self.read_bytes(self.base_address, 1000000000) self.u_world_base = search_data_for_pattern( bulk_scan, UWORLDPATTERN) self.g_object_base = search_data_for_pattern( bulk_scan, GOBJECTPATTERN) self.g_name_base = search_data_for_pattern(bulk_scan, GNAMEPATTERN) del bulk_scan g_name_offset = self.read_ulong(self.base_address + self.g_name_base + 3) g_name_ptr = self.base_address + self.g_name_base + g_name_offset + 7 self.g_name_start_address = self.read_ptr(g_name_ptr) logger.info(f"gObject offset: {hex(self.g_object_base)}") logger.info(f"uWorld offset: {hex(self.u_world_base)}") logger.info(f"gName offset: {hex(self.g_name_base)}") except Exception as e: logger.error(f"Error initializing memory reader: {e}")
def execute(self, command, params): """Execute a Timer command.""" version = self.state.dzvents # date_str = datetime.strptime(self.state.lastupdate, "%Y-%m-%d %H:%M:%S") # timestamp = datetime.timestamp(date_str) # print("date =", date_str) # print("timestamp =", timestamp) if version is not None and version >= '3.0.0': if command == COMMAND_TIMER_START: url = DOMOTICZ_URL + '/json.htm?type=command¶m=customevent&event=TIMER&data={"idx":' + self.state.id + ',"time":' + str(params['timerTimeSec']) + ',"on":true}' r = requests.get(url, auth=CREDITS) if command == COMMAND_TIMER_CANCEL: url = DOMOTICZ_URL + '/json.htm?type=command¶m=customevent&event=TIMER&data={"idx":' + self.state.id + ',"cancel":true}' r = requests.get(url, auth=CREDITS) else: logger.error('To use Timer function you need to run Domoticz version above 2020.1.11804') logger.error('and have dzVents Dzga_Timer script installed and active') raise SmartHomeError('functionNotSupported', 'Unable to execute {} for {} check your settings'.format(command, self.state.entity_id))
colorDOMAIN, mediaDOMAIN, speakerDOMAIN, cameraDOMAIN, securityDOMAIN, outletDOMAIN, sensorDOMAIN, doorDOMAIN, selectorDOMAIN, fanDOMAIN, ATTRS_BRIGHTNESS, ATTRS_THERMSTATSETPOINT, ATTRS_COLOR, ATTRS_COLOR_TEMP, ATTRS_PERCENTAGE, VERSION, PUBLIC_URL) print("The system uptime is:", uptime()) try: 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'])) except Exception as e: logger.error('Connection to Domoticz refused!. Check configuration') update = 0 confJSON = json.dumps(configuration) public_url = PUBLIC_URL def checkupdate(): try: r = requests.get( 'https://raw.githubusercontent.com/DewGew/Domoticz-Google-Assistant/master/const.py' ) text = r.text if VERSION not in text: update = 1 logger.info("========")
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
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 ReportState = ReportState() if not ReportState.enable_report_state(): logger.error("Service account key is not found.") logger.error("Report state will be unavailable") def checkupdate(): if 'CheckForUpdates' in configuration and configuration[