繁体   English   中英

如何通过javascript将TLS与Paho MQTT一起使用?

[英]How can I use TLS with Paho MQTT over Javascript?

我当前在我的网站上使用的代码

var client       = null;
var device_is_on    = null;
var hostname       = "********";
var port           = "8003";
var clientId       = "mqtt_js_" + parseInt(Math.random() * 100000, 10);
var device_topic     = "stat/Device_001/POWER";
var status_topic   = "cmnd/Device_001/power";


function connect(){
    client = new Paho.MQTT.Client(hostname, Number(port), clientId);

    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;

    var options = {
        useSSL: true,
        userName : "***",
        password : "********",
        onSuccess: onConnect,
        onFailure: onFail
    };
    client.connect(options);
}


function onConnect(context) {
    options = {qos:0}
    client.subscribe(device_topic, options);
    client.subscribe(status_topic, options);

    var payloadd = "6";

    message = new Paho.MQTT.Message(payloadd);
    message.destinationName = status_topic;
    message.retained = true;
    client.send(message);
}

function onFail(context) {
}

function onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
        window.alert("Connection Lost!\nPlease Refresh.");
    }
}

function onMessageArrived(message) {

    if (message.destinationName == device_topic){ 
        var temperature_heading = document.getElementById("device_display");
        temperature_heading.innerHTML = "Air Conditioner: " + message.payloadString;
        if (message.payloadString == "ON" || message.payloadString == "o"){
            device_is_on = true;
        } else {
            device_is_on = false;
        }
    }
}

function device_toggle(){
    if (device_is_on){
        var payload = "off";
        device_is_on = false;
    } else {
        var payload = "on";
        device_is_on = true;
    }

    message = new Paho.MQTT.Message(payload);
    message.destinationName = status_topic;
    message.retained = true;
    client.send(message);
}

我应该在““ var options”“部分下放置什么? 目前,我在Google Chrome浏览器的控制台中收到错误ERR_CERT_AUTHORITY_INVALID。

注意1:这段代码可以在http上正常运行,但是我正在转换为https。

注意2:我使用Mosquitto作为我的MQTT经纪人。

帮助非常感谢。

您好像正在使用自签名证书。 这将不会被您的浏览器信任,因此它将无法连接,从而引发您所显示的错误。

您有2个选择:

  1. 将证书导入到您的浏览器中,并将其标记为受信任(此操作的方式将根据所使用的浏览器而有所不同)。 这仅对测试/开发真正有用,因为普通用户不应导入随机证书,因为这会使它们面临各种安全问题。

  2. 为您的网站和经纪人获得真实可信的证书。 最简单/最便宜的方法是使用letsencrypt 然后,您可以将mosquitto配置为使用此证书。

TLS javascript paho客户端可用: Github paho.mqtt.javascript / issues / 88

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM