reconnectFrame method

Future<void> reconnectFrame()
inherited

Implementation

Future<void> reconnectFrame() async {
  if (frame != null) {
    try {
      _log.fine('reconnecting to existing device: $frame');
      // TODO get the BrilliantDevice return value from the reconnect call?
      // TODO am I getting duplicate devices/subscriptions?
      // Rather than fromUuid(), can I just call connectedDevice.device.connect() myself?
      await BrilliantBluetooth.reconnect(frame!.uuid);
      _log.fine('device connected: $frame');

      // subscribe to connection state for the device to detect disconnections
      // and 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(() {});
    }
  } else {
    currentState = ApplicationState.disconnected;
    _log.fine('Current device is null, reconnection not possible');
    if (mounted) setState(() {});
  }
}