Commit 883a2aac authored by Andrey's avatar Andrey

Example bluetooth project: can scan and print once.

parent 1923b6dc
PODS: PODS:
- Flutter (1.0.0) - Flutter (1.0.0)
- flutter_blue (0.0.1): - flutter_bluetooth_basic (0.0.1):
- Flutter - Flutter
- flutter_blue/Protos (= 0.0.1)
- flutter_blue/Protos (0.0.1):
- Flutter
- Protobuf
- Protobuf (3.11.0)
DEPENDENCIES: DEPENDENCIES:
- Flutter (from `Flutter`) - Flutter (from `Flutter`)
- flutter_blue (from `.symlinks/plugins/flutter_blue/ios`) - flutter_bluetooth_basic (from `.symlinks/plugins/flutter_bluetooth_basic/ios`)
SPEC REPOS:
trunk:
- Protobuf
EXTERNAL SOURCES: EXTERNAL SOURCES:
Flutter: Flutter:
:path: Flutter :path: Flutter
flutter_blue: flutter_bluetooth_basic:
:path: ".symlinks/plugins/flutter_blue/ios" :path: ".symlinks/plugins/flutter_bluetooth_basic/ios"
SPEC CHECKSUMS: SPEC CHECKSUMS:
Flutter: 0e3d915762c693b495b44d77113d4970485de6ec Flutter: 0e3d915762c693b495b44d77113d4970485de6ec
flutter_blue: be3f2be2f5fda254d174896c0738b2fcb6b1073e flutter_bluetooth_basic: 0e4e27e22b50b3a25cc1d1e131953feb4af414f4
Protobuf: 394b2bf29ec303f4325e3ee4892c09e675647152
PODFILE CHECKSUM: 3dbe063e9c90a5d7c9e4e76e70a821b9e2c1d271 PODFILE CHECKSUM: 3dbe063e9c90a5d7c9e4e76e70a821b9e2c1d271
......
...@@ -40,8 +40,15 @@ ...@@ -40,8 +40,15 @@
<string>UIInterfaceOrientationLandscapeRight</string> <string>UIInterfaceOrientationLandscapeRight</string>
</array> </array>
<key>NSBluetoothAlwaysUsageDescription</key> <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> <key>UIViewControllerBasedStatusBarAppearance</key>
<false/> <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> </dict>
</plist> </plist>
import 'dart:convert';
import 'package:flutter/material.dart'; 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()); void main() => runApp(MyApp());
...@@ -7,7 +8,7 @@ class MyApp extends StatelessWidget { ...@@ -7,7 +8,7 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
title: 'Flutter Demo', title: 'Bluetooth demo',
theme: ThemeData( theme: ThemeData(
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
), ),
...@@ -19,82 +20,60 @@ class MyApp extends StatelessWidget { ...@@ -19,82 +20,60 @@ class MyApp extends StatelessWidget {
class MyHomePage extends StatefulWidget { class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key); MyHomePage({Key key, this.title}) : super(key: key);
final String title; final String title;
final FlutterBlue flutterBlue = FlutterBlue.instance; // final FlutterBlue flutterBlue = FlutterBlue.instance;
@override @override
_MyHomePageState createState() => _MyHomePageState(); _MyHomePageState createState() => _MyHomePageState();
} }
class _MyHomePageState extends State<MyHomePage> { class _MyHomePageState extends State<MyHomePage> {
List<ScanResult> _scanResults = []; BluetoothManager bluetoothManager = BluetoothManager.instance;
bool _connected = false;
void _scanDevices() { Future sleep3() {
setState(() { return Future<dynamic>.delayed(const Duration(seconds: 7), () => "1");
_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}');
print('FOUND !!! ${scanResult.length}'); void _testPrint(BluetoothDevice printer) async {
scanResult.forEach((ScanResult scanRes) async { // print('Test print.... name: ${printer.name}');
if (scanRes.device.name.isNotEmpty) { if (printer != null && printer.address != null) {
if (!_scanResults.contains(scanRes)) { // Connect
_scanResults.add(scanRes); await bluetoothManager.connect(printer);
setState(() {
_scanResults // Subscribe to the events
.sort((scanRes1, scanRes2) => scanRes2.rssi - scanRes1.rssi); 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( _connected = true;
'\t> ${scanRes.device.name} : ${scanRes.rssi} : ${_scanResults.length}'); 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(); // TODO show message "Data sent"
print('\t>connected'); } else {
// TODO show message "Can't connect to the device"
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');
} }
@override @override
...@@ -103,49 +82,64 @@ class _MyHomePageState extends State<MyHomePage> { ...@@ -103,49 +82,64 @@ class _MyHomePageState extends State<MyHomePage> {
appBar: AppBar( appBar: AppBar(
title: Text(widget.title), title: Text(widget.title),
), ),
body: ListView.builder( body: StreamBuilder<List<BluetoothDevice>>(
itemCount: _scanResults.length, stream: bluetoothManager.scanResults,
itemBuilder: (BuildContext context, int index) { initialData: [],
return InkWell( builder: (c, snapshot) => Column(
onTap: () => testPrint(_scanResults[index], context), children: snapshot.data
child: Column( .map((d) => InkWell(
children: <Widget>[ onTap: () => _testPrint(d),
Container( child: Column(
height: 60, children: <Widget>[
padding: EdgeInsets.only(left: 10), Container(
alignment: Alignment.centerLeft, height: 60,
child: Row( padding: EdgeInsets.only(left: 10),
children: <Widget>[ alignment: Alignment.centerLeft,
Icon(Icons.print), child: Row(
SizedBox(width: 10), children: <Widget>[
Expanded( Icon(Icons.print),
child: Column( SizedBox(width: 10),
crossAxisAlignment: CrossAxisAlignment.start, Expanded(
mainAxisAlignment: MainAxisAlignment.center, child: Column(
children: <Widget>[ crossAxisAlignment: CrossAxisAlignment.start,
Text( mainAxisAlignment: MainAxisAlignment.center,
'Signal ${_scanResults[index].rssi + 100}% : ${_scanResults[index].device.name}', children: <Widget>[
), Text(d.name ?? ''),
Text( Text(d.address),
'Click to print a test receipt', Text(
style: TextStyle(color: Colors.grey[700]), 'Click to print a test receipt',
), style: TextStyle(color: Colors.grey[700]),
], ),
],
),
)
],
),
), ),
) Divider(),
], ],
), ),
), ))
Divider(), .toList(),
], ),
),
);
},
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: StreamBuilder<bool>(
onPressed: _scanDevices, stream: bluetoothManager.isScanning,
tooltip: 'Scan', initialData: false,
child: Icon(Icons.add), 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 name: blue
description: A new Flutter project. 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 version: 1.0.0+1
environment: environment:
...@@ -19,54 +8,15 @@ environment: ...@@ -19,54 +8,15 @@ environment:
dependencies: dependencies:
flutter: flutter:
sdk: 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 cupertino_icons: ^0.1.2
flutter_bluetooth_basic:
git:
url: git://github.com/andrey-ushakov/flutter_bluetooth_basic
ref: master
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter 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: 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 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: ...@@ -13,6 +13,10 @@ dependencies:
hex: ^0.1.2 hex: ^0.1.2
image: ^2.1.4 image: ^2.1.4
gbk_codec: ^0.3.1+3 gbk_codec: ^0.3.1+3
flutter_bluetooth_basic:
git:
url: git://github.com/andrey-ushakov/flutter_bluetooth_basic
ref: master
dev_dependencies: dev_dependencies:
flutter_test: 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