Skip to content

feat: added csv functionalities in soundmeter screen. #2796

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: flutter
Choose a base branch
from

Conversation

Yugesh-Kumar-S
Copy link
Contributor

@Yugesh-Kumar-S Yugesh-Kumar-S commented Jul 20, 2025

Fixes #2795

Changes

Screenshots / Recordings

screen-20250720-130234.mp4

Checklist:

  • No hard coding: I have used resources from strings.xml, dimens.xml and colors.xml without hard coding any value.
  • No end of file edits: No modifications done at end of resource files strings.xml, dimens.xml or colors.xml.
  • Code reformatting: I have reformatted code and fixed indentation in every file included in this pull request.
  • No extra space: My code does not contain any extra lines or extra spaces than the ones that are necessary.

Summary by Sourcery

Implement CSV data recording in the sound meter screen, providing UI controls to start/stop recording, save data files, and view logged recordings, while enhancing state management and error handling.

New Features:

  • Add recording toggle button to capture sound meter readings and store them in memory
  • Provide a save dialog for users to name and save recorded data as CSV files via CsvService
  • Add navigation to a logged data screen for reviewing previously recorded sound meter data

Enhancements:

  • Refactor SoundMeterStateProvider to support recording lifecycle, sensor error callbacks, and provider disposal
  • Replace MultiProvider with ChangeNotifierProvider and Consumer to streamline state management in the screen
  • Introduce localized strings for sensor error messages and chart annotations

Documentation:

  • Add new localization keys for sensor access errors and the 'Dangerous' label

Summary by Sourcery

Add CSV recording and viewing capabilities to the sound meter screen, including controls to start/stop recordings, save CSV files with headers, and navigate to previously logged data

New Features:

  • Provide a recording toggle to capture sound meter readings and store them in CSV format
  • Show a dialog to name and save recorded data as CSV files with ['Timestamp','DateTime','Readings','Latitude','Longitude'] headers
  • Add navigation to a logged data screen for reviewing saved recordings

Enhancements:

  • Refactor SoundMeterStateProvider to manage recording state, sensor error callbacks, and disposal
  • Replace MultiProvider with ChangeNotifierProvider and Consumer for streamlined state management
  • Enhance LoggedDataChartScreen to compute relative time axis and render custom side title widgets

Documentation:

  • Add localization keys for sensor access errors and the 'Dangerous' chart annotation

Copy link

sourcery-ai bot commented Jul 20, 2025

Reviewer's Guide

This PR adds full CSV recording support to the sound meter feature by integrating a CsvService into the UI, extending the state provider to track and export readings, refactoring the chart display to use timestamped data with formatted axis labels, and ensuring consistent CSV headers and localization across both sound and lux meter screens.

Sequence diagram for sound meter CSV recording and save flow

sequenceDiagram
    actor User
    participant SoundMeterScreen
    participant SoundMeterStateProvider
    participant CsvService
    User->>SoundMeterScreen: Tap record button
    SoundMeterScreen->>SoundMeterStateProvider: startRecording()
    SoundMeterStateProvider-->>SoundMeterScreen: isRecording = true
    User->>SoundMeterScreen: Tap stop record button
    SoundMeterScreen->>SoundMeterStateProvider: stopRecording()
    SoundMeterStateProvider-->>SoundMeterScreen: recordedData
    SoundMeterScreen->>User: Show save dialog
    User->>SoundMeterScreen: Enter file name
    SoundMeterScreen->>CsvService: saveCsvFile('soundmeter', fileName, data)
    CsvService-->>SoundMeterScreen: File saved
    SoundMeterScreen->>User: Show success/failure message
Loading

Sequence diagram for sensor error handling in sound meter

sequenceDiagram
    participant SoundMeterScreen
    participant SoundMeterStateProvider
    participant User
    SoundMeterScreen->>SoundMeterStateProvider: initializeSensors(onError)
    SoundMeterStateProvider-->>SoundMeterScreen: onSensorError callback (if error)
    SoundMeterScreen->>User: Show snackbar with error message
Loading

ER diagram for CSV data structure for sound and lux meter

