Professional Documents
Culture Documents
Getting Started With Iot Using A Raspberry Pi and Python
Getting Started With Iot Using A Raspberry Pi and Python
Quelle: https://zoetrope.io/tech-blog/brief-practical-introduction-mqtt-protocol-and-its-application-iot
XMPP Implementation: Eclipse Mosquitto
FROM ubuntu:14.04
Documentation: https://pypi.python.org/pypi/paho-mqtt/
Source: https://github.com/eclipse/paho.mqtt.python
MQTT: Subscribe
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
host = "192.168.99.100"
print("Connecting to " + host)
client.connect(host, port=1883, keepalive=60)
client.loop_forever()
MQTT: Publish
# The callback for when a PUBLISH message is received from the server.
# unused for this demo
def on_publish(client, userdata, mid):
pass
client = mqtt.Client()
client.on_connect = on_connect
client.on_publish = on_publish
host = "192.168.99.100"
client.connect(host, port=1883, keepalive=60)
client.loop_start()
topic = "SensorXY"
s = ""
while s != "exit":
s = input("payload >")
client.publish(topic, s)
client.loop_stop()
Simple example: Remote-control a light from anywhere in the world
In the first example we turn on/off a LED using MQTT. The LED is connected
on GPIO Pin 11 (GPIO 17)
https://ms-iot.github.io/content/en-US/win10/samples/PinMappingsRPi2.htm
How it works:
Controller
Interface
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
s = str(msg.payload, encoding="ascii")
print("retrieved message: " + s)
if s == "lighton":
GPIO.output(LedPin, GPIO.LOW)
elif s == "lightoff":
GPIO.output(LedPin, GPIO.HIGH)
# Initialize GPIO
LedPin = 11 # pin GPIO 17, change if you connect to other pin!
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LedPin, GPIO.OUT)
GPIO.output(LedPin, GPIO.HIGH) # turn off led
# Initialize MQTT
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
host = "192.168.99.100"
print("Connecting to " + host)
client.connect(host, port=1883, keepalive=60)
client.loop_forever()
import paho.mqtt.client as mqtt
client = mqtt.Client()
Control Raspberry Pi host = "192.168.99.100"
client.connect(host, port=1883,
keepalive=60)
client.loop_start()
topic = "Raspberry"
print("COMMANDS:")
print("0: turn light off")
print("1: turn light on")
print("3: quit application")
s=0
while s!=3:
s = int(input("command >"))
if s == 0:
client.publish(topic, "lightoff")
elif s == 1:
client.publish(topic, "lighton")
elif s == 3:
print("bye")
else:
print("unknown command")
client.loop_stop()
Dudas ?