summaryrefslogtreecommitdiff
path: root/lib/device.dart
blob: 94b2899943bcb14bb6328172ddf9d9a1f6cf2e44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:logger/logger.dart';

var logger = Logger(printer: PrettyPrinter());

// Is this even needed? I have no idea...
class Device extends StatelessWidget {
  const Device({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp();
  }
}

class DeviceScreen extends StatefulWidget {
  final BluetoothDevice btDevice;

  const DeviceScreen({super.key, required this.btDevice});

  @override
  State<StatefulWidget> createState() {
    return DeviceState();
  }
}

class DeviceState extends State<DeviceScreen> {
  String connectStatus = "<Status>";
  // ???
  StreamSubscription<BluetoothConnectionState> subs =
      Stream<BluetoothConnectionState>.empty().listen((e) => ());
  bool backActive = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Device details")),
      body: Center(
        child: Column(
          spacing: 20,
          children: [
            Text(connectStatus),
            ElevatedButton(
              onPressed: backActive ? backClick : null,
              child: Text("Back"),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _doConnect();
  }

  void backClick() {
    Navigator.pop(context);
  }

  void onConnStateChange(BluetoothConnectionState event) {
    setState(() {
      connectStatus = event.toString();
    });
    logger.i("New conn state: ${event.toString()}");
  }

  @override
  void deactivate() {
    super.deactivate();
    logger.i("Closing state");
    subs.cancel().ignore();
    widget.btDevice.disconnect().ignore();
  }

  void _doConnect() async {
    final dev = widget.btDevice;
    subs.cancel().ignore();
    subs = dev.connectionState.listen(onConnStateChange);
    try {
      logger.i("Try to connect...");
      // connect timeout doesn't work under Linux
      await dev.connect().timeout(Duration(seconds: 1));
      logger.i("Connected!");

      connectStatus = "Connected";
    } catch (e) {
      dev.disconnect().ignore();
      connectStatus = e.toString();
    } finally {
      backActive = true;
      if (mounted) {
        setState(() {});
      }
    }
  }
}