esp_bluetooth_provisioning 0.0.6 copy "esp_bluetooth_provisioning: ^0.0.6" to clipboard
esp_bluetooth_provisioning: ^0.0.6 copied to clipboard

outdated

A new Flutter plugin.

example/lib/main.dart

import 'dart:io';
import 'dart:math';
import 'package:esp_bluetooth_provisioning/esp_bluetooth_provisioning.dart';
import 'package:esp_bluetooth_provisioning_example/POPDialog.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;
  final _formKey = GlobalKey<FormState>();
  bool isScanned =  false;
  bool isLoading = false;
  bool securityCheck = false;
  List<BleDevices> devices;
  String loading;
  String pin;


  @override
  void initState() {
    super.initState();
    devices = [];
    loading = "";
    pin = "";
    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 _showPOPDialog( BuildContext _context) {
    showDialog(
        context: _context,
        builder: (BuildContext context) {
          return POPDialog(
            pin:"",
            onSubmit: (pin) async {
              print('pin =$pin');
              checkProof(pin);
            },
          );
        });
  }



  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: 5), () {
          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<bool> checkProof(String pin) {
    setState(() {
      isLoading = true;
      loading = "Checking security verification";
    });
    EspBleProvisioning().checkProof(pin).then((value) {
      setState(() {
        print(value);
        isLoading = false;
        devices.clear();
        print("************security check completed");
        _showDialog(context);

        return true;
      });


    }).catchError((error) async {
      print("*************************");
      print(error);
      setState(() {
        isLoading = false;
      });
      return true;
    });
  }

  Future<bool> startProvisioning(String ssid, String password)
  async {
    setState(() {
      isLoading = true;
      loading = "Provisioning device";
    });
    print("***********START WIFI PROVISIONING");
    EspBleProvisioning().startProvisioning(ssid, password).then((value) async {
      setState(() {
        print(value);
        isLoading = false;
        devices.clear();
      });
      return true;


    }).catchError((error) async {
      print("*************************");
      print(error);
      setState(() {
        isLoading = false;
      });
      return true;

    });

    await checkStatus();

  }

  Future<bool> checkStatus()
  {
    setState(() {
      isLoading = true;
      loading = "Getting provisioned status";
    });
    EspBleProvisioning().checkProvisioningStatus().then((value){
      setState(() {
        isLoading = false;
        isScanned = false;
        print(value);
        if(value.isNotEmpty || value != null)
          messageDialog(value, context);
      });
    });
  }

  Future<bool> start()
  {
    setState(() {
      isLoading = true;
      loading = "Scanning bluetooth devices";
    });
    print("Start scan");
    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.length == 0)
      {
        showSnackBar("No devices found!");
      }
      return true;

    });

  }


  @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].id).then((value) async {
                                  setState(() {
                                    isLoading = false;
                                    _showPOPDialog(context);
                                    // isScanned = false;
                                    // securityCheck = true;
                                  });
                              }
                                );
                            },
                            child: Container(
                              width: double.infinity,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(4.0),
                                    child: Text(devices[index].name,
                                      style: TextStyle(fontSize:16, color: Colors.black),),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(4.0),
                                    child: Text(devices[index].id,
                                      style: TextStyle(fontSize:14, color: Colors.grey),),
                                  ),
                                ],
                              ),
                            ));
                      }
                  ),
                ),
              ],
            )
        ) : 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} }';
  }
}
1
likes
0
pub points
0%
popularity

Publisher

unverified uploader

A new Flutter plugin.

Homepage

License

unknown (license)

Dependencies

flutter

More

Packages that depend on esp_bluetooth_provisioning