[英]Mqtt Client works on Node.js, doesn't on Python
我正在嘗試制作一個小腳本來獲取 ShareNow的汽車信息並對其進行處理。 在網上尋找 api 時,我只發現了這個GitHub 存儲庫,其中他使用 Node.js 連接到 mqtt 經紀人並獲取有關汽車的信息。
現在,我從未使用過 Node,也從未聽說過 mqtt,但是我嘗試翻譯他在 python 中連接到代理的部分代碼,但它不起作用,我似乎無法找到翻譯這行的方法
let client = mqtt.connect('mqtts://driver.eu.share-now.com:443', {
clientId,
rejectUnauthorized: false,
reconnectPeriod: 0
});
進入一種連接到 Node.js 之外的代理的方法。 我所了解的是 url 是driver.eu.share-now.com並且端口是443 ,我不知道它是否正確但是當我嘗試連接到它時(使用 Z23EEEB7347BDD756BDDZFC 外部程序)它只是無所事事或超時。
我不明白的是它為什么以及如何在他的代碼上工作,但即使在 mqtt 客戶端測試器上嘗試,我也找不到連接的方法。
這是 node.js 中 GitHub 代碼的簡化(並且仍在工作)版本:
const mqtt = require("mqtt");
const uuid = require("uuid-random");
const zlib = require("zlib");
class ShareNowClient {
static VEHICLELIST = "C2G/S2C/20/VEHICLELIST.GZ"
vehicles = [];
#updateCallback;
connect() {
let clientId = `a:${uuid()}`;
let client = mqtt.connect('mqtts://driver.eu.share-now.com:443', {
clientId,
rejectUnauthorized: false,
reconnectPeriod: 0
});
client.on('connect', () => {
client.subscribe(ShareNowClient.VEHICLELIST, {qos: 0});
});
client.on("message", (topic, message) => {
let json = JSON.parse(zlib.gunzipSync(message));
if (topic === ShareNowClient.VEHICLELIST) {
client.unsubscribe(ShareNowClient.VEHICLELIST);
this.vehicles = json.connectedVehicles;
console.log(this.vehicles[0]) //prints the first vehicle to check if it works
client.end();
}
});
client.on("error", error => {
console.log(`Error: ${error}`);
});
}
}
let cars = new ShareNowClient();
cars.connect();
這是我在 python 中嘗試過的(它顯然不起作用)
import paho.mqtt.client as mqtt
import uuid
def on_connect(client, userdata, flags, rc):
print("Connected with result code {0}".format(str(rc)))
client.subscribe(topic)
def on_message(client, userdata, msg):
print(str(msg.payload))
#print("Message received-> " + msg.topic + " " + str(msg.payload))
clientId = f'a:{uuid.uuid4()}'
client = mqtt.Client(clientId)
client.on_connect = on_connect
client.on_message = on_message
broker = 'driver.eu.share-now.com'
port = 443
topic = "C2G/S2C/20/VEHICLELIST.GZ"
client.connect(broker , port)
client.loop_forever()
當我嘗試連接到測試代理時,python 代碼有效,但是當我嘗試連接到 sharenow 的 url 時,只是循環什么都不做。
任何人都可以幫助它工作嗎? 謝謝
您傳遞給 NodeJS 客戶端的 URL 以mqtts://
開頭,這表示 MQTT over TLS 連接,因為您沒有告訴 python 客戶端您正在嘗試連接到啟用 TLS 的代理,它沒有嘗試執行 TLS握手。
在調用client.connect()
client.tls_set()
) 將解決問題。
import paho.mqtt.client as mqtt
import uuid
def on_connect(client, userdata, flags, rc):
print("Connected with result code {0}".format(str(rc)))
client.subscribe(topic)
def on_message(client, userdata, msg):
print(str(msg.payload))
#print("Message received-> " + msg.topic + " " + str(msg.payload))
clientId = f'a:{uuid.uuid4()}'
client = mqtt.Client(clientId)
client.on_connect = on_connect
client.on_message = on_message
broker = 'driver.eu.share-now.com'
port = 443
topic = "C2G/S2C/20/VEHICLELIST.GZ"
client.tls_set()
client.connect(broker , port)
client.loop_forever()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.