Last active
May 6, 2023 17:59
-
-
Save darksh3ll/d23a72e854245e1c516dda0bc25682b2 to your computer and use it in GitHub Desktop.
app flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:mqtt_client/mqtt_client.dart'; | |
import 'package:mqtt_client/mqtt_server_client.dart'; | |
import 'dart:async'; | |
final StreamController<Map<String, String>> mqttMessageController = StreamController<Map<String, String>>.broadcast(); | |
Future<void> connectAndSubscribeToMQTT() async { | |
const String broker = ''; | |
const int port = 1883; | |
const String clientId = 'flutter_mqtt_client'; | |
final MqttServerClient client = MqttServerClient(broker, clientId); | |
client.port = port; | |
client.keepAlivePeriod = 60; | |
client.onConnected = () { | |
print('Connected to MQTT Broker'); | |
}; | |
client.onDisconnected = () { | |
print('Disconnected from MQTT Broker'); | |
}; | |
try { | |
await client.connect(); | |
} on Exception catch (e) { | |
print('Exception: $e'); | |
client.disconnect(); | |
} | |
if (client.connectionStatus!.state == MqttConnectionState.connected) { | |
print('MQTT client connected successfully'); | |
} else { | |
print('Failed to connect to MQTT broker'); | |
client.disconnect(); | |
return; | |
} | |
const String topic = '#'; | |
client.subscribe(topic, MqttQos.atLeastOnce); | |
client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> messages) { | |
final MqttPublishMessage message = messages[0].payload as MqttPublishMessage; | |
final String payload = MqttPublishPayload.bytesToStringAsString(message.payload.message!); | |
final String topic = messages[0].topic; | |
mqttMessageController.add({topic: payload}); | |
print('Received message on topic "$topic": $payload'); | |
}); | |
} | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
MyAppState createState() => MyAppState(); | |
} | |
class MyAppState extends State<MyApp> { | |
bool _isDarkTheme = true; | |
@override | |
void initState() { | |
super.initState(); | |
connectAndSubscribeToMQTT(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
theme: _isDarkTheme | |
? ThemeData.dark().copyWith( | |
primaryColor: Colors.blueGrey, colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.lightBlueAccent), | |
) | |
: ThemeData.light().copyWith( | |
primaryColor: Colors.deepPurple, colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.deepPurpleAccent), | |
), | |
home: DefaultTabController( | |
length: 4, | |
child: Scaffold( | |
body: const MyHomePage(), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
_isDarkTheme = !_isDarkTheme; | |
}); | |
}, | |
child: Icon(_isDarkTheme ? Icons.brightness_high : Icons.brightness_low), | |
), | |
), | |
), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({Key? key}) : super(key: key); | |
@override | |
MyHomePageState createState() => MyHomePageState(); | |
} | |
class MyHomePageState extends State<MyHomePage> { | |
Map<String, String> _mqttData = {}; | |
String getData(String topic) { | |
return _mqttData[topic] ?? 'N/A'; | |
} | |
@override | |
void initState() { | |
super.initState(); | |
mqttMessageController.stream.listen((Map<String, String> message) { | |
setState(() { | |
_mqttData = {..._mqttData, ...message}; | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
final ThemeData theme = Theme.of(context); | |
return Scaffold( | |
appBar: AppBar( | |
backgroundColor: theme.primaryColor, | |
title: const Text('Mqtt esp32'), | |
bottom: const TabBar( | |
tabs: [ | |
Tab(text: 'Chambre'), | |
Tab(text: 'Bureau'), | |
Tab(text: 'Salon'), | |
Tab(text: 'Extérieur'), | |
], | |
), | |
), | |
body: TabBarView( | |
children: [ | |
SingleChildScrollView( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
children: [ | |
buildItem(context, Icons.thermostat, "Temperature", "${getData('chambre/temperature')}°C", Colors.redAccent), | |
buildItem(context, Icons.water, "Humidité", "${getData('chambre/humidity')}%", Colors.blueAccent), | |
buildItem(context, Icons.cloud, "CO2", "${getData('chambre/c02')} ppm", Colors.greenAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM2.5", "${getData('chambre/pm2.5')} μg/m³", Colors.orangeAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM10", "${getData('chambre/pm10')} μg/m³", Colors.purpleAccent), | |
], | |
), | |
), | |
SingleChildScrollView( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
children: [ | |
buildItem(context, Icons.thermostat, "Temperature", "${getData('bureau/temperature')}°C", Colors.redAccent), | |
buildItem(context, Icons.water, "Humidité", "${getData('bureau/humidity')}%", Colors.blueAccent), | |
buildItem(context, Icons.cloud, "CO2", "${getData('bureau/c02')} ppm", Colors.greenAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM2.5", "${getData('bureau/pm2.5')} μg/m³", Colors.orangeAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM10", "${getData('bureau/pm10')} μg/m³", Colors.purpleAccent), | |
], | |
), | |
), | |
SingleChildScrollView( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
children: [ | |
buildItem(context, Icons.thermostat, "Temperature", "${getData('salon/temperature')}°C", Colors.redAccent), | |
buildItem(context, Icons.water, "Humidité", "${getData('salon/humidity')}%", Colors.blueAccent), | |
buildItem(context, Icons.cloud, "CO2", "${getData('salon/c02')} ppm", Colors.greenAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM2.5", "${getData('salon/pm2.5')} μg/m³", Colors.orangeAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM10", "${getData('salon/pm10')} μg/m³", Colors.purpleAccent), | |
], | |
), | |
), | |
SingleChildScrollView( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
children: [ | |
buildItem(context, Icons.thermostat, "Temperature", "${getData('exterieur/temperature')}°C", Colors.redAccent), | |
buildItem(context, Icons.water, "Humidité", "${getData('exterieur/humidity')}%", Colors.blueAccent), | |
buildItem(context, Icons.cloud, "CO2", "${getData('exterieur/c02')} ppm", Colors.greenAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM2.5", "${getData('exterieur/pm2.5')} μg/m³", Colors.orangeAccent), | |
buildItem(context, Icons.filter_alt, "Particules PM10", "${getData('exterieur/pm10')} μg/m³", Colors.purpleAccent), | |
], | |
), | |
), | |
], | |
), | |
); | |
} | |
Widget buildItem(BuildContext context, IconData icon, String title, String value, Color color) { | |
final ThemeData theme = Theme.of(context); | |
return Card( | |
elevation: 4, | |
margin: const EdgeInsets.all(10), | |
color: theme.cardColor, | |
child: Padding( | |
padding: const EdgeInsets.all(20), | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Icon(icon, size: 42, color: color), | |
const SizedBox(height: 10), | |
Text(title, style: TextStyle(fontSize: 20, color: theme.textTheme.bodyLarge?.color)), | |
const SizedBox(height: 10), | |
Text(value, style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: theme.textTheme.bodyLarge?.color)), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment