Last active
December 22, 2017 12:48
-
-
Save tomoto/deaab1ee37a1b51f4fc05d91811146da to your computer and use it in GitHub Desktop.
Controlling drone by MQTT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import logging | |
logging.basicConfig(level=logging.DEBUG) | |
logger = logging.getLogger("main") | |
# Mambo | |
from Mambo import Mambo | |
import random | |
def create_mambo(): | |
# you will need to change this to the address of YOUR mambo | |
mamboAddr = "00:00:00:00:00:00" | |
return Mambo(mamboAddr, 4) | |
def connect_mambo(mambo): | |
logger.info("Connecting to Mambo...") | |
success = mambo.connect(num_retries=3) | |
logger.info("Mambo connected: %s" % success) | |
# MQTT | |
import paho.mqtt.client as mqtt | |
import json | |
TOKEN = "<YOUR TOKEN>" | |
HOSTNAME = "api.beebotte.com" | |
PORT = 1883 | |
TOPIC = "<YOUR CHANNEL>/<YOUR RESOURCE>" | |
def on_connect(client, mambo, flags, response_code): | |
logger.info("MQTT broker connected. %s" % response_code) | |
client.subscribe(TOPIC) | |
def on_message(client, mambo, msg): | |
logger.debug("Entering to on_message"); | |
data = json.loads(msg.payload.decode("utf-8")) | |
logger.info(data) | |
command = data[u'data'][u'command'].strip() | |
if u'take off' in command: | |
logger.info('Taking off!') | |
mambo.takeoff() | |
if u'land' in command: | |
logger.info('Landing!') | |
mambo.land() | |
if u'flip' in command: | |
logger.info('Flipping!') | |
mambo.flip(random.choice(['front', 'back'])) | |
if u'turn' in command: | |
logger.info('Turning!') | |
mambo.turn_degrees(180) | |
if u'higher' in command: | |
logger.info('Going up!') | |
mambo.fly_direct(0, 0, 0, 50, 1) | |
if u'lower' in command: | |
logger.info('Going down!') | |
mambo.fly_direct(0, 0, 0, -50, 1) | |
logger.debug("Exiting from on_message"); | |
def main(): | |
mambo = create_mambo() | |
connect_mambo(mambo) | |
client = mqtt.Client(userdata=mambo) | |
client.username_pw_set("token:%s" % TOKEN) | |
client.on_connect = on_connect | |
client.on_message = on_message | |
client.connect(HOSTNAME, port=PORT, keepalive=60) | |
logger.info("Connecting to MQTT broker...") | |
while True: | |
logger.debug("Requesting state update...") | |
mambo.ask_for_state_update() | |
for i in range(0, 10): | |
client.loop() | |
mambo.smart_sleep(0.1) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment