getAudioCodec method

Future<AudioCodec> getAudioCodec()

Implementation

Future<AudioCodec> getAudioCodec() async {
  if (!isConnected || _connectedDevice == null) {
    throw Exception('Device not connected');
  }

  try {
    final services = await _connectedDevice!.discoverServices();
    final audioService = services.firstWhere(
      (s) =>
          s.uuid.str128.toLowerCase() ==
          DeviceConstants.omiServiceUuid.toLowerCase(),
      orElse: () => throw Exception('Audio service not found'),
    );

    final codecCharacteristic = audioService.characteristics.firstWhere(
      (c) =>
          c.uuid.str128.toLowerCase() ==
          DeviceConstants.codecCharacteristicUuid.toLowerCase(),
      orElse: () => throw Exception('Audio codec characteristic not found'),
    );

    final codecValue = await codecCharacteristic.read();
    print('Raw codec value from Omi firmware: $codecValue');

    if (codecValue.isNotEmpty) {
      final codecByte = codecValue[0];
      print('Omi codec byte: $codecByte');

      // Use the same mapping as Python client
      switch (codecByte) {
        case 1:
          return AudioCodec.pcm8;
        case 20:
          return AudioCodec.opus;
        case 21:
          return AudioCodec.opusFS320;
        default:
          print('Unknown codec byte: $codecByte, defaulting to Opus');
          return AudioCodec.opus; // Default to Opus as per Python client
      }
    }

    return AudioCodec.opus; // Default to Opus
  } catch (e) {
    print('Failed to get audio codec: $e, defaulting to Opus');
    return AudioCodec.opus;
  }
}