python paho MQTT通过MQTT连接onenet

移动云onenet是开源的,文档齐全,所以先用这个试试MQTT上云过程。
系统:windows10专业版,linux系统亦可
软件:Anaconda3,jupyter lab,用其他的IDE亦可,如idle
我以Anaconda3为例:

  1. 使用Anaconda终端cd到目的目录,启动jupyter lab。
    1). cd F:\pahoMQTT
    2). f:
    3). jupyter lab
  2. 拷贝库,参考官方网址:https://pypi.org/project/paho-mqtt/#description
  3. 我移动云产品、设备信息:
    1). 客户端ID(设备ID)631070225
    2). 用户名(产品ID)373087
    3). 密码(鉴权信息)kfbskd
  4. 将官方代码稍作修改,改成自己的产品ID即可:
import paho.mqtt.client as mqtt
HOST="183.230.40.39"
PORT=6002
client_id="631070159"
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("$SYS/#")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client(client_id)
client.username_pw_set("373087","appkzd")
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, 90)


# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
  1. 可以在移动云onenet上看到设备已经在线了。
    在这里插入图片描述
    -------------------------202009291604-------------------------
    假设有两个工控机,A和B,B订阅了主题"data/receive",然后A主机在这个主题publish相关内容,则B就可以收到这些。比如:A在主题"data/receive"中发送当前时间。
  2. 主要就是多了一个线程,代码如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2010-2013 Roger Light <roger@atchoo.org>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Distribution License v1.0
# which accompanies this distribution.
#
# The Eclipse Distribution License is available at
#   http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
#    Roger Light - initial implementation
# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org>
# All rights reserved.

# This shows a simple example of an MQTT subscriber.

#import context  # Ensures paho is in PYTHONPATH
import paho.mqtt.client as mqtt

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, name=None):
        super().__init__(name=name)

    # 线程体函数
    def run(self):
        # 当前线程对象
        t = threading.current_thread()
        for n in range(5):
            a = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            # 当前线程名
            client.publish("data/receive", a, qos=0, retain=False)
            # 线程休眠
            time.sleep(4)
        print('线程{0}执行完成!'.format(t.name))

        
HOST="183.230.40.39"
PORT=6002
client_id="631070159"
import paho.mqtt.publish as publish

def on_connect(mqttc, obj, flags, rc):
    print("rc: " + str(rc))


def on_message(mqttc, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))


def on_publish(mqttc, obj, mid):
    print("mid: " + str(mid))


def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))


def on_log(mqttc, obj, level, string):
    print(string)


# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.

t1 = MyThread()

client = mqtt.Client(client_id)
client.username_pw_set("373087", "appkzd")
t1.start()
client.on_message = on_message
client.on_connect = on_connect
client.connect(HOST, PORT, 90)

client.on_publish = on_publish
client.on_subscribe = on_subscribe
# Uncomment to enable debug messages
# mqttc.on_log = on_log


client.subscribe("$SYS/#", 0)
#client.publish("data/receive", 112233445566778899, qos=0, retain=False)
client.loop_forever()

然后在B主机就可以看到A主机发送的当前时间,结果如下:
在这里插入图片描述

其中:
client = mqtt.Client(client_id, clean_session=True)
如果cleant_session=True,则表示断开的时候,不再接收发布者发送的数据。
否则一上线,服务器就会推送发布者发布的很多数据。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值