在 React Native & raspberry & MQTT 之间建立连接

物联网 MQTT 树莓派 天蓝色 帕霍
2021-06-12 13:14:26

我目前正在制作一个 IoT 应用程序,我正在尝试使用 MQTT 连接到 Raspberry Pi。我使用 react_native_mqtt 包。我遇到的问题是它无法连接。我想要实现的是从锉刀接收数据并将其与本机反应一起使用。但是连接不起作用。任何帮助表示赞赏。

错误:对象 {“errorCode”:7,“errorMessage”:“AMQJS0007E 套接字错误:未定义。”,“invocationContext”:未定义,}

import init from 'react_native_mqtt'
import AsyncStorage from '@react-native-async-storage/async-storage'

 init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  reconnect: true,
  sync : {
  }
});

const host = '52.11.11.11'
const port = '8883'
const connectUrl = `mqtt://${host}:${port}`
clientID = "clientID-" + parseInt(Math.random() * 100);
export default class TestScreen extends Component {

  constructor(){
    super();
    this.onConnectionLost = this.onConnectionLost.bind(this)
    this.onConnect = this.onConnect.bind(this)
    const client = new Paho.MQTT.Client(host, Number(port), clientID);
    client.onConnectionLost = this.onConnectionLost;
    client.connect({ 
      onSuccess: this.onConnect,
      useSSL: true,
      userName: 'admin',
      password: 'admin',
      onFailure: (e) => {console.log("here is the error" , e); }

    });

    this.state = {
      message: [''],
      client,
      messageToSend:'',
      isConnected: false,
    };
  }
  onConnect = () => {
   // const { client } = this.state;
    console.log("Connected!!!!");
    //client.subscribe('hello/world');
    this.setState({isConnected: true, error: ''})
  };

Nodejs.test:

const mqtt = require('mqtt')
const host = '52.xx.xx.xx'
const port = '1883'
const clientId = `id_${Math.random().toString(16).slice(3)}`
const connectUrl = `mqtt://${host}:${port}`
const client = mqtt.connect(connectUrl, {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'xxx',
  password: 'xxx',
  reconnectPeriod: 1000,
})
module.exports = client;

const topic = 'EnergyMonitoring/energy'

client.on('connect', () => {
  console.log('Connected')
  client.subscribe([topic], () => {
    console.log(`Subscribe to topic '${topic}'`)
  })
})

client.on('message', (topic, payload) => {
  console.log('Received Message :', topic, payload.toString())
})

app.listen(1883, ()=>{
  console.log("server is running")
})
1个回答

我们通过编辑 Mosquitto 配置文件来添加新的侦听器端口 8883 并对该端口使用 WebSocket 协议来解决此问题。

来自 Stack Overflow:设置 mosquitto 代理监听两个端口?

这是一个配置问题。感谢@hardillb 的帮助和@kalyanswaroop 的回复。