def socketio_duplicate(message): with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') print('Duplicate EnergyAsset: %s' % message) duplicate = duplicate_energy_asset(esh, active_es_id, message['asset_id']) self.add_asset_and_emit(esh, active_es_id, duplicate, message['area_bld_id'])
def set_area_restrictions(area_id): with self.flask_app.app_context(): esh = get_handler() print(area_id) area_id = get_area_id_from_mapeditor_id(area_id) active_es_id = get_session('active_es_id') current_es = esh.get_energy_system(active_es_id) top_area = current_es.instance[0].area area = ESDLEnergySystem.find_area(top_area, area_id) measures = area.measures current_area_measures_list = [] if measures: for m in measures.measure: if isinstance(m, esdl.MeasureReference): this_measure = m.reference else: this_measure = m current_area_measures_list.append({ "id": this_measure.id, "name": this_measure.name }) data = { "current_measures": current_area_measures_list, "area_id": area_id } emit('vesta_restrictions_data', data)
def delete_ref(self, message: DeleteRefMessage): parent_object = self.get_object_from_identifier(message.parent) esh = get_handler() active_es_id = get_session('active_es_id') reference: EReference = parent_object.eClass.findEStructuralFeature( message.ref_name) ref_object = parent_object.eGet(reference) print('deleting', message, ref_object) if reference.containment: try: esh.remove_object_from_dict(active_es_id, ref_object, True) resource = esh.get_resource(active_es_id) fragment = ref_object.eURIFragment() del resource._resolve_mem[ fragment] # update fragment cache for pyecore<0.12.0 except KeyError as e: print('ESDL Browser: can\'t delete id from uuid_dict', e) ref_object.delete( recursive=True ) # will automatically remove the reference from the list else: if reference.many: eOrderedSet = parent_object.eGet(reference) eOrderedSet.remove(ref_object) else: parent_object.eSet(reference, reference.get_default_value()) # send updated reference description to frontend response = ESDLEcore.describe_reference_value( parent_object.eGet(reference), ESDLBrowser.generate_repr) print('delete ref response', response) return response
def socket_io_delete_ref(message): # esdl_browse_delete_ref active_es_id = get_session('active_es_id') esh = get_handler() reference_name = message['name'] ref_object = self.get_object_from_identifier(message['ref_id']) parent_object = self.get_object_from_identifier(message['parent']) reference: EReference = parent_object.eClass.findEStructuralFeature(reference_name) if reference.containment: try: esh.remove_object_from_dict(active_es_id, ref_object, True) resource = esh.get_resource(active_es_id) fragment = ref_object.eURIFragment() del resource._resolve_mem[fragment] except KeyError as e: print('ESDL Browser: can\'t delete id from uuid_dict') if isinstance(ref_object, esdl.EnergyAsset): emit('delete_esdl_object', {'asset_id': ref_object.id}) for port in ref_object.port: from_id = port.id to_ports = port.connectedTo for to_port in to_ports: to_id = to_port.id emit('remove_single_connection', {'from-port-id':from_id, 'to-port-id':to_id, 'es_id': active_es_id}) ref_object.delete(recursive=True) # will automatically remove the reference from the list else: if reference.many: eOrderedSet = parent_object.eGet(reference) eOrderedSet.remove(ref_object) else: parent_object.eSet(reference, reference.get_default_value()) browse_data = self.get_browse_to_data(parent_object) emit('esdl_browse_to', browse_data, namespace='/esdl')
def spatop_preprocess_subarea(): with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') es = esh.get_energy_system(active_es_id) area = es.instance[0].area return self.preprocess_area(area)
def set_param(self, object, attr_name, attr_value): with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') try: attribute = object.eClass.findEStructuralFeature(attr_name) if attribute is not None: if attr_value == "": parsed_value = attribute.eType.default_value else: parsed_value = attribute.eType.from_string(attr_value) if attribute.many: eOrderedSet = object.eGet(attr_name) eOrderedSet.clear() # TODO no support for multi-select of enums eOrderedSet.append(parsed_value) object.eSet(attr_name, eOrderedSet) else: if attribute.name == 'id': esh.remove_object_from_dict(active_es_id, object) object.eSet(attr_name, parsed_value) esh.add_object_to_dict(active_es_id, object) else: object.eSet(attr_name, parsed_value) else: print('Error setting attribute {} of {} to {}, unknown attribute'.format(attr_name, object.name, attr_value)) except Exception as e: print('Error setting attribute {} of {} to {}, caused by {}'.format(attr_name, object.name, attr_value, str(e)))
def call_residentail_EG_service(self, area_id, area_type): esh = get_handler() url = "http://10.30.2.1:4008/" + area_type.name + "/" + area_id + "?format=xml" headers = {"Accept": "test/xml", "User-Agent": "ESDL Mapeditor/0.1"} asset_list = list() qau_list = list() try: r = requests.get(url, headers=headers) if r.status_code == 200: corrected_esdl = r.text.replace('aggregationCount=""', 'aggregationCount="1"') print(corrected_esdl) res_eg_es = esh.load_external_string(corrected_esdl, "residentail_EG.esdl") for asset in res_eg_es.instance[0].area.asset: asset_copy = asset.deepcopy() asset_copy.id = str(uuid.uuid4()) asset_copy.port[0].id = str(uuid.uuid4()) asset_copy.port[0].profile[0].id = str(uuid.uuid4()) asset_list.append(asset_copy) for qau in res_eg_es.energySystemInformation.quantityAndUnits.quantityAndUnit: qau_list.append(qau.deepcopy()) except: print("Error accessing API") return asset_list, qau_list
def receive_energyasset_info(shapefile_energyasset_list): with self.flask_app.app_context(): print("Received shpcvrt_receive_energyasset_info") esh = get_handler() active_es_id = get_session('active_es_id') es = esh.get_energy_system(active_es_id) area = es.instance[0].area for shapefile_energyasset in shapefile_energyasset_list: energy_asset = shapefile_energyasset['energy_asset'] shapefile_name = shapefile_energyasset['shapefile_name'] zipfile_row = shapefile_energyasset['zipfile_row'] # zipfile_name = self.zipfiles[int(zipfile_row)] # directory = get_session('shapefile_dir' + zipfile_row) shapefile_name_base = os.path.splitext(shapefile_name)[0] print(shapefile_name_base + ' --> ' + energy_asset) if energy_asset != 'ignore': basename = os.path.basename(shapefile_name_base) subarea = esdl.Area(id=str(uuid4()), name=basename) area.area.append(subarea) self.process_shapefile(subarea, shapefile_name_base, energy_asset) # update uuid_dict recursively for the main area (could take long?) esh.add_object_to_dict(es_id=active_es_id, esdl_object=area, recursive=True) self.executor.submit(process_energy_system, esh=esh, filename='test', force_update_es_id=active_es_id)
def query_pico_rooftoppv_api(area): esh = get_handler() asset_copy = None for code in PICO_ID_TO_URL_MAPPING: if area.id[0: len(code)].upper() == code: url = PICO_API_URL + PICO_ID_TO_URL_MAPPING[code] + "/" + area.id.upper() + "/zonopdak?geometrie=false" headers = { "Accept": "application/esdl+xml", "User-Agent": "ESDL Mapeditor/0.1", } try: r = requests.get(url, headers=headers) if r.status_code == 200: # print(r.text) pzod_es, parse_info = esh.load_external_string(r.text, "pico_zon_op_dak") asset = pzod_es.instance[0].area.asset[0] if asset: if isinstance(asset, esdl.AggregatedBuilding): asset_copy = asset.deepcopy() else: logger.warning("PICO API requests returned error {} for area ID {}".format(r.status_code, area.id)) except Exception as e: logger.warning("Error accessing PICO API: " + str(e)) return asset_copy
def socketio_create_object(message): # {'parent': {'id': parent_object.id, 'fragment': parent_object.fragment}, 'name': reference_data.name, 'type': types[0]} esh = get_handler() active_es_id = get_session('active_es_id') parent_object = self.get_object_from_identifier(message['parent']) reference_name = message['name'] attribute = parent_object.eClass.findEStructuralFeature(reference_name) if attribute is not None: object_type = message['type'] new_object = ESDLEcore.instantiate_type(object_type) if attribute.many: eOrderedSet = parent_object.eGet(reference_name) eOrderedSet.append(new_object) else: parent_object.eSet(reference_name, new_object) else: print("Error: Can't find reference {} of {}", reference_name, parent_object.name) return if hasattr(new_object, 'id'): new_object.id = esh.generate_uuid() esh.add_object_to_dict(active_es_id, new_object) print('adding to uuid dict ' + new_object.id) if hasattr(new_object, 'name'): new_object.name = 'New' + new_object.eClass.name browse_data = self.get_browse_to_data(new_object) emit('esdl_browse_to', browse_data, namespace='/esdl')
def get_ibis_contours(info): with self.flask_app.app_context(): logger.info("getting ibis request") esh = get_handler() active_es_id = get_session('active_es_id') add_boundary_to_ESDL = info["add_boundary_to_ESDL"] rin_list = info["rin_list"] es_edit = esh.get_energy_system(es_id=active_es_id) instance = es_edit.instance area = instance[0].area try: url = 'http://' + settings.ibis_config["host"] + ':' + settings.ibis_config["port"] + \ settings.ibis_config["path_contour"] + rin_list logger.info(url) r = requests.get(url) if len(r.text) > 0: area_list = json.loads(r.text) except Exception as e: logger.info( 'ERROR in accessing IBIS boundary service for {}'. format(rin_list)) return None if add_boundary_to_ESDL: self.add_geometries_to_esdl(esh, active_es_id, area_list) self.emit_geometries_to_client(esh, active_es_id, area_list)
def socketio_esdldrive_open(message): with self.flask_app.app_context(): path = message['path'] token = get_session('jwt-token') uri = ESDLDriveHttpURI( url + resource_endpoint + path, headers_function=add_authorization_header) logger.debug('ESDLDrive open: {} ({})'.format( message, uri.plain)) esh = get_handler() try: es = esh.load_file(uri) except Exception as e: logger.error("Error in loading file from ESDLDrive: " + str(e)) #send_alert('Error loading ESDL file with id {} from store'.format(store_id)) return if es.name: title = drive_name + ': ' + es.name else: title = drive_name + ' ES id: ' + es.id set_session('active_es_id', es.id) set_session('es_filename', title) # TODO: separate filename and title es_info_list = {} set_session("es_info_list", es_info_list) emit('clear_ui') emit('clear_esdl_layer_list') self.executor.submit(process_energy_system, esh, None, title) # run in seperate thread
def calculate_ldc(asset_id): with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') asset = esh.get_by_id(active_es_id, asset_id) self.calculate_load_duration_curve(asset_id, asset.name)
def get_colors(self): active_es_id = get_session('active_es_id') esh = get_handler() colors = dict() num_default_colors = 0 es = esh.get_energy_system(active_es_id) esi = es.energySystemInformation if esi: carriers = esi.carriers if carriers: for c in carriers.carrier: if active_es_id + c.id in self.mapeditor_colors: colors[active_es_id + c.id] = self.mapeditor_colors[active_es_id + c.id] else: colors[active_es_id + c.id] = { "es_id": active_es_id, "carrier_id": c.id, "color": default_colors[num_default_colors] } num_default_colors += 1 return colors
def get_carrier(carr_id): active_es_id = get_session('active_es_id') esh = get_handler() response = CarrierMessage() carr = esh.get_by_id(active_es_id, carr_id) if carr: response.id = carr_id response.name = carr.name response.type = carr.eClass.name if isinstance(carr, esdl.EnergyCarrier): response.emission = carr.emission response.energy_content = carr.energyContent response.energy_content_unit = unit_to_string( carr.energyContentUnit) response.state_of_matter = carr.stateOfMatter.__str__() response.renewable_type = carr.energyCarrierType.__str__() if isinstance(carr, esdl.ElectricityCommodity): response.voltage = carr.voltage if isinstance(carr, esdl.GasCommodity): response.pressure = carr.pressure if isinstance(carr, esdl.HeatCommodity): response.supply_temperature = carr.supplyTemperature response.return_temperature = carr.returnTemperature return response
def spatop_connect_unconnected_assets(params): with self.flask_app.app_context(): print(params) connect_asset_type = params["connect_asset_type"] connect_to_asset_type = params["connect_to_asset_type"] esh = get_handler() active_es_id = get_session('active_es_id') es = esh.get_energy_system(active_es_id) # Collect all assets of the required types connect_asset_list = list() connect_to_asset_list = list() for c in es.eAllContents(): if type(c).__name__ == connect_asset_type: connect_asset_list.append(c) if type(c).__name__ == connect_to_asset_type: connect_to_asset_list.append(c) connections_list = list() # Iterate over connect_asset_list for c in connect_asset_list: # TODO: fix assume one port port_c = c.port[0] if not port_c.connectedTo: shape_c = Shape.create(c.geometry) min_distance = 1e99 closest_ct = None # Find closest asset to connect to for ct in connect_to_asset_list: shape_ct = Shape.create(ct.geometry) if shape_ct.shape.distance(shape_c.shape) < min_distance: min_distance = shape_ct.shape.distance(shape_c.shape) closest_ct = ct # Determine the type of port to connect to if type(port_c) == esdl.InPort: find_port_type = esdl.OutPort else: find_port_type = esdl.InPort # Find first port that matches criteria for p in closest_ct.port: if isinstance(p, find_port_type): p.connectedTo.append(port_c) pct_coord = get_asset_and_coord_from_port_id(esh, active_es_id, p.id)['coord'] pc_coord = get_asset_and_coord_from_port_id(esh, active_es_id, port_c.id)['coord'] connections_list.append \ ({'from-port-id': port_c.id, 'from-asset-id': c.id, 'from-asset-coord': pc_coord, 'to-port-id': p.id, 'to-asset-id': closest_ct.id, 'to-asset-coord': pct_coord}) break emit('add_connections', {'es_id': active_es_id, 'conn_list': connections_list})
def spatop_collect_info(): with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') es = esh.get_energy_system(active_es_id) area = es.instance[0].area self.collect_info(area, True)
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 get_environmental_profiles(self): active_es_id = get_session('active_es_id') esh = get_handler() result = list() es = esh.get_energy_system(active_es_id) esi = es.energySystemInformation for x in esdl.EnvironmentalProfiles.eClass.eAllStructuralFeatures(): if isinstance(x, EReference): ep_instance = dict() ep_instance['key'] = str(uuid4()) ep_instance['name'] = x.name ep_instance['uiname'] = camelCaseToWords(x.name) ep_instance['type'] = 'Unset' ep_instance[ 'default_unit'] = self.get_default_qau_for_env_profile( x.name) if esi and esi.environmentalProfiles: env_profiles = esi.environmentalProfiles profile = env_profiles.eGet(x) if profile: if isinstance(profile, esdl.SingleValue): ep_instance['type'] = 'SingleValue' ep_instance['value'] = profile.value elif isinstance(profile, esdl.InfluxDBProfile): ep_instance['type'] = 'InfluxDBProfile' # check if it is a 'standard profile' that is present in our configuration profiles = Profiles.get_instance().get_profiles( )['profiles'] for pkey in profiles: std_profile = profiles[pkey] if profile.database == std_profile['database'] and \ profile.measurement == std_profile['measurement'] and \ profile.field == std_profile['field']: ep_instance['profile_id'] = pkey else: logger.warn( 'Environmental profiles other than SingleValue/InfluxDB are not supported' ) ep_instance['value'] = '' if profile.profileQuantityAndUnit: qau = profile.profileQuantityAndUnit if isinstance(qau, esdl.QuantityAndUnitReference): qau = qau.reference ep_instance['unit'] = unit_to_string(qau) else: ep_instance['unit'] = '' else: ep_instance['value'] = '' result.append(ep_instance) return result
def set_simulation_id(sim_id): with self.flask_app.app_context(): esh = get_handler() print('Set ESSIM simulationRun ID: ' + sim_id) set_session('simulationRun', sim_id) ESSIM_config = settings.essim_config url = ESSIM_config['ESSIM_host'] + ESSIM_config[ 'ESSIM_path'] + '/' + sim_id try: r = requests.get(url) if r.status_code == 200: result = json.loads(r.text) active_simulation = { 'sim_id': sim_id, 'scenarioID': result['scenarioID'], 'simulationDescription': result['simulationDescription'], 'startDate': result['startDate'], 'endDate': result['endDate'], 'dashboardURL': result['dashboardURL'] } set_session('active_simulation', active_simulation) esdlstr_base64 = result['esdlContents'] esdlstr_base64_bytes = esdlstr_base64.encode('ascii') esdlstr_bytes = base64.decodebytes( esdlstr_base64_bytes) esdlstr = esdlstr_bytes.decode('ascii') res_es = esh.add_from_string(name=str(uuid.uuid4()), esdl_string=esdlstr) set_session('active_es_id', res_es.id) sdt = datetime.strptime(result['startDate'], '%Y-%m-%dT%H:%M:%S%z') edt = datetime.strptime(result['endDate'], '%Y-%m-%dT%H:%M:%S%z') influxdb_startdate = sdt.strftime('%Y-%m-%dT%H:%M:%SZ') influxdb_enddate = edt.strftime('%Y-%m-%dT%H:%M:%SZ') # Call init_simulation to enable the loadflow calculations self.essim_kpis.init_simulation( res_es, sim_id, influxdb_startdate, influxdb_enddate) self.executor.submit(process_energy_system, esh, 'test') # run in seperate thread except Exception as e: # print('Exception: ') # print(e) send_alert('Error accessing ESSIM API: ' + str(e))
def reverse_conductor(message): # reverses the points in the line, so the in and outport are swapped esh = get_handler() active_es_id = get_session('active_es_id') print('Reverse conductor: %s' % message) asset_id = message['asset_id'] conductor = esh.get_by_id(es_id=active_es_id, object_id=asset_id) self.reverse_conductor(active_es_id, conductor) resource = esh.get_resource(active_es_id)
def remove_profile_from_port(port, profile_id): esh = get_handler() active_es_id = get_session('active_es_id') profile_list = port.profile for profile in set(profile_list): if profile.id == profile_id: profile_list.remove(profile) esh.remove_object_from_dict(active_es_id, profile, True)
def get_services(self): active_es_id = get_session('active_es_id') esh = get_handler() es = esh.get_energy_system(active_es_id) services = es.services if not services: services = esdl.Services(id=str(uuid4())) es.services = services return services
def remove_control_strategy(asset): active_es_id = get_session('active_es_id') esh = get_handler() cs = asset.controlStrategy if cs: services = cs.eContainer() services.service.remove(cs) esh.remove_object_from_dict(active_es_id, cs, True) asset.controlStrategy = None
def socketio_esdldrive_save(message): with self.flask_app.app_context(): path = message['path'] overwrite = False commitMessage = "" params = {} if 'commitMessage' in message: commitMessage = message['commitMessage'] params['commitMessage'] = commitMessage if 'forceOverwrite' in message: overwrite = message['forceOverwrite'] params['overwrite'] = overwrite print(message) uri = url + resource_endpoint + path esh = get_handler() active_es_id = get_session('active_es_id') esh.update_version(es_id=active_es_id) resource: Resource = esh.get_resource(active_es_id) logger.debug( 'ESDLDrive saving resource {}, commitMessage={}, overwrite={}' .format(resource.uri, commitMessage, overwrite)) if resource.uri.normalize() == uri: # resource already in CDO logger.debug( 'Saving resource that is already loaded from ESDLDrive: {}' .format(resource.uri.plain)) # update uri with commit message resource.uri = ESDLDriveHttpURI( uri, headers_function=add_authorization_header, putparams=params) response = resource.save() else: logger.debug( 'Saving to a new resource in ESDLDrive: {}'.format( resource.uri.plain)) resource.uri = ESDLDriveHttpURI( uri, headers_function=add_authorization_header, putparams=params) response: requests.Response = resource.save() esh.esid_uri_dict[ resource.contents[0].id] = resource.uri.normalize() # new resource if response.ok: return {'path': path, 'success': True} else: return { 'path': path, 'success': False, 'error': str(response.content), 'status': response.status_code }
def set_cost_information(obj, cost_information_data): esh = get_handler() active_es_id = get_session('active_es_id') obj_ci = obj.costInformation if not obj_ci: obj_ci = esdl.CostInformation(id=str(uuid4())) obj.costInformation = obj_ci esh.add_object_to_dict(active_es_id, obj.costInformation) for ci_component in cost_information_data: ci_component_name = ci_component['name'] attribute = obj_ci.eClass.findEStructuralFeature(ci_component_name) if attribute is not None: if ci_component['changed']: current_cost_component_profile = obj_ci.eGet(ci_component_name) if current_cost_component_profile: if ci_component['value'] is None: current_cost_component_profile.delete() elif isinstance(current_cost_component_profile, esdl.SingleValue): new_value_str = ci_component['value'] if new_value_str != '': current_cost_component_profile.value = str2float( new_value_str) qau = current_cost_component_profile.profileQuantityAndUnit if qau: if isinstance(qau, esdl.QuantityAndUnitReference): qau = qau.reference current_unit = unit_to_string(qau) if current_unit != ci_component['unit']: _change_cost_unit(qau, ci_component['unit']) else: if ci_component[ 'unit'] is not None and ci_component[ 'unit'] != '': qau = _create_cost_qau(ci_component['unit']) else: if ci_component['value'] is not None and ci_component[ 'value'] != '': new_cost_component_profile = esdl.SingleValue( id=str(uuid4())) new_cost_component_profile.value = str2float( ci_component['value']) if ci_component['unit'] is not None and ci_component[ 'unit'] != '': new_cost_component_profile.profileQuantityAndUnit = _create_cost_qau( ci_component['unit']) obj_ci.eSet(ci_component_name, new_cost_component_profile) esh.add_object_to_dict(active_es_id, new_cost_component_profile)
def socketio_esdldrive_open(message): with self.flask_app.app_context(): path = message['path'] params = dict() import_es = False if 'revision' in message: params['revision'] = message['revision'] if 'nocache' in message: params['nocache'] = message['nocache'] if 'import' in message: import_es = message['import'] logger.debug("Open params: {}".format(params)) #token = get_session('jwt-token') uri = ESDLDriveHttpURI( url + resource_endpoint + path, headers_function=add_authorization_header, getparams=params) logger.debug('ESDLDrive open: {} ({})'.format( message, uri.plain)) esh = get_handler() try: if import_es: es, parse_info = esh.import_file(uri) else: es, parse_info = esh.load_file(uri) if len(parse_info) > 0: info = '' for line in parse_info: info += line + "\n" message = "Warnings while opening {}:\n\n{}".format( uri.last_segment, info) emit('alert', message, namespace='/esdl') print(esh.rset.resources) except Exception as e: logger.error("Error in loading file from ESDLDrive: " + str(e)) return if hasattr(es, 'name') and es.name: title = drive_name + ': ' + es.name else: title = drive_name + ' ES id: ' + es.id set_session('active_es_id', es.id) set_session( 'es_filename', uri.last_segment) # TODO: separate filename and title es_info_list = {} set_session("es_info_list", es_info_list) emit('clear_ui') emit('clear_esdl_layer_list') self.executor.submit(process_energy_system, esh, uri.last_segment, title) # run in seperate thread
def request_ielgas_ldc(info): asset_id = info['id'] # set_session('ielgas_monitor_id', asset_id) active_es_id = get_session('active_es_id') esh = get_handler() asset = esh.get_by_id(active_es_id, asset_id) asset_name = asset.name power = None if hasattr(asset, 'power'): power = asset.power elif hasattr(asset, 'capacity'): power = asset.capacity power_pos = None power_neg = None self.database_client = InfluxDBClient(host=self.plugin_settings['database_host'], port=self.plugin_settings['database_port'], database=self.plugin_settings['database_name']) user = get_session('user-email') user_config = self.get_user_settings(user) results = dict() measurements = user_config['measurements'] for m in measurements: try: query = 'SELECT "'+FIELD_NAME+'" FROM "' + m + '" WHERE assetId=\'' + asset_id + '\'' logger.debug(query) res = self.database_client.query(query) if res: results = res break except Exception as e: logger.error('error with query: ', str(e)) first_key = list(results.keys())[0] series = results[first_key] ldc_series = [] for item in series: ldc_series.append(item['allocationEnergy']) ldc_series.sort(reverse=True) ldc_series_decimate = [] for idx, item in enumerate(ldc_series): if idx % 40 == 0: ldc_series_decimate.append(item * 1e6) if item > 0: power_pos = power if item < 0: power_neg = -power emit('ldc-data', {'asset_name': asset_name, 'ldc_series': ldc_series_decimate, 'power_pos': power_pos, 'power_neg': power_neg})
def essim_sensitivity_asset_info(id): with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') asset = esh.get_by_id(active_es_id, id) asset_info = dict() asset_info['attrs_sorted'] = ESDLEcore.get_asset_attributes(asset) asset_info['port_profile_list'] = get_port_profile_info(asset) return asset_info
def use_part_of_potential(pot_id, percentage, all_potentials): """ Use part of a SolarPotential to install a PVInstallation :param pot_id: id of the SolarPotential :param percentage: percentage (0-100) of the SolarPotential that should be installed as a PVInstallation :param all_potentials: boolean specifying if this action should be applied to all SolarPotentials in the energy system :return: None """ with self.flask_app.app_context(): esh = get_handler() active_es_id = get_session('active_es_id') asset_list = [] add_to_building = False pot = esh.get_by_id(active_es_id, pot_id) if pot.solarPotentialType != esdl.PVInstallationTypeEnum.ROOFTOP_PV: send_alert('SolarPotential is not of type ROOFTOP_PV') else: self.convert_potential(esh, active_es_id, pot, add_to_building, percentage, asset_list) emit('add_esdl_objects', {'es_id': active_es_id, 'add_to_building': add_to_building, 'asset_pot_list': asset_list, 'zoom': False}) if all_potentials: es = esh.get_energy_system(active_es_id) area = es.instance[0].area for obj in area.eAllContents(): if isinstance(obj, esdl.SolarPotential): if obj.solarPotentialType == esdl.PVInstallationTypeEnum.ROOFTOP_PV and obj.id != pot_id: # not the selected one asset_list = [] add_to_building = False pvi = self.convert_potential(esh, active_es_id, obj, add_to_building, percentage, asset_list) if add_to_building: # if the PVInstalliation is in the same building as the selected potential if pot.eContainer() == pvi.eContainer(): emit('add_esdl_objects', {'es_id': active_es_id, 'add_to_building': True, 'asset_pot_list': asset_list, 'zoom': False}) # for potentials/assets that are in another building, we don't need to do anything here else: # for all potentials outside a building emit('add_esdl_objects', {'es_id': active_es_id, 'add_to_building': False, 'asset_pot_list': asset_list, 'zoom': False})