bluetooth_connection_plugin 1.0.0 copy "bluetooth_connection_plugin: ^1.0.0" to clipboard
bluetooth_connection_plugin: ^1.0.0 copied to clipboard

A Flutter plugin for connecting to Bluetooth devices, specifically designed for weighing machines and similar devices. Supports device discovery, connection, data reading, and real-time weight monitoring.

Bluetooth Connection Plugin #

A comprehensive Flutter plugin for connecting to Bluetooth devices, specifically designed for weighing machines and similar IoT devices. This plugin provides robust connectivity, data reading capabilities, and real-time weight monitoring.

Features #

Device Discovery: Scan and list paired Bluetooth devices
Connection Management: Connect to and disconnect from Bluetooth devices
Data Reading: Read data from connected devices with multiple attempt retries
Real-time Listening: Continuous data monitoring with background listening
Weight Extraction: Built-in weight value parsing from raw device data
Multiple UUID Support: Compatible with various Bluetooth protocols (SPP, Weight Scale Service, etc.)
Permission Handling: Automatic Bluetooth permission management for Android 12+
Error Handling: Comprehensive error handling with descriptive error messages
Universal Compatibility: Works with any Bluetooth weighing machine or similar devices

Supported Platforms #

  • Android (API 21+)
  • 🚧 iOS (Coming soon)

Installation #

Add this to your package's pubspec.yaml file:

dependencies:
  bluetooth_connection_plugin: ^1.0.0

Then run:

flutter pub get

Android Setup #

Permissions #

The plugin automatically handles all required permissions. The following permissions are included in the plugin's Android manifest:

For Android 12+ (API 31+):

  • BLUETOOTH_SCAN
  • BLUETOOTH_CONNECT
  • BLUETOOTH_ADVERTISE

For Older Android versions:

  • BLUETOOTH
  • BLUETOOTH_ADMIN
  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION

Minimum SDK Version #

Ensure your app's android/app/build.gradle has:

android {
    compileSdkVersion 34
    
    defaultConfig {
        minSdkVersion 21  // Required minimum
        targetSdkVersion 34
    }
}

Usage #

1. Initialize the Plugin #

import 'package:bluetooth_connection_plugin/bluetooth_connection_plugin.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    BluetoothConnectionPlugin.initialize();
  }
}

2. Get Paired Devices #

Future<void> getPairedDevices() async {
  try {
    List<Map<String, dynamic>> devices = await BluetoothConnectionPlugin.getPairedDevices();
    
    for (var device in devices) {
      print('Device: ${device['name']} - ${device['address']}');
    }
  } on BluetoothException catch (e) {
    print('Error: ${e.message}');
  }
}

3. Connect to a Device #

Future<void> connectToDevice(String deviceAddress) async {
  try {
    Map<String, dynamic> result = await BluetoothConnectionPlugin.connectToDevice(deviceAddress);
    print('Connected to: ${result['deviceName']}');
  } on BluetoothException catch (e) {
    print('Connection failed: ${e.message}');
  }
}

4. Read Weight Data #

Future<void> getWeight() async {
  try {
    BluetoothData data = await BluetoothConnectionPlugin.readData();
    
    if (data.data.isNotEmpty) {
      String weight = data.cleanWeight;  // Automatically extracted weight value
      print('Weight: $weight');
      print('Raw data: ${data.rawData}');
      print('Timestamp: ${data.dateTime}');
    }
  } on BluetoothException catch (e) {
    print('Read failed: ${e.message}');
  }
}

5. Real-time Data Listening #

Future<void> startListening() async {
  try {
    await BluetoothConnectionPlugin.startListening();
    print('Started listening for data');
    
    // Data will be received via method channel callbacks
    // Implement _handleMethodCall to receive data
  } on BluetoothException catch (e) {
    print('Start listening failed: ${e.message}');
  }
}

Future<void> stopListening() async {
  try {
    await BluetoothConnectionPlugin.stopListening();
    print('Stopped listening');
  } on BluetoothException catch (e) {
    print('Stop listening failed: ${e.message}');
  }
}

6. Disconnect Device #

Future<void> disconnect() async {
  try {
    await BluetoothConnectionPlugin.disconnectDevice();
    print('Disconnected from device');
  } on BluetoothException catch (e) {
    print('Disconnect failed: ${e.message}');
  }
}

7. Check Connection Status #

