connectToScannedFrame method

Future<void> connectToScannedFrame(
  1. BrilliantScannedDevice device
)

Implementation

Future<void> connectToScannedFrame(BrilliantScannedDevice device) async {
  try {
    _log.fine('connecting to scanned device: $device');
    frame = await BrilliantBluetooth.connect(device);
    _log.fine('device connected: ${frame!.device.remoteId}');

    // subscribe to connection state for the device to detect disconnections
    // so we can transition the app to a disconnected state
    await _refreshDeviceStateSubs();

    // refresh subscriptions to String rx and Data rx
    await _refreshRxSubs();

    try {
      // terminate the main.lua (if currently running) so we can run our lua code
      // TODO looks like if the signal comes too early after connection, it isn't registered
      await Future.delayed(const Duration(milliseconds: 500));
      await frame!.sendBreakSignal();
      await Future.delayed(const Duration(milliseconds: 500));

      await frame!.sendString(
          'print("Connected to Frame " .. frame.FIRMWARE_VERSION .. ", Mem: " .. tostring(collectgarbage("count")))',
          awaitResponse: true);

      // Frame is ready to go!
      currentState = ApplicationState.connected;
      if (mounted) setState(() {});
    } catch (e) {
      currentState = ApplicationState.disconnected;
      _log.fine('Error while sending break signal: $e');
      if (mounted) setState(() {});

      await disconnectFrame();
    }
  } catch (e) {
    currentState = ApplicationState.disconnected;
    _log.fine('Error while connecting and/or discovering services: $e');
    if (mounted) setState(() {});
  }
}