简体   繁体   English

如何修复 Futter Mqtt 数据

[英]How to fix Futter Mqtt data

I was working on Flutter Aws IoT App我正在开发 Flutter Aws IoT App

I was able to connect and get data from the server.我能够连接并从服务器获取数据。

I would like to get the proper data.我想获得正确的数据。

Here is the data on my Aws这是我的 aws 上的数据

亚马逊响应

Here what I receive in Flutter这是我在 Flutter 收到的

颤动响应

D/InputConnectionAdaptor( 4852): The input method toggled cursor monitoring on
I/flutter ( 4852): [123, 13, 10, 13, 10, 34, 65, 34, 58, 56, 56, 52, 44, 13, 10, 34, 66, 34, 58, 49, 50, 51, 44, 13, 10, 34, 67, 34, 58, 56, 55, 44, 13, 10, 34, 68, 34, 58, 50, 49, 51, 13, 10, 13, 10, 125]
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as img;
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:ndialog/ndialog.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'MQTT Flutter',
      themeMode: ThemeMode.dark,
      darkTheme: ThemeData.dark(),
      home: MQTTClient(),
    );
  }
}

class MQTTClient extends StatefulWidget {
  const MQTTClient({Key? key}) : super(key: key);

  @override
  _MQTTClientState createState() => _MQTTClientState();
}

class _MQTTClientState extends State<MQTTClient> {
  String statusText = "Status Text";
  bool isConnected = false;
  TextEditingController idTextController = TextEditingController();

  final MqttServerClient client =
      MqttServerClient('a119pogd0sq1sy-ats.iot.us-east-2.amazonaws.com', '');

  @override
  void dispose() {
    idTextController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    final bool hasShortWidth = width < 600;

    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [header(), body(hasShortWidth), footer()],
        ),
      ),
    );
  }

  Widget header() {
    return Expanded(
      child: Container(
        child: Center(
          child: Text(
            'Flutter - AWS IoT -',
            style: TextStyle(
                fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
        ),
      ),
      flex: 3,
    );
  }

  Widget body(bool hasShortWidth) {
    return Expanded(
      child: Container(
        child: hasShortWidth
            ? Column(
                children: [bodyMenu(), Expanded(child: bodySteam())],
              )
            : Row(
                children: [
                  Expanded(
                    child: bodyMenu(),
                    flex: 2,
                  ),
                  Expanded(
                    child: bodySteam(),
                    flex: 8,
                  )
                ],
              ),
      ),
      flex: 20,
    );
  }

  Widget bodyMenu() {
    return Container(
      color: Colors.black26,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: TextFormField(
                enabled: !isConnected,
                controller: idTextController,
                decoration: InputDecoration(
                    border: UnderlineInputBorder(),
                    labelText: 'MQTT Client Id',
                    labelStyle: TextStyle(fontSize: 10),
                    suffixIcon: IconButton(
                      icon: Icon(Icons.subdirectory_arrow_left),
                      onPressed: _connect,
                    ))),
          ),
          isConnected
              ? TextButton(onPressed: _disconnect, child: Text('Disconnect'))
              : Container()
        ],
      ),
    );
  }

  Widget bodySteam() {
    return Container(
      color: Colors.black,
      child: StreamBuilder(
        stream: client.updates,
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            );
          else {
            final mqttReceivedMessages =
                snapshot.data as List<MqttReceivedMessage<MqttMessage?>>?;

            final recMess =
                mqttReceivedMessages![0].payload as MqttPublishMessage;
            print(recMess.payload.message);

            // img.Image jpegImage = img.decodeJpg(recMess.payload.message!);

            return Center(
              child: Text(
                'de+\'recMess',
                style: TextStyle(
                    fontSize: 28,
                    color: Colors.white,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            );
          }
        },
      ),
    );
  }

  Widget footer() {
    return Expanded(
      child: Container(
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 16),
        child: Text(
          statusText,
          style: TextStyle(
              fontWeight: FontWeight.normal, color: Colors.amberAccent),
        ),
      ),
      flex: 1,
    );
  }

  _connect() async {
    if (idTextController.text.trim().isNotEmpty) {
      ProgressDialog progressDialog = ProgressDialog(context,
          blur: 0,
          dialogTransitionType: DialogTransitionType.Shrink,
          dismissable: false);
      progressDialog.setLoadingWidget(CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation(Colors.red),
      ));
      progressDialog
          .setMessage(Text("Please Wait, Connecting to AWS IoT MQTT Broker"));
      progressDialog.setTitle(Text("Connecting"));
      progressDialog.show();

      isConnected = await mqttConnect(idTextController.text.trim());
      progressDialog.dismiss();
    }
  }

  _disconnect() {
    client.disconnect();
  }

  Future<bool> mqttConnect(String uniqueId) async {
    setStatus("Connecting MQTT Broker");

    // After adding your certificates to the pubspec.yaml, you can use Security Context.
    //
    ByteData rootCA = await rootBundle.load('assests/RootCA.crt');
    ByteData deviceCert =
        await rootBundle.load('assests/DeviceCertificate.crt');
    ByteData privateKey = await rootBundle.load('assests/Private.key');

    SecurityContext context = SecurityContext.defaultContext;
    context.setClientAuthoritiesBytes(rootCA.buffer.asUint8List());
    context.useCertificateChainBytes(deviceCert.buffer.asUint8List());
    context.usePrivateKeyBytes(privateKey.buffer.asUint8List());

    client.securityContext = context;

    client.logging(on: true);
    client.keepAlivePeriod = 20;
    client.port = 8883;
    client.secure = true;
    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    client.pongCallback = pong;

    final MqttConnectMessage connMess =
        MqttConnectMessage().withClientIdentifier(uniqueId).startClean();
    client.connectionMessage = connMess;

    await client.connect();
    if (client.connectionStatus!.state == MqttConnectionState.connected) {
      print("Connected to AWS Successfully!");
    } else {
      return false;
    }

    const topic = 'Flutter';
    client.subscribe(topic, MqttQos.atMostOnce);

    return true;
  }

  void setStatus(String content) {
    setState(() {
      statusText = content;
    });
  }

  void onConnected() {
    setStatus("Client connection was successful");
  }

  void onDisconnected() {
    setStatus("Client Disconnected");
    isConnected = false;
  }

  void pong() {
    print('Ping response client callback invoked');
  }
}

