btlib 0.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 69

Btlib #

A bluetooth driver plugin project, using a easy event-driven way.

Cross-Platform Bluetooth LE #

This plugin support both platforms (iOS and Android).

Example Code #

class BTUUID {
  static const String TX_SERV       = "1802";
  static const String TX_CHAR       = "2A06";
  static const String RX_SERV       = "180F";
  static const String RX_CHAR       = "2A19";
  static const String NOTIFY_SERV   = "FFE0";
  static const String NOTIFY_CHAR   = "FFE1";
}

main() {
    /// get instance
    Btlib driver = Btlib();

    /// listen to events
    StreamSubscription subscription;
    subscription = driver.listen(onEvent);

    /// start scan
    driver.startScan();

    /// waitting scan result...
    /// get device address...

    /// stop scan
    driver.stopScan();

    /// connect to device
    driver.connect(address);

    /// waitting connect result...
    /// get device services & characteristics ...

    /// write characteristic
    driver.writeCharacteristic(
        address,
        BTUUID.TX_SERV, 
        BTUUID.TX_CHAR, 
        Uint8List.fromList([0,1,2,3]));

    /// read characteristic
    driver.readCharacteristic(
        address,
        BTUUID.RX_SERV, 
        BTUUID.RX_CHAR);

    /// wait data available...

    /// set notification
    driver.setCharacteristicNotification(
        address,
        BTUUID.NOTIFY_SERV, 
        BTUUID.NOTIFY_CHAR, 
        true);

    /// wait data available (notification)...

    /// get rssi
    driver.getRSSI(address);

    /// wait rssi value...

    /// desconnect device
    driver.disconnect(address);
}
/*
events:
    BTEvent.BLE_START_SCAN               
    BTEvent.BLE_STOP_SCAN                   
    BTEvent.BLE_SCAN_RESULT                 /// return name,address,rssi       
    BTEvent.BLE_CONNECTED                   /// return address 
    BTEvent.BLE_DISCONNECTED                /// return address
    BTEvent.BLE_SERVICES_CHARACTERISTICS    /// return address,service,characteristic
    BTEvent.BLE_DATA_AVAILABLE              /// return address,service,characteristic,data
    BTEvent.BLE_RSSI                        /// return address,rssi             
*/
void onEvent(Object event) {
    HashMap<String, Object> map = HashMap.from(event);
    print(map);
    if (map["event"] == BTEvent.BLE_START_SCAN) {
        print( "start scan" );
    } else if (map["event"] == BTEvent.BLE_STOP_SCAN) {
        print( "stop scan" );
    } else if (map["event"] == BTEvent.BLE_SCAN_RESULT) {
        print( map["name"] );
        print( map["address"] );
        print( map["rssi"] );
    } else if (map["event"] == BTEvent.BLE_CONNECTED) {
        print( map["address"] );
    } else if (map["event"] == BTEvent.BLE_DISCONNECTED) {
        print( map["address"] );
    } else if (map["event"] == BTEvent.BLE_SERVICES_CHARACTERISTICS) {
        print( map["address"] );
        print( map["service"] );
        print( map["characteristic"] );
    } else if (map["event"] == BTEvent.BLE_DATA_AVAILABLE) {
        print( map["address"] );
        print( map["service"] );
        print( map["characteristic"] );
        print( map["data"] );
    } else if (map["event"] == BTEvent.BLE_RSSI) {
        print( map["address"] );
        print( map["rssi"] );
    }
}

0.1.1 #

  • Update README.md documentation
  • Update example code

0.1.0 #

  • Update pubspec.yaml description
  • Avoid "Close instances of dart.core.Sink" warning

0.0.3 #

  • Update README.md

0.0.2 #

  • Update README.md

0.0.1 #

  • Initial Release.

example/lib/main.dart

