zyg_mqtt_plugin 0.0.2 zyg_mqtt_plugin: ^0.0.2 copied to clipboard
这是中裕冠的mqtt插件
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:zyg_mqtt_plugin/zyg_mqtt_plugin.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _zygMqttPlugin = ZygMqttPlugin();
List<String> receiveDataList = [];
@override
void initState() {
super.initState();
}
String connectState = '未连接';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Stack(
children: [
ZygMqttWidget(),
ListView(
children: [
Text(
'连接状态:$connectState',
style: TextStyle(color: Colors.red),
),
SizedBox(
height: 20,
),
FilledButton(
onPressed: () {
//先配置,再去连接
const productKey = 'a1WPnByrqko';
const deviceName = '1224708605@qq.com';
const deviceSecret = '3a694c1543fa8582ffc6d8ff1d7af6ca';
// 当前产品和设备所属地域的ID
// const region = 'us-west-1';
const region = 'cn-shanghai';
// const productKey = 'a3Q9ncgAkZp';
// const deviceName = '1224708605@qq.com';
// const deviceSecret = 'b5829c0cde2d0eb43989cc8e0c63f607';
// // 当前产品和设备所属地域的ID。
// const region = 'us-west-1';
// 接收消息的时候需要用到
String subscribeUrl =
'/${productKey}/${deviceName}/user/get';
//发送消息的时候需要用到
String publishUrl =
'/${productKey}/${deviceName}/user/update';
//配置
ZygMqttPlugin().setConfigure(productKey, deviceName,
deviceSecret, region, subscribeUrl, publishUrl);
//连接状态回调
ZygMqttPlugin().myConnectStateCallback = (state) {
if (ZygConnectState.connected == state) {
print('已连接');
setState(() {
connectState = '已连接';
});
} else if (ZygConnectState.disconnect == state) {
print('已断开');
connectState = '已断开';
}
};
//接收消息回调, rawData是接收到的原始数据,mapData是json格式的数据
ZygMqttPlugin().myReceiveCallback =
(rawData, jsonData) {
//
setState(() {
receiveDataList.add(rawData.toString());
});
};
//连接
ZygMqttPlugin().goToConnetMqtt();
},
child: Text('连接mqtt')),
SizedBox(
height: 20,
),
FilledButton(
onPressed: () {
//电量
Map map = {
"target_device": "89860124801080169975",
"cmd": "detect_battery"
};
String msg = jsonEncode(map);
//发送数据
ZygMqttPlugin().sendData(msg);
},
child: Text('发送数据')),
...receiveDataList.map((toElement) {
return Text(toElement);
}).toList()
],
)
],
),
),
),
);
}
}