樹莓派mqtt通訊

一、sudo pip install paho-mqttpython

二、python代碼json

# -*- 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")oop

# 消息推送回調函數 .decode("utf-8")
def on_message(client, userdata, msg):spa

    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)code

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()ip

發送數據爲{"pin":12,"value":1}utf-8

相關文章
相關標籤/搜索