Skip to content

Commit

Permalink
clearer sdcard variable names + exclusive access for storage page
Browse files Browse the repository at this point in the history
  • Loading branch information
kevvz committed Sep 30, 2024
1 parent c38b292 commit 10aa9e2
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 73 deletions.
4 changes: 2 additions & 2 deletions app/lib/backend/http/api/memories.dart
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,10 @@ Future<bool> setMemoryEventsState(
}

//this is expected to return complete memories
Future<List<ServerMemory>> sendStorageToBackend(File file, String dateTimeStorageString) async {
Future<List<ServerMemory>> sendStorageToBackend(File file, String sdCardDateTimeString) async {
var request = http.MultipartRequest(
'POST',
Uri.parse('${Env.apiBaseUrl}sdcard_memory?date_time=$dateTimeStorageString'),
Uri.parse('${Env.apiBaseUrl}sdcard_memory?date_time=$sdCardDateTimeString'),
);
request.headers.addAll({'Authorization': await getAuthHeader()});
request.files.add(await http.MultipartFile.fromPath('file', file.path, filename: basename(file.path)));
Expand Down
19 changes: 12 additions & 7 deletions app/lib/backend/preferences.dart
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,18 @@ class SharedPreferencesUtil {

set showDiscardedMemories(bool value) => saveBool('showDiscardedMemories', value);

int get currentStorageBytes => getInt('currentStorageBytes') ?? 0;

set currentStorageBytes(int value) => saveInt('currentStorageBytes', value);

int get previousStorageBytes => getInt('previousStorageBytes') ?? 0;

set previousStorageBytes(int value) => saveInt('previousStorageBytes', value);

bool get deviceIsV2 => getBool('deviceIsV2') ?? false;

set deviceIsV2(bool value) => saveBool('deviceIsV2', value);

int get enabledPluginsCount => pluginsList.where((element) => element.enabled).length;

int get enabledPluginsIntegrationsCount =>
Expand Down Expand Up @@ -407,11 +419,4 @@ class SharedPreferencesUtil {

bool get locationPermissionRequested => getBool('locationPermissionRequested') ?? false;

int get currentStorageBytes => getInt('currentStorageBytes') ?? 0;

set currentStorageBytes(int value) => saveInt('currentStorageBytes', value);

int get previousStorageBytes => getInt('previousStorageBytes') ?? 0;

set previousStorageBytes(int value) => saveInt('previousStorageBytes', value);
}
8 changes: 4 additions & 4 deletions app/lib/pages/memories/widgets/processing_capture.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ class _MemoryCaptureWidgetState extends State<MemoryCaptureWidget> {
bool havingCapturingMemory = provider.capturingProcessingMemory != null;

/// Friend V2 SD CARD functionality
String totalTimeRemainingString = (provider.timeToSend - provider.timeAlreadySent).toStringAsFixed(2);
String totalsdCardSecondsRemainingString = (provider.sdCardSecondsTotal - provider.sdCardSecondsReceived).toStringAsFixed(2);

if (provider.storageIsReady) {
var banner = 'You have $totalTimeRemainingString seconds of Storage Remaining. Click here to see';
if (provider.sdCardReady) {
var banner = 'You have $totalsdCardSecondsRemainingString seconds of Storage Remaining. Click here to see';
Future.delayed(Duration.zero, () {
ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
ScaffoldMessenger.of(context).showMaterialBanner(
Expand All @@ -68,7 +68,7 @@ class _MemoryCaptureWidgetState extends State<MemoryCaptureWidget> {
),
);
});
provider.setStorageIsReady(false);
provider.setsdCardReady(false);
}

return (showPhoneMic || isConnected || havingCapturingMemory)
Expand Down
10 changes: 5 additions & 5 deletions app/lib/pages/sdcard/page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ class _SdCardCapturePageState extends State<SdCardCapturePage> {
@override
Widget build(BuildContext context) {
return Consumer2<CaptureProvider, DeviceProvider>(builder: (context, provider, deviceProvider, child) {
String timeRemaining = (provider.timeToSend - provider.timeAlreadySent).toStringAsFixed(2);
String sdCardSecondsRemaining = (provider.sdCardSecondsTotal - provider.sdCardSecondsReceived).toStringAsFixed(2);
String percentageRemaining = provider.totalStorageFileBytes == 0
? '0.0'
: (provider.totalBytesReceived / provider.totalStorageFileBytes * 100).toStringAsFixed(2);

String displayText = 'about $timeRemaining seconds remaining\n$percentageRemaining% there';
if (provider.isDone) {
String displayText = 'about $sdCardSecondsRemaining seconds remaining\n$percentageRemaining% there';
if (provider.sdCardDownloadDone) {
displayText = 'Done! Check back later for your memories.';
}

Expand All @@ -44,7 +44,7 @@ class _SdCardCapturePageState extends State<SdCardCapturePage> {
mainAxisAlignment: MainAxisAlignment.center,
children: [
LinearProgressIndicator(
value: provider.timeAlreadySent / provider.timeToSend,
value: provider.sdCardSecondsReceived / (provider.sdCardSecondsTotal == 0 ? 1 : provider.sdCardSecondsTotal),
backgroundColor: Colors.grey,
color: Colors.green,
minHeight: 10,
Expand All @@ -60,7 +60,7 @@ class _SdCardCapturePageState extends State<SdCardCapturePage> {
),
onPressed: () {
setState(() {
displayText = 'about $timeRemaining seconds remaining, about $percentageRemaining% there';
displayText = 'about $sdCardSecondsRemaining seconds remaining, about $percentageRemaining% there';
});
if (!provider.sdCardIsDownloading) {
provider.sendStorage(deviceProvider.connectedDevice!.id);
Expand Down
24 changes: 22 additions & 2 deletions app/lib/pages/settings/page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,28 @@ class _SettingsPageState extends State<SettingsPage> {
),
const SizedBox(height: 20),
getItemAddOn2(
'SD Card Import',
() => routeToPage(context, const SdCardCapturePage()),
'SD Card Import (V2)',
() {
if (!SharedPreferencesUtil().deviceIsV2) {
showDialog(
context: context,
builder: (c) => getDialog(
context,
() => Navigator.of(context).pop(),
() => {},
'V2 undetected',
'We see that you either have a V1 device or your device is not connected. SD Card functionality is available only for V2 devices.',
singleButton: true,
),
);
}
else {
var page = const SdCardCapturePage();
routeToPage(context, page);
}

},
// https://www.omi.me/products/friend-dev-kit-2
icon: Icons.sd_card,
),
const SizedBox(height: 8),
Expand Down
73 changes: 34 additions & 39 deletions app/lib/providers/capture_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,32 +75,26 @@ class CaptureProvider extends ChangeNotifier
// Memory creation variables
String conversationId = const Uuid().v4();
int elapsedSeconds = 0;
List<int> currentStorageFiles = <int>[];
StorageBytesUtil storageUtil = StorageBytesUtil();

// -----------------------

String? processingMemoryId;
ServerProcessingMemory? capturingProcessingMemory;
Timer? _processingMemoryWatchTimer;

int totalStorageFileBytes = 0;
int totalBytesReceived = 0;
double timeToSend = 0.0;
double timeAlreadySent = 0.0;
bool isDone = false;
bool storageIsReady = false;
List<int> currentStorageFiles = <int>[];
int sdCardFileNum = 1;

int totalStorageFileBytes = 0; // how much in storage
int totalBytesReceived = 0; // how much already received
double sdCardSecondsTotal = 0.0; // time to send the next chunk
double sdCardSecondsReceived = 0.0;
bool sdCardDownloadDone = false;
bool sdCardReady = false;
bool sdCardIsDownloading = false;
bool sendNotification = false;
String btConnectedTime = "";
String dateTimeStorageString = "";
Timer? sdCardReconnectionTimer;

void setIsDone(bool value) {
isDone = value;
notifyListeners();
}


void setSdCardIsDownloading(bool value) {
sdCardIsDownloading = value;
notifyListeners();
Expand Down Expand Up @@ -406,7 +400,6 @@ class CaptureProvider extends ChangeNotifier
}

Future sendStorage(String id) async {
// storageUtil = StorageBytesUtil();
if (_storageStream != null) {
_storageStream?.cancel();
}
Expand Down Expand Up @@ -436,34 +429,30 @@ class CaptureProvider extends ChangeNotifier
if (value[0] == 0) {
//valid command
DateTime storageStartTime = DateTime.now();
dateTimeStorageString = storageStartTime.toIso8601String();
debugPrint('good to go');
} else if (value[0] == 3) {
debugPrint('bad file size. finishing...');
} else if (value[0] == 4) {
//file size is zero.
debugPrint('file size is zero. going to next one....');
// getFileFromDevice(storageUtil.getFileNum() + 1);
// getFileFromDevice(sdCardFileNum + 1);
} else if (value[0] == 100) {
//valid end command

isDone = true;
sdCardDownloadDone = true;
sdCardIsDownloading = false;
debugPrint('done. sending to backend....trying to dl more');

sdCardSocket.sdCardChannel?.sink.add(value); //replace

storageUtil.clearAudioBytes();
SharedPreferencesUtil().currentStorageBytes = 0;
SharedPreferencesUtil().previousStorageBytes = 0;
clearFileFromDevice(storageUtil.getFileNum());
clearFileFromDevice(sdCardFileNum);
} else {
//bad bit
debugPrint('Error bit returned');
}
} else if (value.length == 83) {
totalBytesReceived += 80;
// storageUtil!.storeFrameStoragePacket(value);
if (sdCardSocket.sdCardConnectionState != WebsocketConnectionStatus.connected) {
debugPrint('websocket provider state: ${sdCardSocket.sdCardConnectionState}');
//means we are disconnected, stop all transmission. attempt reconnection
Expand All @@ -472,7 +461,7 @@ class CaptureProvider extends ChangeNotifier
return;
}
sdCardIsDownloading = false;
pauseFileFromDevice(storageUtil.getFileNum());
pauseFileFromDevice(sdCardFileNum);
debugPrint('paused file from device');
//attempt reconnection
sdCardSocket.sdCardChannel?.sink.close();
Expand All @@ -490,7 +479,7 @@ class CaptureProvider extends ChangeNotifier
debugPrint('sdCardReconnectionTimer');
if (sdCardSocket.sdCardConnectionState == WebsocketConnectionStatus.connected) {
sdCardIsDownloading = true;
getFileFromDevice(storageUtil.getFileNum(), totalBytesReceived);
getFileFromDevice(sdCardFileNum, totalBytesReceived);
}
});

Expand All @@ -499,32 +488,32 @@ class CaptureProvider extends ChangeNotifier
}

sdCardSocket.sdCardChannel?.sink.add(value);
timeAlreadySent = ((totalBytesReceived.toDouble() / 80.0) / 100.0) * 2.2;
sdCardSecondsReceived = ((totalBytesReceived.toDouble() / 80.0) / 100.0) * 2.2;
SharedPreferencesUtil().currentStorageBytes = totalBytesReceived;
}
notifyListeners();
});

getFileFromDevice(storageUtil.getFileNum(), totalBytesReceived);
getFileFromDevice(sdCardFileNum, totalBytesReceived);
// notifyListeners();
}

Future getFileFromDevice(int fileNum, int offset) async {
storageUtil.fileNum = fileNum;
sdCardFileNum = fileNum;
int command = 0;
_writeToStorage(_recordingDevice!.id, storageUtil.fileNum, command, offset);
_writeToStorage(_recordingDevice!.id, sdCardFileNum, command, offset);
}

Future clearFileFromDevice(int fileNum) async {
storageUtil.fileNum = fileNum;
sdCardFileNum = fileNum;
int command = 1;
_writeToStorage(_recordingDevice!.id, storageUtil.fileNum, command, 0);
_writeToStorage(_recordingDevice!.id, sdCardFileNum, command, 0);
}

Future pauseFileFromDevice(int fileNum) async {
storageUtil.fileNum = fileNum;
sdCardFileNum = fileNum;
int command = 3;
_writeToStorage(_recordingDevice!.id, storageUtil.fileNum, command, 0);
_writeToStorage(_recordingDevice!.id, sdCardFileNum, command, 0);
}

void _notifySdCardComplete() {
Expand All @@ -536,8 +525,8 @@ class CaptureProvider extends ChangeNotifier
);
}

void setStorageIsReady(bool value) {
storageIsReady = value;
void setsdCardReady(bool value) {
sdCardReady = value;
notifyListeners();
}

Expand Down Expand Up @@ -674,8 +663,14 @@ class CaptureProvider extends ChangeNotifier
currentStorageFiles = await _getStorageList(_recordingDevice!.id);
if (currentStorageFiles.isEmpty) {
debugPrint('No storage files found');
SharedPreferencesUtil().deviceIsV2 = false;
debugPrint('Device is not V2');

return;
}
SharedPreferencesUtil().deviceIsV2 = true;
debugPrint('Device is V2');
debugPrint('Device model name: ${_recordingDevice!.name}');
debugPrint('Storage files: $currentStorageFiles');
totalStorageFileBytes = currentStorageFiles.fold(0, (sum, fileSize) => sum + fileSize);
var previousStorageBytes = SharedPreferencesUtil().previousStorageBytes;
Expand All @@ -691,7 +686,7 @@ class CaptureProvider extends ChangeNotifier
totalBytesReceived = 0;
}
SharedPreferencesUtil().previousStorageBytes = totalStorageFileBytes;
timeToSend = ((totalStorageFileBytes.toDouble() / 80.0) / 100.0) * 2.2;
sdCardSecondsTotal = ((totalStorageFileBytes.toDouble() / 80.0) / 100.0) * 2.2; // change 2.2 depending on empirical dl speed

debugPrint('totalBytesReceived in initiateStorageBytesStreaming: $totalBytesReceived');
debugPrint('previousStorageBytes in initiateStorageBytesStreaming: $previousStorageBytes');
Expand All @@ -708,8 +703,8 @@ class CaptureProvider extends ChangeNotifier
btConnectedTime: btConnectedTime,
);

if (totalStorageFileBytes > 0) {
storageIsReady = true;
if (totalStorageFileBytes > 100) {
sdCardReady = true;
}
notifyListeners();
}
Expand Down
Loading

0 comments on commit 10aa9e2

Please sign in to comment.