예제 #1
0
def send_anomaly(anomaly, drone_identifier):
    """Send the detected anomaly to the central server."""
    post_anomaly = RES_CS.find_suitable_operation(
        operation_type=SCHEMA.AddAction, input_type=CENTRAL_SERVER.Anomaly)
    resp, body = post_anomaly(anomaly)
    assert resp.status in [200, 201], "%s %s" % (resp.status, resp.reason)
    print("Anomaly added successfully.")
    body = json.loads(body.decode('utf-8'))
    http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)),
                                  "PUT Anomaly", "Controller")
    send_http_api_log(http_api_log)

    try:
        # Get the anomaly_id from body
        anomaly_id = body[list(body.keys())[0]].split(" ")[3]
        print("ID assigned to anomaly is", anomaly_id)
        # Update the anomalyID at central controller
        anomaly["AnomalyID"] = anomaly_id
        update_anomaly_at_controller(anomaly, anomaly_id, drone_identifier)
    except Exception as e:
        print(e)
        return None

    dronelog = gen_DroneLog(
        "Drone %s" % (str(drone_identifier), ),
        "detected anomaly at %s" % (str(anomaly["Location"])))
    send_dronelog(dronelog)
예제 #2
0
def handle_drone_commands(drone):
    """Handle the commands on the drone server and update drone accordingly."""
    # Using the latest command, not following previously stored ones, server will ensure order
    drone_identifier = drone["DroneID"]
    commands = get_command_collection()
    command_identifiers = [x["@id"] for x in commands]
    temp_list = list()
    for id_ in command_identifiers:
        regex = r'/(.*)/(\d*)'
        matchObj = re.match(regex, id_)
        if matchObj:
            command_id = matchObj.group(2)
            temp_list.append(command_id)
    temp_list.sort()

    if len(temp_list) > 0:
        latest_command = get_command(temp_list[-1])

        ## Generate and send Dronelog
        dronelog = gen_DroneLog(
            "Drone %s" % (str(drone_identifier), ),
            "executing command with id %s" % (str(temp_list[-1])))
        send_dronelog(dronelog)

        ## Generate and send HttpApiLog
        http_api_log = gen_HttpApiLog("Drone %s" % (str(drone["DroneID"])),
                                      "PUT DroneLog", "Controller")
        send_http_api_log(http_api_log)

        # Execute the latest command
        drone = execute_command(latest_command, drone)
        # Delete after execution
        delete_commands(temp_list)

    return drone
예제 #3
0
def handle_anomaly(drone):
    """Handle the anomaly that the drone needs to check on."""
    anomaly = get_anomaly()
    if anomaly is not None:
        destination = tuple(float(a) for a in anomaly["Location"].split(","))
        if not drone_reached_destination(drone, destination):
            print("Drone moving toward anomaly")
            source = tuple(
                float(a) for a in drone["State"]["Position"].split(","))
            new_direction = get_direction(source, destination)
            print(new_direction)
            if new_direction != drone["State"]["Direction"]:
                drone["State"]["Direction"] = new_direction

                dronelog = gen_DroneLog(
                    "Drone %s" % (str(drone["DroneID"]), ),
                    "changed direction to %s" % (str(new_direction)))
                send_dronelog(dronelog)

        else:
            # if reached destination
            print("Drone reached destination")
            dronelog = gen_DroneLog("Drone %s" % (str(drone["DroneID"])),
                                    "reached anomaly location, scanning")
            send_dronelog(dronelog)
            ## Check if anomaly exists at that location
            confirm_anomaly = gen_grid_anomaly(drone)
            if confirm_anomaly is not None:
                anomaly["Status"] = "Positive"

                dronelog = gen_DroneLog("Drone %s" % (str(drone["DroneID"])),
                                        "detected POSITIVE anomaly.")
                send_dronelog(dronelog)

            else:
                anomaly["Status"] = "Negative"

                dronelog = gen_DroneLog("Drone %s" % (str(drone["DroneID"])),
                                        "detected NEGATIVE anomaly.")
                send_dronelog(dronelog)

            print("Updating anomaly locally")
            update_anomaly_locally(anomaly, drone["DroneID"])

            print("Updating anomaly at controller")
            update_anomaly_at_controller(anomaly, anomaly["AnomalyID"],
                                         drone["DroneID"])
            print("Anomaly confirmation done")

            drone["State"]["Status"] = "Active"

        http_api_log = gen_HttpApiLog("Drone %s" % (str(drone["DroneID"])),
                                      "PUT DroneLog", "Controller")
        send_http_api_log(http_api_log)

    return drone
