简体   繁体   中英

How can I connect mosquitto server between raspberry pi and windows7?

Hello I'm trying to use mosquitto server in Raspberry Pi using MQTT to send a json data from r-pi to window.

Before I use mosquitto server, I used "test.mosquitto.org" It worked well.

I mean It sended some json data to windows.

However, when I turned mosquitto server in r-pi on, the windows put some error message which is

opts.protocol = opts.protocol.replace, cannot read property 'replace' of null.

Would you mind telling me what it is going on and fix it?

this is javascript on windows code (I use python in raspberry pi)

    console.log("start");
    var mqtt = require('mqtt');
    var client = mqtt.connect('mqtt://test.mosquitto.org');
    var client = mqtt.connect('192.168.1.2'); // IP of main-broker

    client.on('connect', function () {
        client.subscribe('sensor_A');
    });

    client.on('message', function (topic, message) {
        console.log("Topic: " + topic);
        var parsedData = JSON.parse(message);
        var dataLen = parsedData.length
        console.log('dataLen: ' + dataLen);

        for (var i = 0; i < dataLen; i++) {
            var data = JSON.parse(parsedData[i]);
            console.log('data ' + i + ': ' + data.time + ' ' + data.tem + ' ' + data.hum + ' ' + data.gas);
}
    });

I am using two r-pi which is sub-borker and main-broker.

sub-broker just send some sensor data as json and main-broker controls the json data and send again as json to windows.

I think my writing is quite complex to understand.

In short, I don't want to use "test.mosquitto.org" in r-pi so I turn mosquitto server on in r-pi to send data to window, however, there a error in window.

First you need to remove the line connecting to test.mosquitto.org as that will just confuse things.

Secondly you have missed out the mqtt:// from the URL for the local instance of mosquitto. The error is points out it can not find the protocol from the url.

console.log("start");
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.1.2'); // IP of main-broker

client.on('connect', function () {
    client.subscribe('sensor_A');
});

client.on('message', function (topic, message) {
    console.log("Topic: " + topic);
    var parsedData = JSON.parse(message);
    var dataLen = parsedData.length
    console.log('dataLen: ' + dataLen);

    for (var i = 0; i < dataLen; i++) {
        var data = JSON.parse(parsedData[i]);
        console.log('data ' + i + ': ' + data.time + ' ' + data.tem + ' ' + data.hum + ' ' + data.gas);
    }
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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