def update(self, name, password): """Method used to update a User. Returns True for a successful creation, False otherwise""" # creating the triples to remove and to update atriples = [] rtriples = [] rtriples.append( Triple(URI(self.user_uri), URI(NS + "hasName"), Literal(self.user_name))) rtriples.append( Triple(URI(self.user_uri), URI(NS + "hasPassword"), Literal(self.user_password))) atriples.append( Triple(URI(self.user_uri), URI(NS + "hasName"), Literal(name))) atriples.append( Triple(URI(self.user_uri), URI(NS + "hasPassword"), Literal(password))) # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_update(atriples, rtriples) self.user_name = name return True, self except: return False, None
def __init__(self, kp=None): print("Инициализация клиента") self.kp = kp if kp else m3_kp_api() self.agent_name = None self.start = False self.current_number = None
def reservation_exists(settings, user_uid, vehicle_id, gs_id, res_type): """This method is used to check if a reservation with the given details exists. If affirmative returns True, False otherwise.""" # connect to the sib kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) # check reservation type if res_type == "OTM": # perform the query kp.load_query_sparql(reservation_exists_query % (vehicle_id, user_uid, gs_id)) print reservation_exists_query % (vehicle_id, user_uid, gs_id) result = str(kp.result_sparql_query[0][0]) elif res_type == "TRA": # perform the query kp.load_query_sparql(tra_reservation_exists_query % (user_uid, vehicle_id, gs_id)) print tra_reservation_exists_query % (user_uid, vehicle_id, gs_id) result = str(kp.result_sparql_query[0][0]) # return True or False if result == "true": return True else: return False
def reservations(): """Returns the list of reservations for a given user. JSON output.""" # check if the user_id was provided user_id = None if if request.args.has_key('user_id'): # read the user_id user_id = request.args['user_id'] # get the reservation list kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) kp.load_query_sparql(reservations_query % user_id) results = kp.result_sparql_query # parse the results reservations = [] for result in results: reservation = {} for field in result: reservation[field[0]] = field[2] reservations.append(reservation) else: return make_response(jsonify({'error': 'Bad Request - The user_id must be provided'}), 401) # return return jsonify(results = reservations)
def clean_sib(self, sib_host, sib_port, sib_name, sib_protocol): """This method is used to clean the SIB before loading the KB""" # connect to the sib and clean it! kp = None if sib_protocol == "SSAP": try: self.oh.p( "clean_sib", "Cleaning the SIB %s (%s:%s)..." % (sib_name, sib_host, sib_port)) kp = m3_kp_api(False, sib_host, sib_port) kp.load_rdf_remove(Triple(None, None, None)) except Exception as e: if self.debug: self.oh.p("clean_sib", "Cleaning failed!", True) print traceback.print_exc() return False elif sib_protocol == "JSSAP": try: self.oh.p( "clean_sib", "Cleaning the SIB %s (%s:%s)..." % (sib_name, sib_host, sib_port)) kp = JKP(sib_host, sib_port, "X", False) kp.remove(JTriple(None, None, None)) except Exception as e: if self.debug: self.oh.p("clean_sib", "Cleaning failed!", True) print traceback.print_exc() return False else: return False
def create(self): """Create a reservation""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # generate an uuid res_uuid = str(uuid.uuid4()) res_id = "Reserv_%s" % (res_uuid.split("-")[0]) res_uri = NS + res_uuid # UPDATE SPARQL query query = """PREFIX rdf:<%s> PREFIX ns:<%s> INSERT { <%s> rdf:type ns:Reservation . <%s> ns:hasReservationIdentifier "%s" . <%s> ns:reservedByVehicle ?vehicle_uri . <%s> ns:hasUser ?user_uri . <%s> ns:hasGS ?gs_uri } WHERE { ?user_uri ns:hasUserIdentifier "%s" . ?vehicle_uri ns:hasVehicleIdentifier "%s" . ?gs_uri ns:hasGSIdentifier "%s" }""" try: kp.load_query_sparql(query % (RDF, NS, res_uri, res_uri, res_id, res_uri, res_uri, res_uri, self.user_id, self.vehicle_id, self.gs_id)) ret_model = self.find_reservation(res_id) return True, ret_model except: return False, None
def delete(self, vehicle_id): # sparql query query = """PREFIX rdf:<%s> PREFIX ns:<%s> DELETE { ?vehicle_uri rdf:type ns:Vehicle . ?vehicle_uri ns:hasVehicleIdentifier "%s" . ?vehicle_uri ns:hasManufacturer ?manufacturer . ?vehicle_uri ns:hasModel ?model . ?vehicle_uri ns:hasPlate ?plate . ?user_uri ns:hasVehicle ?vehicle_uri . ?reservation_uri rdf:type ns:Reservation . ?reservation_uri ns:reservedByVehicle ?vehicle_uri . ?reservation_uri ns:hasUser ?user_uri . ?reservation_uri ns:hasGS ?gs_uri . ?reservation_uri ns:hasReservationIdentifier ?reservation_id } WHERE { ?vehicle_uri ns:hasVehicleIdentifier "%s" . }""" # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(query % (RDF, NS, vehicle_id, vehicle_id)) return True except Exception as e: return False
def find_by_user_id(self, user_id): """This method is used to retrieve all the vehicles of a user, given its user_id""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # query query = """PREFIX rdf:<%s> PREFIX ns:<%s> SELECT ?vehicle_uri ?brand ?model ?vehicle_id ?plate WHERE { ?vehicle_uri rdf:type <%s> . ?vehicle_uri ns:hasManufacturer ?brand . ?vehicle_uri ns:hasModel ?model . ?vehicle_uri ns:hasVehicleIdentifier ?vehicle_id . ?user_uri ns:hasUserIdentifier "%s" . ?user_uri ns:hasVehicle ?vehicle_uri . ?vehicle_uri ns:hasPlate ?plate }""" print query % (RDF, NS, VEHICLE_CLASS, user_id) kp.load_query_sparql(query % (RDF, NS, VEHICLE_CLASS, user_id)) results = kp.result_sparql_query # return return results
def clean_sib(self, sib_host, sib_port, sib_name, sib_protocol): """This method is used to clean the SIB before loading the KB""" # connect to the sib and clean it! kp = None if sib_protocol == "SSAP": try: self.oh.p("clean_sib", "Cleaning the SIB %s (%s:%s)..." % (sib_name, sib_host, sib_port)) kp = m3_kp_api(False, sib_host, sib_port) kp.load_rdf_remove(Triple(None, None, None)) except Exception as e: if self.debug: self.oh.p("clean_sib", "Cleaning failed!", True) print traceback.print_exc() return False elif sib_protocol == "JSSAP": try: self.oh.p("clean_sib", "Cleaning the SIB %s (%s:%s)..." % (sib_name, sib_host, sib_port)) kp = JKP(sib_host, sib_port, "X", False) kp.remove(JTriple(None, None, None)) except Exception as e: if self.debug: self.oh.p("clean_sib", "Cleaning failed!", True) print traceback.print_exc() return False else: return False
def __init__(self): super(Tachometer, self).__init__() self.km = 0 self.m3 = m3_kp_api() global carEngineOn carEngineOn = True
def reservations(): """Returns the list of reservations for a given user. JSON output.""" # check if the user_id was provided user_id = None if if request.args.has_key('user_id'): # read the user_id user_id = request.args['user_id'] # get the reservation list kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) kp.load_query_sparql(reservations_query % user_id) results = kp.result_sparql_query # parse the results reservations = [] for result in results: reservation = {} for field in result: reservation[field[0]] = field[2] reservations.append(reservation) else: return make_response( jsonify({'error': 'Bad Request - The user_id must be provided'}), 401) # return return jsonify(results=reservations)
def delete(self, reservation_id): """Method used to delete a reservation""" # sparql query query = """PREFIX rdf:<%s> PREFIX ns:<%s> DELETE { ?reservation_uri rdf:type ns:Reservation . ?reservation_uri ns:reservedByVehicle ?vehicle_uri . ?reservation_uri ns:hasUser ?user_uri . ?reservation_uri ns:hasGS ?gs_uri . ?reservation_uri ns:hasReservationIdentifier "%s" } WHERE { ?reservation_uri ns:hasReservationIdentifier "%s" . }""" # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(query % (RDF, NS, reservation_id, reservation_id)) return True except Exception as e: return False
def create(self): """Method used to create a NEW user. Returns True for a successful creation, False otherwise""" # generating an UUID for the user uid = str(uuid.uuid4()) self.user_uri = NS + uid # creating the triples triples = [] triples.append( Triple(URI(self.user_uri), URI(RDF_TYPE), URI(PERSON_CLASS))) triples.append( Triple(URI(self.user_uri), URI(NS + "hasUserIdentifier"), Literal(self.user_uid))) triples.append( Triple(URI(self.user_uri), URI(NS + "hasName"), Literal(self.user_name))) triples.append( Triple(URI(self.user_uri), URI(NS + "hasPassword"), Literal(self.user_password))) # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_insert(triples) return True, self except: return False, None
def check_user_authorization(self, evse_id, user_id, tolerance): """This method is used to check if the user can recharge""" # initialize results res = {} authorized = False # determine current time now = int(round(time.time() * 1000)) # check if the user reserved the EVSE for this time kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(user_auth_query % (evse_id, user_id)) query_results = kp.result_sparql_query for res in query_results: if int(res[2][2]) <= now <= int(res[3][2]): return True # check if the user that reserved the EVSE is himself status = self.check_evse_status(evse_id) if status["nextUser"] == user_id and status["nextReservationIn"] <= tolerance: return True # ...else... return False
def get_gcp_details(self, evse_name): # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # perform the query kp.load_query_sparql(gcp_details_query % evse_name) query_results = kp.result_sparql_query # build a dict results = [] for res in query_results: results.append({ "gcp_connector": res[0][2], "gcp_evsename": res[1][2], "gcp_pow": res[2][2], "gcp_volt": res[3][2], "gcp_price": res[4][2], "gcp_cout": res[5][2], "gcp_cin": res[6][2], "gcp_stat": res[7][2], }) # return results return results
def charge_option_confirm(self, charge_option): """This method is used to confirm a charge option""" # insert the triple kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_insert([ Triple(URI(NS + charge_option), URI(NS + "confirmByUser"), LLiteral("true")) ]) # look for system confirm (subscription replaced by iterative query) results = None while not results: kp.load_query_rdf( Triple(URI(NS + charge_option), URI(NS + "confirmBySystem"), None)) results = kp.result_rdf_query sysconfirm = results[0][2] # return if str(sysconfirm).lower() == "true": kp.load_rdf_insert([ Triple(URI(NS + charge_option), URI(NS + "ackByUser"), LLiteral("true")) ]) return True else: return False
def check_user_authorization(self, evse_id, user_id, tolerance): """This method is used to check if the user can recharge""" # initialize results res = {} authorized = False # determine current time now = int(round(time.time() * 1000)) # check if the user reserved the EVSE for this time kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(user_auth_query % (evse_id, user_id)) query_results = kp.result_sparql_query for res in query_results: if int(res[2][2]) <= now <= int(res[3][2]): return True # check if the user that reserved the EVSE is himself status = self.check_evse_status(evse_id) if status["nextUser"] == user_id and status[ "nextReservationIn"] <= tolerance: return True # ...else... return False
def basic_sparql_test(self): # initialize the results self.results = {} for sib in self.sibs: self.results[sib["name"]] = [] # connect to the SIBs for sib in self.sibs: # SSAP or JSSAP? if sib["protocol"] == "SSAP": # connect and add the KP to the dictionary kp = m3_kp_api(False, sib["host"], sib["port"]) sib["kp"] = kp elif sib["protocol"] == "JSSAP": # connect and add the KP to the dictionary kp = JKP(sib["host"], sib["port"], "X", False) sib["kp"] = kp # iterate over the SIBs for sib in self.sibs: # iterate over the number of iterations for iteration in range(self.iterations): # debug if self.debug: self.oh.p("sparql_test", "--- Iteration: %s" % iteration) # retrieve data if sib["protocol"] == "SSAP": # try to query and measure time try: self.results[sib["name"]].append(round(timeit.timeit(lambda: sib["kp"].load_query_sparql(self.query_text), number=1), 3)) except Exception as e: if self.debug: self.oh.p("sparql_test", "Query failed with exception %s" % e, False) raise QueryTestException(str(e)) elif sib["protocol"] == "JSSAP": # try to query and measure time try: # query self.results[sib["name"]].append(round(timeit.timeit(lambda: sib["kp"].query_sparql(self.query_text), number=1), 3)) except Exception as e: if self.debug: self.oh.p("sparql_test", "Query failed with exception %s" % e, False) raise QueryTestException(str(e)) # sleep time.sleep(self.sleep)
def get_charge_options(self, lat, lng, rad, timeto, timefrom, user_uri, vehicle_uri, bidirectional, req_energy): """Method used to retrieve the possible charge options""" # generate UUIDs request_uri = NS + str(uuid4()) time_interval_uri = NS + str(uuid4()) energy_uri = NS + str(uuid4()) spatial_range_uri = NS + str(uuid4()) # insert triple_list = [] triple_list.append(Triple(URI(request_uri), URI(RDF_TYPE), URI(NS + "ChargeRequest"))) triple_list.append(Triple(URI(request_uri), URI(NS + "hasRequestingVehicle"), URI(NS + vehicle_uri))) triple_list.append(Triple(URI(request_uri), URI(NS + "hasRequestingUser"), URI(NS + user_uri))) triple_list.append(Triple(URI(request_uri), URI(NS + "allowBidirectional"), LLiteral("true"))) triple_list.append(Triple(URI(time_interval_uri), URI(RDF_TYPE), URI(NS + "TimeInterval"))) triple_list.append(Triple(URI(request_uri), URI(NS + "hasTimeInterval"), URI(time_interval_uri))) triple_list.append(Triple(URI(time_interval_uri), URI(NS + "hasFromTimeMillisec"), LLiteral(str(timefrom)))) triple_list.append(Triple(URI(time_interval_uri), URI(NS + "hasToTimeMillisec"), LLiteral(timeto))) triple_list.append(Triple(URI(energy_uri), URI(RDF_TYPE), URI(NS + "EnergyData"))) triple_list.append(Triple(URI(request_uri), URI(NS + "hasRequestedEnergy"), URI(energy_uri))) triple_list.append(Triple(URI(energy_uri), URI(NS + "hasUnitOfMeasure"), URI(NS + "kiloWattHour"))) triple_list.append(Triple(URI(energy_uri), URI(NS + "hasValue"), LLiteral(req_energy))) triple_list.append(Triple(URI(spatial_range_uri), URI(RDF_TYPE), URI(NS + "SpatialRangeData"))) triple_list.append(Triple(URI(request_uri), URI(NS + "hasSpatialRange"), URI(spatial_range_uri))) triple_list.append(Triple(URI(spatial_range_uri), URI(NS + "hasGPSLatitude"), LLiteral(lat))) triple_list.append(Triple(URI(spatial_range_uri), URI(NS + "hasGPSLongitude"), LLiteral(lng))) triple_list.append(Triple(URI(spatial_range_uri), URI(NS + "hasRadius"), LLiteral(rad))) kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_insert(triple_list) # query (instead of subscription) results = False while not results: # perform the query kp.load_query_rdf(Triple(None, URI(NS + "hasRelatedRequest"), URI(request_uri))) query_results = kp.result_rdf_query if len(query_results) > 0: results = query_results # query: res_uri = results[0][0] kp.load_query_sparql(chargeresponse_query % (res_uri, res_uri)) charge_requests = [] results2 = kp.result_sparql_query # parse the results charge_requests = [] for result in results2: charge_request = {} for field in result: charge_request[field[0]] = field[2] charge_requests.append(charge_request) # return return charge_requests
def evses(): """Returns the list of evses. Default data format for the results is JSON. Note: the gcp_name must be provided. """ # check if the user_id was provided user_id = None if if request.args.has_key('gcp_name'): # read the user_id gcp_name = request.args['gcp_name'] # get the evse list kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) kp.load_query_sparql(evses_query % gcp_name) results = kp.result_sparql_query # parse the results evses = [] for result in results: evse = {} for field in result: evse[field[0]] = field[2] evses.append(evse) else: # get the evse list kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) kp.load_query_sparql(evses_query_all) results = kp.result_sparql_query # parse the results evses = [] for result in results: evse = {} for field in result: evse[field[0]] = field[2] evses.append(evse) # return return jsonify(results = evses)
def evses(): """Returns the list of evses. Default data format for the results is JSON. Note: the gcp_name must be provided. """ # check if the user_id was provided user_id = None if if request.args.has_key('gcp_name'): # read the user_id gcp_name = request.args['gcp_name'] # get the evse list kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) kp.load_query_sparql(evses_query % gcp_name) results = kp.result_sparql_query # parse the results evses = [] for result in results: evse = {} for field in result: evse[field[0]] = field[2] evses.append(evse) else: # get the evse list kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) kp.load_query_sparql(evses_query_all) results = kp.result_sparql_query # parse the results evses = [] for result in results: evse = {} for field in result: evse[field[0]] = field[2] evses.append(evse) # return return jsonify(results=evses)
def update(self, name, slat, slong, elat, elong): """Update a ground station""" # query sparql query = """PREFIX rdf:<%s> PREFIX ns:<%s> INSERT { ?gs_uri ns:hasName "%s" . ?sgpsdata ns:hasLatitude "%s" . ?sgpsdata ns:hasLongitude "%s" . ?egpsdata ns:hasLatitude "%s" . ?egpsdata ns:hasLongitude "%s" . } DELETE { ?gs_uri ns:hasName ?old_name . ?sgpsdata ns:hasLatitude ?old_slat . ?sgpsdata ns:hasLongitude ?old_slong . ?egpsdata ns:hasLatitude ?old_elat . ?egpsdata ns:hasLongitude ?old_elong . } WHERE { ?gs_uri rdf:type ns:GroundStation . ?gs_uri ns:hasGSIdentifier "%s" . ?gs_uri ns:hasName ?old_name . ?gs_uri ns:hasStartGPSData ?sgpsdata . ?gs_uri ns:hasEndGPSData ?egpsdata . ?sgpsdata ns:hasLatitude ?old_slat . ?sgpsdata ns:hasLongitude ?old_slong . ?egpsdata ns:hasLatitude ?old_elat . ?egpsdata ns:hasLongitude ?old_elong . }""" # remove the triples try: # connect to the SIB and remove the triples kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) print query % (RDF, NS, name, slat, slong, elat, elong, self.gs_id) kp.load_query_sparql(query % (RDF, NS, name, slat, slong, elat, elong, self.gs_id)) # update self data self.gs_name = name self.slatitude = slat self.slongitude = slong self.elatitude = elat self.elongitude = elong # return return True except Exception as e: print e return False
def __init__(self): # Init DB access database = 'history' global DB DB = DatabaseWriter.DatabaseWriter('localhost', 'root', 'luca123', database, False) # Init Smart M3 API global M3 M3 = m3_kp_api(False, 'localhost')#'192.168.1.104') # Decanter global Decanter Decanter = HistoryDecanter(DB) Decanter.start() # Subscribe to history requests self.historyRequestSubscription = M3.load_subscribe_RDF([ Triple( URI(HISTORY), URI(HAS_HISTORY_INPUT), None) ], HistoryRequestHandler() ) logger.info('Existing requests:') logger.info(M3.result_RDF_first_sub) # Simulate a notification for the request already present in the SIB if len(M3.result_RDF_first_sub): HistoryRequestHandler().handle(M3.result_RDF_first_sub, []) else: logger.info('No History requests') # Subscribe to read request self.historyReadSubscription = M3.load_subscribe_RDF([ Triple( URI(HISTORY), URI(HAS_HISTORY_READ), None ) ], HistoryReadRequestHandler()) if len(M3.result_RDF_first_sub): HistoryReadRequestHandler().handle(M3.result_RDF_first_sub, []) else: logger.info('No read requests')
def delete(self, user_id): """Method used to delete a user""" # sparql query query = """PREFIX rdf:<%s> PREFIX ns:<%s> DELETE { ?user_uri rdf:type ns:Person . ?user_uri ns:hasVehicle ?vehicle_uri . ?user_uri ns:hasName ?name . ?user_uri ns:hasPassword ?user_password . ?user_uri ns:hasUserIdentifier "%s" . ?vehicle_uri rdf:type ns:Vehicle . ?vehicle_uri ns:hasVehicleIdentifier ?vehicle_id . ?vehicle_uri ns:hasManufacturer ?manufacturer . ?vehicle_uri ns:hasModel ?model . ?reservation_uri rdf:type ns:Reservation . ?reservation_uri ns:reservedByVehicle ?vehicle_uri . ?reservation_uri ns:hasUser ?user_uri . ?reservation_uri ns:hasGS ?gs_uri . ?reservation_uri ns:hasReservationIdentifier ?reservation_id } WHERE { ?user_uri rdf:type ns:Person . ?user_uri ns:hasName ?name . ?user_uri ns:hasPassword ?user_password . ?user_uri ns:hasUserIdentifier "%s" . OPTIONAL { ?user_uri ns:hasVehicle ?vehicle_uri . ?vehicle_uri rdf:type ns:Vehicle . ?vehicle_uri ns:hasVehicleIdentifier ?vehicle_id . ?vehicle_uri ns:hasManufacturer ?manufacturer . ?vehicle_uri ns:hasModel ?model . OPTIONAL { ?reservation_uri rdf:type ns:Reservation . ?reservation_uri ns:reservedByVehicle ?vehicle_uri . ?reservation_uri ns:hasUser ?user_uri . ?reservation_uri ns:hasGS ?gs_uri . ?reservation_uri ns:hasReservationIdentifier ?reservation_id } } }""" # deleting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(query % (RDF, NS, user_id, user_id)) return True except Exception as e: return False
def create(self): """This method is used to create the gs by storing its triples into the SIB""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # generate an uuid self.uuid = str(uuid.uuid4()) self.gs_uri = NS + self.uuid self.gs_id = self.uuid.split("-")[0] # generate URIs for GPSdatas self.sgpsdata_uri = NS + str(uuid.uuid4()) self.egpsdata_uri = NS + str(uuid.uuid4()) # create the triples triples = [] triples.append(Triple(URI(self.gs_uri), URI(RDF_TYPE), URI(GS_CLASS))) triples.append(Triple(URI(self.gs_uri), URI(NS + "hasGSIdentifier"), Literal(self.gs_id))) triples.append(Triple(URI(self.gs_uri), URI(NS + "hasName"), Literal(self.gs_name))) triples.append(Triple(URI(self.gs_uri), URI(NS + "hasStartGPSData"), URI(self.sgpsdata_uri))) triples.append(Triple(URI(self.gs_uri), URI(NS + "hasEndGPSData"), URI(self.egpsdata_uri))) triples.append(Triple(URI(self.sgpsdata_uri), URI(NS + "hasLatitude"), Literal(self.slatitude))) triples.append(Triple(URI(self.sgpsdata_uri), URI(NS + "hasLongitude"), Literal(self.slongitude))) triples.append(Triple(URI(self.egpsdata_uri), URI(NS + "hasLatitude"), Literal(self.elatitude))) triples.append(Triple(URI(self.egpsdata_uri), URI(NS + "hasLongitude"), Literal(self.elongitude))) # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_insert(triples) return True, self except Exception as e: return False, None
def update(self, manufacturer, model, plate, user_id): """Method used to update the model of a vehicle""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # SPARQL query query = """PREFIX rdf:<%s> PREFIX ns:<%s> INSERT { ?vehicle_uri ns:hasModel "%s" . ?vehicle_uri ns:hasManufacturer "%s" . ?vehicle_uri ns:hasPlate "%s" . ?user_uri ns:hasVehicle ?vehicle_uri . ?reservation_uri ns:hasUser ?user_uri } DELETE { ?vehicle_uri ns:hasModel ?old_model . ?vehicle_uri ns:hasManufacturer ?old_manufacturer . ?vehicle_uri ns:hasPlate ?plate ?old_user_uri ns:hasVehicle ?vehicle_uri . ?reservation_uri ns:hasUser ?old_user_uri } WHERE { ?vehicle_uri rdf:type ns:Vehicle . ?vehicle_uri ns:hasModel ?old_model . ?vehicle_uri ns:hasManufacturer ?old_manufacturer . ?vehicle_uri ns:hasPlate ?plate . ?vehicle_uri ns:hasVehicleIdentifier "%s" . ?old_user_uri ns:hasVehicle ?vehicle_uri . ?old_user_uri ns:hasUserIdentifier ?old_user_id . ?user_uri ns:hasUserIdentifier "%s" . OPTIONAL { ?reservation_uri ns:hasUser ?old_user_uri } }""" try: kp.load_query_sparql(query % (RDF, NS, model, manufacturer, plate, self.vehicle_id, user_id)) results = kp.result_sparql_query model = self.find_vehicle(self.vehicle_id) return True, model except: return False, None
def find_reservation(self, reservation_id): """Method used to retrieve a reservation given the id""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # perform a SPARQL query query = """PREFIX rdf:<%s> PREFIX ns:<%s> SELECT ?reservation_uri ?vehicle_uri ?vehicle_id ?vehicle_manufacturer ?vehicle_model ?user_uri ?user_id ?user_name ?gs_uri ?gs_id ?gs_name WHERE { ?reservation_uri rdf:type <%s> . ?reservation_uri ns:hasReservationIdentifier "%s" . ?reservation_uri ns:reservedByVehicle ?vehicle_uri . ?vehicle_uri ns:hasVehicleIdentifier ?vehicle_id . ?vehicle_uri ns:hasManufacturer ?vehicle_manufacturer . ?vehicle_uri ns:hasModel ?vehicle_model . ?reservation_uri ns:hasUser ?user_uri . ?user_uri ns:hasUserIdentifier ?user_id . ?user_uri ns:hasName ?user_name . ?reservation_uri ns:hasGS ?gs_uri . ?gs_uri ns:hasGSIdentifier ?gs_id . ?gs_uri ns:hasName ?gs_name }""" print query % (RDF, NS, RESERVATION_CLASS, reservation_id) kp.load_query_sparql(query % (RDF, NS, RESERVATION_CLASS, reservation_id)) results = kp.result_sparql_query # build a model r = Reservation(self.settings) r.res_id = reservation_id r.res_uri = results[0][0][2] r.vehicle_uri = results[0][1][2] r.vehicle_id = results[0][2][2] r.vehicle_manufacturer = results[0][3][2] r.vehicle_model = results[0][4][2] r.user_uri = results[0][5][2] r.user_id = results[0][6][2] r.user_name = results[0][7][2] r.gs_uri = results[0][8][2] r.gs_id = results[0][9][2] r.gs_name = results[0][10][2] # return return r
def get_gcp_list(self): # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(gcps_list_query) query_results = kp.result_sparql_query # build a dict results = [] for res in query_results: results.append({ "gcp_uri" : res[0][2], "gcp_name" : res[1][2], "gcp_lat" : res[2][2], "gcp_lng" : res[3][2] }) # return results return results
def set_evse_status(self, evse_id, status, reservation): """Method used to set the status of an EVSE""" # calculate current time Tnow = int(round(time.time() * 1000)) try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) if status.lower() == "start": kp.load_query_sparql(set_evse_status_start % (reservation, Tnow)) elif status.lower() == "stop": kp.load_query_sparql(set_evse_status_stop % (reservation, Tnow)) return True except Exception as e: return False
def user_uid_available(settings, user_uid): """This method is used to verify if a user uid is free or already in use. It returns False if the user uid is free, True otherwise""" # connect to the sib kp = m3_kp_api(False, settings["sib_host"], settings["sib_port"]) # perform the query kp.load_query_sparql(user_exists_query % user_uid) result = str(kp.result_sparql_query[0][0]) # return True or False if result == "true": return False else: return True
def delete_reservation(self, res_id): """This method is used to retire a reservation""" # initialize the return value success = True # connect to the SIB try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # get the res_uri res_uri = NS + res_id # generate a reservation retire uri res_ret_uri = NS + str(uuid4()) # get the reservation user kp.load_query_rdf( Triple(URI(res_uri), URI(NS + "reservationHasUser"), None)) query_results = kp.result_rdf_query user_uri = query_results[0][2] # build the triple list triple_list = [] triple_list.append( Triple(URI(res_ret_uri), URI(RDF_TYPE), URI(NS + "ReservationRetire"))) triple_list.append( Triple(URI(res_ret_uri), URI(NS + "retiredByUser"), URI(user_uri))) triple_list.append( Triple(URI(res_ret_uri), URI(NS + "retiredReservation"), URI(res_uri))) # insert the reservation retire request kp.load_rdf_insert(triple_list) except: # no success :'( success = False return success
def get_gcp_list(self): # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(gcps_list_query) query_results = kp.result_sparql_query # build a dict results = [] for res in query_results: results.append({ "gcp_uri": res[0][2], "gcp_name": res[1][2], "gcp_lat": res[2][2], "gcp_lng": res[3][2] }) # return results return results
def charge_option_confirm(self, charge_option): """This method is used to confirm a charge option""" # insert the triple kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_insert([Triple(URI(NS + charge_option), URI(NS + "confirmByUser"), LLiteral("true"))]) # look for system confirm (subscription replaced by iterative query) results = None while not results: kp.load_query_rdf(Triple(URI(NS + charge_option), URI(NS + "confirmBySystem"), None)) results = kp.result_rdf_query sysconfirm = results[0][2] # return if str(sysconfirm).lower() == "true": kp.load_rdf_insert([Triple(URI(NS + charge_option), URI(NS + "ackByUser"), LLiteral("true"))]) return True else: return False
def update(self, name, password): """Method used to update a User. Returns True for a successful creation, False otherwise""" # creating the triples to remove and to update atriples = [] rtriples = [] rtriples.append(Triple(URI(self.user_uri), URI(NS + "hasName"), Literal(self.user_name))) rtriples.append(Triple(URI(self.user_uri), URI(NS + "hasPassword"), Literal(self.user_password))) atriples.append(Triple(URI(self.user_uri), URI(NS + "hasName"), Literal(name))) atriples.append(Triple(URI(self.user_uri), URI(NS + "hasPassword"), Literal(password))) # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_update(atriples, rtriples) self.user_name = name return True, self except: return False, None
def find_gs(self, gsid): """Retrieves a single Ground Station from the SIB""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # perform the SPARQL query query = """PREFIX rdf:<%s> PREFIX ns:<%s> SELECT ?gs ?gsname ?slatitude ?slongitude ?elatitude ?elongitude WHERE { ?gs rdf:type <%s> . ?gs ns:hasGSIdentifier "%s" . ?gs ns:hasName ?gsname . ?gs ns:hasStartGPSData ?sgpsdata . ?gs ns:hasEndGPSData ?egpsdata . ?sgpsdata ns:hasLatitude ?slatitude . ?sgpsdata ns:hasLongitude ?slongitude . ?egpsdata ns:hasLatitude ?elatitude . ?egpsdata ns:hasLongitude ?elongitude . }""" print query % (RDF, NS, GS_CLASS, gsid) kp.load_query_sparql(query % (RDF, NS, GS_CLASS, gsid)) results = kp.result_sparql_query print results # build the models to return gs_model = GroundStation(self.settings) for result in results: gs_model.gs_uri = result[0][2] gs_model.gs_name = result[1][2] gs_model.slatitude = result[2][2] gs_model.slongitude = result[3][2] gs_model.elatitude = result[4][2] gs_model.elongitude = result[5][2] gs_model.gs_id = gsid # return return gs_model
def get_evse_coordinates(self, evse_id): """This method is used to retrieve the coordinates of an EVSE""" # building the query q = evse_coords_query % evse_id print q # connect to the SIB and perform the query try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(q) results = kp.result_sparql_query except Exception as e: print e return None lat = results[0][0][2] lng = results[0][1][2] powe = results[0][2][2] return lat, lng, powe
def get_tres(self, res_id): """This method is used to retrieve a traditional reservation""" # connect to the SIB try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) res = NS + res_id q = tres_query % (res, res, res, res, res, res) print q kp.load_query_sparql(q) results = kp.result_sparql_query json_result = {} for field in results[0]: json_result[field[0]] = field[2] return True, json_result except Exception as e: print e return False, None
def find_vehicle(self, vehicle_id): """Method used to retrieve a vehicle from the SIB""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # query query = """PREFIX rdf:<%s> PREFIX ns:<%s> SELECT ?vehicle_uri ?brand ?model ?person_uri ?person_name ?person_uid ?plate WHERE { ?vehicle_uri rdf:type <%s> . ?vehicle_uri ns:hasManufacturer ?brand . ?vehicle_uri ns:hasModel ?model . ?vehicle_uri ns:hasVehicleIdentifier "%s" . ?vehicle_uri ns:hasPlate ?plate . OPTIONAL { ?person_uri ns:hasVehicle ?vehicle_uri . ?person_uri ns:hasName ?person_name . ?person_uri ns:hasUserIdentifier ?person_uid } }""" print query % (RDF, NS, VEHICLE_CLASS, vehicle_id) kp.load_query_sparql(query % (RDF, NS, VEHICLE_CLASS, vehicle_id)) results = kp.result_sparql_query # build the model to return model_result = Vehicle(self.settings) model_result.vehicle_uri = results[0][0][2] model_result.brand = results[0][1][2] model_result.model = results[0][2][2] model_result.user_uri = results[0][3][2] model_result.user_name = results[0][4][2] model_result.user_uid = results[0][5][2] model_result.plate = results[0][6][2] model_result.vehicle_id = vehicle_id # return return model_result
def check_treservations(self, user_id, evse_id): """This method is used to check if the user can be authorized to perform a recharge""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # perform the query kp.load_query_sparql(check_trad_res_query % (evse_id, user_id)) query_results = kp.result_sparql_query # results initialization status = {"status": "error", "reservation": None} Tnow = int(round(time() * 1000)) minDifference = 0 reservationf = "" # building results for results in query_results: for result in results: if result[0] == "Tstart": tstart = result[2] elif result[0] == "Tend": tend = result[2] elif result[0] == "r": reservation = result[2] elif result[0] == "end": end = result[2] difference = int(tstart) - int(Tnow) if ((int(tend) - int(Tnow) > 0) and (end == None) and ((difference < minDifference) or (minDifference == 0))): minDifference = difference reservationf = reservation status = {"status": "OK", "reservation": reservationf} # return return status
def get_tres_list(self): """This method is used to retrieve a list of all the traditional reservations""" # connect to the SIB try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_query_sparql(tres_list_query) print tres_list_query results = kp.result_sparql_query json_results = [] for result in results: json_result = {} for field in result: json_result[field[0]] = field[2] json_results.append(json_result) return True, json_results except: return False, None
def find_gs_reservations(self, gsid): """Retrieves the list of reservations for the given ground station""" # connect to the SIB kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) # perform the SPARQL query query = """PREFIX rdf:<%s> PREFIX ns:<%s> SELECT ?reservation_uri WHERE { ?reservation_uri rdf:type <%s> . ?reservation_uri ns:hasGS ?gs_uri . ?gs_uri ns:hasGSIdentifier "%s" }""" print query % (RDF, NS, RESERVATION_CLASS, gsid) kp.load_query_sparql(query % (RDF, NS, RESERVATION_CLASS, gsid)) results = kp.result_sparql_query print results # return return results
def create(self): """Method used to create a NEW user. Returns True for a successful creation, False otherwise""" # generating an UUID for the user uid = str(uuid.uuid4()) self.user_uri = NS + uid # creating the triples triples = [] triples.append(Triple(URI(self.user_uri), URI(RDF_TYPE), URI(PERSON_CLASS))) triples.append(Triple(URI(self.user_uri), URI(NS + "hasUserIdentifier"), Literal(self.user_uid))) triples.append(Triple(URI(self.user_uri), URI(NS + "hasName"), Literal(self.user_name))) triples.append(Triple(URI(self.user_uri), URI(NS + "hasPassword"), Literal(self.user_password))) # putting triples try: kp = m3_kp_api(False, self.settings["sib_host"], self.settings["sib_port"]) kp.load_rdf_insert(triples) return True, self except: return False, None