Search code examples
jsonfluttermqtt

How to convert MQTT Message to JSON format in Flutter


I already connect and get data from MQTT broker using snapshot method. However, I want to convert the MQTT message to JSON format cause I want to do some condition code to certain data.

My problem is when I stream data from the MQTT broker, my data only came out for the last data for that index. That index consists three different data, but since the index hold 3 data at the same time, only the last data of the index that displayed. This is my current code. How can I do that?

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter MQTT"),
      ),
      body: FutureBuilder(
        future: mqttSubscribe(topic: "/sensor_simulator/data"),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text("Error: ${snapshot.error}"),
            );
          }

          // if succeed to connect
          if (snapshot.connectionState == ConnectionState.done) {
            return StreamBuilder(
              stream: snapshot.data,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                // if have error--> display
                if (snapshot.hasError) {
                  return Center(
                    child: Text("Error: ${snapshot.error}"),
                  );
                }

                // if data detected--> display
                if (snapshot.hasData) {
                  try {
                    final List<MqttReceivedMessage> receiveMessage =
                        snapshot.data;
                    final recMess =
                        receiveMessage[0].payload as MqttPublishMessage;
                    String payload = MqttPublishPayload.bytesToStringAsString(
                        recMess.payload.message);

                    return ListView(
                      children: [
                        Card(
                            child: ListTile(
                          title: Text(payload),
                        ))
                      ],
                      padding: EdgeInsets.all(10),
                    );
                  } catch (e) {
                    return Center(
                      child: Text("Error: ${e.toString()}"),
                    );
                  }
                }

                return Center(child: CircularProgressIndicator());
              },
            );
          }

          return Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

Solution

  • You can use this piece of code:

    void _subscribeToTopic(String topicName) {
      
      print('MQTTClientWrapper::Subscribing to the $topicName topic');
      client.subscribe(topicName, MqttQos.atMostOnce);
    
      client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final recMess = c[0].payload as MqttPublishMessage;
    
      String message =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      String decodeMessage = Utf8Decoder().convert(message.codeUnits);
    
      print("MQTTClientWrapper::GOT A NEW MESSAGE $decodeMessage");
      
      });
    }