예제 #4
0
def execute_command(command, drone):
    """Execute the command on the drone."""
    drone_identifier = drone["DroneID"]
    if command["DroneID"] == drone_identifier:
        for prop in command["State"]:
            if prop != "@type" and prop in drone["State"].keys():
                prop_val = command["State"][prop]

                # Handle direction prop
                if prop == "Direction":
                    drone["State"]["Direction"] = prop_val

                    ## Generate and send Dronelog
                    dronelog = gen_DroneLog(
                        "Drone %s" % (str(drone_identifier), ),
                        "changed direction to %s after command execution." %
                        (str(prop_val)))
                    send_dronelog(dronelog)

                # Handle speed prop
                if prop == "Speed":
                    if float(prop_val) <= float(drone["MaxSpeed"]):
                        drone["State"]["Speed"] = prop_val
                    else:
                        drone["State"]["Speed"] = drone["MaxSpeed"]

                    ## Generate and send Dronelog
                    dronelog = gen_DroneLog(
                        "Drone %s" % (str(drone_identifier), ),
                        "changed speed to %s after command execution." %
                        (str(drone["State"]["Speed"])))
                    send_dronelog(dronelog)

                # Handle status prop
                if prop == "Status":
                    if prop_val in ["Active", "Off"]:
                        drone["State"]["Status"] = prop_val

                        ## Generate and send Dronelog
                    dronelog = gen_DroneLog(
                        "Drone %s" % (str(drone_identifier), ),
                        "changed status to %s after command execution." %
                        (str(prop_val)))
                    send_dronelog(dronelog)

    # Generate and Send HttpApiLog
    http_api_log = gen_HttpApiLog("Drone %s" % (str(drone["DroneID"])),
                                  "PUT DroneLog", "Controller")
    send_http_api_log(http_api_log)

    return drone
예제 #5
0
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)
예제 #6
0
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)
예제 #7
0
def send_datastream(datastream):
    """Post the drone current datastream to the central server."""
    try:
        drone_identifier = datastream["DroneID"]
        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)
        print("Datastream posted successfully.")

        http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)),
                                      "PUT Datastream", "Controller")
        send_http_api_log(http_api_log)

    except Exception as e:
        print(e)
        return None
예제 #8
0
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)
예제 #9
0
def send_datastream(datastream):
    """Post the drone current datastream to the central server."""
    try:
        drone_identifier = datastream["DroneID"]
        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)
        print("Datastream posted successfully.")

        http_api_log = gen_HttpApiLog("Drone %s" % (
            str(drone_identifier)), "PUT Datastream", "Controller")
        send_http_api_log(http_api_log)

    except Exception as e:
        print(e)
        return None
예제 #10
0
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)
예제 #11
0
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)
예제 #12
0
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)
예제 #13
0
def handle_drone_position(drone):
    """Handle the drone position changes."""
    if not is_charging(drone):
        drone_speed = float(drone["State"]["Speed"])
        distance_travelled = calculate_dis_travelled(drone_speed, LOOP_TIME)
        drone_direction = str(drone["State"]["Direction"])
        drone_identifier = drone["DroneID"]
        drone = update_drone_position(drone, distance_travelled,
                                      drone_direction)

        if (drone["State"]["Direction"] != drone_direction):

            dronelog = gen_DroneLog(
                "Drone %s" % (str(drone_identifier), ),
                "changed direction to %s" % (str(drone["State"]["Direction"])))
            send_dronelog(dronelog)

            http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)),
                                          "PUT DroneLog", "Controller")
            send_http_api_log(http_api_log)

    return drone
예제 #14
0
def charge_drone_battery(drone):
    """Handle the drone battery charging operation."""
    battery_level = drone["State"]["Battery"]
    if float(battery_level) < 95:
        # Increase battery level
        drone["State"]["Battery"] = float(battery_level) + 5
    else:
        # If battery >= 95 set battery level to 100%
        drone["State"]["Battery"] = 100

        dronelog = gen_DroneLog(
            "Drone %s" % (str(drone["DroneID"])),
            "charging complete, returning to Active state")
        send_dronelog(dronelog)

        drone["State"]["Status"] = "Active"

        http_api_log = gen_HttpApiLog("Drone %s" % (str(drone["DroneID"])),
                                      "PUT DroneLog", "Controller")
        send_http_api_log(http_api_log)

    return drone
예제 #15
0
def discharge_drone_battery(drone):
    """Handle drone battery discharging."""
    battery_level = drone["State"]["Battery"]
    drone_identifier = drone["DroneID"]
    if float(battery_level) > 20:
        drone["State"]["Battery"] = int(drone["State"]["Battery"]) - 1
    elif float(battery_level) <= 20 and float(battery_level) > 3:
        # Drone in inactive state will take less battery per iteration (1/4 of normal battery usage).
        drone["State"]["Battery"] = float(drone["State"]["Battery"]) - 0.25

    if float(battery_level) == 20.0:
        drone["State"]["Status"] = "Inactive"
        drone["State"]["Battery"] = int(drone["State"]["Battery"]) - 1

        dronelog = gen_DroneLog(
            "Drone %s" % (str(drone_identifier), ),
            "battery Low %s, changing to Inactive state" %
            (str(drone["State"]["Battery"])))
        send_dronelog(dronelog)

        http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)),
                                      "PUT DroneLog", "Controller")
        send_http_api_log(http_api_log)

    elif float(battery_level) <= 4.0:
        # Battery level critical change drone status to OFF
        drone["State"]["Status"] = "Off"

        dronelog = gen_DroneLog("Drone %s" % (str(drone_identifier)),
                                "Battery level critical, shutting down!")
        send_dronelog(dronelog)

        http_api_log = gen_HttpApiLog("Drone %s" % (str(drone_identifier)),
                                      "PUT DroneLog", "Controller")
        send_http_api_log(http_api_log)

    return drone