def main(): the_iri_of_the_resource = 'http://www.markus-lanthaler.com/hydra/event-api/' from hydra import Resource, SCHEMA res = Resource.from_iri(the_iri_of_the_resource) print(res) print("\nApi documentation:") for supcls in res.api_documentation.supported_classes: print(" %s" % supcls.identifier) for supop in supcls.supported_operations: print(" %s" % supop.identifier) print("") create_event = res.find_suitable_operation(SCHEMA.AddAction, SCHEMA.Event) resp, body = create_event({ "@context": "http://schema.org/", "@type": "http://schema.org/Event", "name": "Halloween", "description": "This is halloween, this is halloween", "startDate": "2015-10-31T00:00:00Z", "endDate": "2015-10-31T23:59:59Z", }) assert resp.status == 201, "%s %s" % (resp.status, resp.reason) new_event = Resource.from_iri(resp['location']) print(new_event)
def get_drone(id_): """Get the drone from the server given the drone ID.""" RES = Resource(IRI_CS + "/DroneCollection/" + str(id_)) get_drone_ = RES.find_suitable_operation(None, None, CENTRAL_SERVER.Drone) resp, body = get_drone_() assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) body = json.loads(body.decode('utf-8')) body.pop("@context") body.pop("@type") return body
def update_anomaly(id_, anomaly): """Update the anomaly at central controller.""" try: RES = Resource.from_iri(IRI_CS + "/AnomalyCollection/" + str(id_)) update_anomaly_ = RES.find_suitable_operation( operation_type=SCHEMA.UpdateAction, input_type=CENTRAL_SERVER.Anomaly) resp, body = update_anomaly_(anomaly) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) print("Anomaly Updated successfully.") return Resource.from_iri(resp['location']) except Exception as e: print(e) return None
def get_anomaly(id_): """Get the anomaly from central server.""" try: RES = Resource(IRI_CS + "/AnomalyCollection/" + str(id_)) get_anomaly_ = RES.find_suitable_operation(None, None, CENTRAL_SERVER.Anomaly) resp, body = get_anomaly_() assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) anomaly = json.loads(body.decode('utf-8')) anomaly.pop("@context", None) anomaly.pop("@id", None) return anomaly except ConnectionRefusedError: raise ConnectionRefusedError( "Connection Refused! Please check the drone server.")
def create_command(command): """Add a command entity to the central server.""" create_command_ = RES_CS.find_suitable_operation(SCHEMA.AddAction, CENTRAL_SERVER.Command) resp, body = create_command_(command) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_command = Resource.from_iri(resp['location']) print("Command created successfully.") return new_command
def issue_command(RES, Namespace_, command): """Issue Commands to Drones.""" issue_command_ = RES.find_suitable_operation(SCHEMA.AddAction, Namespace_.Command) resp, body = issue_command_(command) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_command = Resource.from_iri(resp['location']) print("Command issued successfully.") return new_command
def add_command(command): """Add command to drone server.""" add_command_ = RES_DRONE.find_suitable_operation(SCHEMA.AddAction, DRONE1.Command) resp, body = add_command_(command) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_command = Resource.from_iri(resp['location']) print("Command posted successfully.") return new_command
def add_location(location): """Update the area of interest on central server.""" add_location_ = RES_CS.find_suitable_operation( operation_type=SCHEMA.AddAction, input_type=CENTRAL_SERVER.Location) resp, body = add_location_(location) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) return Resource.from_iri(resp['location'])
def send_http_api_log(http_api_log): """Post the drone http Api Log to the central server.""" post_http_api_log = RES_CS.find_suitable_operation(SCHEMA.AddAction, CENTRAL_SERVER.HttpApiLog) resp, body = post_http_api_log(http_api_log) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_http_api_log = Resource.from_iri(resp['location']) print("Http Api Log posted successfully.") return new_http_api_log
def send_datastream(datastream): """Post the drone current datastream to the central server.""" post_datastream = RES_CS.find_suitable_operation(SCHEMA.AddAction, CENTRAL_SERVER.Datastream) resp, body = post_datastream(datastream) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_datastream = Resource.from_iri(resp['location']) print("Datastream posted successfully.") return new_datastream
def create_message(message): """Add a message object entity to the central server.""" create_message_ = RES_CS.find_suitable_operation(SCHEMA.AddAction, CENTRAL_SERVER.Message) resp, body = create_message_(message) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_message = Resource.from_iri(resp['location']) print("Message created successfully.") return new_message
def add_datastream(datastream): """Update the drone datastream on drone server.""" try: update_datastream_ = RES_DRONE.find_suitable_operation( operation_type=SCHEMA.AddAction, input_type=DRONE.Datastream) resp, body = update_datastream_(datastream) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) return Resource.from_iri(resp['location']) except Exception as e: print(e) return None
def delete_command(id_): """Delete a command from the collection given command @id attribute.""" try: i = Resource.from_iri(DRONE_URL + "/api/CommandCollection/" + str(id_)) resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction)() if resp.status // 100 != 2: return "error deleting <%s>" % i.identifier else: return "deleted <%s>" % i.identifier except Exception as e: print(e) return None
def delete_command(id_): """Delete a command from the collection given command @id attribute.""" try: i = Resource.from_iri(DRONE_URL + id_) # name = i.value(SCHEMA.name) resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction)() if resp.status // 100 != 2: return "error deleting <%s>" % i.identifier else: return "deleted <%s>" % i.identifier except: return {404: "Resource with Id %s not found!" % (id_,)}
def remove_drone(drone_id): """Remove previous drone object from the central server.""" try: i = Resource.from_iri(CENTRAL_SERVER_URL + "/api/DroneCollection" + str(drone_id)) resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction, None)() if resp.status // 100 != 2: return "error deleting <%s>" % i.identifier else: return "successfully deleted <%s>" % i.identifier except Exception as e: print(e) return {404: "Resource with Id %s not found!" % (drone_id,)}
def update_location(location): """Update the area of interest on central server.""" try: update_location_ = RES_CS.find_suitable_operation( operation_type=SCHEMA.UpdateAction, input_type=CENTRAL_SERVER.Location) resp, body = update_location_(location) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) return Resource.from_iri(resp['location']) except Exception as e: print(e) return None
def remove_drone(drone_id): """Remove previous drone object from the central server.""" try: i = Resource.from_iri(CENTRAL_SERVER_URL + "/api/DroneCollection" + str(drone_id)) resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction, None)() if resp.status // 100 != 2: return "error deleting <%s>" % i.identifier else: return "successfully deleted <%s>" % i.identifier except Exception as e: print(e) return {404: "Resource with Id %s not found!" % (drone_id, )}
def post_drone(id_, drone): """Update a drone object in the collection given command @id attribute.""" try: i = Resource.from_iri(CENTRAL_SERVER_URL + id_) # name = i.value(SCHEMA.name) resp, _ = i.find_suitable_operation(SCHEMA.UpdateAction, CENTRAL_SERVER.Drone)(drone) if resp.status // 100 != 2: return "error updating <%s>" % i.identifier else: return "successfully updated <%s>" % i.identifier except: return {404: "Resource with Id %s not found!" % (id_, )}
def send_controllerlog(controllerlog): """Post the controller log to the central server.""" try: post_controllerlog = RES_CS.find_suitable_operation( SCHEMA.AddAction, CENTRAL_SERVER.ControllerLog) resp, body = post_controllerlog(controllerlog) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_controllerlog = Resource.from_iri(resp['location']) print("Controller Log successfully.") return new_controllerlog except Exception as e: print(e) return None
def add_command(command): """Add command to drone server.""" try: add_command_ = RES_DRONE.find_suitable_operation( SCHEMA.AddAction, DRONE.Command) resp, body = add_command_(command) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_command = Resource.from_iri(resp['location']) print("Command posted successfully.") return new_command except Exception as e: print(e) return None
def send_http_api_log(http_api_log): """Post the drone http Api Log to the central server.""" try: post_http_api_log = RES_CS.find_suitable_operation( SCHEMA.AddAction, CENTRAL_SERVER.HttpApiLog) resp, body = post_http_api_log(http_api_log) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) new_http_api_log = Resource.from_iri(resp['location']) print("Http Api Log posted successfully.") return new_http_api_log except Exception as e: print(e) return None
def delete_anomaly(id_): """Delete an anomaly from the collection given the anomaly id.""" try: i = Resource.from_iri(IRI_CS + "/AnomalyCollection/" + str(id_)) # name = i.value(SCHEMA.name) resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction)() print("RESP, RESP") if resp.status // 100 != 2: return "error deleting <%s>" % i.identifier else: return "deleted <%s>" % i.identifier except Exception as e: print(e) return {404: "Resource with Id %s not found!" % (id_, )}
def get_command(id_): """Get the command using @id.""" try: i = Resource.from_iri(DRONE_URL + "/api/CommandCollection/" + str(id_)) resp, body = i.find_suitable_operation(operation_type=None, input_type=None, output_type=DRONE.Command)() assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) body = json.loads(body.decode('utf-8')) body.pop("@context") body.pop("@type") return body except Exception as e: print(e) return None
def get_anomaly(id_): """Get the anomaly with id=id_ from central server.""" try: RES = Resource.from_iri(IRI_CS + "/AnomalyCollection/" + str(id_)) get_anomaly_ = RES.find_suitable_operation(None, None, CENTRAL_SERVER.Anomaly) resp, body = get_anomaly_() assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) anomaly = json.loads(body.decode('utf-8')) anomaly.pop("@context", None) anomaly.pop("@id", None) return anomaly except exception as e: print(e) return None
def update_drone(drone): """Update the drone object on drone server.""" drone_identifier = drone["DroneID"] try: update_drone_ = RES_DRONE.find_suitable_operation(operation_type=SCHEMA.UpdateAction, input_type=DRONE.Drone) resp, body = update_drone_(drone) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) return Resource.from_iri(resp['location']) except Exception as e: print(e) return None http_api_log = gen_HttpApiLog("Drone %s" % ( str(drone_identifier)), "POST Drone State", "Localhost") send_http_api_log(http_api_log)
def update_drone(drone): """Update the drone object on drone server.""" drone_identifier = drone["DroneID"] try: update_drone_ = RES_DRONE.find_suitable_operation( operation_type=SCHEMA.UpdateAction, input_type=DRONE.Drone) resp, body = update_drone_(drone) assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) return Resource.from_iri(resp['location']) except Exception as e: print(e) return None http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)), "POST Drone State", "Localhost") send_http_api_log(http_api_log)
def get_drone(id_): """Get the drone from the server given the drone ID.""" try: IRI = IRI_CS + "/DroneCollection/" + str(id_) RES = Resource.from_iri(IRI) get_drone_ = RES.find_suitable_operation( output_type=CENTRAL_SERVER.Drone) resp, body = get_drone_() assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason) body = json.loads(body.decode('utf-8')) body.pop("@context") body.pop("@type") return body except Exception as e: print(e) return None
def update_drone_at_controller(drone, drone_identifier): """Update the drone object at central controller.""" id_ = "/api/DroneCollection/" + str(drone_identifier) try: print("Updating drone") RES = Resource.from_iri(CENTRAL_SERVER_URL + id_) operation = RES.find_suitable_operation( operation_type=SCHEMA.UpdateAction, input_type=CENTRAL_SERVER.Drone) assert operation is not None resp, body = operation(drone) assert resp.status in [200, 201] except Exception as e: print(e) return None http_api_log = gen_HttpApiLog("Drone %s" % ( str(drone_identifier)), "POST Drone", "Controller") send_http_api_log(http_api_log)
def main(): from hydra import Collection, Resource, SCHEMA res = Collection.from_iri("http://www.markus-lanthaler.com/hydra/event-api/events/") print res for i in res.members: # below, we must force to load each member, # because the collection contains *some* info about its members, # causing the code to assume that *all* info is present in the collection graph i = Resource.from_iri(i.identifier) name = i.value(SCHEMA.name) if "hydra-py" in name or "py-hydra" in name or "Halloween" in name: resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction)() if resp.status // 100 != 2: print ("error deleting <%s>" % i.identifier) else: print ("deleted <%s>" % i.identifier)
def update_drone_at_controller(drone, drone_identifier): """Update the drone object at central controller.""" id_ = "/api/DroneCollection/" + str(drone_identifier) try: print("Updating drone") RES = Resource.from_iri(CENTRAL_SERVER_URL + id_) operation = RES.find_suitable_operation( operation_type=SCHEMA.UpdateAction, input_type=CENTRAL_SERVER.Drone) assert operation is not None resp, body = operation(drone) assert resp.status in [200, 201] except Exception as e: print(e) return None http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)), "POST Drone", "Controller") send_http_api_log(http_api_log)
def main(): from hydra import Collection, Resource, SCHEMA res = Collection.from_iri( "http://www.markus-lanthaler.com/hydra/event-api/events/") print res for i in res.members: # below, we must force to load each member, # because the collection contains *some* info about its members, # causing the code to assume that *all* info is present in the collection graph i = Resource.from_iri(i.identifier) name = i.value(SCHEMA.name) if "hydra-py" in name or "py-hydra" in name or "Halloween" in name: resp, _ = i.find_suitable_operation(SCHEMA.DeleteAction)() if resp.status // 100 != 2: print("error deleting <%s>" % i.identifier) else: print("deleted <%s>" % i.identifier)
def update_anomaly_at_controller(anomaly, anomaly_id, drone_identifier): """Update the anomaly object at central controller.""" id_ = "/api/AnomalyCollection/" + str(anomaly_id) try: print("Updating anomaly") RES = Resource.from_iri(CENTRAL_SERVER_URL + id_) operation = RES.find_suitable_operation( operation_type=SCHEMA.UpdateAction) assert operation is not None print(anomaly) resp, body = operation(anomaly) assert resp.status in [200, 201] return resp except Exception as e: print(e) return None http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)), "POST Anomaly", "Controller") send_http_api_log(http_api_log)
def update_anomaly_locally(anomaly, drone_identifier): """Update the anomaly object at local drone server.""" id_ = "/api/Anomaly" try: print("Updating anomaly") RES = Resource.from_iri(DRONE_URL + id_) operation = RES.find_suitable_operation( operation_type=SCHEMA.UpdateAction) assert operation is not None print(anomaly) resp, body = operation(anomaly) assert resp.status in [200, 201] return resp except Exception as e: print(e) return None http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)), "POST Anomaly", "Localhost") send_http_api_log(http_api_log)
"""Operation related to datastream post operations.""" import os import sys curDir = os.path.dirname(__file__) # this will return parent directory. parentDir = os.path.abspath(os.path.join(curDir, os.pardir)) # this will return parent directory. superParentDir = os.path.abspath(os.path.join(parentDir, os.pardir)) sys.path.insert(0, superParentDir) from flock_drone.settings import CENTRAL_SERVER_NAMESPACE, IRI_CS from hydra import SCHEMA, Resource from rdflib import Namespace CENTRAL_SERVER = Namespace(CENTRAL_SERVER_NAMESPACE) RES_CS = Resource.from_iri(IRI_CS) def gen_DroneLog(drone_id, log_string): """Generate a Drone log object from log string.""" dronelog = { "@type": "DroneLog", "DroneID": drone_id, "LogString": log_string } return dronelog def gen_HttpApiLog(source, action, target): """Generate a Http Api Log object from action and target.""" httpapilog = {
print "\nCreating new event" add_event = entrypoint.find_suitable_operation(SCHEMA.AddAction, SCHEMA.Event) start = datetime.utcnow() end = (start + timedelta(0,1)) resp, body = add_event({ "@context": "http://www.markus-lanthaler.com/hydra/event-api/contexts/Event.jsonld", "@type": "Event", "name": "Testing hydra-py", "description": "In the process of testing hyda-py", "start_date": start.isoformat()[:19] + 'Z', "end_date": end.isoformat()[:19] + 'Z', }) if resp.status != 201: print "failed... (%s %s)" % (resp.status, resp.reason) evt = Resource.from_iri(resp['location']) print evt.identifier print "\nUpdating event" evt.set(SCHEMA.description, evt.value(SCHEMA.description)+" (updated)") update_event = evt.find_suitable_operation(SCHEMA.UpdateAction, SCHEMA.Event) resp, body = update_event(evt.graph.default_context) if resp.status // 100 != 2: print "failed... (%s %s)" % (resp.status, resp.reason) else: print "succeeded" exit() print "trying again with ad-hoc JSON" resp, body = update_event({ "@context": "http://www.markus-lanthaler.com/hydra/event-api/contexts/Event.jsonld",
from hydra import Resource, SCHEMA from rdflib import Namespace from flock_drone.settings import CENTRAL_SERVER_NAMESPACE, DRONE_NAMESPACE from flock_drone.settings import CENTRAL_SERVER_URL from flock_drone.settings import IRI_CS, IRI_DRONE, DRONE_DEFAULT import pdb import time from flock_drone.mechanics.logs import send_http_api_log, gen_HttpApiLog global CENTRAL_SERVER, DRONE, RES_CS, RES_DRONE CENTRAL_SERVER = Namespace(CENTRAL_SERVER_NAMESPACE) DRONE = Namespace(DRONE_NAMESPACE) RES_CS = Resource.from_iri(IRI_CS) RES_DRONE = Resource.from_iri(IRI_DRONE) def get_drone_default(): """Return the default drone object from settings.""" return DRONE_DEFAULT def get_drone(): """Get the drone object from drone server.""" try: get_drone_ = RES_DRONE.find_suitable_operation(operation_type=None, input_type=None, output_type=DRONE.Drone) resp, body = get_drone_() assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason)
print "\nCreating new event" add_event = entrypoint.find_suitable_operation(SCHEMA.AddAction, SCHEMA.Event) start = datetime.utcnow() end = (start + timedelta(0, 1)) resp, body = add_event({ "@context": "http://www.markus-lanthaler.com/hydra/event-api/contexts/Event.jsonld", "@type": "Event", "name": "Testing hydra-py", "description": "In the process of testing hyda-py", "start_date": start.isoformat()[:19] + 'Z', "end_date": end.isoformat()[:19] + 'Z', }) if resp.status != 201: print "failed... (%s %s)" % (resp.status, resp.reason) evt = Resource.from_iri(resp['location']) print evt.identifier print "\nUpdating event" evt.set(SCHEMA.description, evt.value(SCHEMA.description) + " (updated)") update_event = evt.find_suitable_operation(SCHEMA.UpdateAction, SCHEMA.Event) resp, body = update_event(evt.graph.default_context) if resp.status // 100 != 2: print "failed... (%s %s)" % (resp.status, resp.reason) else: print "succeeded" exit() print "trying again with ad-hoc JSON" resp, body = update_event({ "@context": "http://www.markus-lanthaler.com/hydra/event-api/contexts/Event.jsonld",
from flock_controller.settings import CENTRAL_SERVER_NAMESPACE from flock_controller.settings import DRONE1_NAMESPACE, DRONE2_NAMESPACE, DRONE3_NAMESPACE, DRONE4_NAMESPACE from flock_controller.settings import IRI_CS, IRI_DRONE1, IRI_DRONE2, IRI_DRONE3, IRI_DRONE4 import pdb global CENTRAL_SERVER, DRONE1, DRONE2, DRONE3, DRONE4 CENTRAL_SERVER = Namespace(CENTRAL_SERVER_NAMESPACE) DRONE1 = Namespace(DRONE1_NAMESPACE) DRONE2 = Namespace(DRONE2_NAMESPACE) DRONE3 = Namespace(DRONE3_NAMESPACE) DRONE4 = Namespace(DRONE4_NAMESPACE) DRONES = [DRONE1, DRONE2, DRONE3, DRONE4] global RES_CS, RES_DRONE1, RES_DRONE2, RES_DRONE3, RES_DRONE4 RES_CS = Resource.from_iri(IRI_CS) RES_DRONE1 = Resource.from_iri(IRI_DRONE1) RES_DRONE2 = Resource.from_iri(IRI_DRONE2) RES_DRONE3 = Resource.from_iri(IRI_DRONE3) RES_DRONE4 = Resource.from_iri(IRI_DRONE4) RES_DRONES = [RES_DRONE1, RES_DRONE2, RES_DRONE3, RES_DRONE4] def gen_State(drone_id, battery, direction, position, sensor_status, speed): """Generate a State objects.""" state = { "@type": "State", "DroneID": drone_id, "Battery": battery, "Direction": direction, "Position": position,
from hydra import Resource, SCHEMA from rdflib import Namespace from flock_drone.settings import CENTRAL_SERVER_NAMESPACE, DRONE_NAMESPACE from flock_drone.settings import CENTRAL_SERVER_URL from flock_drone.settings import IRI_CS, IRI_DRONE, DRONE_DEFAULT import pdb import time from flock_drone.mechanics.logs import send_http_api_log, gen_HttpApiLog global CENTRAL_SERVER, DRONE, RES_CS, RES_DRONE CENTRAL_SERVER = Namespace(CENTRAL_SERVER_NAMESPACE) DRONE = Namespace(DRONE_NAMESPACE) RES_CS = Resource.from_iri(IRI_CS) RES_DRONE = Resource.from_iri(IRI_DRONE) def get_drone_default(): """Return the default drone object from settings.""" return DRONE_DEFAULT def get_drone(): """Get the drone object from drone server.""" try: get_drone_ = RES_DRONE.find_suitable_operation(operation_type=None, input_type=None, output_type=DRONE.Drone) resp, body = get_drone_()