樹莓派物聯(lián)網(wǎng)應(yīng)用基礎(chǔ)(4):Python物聯(lián)網(wǎng)MQTT聊天室
這實(shí)驗(yàn)是用一臺(tái)Windows計(jì)算機(jī)和一臺(tái)樹莓派分別運(yùn)行Python聊天室程序,在樹莓派運(yùn)行的程序加上有信息通訊小燈閃一下代碼。程序使用的是古德微機(jī)器人的MQTT服務(wù)器"www.gdwrobot.top", 1883。
演示視頻
一、以下是Windows系統(tǒng)計(jì)算機(jī)運(yùn)行的代碼:
#Python物聯(lián)網(wǎng):聊天室? windows
#!/usr/bin/env python
# coding: utf-8
#!/usr/bin/python
import paho.mqtt.client as mqtt
import time
import threading? ? ? ? #導(dǎo)入多線程庫(kù)
def talk1():? ? ? ? ? ? ? ? ?#輸入聊天內(nèi)容自定義函數(shù)
????? ? while True:
????????? ? ? ? time.sleep(0.1)
????????? ? ? ? txt=input('>>>>')
????????? ? ? ? client.publish('ospchatroom',txt)????????????#向MQTT發(fā)布主題,消息
def on_connect(client, userdata, flags, rc):? ? ? ? ? ??
? ? ? ?print("Connected with result code "+str(rc))
? ? ? ?client.subscribe("ospchatroom")? ? ? ? ? ##訂閱主題,主題名
def on_message(client, userdata, msg):?????????????????????????#函數(shù),獲得主題返回消息
? ????? #txt=str(msg.payload,encoding=='utf8')? ? ? ? ? ? ? ? #下面兩行代碼寫法測(cè)試時(shí)沒有返回信息
? ????? #print(txt)
? ? ????print(msg.topic + ":" + str(msg.payload, encoding="utf8"))? ? ? ? #用這行代碼寫法可以解決以上兩條代碼的問題
? ????? time.sleep(0.1)
? ? ? ? #return msg.payload????????????#這行代碼不用不影響功能
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("www.gdwrobot.top", 1883, 60)? ? ? ? # 60是keep alive的時(shí)間間隔
threading1=threading.Thread(target=talk1)? ? ? ? ? ? ? ? #talk1模塊加到多線程中
threading1.start()
client.loop_forever()????????????# 保持連接
二、以下是樹莓派運(yùn)行的代碼(加了代碼:當(dāng)接收到信息小燈閃一下):
#!/usr/bin/env python
# coding: utf-8
#!/usr/bin/python
import paho.mqtt.client as mqtt
import time
import RPi.GPIO as GPIO? ? #導(dǎo)入樹莓派BCM模塊
import threading
GPIO.setmode(GPIO.BCM)? ? #設(shè)置GPIO引腳為BCM編碼模式
GPIO.setup(5,GPIO.OUT)? ? #設(shè)置該端口為輸出模式
def talk1():
? ? while True:
? ? ? ? time.sleep(0.1)
? ? ? ? txt=input('>>>>')
? ? ? ? client.publish( 'ospchatroom' , txt? )? ? ? ? ? ? ?
def on_connect(client, userdata, flags, rc):? ? ? ? ? ? #連接MQTT函數(shù)
? ? print("Connected with result code "+str(rc))
? ? client.subscribe("ospchatroom")? ? ? ? ? ?#訂閱主題,同一主題名
def on_message(client, userdata, msg):? ? ? ?
? ? print(msg.topic + ":" + str(msg.payload, encoding="utf8"))
? ? GPIO.output(5,GPIO.HIGH)
? ? time.sleep(0.1)
? ? GPIO.output(5,GPIO.LOW)
? ? #return msg.payload????????????#這行代碼不用不影響功能
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("www.gdwrobot.top", 1883, 60)
threading1=threading.Thread(target=talk1)
threading1.start()
client.loop_forever()
參考:paho-mqtt·項(xiàng)目簡(jiǎn)介
https://pypi.org/project/paho-mqtt/