Thomas Hondema 1 месяц назад
Сommit
e19c644fa6
100 измененных файлов с 7193 добавлено и 0 удалено
  1. 1 0
      .flutter-plugins-dependencies
  2. 45 0
      .gitignore
  3. 36 0
      .metadata
  4. 108 0
      README.md
  5. 28 0
      analysis_options.yaml
  6. 14 0
      android/.gitignore
  7. 45 0
      android/app/build.gradle.kts
  8. 7 0
      android/app/src/debug/AndroidManifest.xml
  9. 51 0
      android/app/src/main/AndroidManifest.xml
  10. 353 0
      android/app/src/main/kotlin/com/example/mebarista/ClassicBluetoothChannel.kt
  11. 29 0
      android/app/src/main/kotlin/com/example/mebarista/MainActivity.kt
  12. BIN
      android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png
  13. BIN
      android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png
  14. 12 0
      android/app/src/main/res/drawable-v21/launch_background.xml
  15. BIN
      android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png
  16. BIN
      android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png
  17. BIN
      android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png
  18. 12 0
      android/app/src/main/res/drawable/launch_background.xml
  19. 9 0
      android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
  20. BIN
      android/app/src/main/res/mipmap-hdpi/ic_launcher.png
  21. BIN
      android/app/src/main/res/mipmap-mdpi/ic_launcher.png
  22. BIN
      android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
  23. BIN
      android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
  24. BIN
      android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
  25. 18 0
      android/app/src/main/res/values-night/styles.xml
  26. 4 0
      android/app/src/main/res/values/colors.xml
  27. 18 0
      android/app/src/main/res/values/styles.xml
  28. 7 0
      android/app/src/profile/AndroidManifest.xml
  29. 24 0
      android/build.gradle.kts
  30. 663 0
      android/build/reports/problems/problems-report.html
  31. 6 0
      android/gradle.properties
  32. 5 0
      android/gradle/wrapper/gradle-wrapper.properties
  33. 26 0
      android/settings.gradle.kts
  34. BIN
      assets/icons/mebarista.png
  35. BIN
      assets/icons/mebarista_foreground.png
  36. 11 0
      flutter_launcher_icons.yaml
  37. 34 0
      ios/.gitignore
  38. 24 0
      ios/Flutter/AppFrameworkInfo.plist
  39. 1 0
      ios/Flutter/Debug.xcconfig
  40. 1 0
      ios/Flutter/Release.xcconfig
  41. 644 0
      ios/Runner.xcodeproj/project.pbxproj
  42. 7 0
      ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
  43. 8 0
      ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
  44. 8 0
      ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
  45. 119 0
      ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
  46. 7 0
      ios/Runner.xcworkspace/contents.xcworkspacedata
  47. 8 0
      ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
  48. 8 0
      ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
  49. 16 0
      ios/Runner/AppDelegate.swift
  50. 1 0
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
  51. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png
  52. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png
  53. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png
  54. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png
  55. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png
  56. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png
  57. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png
  58. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png
  59. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png
  60. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png
  61. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png
  62. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png
  63. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png
  64. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png
  65. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png
  66. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png
  67. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png
  68. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png
  69. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png
  70. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png
  71. BIN
      ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png
  72. 23 0
      ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json
  73. BIN
      ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png
  74. BIN
      ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png
  75. BIN
      ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png
  76. 5 0
      ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
  77. 37 0
      ios/Runner/Base.lproj/LaunchScreen.storyboard
  78. 26 0
      ios/Runner/Base.lproj/Main.storyboard
  79. 74 0
      ios/Runner/Info.plist
  80. 1 0
      ios/Runner/Runner-Bridging-Header.h
  81. 6 0
      ios/Runner/SceneDelegate.swift
  82. 12 0
      ios/RunnerTests/RunnerTests.swift
  83. 495 0
      lib/main.dart
  84. 16 0
      lib/models/diagnostic_entry.dart
  85. 258 0
      lib/models/machine_state.dart
  86. 14 0
      lib/models/temperature_sample.dart
  87. 98 0
      lib/screens/connection_screen.dart
  88. 97 0
      lib/screens/diagnostics_screen.dart
  89. 174 0
      lib/screens/hardware_settings_screen.dart
  90. 157 0
      lib/screens/pid_settings_screen.dart
  91. 93 0
      lib/screens/pressure_settings_screen.dart
  92. 307 0
      lib/screens/settings_screen.dart
  93. 67 0
      lib/screens/statistics_screen.dart
  94. 131 0
      lib/screens/timer_settings_screen.dart
  95. 1492 0
      lib/services/bluetooth_service.dart
  96. 250 0
      lib/services/classic_bluetooth_transport.dart
  97. 350 0
      lib/services/firmware_updater.dart
  98. 366 0
      lib/services/me_coffee_protocol.dart
  99. 226 0
      lib/widgets/temperature_chart.dart
  100. 0 0
      macos/.gitignore

Разница между файлами не показана из-за своего большого размера
+ 1 - 0
.flutter-plugins-dependencies


+ 45 - 0
.gitignore

@@ -0,0 +1,45 @@
+# Miscellaneous
+*.class
+*.log
+*.pyc
+*.swp
+.DS_Store
+.atom/
+.build/
+.buildlog/
+.history
+.svn/
+.swiftpm/
+migrate_working_dir/
+
+# IntelliJ related
+*.iml
+*.ipr
+*.iws
+.idea/
+
+# The .vscode folder contains launch configuration and tasks you configure in
+# VS Code which you may wish to be included in version control, so this line
+# is commented out by default.
+#.vscode/
+
+# Flutter/Dart/Pub related
+**/doc/api/
+**/ios/Flutter/.last_build_id
+.dart_tool/
+.flutter-plugins-dependencies
+.pub-cache/
+.pub/
+/build/
+/coverage/
+
+# Symbolication related
+app.*.symbols
+
+# Obfuscation related
+app.*.map.json
+
+# Android Studio will place build artifacts here
+/android/app/debug
+/android/app/profile
+/android/app/release

+ 36 - 0
.metadata

@@ -0,0 +1,36 @@
+# This file tracks properties of this Flutter project.
+# Used by Flutter tool to assess capabilities and perform upgrades etc.
+#
+# This file should be version controlled and should not be manually edited.
+
+version:
+  revision: "ee80f08bbf97172ec030b8751ceab557177a34a6"
+  channel: "stable"
+
+project_type: app
+
+# Tracks metadata for the flutter migrate command
+migration:
+  platforms:
+    - platform: root
+      create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+      base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+    - platform: android
+      create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+      base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+    - platform: ios
+      create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+      base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+    - platform: macos
+      create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+      base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6
+
+  # User provided section
+
+  # List of Local paths (relative to this file) that should be
+  # ignored by the migrate tool.
+  #
+  # Files that are not part of the templates will be ignored by default.
+  unmanaged_files:
+    - 'lib/main.dart'
+    - 'ios/Runner.xcodeproj/project.pbxproj'

+ 108 - 0
README.md

@@ -0,0 +1,108 @@
+# meBarista Flutter
+
+A modern, cross-platform Flutter port of the original **meBarista** app for the **meCoffee** espresso PID controller.
+
+## About the Project
+
+meBarista is the software interface for the meCoffee PID, an internal controller that adds advanced features to espresso machines like the Silvia, Gaggia Classic, and others. This project aims to bring the functionality of the original Android and Ionic-based apps to a modern Flutter codebase, providing a unified experience across iOS and Android.
+
+For more information on the original project and its opening to the community, visit: [Opening up meBarista](https://mecoffee.nl/opening-up-mebarista/)
+
+## Key Features
+
+- **Real-time PID Monitoring**: Live temperature tracking with stability visualization (FL Chart).
+- **Bluetooth Connectivity**: BLE via `flutter_blue_plus`, including write-without-response modules, and Android Bluetooth Classic/SPP via a native channel. Pair Classic controllers in Android settings, then select them in the connection screen. iOS and macOS remain BLE-only.
+- **Shot Automation**: Automatic shot timer detection based on pump activation.
+- **Advanced Configuration**:
+  - Precision Brew Temperature control.
+  - Steam Temperature management.
+  - Customizable pre-infusion pump/pause duration and valve behavior.
+  - Firmware-aware V4 PID and pre-infusion scaling.
+- **Telemetry freshness**: A warning appears after three seconds without a valid temperature frame. Stale readings are retained for reference, but heating/brewing indicators and the running shot timer are stopped.
+- **History**: Up to 5,000 timestamped samples, including historical setpoints and aligned second-sensor readings, with selectable time windows and history navigation. History is session-only, not a persisted shot database.
+- **Diagnostics**: A bounded, in-memory log of the last 1,000 received/sent/event entries. Use the dashboard Diagnostics button to copy or clear it. Nothing is uploaded automatically.
+- **Persistence**: Settings are saved locally after successful Bluetooth delivery.
+  Connect before editing; failed writes display an error and do not save the
+  requested setting. A multi-command failure may leave the controller partially
+  updated, so reconnect to read back its settings before retrying. Bluetooth write
+  completion is not confirmation that firmware accepted a setting; no-response
+  BLE modules cannot provide transport acknowledgments.
+  Settings writes wait for the controller's firmware identity. Individual
+  controls send only the edited parameter, rather than resending cached companion
+  settings. Dashboard temperature adjustments also wait for the controller's
+  brew setpoint readback.
+- **Dark Mode**: High-contrast, industrial theme optimized for kitchen environments.
+
+## Implementation Roadmap
+
+- [x] Phase 1: Infrastructure & BLE Connectivity
+- [x] Phase 2: Core Monitoring Dashboard & Real-time Graphs
+- [x] Phase 3: Machine Configuration & Settings Persistence
+- [x] Phase 4: Shot Automation (Timer) & Steam Controls
+- [x] Phase 5: Guarded Bluetooth Classic firmware updates (Experimental)
+- [ ] Phase 6: Shot Logging and Extraction Analytics
+
+## Getting Started
+
+### Prerequisites
+
+- Flutter SDK
+- Android Studio / VS Code
+- A meCoffee PID controller installed in your espresso machine.
+
+### Installation
+
+1. Clone the repository.
+2. Run `flutter pub get`.
+3. Enable Bluetooth permissions on your mobile device.
+4. Launch the app and tap "Connect to meCoffee". On Android, choose BLE scanning
+   or a paired Classic/SPP controller.
+
+## Firmware updates
+
+Hardware Configuration can install the existing bundled V10 firmware through an
+Android Classic/SPP connection. This is an experimental STK500v1 operation, not a
+network download or a BLE OTA implementation. It requires live temperature data,
+an idle machine with a fresh PID frame confirming heating off, a boiler at or
+below 50 C, and explicit confirmation. Pending settings finish while telemetry
+continues to be parsed; the safety conditions are rechecked before controller reset.
+
+The Intel HEX image is validated before resetting the controller. The programmer
+checks the ATmega328P signature before writing and verifies programmed pages by
+reading them back. Unsupported bootloaders, timeouts, checksum errors, and
+verification failures stop the operation and surface an error.
+
+Do not brew, close the app, or interrupt controller power/Bluetooth during an
+update. There is no rollback: a failed update may require manual bootloader
+recovery. Only use this function if you can recover your controller. The app
+reconnects and reads settings after a successful update; settings may have changed.
+
+## App icons
+
+Launcher icons use the original meCoffee artwork from
+`meBarista_in_Ionic2/resources/icon.png`. The generator sources are
+`assets/icons/mebarista.png` and `assets/icons/mebarista_foreground.png`; the
+foreground has a transparent background for Android adaptive masks.
+
+After changing the artwork, regenerate the Android, iOS, and macOS icons:
+
+```bash
+flutter pub get
+dart run flutter_launcher_icons
+```
+
+Configuration is in `flutter_launcher_icons.yaml`. Android uses a white
+adaptive background and foreground padding to avoid mask clipping; iOS icons
+are generated without an alpha channel. Keep both source images square and
+prefer original 1024 x 1024 artwork when available (the legacy source is
+512 x 512). Do not bake rounded corners into the images.
+
+Rebuild and reinstall the app to see launcher changes; hot reload does not
+update launcher icons.
+
+## Contributing
+
+This project is inspired by the open-source spirit of the original meCoffee community. Feel free to submit pull requests, report issues, or suggest new features to help make the perfect shot.
+
+---
+*Disclaimer: this meBarista app is an independent project and is not officially affiliated with the hardware manufacturer.*

+ 28 - 0
analysis_options.yaml

@@ -0,0 +1,28 @@
+# This file configures the analyzer, which statically analyzes Dart code to
+# check for errors, warnings, and lints.
+#
+# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
+# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
+# invoked from the command line by running `flutter analyze`.
+
+# The following line activates a set of recommended lints for Flutter apps,
+# packages, and plugins designed to encourage good coding practices.
+include: package:flutter_lints/flutter.yaml
+
+linter:
+  # The lint rules applied to this project can be customized in the
+  # section below to disable rules from the `package:flutter_lints/flutter.yaml`
+  # included above or to enable additional rules. A list of all available lints
+  # and their documentation is published at https://dart.dev/lints.
+  #
+  # Instead of disabling a lint rule for the entire project in the
+  # section below, it can also be suppressed for a single line of code
+  # or a specific dart file by using the `// ignore: name_of_lint` and
+  # `// ignore_for_file: name_of_lint` syntax on the line or in the file
+  # producing the lint.
+  rules:
+    # avoid_print: false  # Uncomment to disable the `avoid_print` rule
+    # prefer_single_quotes: true  # Uncomment to enable the `prefer_single_quotes` rule
+
+# Additional information about this file can be found at
+# https://dart.dev/guides/language/analysis-options

+ 14 - 0
android/.gitignore

@@ -0,0 +1,14 @@
+gradle-wrapper.jar
+/.gradle
+/captures/
+/gradlew
+/gradlew.bat
+/local.properties
+GeneratedPluginRegistrant.java
+.cxx/
+
+# Remember to never publicly share your keystore.
+# See https://flutter.dev/to/reference-keystore
+key.properties
+**/*.keystore
+**/*.jks

+ 45 - 0
android/app/build.gradle.kts

@@ -0,0 +1,45 @@
+plugins {
+    id("com.android.application")
+    // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
+    id("dev.flutter.flutter-gradle-plugin")
+}
+
+android {
+    namespace = "com.example.mebarista"
+    compileSdk = flutter.compileSdkVersion
+    ndkVersion = flutter.ndkVersion
+
+    compileOptions {
+        sourceCompatibility = JavaVersion.VERSION_17
+        targetCompatibility = JavaVersion.VERSION_17
+    }
+
+    defaultConfig {
+        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
+        applicationId = "com.example.mebarista"
+        // You can update the following values to match your application needs.
+        // For more information, see: https://flutter.dev/to/review-gradle-config.
+        minSdk = flutter.minSdkVersion
+        targetSdk = flutter.targetSdkVersion
+        versionCode = flutter.versionCode
+        versionName = flutter.versionName
+    }
+
+    buildTypes {
+        release {
+            // TODO: Add your own signing config for the release build.
+            // Signing with the debug keys for now, so `flutter run --release` works.
+            signingConfig = signingConfigs.getByName("debug")
+        }
+    }
+}
+
+kotlin {
+    compilerOptions {
+        jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
+    }
+}
+
+flutter {
+    source = "../.."
+}

+ 7 - 0
android/app/src/debug/AndroidManifest.xml

@@ -0,0 +1,7 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+    <!-- The INTERNET permission is required for development. Specifically,
+         the Flutter tool needs it to communicate with the running application
+         to allow setting breakpoints, to provide hot reload, etc.
+    -->
+    <uses-permission android:name="android.permission.INTERNET"/>
+</manifest>

+ 51 - 0
android/app/src/main/AndroidManifest.xml

@@ -0,0 +1,51 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
+    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
+    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+
+    <application
+        android:label="meBarista"
+        android:name="${applicationName}"
+        android:icon="@mipmap/ic_launcher">
+        <activity
+            android:name=".MainActivity"
+            android:exported="true"
+            android:launchMode="singleTop"
+            android:taskAffinity=""
+            android:theme="@style/LaunchTheme"
+            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
+            android:hardwareAccelerated="true"
+            android:windowSoftInputMode="adjustResize">
+            <!-- Specifies an Android theme to apply to this Activity as soon as
+                 the Android process has started. This theme is visible to the user
+                 while the Flutter UI initializes. After that, this theme continues
+                 to determine the Window background behind the Flutter UI. -->
+            <meta-data
+              android:name="io.flutter.embedding.android.NormalTheme"
+              android:resource="@style/NormalTheme"
+              />
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+        <!-- Don't delete the meta-data below.
+             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
+        <meta-data
+            android:name="flutterEmbedding"
+            android:value="2" />
+    </application>
+    <!-- Required to query activities that can process text, see:
+         https://developer.android.com/training/package-visibility and
+         https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
+
+         In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
+    <queries>
+        <intent>
+            <action android:name="android.intent.action.PROCESS_TEXT"/>
+            <data android:mimeType="text/plain"/>
+        </intent>
+    </queries>
+</manifest>

+ 353 - 0
android/app/src/main/kotlin/com/example/mebarista/ClassicBluetoothChannel.kt

@@ -0,0 +1,353 @@
+package com.example.mebarista
+
+import android.Manifest
+import android.app.Activity
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothSocket
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import io.flutter.plugin.common.BinaryMessenger
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import java.io.IOException
+import java.util.UUID
+import java.util.concurrent.Executors
+
+/** Paired devices only: no discovery, location request, or silent adapter enable. */
+class ClassicBluetoothChannel(
+    private val activity: Activity,
+    messenger: BinaryMessenger,
+) : MethodChannel.MethodCallHandler, EventChannel.StreamHandler {
+    companion object {
+        private const val PERMISSION_REQUEST = 0x4D43
+        private const val CONNECT_TIMEOUT_MS = 20000L
+        private val SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
+    }
+
+    private val methods = MethodChannel(messenger, "mebarista/classic")
+    private val events = EventChannel(messenger, "mebarista/classic/events")
+    private val main = Handler(Looper.getMainLooper())
+    private val connector = Executors.newSingleThreadExecutor()
+    private val writer = Executors.newSingleThreadExecutor()
+    private val reader = Executors.newSingleThreadExecutor()
+    private val closer = Executors.newSingleThreadExecutor()
+    private val lock = Any()
+    private var generation = 0L
+    private var socket: BluetoothSocket? = null
+    private var connected = false
+    private var address: String? = null
+    private var disposed = false
+    private var sink: EventChannel.EventSink? = null
+    private var permissionCall: Pair<MethodCall, MethodChannel.Result>? = null
+    private var permissionRequestInFlight = false
+    private var pendingConnect: MethodChannel.Result? = null
+
+    init {
+        methods.setMethodCallHandler(this)
+        events.setStreamHandler(this)
+    }
+
+    override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink) {
+        sink = eventSink
+        eventSink.success(mapOf("type" to "ready"))
+        if (connected) eventSink.success(mapOf("type" to "connected", "address" to address))
+    }
+
+    override fun onCancel(arguments: Any?) {
+        sink = null
+        terminate(explicit = true, code = "cancelled", message = "Event listener cancelled.")
+    }
+
+    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+        if (disposed) {
+            result.error("disposed", "Bluetooth transport has been disposed.", null)
+            return
+        }
+        when (call.method) {
+            "listBondedDevices", "connect" -> {
+                if (needsPermission()) {
+                    if (permissionRequestInFlight) {
+                        result.error("permission_pending", "Bluetooth permission request is pending.", null)
+                    } else {
+                        permissionCall = call to result
+                        permissionRequestInFlight = true
+                        activity.requestPermissions(
+                            arrayOf(Manifest.permission.BLUETOOTH_CONNECT), PERMISSION_REQUEST,
+                        )
+                    }
+                } else perform(call, result)
+            }
+            "write" -> write(call, result)
+            "disconnect" -> {
+                permissionCall?.second?.error("cancelled", "Bluetooth operation cancelled.", null)
+                permissionCall = null
+                terminate(
+                    explicit = true, code = "cancelled", message = "Connection cancelled.",
+                    onClosed = { result.success(null) },
+                )
+            }
+            else -> result.notImplemented()
+        }
+    }
+
+    private fun needsPermission(): Boolean =
+        Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
+            activity.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) !=
+            PackageManager.PERMISSION_GRANTED
+
+    fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray): Boolean {
+        if (requestCode != PERMISSION_REQUEST) return false
+        permissionRequestInFlight = false
+        val pending = permissionCall ?: return true
+        permissionCall = null
+        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+            perform(pending.first, pending.second)
+        } else {
+            pending.second.error("permission_denied", "Bluetooth connection permission denied.", null)
+        }
+        return true
+    }
+
+    private fun adapter(): BluetoothAdapter? =
+        (activity.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
+
+    private fun perform(call: MethodCall, result: MethodChannel.Result) {
+        try {
+            val adapter = adapter()
+            if (adapter == null) {
+                result.error("unavailable", "Bluetooth is unavailable on this device.", null)
+            } else if (!adapter.isEnabled) {
+                result.error("bluetooth_disabled", "Enable Bluetooth in Android settings.", null)
+            } else if (call.method == "listBondedDevices") {
+                connector.execute {
+                    try {
+                        val devices = adapter.bondedDevices.map {
+                            mapOf("address" to it.address, "name" to it.name)
+                        }.sortedWith(compareBy(
+                            { if (isCoffeeName(it["name"])) 0 else 1 },
+                            { it["name"] ?: "" }, { it["address"] ?: "" },
+                        ))
+                        main.post { result.success(devices) }
+                    } catch (error: SecurityException) {
+                        main.post { result.error("permission_denied", "Bluetooth permission revoked.", null) }
+                    }
+                }
+            } else connect(adapter, call, result)
+        } catch (error: SecurityException) {
+            result.error("permission_denied", "Bluetooth permission revoked.", null)
+        }
+    }
+
+    private fun isCoffeeName(name: String?): Boolean =
+        name?.contains("meCoffee", ignoreCase = true) == true ||
+            name?.contains("MissSilvia", ignoreCase = true) == true
+
+    private fun connect(adapter: BluetoothAdapter, call: MethodCall, result: MethodChannel.Result) {
+        val target = call.argument<String>("address")
+        if (target == null || !BluetoothAdapter.checkBluetoothAddress(target)) {
+            result.error("invalid_address", "A valid Bluetooth device address is required.", null)
+            return
+        }
+        if (sink == null) {
+            result.error("event_listener_required", "Subscribe to Bluetooth events before connecting.", null)
+            return
+        }
+        if (permissionCall != null || pendingConnect != null || synchronized(lock) { socket != null }) {
+            result.error("busy", "Disconnect the current Bluetooth connection first.", null)
+            return
+        }
+        val device = adapter.getRemoteDevice(target)
+        if (device.bondState != android.bluetooth.BluetoothDevice.BOND_BONDED) {
+            result.error("not_paired", "Pair the device in Android settings first.", null)
+            return
+        }
+        val token = synchronized(lock) { ++generation }
+        address = target
+        pendingConnect = result
+        main.postDelayed({
+            if (isCurrent(token) && pendingConnect != null) {
+                terminate(false, "connect_timeout", "Bluetooth connection timed out.")
+            }
+        }, CONNECT_TIMEOUT_MS)
+        connector.execute {
+            try {
+                var candidate = device.createRfcommSocketToServiceRecord(SPP_UUID)
+                if (!claim(token, candidate)) return@execute
+                try {
+                    candidate.connect()
+                } catch (primary: IOException) {
+                    closeSocket(candidate, token)
+                    if (!isCurrent(token)) return@execute
+                    // Legacy meCoffee SPP modules advertise unreliable SDP;
+                    // the original Android client also falls back to channel 1.
+                    candidate = try {
+                        device.javaClass.getMethod("createRfcommSocket", Int::class.javaPrimitiveType)
+                            .invoke(device, 1) as BluetoothSocket
+                    } catch (fallback: ReflectiveOperationException) {
+                        primary.addSuppressed(fallback)
+                        throw primary
+                    }
+                    if (!claim(token, candidate)) return@execute
+                    candidate.connect()
+                }
+                val active = candidate
+                main.post {
+                    if (isCurrent(token)) {
+                        connected = true
+                        sink?.success(mapOf("type" to "connected", "address" to target))
+                        pendingConnect?.success(null)
+                        pendingConnect = null
+                        reader.execute { read(token, active) }
+                    }
+                }
+            } catch (error: SecurityException) {
+                fail(token, "permission_denied", "Bluetooth permission revoked.")
+            } catch (error: IOException) {
+                fail(token, "connect_failed", "Could not connect to the paired Bluetooth device.")
+            }
+        }
+    }
+
+    private fun claim(token: Long, candidate: BluetoothSocket): Boolean {
+        val accepted = synchronized(lock) {
+            if (disposed || token != generation) false else {
+                socket = candidate
+                true
+            }
+        }
+        if (!accepted) closeSocket(candidate, token)
+        return accepted
+    }
+
+    private fun isCurrent(token: Long): Boolean =
+        synchronized(lock) { !disposed && token == generation }
+
+    private fun read(token: Long, active: BluetoothSocket) {
+        try {
+            val input = active.inputStream
+            val buffer = ByteArray(4096)
+            while (isCurrent(token)) {
+                val count = input.read(buffer)
+                if (count < 0) {
+                    main.post {
+                        if (isCurrent(token)) terminate(false, null, "Remote device disconnected.")
+                    }
+                    return
+                }
+                if (count == 0) continue
+                val bytes = buffer.copyOf(count)
+                main.post {
+                    if (isCurrent(token)) sink?.success(mapOf("type" to "data", "bytes" to bytes))
+                }
+            }
+        } catch (error: IOException) {
+            fail(token, "read_failed", "Bluetooth connection was lost.")
+        } catch (error: SecurityException) {
+            fail(token, "permission_denied", "Bluetooth permission revoked.")
+        }
+    }
+
+    private fun write(call: MethodCall, result: MethodChannel.Result) {
+        val bytes = call.argument<ByteArray>("bytes")
+        val active = synchronized(lock) { socket }
+        val token = synchronized(lock) { generation }
+        if (bytes == null) {
+            result.error("invalid_bytes", "Binary bytes are required.", null)
+        } else if (!connected || active == null) {
+            result.error("not_connected", "Bluetooth is not connected.", null)
+        } else writer.execute {
+            try {
+                if (!isCurrent(token)) {
+                    main.post { result.error("cancelled", "Bluetooth write cancelled.", null) }
+                    return@execute
+                }
+                active.outputStream.write(bytes)
+                active.outputStream.flush()
+                main.post {
+                    if (isCurrent(token)) result.success(null)
+                    else result.error("cancelled", "Bluetooth write cancelled.", null)
+                }
+            } catch (error: IOException) {
+                main.post {
+                    result.error("write_failed", "Could not write Bluetooth bytes.", null)
+                    if (isCurrent(token)) terminate(false, "write_failed", "Bluetooth write failed.")
+                }
+            } catch (error: SecurityException) {
+                main.post {
+                    result.error("permission_denied", "Bluetooth permission revoked.", null)
+                    if (isCurrent(token)) terminate(false, "permission_denied", "Bluetooth permission revoked.")
+                }
+            }
+        }
+    }
+
+    private fun fail(token: Long, code: String, message: String) {
+        main.post { if (isCurrent(token)) terminate(false, code, message) }
+    }
+
+    private fun terminate(
+        explicit: Boolean,
+        code: String?,
+        message: String,
+        onClosed: (() -> Unit)? = null,
+    ) {
+        val old = synchronized(lock) {
+            generation++
+            val previous = socket
+            socket = null
+            previous
+        }
+        val hadConnection = connected || pendingConnect != null || old != null
+        connected = false
+        pendingConnect?.error(code ?: "disconnected", message, null)
+        pendingConnect = null
+        if (!explicit && code != null && hadConnection) {
+            sink?.success(mapOf("type" to "error", "address" to address, "code" to code, "message" to message))
+        }
+        if (hadConnection) {
+            sink?.success(mapOf("type" to "disconnected", "address" to address, "explicit" to explicit))
+        }
+        address = null
+        if (old != null) {
+            val token = synchronized(lock) { generation }
+            closer.execute {
+                closeSocket(old, token)
+                if (onClosed != null) main.post { onClosed() }
+            }
+        } else onClosed?.invoke()
+    }
+
+    private fun closeSocket(value: BluetoothSocket, token: Long) {
+        try {
+            value.close()
+        } catch (error: IOException) {
+            main.post {
+                if (isCurrent(token)) sink?.success(mapOf(
+                    "type" to "error", "code" to "close_failed",
+                    "message" to "Could not close Bluetooth socket cleanly.",
+                ))
+            }
+        }
+    }
+
+    fun dispose() {
+        if (disposed) return
+        permissionCall?.second?.error("disposed", "Bluetooth activity was destroyed.", null)
+        permissionCall = null
+        terminate(true, "disposed", "Bluetooth activity was destroyed.")
+        synchronized(lock) { disposed = true }
+        sink?.endOfStream()
+        sink = null
+        methods.setMethodCallHandler(null)
+        events.setStreamHandler(null)
+        connector.shutdown()
+        writer.shutdown()
+        reader.shutdown()
+        closer.shutdown()
+    }
+}