Future<void> checkConnection() async {
  try {
    bool isConnected = await BluetoothConnectionPlugin.isConnected();
    print('Connection status: $isConnected');
  } on BluetoothException catch (e) {
    print('Status check failed: ${e.message}');
  }
}

Data Models #

BluetoothData #

Represents data received from a Bluetooth device:

class BluetoothData {
  final String data;          // Processed data
  final String rawData;       // Raw data from device
  final int bytesRead;        // Number of bytes read
  final int timestamp;        // Timestamp in milliseconds
  
  DateTime get dateTime;      // Converted timestamp
  String get cleanWeight;     // Extracted weight value
}

BluetoothDeviceInfo #

Represents a Bluetooth device:

class BluetoothDeviceInfo {
  final String name;          // Device name
  final String address;       // Device MAC address
  final String type;          // Device type (Classic, LE, Dual Mode)
}

BluetoothException #

Custom exception for Bluetooth operations:

class BluetoothException implements Exception {
  final String code;          // Error code
  final String message;       // Error message
}

Weight Value Extraction #

The plugin includes intelligent weight value extraction from raw device data:

String rawData = "ST,GS,+001.50kg";
String weight = BluetoothConnectionPlugin.extractWeightValue(rawData);
// Result: "001.50"

The extraction algorithm:

  • Removes non-numeric characters except decimals, minus, and plus signs
  • Handles multiple values by selecting the first valid number
  • Works with various data formats from different weighing machine brands

Complete Example #

import 'package:flutter/material.dart';
import 'package:bluetooth_connection_plugin/bluetooth_connection_plugin.dart';

class WeighingMachineScreen extends StatefulWidget {
  @override
  _WeighingMachineScreenState createState() => _WeighingMachineScreenState();
}

class _WeighingMachineScreenState extends State<WeighingMachineScreen> {
  List<BluetoothDeviceInfo> devices = [];
  String currentWeight = 'No data';
  bool isConnected = false;

  @override
  void initState() {
    super.initState();
    BluetoothConnectionPlugin.initialize();
    loadDevices();
  }

  Future<void> loadDevices() async {
    try {
      final deviceMaps = await BluetoothConnectionPlugin.getPairedDevices();
      setState(() {
        devices = deviceMaps.map((d) => BluetoothDeviceInfo.fromMap(d)).toList();
      });
    } catch (e) {
      print('Error loading devices: $e');
    }
  }

  Future<void> connectAndGetWeight(String address) async {
    try {
      await BluetoothConnectionPlugin.connectToDevice(address);
      setState(() => isConnected = true);
      
      final data = await BluetoothConnectionPlugin.readData();
      setState(() => currentWeight = data.cleanWeight);
    } catch (e) {
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Weighing Machine')),
      body: Column(
        children: [
          Text('Current Weight: $currentWeight', 
               style: TextStyle(fontSize: 24)),
          Expanded(
            child: ListView.builder(
              itemCount: devices.length,
              itemBuilder: (context, index) {
                final device = devices[index];
                return ListTile(
                  title: Text(device.name),
                  subtitle: Text(device.address),
                  onTap: () => connectAndGetWeight(device.address),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

Troubleshooting #

Common Issues #

  1. Permission Denied: Ensure Bluetooth permissions are granted in Android settings
  2. Connection Failed: Check if the device is paired and within range
  3. No Data: Some devices require specific commands to start data transmission
  4. Compatibility: Test with your specific weighing machine model

Debug Tips #

  1. Enable detailed logging in your app
  2. Check raw data format from your device
  3. Test connection with Bluetooth terminal apps first
  4. Verify device pairing in Android Bluetooth settings

Supported Device Types #

  • Digital weighing scales
  • Medical weighing machines
  • Industrial scales
  • Bluetooth serial devices
  • Any device using SPP (Serial Port Profile)

Contributing #

Contributions are welcome! Please feel free to submit a Pull Request.

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Support #

For issues and feature requests, please use the GitHub Issues page.

Changelog #

See CHANGELOG.md for a detailed list of changes.

0
likes
0
points
21
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin for connecting to Bluetooth devices, specifically designed for weighing machines and similar devices. Supports device discovery, connection, data reading, and real-time weight monitoring.

Repository (GitHub)
View/report issues

Topics

#bluetooth #weighing-machine #iot #device-communication #serial-communication

Documentation

Documentation

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on bluetooth_connection_plugin

Packages that implement bluetooth_connection_plugin