├── .dockerignore ├── README.md ├── client ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .storybook │ ├── addons.ts │ ├── config.ts │ ├── decorators.tsx │ └── webpack.config.js ├── Dockerfile ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src │ ├── App.css │ ├── App.test.tsx │ ├── App.tsx │ ├── ArrowDown.svg │ ├── ArrowLeft.svg │ ├── ArrowRight.svg │ ├── ArrowUp.svg │ ├── Command.tsx │ ├── CommandBoard.tsx │ ├── ControlCommand.tsx │ ├── DraggableCommands.tsx │ ├── DroneService.ts │ ├── PlayStopIcon.tsx │ ├── ServerConnectIcon.tsx │ ├── WebRTC.tsx │ ├── index.css │ ├── index.tsx │ ├── logo.svg │ ├── react-app-env.d.ts │ ├── serviceWorker.ts │ └── theme.ts ├── stories │ ├── Command.stories.tsx │ ├── CommandBoard.stories.tsx │ ├── PlayStopIcon.stories.tsx │ ├── ServerConnectIcon.stories.tsx │ └── index.stories.tsx ├── tsconfig.json └── yarn.lock ├── demo.gif ├── docker-compose.yml ├── go.mod ├── go.sum ├── makefile └── server ├── Dockerfile ├── gst.c ├── gst.go ├── gst.h ├── main.go ├── server.go └── tello.go /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | Dockerfile* 4 | docker-compose* 5 | .dockerignore 6 | .git 7 | .gitignore 8 | .env 9 | */bin 10 | */obj 11 | README.md 12 | LICENSE 13 | .vscode -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tello on the web via WebRTC 2 | 3 | ## What is this? 4 | Playing around with the [Tello SDK](https://terra-1-g.djicdn.com/2d4dce68897a46b19fc717f3576b7c6a/Tello%20%E7%BC%96%E7%A8%8B%E7%9B%B8%E5%85%B3/For%20Tello/Tello%20SDK%20Documentation%20EN_1.3_1122.pdf) 5 | 6 | ![](./demo.gif) 7 | 8 | ## Built with 9 | * [Pion](https://github.com/pion/) to handle all things WebRTC 10 | * [GStreamer](https://gstreamer.freedesktop.org/) for parsing video stream 11 | * [React](https://reactjs.org/) for UI 12 | 13 | ## Related work 14 | 15 | * [Tello-WebRTC-FPV](https://github.com/oliverpool/tello-webrtc-fpv) 16 | 17 | ## Development 18 | 19 | You need to install GStreamer locally unfortunately. 20 | Follow [these steps](https://gstreamer.freedesktop.org/documentation/installing/index.html?gi-language=c) 21 | 22 | ### Make 23 | 24 | ``` 25 | make install 26 | ``` 27 | 28 | ``` 29 | make start_client 30 | ``` 31 | 32 | ``` 33 | make start_server 34 | ``` 35 | 36 | ### WIP Docker 37 | WebRTC negotiates and connects on a random UDP port. This means that all UDP ports need to be forwarded or docker need to run on [host network](https://docs.docker.com/network/host/) 38 | 39 | 40 | ## Debug 41 | 42 | Run video stream via GStreamer CLI 43 | ``` 44 | gst-launch-1.0 -v udpsrc port=11111 caps="video/x-h264, stream-format=(string)byte-stream, width=(int)960, height=(int)720, framerate=(fraction)24/1, skip-first-bytes=2" \ 45 | ! queue \ 46 | ! decodebin \ 47 | ! videoconvert \ 48 | ! autovideosink sync=false 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /client/.eslintignore: -------------------------------------------------------------------------------- 1 | # Lint config files as well 2 | !.*.js 3 | !.storybook/ -------------------------------------------------------------------------------- /client/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es6: true, 5 | }, 6 | extends: [ 7 | 'plugin:react/recommended', 8 | 'plugin:@typescript-eslint/recommended', 9 | 'prettier/@typescript-eslint', 10 | 'plugin:prettier/recommended', 11 | 'prettier/react', 12 | ], 13 | globals: { 14 | Atomics: 'readonly', 15 | SharedArrayBuffer: 'readonly', 16 | }, 17 | parser: '@typescript-eslint/parser', 18 | parserOptions: { 19 | ecmaFeatures: { 20 | jsx: true, 21 | }, 22 | ecmaVersion: 2018, 23 | sourceType: 'module', 24 | }, 25 | plugins: ['react'], 26 | rules: { 27 | 'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx', '.tsx'] }], 28 | 'prettier/prettier': [ 29 | 'error', 30 | { 31 | trailingComma: 'es5', 32 | singleQuote: true, 33 | printWidth: 90, 34 | semi: false, 35 | }, 36 | ], 37 | 38 | // Rules that consumers might want to enforce, but seems to restrictive to be default: 39 | '@typescript-eslint/explicit-function-return-type': 'off', 40 | '@typescript-eslint/explicit-member-accessibility': 'off', 41 | '@typescript-eslint/no-use-before-define': 'off', 42 | '@typescript-eslint/array-type': 'off', 43 | 44 | // Rules that doesn't make sense: 45 | '@typescript-eslint/no-explicit-any': 'off', // that seems to restrictive 46 | '@typescript-eslint/prefer-interface': 'off', // you might not want people to extend your types 47 | 'no-unused-vars': 'off', // replaced by @typescript-eslint/no-unused-vars 48 | }, 49 | settings: { 50 | react: { 51 | version: 'detect', 52 | }, 53 | }, 54 | } 55 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /client/.storybook/addons.ts: -------------------------------------------------------------------------------- 1 | import '@storybook/addon-actions/register' 2 | import '@storybook/addon-links/register' 3 | import '@storybook/addon-knobs/register' 4 | -------------------------------------------------------------------------------- /client/.storybook/config.ts: -------------------------------------------------------------------------------- 1 | import { configure } from '@storybook/react' 2 | 3 | const req = require.context('../stories', true, /\.stories\.tsx$/) 4 | 5 | function loadStories() { 6 | req.keys().forEach(req) 7 | } 8 | 9 | configure(loadStories, module) 10 | -------------------------------------------------------------------------------- /client/.storybook/decorators.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export function center(storyFn: Function) { 4 | return ( 5 |
17 | {storyFn()} 18 |
19 | ) 20 | } 21 | -------------------------------------------------------------------------------- /client/.storybook/webpack.config.js: -------------------------------------------------------------------------------- 1 | module.exports = ({ config }) => { 2 | config.module.rules.push({ 3 | test: /\.(ts|tsx)$/, 4 | loader: require.resolve('babel-loader'), 5 | options: { 6 | presets: [['react-app', { flow: false, typescript: true }]], 7 | }, 8 | }) 9 | config.resolve.extensions.push('.ts', '.tsx') 10 | return config 11 | } 12 | -------------------------------------------------------------------------------- /client/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:11-alpine 2 | 3 | WORKDIR /src/app 4 | 5 | RUN npm install -g serve 6 | 7 | ADD yarn.lock package.json ./ 8 | RUN yarn install 9 | 10 | COPY . . 11 | 12 | RUN yarn build 13 | 14 | EXPOSE 5000 15 | CMD ["serve", "-s", "build"] 16 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@types/jest": "24.0.11", 7 | "@types/lodash-es": "^4.17.3", 8 | "@types/node": "11.13.7", 9 | "@types/react": "16.8.14", 10 | "@types/react-beautiful-dnd": "^11.0.1", 11 | "@types/react-dom": "16.8.4", 12 | "lodash-es": "^4.17.11", 13 | "react": "^16.8.6", 14 | "react-beautiful-dnd": "^11.0.2", 15 | "react-dom": "^16.8.6", 16 | "react-scripts": "3.0.0", 17 | "react-spring": "^8.0.20", 18 | "react-use-gesture": "^5.0.0", 19 | "react-with-gesture": "^4.0.8", 20 | "typescript": "3.4.5" 21 | }, 22 | "scripts": { 23 | "start": "react-scripts start", 24 | "build": "react-scripts build", 25 | "test": "react-scripts test", 26 | "eject": "react-scripts eject", 27 | "lint": "eslint . --ext js,ts,tsx --fix", 28 | "typecheck": "tsc --noEmit -p .", 29 | "storybook": "start-storybook -p 9009 -s public", 30 | "build-storybook": "build-storybook -s public" 31 | }, 32 | "eslintConfig": { 33 | "extends": "react-app" 34 | }, 35 | "browserslist": { 36 | "production": [ 37 | ">0.2%", 38 | "not dead", 39 | "not op_mini all" 40 | ], 41 | "development": [ 42 | "last 1 chrome version", 43 | "last 1 firefox version", 44 | "last 1 safari version" 45 | ] 46 | }, 47 | "devDependencies": { 48 | "@babel/core": "^7.4.4", 49 | "@storybook/addon-actions": "^5.0.11", 50 | "@storybook/addon-knobs": "^5.0.11", 51 | "@storybook/addon-links": "^5.0.11", 52 | "@storybook/addons": "^5.0.11", 53 | "@storybook/react": "^5.0.11", 54 | "@types/storybook__addon-actions": "^3.4.2", 55 | "@types/storybook__addon-knobs": "^5.0.0", 56 | "@typescript-eslint/eslint-plugin": "^1.7.0", 57 | "@typescript-eslint/parser": "^1.7.0", 58 | "babel-loader": "^8.0.5", 59 | "eslint": "^5.16.0", 60 | "eslint-config-prettier": "^4.2.0", 61 | "eslint-plugin-prettier": "^3.0.1", 62 | "eslint-plugin-react": "^7.13.0", 63 | "prettier": "^1.17.0" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ragnar-H/TelloGo/cc3950588b70e4539d7522502e522fe9f30af6d1/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 22 | React App 23 | 24 | 25 | 26 |
27 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /client/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | -------------------------------------------------------------------------------- /client/src/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom' 3 | import App from './App' 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div') 7 | ReactDOM.render(, div) 8 | ReactDOM.unmountComponentAtNode(div) 9 | }) 10 | -------------------------------------------------------------------------------- /client/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import './App.css' 3 | 4 | import { CommandBoard } from './CommandBoard' 5 | 6 | const App: React.FC = () => { 7 | return 8 | } 9 | 10 | export default App 11 | -------------------------------------------------------------------------------- /client/src/ArrowDown.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /client/src/ArrowLeft.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /client/src/ArrowRight.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /client/src/ArrowUp.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /client/src/Command.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { CommandDirection } from 'DraggableCommands' 3 | import { useSpring, animated } from 'react-spring' 4 | import { secondaryTextColor, secondaryDarkColor, sizingUnit } from './theme' 5 | export const MAX_SPEED = 100 6 | export const MIN_SPEED = 10 7 | export const MAX_DISTANCE = 500 8 | export const MIN_DISTANCE = 20 9 | const STEP = 5 10 | 11 | export type DirectedCommand = { 12 | id: string 13 | action: CommandDirection 14 | speed: number 15 | distance: number 16 | } 17 | 18 | type Props = DirectedCommand & { 19 | onSetSpeed: (speed: number) => void 20 | onSetDistance: (distance: number) => void 21 | timeLeft: number 22 | } 23 | 24 | function getRotation(direction: CommandDirection) { 25 | switch (direction) { 26 | case 'left': 27 | return 0 28 | case 'right': 29 | return 180 30 | case 'forward': 31 | case 'up': 32 | return 90 33 | case 'back': 34 | case 'down': 35 | return -90 36 | default: 37 | throw new Error('Unknown direction') 38 | } 39 | } 40 | 41 | function getInitialCoordinates(command: DirectedCommand) { 42 | const minArrowLength = 8 43 | const minBaseLength = 24 44 | const speed = (command.speed / MAX_SPEED) * 8 + minArrowLength 45 | const distance = (command.distance / MAX_DISTANCE) * 16 + minBaseLength 46 | const tip = { x: 24 - distance / 2, y: 24 } 47 | const base = { x: tip.x + distance, y: 24 } 48 | const head = { 49 | x1: tip.x + speed, 50 | y1: tip.y - speed, 51 | x2: tip.x, 52 | y2: tip.y, 53 | x3: tip.x + speed, 54 | y3: tip.y + speed, 55 | } 56 | 57 | return { tip, base, head } 58 | } 59 | 60 | export function Command(props: Props) { 61 | const coords = getInitialCoordinates({ 62 | action: props.action, 63 | distance: props.distance, 64 | speed: props.speed, 65 | id: props.id, 66 | }) 67 | const rotation = getRotation(props.action) 68 | const { tip, base, head } = coords 69 | const bodyPath = `M${tip.x} ${tip.y}L${base.x} ${base.y}` 70 | const arrowPath = `M${head.x1} ${head.y1}L${head.x2} ${head.y2}L${head.x3} ${head.y3}` 71 | const animatedPaths = useSpring({ 72 | bodyPath, 73 | arrowPath, 74 | }) 75 | const durationLeft = useSpring({ height: 48 * props.timeLeft }) 76 | return ( 77 |
86 | 87 | 93 | 94 | {(props.action === 'up' || props.action === 'down') && ( 95 | 100 | )} 101 | 106 | 111 | 112 | 113 | 114 |
117 | 129 | { 137 | const newValue = parseInt(event.currentTarget.value) 138 | if (newValue >= MIN_DISTANCE && newValue <= MAX_DISTANCE) { 139 | props.onSetDistance(newValue) 140 | } 141 | }} 142 | style={{ 143 | width: '100%', 144 | minWidth: 0, 145 | display: 'flex', 146 | color: secondaryTextColor, 147 | backgroundColor: secondaryDarkColor, 148 | border: 0, 149 | borderRadius: `${sizingUnit}px`, 150 | padding: `${sizingUnit / 2}px`, 151 | }} 152 | /> 153 | 165 | { 173 | const newValue = parseInt(event.currentTarget.value) 174 | if (newValue >= MIN_SPEED && newValue <= MAX_SPEED) { 175 | props.onSetSpeed(newValue) 176 | } 177 | }} 178 | style={{ 179 | width: '100%', 180 | minWidth: 0, 181 | display: 'flex', 182 | color: secondaryTextColor, 183 | backgroundColor: secondaryDarkColor, 184 | border: 0, 185 | borderRadius: `${sizingUnit}px`, 186 | padding: `${sizingUnit / 2}px`, 187 | }} 188 | /> 189 |
190 |
191 | ) 192 | } 193 | -------------------------------------------------------------------------------- /client/src/CommandBoard.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react' 2 | import { 3 | DragDropContext, 4 | DropResult, 5 | ResponderProvided, 6 | Droppable, 7 | DroppableProvided, 8 | DraggableLocation, 9 | } from 'react-beautiful-dnd' 10 | import { CommandItem, Commands, CommandDirection } from './DraggableCommands' 11 | import { sizingUnit } from './theme' 12 | import { PlayStopIcon } from './PlayStopIcon' 13 | import { Control } from './ControlCommand' 14 | import { setSpeed, sendCommand } from './DroneService' 15 | import { WebRTC } from './WebRTC' 16 | 17 | async function wait(seconds: number) { 18 | return new Promise(resolve => { 19 | setTimeout(resolve, seconds * 1000) 20 | }) 21 | } 22 | 23 | const reorder = ( 24 | list: CommandItem[], 25 | startIndex: number, 26 | endIndex: number 27 | ): CommandItem[] => { 28 | const result = [...list] 29 | const [removed] = result.splice(startIndex, 1) 30 | result.splice(endIndex, 0, removed) 31 | 32 | return result 33 | } 34 | 35 | const move = ({ 36 | source, 37 | destination, 38 | droppableSource, 39 | droppableDestination, 40 | }: { 41 | source: CommandItem[] 42 | destination: CommandItem[] 43 | droppableSource: DraggableLocation 44 | droppableDestination: DraggableLocation 45 | }) => { 46 | const sourceClone = [...source] 47 | const destClone = [...destination] 48 | const [removed] = sourceClone.splice(droppableSource.index, 1) 49 | 50 | destClone.splice(droppableDestination.index, 0, removed) 51 | 52 | return { source: sourceClone, destination: destClone } 53 | } 54 | 55 | function fillMissingCommands(commandList: CommandItem[]): CommandItem[] { 56 | const commands = commandList.slice() 57 | 58 | initialCommands.map(command => { 59 | const commandIsAvailable = commands.find( 60 | availableCommand => availableCommand.action === command.action 61 | ) 62 | if (!commandIsAvailable) { 63 | if (command.action === 'takeoff' || command.action === 'land') { 64 | commands.push(createControlledCommand(command.action)) 65 | } else { 66 | commands.push(createDirectedCommand(command.action)) 67 | } 68 | } 69 | }) 70 | 71 | return commands 72 | } 73 | 74 | let commandIdx = 0 75 | 76 | function createDirectedCommand(direction: CommandDirection): CommandItem { 77 | return { 78 | action: direction, 79 | id: `${commandIdx++}-command`, 80 | speed: 10, 81 | distance: 20, 82 | } 83 | } 84 | 85 | function createControlledCommand(action: Control): CommandItem { 86 | return { 87 | action, 88 | id: `${commandIdx++}-command`, 89 | } 90 | } 91 | 92 | const initialCommands: CommandItem[] = [ 93 | createControlledCommand('takeoff'), 94 | createControlledCommand('land'), 95 | createDirectedCommand('up'), 96 | createDirectedCommand('down'), 97 | createDirectedCommand('right'), 98 | createDirectedCommand('left'), 99 | createDirectedCommand('forward'), 100 | createDirectedCommand('back'), 101 | ] 102 | 103 | export function CommandBoard() { 104 | const [queuedCommands, setQueuedCommands] = useState([]) 105 | const [availableCommands, setAvailableCommands] = useState(initialCommands) 106 | const [firstItemTimeLeft, setFirstItemTimeLeft] = useState(1) 107 | 108 | const [isPlaying, setIsPlaying] = useState(false) 109 | 110 | useEffect(() => { 111 | playCommands(queuedCommands) 112 | }, [isPlaying]) 113 | 114 | function playCommands(commands: CommandItem[]) { 115 | async function executeCommand() { 116 | if (!isPlaying) { 117 | return 118 | } 119 | if (commands.length === 0) { 120 | setIsPlaying(false) 121 | return 122 | } 123 | const currentCommand = commands[0] 124 | if (currentCommand) { 125 | const { speed, distance, action } = currentCommand as any 126 | setFirstItemTimeLeft(1) 127 | if (speed) { 128 | setSpeed(speed) 129 | await wait(2) 130 | sendCommand(`${action} ${distance}`) 131 | const totalDuration = distance / speed 132 | let secondsSpent = 0 133 | while (secondsSpent <= totalDuration) { 134 | setFirstItemTimeLeft(1 - secondsSpent / totalDuration) 135 | secondsSpent++ 136 | await wait(1) 137 | } 138 | } else { 139 | sendCommand(action) 140 | const totalDuration = 8 141 | let secondsSpent = 0 142 | while (secondsSpent <= totalDuration) { 143 | setFirstItemTimeLeft(1 - secondsSpent / totalDuration) 144 | secondsSpent++ 145 | await wait(1) 146 | } 147 | } 148 | } 149 | 150 | const newCommands = commands.splice(1) 151 | setQueuedCommands(newCommands) 152 | playCommands(newCommands) 153 | } 154 | executeCommand() 155 | } 156 | 157 | function handleSetSpeed(commandId: string, speed: number) { 158 | const availableClone = availableCommands.slice() 159 | const availableIdx = availableClone.findIndex(command => command.id === commandId) 160 | if (availableIdx >= 0) { 161 | ;(availableCommands[availableIdx] as any).speed = speed 162 | 163 | setAvailableCommands(availableClone) 164 | } else { 165 | const queuedClone = queuedCommands.slice() 166 | 167 | const queuedIdx = queuedClone.findIndex(command => command.id === commandId) 168 | if (queuedIdx < 0) { 169 | throw new Error(`Cannot find command by id ${commandId}`) 170 | } 171 | ;(queuedClone[queuedIdx] as any).speed = speed 172 | setQueuedCommands(queuedClone) 173 | } 174 | } 175 | 176 | function handleSetDistance(commandId: string, distance: number) { 177 | const availableClone = availableCommands.slice() 178 | const availableIdx = availableClone.findIndex(command => command.id === commandId) 179 | if (availableIdx >= 0) { 180 | ;(availableCommands[availableIdx] as any).distance = distance 181 | setAvailableCommands(availableClone) 182 | } else { 183 | const queuedClone = queuedCommands.slice() 184 | 185 | const queuedIdx = queuedClone.findIndex(command => command.id === commandId) 186 | if (queuedIdx < 0) { 187 | throw new Error(`Cannot find command by id ${commandId}`) 188 | } 189 | ;(queuedClone[queuedIdx] as any).distance = distance 190 | setQueuedCommands(queuedClone) 191 | } 192 | } 193 | 194 | function onDragEnd(result: DropResult, provided: ResponderProvided) { 195 | const { source, destination } = result 196 | 197 | if (!destination) { 198 | return 199 | } 200 | 201 | if (source.droppableId === destination.droppableId) { 202 | if (source.droppableId === 'commands') { 203 | const items = reorder(availableCommands, source.index, destination.index) 204 | setAvailableCommands(items) 205 | } else if (source.droppableId === 'queuedCommands') { 206 | const items = reorder(queuedCommands, source.index, destination.index) 207 | setQueuedCommands(items) 208 | } 209 | } else { 210 | if (source.droppableId === 'commands') { 211 | const resultFromMove = move({ 212 | source: availableCommands, 213 | destination: queuedCommands, 214 | droppableSource: source, 215 | droppableDestination: destination, 216 | }) 217 | 218 | const filledCommands = fillMissingCommands(resultFromMove.source) 219 | 220 | setAvailableCommands(filledCommands) 221 | setQueuedCommands(resultFromMove.destination) 222 | } else { 223 | const resultFromMove = move({ 224 | source: queuedCommands, 225 | destination: availableCommands, 226 | droppableSource: source, 227 | droppableDestination: destination, 228 | }) 229 | setAvailableCommands(resultFromMove.destination) 230 | setQueuedCommands(resultFromMove.source) 231 | } 232 | } 233 | } 234 | 235 | return ( 236 |
246 | 247 | 248 | {(provided: DroppableProvided) => ( 249 |
258 |
267 | setIsPlaying(prevIsPlaying => !prevIsPlaying)} 269 | isPlaying={isPlaying} 270 | /> 271 |
272 |
273 | 280 |
281 | {provided.placeholder} 282 |
283 | )} 284 |
285 | 286 | 287 | {(provided: DroppableProvided) => ( 288 |
293 | 300 |
301 | )} 302 |
303 |
304 |
305 | ) 306 | } 307 | -------------------------------------------------------------------------------- /client/src/ControlCommand.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { secondaryTextColor, secondaryDarkColor } from './theme' 3 | import { useSpring, animated } from 'react-spring' 4 | 5 | export type Control = 'land' | 'takeoff' 6 | export type ControlledCommand = { 7 | id: string 8 | action: Control 9 | } 10 | type Props = { 11 | action: Control 12 | timeLeft: number 13 | } 14 | 15 | export function ControlCommand(props: Props) { 16 | const durationLeft = useSpring({ height: 52 * props.timeLeft }) 17 | return ( 18 |
19 | 26 | 32 | 33 | {props.action === 'takeoff' ? ( 34 | 35 | ) : ( 36 | 37 | )} 38 | 42 | 43 |
44 | ) 45 | } 46 | -------------------------------------------------------------------------------- /client/src/DraggableCommands.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { Draggable, DraggableProvided, DraggableStateSnapshot } from 'react-beautiful-dnd' 3 | import { Command, DirectedCommand } from './Command' 4 | import { secondaryColor, secondaryLightColor, sizingUnit } from './theme' 5 | import { ControlledCommand, ControlCommand } from './ControlCommand' 6 | 7 | export type CommandDirection = 'up' | 'down' | 'left' | 'right' | 'forward' | 'back' 8 | 9 | const getItemStyle = (draggableStyle: any, isDragging: boolean): {} => ({ 10 | userSelect: 'none', 11 | padding: 2 * sizingUnit, 12 | margin: `0 ${sizingUnit}px ${sizingUnit}px 0`, 13 | minWidth: `${sizingUnit}rem`, 14 | width: `${sizingUnit}rem`, 15 | display: 'flex', 16 | justifyContent: 'center', 17 | alignItems: 'center', 18 | borderRadius: '15px', 19 | background: isDragging ? secondaryLightColor : secondaryColor, 20 | ...draggableStyle, 21 | }) 22 | 23 | export type CommandItem = DirectedCommand | ControlledCommand 24 | 25 | type CommandProps = { 26 | index: number 27 | commandItem: CommandItem 28 | onSetSpeed: (speed: number) => void 29 | onSetDistance: (distance: number) => void 30 | timeLeft: number 31 | } 32 | 33 | export function DraggableCommand(props: CommandProps) { 34 | return ( 35 | 36 | {( 37 | providedDraggable: DraggableProvided, 38 | snapshotDraggable: DraggableStateSnapshot 39 | ) => ( 40 |
49 | {props.commandItem.action === 'land' || 50 | props.commandItem.action === 'takeoff' ? ( 51 | 52 | ) : ( 53 | 62 | )} 63 |
64 | )} 65 |
66 | ) 67 | } 68 | 69 | type CommandsProps = { 70 | list: CommandItem[] 71 | direction: 'row' | 'column' 72 | onSetSpeed: (commandId: string, speed: number) => void 73 | onSetDistance: (commandId: string, distance: number) => void 74 | firstItemTimeLeft: number 75 | } 76 | 77 | export function Commands(props: CommandsProps) { 78 | return ( 79 |
88 | {props.list.map((command, index) => ( 89 | { 95 | props.onSetDistance(command.id, distance) 96 | }} 97 | onSetSpeed={speed => { 98 | props.onSetSpeed(command.id, speed) 99 | }} 100 | /> 101 | ))} 102 |
103 | ) 104 | } 105 | -------------------------------------------------------------------------------- /client/src/DroneService.ts: -------------------------------------------------------------------------------- 1 | let _peerConnection: RTCPeerConnection | null = null 2 | let _dataChannel: RTCDataChannel | null = null 3 | 4 | export function setPeerConnection() { 5 | _peerConnection = new RTCPeerConnection({ 6 | iceServers: [ 7 | { 8 | urls: 'stun:stun.l.google.com:19302', 9 | }, 10 | ], 11 | }) 12 | } 13 | 14 | export function getPeerConnection() { 15 | if (_peerConnection === null) { 16 | throw new Error('Set drone connection before accessing it') 17 | } 18 | return _peerConnection 19 | } 20 | 21 | export function setStreamCallback(video: HTMLVideoElement) { 22 | const peerConnection = getPeerConnection() 23 | peerConnection.addTransceiver('video', { direction: 'recvonly' }) 24 | peerConnection.ontrack = event => { 25 | video.srcObject = event.streams[0] 26 | video.autoplay = true 27 | } 28 | } 29 | 30 | export async function negotiateConnection() { 31 | const peerConnection = getPeerConnection() 32 | const dataChannelIsOpen = setCommandDataChannel() 33 | 34 | const offer = await peerConnection.createOffer() 35 | peerConnection.setLocalDescription(offer) 36 | const answer = await fetch('http://localhost:50000', { 37 | method: 'POST', 38 | headers: { 39 | 'Content-Type': 'application/json', 40 | }, 41 | body: JSON.stringify(offer), 42 | }) 43 | const response = await answer.json() 44 | await peerConnection.setRemoteDescription(response) 45 | await dataChannelIsOpen 46 | } 47 | 48 | export function setCommandDataChannel(): Promise<{}> { 49 | const peerConnection = getPeerConnection() 50 | const initiateDataChannel = peerConnection.createDataChannel('commands') 51 | 52 | const isOpen = new Promise(resolve => { 53 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 54 | initiateDataChannel.onopen = e => { 55 | _dataChannel = initiateDataChannel 56 | resolve() 57 | } 58 | }) 59 | 60 | return isOpen 61 | } 62 | 63 | export function getCommandDataChannel() { 64 | if (_dataChannel === null) { 65 | throw new Error('Set command channel before accessing it') 66 | } 67 | return _dataChannel 68 | } 69 | 70 | // type Command = 'connect' | 'streamon' | 'streamoff' | 'land' | 'takeoff' | 'down' 71 | export function sendCommand(command: string) { 72 | const dataChannel = getCommandDataChannel() 73 | dataChannel.send(command) 74 | } 75 | 76 | export function connectToDrone() { 77 | sendCommand('command') 78 | } 79 | 80 | export function streamOn() { 81 | sendCommand('streamon') 82 | } 83 | 84 | export function streamOff() { 85 | sendCommand('streamoff') 86 | } 87 | 88 | export function takeOff() { 89 | sendCommand('takeoff') 90 | } 91 | 92 | export function land() { 93 | sendCommand('land') 94 | } 95 | 96 | export function down(distance: number) { 97 | sendCommand(`down ${distance}`) 98 | } 99 | 100 | export function up(distance: number) { 101 | sendCommand(`up ${distance}`) 102 | } 103 | 104 | export function left(distance: number) { 105 | sendCommand(`left ${distance}`) 106 | } 107 | 108 | export function right(distance: number) { 109 | sendCommand(`right ${distance}`) 110 | } 111 | 112 | export function setSpeed(speed: number) { 113 | sendCommand(`speed ${speed}`) 114 | } 115 | -------------------------------------------------------------------------------- /client/src/PlayStopIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { useSpring, animated } from 'react-spring' 3 | 4 | type Props = { 5 | isPlaying: boolean 6 | onClick: () => void 7 | } 8 | 9 | export function PlayStopIcon(props: Props) { 10 | const { isPlaying, onClick } = props 11 | 12 | const path = isPlaying ? 'M0 0L260 0L260 260L0 260' : 'M130 0L260 130L130 260L130 130' 13 | const animations = useSpring({ iconPath: path }) 14 | return ( 15 | 22 | 23 | 24 | ) 25 | } 26 | -------------------------------------------------------------------------------- /client/src/ServerConnectIcon.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { useSpring, animated } from 'react-spring' 3 | type Props = { 4 | isConnected: boolean 5 | onClick: () => void 6 | } 7 | 8 | function getCoords(connected: boolean) { 9 | const center = connected ? { x1: 50, x2: 50 } : { x1: 30, x2: 70 } 10 | 11 | const line1Path = `M${center.x1 - 30} 50L${center.x1} 50 M${center.x1} 20L${ 12 | center.x1 13 | } 80` 14 | 15 | const line2Path = `M${center.x2 + 30} 50L${center.x2} 50 M${center.x2} 20L${ 16 | center.x2 17 | } 80` 18 | return { 19 | line1Path, 20 | line2Path, 21 | } 22 | } 23 | 24 | export function ServerConnectIcon(props: Props) { 25 | const { isConnected, onClick } = props 26 | const coords = getCoords(isConnected) 27 | const animations = useSpring({ ...coords }) 28 | return ( 29 | 36 | 37 | 38 | 39 | ) 40 | } 41 | -------------------------------------------------------------------------------- /client/src/WebRTC.tsx: -------------------------------------------------------------------------------- 1 | import React, { useRef, useState } from 'react' 2 | import { 3 | setPeerConnection, 4 | negotiateConnection, 5 | connectToDrone, 6 | setStreamCallback, 7 | streamOn, 8 | } from './DroneService' 9 | import { ServerConnectIcon } from './ServerConnectIcon' 10 | import { primaryDarkColor, primaryColor } from './theme' 11 | 12 | async function startWebRTC(video: HTMLVideoElement) { 13 | setPeerConnection() 14 | setStreamCallback(video) 15 | await negotiateConnection() 16 | connectToDrone() 17 | streamOn() 18 | } 19 | 20 | export function WebRTC() { 21 | const video = useRef(null) 22 | const [isConnected, setIsConnected] = useState(false) 23 | return ( 24 |
25 |
53 | ) 54 | } 55 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | html { 2 | background: #c67600 3 | } 4 | body { 5 | margin: 0; 6 | padding: 0; 7 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 8 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 9 | sans-serif; 10 | -webkit-font-smoothing: antialiased; 11 | -moz-osx-font-smoothing: grayscale; 12 | } 13 | 14 | code { 15 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 16 | monospace; 17 | } 18 | -------------------------------------------------------------------------------- /client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom' 3 | import './index.css' 4 | import App from './App' 5 | import * as serviceWorker from './serviceWorker' 6 | 7 | ReactDOM.render(, document.getElementById('root')) 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister() 13 | -------------------------------------------------------------------------------- /client/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /client/src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ) 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void 26 | } 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL( 32 | (process as { env: { [key: string]: string } }).env.PUBLIC_URL, 33 | window.location.href 34 | ) 35 | if (publicUrl.origin !== window.location.origin) { 36 | // Our service worker won't work if PUBLIC_URL is on a different origin 37 | // from what our page is served on. This might happen if a CDN is used to 38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 39 | return 40 | } 41 | 42 | window.addEventListener('load', () => { 43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js` 44 | 45 | if (isLocalhost) { 46 | // This is running on localhost. Let's check if a service worker still exists or not. 47 | checkValidServiceWorker(swUrl, config) 48 | 49 | // Add some additional logging to localhost, pointing developers to the 50 | // service worker/PWA documentation. 51 | navigator.serviceWorker.ready.then(() => { 52 | console.log( 53 | 'This web app is being served cache-first by a service ' + 54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 55 | ) 56 | }) 57 | } else { 58 | // Is not localhost. Just register service worker 59 | registerValidSW(swUrl, config) 60 | } 61 | }) 62 | } 63 | } 64 | 65 | function registerValidSW(swUrl: string, config?: Config) { 66 | navigator.serviceWorker 67 | .register(swUrl) 68 | .then(registration => { 69 | registration.onupdatefound = () => { 70 | const installingWorker = registration.installing 71 | if (installingWorker == null) { 72 | return 73 | } 74 | installingWorker.onstatechange = () => { 75 | if (installingWorker.state === 'installed') { 76 | if (navigator.serviceWorker.controller) { 77 | // At this point, the updated precached content has been fetched, 78 | // but the previous service worker will still serve the older 79 | // content until all client tabs are closed. 80 | console.log( 81 | 'New content is available and will be used when all ' + 82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 83 | ) 84 | 85 | // Execute callback 86 | if (config && config.onUpdate) { 87 | config.onUpdate(registration) 88 | } 89 | } else { 90 | // At this point, everything has been precached. 91 | // It's the perfect time to display a 92 | // "Content is cached for offline use." message. 93 | console.log('Content is cached for offline use.') 94 | 95 | // Execute callback 96 | if (config && config.onSuccess) { 97 | config.onSuccess(registration) 98 | } 99 | } 100 | } 101 | } 102 | } 103 | }) 104 | .catch(error => { 105 | console.error('Error during service worker registration:', error) 106 | }) 107 | } 108 | 109 | function checkValidServiceWorker(swUrl: string, config?: Config) { 110 | // Check if the service worker can be found. If it can't reload the page. 111 | fetch(swUrl) 112 | .then(response => { 113 | // Ensure service worker exists, and that we really are getting a JS file. 114 | const contentType = response.headers.get('content-type') 115 | if ( 116 | response.status === 404 || 117 | (contentType != null && contentType.indexOf('javascript') === -1) 118 | ) { 119 | // No service worker found. Probably a different app. Reload the page. 120 | navigator.serviceWorker.ready.then(registration => { 121 | registration.unregister().then(() => { 122 | window.location.reload() 123 | }) 124 | }) 125 | } else { 126 | // Service worker found. Proceed as normal. 127 | registerValidSW(swUrl, config) 128 | } 129 | }) 130 | .catch(() => { 131 | console.log('No internet connection found. App is running in offline mode.') 132 | }) 133 | } 134 | 135 | export function unregister() { 136 | if ('serviceWorker' in navigator) { 137 | navigator.serviceWorker.ready.then(registration => { 138 | registration.unregister() 139 | }) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /client/src/theme.ts: -------------------------------------------------------------------------------- 1 | export const primaryColor = '#ffa500' 2 | export const primaryLightColor = '#ffd64a' 3 | export const primaryDarkColor = '#c67600' 4 | export const secondaryColor = '#424242' 5 | export const secondaryLightColor = '#6d6d6d' 6 | export const secondaryDarkColor = '#1b1b1b' 7 | export const primaryTextColor = '#424242' 8 | export const secondaryTextColor = '#ffffff' 9 | 10 | export const sizingUnit = 8 11 | -------------------------------------------------------------------------------- /client/stories/Command.stories.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react' 2 | 3 | import { storiesOf } from '@storybook/react' 4 | import { withKnobs, number } from '@storybook/addon-knobs' 5 | import { action } from '@storybook/addon-actions' 6 | import { Command } from '../src/Command' 7 | import { ControlCommand } from '../src/ControlCommand' 8 | import { center } from '../.storybook/decorators' 9 | 10 | type Props = { 11 | children: ReactNode 12 | } 13 | 14 | function CommandContainer(props: Props) { 15 | return ( 16 |
24 | {props.children} 25 |
26 | ) 27 | } 28 | 29 | storiesOf('Command', module) 30 | .addDecorator(withKnobs) 31 | .addDecorator(center) 32 | .add('default', () => ( 33 | 34 | 43 | 44 | )) 45 | .add('control commands', () => ( 46 |
47 | 48 | 49 | 50 | 51 | 52 | 53 |
54 | )) 55 | .add('multiple', () => ( 56 |
57 | 58 | 67 | 68 | 69 | 78 | 79 | 80 | 89 | 90 | 91 | 100 | 101 | 102 | 111 | 112 | 113 | 122 | 123 |
124 | )) 125 | -------------------------------------------------------------------------------- /client/stories/CommandBoard.stories.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | import { storiesOf } from '@storybook/react' 4 | 5 | import { CommandBoard } from '../src/CommandBoard' 6 | 7 | storiesOf('CommandBoard', module).add('default', () => ) 8 | -------------------------------------------------------------------------------- /client/stories/PlayStopIcon.stories.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react' 2 | 3 | import { storiesOf } from '@storybook/react' 4 | 5 | import { PlayStopIcon } from '../src/PlayStopIcon' 6 | 7 | function PlayStopIconContainer() { 8 | const [isPlaying, setIsPlaying] = useState(true) 9 | return ( 10 |
11 | setIsPlaying(oldIsPlaying => !oldIsPlaying)} 14 | /> 15 |
16 | ) 17 | } 18 | 19 | storiesOf('PlayStopIcon', module).add('default', () => ) 20 | -------------------------------------------------------------------------------- /client/stories/ServerConnectIcon.stories.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react' 2 | 3 | import { storiesOf } from '@storybook/react' 4 | 5 | import { ServerConnectIcon } from '../src/ServerConnectIcon' 6 | 7 | function ServerConnectIconContainer() { 8 | const [isConnected, setIsConnected] = useState(true) 9 | return ( 10 |
11 | { 14 | setIsConnected(oldIsConnected => !oldIsConnected) 15 | }} 16 | /> 17 |
18 | ) 19 | } 20 | 21 | storiesOf('ServerConnectIcon', module).add('default', () => ( 22 | 23 | )) 24 | -------------------------------------------------------------------------------- /client/stories/index.stories.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | import { storiesOf } from '@storybook/react' 4 | import { action } from '@storybook/addon-actions' 5 | 6 | import { ReactNode } from 'react' 7 | 8 | type Props = { 9 | onClick: () => void 10 | children?: ReactNode 11 | } 12 | 13 | function Button(props: Props) { 14 | return 15 | } 16 | 17 | storiesOf('Button', module) 18 | .add('with text', () => ) 19 | .add('with some emoji', () => ( 20 | 25 | )) 26 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "rootDirs": [ 4 | "src", 5 | "stories" 6 | ], 7 | "baseUrl": "src", 8 | "target": "es5", 9 | "lib": [ 10 | "dom", 11 | "dom.iterable", 12 | "esnext" 13 | ], 14 | "allowJs": true, 15 | "skipLibCheck": true, 16 | "esModuleInterop": true, 17 | "allowSyntheticDefaultImports": true, 18 | "strict": true, 19 | "forceConsistentCasingInFileNames": true, 20 | "module": "esnext", 21 | "moduleResolution": "node", 22 | "resolveJsonModule": true, 23 | "isolatedModules": true, 24 | "noEmit": true, 25 | "jsx": "preserve" 26 | }, 27 | "include": [ 28 | "src", 29 | "stories" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ragnar-H/TelloGo/cc3950588b70e4539d7522502e522fe9f30af6d1/demo.gif -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | server: 4 | build: ./server 5 | ports: 6 | # Note that you need to forward a large range of ports for WebRTC 7 | # https://stackoverflow.com/questions/29563830/use-specific-ports-for-webrtc 8 | - "8089:8089/udp" # Drone 9 | - "8090:8090/udp" # Drone 10 | - "11111:11111/udp" # Drone 11 | - "6038:6038/udp" # Drone 12 | - "50000:50000" # API Server 13 | client: 14 | build: ./client 15 | ports: 16 | - "5000:5000" 17 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ragnar-h/TelloGo 2 | 3 | go 1.12 4 | 5 | require github.com/pion/webrtc/v2 v2.0.14 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cheekybits/genny v1.0.0/go.mod h1:+tQajlRqAUrPI7DOSpB0XAqZYtQakVtB7wXkRAgjxjQ= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 5 | github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 6 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 7 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 8 | github.com/lucas-clemente/quic-go v0.7.1-0.20190401152353-907071221cf9/go.mod h1:PpMmPfPKO9nKJ/psF49ESTAGQSdfXxlg1otPbEB2nOw= 9 | github.com/marten-seemann/qtls v0.2.3/go.mod h1:xzjG7avBwGGbdZ8dTGxlBnLArsVKLvwmjgmPuiQEcYk= 10 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 11 | github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 12 | github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 13 | github.com/pion/datachannel v1.4.3 h1:tqS6YiqqAiFCxGGhvn1K7fHEzemK9Aov025dE/isGFo= 14 | github.com/pion/datachannel v1.4.3/go.mod h1:SpMJbuu8v+qbA94m6lWQwSdCf8JKQvgmdSHDNtcbe+w= 15 | github.com/pion/dtls v1.3.4 h1:MdOMsCfd44m2iTrxtkzA6UndvYVjLWWjua7hxU8EXEA= 16 | github.com/pion/dtls v1.3.4/go.mod h1:CjlPLfQdsTg3G4AEXjJp8FY5bRweBlxHrgoFrN+fQsk= 17 | github.com/pion/ice v0.2.6 h1:N/xhQtO6WfWlyMvIZgE+cqG5AHJnKL+aEboade72qno= 18 | github.com/pion/ice v0.2.6/go.mod h1:igvbO76UeYthbSu0UsUTqjyWpFT3diUmM+x2vt4p4fw= 19 | github.com/pion/logging v0.2.1 h1:LwASkBKZ+2ysGJ+jLv1E/9H1ge0k1nTfi1X+5zirkDk= 20 | github.com/pion/logging v0.2.1/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= 21 | github.com/pion/quic v0.1.1/go.mod h1:zEU51v7ru8Mp4AUBJvj6psrSth5eEFNnVQK5K48oV3k= 22 | github.com/pion/rtcp v1.2.0 h1:rT2FptW5YHIern+4XlbGYnnsT26XGxurnkNLnzhtDXg= 23 | github.com/pion/rtcp v1.2.0/go.mod h1:a5dj2d6BKIKHl43EnAOIrCczcjESrtPuMgfmL6/K6QM= 24 | github.com/pion/rtp v1.1.2 h1:ERNugzYHW9F2ldpwoARbeFGKRoq1REe5Jxdjvm/rOx8= 25 | github.com/pion/rtp v1.1.2/go.mod h1:/l4cvcKd0D3u9JLs2xSVI95YkfXW87a3br3nqmVtSlE= 26 | github.com/pion/sctp v1.6.3 h1:SC4vKOjcddK8tXiTNj05a+0/GyPpCmuNfeBA/rzNFqs= 27 | github.com/pion/sctp v1.6.3/go.mod h1:cCqpLdYvgEUdl715+qbWtgT439CuQrAgy8BZTp0aEfA= 28 | github.com/pion/sdp/v2 v2.1.1 h1:i3fAyjiLuQseYNo0BtCOPfzp91Ppb7vasRGmUUTog28= 29 | github.com/pion/sdp/v2 v2.1.1/go.mod h1:idSlWxhfWQDtTy9J05cgxpHBu/POwXN2VDRGYxT/EjU= 30 | github.com/pion/srtp v1.2.4 h1:wwGKC5ewuBukkZ+i+pZ8aO33+t6z2y/XRiYtyP0Xpv0= 31 | github.com/pion/srtp v1.2.4/go.mod h1:52qiP0g3FVMG/5NL6Ko8Vr2qirevKH+ukYbNS/4EX40= 32 | github.com/pion/stun v0.2.1 h1:rSKJ0ynYkRalRD8BifmkaGLeepCFuGTwG6FxPsrPK8o= 33 | github.com/pion/stun v0.2.1/go.mod h1:TChCNKgwnFiFG/c9K+zqEdd6pO6tlODb9yN1W/zVfsE= 34 | github.com/pion/transport v0.6.0/go.mod h1:iWZ07doqOosSLMhZ+FXUTq+TamDoXSllxpbGcfkCmbE= 35 | github.com/pion/transport v0.7.0 h1:EsXN8TglHMlKZMo4ZGqwK6QgXBu0WYg7wfGMWIXsS+w= 36 | github.com/pion/transport v0.7.0/go.mod h1:iWZ07doqOosSLMhZ+FXUTq+TamDoXSllxpbGcfkCmbE= 37 | github.com/pion/webrtc/v2 v2.0.14 h1:DTbZJKfBZUgS4quwEVYvw7aO+S04ru6+b60VYtWfhuE= 38 | github.com/pion/webrtc/v2 v2.0.14/go.mod h1:ovVq/ED/KYNHWEzbKx7ecLZ9juWgptg0uniZIdJxWbg= 39 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 40 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 41 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 42 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 43 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 44 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 45 | golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 46 | golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5 h1:bselrhR0Or1vomJZC8ZIjWtbDmn9OYFLX5Ik9alpJpE= 47 | golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= 48 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 49 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 50 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 51 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 52 | golang.org/x/sys v0.0.0-20190228124157-a34e9553db1e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 53 | golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 54 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 55 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 56 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 57 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 58 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 59 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | MAKEFLAGS += -j2 2 | 3 | all: start_client start_server 4 | 5 | install: install_client install_server 6 | 7 | start_client: 8 | cd client && yarn start 9 | 10 | start_server: 11 | cd server && go run . 12 | 13 | start_server_dev: 14 | cd server && GST_DEBUG=*:3 go run . -video-src "videotestsrc" 15 | 16 | install_client: 17 | cd client && yarn install 18 | 19 | install_server: 20 | cd server && go install . -------------------------------------------------------------------------------- /server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.12.1-alpine3.9 as build 2 | RUN apk add --update git 3 | ENV GO111MODULE=on 4 | 5 | WORKDIR /src/app 6 | COPY go.mod go.sum ./ 7 | RUN go mod download 8 | 9 | COPY . ./ 10 | RUN go install 11 | 12 | FROM alpine:3.9 13 | COPY --from=build /go/bin/TelloGo /app 14 | # EXPOSE 50000 15 | ENTRYPOINT ./app -------------------------------------------------------------------------------- /server/gst.c: -------------------------------------------------------------------------------- 1 | #include "gst.h" 2 | 3 | #include 4 | 5 | typedef struct SampleHandlerUserData { 6 | int pipelineId; 7 | } SampleHandlerUserData; 8 | 9 | GMainLoop *gstreamer_send_main_loop = NULL; 10 | void gstreamer_send_start_mainloop(void) { 11 | gstreamer_send_main_loop = g_main_loop_new(NULL, FALSE); 12 | 13 | g_main_loop_run(gstreamer_send_main_loop); 14 | } 15 | 16 | static gboolean gstreamer_send_bus_call(GstBus *bus, GstMessage *msg, gpointer data) { 17 | switch (GST_MESSAGE_TYPE(msg)) { 18 | 19 | case GST_MESSAGE_EOS: 20 | g_print("End of stream\n"); 21 | exit(1); 22 | break; 23 | 24 | case GST_MESSAGE_ERROR: { 25 | gchar *debug; 26 | GError *error; 27 | 28 | gst_message_parse_error(msg, &error, &debug); 29 | g_free(debug); 30 | 31 | g_printerr("Error: %s\n", error->message); 32 | g_error_free(error); 33 | exit(1); 34 | } 35 | default: 36 | break; 37 | } 38 | 39 | return TRUE; 40 | } 41 | 42 | GstFlowReturn gstreamer_send_new_sample_handler(GstElement *object, gpointer user_data) { 43 | GstSample *sample = NULL; 44 | GstBuffer *buffer = NULL; 45 | gpointer copy = NULL; 46 | gsize copy_size = 0; 47 | SampleHandlerUserData *s = (SampleHandlerUserData *)user_data; 48 | 49 | g_signal_emit_by_name (object, "pull-sample", &sample); 50 | if (sample) { 51 | buffer = gst_sample_get_buffer(sample); 52 | if (buffer) { 53 | gst_buffer_extract_dup(buffer, 0, gst_buffer_get_size(buffer), ©, ©_size); 54 | goHandlePipelineBuffer(copy, copy_size, GST_BUFFER_DURATION(buffer), s->pipelineId); 55 | } 56 | gst_sample_unref (sample); 57 | } 58 | 59 | return GST_FLOW_OK; 60 | } 61 | 62 | GstElement *gstreamer_send_create_pipeline(char *pipeline) { 63 | gst_init(NULL, NULL); 64 | GError *error = NULL; 65 | return gst_parse_launch(pipeline, &error); 66 | } 67 | 68 | void gstreamer_send_start_pipeline(GstElement *pipeline, int pipelineId) { 69 | SampleHandlerUserData *s = calloc(1, sizeof(SampleHandlerUserData)); 70 | s->pipelineId = pipelineId; 71 | 72 | GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline)); 73 | gst_bus_add_watch(bus, gstreamer_send_bus_call, NULL); 74 | gst_object_unref(bus); 75 | 76 | GstElement *appsink = gst_bin_get_by_name(GST_BIN(pipeline), "appsink"); 77 | g_object_set(appsink, "emit-signals", TRUE, NULL); 78 | g_signal_connect(appsink, "new-sample", G_CALLBACK(gstreamer_send_new_sample_handler), s); 79 | gst_object_unref(appsink); 80 | 81 | gst_element_set_state(pipeline, GST_STATE_PLAYING); 82 | } 83 | 84 | void gstreamer_send_stop_pipeline(GstElement *pipeline) { 85 | gst_element_set_state(pipeline, GST_STATE_NULL); 86 | } 87 | 88 | 89 | -------------------------------------------------------------------------------- /server/gst.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo pkg-config: gstreamer-1.0 gstreamer-app-1.0 5 | 6 | #include "gst.h" 7 | 8 | */ 9 | import "C" 10 | import ( 11 | "fmt" 12 | "sync" 13 | "unsafe" 14 | 15 | "github.com/pion/webrtc/v2" 16 | "github.com/pion/webrtc/v2/pkg/media" 17 | ) 18 | 19 | func init() { 20 | go C.gstreamer_send_start_mainloop() 21 | } 22 | 23 | // Pipeline is a wrapper for a GStreamer Pipeline 24 | type Pipeline struct { 25 | Pipeline *C.GstElement 26 | tracks []*webrtc.Track 27 | id int 28 | codecName string 29 | } 30 | 31 | var pipelines = make(map[int]*Pipeline) 32 | var pipelinesLock sync.Mutex 33 | 34 | // CreateMyPipeline creates a GStreamer Pipeline 35 | func CreateMyPipeline(codecName string, tracks []*webrtc.Track, pipelineSrc string) *Pipeline { 36 | fmt.Println("creating a pipeline") 37 | pipelineStr := "appsink name=appsink" 38 | switch codecName { 39 | case webrtc.VP8: 40 | pipelineStr = pipelineSrc + " ! vp8enc error-resilient=partitions keyframe-max-dist=10 auto-alt-ref=true cpu-used=5 deadline=1 ! " + pipelineStr 41 | case webrtc.VP9: 42 | pipelineStr = pipelineSrc + " ! vp9enc ! " + pipelineStr 43 | case webrtc.H264: 44 | pipelineStr = pipelineSrc + " ! video/x-raw,format=I420 ! x264enc bframes=0 speed-preset=veryfast key-int-max=60 ! video/x-h264,stream-format=byte-stream ! " + pipelineStr 45 | case webrtc.Opus: 46 | pipelineStr = pipelineSrc + " ! opusenc ! " + pipelineStr 47 | case webrtc.G722: 48 | pipelineStr = pipelineSrc + " ! avenc_g722 ! " + pipelineStr 49 | default: 50 | panic("Unhandled codec " + codecName) 51 | } 52 | 53 | pipelineStrUnsafe := C.CString(pipelineStr) 54 | defer C.free(unsafe.Pointer(pipelineStrUnsafe)) 55 | 56 | pipelinesLock.Lock() 57 | defer pipelinesLock.Unlock() 58 | 59 | pipeline := &Pipeline{ 60 | Pipeline: C.gstreamer_send_create_pipeline(pipelineStrUnsafe), 61 | tracks: tracks, 62 | id: len(pipelines), 63 | codecName: codecName, 64 | } 65 | 66 | pipelines[pipeline.id] = pipeline 67 | return pipeline 68 | } 69 | 70 | // Start starts the GStreamer Pipeline 71 | func (p *Pipeline) Start() { 72 | C.gstreamer_send_start_pipeline(p.Pipeline, C.int(p.id)) 73 | } 74 | 75 | // Stop stops the GStreamer Pipeline 76 | func (p *Pipeline) Stop() { 77 | C.gstreamer_send_stop_pipeline(p.Pipeline) 78 | } 79 | 80 | const ( 81 | videoClockRate = 90000 82 | audioClockRate = 48000 83 | ) 84 | 85 | //export goHandlePipelineBuffer 86 | func goHandlePipelineBuffer(buffer unsafe.Pointer, bufferLen C.int, duration C.int, pipelineID C.int) { 87 | pipelinesLock.Lock() 88 | pipeline, ok := pipelines[int(pipelineID)] 89 | pipelinesLock.Unlock() 90 | 91 | if ok { 92 | var samples uint32 93 | if pipeline.codecName == webrtc.Opus { 94 | samples = uint32(audioClockRate * (float32(duration) / 1000000000)) 95 | } else { 96 | samples = uint32(videoClockRate * (float32(duration) / 1000000000)) 97 | } 98 | for _, t := range pipeline.tracks { 99 | if err := t.WriteSample(media.Sample{Data: C.GoBytes(buffer, bufferLen), Samples: samples}); err != nil { 100 | panic(err) 101 | } 102 | } 103 | } else { 104 | fmt.Printf("discarding buffer, no pipeline with id %d", int(pipelineID)) 105 | } 106 | C.free(buffer) 107 | } 108 | -------------------------------------------------------------------------------- /server/gst.h: -------------------------------------------------------------------------------- 1 | #ifndef GST_H 2 | #define GST_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | extern void goHandlePipelineBuffer(void *buffer, int bufferLen, int samples, int pipelineId); 10 | 11 | GstElement *gstreamer_send_create_pipeline(char *pipeline); 12 | void gstreamer_send_start_pipeline(GstElement *pipeline, int pipelineId); 13 | void gstreamer_send_stop_pipeline(GstElement *pipeline); 14 | void gstreamer_send_start_mainloop(void); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println("Starting the server") 7 | Server() 8 | } 9 | -------------------------------------------------------------------------------- /server/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "fmt" 7 | "math/rand" 8 | "net/http" 9 | 10 | "github.com/pion/webrtc/v2" 11 | ) 12 | 13 | // Server sets up an endpoint that negotiates and creates WebRTC 14 | func Server() { 15 | address := flag.String("address", ":50000", "Address to host the HTTP server on.") 16 | videoSrc := flag.String("video-src", gstreamerCommand, "GStreamer video src") 17 | flag.Parse() 18 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 19 | fmt.Println("Got a request") 20 | setupResponse(&w, r) 21 | if (*r).Method == "OPTIONS" { 22 | // Handle CORS 23 | return 24 | } 25 | 26 | var offer webrtc.SessionDescription 27 | 28 | err := json.NewDecoder(r.Body).Decode(&offer) 29 | if err != nil { 30 | panic(err) 31 | } 32 | 33 | tello := NewTello() 34 | // Start new peerConnection and create answer 35 | answer := droneWebRTC(offer, *videoSrc, tello) 36 | 37 | err = json.NewEncoder(w).Encode(answer) 38 | if err != nil { 39 | panic(err) 40 | } 41 | }) 42 | 43 | go func() { 44 | panic(http.ListenAndServe(*address, nil)) 45 | }() 46 | fmt.Println("Listening on", *address) 47 | // Block forever 48 | select {} 49 | } 50 | 51 | func setupResponse(w *http.ResponseWriter, req *http.Request) { 52 | (*w).Header().Set("Access-Control-Allow-Origin", "*") 53 | (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") 54 | (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") 55 | } 56 | 57 | func droneWebRTC(offer webrtc.SessionDescription, videoSrc string, tello Tello) webrtc.SessionDescription { 58 | config := webrtc.Configuration{ 59 | ICEServers: []webrtc.ICEServer{ 60 | { 61 | URLs: []string{"stun:stun.l.google.com:19302"}, 62 | }, 63 | }, 64 | } 65 | m := webrtc.MediaEngine{} 66 | m.RegisterCodec(webrtc.NewRTPVP8Codec(webrtc.DefaultPayloadTypeVP8, 90000)) 67 | 68 | api := webrtc.NewAPI(webrtc.WithMediaEngine(m)) 69 | // Create a new RTCPeerConnection 70 | peerConnection, err := api.NewPeerConnection(config) 71 | if err != nil { 72 | panic(err) 73 | } 74 | 75 | // Setup tracks and event handlers 76 | firstVideoTrack, err := peerConnection.NewTrack(webrtc.DefaultPayloadTypeVP8, rand.Uint32(), "video", "droneStream") 77 | if err != nil { 78 | panic(err) 79 | } 80 | _, err = peerConnection.AddTrack(firstVideoTrack) 81 | if err != nil { 82 | panic(err) 83 | } 84 | 85 | peerConnection.OnDataChannel(func(d *webrtc.DataChannel) { 86 | fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID()) 87 | 88 | // Register channel opening handling 89 | d.OnOpen(func() { 90 | fmt.Printf("Data channel '%s'-'%d' open.\n", d.Label(), d.ID()) 91 | }) 92 | 93 | // Register text message handling 94 | d.OnMessage(func(msg webrtc.DataChannelMessage) { 95 | fmt.Printf("Message from DataChannel '%s': '%s'\n", d.Label(), string(msg.Data)) 96 | tello.sendCommand(string(msg.Data)) 97 | }) 98 | }) 99 | 100 | CreateMyPipeline(webrtc.VP8, []*webrtc.Track{firstVideoTrack}, videoSrc).Start() 101 | 102 | // Answer WebRTC 103 | 104 | err = peerConnection.SetRemoteDescription(offer) 105 | if err != nil { 106 | panic(err) 107 | } 108 | 109 | answer, err := peerConnection.CreateAnswer(nil) 110 | if err != nil { 111 | panic(err) 112 | } 113 | 114 | // Sets the LocalDescription, and starts our UDP listeners 115 | err = peerConnection.SetLocalDescription(answer) 116 | if err != nil { 117 | panic(err) 118 | } 119 | 120 | return answer 121 | } 122 | -------------------------------------------------------------------------------- /server/tello.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "strconv" 7 | ) 8 | 9 | const ( 10 | udpAddr = "192.168.10.1" 11 | commandPort = 8889 12 | gstreamerCommand = `udpsrc port=11111 caps="video/x-h264, stream-format=(string)byte-stream, width=(int)960, height=(int)720, framerate=(fraction)24/1, skip-first-bytes=2" ! decodebin ! videoconvert ! queue` 13 | ) 14 | 15 | // Tello is a thin layer ontop of 16 | // https://terra-1-g.djicdn.com/2d4dce68897a46b19fc717f3576b7c6a/Tello%20%E7%BC%96%E7%A8%8B%E7%9B%B8%E5%85%B3/For%20Tello/Tello%20SDK%20Documentation%20EN_1.3_1122.pdf 17 | type Tello struct { 18 | commandConnection net.Conn 19 | } 20 | 21 | // NewTello initializes Tello 22 | func NewTello() Tello { 23 | droneConnection, err := net.Dial("udp4", udpAddr+":"+strconv.Itoa(commandPort)) 24 | if err != nil { 25 | fmt.Println(err) 26 | } 27 | 28 | return Tello{commandConnection: droneConnection} 29 | } 30 | 31 | func (tello *Tello) sendCommand(command string) { 32 | payload := []byte(command) 33 | tello.commandConnection.Write((payload)) 34 | } 35 | 36 | func (tello *Tello) connect() { 37 | tello.sendCommand("command") 38 | } 39 | 40 | func (tello *Tello) streamOn() { 41 | tello.sendCommand("streamon") 42 | } 43 | 44 | func (tello *Tello) streamOff() { 45 | tello.sendCommand("streamoff") 46 | } 47 | 48 | func (tello *Tello) land() { 49 | tello.sendCommand("land") 50 | } 51 | 52 | func (tello *Tello) takeOff() { 53 | tello.sendCommand("takeoff") 54 | } 55 | 56 | func (tello *Tello) down(downCommand string) { 57 | tello.sendCommand(downCommand) 58 | } 59 | --------------------------------------------------------------------------------