import 'dart:async';
import 'dart:collection';
import 'dart:typed_data';

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const String TAG = "iTAG";
  static const String ALARM_SERV = "1802";
  static const String ALARM_CHAR = "2A06";
  static const String BATTERY_SERV = "180F";
  static const String BATTERY_CHAR = "2A19";
  static const String KEY_SERV = "FFE0";
  static const String KEY_CHAR = "FFE1";

  Btlib driver = Btlib();
  StreamSubscription subscription;
  String address;
  bool scanning = false;
  bool connected = false;
  int counter = 0;
  int battery = 0;
  int rssi = 0;

  @override
  void initState() {
    super.initState();
    subscription = driver.listen(onEvent);
  }

  @override
  void dispose() {
    subscription.cancel();
    super.dispose();
  }

  void onEvent(Object e) {
    HashMap<String, Object> map = HashMap.from(e);
    print(map);
    var event = map["event"];
    if (event == BTEvent.BLE_START_SCAN) {
      scanning = true;
    } else if (event == BTEvent.BLE_STOP_SCAN) {
      scanning = false;
    } else if (event == BTEvent.BLE_CONNECTED) {
      connected = true;
      address = map["address"];
      driver.setCharacteristicNotification(address, KEY_SERV, KEY_CHAR, true);
      driver.readCharacteristic(address, BATTERY_SERV, BATTERY_CHAR);
      driver.getRSSI(address);
    } else if (event == BTEvent.BLE_DISCONNECTED) {
      connected = false;
      counter = 0;
      battery = 0;
      rssi = 0;
    } else if (event == BTEvent.BLE_SCAN_RESULT) {
      if (map["name"].toString().startsWith(TAG))
      {
        driver.stopScan();
        driver.connect(map["address"]);
      }
    } else if (event == BTEvent.BLE_DATA_AVAILABLE) {
      if (map["characteristic"].toString() == KEY_CHAR) {
        counter++;
      }
      if (map["characteristic"].toString() == BATTERY_CHAR) {
        Uint8List data = map["data"];
        battery = data[0];
      }
    } else if (event == BTEvent.BLE_SERVICES_CHARACTERISTICS) {
    } else if (event == BTEvent.BLE_RSSI) {
      rssi = int.parse(map["rssi"]);
    }

    setState(() {});
  }

  _buildActionButtons() {
    return <Widget>[
      new IconButton(
        icon: const Icon(Icons.cancel),
        onPressed: () => driver.disconnect(address),
      )
    ];
  }

  _buildFloatingActionButton() {
    return new FloatingActionButton(
      child: new Icon(scanning ? Icons.stop : Icons.search),
      onPressed: () {
        scanning ? driver.stopScan() : driver.startScan();
      },
      backgroundColor: scanning ? Colors.red : Colors.blue,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: connected ? _buildActionButtons() : null,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              scanning ? 'Scanning...' : connected ? '$address Connected' : 'Tap to scan',
            ),
            RaisedButton(
              onPressed: () => driver.writeCharacteristic(
                  address, ALARM_SERV, ALARM_CHAR, Uint8List.fromList([2])),
              child: Text("Alarm ON."),
            ),
            RaisedButton(
              onPressed: () => driver.writeCharacteristic(
                  address, ALARM_SERV, ALARM_CHAR, Uint8List.fromList([0])),
              child: Text("Alarm OFF"),
            ),
            Text(
              'Pushed:$counter\nBattery:$battery\nRSSI:$rssi',
              textAlign: TextAlign.left,
            ),
          ],
        ),
      ),
      floatingActionButton: _buildFloatingActionButton(),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  btlib: ^0.1.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:btlib/btlib.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
38
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
69
Learn more about scoring.

We analyzed this package on Jul 8, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because of import path [package:btlib/btlib.dart] that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because of import path [package:btlib/btlib.dart] that declares support for platforms: android, ios

Package does not support Flutter platform web

Because of import path [package:btlib/btlib.dart] that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because of import path [package:btlib/btlib.dart] that declares support for platforms: android, ios

Package not compatible with SDK dart

because of import path [btlib] that is in a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.1
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test