您好,登录后才能下订单哦!
这篇文章主要为大家展示了“树莓派如何实现mqtt通信”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“树莓派如何实现mqtt通信”这篇文章吧。
1、sudo pip install paho-mqtt
2、python代码
# -*- coding: utf-8 -*- 
 import paho.mqtt.client as mqtt
 # import RPi.GPIO as GPIO
 import json,sys
 # if sys.version_info < (3, 0):
 #     reload(sys)
 #     sys.setdefaultencoding('utf8')
 # else:
 #     raw_input = input
 username='public'
 password='123456'
 hostname='xxx.xxx.xxx.xxx'
# BCM GPIO编号
 pins = [17,18,27,22,23,24,25,4]
 def gpio_setup():
     # 采用BCM编号
     GPIO.setmode(GPIO.BCM)
     # 设置所有GPIO为输出状态,且输出低电平
     for pin in pins:
         GPIO.setup(pin, GPIO.OUT)
         GPIO.output(pin, GPIO.LOW)
        
 def gpio_destroy():
     for pin in pins:
         GPIO.output(pin, GPIO.LOW)
         GPIO.setup(pin, GPIO.IN)
        
 # 连接成功回调函数
 def on_connect(client, userdata, flags, rc):
     print("Connected with result code " + str(rc))
     # 连接完成之后订阅gpio主题
     client.subscribe("gpio")
# 消息推送回调函数 .decode("utf-8")
 def on_message(client, userdata, msg):
    print(msg.topic+""+str(msg.payload))
     #获得负载中的pin 和 value
     # gpio = json.loads(str(msg.payload))
    # if gpio['pin'] in pins:
     #     if gpio['value'] == 0:
     #         GPIO.output(gpio['pin'], GPIO.LOW)
     #     else:
     #         GPIO.output(gpio['pin'], GPIO.HIGH)
if __name__ == '__main__':
     client = mqtt.Client()
     client.on_connect = on_connect
     client.on_message = on_message
     # gpio_setup()
    
     try:
         # 请根据实际情况改变MQTT代理服务器的IP地址及账户密码认证
         #client.username_pw_set(username,password)
         client.connect("xxx.xxx.xxx.xxx", 1883, 60)
         client.loop_forever()
     except KeyboardInterrupt:
         client.disconnect()
         gpio_destroy()
发送数据为{"pin":12,"value":1}
以上是“树莓派如何实现mqtt通信”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。