MQTT messages are always just a collection of bytes, sometimes those bytes can represent an image, sometimes they can represent a string or something else. MQTT 消息始终只是字节的集合,有时这些字节可以表示图像,有时它们可以表示字符串或其他内容。

In the case of the output you have posted, it's the byte representation of a String which happens to represent a JSON object.对于您发布的 output,它是字符串的字节表示形式,恰好表示 JSON object。

But something like this will convert it to a String you can then use JSON.parse() on.但是像这样的东西会将它转换为一个字符串,然后你可以使用JSON.parse() on。

I can't see where in the code you've posted the incoming message is actually handled but something based on the following should help.我看不到您发布的代码中实际处理传入消息的位置,但基于以下内容的内容应该有所帮助。

const arrayToString = (a) => String.fromCharCode(...a)
const array = [123, 13, 10, 13, 10, 34, 65, 34, 58, 56, 56, 52, 44, 13, 10, 34, 66, 34, 58, 49, 50, 51, 44, 13, 10, 34, 67, 34, 58, 56, 55, 44, 13, 10, 34, 68, 34, 58, 50, 49, 51, 13, 10, 13, 10, 125]
const message_payload = JSON.parse(arrayToString(array))

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

相关问题 如何使用 Firebase Firestore 在 Futter 中显示用户名和个人资料图片 - How to show user name and profile picture in Futter using Firebase Firestore 如何在AWS IOT和Azure IOT HUB中查看MQTT数据 - How to see MQTT data in AWS IOT and Azure IOT HUB 如何修复数据未插入本地 dynamodb (NodeJS) - How to fix data not inserting into local dynamodb (NodeJS) 如何使用 mqtt.js 连接到运行在谷歌云虚拟机实例上的 Mosquitto MQTT Broker - How to connect to Mosquitto MQTT Broker, that is running on a Google Cloud Virtual Machine Instance, using mqtt.js 如何在 IoT Core 中长期使用 MQTT? - How can I use MQTT long term in IoT Core? 如何修复我的 Vue 应用程序未从 Firebase 获取数据的错误? - How to fix error that my Vue app doesn't get data from Firebase? 如何修复 UnhandledPromiseRejectionWarning: TypeError? - How to fix UnhandledPromiseRejectionWarning: TypeError? Flutter 在使用 StreamBuilder 从 firebase 加载数据之前显示红色错误屏幕,如何解决? - Flutter show's a red error screen before loading data from firebase using StreamBuilder, how to fix? 我无法从 firestore 获取数据 stream 我该如何解决 Ï - I can't get data stream from firestore how do I fix this ؟ 如何为 Alexa 技能调用配置 MQTT (AWS IoT) 测试控制台? - How do configure the MQTT (AWS IoT) test console for an Alexa skill invocation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM