esp_bluetooth_provisioning 0.0.3 esp_bluetooth_provisioning: ^0.0.3 copied to clipboard
A new Flutter plugin.
import 'dart:io';
import 'package:esp_bluetooth_provisioning/esp_bluetooth_provisioning.dart';
import 'package:esp_bluetooth_provisioning_example/wifi_dialog.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
PermissionStatus _locationPermissionStatus = PermissionStatus.unknown;
bool isScanned = false;
bool isLoading = false;
List<BleDevices> devices;
String loading;
@override
void initState() {
super.initState();
devices = [];
loading = "";
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await EspBleProvisioning.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
void showSnackBar(message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
message,
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.black,
action: SnackBarAction(
label: 'Dismiss',
disabledTextColor: Colors.white,
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
));
}
Future<void> _checkPermissions() async {
if (Platform.isAndroid) {
var permissionStatus = await PermissionHandler()
.requestPermissions([PermissionGroup.location]);
_locationPermissionStatus = permissionStatus[PermissionGroup.location];
if (_locationPermissionStatus != PermissionStatus.granted) {
return Future.error(Exception("Location permission not granted"));
}
else
{
start();
}
}
}
void _showDialog( BuildContext _context) {
showDialog(
context: _context,
builder: (BuildContext context) {
return WifiDialog(
wifiName:"",
onSubmit: (ssid, password) async {
print('ssid =$ssid, password = $password');
startProvisioning(ssid, password);
},
);
});
}
messageDialog(String message, BuildContext _context)
{
showDialog(
barrierDismissible: true,
context: _context,
builder: (BuildContext context) {
Future.delayed(Duration(seconds: 3), () {
Navigator.of(context).pop(true);
});
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
content:
Stack(
overflow: Overflow.visible,
children: <Widget>[
StatefulBuilder(
builder: (BuildContext context, StateSetter alertState) {
return
Container(
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 8.0),
child: Text(message, textAlign :TextAlign.center, style: TextStyle(fontFamily: "Montserrat",fontSize: 16.0, color: Colors.black,),),
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
child: ElevatedButton(
onPressed: () { },
child: Text("Ok", style: TextStyle(fontSize: 15, color: Colors.white),),
),
),
),
],
));
},
),
],
),
);
},
);
}
Future<void> startProvisioning(String ssid, String password)
async {
setState(() {
isLoading = true;
loading = "Provisioning device";
});
print("***********START WIFI PROVISIONING");
EspBleProvisioning().startProvisioning(ssid, password).then((value) {
setState(() {
isScanned = false;
print(value);
isLoading = false;
devices.clear();
});
if(value.isNotEmpty)
messageDialog(value, context);
}).catchError((error) async {
print("*************************");
print(error);
setState(() {
isLoading = false;
});
messageDialog("Error provisioning device", context);
});
}
start()
async {
setState(() {
isLoading = true;
loading = "Scanning bluetooth device";
});
print("Start scan");
// EspBleProvisioning().requestPermission();
EspBleProvisioning().scanBluetoothDevice().then((value) {
setState(() {
print("************DEVICE SCAN RESULT : $value");
isScanned = true;
isLoading = false;
// devices = value;
if(value.length > 0)
{
value.forEach((k, v) {
BleDevices bleDevices = new BleDevices(k, v);
devices.add(bleDevices);
});
}
else
{
isScanned = false;
}
});
if(value.isEmpty)
{
showSnackBar("No devices found!");
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Esp Ble Provisioning'),
),
body: !isLoading ? isScanned ? Container(
padding: EdgeInsets.all(16),
child: Column(
children: [
Text("Select a device for provisioning",
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 18),),
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: ListView.builder(
shrinkWrap: true,
itemCount: devices.length,
itemBuilder: (_context, index) {
return GestureDetector(
onTap: (){
setState(() {
print("Connect to Device****************");
loading = "Connecting to device";
isLoading = true;
});
EspBleProvisioning().connectToBluetoothDevice(devices[index].name).then((value){
setState(() {
isLoading = false;
_showDialog(context);
});
}
);
},
child: Container(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(devices[index].name,
style: TextStyle(fontSize:16, color: Colors.black),),
),
));
}
),
),
],
)
) : Container(
height : double.infinity,
child:
Center(
child: ElevatedButton(
onPressed: ()=>{
_checkPermissions()
},
child: Text("Scan for bluetooth device"),
),
),
) : Align(
alignment: Alignment.center,
child: Container(
padding: EdgeInsets.only(top: 250),
color: Colors.white,
child: Center(
child: Column(
children: [
SpinKitRipple(color: Theme.of(context).textSelectionColor),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(loading, style: TextStyle(fontSize: 14, ),),
)
],
),
),
),
)),
);
}
}
class BleDevices {
String name;
String id;
BleDevices(this.name, this.id);
@override
String toString() {
return '{ ${this.name}, ${this.id} }';
}
}