+ 29 - 0
android/app/src/main/kotlin/com/example/mebarista/MainActivity.kt

@@ -0,0 +1,29 @@
+package com.example.mebarista
+
+import io.flutter.embedding.android.FlutterActivity
+import io.flutter.embedding.engine.FlutterEngine
+
+class MainActivity : FlutterActivity() {
+    private var classicBluetooth: ClassicBluetoothChannel? = null
+
+    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+        super.configureFlutterEngine(flutterEngine)
+        classicBluetooth = ClassicBluetoothChannel(this, flutterEngine.dartExecutor.binaryMessenger)
+    }
+
+    override fun onRequestPermissionsResult(
+        requestCode: Int,
+        permissions: Array<out String>,
+        grantResults: IntArray,
+    ) {
+        if (classicBluetooth?.onRequestPermissionsResult(requestCode, grantResults) != true) {
+            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+        }
+    }
+
+    override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
+        classicBluetooth?.dispose()
+        classicBluetooth = null
+        super.cleanUpFlutterEngine(flutterEngine)
+    }
+}

BIN
android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png


BIN
android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png


+ 12 - 0
android/app/src/main/res/drawable-v21/launch_background.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Modify this file to customize your launch splash screen -->
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:drawable="?android:colorBackground" />
+
+    <!-- You can insert your own image assets here -->
+    <!-- <item>
+        <bitmap
+            android:gravity="center"
+            android:src="@mipmap/launch_image" />
+    </item> -->
+</layer-list>

BIN
android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png


BIN
android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png


BIN
android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png


+ 12 - 0
android/app/src/main/res/drawable/launch_background.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Modify this file to customize your launch splash screen -->
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:drawable="@android:color/white" />
+
+    <!-- You can insert your own image assets here -->
+    <!-- <item>
+        <bitmap
+            android:gravity="center"
+            android:src="@mipmap/launch_image" />
+    </item> -->
+</layer-list>

+ 9 - 0
android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+  <background android:drawable="@color/ic_launcher_background"/>
+  <foreground>
+      <inset
+          android:drawable="@drawable/ic_launcher_foreground"
+          android:inset="16%" />
+  </foreground>
+</adaptive-icon>

BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher.png


BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher.png


BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher.png


BIN
android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png


BIN
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png


+ 18 - 0
android/app/src/main/res/values-night/styles.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
+    <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
+        <!-- Show a splash screen on the activity. Automatically removed when
+             the Flutter engine draws its first frame -->
+        <item name="android:windowBackground">@drawable/launch_background</item>
+    </style>
+    <!-- Theme applied to the Android Window as soon as the process has started.
+         This theme determines the color of the Android Window while your
+         Flutter UI initializes, as well as behind your Flutter UI while its
+         running.
+
+         This Theme is only used starting with V2 of Flutter's Android embedding. -->
+    <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
+        <item name="android:windowBackground">?android:colorBackground</item>
+    </style>
+</resources>

+ 4 - 0
android/app/src/main/res/values/colors.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <color name="ic_launcher_background">#FFFFFF</color>
+</resources>

+ 18 - 0
android/app/src/main/res/values/styles.xml

@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
+    <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
+        <!-- Show a splash screen on the activity. Automatically removed when
+             the Flutter engine draws its first frame -->
+        <item name="android:windowBackground">@drawable/launch_background</item>
+    </style>
+    <!-- Theme applied to the Android Window as soon as the process has started.
+         This theme determines the color of the Android Window while your
+         Flutter UI initializes, as well as behind your Flutter UI while its
+         running.
+
+         This Theme is only used starting with V2 of Flutter's Android embedding. -->
+    <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
+        <item name="android:windowBackground">?android:colorBackground</item>
+    </style>
+</resources>

+ 7 - 0
android/app/src/profile/AndroidManifest.xml

@@ -0,0 +1,7 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+    <!-- The INTERNET permission is required for development. Specifically,
+         the Flutter tool needs it to communicate with the running application
+         to allow setting breakpoints, to provide hot reload, etc.
+    -->
+    <uses-permission android:name="android.permission.INTERNET"/>
+</manifest>

+ 24 - 0
android/build.gradle.kts

@@ -0,0 +1,24 @@
+allprojects {
+    repositories {
+        google()
+        mavenCentral()
+    }
+}
+
+val newBuildDir: Directory =
+    rootProject.layout.buildDirectory
+        .dir("../../build")
+        .get()
+rootProject.layout.buildDirectory.value(newBuildDir)
+
+subprojects {
+    val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
+    project.layout.buildDirectory.value(newSubprojectBuildDir)
+}
+subprojects {
+    project.evaluationDependsOn(":app")
+}
+
+tasks.register<Delete>("clean") {
+    delete(rootProject.layout.buildDirectory)
+}

Разница между файлами не показана из-за своего большого размера
+ 663 - 0
android/build/reports/problems/problems-report.html


+ 6 - 0
android/gradle.properties

@@ -0,0 +1,6 @@
+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
+android.useAndroidX=true
+# This newDsl flag was added by the Flutter template
+android.newDsl=false
+# This builtInKotlin flag was added by the Flutter template
+android.builtInKotlin=false

+ 5 - 0
android/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip

+ 26 - 0
android/settings.gradle.kts

@@ -0,0 +1,26 @@
+pluginManagement {
+    val flutterSdkPath =
+        run {
+            val properties = java.util.Properties()
+            file("local.properties").inputStream().use { properties.load(it) }
+            val flutterSdkPath = properties.getProperty("flutter.sdk")
+            require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
+            flutterSdkPath
+        }
+
+    includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
+
+    repositories {
+        google()
+        mavenCentral()
+        gradlePluginPortal()
+    }
+}
+
+plugins {
+    id("dev.flutter.flutter-plugin-loader") version "1.0.0"
+    id("com.android.application") version "9.0.1" apply false
+    id("org.jetbrains.kotlin.android") version "2.3.20" apply false
+}
+
+include(":app")

BIN
assets/icons/mebarista.png


BIN
assets/icons/mebarista_foreground.png


+ 11 - 0
flutter_launcher_icons.yaml

@@ -0,0 +1,11 @@
+flutter_launcher_icons:
+  android: true
+  ios: true
+  image_path: "assets/icons/mebarista.png"
+  adaptive_icon_background: "#FFFFFF"
+  adaptive_icon_foreground: "assets/icons/mebarista_foreground.png"
+  adaptive_icon_foreground_inset: 16
+  remove_alpha_ios: true
+  background_color_ios: "#FFFFFF"
+  macos:
+    generate: true

+ 34 - 0
ios/.gitignore

@@ -0,0 +1,34 @@
+**/dgph
+*.mode1v3
+*.mode2v3
+*.moved-aside
+*.pbxuser
+*.perspectivev3
+**/*sync/
+.sconsign.dblite
+.tags*
+**/.vagrant/
+**/DerivedData/
+Icon?
+**/Pods/
+**/.symlinks/
+profile
+xcuserdata
+**/.generated/
+Flutter/App.framework
+Flutter/Flutter.framework
+Flutter/Flutter.podspec
+Flutter/Generated.xcconfig
+Flutter/ephemeral/
+Flutter/app.flx
+Flutter/app.zip
+Flutter/flutter_assets/
+Flutter/flutter_export_environment.sh
+ServiceDefinitions.json
+Runner/GeneratedPluginRegistrant.*
+
+# Exceptions to above rules.
+!default.mode1v3
+!default.mode2v3
+!default.pbxuser
+!default.perspectivev3

+ 24 - 0
ios/Flutter/AppFrameworkInfo.plist

@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+  <key>CFBundleDevelopmentRegion</key>
+  <string>en</string>
+  <key>CFBundleExecutable</key>
+  <string>App</string>
+  <key>CFBundleIdentifier</key>
+  <string>io.flutter.flutter.app</string>
+  <key>CFBundleInfoDictionaryVersion</key>
+  <string>6.0</string>
+  <key>CFBundleName</key>
+  <string>App</string>
+  <key>CFBundlePackageType</key>
+  <string>FMWK</string>
+  <key>CFBundleShortVersionString</key>
+  <string>1.0</string>
+  <key>CFBundleSignature</key>
+  <string>????</string>
+  <key>CFBundleVersion</key>
+  <string>1.0</string>
+</dict>
+</plist>

+ 1 - 0
ios/Flutter/Debug.xcconfig

@@ -0,0 +1 @@
+#include "Generated.xcconfig"

+ 1 - 0
ios/Flutter/Release.xcconfig

@@ -0,0 +1 @@
+#include "Generated.xcconfig"

+ 644 - 0
ios/Runner.xcodeproj/project.pbxproj

