다음을 통해 공유


Azure Cloud Services for Tello Drones: How to Config Tello by Azure Direct Methods

Introduction

Tello is a programmable mini drone, which is perfect and popular for beginners. Users can easily use programming languages such as Scratch, Python, and Swift to communicate with Tello. Microsoft Azure provides a variety of cloud computing services including artificial intelligence, machine learning, IoT, storage, security, networking, media, integration and so on. For IoT applications, Azure IoT Hub provides a cloud-hosted solution back end to connect any device over the internet. 
In this article, we will walk you through the steps required to config Tello by Azure direct methods with Python Azure IoT SDK.

Prerequisites

  1. Tello Drone.
  2. Python Azure IoT Device SDK
  3. IDE: PyCharm Community
  4. Azure subscription

Network Access for PC

Since Tello is connected to the PC by Wi-Fi, it is straightforward to know that our PC should equipped with two network interface cards, one is for connecting with Tello, and the other one is for connecting with Internet. 

Fig. 1 Network Access

Azure Direct Methods

Azure IoT Hub provides the ability to invoke direct methods on devices from the cloud. Direct methods represent a request-reply interaction with a device similar to an HTTP call in that they succeed or fail immediately (after a user-specified timeout). This approach is useful for scenarios where the course of immediate action is different depending on whether the device was able to respond. Direct methods follow a request-response pattern and are meant for communications that require immediate confirmation of their result.
In this project, Azure direct methods are leveraged to config the interval of the telemetry sending. In order to demonstrate the user scenario, the status of the Tello are collected and transmitted to Azure IoTHub at fixed intervals, which is shown in this article “Azure Cloud Services for Tello Drones: How to send telemetry to Azure IoTHub”.

Install Python Packages and Create Azure IoTHub

In this project, we will install “djitellopy” and “azure-iot-device” packages to accelerate the development. Please refer to the “Install Python Azure IoT SDK and Tello Python SDK” section of the article “Azure Cloud Services for Tello Drones: How to send telemetry to Azure IoTHub” to complete this step. Also, you will see the detail steps to create an Azure IoTHub and register a new device.

Create and Debug Python Code on Your PC

Copy and paste the following code to your PyCharm project.

01.from djitellopy import tello
02.from azure.iot.device import IoTHubDeviceClient, Message, MethodResponse
03.import asyncio
04.import time
05.import uuid
06. 
07.me =  tello.Tello()
08.me.connect()
09.# interval for sending messages
10.interval =  5
11.# The connection string for a device.
12.conn_str =  "your connection string"
13. 
14. 
15.def create_client():
16.    # The client object is used to interact with your Azure IoT hub.
17.    device_client =  IoTHubDeviceClient.create_from_connection_string(conn_str)
18. 
19.    # Define behavior for handling methods
20.    def method_request_handler(method_request):
21.        # Determine how to respond to the method request based on the method name
22.        if method_request.name == "SetTelemetryInterval":
23.            try:
24.                global interval
25.                interval =  int(method_request.payload)
26.                print("The time interval is set to " + str(method_request.payload))
27.            except ValueError:
28.                response_payload =  {"Response":  "Invalid parameter"}
29.                response_status =  400
30.            else:
31.                response_payload =  {"Response":  "Executed direct method {}".format(method_request.name)}
32.                response_status =  200
33.        else:
34.            response_payload =  {"Response":  "Direct method {} not defined".format(method_request.name)}
35.            response_status =  404
36. 
37.        # Send the response
38.        method_response =  MethodResponse.create_from_method_request(method_request, response_status, response_payload)
39.        device_client.send_method_response(method_response)
40. 
41.    try:
42.        # Attach the method request handler
43.        device_client.on_method_request_received =  method_request_handler
44.    except ValueError:
45.        # Clean up in the event of failure
46.        device_client.shutdown()
47.        raise
48. 
49.    return device_client
50. 
51. 
52.# Define behavior for telemetry sending
53.def send_tello_telemetry(device_client):
54.    # Connect the client.
55.    device_client.connect()
56. 
57.    # Send tello telemetry
58.    while True:
59.        msg =  Message(str(me.get_current_state()))
60.        msg.message_id =  uuid.uuid4()
61.        msg.correlation_id =  "correlation-1234"
62.        msg.custom_properties["tornado-warning"] =  "yes"
63.        msg.content_encoding =  "utf-8"
64.        msg.content_type =  "application/json"
65.        print("sending message: " +  str(me.get_current_state()))
66.        device_client.send_message(msg)
67.        time.sleep(interval)
68. 
69. 
70.def main():
71.    print("IoTHub Device Client Sending Tello Telemetry")
72.    print("Press Ctrl+C to exit")
73.    # Instantiate the client. Use the same instance of the client for the duration of
74.    # your application
75.    client =  create_client()
76.    # Send telemetry
77.    try:
78.        send_tello_telemetry(client)
79.    except KeyboardInterrupt:
80.        print("IoTHubClient Device Client stopped by user")
81.    finally:
82.        print("Shutting down IoTHubClient")
83.        client.shutdown()
84. 
85. 
86.if __name__ == "__main__":
87.    main()

In this Python application, we define a function create_client to define an Azure IoTHub device client. Then, in order to handle the direct method, we define method_request_handler for method parsing and payload checking. If the method name is SetTelemetryInterval, we will substitute the global variable “interval” with the payload, which will be used for time.sleep function later. Furthermore, we will fill out the JSON message and response the invoke with send_method_response method.
To achieve the Tello status telemetry sending, we define the function send_tello_telemetry. A loop of message collecting and transmitting is implemented via a specific time interval, which is set as 5 seconds by default. And it can be modified by user direct method invoke in the method_request_handler function we defined above.
Please do substitute the connection string with yours that created before. Then, power on the Tello, connect your PC with Tello by Wi-Fi. You will notice that the LED on the Tello will flash quickly with yellow color. Press Run or Debug button to start the process. You will see the output in output window as shown in Fig. 2. The status of the Tello will be transmitted to Azure IoTHub every 5 seconds.

Fig. 2 Realtime Debug Information

Send direct methods invoke with payload by Azure CLI

We can use Azure IoT Explorer to send direct methods invoke with payload, as we mentioned in this article “Azure Cloud Services for Tello Drones: How to send telemetry to Azure IoTHub”. Additionally, we can send direct methods invoke via Azure CLI. For example, we can config the time interval on the device to transmitting the status of the Tello. The messages are organized as 
az iot hub invoke-device-method --device-id <your device id> --hub-name <your IoT Hub name> --method-name <desired method> --method-payload <your payload>
please do substitute the device id, your IoT Hub name, your method name and method payload in the message. The example is shown in Fig. 3 below.

Fig. 3 Send direct method via Azure CLI

Once the device application receives the direct method invoke, it will be parsed and the corresponding time interval will be set to the desired value. You will see the response of the method with 200 result code as shown in Fig. 3. Additionally, notification in the output window indicates that the time interval is set to the user specific value, as shown in Fig. 4. We can see that the frequency of the message transmitting is modified as we desired.

Fig. 4 Debug Information

Summary

In this tutorial, we have presented the steps and Python codes on how to remotely config Tello drones by Azure IoT Hub direct methods.

Resources

  1. MS Docs for Azure IoT Hub.
  2. MS Docs for Connect Raspberry Pi to Azure IoT Hub.
  3. MS Docs for invoke direct methods
  4. MS Docs for Azure CLI.

See Also

  1. Azure Cloud Services for Tello Drones: How to send telemetry to Azure IoTHub
  2. Azure Cloud Services for Tello Drones: How to Control Tello by Azure C2D Messages