flutter_ota 0.1.6 copy "flutter_ota: ^0.1.6" to clipboard
flutter_ota: ^0.1.6 copied to clipboard

A Flutter package for OTA updating firmware of ESP32 using Bluetooth Low Energy (BLE).

example/lib/main.dart

// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_ota/ota_package.dart';
import 'package:get/get.dart';

import 'controllers/bleUart_controller.dart';
import 'controllers/ble_servicescontroller.dart';


class OtaUpdatePage extends StatelessWidget {
  final TextEditingController commandController = TextEditingController();
  final TextEditingController receivedController = TextEditingController();
  final BleUartController bleUartController = BleUartController();
  bool showProgressDialog = true;
  bool firmwareFileSelected = false;
  BluetoothCharacteristic? dataUuid;
  BluetoothCharacteristic? controlUuid;
  String? binfile;

  @override
  Widget build(BuildContext context) {
    Completer<bool> _completer = Completer<bool>();
    String? customPath;

    return WillPopScope(
      onWillPop: () async {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('Disconnect and Go Back?'),
            content: const Text(
              'Do you want to disconnect from the available Bluetooth devices and go back to the scanning page?',
            ),
            actions: [
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Colors.lightBlue,
                  onPrimary: Colors.white,
                ),
                onPressed: () async {
                 
                  Navigator.pop(context);
                  Navigator.pushReplacementNamed(context, '/scanningpage');
                  _completer.complete(true);
                },
                child: const Text('Disconnect'),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Colors.lightBlue,
                  onPrimary: Colors.white,
                ),
                onPressed: () {
                  Navigator.pop(context);
                  _completer.complete(false);
                },
                child: const Text('Cancel'),
              ),
            ],
          ),
        );
        return await _completer.future;
      },
      child: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color.fromRGBO(125, 186, 236, 1),
              Color.fromRGBO(82, 116, 211, 0.933),
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    // Assume the user will type the path manually
                    customPath = await showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        title: const Text('Enter Custom Firmware Path'),
                        content: TextField(
                          onChanged: (value) {
                            customPath = value;
                          },
                          decoration: const InputDecoration(
                            hintText: 'Enter Firmware Path',
                          ),
                        ),
                        actions: [
                          ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context, customPath);
                            },
                            child: const Text('OK'),
                          ),
                        ],
                      ),
                    );

                    if (customPath == null || customPath!.isEmpty) {
                      // User canceled or did not enter a path
                      firmwareFileSelected = false;
                      return;
                    } else {
                      firmwareFileSelected = true;
                    }

                    BluetoothDevice? device =
                        Get.find<BleDeviceController>().connectedDevice;
                    List<BluetoothService> services =
                        Get.find<BleDeviceController>().bleServices;

                    if (device == null || services.isEmpty) {
                      print("Device or services not available for OTA update");
                      return;
                    }

                    bool characteristicsFound = false;

                    for (BluetoothService service in services) {
                      if (service.uuid.toString() ==
                          'd6f1d96d-594c-4c53-b1c6-144a1dfde6d8') {
                        final characteristics = service.characteristics;
                        BluetoothCharacteristic? dataUuid;
                        BluetoothCharacteristic? controlUuid;

                        for (BluetoothCharacteristic c in characteristics) {
                          if (c.uuid.toString() ==
                              '23408888-1f40-4cd8-9b89-ca8d45f8a5b0') {
                            dataUuid = c;
                          }
                          if (c.uuid.toString() ==
                              '7ad671aa-21c0-46a4-b722-270e3ae3d830') {
                            controlUuid = c;
                          }
                        }

                        if (dataUuid != null && controlUuid != null) {
                          if (Platform.isAndroid) {
                            const newMtu = 300;
                            await device.requestMtu(newMtu);
                            print('New MTU size (Android): $newMtu');
                          } else if (Platform.isIOS) {
                            const newMtu = 185;
                            print('New MTU size (iOS): $newMtu');
                          }

                          final esp32otaPackage =
                              Esp32OtaPackage(dataUuid, controlUuid);

                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (context) => AlertDialog(
                              title: const Text('OTA Update in Progress'),
                              content: StreamBuilder<int>(
                                stream: esp32otaPackage.percentageStream,
                                initialData: 0,
                                builder: (BuildContext context,
                                    AsyncSnapshot<int> snapshot) {
                                  double progress =
                                      snapshot.data! / 100.toDouble();
                                  if (progress >= 1.0 && showProgressDialog) {
                                    WidgetsBinding.instance
                                        ?.addPostFrameCallback((_) {
                                      showProgressDialog = false;
                                      Navigator.pop(context);
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(
                                        const SnackBar(
                                          content: Text('OTA Update Complete'),
                                          duration: Duration(seconds: 2),
                                        ),
                                      );
                                    });
                                  }
                                  return LinearProgressIndicator(
                                    value: progress,
                                    valueColor:
                                        const AlwaysStoppedAnimation<Color>(
                                            Colors.blue),
                                    backgroundColor: Colors.grey[300],
                                  );
                                },
                              ),
                            ),
                          );

                          if (firmwareFileSelected) {
                            await esp32otaPackage.updateFirmware(
                              device,
                              2, // Set firmwareType to 4 for custom path
                              service,
                              dataUuid,
                              controlUuid,
                              
                            );
                          }

                          characteristicsFound = true;
                          break;
                        }
                      }
                    }

                    if (!characteristicsFound) {
                      showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: const Text('Device Not Compatible'),
                          content: const Text(
                            'The device does not have the required characteristics for OTA firmware update.',
                          ),
                          actions: [
                            ElevatedButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: const Text('OK'),
                            ),
                          ],
                        ),
                      );
                    }
                  },
                  child: const Text('OTA Update'),
                ),
                const SizedBox(height: 50),
                const Text(
                  'Send Command',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 20),
                Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 20), // Add desired horizontal padding
                  child: TextField(
                    controller: commandController,
                    enabled: true,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                      hintText: 'Enter Command Here',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                      contentPadding: const EdgeInsets.all(16),
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    String command = commandController.text;
                    print("Sent data:  $command");

                    bleUartController.sendCommand(command);

                    FocusScope.of(context).unfocus();
                  },
                  child: const Text('Send'),
                ),
                const SizedBox(height: 20),
                const Text(
                  'Received Data',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 10),
                Obx(
                  () => Text(
                    bleUartController.recievingvaue.value,
                    style: const TextStyle(
                      fontSize: 24,
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
16
likes
0
pub points
71%
popularity

Publisher

verified publishersparkleo.io

A Flutter package for OTA updating firmware of ESP32 using Bluetooth Low Energy (BLE).

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

cupertino_icons, file_picker, flutter, flutter_blue_plus, get, http, mockito, path, path_provider, permission_handler

More

Packages that depend on flutter_ota