@@ -0,0 +1,644 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 54;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
+		331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
+		3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
+		74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
+		7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
+		78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
+		97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
+		97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
+		97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+		331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 97C146E61CF9000F007C117D /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 97C146ED1CF9000F007C117D;
+			remoteInfo = Runner;
+		};
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXCopyFilesBuildPhase section */
+		9705A1C41CF9048500538489 /* Embed Frameworks */ = {
+			isa = PBXCopyFilesBuildPhase;
+			buildActionMask = 2147483647;
+			dstPath = "";
+			dstSubfolderSpec = 10;
+			files = (
+			);
+			name = "Embed Frameworks";
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXCopyFilesBuildPhase section */
+
+/* Begin PBXFileReference section */
+		1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
+		1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
+		331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
+		331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
+		3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
+		74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
+		74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
+		7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
+		78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
+		7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
+		9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
+		9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
+		97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
+		97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
+		97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+		97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
+		97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		97C146EB1CF9000F007C117D /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		331C8082294A63A400263BE5 /* RunnerTests */ = {
+			isa = PBXGroup;
+			children = (
+				331C807B294A618700263BE5 /* RunnerTests.swift */,
+			);
+			path = RunnerTests;
+			sourceTree = "<group>";
+		};
+		9740EEB11CF90186004384FC /* Flutter */ = {
+			isa = PBXGroup;
+			children = (
+				78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,
+				3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
+				9740EEB21CF90195004384FC /* Debug.xcconfig */,
+				7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
+				9740EEB31CF90195004384FC /* Generated.xcconfig */,
+			);
+			name = Flutter;
+			sourceTree = "<group>";
+		};
+		97C146E51CF9000F007C117D = {
+			isa = PBXGroup;
+			children = (
+				9740EEB11CF90186004384FC /* Flutter */,
+				97C146F01CF9000F007C117D /* Runner */,
+				97C146EF1CF9000F007C117D /* Products */,
+				331C8082294A63A400263BE5 /* RunnerTests */,
+			);
+			sourceTree = "<group>";
+		};
+		97C146EF1CF9000F007C117D /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				97C146EE1CF9000F007C117D /* Runner.app */,
+				331C8081294A63A400263BE5 /* RunnerTests.xctest */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		97C146F01CF9000F007C117D /* Runner */ = {
+			isa = PBXGroup;
+			children = (
+				97C146FA1CF9000F007C117D /* Main.storyboard */,
+				97C146FD1CF9000F007C117D /* Assets.xcassets */,
+				97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
+				97C147021CF9000F007C117D /* Info.plist */,
+				1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
+				1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
+				74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
+				7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
+				74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
+			);
+			path = Runner;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+		331C8080294A63A400263BE5 /* RunnerTests */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
+			buildPhases = (
+				331C807D294A63A400263BE5 /* Sources */,
+				331C807F294A63A400263BE5 /* Resources */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				331C8086294A63A400263BE5 /* PBXTargetDependency */,
+			);
+			name = RunnerTests;
+			productName = RunnerTests;
+			productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */;
+			productType = "com.apple.product-type.bundle.unit-test";
+		};
+		97C146ED1CF9000F007C117D /* Runner */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
+			buildPhases = (
+				9740EEB61CF901F6004384FC /* Run Script */,
+				97C146EA1CF9000F007C117D /* Sources */,
+				97C146EB1CF9000F007C117D /* Frameworks */,
+				97C146EC1CF9000F007C117D /* Resources */,
+				9705A1C41CF9048500538489 /* Embed Frameworks */,
+				3B06AD1E1E4923F5004D2608 /* Thin Binary */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = Runner;
+			packageProductDependencies = (
+				78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
+			);
+			productName = Runner;
+			productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
+			productType = "com.apple.product-type.application";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		97C146E61CF9000F007C117D /* Project object */ = {
+			isa = PBXProject;
+			attributes = {
+				BuildIndependentTargetsInParallel = YES;
+				LastUpgradeCheck = 1510;
+				ORGANIZATIONNAME = "";
+				TargetAttributes = {
+					331C8080294A63A400263BE5 = {
+						CreatedOnToolsVersion = 14.0;
+						TestTargetID = 97C146ED1CF9000F007C117D;
+					};
+					97C146ED1CF9000F007C117D = {
+						CreatedOnToolsVersion = 7.3.1;
+						LastSwiftMigration = 1100;
+					};
+				};
+			};
+			buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
+			compatibilityVersion = "Xcode 9.3";
+			developmentRegion = en;
+			hasScannedForEncodings = 0;
+			knownRegions = (
+				en,
+				Base,
+			);
+			mainGroup = 97C146E51CF9000F007C117D;
+			packageReferences = (
+				781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,
+			);
+			productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				97C146ED1CF9000F007C117D /* Runner */,
+				331C8080294A63A400263BE5 /* RunnerTests */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+		331C807F294A63A400263BE5 /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		97C146EC1CF9000F007C117D /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
+				3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
+				97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
+				97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXShellScriptBuildPhase section */
+		3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
+			isa = PBXShellScriptBuildPhase;
+			alwaysOutOfDate = 1;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+				"${TARGET_BUILD_DIR}/${INFOPLIST_PATH}",
+			);
+			name = "Thin Binary";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
+		};
+		9740EEB61CF901F6004384FC /* Run Script */ = {
+			isa = PBXShellScriptBuildPhase;
+			alwaysOutOfDate = 1;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+			);
+			name = "Run Script";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
+		};
+/* End PBXShellScriptBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+		331C807D294A63A400263BE5 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		97C146EA1CF9000F007C117D /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
+				1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
+				7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+		331C8086294A63A400263BE5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 97C146ED1CF9000F007C117D /* Runner */;
+			targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */;
+		};
+/* End PBXTargetDependency section */
+
+/* Begin PBXVariantGroup section */
+		97C146FA1CF9000F007C117D /* Main.storyboard */ = {
+			isa = PBXVariantGroup;
+			children = (
+				97C146FB1CF9000F007C117D /* Base */,
+			);
+			name = Main.storyboard;
+			sourceTree = "<group>";
+		};
+		97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
+			isa = PBXVariantGroup;
+			children = (
+				97C147001CF9000F007C117D /* Base */,
+			);
+			name = LaunchScreen.storyboard;
+			sourceTree = "<group>";
+		};
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+		249021D3217E4FDB00AE95B9 /* Profile */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+				CLANG_CXX_LIBRARY = "libc++";
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_COMMA = YES;
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_EMPTY_BODY = YES;
+				CLANG_WARN_ENUM_CONVERSION = YES;
+				CLANG_WARN_INFINITE_RECURSION = YES;
+				CLANG_WARN_INT_CONVERSION = YES;
+				CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+				CLANG_WARN_STRICT_PROTOTYPES = YES;
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
+				CLANG_WARN_UNREACHABLE_CODE = YES;
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				COPY_PHASE_STRIP = NO;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				ENABLE_NS_ASSERTIONS = NO;
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
+				ENABLE_USER_SCRIPT_SANDBOXING = NO;
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_NO_COMMON_BLOCKS = YES;
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 13.0;
+				MTL_ENABLE_DEBUG_INFO = NO;
+				SDKROOT = iphoneos;
+				SUPPORTED_PLATFORMS = iphoneos;
+				TARGETED_DEVICE_FAMILY = "1,2";
+				VALIDATE_PRODUCT = YES;
+			};
+			name = Profile;
+		};
+		249021D4217E4FDB00AE95B9 /* Profile */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+			buildSettings = {
+				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CLANG_ENABLE_MODULES = YES;
+				CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+				ENABLE_BITCODE = NO;
+				INFOPLIST_FILE = Runner/Info.plist;
+				LD_RUNPATH_SEARCH_PATHS = (
+					"$(inherited)",
+					"@executable_path/Frameworks",
+				);
+				PRODUCT_BUNDLE_IDENTIFIER = com.example.mebarista;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+				SWIFT_VERSION = 5.0;
+				VERSIONING_SYSTEM = "apple-generic";
+			};
+			name = Profile;
+		};
+		331C8088294A63A400263BE5 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CODE_SIGN_STYLE = Automatic;
+				CURRENT_PROJECT_VERSION = 1;
+				GENERATE_INFOPLIST_FILE = YES;
+				MARKETING_VERSION = 1.0;
+				PRODUCT_BUNDLE_IDENTIFIER = com.example.mebarista.RunnerTests;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 5.0;
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
+			};
+			name = Debug;
+		};
+		331C8089294A63A400263BE5 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CODE_SIGN_STYLE = Automatic;
+				CURRENT_PROJECT_VERSION = 1;
+				GENERATE_INFOPLIST_FILE = YES;
+				MARKETING_VERSION = 1.0;
+				PRODUCT_BUNDLE_IDENTIFIER = com.example.mebarista.RunnerTests;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_VERSION = 5.0;
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
+			};
+			name = Release;
+		};
+		331C808A294A63A400263BE5 /* Profile */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CODE_SIGN_STYLE = Automatic;
+				CURRENT_PROJECT_VERSION = 1;
+				GENERATE_INFOPLIST_FILE = YES;
+				MARKETING_VERSION = 1.0;
+				PRODUCT_BUNDLE_IDENTIFIER = com.example.mebarista.RunnerTests;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_VERSION = 5.0;
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
+			};
+			name = Profile;
+		};
+		97C147031CF9000F007C117D /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon;
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+				CLANG_CXX_LIBRARY = "libc++";
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_COMMA = YES;
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_EMPTY_BODY = YES;
+				CLANG_WARN_ENUM_CONVERSION = YES;
+				CLANG_WARN_INFINITE_RECURSION = YES;
+				CLANG_WARN_INT_CONVERSION = YES;
+				CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+				CLANG_WARN_STRICT_PROTOTYPES = YES;
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
+				CLANG_WARN_UNREACHABLE_CODE = YES;
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				COPY_PHASE_STRIP = NO;
+				DEBUG_INFORMATION_FORMAT = dwarf;
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
+				ENABLE_TESTABILITY = YES;
+				ENABLE_USER_SCRIPT_SANDBOXING = NO;
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_NO_COMMON_BLOCKS = YES;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					"DEBUG=1",
+					"$(inherited)",
+				);
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 13.0;
+				MTL_ENABLE_DEBUG_INFO = YES;
+				ONLY_ACTIVE_ARCH = YES;
+				SDKROOT = iphoneos;
+				TARGETED_DEVICE_FAMILY = "1,2";
+			};
+			name = Debug;
+		};
+		97C147041CF9000F007C117D /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon;
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+				CLANG_CXX_LIBRARY = "libc++";
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_COMMA = YES;
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_EMPTY_BODY = YES;
+				CLANG_WARN_ENUM_CONVERSION = YES;
+				CLANG_WARN_INFINITE_RECURSION = YES;
+				CLANG_WARN_INT_CONVERSION = YES;
+				CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+				CLANG_WARN_STRICT_PROTOTYPES = YES;
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
+				CLANG_WARN_UNREACHABLE_CODE = YES;
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				COPY_PHASE_STRIP = NO;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				ENABLE_NS_ASSERTIONS = NO;
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
+				ENABLE_USER_SCRIPT_SANDBOXING = NO;
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_NO_COMMON_BLOCKS = YES;
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 13.0;
+				MTL_ENABLE_DEBUG_INFO = NO;
+				SDKROOT = iphoneos;
+				SUPPORTED_PLATFORMS = iphoneos;
+				SWIFT_COMPILATION_MODE = wholemodule;
+				SWIFT_OPTIMIZATION_LEVEL = "-O";
+				TARGETED_DEVICE_FAMILY = "1,2";
+				VALIDATE_PRODUCT = YES;
+			};
+			name = Release;
+		};
+		97C147061CF9000F007C117D /* Debug */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
+			buildSettings = {
+				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CLANG_ENABLE_MODULES = YES;
+				CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+				ENABLE_BITCODE = NO;
+				INFOPLIST_FILE = Runner/Info.plist;
+				LD_RUNPATH_SEARCH_PATHS = (
+					"$(inherited)",
+					"@executable_path/Frameworks",
+				);
+				PRODUCT_BUNDLE_IDENTIFIER = com.example.mebarista;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 5.0;
+				VERSIONING_SYSTEM = "apple-generic";
+			};
+			name = Debug;
+		};
+		97C147071CF9000F007C117D /* Release */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+			buildSettings = {
+				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CLANG_ENABLE_MODULES = YES;
+				CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+				ENABLE_BITCODE = NO;
+				INFOPLIST_FILE = Runner/Info.plist;
+				LD_RUNPATH_SEARCH_PATHS = (
+					"$(inherited)",
+					"@executable_path/Frameworks",
+				);
+				PRODUCT_BUNDLE_IDENTIFIER = com.example.mebarista;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+				SWIFT_VERSION = 5.0;
+				VERSIONING_SYSTEM = "apple-generic";
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				331C8088294A63A400263BE5 /* Debug */,
+				331C8089294A63A400263BE5 /* Release */,
+				331C808A294A63A400263BE5 /* Profile */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				97C147031CF9000F007C117D /* Debug */,
+				97C147041CF9000F007C117D /* Release */,
+				249021D3217E4FDB00AE95B9 /* Profile */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				97C147061CF9000F007C117D /* Debug */,
+				97C147071CF9000F007C117D /* Release */,
+				249021D4217E4FDB00AE95B9 /* Profile */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+
+/* Begin XCLocalSwiftPackageReference section */
+		781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {
+			isa = XCLocalSwiftPackageReference;
+			relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
+		};
+/* End XCLocalSwiftPackageReference section */
+
+/* Begin XCSwiftPackageProductDependency section */
+		78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
+			isa = XCSwiftPackageProductDependency;
+			productName = FlutterGeneratedPluginSwiftPackage;
+		};
+/* End XCSwiftPackageProductDependency section */
+	};
+	rootObject = 97C146E61CF9000F007C117D /* Project object */;
+}

+ 7 - 0
ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+   version = "1.0">
+   <FileRef
+      location = "self:">
+   </FileRef>
+</Workspace>

+ 8 - 0
ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IDEDidComputeMac32BitWarning</key>
+	<true/>
+</dict>
+</plist>

+ 8 - 0
ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>PreviewsEnabled</key>
+	<false/>
+</dict>
+</plist>

+ 119 - 0
ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme

@@ -0,0 +1,119 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+   LastUpgradeVersion = "1510"
+   version = "1.3">
+   <BuildAction
+      parallelizeBuildables = "YES"
+      buildImplicitDependencies = "YES">
+      <PreActions>
+         <ExecutionAction
+            ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
+            <ActionContent
+               title = "Run Prepare Flutter Framework Script"
+               scriptText = "/bin/sh &quot;$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh&quot; prepare&#10;">
+               <EnvironmentBuildable>
+                  <BuildableReference
+                     BuildableIdentifier = "primary"
+                     BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+                     BuildableName = "Runner.app"
+                     BlueprintName = "Runner"
+                     ReferencedContainer = "container:Runner.xcodeproj">
+                  </BuildableReference>
+               </EnvironmentBuildable>
+            </ActionContent>
+         </ExecutionAction>
+      </PreActions>
+      <BuildActionEntries>
+         <BuildActionEntry
+            buildForTesting = "YES"
+            buildForRunning = "YES"
+            buildForProfiling = "YES"
+            buildForArchiving = "YES"
+            buildForAnalyzing = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+               BuildableName = "Runner.app"
+               BlueprintName = "Runner"
+               ReferencedContainer = "container:Runner.xcodeproj">
+            </BuildableReference>
+         </BuildActionEntry>
+      </BuildActionEntries>
+   </BuildAction>
+   <TestAction
+      buildConfiguration = "Debug"
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
+      shouldUseLaunchSchemeArgsEnv = "YES">
+      <MacroExpansion>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+            BuildableName = "Runner.app"
+            BlueprintName = "Runner"
+            ReferencedContainer = "container:Runner.xcodeproj">
+         </BuildableReference>
+      </MacroExpansion>
+      <Testables>
+         <TestableReference
+            skipped = "NO"
+            parallelizable = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "331C8080294A63A400263BE5"
+               BuildableName = "RunnerTests.xctest"
+               BlueprintName = "RunnerTests"
+               ReferencedContainer = "container:Runner.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+      </Testables>
+   </TestAction>
+   <LaunchAction
+      buildConfiguration = "Debug"
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"
+      launchStyle = "0"
+      useCustomWorkingDirectory = "NO"
+      ignoresPersistentStateOnLaunch = "NO"
+      debugDocumentVersioning = "YES"
+      debugServiceExtension = "internal"
+      enableGPUValidationMode = "1"
+      allowLocationSimulation = "YES">
+      <BuildableProductRunnable
+         runnableDebuggingMode = "0">
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+            BuildableName = "Runner.app"
+            BlueprintName = "Runner"
+            ReferencedContainer = "container:Runner.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+   </LaunchAction>
+   <ProfileAction
+      buildConfiguration = "Profile"
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      savedToolIdentifier = ""
+      useCustomWorkingDirectory = "NO"
+      debugDocumentVersioning = "YES">
+      <BuildableProductRunnable
+         runnableDebuggingMode = "0">
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+            BuildableName = "Runner.app"
+            BlueprintName = "Runner"
+            ReferencedContainer = "container:Runner.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+   </ProfileAction>
+   <AnalyzeAction
+      buildConfiguration = "Debug">
+   </AnalyzeAction>
+   <ArchiveAction
+      buildConfiguration = "Release"
+      revealArchiveInOrganizer = "YES">
+   </ArchiveAction>
+</Scheme>

+ 7 - 0
ios/Runner.xcworkspace/contents.xcworkspacedata

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+   version = "1.0">
+   <FileRef
+      location = "group:Runner.xcodeproj">
+   </FileRef>
+</Workspace>

+ 8 - 0
ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IDEDidComputeMac32BitWarning</key>
+	<true/>
+</dict>
+</plist>

+ 8 - 0
ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>PreviewsEnabled</key>
+	<false/>
+</dict>
+</plist>

+ 16 - 0
ios/Runner/AppDelegate.swift

@@ -0,0 +1,16 @@
+import Flutter
+import UIKit
+
+@main
+@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
+  override func application(
+    _ application: UIApplication,
+    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
+  ) -> Bool {
+    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
+  }
+
+  func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
+    GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
+  }
+}

Разница между файлами не показана из-за своего большого размера
+ 1 - 0
ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png


BIN
ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png


+ 23 - 0
ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json

@@ -0,0 +1,23 @@
+{
+  "images" : [
+    {
+      "idiom" : "universal",
+      "filename" : "LaunchImage.png",
+      "scale" : "1x"
+    },
+    {
+      "idiom" : "universal",
+      "filename" : "LaunchImage@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "idiom" : "universal",
+      "filename" : "LaunchImage@3x.png",
+      "scale" : "3x"
+    }
+  ],
+  "info" : {
+    "version" : 1,
+    "author" : "xcode"
+  }
+}

BIN
ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png


BIN
ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png


BIN
ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png


+ 5 - 0
ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md

@@ -0,0 +1,5 @@
+# Launch Screen Assets
+
+You can customize the launch screen with your own desired assets by replacing the image files in this directory.
+
+You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.

+ 37 - 0
ios/Runner/Base.lproj/LaunchScreen.storyboard

@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
+    <dependencies>
+        <deployment identifier="iOS"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
+    </dependencies>
+    <scenes>
+        <!--View Controller-->
+        <scene sceneID="EHf-IW-A2E">
+            <objects>
+                <viewController id="01J-lp-oVM" sceneMemberID="viewController">
+                    <layoutGuides>
+                        <viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
+                        <viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
+                    </layoutGuides>
+                    <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <subviews>
+                            <imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
+                            </imageView>
+                        </subviews>
+                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
+                        <constraints>
+                            <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
+                            <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
+                        </constraints>
+                    </view>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
+            </objects>
+            <point key="canvasLocation" x="53" y="375"/>
+        </scene>
+    </scenes>
+    <resources>
+        <image name="LaunchImage" width="168" height="185"/>
+    </resources>
+</document>

+ 26 - 0
ios/Runner/Base.lproj/Main.storyboard

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
+    <dependencies>
+        <deployment identifier="iOS"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
+    </dependencies>
+    <scenes>
+        <!--Flutter View Controller-->
+        <scene sceneID="tne-QT-ifu">
+            <objects>
+                <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
+                    <layoutGuides>
+                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
+                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
+                    </layoutGuides>
+                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
+                        <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
+                    </view>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
+            </objects>
+        </scene>
+    </scenes>
+</document>

+ 74 - 0
ios/Runner/Info.plist

@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CADisableMinimumFrameDurationOnPhone</key>
+	<true/>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>$(DEVELOPMENT_LANGUAGE)</string>
+	<key>CFBundleDisplayName</key>
+	<string>meBarista</string>
+	<key>CFBundleExecutable</key>
+	<string>$(EXECUTABLE_NAME)</string>
+	<key>CFBundleIdentifier</key>
+	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>meBarista</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>$(FLUTTER_BUILD_NAME)</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CFBundleVersion</key>
+	<string>$(FLUTTER_BUILD_NUMBER)</string>
+	<key>LSRequiresIPhoneOS</key>
+	<true/>
+	<key>UIApplicationSceneManifest</key>
+	<dict>
+		<key>UIApplicationSupportsMultipleScenes</key>
+		<false/>
+		<key>UISceneConfigurations</key>
+		<dict>
+			<key>UIWindowSceneSessionRoleApplication</key>
+			<array>
+				<dict>
+					<key>UISceneClassName</key>
+					<string>UIWindowScene</string>
+					<key>UISceneConfigurationName</key>
+					<string>flutter</string>
+					<key>UISceneDelegateClassName</key>
+					<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
+					<key>UISceneStoryboardFile</key>
+					<string>Main</string>
+				</dict>
+			</array>
+		</dict>
+	</dict>
+	<key>NSBluetoothAlwaysUsageDescription</key>
+	<string>This app needs Bluetooth to connect to your meCoffee device.</string>
+	<key>NSBluetoothPeripheralUsageDescription</key>
+	<string>This app needs Bluetooth to connect to your meCoffee device.</string>
+	<key>UIApplicationSupportsIndirectInputEvents</key>
+	<true/>
+	<key>UILaunchStoryboardName</key>
+	<string>LaunchScreen</string>
+	<key>UIMainStoryboardFile</key>
+	<string>Main</string>
+	<key>UISupportedInterfaceOrientations</key>
+	<array>
+		<string>UIInterfaceOrientationPortrait</string>
+		<string>UIInterfaceOrientationLandscapeLeft</string>
+		<string>UIInterfaceOrientationLandscapeRight</string>
+	</array>
+	<key>UISupportedInterfaceOrientations~ipad</key>
+	<array>
+		<string>UIInterfaceOrientationPortrait</string>
+		<string>UIInterfaceOrientationPortraitUpsideDown</string>
+		<string>UIInterfaceOrientationLandscapeLeft</string>
+		<string>UIInterfaceOrientationLandscapeRight</string>
+	</array>
+</dict>
+</plist>

