python收到MQTT訊息後再發http請求

海乐学习發表於2024-04-10

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

相關文章