首页 > 编程语言 >python收到MQTT消息后再发http请求

python收到MQTT消息后再发http请求

时间:2024-04-10 16:37:16浏览次数:28  
标签:http RECONNECT python mqtt MQTT client connect reconnect logging

python 收MQTT消息 和 发http请求 的代码在前面的文章都有介绍,这里直接上完整的功能代码

mqtt2http.py

# python 3.6

import logging
import random
import time
import requests


#from paho.mqtt import client as mqtt_client
import paho.mqtt.client as mqtt

BROKER = '*******.ala.cn-hangzhou.emqxsl.cn'
PORT = 8084
TOPIC = "python-mqtt/wss"
# generate client ID with pub prefix randomly
CLIENT_ID = f'python-mqtt-wss-sub-{random.randint(0, 1000)}'
USERNAME = '********'
PASSWORD = '********'

FIRST_RECONNECT_DELAY = 1
RECONNECT_RATE = 2
MAX_RECONNECT_COUNT = 12
MAX_RECONNECT_DELAY = 60

FLAG_EXIT = False

 
def on_connect(client, userdata, flags, rc):
    if rc == 0 and client.is_connected():
        print("Connected to MQTT Broker!")
        client.subscribe(TOPIC)
    else:
        print(f'Failed to connect, return code {rc}')


def on_disconnect(client, userdata, rc):
    logging.info("Disconnected with result code: %s", rc)
    reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAY
    while reconnect_count < MAX_RECONNECT_COUNT:
        logging.info("Reconnecting in %d seconds...", reconnect_delay)
        time.sleep(reconnect_delay)

        try:
            client.reconnect()
            logging.info("Reconnected successfully!")
            return
        except Exception as err:
            logging.error("%s. Reconnect failed. Retrying...", err)

        reconnect_delay *= RECONNECT_RATE
        reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)
        reconnect_count += 1
    logging.info("Reconnect failed after %s attempts. Exiting...", reconnect_count)
    global FLAG_EXIT
    FLAG_EXIT = True


def on_message(client, userdata, msg):
    print(f'Received `{msg.payload.decode()}` from `{msg.topic}` topic')
    send_http(msg.payload.decode())


def connect_mqtt():
    client = mqtt.Client(client_id=CLIENT_ID, transport='websockets',callback_api_version=mqtt.CallbackAPIVersion.VERSION1)
    #client = mqtt_client.Client(CLIENT_ID, transport='websockets')
    client.tls_set(ca_certs='./emqxsl-ca.crt')
    client.username_pw_set(USERNAME, PASSWORD)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(BROKER, PORT, keepalive=120)
    client.on_disconnect = on_disconnect
    return client

def send_http(msg):
    # 目标URL
    #url = "http://192.168.1.1/get.php?calltel=13941128888888"
    url = "http://localhost:1234/?"+msg

    # 发送GET请求
    response = requests.get(url)

    # 检查请求是否成功
    if response.status_code == 200:
        print("请求成功!")
        print("响应内容:", response.text)
    else:
        print("请求失败,状态码:", response.status_code)


def run():
    logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s',
                        level=logging.DEBUG)
    client = connect_mqtt()
    client.loop_forever()


if __name__ == '__main__':
    run()

 

标签:http,RECONNECT,python,mqtt,MQTT,client,connect,reconnect,logging
From: https://www.cnblogs.com/hailexuexi/p/18126295

相关文章

  • python 使用waitress替代flask自带的web服务器
    首席引入依赖安装waitrsspipintsllwaitress 然后在flask程序内引入依赖使用server()函数代替app.run()函数启动时,直接pythonxxx.py即可fromwaitressimportservefromflaskimportFlaskapp=Flask(__name__)@app.route('/')defhello_world():return'HelloWor......
  • python paramiko_具有连续标准输出,非一次性读全
    如何完全读取Paramiko通道的缓冲区?要完全读取Paramiko通道的缓冲区,可以使用以下代码:importparamikossh=paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect('hostname',username='user',password='pass')stdin,st......
  • python收到MQTT消息后写入mySQL
    python收MQTT消息和写mySQL的代码在前面的文章都有介绍,这里直接上完整的功能代码mqtt2mysql.py#python3.6importloggingimportrandomimporttimeimportmysql.connector#frompaho.mqttimportclientasmqtt_clientimportpaho.mqtt.clientasmqttBROKER......
  • python发http请求
    第一步安装 requests 库pipinstallrequests python代码#导入requests库importrequests#目标URLurl="http://192.168.1.1/get.php?calltel=13941128888888"#发送GET请求response=requests.get(url)#检查请求是否成功ifresponse.status_code==20......
  • OpenGauss数据库之Python驱动快速入门
    OpenGauss数据库之Python驱动openGauss是一款开源关系型数据库管理系统,采用木兰宽松许可证v2发行。openGauss内核源自PostgreSQL,深度融合华为在数据库领域多年的经验,结合企业级场景需求,持续构建竞争力特性。可是目前针对于OpenGauss数据库的Python应用程序的开发少......
  • 那些场景需要进行实名认证?python身份证实名认证接口案例
    身份证实名认证接口是用来核验用户身份证信息真伪的接口,从而确保用户身份的真实性,常见的应用场景包含:1、在线教育:线上教育平台为了保障学习者身份的真实性和安全性,通常通过集成身份证实名认证接口来验证学习者身份是否为本人。2、企事业单位:政务部门、企事业单位等......
  • :error=>"Elasticsearch Unreachable: [http://192.168.100.44:9200/][Manticore::Soc
    [2024-04-10T14:02:09,005][WARN][logstash.outputs.elasticsearch]AttemptedtoresurrectconnectiontodeadESinstance,butgotanerror.{:url=>"http://192.168.100.44:9200/",:error_type=>LogStash::Outputs::ElasticSearch::HttpClient::Pool......
  • 想用Python做副业?看这一篇就够了
    随着人工智能、大数据、物联网的广泛应用,与之紧密关联的Python技术开始受到人们的极大关注。各行业对Python技术服务的需求量呈指数级暴增,尤以爬虫技术服务为甚,供不应求早已成为常态。而近两年受到各种不可抗力的影响,做副业兼职赚钱的人越来越多。也是,在面对越来越大的资金......
  • python爬取京东商品信息与可视化
    项目介绍:使用python爬取京东电商拿到价格、店铺、链接、销量并做可视化...........................................................................................................................................................项目介绍效果展示全部代码..............
  • Python数据分析大作业(ARIMA 自回归积分滑动平均模型) 2000+字 图文分析文档 疫情分析
    资源地址:Python数据分析大作业2000+字图文分析文档疫情分析+完整python代码数据分析数据来自法国疫情数据时间序列是由四种因素组成的:长期趋势、季节变动、循环变动、随机波动。当我们对一个时间序列进行预测时,应该考虑将上述四种因素从时间序列中分解出来。分解之......