erDiagram
    CSV_FILE {
      string Timestamp
      string DateTime
      string Readings
      string Latitude
      string Longitude
    }
    SOUND_METER ||--o{ CSV_FILE : records
    LUX_METER ||--o{ CSV_FILE : records
Loading

Class diagram for updated LuxMeterStateProvider CSV header structure

classDiagram
    class LuxMeterStateProvider {
      - bool _isRecording
      - List<List<dynamic>> _recordedData
      + bool get isRecording
      + void startRecording()
    }
    %% CSV header now: ['Timestamp', 'DateTime', 'Readings', 'Latitude', 'Longitude']
Loading

File-Level Changes

Change Details Files
Integrate CSV export and recording UI
  • Instantiate CsvService and inject into screen state
  • Add record toggle button to CommonScaffold with _toggleRecording handler
  • Implement _showSaveFileDialog and _navigateToLoggedData methods
lib/view/soundmeter_screen.dart
Enhance SoundMeterStateProvider for recording lifecycle
  • Introduce isRecording flag, _recordedData list and header initialization
  • Add startRecording/stopRecording methods and append timestamped rows
  • Refactor initializeSensors to accept onError callback and dispose provider
lib/providers/soundmeter_state_provider.dart
Adjust logged data chart to use timestamps and formatted labels
  • Set xDataColumnIndex to 0 for time column
  • Compute relativeTime from initial timestamp for FlSpot
  • Extract and use _sideTitleWidgets for time axis formatting
lib/view/logged_data_chart_screen.dart
Synchronize CSV headers and data indices for logged screens
  • Update xDataColumnIndex to 0 in LoggedDataScreen for both soundmeter and luxmeter
  • Initialize CSV header row in LuxMeterStateProvider
lib/view/logged_data_screen.dart
lib/providers/luxmeter_state_provider.dart
Add and apply new localization keys
  • Add soundmeterSnackBarMessage and dangerous keys to AppLocalizations
  • Provide English translations in app_localizations_en.dart
  • Use appLocalizations.dangerous in chart labelResolver
lib/l10n/app_localizations.dart
lib/l10n/app_localizations_en.dart

Assessment against linked issues

Issue Objective Addressed Explanation
#2795 Add CSV functionalities to the soundmeter instrument using csv_service.dart.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Yugesh-Kumar-S - I've reviewed your changes - here's some feedback:

  • The _showSaveFileDialog method mixes UI and CSV logic—consider extracting the file‐dialog UI and CSV operations into separate helpers or widgets to keep the screen code concise and testable.
  • Currently the filename input defaults to an empty string—pre-populating it with a timestamp-based default (e.g. “soundmeter_20240612_1530”) would improve the UX.
  • The TextEditingController in _showSaveFileDialog isn’t disposed; consider managing it at the widget level or disposing it after the dialog closes to prevent potential memory leaks.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The `_showSaveFileDialog` method mixes UI and CSV logic—consider extracting the file‐dialog UI and CSV operations into separate helpers or widgets to keep the screen code concise and testable.
- Currently the filename input defaults to an empty string—pre-populating it with a timestamp-based default (e.g. “soundmeter_20240612_1530”) would improve the UX.
- The `TextEditingController` in `_showSaveFileDialog` isn’t disposed; consider managing it at the widget level or disposing it after the dialog closes to prevent potential memory leaks.

## Individual Comments

### Comment 1
<location> `lib/view/soundmeter_screen.dart:135` </location>
<code_context>
+
+  Future<void> _showSaveFileDialog(List<List<dynamic>> data) async {
+    final TextEditingController filenameController = TextEditingController();
+    final String defaultFilename = '';
+    filenameController.text = defaultFilename;
+
</code_context>

<issue_to_address>
Default filename is set to an empty string, which may lead to invalid file names.

An empty default filename may cause issues on some platforms. Please use a meaningful default, like a timestamp or instrument name.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
  Future<void> _showSaveFileDialog(List<List<dynamic>> data) async {
    final TextEditingController filenameController = TextEditingController();
    final String defaultFilename = '';
    filenameController.text = defaultFilename;
=======
  Future<void> _showSaveFileDialog(List<List<dynamic>> data) async {
    final TextEditingController filenameController = TextEditingController();
    final String defaultFilename = 'soundmeter_${DateTime.now().toIso8601String().replaceAll(":", "").replaceAll("-", "").replaceAll(".", "").substring(0, 15)}.csv';
    filenameController.text = defaultFilename;
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `lib/view/soundmeter_screen.dart:167` </location>
<code_context>
+    );
+
+    if (fileName != null) {
+      _csvService.writeMetaData('soundmeter', data);
+      final file = await _csvService.saveCsvFile('soundmeter', fileName, data);
+      if (mounted) {
</code_context>

<issue_to_address>
writeMetaData is called before saveCsvFile, but its necessity is unclear.

If writeMetaData isn't always needed or may fail, handle its result or errors. Otherwise, clarify its purpose in the save process.
</issue_to_address>

### Comment 3
<location> `lib/providers/soundmeter_state_provider.dart:105` </location>
<code_context>
   void _updateData() {
     final db = _currentDb;
     final time = _currentTime;
+    if (_isRecording) {
+      final relativeTime = time - _recordingStartTime;
+      final now = DateTime.now();
</code_context>

<issue_to_address>
Recording data includes formatted date and relative time, but may grow unbounded.

Long recording sessions may cause _recordedData to consume excessive memory. Consider limiting recording duration or implementing data chunking.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

github-actions bot commented Jul 20, 2025

@Yugesh-Kumar-S
Copy link
Contributor Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Yugesh-Kumar-S - I've reviewed your changes - here's some feedback:

  • CSV header definitions are duplicated in each provider; consider defining them in a shared constant or in CsvService to avoid repetition.
  • The save-file dialog and snackbar UI logic could be factored out into helper methods or widgets to DRY up the sound meter screen.
  • The sensor error handling strategy is only applied during initialization; consider unifying error callbacks for runtime sensor failures to ensure consistent reporting.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- CSV header definitions are duplicated in each provider; consider defining them in a shared constant or in CsvService to avoid repetition.
- The save-file dialog and snackbar UI logic could be factored out into helper methods or widgets to DRY up the sound meter screen.
- The sensor error handling strategy is only applied during initialization; consider unifying error callbacks for runtime sensor failures to ensure consistent reporting.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

add csv functionalities to soundmeter.
1 participant