订阅消息
#!/usr/bin/python
-- coding:utf-8 --
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))
def on_message(client, userdata, msg):
# print(msg.topic + " " + str(msg.payload))
mes = msg.payload
print mes
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect(‘127.0.0.1’, 1883, 600) # 600为keepalive的时间间隔
client.subscribe(‘A’, qos=0)
client.loop_forever() # 保持连接
推送消息
#!/usr/bin/python
-- coding:utf-8 --
import paho.mqtt.client as mqtt
import os
def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
def publish(ip, post, live_time, name, info):
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(ip, post, live_time) # 600为keepalive的时间间隔
client.publish(name, payload=str(info), qos=0)
if name == ‘main’:
ip1 = '127.0.0.1"
post1 = 1883
live_time1 = 600
name1 = ‘A’
info1 = os.getenv(‘PARAMS’)
publish(ip1, post1, live_time1, name1, info1)