# MQTT python ###### tags: `python` `IoT` `MQTT` ## Free MQTT Broker   ## Download paho MQTT library ```bash! pip install paho-mqtt ``` ## Publish Client ### Inside temperature ```python= import paho.mqtt.client as mqtt from random import randrange, uniform import time #Connect to broker and create the client mqttBroker ="mqtt.eclipseprojects.io" client = mqtt.Client("Temperature_inside") client.connect(mqttBroker) while True: randNumber=uniform(25.0,26.0) #Definde a rand of the range client.publish("temperature",randNumber) #Difind the topic print("Inside temperature" + str(randNumber) + "to topic: temperature") # print waht action happen in public client time.sleep(1) ``` Result  ### Outside temperature ```python= import paho.mqtt.client as mqtt from random import randrange, uniform import time #Connect to broker and create the client mqttBroker ="mqtt.eclipseprojects.io" client = mqtt.Client("Temperature_outside") client.connect(mqttBroker) while True: randNumber=uniform(30.0,31.0) client.publish("temperature",randNumber) print("Outside temerature " + str(randNumber) + "to topic: temperature") time.sleep(1) ``` Result  ## Subscribe client ### Smartphone ```python= import paho.mqtt.client as mqtt import time #Connect to broker and create the client mqttBroker ="mqtt.eclipseprojects.io" client = mqtt.Client("Smartphone") client.connect(mqttBroker) def callBackMessage(client, userdata, message): print("Received message:" , str(message.payload.decode("utf-8"))) client.loop_start() client.subscribe('temperature') client.on_message = callBackMessage time.sleep(30) client.loop_end() ``` Result 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up