def get_edr_vesta_measures(self, measures_id): url = self.vesta_plugin_settings[ "edr_url"] + "/store/esdl/" + measures_id + "?format=xml" try: r = requests.get(url) if r.status_code == 200: result = [] self.selected_measures = ESDLAsset.load_asset_from_string( r.text) for m in self.selected_measures.measure: result.append({"id": m.id, "name": m.name}) return result else: print( 'EDR returned unexpected result. Check Vesta plugin settings' ) send_alert( 'EDR returned unexpected result. Check Vesta plugin settings' ) return None except Exception as e: print('Error accessing EDR API: ' + str(e)) send_alert('Error accessing EDR API: ' + str(e)) return None
def get_bag_contours(info): with self.flask_app.app_context(): print("getting bag information") esh = get_handler() active_es_id = get_session('active_es_id') area_id = info["id"] area_polygon = { 'type': 'polygon', 'coordinates': info["polygon"] } geometry = ESDLGeometry.create_ESDL_geometry(area_polygon) boundary_wgs = ESDLGeometry.create_boundary_from_geometry(geometry) # boundary_geojson = ESDLGeometry.create_geojson(area_id, '', [], boundary_wgs) wkt_string = wkt.dumps(boundary_wgs) # wkt_string = 'POLYGON ((4.359093904495239 52.012174264626445, 4.357388019561768 52.01154692445308, 4.357978105545044 52.01078750089633, 4.360188245773315 52.01160635705717, 4.362355470657349 52.012478026181434, 4.360767602920532 52.012847820073766, 4.359093904495239 52.012174264626445))' # wkt_quoted = urllib.parse.quote(wkt_string) es_edit = esh.get_energy_system(es_id=active_es_id) instance = es_edit.instance top_area = instance[0].area target_area = ESDLEnergySystem.find_area(top_area, area_id) if target_area: try: # url = 'http://' + settings.bag_config["host"] + ':' + settings.bag_config["port"] + \ # settings.bag_config["path_contour"] + '?wkt=' + wkt_quoted + '&format=xml' # print(url) # r = requests.get(url) url = 'http://' + settings.bag_config["host"] + ':' + settings.bag_config["port"] + \ settings.bag_config["path_contour"] + '?format=xml' print(url) r = requests.post(url, json={"wkt": wkt_string}) if r.status_code == 201: esdl_string = r.text bag_es = ESDLAsset.load_asset_from_string(esdl_string) if bag_es: bag_inst = bag_es.instance[0] if bag_inst: bag_area = bag_inst.area if bag_area: bld_list = [] for bld in bag_area.asset: if isinstance(bld, esdl.Building): target_area.asset.append(bld.deepcopy()) geometry = bld.geometry boundary_wgs = ESDLGeometry.create_boundary_from_geometry(geometry) bld_list.append(ESDLGeometry.create_geojson(bld.id, bld.name, [], boundary_wgs)) if bld_list: emit('geojson', {"layer": "bld_layer", "geojson": bld_list}) except Exception as e: print('ERROR in accessing BAG service: '+str(e)) return None # @EWOUD: Deze 'mogelijkheid' kunnen we ook gebruiken om geometries te renderen in de frontend # self.emit_geometries_to_client(esh, active_es_id, bld_list) else: print("ERROR in finding area in ESDL for BAG service") # self.flask_app.send_alert("ERROR in finding area in ESDL for BAG service") return None
def call_esdl_service(self, service_params): """Actually call an ESDL service.""" esh = get_handler() active_es_id = get_session("active_es_id") # {'service_id': '18d106cf-2af1-407d-8697-0dae23a0ac3e', 'area_scope': 'provincies', 'area_id': '12', # 'query_parameters': {'bebouwingsafstand': '32432', 'restrictie': 'vliegveld', 'preferentie': 'infrastructuur', 'geometrie': 'true'}} # Find the currently active service. service = None for config_service in self.config: if config_service["id"] == service_params["service_id"]: service = config_service break # If it's a workflow, lookin its steps. if config_service["type"] == "workflow": for step in config_service["workflow"]: if (step["type"] == "service" and step["service"]["id"] == service_params["service_id"]): service = step["service"] break if service is None: return False, None url = service["url"] headers = service["headers"] if service.get("with_jwt_token", False): jwt_token = get_session("jwt-token") headers["Authorization"] = f"Bearer {jwt_token}" body = {} if "send_email_in_post_body_parameter" in service: body[service["send_email_in_post_body_parameter"]] = get_session( "user-email") if service["type"] == "geo_query": area_scope_tag = service["geographical_scope"]["url_area_scope"] area_id_tag = service["geographical_scope"]["url_area_id"] area_scope = service_params["area_scope"] url = url.replace(area_scope_tag, area_scope) ares_id = service_params["area_id"] url = url.replace(area_id_tag, ares_id) if "url_area_subscope" in service["geographical_scope"]: area_subscope_tag = service["geographical_scope"][ "url_area_subscope"] area_subscope = service_params["area_subscope"] url = url.replace(area_subscope_tag, area_subscope) elif service["type"] == "send_esdl": esdlstr = esh.to_string(active_es_id) if service["body"] == "url_encoded": body["energysystem"] = urllib.parse.quote(esdlstr) # print(body) elif service["body"] == "base64_encoded": esdlstr_bytes = esdlstr.encode('ascii') esdlstr_base64_bytes = base64.b64encode(esdlstr_bytes) body["energysystem"] = esdlstr_base64_bytes.decode('ascii') else: body = esdlstr elif service["type"] == "simulation": esdlstr = esh.to_string(active_es_id) if service["body"] == "url_encoded": body["energysystem"] = urllib.parse.quote(esdlstr) elif service["body"] == "base64_encoded": esdlstr_bytes = esdlstr.encode('ascii') esdlstr_base64_bytes = base64.b64encode(esdlstr_bytes) body["energysystem"] = esdlstr_base64_bytes.decode('ascii') else: body = esdlstr query_params = service_params["query_parameters"] config_service_params = service["query_parameters"] if query_params: first_qp = True for key in query_params: if query_params[ key]: # to filter empty lists for multi-selection parameters for cfg_service_param in config_service_params: if cfg_service_param["parameter_name"] == key: if "location" in cfg_service_param: if cfg_service_param["location"] == "url": url = url.replace( "<" + cfg_service_param["parameter_name"] + ">", query_params[key], ) elif cfg_service_param[ "location"] == "body" and isinstance( body, dict): body[cfg_service_param[ "parameter_name"]] = query_params[key] else: if first_qp: url = url + "?" else: url = url + "&" url = (url + key + "=" + self.array2list(query_params[key])) first_qp = False try: if service["http_method"] == "get": r = requests.get(url, headers=headers) elif service["http_method"] == "post": if service["type"] == "json": kwargs = {"json": body} else: kwargs = {"data": body} r = requests.post(url, headers=headers, **kwargs) else: # Should not happen, there should always be a method. return False, None if (service["http_method"] == "get" and r.status_code == 200) or \ (service["http_method"] == "post" and r.status_code == 201): # print(r.text) if service["result"][0]["action"] == "esdl": esh.add_from_string(service["name"], r.text) return True, None elif service["result"][0]["action"] == "print": return True, json.loads(r.text) elif service["result"][0]["action"] == "add_assets": es_edit = esh.get_energy_system(es_id=active_es_id) instance = es_edit.instance area = instance[0].area asset_str_list = json.loads(r.text) try: for asset_str in asset_str_list["add_assets"]: asset = ESDLAsset.load_asset_from_string(asset_str) esh.add_object_to_dict(active_es_id, asset) ESDLAsset.add_asset_to_area( es_edit, asset, area.id) asset_ui, conn_list = energy_asset_to_ui( esh, active_es_id, asset) emit( "add_esdl_objects", { "es_id": active_es_id, "asset_pot_list": [asset_ui], "zoom": True, }, ) emit( "add_connections", { "es_id": active_es_id, "conn_list": conn_list }, ) except Exception as e: logger.warning("Exception occurred: " + str(e)) return False, None return True, {"send_message_to_UI_but_do_nothing": {}} elif service["result"][0]["action"] == "show_message": return True, {"message": service["result"][0]["message"]} else: logger.warning("Error running ESDL service - response " + str(r.status_code) + " with reason: " + str(r.reason)) logger.warning(r) logger.warning(r.content) return False, None except Exception as e: logger.warning("Error accessing external ESDL service: " + str(e)) return False, None return False, None
def call_esdl_service(self, service_params): """Actually call an ESDL service.""" esh = get_handler() active_es_id = get_session("active_es_id") # {'service_id': '18d106cf-2af1-407d-8697-0dae23a0ac3e', 'area_scope': 'provincies', 'area_id': '12', # 'query_parameters': {'bebouwingsafstand': '32432', 'restrictie': 'vliegveld', 'preferentie': 'infrastructuur', 'geometrie': 'true'}} # Find the currently active service. service = None # services_list = get_session('services_list') user_email = get_session('user-email') role = get_session('user-role') services_list = self.get_user_services_list(user_email, role) for config_service in services_list: if config_service["id"] == service_params["service_id"]: service = config_service break # If it's a workflow, look in its steps. if config_service["type"] in ("workflow", "vueworkflow"): for step in config_service["workflow"]: if (step["type"] in ("service", "custom")): if "service" in step and step["service"][ "id"] == service_params["service_id"]: service = step["service"] break if service is None: return False, None url = service["url"] headers = service["headers"] if service.get("with_jwt_token", False): jwt_token = get_session("jwt-token") headers["Authorization"] = f"Bearer {jwt_token}" body = {} if "send_email_in_post_body_parameter" in service: body[service["send_email_in_post_body_parameter"]] = get_session( "user-email") if service["type"] == "geo_query": area_scope_tag = service["geographical_scope"]["url_area_scope"] area_id_tag = service["geographical_scope"]["url_area_id"] area_scope = service_params["area_scope"] url = url.replace(area_scope_tag, area_scope) ares_id = service_params["area_id"] url = url.replace(area_id_tag, ares_id) if "url_area_subscope" in service["geographical_scope"]: area_subscope_tag = service["geographical_scope"][ "url_area_subscope"] area_subscope = service_params["area_subscope"] url = url.replace(area_subscope_tag, area_subscope) elif service["type"].startswith("send_esdl"): esdlstr = esh.to_string(active_es_id) if service["body"] == "url_encoded": body["energysystem"] = urllib.parse.quote(esdlstr) # print(body) elif service["body"] == "base64_encoded": esdlstr_bytes = esdlstr.encode('utf-8') esdlstr_base64_bytes = base64.b64encode(esdlstr_bytes) body["energysystem"] = esdlstr_base64_bytes.decode('utf-8') else: body = esdlstr elif service["type"] == "simulation": esdlstr = esh.to_string(active_es_id) if service["body"] == "url_encoded": body["energysystem"] = urllib.parse.quote(esdlstr) elif service["body"] == "base64_encoded": esdlstr_bytes = esdlstr.encode('utf-8') esdlstr_base64_bytes = base64.b64encode(esdlstr_bytes) body["energysystem"] = esdlstr_base64_bytes.decode('utf-8') else: body = esdlstr if "body_config" in service: if service["body_config"]["type"] == "text": esdlstr = esh.to_string(active_es_id) if service["body_config"]["encoding"] == "none": body = esdlstr if service["body_config"]["encoding"] == "url_encoded": body = urllib.parse.quote(esdlstr) if service["body_config"]["encoding"] == "base64_encoded": esdlstr_bytes = esdlstr.encode('utf-8') esdlstr_base64_bytes = base64.b64encode(esdlstr_bytes) body = esdlstr_base64_bytes.decode('utf-8') if service["body_config"]["type"] == "json": body = {} for param in service["body_config"]['parameters']: if param["type"] == "esdl": esdlstr = esh.to_string(active_es_id) if param["encoding"] == "none": body[param["parameter"]] = esdlstr if param["encoding"] == "url_encoded": body[param["parameter"]] = urllib.parse.quote( esdlstr) if param["encoding"] == "base64_encoded": esdlstr_bytes = esdlstr.encode('utf-8') esdlstr_base64_bytes = base64.b64encode( esdlstr_bytes) body[param[ "parameter"]] = esdlstr_base64_bytes.decode( 'utf-8') if param["type"] == "value": body[param["parameter"]] = param["value"] if param["type"] == "json_string": body_params = service_params["body_config"] for bp in body_params: if param["parameter"] == bp: body[param["parameter"]] = body_params[bp] query_params = service_params["query_parameters"] config_service_params = service.get("query_parameters", {}) if query_params: first_qp = True for key in query_params: if query_params[ key]: # to filter empty lists for multi-selection parameters for cfg_service_param in config_service_params: if cfg_service_param["parameter_name"] == key: if "location" in cfg_service_param: if cfg_service_param["location"] == "url": url = url.replace( "<" + cfg_service_param["parameter_name"] + ">", str(query_params[key]), ) elif cfg_service_param[ "location"] == "body" and isinstance( body, dict): body[cfg_service_param[ "parameter_name"]] = query_params[key] else: if first_qp: url = url + "?" else: url = url + "&" url = (url + key + "=" + self.array2list(query_params[key])) first_qp = False try: if service["http_method"] == "get": r = requests.get(url, headers=headers) elif service["http_method"] == "post": if service["type"].endswith("json") or ( "body_config" in service and service["body_config"]["type"] == "json"): kwargs = {"json": body} else: kwargs = {"data": body} r = requests.post(url, headers=headers, **kwargs) else: # Should not happen, there should always be a method. return False, None if r.status_code == 200 or r.status_code == 201: # print(r.text) if service["result"][0]["action"] == "esdl": if "encoding" in service["result"][0]: if service["result"][0]["encoding"] == "url_encoded": esdl_response = urllib.parse.quote(r.text) elif service["result"][0][ "encoding"] == "base64_encoded": esdlstr_bytes = r.text.encode('utf-8') esdlstr_base64_bytes = base64.b64decode( esdlstr_bytes) esdl_response = esdlstr_base64_bytes.decode( 'utf-8') else: esdl_response = r.text else: esdl_response = r.text es, parse_info = esh.add_from_string( service["name"], esdl_response) # TODO deal with parse_info? return True, None elif service["result"][0]["action"] == "print": return True, json.loads(r.text) elif service["result"][0]["action"] == "add_assets": es_edit = esh.get_energy_system(es_id=active_es_id) instance = es_edit.instance area = instance[0].area asset_str_list = json.loads(r.text) # Fix for services that return an ESDL string that represents one asset if isinstance(asset_str_list, str): asset_str_list = {"add_assets": [asset_str_list]} try: for asset_str in asset_str_list["add_assets"]: asset = ESDLAsset.load_asset_from_string(asset_str) esh.add_object_to_dict(active_es_id, asset) ESDLAsset.add_object_to_area( es_edit, asset, area.id) asset_ui, conn_list = energy_asset_to_ui( esh, active_es_id, asset) emit( "add_esdl_objects", { "es_id": active_es_id, "asset_pot_list": [asset_ui], "zoom": True, }, ) emit( "add_connections", { "es_id": active_es_id, "conn_list": conn_list }, ) except Exception as e: logger.warning("Exception occurred: " + str(e)) return False, None return True, {"send_message_to_UI_but_do_nothing": {}} elif service["result"][0]["action"] == "add_notes": es_edit = esh.get_energy_system(es_id=active_es_id) esi = es_edit.energySystemInformation if not esi: esi = es_edit.energySystemInformation = esdl.EnergySystemInformation( id=str(uuid.uuid4())) esh.add_object_to_dict(active_es_id, esi) notes = esi.notes if not notes: notes = esi.notes = esdl.Notes(id=str(uuid.uuid4())) esh.add_object_to_dict(active_es_id, notes) notes_from_service = ESDLAsset.load_asset_from_string( esdl_string=r.text) if isinstance(notes_from_service, esdl.Notes): notes_list = [] for note in list(notes_from_service.note): notes.note.append(note) esh.add_object_to_dict(active_es_id, note) map_location = note.mapLocation if map_location: coords = { 'lng': map_location.lon, 'lat': map_location.lat } notes_list.append({ 'id': note.id, 'location': coords, 'title': note.title, 'text': note.text, 'author': note.author }) # , 'date': n.date}) emit('add_notes', { 'es_id': active_es_id, 'notes_list': notes_list }) else: logger.error("Service with id " + service_params["service_id"] + " did not return a esdl.Notes object") return False, None return True, {"send_message_to_UI_but_do_nothing": {}} elif service["result"][0]["action"] == "asset_feedback": service_results = json.loads(r.text) asset_results_dict = dict() for sr in service_results: asset_results_dict[sr['assetID']] = sr['messages'] return True, {"asset_feedback": asset_results_dict} elif service["result"][0]["action"] == "show_message": return True, {"message": service["result"][0]["message"]} else: logger.warning("Error running ESDL service - response " + str(r.status_code) + " with reason: " + str(r.reason)) logger.warning(r) logger.warning(r.content) return False, str(r.content) except Exception as e: logger.exception("Error accessing external ESDL service: " + str(e)) return False, None return False, None