Example #1
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
Example #2
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
Example #3
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)
Example #4
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
Example #5
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
Example #6
0
def handle_drone_low_battery(drone):
    """Handle the drone inactive state ( when 3< battery < 20)."""
    destination = CONTROLLER_LOC
    if not drone_reached_destination(drone, destination):
        print("Drone moving toward central controller")
        source = tuple(float(a) for a in drone["State"]["Position"].split(","))
        new_direction = get_direction(source, destination)
        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
        dronelog = gen_DroneLog("Drone %s" % (str(drone["DroneID"]), ),
                                "reached central controller, charging.")
        send_dronelog(dronelog)

        print("Drone reached destination")
        drone["State"]["Status"] = "Charging"
    return drone
Example #7
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
Example #8
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