Flying a Drone With Javascript

Flying a drone with javascript probably sounds crazy and hard. Do I use a framework? Will the 10 GB of node_modules weigh it down? NOPE! It’s all pretty simple to do.

The other day I came across a neat drone called the DJI Tello. It is a relatively inexpensive quadcopter that offers a simple SDK which can be accessed over WiFI. Using the NodeJS dgram library, I can send commands via UDP to the drone to perform actions such as takeoff, left 20, and land. Let’s go step by throught his code:

Imports

You will need to Nodejs’s builtin dgram library. It will allow you to send data via UDP to the drone. You must use this because the drone does not support TCP.

const dgram = require('dgram');

I am also importing the readline library so that we can capture user input.

const readline = require('readline');

Connecting via Host and Port

The host and port are defined in the tello sdk . We will create a socket to that location.

const PORT = 8889;
const HOST = '192.168.10.1';

const client = dgram.createSocket('udp4');
client.bind(PORT);

Sending a Message via UDP.

Let’s wrap this in a function so we can make it re-usable later. In this function are accepting a string command and sending that command to the host.

function sendMessage(command) {
  client.send(command, 0, command.length, PORT, HOST, (err, bytes) => {
    if (err) throw err;
    console.log(`UDP message sent to ${HOST}:${PORT}`);
  });
}

We will also create a listener to receive any responses we get back from the drone.

client.on('message', (message, remote) => {
  console.log(`${remote.address}:${remote.port} - ${message}`);
});

User Input

Finally, let’s create an anonymous self-invoking function that will ask the user to enter a command and send their input to our sendMessage function.

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

(function userInput() {
  rl.question('Enter command:  ', (command) => {
    if (command === 'exit') {
      rl.close();
    } else {
      sendMessage(command);
      userInput();
    }
  });
}());

That’s all there is to it. Now, just power on your drone and connect your PC to it via WiFi. Once you are connected, run javascript file and begin by entering in the command command to put it in command mode. From there, you can issue any of the other commands that are available to use.

Full code is available on GitHub