當前位置:首頁 > IT技術 > 編程語言 > 正文

Python連接巴法云,通過mqtt協(xié)議,和tcp協(xié)議
2021-10-21 23:07:26

第一,tcp協(xié)議連接

說明:
tcp服務器地址:bemfa.com 端口 8344

tcp協(xié)議詳細訂閱、發(fā)布指令,見接入文檔:點擊跳轉

# -*- coding: utf-8
import socket
import threading

def connTCP():
    global tcp_client_socket
    # 創(chuàng)建socket
    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # IP 和端口
    server_ip = 'bemfa.com'
    server_port = 8344
    try:
        # 連接服務器
        tcp_client_socket.connect((server_ip, server_port))
        #發(fā)送訂閱指令
        substr = 'cmd=1&uid=4d9ec352e0376f2110a0c601a2857225&topic=led002
'
        tcp_client_socket.send(substr.encode("utf-8"))
    except:
        time.sleep(2)
        connTCP()

#心跳
def Ping():
    # 發(fā)送心跳
    try:
        keeplive = 'ping
'
        tcp_client_socket.send(keeplive.encode("utf-8"))
    except:
        time.sleep(2)
        connTCP()
    #開啟定時,30秒發(fā)送一次心跳
    t = threading.Timer(30,Ping)
    t.start()

    
connTCP()
Ping()

while True:
    # 接收服務器發(fā)送過來的數(shù)據(jù)
    recvData = tcp_client_socket.recv(1024)
    if len(recvData) != 0:
        print('recv:', recvData.decode('utf-8'))
    else:
        print("conn err")
        connTCP()

第二,MQTT 協(xié)議連接

說明:
mqtt服務器地址:bemfa.com 端口:9501
連接服務器
1.用戶私鑰作為連接MQTT服務器的客戶端ID
2.連接時用戶名和密碼為空,或隨意填寫,即設備連接時不需要賬號和密碼

mqtt程序使用前需安裝mqtt庫文件,安裝命令:

pip3 install paho-mqtt
# -*- coding: utf-8 -*-
# 以下代碼在2021年10月21日 python3.10環(huán)境下運行通過

import paho.mqtt.client as mqtt

HOST = "bemfa.com"
PORT = 9501
client_id = "4d9ec352e0376f2110a0c601a2857225"                       
#連接并訂閱
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("led00202")         # 訂閱消息

#消息接收
def on_message(client, userdata, msg):
    print("主題:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8')))

#訂閱成功
def on_subscribe(client, userdata, mid, granted_qos):
    print("On Subscribed: qos = %d" % granted_qos)

# 失去連接
def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection %s" % rc)


client = mqtt.Client(client_id)
client.username_pw_set("userName", "passwd")
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect
client.connect(HOST, PORT, 60)
client.loop_forever()


本文摘自 :https://www.cnblogs.com/

開通會員,享受整站包年服務立即開通 >