+ 1 - 0
ios/Runner/Runner-Bridging-Header.h

@@ -0,0 +1 @@
+#import "GeneratedPluginRegistrant.h"

+ 6 - 0
ios/Runner/SceneDelegate.swift

@@ -0,0 +1,6 @@
+import Flutter
+import UIKit
+
+class SceneDelegate: FlutterSceneDelegate {
+
+}

+ 12 - 0
ios/RunnerTests/RunnerTests.swift

@@ -0,0 +1,12 @@
+import Flutter
+import UIKit
+import XCTest
+
+class RunnerTests: XCTestCase {
+
+  func testExample() {
+    // If you add code to the Runner application, consider adding tests here.
+    // See https://developer.apple.com/documentation/xctest for more information about using XCTest.
+  }
+
+}

+ 495 - 0
lib/main.dart

@@ -0,0 +1,495 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'services/bluetooth_service.dart';
+import 'widgets/temperature_chart.dart';
+import 'screens/settings_screen.dart';
+import 'screens/connection_screen.dart';
+import 'screens/diagnostics_screen.dart';
+
+void main() {
+  runApp(const ProviderScope(child: MyApp()));
+}
+
+class MyApp extends StatelessWidget {
+  const MyApp({super.key});
+
+  @override
+  Widget build(BuildContext context) {
+    return MaterialApp(
+      title: 'meBarista',
+      theme: ThemeData(
+        brightness: Brightness.dark,
+        colorScheme: ColorScheme.fromSeed(
+          seedColor: Colors.brown,
+          brightness: Brightness.dark,
+        ),
+        useMaterial3: true,
+      ),
+      home: const MyHomePage(title: 'meBarista Dashboard'),
+    );
+  }
+}
+
+class MyHomePage extends ConsumerWidget {
+  const MyHomePage({super.key, required this.title});
+
+  final String title;
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+    final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
+    void connect() {
+      if (bluetoothService.supportsClassic) {
+        Navigator.of(
+          context,
+        ).push(MaterialPageRoute(builder: (_) => const ConnectionScreen()));
+      } else {
+        bluetoothService.startScan();
+      }
+    }
+
+    ref.listen(bluetoothServiceProvider, (previous, next) {
+      if (next.commandError != null &&
+          next.commandError != previous?.commandError) {
+        ScaffoldMessenger.of(
+          context,
+        ).showSnackBar(SnackBar(content: Text(next.commandError!)));
+      }
+    });
+
+    return Scaffold(
+      appBar: AppBar(
+        title: Text(title),
+        actions: [
+          IconButton(
+            tooltip: 'Diagnostics',
+            icon: const Icon(Icons.receipt_long),
+            onPressed: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(builder: (_) => const DiagnosticsScreen()),
+              );
+            },
+          ),
+          IconButton(
+            icon: const Icon(Icons.settings),
+            onPressed: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(builder: (context) => const SettingsScreen()),
+              );
+            },
+          ),
+          IconButton(
+            onPressed: machineState.firmwareUpdating ? null : connect,
+            icon: Icon(
+              machineState.connectionStatus == 'Connected'
+                  ? Icons.bluetooth_connected
+                  : machineState.connectionStatus.startsWith('Error')
+                  ? Icons.bluetooth_disabled
+                  : Icons.bluetooth_searching,
+              color: machineState.connectionStatus == 'Connected'
+                  ? Colors.blue
+                  : machineState.connectionStatus.startsWith('Error')
+                  ? Colors.redAccent
+                  : null,
+            ),
+          ),
+        ],
+      ),
+      body: SafeArea(
+        top: false,
+        child: SingleChildScrollView(
+          padding: const EdgeInsets.all(16.0),
+          child: Column(
+            crossAxisAlignment: CrossAxisAlignment.stretch,
+            children: [
+              if (machineState.connectionStatus == 'Connected' &&
+                  machineState.telemetryStale)
+                Card(
+                  color: Colors.amber.withValues(alpha: 0.15),
+                  child: Padding(
+                    padding: const EdgeInsets.all(12),
+                    child: Text(
+                      machineState.lastTelemetryAt == null
+                          ? 'Waiting for temperature telemetry. Readings are unavailable.'
+                          : 'Telemetry stale: no temperature sample for 3 seconds. '
+                                'Displayed readings are the last received values.',
+                      style: const TextStyle(color: Colors.amber),
+                    ),
+                  ),
+                ),
+              if (machineState.firmwareUpdating)
+                Card(
+                  child: Padding(
+                    padding: const EdgeInsets.all(16),
+                    child: Column(
+                      children: [
+                        Text(machineState.firmwareUpdateStatus),
+                        const SizedBox(height: 8),
+                        LinearProgressIndicator(
+                          value: machineState.firmwareProgress,
+                        ),
+                        const Text(
+                          'Keep controller power and Bluetooth connected.',
+                        ),
+                      ],
+                    ),
+                  ),
+                ),
+              // Temperature Display Card
+              Card(
+                child: Padding(
+                  padding: const EdgeInsets.all(20.0),
+                  child: Column(
+                    children: [
+                      Row(
+                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
+                        children: [
+                          const Text(
+                            'Boiler Temperature',
+                            style: TextStyle(fontSize: 18),
+                          ),
+                          Icon(
+                            Icons.coffee_maker,
+                            size: 32,
+                            color:
+                                machineState.connectionStatus == 'Connected' &&
+                                    !machineState.telemetryStale
+                                ? (machineState.isHeating
+                                      ? Colors.redAccent
+                                      : Colors.blueAccent)
+                                : Colors.grey,
+                          ),
+                        ],
+                      ),
+                      const SizedBox(height: 10),
+                      Text(
+                        '${machineState.temperature.toStringAsFixed(1)}°C',
+                        style: const TextStyle(
+                          fontSize: 64,
+                          fontWeight: FontWeight.bold,
+                          color: Colors.orangeAccent,
+                        ),
+                      ),
+                      // Second sensor reading (shown only when present)
+                      if (machineState.sensor2Temperature > 0)
+                        Padding(
+                          padding: const EdgeInsets.only(top: 4.0),
+                          child: Row(
+                            mainAxisAlignment: MainAxisAlignment.center,
+                            children: [
+                              const Icon(
+                                Icons.thermostat,
+                                size: 14,
+                                color: Colors.greenAccent,
+                              ),
+                              const SizedBox(width: 4),
+                              Text(
+                                'Sensor 2: ${machineState.sensor2Temperature.toStringAsFixed(1)}°C',
+                                style: const TextStyle(
+                                  fontSize: 13,
+                                  color: Colors.greenAccent,
+                                ),
+                              ),
+                            ],
+                          ),
+                        ),
+                      const SizedBox(height: 10),
+                      // PID Power Indicator
+                      Row(
+                        children: [
+                          const Icon(
+                            Icons.bolt,
+                            size: 16,
+                            color: Colors.yellowAccent,
+                          ),
+                          Expanded(
+                            child: Padding(
+                              padding: const EdgeInsets.symmetric(
+                                horizontal: 8.0,
+                              ),
+                              child: LinearProgressIndicator(
+                                value: machineState.telemetryStale
+                                    ? 0
+                                    : machineState.heatingPower,
+                                backgroundColor: Colors.grey.withValues(
+                                  alpha: 0.2,
+                                ),
+                                color: Colors.redAccent,
+                                minHeight: 8,
+                                borderRadius: BorderRadius.circular(4),
+                              ),
+                            ),
+                          ),
+                          Text(
+                            machineState.telemetryStale
+                                ? 'Unavailable'
+                                : '${(machineState.heatingPower * 100).toStringAsFixed(0)}%',
+                            style: const TextStyle(
+                              fontSize: 12,
+                              color: Colors.grey,
+                            ),
+                          ),
+                        ],
+                      ),
+                      const SizedBox(height: 16),
+                      // Target Control
+                      Row(
+                        mainAxisAlignment: MainAxisAlignment.center,
+                        children: [
+                          IconButton(
+                            onPressed: () =>
+                                bluetoothService.decrementSetpoint(),
+                            icon: const Icon(
+                              Icons.remove_circle_outline,
+                              color: Colors.grey,
+                            ),
+                          ),
+                          Column(
+                            children: [
+                              const Text(
+                                'BREW TARGET',
+                                style: TextStyle(
+                                  fontSize: 10,
+                                  color: Colors.grey,
+                                ),
+                              ),
+                              Text(
+                                '${machineState.brewTemperature.toStringAsFixed(1)}°C',
+                                style: const TextStyle(
+                                  fontSize: 18,
+                                  fontWeight: FontWeight.bold,
+                                ),
+                              ),
+                            ],
+                          ),
+                          IconButton(
+                            onPressed: () =>
+                                bluetoothService.incrementSetpoint(),
+                            icon: const Icon(
+                              Icons.add_circle_outline,
+                              color: Colors.grey,
+                            ),
+                          ),
+                        ],
+                      ),
+                    ],
+                  ),
+                ),
+              ),
+              const SizedBox(height: 16),
+              // Shot Timer (Visible when brewing or after a shot)
+              if (machineState.isBrewing || machineState.shotTimer > 0)
+                Card(
+                  color: machineState.isBrewing && !machineState.telemetryStale
+                      ? Colors.green.withValues(alpha: 0.2)
+                      : null,
+                  child: Padding(
+                    padding: const EdgeInsets.all(16.0),
+                    child: Row(
+                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
+                      children: [
+                        const Text(
+                          'Shot Timer',
+                          style: TextStyle(
+                            fontSize: 18,
+                            fontWeight: FontWeight.bold,
+                          ),
+                        ),
+                        Text(
+                          '${machineState.shotTimer}s',
+                          style: TextStyle(
+                            fontSize: 32,
+                            fontWeight: FontWeight.bold,
+                            color:
+                                machineState.isBrewing &&
+                                    !machineState.telemetryStale
+                                ? Colors.greenAccent
+                                : Colors.grey,
+                          ),
+                        ),
+                      ],
+                    ),
+                  ),
+                ),
+              const SizedBox(height: 16),
+              // Status Indicators
+              Row(
+                children: [
+                  Expanded(
+                    child: _StatusCard(
+                      label: 'Heating',
+                      isActive:
+                          machineState.isHeating &&
+                          !machineState.telemetryStale,
+                      activeColor: Colors.redAccent,
+                      icon: Icons.hot_tub,
+                    ),
+                  ),
+                  const SizedBox(width: 16),
+                  Expanded(
+                    child: _StatusCard(
+                      label: 'Brewing',
+                      isActive:
+                          machineState.isBrewing &&
+                          !machineState.telemetryStale,
+                      activeColor: Colors.greenAccent,
+                      icon: Icons.coffee,
+                    ),
+                  ),
+                ],
+              ),
+              const SizedBox(height: 16),
+              // Temperature Chart
+              Card(
+                child: Padding(
+                  padding: const EdgeInsets.all(16.0),
+                  child: Column(
+                    crossAxisAlignment: CrossAxisAlignment.start,
+                    children: [
+                      Row(
+                        children: [
+                          const Text(
+                            'Temperature Stability',
+                            style: TextStyle(fontSize: 16),
+                          ),
+                          const Spacer(),
+                          // Legend
+                          const _LegendDot(
+                            color: Colors.redAccent,
+                            label: 'Boiler',
+                          ),
+                          if (machineState
+                              .sensor2TemperatureHistory
+                              .isNotEmpty) ...[
+                            const SizedBox(width: 12),
+                            const _LegendDot(
+                              color: Colors.greenAccent,
+                              label: 'Sensor 2',
+                            ),
+                          ],
+                          const SizedBox(width: 12),
+                          _LegendDot(
+                            color: Colors.blue.withValues(alpha: 0.5),
+                            label: 'Target',
+                          ),
+                        ],
+                      ),
+                      const SizedBox(height: 20),
+                      SizedBox(
+                        height: 320,
+                        child: TemperatureChart(
+                          history: machineState.temperatureHistory,
+                          sensor2History:
+                              machineState.sensor2TemperatureHistory,
+                          targetTemperature: machineState.targetTemperature,
+                          samples: machineState.temperatureSamples,
+                        ),
+                      ),
+                    ],
+                  ),
+                ),
+              ),
+              const SizedBox(height: 20),
+              if (machineState.connectionStatus != 'Connected')
+                ElevatedButton.icon(
+                  onPressed: machineState.connectionStatus == 'Scanning...'
+                      ? null
+                      : machineState.firmwareUpdating
+                      ? null
+                      : connect,
+                  icon: Icon(
+                    machineState.connectionStatus.startsWith('Error')
+                        ? Icons.bluetooth_disabled
+                        : Icons.search,
+                  ),
+                  style: machineState.connectionStatus.startsWith('Error')
+                      ? ElevatedButton.styleFrom(
+                          backgroundColor: Colors.redAccent.withValues(
+                            alpha: 0.2,
+                          ),
+                        )
+                      : null,
+                  label: Text(switch (machineState.connectionStatus) {
+                    'Scanning...' => 'Scanning…',
+                    'Reconnecting...' =>
+                      'Reconnecting in 30s…  (tap to retry now)',
+                    'Not found' => 'Not found — tap to retry',
+                    String s when s.startsWith('Error') =>
+                      '${machineState.connectionStatus}  —  tap to retry',
+                    _ => 'Connect to meCoffee',
+                  }),
+                )
+              else
+                OutlinedButton(
+                  onPressed: machineState.firmwareUpdating
+                      ? null
+                      : () => bluetoothService.disconnect(),
+                  child: const Text('Disconnect'),
+                ),
+            ],
+          ),
+        ),
+      ),
+    );
+  }
+}
+
+class _StatusCard extends StatelessWidget {
+  final String label;
+  final bool isActive;
+  final Color activeColor;
+  final IconData icon;
+
+  const _StatusCard({
+    required this.label,
+    required this.isActive,
+    required this.activeColor,
+    required this.icon,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return Card(
+      color: isActive ? activeColor.withValues(alpha: 0.2) : null,
+      child: Padding(
+        padding: const EdgeInsets.symmetric(vertical: 16.0),
+        child: Column(
+          children: [
+            Icon(icon, color: isActive ? activeColor : Colors.grey),
+            const SizedBox(height: 8),
+            Text(
+              label,
+              style: TextStyle(
+                color: isActive ? activeColor : Colors.grey,
+                fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
+              ),
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+}
+
+class _LegendDot extends StatelessWidget {
+  final Color color;
+  final String label;
+  const _LegendDot({required this.color, required this.label});
+
+  @override
+  Widget build(BuildContext context) {
+    return Row(
+      mainAxisSize: MainAxisSize.min,
+      children: [
+        Container(
+          width: 10,
+          height: 10,
+          decoration: BoxDecoration(color: color, shape: BoxShape.circle),
+        ),
+        const SizedBox(width: 4),
+        Text(label, style: const TextStyle(fontSize: 11, color: Colors.grey)),
+      ],
+    );
+  }
+}

+ 16 - 0
lib/models/diagnostic_entry.dart

@@ -0,0 +1,16 @@
+enum DiagnosticDirection { received, sent, event }
+
+class DiagnosticEntry {
+  final DateTime timestamp;
+  final DiagnosticDirection direction;
+  final String message;
+
+  const DiagnosticEntry({
+    required this.timestamp,
+    required this.direction,
+    required this.message,
+  });
+
+  String get text =>
+      '${timestamp.toIso8601String()} ${direction.name.toUpperCase()} $message';
+}

+ 258 - 0
lib/models/machine_state.dart

@@ -0,0 +1,258 @@
+import 'diagnostic_entry.dart';
+import 'temperature_sample.dart';
+
+class MachineState {
+  final double temperature;
+  final double targetTemperature;
+  final bool isHeating;
+  final bool isBrewing;
+  final int shotTimer;
+  final String connectionStatus;
+  final String? commandError;
+  final List<double> temperatureHistory;
+  final List<TemperatureSample> temperatureSamples;
+  final List<DiagnosticEntry> diagnosticLog;
+  final DateTime? lastTelemetryAt;
+  final bool telemetryStale;
+  final String transportName;
+  final bool firmwareUpdating;
+  final double firmwareProgress;
+  final String firmwareUpdateStatus;
+
+  // Second temperature sensor (group-head / inline sensor, when present)
+  final double sensor2Temperature;
+  final List<double> sensor2TemperatureHistory;
+
+  // Configuration Parameters
+  final double preinfusionTime;
+  final int preinfusionPower;
+  final double brewTemperature;
+  final double steamTemperature;
+
+  // PID Parameters
+  final double pidP;
+  final double pidI;
+  final double pidD;
+  final double pidIWindDownMin;
+  final double pidIWindDownMax;
+  final int pidPollingInterval;
+
+  // Statistics
+  final int shotCounter;
+  final int grinderCounter;
+
+  // Pressure Profiling
+  final int pressureStart;
+  final int pressureEnd;
+  final int pressurePeriod;
+
+  // Real-time Power
+  final double heatingPower; // 0.0 to 1.0
+
+  // Advanced Logic
+  final bool valveClosedWhilePaused;
+  final int proActivePercentage;
+  final double temperatureOffset;
+  final int autoShutoffMinutes;
+
+  // Scheduling
+  final bool wakeupEnabled;
+  final String wakeupTime;
+  final bool shutdownEnabled;
+  final String shutdownTime;
+
+  // Ionic 2 / Hardware features
+  final bool preinfusionEnabled;
+  final double preinfusionPauseTime;
+  final int output0;
+  final int output1;
+  final int output2;
+  final bool installedAsTimer;
+  final bool powerButtonFlipsBack;
+
+  // Firmware / compatibility
+  final bool
+  isLegacyV4Firmware; // V4 firmware uses scale=1 for pistrt/piprd instead of 1000
+  final String
+  firmwareVersion; // Full uname string from device (e.g. "meCoffee V5.3.1")
+
+  // Automation
+  final int maxShotTime; // shtmx – stops shot after N seconds (0 = disabled)
+  final bool continuousMode; // tmpcntns – keep heating without shot trigger
+
+  MachineState({
+    this.temperature = 0.0,
+    this.targetTemperature = 101.0,
+    this.isHeating = false,
+    this.isBrewing = false,
+    this.shotTimer = 0,
+    this.connectionStatus = 'Disconnected',
+    this.commandError,
+    this.temperatureHistory = const [],
+    this.temperatureSamples = const [],
+    this.diagnosticLog = const [],
+    this.lastTelemetryAt,
+    this.telemetryStale = true,
+    this.transportName = '',
+    this.firmwareUpdating = false,
+    this.firmwareProgress = 0,
+    this.firmwareUpdateStatus = '',
+    this.sensor2Temperature = 0.0,
+    this.sensor2TemperatureHistory = const [],
+    this.preinfusionTime = 3.0,
+    this.preinfusionPower = 100,
+    this.brewTemperature = 101.0,
+    this.steamTemperature = 125.0,
+    this.pidP = 20.0,
+    this.pidI = 0.3,
+    this.pidD = 128.0,
+    this.pidIWindDownMin = 0.0,
+    this.pidIWindDownMax = 20.0,
+    this.pidPollingInterval = 1000,
+    this.shotCounter = 0,
+    this.grinderCounter = 0,
+    this.pressureStart = 100,
+    this.pressureEnd = 100,
+    this.pressurePeriod = 25,
+    this.heatingPower = 0.0,
+    this.valveClosedWhilePaused = false,
+    this.proActivePercentage = 33,
+    this.temperatureOffset = 0.0,
+    this.autoShutoffMinutes = 60,
+    this.wakeupEnabled = false,
+    this.wakeupTime = "07:00",
+    this.shutdownEnabled = false,
+    this.shutdownTime = "22:00",
+    this.preinfusionEnabled = true,
+    this.preinfusionPauseTime = 3.0,
+    this.output0 = 112,
+    this.output1 = 98,
+    this.output2 = 118,
+    this.installedAsTimer = false,
+    this.powerButtonFlipsBack = false,
+    this.isLegacyV4Firmware = false,
+    this.firmwareVersion = '',
+    this.maxShotTime = 60,
+    this.continuousMode = false,
+  });
+
+  MachineState copyWith({
+    double? temperature,
+    double? targetTemperature,
+    bool? isHeating,
+    bool? isBrewing,
+    int? shotTimer,
+    String? connectionStatus,
+    String? commandError,
+    bool clearCommandError = false,
+    List<double>? temperatureHistory,
+    List<TemperatureSample>? temperatureSamples,
+    List<DiagnosticEntry>? diagnosticLog,
+    DateTime? lastTelemetryAt,
+    bool clearLastTelemetry = false,
+    bool? telemetryStale,
+    String? transportName,
+    bool? firmwareUpdating,
+    double? firmwareProgress,
+    String? firmwareUpdateStatus,
+    double? sensor2Temperature,
+    List<double>? sensor2TemperatureHistory,
+    double? preinfusionTime,
+    int? preinfusionPower,
+    double? brewTemperature,
+    double? steamTemperature,
+    double? pidP,
+    double? pidI,
+    double? pidD,
+    double? pidIWindDownMin,
+    double? pidIWindDownMax,
+    int? pidPollingInterval,
+    int? shotCounter,
+    int? grinderCounter,
+    int? pressureStart,
+    int? pressureEnd,
+    int? pressurePeriod,
+    double? heatingPower,
+    bool? valveClosedWhilePaused,
+    int? proActivePercentage,
+    double? temperatureOffset,
+    int? autoShutoffMinutes,
+    bool? wakeupEnabled,
+    String? wakeupTime,
+    bool? shutdownEnabled,
+    String? shutdownTime,
+    bool? preinfusionEnabled,
+    double? preinfusionPauseTime,
+    int? output0,
+    int? output1,
+    int? output2,
+    bool? installedAsTimer,
+    bool? powerButtonFlipsBack,
+    bool? isLegacyV4Firmware,
+    String? firmwareVersion,
+    int? maxShotTime,
+    bool? continuousMode,
+  }) {
+    return MachineState(
+      temperature: temperature ?? this.temperature,
+      targetTemperature: targetTemperature ?? this.targetTemperature,
+      isHeating: isHeating ?? this.isHeating,
+      isBrewing: isBrewing ?? this.isBrewing,
+      shotTimer: shotTimer ?? this.shotTimer,
+      connectionStatus: connectionStatus ?? this.connectionStatus,
+      commandError: clearCommandError
+          ? null
+          : commandError ?? this.commandError,
+      temperatureHistory: temperatureHistory ?? this.temperatureHistory,
+      temperatureSamples: temperatureSamples ?? this.temperatureSamples,
+      diagnosticLog: diagnosticLog ?? this.diagnosticLog,
+      lastTelemetryAt: clearLastTelemetry
+          ? null
+          : lastTelemetryAt ?? this.lastTelemetryAt,
+      telemetryStale: telemetryStale ?? this.telemetryStale,
+      transportName: transportName ?? this.transportName,
+      firmwareUpdating: firmwareUpdating ?? this.firmwareUpdating,
+      firmwareProgress: firmwareProgress ?? this.firmwareProgress,
+      firmwareUpdateStatus: firmwareUpdateStatus ?? this.firmwareUpdateStatus,
+      sensor2Temperature: sensor2Temperature ?? this.sensor2Temperature,
+      sensor2TemperatureHistory:
+          sensor2TemperatureHistory ?? this.sensor2TemperatureHistory,
+      preinfusionTime: preinfusionTime ?? this.preinfusionTime,
+      preinfusionPower: preinfusionPower ?? this.preinfusionPower,
+      brewTemperature: brewTemperature ?? this.brewTemperature,
+      steamTemperature: steamTemperature ?? this.steamTemperature,
+      pidP: pidP ?? this.pidP,
+      pidI: pidI ?? this.pidI,
+      pidD: pidD ?? this.pidD,
+      pidIWindDownMin: pidIWindDownMin ?? this.pidIWindDownMin,
+      pidIWindDownMax: pidIWindDownMax ?? this.pidIWindDownMax,
+      pidPollingInterval: pidPollingInterval ?? this.pidPollingInterval,
+      shotCounter: shotCounter ?? this.shotCounter,
+      grinderCounter: grinderCounter ?? this.grinderCounter,
+      pressureStart: pressureStart ?? this.pressureStart,
+      pressureEnd: pressureEnd ?? this.pressureEnd,
+      pressurePeriod: pressurePeriod ?? this.pressurePeriod,
+      heatingPower: heatingPower ?? this.heatingPower,
+      valveClosedWhilePaused:
+          valveClosedWhilePaused ?? this.valveClosedWhilePaused,
+      proActivePercentage: proActivePercentage ?? this.proActivePercentage,
+      temperatureOffset: temperatureOffset ?? this.temperatureOffset,
+      autoShutoffMinutes: autoShutoffMinutes ?? this.autoShutoffMinutes,
+      wakeupEnabled: wakeupEnabled ?? this.wakeupEnabled,
+      wakeupTime: wakeupTime ?? this.wakeupTime,
+      shutdownEnabled: shutdownEnabled ?? this.shutdownEnabled,
+      shutdownTime: shutdownTime ?? this.shutdownTime,
+      preinfusionEnabled: preinfusionEnabled ?? this.preinfusionEnabled,
+      preinfusionPauseTime: preinfusionPauseTime ?? this.preinfusionPauseTime,
+      output0: output0 ?? this.output0,
+      output1: output1 ?? this.output1,
+      output2: output2 ?? this.output2,
+      installedAsTimer: installedAsTimer ?? this.installedAsTimer,
+      powerButtonFlipsBack: powerButtonFlipsBack ?? this.powerButtonFlipsBack,
+      isLegacyV4Firmware: isLegacyV4Firmware ?? this.isLegacyV4Firmware,
+      firmwareVersion: firmwareVersion ?? this.firmwareVersion,
+      maxShotTime: maxShotTime ?? this.maxShotTime,
+      continuousMode: continuousMode ?? this.continuousMode,
+    );
+  }
+}

+ 14 - 0
lib/models/temperature_sample.dart

@@ -0,0 +1,14 @@
+/// A timestamped reading with the setpoint active when it was received.
+class TemperatureSample {
+  final DateTime timestamp;
+  final double boiler;
+  final double target;
+  final double? sensor2;
+
+  const TemperatureSample({
+    required this.timestamp,
+    required this.boiler,
+    required this.target,
+    this.sensor2,
+  });
+}

+ 98 - 0
lib/screens/connection_screen.dart

@@ -0,0 +1,98 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+
+import '../services/bluetooth_service.dart';
+import '../services/classic_bluetooth_transport.dart';
+
+class ConnectionScreen extends ConsumerStatefulWidget {
+  const ConnectionScreen({super.key});
+
+  @override
+  ConsumerState<ConnectionScreen> createState() => _ConnectionScreenState();
+}
+
+class _ConnectionScreenState extends ConsumerState<ConnectionScreen> {
+  late Future<List<ClassicBluetoothDevice>> _devices;
+
+  @override
+  void initState() {
+    super.initState();
+    _devices = ref.read(bluetoothServiceProvider.notifier).listClassicDevices();
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    final service = ref.read(bluetoothServiceProvider.notifier);
+    final state = ref.watch(bluetoothServiceProvider);
+    final busy =
+        state.connectionStatus == 'Connecting...' ||
+        state.connectionStatus == 'Connected' ||
+        state.firmwareUpdating;
+    return Scaffold(
+      appBar: AppBar(title: const Text('Connect to meCoffee')),
+      body: ListView(
+        padding: const EdgeInsets.all(16),
+        children: [
+          ListTile(
+            leading: const Icon(Icons.bluetooth_searching),
+            title: const Text('Scan for Bluetooth LE'),
+            subtitle: const Text('HM-10 / FFE0 controllers'),
+            enabled: !busy,
+            onTap: () {
+              service.startScan();
+              Navigator.of(context).pop();
+            },
+          ),
+          const Divider(),
+          const Text(
+            'Bluetooth Classic / SPP (Android)\n'
+            'Pair your controller in Android Bluetooth settings first, then '
+            'select it below. Select only a meCoffee controller.',
+          ),
+          TextButton.icon(
+            icon: const Icon(Icons.refresh),
+            label: const Text('Refresh paired devices'),
+            onPressed: busy
+                ? null
+                : () {
+                    setState(() {
+                      _devices = service.listClassicDevices();
+                    });
+                  },
+          ),
+          FutureBuilder<List<ClassicBluetoothDevice>>(
+            future: _devices,
+            builder: (context, snapshot) {
+              if (snapshot.hasError) {
+                return Text('Cannot list paired devices: ${snapshot.error}');
+              }
+              if (!snapshot.hasData) {
+                return const Center(child: CircularProgressIndicator());
+              }
+              if (snapshot.data!.isEmpty) {
+                return const Text('No paired devices found.');
+              }
+              return Column(
+                children: [
+                  for (final device in snapshot.data!)
+                    ListTile(
+                      leading: const Icon(Icons.bluetooth),
+                      title: Text(
+                        device.name.isEmpty ? device.address : device.name,
+                      ),
+                      subtitle: Text(device.address),
+                      enabled: !busy,
+                      onTap: () {
+                        service.connectToClassicDevice(device);
+                        Navigator.of(context).pop();
+                      },
+                    ),
+                ],
+              );
+            },
+          ),
+        ],
+      ),
+    );
+  }
+}

+ 97 - 0
lib/screens/diagnostics_screen.dart

@@ -0,0 +1,97 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+
+import '../services/bluetooth_service.dart';
+
+class DiagnosticsScreen extends ConsumerWidget {
+  const DiagnosticsScreen({super.key});
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final state = ref.watch(bluetoothServiceProvider);
+    final service = ref.read(bluetoothServiceProvider.notifier);
+    return Scaffold(
+      appBar: AppBar(
+        title: const Text('Diagnostics'),
+        actions: [
+          IconButton(
+            tooltip: 'Copy log',
+            icon: const Icon(Icons.copy),
+            onPressed: state.diagnosticLog.isEmpty
+                ? null
+                : () async {
+                    await Clipboard.setData(
+                      ClipboardData(text: service.exportDiagnosticLog()),
+                    );
+                    if (context.mounted) {
+                      ScaffoldMessenger.of(context).showSnackBar(
+                        const SnackBar(content: Text('Diagnostic log copied')),
+                      );
+                    }
+                  },
+          ),
+          IconButton(
+            tooltip: 'Clear log',
+            icon: const Icon(Icons.delete_outline),
+            onPressed: state.diagnosticLog.isEmpty
+                ? null
+                : service.clearDiagnosticLog,
+          ),
+        ],
+      ),
+      body: Column(
+        crossAxisAlignment: CrossAxisAlignment.stretch,
+        children: [
+          Padding(
+            padding: const EdgeInsets.all(16),
+            child: Text(
+              '${state.connectionStatus}'
+              '${state.transportName.isEmpty ? '' : ' - ${state.transportName}'}'
+              '\nFirmware: ${state.firmwareVersion.isEmpty ? 'Unknown' : state.firmwareVersion}'
+              '\nTemperature data: ${state.telemetryStale ? 'stale / unavailable' : 'live'}'
+              '\nLast sample: ${state.lastTelemetryAt?.toLocal().toIso8601String() ?? 'none'}'
+              '\nLast 1000 RX/TX/events, held in memory only. Nothing is uploaded.',
+            ),
+          ),
+          if (state.commandError != null)
+            Padding(
+              padding: const EdgeInsets.symmetric(horizontal: 16),
+              child: Text(
+                state.commandError!,
+                style: const TextStyle(color: Colors.redAccent),
+              ),
+            ),
+          const Divider(),
+          Expanded(
+            child: state.diagnosticLog.isEmpty
+                ? const Center(child: Text('No diagnostic entries yet'))
+                : ListView.builder(
+                    reverse: true,
+                    itemCount: state.diagnosticLog.length,
+                    itemBuilder: (context, index) {
+                      final entry =
+                          state.diagnosticLog[state.diagnosticLog.length -
+                              index -
+                              1];
+                      return Padding(
+                        padding: const EdgeInsets.symmetric(
+                          horizontal: 16,
+                          vertical: 4,
+                        ),
+                        child: SelectableText(
+                          entry.text,
+                          style: const TextStyle(
+                            fontFamily: 'monospace',
+                            fontSize: 12,
+                          ),
+                        ),
+                      );
+                    },
+                  ),
+          ),
+        ],
+      ),
+    );
+  }
+}

+ 174 - 0
lib/screens/hardware_settings_screen.dart

@@ -0,0 +1,174 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/bluetooth_service.dart';
+
+class HardwareSettingsScreen extends ConsumerWidget {
+  const HardwareSettingsScreen({super.key});
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+    final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
+
+    return Scaffold(
+      appBar: AppBar(title: const Text('Hardware Configuration')),
+      body: ListView(
+        padding: const EdgeInsets.all(16),
+        children: [
+          if (machineState.isLegacyV4Firmware)
+            const Padding(
+              padding: EdgeInsets.all(16),
+              child: Text(
+                'V4 firmware does not support configurable output mapping or a momentary power button.',
+              ),
+            ),
+          if (!machineState.isLegacyV4Firmware) ...[
+            _SectionHeader(title: 'Output Mapping'),
+            _OutputTile(
+              label: 'Output 1',
+              value: machineState.output0,
+              onChanged: (v) =>
+                  bluetoothService.updateHardwareSettings(output0: v!),
+            ),
+          ],
+          _OutputTile(
+            label: 'Output 2',
+            value: machineState.output1,
+            onChanged: machineState.isLegacyV4Firmware
+                ? null
+                : (v) => bluetoothService.updateHardwareSettings(output1: v!),
+          ),
+          _OutputTile(
+            label: 'Output 3',
+            value: machineState.output2,
+            onChanged: machineState.isLegacyV4Firmware
+                ? null
+                : (v) => bluetoothService.updateHardwareSettings(output2: v!),
+          ),
+          const Divider(),
+          _SectionHeader(title: 'Machine Quirks'),
+          SwitchListTile(
+            title: const Text('Installed as Timer'),
+            subtitle: const Text('Prevent warmup after power outage'),
+            value: machineState.installedAsTimer,
+            onChanged: bluetoothService.updateInstalledAsTimer,
+          ),
+          if (!machineState.isLegacyV4Firmware)
+            SwitchListTile(
+              title: const Text('Power Button Flips Back'),
+              subtitle: const Text('Enable for Silvia V5 or similar'),
+              value: machineState.powerButtonFlipsBack,
+              onChanged: (v) =>
+                  bluetoothService.updateHardwareSettings(flips: v),
+            ),
+          const Divider(),
+          _SectionHeader(title: 'Firmware'),
+          ListTile(
+            leading: const Icon(Icons.memory_outlined),
+            title: const Text('Firmware Version'),
+            subtitle: Text(
+              machineState.firmwareVersion.isEmpty
+                  ? 'Unknown (connect to device)'
+                  : machineState.firmwareVersion,
+            ),
+          ),
+          ListTile(
+            leading: const Icon(Icons.system_update),
+            title: const Text('Install bundled V10 firmware'),
+            subtitle: const Text(
+              'Experimental STK500 update with read-back verification. '
+              'Requires Bluetooth Classic, live telemetry, heating off, no shot, and a boiler '
+              'at or below 50 C. BLE flashing is not available.',
+            ),
+            enabled: bluetoothService.canUpdateFirmware,
+            onTap: () async {
+              final confirmed = await showDialog<bool>(
+                context: context,
+                builder: (context) => AlertDialog(
+                  title: const Text('Update controller firmware?'),
+                  content: const Text(
+                    'This replaces the controller firmware with the bundled V10 '
+                    'image. Only ATmega328P controllers with a compatible STK500 '
+                    'bootloader are supported. Settings may change after updating.\n\n'
+                    'Do not operate the machine, close the app, or interrupt '
+                    'power/Bluetooth. Failure may require manual bootloader '
+                    'recovery. Continue only if you can recover your controller.',
+                  ),
+                  actions: [
+                    TextButton(
+                      onPressed: () => Navigator.pop(context, false),
+                      child: const Text('Cancel'),
+                    ),
+                    FilledButton(
+                      onPressed: () => Navigator.pop(context, true),
+                      child: const Text('I understand - update'),
+                    ),
+                  ],
+                ),
+              );
+              if (confirmed == true) await bluetoothService.updateFirmware();
+            },
+          ),
+          if (machineState.firmwareUpdateStatus.isNotEmpty)
+            Padding(
+              padding: const EdgeInsets.all(16),
+              child: Text(machineState.firmwareUpdateStatus),
+            ),
+          if (machineState.firmwareUpdating)
+            LinearProgressIndicator(value: machineState.firmwareProgress),
+        ],
+      ),
+    );
+  }
+}
+
+class _OutputTile extends StatelessWidget {
+  final String label;
+  final int value;
+  final ValueChanged<int?>? onChanged;
+
+  const _OutputTile({
+    required this.label,
+    required this.value,
+    required this.onChanged,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return ListTile(
+      title: Text(label),
+      trailing: DropdownButton<int>(
+        value: value,
+        items: const [
+          DropdownMenuItem(value: 112, child: Text('Pump')),
+          DropdownMenuItem(value: 98, child: Text('Boiler')),
+          DropdownMenuItem(value: 118, child: Text('Valve')),
+          DropdownMenuItem(value: 105, child: Text('Indicator')),
+          DropdownMenuItem(value: 103, child: Text('Grinder')),
+          DropdownMenuItem(value: 110, child: Text('None')),
+        ],
+        onChanged: onChanged,
+      ),
+    );
+  }
+}
+
+class _SectionHeader extends StatelessWidget {
+  final String title;
+  const _SectionHeader({required this.title});
+
+  @override
+  Widget build(BuildContext context) {
+    return Padding(
+      padding: const EdgeInsets.symmetric(vertical: 8.0),
+      child: Text(
+        title.toUpperCase(),
+        style: TextStyle(
+          color: Theme.of(context).colorScheme.primary,
+          fontWeight: FontWeight.bold,
+          fontSize: 12,
+        ),
+      ),
+    );
+  }
+}

+ 157 - 0
lib/screens/pid_settings_screen.dart

@@ -0,0 +1,157 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/bluetooth_service.dart';
+
+class PIDSettingsScreen extends ConsumerWidget {
+  const PIDSettingsScreen({super.key});
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+    final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
+    final isLegacyV4 = machineState.isLegacyV4Firmware;
+
+    return Scaffold(
+      appBar: AppBar(title: const Text('PID Tuning')),
+      body: ListView(
+        padding: const EdgeInsets.all(16),
+        children: [
+          Text(
+            isLegacyV4
+                ? 'V4 defaults: P 25, I 3, D 128, I limit 3750.'
+                : 'Defaults: P 20, I 0.30, D 128, I limit 20%.',
+          ),
+          _PIDSlider(
+            label: 'Proportional (P)',
+            value: machineState.pidP,
+            min: 0,
+            max: 100,
+            onChanged: (v) => bluetoothService.updatePIDSettings(p: v),
+          ),
+          _PIDSlider(
+            label: 'Integral (I)',
+            value: machineState.pidI,
+            min: 0,
+            max: isLegacyV4 ? 10 : 1,
+            step: isLegacyV4 ? 1 : 0.01,
+            decimalPlaces: isLegacyV4 ? 0 : 2,
+            onChanged: (v) => bluetoothService.updatePIDSettings(i: v),
+          ),
+          _PIDSlider(
+            label: 'Derivative (D)',
+            value: machineState.pidD,
+            min: 0,
+            max: 256,
+            onChanged: (v) => bluetoothService.updatePIDSettings(d: v),
+          ),
+          const Divider(),
+          _PIDSlider(
+            label: 'Pro-Active Percentage',
+            value: machineState.proActivePercentage.toDouble(),
+            min: 0,
+            max: 100,
+            onChanged: (v) => bluetoothService.updateProActive(v.toInt()),
+          ),
+          if (!isLegacyV4)
+            _PIDSlider(
+              label: 'Temperature Offset (°C)',
+              value: machineState.temperatureOffset,
+              min: -10,
+              max: 10,
+              step: 0.1,
+              decimalPlaces: 1,
+              onChanged: (v) => bluetoothService.updateOffset(v),
+            ),
+          const Divider(),
+          if (!isLegacyV4)
+            _PIDSlider(
+              label: 'I-Wind-down Min (%)',
+              value: machineState.pidIWindDownMin,
+              min: 0,
+              max: 100,
+              onChanged: (v) => bluetoothService.updatePIDLimitSettings(min: v),
+            ),
+          _PIDSlider(
+            label: isLegacyV4 ? 'I-Wind-down Max (raw)' : 'I-Wind-down Max (%)',
+            value: machineState.pidIWindDownMax,
+            min: 0,
+            max: isLegacyV4 ? 6000 : 100,
+            step: isLegacyV4 ? 250 : 1,
+            onChanged: (v) => bluetoothService.updatePIDLimitSettings(max: v),
+          ),
+          ListTile(
+            title: const Text('Polling Interval (ms)'),
+            subtitle: Text('${machineState.pidPollingInterval} ms'),
+            trailing: SizedBox(
+              width: 200,
+              child: Slider(
+                value: machineState.pidPollingInterval.toDouble().clamp(
+                  1000.0,
+                  10000.0,
+                ),
+                min: 1000,
+                max: 10000,
+                divisions: 18, // 500 ms steps
+                label: '${machineState.pidPollingInterval} ms',
+                onChanged: (v) {
+                  bluetoothService.updatePIDLimitSettings(interval: v.round());
+                },
+              ),
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _PIDSlider extends StatelessWidget {
+  final String label;
+  final double value;
+  final double min;
+  final double max;
+  final double step;
+  final int decimalPlaces;
+  final ValueChanged<double> onChanged;
+
+  const _PIDSlider({
+    required this.label,
+    required this.value,
+    required this.min,
+    required this.max,
+    this.step = 1,
+    this.decimalPlaces = 0,
+    required this.onChanged,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    final rounded = value.toStringAsFixed(decimalPlaces);
+    final reading = double.tryParse(rounded) == value
+        ? rounded
+        : value.toString();
+    return Column(
+      crossAxisAlignment: CrossAxisAlignment.start,
+      children: [
+        Padding(
+          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+          child: Text('$label: $reading'),
+        ),
+        Slider(
+          value: value.clamp(min, max),
+          min: min,
+          max: max,
+          divisions: ((max - min) / step).round(),
+          label: reading,
+          onChanged: (v) => onChanged(
+            double.parse(
+              (min + ((v - min) / step).round() * step).toStringAsFixed(
+                decimalPlaces,
+              ),
+            ),
+          ),
+        ),
+      ],
+    );
+  }
+}

+ 93 - 0
lib/screens/pressure_settings_screen.dart

@@ -0,0 +1,93 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/bluetooth_service.dart';
+
+class PressureSettingsScreen extends ConsumerWidget {
+  const PressureSettingsScreen({super.key});
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+    final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
+
+    return Scaffold(
+      appBar: AppBar(title: const Text('Pressure Profiling')),
+      body: ListView(
+        padding: const EdgeInsets.all(16),
+        children: [
+          _PressureSlider(
+            label: 'Start Pressure (%)',
+            value: machineState.pressureStart.toDouble(),
+            min: 0,
+            max: 100,
+            onChanged: (v) =>
+                bluetoothService.updatePressureSettings(start: v.toInt()),
+          ),
+          _PressureSlider(
+            label: 'End Pressure (%)',
+            value: machineState.pressureEnd.toDouble(),
+            min: 0,
+            max: 100,
+            onChanged: (v) =>
+                bluetoothService.updatePressureSettings(end: v.toInt()),
+          ),
+          _PressureSlider(
+            label: 'Period (s)',
+            value: machineState.pressurePeriod.toDouble(),
+            min: 0,
+            max: 60,
+            onChanged: (v) =>
+                bluetoothService.updatePressureSettings(period: v.toInt()),
+          ),
+          const Divider(),
+          const Padding(
+            padding: EdgeInsets.all(16.0),
+            child: Text(
+              'The pump will linearly transition from the start pressure to the end pressure over the specified period.',
+              style: TextStyle(color: Colors.grey, fontSize: 14),
+              textAlign: TextAlign.center,
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _PressureSlider extends StatelessWidget {
+  final String label;
+  final double value;
+  final double min;
+  final double max;
+  final ValueChanged<double> onChanged;
+
+  const _PressureSlider({
+    required this.label,
+    required this.value,
+    required this.min,
+    required this.max,
+    required this.onChanged,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return Column(
+      crossAxisAlignment: CrossAxisAlignment.start,
+      children: [
+        Padding(
+          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+          child: Text(
+            '$label: ${value.toInt()}${label.contains('%') ? '%' : 's'}',
+          ),
+        ),
+        Slider(
+          value: value.clamp(min, max),
+          min: min,
+          max: max,
+          divisions: (max - min).toInt(),
+          onChanged: onChanged,
+        ),
+      ],
+    );
+  }
+}

+ 307 - 0
lib/screens/settings_screen.dart

@@ -0,0 +1,307 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/bluetooth_service.dart';
+import 'pid_settings_screen.dart';
+import 'statistics_screen.dart';
+import 'pressure_settings_screen.dart';
+import 'timer_settings_screen.dart';
+import 'hardware_settings_screen.dart';
+
+class SettingsScreen extends ConsumerWidget {
+  const SettingsScreen({super.key});
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+    final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
+
+    return Scaffold(
+      appBar: AppBar(title: const Text('Machine Settings')),
+      body: ListView(
+        padding: const EdgeInsets.all(16.0),
+        children: [
+          _SectionHeader(title: 'Extraction'),
+          ListTile(
+            title: const Text('Brew Temperature'),
+            subtitle: Text(
+              '${machineState.brewTemperature.toStringAsFixed(1)}°C',
+            ),
+            trailing: SizedBox(
+              width: 200,
+              child: _DraftSlider(
+                value: machineState.brewTemperature,
+                min: 50,
+                max: 125,
+                divisions: 750,
+                format: (val) => '${val.toStringAsFixed(1)}°C',
+                onSubmitted: (val) =>
+                    bluetoothService.updateBrewTemperature(val),
+              ),
+            ),
+          ),
+          ListTile(
+            title: const Text('PID Tuning'),
+            subtitle: const Text('Advanced temperature control parameters'),
+            trailing: const Icon(Icons.chevron_right),
+            onTap: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(
+                  builder: (context) => const PIDSettingsScreen(),
+                ),
+              );
+            },
+          ),
+          SwitchListTile(
+            title: const Text('Continuous Mode'),
+            subtitle: const Text(
+              'Keep boiler hot without waiting for a shot trigger',
+            ),
+            value: machineState.continuousMode,
+            onChanged: (val) => bluetoothService.updateContinuousMode(val),
+          ),
+          const Divider(),
+          _SectionHeader(title: 'Steam'),
+          ListTile(
+            title: const Text('Steam Temperature'),
+            subtitle: Text(
+              '${machineState.steamTemperature.toStringAsFixed(1)}°C',
+            ),
+            trailing: SizedBox(
+              width: 200,
+              child: _DraftSlider(
+                value: machineState.steamTemperature,
+                min: 110,
+                max: 150,
+                divisions: 80,
+                format: (val) => '${val.toStringAsFixed(1)}°C',
+                onSubmitted: (val) =>
+                    bluetoothService.updateSteamTemperature(val),
+              ),
+            ),
+          ),
+          _SectionHeader(title: 'Pressure'),
+          ListTile(
+            title: const Text('Pressure Profiling'),
+            subtitle: const Text('Start pressure, end pressure and period'),
+            trailing: const Icon(Icons.chevron_right),
+            onTap: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(
+                  builder: (context) => const PressureSettingsScreen(),
+                ),
+              );
+            },
+          ),
+          const Divider(),
+          _SectionHeader(title: 'Pre-infusion'),
+          SwitchListTile(
+            title: const Text('Enable Pre-infusion'),
+            value: machineState.preinfusionEnabled,
+            onChanged: (val) =>
+                bluetoothService.updatePreinfusionSettings(enabled: val),
+          ),
+          ListTile(
+            title: const Text('Pump Time'),
+            subtitle: Text(
+              '${machineState.preinfusionTime.toStringAsFixed(1)}s',
+            ),
+            enabled: machineState.preinfusionEnabled,
+            trailing: SizedBox(
+              width: 200,
+              child: _DraftSlider(
+                value: machineState.preinfusionTime,
+                min: 0,
+                max: 10,
+                divisions: machineState.isLegacyV4Firmware ? 10 : 100,
+                format: (val) =>
+                    '${val.toStringAsFixed(machineState.isLegacyV4Firmware ? 0 : 1)}s',
+                onSubmitted: machineState.preinfusionEnabled
+                    ? (val) =>
+                          bluetoothService.updatePreinfusionSettings(time: val)
+                    : null,
+              ),
+            ),
+          ),
+          ListTile(
+            title: const Text('Pause Time'),
+            subtitle: Text(
+              '${machineState.preinfusionPauseTime.toStringAsFixed(1)}s',
+            ),
+            enabled: machineState.preinfusionEnabled,
+            trailing: SizedBox(
+              width: 200,
+              child: _DraftSlider(
+                value: machineState.preinfusionPauseTime,
+                min: 0,
+                max: 10,
+                divisions: machineState.isLegacyV4Firmware ? 10 : 100,
+                format: (val) =>
+                    '${val.toStringAsFixed(machineState.isLegacyV4Firmware ? 0 : 1)}s',
+                onSubmitted: machineState.preinfusionEnabled
+                    ? (val) =>
+                          bluetoothService.updatePreinfusionSettings(pause: val)
+                    : null,
+              ),
+            ),
+          ),
+          SwitchListTile(
+            title: const Text('Close Valve While Paused'),
+            subtitle: const Text(
+              'Prevents pressure venting during pre-infusion',
+            ),
+            value: machineState.valveClosedWhilePaused,
+            onChanged: machineState.preinfusionEnabled
+                ? (val) => bluetoothService.updatePreinfusionSettings(
+                    closeValve: val,
+                  )
+                : null,
+          ),
+          if (!machineState.isLegacyV4Firmware)
+            ListTile(
+              title: const Text('Max Shot Time'),
+              subtitle: Text(
+                machineState.maxShotTime == 0
+                    ? 'Disabled'
+                    : '${machineState.maxShotTime} s',
+              ),
+              trailing: SizedBox(
+                width: 200,
+                child: _DraftSlider(
+                  value: machineState.maxShotTime.toDouble(),
+                  min: 0,
+                  max: 120,
+                  divisions: 120,
+                  format: (val) => val == 0 ? 'Off' : '${val.round()} s',
+                  onSubmitted: (val) =>
+                      bluetoothService.updateMaxShotTime(val.round()),
+                ),
+              ),
+            ),
+          const Divider(),
+          _SectionHeader(title: 'Automation'),
+          ListTile(
+            title: const Text('Timers & Scheduling'),
+            subtitle: const Text('Wakeup, shutdown, and auto-off'),
+            trailing: const Icon(Icons.chevron_right),
+            onTap: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(
+                  builder: (context) => const TimerSettingsScreen(),
+                ),
+              );
+            },
+          ),
+          const Divider(),
+          _SectionHeader(title: 'Machine Information'),
+          ListTile(
+            title: const Text('Hardware Configuration'),
+            subtitle: const Text('Output mapping and machine quirks'),
+            trailing: const Icon(Icons.chevron_right),
+            onTap: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(
+                  builder: (context) => const HardwareSettingsScreen(),
+                ),
+              );
+            },
+          ),
+          ListTile(
+            title: const Text('Usage Statistics'),
+            subtitle: const Text('Shot counts and grinder usage'),
+            trailing: const Icon(Icons.chevron_right),
+            onTap: () {
+              Navigator.of(context).push(
+                MaterialPageRoute(
+                  builder: (context) => const StatisticsScreen(),
+                ),
+              );
+            },
+          ),
+          ListTile(
+            title: const Text('Connection Status'),
+            subtitle: Text(machineState.connectionStatus),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _DraftSlider extends StatefulWidget {
+  final double value;
+  final double min;
+  final double max;
+  final int divisions;
+  final String Function(double) format;
+  final ValueChanged<double>? onSubmitted;
+
+  const _DraftSlider({
+    required this.value,
+    required this.min,
+    required this.max,
+    required this.divisions,
+    required this.format,
+    required this.onSubmitted,
+  });
+
+  @override
+  State<_DraftSlider> createState() => _DraftSliderState();
+}
+
+class _DraftSliderState extends State<_DraftSlider> {
+  double? _draft;
+
+  @override
+  void didUpdateWidget(covariant _DraftSlider oldWidget) {
+    super.didUpdateWidget(oldWidget);
+    if (oldWidget.value != widget.value ||
+        oldWidget.divisions != widget.divisions ||
+        widget.onSubmitted == null) {
+      _draft = null;
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    final value = (_draft ?? widget.value).clamp(widget.min, widget.max);
+    return Slider(
+      value: value,
+      min: widget.min,
+      max: widget.max,
+      divisions: widget.divisions,
+      label: widget.format(value),
+      onChanged: widget.onSubmitted == null
+          ? null
+          : (value) => setState(() => _draft = value),
+      onChangeEnd: widget.onSubmitted == null
+          ? null
+          : (value) {
+              setState(() => _draft = null);
+              final step = (widget.max - widget.min) / widget.divisions;
+              final rounded =
+                  widget.min + ((value - widget.min) / step).round() * step;
+              widget.onSubmitted!(double.parse(rounded.toStringAsFixed(3)));
+            },
+    );
+  }
+}
+
+class _SectionHeader extends StatelessWidget {
+  final String title;
+  const _SectionHeader({required this.title});
+
+  @override
+  Widget build(BuildContext context) {
+    return Padding(
+      padding: const EdgeInsets.symmetric(vertical: 8.0),
+      child: Text(
+        title.toUpperCase(),
+        style: TextStyle(
+          color: Theme.of(context).colorScheme.primary,
+          fontWeight: FontWeight.bold,
+          fontSize: 12,
+        ),
+      ),
+    );
+  }
+}

+ 67 - 0
lib/screens/statistics_screen.dart

@@ -0,0 +1,67 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/bluetooth_service.dart';
+
+class StatisticsScreen extends ConsumerWidget {
+  const StatisticsScreen({super.key});
+
+  @override
+  Widget build(BuildContext context, WidgetRef ref) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+
+    return Scaffold(
+      appBar: AppBar(title: const Text('Statistics')),
+      body: ListView(
+        padding: const EdgeInsets.all(16),
+        children: [
+          _StatTile(
+            label: 'Total Shots',
+            value: '${machineState.shotCounter}',
+            icon: Icons.coffee,
+          ),
+          _StatTile(
+            label: 'Grinder Cycles',
+            value: '${machineState.grinderCounter}',
+            icon: Icons.settings_input_component,
+          ),
+          const Divider(),
+          const Padding(
+            padding: EdgeInsets.all(16.0),
+            child: Text(
+              'Shot counter is tracked on this device. Grinder counter is reported directly by the meCoffee hardware.',
+              style: TextStyle(color: Colors.grey, fontSize: 12),
+              textAlign: TextAlign.center,
+            ),
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _StatTile extends StatelessWidget {
+  final String label;
+  final String value;
+  final IconData icon;
+
+  const _StatTile({
+    required this.label,
+    required this.value,
+    required this.icon,
+  });
+
+  @override
+  Widget build(BuildContext context) {
+    return ListTile(
+      leading: Icon(icon, color: Colors.orangeAccent),
+      title: Text(label),
+      trailing: Text(
+        value,
+        style: const TextStyle(
+          fontSize: 20,
+          fontWeight: FontWeight.bold,
+        ),
+      ),
+    );
+  }
+}

+ 131 - 0
lib/screens/timer_settings_screen.dart

@@ -0,0 +1,131 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../services/bluetooth_service.dart';
+
+class TimerSettingsScreen extends ConsumerStatefulWidget {
+  const TimerSettingsScreen({super.key});
+
+  @override
+  ConsumerState<TimerSettingsScreen> createState() =>
+      _TimerSettingsScreenState();
+}
+
+class _TimerSettingsScreenState extends ConsumerState<TimerSettingsScreen> {
+  double? _autoShutoffDraft;
+
+  @override
+  Widget build(BuildContext context) {
+    final machineState = ref.watch(bluetoothServiceProvider);
+    final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
+    ref.listen(
+      bluetoothServiceProvider.select((state) => state.autoShutoffMinutes),
+      (_, _) => setState(() => _autoShutoffDraft = null),
+    );
+
+    return Scaffold(
+      appBar: AppBar(title: const Text('Timers & Automation')),
+      body: ListView(
+        padding: const EdgeInsets.all(16),
+        children: [
+          if (!machineState.isLegacyV4Firmware) ...[
+            _SectionHeader(title: 'Auto-Shutoff'),
+            ListTile(
+              title: const Text('Inactivity Timer'),
+              subtitle: Text('${machineState.autoShutoffMinutes} minutes'),
+              trailing: SizedBox(
+                width: 150,
+                child: Slider(
+                  value:
+                      (_autoShutoffDraft ??
+                              machineState.autoShutoffMinutes.toDouble())
+                          .clamp(0.0, 120.0),
+                  min: 0,
+                  max: 120,
+                  divisions: 120,
+                  label:
+                      '${(_autoShutoffDraft ?? machineState.autoShutoffMinutes).round()} minutes',
+                  onChanged: (v) => setState(() => _autoShutoffDraft = v),
+                  onChangeEnd: (v) {
+                    setState(() => _autoShutoffDraft = null);
+                    bluetoothService.updateAutoShutoff(v.round());
+                  },
+                ),
+              ),
+            ),
+            const Divider(),
+          ],
+          _SectionHeader(title: 'Daily Schedule'),
+          SwitchListTile(
+            title: const Text('Enable Wakeup Timer'),
+            value: machineState.wakeupEnabled,
+            onChanged: (v) => bluetoothService.updateSchedule(wEnabled: v),
+          ),
+          ListTile(
+            title: const Text('Wakeup Time'),
+            subtitle: Text(machineState.wakeupTime),
+            enabled: machineState.wakeupEnabled,
+            onTap: () async {
+              final time = await showTimePicker(
+                context: context,
+                initialTime: TimeOfDay(
+                  hour: int.parse(machineState.wakeupTime.split(':')[0]),
+                  minute: int.parse(machineState.wakeupTime.split(':')[1]),
+                ),
+              );
+              if (time != null) {
+                final formattedTime =
+                    '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
+                bluetoothService.updateSchedule(wTime: formattedTime);
+              }
+            },
+          ),
+          const SizedBox(height: 16),
+          SwitchListTile(
+            title: const Text('Enable Shutdown Timer'),
+            value: machineState.shutdownEnabled,
+            onChanged: (v) => bluetoothService.updateSchedule(sEnabled: v),
+          ),
+          ListTile(
+            title: const Text('Shutdown Time'),
+            subtitle: Text(machineState.shutdownTime),
+            enabled: machineState.shutdownEnabled,
+            onTap: () async {
+              final time = await showTimePicker(
+                context: context,
+                initialTime: TimeOfDay(
+                  hour: int.parse(machineState.shutdownTime.split(':')[0]),
+                  minute: int.parse(machineState.shutdownTime.split(':')[1]),
+                ),
+              );
+              if (time != null) {
+                final formattedTime =
+                    '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
+                bluetoothService.updateSchedule(sTime: formattedTime);
+              }
+            },
+          ),
+        ],
+      ),
+    );
+  }
+}
+
+class _SectionHeader extends StatelessWidget {
+  final String title;
+  const _SectionHeader({required this.title});
+
+  @override
+  Widget build(BuildContext context) {
+    return Padding(
+      padding: const EdgeInsets.symmetric(vertical: 8.0),
+      child: Text(
+        title.toUpperCase(),
+        style: TextStyle(
+          color: Theme.of(context).colorScheme.primary,
+          fontWeight: FontWeight.bold,
+          fontSize: 12,
+        ),
+      ),
+    );
+  }
+}

Разница между файлами не показана из-за своего большого размера
+ 1492 - 0
lib/services/bluetooth_service.dart


+ 250 - 0
lib/services/classic_bluetooth_transport.dart

@@ -0,0 +1,250 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+class ClassicBluetoothDevice {
+  const ClassicBluetoothDevice({required this.address, this.name = ''});
+
+  final String address;
+  final String name;
+}
+
+enum ClassicBluetoothEventType { connected, disconnected, error }
+
+class ClassicBluetoothEvent {
+  const ClassicBluetoothEvent({
+    required this.type,
+    this.address,
+    this.code,
+    this.message,
+    this.explicitDisconnect = false,
+  });
+
+  final ClassicBluetoothEventType type;
+  final String? address;
+  final String? code;
+  final String? message;
+  final bool explicitDisconnect;
+}
+
+/// Android's paired-device RFCOMM transport. Subscribe before calling [connect]
+/// so incoming binary data and connection changes cannot be missed.
+class ClassicBluetoothTransport {
+  ClassicBluetoothTransport();
+
+  final MethodChannel _methodChannel = const MethodChannel('mebarista/classic');
+  final EventChannel _eventChannel = const EventChannel(
+    'mebarista/classic/events',
+  );
+  final _received = StreamController<List<int>>.broadcast();
+  final _events = StreamController<ClassicBluetoothEvent>.broadcast();
+  var _ready = Completer<void>();
+  StreamSubscription<dynamic>? _subscription;
+  Future<void>? _streamRestart;
+  int _streamGeneration = 0;
+  int _connectionGeneration = 0;
+  Object? _streamError;
+  bool _disposed = false;
+  Future<void>? _disposeFuture;
+
+  bool get isSupported =>
+      !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
+
+  Stream<List<int>> get received => _received.stream;
+  Stream<ClassicBluetoothEvent> get events => _events.stream;
+  Stream<ClassicBluetoothEvent> get connectionEvents => events;
+
+  Future<void> _listenNative() async {
+    if (_streamRestart case final restart?) {
+      await restart;
+      return;
+    }
+    if (_streamError != null) {
+      final restart = _restartNativeStream();
+      _streamRestart = restart;
+      try {
+        await restart;
+      } finally {
+        _streamRestart = null;
+      }
+    } else if (_subscription == null) {
+      _subscribeNative();
+    }
+  }
+
+  Future<void> _restartNativeStream() async {
+    _streamGeneration++;
+    await _subscription?.cancel();
+    _checkAvailable();
+    _subscription = null;
+    _streamError = null;
+    _ready = Completer<void>();
+    _subscribeNative();
+  }
+
+  void _subscribeNative() {
+    final generation = ++_streamGeneration;
+    _subscription = _eventChannel.receiveBroadcastStream().listen(
+      (dynamic value) {
+        if (generation == _streamGeneration) _onNativeEvent(value);
+      },
+      onError: (Object error) {
+        if (generation == _streamGeneration) _onNativeError(error);
+      },
+      onDone: () {
+        if (generation == _streamGeneration) {
+          _onNativeError(
+            PlatformException(
+              code: 'event_stream_closed',
+              message: 'Bluetooth event stream closed.',
+            ),
+          );
+        }
+      },
+    );
+  }
+
+  void _onNativeEvent(dynamic value) {
+    if (_disposed || value is! Map) return;
+    final type = value['type'];
+    if (type == 'ready') {
+      if (!_ready.isCompleted) _ready.complete();
+      return;
+    }
+    if (type == 'data') {
+      final bytes = value['bytes'];
+      if (bytes is List) {
+        _received.add(List<int>.unmodifiable(bytes.cast<int>()));
+      }
+      return;
+    }
+    final eventType = switch (type) {
+      'connected' => ClassicBluetoothEventType.connected,
+      'disconnected' => ClassicBluetoothEventType.disconnected,
+      'error' => ClassicBluetoothEventType.error,
+      _ => null,
+    };
+    if (eventType == null) return;
+    _events.add(
+      ClassicBluetoothEvent(
+        type: eventType,
+        address: value['address'] as String?,
+        code: value['code'] as String?,
+        message: value['message'] as String?,
+        explicitDisconnect: value['explicit'] == true,
+      ),
+    );
+  }
+
+  void _onNativeError(Object error) {
+    if (_disposed) return;
+    _streamError = error;
+    // Complete normally, then throw in the waiting operation. This avoids an
+    // unhandled Future error when no connection operation is pending.
+    if (!_ready.isCompleted) _ready.complete();
+    _events.add(
+      ClassicBluetoothEvent(
+        type: ClassicBluetoothEventType.error,
+        code: error is PlatformException ? error.code : 'event_stream_error',
+        message: error is PlatformException
+            ? error.message
+            : 'Bluetooth event stream unavailable.',
+      ),
+    );
+  }
+
+  void _checkAvailable() {
+    if (_disposed) throw StateError('Bluetooth transport has been disposed.');
+    if (!isSupported) {
+      throw PlatformException(
+        code: 'unsupported',
+        message: 'Bluetooth Classic is supported only on Android.',
+      );
+    }
+  }
+
+  Future<T?> _invoke<T>(String method, [Object? arguments]) async {
+    try {
+      return await _methodChannel.invokeMethod<T>(method, arguments);
+    } on MissingPluginException {
+      throw PlatformException(
+        code: 'unsupported',
+        message: 'Android Bluetooth Classic transport is unavailable.',
+      );
+    }
+  }
+
+  Future<List<ClassicBluetoothDevice>> listBondedDevices() async {
+    _checkAvailable();
+    final devices = await _invoke<List<dynamic>>('listBondedDevices');
+    return (devices ?? []).map((dynamic value) {
+      final device = value as Map;
+      return ClassicBluetoothDevice(
+        address: device['address'] as String,
+        name: device['name'] as String? ?? '',
+      );
+    }).toList();
+  }
+
+  Future<void> connect(String address) async {
+    _checkAvailable();
+    final generation = ++_connectionGeneration;
+    await _listenNative();
+    _checkConnectionAttempt(generation);
+    await _ready.future.timeout(
+      const Duration(seconds: 5),
+      onTimeout: () {
+        final error = PlatformException(
+          code: 'event_stream_unavailable',
+          message: 'Android Bluetooth event stream did not become ready.',
+        );
+        _onNativeError(error);
+        throw error;
+      },
+    );
+    _checkConnectionAttempt(generation);
+    if (_streamError case final error?) throw error;
+    await _invoke<void>('connect', {'address': address});
+  }
+
+  void _checkConnectionAttempt(int generation) {
+    _checkAvailable();
+    if (generation != _connectionGeneration) {
+      throw StateError('Bluetooth connection attempt has been canceled.');
+    }
+  }
+
+  Future<void> write(List<int> bytes) async {
+    _checkAvailable();
+    if (bytes.any((byte) => byte < 0 || byte > 255)) {
+      throw ArgumentError.value(bytes, 'bytes', 'Must contain unsigned bytes.');
+    }
+    await _invoke<void>('write', {'bytes': Uint8List.fromList(bytes)});
+  }
+
+  Future<void> disconnect() async {
+    _connectionGeneration++;
+    _checkAvailable();
+    await _invoke<void>('disconnect');
+  }
+
+  Future<void> dispose() => _disposeFuture ??= _dispose();
+
+  Future<void> _dispose() async {
+    _connectionGeneration++;
+    _disposed = true;
+    if (!_ready.isCompleted) _ready.complete();
+    try {
+      if (isSupported && _subscription != null) {
+        await _invoke<void>('disconnect');
+      }
+    } on PlatformException catch (error) {
+      if (error.code != 'unsupported') rethrow;
+    } finally {
+      await _subscription?.cancel();
+      await _received.close();
+      await _events.close();
+    }
+  }
+}

+ 350 - 0
lib/services/firmware_updater.dart

@@ -0,0 +1,350 @@
+import 'dart:async';
+import 'dart:collection';
+
+/// A validated, immutable ATmega328P application image.
+///
+/// Gaps are erased-flash bytes (0xff). The final 512 bytes are reserved for a
+/// compatible STK500v1 bootloader; images targeting that area are rejected.
+class IntelHexFirmware {
+  static const int maxApplicationSize = 0x7e00;
+
+  final List<int> bytes;
+
+  IntelHexFirmware._(List<int> bytes) : bytes = List.unmodifiable(bytes);
+
+  factory IntelHexFirmware.parse(String source) {
+    final data = <int, int>{};
+    var baseAddress = 0;
+    var ended = false;
+    var lineNumber = 0;
+    for (final rawLine in source.split('\n')) {
+      lineNumber++;
+      final line = rawLine.trim();
+      if (line.isEmpty) continue;
+      Never invalid(String reason) =>
+          throw FormatException('Intel HEX line $lineNumber: $reason');
+      if (ended) invalid('record after EOF');
+      if (!RegExp(r'^:[0-9a-fA-F]+$').hasMatch(line) ||
+          line.length < 11 ||
+          line.length.isEven) {
+        invalid('malformed or truncated record');
+      }
+      final record = <int>[
+        for (var i = 1; i < line.length; i += 2)
+          int.parse(line.substring(i, i + 2), radix: 16),
+      ];
+      final count = record[0];
+      if (record.length != count + 5) invalid('incorrect record length');
+      if (record.fold<int>(0, (sum, byte) => sum + byte) & 0xff != 0) {
+        invalid('incorrect checksum');
+      }
+      final address = (record[1] << 8) | record[2];
+      switch (record[3]) {
+        case 0:
+          if (count == 0) invalid('empty data record');
+          if (address + count > 0x10000 ||
+              baseAddress + address + count > maxApplicationSize) {
+            invalid('address outside application flash');
+          }
+          for (var i = 0; i < count; i++) {
+            final target = baseAddress + address + i;
+            if (data.containsKey(target)) invalid('overlapping data');
+            data[target] = record[4 + i];
+          }
+        case 1:
+          if (count != 0 || address != 0) invalid('invalid EOF');
+          ended = true;
+        case 2:
+        case 4:
+          if (count != 2 || address != 0) invalid('invalid extended address');
+          final extended = (record[4] << 8) | record[5];
+          baseAddress = extended << (record[3] == 2 ? 4 : 16);
+          if (baseAddress >= maxApplicationSize) {
+            invalid('extended address outside application flash');
+          }
+        default:
+          invalid('unsupported record type ${record[3]}');
+      }
+    }
+    if (!ended) throw const FormatException('Intel HEX missing EOF');
+    if (data.isEmpty) throw const FormatException('Intel HEX empty image');
+    final lastAddress = data.keys.reduce((a, b) => a > b ? a : b);
+    final bytes = List<int>.filled(lastAddress + 1, 0xff);
+    data.forEach((address, value) => bytes[address] = value);
+    return IntelHexFirmware._(bytes);
+  }
+}
+
+enum FirmwareUpdateError {
+  busy,
+  disposed,
+  disconnected,
+  transport,
+  timeout,
+  protocol,
+  bufferOverflow,
+  signatureMismatch,
+  verificationFailed,
+}
+
+class FirmwareUpdateException implements Exception {
+  final FirmwareUpdateError code;
+  final String message;
+  final Object? cause;
+
+  const FirmwareUpdateException(this.code, this.message, {this.cause});
+
+  @override
+  String toString() => 'FirmwareUpdateException(${code.name}): $message';
+}
+
+/// Sequential STK500v1 programmer. The transport must already be in bootloader
+/// mode and deliver only bootloader bytes, closing/erroring on disconnection.
+///
+/// A failed programmer is terminal: reconnect and create a new instance rather
+/// than retrying an ambiguous page write. No chip-erase command is issued.
+class FirmwareUpdater {
+  static const int expectedSignature = 0x1e950f;
+  static const int pageSize = 128;
+  static const int _maxBufferedBytes = 4096;
+
+  final Future<void> Function(List<int>) write;
+  final Duration timeout;
+  final Queue<int> _buffer = Queue<int>();
+  late final StreamSubscription<List<int>> _subscription;
+  Completer<List<int>>? _reply;
+  int _replyLength = 0;
+  FirmwareUpdateException? _failure;
+  bool _flashing = false;
+  bool _disposed = false;
+  bool _finished = false;
+
+  FirmwareUpdater({
+    required this.write,
+    required Stream<List<int>> received,
+    this.timeout = const Duration(seconds: 3),
+  }) {
+    if (timeout <= Duration.zero) {
+      throw ArgumentError.value(timeout, 'timeout', 'Must be positive');
+    }
+    // Install before the first write, including synchronous transport replies.
+    _subscription = received.listen(
+      _receive,
+      onError: (Object error, StackTrace stack) => _fail(
+        FirmwareUpdateException(
+          FirmwareUpdateError.transport,
+          'Bootloader input failed',
+          cause: error,
+        ),
+      ),
+      onDone: () => _fail(
+        const FirmwareUpdateException(
+          FirmwareUpdateError.disconnected,
+          'Bootloader transport disconnected',
+        ),
+      ),
+    );
+  }
+
+  void _fail(FirmwareUpdateException failure) {
+    _failure ??= failure;
+    _buffer.clear();
+    final reply = _reply;
+    if (reply != null && !reply.isCompleted) reply.completeError(_failure!);
+  }
+
+  void _receive(List<int> bytes) {
+    if (_failure != null || _disposed) return;
+    if (_buffer.length + bytes.length > _maxBufferedBytes) {
+      _fail(
+        const FirmwareUpdateException(
+          FirmwareUpdateError.bufferOverflow,
+          'Bootloader receive buffer exceeded its limit',
+        ),
+      );
+      return;
+    }
+    if (bytes.any((byte) => byte < 0 || byte > 255)) {
+      _fail(
+        const FirmwareUpdateException(
+          FirmwareUpdateError.protocol,
+          'Transport supplied a non-byte value',
+        ),
+      );
+      return;
+    }
+    _buffer.addAll(bytes);
+    _drain();
+  }
+
+  void _drain() {
+    final reply = _reply;
+    if (reply == null || reply.isCompleted || _buffer.isEmpty) return;
+    if (_buffer.first != 0x14) {
+      _fail(
+        const FirmwareUpdateException(
+          FirmwareUpdateError.protocol,
+          'Bootloader did not respond with STK_INSYNC',
+        ),
+      );
+      return;
+    }
+    if (_buffer.length < _replyLength + 2) return;
+    _buffer.removeFirst();
+    final payload = <int>[
+      for (var i = 0; i < _replyLength; i++) _buffer.removeFirst(),
+    ];
+    if (_buffer.removeFirst() != 0x10) {
+      _fail(
+        const FirmwareUpdateException(
+          FirmwareUpdateError.protocol,
+          'Bootloader did not respond with STK_OK',
+        ),
+      );
+      return;
+    }
+    reply.complete(payload);
+  }
+
+  Future<List<int>> _exchange(
+    List<int> command, {
+    int responseLength = 0,
+  }) async {
+    if (_failure case final failure?) throw failure;
+    final reply = Completer<List<int>>();
+    _reply = reply;
+    _replyLength = responseLength;
+    try {
+      final results =
+          await Future.wait<Object?>([
+            reply.future,
+            Future<void>.sync(() => write(List<int>.unmodifiable(command))),
+          ], eagerError: true).timeout(
+            timeout,
+            onTimeout: () => throw const FirmwareUpdateException(
+              FirmwareUpdateError.timeout,
+              'Timed out waiting for bootloader command delivery/response',
+            ),
+          );
+      if (_failure case final failure?) throw failure;
+      return results.first! as List<int>;
+    } on FirmwareUpdateException catch (error) {
+      _fail(error);
+      rethrow;
+    } catch (error) {
+      final failure = FirmwareUpdateException(
+        FirmwareUpdateError.transport,
+        'Bootloader command delivery failed',
+        cause: error,
+      );
+      _fail(failure);
+      throw failure;
+    } finally {
+      _reply = null;
+    }
+  }
+
+  Future<void> _loadAddress(int byteAddress) async {
+    final wordAddress = byteAddress ~/ 2;
+    await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
+  }
+
+  Future<void> flash(
+    IntelHexFirmware firmware, {
+    void Function(double)? onProgress,
+  }) async {
+    if (_disposed) {
+      throw const FirmwareUpdateException(
+        FirmwareUpdateError.disposed,
+        'Programmer has been disposed',
+      );
+    }
+    if (_flashing || _finished) {
+      throw const FirmwareUpdateException(
+        FirmwareUpdateError.busy,
+        'Programmer is already running or has completed',
+      );
+    }
+    if (_failure case final failure?) throw failure;
+    _flashing = true;
+    try {
+      onProgress?.call(0);
+      await _exchange([0x30, 0x20]);
+      await _exchange([0x50, 0x20]);
+      final signature = await _exchange([0x75, 0x20], responseLength: 3);
+      final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];
+      if (actual != expectedSignature) {
+        final failure = FirmwareUpdateException(
+          FirmwareUpdateError.signatureMismatch,
+          'Expected ATmega328P signature 1e950f, received '
+          '${actual.toRadixString(16).padLeft(6, '0')}',
+        );
+        _fail(failure);
+        throw failure;
+      }
+      final pageCount = (firmware.bytes.length + pageSize - 1) ~/ pageSize;
+      for (var page = 0; page < pageCount; page++) {
+        final address = page * pageSize;
+        final bytes = List<int>.filled(pageSize, 0xff);
+        for (
+          var i = 0;
+          i < pageSize && address + i < firmware.bytes.length;
+          i++
+        ) {
+          bytes[i] = firmware.bytes[address + i];
+        }
+        await _loadAddress(address);
+        await _exchange([0x64, 0, pageSize, 0x46, ...bytes, 0x20]);
+        await _loadAddress(address);
+        final readBack = await _exchange([
+          0x74,
+          0,
+          pageSize,
+          0x46,
+          0x20,
+        ], responseLength: pageSize);
+        for (var i = 0; i < pageSize; i++) {
+          if (readBack[i] != bytes[i]) {
+            final failure = FirmwareUpdateException(
+              FirmwareUpdateError.verificationFailed,
+              'Flash read-back mismatch at byte 0x'
+              '${(address + i).toRadixString(16)}',
+            );
+            _fail(failure);
+            throw failure;
+          }
+        }
+        // Reserve completion for a successfully acknowledged LEAVE_PROGMODE.
+        onProgress?.call((page + 1) / (pageCount + 1));
+      }
+      await _exchange([0x51, 0x20]);
+      _finished = true;
+      onProgress?.call(1);
+    } catch (error) {
+      _fail(
+        error is FirmwareUpdateException
+            ? error
+            : FirmwareUpdateException(
+                FirmwareUpdateError.transport,
+                'Firmware update interrupted',
+                cause: error,
+              ),
+      );
+      rethrow;
+    } finally {
+      _flashing = false;
+    }
+  }
+
+  Future<void> dispose() async {
+    if (_disposed) return;
+    _disposed = true;
+    _fail(
+      const FirmwareUpdateException(
+        FirmwareUpdateError.disposed,
+        'Programmer has been disposed',
+      ),
+    );
+    await _subscription.cancel();
+  }
+}

+ 366 - 0
lib/services/me_coffee_protocol.dart

@@ -0,0 +1,366 @@
+import '../models/machine_state.dart';
+
+class MeCoffeeProtocol {
+  static MachineState parse(
+    String msg,
+    MachineState currentState, {
+    bool isLegacyV4 = false,
+  }) {
+    msg = msg.trim();
+    if (msg.isEmpty) return currentState;
+
+    final parts = msg.split(RegExp(r'\s+'));
+    if (parts.last == 'OK') parts.removeLast();
+    if (parts.isEmpty) return currentState;
+
+    final command = parts[0];
+
+    // Temperature update: tmp <timestamp> <setpoint> <boiler> <sensor2>
+    if (command == 'tmp' || command == 'T') {
+      if (parts.length < 4) return currentState;
+      try {
+        final timestamp = double.parse(parts[1]);
+        double setpoint = double.parse(parts[2]) / 100.0;
+        double boiler = double.parse(parts[3]) / 100.0;
+        if (!timestamp.isFinite || !setpoint.isFinite || !boiler.isFinite) {
+          return currentState;
+        }
+        // sensor2: validate range (same guard as Android: 0.05 – 200 °C raw)
+        double? sensor2;
+        if (parts.length >= 5) {
+          final raw = double.parse(parts[4]);
+          if (!raw.isFinite) return currentState;
+          if (raw > 5.0 && raw < 20000) sensor2 = raw / 100.0;
+        }
+        return currentState.copyWith(
+          targetTemperature: setpoint,
+          temperature: boiler,
+          sensor2Temperature: sensor2 ?? currentState.sensor2Temperature,
+        );
+      } catch (_) {}
+    }
+
+    // PID Power update: pid <p> <i> <d> <f>
+    if (command == 'pid') {
+      if (parts.length < 4) return currentState;
+      try {
+        int p = int.parse(parts[1]);
+        int i = int.parse(parts[2]);
+        int d = int.parse(parts[3]);
+        int f = parts.length >= 5 ? int.parse(parts[4]) : 0;
+
+        double totalPower = (p + i + d + f) / 65535.0;
+        return currentState.copyWith(
+          heatingPower: totalPower.clamp(0.0, 1.0),
+          isHeating: totalPower > 0,
+        );
+      } catch (_) {}
+    }
+
+    // Shot timer update: sht <val1> <time_ms>
+    if (command == 'sht') {
+      if (parts.length < 3) return currentState;
+      try {
+        int shottimeMs = int.parse(parts[2]);
+        if (shottimeMs == 0) {
+          return currentState.copyWith(isBrewing: true, shotTimer: 0);
+        } else {
+          return currentState.copyWith(
+            isBrewing: false,
+            shotTimer: (shottimeMs / 1000).round(),
+          );
+        }
+      } catch (_) {}
+    }
+
+    // The bundled V4 image identifies itself as "meCoffee V4 ".
+    final identityStart = command == 'uname'
+        ? 1
+        : command == 'cmd' && parts.length >= 2 && parts[1] == 'uname'
+        ? 2
+        : null;
+    if (identityStart != null) {
+      if (parts.length <= identityStart) return currentState;
+      final version = parts.sublist(identityStart).join(' ');
+      final isV4 = RegExp(
+        r'(^|[^a-z0-9])v4($|[^a-z0-9])',
+        caseSensitive: false,
+      ).hasMatch(version);
+      return currentState.copyWith(
+        isLegacyV4Firmware: isV4,
+        firmwareVersion: version,
+      );
+    }
+
+    // Command responses: cmd <set/get> <key> <value>
+    if (command == 'cmd') {
+      if (parts.length >= 4 && (parts[1] == 'set' || parts[1] == 'get')) {
+        final key = parts[2];
+        final valStr = parts[3];
+        return _updateFromKeyVal(
+          currentState,
+          key,
+          valStr,
+          isLegacyV4: isLegacyV4 || currentState.isLegacyV4Firmware,
+        );
+      }
+    }
+
+    // Legacy compatibility: get <key> <value>
+    if (command == 'get' && parts.length >= 3) {
+      return _updateFromKeyVal(
+        currentState,
+        parts[1],
+        parts[2],
+        isLegacyV4: isLegacyV4 || currentState.isLegacyV4Firmware,
+      );
+    }
+
+    return currentState;
+  }
+
+  static MachineState _updateFromKeyVal(
+    MachineState state,
+    String key,
+    String valStr, {
+    required bool isLegacyV4,
+  }) {
+    try {
+      final val = double.parse(valStr);
+      if (!val.isFinite) return state;
+      // V4 legacy firmware uses raw seconds (scale=1) for pistrt/piprd;
+      // newer firmware uses milliseconds (scale=1000).
+      final preinfusionScale = isLegacyV4 ? 1.0 : 1000.0;
+      switch (key) {
+        case 'tmpsp':
+          return state.copyWith(
+            brewTemperature: val / 100.0,
+            targetTemperature: val / 100.0,
+          );
+        case 'tmpstm':
+          return state.copyWith(steamTemperature: val / 100.0);
+        case 'pd1p':
+          return state.copyWith(pidP: val);
+        case 'pd1i':
+          return state.copyWith(pidI: isLegacyV4 ? val : val / 100.0);
+        case 'pd1d':
+          return state.copyWith(pidD: val);
+        case 'pd1imm':
+        case 'pd1imn':
+          if (isLegacyV4) return state;
+          return state.copyWith(pidIWindDownMin: (val / 655.36).clamp(0, 100));
+        case 'pd1imx':
+          return state.copyWith(
+            pidIWindDownMax: isLegacyV4 ? val : (val / 655.36).clamp(0, 100),
+          );
+        case 'pd1sz':
+          return state.copyWith(pidPollingInterval: val.toInt());
+        case 'pistrt':
+          return state.copyWith(preinfusionTime: val / preinfusionScale);
+        case 'piprd':
+          return state.copyWith(preinfusionPauseTime: val / preinfusionScale);
+        case 'pinbl':
+          return state.copyWith(preinfusionEnabled: val != 0);
+        case 'pivlv':
+          return state.copyWith(valveClosedWhilePaused: val != 0);
+        case 'tmppap':
+          return state.copyWith(proActivePercentage: val.toInt());
+        case 'tmpoff':
+          return state.copyWith(temperatureOffset: val / 100.0);
+        case 'tmrosd':
+          return state.copyWith(autoShutoffMinutes: val.toInt());
+        case 'o0':
+          return state.copyWith(output0: val.toInt());
+        case 'o1':
+          return state.copyWith(output1: val.toInt());
+        case 'o2':
+          return state.copyWith(output2: val.toInt());
+        case 'tmrpwr':
+          return state.copyWith(installedAsTimer: val != 0);
+        case 'pwrflp':
+          return state.copyWith(powerButtonFlipsBack: val != 0);
+        case 'tmrwnbl':
+          return state.copyWith(wakeupEnabled: val != 0);
+        case 'tmron':
+          return state.copyWith(wakeupTime: _secondsToTimeString(val.toInt()));
+        case 'tmrsnbl':
+          return state.copyWith(shutdownEnabled: val != 0);
+        case 'tmroff':
+          return state.copyWith(
+            shutdownTime: _secondsToTimeString(val.toInt()),
+          );
+        case 'pp1':
+          return state.copyWith(pressureStart: val.toInt());
+        case 'pp2':
+          return state.copyWith(pressureEnd: val.toInt());
+        case 'ppt':
+          return state.copyWith(pressurePeriod: val.toInt());
+        case 'grndr_cnt':
+          return state.copyWith(grinderCounter: val.toInt());
+        case 'shtmx':
+          return state.copyWith(maxShotTime: val.toInt());
+        case 'tmpcntns':
+          return state.copyWith(continuousMode: val != 0);
+      }
+    } catch (_) {}
+    return state;
+  }
+
+  static String encodeSet(
+    String key,
+    dynamic value, {
+    bool isLegacyV4 = false,
+  }) {
+    String valStr;
+    if (value is bool) {
+      valStr = value ? '1' : '0';
+    } else if (value is String && (key == 'tmron' || key == 'tmroff')) {
+      valStr = _timeStringToSeconds(value).toString();
+    } else if (value is double) {
+      if (key == 'tmpsp' || key == 'tmpstm' || key == 'tmpoff') {
+        valStr = (value * 100).round().toString();
+      } else if (key == 'pistrt' || key == 'piprd') {
+        valStr = (value * (isLegacyV4 ? 1 : 1000)).round().toString();
+      } else if (key == 'pd1i') {
+        valStr = (value * (isLegacyV4 ? 1 : 100)).round().toString();
+      } else if (key == 'pd1imm' || key == 'pd1imn' || key == 'pd1imx') {
+        valStr = (value * (isLegacyV4 ? 1 : 655.36)).round().toString();
+      } else {
+        valStr = value.round().toString();
+      }
+    } else {
+      valStr = value.toString();
+    }
+    return "cmd set $key $valStr\n";
+  }
+
+  static List<int> encodeTemperature(double temp) {
+    return _toBytes(encodeSet('tmpsp', temp));
+  }
+
+  static List<int> encodeSteamTemperature(double temp) {
+    return _toBytes(encodeSet('tmpstm', temp));
+  }
+
+  static List<int> encodePreinfusion(
+    bool enabled,
+    double time,
+    double pause,
+    bool closeValve, {
+    bool isLegacyV4 = false,
+  }) {
+    // V4 firmware uses raw seconds (scale=1); newer firmware uses milliseconds (scale=1000).
+    final scale = isLegacyV4 ? 1 : 1000;
+    return _toBytes(
+      encodeSet('pinbl', enabled ? 1 : 0) +
+          encodeSet('pistrt', (time * scale).round()) +
+          encodeSet('piprd', (pause * scale).round()) +
+          encodeSet('pivlv', closeValve ? 1 : 0),
+    );
+  }
+
+  static List<int> encodeHardware(
+    int o0,
+    int o1,
+    int o2,
+    bool timer,
+    bool flips,
+  ) {
+    return _toBytes(
+      encodeSet('o0', o0) +
+          encodeSet('o1', o1) +
+          encodeSet('o2', o2) +
+          encodeSet('tmrpwr', timer ? 1 : 0) +
+          encodeSet('pwrflp', flips ? 1 : 0),
+    );
+  }
+
+  static List<int> encodePID(
+    double p,
+    double i,
+    double d, {
+    bool isLegacyV4 = false,
+  }) {
+    return _toBytes(
+      encodeSet('pd1p', p) +
+          encodeSet('pd1i', (i * (isLegacyV4 ? 1 : 100)).round()) +
+          encodeSet('pd1d', d),
+    );
+  }
+
+  static List<int> encodePIDLimits(
+    double min,
+    double max,
+    int interval, {
+    bool isLegacyV4 = false,
+  }) {
+    return _toBytes(
+      // V10's key table uses pd1imn; Android's modern XML also has pd1imm.
+      // V4 exposes only the maximum, in direct units rather than percent.
+      (isLegacyV4 ? '' : encodeSet('pd1imn', min)) +
+          encodeSet('pd1imx', isLegacyV4 ? max.round() : max) +
+          encodeSet('pd1sz', interval),
+    );
+  }
+
+  static List<int> encodePressure(int start, int end, int period) {
+    return _toBytes(
+      encodeSet('pp1', start) +
+          encodeSet('pp2', end) +
+          encodeSet('ppt', period),
+    );
+  }
+
+  static List<int> encodeProActive(int percentage) {
+    return _toBytes(encodeSet('tmppap', percentage));
+  }
+
+  static List<int> encodeOffset(double offset) {
+    return _toBytes(encodeSet('tmpoff', offset));
+  }
+
+  static List<int> encodeAutoShutoff(int minutes) {
+    return _toBytes(encodeSet('tmrosd', minutes));
+  }
+
+  static List<int> encodeMaxShotTime(int seconds) {
+    return _toBytes(encodeSet('shtmx', seconds));
+  }
+
+  static List<int> encodeContinuousMode(bool enabled) {
+    return _toBytes(encodeSet('tmpcntns', enabled ? 1 : 0));
+  }
+
+  static List<int> encodeSchedule(
+    bool wEnabled,
+    String wTime,
+    bool sEnabled,
+    String sTime,
+  ) {
+    return _toBytes(
+      encodeSet('tmrwnbl', wEnabled ? 1 : 0) +
+          encodeSet('tmron', _timeStringToSeconds(wTime)) +
+          encodeSet('tmrsnbl', sEnabled ? 1 : 0) +
+          encodeSet('tmroff', _timeStringToSeconds(sTime)),
+    );
+  }
+
+  static int _timeStringToSeconds(String time) {
+    final parts = time.split(':');
+    if (parts.length != 2) return 0;
+    final hours = int.tryParse(parts[0]) ?? 0;
+    final minutes = int.tryParse(parts[1]) ?? 0;
+    final clampedHours = hours.clamp(0, 23);
+    final clampedMinutes = minutes.clamp(0, 59);
+    return clampedHours * 3600 + clampedMinutes * 60;
+  }
+
+  static String _secondsToTimeString(int totalSeconds) {
+    final normalized = ((totalSeconds % 86400) + 86400) % 86400;
+    final hours = (normalized ~/ 3600).toString().padLeft(2, '0');
+    final minutes = ((normalized % 3600) ~/ 60).toString().padLeft(2, '0');
+    return '$hours:$minutes';
+  }
+
+  static List<int> _toBytes(String s) => s.codeUnits;
+}

+ 226 - 0
lib/widgets/temperature_chart.dart

@@ -0,0 +1,226 @@
+import 'package:fl_chart/fl_chart.dart';
+import 'package:flutter/material.dart';
+import '../models/temperature_sample.dart';
+
+class TemperatureChart extends StatefulWidget {
+  final List<double> history;
+  final List<double> sensor2History;
+  final double targetTemperature;
+  final List<TemperatureSample> samples;
+
+  const TemperatureChart({
+    super.key,
+    required this.history,
+    required this.targetTemperature,
+    this.sensor2History = const [],
+    this.samples = const [],
+  });
+
+  @override
+  State<TemperatureChart> createState() => _TemperatureChartState();
+}
+
+class _TemperatureChartState extends State<TemperatureChart> {
+  int _windowMinutes = 5;
+  DateTime? _windowEnd;
+
+  double _minutesSince(DateTime timestamp, DateTime origin) =>
+      timestamp.difference(origin).inMicroseconds /
+      Duration.microsecondsPerMinute;
+
+  @override
+  Widget build(BuildContext context) {
+    final samples = widget.samples;
+    final timestamped = samples.isNotEmpty;
+    if (!timestamped && widget.history.isEmpty) {
+      return const Center(child: Text('No data yet'));
+    }
+
+    final origin = timestamped ? samples.first.timestamp : null;
+    final latest = timestamped ? samples.last.timestamp : null;
+    final duration = timestamped ? _minutesSince(latest!, origin!) : 0.0;
+    final earliestEnd = duration < _windowMinutes
+        ? duration
+        : _windowMinutes.toDouble();
+    final end = timestamped
+        ? (_windowEnd == null ? duration : _minutesSince(_windowEnd!, origin!))
+              .clamp(earliestEnd, duration)
+        : 0.0;
+    final minX = timestamped ? (end - _windowMinutes).clamp(0.0, end) : 0.0;
+    final legacyLength = widget.history.length > widget.sensor2History.length
+        ? widget.history.length
+        : widget.sensor2History.length;
+    // A single timestamp still needs a nonzero axis span.
+    final maxX = timestamped
+        ? (end > minX ? end : minX + 1 / 60)
+        : (legacyLength > 1 ? legacyLength - 1.0 : 1.0);
+    final visible = timestamped
+        ? samples.where((sample) {
+            final x = _minutesSince(sample.timestamp, origin!);
+            return x >= minX && x <= maxX;
+          }).toList()
+        : <TemperatureSample>[];
+    final boilerSpots = timestamped
+        ? visible
+              .map((s) => FlSpot(_minutesSince(s.timestamp, origin!), s.boiler))
+              .toList()
+        : widget.history
+              .asMap()
+              .entries
+              .map((e) => FlSpot(e.key.toDouble(), e.value))
+              .toList();
+    final targetSpots = timestamped
+        ? visible
+              .map((s) => FlSpot(_minutesSince(s.timestamp, origin!), s.target))
+              .toList()
+        : [
+            FlSpot(minX, widget.targetTemperature),
+            FlSpot(maxX, widget.targetTemperature),
+          ];
+    final sensorSpots = timestamped
+        ? visible
+              .map(
+                (s) => s.sensor2 == null
+                    ? FlSpot.nullSpot
+                    : FlSpot(_minutesSince(s.timestamp, origin!), s.sensor2!),
+              )
+              .toList()
+        : widget.sensor2History
+              .asMap()
+              .entries
+              .map((e) => FlSpot(e.key.toDouble(), e.value))
+              .toList();
+    final hasSensor2 = timestamped
+        ? visible.any((s) => s.sensor2 != null)
+        : widget.sensor2History.isNotEmpty;
+
+    // Retained-history bounds keep the vertical scale steady while browsing.
+    final values = timestamped
+        ? samples.expand((s) => [s.boiler, s.target, ?s.sensor2])
+        : [
+            ...widget.history,
+            ...widget.sensor2History,
+            widget.targetTemperature,
+          ];
+    final dataMin = values.reduce((a, b) => a < b ? a : b);
+    final dataMax = values.reduce((a, b) => a > b ? a : b);
+    final minY = ((dataMin - 5) / 5).floorToDouble() * 5;
+    final maxY = ((dataMax + 5) / 5).ceilToDouble() * 5;
+    final chart = LineChart(
+      LineChartData(
+        minY: minY,
+        maxY: maxY,
+        minX: minX,
+        maxX: maxX,
+        clipData: const FlClipData.all(),
+        lineBarsData: [
+          _line(boilerSpots, Colors.redAccent, 3),
+          LineChartBarData(
+            spots: targetSpots,
+            isCurved: false,
+            color: Colors.blue.withValues(alpha: 0.5),
+            barWidth: 1,
+            dashArray: [5, 5],
+            dotData: const FlDotData(show: false),
+          ),
+          if (hasSensor2) _line(sensorSpots, Colors.greenAccent, 2),
+        ],
+        titlesData: FlTitlesData(
+          rightTitles: const AxisTitles(
+            sideTitles: SideTitles(showTitles: false),
+          ),
+          topTitles: const AxisTitles(
+            sideTitles: SideTitles(showTitles: false),
+          ),
+          bottomTitles: AxisTitles(
+            sideTitles: SideTitles(
+              showTitles: true,
+              reservedSize: 28,
+              getTitlesWidget: (value, meta) => Text(
+                timestamped
+                    ? '${value.toStringAsFixed(1)}m'
+                    : value.toInt().toString(),
+                style: const TextStyle(fontSize: 10),
+              ),
+            ),
+          ),
+        ),
+        gridData: const FlGridData(show: true, drawVerticalLine: false),
+        borderData: FlBorderData(show: true),
+      ),
+      duration: Duration.zero,
+    );
+
+    if (!timestamped) return chart;
+    return Column(
+      children: [
+        Wrap(
+          spacing: 4,
+          children: [
+            for (final minutes in [1, 5, 10, 20, 30])
+              ChoiceChip(
+                label: Text('$minutes min'),
+                selected: _windowMinutes == minutes,
+                onSelected: (_) => setState(() => _windowMinutes = minutes),
+                visualDensity: VisualDensity.compact,
+              ),
+          ],
+        ),
+        Row(
+          mainAxisAlignment: MainAxisAlignment.center,
+          children: [
+            TextButton(
+              onPressed: end > earliestEnd
+                  ? () => setState(() {
+                      final older = (end - _windowMinutes).clamp(
+                        earliestEnd,
+                        duration,
+                      );
+                      _windowEnd = origin!.add(
+                        Duration(
+                          microseconds: (older * Duration.microsecondsPerMinute)
+                              .round(),
+                        ),
+                      );
+                    })
+                  : null,
+              child: const Text('Older'),
+            ),
+            TextButton(
+              onPressed: end < duration
+                  ? () => setState(() {
+                      final newer = (end + _windowMinutes).clamp(
+                        earliestEnd,
+                        duration,
+                      );
+                      _windowEnd = origin!.add(
+                        Duration(
+                          microseconds: (newer * Duration.microsecondsPerMinute)
+                              .round(),
+                        ),
+                      );
+                    })
+                  : null,
+              child: const Text('Newer'),
+            ),
+            TextButton(
+              onPressed: () => setState(() => _windowEnd = null),
+              child: Text(_windowEnd == null ? 'Live' : 'Return to Live'),
+            ),
+          ],
+        ),
+        Expanded(child: chart),
+      ],
+    );
+  }
+
+  LineChartBarData _line(List<FlSpot> spots, Color color, double width) =>
+      LineChartBarData(
+        spots: spots,
+        isCurved: false,
+        color: color,
+        barWidth: width,
+        isStrokeCapRound: true,
+        dotData: const FlDotData(show: false),
+      );
+}

+ 0 - 0
macos/.gitignore


Некоторые файлы не были показаны из-за большого количества измененных файлов