davesters / rn-native-mqtt

An MQTT client for React Native that actually works and exposes a simple Javascript interface
MIT License
64 stars 44 forks source link

rn-natinve-mqtt in Expo #21

Open Munklinde96 opened 3 years ago

Munklinde96 commented 3 years ago

Hello!

I have tried using the module while using react-native-cli. After some time I managed to get it to work. I have however now tried to use it using Expo, and I keep getting the same error: 159288707_4359902857357359_1306682232082495332_n 159111102_830239467529853_2073563605472444013_n (1) 159238157_215948980282503_9178310791409286977_n

I have the following code: import React, {useEffect, useState} from 'react' import { View, Button, Text} from 'react-native'; import * as Mqtt from 'react-native-native-mqtt'; import buffer from 'buffer' global.Buffer = buffer.Buffer;

const Mqtt = ({client}) => { const [error, setError] = useState(''); const [payload, setPayload] = useState(''); const [connectStatus, setConnectStatus] = useState('Disconnected');

const mqttConnect = () => {
    setConnectStatus("connecting");expo
    client.connect({
        clientId: "client",
        username: "crel",
        password: "pass",
        cleanSession: true,

    }, err => {setError(err)});
};

const mqttDisconnect = () => {
    setConnectStatus("disconnecting");
    client.disconnect();
};

useEffect(() => {
    if(client != null)
    {
        client.on(Mqtt.Event.Message, (topic, message) => {
            setPayload(message.toString());
        });

        client.on(Mqtt.Event.Connect, () => {
            client.subscribe(["robot/+"], [0]);
            setConnectStatus('connected');
        });

        client.on(Mqtt.Event.Error, (error) => {
            console.error('error', (error));
            setError(error);
        });

        client.on(Mqtt.Event.Disconnect, (cause) => {
            setConnectStatus('Disconnected');
        });
    }
}, [client]);

const publishMessage = (str) => {
    if(client != null && connectStatus == 'connected'){
        const buf = Buffer.from(str);
        client.publish("robot/test", buf, 0, false);
    }
};

return (
    <View>
        <Text>{connectStatus}</Text>
        <Text>error: {error}</Text>
        <Button
            onPress={mqttConnect}
            title = "connect"
        />
        <Button
            onPress={mqttDisconnect}
            title = "disconnect"
        />
        <Button
            onPress={
                publishMessage
            }
            title = "publish test message"
        />
        <Text>{payload}</Text>
    </View>

)

} export default Mqtt;

Does anyone have a tip, or experienced similar things?

sysoev2 commented 3 years ago

I have the same problem

M0ngi commented 2 years ago

I'm facing the same problem, any updates on this?

GaWr26 commented 1 year ago

anyone got this working?