### Create Example Application Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Command to generate an example application for a Flutter package or plugin. ```bash flutter create example ``` -------------------------------- ### Complete Android Manifest Example Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/app_usage/README.md An example of the beginning of your `AndroidManifest.xml` file, including the package name, the usage stats permission, and the tools namespace. ```xml ``` -------------------------------- ### Start Listening for Notifications in Flutter Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/notifications/README.md Set up a stream subscription to listen for incoming notification events. Handle potential NotificationExceptions during setup. ```dart Notifications _notifications; StreamSubscription _subscription; ... void onData(NotificationEvent event) { print(event); } void startListening() { _notifications = new Notifications(); try { _subscription = _notifications!.notificationStream!.listen(onData); } on NotificationException catch (exception) { print(exception); } } ``` -------------------------------- ### Changelog Entry Example Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Example of a version entry in the CHANGELOG.md file, detailing changes made in a specific version. ```markdown ## 2.0.2 * Updated the API to take a list of types rather than a single type, when requesting health data. ``` -------------------------------- ### Start Foreground Service Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/flutter_foreground_service/README.md Use this code to initiate the foreground service. Ensure the package is imported and set up correctly. ```dart await ForegroundService().start(); ``` -------------------------------- ### Pubspec.yaml Example Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Configuration file for a Flutter package or plugin. Includes name, description, version, and homepage. ```yaml name: health description: Wrapper for the iOS HealthKit and Android GoogleFit services. version: 2.0.2 homepage: https://github.com/cph-cachet/flutter-plugins ``` -------------------------------- ### Initialize and Authenticate Empatica Device Manager Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/empatica_e4link/README.md Set up the Empatica plugin by creating a device manager instance and authenticating with your Empatica API key. Ensure you listen to status events before starting the scan. ```dart import 'package:empatica_e4link/empatica.dart'; ... // create a device manager that will handle method calls EmpaticaPlugin deviceManager = EmpaticaPlugin(); await deviceManager .authenticateWithAPIKey('your api key goes '); ... // first listen to status events before trying to connect deviceManager.statusEventSink?.listen((event) async { switch (event.runtimeType) { case UpdateStatus: //the status of the device manager print((event as UpdateStatus).status) break; case DiscoverDevice: await deviceManager.connectDevice((event as DiscoverDevice).device); break; } }); // when status is READY we can start scanning for devices await deviceManager.startScanning(); ``` -------------------------------- ### Dart Usage: Configure and Start Location Tracking Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/carp_background_location/README.md Configure the LocationManager with desired interval, distance filter, and notification details, then start listening for location updates. ```dart // configure the location manager LocationManager().interval = 1; LocationManager().distanceFilter = 0; LocationManager().notificationTitle = 'CARP Location Example'; LocationManager().notificationMsg = 'CARP is tracking your location'; // get the current location await LocationManager().getCurrentLocation(); // start listen to location updates StreamSubscription locationSubscription = LocationManager() .locationStream .listen((LocationDto loc) => print(loc)); // cancel listening and stop the location manager locationSubscription?.cancel(); LocationManager().stop(); ``` -------------------------------- ### Start Screen State Listening in Flutter Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/screen_state/README.md Initiates listening to screen state changes by creating a Screen instance and subscribing to its stream. Handles potential ScreenStateException during subscription. ```dart Screen _screen; StreamSubscription _subscription; void onData(ScreenStateEvent event) { print(event); } void startListening() { _screen = new Screen(); try { _subscription = _screen.screenStateStream.listen(onData); } on ScreenStateException catch (exception) { print(exception); } } ``` -------------------------------- ### Get Five-Day Weather Forecast by Location Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/weather/README.md Fetches a 5-day weather forecast with 3-hour intervals for a given latitude and longitude. Requires an initialized WeatherFactory. ```dart double lat = 55.0111; double lon = 15.0569; String key = '856822fd8e22db5e1ba48c0e7d69844a'; String cityName = 'Kongens Lyngby'; WeatherFactory wf = WeatherFactory(key); List forecast = await wf.fiveDayForecastByLocation(lat, lon); ``` -------------------------------- ### Fetch Air Quality Data by City Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/air_quality/README.md Fetch air quality data for a specific city using its name. Example shown for 'Munich'. ```dart /// Via city name (Munich) AirQualityData feedFromCity = await airQuality.feedFromCity('munich'); ``` -------------------------------- ### Listening to Ambient Light Sensor Events Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/light/README.md Listen for ambient light sensor events (lux values) after requesting authorization. Cancel the subscription when no longer needed. This stream may emit PlatformException on iOS if setup is incomplete. ```dart StreamSubscription? _lightEvents; Future startListening() async { await Light().requestAuthorization(); // no-op on Android _lightEvents = Light().lightSensorStream.listen((int luxValue) { // Do something with lux. }); } void stopListening() { _lightEvents?.cancel(); } ``` -------------------------------- ### Fetch Air Quality Data by Station ID Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/air_quality/README.md Fetch air quality data for a specific station using its ID. Example shown for Gothenburg weather station. ```dart /// Via station ID (Gothenburg weather station) AirQualityData feedFromStationId = await airQuality.feedFromStationId('7867'); ``` -------------------------------- ### Invoke MethodChannel for Simple Calls Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Use MethodChannel for 'get' calls that produce a single result. Ensure parameters are correctly formatted as a Map. ```dart /// Set parameters Map interval = {'start': start, 'end': end}; /// Get result and parse it as a Map of Map usage = await _methodChannel.invokeMethod('getUsage', interval); ``` -------------------------------- ### Get Current Weather by City Name Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/weather/README.md Retrieves the current weather information for a specified city name. Requires an initialized WeatherFactory instance. ```dart double lat = 55.0111; double lon = 15.0569; String key = '856822fd8e22db5e1ba48c0e7d69844a'; String cityName = 'Kongens Lyngby'; WeatherFactory wf = WeatherFactory(key); Weather w = await wf.currentWeatherByCityName(cityName); ``` -------------------------------- ### Get Current Weather by Location Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/weather/README.md Fetches the current weather data for a given latitude and longitude. Ensure you have initialized WeatherFactory with a valid API key. ```dart double lat = 55.0111; double lon = 15.0569; String key = '856822fd8e22db5e1ba48c0e7d69844a'; String cityName = 'Kongens Lyngby'; WeatherFactory wf = WeatherFactory(key); Weather w = await wf.currentWeatherByLocation(lat, lon); ``` -------------------------------- ### Get Actual Sampling Rate Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/audio_streamer/README.md Retrieve the actual sampling rate being used by the audio stream. This may differ from the requested rate, especially on iOS. ```dart // Get the real sampling rate - may be different from the requested sampling rate. int sampleRate = await AudioStreamer().actualSampleRate; ``` -------------------------------- ### Fetch Air Quality Data by Geo Location Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/air_quality/README.md Fetch air quality data using geographical coordinates (latitude and longitude). Example shown for Berlin. ```dart /// Via Geo Location (Berlin) AirQualityData feedFromGeoLocation = await airQuality.feedFromGeoLocation('52.6794', '12.5346'); ``` -------------------------------- ### Get Five-Day Weather Forecast by City Name Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/weather/README.md Retrieves a 5-day weather forecast, with data points every 3 hours, for a specified city name. Ensure WeatherFactory is properly initialized. ```dart double lat = 55.0111; double lon = 15.0569; String key = '856822fd8e22db5e1ba48c0e7d69844a'; String cityName = 'Kongens Lyngby'; WeatherFactory wf = WeatherFactory(key); List forecast = await wf.fiveDayForecastByCityName(cityName); ``` -------------------------------- ### Get Device Information and Battery Status Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Retrieve device information, including product name, and check the battery level after connecting to a Movesense device. ```dart var info = await device.getDeviceInfo(); print('Product name: ${info?.productName}'); var battery = await device.getBatteryStatus(); print('Battery level: ${battery.name}'); ``` -------------------------------- ### Listen to Heart Rate Stream Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Start listening to the heart rate stream to receive average BPM and R-R interval data. Remember to cancel the subscription when done to prevent memory leaks. ```dart // Start listening to the stream of heart rate readings hrSubscription = device.hr.listen((hr) { print('Heart Rate: ${hr.average}, R-R Interval: ${hr.rr} ms'); }); // Stop listening. hrSubscription?.cancel(); ``` -------------------------------- ### Requesting Light Sensor Authorization Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/light/README.md Request authorization to access the light sensor. This is a no-op on Android, but required for iOS. Ensure iOS setup is complete before calling. ```dart final LightAuthorizationStatus status = await Light().requestAuthorization(); ``` -------------------------------- ### Get App Usage Statistics Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/app_usage/README.md Retrieve application usage statistics within a specified date range using the `AppUsage().getAppUsage()` method. Ensure you handle potential `AppUsageException`. ```dart void getUsageStats() async { try { DateTime endDate = DateTime.now(); DateTime startDate = endDate.subtract(Duration(hours: 1)); List infoList = await AppUsage().getAppUsage(startDate, endDate); setState(() => _infos = infoList); for (var info in infoList) { print(info.toString()); } } on AppUsageException catch (exception) { print(exception); } } ``` -------------------------------- ### Listen to Empatica Data Events Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/empatica_e4link/README.md Listen to the dataEventSink stream to receive real-time physiological data from the Empatica E4 device. It's recommended to start listening when the status is CONNECTING. ```dart deviceManager.dataEventSink?.listen((event) { switch (event.runtimeType) { // update each data point with the appropriate data case ReceiveBVP: event as ReceiveBVP; break; ``` -------------------------------- ### Initialize and Connect to eSense Device Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Instantiate ESenseManager with the device name and listen to connection events before initiating the connection. The connect() method is asynchronous. ```dart import 'package:esense_flutter/esense.dart'; ... // create an ESenseManager by specifying the name of the device ESenseManager eSenseManager = ESenseManager('eSense-0332'); ... // first listen to connection events before trying to connect eSenseManager.connectionEvents.listen((event) { print('CONNECTION event: $event'); } ... // try to connect to the eSense device bool connecting = await eSenseManager.connect(); ``` -------------------------------- ### Initialize Air Quality Service Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/air_quality/README.md Initialize the AirQuality service with your API key. Obtain an API key from https://aqicn.org/api/ ```dart String key = 'XXX38456b2b85c92647d8b65090e29f957638c77'; AirQuality airQuality = new AirQuality(key); ``` -------------------------------- ### Initialize Location and Mobility Streams Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/mobility_features/README.md Set up the location stream from a chosen location plugin (e.g., carp_background_location) and map it to LocationSample objects. Then, provide this stream to MobilityFeatures and subscribe to the contextStream for computed mobility features. Ensure background location permissions are handled at the app level. ```dart /// Set up streams: /// * Location streaming to MobilityContext /// * Subscribe to MobilityContext updates void streamInit() async { locationStream = LocationManager().locationStream; // start the location service (specific to carp_background_location) await LocationManager().start(); // map from [LocationDto] to [LocationSample] Stream locationSampleStream = locationStream.map( (location) => LocationSample( GeoLocation(location.latitude, location.longitude), DateTime.now())); // provide the [MobilityFeatures] instance with the LocationSample stream MobilityFeatures().startListening(locationSampleStream); // start listening to incoming MobilityContext objects mobilitySubscription = MobilityFeatures().contextStream.listen(onMobilityContext); } ``` -------------------------------- ### Import Air Quality Package Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/air_quality/README.md Import the necessary AirQuality package. The 'location' package is also required. ```dart import 'package:air_quality/air_quality.dart'; ``` -------------------------------- ### Initialize Pedometer Streams and Listeners Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/pedometer/README.md Initializes the step count and pedestrian status streams and sets up listeners to handle data changes and errors. Ensure necessary permissions are granted. ```dart Stream _stepCountStream; Stream _pedestrianStatusStream; /// Handle step count changed void onStepCount(StepCount event) { int steps = event.steps; DateTime timeStamp = event.timeStamp; } /// Handle status changed void onPedestrianStatusChanged(PedestrianStatus event) { String status = event.status; DateTime timeStamp = event.timeStamp; } /// Handle the error void onPedestrianStatusError(error) {} /// Handle the error void onStepCountError(error) {} Future initPlatformState() async { // Init streams _pedestrianStatusStream = await Pedometer.pedestrianStatusStream; _stepCountStream = await Pedometer.stepCountStream; // Listen to streams and handle errors _stepCountStream.listen(onStepCount).onError(onStepCountError); _pedestrianStatusStream .listen(onPedestrianStatusChanged) .onError(onPedestrianStatusError); } ``` -------------------------------- ### Publish Flutter Package Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Command to publish a Flutter package or plugin to pub.dev. ```bash flutter packages pub publish ``` -------------------------------- ### iOS Info.plist Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/pedometer/README.md Configure your iOS Info.plist file to request motion usage description and enable background processing for step tracking. ```xml NSMotionUsageDescription This application tracks your steps UIBackgroundModes processing ``` -------------------------------- ### Initialize WeatherFactory Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/weather/README.md Instantiate the WeatherFactory with your OpenWeatherMap API key. You can optionally specify a language for weather reports. ```dart import 'package:weather/weather.dart'; ... WeatherFactory wf = new WeatherFactory("YOUR_API_KEY"); ``` ```dart WeatherFactory wf = new WeatherFactory("YOUR_API_KEY", language: Language.DANISH); ``` -------------------------------- ### Initialize and Connect to Movisens Device Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movisens_flutter/README.md Connect to a Movisens device using its name. Connection may take up to 10 seconds. ```dart // The name of your device String deviceName = "MOVISENS Sensor 03348"; MovisensDevice device = MovisensDevice(name: deviceName); // Connect to the device. await device.connect(); ``` -------------------------------- ### iOS Podfile Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/audio_streamer/README.md Modify the Podfile to include microphone permissions for iOS builds. ```ruby post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| # for more infomation: https://github.com/BaseflowIT/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [ '$(inherited)', 'PERMISSION_MICROPHONE=1', ] end end end ``` -------------------------------- ### iOS Info.plist Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/audio_streamer/README.md Configure Info.plist for microphone usage description and background audio mode. ```xml NSMicrophoneUsageDescription YOUR DESCRIPTION UIBackgroundModes audio ``` -------------------------------- ### Generate New Flutter Package Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Use this command to create a new Flutter package from a template. Specify the organization and template type. ```bash flutter create --org dk.cachet --template=package hello_world_package ``` -------------------------------- ### Generate New Flutter Plugin Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Use this command to create a new Flutter plugin from a template. Specify the organization, template type, target platforms, and native languages. ```bash flutter create --org dk.cachet --template=plugin --platforms=android,ios -i swift -a java hello_world_plugin ``` -------------------------------- ### iOS Info.plist Usage Description Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/activity_recognition_flutter/README.md Include this key in your iOS Info.plist file to request permission for accessing motion and fitness data. ```xml NSMotionUsageDescription Detects human activity ``` -------------------------------- ### Android Manifest Permission Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/audio_streamer/README.md Add this permission to your AndroidManifest.xml to allow audio recording. ```xml ``` -------------------------------- ### iOS Info.plist Permissions for Bluetooth and Location Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movisens_flutter/README.md Add these keys and string values to your `ios/Runner/Info.plist` file to request necessary Bluetooth and Location permissions for the plugin. ```xml NSBluetoothAlwaysUsageDescription Need BLE permission NSBluetoothPeripheralUsageDescription Need BLE permission NSLocationAlwaysAndWhenInUseUsageDescription Need Location permission NSLocationAlwaysUsageDescription Need Location permission NSLocationWhenInUseUsageDescription Need Location permission ``` -------------------------------- ### Scan for Movesense Devices Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Use the Movesense singleton to listen for discovered devices and initiate scanning. Stop scanning when no longer needed. ```dart /// Listen for discovered devices Movesense().devices.listen((device) { print('Discovered device: ${device.name} [${device.address}]'); }); /// Start scanning. Movesense().scan(); /// Stop scanning at some later point. Movesense().stopScan(); ``` -------------------------------- ### iOS Bluetooth Permissions and Background Modes Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Configure Info.plist for Bluetooth usage description and background modes. Ensure your Podfile targets iOS 10.0 or later. ```xml NSBluetoothAlwaysUsageDescription Uses bluetooth to connect to the eSense device UIBackgroundModes bluetooth-central bluetooth-peripheral audio external-accessory fetch ``` -------------------------------- ### Android Manifest Permissions Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/activity_recognition_flutter/README.md Add these permissions to your AndroidManifest.xml file to enable activity recognition and foreground services. ```xml ``` -------------------------------- ### Import Flutter Foreground Service Package Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/flutter_foreground_service/README.md Import the necessary package into your Dart file to use the foreground service functionalities. ```dart import 'package:flutter_foreground_service/foreground_service.dart'; ``` -------------------------------- ### Set Minimum SDK Version Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/app_usage/README.md Ensure your Android app meets the minimum API level requirement of 21 by setting it in your `build.gradle` file. ```xml minSdkVersion 21 ``` -------------------------------- ### iOS Info.plist Configuration for Location Usage Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/carp_background_location/README.md Add these keys to your Info.plist file to describe the app's need for location access, both when in use and in the background, and to enable location background modes. ```xml NSLocationAlwaysAndWhenInUseUsageDescription This app needs access to location when open and in the background. NSLocationAlwaysUsageDescription This app needs access to location when in the background. NSLocationWhenInUseUsageDescription This app needs access to location when open. UIBackgroundModes location ``` -------------------------------- ### Add Manifest Namespace Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/app_usage/README.md Include the `tools` namespace in your `AndroidManifest.xml` to enable specific manifest attributes. ```xml xmlns:tools="http://schemas.android.com/tools" ``` -------------------------------- ### iOS AppDelegate Swift Configuration for Background Locator Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/carp_background_location/README.md Overwrite your AppDelegate.swift with this code to register the BackgroundLocatorPlugin and set its callback for plugin registration. ```swift import UIKit import Flutter import background_locator_2 func registerPlugins(registry: FlutterPluginRegistry) -> () { if (!registry.hasPlugin("BackgroundLocatorPlugin")) { GeneratedPluginRegistrant.register(with: registry) } } @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) BackgroundLocatorPlugin.setPluginRegistrantCallback(registerPlugins) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ``` -------------------------------- ### Add Movesense Pod to iOS Podfile Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Configure your iOS Podfile to include the Movesense pod with static linkage. ```ruby target 'Runner' do # replace "use_frameworks!" with static packages for the Movesense pod use_modular_headers! use_frameworks! :linkage => :static # add Movesense pod pod 'Movesense', :git => 'https://bitbucket.org/movesense/movesense-mobile-lib.git' flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end ``` -------------------------------- ### Handle eSense BTLE Interface Limitations Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Avoid invoking ESenseManager methods rapidly. Use delays to ensure proper communication, as rapid calls may fail. ```dart // set up a event listener eSenseManager.eSenseEvents.listen((event) { print('ESENSE event: $event'); } // now invoke read operations on the manager // THIS WILL NOT WORK! eSenseManager.getDeviceName(); eSenseManager.getAccelerometerOffset(); eSenseManager.getAdvertisementAndConnectionInterval(); ``` ```dart // get the battery level every 10 secs Timer.periodic(Duration(seconds: 10), (timer) async => await eSenseManager.getBatteryVoltage()); // wait 2, 3, 4, 5, ... secs before getting the name, offset, etc. // it seems like the eSense BTLE interface does NOT like to get called // several times in a row -- hence, delays are added in the following calls Timer(Duration(seconds: 2), () async => await eSenseManager.getDeviceName()); Timer(Duration(seconds: 3), () async => await eSenseManager.getAccelerometerOffset()); Timer(Duration(seconds: 4), () async => await eSenseManager.getAdvertisementAndConnectionInterval()); Timer(Duration(seconds: 5), () async => await eSenseManager.getSensorConfig()); ``` -------------------------------- ### Listen to System State Events Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Subscribe to specific system state events, such as 'tap' events. Note that only one state event type can be listened to at a time, and not all devices support all event types. ```dart stateSubscription = device .getStateEvents(SystemStateComponent.tap) .listen((state) { print('State: $state'); }); ``` -------------------------------- ### Set iOS Platform Version in Podfile Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Ensure your Podfile specifies the minimum iOS platform version. This is required for certain iOS features and APIs. ```ruby platform :ios, '10.0' ``` -------------------------------- ### Fetch Air Quality Data by IP Address Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/air_quality/README.md Fetch air quality data based on the IP address. The result may depend on the service provider. ```dart /// Via IP (depends on service provider) AirQualityData fromIP = await airQuality.feedFromIP(); ``` -------------------------------- ### Request Package Usage Stats Permission Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/app_usage/README.md Add the `PACKAGE_USAGE_STATS` permission to your `AndroidManifest.xml` to allow the app to access usage statistics. The `tools:ignore="ProtectedPermissions"` attribute is used to suppress warnings. ```xml ``` -------------------------------- ### Flutter Package/Plugin Source File Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Declares that a source file belongs to a specific library using the 'part of' keyword. Imports from the library are available. ```dart part of health; /// Source code below String _enumToString(enumItem) => enumItem.toString().split('.').last; enum PlatformType { IOS, ANDROID } ``` -------------------------------- ### Listen to Audio Stream Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/audio_streamer/README.md Listen to the audioStream for incoming PCM audio data buffers. Ensure cancelOnError is set to true to automatically cancel the stream on error. ```dart AudioStreamer().audioStream.listen( (List buffer) { print('Max amp: ${buffer.reduce(max)}'); print('Min amp: ${buffer.reduce(min)}'); }, onError: (Object error) { print(error); }, cancelOnError: true, ); ``` -------------------------------- ### Android Manifest Services and Receiver Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/activity_recognition_flutter/README.md Register the plugin's receiver and services within the tag in your AndroidManifest.xml. ```xml ``` -------------------------------- ### Set up EventChannel for Streaming Data Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Configure an EventChannel to receive a stream of events. The stream can be mapped and parsed into a specific data type, such as List. ```dart static const EventChannel _noiseEventChannel = EventChannel(EVENT_CHANNEL_NAME); Stream> _stream; StreamSubscription> _subscription; Stream> get audioStream { if (_stream == null) { _stream = _noiseEventChannel .receiveBroadcastStream() .map((buffer) => buffer as List) .map((list) => list.map((e) => double.parse('$e')).toList()); } return _stream; } ``` -------------------------------- ### Android Gradle Build Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movisens_flutter/README.md Update your `android/app/build.gradle` file to set the `minSdkVersion` to at least 21 for compatibility with Bluetooth LE features. ```gradle android { defaultConfig { ... minSdkVersion 21 ... } } ``` -------------------------------- ### Flutter Package/Plugin Library Structure Source: https://github.com/carp-dk/flutter-plugins/wiki/CACHET-Flutter-Plugins-and-Packages Defines the library declaration and imports for a Flutter package or plugin. It uses the 'part' keyword to include other source files. ```dart /// Library declaration library health; /// Other packages to import import 'dart:async'; import 'package:flutter/services.dart'; import 'dart:io' show Platform; import 'package:device_id/device_id.dart'; /// Files to include (use the part keyword) part 'package:health/src/units.dart'; part 'package:health/src/data_types.dart'; part 'package:health/src/functions.dart'; part 'package:health/src/health_data_point.dart'; part 'package:health/src/health_factory.dart'; ``` -------------------------------- ### Configure Mobility Features Parameters Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/mobility_features/README.md Configure parameters that influence the mobility feature calculation algorithms. Adjust stop duration, place radius, and stop radius based on desired granularity and use case. Low values increase granularity but may lead to noisy features. ```dart StreamSubscription mobilitySubscription; MobilityContext _mobilityContext; void initState() { ... MobilityFeatures().stopDuration = Duration(seconds: 20); MobilityFeatures().placeRadius = 50; MobilityFeatures().stopRadius = 5.0; } ``` -------------------------------- ### iOS SensorKit Entitlement Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/light/README.md Configure the SensorKit entitlement in your project to allow reading ambient light sensor data. This is required for iOS devices. ```xml com.apple.developer.sensorkit.reader.allow ambient-light-sensor ``` -------------------------------- ### Add Dependency to pubspec.yaml Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/flutter_foreground_service/README.md Add the flutter_foreground_service plugin to your project's pubspec.yaml file. Ensure you replace LATEST_VERSION_HERE with the actual latest version number. ```yaml dependencies: flutter: sdk: flutter flutter_foreground_service: ^LATEST_VERSION_HERE ``` -------------------------------- ### Import Mobility Features Package Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/mobility_features/README.md Import the Mobility Features package into your Dart file. This is the first step to using the plugin's functionality. ```dart import 'package:mobility_features/mobility_features.dart'; ``` -------------------------------- ### Configure AndroidManifest.xml for Notifications Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/notifications/README.md Add this snippet to your AndroidManifest.xml file within the application tag to enable the notification listener service. ```xml ... ``` -------------------------------- ### Change eSense Device Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Methods to change device name, advertisement and connection interval, and IMU sensor configuration. Note: setSensorConfig() is not yet implemented. ```dart eSenseManager.setDeviceName("MyESense"); eSenseManager.setAdvertisementAndConnectiontInterval(50.0, 30.0); eSenseManager.setSensorConfig(); ``` -------------------------------- ### Connect to a Movesense Device Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Initiate a connection to a Movesense device using its MovesenseDevice object. Connection status is available via the status field and the statusEvents stream. ```dart if (!device.isConnected) { device.connect(); } ``` ```dart final MovesenseDevice device = MovesenseDevice(address: '0C:8C:DC:1B:23:BF'); device.connect(); ``` ```dart print(device.status); device.statusEvents.listen((status) { print('Device connection status changed: ${status.name}'); }); ``` -------------------------------- ### iOS Podfile Configuration for Microphone Permission Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/noise_meter/README.md Modify your iOS Podfile to include microphone permissions for the noise meter plugin. This ensures the app can access the microphone. ```ruby post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| # for more infomation: https://github.com/BaseflowIT/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [ '$(inherited)', 'PERMISSION_MICROPHONE=1', ] end end end ``` -------------------------------- ### Configure Android Project for Movesense AAR Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movesense_plus/README.md Add the Movesense AAR library to your Android project's repositories using Groovy or Kotlin. ```groovy allprojects { repositories { ... flatDir{ dirs "$rootDir/libs" } } } ``` ```kotlin dirs("$rootDir/libs") ``` -------------------------------- ### Listen to Sensor Events Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Access a stream of SensorEvent events. Sampling rate can be set when not listening. Ensure to cancel the subscription when done. ```dart StreamSubscription subscription = eSenseManager.sensorEvents.listen((event) { print('SENSOR event: $event' }); ``` ```dart subscription.cancel(); eSenseManager.setSamplingRate(5); ``` ```dart subscription = eSenseManager.sensorEvents.listen((event) { print('SENSOR event: $event'); }); ``` -------------------------------- ### AppUsageInfo Fields Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/app_usage/README.md Details the public fields available on an `AppUsageInfo` object, including application name, package name, usage duration, and time intervals. ```dart /// The name of the application String get appName => _appName; /// The name of the application package String get packageName => _packageName; /// The amount of time the application has been used /// in the specified interval Duration get usage => _usage; /// The start of the interval DateTime get startDate => _startDate; /// The end of the interval DateTime get endDate => _endDate; /// Last time app was in foreground DateTime get lastForeground => _lastForeground; ``` -------------------------------- ### Declare Android Permissions and Features Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/empatica_e4link/README.md Add these permissions and features to your Android manifest to enable Bluetooth and location tracking for the Empatica E4 device. ```xml ``` -------------------------------- ### Android Manifest Permissions for Bluetooth LE Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movisens_flutter/README.md Add these permissions to your `android/app/src/main/AndroidManifest.xml` file to enable Bluetooth Low Energy functionality and comply with Android 12+ Bluetooth permissions. ```xml ``` -------------------------------- ### Decibel Conversion Formula Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/noise_meter/README.md This Python formula shows how to convert a PCM value to decibels. The PCM value is first scaled by 2^15 before applying the logarithm. ```python db = 20 * log10(2**15 * pcmValue) ``` -------------------------------- ### iOS SensorKit Purpose Text Configuration Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/light/README.md Add the SensorKit purpose text to your Info.plist file to explain why your app needs ambient light sensor data. This is a requirement for iOS. ```xml NSSensorKitUsageDetail SRSensorUsageAmbientLightSensor Explain why your app needs ambient light sensor data. ``` -------------------------------- ### Android Application Configuration for Background Locator Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/carp_background_location/README.md Include these receiver and service entries within the application tag in your AndroidManifest.xml for background location tracking functionality. ```xml ``` -------------------------------- ### Set Sampling Rate Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/audio_streamer/README.md Set the desired sampling rate before listening to the audio stream. Note that the actual sample rate may differ on iOS. ```dart // Set the sampling rate. Must be done BEFORE listening to the audioStream. AudioStreamer().sampleRate = 22100; ``` -------------------------------- ### Access Temperature Units Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/weather/README.md Extract temperature values in Celsius, Fahrenheit, or Kelvin from a Weather object. ```dart double celsius = w.temperature.celsius; double fahrenheit = w.temperature.fahrenheit; double kelvin = w.temperature.kelvin; ``` -------------------------------- ### Android Manifest Permission Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/pedometer/README.md Add this permission to your AndroidManifest.xml for Android 10 and above to access activity recognition data. ```xml ``` -------------------------------- ### Read eSense Device Events Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Listen to ESenseEvents and invoke read operations to obtain device properties. Button presses trigger ButtonEventChanged events. ```dart // set up a event listener eSenseManager.eSenseEvents.listen((event) { print('ESENSE event: $event'); } // now invoke read operations on the manager eSenseManager.getDeviceName(); ``` -------------------------------- ### Android Permissions for Noise Meter Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/noise_meter/README.md Add these permissions to your AndroidManifest.xml file to allow the noise meter plugin to record audio and write to external storage. ```xml ``` -------------------------------- ### Android Permissions for Background Location Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/carp_background_location/README.md Add these permissions to your AndroidManifest.xml to enable internet, location access (fine and coarse), background location, wake locks, foreground services, and boot completion reception. ```xml ``` -------------------------------- ### Android Bluetooth Permissions Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/esense_flutter/README.md Declare necessary Bluetooth permissions in your AndroidManifest.xml. Note that BLUETOOTH_SCAN and BLUETOOTH_CONNECT are for newer Android versions. ```xml ``` -------------------------------- ### Handle Incoming Mobility Contexts in Dart Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/mobility_features/README.md Use the onMobilityContext callback to process incoming MobilityContext objects. The context can be serialized to JSON using toJson(). ```dart /// Handle incoming contexts void onMobilityContext(MobilityContext context) { /// Do something with the context print('Context received: ${context.toJson()}'); } ``` -------------------------------- ### Set Device Data Deletion Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/movisens_flutter/README.md Write to the sensor control service to delete data from the device. This action is only possible if no measurement is currently running. ```dart await device.sensorControlService?.setDeleteData(true); ``` -------------------------------- ### MobilityContext JSON Structure Source: https://github.com/carp-dk/flutter-plugins/blob/master/packages/mobility_features/README.md The MobilityContext object can be serialized to JSON, providing details about the user's mobility, including timestamps, stops, moves, places, and various derived features. ```json { "timestamp": "2024-09-26T10:56:21.397768", "date": "2020-01-01T00:00:00.000", "numberOfStops": 2, "numberOfMoves": 1, "numberOfSignificantPlaces": 2, "locationVariance": 0.00011097661986704458, "entropy": 0.6365141682948128, "normalizedEntropy": 0.9182958340544894, "homeStay": 0.64, "distanceTraveled": 0.0 } ```