Commit 883a2aac authored by Andrey's avatar Andrey

Example bluetooth project: can scan and print once.

parent 1923b6dc
PODS:
- Flutter (1.0.0)
- flutter_blue (0.0.1):
- flutter_bluetooth_basic (0.0.1):
- Flutter
- flutter_blue/Protos (= 0.0.1)
- flutter_blue/Protos (0.0.1):
- Flutter
- Protobuf
- Protobuf (3.11.0)
DEPENDENCIES:
- Flutter (from `Flutter`)
- flutter_blue (from `.symlinks/plugins/flutter_blue/ios`)
SPEC REPOS:
trunk:
- Protobuf
- flutter_bluetooth_basic (from `.symlinks/plugins/flutter_bluetooth_basic/ios`)
EXTERNAL SOURCES:
Flutter:
:path: Flutter
flutter_blue:
:path: ".symlinks/plugins/flutter_blue/ios"
flutter_bluetooth_basic:
:path: ".symlinks/plugins/flutter_bluetooth_basic/ios"
SPEC CHECKSUMS:
Flutter: 0e3d915762c693b495b44d77113d4970485de6ec
flutter_blue: be3f2be2f5fda254d174896c0738b2fcb6b1073e
Protobuf: 394b2bf29ec303f4325e3ee4892c09e675647152
flutter_bluetooth_basic: 0e4e27e22b50b3a25cc1d1e131953feb4af414f4
PODFILE CHECKSUM: 3dbe063e9c90a5d7c9e4e76e70a821b9e2c1d271
......
......@@ -40,8 +40,15 @@
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Bluetooth is used to scan for pos printers and send the data</string>
<string>Bluetooth is used to scan for printers and send the data</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Bluetooth is used to scan for printers and send the data</string>
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>bluetooth-peripheral</string>
</array>
</dict>
</plist>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_bluetooth_basic/flutter_bluetooth_basic.dart';
void main() => runApp(MyApp());
......@@ -7,7 +8,7 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: 'Bluetooth demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
......@@ -19,82 +20,60 @@ class MyApp extends StatelessWidget {
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
final FlutterBlue flutterBlue = FlutterBlue.instance;
// final FlutterBlue flutterBlue = FlutterBlue.instance;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<ScanResult> _scanResults = [];
BluetoothManager bluetoothManager = BluetoothManager.instance;
bool _connected = false;
void _scanDevices() {
setState(() {
_scanResults = [];
});
// Start scanning
widget.flutterBlue.startScan(timeout: Duration(seconds: 4));
// Listen to scan results
var subscription = widget.flutterBlue.scanResults.listen((scanResult) {
// do something with scan result
// device = scanResult.device;
// print('${device.name} found! rssi: ${scanResult.rssi}');
Future sleep3() {
return Future<dynamic>.delayed(const Duration(seconds: 7), () => "1");
}
print('FOUND !!! ${scanResult.length}');
scanResult.forEach((ScanResult scanRes) async {
if (scanRes.device.name.isNotEmpty) {
if (!_scanResults.contains(scanRes)) {
_scanResults.add(scanRes);
setState(() {
_scanResults
.sort((scanRes1, scanRes2) => scanRes2.rssi - scanRes1.rssi);
void _testPrint(BluetoothDevice printer) async {
// print('Test print.... name: ${printer.name}');
if (printer != null && printer.address != null) {
// Connect
await bluetoothManager.connect(printer);
// Subscribe to the events
bluetoothManager.state.listen((state) async {
// print('**************cur device status: $state');
switch (state) {
case BluetoothManager.CONNECTED:
print('********************* CONNECTED');
// to avoid double call
if (!_connected) {
print('@@@@SEND DATA......');
final List<int> bytes = latin1.encode('test!\n\n\n').toList();
await bluetoothManager.writeData(bytes);
// print('################## print send #############');
// bluetoothManager.
}
sleep3().then((dynamic printer) async {
print('@@@@DISCONNECTING......');
await bluetoothManager.disconnect();
});
}
print(
'\t> ${scanRes.device.name} : ${scanRes.rssi} : ${_scanResults.length}');
_connected = true;
break;
case BluetoothManager.DISCONNECTED:
print('********************* DISCONNECTED');
_connected = false;
break;
default:
break;
}
});
});
// Stop scanning
widget.flutterBlue.stopScan();
}
void testPrint(ScanResult scanResult, BuildContext ctx) async {
BluetoothDevice device = scanResult.device;
print('Sending test print to... ${device.name}');
await device.connect();
print('\t>connected');
List<BluetoothService> services = await device.discoverServices();
services.forEach((service) async {
print('> Service // isPrimary: ${service.isPrimary} // ${service.uuid}');
// Reads all characteristics
final characteristics = service.characteristics;
for (BluetoothCharacteristic c in characteristics) {
// List<int> value = await c.read();
// print('\t\t## charact. // $value');
}
});
// const esc = '\x1B';
// const cInit = '$esc@'; // Initialize printer
// reset
// _socket.write(cInit);
// print text
// _socket.add(latin1.encode(text));
// empty lines
// _socket.write(List.filled(5, '\n').join());
// reset
// _socket.write(cInit);
device.disconnect();
print('\t>disconnected');
// TODO show message "Data sent"
} else {
// TODO show message "Can't connect to the device"
}
}
@override
......@@ -103,49 +82,64 @@ class _MyHomePageState extends State<MyHomePage> {
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: _scanResults.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: () => testPrint(_scanResults[index], context),
child: Column(
children: <Widget>[
Container(
height: 60,
padding: EdgeInsets.only(left: 10),
alignment: Alignment.centerLeft,
child: Row(
children: <Widget>[
Icon(Icons.print),
SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Signal ${_scanResults[index].rssi + 100}% : ${_scanResults[index].device.name}',
),
Text(
'Click to print a test receipt',
style: TextStyle(color: Colors.grey[700]),
),
],
body: StreamBuilder<List<BluetoothDevice>>(
stream: bluetoothManager.scanResults,
initialData: [],
builder: (c, snapshot) => Column(
children: snapshot.data
.map((d) => InkWell(
onTap: () => _testPrint(d),
child: Column(
children: <Widget>[
Container(
height: 60,
padding: EdgeInsets.only(left: 10),
alignment: Alignment.centerLeft,
child: Row(
children: <Widget>[
Icon(Icons.print),
SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(d.name ?? ''),
Text(d.address),
Text(
'Click to print a test receipt',
style: TextStyle(color: Colors.grey[700]),
),
],
),
)
],
),
),
)
],
),
),
Divider(),
],
),
);
},
Divider(),
],
),
))
.toList(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _scanDevices,
tooltip: 'Scan',
child: Icon(Icons.add),
floatingActionButton: StreamBuilder<bool>(
stream: bluetoothManager.isScanning,
initialData: false,
builder: (c, snapshot) {
if (snapshot.data) {
return FloatingActionButton(
child: Icon(Icons.stop),
onPressed: () => bluetoothManager.stopScan(),
backgroundColor: Colors.red,
);
} else {
return FloatingActionButton(
child: Icon(Icons.search),
onPressed: () =>
bluetoothManager.startScan(timeout: Duration(seconds: 4)));
}
},
),
);
}
......
name: blue
description: A new Flutter project.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
......@@ -19,54 +8,15 @@ environment:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
flutter_bluetooth_basic:
git:
url: git://github.com/andrey-ushakov/flutter_bluetooth_basic
ref: master
dev_dependencies:
flutter_test:
sdk: flutter
flutter_blue: ^0.6.3+1
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
......@@ -13,6 +13,10 @@ dependencies:
hex: ^0.1.2
image: ^2.1.4
gbk_codec: ^0.3.1+3
flutter_bluetooth_basic:
git:
url: git://github.com/andrey-ushakov/flutter_bluetooth_basic
ref: master
dev_dependencies:
flutter_test:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment